mirror of
https://github.com/rust-windowing/winit.git
synced 2026-06-26 22:53:15 -04:00
Compare commits
146 Commits
notgull/in
...
waker
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a391b348a | ||
|
|
488c036a05 | ||
|
|
a4af50ec13 | ||
|
|
317d62fb93 | ||
|
|
b13b39aa0b | ||
|
|
abea6e64e4 | ||
|
|
d6f7a28499 | ||
|
|
bd98561b38 | ||
|
|
ca6f523924 | ||
|
|
d7fdfb1bca | ||
|
|
120f21a010 | ||
|
|
5904529ba1 | ||
|
|
e7a6034b55 | ||
|
|
eb66c25980 | ||
|
|
0ccb8a9f87 | ||
|
|
abed32eb80 | ||
|
|
08907148ec | ||
|
|
fa0795a50c | ||
|
|
fe1eab07ae | ||
|
|
552c7a6252 | ||
|
|
50c0180af3 | ||
|
|
4f33643509 | ||
|
|
0b21c55b72 | ||
|
|
e1bccb68d8 | ||
|
|
e540062ac0 | ||
|
|
f1e0f6c646 | ||
|
|
3218316420 | ||
|
|
2900ecab93 | ||
|
|
3a84da6951 | ||
|
|
478427b0bd | ||
|
|
b0f26c79ff | ||
|
|
969237f422 | ||
|
|
e542a78deb | ||
|
|
2d4b9938f0 | ||
|
|
8ad016362a | ||
|
|
5f2c7350e9 | ||
|
|
256bbe949e | ||
|
|
1126e9ea2f | ||
|
|
927af44aa4 | ||
|
|
0adc0898f0 | ||
|
|
3b986f5583 | ||
|
|
b1f8d778a1 | ||
|
|
04482d5a2e | ||
|
|
3e50911adb | ||
|
|
f51a470872 | ||
|
|
47b938dbe7 | ||
|
|
e2b883d215 | ||
|
|
38fd3c6a99 | ||
|
|
5190472bee | ||
|
|
eab03dca80 | ||
|
|
59e3dda89f | ||
|
|
c846f67bcb | ||
|
|
03c01e038b | ||
|
|
ed4ebd4242 | ||
|
|
b5921d89f2 | ||
|
|
b5a6a4e616 | ||
|
|
9598eb371c | ||
|
|
634b9baea2 | ||
|
|
cf5e422dc8 | ||
|
|
276597e009 | ||
|
|
c0b737de4a | ||
|
|
79fa4061cb | ||
|
|
056421546a | ||
|
|
b4c5b76155 | ||
|
|
c8b9a86885 | ||
|
|
fe2df61884 | ||
|
|
446482367b | ||
|
|
cbb29ab526 | ||
|
|
a491c2abed | ||
|
|
3142355417 | ||
|
|
3493a20173 | ||
|
|
bf0bde8067 | ||
|
|
519947463f | ||
|
|
8c36ed4900 | ||
|
|
7b2c9d42b4 | ||
|
|
587ade844d | ||
|
|
6756549ac9 | ||
|
|
17666e3171 | ||
|
|
f6ca06cd58 | ||
|
|
e634cc609f | ||
|
|
aa83726c72 | ||
|
|
1800fa1670 | ||
|
|
a5e6d0aaaf | ||
|
|
4fe4ce3d77 | ||
|
|
078c4c0c4f | ||
|
|
c8579a1882 | ||
|
|
ab96fa8395 | ||
|
|
6461cfa9b1 | ||
|
|
6c214e71ae | ||
|
|
ecc884ac91 | ||
|
|
24e2c6914a | ||
|
|
ed4d70fdd4 | ||
|
|
07c25b9703 | ||
|
|
cdbdd974fb | ||
|
|
7e13248be3 | ||
|
|
b15a40cd14 | ||
|
|
8db4a9cc61 | ||
|
|
a4ab7dc64c | ||
|
|
afb731bb52 | ||
|
|
ef37b1d5dd | ||
|
|
2b4e8ef916 | ||
|
|
ae28eea406 | ||
|
|
a0464ae83b | ||
|
|
16d5f46db1 | ||
|
|
5cada36ae8 | ||
|
|
b3dcfa1275 | ||
|
|
f1c5afd84e | ||
|
|
be1baf164c | ||
|
|
39c0862198 | ||
|
|
aa8ebdc795 | ||
|
|
ea68916055 | ||
|
|
e26b831f23 | ||
|
|
8c3e69c08b | ||
|
|
46879429ed | ||
|
|
0c89ea7386 | ||
|
|
6c0e3c3b15 | ||
|
|
675582bd46 | ||
|
|
4d6fe7e35c | ||
|
|
f9912baf09 | ||
|
|
f290619dce | ||
|
|
23011c6b0a | ||
|
|
3a39a6ddb0 | ||
|
|
90cf9a3398 | ||
|
|
05d8fa0b91 | ||
|
|
d7d20507ed | ||
|
|
f6e66a71f8 | ||
|
|
c09160d1a8 | ||
|
|
2230e71093 | ||
|
|
5e6350d142 | ||
|
|
a6998af997 | ||
|
|
5c48ec7977 | ||
|
|
953d9b4268 | ||
|
|
f5dcd2aabe | ||
|
|
77f1c73f06 | ||
|
|
24c226416e | ||
|
|
69382fda9a | ||
|
|
ee245c569d | ||
|
|
5462f27dda | ||
|
|
927deb030f | ||
|
|
5ea81efc74 | ||
|
|
6896de5b73 | ||
|
|
d736763216 | ||
|
|
e316a89847 | ||
|
|
f0d8689039 | ||
|
|
4d5e68c6e2 | ||
|
|
5835c9102e |
31
.github/CODEOWNERS
vendored
31
.github/CODEOWNERS
vendored
@@ -1,31 +1,26 @@
|
|||||||
# Android
|
# Android
|
||||||
/src/platform/android.rs @MarijnS95
|
/winit-android @MarijnS95
|
||||||
/src/platform_impl/android @MarijnS95
|
|
||||||
|
|
||||||
# Apple (AppKit + UIKit)
|
# Apple (AppKit + UIKit)
|
||||||
/src/platform/ios.rs @madsmtm
|
/winit-appkit @madsmtm
|
||||||
/src/platform/macos.rs @madsmtm
|
/winit-uikit @madsmtm
|
||||||
/src/platform_impl/apple @madsmtm
|
/winit-common/src/core_foundation @madsmtm
|
||||||
|
/winit-common/src/event_handler.rs @madsmtm
|
||||||
|
|
||||||
# Unix
|
# XKB
|
||||||
/src/platform_impl/linux/mod.rs @kchibisov
|
/winit-common/src/xkb @kchibisov
|
||||||
|
|
||||||
# Wayland
|
# Wayland
|
||||||
/src/platform/wayland.rs @kchibisov
|
/winit-wayland @kchibisov
|
||||||
/src/platform_impl/linux/wayland @kchibisov
|
|
||||||
|
|
||||||
# X11
|
# X11
|
||||||
/src/platform/x11.rs @kchibisov @notgull
|
/winit-x11 @kchibisov
|
||||||
/src/platform_impl/linux/x11 @kchibisov @notgull
|
|
||||||
|
|
||||||
# Web
|
# Web
|
||||||
/src/platform/web.rs @daxpedda
|
/winit-web @daxpedda
|
||||||
/src/platform_impl/web @daxpedda
|
|
||||||
|
|
||||||
# Windows
|
# Windows (Win32) (UNOWNED)
|
||||||
/src/platform/windows.rs @notgull
|
#/winit-win32
|
||||||
/src/platform_impl/windows @notgull
|
|
||||||
|
|
||||||
# Orbital (Redox OS)
|
# Orbital (Redox OS)
|
||||||
/src/platform/orbital.rs @jackpot51
|
/winit-orbital @jackpot51
|
||||||
/src/platform_impl/orbital @jackpot51
|
|
||||||
|
|||||||
92
.github/workflows/ci.yml
vendored
92
.github/workflows/ci.yml
vendored
@@ -55,7 +55,7 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
toolchain: [stable, nightly, '1.73']
|
toolchain: [stable, nightly, '1.80']
|
||||||
platform:
|
platform:
|
||||||
# Note: Make sure that we test all the `docs.rs` targets defined in Cargo.toml!
|
# 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, }
|
- { name: 'Windows 64bit MSVC', target: x86_64-pc-windows-msvc, os: windows-latest, }
|
||||||
@@ -66,7 +66,7 @@ jobs:
|
|||||||
- { name: 'Linux 64bit', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, }
|
- { name: 'Linux 64bit', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, }
|
||||||
- { name: 'X11', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: '--no-default-features --features=x11' }
|
- { name: 'X11', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: '--no-default-features --features=x11' }
|
||||||
- { name: 'Wayland', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: '--no-default-features --features=wayland,wayland-dlopen' }
|
- { name: 'Wayland', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: '--no-default-features --features=wayland,wayland-dlopen' }
|
||||||
- { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
- { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package winit --features=android-native-activity', cmd: 'apk -- ' }
|
||||||
- { name: 'Redox OS', target: x86_64-unknown-redox, os: ubuntu-latest, }
|
- { name: 'Redox OS', target: x86_64-unknown-redox, os: ubuntu-latest, }
|
||||||
- { name: 'macOS x86_64', target: x86_64-apple-darwin, os: macos-latest, }
|
- { name: 'macOS x86_64', target: x86_64-apple-darwin, os: macos-latest, }
|
||||||
- { name: 'macOS Aarch64', target: aarch64-apple-darwin, os: macos-latest, }
|
- { name: 'macOS Aarch64', target: aarch64-apple-darwin, os: macos-latest, }
|
||||||
@@ -74,18 +74,22 @@ jobs:
|
|||||||
- { name: 'iOS Aarch64', target: aarch64-apple-ios, os: macos-latest, }
|
- { name: 'iOS Aarch64', target: aarch64-apple-ios, os: macos-latest, }
|
||||||
- { name: 'Web', target: wasm32-unknown-unknown, os: ubuntu-latest, }
|
- { name: 'Web', target: wasm32-unknown-unknown, os: ubuntu-latest, }
|
||||||
exclude:
|
exclude:
|
||||||
# Web on nightly needs extra arguments
|
# Web on nightly needs extra arguments
|
||||||
|
|
||||||
- toolchain: nightly
|
- toolchain: nightly
|
||||||
platform: { name: 'Web', target: wasm32-unknown-unknown, os: ubuntu-latest }
|
platform: { name: 'Web' }
|
||||||
|
# Rustup is broken.
|
||||||
|
- toolchain: nightly
|
||||||
|
platform: { name: 'Windows 32bit GNU' }
|
||||||
# Android is tested on stable-3
|
# Android is tested on stable-3
|
||||||
- toolchain: '1.73'
|
- toolchain: '1.80'
|
||||||
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
platform: { name: 'Android' }
|
||||||
# Redox OS doesn't follow MSRV
|
# Redox OS doesn't follow MSRV
|
||||||
- toolchain: '1.73'
|
- toolchain: '1.80'
|
||||||
platform: { name: 'Redox OS', target: x86_64-unknown-redox, os: ubuntu-latest }
|
platform: { name: 'Redox OS' }
|
||||||
include:
|
include:
|
||||||
- toolchain: '1.73'
|
- toolchain: '1.80'
|
||||||
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package winit --features=android-native-activity', cmd: 'apk -- ' }
|
||||||
- toolchain: 'nightly'
|
- toolchain: 'nightly'
|
||||||
platform: { name: 'Web', target: wasm32-unknown-unknown, os: ubuntu-latest, test-options: -Zdoctest-xcompile }
|
platform: { name: 'Web', target: wasm32-unknown-unknown, os: ubuntu-latest, test-options: -Zdoctest-xcompile }
|
||||||
- toolchain: 'nightly'
|
- toolchain: 'nightly'
|
||||||
@@ -175,17 +179,70 @@ jobs:
|
|||||||
- name: Build crate
|
- name: Build crate
|
||||||
run: cargo $CMD build $OPTIONS
|
run: cargo $CMD build $OPTIONS
|
||||||
|
|
||||||
|
- name: Test winit core
|
||||||
|
run: cargo test -p winit-core
|
||||||
|
|
||||||
|
- name: Test winit Android
|
||||||
|
if: contains(matrix.platform.target, 'android')
|
||||||
|
run: cargo $CMD test -p winit-android --features native-activity --no-run
|
||||||
|
|
||||||
|
- name: Test winit Common (EventHandler)
|
||||||
|
run: cargo $CMD test -p winit-common --features event-handler --no-run
|
||||||
|
|
||||||
|
- name: Test winit Common (CF)
|
||||||
|
if: contains(matrix.platform.target, 'apple')
|
||||||
|
run: cargo $CMD test -p winit-common --features core-foundation --no-run
|
||||||
|
|
||||||
|
- name: Test winit Common (XKB)
|
||||||
|
if: contains(matrix.platform.target, 'linux-gnu')
|
||||||
|
run: cargo $CMD test -p winit-common --features xkb,x11,wayland --no-run
|
||||||
|
|
||||||
|
- name: Test winit AppKit
|
||||||
|
if: contains(matrix.platform.target, 'macos')
|
||||||
|
run: cargo $CMD test -p winit-appkit $OPTIONS
|
||||||
|
|
||||||
|
- name: Test winit Orbital
|
||||||
|
if: contains(matrix.platform.target, 'redox')
|
||||||
|
run: cargo test -p winit-orbital
|
||||||
|
|
||||||
|
- name: Test winit UIKit
|
||||||
|
if: contains(matrix.platform.target, 'ios')
|
||||||
|
# TODO: Run on Simulator
|
||||||
|
run: cargo $CMD test -p winit-uikit $OPTIONS --no-run
|
||||||
|
|
||||||
|
- name: Test winit Web
|
||||||
|
if: contains(matrix.platform.target, 'wasm')
|
||||||
|
run: cargo $CMD test -p winit-web $OPTIONS --no-run
|
||||||
|
|
||||||
|
- name: Test winit Win32
|
||||||
|
if: contains(matrix.platform.target, 'windows')
|
||||||
|
run: cargo $CMD test -p winit-win32 $OPTIONS
|
||||||
|
|
||||||
|
- name: Test winit X11
|
||||||
|
if: contains(matrix.platform.target, 'linux-gnu')
|
||||||
|
run: cargo $CMD test -p winit-x11 --target=${{ matrix.platform.target }}
|
||||||
|
|
||||||
|
- name: Test winit Wayland
|
||||||
|
if: contains(matrix.platform.target, 'linux-gnu')
|
||||||
|
run: cargo $CMD test -p winit-wayland --target=${{ matrix.platform.target }}
|
||||||
|
|
||||||
# Test only on Linux x86_64, so we avoid spending unnecessary CI hours.
|
# Test only on Linux x86_64, so we avoid spending unnecessary CI hours.
|
||||||
- name: Test dpi crate
|
- name: Test dpi crate
|
||||||
if: >
|
if: >
|
||||||
contains(matrix.platform.name, 'Linux 64bit') &&
|
contains(matrix.platform.name, 'Linux 64bit') &&
|
||||||
matrix.toolchain != '1.73'
|
matrix.toolchain != '1.80'
|
||||||
run: cargo test -p dpi
|
run: cargo test -p dpi
|
||||||
|
|
||||||
|
- name: Check dpi crate (no_std)
|
||||||
|
if: >
|
||||||
|
contains(matrix.platform.name, 'Linux 64bit') &&
|
||||||
|
matrix.toolchain != '1.80'
|
||||||
|
run: cargo check -p dpi --no-default-features
|
||||||
|
|
||||||
- name: Build tests
|
- name: Build tests
|
||||||
if: >
|
if: >
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.toolchain != '1.73'
|
matrix.toolchain != '1.80'
|
||||||
run: cargo $CMD test --no-run $OPTIONS
|
run: cargo $CMD test --no-run $OPTIONS
|
||||||
|
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
@@ -194,7 +251,7 @@ jobs:
|
|||||||
!contains(matrix.platform.target, 'ios') &&
|
!contains(matrix.platform.target, 'ios') &&
|
||||||
(!contains(matrix.platform.target, 'wasm32') || matrix.toolchain == 'nightly') &&
|
(!contains(matrix.platform.target, 'wasm32') || matrix.toolchain == 'nightly') &&
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.toolchain != '1.73'
|
matrix.toolchain != '1.80'
|
||||||
run: cargo $CMD test $OPTIONS
|
run: cargo $CMD test $OPTIONS
|
||||||
|
|
||||||
- name: Lint with clippy
|
- name: Lint with clippy
|
||||||
@@ -204,7 +261,7 @@ jobs:
|
|||||||
- name: Build tests with serde enabled
|
- name: Build tests with serde enabled
|
||||||
if: >
|
if: >
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.toolchain != '1.73'
|
matrix.toolchain != '1.80'
|
||||||
run: cargo $CMD test --no-run $OPTIONS $TEST_OPTIONS --features serde
|
run: cargo $CMD test --no-run $OPTIONS $TEST_OPTIONS --features serde
|
||||||
|
|
||||||
- name: Run tests with serde enabled
|
- name: Run tests with serde enabled
|
||||||
@@ -213,7 +270,7 @@ jobs:
|
|||||||
!contains(matrix.platform.target, 'ios') &&
|
!contains(matrix.platform.target, 'ios') &&
|
||||||
(!contains(matrix.platform.target, 'wasm32') || matrix.toolchain == 'nightly') &&
|
(!contains(matrix.platform.target, 'wasm32') || matrix.toolchain == 'nightly') &&
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.toolchain != '1.73'
|
matrix.toolchain != '1.80'
|
||||||
run: cargo $CMD test $OPTIONS $TEST_OPTIONS --features serde
|
run: cargo $CMD test $OPTIONS $TEST_OPTIONS --features serde
|
||||||
|
|
||||||
- name: Check docs.rs documentation
|
- name: Check docs.rs documentation
|
||||||
@@ -256,6 +313,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
command: check
|
command: check
|
||||||
log-level: error
|
log-level: error
|
||||||
|
manifest-path: winit/Cargo.toml
|
||||||
arguments: --all-features --target ${{ matrix.platform.target }}
|
arguments: --all-features --target ${{ matrix.platform.target }}
|
||||||
|
|
||||||
eslint:
|
eslint:
|
||||||
@@ -264,7 +322,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
defaults:
|
defaults:
|
||||||
run:
|
run:
|
||||||
working-directory: ./src/platform_impl/web/script
|
working-directory: ./winit-web/src/script
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: taiki-e/checkout-action@v1
|
- uses: taiki-e/checkout-action@v1
|
||||||
@@ -279,7 +337,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
defaults:
|
defaults:
|
||||||
run:
|
run:
|
||||||
working-directory: ./src/platform_impl/web/script
|
working-directory: ./winit-web/src/script
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: taiki-e/checkout-action@v1
|
- uses: taiki-e/checkout-action@v1
|
||||||
|
|||||||
4
.github/workflows/docs.yml
vendored
4
.github/workflows/docs.yml
vendored
@@ -19,7 +19,7 @@ jobs:
|
|||||||
id-token: write
|
id-token: write
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v5
|
||||||
|
|
||||||
- uses: dtolnay/rust-toolchain@master
|
- uses: dtolnay/rust-toolchain@master
|
||||||
with:
|
with:
|
||||||
@@ -41,7 +41,7 @@ jobs:
|
|||||||
done
|
done
|
||||||
|
|
||||||
- name: Upload artifact
|
- name: Upload artifact
|
||||||
uses: actions/upload-pages-artifact@v3
|
uses: actions/upload-pages-artifact@v4
|
||||||
with:
|
with:
|
||||||
path: target/doc
|
path: target/doc
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,6 @@ Changelog entries should be put in the [`changelog::unreleased`].
|
|||||||
The changelog can also be viewed [on docs.rs][docs_rs] or [on the current
|
The changelog can also be viewed [on docs.rs][docs_rs] or [on the current
|
||||||
master docs][master_docs].
|
master docs][master_docs].
|
||||||
|
|
||||||
[`changelog::unreleased`]: src/changelog/unreleased.md
|
[`changelog::unreleased`]: winit/src/changelog/unreleased.md
|
||||||
[docs_rs]: https://docs.rs/winit/latest/winit/changelog/index.html
|
[docs_rs]: https://docs.rs/winit/latest/winit/changelog/index.html
|
||||||
[master_docs]: https://rust-windowing.github.io/winit/winit/changelog/index.html
|
[master_docs]: https://rust-windowing.github.io/winit/winit/changelog/index.html
|
||||||
|
|||||||
@@ -13,12 +13,29 @@ To save your time it's wise to check already opened [pull requests][prs] and
|
|||||||
accepted, however larger new API proposals should go into the issue first. When
|
accepted, however larger new API proposals should go into the issue first. When
|
||||||
in doubt contact us on [Matrix][matrix] or via opening an issue.
|
in doubt contact us on [Matrix][matrix] or via opening an issue.
|
||||||
|
|
||||||
|
### Windows
|
||||||
|
|
||||||
|
To run the examples on Windows, you must have symlinks enabled, see
|
||||||
|
[this][git-windows-symlinks].
|
||||||
|
|
||||||
|
[git-windows-symlinks]: https://gitforwindows.org/symbolic-links.html
|
||||||
|
|
||||||
### Submitting your work and handling review
|
### Submitting your work and handling review
|
||||||
|
|
||||||
All patches have to be sent on Github as [pull requests][prs]. To simplify your
|
All patches have to be sent on Github as [pull requests][prs]. To simplify your
|
||||||
life during review it's recommended to check the "give contributors write access
|
life during review it's recommended to check the "give contributors write access
|
||||||
to the branch" checkbox.
|
to the branch" checkbox.
|
||||||
|
|
||||||
|
We use unstable Rustfmt options across the project, so please run
|
||||||
|
`cargo +nightly fmt` before submitting your work. If you are unable to do so,
|
||||||
|
the maintainers can do it for you before merging, just state so in your pull
|
||||||
|
request description. For details on how to use nightly, consult [the
|
||||||
|
documentation][toolchains].
|
||||||
|
|
||||||
|
When editing markdown files (`.md`) they must be wrapped at 80 characters.
|
||||||
|
|
||||||
|
[toolchains]: https://rust-lang.github.io/rustup/concepts/toolchains.html
|
||||||
|
|
||||||
#### Handling review
|
#### Handling review
|
||||||
|
|
||||||
During the review process certain events could require an action from your side,
|
During the review process certain events could require an action from your side,
|
||||||
|
|||||||
446
Cargo.toml
446
Cargo.toml
@@ -1,364 +1,104 @@
|
|||||||
[package]
|
|
||||||
authors = ["The winit contributors", "Pierre Krieger <pierre.krieger1708@gmail.com>"]
|
|
||||||
categories = ["gui"]
|
|
||||||
description = "Cross-platform window creation library."
|
|
||||||
documentation = "https://docs.rs/winit"
|
|
||||||
edition.workspace = true
|
|
||||||
include = [
|
|
||||||
"/build.rs",
|
|
||||||
"/docs",
|
|
||||||
"/examples",
|
|
||||||
"/FEATURES.md",
|
|
||||||
"/LICENSE",
|
|
||||||
"/src",
|
|
||||||
"!/src/platform_impl/web/script",
|
|
||||||
"/src/platform_impl/web/script/**/*.min.js",
|
|
||||||
"/tests",
|
|
||||||
]
|
|
||||||
keywords = ["windowing"]
|
|
||||||
license.workspace = true
|
|
||||||
name = "winit"
|
|
||||||
readme = "README.md"
|
|
||||||
repository.workspace = true
|
|
||||||
rust-version.workspace = true
|
|
||||||
version = "0.30.5"
|
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
|
||||||
features = [
|
|
||||||
"serde",
|
|
||||||
"mint",
|
|
||||||
# Enabled to get docs to compile
|
|
||||||
"android-native-activity",
|
|
||||||
]
|
|
||||||
# These are all tested in CI
|
|
||||||
rustdoc-args = ["--cfg", "docsrs"]
|
|
||||||
targets = [
|
|
||||||
# Windows
|
|
||||||
"i686-pc-windows-msvc",
|
|
||||||
"x86_64-pc-windows-msvc",
|
|
||||||
# macOS
|
|
||||||
"aarch64-apple-darwin",
|
|
||||||
"x86_64-apple-darwin",
|
|
||||||
# Unix (X11 & Wayland)
|
|
||||||
"i686-unknown-linux-gnu",
|
|
||||||
"x86_64-unknown-linux-gnu",
|
|
||||||
# iOS
|
|
||||||
"aarch64-apple-ios",
|
|
||||||
# Android
|
|
||||||
"aarch64-linux-android",
|
|
||||||
# Web
|
|
||||||
"wasm32-unknown-unknown",
|
|
||||||
]
|
|
||||||
|
|
||||||
# Features are documented in either `lib.rs` or under `winit::platform`.
|
|
||||||
[features]
|
|
||||||
android-game-activity = ["android-activity/game-activity"]
|
|
||||||
android-native-activity = ["android-activity/native-activity"]
|
|
||||||
default = ["x11", "wayland", "wayland-dlopen", "wayland-csd-adwaita"]
|
|
||||||
mint = ["dpi/mint"]
|
|
||||||
serde = ["dep:serde", "cursor-icon/serde", "smol_str/serde", "dpi/serde", "bitflags/serde"]
|
|
||||||
wayland = [
|
|
||||||
"wayland-client",
|
|
||||||
"wayland-backend",
|
|
||||||
"wayland-protocols",
|
|
||||||
"wayland-protocols-plasma",
|
|
||||||
"sctk",
|
|
||||||
"ahash",
|
|
||||||
"memmap2",
|
|
||||||
]
|
|
||||||
wayland-csd-adwaita = ["sctk-adwaita", "sctk-adwaita/ab_glyph"]
|
|
||||||
wayland-csd-adwaita-crossfont = ["sctk-adwaita", "sctk-adwaita/crossfont"]
|
|
||||||
wayland-csd-adwaita-notitle = ["sctk-adwaita"]
|
|
||||||
wayland-dlopen = ["wayland-backend/dlopen"]
|
|
||||||
x11 = ["x11-dl", "bytemuck", "percent-encoding", "xkbcommon-dl/x11", "x11rb"]
|
|
||||||
|
|
||||||
[build-dependencies]
|
|
||||||
cfg_aliases = "0.2.1"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
bitflags = "2"
|
|
||||||
cursor-icon = "1.1.0"
|
|
||||||
dpi = { version = "0.1.1", path = "dpi" }
|
|
||||||
rwh_06 = { package = "raw-window-handle", version = "0.6", features = ["std"] }
|
|
||||||
serde = { workspace = true, optional = true }
|
|
||||||
smol_str = "0.3"
|
|
||||||
tracing = { version = "0.1.40", default-features = false }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
image = { version = "0.25.0", default-features = false, features = ["png"] }
|
|
||||||
tracing = { version = "0.1.40", default-features = false, features = ["log"] }
|
|
||||||
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
|
|
||||||
|
|
||||||
[target.'cfg(not(target_os = "android"))'.dev-dependencies]
|
|
||||||
softbuffer = { version = "0.4.6", default-features = false, features = [
|
|
||||||
"x11",
|
|
||||||
"x11-dlopen",
|
|
||||||
"wayland",
|
|
||||||
"wayland-dlopen",
|
|
||||||
] }
|
|
||||||
|
|
||||||
# Android
|
|
||||||
[target.'cfg(target_os = "android")'.dependencies]
|
|
||||||
android-activity = "0.6.0"
|
|
||||||
ndk = { version = "0.9.0", features = ["rwh_06"], default-features = false }
|
|
||||||
|
|
||||||
# AppKit or UIKit
|
|
||||||
[target.'cfg(target_vendor = "apple")'.dependencies]
|
|
||||||
block2 = "0.5.1"
|
|
||||||
core-foundation = "0.9.3"
|
|
||||||
objc2 = "0.5.2"
|
|
||||||
|
|
||||||
# AppKit
|
|
||||||
[target.'cfg(target_os = "macos")'.dependencies]
|
|
||||||
core-graphics = "0.23.1"
|
|
||||||
objc2-app-kit = { version = "0.2.2", features = [
|
|
||||||
"NSAppearance",
|
|
||||||
"NSApplication",
|
|
||||||
"NSBitmapImageRep",
|
|
||||||
"NSButton",
|
|
||||||
"NSColor",
|
|
||||||
"NSControl",
|
|
||||||
"NSCursor",
|
|
||||||
"NSDragging",
|
|
||||||
"NSEvent",
|
|
||||||
"NSGraphics",
|
|
||||||
"NSGraphicsContext",
|
|
||||||
"NSImage",
|
|
||||||
"NSImageRep",
|
|
||||||
"NSMenu",
|
|
||||||
"NSMenuItem",
|
|
||||||
"NSOpenGLView",
|
|
||||||
"NSPasteboard",
|
|
||||||
"NSResponder",
|
|
||||||
"NSRunningApplication",
|
|
||||||
"NSScreen",
|
|
||||||
"NSTextInputClient",
|
|
||||||
"NSTextInputContext",
|
|
||||||
"NSToolbar",
|
|
||||||
"NSView",
|
|
||||||
"NSWindow",
|
|
||||||
"NSWindowScripting",
|
|
||||||
"NSWindowTabGroup",
|
|
||||||
] }
|
|
||||||
objc2-foundation = { version = "0.2.2", features = [
|
|
||||||
"block2",
|
|
||||||
"dispatch",
|
|
||||||
"NSArray",
|
|
||||||
"NSAttributedString",
|
|
||||||
"NSData",
|
|
||||||
"NSDictionary",
|
|
||||||
"NSDistributedNotificationCenter",
|
|
||||||
"NSEnumerator",
|
|
||||||
"NSGeometry",
|
|
||||||
"NSKeyValueObserving",
|
|
||||||
"NSNotification",
|
|
||||||
"NSObjCRuntime",
|
|
||||||
"NSOperation",
|
|
||||||
"NSPathUtilities",
|
|
||||||
"NSProcessInfo",
|
|
||||||
"NSRunLoop",
|
|
||||||
"NSString",
|
|
||||||
"NSThread",
|
|
||||||
"NSValue",
|
|
||||||
] }
|
|
||||||
|
|
||||||
# UIKit
|
|
||||||
[target.'cfg(all(target_vendor = "apple", not(target_os = "macos")))'.dependencies]
|
|
||||||
objc2-foundation = { version = "0.2.2", features = [
|
|
||||||
"block2",
|
|
||||||
"dispatch",
|
|
||||||
"NSArray",
|
|
||||||
"NSEnumerator",
|
|
||||||
"NSGeometry",
|
|
||||||
"NSObjCRuntime",
|
|
||||||
"NSOperation",
|
|
||||||
"NSString",
|
|
||||||
"NSProcessInfo",
|
|
||||||
"NSThread",
|
|
||||||
"NSSet",
|
|
||||||
] }
|
|
||||||
objc2-ui-kit = { version = "0.2.2", features = [
|
|
||||||
"UIApplication",
|
|
||||||
"UIDevice",
|
|
||||||
"UIEvent",
|
|
||||||
"UIGeometry",
|
|
||||||
"UIGestureRecognizer",
|
|
||||||
"UITextInput",
|
|
||||||
"UITextInputTraits",
|
|
||||||
"UIOrientation",
|
|
||||||
"UIPanGestureRecognizer",
|
|
||||||
"UIPinchGestureRecognizer",
|
|
||||||
"UIResponder",
|
|
||||||
"UIRotationGestureRecognizer",
|
|
||||||
"UIScreen",
|
|
||||||
"UIScreenMode",
|
|
||||||
"UITapGestureRecognizer",
|
|
||||||
"UITouch",
|
|
||||||
"UITraitCollection",
|
|
||||||
"UIView",
|
|
||||||
"UIViewController",
|
|
||||||
"UIWindow",
|
|
||||||
] }
|
|
||||||
|
|
||||||
# Windows
|
|
||||||
[target.'cfg(target_os = "windows")'.dependencies]
|
|
||||||
unicode-segmentation = "1.7.1"
|
|
||||||
windows-sys = { version = "0.52.0", features = [
|
|
||||||
"Win32_Devices_HumanInterfaceDevice",
|
|
||||||
"Win32_Foundation",
|
|
||||||
"Win32_Globalization",
|
|
||||||
"Win32_Graphics_Dwm",
|
|
||||||
"Win32_Graphics_Gdi",
|
|
||||||
"Win32_Media",
|
|
||||||
"Win32_System_Com_StructuredStorage",
|
|
||||||
"Win32_System_Com",
|
|
||||||
"Win32_System_LibraryLoader",
|
|
||||||
"Win32_System_Ole",
|
|
||||||
"Win32_Security",
|
|
||||||
"Win32_System_SystemInformation",
|
|
||||||
"Win32_System_SystemServices",
|
|
||||||
"Win32_System_Threading",
|
|
||||||
"Win32_System_WindowsProgramming",
|
|
||||||
"Win32_UI_Accessibility",
|
|
||||||
"Win32_UI_Controls",
|
|
||||||
"Win32_UI_HiDpi",
|
|
||||||
"Win32_UI_Input_Ime",
|
|
||||||
"Win32_UI_Input_KeyboardAndMouse",
|
|
||||||
"Win32_UI_Input_Pointer",
|
|
||||||
"Win32_UI_Input_Touch",
|
|
||||||
"Win32_UI_Shell",
|
|
||||||
"Win32_UI_TextServices",
|
|
||||||
"Win32_UI_WindowsAndMessaging",
|
|
||||||
] }
|
|
||||||
|
|
||||||
# Linux
|
|
||||||
[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_vendor = "apple"))))'.dependencies]
|
|
||||||
ahash = { version = "0.8.7", features = ["no-rng"], optional = true }
|
|
||||||
bytemuck = { version = "1.13.1", default-features = false, optional = true }
|
|
||||||
calloop = "0.13.0"
|
|
||||||
libc = "0.2.64"
|
|
||||||
memmap2 = { version = "0.9.0", optional = true }
|
|
||||||
percent-encoding = { version = "2.0", optional = true }
|
|
||||||
rustix = { version = "0.38.4", default-features = false, features = [
|
|
||||||
"std",
|
|
||||||
"system",
|
|
||||||
"thread",
|
|
||||||
"process",
|
|
||||||
] }
|
|
||||||
sctk = { package = "smithay-client-toolkit", version = "0.19.2", default-features = false, features = [
|
|
||||||
"calloop",
|
|
||||||
], optional = true }
|
|
||||||
sctk-adwaita = { version = "0.10.1", default-features = false, optional = true }
|
|
||||||
wayland-backend = { version = "0.3.5", default-features = false, features = [
|
|
||||||
"client_system",
|
|
||||||
], optional = true }
|
|
||||||
wayland-client = { version = "0.31.4", optional = true }
|
|
||||||
wayland-protocols = { version = "0.32.2", features = ["staging"], optional = true }
|
|
||||||
wayland-protocols-plasma = { version = "0.3.2", features = ["client"], optional = true }
|
|
||||||
x11-dl = { version = "2.19.1", optional = true }
|
|
||||||
x11rb = { version = "0.13.0", default-features = false, features = [
|
|
||||||
"allow-unsafe-code",
|
|
||||||
"cursor",
|
|
||||||
"dl-libxcb",
|
|
||||||
"randr",
|
|
||||||
"resource_manager",
|
|
||||||
"sync",
|
|
||||||
"xinput",
|
|
||||||
"xkb",
|
|
||||||
], optional = true }
|
|
||||||
xkbcommon-dl = "0.4.2"
|
|
||||||
|
|
||||||
# Orbital
|
|
||||||
[target.'cfg(target_os = "redox")'.dependencies]
|
|
||||||
orbclient = { version = "0.3.47", default-features = false }
|
|
||||||
redox_syscall = "0.5.7"
|
|
||||||
|
|
||||||
# Web
|
|
||||||
[target.'cfg(target_family = "wasm")'.dependencies]
|
|
||||||
js-sys = "0.3.70"
|
|
||||||
pin-project = "1"
|
|
||||||
wasm-bindgen = "0.2.93"
|
|
||||||
wasm-bindgen-futures = "0.4.43"
|
|
||||||
web-time = "1"
|
|
||||||
web_sys = { package = "web-sys", version = "0.3.70", features = [
|
|
||||||
"AbortController",
|
|
||||||
"AbortSignal",
|
|
||||||
"Blob",
|
|
||||||
"BlobPropertyBag",
|
|
||||||
"console",
|
|
||||||
"CssStyleDeclaration",
|
|
||||||
"Document",
|
|
||||||
"DomException",
|
|
||||||
"DomRect",
|
|
||||||
"DomRectReadOnly",
|
|
||||||
"Element",
|
|
||||||
"Event",
|
|
||||||
"EventTarget",
|
|
||||||
"FocusEvent",
|
|
||||||
"HtmlCanvasElement",
|
|
||||||
"HtmlElement",
|
|
||||||
"HtmlHtmlElement",
|
|
||||||
"HtmlImageElement",
|
|
||||||
"ImageBitmap",
|
|
||||||
"ImageBitmapOptions",
|
|
||||||
"ImageBitmapRenderingContext",
|
|
||||||
"ImageData",
|
|
||||||
"IntersectionObserver",
|
|
||||||
"IntersectionObserverEntry",
|
|
||||||
"KeyboardEvent",
|
|
||||||
"MediaQueryList",
|
|
||||||
"MessageChannel",
|
|
||||||
"MessagePort",
|
|
||||||
"Navigator",
|
|
||||||
"Node",
|
|
||||||
"OrientationLockType",
|
|
||||||
"OrientationType",
|
|
||||||
"PageTransitionEvent",
|
|
||||||
"Permissions",
|
|
||||||
"PermissionState",
|
|
||||||
"PermissionStatus",
|
|
||||||
"PointerEvent",
|
|
||||||
"PremultiplyAlpha",
|
|
||||||
"ResizeObserver",
|
|
||||||
"ResizeObserverBoxOptions",
|
|
||||||
"ResizeObserverEntry",
|
|
||||||
"ResizeObserverOptions",
|
|
||||||
"ResizeObserverSize",
|
|
||||||
"Screen",
|
|
||||||
"ScreenOrientation",
|
|
||||||
"Url",
|
|
||||||
"VisibilityState",
|
|
||||||
"WheelEvent",
|
|
||||||
"Window",
|
|
||||||
"Worker",
|
|
||||||
] }
|
|
||||||
|
|
||||||
[target.'cfg(all(target_family = "wasm", target_feature = "atomics"))'.dependencies]
|
|
||||||
atomic-waker = "1"
|
|
||||||
concurrent-queue = { version = "2", default-features = false }
|
|
||||||
|
|
||||||
[target.'cfg(target_family = "wasm")'.dev-dependencies]
|
|
||||||
console_error_panic_hook = "0.1"
|
|
||||||
tracing-web = "0.1"
|
|
||||||
wasm-bindgen-test = "0.3"
|
|
||||||
|
|
||||||
[[example]]
|
|
||||||
doc-scrape-examples = true
|
|
||||||
name = "window"
|
|
||||||
|
|
||||||
[[example]]
|
|
||||||
name = "child_window"
|
|
||||||
|
|
||||||
[workspace]
|
[workspace]
|
||||||
members = ["dpi"]
|
default-members = ["winit"]
|
||||||
|
members = ["dpi", "winit*"]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
repository = "https://github.com/rust-windowing/winit"
|
repository = "https://github.com/rust-windowing/winit"
|
||||||
rust-version = "1.73"
|
rust-version = "1.80"
|
||||||
|
version = "0.30.12"
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
|
# Workspace dependencies.
|
||||||
|
# `winit` has no version here to allow using it in dev deps for docs.
|
||||||
|
winit = { path = "winit" }
|
||||||
|
winit-android = { version = "0.30.12", path = "winit-android" }
|
||||||
|
winit-appkit = { version = "0.30.12", path = "winit-appkit" }
|
||||||
|
winit-common = { version = "0.30.12", path = "winit-common" }
|
||||||
|
winit-core = { version = "0.30.12", path = "winit-core" }
|
||||||
|
winit-orbital = { version = "0.30.12", path = "winit-orbital" }
|
||||||
|
winit-uikit = { version = "0.30.12", path = "winit-uikit" }
|
||||||
|
winit-wayland = { version = "0.30.12", path = "winit-wayland", default-features = false }
|
||||||
|
winit-web = { version = "0.30.12", path = "winit-web" }
|
||||||
|
winit-win32 = { version = "0.30.12", path = "winit-win32" }
|
||||||
|
winit-x11 = { version = "0.30.12", path = "winit-x11" }
|
||||||
|
|
||||||
|
# Core dependencies.
|
||||||
|
bitflags = "2"
|
||||||
|
cfg_aliases = "0.2.1"
|
||||||
|
cursor-icon = "1.1.0"
|
||||||
|
dpi = { version = "0.1.2", path = "dpi" }
|
||||||
|
keyboard-types = "0.8.0"
|
||||||
mint = "0.5.6"
|
mint = "0.5.6"
|
||||||
|
rwh_06 = { package = "raw-window-handle", version = "0.6", features = ["std"] }
|
||||||
serde = { version = "1", features = ["serde_derive"] }
|
serde = { version = "1", features = ["serde_derive"] }
|
||||||
|
smol_str = "0.3"
|
||||||
|
tracing = { version = "0.1.40", default-features = false }
|
||||||
|
|
||||||
|
# Dev dependencies.
|
||||||
|
image = { version = "0.25.0", default-features = false }
|
||||||
|
softbuffer = { version = "0.4.6", default-features = false, features = [
|
||||||
|
"x11",
|
||||||
|
"x11-dlopen",
|
||||||
|
"wayland",
|
||||||
|
"wayland-dlopen",
|
||||||
|
] }
|
||||||
|
tracing-subscriber = "0.3.18"
|
||||||
|
|
||||||
|
# Android dependencies.
|
||||||
|
android-activity = "0.6.0"
|
||||||
|
ndk = { version = "0.9.0", features = ["rwh_06"], default-features = false }
|
||||||
|
|
||||||
|
# Apple dependencies.
|
||||||
|
block2 = "0.6.1"
|
||||||
|
dispatch2 = { version = "0.3.0", default-features = false, features = ["std", "objc2"] }
|
||||||
|
objc2 = { version = "0.6.1", features = ["relax-sign-encoding"] }
|
||||||
|
objc2-app-kit = { version = "0.3.1", default-features = false }
|
||||||
|
objc2-core-foundation = { version = "0.3.1", default-features = false }
|
||||||
|
objc2-core-graphics = { version = "0.3.1", default-features = false }
|
||||||
|
objc2-core-video = { version = "0.3.1", default-features = false }
|
||||||
|
objc2-foundation = { version = "0.3.1", default-features = false }
|
||||||
|
objc2-ui-kit = { version = "0.3.1", default-features = false }
|
||||||
|
|
||||||
|
# Windows dependencies.
|
||||||
|
unicode-segmentation = "1.7.1"
|
||||||
|
windows-sys = "0.59.0"
|
||||||
|
|
||||||
|
# Linux dependencies.
|
||||||
|
ahash = { version = "0.8.7", features = ["no-rng"] }
|
||||||
|
bytemuck = { version = "1.13.1", default-features = false }
|
||||||
|
calloop = "0.13.0"
|
||||||
|
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.
|
||||||
|
orbclient = { version = "0.3.47", default-features = false }
|
||||||
|
redox_syscall = "0.5.7"
|
||||||
|
|
||||||
|
# Web dependencies.
|
||||||
|
atomic-waker = "1"
|
||||||
|
concurrent-queue = { version = "2", default-features = false }
|
||||||
|
console_error_panic_hook = "0.1"
|
||||||
|
js-sys = "0.3.70"
|
||||||
|
pin-project = "1"
|
||||||
|
tracing-web = "0.1"
|
||||||
|
wasm-bindgen = "0.2.93"
|
||||||
|
wasm-bindgen-futures = "0.4.43"
|
||||||
|
wasm-bindgen-test = "0.3"
|
||||||
|
web-time = "1"
|
||||||
|
web_sys = { package = "web-sys", version = "0.3.70" }
|
||||||
|
|||||||
14
README.md
14
README.md
@@ -8,7 +8,7 @@
|
|||||||
|
|
||||||
```toml
|
```toml
|
||||||
[dependencies]
|
[dependencies]
|
||||||
winit = "0.30.5"
|
winit = "0.30.12"
|
||||||
```
|
```
|
||||||
|
|
||||||
## [Documentation](https://docs.rs/winit)
|
## [Documentation](https://docs.rs/winit)
|
||||||
@@ -33,9 +33,13 @@ Winit is designed to be a low-level brick in a hierarchy of libraries. Consequen
|
|||||||
show something on the window you need to use the platform-specific getters provided by winit, or
|
show something on the window you need to use the platform-specific getters provided by winit, or
|
||||||
another library.
|
another library.
|
||||||
|
|
||||||
|
## CONTRIBUTING
|
||||||
|
|
||||||
|
For contributing guidelines see [CONTRIBUTING.md](./CONTRIBUTING.md).
|
||||||
|
|
||||||
## MSRV Policy
|
## MSRV Policy
|
||||||
|
|
||||||
This crate's Minimum Supported Rust Version (MSRV) is **1.73**. 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.
|
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
|
As a **tentative** policy, the upper bound of the MSRV is given by the following
|
||||||
@@ -67,3 +71,9 @@ same MSRV policy.
|
|||||||
### Platform-specific usage
|
### Platform-specific usage
|
||||||
|
|
||||||
Check out the [`winit::platform`](https://docs.rs/winit/latest/winit/platform/index.html) module for platform-specific usage.
|
Check out the [`winit::platform`](https://docs.rs/winit/latest/winit/platform/index.html) module for platform-specific usage.
|
||||||
|
|
||||||
|
### Repository License
|
||||||
|
|
||||||
|
Note that the license in `LICENSE` doesn't apply in full to the DPI package [./dpi](./dpi).
|
||||||
|
Full details can be found in that folder's README.
|
||||||
|
<!-- This doesn't apply to users of the Winit crate, but this is also the repository level README -->
|
||||||
|
|||||||
29
clippy.toml
29
clippy.toml
@@ -1,16 +1,17 @@
|
|||||||
|
# Using allow-invalid because this is platform-specific code
|
||||||
disallowed-methods = [
|
disallowed-methods = [
|
||||||
{ 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::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." },
|
||||||
{ path = "objc2_app_kit::NSWindow::setFrameTopLeftPoint", reason = "Not sufficient when working with Winit's coordinate system, use `flip_window_screen_coordinates` 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" },
|
||||||
{ path = "web_sys::Document::exit_fullscreen", reason = "Doesn't account for compatibility with Safari" },
|
{ allow-invalid = true, path = "web_sys::Document::exit_fullscreen", reason = "Doesn't account for compatibility with Safari" },
|
||||||
{ path = "web_sys::Document::fullscreen_element", reason = "Doesn't account for compatibility with Safari" },
|
{ allow-invalid = true, path = "web_sys::Document::fullscreen_element", reason = "Doesn't account for compatibility with Safari" },
|
||||||
{ path = "web_sys::Element::request_fullscreen", reason = "Doesn't account for compatibility with Safari" },
|
{ allow-invalid = true, path = "web_sys::Element::request_fullscreen", reason = "Doesn't account for compatibility with Safari" },
|
||||||
{ path = "web_sys::HtmlCanvasElement::height", reason = "Winit shouldn't touch the internal canvas size" },
|
{ allow-invalid = true, path = "web_sys::HtmlCanvasElement::height", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
{ path = "web_sys::HtmlCanvasElement::set_height", reason = "Winit shouldn't touch the internal canvas size" },
|
{ allow-invalid = true, path = "web_sys::HtmlCanvasElement::set_height", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
{ path = "web_sys::HtmlCanvasElement::set_width", reason = "Winit shouldn't touch the internal canvas size" },
|
{ allow-invalid = true, path = "web_sys::HtmlCanvasElement::set_width", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
{ path = "web_sys::HtmlCanvasElement::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" },
|
||||||
{ path = "web_sys::HtmlElement::style", reason = "cache this to reduce calls to JS" },
|
{ allow-invalid = true, path = "web_sys::HtmlElement::style", reason = "cache this to reduce calls to JS" },
|
||||||
{ path = "web_sys::Window::document", reason = "cache this to reduce calls to JS" },
|
{ allow-invalid = true, path = "web_sys::Window::document", reason = "cache this to reduce calls to JS" },
|
||||||
{ path = "web_sys::Window::get_computed_style", 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" },
|
||||||
{ path = "web_sys::Window::navigator", reason = "cache this to reduce calls to JS" },
|
{ allow-invalid = true, path = "web_sys::Window::navigator", reason = "cache this to reduce calls to JS" },
|
||||||
{ path = "web_sys::window", reason = "is not available in every context" },
|
{ allow-invalid = true, path = "web_sys::window", reason = "is not available in every context" },
|
||||||
]
|
]
|
||||||
|
|||||||
12
deny.toml
12
deny.toml
@@ -38,8 +38,12 @@ private = { ignore = true }
|
|||||||
|
|
||||||
[bans]
|
[bans]
|
||||||
multiple-versions = "deny"
|
multiple-versions = "deny"
|
||||||
skip = [{ crate = "bitflags@1", reason = "the ecosystem is in the process of migrating" }]
|
skip = [
|
||||||
wildcards = "allow" # at least until https://github.com/EmbarkStudios/cargo-deny/issues/241 is fixed
|
{ 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" },
|
||||||
|
]
|
||||||
|
wildcards = "allow" # at least until https://github.com/EmbarkStudios/cargo-deny/issues/241 is fixed
|
||||||
|
|
||||||
[bans.build]
|
[bans.build]
|
||||||
include-archives = true
|
include-archives = true
|
||||||
@@ -51,6 +55,10 @@ allow = [
|
|||||||
]
|
]
|
||||||
crate = "android-activity"
|
crate = "android-activity"
|
||||||
|
|
||||||
|
[[bans.build.bypass]]
|
||||||
|
allow-globs = ["ci/*", "githooks/*"]
|
||||||
|
crate = "zerocopy"
|
||||||
|
|
||||||
[[bans.build.bypass]]
|
[[bans.build.bypass]]
|
||||||
allow-globs = ["freetype2/*"]
|
allow-globs = ["freetype2/*"]
|
||||||
crate = "freetype-sys"
|
crate = "freetype-sys"
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
# Image Attribution
|
|
||||||
|
|
||||||
These images are used in the documentation of `winit`.
|
|
||||||
|
|
||||||
## keyboard_*.svg
|
|
||||||
|
|
||||||
These files are a modified version of "[ANSI US QWERTY (Windows)](https://commons.wikimedia.org/wiki/File:ANSI_US_QWERTY_(Windows).svg)"
|
|
||||||
by [Tomiĉo] (https://commons.wikimedia.org/wiki/User:Tomi%C4%89o). It was
|
|
||||||
originally released under the [CC-BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/deed.en)
|
|
||||||
License. Minor modifications have been made by [John Nunley](https://github.com/notgull),
|
|
||||||
which have been released under the same license as a derivative work.
|
|
||||||
|
|
||||||
## `coordinate-systems*`
|
|
||||||
|
|
||||||
These files are created by [Mads Marquart](https://github.com/madsmtm) using
|
|
||||||
[draw.io](https://draw.io/), and compressed using [svgomg.net](https://svgomg.net/).
|
|
||||||
|
|
||||||
They are licensed under the [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/) license.
|
|
||||||
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 73 KiB |
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 73 KiB |
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 73 KiB |
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 73 KiB |
@@ -11,7 +11,10 @@ Unreleased` header.
|
|||||||
|
|
||||||
## Unreleased
|
## Unreleased
|
||||||
|
|
||||||
|
## 0.1.2
|
||||||
|
|
||||||
- Added `Insets`, `LogicalInsets` and `PhysicalInsets` types.
|
- Added `Insets`, `LogicalInsets` and `PhysicalInsets` types.
|
||||||
|
- Make `no_std` compatible. If you use this functionality, DPI's license has changed.
|
||||||
|
|
||||||
## 0.1.1
|
## 0.1.1
|
||||||
|
|
||||||
|
|||||||
@@ -3,16 +3,22 @@ categories = ["gui"]
|
|||||||
description = "Types for handling UI scaling"
|
description = "Types for handling UI scaling"
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
keywords = ["DPI", "HiDPI", "scale-factor"]
|
keywords = ["DPI", "HiDPI", "scale-factor"]
|
||||||
license.workspace = true
|
# N.B. This is "AND", because of the imported libm code.
|
||||||
|
license = "Apache-2.0 AND MIT"
|
||||||
name = "dpi"
|
name = "dpi"
|
||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
version = "0.1.1"
|
version = "0.1.2"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
|
default = ["std"]
|
||||||
|
|
||||||
mint = ["dep:mint"]
|
mint = ["dep:mint"]
|
||||||
serde = ["dep:serde"]
|
serde = ["dep:serde"]
|
||||||
|
|
||||||
|
# Access mathematical functions using the standard library implementations
|
||||||
|
std = []
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
mint = { workspace = true, optional = true }
|
mint = { workspace = true, optional = true }
|
||||||
serde = { workspace = true, optional = true }
|
serde = { workspace = true, optional = true }
|
||||||
|
|||||||
51
dpi/LICENSE-LIBM-MIT
Normal file
51
dpi/LICENSE-LIBM-MIT
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
rust-lang/libm as a whole is available for use under the MIT license:
|
||||||
|
|
||||||
|
------------------------------------------------------------------------------
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
This Rust library contains the following copyrights:
|
||||||
|
|
||||||
|
Copyright (c) 2018 Jorge Aparicio
|
||||||
|
|
||||||
|
Portions of this software are derived from third-party works licensed under
|
||||||
|
terms compatible with the above MIT license:
|
||||||
|
|
||||||
|
* musl libc https://www.musl-libc.org/. This library contains the following
|
||||||
|
copyright:
|
||||||
|
|
||||||
|
Copyright © 2005-2020 Rich Felker, et al.
|
||||||
|
|
||||||
|
* The CORE-MATH project https://core-math.gitlabpages.inria.fr/. CORE-MATH
|
||||||
|
routines are available under the MIT license on a per-file basis.
|
||||||
|
|
||||||
|
The musl libc COPYRIGHT file also includes the following notice relevant to
|
||||||
|
math portions of the library:
|
||||||
|
|
||||||
|
------------------------------------------------------------------------------
|
||||||
|
Much of the math library code (src/math/* and src/complex/*) is
|
||||||
|
Copyright © 1993,2004 Sun Microsystems or
|
||||||
|
Copyright © 2003-2011 David Schultz or
|
||||||
|
Copyright © 2003-2009 Steven G. Kargl or
|
||||||
|
Copyright © 2003-2009 Bruce D. Evans or
|
||||||
|
Copyright © 2008 Stephen L. Moshier or
|
||||||
|
Copyright © 2017-2018 Arm Limited
|
||||||
|
and labelled as such in comments in the individual source files. All
|
||||||
|
have been licensed under extremely permissive terms.
|
||||||
|
------------------------------------------------------------------------------
|
||||||
18
dpi/README.md
Normal file
18
dpi/README.md
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
# DPI
|
||||||
|
|
||||||
|
Full docs can be found on docs.rs.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Most of DPI is licensed under the Apache License, Version 2.0 ([LICENSE](LICENSE)).
|
||||||
|
All files except for `src/libm.rs` (and `LICENSE-LIBM-MIT`) are available solely under that license.
|
||||||
|
|
||||||
|
For its `no_std` support, DPI uses code from the [libm](https://crates.io/crates/libm) crate.
|
||||||
|
This is in the `libm.rs` file, and is licensed solely under the MIT Licence ([LICENSE-LIBM-MIT](LICENSE-LIBM-MIT)).
|
||||||
|
That file contains details of all potentially applicable copyright notices.
|
||||||
|
This is feature gated to only be included if you disable the `std` feature, otherwise it will not be compiled into your final binary
|
||||||
|
(and so these license terms will not apply).
|
||||||
|
|
||||||
|
Overall, this means that the license for this crate depends on what features you have enabled.
|
||||||
|
If you enable the `std` feature, then DPI uses only code available under the Apache-2.0 license, and so can be used under the terms of that license.
|
||||||
|
However, if you disable the `std` feature, then both these licenses must be followed to use the crate as a whole.
|
||||||
@@ -54,13 +54,25 @@
|
|||||||
//!
|
//!
|
||||||
//! * `serde`: Enables serialization/deserialization of certain types with [Serde](https://crates.io/crates/serde).
|
//! * `serde`: Enables serialization/deserialization of certain types with [Serde](https://crates.io/crates/serde).
|
||||||
//! * `mint`: Enables mint (math interoperability standard types) conversions.
|
//! * `mint`: Enables mint (math interoperability standard types) conversions.
|
||||||
|
//! * `std` (enabled by default): Uses the standard library mathematical functions (normally through
|
||||||
|
//! your target platform's libm). This feature also changes the library's license from `Apache-2.0
|
||||||
|
//! AND MIT` to `APACHE-2.0` (only). For full details, see the package README.
|
||||||
//!
|
//!
|
||||||
|
//! To use this library on a target without the standard library available, you should disable
|
||||||
|
//! default features (thus disabling the `std` feature, with the license consequences thereof).
|
||||||
//!
|
//!
|
||||||
//! [points]: https://en.wikipedia.org/wiki/Point_(typography)
|
//! [points]: https://en.wikipedia.org/wiki/Point_(typography)
|
||||||
//! [picas]: https://en.wikipedia.org/wiki/Pica_(typography)
|
//! [picas]: https://en.wikipedia.org/wiki/Pica_(typography)
|
||||||
|
|
||||||
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide), doc(cfg_hide(doc, docsrs)))]
|
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide), doc(cfg_hide(doc, docsrs)))]
|
||||||
#![forbid(unsafe_code)]
|
#![cfg_attr(feature = "std", forbid(unsafe_code))]
|
||||||
|
#![no_std]
|
||||||
|
|
||||||
|
#[cfg(not(feature = "std"))]
|
||||||
|
mod libm;
|
||||||
|
|
||||||
|
#[cfg(any(feature = "std", test))]
|
||||||
|
extern crate std;
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -74,32 +86,32 @@ pub trait Pixel: Copy + Into<f64> {
|
|||||||
|
|
||||||
impl Pixel for u8 {
|
impl Pixel for u8 {
|
||||||
fn from_f64(f: f64) -> Self {
|
fn from_f64(f: f64) -> Self {
|
||||||
f.round() as u8
|
round(f) as u8
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Pixel for u16 {
|
impl Pixel for u16 {
|
||||||
fn from_f64(f: f64) -> Self {
|
fn from_f64(f: f64) -> Self {
|
||||||
f.round() as u16
|
round(f) as u16
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Pixel for u32 {
|
impl Pixel for u32 {
|
||||||
fn from_f64(f: f64) -> Self {
|
fn from_f64(f: f64) -> Self {
|
||||||
f.round() as u32
|
round(f) as u32
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Pixel for i8 {
|
impl Pixel for i8 {
|
||||||
fn from_f64(f: f64) -> Self {
|
fn from_f64(f: f64) -> Self {
|
||||||
f.round() as i8
|
round(f) as i8
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Pixel for i16 {
|
impl Pixel for i16 {
|
||||||
fn from_f64(f: f64) -> Self {
|
fn from_f64(f: f64) -> Self {
|
||||||
f.round() as i16
|
round(f) as i16
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Pixel for i32 {
|
impl Pixel for i32 {
|
||||||
fn from_f64(f: f64) -> Self {
|
fn from_f64(f: f64) -> Self {
|
||||||
f.round() as i32
|
round(f) as i32
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Pixel for f32 {
|
impl Pixel for f32 {
|
||||||
@@ -113,6 +125,15 @@ impl Pixel for f64 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Round f to the closest integer, rounding away from `0.0`
|
||||||
|
#[inline]
|
||||||
|
fn round(f: f64) -> f64 {
|
||||||
|
#[cfg(feature = "std")]
|
||||||
|
return f.round();
|
||||||
|
#[cfg(not(feature = "std"))]
|
||||||
|
return libm::round(f);
|
||||||
|
}
|
||||||
|
|
||||||
/// Checks that the scale factor is a normal positive `f64`.
|
/// Checks that the scale factor is a normal positive `f64`.
|
||||||
///
|
///
|
||||||
/// All functions that take a scale factor assert that this will return `true`. If you're sourcing
|
/// All functions that take a scale factor assert that this will return `true`. If you're sourcing
|
||||||
@@ -1270,20 +1291,20 @@ mod tests {
|
|||||||
// Eat coverage for the Debug impls et al
|
// Eat coverage for the Debug impls et al
|
||||||
#[test]
|
#[test]
|
||||||
fn ensure_attrs_do_not_panic() {
|
fn ensure_attrs_do_not_panic() {
|
||||||
let _ = format!("{:?}", LogicalPosition::<u32>::default().clone());
|
let _ = std::format!("{:?}", LogicalPosition::<u32>::default().clone());
|
||||||
HashSet::new().insert(LogicalPosition::<u32>::default());
|
HashSet::new().insert(LogicalPosition::<u32>::default());
|
||||||
|
|
||||||
let _ = format!("{:?}", PhysicalPosition::<u32>::default().clone());
|
let _ = std::format!("{:?}", PhysicalPosition::<u32>::default().clone());
|
||||||
HashSet::new().insert(PhysicalPosition::<u32>::default());
|
HashSet::new().insert(PhysicalPosition::<u32>::default());
|
||||||
|
|
||||||
let _ = format!("{:?}", LogicalSize::<u32>::default().clone());
|
let _ = std::format!("{:?}", LogicalSize::<u32>::default().clone());
|
||||||
HashSet::new().insert(LogicalSize::<u32>::default());
|
HashSet::new().insert(LogicalSize::<u32>::default());
|
||||||
|
|
||||||
let _ = format!("{:?}", PhysicalSize::<u32>::default().clone());
|
let _ = std::format!("{:?}", PhysicalSize::<u32>::default().clone());
|
||||||
HashSet::new().insert(PhysicalSize::<u32>::default());
|
HashSet::new().insert(PhysicalSize::<u32>::default());
|
||||||
|
|
||||||
let _ = format!("{:?}", Size::Physical((1, 2).into()).clone());
|
let _ = std::format!("{:?}", Size::Physical((1, 2).into()).clone());
|
||||||
let _ = format!("{:?}", Position::Physical((1, 2).into()).clone());
|
let _ = std::format!("{:?}", Position::Physical((1, 2).into()).clone());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
56
dpi/src/libm.rs
Normal file
56
dpi/src/libm.rs
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
// Copyright (c) 2018 Jorge Aparicio
|
||||||
|
// Copyright © 2005-2020 Rich Felker, et al.
|
||||||
|
// Copyright © 1993,2004 Sun Microsystems or
|
||||||
|
// Copyright © 2003-2011 David Schultz or
|
||||||
|
// Copyright © 2003-2009 Steven G. Kargl or
|
||||||
|
// Copyright © 2003-2009 Bruce D. Evans or
|
||||||
|
// Copyright © 2008 Stephen L. Moshier or
|
||||||
|
// Copyright © 2017-2018 Arm Limited
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
// This file is licensed solely under the terms discussed in LICENSE-LIBM-MIT at the crate root.
|
||||||
|
// See the package-level README for full details.
|
||||||
|
|
||||||
|
// Taken from https://github.com/rust-lang/libm/blob/master/src/math/mod.rs#L1
|
||||||
|
macro_rules! force_eval {
|
||||||
|
($e:expr) => {
|
||||||
|
unsafe { ::core::ptr::read_volatile(&$e) }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Taken from https://github.com/rust-lang/libm/blob/libm-v0.2.11/src/math/round.rs
|
||||||
|
pub(crate) fn round(x: f64) -> f64 {
|
||||||
|
trunc(x + copysign(0.5 - 0.25 * f64::EPSILON, x))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adapted from: https://github.com/rust-lang/libm/blob/libm-v0.2.11/src/math/trunc.rs#L8-L12
|
||||||
|
#[allow(clippy::needless_late_init /*, reason = "The original libm code uses this style" */)]
|
||||||
|
fn trunc(x: f64) -> f64 {
|
||||||
|
let x1p120 = f64::from_bits(0x4770000000000000); // 0x1p120f === 2 ^ 120
|
||||||
|
|
||||||
|
let mut i: u64 = x.to_bits();
|
||||||
|
let mut e: i64 = ((i >> 52) & 0x7ff) as i64 - 0x3ff + 12;
|
||||||
|
let m: u64;
|
||||||
|
|
||||||
|
if e >= 52 + 12 {
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
if e < 12 {
|
||||||
|
e = 1;
|
||||||
|
}
|
||||||
|
m = -1i64 as u64 >> e;
|
||||||
|
if (i & m) == 0 {
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
force_eval!(x + x1p120);
|
||||||
|
i &= !m;
|
||||||
|
f64::from_bits(i)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Taken from https://github.com/rust-lang/libm/blob/libm-v0.2.11/src/math/copysign.rs
|
||||||
|
fn copysign(x: f64, y: f64) -> f64 {
|
||||||
|
let mut ux = x.to_bits();
|
||||||
|
let uy = y.to_bits();
|
||||||
|
ux &= (!0) >> 1;
|
||||||
|
ux |= uy & (1 << 63);
|
||||||
|
f64::from_bits(ux)
|
||||||
|
}
|
||||||
1416
examples/application.rs
Normal file
1416
examples/application.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -13,10 +13,22 @@ fn main() -> Result<(), impl std::error::Error> {
|
|||||||
#[path = "util/fill.rs"]
|
#[path = "util/fill.rs"]
|
||||||
mod fill;
|
mod fill;
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Debug)]
|
||||||
|
struct WindowData {
|
||||||
|
window: Box<dyn Window>,
|
||||||
|
color: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowData {
|
||||||
|
fn new(window: Box<dyn Window>, color: u32) -> Self {
|
||||||
|
Self { window, color }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Debug)]
|
||||||
struct Application {
|
struct Application {
|
||||||
parent_window_id: Option<WindowId>,
|
parent_window_id: Option<WindowId>,
|
||||||
windows: HashMap<WindowId, Box<dyn Window>>,
|
windows: HashMap<WindowId, WindowData>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ApplicationHandler for Application {
|
impl ApplicationHandler for Application {
|
||||||
@@ -26,11 +38,10 @@ fn main() -> Result<(), impl std::error::Error> {
|
|||||||
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
||||||
.with_surface_size(LogicalSize::new(640.0f32, 480.0f32));
|
.with_surface_size(LogicalSize::new(640.0f32, 480.0f32));
|
||||||
let window = event_loop.create_window(attributes).unwrap();
|
let window = event_loop.create_window(attributes).unwrap();
|
||||||
|
|
||||||
println!("Parent window id: {:?})", window.id());
|
println!("Parent window id: {:?})", window.id());
|
||||||
self.parent_window_id = Some(window.id());
|
self.parent_window_id = Some(window.id());
|
||||||
|
|
||||||
self.windows.insert(window.id(), window);
|
self.windows.insert(window.id(), WindowData::new(window, 0xffbbbbbb));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn window_event(
|
fn window_event(
|
||||||
@@ -56,15 +67,24 @@ fn main() -> Result<(), impl std::error::Error> {
|
|||||||
event: KeyEvent { state: ElementState::Pressed, .. },
|
event: KeyEvent { state: ElementState::Pressed, .. },
|
||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
|
let child_index = self.windows.len() - 1;
|
||||||
|
let child_color =
|
||||||
|
0xff000000 + 3_u32.pow((child_index + 2).rem_euclid(16) as u32);
|
||||||
|
|
||||||
let parent_window = self.windows.get(&self.parent_window_id.unwrap()).unwrap();
|
let parent_window = self.windows.get(&self.parent_window_id.unwrap()).unwrap();
|
||||||
let child_window = spawn_child_window(parent_window.as_ref(), event_loop);
|
let child_window =
|
||||||
|
spawn_child_window(parent_window.window.as_ref(), event_loop, child_index);
|
||||||
let child_id = child_window.id();
|
let child_id = child_window.id();
|
||||||
println!("Child window created with id: {child_id:?}");
|
println!("Child window created with id: {child_id:?}");
|
||||||
self.windows.insert(child_id, child_window);
|
self.windows.insert(child_id, WindowData::new(child_window, child_color));
|
||||||
},
|
},
|
||||||
WindowEvent::RedrawRequested => {
|
WindowEvent::RedrawRequested => {
|
||||||
if let Some(window) = self.windows.get(&window_id) {
|
if let Some(window) = self.windows.get(&window_id) {
|
||||||
fill::fill_window(window.as_ref());
|
if window_id == self.parent_window_id.unwrap() {
|
||||||
|
fill::fill_window(window.window.as_ref());
|
||||||
|
} else {
|
||||||
|
fill::fill_window_with_color(window.window.as_ref(), window.color);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
_ => (),
|
_ => (),
|
||||||
@@ -75,12 +95,20 @@ fn main() -> Result<(), impl std::error::Error> {
|
|||||||
fn spawn_child_window(
|
fn spawn_child_window(
|
||||||
parent: &dyn Window,
|
parent: &dyn Window,
|
||||||
event_loop: &dyn ActiveEventLoop,
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
child_count: usize,
|
||||||
) -> Box<dyn Window> {
|
) -> Box<dyn Window> {
|
||||||
let parent = parent.raw_window_handle().unwrap();
|
let parent = parent.raw_window_handle().unwrap();
|
||||||
|
|
||||||
|
// As child count increases, x goes from 0*128 to 5*128 and then repeats
|
||||||
|
let x: f64 = child_count.rem_euclid(5) as f64 * 128.0;
|
||||||
|
|
||||||
|
// After 5 windows have been put side by side horizontally, a new row starts
|
||||||
|
let y: f64 = (child_count / 5) as f64 * 96.0;
|
||||||
|
|
||||||
let mut window_attributes = WindowAttributes::default()
|
let mut window_attributes = WindowAttributes::default()
|
||||||
.with_title("child window")
|
.with_title("child window")
|
||||||
.with_surface_size(LogicalSize::new(200.0f32, 200.0f32))
|
.with_surface_size(LogicalSize::new(128.0f32, 96.0))
|
||||||
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
.with_position(Position::Logical(LogicalPosition::new(x, y)))
|
||||||
.with_visible(true);
|
.with_visible(true);
|
||||||
// `with_parent_window` is unsafe. Parent window must be a valid window.
|
// `with_parent_window` is unsafe. Parent window must be a valid window.
|
||||||
window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) };
|
window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) };
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ fn main() -> Result<(), impl std::error::Error> {
|
|||||||
event_loop.run_app(ControlFlowDemo::default())
|
event_loop.run_app(ControlFlowDemo::default())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default, Debug)]
|
||||||
struct ControlFlowDemo {
|
struct ControlFlowDemo {
|
||||||
mode: Mode,
|
mode: Mode,
|
||||||
request_redraw: bool,
|
request_redraw: bool,
|
||||||
|
|||||||
65
examples/dnd.rs
Normal file
65
examples/dnd.rs
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
|
||||||
|
use winit::application::ApplicationHandler;
|
||||||
|
use winit::event::WindowEvent;
|
||||||
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
#[path = "util/tracing.rs"]
|
||||||
|
mod tracing;
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
tracing::init();
|
||||||
|
|
||||||
|
let event_loop = EventLoop::new()?;
|
||||||
|
|
||||||
|
let app = Application::new();
|
||||||
|
Ok(event_loop.run_app(app)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Application state and event handling.
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Application {
|
||||||
|
window: Option<Box<dyn Window>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Application {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self { window: None }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for Application {
|
||||||
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
let window_attributes =
|
||||||
|
WindowAttributes::default().with_title("Drag and drop files on me!");
|
||||||
|
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
_window_id: WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
match event {
|
||||||
|
WindowEvent::DragLeft { .. }
|
||||||
|
| WindowEvent::DragEntered { .. }
|
||||||
|
| WindowEvent::DragMoved { .. }
|
||||||
|
| WindowEvent::DragDropped { .. } => {
|
||||||
|
println!("{event:?}");
|
||||||
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
let window = self.window.as_ref().unwrap();
|
||||||
|
window.pre_present_notify();
|
||||||
|
fill::fill_window(window.as_ref());
|
||||||
|
},
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
event_loop.exit();
|
||||||
|
},
|
||||||
|
_ => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,14 +9,14 @@ fn main() -> std::process::ExitCode {
|
|||||||
|
|
||||||
use winit::application::ApplicationHandler;
|
use winit::application::ApplicationHandler;
|
||||||
use winit::event::WindowEvent;
|
use winit::event::WindowEvent;
|
||||||
|
use winit::event_loop::pump_events::{EventLoopExtPumpEvents, PumpStatus};
|
||||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
use winit::platform::pump_events::{EventLoopExtPumpEvents, PumpStatus};
|
|
||||||
use winit::window::{Window, WindowAttributes, WindowId};
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
#[path = "util/fill.rs"]
|
#[path = "util/fill.rs"]
|
||||||
mod fill;
|
mod fill;
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default, Debug)]
|
||||||
struct PumpDemo {
|
struct PumpDemo {
|
||||||
window: Option<Box<dyn Window>>,
|
window: Option<Box<dyn Window>>,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,14 +7,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
|
|
||||||
use winit::application::ApplicationHandler;
|
use winit::application::ApplicationHandler;
|
||||||
use winit::event::WindowEvent;
|
use winit::event::WindowEvent;
|
||||||
|
use winit::event_loop::run_on_demand::EventLoopExtRunOnDemand;
|
||||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
use winit::platform::run_on_demand::EventLoopExtRunOnDemand;
|
|
||||||
use winit::window::{Window, WindowAttributes, WindowId};
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
#[path = "util/fill.rs"]
|
#[path = "util/fill.rs"]
|
||||||
mod fill;
|
mod fill;
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default, Debug)]
|
||||||
struct App {
|
struct App {
|
||||||
idx: usize,
|
idx: usize,
|
||||||
window_id: Option<WindowId>,
|
window_id: Option<WindowId>,
|
||||||
|
|||||||
@@ -9,7 +9,12 @@
|
|||||||
|
|
||||||
#[allow(unused_imports)]
|
#[allow(unused_imports)]
|
||||||
pub use platform::cleanup_window;
|
pub use platform::cleanup_window;
|
||||||
|
#[allow(unused_imports)]
|
||||||
pub use platform::fill_window;
|
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")))]
|
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||||
mod platform {
|
mod platform {
|
||||||
@@ -18,8 +23,12 @@ mod platform {
|
|||||||
use std::mem;
|
use std::mem;
|
||||||
use std::mem::ManuallyDrop;
|
use std::mem::ManuallyDrop;
|
||||||
use std::num::NonZeroU32;
|
use std::num::NonZeroU32;
|
||||||
|
#[cfg(all(not(android_platform), not(web_platform)))]
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
use softbuffer::{Context, Surface};
|
use softbuffer::{Context, Surface};
|
||||||
|
#[cfg(all(web_platform, not(android_platform)))]
|
||||||
|
use web_time::Instant;
|
||||||
use winit::window::{Window, WindowId};
|
use winit::window::{Window, WindowId};
|
||||||
|
|
||||||
thread_local! {
|
thread_local! {
|
||||||
@@ -70,7 +79,7 @@ mod platform {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fill_window(window: &dyn Window) {
|
pub fn fill_window_with_color(window: &dyn Window, color: u32) {
|
||||||
GC.with(|gc| {
|
GC.with(|gc| {
|
||||||
let size = window.surface_size();
|
let size = window.surface_size();
|
||||||
let (Some(width), Some(height)) =
|
let (Some(width), Some(height)) =
|
||||||
@@ -84,17 +93,31 @@ mod platform {
|
|||||||
let surface =
|
let surface =
|
||||||
gc.get_or_insert_with(|| GraphicsContext::new(window)).create_surface(window);
|
gc.get_or_insert_with(|| GraphicsContext::new(window)).create_surface(window);
|
||||||
|
|
||||||
// Fill a buffer with a solid color.
|
// Fill a buffer with a solid color
|
||||||
const DARK_GRAY: u32 = 0xff181818;
|
|
||||||
|
|
||||||
surface.resize(width, height).expect("Failed to resize the softbuffer surface");
|
surface.resize(width, height).expect("Failed to resize the softbuffer surface");
|
||||||
|
|
||||||
let mut buffer = surface.buffer_mut().expect("Failed to get the softbuffer buffer");
|
let mut buffer = surface.buffer_mut().expect("Failed to get the softbuffer buffer");
|
||||||
buffer.fill(DARK_GRAY);
|
buffer.fill(color);
|
||||||
buffer.present().expect("Failed to present the softbuffer buffer");
|
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)]
|
#[allow(dead_code)]
|
||||||
pub fn cleanup_window(window: &dyn Window) {
|
pub fn cleanup_window(window: &dyn Window) {
|
||||||
GC.with(|gc| {
|
GC.with(|gc| {
|
||||||
@@ -108,10 +131,24 @@ mod platform {
|
|||||||
|
|
||||||
#[cfg(any(target_os = "android", target_os = "ios"))]
|
#[cfg(any(target_os = "android", target_os = "ios"))]
|
||||||
mod platform {
|
mod platform {
|
||||||
|
#[allow(dead_code)]
|
||||||
pub fn fill_window(_window: &dyn winit::window::Window) {
|
pub fn fill_window(_window: &dyn winit::window::Window) {
|
||||||
// No-op on mobile platforms.
|
// 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)]
|
#[allow(dead_code)]
|
||||||
pub fn cleanup_window(_window: &dyn winit::window::Window) {
|
pub fn cleanup_window(_window: &dyn winit::window::Window) {
|
||||||
// No-op on mobile platforms.
|
// No-op on mobile platforms.
|
||||||
|
|||||||
1282
examples/window.rs
1282
examples/window.rs
File diff suppressed because it is too large
Load Diff
@@ -6,12 +6,13 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
use winit::application::ApplicationHandler;
|
use winit::application::ApplicationHandler;
|
||||||
use winit::event::WindowEvent;
|
use winit::event::WindowEvent;
|
||||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
use winit::platform::x11::WindowAttributesExtX11;
|
use winit::platform::x11::WindowAttributesX11;
|
||||||
use winit::window::{Window, WindowAttributes, WindowId};
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
#[path = "util/fill.rs"]
|
#[path = "util/fill.rs"]
|
||||||
mod fill;
|
mod fill;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
pub struct XEmbedDemo {
|
pub struct XEmbedDemo {
|
||||||
parent_window_id: u32,
|
parent_window_id: u32,
|
||||||
window: Option<Box<dyn Window>>,
|
window: Option<Box<dyn Window>>,
|
||||||
@@ -19,10 +20,12 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
|
|
||||||
impl ApplicationHandler for XEmbedDemo {
|
impl ApplicationHandler for XEmbedDemo {
|
||||||
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
let window_attributes = WindowAttributes::default()
|
let mut window_attributes = WindowAttributes::default()
|
||||||
.with_title("An embedded window!")
|
.with_title("An embedded window!")
|
||||||
.with_surface_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
.with_surface_size(winit::dpi::LogicalSize::new(128.0, 128.0));
|
||||||
.with_embed_parent_window(self.parent_window_id);
|
let x11_attrs =
|
||||||
|
WindowAttributesX11::default().with_embed_parent_window(self.parent_window_id);
|
||||||
|
window_attributes = window_attributes.with_platform_attributes(Box::new(x11_attrs));
|
||||||
|
|
||||||
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,545 +0,0 @@
|
|||||||
//! The [`EventLoop`] struct and assorted supporting types, including
|
|
||||||
//! [`ControlFlow`].
|
|
||||||
//!
|
|
||||||
//! If you want to send custom events to the event loop, use
|
|
||||||
//! [`EventLoop::create_proxy`] to acquire an [`EventLoopProxy`] and call its
|
|
||||||
//! [`wake_up`][EventLoopProxy::wake_up] method. Then during handling the wake up
|
|
||||||
//! you can poll your event sources.
|
|
||||||
//!
|
|
||||||
//! See the root-level documentation for information on how to create and use an event loop to
|
|
||||||
//! handle events.
|
|
||||||
use std::fmt;
|
|
||||||
use std::marker::PhantomData;
|
|
||||||
#[cfg(any(x11_platform, wayland_platform))]
|
|
||||||
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
|
|
||||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
|
||||||
use std::sync::Arc;
|
|
||||||
#[cfg(not(web_platform))]
|
|
||||||
use std::time::{Duration, Instant};
|
|
||||||
|
|
||||||
use rwh_06::{DisplayHandle, HandleError, HasDisplayHandle};
|
|
||||||
#[cfg(web_platform)]
|
|
||||||
use web_time::{Duration, Instant};
|
|
||||||
|
|
||||||
use crate::application::ApplicationHandler;
|
|
||||||
use crate::error::{EventLoopError, RequestError};
|
|
||||||
use crate::monitor::MonitorHandle;
|
|
||||||
use crate::platform_impl;
|
|
||||||
use crate::utils::AsAny;
|
|
||||||
use crate::window::{CustomCursor, CustomCursorSource, Theme, Window, WindowAttributes};
|
|
||||||
|
|
||||||
/// Provides a way to retrieve events from the system and from the windows that were registered to
|
|
||||||
/// the events loop.
|
|
||||||
///
|
|
||||||
/// An `EventLoop` can be seen more or less as a "context". Calling [`EventLoop::new`]
|
|
||||||
/// initializes everything that will be required to create windows. For example on Linux creating
|
|
||||||
/// an event loop opens a connection to the X or Wayland server.
|
|
||||||
///
|
|
||||||
/// To wake up an `EventLoop` from a another thread, see the [`EventLoopProxy`] docs.
|
|
||||||
///
|
|
||||||
/// Note that this cannot be shared across threads (due to platform-dependant logic
|
|
||||||
/// forbidding it), as such it is neither [`Send`] nor [`Sync`]. If you need cross-thread access,
|
|
||||||
/// the [`Window`] created from this _can_ be sent to an other thread, and the
|
|
||||||
/// [`EventLoopProxy`] allows you to wake up an `EventLoop` from another thread.
|
|
||||||
///
|
|
||||||
/// [`Window`]: crate::window::Window
|
|
||||||
pub struct EventLoop {
|
|
||||||
pub(crate) event_loop: platform_impl::EventLoop,
|
|
||||||
pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Object that allows building the event loop.
|
|
||||||
///
|
|
||||||
/// This is used to make specifying options that affect the whole application
|
|
||||||
/// easier. But note that constructing multiple event loops is not supported.
|
|
||||||
///
|
|
||||||
/// This can be created using [`EventLoop::builder`].
|
|
||||||
#[derive(Default, PartialEq, Eq, Hash)]
|
|
||||||
pub struct EventLoopBuilder {
|
|
||||||
pub(crate) platform_specific: platform_impl::PlatformSpecificEventLoopAttributes,
|
|
||||||
}
|
|
||||||
|
|
||||||
static EVENT_LOOP_CREATED: AtomicBool = AtomicBool::new(false);
|
|
||||||
|
|
||||||
impl EventLoopBuilder {
|
|
||||||
/// Builds a new event loop.
|
|
||||||
///
|
|
||||||
/// ***For cross-platform compatibility, the [`EventLoop`] must be created on the main thread,
|
|
||||||
/// and only once per application.***
|
|
||||||
///
|
|
||||||
/// Calling this function will result in display backend initialisation.
|
|
||||||
///
|
|
||||||
/// ## Panics
|
|
||||||
///
|
|
||||||
/// Attempting to create the event loop off the main thread will panic. This
|
|
||||||
/// restriction isn't strictly necessary on all platforms, but is imposed to
|
|
||||||
/// eliminate any nasty surprises when porting to platforms that require it.
|
|
||||||
/// `EventLoopBuilderExt::with_any_thread` functions are exposed in the relevant
|
|
||||||
/// [`platform`] module if the target platform supports creating an event
|
|
||||||
/// loop on any thread.
|
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// - **Wayland/X11:** to prevent running under `Wayland` or `X11` unset `WAYLAND_DISPLAY` or
|
|
||||||
/// `DISPLAY` respectively when building the event loop.
|
|
||||||
/// - **Android:** must be configured with an `AndroidApp` from `android_main()` by calling
|
|
||||||
/// [`.with_android_app(app)`] before calling `.build()`, otherwise it'll panic.
|
|
||||||
///
|
|
||||||
/// [`platform`]: crate::platform
|
|
||||||
#[cfg_attr(
|
|
||||||
android_platform,
|
|
||||||
doc = "[`.with_android_app(app)`]: \
|
|
||||||
crate::platform::android::EventLoopBuilderExtAndroid::with_android_app"
|
|
||||||
)]
|
|
||||||
#[cfg_attr(
|
|
||||||
not(android_platform),
|
|
||||||
doc = "[`.with_android_app(app)`]: #only-available-on-android"
|
|
||||||
)]
|
|
||||||
#[inline]
|
|
||||||
pub fn build(&mut self) -> Result<EventLoop, EventLoopError> {
|
|
||||||
let _span = tracing::debug_span!("winit::EventLoopBuilder::build").entered();
|
|
||||||
|
|
||||||
if EVENT_LOOP_CREATED.swap(true, Ordering::Relaxed) {
|
|
||||||
return Err(EventLoopError::RecreationAttempt);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Certain platforms accept a mutable reference in their API.
|
|
||||||
#[allow(clippy::unnecessary_mut_passed)]
|
|
||||||
Ok(EventLoop {
|
|
||||||
event_loop: platform_impl::EventLoop::new(&mut self.platform_specific)?,
|
|
||||||
_marker: PhantomData,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(web_platform)]
|
|
||||||
pub(crate) fn allow_event_loop_recreation() {
|
|
||||||
EVENT_LOOP_CREATED.store(false, Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Debug for EventLoopBuilder {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.debug_struct("EventLoopBuilder").finish_non_exhaustive()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Debug for EventLoop {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.debug_struct("EventLoop").finish_non_exhaustive()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set through [`ActiveEventLoop::set_control_flow()`].
|
|
||||||
///
|
|
||||||
/// Indicates the desired behavior of the event loop after [`about_to_wait`] is called.
|
|
||||||
///
|
|
||||||
/// Defaults to [`Wait`].
|
|
||||||
///
|
|
||||||
/// [`Wait`]: Self::Wait
|
|
||||||
/// [`about_to_wait`]: crate::application::ApplicationHandler::about_to_wait
|
|
||||||
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
|
|
||||||
pub enum ControlFlow {
|
|
||||||
/// When the current loop iteration finishes, immediately begin a new iteration regardless of
|
|
||||||
/// whether or not new events are available to process.
|
|
||||||
Poll,
|
|
||||||
|
|
||||||
/// When the current loop iteration finishes, suspend the thread until another event arrives.
|
|
||||||
#[default]
|
|
||||||
Wait,
|
|
||||||
|
|
||||||
/// When the current loop iteration finishes, suspend the thread until either another event
|
|
||||||
/// arrives or the given time is reached.
|
|
||||||
///
|
|
||||||
/// Useful for implementing efficient timers. Applications which want to render at the
|
|
||||||
/// display's native refresh rate should instead use [`Poll`] and the VSync functionality
|
|
||||||
/// of a graphics API to reduce odds of missed frames.
|
|
||||||
///
|
|
||||||
/// [`Poll`]: Self::Poll
|
|
||||||
WaitUntil(Instant),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ControlFlow {
|
|
||||||
/// Creates a [`ControlFlow`] that waits until a timeout has expired.
|
|
||||||
///
|
|
||||||
/// In most cases, this is set to [`WaitUntil`]. However, if the timeout overflows, it is
|
|
||||||
/// instead set to [`Wait`].
|
|
||||||
///
|
|
||||||
/// [`WaitUntil`]: Self::WaitUntil
|
|
||||||
/// [`Wait`]: Self::Wait
|
|
||||||
pub fn wait_duration(timeout: Duration) -> Self {
|
|
||||||
match Instant::now().checked_add(timeout) {
|
|
||||||
Some(instant) => Self::WaitUntil(instant),
|
|
||||||
None => Self::Wait,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventLoop {
|
|
||||||
/// Create the event loop.
|
|
||||||
///
|
|
||||||
/// This is an alias of `EventLoop::builder().build()`.
|
|
||||||
#[inline]
|
|
||||||
pub fn new() -> Result<EventLoop, EventLoopError> {
|
|
||||||
Self::builder().build()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Start building a new event loop.
|
|
||||||
///
|
|
||||||
/// This returns an [`EventLoopBuilder`], to allow configuring the event loop before creation.
|
|
||||||
///
|
|
||||||
/// To get the actual event loop, call [`build`][EventLoopBuilder::build] on that.
|
|
||||||
#[inline]
|
|
||||||
pub fn builder() -> EventLoopBuilder {
|
|
||||||
EventLoopBuilder { platform_specific: Default::default() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventLoop {
|
|
||||||
/// Run the application with the event loop on the calling thread.
|
|
||||||
///
|
|
||||||
/// See the [`set_control_flow()`] docs on how to change the event loop's behavior.
|
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// - **iOS:** Will never return to the caller and so values not passed to this function will
|
|
||||||
/// *not* be dropped before the process exits.
|
|
||||||
/// - **Web:** Will _act_ as if it never returns to the caller by throwing a Javascript
|
|
||||||
/// exception (that Rust doesn't see) that will also mean that the rest of the function is
|
|
||||||
/// never executed and any values not passed to this function will *not* be dropped.
|
|
||||||
///
|
|
||||||
/// Web applications are recommended to use
|
|
||||||
#[cfg_attr(
|
|
||||||
any(web_platform, docsrs),
|
|
||||||
doc = " [`EventLoopExtWeb::spawn_app()`][crate::platform::web::EventLoopExtWeb::spawn_app()]"
|
|
||||||
)]
|
|
||||||
#[cfg_attr(not(any(web_platform, docsrs)), doc = " `EventLoopExtWeb::spawn_app()`")]
|
|
||||||
/// [^1] instead of [`run_app()`] to avoid the need for the Javascript exception trick, and to
|
|
||||||
/// make it clearer that the event loop runs asynchronously (via the browser's own,
|
|
||||||
/// internal, event loop) and doesn't block the current thread of execution like it does
|
|
||||||
/// on other platforms.
|
|
||||||
///
|
|
||||||
/// This function won't be available with `target_feature = "exception-handling"`.
|
|
||||||
///
|
|
||||||
/// [^1]: `spawn_app()` is only available on the Web platform.
|
|
||||||
///
|
|
||||||
/// [`set_control_flow()`]: ActiveEventLoop::set_control_flow()
|
|
||||||
/// [`run_app()`]: Self::run_app()
|
|
||||||
#[inline]
|
|
||||||
#[cfg(not(all(web_platform, target_feature = "exception-handling")))]
|
|
||||||
pub fn run_app<A: ApplicationHandler>(self, app: A) -> Result<(), EventLoopError> {
|
|
||||||
self.event_loop.run_app(app)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates an [`EventLoopProxy`] that can be used to dispatch user events
|
|
||||||
/// to the main event loop, possibly from another thread.
|
|
||||||
pub fn create_proxy(&self) -> EventLoopProxy {
|
|
||||||
self.event_loop.window_target().create_proxy()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets a persistent reference to the underlying platform display.
|
|
||||||
///
|
|
||||||
/// See the [`OwnedDisplayHandle`] type for more information.
|
|
||||||
pub fn owned_display_handle(&self) -> OwnedDisplayHandle {
|
|
||||||
self.event_loop.window_target().owned_display_handle()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Change if or when [`DeviceEvent`]s are captured.
|
|
||||||
///
|
|
||||||
/// See [`ActiveEventLoop::listen_device_events`] for details.
|
|
||||||
///
|
|
||||||
/// [`DeviceEvent`]: crate::event::DeviceEvent
|
|
||||||
pub fn listen_device_events(&self, allowed: DeviceEvents) {
|
|
||||||
let _span = tracing::debug_span!(
|
|
||||||
"winit::EventLoop::listen_device_events",
|
|
||||||
allowed = ?allowed
|
|
||||||
)
|
|
||||||
.entered();
|
|
||||||
self.event_loop.window_target().listen_device_events(allowed)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the [`ControlFlow`].
|
|
||||||
pub fn set_control_flow(&self, control_flow: ControlFlow) {
|
|
||||||
self.event_loop.window_target().set_control_flow(control_flow);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create custom cursor.
|
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// **iOS / Android / Orbital:** Unsupported.
|
|
||||||
pub fn create_custom_cursor(
|
|
||||||
&self,
|
|
||||||
custom_cursor: CustomCursorSource,
|
|
||||||
) -> Result<CustomCursor, RequestError> {
|
|
||||||
self.event_loop.window_target().create_custom_cursor(custom_cursor)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HasDisplayHandle for EventLoop {
|
|
||||||
fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
|
|
||||||
HasDisplayHandle::display_handle(self.event_loop.window_target().rwh_06_handle())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(x11_platform, wayland_platform))]
|
|
||||||
impl AsFd for EventLoop {
|
|
||||||
/// Get the underlying [EventLoop]'s `fd` which you can register
|
|
||||||
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
|
||||||
/// loop must be polled with the [`pump_app_events`] API.
|
|
||||||
///
|
|
||||||
/// [`calloop`]: https://crates.io/crates/calloop
|
|
||||||
/// [`mio`]: https://crates.io/crates/mio
|
|
||||||
/// [`pump_app_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_app_events
|
|
||||||
fn as_fd(&self) -> BorrowedFd<'_> {
|
|
||||||
self.event_loop.as_fd()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(x11_platform, wayland_platform))]
|
|
||||||
impl AsRawFd for EventLoop {
|
|
||||||
/// Get the underlying [EventLoop]'s raw `fd` which you can register
|
|
||||||
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
|
||||||
/// loop must be polled with the [`pump_app_events`] API.
|
|
||||||
///
|
|
||||||
/// [`calloop`]: https://crates.io/crates/calloop
|
|
||||||
/// [`mio`]: https://crates.io/crates/mio
|
|
||||||
/// [`pump_app_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_app_events
|
|
||||||
fn as_raw_fd(&self) -> RawFd {
|
|
||||||
self.event_loop.as_raw_fd()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait ActiveEventLoop: AsAny {
|
|
||||||
/// Creates an [`EventLoopProxy`] that can be used to dispatch user events
|
|
||||||
/// to the main event loop, possibly from another thread.
|
|
||||||
fn create_proxy(&self) -> EventLoopProxy;
|
|
||||||
|
|
||||||
/// Create the window.
|
|
||||||
///
|
|
||||||
/// Possible causes of error include denied permission, incompatible system, and lack of memory.
|
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// - **Web:** The window is created but not inserted into the Web page automatically. Please
|
|
||||||
/// see the Web platform module for more information.
|
|
||||||
fn create_window(
|
|
||||||
&self,
|
|
||||||
window_attributes: WindowAttributes,
|
|
||||||
) -> Result<Box<dyn Window>, RequestError>;
|
|
||||||
|
|
||||||
/// Create custom cursor.
|
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// **iOS / Android / Orbital:** Unsupported.
|
|
||||||
fn create_custom_cursor(
|
|
||||||
&self,
|
|
||||||
custom_cursor: CustomCursorSource,
|
|
||||||
) -> Result<CustomCursor, RequestError>;
|
|
||||||
|
|
||||||
/// Returns the list of all the monitors available on the system.
|
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// **Web:** Only returns the current monitor without
|
|
||||||
#[cfg_attr(
|
|
||||||
any(web_platform, docsrs),
|
|
||||||
doc = "[detailed monitor permissions][crate::platform::web::ActiveEventLoopExtWeb::request_detailed_monitor_permission]."
|
|
||||||
)]
|
|
||||||
#[cfg_attr(not(any(web_platform, docsrs)), doc = "detailed monitor permissions.")]
|
|
||||||
fn available_monitors(&self) -> Box<dyn Iterator<Item = MonitorHandle>>;
|
|
||||||
|
|
||||||
/// Returns the primary monitor of the system.
|
|
||||||
///
|
|
||||||
/// Returns `None` if it can't identify any monitor as a primary one.
|
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// - **Wayland:** Always returns `None`.
|
|
||||||
/// - **Web:** Always returns `None` without
|
|
||||||
#[cfg_attr(
|
|
||||||
any(web_platform, docsrs),
|
|
||||||
doc = " [detailed monitor permissions][crate::platform::web::ActiveEventLoopExtWeb::request_detailed_monitor_permission]."
|
|
||||||
)]
|
|
||||||
#[cfg_attr(not(any(web_platform, docsrs)), doc = " detailed monitor permissions.")]
|
|
||||||
fn primary_monitor(&self) -> Option<MonitorHandle>;
|
|
||||||
|
|
||||||
/// Change if or when [`DeviceEvent`]s are captured.
|
|
||||||
///
|
|
||||||
/// Since the [`DeviceEvent`] capture can lead to high CPU usage for unfocused windows, winit
|
|
||||||
/// will ignore them by default for unfocused windows on Linux/BSD. This method allows changing
|
|
||||||
/// this at runtime to explicitly capture them again.
|
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// - **Wayland / macOS / iOS / Android / Orbital:** Unsupported.
|
|
||||||
///
|
|
||||||
/// [`DeviceEvent`]: crate::event::DeviceEvent
|
|
||||||
fn listen_device_events(&self, allowed: DeviceEvents);
|
|
||||||
|
|
||||||
/// Returns the current system theme.
|
|
||||||
///
|
|
||||||
/// Returns `None` if it cannot be determined on the current platform.
|
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// - **iOS / Android / Wayland / x11 / Orbital:** Unsupported.
|
|
||||||
fn system_theme(&self) -> Option<Theme>;
|
|
||||||
|
|
||||||
/// Sets the [`ControlFlow`].
|
|
||||||
fn set_control_flow(&self, control_flow: ControlFlow);
|
|
||||||
|
|
||||||
/// Gets the current [`ControlFlow`].
|
|
||||||
fn control_flow(&self) -> ControlFlow;
|
|
||||||
|
|
||||||
/// This exits the event loop.
|
|
||||||
///
|
|
||||||
/// See [`exiting`][crate::application::ApplicationHandler::exiting].
|
|
||||||
fn exit(&self);
|
|
||||||
|
|
||||||
/// Returns if the [`EventLoop`] is about to stop.
|
|
||||||
///
|
|
||||||
/// See [`exit()`][Self::exit].
|
|
||||||
fn exiting(&self) -> bool;
|
|
||||||
|
|
||||||
/// Gets a persistent reference to the underlying platform display.
|
|
||||||
///
|
|
||||||
/// See the [`OwnedDisplayHandle`] type for more information.
|
|
||||||
fn owned_display_handle(&self) -> OwnedDisplayHandle;
|
|
||||||
|
|
||||||
/// Get the raw-window-handle handle.
|
|
||||||
fn rwh_06_handle(&self) -> &dyn HasDisplayHandle;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HasDisplayHandle for dyn ActiveEventLoop + '_ {
|
|
||||||
fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
|
|
||||||
self.rwh_06_handle().display_handle()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A proxy for the underlying display handle.
|
|
||||||
///
|
|
||||||
/// The purpose of this type is to provide a cheaply cloneable handle to the underlying
|
|
||||||
/// display handle. This is often used by graphics APIs to connect to the underlying APIs.
|
|
||||||
/// It is difficult to keep a handle to the [`EventLoop`] type or the [`ActiveEventLoop`]
|
|
||||||
/// type. In contrast, this type involves no lifetimes and can be persisted for as long as
|
|
||||||
/// needed.
|
|
||||||
///
|
|
||||||
/// For all platforms, this is one of the following:
|
|
||||||
///
|
|
||||||
/// - A zero-sized type that is likely optimized out.
|
|
||||||
/// - A reference-counted pointer to the underlying type.
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct OwnedDisplayHandle {
|
|
||||||
pub(crate) handle: Arc<dyn HasDisplayHandle>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl OwnedDisplayHandle {
|
|
||||||
pub(crate) fn new(handle: Arc<dyn HasDisplayHandle>) -> Self {
|
|
||||||
Self { handle }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HasDisplayHandle for OwnedDisplayHandle {
|
|
||||||
fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
|
|
||||||
self.handle.display_handle()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Debug for OwnedDisplayHandle {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.debug_struct("OwnedDisplayHandle").finish_non_exhaustive()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PartialEq for OwnedDisplayHandle {
|
|
||||||
fn eq(&self, other: &Self) -> bool {
|
|
||||||
match (self.display_handle(), other.display_handle()) {
|
|
||||||
(Ok(lhs), Ok(rhs)) => lhs == rhs,
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Eq for OwnedDisplayHandle {}
|
|
||||||
|
|
||||||
pub(crate) trait EventLoopProxyProvider: Send + Sync {
|
|
||||||
/// See [`EventLoopProxy::wake_up`] for details.
|
|
||||||
fn wake_up(&self);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Control the [`EventLoop`], possibly from a different thread, without referencing it directly.
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct EventLoopProxy {
|
|
||||||
pub(crate) proxy: Arc<dyn EventLoopProxyProvider>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Debug for EventLoopProxy {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.debug_struct("EventLoopProxy").finish_non_exhaustive()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventLoopProxy {
|
|
||||||
/// Wake up the [`EventLoop`], resulting in [`ApplicationHandler::proxy_wake_up()`] being
|
|
||||||
/// called.
|
|
||||||
///
|
|
||||||
/// Calls to this method are coalesced into a single call to [`proxy_wake_up`], see the
|
|
||||||
/// documentation on that for details.
|
|
||||||
///
|
|
||||||
/// If the event loop is no longer running, this is a no-op.
|
|
||||||
///
|
|
||||||
/// [`proxy_wake_up`]: ApplicationHandler::proxy_wake_up
|
|
||||||
///
|
|
||||||
/// # Platform-specific
|
|
||||||
///
|
|
||||||
/// - **Windows**: The wake-up may be ignored under high contention, see [#3687].
|
|
||||||
///
|
|
||||||
/// [#3687]: https://github.com/rust-windowing/winit/pull/3687
|
|
||||||
pub fn wake_up(&self) {
|
|
||||||
self.proxy.wake_up();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn new(proxy: Arc<dyn EventLoopProxyProvider>) -> Self {
|
|
||||||
Self { proxy }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Control when device events are captured.
|
|
||||||
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
|
|
||||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
|
||||||
pub enum DeviceEvents {
|
|
||||||
/// Report device events regardless of window focus.
|
|
||||||
Always,
|
|
||||||
/// Only capture device events while the window is focused.
|
|
||||||
#[default]
|
|
||||||
WhenFocused,
|
|
||||||
/// Never capture device events.
|
|
||||||
Never,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A unique identifier of the winit's async request.
|
|
||||||
///
|
|
||||||
/// This could be used to identify the async request once it's done
|
|
||||||
/// and a specific action must be taken.
|
|
||||||
///
|
|
||||||
/// One of the handling scenarios could be to maintain a working list
|
|
||||||
/// containing [`AsyncRequestSerial`] and some closure associated with it.
|
|
||||||
/// Then once event is arriving the working list is being traversed and a job
|
|
||||||
/// executed and removed from the list.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
||||||
pub struct AsyncRequestSerial {
|
|
||||||
serial: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AsyncRequestSerial {
|
|
||||||
// TODO(kchibisov): Remove `cfg` when the clipboard will be added.
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub(crate) fn get() -> Self {
|
|
||||||
static CURRENT_SERIAL: AtomicUsize = AtomicUsize::new(0);
|
|
||||||
// NOTE: We rely on wrap around here, while the user may just request
|
|
||||||
// in the loop usize::MAX times that's issue is considered on them.
|
|
||||||
let serial = CURRENT_SERIAL.fetch_add(1, Ordering::Relaxed);
|
|
||||||
Self { serial }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
118
src/icon.rs
118
src/icon.rs
@@ -1,118 +0,0 @@
|
|||||||
use std::error::Error;
|
|
||||||
use std::{fmt, io, mem};
|
|
||||||
|
|
||||||
use crate::platform_impl::PlatformIcon;
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub(crate) struct Pixel {
|
|
||||||
pub(crate) r: u8,
|
|
||||||
pub(crate) g: u8,
|
|
||||||
pub(crate) b: u8,
|
|
||||||
pub(crate) a: u8,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) const PIXEL_SIZE: usize = mem::size_of::<Pixel>();
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
/// An error produced when using [`Icon::from_rgba`] with invalid arguments.
|
|
||||||
pub enum BadIcon {
|
|
||||||
/// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be
|
|
||||||
/// safely interpreted as 32bpp RGBA pixels.
|
|
||||||
ByteCountNotDivisibleBy4 { byte_count: usize },
|
|
||||||
/// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`.
|
|
||||||
/// At least one of your arguments is incorrect.
|
|
||||||
DimensionsVsPixelCount { width: u32, height: u32, width_x_height: usize, pixel_count: usize },
|
|
||||||
/// Produced when underlying OS functionality failed to create the icon
|
|
||||||
OsError(io::Error),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for BadIcon {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
match self {
|
|
||||||
BadIcon::ByteCountNotDivisibleBy4 { byte_count } => write!(
|
|
||||||
f,
|
|
||||||
"The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making \
|
|
||||||
it impossible to interpret as 32bpp RGBA pixels.",
|
|
||||||
),
|
|
||||||
BadIcon::DimensionsVsPixelCount { width, height, width_x_height, pixel_count } => {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"The specified dimensions ({width:?}x{height:?}) don't match the number of \
|
|
||||||
pixels supplied by the `rgba` argument ({pixel_count:?}). For those \
|
|
||||||
dimensions, the expected pixel count is {width_x_height:?}.",
|
|
||||||
)
|
|
||||||
},
|
|
||||||
BadIcon::OsError(e) => write!(f, "OS error when instantiating the icon: {e:?}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Error for BadIcon {}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
|
||||||
pub(crate) struct RgbaIcon {
|
|
||||||
pub(crate) rgba: Vec<u8>,
|
|
||||||
pub(crate) width: u32,
|
|
||||||
pub(crate) height: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// For platforms which don't have window icons (e.g. Web)
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
|
||||||
pub(crate) struct NoIcon;
|
|
||||||
|
|
||||||
#[allow(dead_code)] // These are not used on every platform
|
|
||||||
mod constructors {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
impl RgbaIcon {
|
|
||||||
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
|
||||||
if rgba.len() % PIXEL_SIZE != 0 {
|
|
||||||
return Err(BadIcon::ByteCountNotDivisibleBy4 { byte_count: rgba.len() });
|
|
||||||
}
|
|
||||||
let pixel_count = rgba.len() / PIXEL_SIZE;
|
|
||||||
if pixel_count != (width * height) as usize {
|
|
||||||
Err(BadIcon::DimensionsVsPixelCount {
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
width_x_height: (width * height) as usize,
|
|
||||||
pixel_count,
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
Ok(RgbaIcon { rgba, width, height })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl NoIcon {
|
|
||||||
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
|
||||||
// Create the rgba icon anyway to validate the input
|
|
||||||
let _ = RgbaIcon::from_rgba(rgba, width, height)?;
|
|
||||||
Ok(NoIcon)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An icon used for the window titlebar, taskbar, etc.
|
|
||||||
#[derive(Clone, Eq, Hash, PartialEq)]
|
|
||||||
pub struct Icon {
|
|
||||||
pub(crate) inner: PlatformIcon,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Debug for Icon {
|
|
||||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
|
||||||
fmt::Debug::fmt(&self.inner, formatter)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Icon {
|
|
||||||
/// Creates an icon from 32bpp RGBA data.
|
|
||||||
///
|
|
||||||
/// The length of `rgba` must be divisible by 4, and `width * height` must equal
|
|
||||||
/// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error.
|
|
||||||
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
|
||||||
let _span = tracing::debug_span!("winit::Icon::from_rgba", width, height).entered();
|
|
||||||
|
|
||||||
Ok(Icon { inner: PlatformIcon::from_rgba(rgba, width, height)? })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
1770
src/keyboard.rs
1770
src/keyboard.rs
File diff suppressed because it is too large
Load Diff
200
src/monitor.rs
200
src/monitor.rs
@@ -1,200 +0,0 @@
|
|||||||
//! Types useful for interacting with a user's monitors.
|
|
||||||
use std::num::{NonZeroU16, NonZeroU32};
|
|
||||||
|
|
||||||
use crate::dpi::{PhysicalPosition, PhysicalSize};
|
|
||||||
use crate::platform_impl;
|
|
||||||
|
|
||||||
/// A handle to a fullscreen video mode of a specific monitor.
|
|
||||||
///
|
|
||||||
/// This can be acquired with [`MonitorHandle::video_modes`].
|
|
||||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
|
||||||
pub struct VideoModeHandle {
|
|
||||||
pub(crate) video_mode: platform_impl::VideoModeHandle,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Debug for VideoModeHandle {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
self.video_mode.fmt(f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PartialOrd for VideoModeHandle {
|
|
||||||
fn partial_cmp(&self, other: &VideoModeHandle) -> Option<std::cmp::Ordering> {
|
|
||||||
Some(self.cmp(other))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Ord for VideoModeHandle {
|
|
||||||
fn cmp(&self, other: &VideoModeHandle) -> std::cmp::Ordering {
|
|
||||||
self.monitor().cmp(&other.monitor()).then(
|
|
||||||
self.size()
|
|
||||||
.cmp(&other.size())
|
|
||||||
.then(
|
|
||||||
self.refresh_rate_millihertz()
|
|
||||||
.cmp(&other.refresh_rate_millihertz())
|
|
||||||
.then(self.bit_depth().cmp(&other.bit_depth())),
|
|
||||||
)
|
|
||||||
.reverse(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl VideoModeHandle {
|
|
||||||
/// Returns the resolution of this video mode. This **must not** be used to create your
|
|
||||||
/// rendering surface. Use [`Window::surface_size()`] instead.
|
|
||||||
///
|
|
||||||
/// [`Window::surface_size()`]: crate::window::Window::surface_size
|
|
||||||
#[inline]
|
|
||||||
pub fn size(&self) -> PhysicalSize<u32> {
|
|
||||||
self.video_mode.size()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the bit depth of this video mode, as in how many bits you have
|
|
||||||
/// available per color. This is generally 24 bits or 32 bits on modern
|
|
||||||
/// systems, depending on whether the alpha channel is counted or not.
|
|
||||||
#[inline]
|
|
||||||
pub fn bit_depth(&self) -> Option<NonZeroU16> {
|
|
||||||
self.video_mode.bit_depth()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the refresh rate of this video mode in mHz.
|
|
||||||
#[inline]
|
|
||||||
pub fn refresh_rate_millihertz(&self) -> Option<NonZeroU32> {
|
|
||||||
self.video_mode.refresh_rate_millihertz()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the monitor that this video mode is valid for. Each monitor has
|
|
||||||
/// a separate set of valid video modes.
|
|
||||||
#[inline]
|
|
||||||
pub fn monitor(&self) -> MonitorHandle {
|
|
||||||
MonitorHandle { inner: self.video_mode.monitor() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Display for VideoModeHandle {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"{}x{} {}{}",
|
|
||||||
self.size().width,
|
|
||||||
self.size().height,
|
|
||||||
self.refresh_rate_millihertz().map(|rate| format!("@ {rate} mHz ")).unwrap_or_default(),
|
|
||||||
self.bit_depth().map(|bit_depth| format!("({bit_depth} bpp)")).unwrap_or_default(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Handle to a monitor.
|
|
||||||
///
|
|
||||||
/// Allows you to retrieve basic information and metadata about a monitor.
|
|
||||||
///
|
|
||||||
/// Can be used in [`Window`] creation to place the window on a specific
|
|
||||||
/// monitor.
|
|
||||||
///
|
|
||||||
/// This can be retrieved from one of the following methods, which return an
|
|
||||||
/// iterator of [`MonitorHandle`]s:
|
|
||||||
/// - [`ActiveEventLoop::available_monitors`](crate::event_loop::ActiveEventLoop::available_monitors).
|
|
||||||
/// - [`Window::available_monitors`](crate::window::Window::available_monitors).
|
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// **Web:** A [`MonitorHandle`] created without
|
|
||||||
#[cfg_attr(
|
|
||||||
any(web_platform, docsrs),
|
|
||||||
doc = "[detailed monitor permissions][crate::platform::web::ActiveEventLoopExtWeb::request_detailed_monitor_permission]."
|
|
||||||
)]
|
|
||||||
#[cfg_attr(not(any(web_platform, docsrs)), doc = "detailed monitor permissions.")]
|
|
||||||
/// will always represent the current monitor the browser window is in instead of a specific
|
|
||||||
/// monitor. See
|
|
||||||
#[cfg_attr(
|
|
||||||
any(web_platform, docsrs),
|
|
||||||
doc = "[`MonitorHandleExtWeb::is_detailed()`][crate::platform::web::MonitorHandleExtWeb::is_detailed]"
|
|
||||||
)]
|
|
||||||
#[cfg_attr(not(any(web_platform, docsrs)), doc = "`MonitorHandleExtWeb::is_detailed()`")]
|
|
||||||
/// to check.
|
|
||||||
///
|
|
||||||
/// [`Window`]: crate::window::Window
|
|
||||||
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
||||||
pub struct MonitorHandle {
|
|
||||||
pub(crate) inner: platform_impl::MonitorHandle,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Debug for MonitorHandle {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
self.inner.fmt(f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorHandle {
|
|
||||||
/// Returns a human-readable name of the monitor.
|
|
||||||
///
|
|
||||||
/// Returns `None` if the monitor doesn't exist anymore.
|
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// **Web:** Always returns [`None`] without
|
|
||||||
#[cfg_attr(
|
|
||||||
any(web_platform, docsrs),
|
|
||||||
doc = "[detailed monitor permissions][crate::platform::web::ActiveEventLoopExtWeb::request_detailed_monitor_permission]."
|
|
||||||
)]
|
|
||||||
#[cfg_attr(not(any(web_platform, docsrs)), doc = "detailed monitor permissions.")]
|
|
||||||
#[inline]
|
|
||||||
pub fn name(&self) -> Option<String> {
|
|
||||||
self.inner.name()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the top-left corner position of the monitor in desktop coordinates.
|
|
||||||
///
|
|
||||||
/// This position is in the same coordinate system as [`Window::outer_position`].
|
|
||||||
///
|
|
||||||
/// [`Window::outer_position`]: crate::window::Window::outer_position
|
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// **Web:** Always returns [`None`] without
|
|
||||||
#[cfg_attr(
|
|
||||||
any(web_platform, docsrs),
|
|
||||||
doc = "[detailed monitor permissions][crate::platform::web::ActiveEventLoopExtWeb::request_detailed_monitor_permission]."
|
|
||||||
)]
|
|
||||||
#[cfg_attr(not(any(web_platform, docsrs)), doc = "detailed monitor permissions.")]
|
|
||||||
#[inline]
|
|
||||||
pub fn position(&self) -> Option<PhysicalPosition<i32>> {
|
|
||||||
self.inner.position()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the scale factor of the underlying monitor. To map logical pixels to physical
|
|
||||||
/// pixels and vice versa, use [`Window::scale_factor`].
|
|
||||||
///
|
|
||||||
/// See the [`dpi`] module for more information.
|
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// - **X11:** Can be overridden using the `WINIT_X11_SCALE_FACTOR` environment variable.
|
|
||||||
/// - **Wayland:** May differ from [`Window::scale_factor`].
|
|
||||||
/// - **Android:** Always returns 1.0.
|
|
||||||
/// - **Web:** Always returns `0.0` without
|
|
||||||
#[cfg_attr(
|
|
||||||
any(web_platform, docsrs),
|
|
||||||
doc = " [detailed monitor permissions][crate::platform::web::ActiveEventLoopExtWeb::request_detailed_monitor_permission]."
|
|
||||||
)]
|
|
||||||
#[cfg_attr(not(any(web_platform, docsrs)), doc = " detailed monitor permissions.")]
|
|
||||||
///
|
|
||||||
#[rustfmt::skip]
|
|
||||||
/// [`Window::scale_factor`]: crate::window::Window::scale_factor
|
|
||||||
#[inline]
|
|
||||||
pub fn scale_factor(&self) -> f64 {
|
|
||||||
self.inner.scale_factor()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the currently active video mode of this monitor.
|
|
||||||
#[inline]
|
|
||||||
pub fn current_video_mode(&self) -> Option<VideoModeHandle> {
|
|
||||||
self.inner.current_video_mode().map(|video_mode| VideoModeHandle { video_mode })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns all fullscreen video modes supported by this monitor.
|
|
||||||
#[inline]
|
|
||||||
pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> {
|
|
||||||
self.inner.video_modes().map(|video_mode| VideoModeHandle { video_mode })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
//! Contains traits with platform-specific methods in them.
|
|
||||||
//!
|
|
||||||
//! Only the modules corresponding to the platform you're compiling to will be available.
|
|
||||||
|
|
||||||
#[cfg(any(android_platform, docsrs))]
|
|
||||||
pub mod android;
|
|
||||||
#[cfg(any(ios_platform, docsrs))]
|
|
||||||
pub mod ios;
|
|
||||||
#[cfg(any(macos_platform, docsrs))]
|
|
||||||
pub mod macos;
|
|
||||||
#[cfg(any(orbital_platform, docsrs))]
|
|
||||||
pub mod orbital;
|
|
||||||
#[cfg(any(x11_platform, wayland_platform, docsrs))]
|
|
||||||
pub mod startup_notify;
|
|
||||||
#[cfg(any(wayland_platform, docsrs))]
|
|
||||||
pub mod wayland;
|
|
||||||
#[cfg(any(web_platform, docsrs))]
|
|
||||||
pub mod web;
|
|
||||||
#[cfg(any(windows_platform, docsrs))]
|
|
||||||
pub mod windows;
|
|
||||||
#[cfg(any(x11_platform, docsrs))]
|
|
||||||
pub mod x11;
|
|
||||||
|
|
||||||
#[allow(unused_imports)]
|
|
||||||
#[cfg(any(
|
|
||||||
windows_platform,
|
|
||||||
macos_platform,
|
|
||||||
android_platform,
|
|
||||||
x11_platform,
|
|
||||||
wayland_platform,
|
|
||||||
docsrs,
|
|
||||||
))]
|
|
||||||
pub mod run_on_demand;
|
|
||||||
|
|
||||||
#[cfg(any(
|
|
||||||
windows_platform,
|
|
||||||
macos_platform,
|
|
||||||
android_platform,
|
|
||||||
x11_platform,
|
|
||||||
wayland_platform,
|
|
||||||
docsrs,
|
|
||||||
))]
|
|
||||||
pub mod pump_events;
|
|
||||||
|
|
||||||
#[cfg(any(
|
|
||||||
windows_platform,
|
|
||||||
macos_platform,
|
|
||||||
x11_platform,
|
|
||||||
wayland_platform,
|
|
||||||
orbital_platform,
|
|
||||||
docsrs
|
|
||||||
))]
|
|
||||||
pub mod modifier_supplement;
|
|
||||||
|
|
||||||
#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform, docsrs))]
|
|
||||||
pub mod scancode;
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
use crate::event::KeyEvent;
|
|
||||||
use crate::keyboard::Key;
|
|
||||||
|
|
||||||
/// Additional methods for the `KeyEvent` which cannot be implemented on all
|
|
||||||
/// platforms.
|
|
||||||
pub trait KeyEventExtModifierSupplement {
|
|
||||||
/// Identical to `KeyEvent::text` but this is affected by <kbd>Ctrl</kbd>.
|
|
||||||
///
|
|
||||||
/// For example, pressing <kbd>Ctrl</kbd>+<kbd>a</kbd> produces `Some("\x01")`.
|
|
||||||
fn text_with_all_modifiers(&self) -> Option<&str>;
|
|
||||||
|
|
||||||
/// This value ignores all modifiers including,
|
|
||||||
/// but not limited to <kbd>Shift</kbd>, <kbd>Caps Lock</kbd>,
|
|
||||||
/// and <kbd>Ctrl</kbd>. In most cases this means that the
|
|
||||||
/// unicode character in the resulting string is lowercase.
|
|
||||||
///
|
|
||||||
/// This is useful for key-bindings / shortcut key combinations.
|
|
||||||
///
|
|
||||||
/// In case `logical_key` reports `Dead`, this will still report the
|
|
||||||
/// key as `Character` according to the current keyboard layout. This value
|
|
||||||
/// cannot be `Dead`.
|
|
||||||
fn key_without_modifiers(&self) -> Key;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl KeyEventExtModifierSupplement for KeyEvent {
|
|
||||||
#[inline]
|
|
||||||
fn text_with_all_modifiers(&self) -> Option<&str> {
|
|
||||||
self.platform_specific.text_with_all_modifiers.as_ref().map(|s| s.as_str())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn key_without_modifiers(&self) -> Key {
|
|
||||||
self.platform_specific.key_without_modifiers.clone()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
//! # Orbital / Redox OS
|
|
||||||
//!
|
|
||||||
//! Redox OS has some functionality not yet present that will be implemented
|
|
||||||
//! when its orbital display server provides it.
|
|
||||||
|
|
||||||
// There are no Orbital specific traits yet.
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
//! # Wayland
|
|
||||||
//!
|
|
||||||
//! **Note:** Windows don't appear on Wayland until you draw/present to them.
|
|
||||||
//!
|
|
||||||
//! By default, Winit loads system libraries using `dlopen`. This can be
|
|
||||||
//! disabled by disabling the `"wayland-dlopen"` cargo feature.
|
|
||||||
//!
|
|
||||||
//! ## Client-side decorations
|
|
||||||
//!
|
|
||||||
//! Winit provides client-side decorations by default, but the behaviour can
|
|
||||||
//! be controlled with the following feature flags:
|
|
||||||
//!
|
|
||||||
//! * `wayland-csd-adwaita` (default).
|
|
||||||
//! * `wayland-csd-adwaita-crossfont`.
|
|
||||||
//! * `wayland-csd-adwaita-notitle`.
|
|
||||||
use crate::event_loop::{ActiveEventLoop, EventLoop, EventLoopBuilder};
|
|
||||||
use crate::monitor::MonitorHandle;
|
|
||||||
pub use crate::window::Theme;
|
|
||||||
use crate::window::{Window as CoreWindow, WindowAttributes};
|
|
||||||
|
|
||||||
/// Additional methods on [`ActiveEventLoop`] that are specific to Wayland.
|
|
||||||
pub trait ActiveEventLoopExtWayland {
|
|
||||||
/// True if the [`ActiveEventLoop`] uses Wayland.
|
|
||||||
fn is_wayland(&self) -> bool;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ActiveEventLoopExtWayland for dyn ActiveEventLoop + '_ {
|
|
||||||
#[inline]
|
|
||||||
fn is_wayland(&self) -> bool {
|
|
||||||
self.as_any().downcast_ref::<crate::platform_impl::wayland::ActiveEventLoop>().is_some()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on [`EventLoop`] that are specific to Wayland.
|
|
||||||
pub trait EventLoopExtWayland {
|
|
||||||
/// True if the [`EventLoop`] uses Wayland.
|
|
||||||
fn is_wayland(&self) -> bool;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventLoopExtWayland for EventLoop {
|
|
||||||
#[inline]
|
|
||||||
fn is_wayland(&self) -> bool {
|
|
||||||
self.event_loop.is_wayland()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on [`EventLoopBuilder`] that are specific to Wayland.
|
|
||||||
pub trait EventLoopBuilderExtWayland {
|
|
||||||
/// Force using Wayland.
|
|
||||||
fn with_wayland(&mut self) -> &mut Self;
|
|
||||||
|
|
||||||
/// Whether to allow the event loop to be created off of the main thread.
|
|
||||||
///
|
|
||||||
/// By default, the window is only allowed to be created on the main
|
|
||||||
/// thread, to make platform compatibility easier.
|
|
||||||
fn with_any_thread(&mut self, any_thread: bool) -> &mut Self;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventLoopBuilderExtWayland for EventLoopBuilder {
|
|
||||||
#[inline]
|
|
||||||
fn with_wayland(&mut self) -> &mut Self {
|
|
||||||
self.platform_specific.forced_backend = Some(crate::platform_impl::Backend::Wayland);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_any_thread(&mut self, any_thread: bool) -> &mut Self {
|
|
||||||
self.platform_specific.any_thread = any_thread;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on [`Window`] that are specific to Wayland.
|
|
||||||
///
|
|
||||||
/// [`Window`]: crate::window::Window
|
|
||||||
pub trait WindowExtWayland {}
|
|
||||||
|
|
||||||
impl WindowExtWayland for dyn CoreWindow + '_ {}
|
|
||||||
|
|
||||||
/// Additional methods on [`WindowAttributes`] that are specific to Wayland.
|
|
||||||
pub trait WindowAttributesExtWayland {
|
|
||||||
/// Build window with the given name.
|
|
||||||
///
|
|
||||||
/// The `general` name sets an application ID, which should match the `.desktop`
|
|
||||||
/// file distributed with your program. The `instance` is a `no-op`.
|
|
||||||
///
|
|
||||||
/// For details about application ID conventions, see the
|
|
||||||
/// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id)
|
|
||||||
fn with_name(self, general: impl Into<String>, instance: impl Into<String>) -> Self;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowAttributesExtWayland for WindowAttributes {
|
|
||||||
#[inline]
|
|
||||||
fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self {
|
|
||||||
self.platform_specific.name =
|
|
||||||
Some(crate::platform_impl::ApplicationName::new(general.into(), instance.into()));
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on `MonitorHandle` that are specific to Wayland.
|
|
||||||
pub trait MonitorHandleExtWayland {
|
|
||||||
/// Returns the inner identifier of the monitor.
|
|
||||||
fn native_id(&self) -> u32;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorHandleExtWayland for MonitorHandle {
|
|
||||||
#[inline]
|
|
||||||
fn native_id(&self) -> u32 {
|
|
||||||
self.inner.native_identifier()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
#![allow(clippy::unnecessary_cast)]
|
|
||||||
|
|
||||||
use std::rc::Rc;
|
|
||||||
|
|
||||||
use objc2::{declare_class, msg_send, mutability, ClassType, DeclaredClass};
|
|
||||||
use objc2_app_kit::{NSApplication, NSEvent, NSEventModifierFlags, NSEventType, NSResponder};
|
|
||||||
use objc2_foundation::{MainThreadMarker, NSObject};
|
|
||||||
|
|
||||||
use super::app_state::AppState;
|
|
||||||
use crate::event::{DeviceEvent, ElementState};
|
|
||||||
|
|
||||||
declare_class!(
|
|
||||||
pub(super) struct WinitApplication;
|
|
||||||
|
|
||||||
unsafe impl ClassType for WinitApplication {
|
|
||||||
#[inherits(NSResponder, NSObject)]
|
|
||||||
type Super = NSApplication;
|
|
||||||
type Mutability = mutability::MainThreadOnly;
|
|
||||||
const NAME: &'static str = "WinitApplication";
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DeclaredClass for WinitApplication {}
|
|
||||||
|
|
||||||
unsafe impl WinitApplication {
|
|
||||||
// Normally, holding Cmd + any key never sends us a `keyUp` event for that key.
|
|
||||||
// Overriding `sendEvent:` like this fixes that. (https://stackoverflow.com/a/15294196)
|
|
||||||
// Fun fact: Firefox still has this bug! (https://bugzilla.mozilla.org/show_bug.cgi?id=1299553)
|
|
||||||
#[method(sendEvent:)]
|
|
||||||
fn send_event(&self, event: &NSEvent) {
|
|
||||||
// For posterity, there are some undocumented event types
|
|
||||||
// (https://github.com/servo/cocoa-rs/issues/155)
|
|
||||||
// but that doesn't really matter here.
|
|
||||||
let event_type = unsafe { event.r#type() };
|
|
||||||
let modifier_flags = unsafe { event.modifierFlags() };
|
|
||||||
if event_type == NSEventType::KeyUp
|
|
||||||
&& modifier_flags.contains(NSEventModifierFlags::NSEventModifierFlagCommand)
|
|
||||||
{
|
|
||||||
if let Some(key_window) = self.keyWindow() {
|
|
||||||
key_window.sendEvent(event);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let app_state = AppState::get(MainThreadMarker::from(self));
|
|
||||||
maybe_dispatch_device_event(&app_state, event);
|
|
||||||
unsafe { msg_send![super(self), sendEvent: event] }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
fn maybe_dispatch_device_event(app_state: &Rc<AppState>, event: &NSEvent) {
|
|
||||||
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 = 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| {
|
|
||||||
app.device_event(event_loop, None, DeviceEvent::PointerMotion {
|
|
||||||
delta: (delta_x, delta_y),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
},
|
|
||||||
NSEventType::LeftMouseDown | NSEventType::RightMouseDown | NSEventType::OtherMouseDown => {
|
|
||||||
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,
|
|
||||||
state: ElementState::Pressed,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
},
|
|
||||||
NSEventType::LeftMouseUp | NSEventType::RightMouseUp | NSEventType::OtherMouseUp => {
|
|
||||||
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,
|
|
||||||
state: ElementState::Released,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
},
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,254 +0,0 @@
|
|||||||
// TODO: Upstream these
|
|
||||||
|
|
||||||
#![allow(dead_code, non_snake_case, non_upper_case_globals)]
|
|
||||||
|
|
||||||
use std::ffi::c_void;
|
|
||||||
|
|
||||||
use core_foundation::array::CFArrayRef;
|
|
||||||
use core_foundation::dictionary::CFDictionaryRef;
|
|
||||||
use core_foundation::string::CFStringRef;
|
|
||||||
use core_foundation::uuid::CFUUIDRef;
|
|
||||||
use core_graphics::base::CGError;
|
|
||||||
use core_graphics::display::{CGDirectDisplayID, CGDisplayConfigRef};
|
|
||||||
use objc2::ffi::NSInteger;
|
|
||||||
use objc2::runtime::AnyObject;
|
|
||||||
|
|
||||||
pub type CGDisplayFadeInterval = f32;
|
|
||||||
pub type CGDisplayReservationInterval = f32;
|
|
||||||
pub type CGDisplayBlendFraction = f32;
|
|
||||||
|
|
||||||
pub const kCGDisplayBlendNormal: f32 = 0.0;
|
|
||||||
pub const kCGDisplayBlendSolidColor: f32 = 1.0;
|
|
||||||
|
|
||||||
pub type CGDisplayFadeReservationToken = u32;
|
|
||||||
pub const kCGDisplayFadeReservationInvalidToken: CGDisplayFadeReservationToken = 0;
|
|
||||||
|
|
||||||
pub type Boolean = u8;
|
|
||||||
pub const FALSE: Boolean = 0;
|
|
||||||
pub const TRUE: Boolean = 1;
|
|
||||||
|
|
||||||
pub const kCGErrorSuccess: i32 = 0;
|
|
||||||
pub const kCGErrorFailure: i32 = 1000;
|
|
||||||
pub const kCGErrorIllegalArgument: i32 = 1001;
|
|
||||||
pub const kCGErrorInvalidConnection: i32 = 1002;
|
|
||||||
pub const kCGErrorInvalidContext: i32 = 1003;
|
|
||||||
pub const kCGErrorCannotComplete: i32 = 1004;
|
|
||||||
pub const kCGErrorNotImplemented: i32 = 1006;
|
|
||||||
pub const kCGErrorRangeCheck: i32 = 1007;
|
|
||||||
pub const kCGErrorTypeCheck: i32 = 1008;
|
|
||||||
pub const kCGErrorInvalidOperation: i32 = 1010;
|
|
||||||
pub const kCGErrorNoneAvailable: i32 = 1011;
|
|
||||||
|
|
||||||
pub const IO1BitIndexedPixels: &str = "P";
|
|
||||||
pub const IO2BitIndexedPixels: &str = "PP";
|
|
||||||
pub const IO4BitIndexedPixels: &str = "PPPP";
|
|
||||||
pub const IO8BitIndexedPixels: &str = "PPPPPPPP";
|
|
||||||
pub const IO16BitDirectPixels: &str = "-RRRRRGGGGGBBBBB";
|
|
||||||
pub const IO32BitDirectPixels: &str = "--------RRRRRRRRGGGGGGGGBBBBBBBB";
|
|
||||||
|
|
||||||
pub const kIO30BitDirectPixels: &str = "--RRRRRRRRRRGGGGGGGGGGBBBBBBBBBB";
|
|
||||||
pub const kIO64BitDirectPixels: &str = "-16R16G16B16";
|
|
||||||
|
|
||||||
pub const kIO16BitFloatPixels: &str = "-16FR16FG16FB16";
|
|
||||||
pub const kIO32BitFloatPixels: &str = "-32FR32FG32FB32";
|
|
||||||
|
|
||||||
pub const IOYUV422Pixels: &str = "Y4U2V2";
|
|
||||||
pub const IO8BitOverlayPixels: &str = "O8";
|
|
||||||
|
|
||||||
pub type CGWindowLevel = i32;
|
|
||||||
pub type CGDisplayModeRef = *mut c_void;
|
|
||||||
|
|
||||||
// `CGDisplayCreateUUIDFromDisplayID` comes from the `ColorSync` framework.
|
|
||||||
// However, that framework was only introduced "publicly" in macOS 10.13.
|
|
||||||
//
|
|
||||||
// Since we want to support older versions, we can't link to `ColorSync`
|
|
||||||
// directly. Fortunately, it has always been available as a subframework of
|
|
||||||
// `ApplicationServices`, see:
|
|
||||||
// https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/OSX_Technology_Overview/SystemFrameworks/SystemFrameworks.html#//apple_ref/doc/uid/TP40001067-CH210-BBCFFIEG
|
|
||||||
#[link(name = "ApplicationServices", kind = "framework")]
|
|
||||||
extern "C" {
|
|
||||||
pub fn CGDisplayCreateUUIDFromDisplayID(display: CGDirectDisplayID) -> CFUUIDRef;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[link(name = "CoreGraphics", kind = "framework")]
|
|
||||||
extern "C" {
|
|
||||||
pub fn CGRestorePermanentDisplayConfiguration();
|
|
||||||
pub fn CGDisplayCapture(display: CGDirectDisplayID) -> CGError;
|
|
||||||
pub fn CGDisplayRelease(display: CGDirectDisplayID) -> CGError;
|
|
||||||
pub fn CGConfigureDisplayFadeEffect(
|
|
||||||
config: CGDisplayConfigRef,
|
|
||||||
fadeOutSeconds: CGDisplayFadeInterval,
|
|
||||||
fadeInSeconds: CGDisplayFadeInterval,
|
|
||||||
fadeRed: f32,
|
|
||||||
fadeGreen: f32,
|
|
||||||
fadeBlue: f32,
|
|
||||||
) -> CGError;
|
|
||||||
pub fn CGAcquireDisplayFadeReservation(
|
|
||||||
seconds: CGDisplayReservationInterval,
|
|
||||||
token: *mut CGDisplayFadeReservationToken,
|
|
||||||
) -> CGError;
|
|
||||||
pub fn CGDisplayFade(
|
|
||||||
token: CGDisplayFadeReservationToken,
|
|
||||||
duration: CGDisplayFadeInterval,
|
|
||||||
startBlend: CGDisplayBlendFraction,
|
|
||||||
endBlend: CGDisplayBlendFraction,
|
|
||||||
redBlend: f32,
|
|
||||||
greenBlend: f32,
|
|
||||||
blueBlend: f32,
|
|
||||||
synchronous: Boolean,
|
|
||||||
) -> CGError;
|
|
||||||
pub fn CGReleaseDisplayFadeReservation(token: CGDisplayFadeReservationToken) -> CGError;
|
|
||||||
pub fn CGShieldingWindowLevel() -> CGWindowLevel;
|
|
||||||
pub fn CGDisplaySetDisplayMode(
|
|
||||||
display: CGDirectDisplayID,
|
|
||||||
mode: CGDisplayModeRef,
|
|
||||||
options: CFDictionaryRef,
|
|
||||||
) -> CGError;
|
|
||||||
pub fn CGDisplayCopyAllDisplayModes(
|
|
||||||
display: CGDirectDisplayID,
|
|
||||||
options: CFDictionaryRef,
|
|
||||||
) -> CFArrayRef;
|
|
||||||
pub fn CGDisplayModeGetPixelWidth(mode: CGDisplayModeRef) -> usize;
|
|
||||||
pub fn CGDisplayModeGetPixelHeight(mode: CGDisplayModeRef) -> usize;
|
|
||||||
pub fn CGDisplayModeGetRefreshRate(mode: CGDisplayModeRef) -> f64;
|
|
||||||
pub fn CGDisplayModeCopyPixelEncoding(mode: CGDisplayModeRef) -> CFStringRef;
|
|
||||||
pub fn CGDisplayModeRetain(mode: CGDisplayModeRef);
|
|
||||||
pub fn CGDisplayModeRelease(mode: CGDisplayModeRef);
|
|
||||||
|
|
||||||
// Wildly used private APIs; Apple uses them for their Terminal.app.
|
|
||||||
pub fn CGSMainConnectionID() -> *mut AnyObject;
|
|
||||||
pub fn CGSSetWindowBackgroundBlurRadius(
|
|
||||||
connection_id: *mut AnyObject,
|
|
||||||
window_id: NSInteger,
|
|
||||||
radius: i64,
|
|
||||||
) -> i32;
|
|
||||||
}
|
|
||||||
|
|
||||||
mod core_video {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[link(name = "CoreVideo", kind = "framework")]
|
|
||||||
extern "C" {}
|
|
||||||
|
|
||||||
// CVBase.h
|
|
||||||
|
|
||||||
pub type CVTimeFlags = i32; // int32_t
|
|
||||||
pub const kCVTimeIsIndefinite: CVTimeFlags = 1 << 0;
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct CVTime {
|
|
||||||
pub time_value: i64, // int64_t
|
|
||||||
pub time_scale: i32, // int32_t
|
|
||||||
pub flags: i32, // int32_t
|
|
||||||
}
|
|
||||||
|
|
||||||
// CVReturn.h
|
|
||||||
|
|
||||||
pub type CVReturn = i32; // int32_t
|
|
||||||
pub const kCVReturnSuccess: CVReturn = 0;
|
|
||||||
|
|
||||||
// CVDisplayLink.h
|
|
||||||
|
|
||||||
pub type CVDisplayLinkRef = *mut c_void;
|
|
||||||
|
|
||||||
extern "C" {
|
|
||||||
pub fn CVDisplayLinkCreateWithCGDisplay(
|
|
||||||
displayID: CGDirectDisplayID,
|
|
||||||
displayLinkOut: *mut CVDisplayLinkRef,
|
|
||||||
) -> CVReturn;
|
|
||||||
pub fn CVDisplayLinkGetNominalOutputVideoRefreshPeriod(
|
|
||||||
displayLink: CVDisplayLinkRef,
|
|
||||||
) -> CVTime;
|
|
||||||
pub fn CVDisplayLinkRelease(displayLink: CVDisplayLinkRef);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub use core_video::*;
|
|
||||||
#[repr(transparent)]
|
|
||||||
pub struct TISInputSource(std::ffi::c_void);
|
|
||||||
pub type TISInputSourceRef = *mut TISInputSource;
|
|
||||||
|
|
||||||
#[repr(transparent)]
|
|
||||||
pub struct UCKeyboardLayout(std::ffi::c_void);
|
|
||||||
|
|
||||||
pub type OptionBits = u32;
|
|
||||||
pub type UniCharCount = std::os::raw::c_ulong;
|
|
||||||
pub type UniChar = std::os::raw::c_ushort;
|
|
||||||
pub type OSStatus = i32;
|
|
||||||
|
|
||||||
#[allow(non_upper_case_globals)]
|
|
||||||
pub const kUCKeyActionDisplay: u16 = 3;
|
|
||||||
#[allow(non_upper_case_globals)]
|
|
||||||
pub const kUCKeyTranslateNoDeadKeysMask: OptionBits = 1;
|
|
||||||
|
|
||||||
#[link(name = "Carbon", kind = "framework")]
|
|
||||||
extern "C" {
|
|
||||||
pub static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
|
|
||||||
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn TISGetInputSourceProperty(
|
|
||||||
inputSource: TISInputSourceRef,
|
|
||||||
propertyKey: CFStringRef,
|
|
||||||
) -> *mut c_void;
|
|
||||||
|
|
||||||
pub fn TISCopyCurrentKeyboardLayoutInputSource() -> TISInputSourceRef;
|
|
||||||
|
|
||||||
pub fn LMGetKbdType() -> u8;
|
|
||||||
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn UCKeyTranslate(
|
|
||||||
keyLayoutPtr: *const UCKeyboardLayout,
|
|
||||||
virtualKeyCode: u16,
|
|
||||||
keyAction: u16,
|
|
||||||
modifierKeyState: u32,
|
|
||||||
keyboardType: u32,
|
|
||||||
keyTranslateOptions: OptionBits,
|
|
||||||
deadKeyState: *mut u32,
|
|
||||||
maxStringLength: UniCharCount,
|
|
||||||
actualStringLength: *mut UniCharCount,
|
|
||||||
unicodeString: *mut UniChar,
|
|
||||||
) -> OSStatus;
|
|
||||||
}
|
|
||||||
|
|
||||||
// CGWindowLevel.h
|
|
||||||
//
|
|
||||||
// Note: There are two different things at play in this header:
|
|
||||||
// `CGWindowLevel` and `CGWindowLevelKey`.
|
|
||||||
//
|
|
||||||
// It seems like there was a push towards using "key" values instead of the
|
|
||||||
// raw window level values, and then you were supposed to use
|
|
||||||
// `CGWindowLevelForKey` to get the actual level.
|
|
||||||
//
|
|
||||||
// But the values that `NSWindowLevel` has are compiled in, and as such has
|
|
||||||
// to remain ABI compatible, so they're safe for us to hardcode as well.
|
|
||||||
#[allow(dead_code, non_upper_case_globals)]
|
|
||||||
mod window_level {
|
|
||||||
const kCGNumReservedWindowLevels: i32 = 16;
|
|
||||||
const kCGNumReservedBaseWindowLevels: i32 = 5;
|
|
||||||
|
|
||||||
pub const kCGBaseWindowLevel: i32 = i32::MIN;
|
|
||||||
pub const kCGMinimumWindowLevel: i32 = kCGBaseWindowLevel + kCGNumReservedBaseWindowLevels;
|
|
||||||
pub const kCGMaximumWindowLevel: i32 = i32::MAX - kCGNumReservedWindowLevels;
|
|
||||||
|
|
||||||
pub const kCGDesktopWindowLevel: i32 = kCGMinimumWindowLevel + 20;
|
|
||||||
pub const kCGDesktopIconWindowLevel: i32 = kCGDesktopWindowLevel + 20;
|
|
||||||
pub const kCGBackstopMenuLevel: i32 = -20;
|
|
||||||
pub const kCGNormalWindowLevel: i32 = 0;
|
|
||||||
pub const kCGFloatingWindowLevel: i32 = 3;
|
|
||||||
pub const kCGTornOffMenuWindowLevel: i32 = 3;
|
|
||||||
pub const kCGModalPanelWindowLevel: i32 = 8;
|
|
||||||
pub const kCGUtilityWindowLevel: i32 = 19;
|
|
||||||
pub const kCGDockWindowLevel: i32 = 20;
|
|
||||||
pub const kCGMainMenuWindowLevel: i32 = 24;
|
|
||||||
pub const kCGStatusWindowLevel: i32 = 25;
|
|
||||||
pub const kCGPopUpMenuWindowLevel: i32 = 101;
|
|
||||||
pub const kCGOverlayWindowLevel: i32 = 102;
|
|
||||||
pub const kCGHelpWindowLevel: i32 = 200;
|
|
||||||
pub const kCGDraggingWindowLevel: i32 = 500;
|
|
||||||
pub const kCGScreenSaverWindowLevel: i32 = 1000;
|
|
||||||
pub const kCGAssistiveTechHighWindowLevel: i32 = 1500;
|
|
||||||
pub const kCGCursorWindowLevel: i32 = kCGMaximumWindowLevel - 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub use window_level::*;
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
#[macro_use]
|
|
||||||
mod util;
|
|
||||||
|
|
||||||
mod app;
|
|
||||||
mod app_state;
|
|
||||||
mod cursor;
|
|
||||||
mod event;
|
|
||||||
mod event_loop;
|
|
||||||
mod ffi;
|
|
||||||
mod menu;
|
|
||||||
mod monitor;
|
|
||||||
mod observer;
|
|
||||||
mod view;
|
|
||||||
mod window;
|
|
||||||
mod window_delegate;
|
|
||||||
|
|
||||||
pub(crate) use self::cursor::CustomCursor as PlatformCustomCursor;
|
|
||||||
pub(crate) use self::event::{physicalkey_to_scancode, scancode_to_physicalkey, KeyEventExtra};
|
|
||||||
pub(crate) use self::event_loop::{
|
|
||||||
ActiveEventLoop, EventLoop, PlatformSpecificEventLoopAttributes,
|
|
||||||
};
|
|
||||||
pub(crate) use self::monitor::{MonitorHandle, VideoModeHandle};
|
|
||||||
pub(crate) use self::window::Window;
|
|
||||||
pub(crate) use self::window_delegate::PlatformSpecificWindowAttributes;
|
|
||||||
pub(crate) use crate::cursor::OnlyCursorImageSource as PlatformCustomCursorSource;
|
|
||||||
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
|
||||||
pub(crate) use crate::platform_impl::Fullscreen;
|
|
||||||
@@ -1,368 +0,0 @@
|
|||||||
#![allow(clippy::unnecessary_cast)]
|
|
||||||
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
use std::fmt;
|
|
||||||
use std::num::{NonZeroU16, NonZeroU32};
|
|
||||||
|
|
||||||
use core_foundation::array::{CFArrayGetCount, CFArrayGetValueAtIndex};
|
|
||||||
use core_foundation::base::{CFRelease, TCFType};
|
|
||||||
use core_foundation::string::CFString;
|
|
||||||
use core_graphics::display::{
|
|
||||||
CGDirectDisplayID, CGDisplay, CGDisplayBounds, CGDisplayCopyDisplayMode,
|
|
||||||
};
|
|
||||||
use objc2::rc::Retained;
|
|
||||||
use objc2::runtime::AnyObject;
|
|
||||||
use objc2_app_kit::NSScreen;
|
|
||||||
use objc2_foundation::{ns_string, run_on_main, MainThreadMarker, NSNumber, NSPoint, NSRect};
|
|
||||||
|
|
||||||
use super::ffi;
|
|
||||||
use crate::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize};
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct VideoModeHandle {
|
|
||||||
size: PhysicalSize<u32>,
|
|
||||||
bit_depth: Option<NonZeroU16>,
|
|
||||||
refresh_rate_millihertz: Option<NonZeroU32>,
|
|
||||||
pub(crate) monitor: MonitorHandle,
|
|
||||||
pub(crate) native_mode: NativeDisplayMode,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PartialEq for VideoModeHandle {
|
|
||||||
fn eq(&self, other: &Self) -> bool {
|
|
||||||
self.size == other.size
|
|
||||||
&& self.bit_depth == other.bit_depth
|
|
||||||
&& self.refresh_rate_millihertz == other.refresh_rate_millihertz
|
|
||||||
&& self.monitor == other.monitor
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Eq for VideoModeHandle {}
|
|
||||||
|
|
||||||
impl std::hash::Hash for VideoModeHandle {
|
|
||||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
|
||||||
self.size.hash(state);
|
|
||||||
self.bit_depth.hash(state);
|
|
||||||
self.refresh_rate_millihertz.hash(state);
|
|
||||||
self.monitor.hash(state);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Debug for VideoModeHandle {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
f.debug_struct("VideoModeHandle")
|
|
||||||
.field("size", &self.size)
|
|
||||||
.field("bit_depth", &self.bit_depth)
|
|
||||||
.field("refresh_rate_millihertz", &self.refresh_rate_millihertz)
|
|
||||||
.field("monitor", &self.monitor)
|
|
||||||
.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct NativeDisplayMode(pub ffi::CGDisplayModeRef);
|
|
||||||
|
|
||||||
unsafe impl Send for NativeDisplayMode {}
|
|
||||||
unsafe impl Sync for NativeDisplayMode {}
|
|
||||||
|
|
||||||
impl Drop for NativeDisplayMode {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
unsafe {
|
|
||||||
ffi::CGDisplayModeRelease(self.0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Clone for NativeDisplayMode {
|
|
||||||
fn clone(&self) -> Self {
|
|
||||||
unsafe {
|
|
||||||
ffi::CGDisplayModeRetain(self.0);
|
|
||||||
}
|
|
||||||
NativeDisplayMode(self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl VideoModeHandle {
|
|
||||||
fn new(
|
|
||||||
monitor: MonitorHandle,
|
|
||||||
mode: NativeDisplayMode,
|
|
||||||
refresh_rate_millihertz: Option<NonZeroU32>,
|
|
||||||
) -> Self {
|
|
||||||
unsafe {
|
|
||||||
let pixel_encoding =
|
|
||||||
CFString::wrap_under_create_rule(ffi::CGDisplayModeCopyPixelEncoding(mode.0))
|
|
||||||
.to_string();
|
|
||||||
let bit_depth = if pixel_encoding.eq_ignore_ascii_case(ffi::IO32BitDirectPixels) {
|
|
||||||
32
|
|
||||||
} else if pixel_encoding.eq_ignore_ascii_case(ffi::IO16BitDirectPixels) {
|
|
||||||
16
|
|
||||||
} else if pixel_encoding.eq_ignore_ascii_case(ffi::kIO30BitDirectPixels) {
|
|
||||||
30
|
|
||||||
} else {
|
|
||||||
unimplemented!()
|
|
||||||
};
|
|
||||||
|
|
||||||
VideoModeHandle {
|
|
||||||
size: PhysicalSize::new(
|
|
||||||
ffi::CGDisplayModeGetPixelWidth(mode.0) as u32,
|
|
||||||
ffi::CGDisplayModeGetPixelHeight(mode.0) as u32,
|
|
||||||
),
|
|
||||||
refresh_rate_millihertz,
|
|
||||||
bit_depth: NonZeroU16::new(bit_depth),
|
|
||||||
monitor: monitor.clone(),
|
|
||||||
native_mode: mode,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn size(&self) -> PhysicalSize<u32> {
|
|
||||||
self.size
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn bit_depth(&self) -> Option<NonZeroU16> {
|
|
||||||
self.bit_depth
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refresh_rate_millihertz(&self) -> Option<NonZeroU32> {
|
|
||||||
self.refresh_rate_millihertz
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn monitor(&self) -> MonitorHandle {
|
|
||||||
self.monitor.clone()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct MonitorHandle(CGDirectDisplayID);
|
|
||||||
|
|
||||||
// `CGDirectDisplayID` changes on video mode change, so we cannot rely on that
|
|
||||||
// for comparisons, but we can use `CGDisplayCreateUUIDFromDisplayID` to get an
|
|
||||||
// unique identifier that persists even across system reboots
|
|
||||||
impl PartialEq for MonitorHandle {
|
|
||||||
fn eq(&self, other: &Self) -> bool {
|
|
||||||
unsafe {
|
|
||||||
ffi::CGDisplayCreateUUIDFromDisplayID(self.0)
|
|
||||||
== ffi::CGDisplayCreateUUIDFromDisplayID(other.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Eq for MonitorHandle {}
|
|
||||||
|
|
||||||
impl PartialOrd for MonitorHandle {
|
|
||||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
|
||||||
Some(self.cmp(other))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Ord for MonitorHandle {
|
|
||||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
|
||||||
unsafe {
|
|
||||||
ffi::CGDisplayCreateUUIDFromDisplayID(self.0)
|
|
||||||
.cmp(&ffi::CGDisplayCreateUUIDFromDisplayID(other.0))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::hash::Hash for MonitorHandle {
|
|
||||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
|
||||||
unsafe {
|
|
||||||
ffi::CGDisplayCreateUUIDFromDisplayID(self.0).hash(state);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn available_monitors() -> VecDeque<MonitorHandle> {
|
|
||||||
if let Ok(displays) = CGDisplay::active_displays() {
|
|
||||||
let mut monitors = VecDeque::with_capacity(displays.len());
|
|
||||||
for display in displays {
|
|
||||||
monitors.push_back(MonitorHandle(display));
|
|
||||||
}
|
|
||||||
monitors
|
|
||||||
} else {
|
|
||||||
VecDeque::with_capacity(0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn primary_monitor() -> MonitorHandle {
|
|
||||||
MonitorHandle(CGDisplay::main().id)
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Debug for MonitorHandle {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.debug_struct("MonitorHandle")
|
|
||||||
.field("name", &self.name())
|
|
||||||
.field("native_identifier", &self.native_identifier())
|
|
||||||
.field("position", &self.position())
|
|
||||||
.field("scale_factor", &self.scale_factor())
|
|
||||||
.finish_non_exhaustive()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorHandle {
|
|
||||||
pub fn new(id: CGDirectDisplayID) -> Self {
|
|
||||||
MonitorHandle(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Be smarter about this:
|
|
||||||
// <https://github.com/glfw/glfw/blob/57cbded0760a50b9039ee0cb3f3c14f60145567c/src/cocoa_monitor.m#L44-L126>
|
|
||||||
pub fn name(&self) -> Option<String> {
|
|
||||||
let MonitorHandle(display_id) = *self;
|
|
||||||
let screen_num = CGDisplay::new(display_id).model_number();
|
|
||||||
Some(format!("Monitor #{screen_num}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn native_identifier(&self) -> u32 {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn position(&self) -> Option<PhysicalPosition<i32>> {
|
|
||||||
// This is already in screen coordinates. If we were using `NSScreen`,
|
|
||||||
// then a conversion would've been needed:
|
|
||||||
// flip_window_screen_coordinates(self.ns_screen(mtm)?.frame())
|
|
||||||
let bounds = unsafe { CGDisplayBounds(self.native_identifier()) };
|
|
||||||
let position = LogicalPosition::new(bounds.origin.x, bounds.origin.y);
|
|
||||||
Some(position.to_physical(self.scale_factor()))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn scale_factor(&self) -> f64 {
|
|
||||||
run_on_main(|mtm| {
|
|
||||||
match self.ns_screen(mtm) {
|
|
||||||
Some(screen) => screen.backingScaleFactor() as f64,
|
|
||||||
None => 1.0, // default to 1.0 when we can't find the screen
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn refresh_rate_millihertz(&self) -> Option<NonZeroU32> {
|
|
||||||
let current_display_mode =
|
|
||||||
NativeDisplayMode(unsafe { CGDisplayCopyDisplayMode(self.0) } as _);
|
|
||||||
refresh_rate_millihertz(self.0, ¤t_display_mode)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn current_video_mode(&self) -> Option<VideoModeHandle> {
|
|
||||||
let mode = NativeDisplayMode(unsafe { CGDisplayCopyDisplayMode(self.0) } as _);
|
|
||||||
let refresh_rate_millihertz = refresh_rate_millihertz(self.0, &mode);
|
|
||||||
Some(VideoModeHandle::new(self.clone(), mode, refresh_rate_millihertz))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> {
|
|
||||||
let refresh_rate_millihertz = self.refresh_rate_millihertz();
|
|
||||||
let monitor = self.clone();
|
|
||||||
|
|
||||||
unsafe {
|
|
||||||
let modes = {
|
|
||||||
let array = ffi::CGDisplayCopyAllDisplayModes(self.0, std::ptr::null());
|
|
||||||
assert!(!array.is_null(), "failed to get list of display modes");
|
|
||||||
let array_count = CFArrayGetCount(array);
|
|
||||||
let modes: Vec<_> = (0..array_count)
|
|
||||||
.map(move |i| {
|
|
||||||
let mode = CFArrayGetValueAtIndex(array, i) as *mut _;
|
|
||||||
ffi::CGDisplayModeRetain(mode);
|
|
||||||
mode
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
CFRelease(array as *const _);
|
|
||||||
modes
|
|
||||||
};
|
|
||||||
|
|
||||||
modes.into_iter().map(move |mode| {
|
|
||||||
let cg_refresh_rate_hertz = ffi::CGDisplayModeGetRefreshRate(mode).round() as i64;
|
|
||||||
|
|
||||||
// CGDisplayModeGetRefreshRate returns 0.0 for any display that
|
|
||||||
// isn't a CRT
|
|
||||||
let refresh_rate_millihertz = if cg_refresh_rate_hertz > 0 {
|
|
||||||
NonZeroU32::new((cg_refresh_rate_hertz * 1000) as u32)
|
|
||||||
} else {
|
|
||||||
refresh_rate_millihertz
|
|
||||||
};
|
|
||||||
|
|
||||||
VideoModeHandle::new(
|
|
||||||
monitor.clone(),
|
|
||||||
NativeDisplayMode(mode),
|
|
||||||
refresh_rate_millihertz,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn ns_screen(&self, mtm: MainThreadMarker) -> Option<Retained<NSScreen>> {
|
|
||||||
let uuid = unsafe { ffi::CGDisplayCreateUUIDFromDisplayID(self.0) };
|
|
||||||
NSScreen::screens(mtm).into_iter().find(|screen| {
|
|
||||||
let other_native_id = get_display_id(screen);
|
|
||||||
let other_uuid = unsafe {
|
|
||||||
ffi::CGDisplayCreateUUIDFromDisplayID(other_native_id as CGDirectDisplayID)
|
|
||||||
};
|
|
||||||
uuid == other_uuid
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn get_display_id(screen: &NSScreen) -> u32 {
|
|
||||||
let key = ns_string!("NSScreenNumber");
|
|
||||||
|
|
||||||
objc2::rc::autoreleasepool(|_| {
|
|
||||||
let device_description = screen.deviceDescription();
|
|
||||||
|
|
||||||
// Retrieve the CGDirectDisplayID associated with this screen
|
|
||||||
//
|
|
||||||
// SAFETY: The value from @"NSScreenNumber" in deviceDescription is guaranteed
|
|
||||||
// to be an NSNumber. See documentation for `deviceDescription` for details:
|
|
||||||
// <https://developer.apple.com/documentation/appkit/nsscreen/1388360-devicedescription?language=objc>
|
|
||||||
let obj = device_description
|
|
||||||
.get(key)
|
|
||||||
.expect("failed getting screen display id from device description");
|
|
||||||
let obj: *const AnyObject = obj;
|
|
||||||
let obj: *const NSNumber = obj.cast();
|
|
||||||
let obj: &NSNumber = unsafe { &*obj };
|
|
||||||
|
|
||||||
obj.as_u32()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Core graphics screen coordinates are relative to the top-left corner of
|
|
||||||
/// the so-called "main" display, with y increasing downwards - which is
|
|
||||||
/// exactly what we want in Winit.
|
|
||||||
///
|
|
||||||
/// However, `NSWindow` and `NSScreen` changes these coordinates to:
|
|
||||||
/// 1. Be relative to the bottom-left corner of the "main" screen.
|
|
||||||
/// 2. Be relative to the bottom-left corner of the window/screen itself.
|
|
||||||
/// 3. Have y increasing upwards.
|
|
||||||
///
|
|
||||||
/// This conversion happens to be symmetric, so we only need this one function
|
|
||||||
/// to convert between the two coordinate systems.
|
|
||||||
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 = CGDisplay::main().bounds().size.height;
|
|
||||||
|
|
||||||
let y = main_screen_height - frame.size.height - frame.origin.y;
|
|
||||||
NSPoint::new(frame.origin.x, y)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn refresh_rate_millihertz(id: CGDirectDisplayID, mode: &NativeDisplayMode) -> Option<NonZeroU32> {
|
|
||||||
unsafe {
|
|
||||||
let refresh_rate = ffi::CGDisplayModeGetRefreshRate(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();
|
|
||||||
if ffi::CVDisplayLinkCreateWithCGDisplay(id, &mut display_link) != ffi::kCVReturnSuccess {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let time = ffi::CVDisplayLinkGetNominalOutputVideoRefreshPeriod(display_link);
|
|
||||||
ffi::CVDisplayLinkRelease(display_link);
|
|
||||||
|
|
||||||
// This value is indefinite if an invalid display link was specified
|
|
||||||
if time.flags & ffi::kCVTimeIsIndefinite != 0 {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
(time.time_scale as i64)
|
|
||||||
.checked_div(time.time_value)
|
|
||||||
.map(|v| (v * 1000) as u32)
|
|
||||||
.and_then(NonZeroU32::new)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
//! Apple/Darwin-specific implementations
|
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
mod appkit;
|
|
||||||
mod event_handler;
|
|
||||||
mod notification_center;
|
|
||||||
#[cfg(not(target_os = "macos"))]
|
|
||||||
mod uikit;
|
|
||||||
|
|
||||||
#[allow(unused_imports)]
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
pub use self::appkit::*;
|
|
||||||
#[allow(unused_imports)]
|
|
||||||
#[cfg(not(target_os = "macos"))]
|
|
||||||
pub use self::uikit::*;
|
|
||||||
@@ -1,714 +0,0 @@
|
|||||||
#![deny(unused_results)]
|
|
||||||
|
|
||||||
use std::cell::{OnceCell, RefCell, RefMut};
|
|
||||||
use std::collections::HashSet;
|
|
||||||
use std::os::raw::c_void;
|
|
||||||
use std::sync::atomic::Ordering;
|
|
||||||
use std::sync::{Arc, Mutex, OnceLock};
|
|
||||||
use std::time::Instant;
|
|
||||||
use std::{mem, ptr};
|
|
||||||
|
|
||||||
use core_foundation::base::CFRelease;
|
|
||||||
use core_foundation::date::CFAbsoluteTimeGetCurrent;
|
|
||||||
use core_foundation::runloop::{
|
|
||||||
kCFRunLoopCommonModes, CFRunLoopAddTimer, CFRunLoopGetMain, CFRunLoopRef, CFRunLoopTimerCreate,
|
|
||||||
CFRunLoopTimerInvalidate, CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate,
|
|
||||||
};
|
|
||||||
use objc2::rc::Retained;
|
|
||||||
use objc2::sel;
|
|
||||||
use objc2_foundation::{
|
|
||||||
CGRect, CGSize, MainThreadMarker, NSInteger, NSObjectProtocol, NSOperatingSystemVersion,
|
|
||||||
NSProcessInfo,
|
|
||||||
};
|
|
||||||
use objc2_ui_kit::{UIApplication, UICoordinateSpace, UIView, UIWindow};
|
|
||||||
|
|
||||||
use super::super::event_handler::EventHandler;
|
|
||||||
use super::window::WinitUIWindow;
|
|
||||||
use super::{ActiveEventLoop, EventLoopProxy};
|
|
||||||
use crate::application::ApplicationHandler;
|
|
||||||
use crate::dpi::PhysicalSize;
|
|
||||||
use crate::event::{StartCause, SurfaceSizeWriter, WindowEvent};
|
|
||||||
use crate::event_loop::ControlFlow;
|
|
||||||
use crate::window::WindowId;
|
|
||||||
|
|
||||||
macro_rules! bug {
|
|
||||||
($($msg:tt)*) => {
|
|
||||||
panic!("winit iOS bug, file an issue: {}", format!($($msg)*))
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! bug_assert {
|
|
||||||
($test:expr, $($msg:tt)*) => {
|
|
||||||
assert!($test, "winit iOS bug, file an issue: {}", format!($($msg)*))
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the global event handler for the application.
|
|
||||||
///
|
|
||||||
/// This is stored separately from AppState, since AppState needs to be accessible while the handler
|
|
||||||
/// is executing.
|
|
||||||
fn get_handler(mtm: MainThreadMarker) -> &'static EventHandler {
|
|
||||||
// TODO(madsmtm): Use `MainThreadBound` once that is possible in `static`s.
|
|
||||||
struct StaticMainThreadBound<T>(T);
|
|
||||||
|
|
||||||
impl<T> StaticMainThreadBound<T> {
|
|
||||||
const fn get(&self, _mtm: MainThreadMarker) -> &T {
|
|
||||||
&self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe impl<T> Send for StaticMainThreadBound<T> {}
|
|
||||||
unsafe impl<T> Sync for StaticMainThreadBound<T> {}
|
|
||||||
|
|
||||||
// SAFETY: Creating `StaticMainThreadBound` in a `const` context, where there is no concept
|
|
||||||
// of the main thread.
|
|
||||||
static GLOBAL: StaticMainThreadBound<OnceCell<EventHandler>> =
|
|
||||||
StaticMainThreadBound(OnceCell::new());
|
|
||||||
|
|
||||||
GLOBAL.get(mtm).get_or_init(EventHandler::new)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub(crate) enum EventWrapper {
|
|
||||||
Window { window_id: WindowId, event: WindowEvent },
|
|
||||||
ScaleFactorChanged(ScaleFactorChanged),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct ScaleFactorChanged {
|
|
||||||
pub(super) window: Retained<WinitUIWindow>,
|
|
||||||
pub(super) suggested_size: PhysicalSize<u32>,
|
|
||||||
pub(super) scale_factor: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventWrapper {
|
|
||||||
fn is_redraw(&self) -> bool {
|
|
||||||
matches!(self, Self::Window { event: WindowEvent::RedrawRequested, .. })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// this is the state machine for the app lifecycle
|
|
||||||
#[derive(Debug)]
|
|
||||||
#[must_use = "dropping `AppStateImpl` without inspecting it is probably a bug"]
|
|
||||||
enum AppStateImpl {
|
|
||||||
Initial {
|
|
||||||
queued_gpu_redraws: HashSet<Retained<WinitUIWindow>>,
|
|
||||||
},
|
|
||||||
ProcessingEvents {
|
|
||||||
queued_gpu_redraws: HashSet<Retained<WinitUIWindow>>,
|
|
||||||
active_control_flow: ControlFlow,
|
|
||||||
},
|
|
||||||
ProcessingRedraws {
|
|
||||||
active_control_flow: ControlFlow,
|
|
||||||
},
|
|
||||||
Waiting {
|
|
||||||
start: Instant,
|
|
||||||
},
|
|
||||||
PollFinished,
|
|
||||||
Terminated,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) struct AppState {
|
|
||||||
// This should never be `None`, except for briefly during a state transition.
|
|
||||||
app_state: Option<AppStateImpl>,
|
|
||||||
control_flow: ControlFlow,
|
|
||||||
waker: EventLoopWaker,
|
|
||||||
event_loop_proxy: Arc<EventLoopProxy>,
|
|
||||||
queued_events: Vec<EventWrapper>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AppState {
|
|
||||||
pub(crate) fn get_mut(_mtm: MainThreadMarker) -> RefMut<'static, AppState> {
|
|
||||||
// basically everything in UIKit requires the main thread, so it's pointless to use the
|
|
||||||
// std::sync APIs.
|
|
||||||
// must be mut because plain `static` requires `Sync`
|
|
||||||
static mut APP_STATE: RefCell<Option<AppState>> = RefCell::new(None);
|
|
||||||
|
|
||||||
#[allow(unknown_lints)] // New lint below
|
|
||||||
#[allow(static_mut_refs)] // TODO: Use `MainThreadBound` instead.
|
|
||||||
let mut guard = unsafe { APP_STATE.borrow_mut() };
|
|
||||||
if guard.is_none() {
|
|
||||||
#[inline(never)]
|
|
||||||
#[cold]
|
|
||||||
fn init_guard(guard: &mut RefMut<'static, Option<AppState>>) {
|
|
||||||
let waker = EventLoopWaker::new(unsafe { CFRunLoopGetMain() });
|
|
||||||
**guard = Some(AppState {
|
|
||||||
app_state: Some(AppStateImpl::Initial { queued_gpu_redraws: HashSet::new() }),
|
|
||||||
control_flow: ControlFlow::default(),
|
|
||||||
waker,
|
|
||||||
event_loop_proxy: Arc::new(EventLoopProxy::new()),
|
|
||||||
queued_events: Vec::new(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
init_guard(&mut guard);
|
|
||||||
}
|
|
||||||
RefMut::map(guard, |state| state.as_mut().unwrap())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn state(&self) -> &AppStateImpl {
|
|
||||||
match &self.app_state {
|
|
||||||
Some(ref state) => state,
|
|
||||||
None => bug!("`AppState` previously failed a state transition"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn state_mut(&mut self) -> &mut AppStateImpl {
|
|
||||||
match &mut self.app_state {
|
|
||||||
Some(ref mut state) => state,
|
|
||||||
None => bug!("`AppState` previously failed a state transition"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn take_state(&mut self) -> AppStateImpl {
|
|
||||||
match self.app_state.take() {
|
|
||||||
Some(state) => state,
|
|
||||||
None => bug!("`AppState` previously failed a state transition"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_state(&mut self, new_state: AppStateImpl) {
|
|
||||||
bug_assert!(
|
|
||||||
self.app_state.is_none(),
|
|
||||||
"attempted to set an `AppState` without calling `take_state` first {:?}",
|
|
||||||
self.app_state
|
|
||||||
);
|
|
||||||
self.app_state = Some(new_state)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn replace_state(&mut self, new_state: AppStateImpl) -> AppStateImpl {
|
|
||||||
match &mut self.app_state {
|
|
||||||
Some(ref mut state) => mem::replace(state, new_state),
|
|
||||||
None => bug!("`AppState` previously failed a state transition"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn has_launched(&self) -> bool {
|
|
||||||
!matches!(self.state(), AppStateImpl::Initial { .. })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn has_terminated(&self) -> bool {
|
|
||||||
matches!(self.state(), AppStateImpl::Terminated)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn did_finish_launching_transition(&mut self) {
|
|
||||||
let queued_gpu_redraws = match self.take_state() {
|
|
||||||
AppStateImpl::Initial { queued_gpu_redraws } => queued_gpu_redraws,
|
|
||||||
s => bug!("unexpected state {:?}", s),
|
|
||||||
};
|
|
||||||
self.set_state(AppStateImpl::ProcessingEvents {
|
|
||||||
active_control_flow: self.control_flow,
|
|
||||||
queued_gpu_redraws,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn wakeup_transition(&mut self) -> Option<StartCause> {
|
|
||||||
// before `AppState::did_finish_launching` is called, pretend there is no running
|
|
||||||
// event loop.
|
|
||||||
if !self.has_launched() || self.has_terminated() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let start_cause = match (self.control_flow, self.take_state()) {
|
|
||||||
(ControlFlow::Poll, AppStateImpl::PollFinished) => StartCause::Poll,
|
|
||||||
(ControlFlow::Wait, AppStateImpl::Waiting { start }) => {
|
|
||||||
StartCause::WaitCancelled { start, requested_resume: None }
|
|
||||||
},
|
|
||||||
(ControlFlow::WaitUntil(requested_resume), AppStateImpl::Waiting { start }) => {
|
|
||||||
if Instant::now() >= requested_resume {
|
|
||||||
StartCause::ResumeTimeReached { start, requested_resume }
|
|
||||||
} else {
|
|
||||||
StartCause::WaitCancelled { start, requested_resume: Some(requested_resume) }
|
|
||||||
}
|
|
||||||
},
|
|
||||||
s => bug!("`EventHandler` unexpectedly woke up {:?}", s),
|
|
||||||
};
|
|
||||||
|
|
||||||
self.set_state(AppStateImpl::ProcessingEvents {
|
|
||||||
queued_gpu_redraws: Default::default(),
|
|
||||||
active_control_flow: self.control_flow,
|
|
||||||
});
|
|
||||||
Some(start_cause)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main_events_cleared_transition(&mut self) -> HashSet<Retained<WinitUIWindow>> {
|
|
||||||
let (queued_gpu_redraws, active_control_flow) = match self.take_state() {
|
|
||||||
AppStateImpl::ProcessingEvents { queued_gpu_redraws, active_control_flow } => {
|
|
||||||
(queued_gpu_redraws, active_control_flow)
|
|
||||||
},
|
|
||||||
s => bug!("unexpected state {:?}", s),
|
|
||||||
};
|
|
||||||
self.set_state(AppStateImpl::ProcessingRedraws { active_control_flow });
|
|
||||||
queued_gpu_redraws
|
|
||||||
}
|
|
||||||
|
|
||||||
fn events_cleared_transition(&mut self) {
|
|
||||||
if !self.has_launched() || self.has_terminated() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let old = match self.take_state() {
|
|
||||||
AppStateImpl::ProcessingRedraws { active_control_flow } => active_control_flow,
|
|
||||||
s => bug!("unexpected state {:?}", s),
|
|
||||||
};
|
|
||||||
|
|
||||||
let new = self.control_flow;
|
|
||||||
match (old, new) {
|
|
||||||
(ControlFlow::Wait, ControlFlow::Wait) => {
|
|
||||||
let start = Instant::now();
|
|
||||||
self.set_state(AppStateImpl::Waiting { start });
|
|
||||||
},
|
|
||||||
(ControlFlow::WaitUntil(old_instant), ControlFlow::WaitUntil(new_instant))
|
|
||||||
if old_instant == new_instant =>
|
|
||||||
{
|
|
||||||
let start = Instant::now();
|
|
||||||
self.set_state(AppStateImpl::Waiting { start });
|
|
||||||
},
|
|
||||||
(_, ControlFlow::Wait) => {
|
|
||||||
let start = Instant::now();
|
|
||||||
self.set_state(AppStateImpl::Waiting { start });
|
|
||||||
self.waker.stop()
|
|
||||||
},
|
|
||||||
(_, ControlFlow::WaitUntil(new_instant)) => {
|
|
||||||
let start = Instant::now();
|
|
||||||
self.set_state(AppStateImpl::Waiting { start });
|
|
||||||
self.waker.start_at(new_instant)
|
|
||||||
},
|
|
||||||
// Unlike on macOS, handle Poll to Poll transition here to call the waker
|
|
||||||
(_, ControlFlow::Poll) => {
|
|
||||||
self.set_state(AppStateImpl::PollFinished);
|
|
||||||
self.waker.start()
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn terminated_transition(&mut self) {
|
|
||||||
match self.replace_state(AppStateImpl::Terminated) {
|
|
||||||
AppStateImpl::ProcessingEvents { .. } => {},
|
|
||||||
s => bug!("terminated while not processing events {:?}", s),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn event_loop_proxy(&self) -> &Arc<EventLoopProxy> {
|
|
||||||
&self.event_loop_proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn set_control_flow(&mut self, control_flow: ControlFlow) {
|
|
||||||
self.control_flow = control_flow;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn control_flow(&self) -> ControlFlow {
|
|
||||||
self.control_flow
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn queue_gl_or_metal_redraw(mtm: MainThreadMarker, window: Retained<WinitUIWindow>) {
|
|
||||||
let mut this = AppState::get_mut(mtm);
|
|
||||||
match this.state_mut() {
|
|
||||||
&mut AppStateImpl::Initial { ref mut queued_gpu_redraws, .. }
|
|
||||||
| &mut AppStateImpl::ProcessingEvents { ref mut queued_gpu_redraws, .. } => {
|
|
||||||
let _ = queued_gpu_redraws.insert(window);
|
|
||||||
},
|
|
||||||
s @ &mut AppStateImpl::ProcessingRedraws { .. }
|
|
||||||
| s @ &mut AppStateImpl::Waiting { .. }
|
|
||||||
| s @ &mut AppStateImpl::PollFinished { .. } => bug!("unexpected state {:?}", s),
|
|
||||||
&mut AppStateImpl::Terminated => {
|
|
||||||
panic!("Attempt to create a `Window` after the app has terminated")
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn launch(mtm: MainThreadMarker, app: &mut dyn ApplicationHandler, run: impl FnOnce()) {
|
|
||||||
get_handler(mtm).set(app, run)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn did_finish_launching(mtm: MainThreadMarker) {
|
|
||||||
let mut this = AppState::get_mut(mtm);
|
|
||||||
|
|
||||||
this.waker.start();
|
|
||||||
|
|
||||||
// have to drop RefMut because the window setup code below can trigger new events
|
|
||||||
drop(this);
|
|
||||||
|
|
||||||
AppState::get_mut(mtm).did_finish_launching_transition();
|
|
||||||
|
|
||||||
get_handler(mtm).handle(|app| app.new_events(&ActiveEventLoop { mtm }, StartCause::Init));
|
|
||||||
get_handler(mtm).handle(|app| app.can_create_surfaces(&ActiveEventLoop { mtm }));
|
|
||||||
handle_nonuser_events(mtm, []);
|
|
||||||
}
|
|
||||||
|
|
||||||
// AppState::did_finish_launching handles the special transition `Init`
|
|
||||||
pub fn handle_wakeup_transition(mtm: MainThreadMarker) {
|
|
||||||
let mut this = AppState::get_mut(mtm);
|
|
||||||
let cause = match this.wakeup_transition() {
|
|
||||||
None => return,
|
|
||||||
Some(cause) => cause,
|
|
||||||
};
|
|
||||||
drop(this);
|
|
||||||
|
|
||||||
get_handler(mtm).handle(|app| app.new_events(&ActiveEventLoop { mtm }, cause));
|
|
||||||
handle_nonuser_events(mtm, []);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn handle_nonuser_event(mtm: MainThreadMarker, event: EventWrapper) {
|
|
||||||
handle_nonuser_events(mtm, std::iter::once(event))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>(
|
|
||||||
mtm: MainThreadMarker,
|
|
||||||
events: I,
|
|
||||||
) {
|
|
||||||
let mut this = AppState::get_mut(mtm);
|
|
||||||
if this.has_terminated() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if !get_handler(mtm).ready() {
|
|
||||||
// Prevent re-entrancy; queue the events up for once we're done handling the event instead.
|
|
||||||
this.queued_events.extend(events);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let processing_redraws = matches!(this.state(), AppStateImpl::ProcessingRedraws { .. });
|
|
||||||
drop(this);
|
|
||||||
|
|
||||||
for event in events {
|
|
||||||
if !processing_redraws && event.is_redraw() {
|
|
||||||
tracing::info!("processing `RedrawRequested` during the main event loop");
|
|
||||||
} else if processing_redraws && !event.is_redraw() {
|
|
||||||
tracing::warn!(
|
|
||||||
"processing non `RedrawRequested` event after the main event loop: {:#?}",
|
|
||||||
event
|
|
||||||
);
|
|
||||||
}
|
|
||||||
handle_wrapped_event(mtm, event)
|
|
||||||
}
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let mut this = AppState::get_mut(mtm);
|
|
||||||
let queued_events = mem::take(&mut this.queued_events);
|
|
||||||
if queued_events.is_empty() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
drop(this);
|
|
||||||
|
|
||||||
for event in queued_events {
|
|
||||||
if !processing_redraws && event.is_redraw() {
|
|
||||||
tracing::info!("processing `RedrawRequested` during the main event loop");
|
|
||||||
} else if processing_redraws && !event.is_redraw() {
|
|
||||||
tracing::warn!(
|
|
||||||
"processing non-`RedrawRequested` event after the main event loop: {:#?}",
|
|
||||||
event
|
|
||||||
);
|
|
||||||
}
|
|
||||||
handle_wrapped_event(mtm, event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn handle_user_events(mtm: MainThreadMarker) {
|
|
||||||
let this = AppState::get_mut(mtm);
|
|
||||||
if matches!(this.state(), AppStateImpl::ProcessingRedraws { .. }) {
|
|
||||||
bug!("user events attempted to be sent out while `ProcessingRedraws`");
|
|
||||||
}
|
|
||||||
let event_loop_proxy = this.event_loop_proxy().clone();
|
|
||||||
drop(this);
|
|
||||||
|
|
||||||
if event_loop_proxy.wake_up.swap(false, Ordering::Relaxed) {
|
|
||||||
get_handler(mtm).handle(|app| app.proxy_wake_up(&ActiveEventLoop { mtm }));
|
|
||||||
}
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let mut this = AppState::get_mut(mtm);
|
|
||||||
let queued_events = mem::take(&mut this.queued_events);
|
|
||||||
if queued_events.is_empty() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
drop(this);
|
|
||||||
|
|
||||||
for event in queued_events {
|
|
||||||
handle_wrapped_event(mtm, event);
|
|
||||||
}
|
|
||||||
|
|
||||||
if event_loop_proxy.wake_up.swap(false, Ordering::Relaxed) {
|
|
||||||
get_handler(mtm).handle(|app| app.proxy_wake_up(&ActiveEventLoop { mtm }));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn send_occluded_event_for_all_windows(application: &UIApplication, occluded: bool) {
|
|
||||||
let mtm = MainThreadMarker::from(application);
|
|
||||||
|
|
||||||
let mut events = Vec::new();
|
|
||||||
#[allow(deprecated)]
|
|
||||||
for window in application.windows().iter() {
|
|
||||||
if window.is_kind_of::<WinitUIWindow>() {
|
|
||||||
// SAFETY: We just checked that the window is a `winit` window
|
|
||||||
let window = unsafe {
|
|
||||||
let ptr: *const UIWindow = window;
|
|
||||||
let ptr: *const WinitUIWindow = ptr.cast();
|
|
||||||
&*ptr
|
|
||||||
};
|
|
||||||
events.push(EventWrapper::Window {
|
|
||||||
window_id: window.id(),
|
|
||||||
event: WindowEvent::Occluded(occluded),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
handle_nonuser_events(mtm, events);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn handle_main_events_cleared(mtm: MainThreadMarker) {
|
|
||||||
let mut this = AppState::get_mut(mtm);
|
|
||||||
if !this.has_launched() || this.has_terminated() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
match this.state_mut() {
|
|
||||||
AppStateImpl::ProcessingEvents { .. } => {},
|
|
||||||
_ => bug!("`ProcessingRedraws` happened unexpectedly"),
|
|
||||||
};
|
|
||||||
drop(this);
|
|
||||||
|
|
||||||
handle_user_events(mtm);
|
|
||||||
|
|
||||||
let mut this = AppState::get_mut(mtm);
|
|
||||||
let redraw_events: Vec<EventWrapper> = this
|
|
||||||
.main_events_cleared_transition()
|
|
||||||
.into_iter()
|
|
||||||
.map(|window| EventWrapper::Window {
|
|
||||||
window_id: window.id(),
|
|
||||||
event: WindowEvent::RedrawRequested,
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
drop(this);
|
|
||||||
|
|
||||||
handle_nonuser_events(mtm, redraw_events);
|
|
||||||
get_handler(mtm).handle(|app| app.about_to_wait(&ActiveEventLoop { mtm }));
|
|
||||||
handle_nonuser_events(mtm, []);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn handle_events_cleared(mtm: MainThreadMarker) {
|
|
||||||
AppState::get_mut(mtm).events_cleared_transition();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn handle_resumed(mtm: MainThreadMarker) {
|
|
||||||
get_handler(mtm).handle(|app| app.resumed(&ActiveEventLoop { mtm }));
|
|
||||||
handle_nonuser_events(mtm, []);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn handle_suspended(mtm: MainThreadMarker) {
|
|
||||||
get_handler(mtm).handle(|app| app.suspended(&ActiveEventLoop { mtm }));
|
|
||||||
handle_nonuser_events(mtm, []);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn handle_memory_warning(mtm: MainThreadMarker) {
|
|
||||||
get_handler(mtm).handle(|app| app.memory_warning(&ActiveEventLoop { mtm }));
|
|
||||||
handle_nonuser_events(mtm, []);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn terminated(application: &UIApplication) {
|
|
||||||
let mtm = MainThreadMarker::from(application);
|
|
||||||
|
|
||||||
let mut events = Vec::new();
|
|
||||||
#[allow(deprecated)]
|
|
||||||
for window in application.windows().iter() {
|
|
||||||
if window.is_kind_of::<WinitUIWindow>() {
|
|
||||||
// SAFETY: We just checked that the window is a `winit` window
|
|
||||||
let window = unsafe {
|
|
||||||
let ptr: *const UIWindow = window;
|
|
||||||
let ptr: *const WinitUIWindow = ptr.cast();
|
|
||||||
&*ptr
|
|
||||||
};
|
|
||||||
events.push(EventWrapper::Window {
|
|
||||||
window_id: window.id(),
|
|
||||||
event: WindowEvent::Destroyed,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
handle_nonuser_events(mtm, events);
|
|
||||||
|
|
||||||
let mut this = AppState::get_mut(mtm);
|
|
||||||
this.terminated_transition();
|
|
||||||
drop(this);
|
|
||||||
|
|
||||||
get_handler(mtm).handle(|app| app.exiting(&ActiveEventLoop { mtm }));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn handle_wrapped_event(mtm: MainThreadMarker, event: EventWrapper) {
|
|
||||||
match event {
|
|
||||||
EventWrapper::Window { window_id, event } => get_handler(mtm)
|
|
||||||
.handle(|app| app.window_event(&ActiveEventLoop { mtm }, window_id, event)),
|
|
||||||
EventWrapper::ScaleFactorChanged(event) => handle_hidpi_proxy(mtm, event),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn handle_hidpi_proxy(mtm: MainThreadMarker, event: ScaleFactorChanged) {
|
|
||||||
let ScaleFactorChanged { suggested_size, scale_factor, window } = event;
|
|
||||||
let new_surface_size = Arc::new(Mutex::new(suggested_size));
|
|
||||||
get_handler(mtm).handle(|app| {
|
|
||||||
app.window_event(&ActiveEventLoop { mtm }, window.id(), WindowEvent::ScaleFactorChanged {
|
|
||||||
scale_factor,
|
|
||||||
surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_surface_size)),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
let (view, screen_frame) = get_view_and_screen_frame(&window);
|
|
||||||
let physical_size = *new_surface_size.lock().unwrap();
|
|
||||||
drop(new_surface_size);
|
|
||||||
let logical_size = physical_size.to_logical(scale_factor);
|
|
||||||
let size = CGSize::new(logical_size.width, logical_size.height);
|
|
||||||
let new_frame: CGRect = CGRect::new(screen_frame.origin, size);
|
|
||||||
view.setFrame(new_frame);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_view_and_screen_frame(window: &WinitUIWindow) -> (Retained<UIView>, CGRect) {
|
|
||||||
let view_controller = window.rootViewController().unwrap();
|
|
||||||
let view = view_controller.view().unwrap();
|
|
||||||
let bounds = window.bounds();
|
|
||||||
let screen = window.screen();
|
|
||||||
let screen_space = screen.coordinateSpace();
|
|
||||||
let screen_frame = window.convertRect_toCoordinateSpace(bounds, &screen_space);
|
|
||||||
(view, screen_frame)
|
|
||||||
}
|
|
||||||
|
|
||||||
struct EventLoopWaker {
|
|
||||||
timer: CFRunLoopTimerRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for EventLoopWaker {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
unsafe {
|
|
||||||
CFRunLoopTimerInvalidate(self.timer);
|
|
||||||
CFRelease(self.timer as _);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventLoopWaker {
|
|
||||||
fn new(rl: CFRunLoopRef) -> EventLoopWaker {
|
|
||||||
extern "C" fn wakeup_main_loop(_timer: CFRunLoopTimerRef, _info: *mut c_void) {}
|
|
||||||
unsafe {
|
|
||||||
// Create a timer with a 0.1µs interval (1ns does not work) to mimic polling.
|
|
||||||
// It is initially setup with a first fire time really far into the
|
|
||||||
// future, but that gets changed to fire immediately in did_finish_launching
|
|
||||||
let timer = CFRunLoopTimerCreate(
|
|
||||||
ptr::null_mut(),
|
|
||||||
f64::MAX,
|
|
||||||
0.000_000_1,
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
wakeup_main_loop,
|
|
||||||
ptr::null_mut(),
|
|
||||||
);
|
|
||||||
CFRunLoopAddTimer(rl, timer, kCFRunLoopCommonModes);
|
|
||||||
|
|
||||||
EventLoopWaker { timer }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn stop(&mut self) {
|
|
||||||
unsafe { CFRunLoopTimerSetNextFireDate(self.timer, f64::MAX) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn start(&mut self) {
|
|
||||||
unsafe { CFRunLoopTimerSetNextFireDate(self.timer, f64::MIN) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn start_at(&mut self, instant: Instant) {
|
|
||||||
let now = Instant::now();
|
|
||||||
if now >= instant {
|
|
||||||
self.start();
|
|
||||||
} else {
|
|
||||||
unsafe {
|
|
||||||
let current = CFAbsoluteTimeGetCurrent();
|
|
||||||
let duration = instant - now;
|
|
||||||
let fsecs =
|
|
||||||
duration.subsec_nanos() as f64 / 1_000_000_000.0 + duration.as_secs() as f64;
|
|
||||||
CFRunLoopTimerSetNextFireDate(self.timer, current + fsecs)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! os_capabilities {
|
|
||||||
(
|
|
||||||
$(
|
|
||||||
$(#[$attr:meta])*
|
|
||||||
$error_name:ident: $objc_call:literal,
|
|
||||||
$name:ident: $major:literal-$minor:literal
|
|
||||||
),*
|
|
||||||
$(,)*
|
|
||||||
) => {
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct OSCapabilities {
|
|
||||||
$(
|
|
||||||
pub $name: bool,
|
|
||||||
)*
|
|
||||||
|
|
||||||
os_version: NSOperatingSystemVersion,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl OSCapabilities {
|
|
||||||
fn from_os_version(os_version: NSOperatingSystemVersion) -> Self {
|
|
||||||
$(let $name = meets_requirements(os_version, $major, $minor);)*
|
|
||||||
Self { $($name,)* os_version, }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl OSCapabilities {$(
|
|
||||||
$(#[$attr])*
|
|
||||||
pub fn $error_name(&self, extra_msg: &str) {
|
|
||||||
tracing::warn!(
|
|
||||||
concat!("`", $objc_call, "` requires iOS {}.{}+. This device is running iOS {}.{}.{}. {}"),
|
|
||||||
$major, $minor, self.os_version.majorVersion, self.os_version.minorVersion, self.os_version.patchVersion,
|
|
||||||
extra_msg
|
|
||||||
)
|
|
||||||
}
|
|
||||||
)*}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
os_capabilities! {
|
|
||||||
/// <https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets?language=objc>
|
|
||||||
#[allow(unused)] // error message unused
|
|
||||||
safe_area_err_msg: "-[UIView safeAreaInsets]",
|
|
||||||
safe_area: 11-0,
|
|
||||||
/// <https://developer.apple.com/documentation/uikit/uiviewcontroller/2887509-setneedsupdateofhomeindicatoraut?language=objc>
|
|
||||||
home_indicator_hidden_err_msg: "-[UIViewController setNeedsUpdateOfHomeIndicatorAutoHidden]",
|
|
||||||
home_indicator_hidden: 11-0,
|
|
||||||
/// <https://developer.apple.com/documentation/uikit/uiviewcontroller/2887507-setneedsupdateofscreenedgesdefer?language=objc>
|
|
||||||
defer_system_gestures_err_msg: "-[UIViewController setNeedsUpdateOfScreenEdgesDeferringSystem]",
|
|
||||||
defer_system_gestures: 11-0,
|
|
||||||
/// <https://developer.apple.com/documentation/uikit/uiscreen/2806814-maximumframespersecond?language=objc>
|
|
||||||
maximum_frames_per_second_err_msg: "-[UIScreen maximumFramesPerSecond]",
|
|
||||||
maximum_frames_per_second: 10-3,
|
|
||||||
/// <https://developer.apple.com/documentation/uikit/uitouch/1618110-force?language=objc>
|
|
||||||
#[allow(unused)] // error message unused
|
|
||||||
force_touch_err_msg: "-[UITouch force]",
|
|
||||||
force_touch: 9-0,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn meets_requirements(
|
|
||||||
version: NSOperatingSystemVersion,
|
|
||||||
required_major: NSInteger,
|
|
||||||
required_minor: NSInteger,
|
|
||||||
) -> bool {
|
|
||||||
(version.majorVersion, version.minorVersion) >= (required_major, required_minor)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_version() -> NSOperatingSystemVersion {
|
|
||||||
let process_info = NSProcessInfo::processInfo();
|
|
||||||
let atleast_ios_8 = process_info.respondsToSelector(sel!(operatingSystemVersion));
|
|
||||||
// Winit requires atleast iOS 8 because no one has put the time into supporting earlier os
|
|
||||||
// versions. Older iOS versions are increasingly difficult to test. For example, Xcode 11 does
|
|
||||||
// not support debugging on devices with an iOS version of less than 8. Another example, in
|
|
||||||
// order to use an iOS simulator older than iOS 8, you must download an older version of Xcode
|
|
||||||
// (<9), and at least Xcode 7 has been tested to not even run on macOS 10.15 - Xcode 8 might?
|
|
||||||
//
|
|
||||||
// The minimum required iOS version is likely to grow in the future.
|
|
||||||
assert!(atleast_ios_8, "`winit` requires iOS version 8 or greater");
|
|
||||||
process_info.operatingSystemVersion()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn os_capabilities() -> OSCapabilities {
|
|
||||||
// Cache the version lookup for efficiency
|
|
||||||
static OS_CAPABILITIES: OnceLock<OSCapabilities> = OnceLock::new();
|
|
||||||
OS_CAPABILITIES.get_or_init(|| OSCapabilities::from_os_version(get_version())).clone()
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
#![allow(clippy::let_unit_value)]
|
|
||||||
|
|
||||||
mod app_state;
|
|
||||||
mod event_loop;
|
|
||||||
mod monitor;
|
|
||||||
mod view;
|
|
||||||
mod view_controller;
|
|
||||||
mod window;
|
|
||||||
|
|
||||||
use std::fmt;
|
|
||||||
|
|
||||||
pub(crate) use self::event_loop::{
|
|
||||||
ActiveEventLoop, EventLoop, EventLoopProxy, PlatformSpecificEventLoopAttributes,
|
|
||||||
};
|
|
||||||
pub(crate) use self::monitor::{MonitorHandle, VideoModeHandle};
|
|
||||||
pub(crate) use self::window::{PlatformSpecificWindowAttributes, Window};
|
|
||||||
pub(crate) use crate::cursor::{
|
|
||||||
NoCustomCursor as PlatformCustomCursor, NoCustomCursor as PlatformCustomCursorSource,
|
|
||||||
};
|
|
||||||
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
|
||||||
pub(crate) use crate::platform_impl::Fullscreen;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
|
||||||
pub struct KeyEventExtra {}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum OsError {}
|
|
||||||
|
|
||||||
impl fmt::Display for OsError {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
write!(f, "os error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
pub mod xkb;
|
|
||||||
@@ -1,421 +0,0 @@
|
|||||||
#![cfg(free_unix)]
|
|
||||||
|
|
||||||
#[cfg(all(not(x11_platform), not(wayland_platform)))]
|
|
||||||
compile_error!("Please select a feature to build for unix: `x11`, `wayland`");
|
|
||||||
|
|
||||||
use std::env;
|
|
||||||
use std::num::{NonZeroU16, NonZeroU32};
|
|
||||||
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
|
|
||||||
use std::time::Duration;
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
use std::{ffi::CStr, mem::MaybeUninit, os::raw::*, sync::Arc, sync::Mutex};
|
|
||||||
|
|
||||||
use smol_str::SmolStr;
|
|
||||||
|
|
||||||
pub(crate) use self::common::xkb::{physicalkey_to_scancode, scancode_to_physicalkey};
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
use self::x11::{XConnection, XError, XNotSupported};
|
|
||||||
use crate::application::ApplicationHandler;
|
|
||||||
pub(crate) use crate::cursor::OnlyCursorImageSource as PlatformCustomCursorSource;
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
use crate::dpi::Size;
|
|
||||||
use crate::dpi::{PhysicalPosition, PhysicalSize};
|
|
||||||
use crate::error::{EventLoopError, NotSupportedError};
|
|
||||||
use crate::event_loop::ActiveEventLoop;
|
|
||||||
pub(crate) use crate::icon::RgbaIcon as PlatformIcon;
|
|
||||||
use crate::keyboard::Key;
|
|
||||||
use crate::platform::pump_events::PumpStatus;
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
use crate::platform::x11::{WindowType as XWindowType, XlibErrorHook};
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
use crate::utils::Lazy;
|
|
||||||
use crate::window::ActivationToken;
|
|
||||||
|
|
||||||
pub(crate) mod common;
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
pub(crate) mod wayland;
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
pub(crate) mod x11;
|
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
|
||||||
pub(crate) enum Backend {
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
X,
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
Wayland,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
|
|
||||||
pub(crate) struct PlatformSpecificEventLoopAttributes {
|
|
||||||
pub(crate) forced_backend: Option<Backend>,
|
|
||||||
pub(crate) any_thread: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct ApplicationName {
|
|
||||||
pub general: String,
|
|
||||||
pub instance: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ApplicationName {
|
|
||||||
pub fn new(general: String, instance: String) -> Self {
|
|
||||||
Self { general, instance }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct PlatformSpecificWindowAttributes {
|
|
||||||
pub name: Option<ApplicationName>,
|
|
||||||
pub activation_token: Option<ActivationToken>,
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
pub x11: X11WindowAttributes,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
pub struct X11WindowAttributes {
|
|
||||||
pub visual_id: Option<x11rb::protocol::xproto::Visualid>,
|
|
||||||
pub screen_id: Option<i32>,
|
|
||||||
pub base_size: Option<Size>,
|
|
||||||
pub override_redirect: bool,
|
|
||||||
pub x11_window_types: Vec<XWindowType>,
|
|
||||||
|
|
||||||
/// The parent window to embed this window into.
|
|
||||||
pub embed_window: Option<x11rb::protocol::xproto::Window>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(not(x11_platform), allow(clippy::derivable_impls))]
|
|
||||||
impl Default for PlatformSpecificWindowAttributes {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
name: None,
|
|
||||||
activation_token: None,
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
x11: X11WindowAttributes {
|
|
||||||
visual_id: None,
|
|
||||||
screen_id: None,
|
|
||||||
base_size: None,
|
|
||||||
override_redirect: false,
|
|
||||||
x11_window_types: vec![XWindowType::Normal],
|
|
||||||
embed_window: None,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
pub(crate) static X11_BACKEND: Lazy<Mutex<Result<Arc<XConnection>, XNotSupported>>> =
|
|
||||||
Lazy::new(|| Mutex::new(XConnection::new(Some(x_error_callback)).map(Arc::new)));
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
||||||
pub enum MonitorHandle {
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
X(x11::MonitorHandle),
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
Wayland(wayland::MonitorHandle),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `x11_or_wayland!(match expr; Enum(foo) => foo.something())`
|
|
||||||
/// expands to the equivalent of
|
|
||||||
/// ```ignore
|
|
||||||
/// match self {
|
|
||||||
/// Enum::X(foo) => foo.something(),
|
|
||||||
/// Enum::Wayland(foo) => foo.something(),
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
/// The result can be converted to another enum by adding `; as AnotherEnum`
|
|
||||||
macro_rules! x11_or_wayland {
|
|
||||||
(match $what:expr; $enum:ident ( $($c1:tt)* ) => $x:expr; as $enum2:ident ) => {
|
|
||||||
match $what {
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
$enum::X($($c1)*) => $enum2::X($x),
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
$enum::Wayland($($c1)*) => $enum2::Wayland($x),
|
|
||||||
}
|
|
||||||
};
|
|
||||||
(match $what:expr; $enum:ident ( $($c1:tt)* ) => $x:expr) => {
|
|
||||||
match $what {
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
$enum::X($($c1)*) => $x,
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
$enum::Wayland($($c1)*) => $x,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorHandle {
|
|
||||||
#[inline]
|
|
||||||
pub fn name(&self) -> Option<String> {
|
|
||||||
x11_or_wayland!(match self; MonitorHandle(m) => m.name())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn native_identifier(&self) -> u32 {
|
|
||||||
x11_or_wayland!(match self; MonitorHandle(m) => m.native_identifier())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn position(&self) -> Option<PhysicalPosition<i32>> {
|
|
||||||
x11_or_wayland!(match self; MonitorHandle(m) => m.position())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn scale_factor(&self) -> f64 {
|
|
||||||
x11_or_wayland!(match self; MonitorHandle(m) => m.scale_factor() as _)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn current_video_mode(&self) -> Option<VideoModeHandle> {
|
|
||||||
x11_or_wayland!(match self; MonitorHandle(m) => m.current_video_mode())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn video_modes(&self) -> Box<dyn Iterator<Item = VideoModeHandle>> {
|
|
||||||
x11_or_wayland!(match self; MonitorHandle(m) => Box::new(m.video_modes()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
|
||||||
pub enum VideoModeHandle {
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
X(x11::VideoModeHandle),
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
Wayland(wayland::VideoModeHandle),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl VideoModeHandle {
|
|
||||||
#[inline]
|
|
||||||
pub fn size(&self) -> PhysicalSize<u32> {
|
|
||||||
x11_or_wayland!(match self; VideoModeHandle(m) => m.size())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn bit_depth(&self) -> Option<NonZeroU16> {
|
|
||||||
x11_or_wayland!(match self; VideoModeHandle(m) => m.bit_depth())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn refresh_rate_millihertz(&self) -> Option<NonZeroU32> {
|
|
||||||
x11_or_wayland!(match self; VideoModeHandle(m) => m.refresh_rate_millihertz())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn monitor(&self) -> MonitorHandle {
|
|
||||||
x11_or_wayland!(match self; VideoModeHandle(m) => m.monitor(); as MonitorHandle)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
|
|
||||||
pub struct KeyEventExtra {
|
|
||||||
pub text_with_all_modifiers: Option<SmolStr>,
|
|
||||||
pub key_without_modifiers: Key,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
|
||||||
pub(crate) enum PlatformCustomCursor {
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
Wayland(wayland::CustomCursor),
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
X(x11::CustomCursor),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Hooks for X11 errors.
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
pub(crate) static XLIB_ERROR_HOOKS: Mutex<Vec<XlibErrorHook>> = Mutex::new(Vec::new());
|
|
||||||
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
unsafe extern "C" fn x_error_callback(
|
|
||||||
display: *mut x11::ffi::Display,
|
|
||||||
event: *mut x11::ffi::XErrorEvent,
|
|
||||||
) -> c_int {
|
|
||||||
let xconn_lock = X11_BACKEND.lock().unwrap_or_else(|e| e.into_inner());
|
|
||||||
if let Ok(ref xconn) = *xconn_lock {
|
|
||||||
// Call all the hooks.
|
|
||||||
let mut error_handled = false;
|
|
||||||
for hook in XLIB_ERROR_HOOKS.lock().unwrap().iter() {
|
|
||||||
error_handled |= hook(display as *mut _, event as *mut _);
|
|
||||||
}
|
|
||||||
|
|
||||||
// `assume_init` is safe here because the array consists of `MaybeUninit` values,
|
|
||||||
// which do not require initialization.
|
|
||||||
let mut buf: [MaybeUninit<c_char>; 1024] = unsafe { MaybeUninit::uninit().assume_init() };
|
|
||||||
unsafe {
|
|
||||||
(xconn.xlib.XGetErrorText)(
|
|
||||||
display,
|
|
||||||
(*event).error_code as c_int,
|
|
||||||
buf.as_mut_ptr() as *mut c_char,
|
|
||||||
buf.len() as c_int,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
let description =
|
|
||||||
unsafe { CStr::from_ptr(buf.as_ptr() as *const c_char) }.to_string_lossy();
|
|
||||||
|
|
||||||
let error = unsafe {
|
|
||||||
XError {
|
|
||||||
description: description.into_owned(),
|
|
||||||
error_code: (*event).error_code,
|
|
||||||
request_code: (*event).request_code,
|
|
||||||
minor_code: (*event).minor_code,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Don't log error.
|
|
||||||
if !error_handled {
|
|
||||||
tracing::error!("X11 error: {:#?}", error);
|
|
||||||
// XXX only update the error, if it wasn't handled by any of the hooks.
|
|
||||||
*xconn.latest_error.lock().unwrap() = Some(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Fun fact: this return value is completely ignored.
|
|
||||||
0
|
|
||||||
}
|
|
||||||
|
|
||||||
pub enum EventLoop {
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
Wayland(Box<wayland::EventLoop>),
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
X(x11::EventLoop),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventLoop {
|
|
||||||
pub(crate) fn new(
|
|
||||||
attributes: &PlatformSpecificEventLoopAttributes,
|
|
||||||
) -> Result<Self, EventLoopError> {
|
|
||||||
if !attributes.any_thread && !is_main_thread() {
|
|
||||||
panic!(
|
|
||||||
"Initializing the event loop outside of the main thread is a significant \
|
|
||||||
cross-platform compatibility hazard. If you absolutely need to create an \
|
|
||||||
EventLoop on a different thread, you can use the \
|
|
||||||
`EventLoopBuilderExtX11::with_any_thread` or \
|
|
||||||
`EventLoopBuilderExtWayland::with_any_thread` functions."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// NOTE: Wayland first because of X11 could be present under Wayland as well. Empty
|
|
||||||
// variables are also treated as not set.
|
|
||||||
let backend = match (
|
|
||||||
attributes.forced_backend,
|
|
||||||
env::var("WAYLAND_DISPLAY")
|
|
||||||
.ok()
|
|
||||||
.filter(|var| !var.is_empty())
|
|
||||||
.or_else(|| env::var("WAYLAND_SOCKET").ok())
|
|
||||||
.filter(|var| !var.is_empty())
|
|
||||||
.is_some(),
|
|
||||||
env::var("DISPLAY").map(|var| !var.is_empty()).unwrap_or(false),
|
|
||||||
) {
|
|
||||||
// User is forcing a backend.
|
|
||||||
(Some(backend), ..) => backend,
|
|
||||||
// Wayland is present.
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
(None, true, _) => Backend::Wayland,
|
|
||||||
// X11 is present.
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
(None, _, true) => Backend::X,
|
|
||||||
// No backend is present.
|
|
||||||
(_, wayland_display, x11_display) => {
|
|
||||||
let msg = if wayland_display && !cfg!(wayland_platform) {
|
|
||||||
"DISPLAY is not set; note: enable the `winit/wayland` feature to support \
|
|
||||||
Wayland"
|
|
||||||
} else if x11_display && !cfg!(x11_platform) {
|
|
||||||
"neither WAYLAND_DISPLAY nor WAYLAND_SOCKET is set; note: enable the \
|
|
||||||
`winit/x11` feature to support X11"
|
|
||||||
} else {
|
|
||||||
"neither WAYLAND_DISPLAY nor WAYLAND_SOCKET nor DISPLAY is set."
|
|
||||||
};
|
|
||||||
return Err(NotSupportedError::new(msg).into());
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
// Create the display based on the backend.
|
|
||||||
match backend {
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
Backend::Wayland => EventLoop::new_wayland_any_thread().map_err(Into::into),
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
Backend::X => EventLoop::new_x11_any_thread().map_err(Into::into),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
fn new_wayland_any_thread() -> Result<EventLoop, EventLoopError> {
|
|
||||||
wayland::EventLoop::new().map(|evlp| EventLoop::Wayland(Box::new(evlp)))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
fn new_x11_any_thread() -> Result<EventLoop, EventLoopError> {
|
|
||||||
let xconn = match X11_BACKEND.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
|
|
||||||
Ok(xconn) => xconn.clone(),
|
|
||||||
Err(err) => return Err(os_error!(err.clone()).into()),
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(EventLoop::X(x11::EventLoop::new(xconn)))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn is_wayland(&self) -> bool {
|
|
||||||
match *self {
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
EventLoop::Wayland(_) => true,
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn run_app<A: ApplicationHandler>(self, app: A) -> Result<(), EventLoopError> {
|
|
||||||
x11_or_wayland!(match self; EventLoop(evlp) => evlp.run_app(app))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn run_app_on_demand<A: ApplicationHandler>(
|
|
||||||
&mut self,
|
|
||||||
app: A,
|
|
||||||
) -> Result<(), EventLoopError> {
|
|
||||||
x11_or_wayland!(match self; EventLoop(evlp) => evlp.run_app_on_demand(app))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn pump_app_events<A: ApplicationHandler>(
|
|
||||||
&mut self,
|
|
||||||
timeout: Option<Duration>,
|
|
||||||
app: A,
|
|
||||||
) -> PumpStatus {
|
|
||||||
x11_or_wayland!(match self; EventLoop(evlp) => evlp.pump_app_events(timeout, app))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn window_target(&self) -> &dyn ActiveEventLoop {
|
|
||||||
x11_or_wayland!(match self; EventLoop(evlp) => evlp.window_target())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AsFd for EventLoop {
|
|
||||||
fn as_fd(&self) -> BorrowedFd<'_> {
|
|
||||||
x11_or_wayland!(match self; EventLoop(evlp) => evlp.as_fd())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AsRawFd for EventLoop {
|
|
||||||
fn as_raw_fd(&self) -> RawFd {
|
|
||||||
x11_or_wayland!(match self; EventLoop(evlp) => evlp.as_raw_fd())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the minimum `Option<Duration>`, taking into account that `None`
|
|
||||||
/// equates to an infinite timeout, not a zero timeout (so can't just use
|
|
||||||
/// `Option::min`)
|
|
||||||
fn min_timeout(a: Option<Duration>, b: Option<Duration>) -> Option<Duration> {
|
|
||||||
a.map_or(b, |a_timeout| b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout))))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
fn is_main_thread() -> bool {
|
|
||||||
rustix::thread::gettid() == rustix::process::getpid()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
fn is_main_thread() -> bool {
|
|
||||||
use libc::pthread_main_np;
|
|
||||||
|
|
||||||
unsafe { pthread_main_np() == 1 }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "netbsd")]
|
|
||||||
fn is_main_thread() -> bool {
|
|
||||||
std::thread::current().name() == Some("main")
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
//! Winit's Wayland backend.
|
|
||||||
|
|
||||||
pub use event_loop::{ActiveEventLoop, EventLoop};
|
|
||||||
pub use output::{MonitorHandle, VideoModeHandle};
|
|
||||||
use sctk::reexports::client::protocol::wl_surface::WlSurface;
|
|
||||||
use sctk::reexports::client::Proxy;
|
|
||||||
pub use window::Window;
|
|
||||||
|
|
||||||
pub(super) use crate::cursor::OnlyCursorImage as CustomCursor;
|
|
||||||
use crate::dpi::{LogicalSize, PhysicalSize};
|
|
||||||
use crate::window::WindowId;
|
|
||||||
|
|
||||||
mod event_loop;
|
|
||||||
mod output;
|
|
||||||
mod seat;
|
|
||||||
mod state;
|
|
||||||
mod types;
|
|
||||||
mod window;
|
|
||||||
|
|
||||||
/// Get the WindowId out of the surface.
|
|
||||||
#[inline]
|
|
||||||
fn make_wid(surface: &WlSurface) -> WindowId {
|
|
||||||
WindowId::from_raw(surface.id().as_ptr() as usize)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The default routine does floor, but we need round on Wayland.
|
|
||||||
fn logical_to_physical_rounded(size: LogicalSize<u32>, scale_factor: f64) -> PhysicalSize<u32> {
|
|
||||||
let width = size.width as f64 * scale_factor;
|
|
||||||
let height = size.height as f64 * scale_factor;
|
|
||||||
(width.round(), height.round()).into()
|
|
||||||
}
|
|
||||||
@@ -1,141 +0,0 @@
|
|||||||
use std::num::{NonZeroU16, NonZeroU32};
|
|
||||||
|
|
||||||
use sctk::output::{Mode, OutputData};
|
|
||||||
use sctk::reexports::client::protocol::wl_output::WlOutput;
|
|
||||||
use sctk::reexports::client::Proxy;
|
|
||||||
|
|
||||||
use crate::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize};
|
|
||||||
use crate::platform_impl::platform::VideoModeHandle as PlatformVideoModeHandle;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct MonitorHandle {
|
|
||||||
pub(crate) proxy: WlOutput,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorHandle {
|
|
||||||
#[inline]
|
|
||||||
pub(crate) fn new(proxy: WlOutput) -> Self {
|
|
||||||
Self { proxy }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn name(&self) -> Option<String> {
|
|
||||||
let output_data = self.proxy.data::<OutputData>().unwrap();
|
|
||||||
output_data.with_output_info(|info| info.name.clone())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn native_identifier(&self) -> u32 {
|
|
||||||
let output_data = self.proxy.data::<OutputData>().unwrap();
|
|
||||||
output_data.with_output_info(|info| info.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn position(&self) -> Option<PhysicalPosition<i32>> {
|
|
||||||
let output_data = self.proxy.data::<OutputData>().unwrap();
|
|
||||||
Some(output_data.with_output_info(|info| {
|
|
||||||
info.logical_position.map_or_else(
|
|
||||||
|| {
|
|
||||||
LogicalPosition::<i32>::from(info.location)
|
|
||||||
.to_physical(info.scale_factor as f64)
|
|
||||||
},
|
|
||||||
|logical_position| {
|
|
||||||
LogicalPosition::<i32>::from(logical_position)
|
|
||||||
.to_physical(info.scale_factor as f64)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn scale_factor(&self) -> i32 {
|
|
||||||
let output_data = self.proxy.data::<OutputData>().unwrap();
|
|
||||||
output_data.scale_factor()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn current_video_mode(&self) -> Option<PlatformVideoModeHandle> {
|
|
||||||
let output_data = self.proxy.data::<OutputData>().unwrap();
|
|
||||||
output_data.with_output_info(|info| {
|
|
||||||
let mode = info.modes.iter().find(|mode| mode.current).cloned();
|
|
||||||
|
|
||||||
mode.map(|mode| {
|
|
||||||
PlatformVideoModeHandle::Wayland(VideoModeHandle::new(self.clone(), mode))
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn video_modes(&self) -> impl Iterator<Item = PlatformVideoModeHandle> {
|
|
||||||
let output_data = self.proxy.data::<OutputData>().unwrap();
|
|
||||||
let modes = output_data.with_output_info(|info| info.modes.clone());
|
|
||||||
|
|
||||||
let monitor = self.clone();
|
|
||||||
|
|
||||||
modes.into_iter().map(move |mode| {
|
|
||||||
PlatformVideoModeHandle::Wayland(VideoModeHandle::new(monitor.clone(), mode))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PartialEq for MonitorHandle {
|
|
||||||
fn eq(&self, other: &Self) -> bool {
|
|
||||||
self.native_identifier() == other.native_identifier()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Eq for MonitorHandle {}
|
|
||||||
|
|
||||||
impl PartialOrd for MonitorHandle {
|
|
||||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
|
||||||
Some(self.cmp(other))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Ord for MonitorHandle {
|
|
||||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
|
||||||
self.native_identifier().cmp(&other.native_identifier())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::hash::Hash for MonitorHandle {
|
|
||||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
|
||||||
self.native_identifier().hash(state);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
|
||||||
pub struct VideoModeHandle {
|
|
||||||
pub(crate) size: PhysicalSize<u32>,
|
|
||||||
pub(crate) refresh_rate_millihertz: Option<NonZeroU32>,
|
|
||||||
pub(crate) monitor: MonitorHandle,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl VideoModeHandle {
|
|
||||||
fn new(monitor: MonitorHandle, mode: Mode) -> Self {
|
|
||||||
VideoModeHandle {
|
|
||||||
size: (mode.dimensions.0 as u32, mode.dimensions.1 as u32).into(),
|
|
||||||
refresh_rate_millihertz: NonZeroU32::new(mode.refresh_rate as u32),
|
|
||||||
monitor: monitor.clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn size(&self) -> PhysicalSize<u32> {
|
|
||||||
self.size
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn bit_depth(&self) -> Option<NonZeroU16> {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn refresh_rate_millihertz(&self) -> Option<NonZeroU32> {
|
|
||||||
self.refresh_rate_millihertz
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn monitor(&self) -> MonitorHandle {
|
|
||||||
self.monitor.clone()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,195 +0,0 @@
|
|||||||
use std::ops::Deref;
|
|
||||||
|
|
||||||
use sctk::globals::GlobalData;
|
|
||||||
use sctk::reexports::client::globals::{BindError, GlobalList};
|
|
||||||
use sctk::reexports::client::protocol::wl_surface::WlSurface;
|
|
||||||
use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle};
|
|
||||||
use sctk::reexports::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 crate::event::{Ime, WindowEvent};
|
|
||||||
use crate::platform_impl::wayland;
|
|
||||||
use crate::platform_impl::wayland::state::WinitState;
|
|
||||||
use crate::window::ImePurpose;
|
|
||||||
|
|
||||||
pub struct TextInputState {
|
|
||||||
text_input_manager: ZwpTextInputManagerV3,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TextInputState {
|
|
||||||
pub fn new(
|
|
||||||
globals: &GlobalList,
|
|
||||||
queue_handle: &QueueHandle<WinitState>,
|
|
||||||
) -> Result<Self, BindError> {
|
|
||||||
let text_input_manager = globals.bind(queue_handle, 1..=1, GlobalData)?;
|
|
||||||
Ok(Self { text_input_manager })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Deref for TextInputState {
|
|
||||||
type Target = ZwpTextInputManagerV3;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
&self.text_input_manager
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Dispatch<ZwpTextInputManagerV3, GlobalData, WinitState> for TextInputState {
|
|
||||||
fn event(
|
|
||||||
_state: &mut WinitState,
|
|
||||||
_proxy: &ZwpTextInputManagerV3,
|
|
||||||
_event: <ZwpTextInputManagerV3 as Proxy>::Event,
|
|
||||||
_data: &GlobalData,
|
|
||||||
_conn: &Connection,
|
|
||||||
_qhandle: &QueueHandle<WinitState>,
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Dispatch<ZwpTextInputV3, TextInputData, WinitState> for TextInputState {
|
|
||||||
fn event(
|
|
||||||
state: &mut WinitState,
|
|
||||||
text_input: &ZwpTextInputV3,
|
|
||||||
event: <ZwpTextInputV3 as Proxy>::Event,
|
|
||||||
data: &TextInputData,
|
|
||||||
_conn: &Connection,
|
|
||||||
_qhandle: &QueueHandle<WinitState>,
|
|
||||||
) {
|
|
||||||
let windows = state.windows.get_mut();
|
|
||||||
let mut text_input_data = data.inner.lock().unwrap();
|
|
||||||
match event {
|
|
||||||
TextInputEvent::Enter { surface } => {
|
|
||||||
let window_id = wayland::make_wid(&surface);
|
|
||||||
text_input_data.surface = Some(surface);
|
|
||||||
|
|
||||||
let mut window = match windows.get(&window_id) {
|
|
||||||
Some(window) => window.lock().unwrap(),
|
|
||||||
None => return,
|
|
||||||
};
|
|
||||||
|
|
||||||
if window.ime_allowed() {
|
|
||||||
text_input.enable();
|
|
||||||
text_input.set_content_type_by_purpose(window.ime_purpose());
|
|
||||||
text_input.commit();
|
|
||||||
state.events_sink.push_window_event(WindowEvent::Ime(Ime::Enabled), window_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
window.text_input_entered(text_input);
|
|
||||||
},
|
|
||||||
TextInputEvent::Leave { surface } => {
|
|
||||||
text_input_data.surface = None;
|
|
||||||
|
|
||||||
// Always issue a disable.
|
|
||||||
text_input.disable();
|
|
||||||
text_input.commit();
|
|
||||||
|
|
||||||
let window_id = wayland::make_wid(&surface);
|
|
||||||
|
|
||||||
// XXX this check is essential, because `leave` could have a
|
|
||||||
// reference to nil surface...
|
|
||||||
let mut window = match windows.get(&window_id) {
|
|
||||||
Some(window) => window.lock().unwrap(),
|
|
||||||
None => return,
|
|
||||||
};
|
|
||||||
|
|
||||||
window.text_input_left(text_input);
|
|
||||||
|
|
||||||
state.events_sink.push_window_event(WindowEvent::Ime(Ime::Disabled), window_id);
|
|
||||||
},
|
|
||||||
TextInputEvent::PreeditString { text, cursor_begin, cursor_end } => {
|
|
||||||
let text = text.unwrap_or_default();
|
|
||||||
let cursor_begin = usize::try_from(cursor_begin)
|
|
||||||
.ok()
|
|
||||||
.and_then(|idx| text.is_char_boundary(idx).then_some(idx));
|
|
||||||
let cursor_end = usize::try_from(cursor_end)
|
|
||||||
.ok()
|
|
||||||
.and_then(|idx| text.is_char_boundary(idx).then_some(idx));
|
|
||||||
|
|
||||||
text_input_data.pending_preedit = Some(Preedit { text, cursor_begin, cursor_end })
|
|
||||||
},
|
|
||||||
TextInputEvent::CommitString { text } => {
|
|
||||||
text_input_data.pending_preedit = None;
|
|
||||||
text_input_data.pending_commit = text;
|
|
||||||
},
|
|
||||||
TextInputEvent::Done { .. } => {
|
|
||||||
let window_id = match text_input_data.surface.as_ref() {
|
|
||||||
Some(surface) => wayland::make_wid(surface),
|
|
||||||
None => return,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Clear preedit at the start of `Done`.
|
|
||||||
state.events_sink.push_window_event(
|
|
||||||
WindowEvent::Ime(Ime::Preedit(String::new(), None)),
|
|
||||||
window_id,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Send `Commit`.
|
|
||||||
if let Some(text) = text_input_data.pending_commit.take() {
|
|
||||||
state
|
|
||||||
.events_sink
|
|
||||||
.push_window_event(WindowEvent::Ime(Ime::Commit(text)), window_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send preedit.
|
|
||||||
if let Some(preedit) = text_input_data.pending_preedit.take() {
|
|
||||||
let cursor_range =
|
|
||||||
preedit.cursor_begin.map(|b| (b, preedit.cursor_end.unwrap_or(b)));
|
|
||||||
|
|
||||||
state.events_sink.push_window_event(
|
|
||||||
WindowEvent::Ime(Ime::Preedit(preedit.text, cursor_range)),
|
|
||||||
window_id,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
TextInputEvent::DeleteSurroundingText { .. } => {
|
|
||||||
// Not handled.
|
|
||||||
},
|
|
||||||
_ => {},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait ZwpTextInputV3Ext {
|
|
||||||
fn set_content_type_by_purpose(&self, purpose: ImePurpose);
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ZwpTextInputV3Ext for ZwpTextInputV3 {
|
|
||||||
fn set_content_type_by_purpose(&self, purpose: ImePurpose) {
|
|
||||||
let (hint, purpose) = match purpose {
|
|
||||||
ImePurpose::Normal => (ContentHint::None, ContentPurpose::Normal),
|
|
||||||
ImePurpose::Password => (ContentHint::SensitiveData, ContentPurpose::Password),
|
|
||||||
ImePurpose::Terminal => (ContentHint::None, ContentPurpose::Terminal),
|
|
||||||
};
|
|
||||||
self.set_content_type(hint, purpose);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The Data associated with the text input.
|
|
||||||
#[derive(Default)]
|
|
||||||
pub struct TextInputData {
|
|
||||||
inner: std::sync::Mutex<TextInputDataInner>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub struct TextInputDataInner {
|
|
||||||
/// The `WlSurface` we're performing input to.
|
|
||||||
surface: Option<WlSurface>,
|
|
||||||
|
|
||||||
/// The commit to submit on `done`.
|
|
||||||
pending_commit: Option<String>,
|
|
||||||
|
|
||||||
/// The preedit to submit on `done`.
|
|
||||||
pending_preedit: Option<Preedit>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The state of the preedit.
|
|
||||||
struct Preedit {
|
|
||||||
text: String,
|
|
||||||
cursor_begin: Option<usize>,
|
|
||||||
cursor_end: Option<usize>,
|
|
||||||
}
|
|
||||||
|
|
||||||
delegate_dispatch!(WinitState: [ZwpTextInputManagerV3: GlobalData] => TextInputState);
|
|
||||||
delegate_dispatch!(WinitState: [ZwpTextInputV3: TextInputData] => TextInputState);
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
use cursor_icon::CursorIcon;
|
|
||||||
use sctk::reexports::client::protocol::wl_shm::Format;
|
|
||||||
use sctk::shm::slot::{Buffer, SlotPool};
|
|
||||||
|
|
||||||
use crate::cursor::CursorImage;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum SelectedCursor {
|
|
||||||
Named(CursorIcon),
|
|
||||||
Custom(CustomCursor),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for SelectedCursor {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::Named(Default::default())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct CustomCursor {
|
|
||||||
pub buffer: Buffer,
|
|
||||||
pub w: i32,
|
|
||||||
pub h: i32,
|
|
||||||
pub hotspot_x: i32,
|
|
||||||
pub hotspot_y: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CustomCursor {
|
|
||||||
pub(crate) fn new(pool: &mut SlotPool, image: &CursorImage) -> Self {
|
|
||||||
let (buffer, canvas) = pool
|
|
||||||
.create_buffer(
|
|
||||||
image.width as i32,
|
|
||||||
image.height as i32,
|
|
||||||
4 * (image.width as i32),
|
|
||||||
Format::Argb8888,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
for (canvas_chunk, rgba) in canvas.chunks_exact_mut(4).zip(image.rgba.chunks_exact(4)) {
|
|
||||||
// Alpha in buffer is premultiplied.
|
|
||||||
let alpha = rgba[3] as f32 / 255.;
|
|
||||||
let r = (rgba[0] as f32 * alpha) as u32;
|
|
||||||
let g = (rgba[1] as f32 * alpha) as u32;
|
|
||||||
let b = (rgba[2] as f32 * alpha) as u32;
|
|
||||||
let color = ((rgba[3] as u32) << 24) + (r << 16) + (g << 8) + b;
|
|
||||||
let array: &mut [u8; 4] = canvas_chunk.try_into().unwrap();
|
|
||||||
*array = color.to_le_bytes();
|
|
||||||
}
|
|
||||||
|
|
||||||
CustomCursor {
|
|
||||||
buffer,
|
|
||||||
w: image.width as i32,
|
|
||||||
h: image.height as i32,
|
|
||||||
hotspot_x: image.hotspot_x as i32,
|
|
||||||
hotspot_y: image.hotspot_y as i32,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
#![allow(clippy::assertions_on_constants)]
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::icon::{Pixel, RgbaIcon, PIXEL_SIZE};
|
|
||||||
|
|
||||||
impl Pixel {
|
|
||||||
pub fn to_packed_argb(&self) -> Cardinal {
|
|
||||||
let mut cardinal = 0;
|
|
||||||
assert!(CARDINAL_SIZE >= PIXEL_SIZE);
|
|
||||||
let as_bytes = &mut cardinal as *mut _ as *mut u8;
|
|
||||||
unsafe {
|
|
||||||
*as_bytes.offset(0) = self.b;
|
|
||||||
*as_bytes.offset(1) = self.g;
|
|
||||||
*as_bytes.offset(2) = self.r;
|
|
||||||
*as_bytes.offset(3) = self.a;
|
|
||||||
}
|
|
||||||
cardinal
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RgbaIcon {
|
|
||||||
pub(crate) fn to_cardinals(&self) -> Vec<Cardinal> {
|
|
||||||
assert_eq!(self.rgba.len() % PIXEL_SIZE, 0);
|
|
||||||
let pixel_count = self.rgba.len() / PIXEL_SIZE;
|
|
||||||
assert_eq!(pixel_count, (self.width * self.height) as usize);
|
|
||||||
let mut data = Vec::with_capacity(pixel_count);
|
|
||||||
data.push(self.width as Cardinal);
|
|
||||||
data.push(self.height as Cardinal);
|
|
||||||
let pixels = self.rgba.as_ptr() as *const Pixel;
|
|
||||||
for pixel_index in 0..pixel_count {
|
|
||||||
let pixel = unsafe { &*pixels.add(pixel_index) };
|
|
||||||
data.push(pixel.to_packed_argb());
|
|
||||||
}
|
|
||||||
data
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
use crate::monitor::{MonitorHandle as RootMonitorHandle, VideoModeHandle as RootVideoModeHandle};
|
|
||||||
use crate::window::Fullscreen as RootFullscreen;
|
|
||||||
|
|
||||||
#[cfg(android_platform)]
|
|
||||||
mod android;
|
|
||||||
#[cfg(target_vendor = "apple")]
|
|
||||||
mod apple;
|
|
||||||
#[cfg(any(x11_platform, wayland_platform))]
|
|
||||||
mod linux;
|
|
||||||
#[cfg(orbital_platform)]
|
|
||||||
mod orbital;
|
|
||||||
#[cfg(web_platform)]
|
|
||||||
mod web;
|
|
||||||
#[cfg(windows_platform)]
|
|
||||||
mod windows;
|
|
||||||
|
|
||||||
#[cfg(android_platform)]
|
|
||||||
use self::android as platform;
|
|
||||||
#[cfg(target_vendor = "apple")]
|
|
||||||
use self::apple as platform;
|
|
||||||
#[cfg(any(x11_platform, wayland_platform))]
|
|
||||||
use self::linux as platform;
|
|
||||||
#[cfg(orbital_platform)]
|
|
||||||
use self::orbital as platform;
|
|
||||||
#[allow(unused_imports)]
|
|
||||||
pub use self::platform::*;
|
|
||||||
#[cfg(web_platform)]
|
|
||||||
use self::web as platform;
|
|
||||||
#[cfg(windows_platform)]
|
|
||||||
use self::windows as platform;
|
|
||||||
|
|
||||||
/// Helper for converting between platform-specific and generic
|
|
||||||
/// [`VideoModeHandle`]/[`MonitorHandle`]
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub(crate) enum Fullscreen {
|
|
||||||
Exclusive(VideoModeHandle),
|
|
||||||
Borderless(Option<MonitorHandle>),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<RootFullscreen> for Fullscreen {
|
|
||||||
fn from(f: RootFullscreen) -> Self {
|
|
||||||
match f {
|
|
||||||
RootFullscreen::Exclusive(mode) => Self::Exclusive(mode.video_mode),
|
|
||||||
RootFullscreen::Borderless(Some(handle)) => Self::Borderless(Some(handle.inner)),
|
|
||||||
RootFullscreen::Borderless(None) => Self::Borderless(None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<Fullscreen> for RootFullscreen {
|
|
||||||
fn from(f: Fullscreen) -> Self {
|
|
||||||
match f {
|
|
||||||
Fullscreen::Exclusive(video_mode) => {
|
|
||||||
Self::Exclusive(RootVideoModeHandle { video_mode })
|
|
||||||
},
|
|
||||||
Fullscreen::Borderless(Some(inner)) => {
|
|
||||||
Self::Borderless(Some(RootMonitorHandle { inner }))
|
|
||||||
},
|
|
||||||
Fullscreen::Borderless(None) => Self::Borderless(None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(all(
|
|
||||||
not(ios_platform),
|
|
||||||
not(windows_platform),
|
|
||||||
not(macos_platform),
|
|
||||||
not(android_platform),
|
|
||||||
not(x11_platform),
|
|
||||||
not(wayland_platform),
|
|
||||||
not(web_platform),
|
|
||||||
not(orbital_platform),
|
|
||||||
))]
|
|
||||||
compile_error!("The platform you're compiling for is not supported by winit");
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
use std::fmt;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct OsError(pub String);
|
|
||||||
|
|
||||||
impl fmt::Display for OsError {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
write!(f, "{}", self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
use super::{backend, HasMonitorPermissionFuture, MonitorPermissionFuture};
|
|
||||||
use crate::application::ApplicationHandler;
|
|
||||||
use crate::error::{EventLoopError, NotSupportedError};
|
|
||||||
use crate::event::Event;
|
|
||||||
use crate::event_loop::ActiveEventLoop as RootActiveEventLoop;
|
|
||||||
use crate::platform::web::{PollStrategy, WaitUntilStrategy};
|
|
||||||
|
|
||||||
mod proxy;
|
|
||||||
pub(crate) mod runner;
|
|
||||||
mod state;
|
|
||||||
mod window_target;
|
|
||||||
|
|
||||||
pub(crate) use window_target::ActiveEventLoop;
|
|
||||||
|
|
||||||
pub struct EventLoop {
|
|
||||||
elw: ActiveEventLoop,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
|
||||||
pub(crate) struct PlatformSpecificEventLoopAttributes {}
|
|
||||||
|
|
||||||
impl EventLoop {
|
|
||||||
pub(crate) fn new(_: &PlatformSpecificEventLoopAttributes) -> Result<Self, EventLoopError> {
|
|
||||||
Ok(EventLoop { elw: ActiveEventLoop::new() })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn run_app<A: ApplicationHandler>(self, mut app: A) -> ! {
|
|
||||||
let event_loop = self.elw.clone();
|
|
||||||
|
|
||||||
// SAFETY: Don't use `move` to make sure we leak the `event_handler` and `target`.
|
|
||||||
let handler: Box<dyn FnMut(Event)> =
|
|
||||||
Box::new(|event| handle_event(&mut app, &event_loop, event));
|
|
||||||
|
|
||||||
// SAFETY: The `transmute` is necessary because `run()` requires `'static`. This is safe
|
|
||||||
// because this function will never return and all resources not cleaned up by the point we
|
|
||||||
// `throw` will leak, making this actually `'static`.
|
|
||||||
let handler = unsafe {
|
|
||||||
std::mem::transmute::<Box<dyn FnMut(Event)>, Box<dyn FnMut(Event) + 'static>>(handler)
|
|
||||||
};
|
|
||||||
self.elw.run(handler, false);
|
|
||||||
|
|
||||||
// Throw an exception to break out of Rust execution and use unreachable to tell the
|
|
||||||
// compiler this function won't return, giving it a return type of '!'
|
|
||||||
backend::throw(
|
|
||||||
"Using exceptions for control flow, don't mind me. This isn't actually an error!",
|
|
||||||
);
|
|
||||||
|
|
||||||
unreachable!();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn spawn_app<A: ApplicationHandler + 'static>(self, mut app: A) {
|
|
||||||
let event_loop = self.elw.clone();
|
|
||||||
self.elw.run(Box::new(move |event| handle_event(&mut app, &event_loop, event)), true);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn window_target(&self) -> &dyn RootActiveEventLoop {
|
|
||||||
&self.elw
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_poll_strategy(&self, strategy: PollStrategy) {
|
|
||||||
self.elw.set_poll_strategy(strategy);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn poll_strategy(&self) -> PollStrategy {
|
|
||||||
self.elw.poll_strategy()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy) {
|
|
||||||
self.elw.set_wait_until_strategy(strategy);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn wait_until_strategy(&self) -> WaitUntilStrategy {
|
|
||||||
self.elw.wait_until_strategy()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn has_multiple_screens(&self) -> Result<bool, NotSupportedError> {
|
|
||||||
self.elw.has_multiple_screens()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn request_detailed_monitor_permission(&self) -> MonitorPermissionFuture {
|
|
||||||
self.elw.request_detailed_monitor_permission()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn has_detailed_monitor_permission(&self) -> HasMonitorPermissionFuture {
|
|
||||||
self.elw.runner.monitor().has_detailed_monitor_permission_async()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn handle_event<A: ApplicationHandler>(app: &mut A, target: &ActiveEventLoop, event: Event) {
|
|
||||||
match event {
|
|
||||||
Event::NewEvents(cause) => app.new_events(target, cause),
|
|
||||||
Event::WindowEvent { window_id, event } => app.window_event(target, window_id, event),
|
|
||||||
Event::DeviceEvent { device_id, event } => app.device_event(target, device_id, event),
|
|
||||||
Event::UserWakeUp => app.proxy_wake_up(target),
|
|
||||||
Event::Suspended => app.suspended(target),
|
|
||||||
Event::Resumed => app.resumed(target),
|
|
||||||
Event::CreateSurfaces => app.can_create_surfaces(target),
|
|
||||||
Event::AboutToWait => app.about_to_wait(target),
|
|
||||||
Event::LoopExiting => app.exiting(target),
|
|
||||||
Event::MemoryWarning => app.memory_warning(target),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,522 +0,0 @@
|
|||||||
use smol_str::SmolStr;
|
|
||||||
|
|
||||||
use crate::keyboard::{Key, KeyCode, NamedKey, NativeKey, NativeKeyCode, PhysicalKey};
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
|
|
||||||
pub(crate) struct KeyEventExtra;
|
|
||||||
|
|
||||||
impl Key {
|
|
||||||
pub(crate) fn from_key_attribute_value(kav: &str) -> Self {
|
|
||||||
Key::Named(match kav {
|
|
||||||
"Unidentified" => return Key::Unidentified(NativeKey::Web(SmolStr::new(kav))),
|
|
||||||
"Dead" => return Key::Dead(None),
|
|
||||||
"Alt" => NamedKey::Alt,
|
|
||||||
"AltGraph" => NamedKey::AltGraph,
|
|
||||||
"CapsLock" => NamedKey::CapsLock,
|
|
||||||
"Control" => NamedKey::Control,
|
|
||||||
"Fn" => NamedKey::Fn,
|
|
||||||
"FnLock" => NamedKey::FnLock,
|
|
||||||
"NumLock" => NamedKey::NumLock,
|
|
||||||
"ScrollLock" => NamedKey::ScrollLock,
|
|
||||||
"Shift" => NamedKey::Shift,
|
|
||||||
"Symbol" => NamedKey::Symbol,
|
|
||||||
"SymbolLock" => NamedKey::SymbolLock,
|
|
||||||
"Hyper" => NamedKey::Hyper,
|
|
||||||
"Meta" => NamedKey::Super,
|
|
||||||
"Enter" => NamedKey::Enter,
|
|
||||||
"Tab" => NamedKey::Tab,
|
|
||||||
" " => NamedKey::Space,
|
|
||||||
"ArrowDown" => NamedKey::ArrowDown,
|
|
||||||
"ArrowLeft" => NamedKey::ArrowLeft,
|
|
||||||
"ArrowRight" => NamedKey::ArrowRight,
|
|
||||||
"ArrowUp" => NamedKey::ArrowUp,
|
|
||||||
"End" => NamedKey::End,
|
|
||||||
"Home" => NamedKey::Home,
|
|
||||||
"PageDown" => NamedKey::PageDown,
|
|
||||||
"PageUp" => NamedKey::PageUp,
|
|
||||||
"Backspace" => NamedKey::Backspace,
|
|
||||||
"Clear" => NamedKey::Clear,
|
|
||||||
"Copy" => NamedKey::Copy,
|
|
||||||
"CrSel" => NamedKey::CrSel,
|
|
||||||
"Cut" => NamedKey::Cut,
|
|
||||||
"Delete" => NamedKey::Delete,
|
|
||||||
"EraseEof" => NamedKey::EraseEof,
|
|
||||||
"ExSel" => NamedKey::ExSel,
|
|
||||||
"Insert" => NamedKey::Insert,
|
|
||||||
"Paste" => NamedKey::Paste,
|
|
||||||
"Redo" => NamedKey::Redo,
|
|
||||||
"Undo" => NamedKey::Undo,
|
|
||||||
"Accept" => NamedKey::Accept,
|
|
||||||
"Again" => NamedKey::Again,
|
|
||||||
"Attn" => NamedKey::Attn,
|
|
||||||
"Cancel" => NamedKey::Cancel,
|
|
||||||
"ContextMenu" => NamedKey::ContextMenu,
|
|
||||||
"Escape" => NamedKey::Escape,
|
|
||||||
"Execute" => NamedKey::Execute,
|
|
||||||
"Find" => NamedKey::Find,
|
|
||||||
"Help" => NamedKey::Help,
|
|
||||||
"Pause" => NamedKey::Pause,
|
|
||||||
"Play" => NamedKey::Play,
|
|
||||||
"Props" => NamedKey::Props,
|
|
||||||
"Select" => NamedKey::Select,
|
|
||||||
"ZoomIn" => NamedKey::ZoomIn,
|
|
||||||
"ZoomOut" => NamedKey::ZoomOut,
|
|
||||||
"BrightnessDown" => NamedKey::BrightnessDown,
|
|
||||||
"BrightnessUp" => NamedKey::BrightnessUp,
|
|
||||||
"Eject" => NamedKey::Eject,
|
|
||||||
"LogOff" => NamedKey::LogOff,
|
|
||||||
"Power" => NamedKey::Power,
|
|
||||||
"PowerOff" => NamedKey::PowerOff,
|
|
||||||
"PrintScreen" => NamedKey::PrintScreen,
|
|
||||||
"Hibernate" => NamedKey::Hibernate,
|
|
||||||
"Standby" => NamedKey::Standby,
|
|
||||||
"WakeUp" => NamedKey::WakeUp,
|
|
||||||
"AllCandidates" => NamedKey::AllCandidates,
|
|
||||||
"Alphanumeric" => NamedKey::Alphanumeric,
|
|
||||||
"CodeInput" => NamedKey::CodeInput,
|
|
||||||
"Compose" => NamedKey::Compose,
|
|
||||||
"Convert" => NamedKey::Convert,
|
|
||||||
"FinalMode" => NamedKey::FinalMode,
|
|
||||||
"GroupFirst" => NamedKey::GroupFirst,
|
|
||||||
"GroupLast" => NamedKey::GroupLast,
|
|
||||||
"GroupNext" => NamedKey::GroupNext,
|
|
||||||
"GroupPrevious" => NamedKey::GroupPrevious,
|
|
||||||
"ModeChange" => NamedKey::ModeChange,
|
|
||||||
"NextCandidate" => NamedKey::NextCandidate,
|
|
||||||
"NonConvert" => NamedKey::NonConvert,
|
|
||||||
"PreviousCandidate" => NamedKey::PreviousCandidate,
|
|
||||||
"Process" => NamedKey::Process,
|
|
||||||
"SingleCandidate" => NamedKey::SingleCandidate,
|
|
||||||
"HangulMode" => NamedKey::HangulMode,
|
|
||||||
"HanjaMode" => NamedKey::HanjaMode,
|
|
||||||
"JunjaMode" => NamedKey::JunjaMode,
|
|
||||||
"Eisu" => NamedKey::Eisu,
|
|
||||||
"Hankaku" => NamedKey::Hankaku,
|
|
||||||
"Hiragana" => NamedKey::Hiragana,
|
|
||||||
"HiraganaKatakana" => NamedKey::HiraganaKatakana,
|
|
||||||
"KanaMode" => NamedKey::KanaMode,
|
|
||||||
"KanjiMode" => NamedKey::KanjiMode,
|
|
||||||
"Katakana" => NamedKey::Katakana,
|
|
||||||
"Romaji" => NamedKey::Romaji,
|
|
||||||
"Zenkaku" => NamedKey::Zenkaku,
|
|
||||||
"ZenkakuHankaku" => NamedKey::ZenkakuHankaku,
|
|
||||||
"Soft1" => NamedKey::Soft1,
|
|
||||||
"Soft2" => NamedKey::Soft2,
|
|
||||||
"Soft3" => NamedKey::Soft3,
|
|
||||||
"Soft4" => NamedKey::Soft4,
|
|
||||||
"ChannelDown" => NamedKey::ChannelDown,
|
|
||||||
"ChannelUp" => NamedKey::ChannelUp,
|
|
||||||
"Close" => NamedKey::Close,
|
|
||||||
"MailForward" => NamedKey::MailForward,
|
|
||||||
"MailReply" => NamedKey::MailReply,
|
|
||||||
"MailSend" => NamedKey::MailSend,
|
|
||||||
"MediaClose" => NamedKey::MediaClose,
|
|
||||||
"MediaFastForward" => NamedKey::MediaFastForward,
|
|
||||||
"MediaPause" => NamedKey::MediaPause,
|
|
||||||
"MediaPlay" => NamedKey::MediaPlay,
|
|
||||||
"MediaPlayPause" => NamedKey::MediaPlayPause,
|
|
||||||
"MediaRecord" => NamedKey::MediaRecord,
|
|
||||||
"MediaRewind" => NamedKey::MediaRewind,
|
|
||||||
"MediaStop" => NamedKey::MediaStop,
|
|
||||||
"MediaTrackNext" => NamedKey::MediaTrackNext,
|
|
||||||
"MediaTrackPrevious" => NamedKey::MediaTrackPrevious,
|
|
||||||
"New" => NamedKey::New,
|
|
||||||
"Open" => NamedKey::Open,
|
|
||||||
"Print" => NamedKey::Print,
|
|
||||||
"Save" => NamedKey::Save,
|
|
||||||
"SpellCheck" => NamedKey::SpellCheck,
|
|
||||||
"Key11" => NamedKey::Key11,
|
|
||||||
"Key12" => NamedKey::Key12,
|
|
||||||
"AudioBalanceLeft" => NamedKey::AudioBalanceLeft,
|
|
||||||
"AudioBalanceRight" => NamedKey::AudioBalanceRight,
|
|
||||||
"AudioBassBoostDown" => NamedKey::AudioBassBoostDown,
|
|
||||||
"AudioBassBoostToggle" => NamedKey::AudioBassBoostToggle,
|
|
||||||
"AudioBassBoostUp" => NamedKey::AudioBassBoostUp,
|
|
||||||
"AudioFaderFront" => NamedKey::AudioFaderFront,
|
|
||||||
"AudioFaderRear" => NamedKey::AudioFaderRear,
|
|
||||||
"AudioSurroundModeNext" => NamedKey::AudioSurroundModeNext,
|
|
||||||
"AudioTrebleDown" => NamedKey::AudioTrebleDown,
|
|
||||||
"AudioTrebleUp" => NamedKey::AudioTrebleUp,
|
|
||||||
"AudioVolumeDown" => NamedKey::AudioVolumeDown,
|
|
||||||
"AudioVolumeUp" => NamedKey::AudioVolumeUp,
|
|
||||||
"AudioVolumeMute" => NamedKey::AudioVolumeMute,
|
|
||||||
"MicrophoneToggle" => NamedKey::MicrophoneToggle,
|
|
||||||
"MicrophoneVolumeDown" => NamedKey::MicrophoneVolumeDown,
|
|
||||||
"MicrophoneVolumeUp" => NamedKey::MicrophoneVolumeUp,
|
|
||||||
"MicrophoneVolumeMute" => NamedKey::MicrophoneVolumeMute,
|
|
||||||
"SpeechCorrectionList" => NamedKey::SpeechCorrectionList,
|
|
||||||
"SpeechInputToggle" => NamedKey::SpeechInputToggle,
|
|
||||||
"LaunchApplication1" => NamedKey::LaunchApplication1,
|
|
||||||
"LaunchApplication2" => NamedKey::LaunchApplication2,
|
|
||||||
"LaunchCalendar" => NamedKey::LaunchCalendar,
|
|
||||||
"LaunchContacts" => NamedKey::LaunchContacts,
|
|
||||||
"LaunchMail" => NamedKey::LaunchMail,
|
|
||||||
"LaunchMediaPlayer" => NamedKey::LaunchMediaPlayer,
|
|
||||||
"LaunchMusicPlayer" => NamedKey::LaunchMusicPlayer,
|
|
||||||
"LaunchPhone" => NamedKey::LaunchPhone,
|
|
||||||
"LaunchScreenSaver" => NamedKey::LaunchScreenSaver,
|
|
||||||
"LaunchSpreadsheet" => NamedKey::LaunchSpreadsheet,
|
|
||||||
"LaunchWebBrowser" => NamedKey::LaunchWebBrowser,
|
|
||||||
"LaunchWebCam" => NamedKey::LaunchWebCam,
|
|
||||||
"LaunchWordProcessor" => NamedKey::LaunchWordProcessor,
|
|
||||||
"BrowserBack" => NamedKey::BrowserBack,
|
|
||||||
"BrowserFavorites" => NamedKey::BrowserFavorites,
|
|
||||||
"BrowserForward" => NamedKey::BrowserForward,
|
|
||||||
"BrowserHome" => NamedKey::BrowserHome,
|
|
||||||
"BrowserRefresh" => NamedKey::BrowserRefresh,
|
|
||||||
"BrowserSearch" => NamedKey::BrowserSearch,
|
|
||||||
"BrowserStop" => NamedKey::BrowserStop,
|
|
||||||
"AppSwitch" => NamedKey::AppSwitch,
|
|
||||||
"Call" => NamedKey::Call,
|
|
||||||
"Camera" => NamedKey::Camera,
|
|
||||||
"CameraFocus" => NamedKey::CameraFocus,
|
|
||||||
"EndCall" => NamedKey::EndCall,
|
|
||||||
"GoBack" => NamedKey::GoBack,
|
|
||||||
"GoHome" => NamedKey::GoHome,
|
|
||||||
"HeadsetHook" => NamedKey::HeadsetHook,
|
|
||||||
"LastNumberRedial" => NamedKey::LastNumberRedial,
|
|
||||||
"Notification" => NamedKey::Notification,
|
|
||||||
"MannerMode" => NamedKey::MannerMode,
|
|
||||||
"VoiceDial" => NamedKey::VoiceDial,
|
|
||||||
"TV" => NamedKey::TV,
|
|
||||||
"TV3DMode" => NamedKey::TV3DMode,
|
|
||||||
"TVAntennaCable" => NamedKey::TVAntennaCable,
|
|
||||||
"TVAudioDescription" => NamedKey::TVAudioDescription,
|
|
||||||
"TVAudioDescriptionMixDown" => NamedKey::TVAudioDescriptionMixDown,
|
|
||||||
"TVAudioDescriptionMixUp" => NamedKey::TVAudioDescriptionMixUp,
|
|
||||||
"TVContentsMenu" => NamedKey::TVContentsMenu,
|
|
||||||
"TVDataService" => NamedKey::TVDataService,
|
|
||||||
"TVInput" => NamedKey::TVInput,
|
|
||||||
"TVInputComponent1" => NamedKey::TVInputComponent1,
|
|
||||||
"TVInputComponent2" => NamedKey::TVInputComponent2,
|
|
||||||
"TVInputComposite1" => NamedKey::TVInputComposite1,
|
|
||||||
"TVInputComposite2" => NamedKey::TVInputComposite2,
|
|
||||||
"TVInputHDMI1" => NamedKey::TVInputHDMI1,
|
|
||||||
"TVInputHDMI2" => NamedKey::TVInputHDMI2,
|
|
||||||
"TVInputHDMI3" => NamedKey::TVInputHDMI3,
|
|
||||||
"TVInputHDMI4" => NamedKey::TVInputHDMI4,
|
|
||||||
"TVInputVGA1" => NamedKey::TVInputVGA1,
|
|
||||||
"TVMediaContext" => NamedKey::TVMediaContext,
|
|
||||||
"TVNetwork" => NamedKey::TVNetwork,
|
|
||||||
"TVNumberEntry" => NamedKey::TVNumberEntry,
|
|
||||||
"TVPower" => NamedKey::TVPower,
|
|
||||||
"TVRadioService" => NamedKey::TVRadioService,
|
|
||||||
"TVSatellite" => NamedKey::TVSatellite,
|
|
||||||
"TVSatelliteBS" => NamedKey::TVSatelliteBS,
|
|
||||||
"TVSatelliteCS" => NamedKey::TVSatelliteCS,
|
|
||||||
"TVSatelliteToggle" => NamedKey::TVSatelliteToggle,
|
|
||||||
"TVTerrestrialAnalog" => NamedKey::TVTerrestrialAnalog,
|
|
||||||
"TVTerrestrialDigital" => NamedKey::TVTerrestrialDigital,
|
|
||||||
"TVTimer" => NamedKey::TVTimer,
|
|
||||||
"AVRInput" => NamedKey::AVRInput,
|
|
||||||
"AVRPower" => NamedKey::AVRPower,
|
|
||||||
"ColorF0Red" => NamedKey::ColorF0Red,
|
|
||||||
"ColorF1Green" => NamedKey::ColorF1Green,
|
|
||||||
"ColorF2Yellow" => NamedKey::ColorF2Yellow,
|
|
||||||
"ColorF3Blue" => NamedKey::ColorF3Blue,
|
|
||||||
"ColorF4Grey" => NamedKey::ColorF4Grey,
|
|
||||||
"ColorF5Brown" => NamedKey::ColorF5Brown,
|
|
||||||
"ClosedCaptionToggle" => NamedKey::ClosedCaptionToggle,
|
|
||||||
"Dimmer" => NamedKey::Dimmer,
|
|
||||||
"DisplaySwap" => NamedKey::DisplaySwap,
|
|
||||||
"DVR" => NamedKey::DVR,
|
|
||||||
"Exit" => NamedKey::Exit,
|
|
||||||
"FavoriteClear0" => NamedKey::FavoriteClear0,
|
|
||||||
"FavoriteClear1" => NamedKey::FavoriteClear1,
|
|
||||||
"FavoriteClear2" => NamedKey::FavoriteClear2,
|
|
||||||
"FavoriteClear3" => NamedKey::FavoriteClear3,
|
|
||||||
"FavoriteRecall0" => NamedKey::FavoriteRecall0,
|
|
||||||
"FavoriteRecall1" => NamedKey::FavoriteRecall1,
|
|
||||||
"FavoriteRecall2" => NamedKey::FavoriteRecall2,
|
|
||||||
"FavoriteRecall3" => NamedKey::FavoriteRecall3,
|
|
||||||
"FavoriteStore0" => NamedKey::FavoriteStore0,
|
|
||||||
"FavoriteStore1" => NamedKey::FavoriteStore1,
|
|
||||||
"FavoriteStore2" => NamedKey::FavoriteStore2,
|
|
||||||
"FavoriteStore3" => NamedKey::FavoriteStore3,
|
|
||||||
"Guide" => NamedKey::Guide,
|
|
||||||
"GuideNextDay" => NamedKey::GuideNextDay,
|
|
||||||
"GuidePreviousDay" => NamedKey::GuidePreviousDay,
|
|
||||||
"Info" => NamedKey::Info,
|
|
||||||
"InstantReplay" => NamedKey::InstantReplay,
|
|
||||||
"Link" => NamedKey::Link,
|
|
||||||
"ListProgram" => NamedKey::ListProgram,
|
|
||||||
"LiveContent" => NamedKey::LiveContent,
|
|
||||||
"Lock" => NamedKey::Lock,
|
|
||||||
"MediaApps" => NamedKey::MediaApps,
|
|
||||||
"MediaAudioTrack" => NamedKey::MediaAudioTrack,
|
|
||||||
"MediaLast" => NamedKey::MediaLast,
|
|
||||||
"MediaSkipBackward" => NamedKey::MediaSkipBackward,
|
|
||||||
"MediaSkipForward" => NamedKey::MediaSkipForward,
|
|
||||||
"MediaStepBackward" => NamedKey::MediaStepBackward,
|
|
||||||
"MediaStepForward" => NamedKey::MediaStepForward,
|
|
||||||
"MediaTopMenu" => NamedKey::MediaTopMenu,
|
|
||||||
"NavigateIn" => NamedKey::NavigateIn,
|
|
||||||
"NavigateNext" => NamedKey::NavigateNext,
|
|
||||||
"NavigateOut" => NamedKey::NavigateOut,
|
|
||||||
"NavigatePrevious" => NamedKey::NavigatePrevious,
|
|
||||||
"NextFavoriteChannel" => NamedKey::NextFavoriteChannel,
|
|
||||||
"NextUserProfile" => NamedKey::NextUserProfile,
|
|
||||||
"OnDemand" => NamedKey::OnDemand,
|
|
||||||
"Pairing" => NamedKey::Pairing,
|
|
||||||
"PinPDown" => NamedKey::PinPDown,
|
|
||||||
"PinPMove" => NamedKey::PinPMove,
|
|
||||||
"PinPToggle" => NamedKey::PinPToggle,
|
|
||||||
"PinPUp" => NamedKey::PinPUp,
|
|
||||||
"PlaySpeedDown" => NamedKey::PlaySpeedDown,
|
|
||||||
"PlaySpeedReset" => NamedKey::PlaySpeedReset,
|
|
||||||
"PlaySpeedUp" => NamedKey::PlaySpeedUp,
|
|
||||||
"RandomToggle" => NamedKey::RandomToggle,
|
|
||||||
"RcLowBattery" => NamedKey::RcLowBattery,
|
|
||||||
"RecordSpeedNext" => NamedKey::RecordSpeedNext,
|
|
||||||
"RfBypass" => NamedKey::RfBypass,
|
|
||||||
"ScanChannelsToggle" => NamedKey::ScanChannelsToggle,
|
|
||||||
"ScreenModeNext" => NamedKey::ScreenModeNext,
|
|
||||||
"Settings" => NamedKey::Settings,
|
|
||||||
"SplitScreenToggle" => NamedKey::SplitScreenToggle,
|
|
||||||
"STBInput" => NamedKey::STBInput,
|
|
||||||
"STBPower" => NamedKey::STBPower,
|
|
||||||
"Subtitle" => NamedKey::Subtitle,
|
|
||||||
"Teletext" => NamedKey::Teletext,
|
|
||||||
"VideoModeNext" => NamedKey::VideoModeNext,
|
|
||||||
"Wink" => NamedKey::Wink,
|
|
||||||
"ZoomToggle" => NamedKey::ZoomToggle,
|
|
||||||
"F1" => NamedKey::F1,
|
|
||||||
"F2" => NamedKey::F2,
|
|
||||||
"F3" => NamedKey::F3,
|
|
||||||
"F4" => NamedKey::F4,
|
|
||||||
"F5" => NamedKey::F5,
|
|
||||||
"F6" => NamedKey::F6,
|
|
||||||
"F7" => NamedKey::F7,
|
|
||||||
"F8" => NamedKey::F8,
|
|
||||||
"F9" => NamedKey::F9,
|
|
||||||
"F10" => NamedKey::F10,
|
|
||||||
"F11" => NamedKey::F11,
|
|
||||||
"F12" => NamedKey::F12,
|
|
||||||
"F13" => NamedKey::F13,
|
|
||||||
"F14" => NamedKey::F14,
|
|
||||||
"F15" => NamedKey::F15,
|
|
||||||
"F16" => NamedKey::F16,
|
|
||||||
"F17" => NamedKey::F17,
|
|
||||||
"F18" => NamedKey::F18,
|
|
||||||
"F19" => NamedKey::F19,
|
|
||||||
"F20" => NamedKey::F20,
|
|
||||||
"F21" => NamedKey::F21,
|
|
||||||
"F22" => NamedKey::F22,
|
|
||||||
"F23" => NamedKey::F23,
|
|
||||||
"F24" => NamedKey::F24,
|
|
||||||
"F25" => NamedKey::F25,
|
|
||||||
"F26" => NamedKey::F26,
|
|
||||||
"F27" => NamedKey::F27,
|
|
||||||
"F28" => NamedKey::F28,
|
|
||||||
"F29" => NamedKey::F29,
|
|
||||||
"F30" => NamedKey::F30,
|
|
||||||
"F31" => NamedKey::F31,
|
|
||||||
"F32" => NamedKey::F32,
|
|
||||||
"F33" => NamedKey::F33,
|
|
||||||
"F34" => NamedKey::F34,
|
|
||||||
"F35" => NamedKey::F35,
|
|
||||||
string => return Key::Character(SmolStr::new(string)),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PhysicalKey {
|
|
||||||
pub fn from_key_code_attribute_value(kcav: &str) -> Self {
|
|
||||||
PhysicalKey::Code(match kcav {
|
|
||||||
"Backquote" => KeyCode::Backquote,
|
|
||||||
"Backslash" => KeyCode::Backslash,
|
|
||||||
"BracketLeft" => KeyCode::BracketLeft,
|
|
||||||
"BracketRight" => KeyCode::BracketRight,
|
|
||||||
"Comma" => KeyCode::Comma,
|
|
||||||
"Digit0" => KeyCode::Digit0,
|
|
||||||
"Digit1" => KeyCode::Digit1,
|
|
||||||
"Digit2" => KeyCode::Digit2,
|
|
||||||
"Digit3" => KeyCode::Digit3,
|
|
||||||
"Digit4" => KeyCode::Digit4,
|
|
||||||
"Digit5" => KeyCode::Digit5,
|
|
||||||
"Digit6" => KeyCode::Digit6,
|
|
||||||
"Digit7" => KeyCode::Digit7,
|
|
||||||
"Digit8" => KeyCode::Digit8,
|
|
||||||
"Digit9" => KeyCode::Digit9,
|
|
||||||
"Equal" => KeyCode::Equal,
|
|
||||||
"IntlBackslash" => KeyCode::IntlBackslash,
|
|
||||||
"IntlRo" => KeyCode::IntlRo,
|
|
||||||
"IntlYen" => KeyCode::IntlYen,
|
|
||||||
"KeyA" => KeyCode::KeyA,
|
|
||||||
"KeyB" => KeyCode::KeyB,
|
|
||||||
"KeyC" => KeyCode::KeyC,
|
|
||||||
"KeyD" => KeyCode::KeyD,
|
|
||||||
"KeyE" => KeyCode::KeyE,
|
|
||||||
"KeyF" => KeyCode::KeyF,
|
|
||||||
"KeyG" => KeyCode::KeyG,
|
|
||||||
"KeyH" => KeyCode::KeyH,
|
|
||||||
"KeyI" => KeyCode::KeyI,
|
|
||||||
"KeyJ" => KeyCode::KeyJ,
|
|
||||||
"KeyK" => KeyCode::KeyK,
|
|
||||||
"KeyL" => KeyCode::KeyL,
|
|
||||||
"KeyM" => KeyCode::KeyM,
|
|
||||||
"KeyN" => KeyCode::KeyN,
|
|
||||||
"KeyO" => KeyCode::KeyO,
|
|
||||||
"KeyP" => KeyCode::KeyP,
|
|
||||||
"KeyQ" => KeyCode::KeyQ,
|
|
||||||
"KeyR" => KeyCode::KeyR,
|
|
||||||
"KeyS" => KeyCode::KeyS,
|
|
||||||
"KeyT" => KeyCode::KeyT,
|
|
||||||
"KeyU" => KeyCode::KeyU,
|
|
||||||
"KeyV" => KeyCode::KeyV,
|
|
||||||
"KeyW" => KeyCode::KeyW,
|
|
||||||
"KeyX" => KeyCode::KeyX,
|
|
||||||
"KeyY" => KeyCode::KeyY,
|
|
||||||
"KeyZ" => KeyCode::KeyZ,
|
|
||||||
"Minus" => KeyCode::Minus,
|
|
||||||
"Period" => KeyCode::Period,
|
|
||||||
"Quote" => KeyCode::Quote,
|
|
||||||
"Semicolon" => KeyCode::Semicolon,
|
|
||||||
"Slash" => KeyCode::Slash,
|
|
||||||
"AltLeft" => KeyCode::AltLeft,
|
|
||||||
"AltRight" => KeyCode::AltRight,
|
|
||||||
"Backspace" => KeyCode::Backspace,
|
|
||||||
"CapsLock" => KeyCode::CapsLock,
|
|
||||||
"ContextMenu" => KeyCode::ContextMenu,
|
|
||||||
"ControlLeft" => KeyCode::ControlLeft,
|
|
||||||
"ControlRight" => KeyCode::ControlRight,
|
|
||||||
"Enter" => KeyCode::Enter,
|
|
||||||
"MetaLeft" => KeyCode::SuperLeft,
|
|
||||||
"MetaRight" => KeyCode::SuperRight,
|
|
||||||
"ShiftLeft" => KeyCode::ShiftLeft,
|
|
||||||
"ShiftRight" => KeyCode::ShiftRight,
|
|
||||||
"Space" => KeyCode::Space,
|
|
||||||
"Tab" => KeyCode::Tab,
|
|
||||||
"Convert" => KeyCode::Convert,
|
|
||||||
"KanaMode" => KeyCode::KanaMode,
|
|
||||||
"Lang1" => KeyCode::Lang1,
|
|
||||||
"Lang2" => KeyCode::Lang2,
|
|
||||||
"Lang3" => KeyCode::Lang3,
|
|
||||||
"Lang4" => KeyCode::Lang4,
|
|
||||||
"Lang5" => KeyCode::Lang5,
|
|
||||||
"NonConvert" => KeyCode::NonConvert,
|
|
||||||
"Delete" => KeyCode::Delete,
|
|
||||||
"End" => KeyCode::End,
|
|
||||||
"Help" => KeyCode::Help,
|
|
||||||
"Home" => KeyCode::Home,
|
|
||||||
"Insert" => KeyCode::Insert,
|
|
||||||
"PageDown" => KeyCode::PageDown,
|
|
||||||
"PageUp" => KeyCode::PageUp,
|
|
||||||
"ArrowDown" => KeyCode::ArrowDown,
|
|
||||||
"ArrowLeft" => KeyCode::ArrowLeft,
|
|
||||||
"ArrowRight" => KeyCode::ArrowRight,
|
|
||||||
"ArrowUp" => KeyCode::ArrowUp,
|
|
||||||
"NumLock" => KeyCode::NumLock,
|
|
||||||
"Numpad0" => KeyCode::Numpad0,
|
|
||||||
"Numpad1" => KeyCode::Numpad1,
|
|
||||||
"Numpad2" => KeyCode::Numpad2,
|
|
||||||
"Numpad3" => KeyCode::Numpad3,
|
|
||||||
"Numpad4" => KeyCode::Numpad4,
|
|
||||||
"Numpad5" => KeyCode::Numpad5,
|
|
||||||
"Numpad6" => KeyCode::Numpad6,
|
|
||||||
"Numpad7" => KeyCode::Numpad7,
|
|
||||||
"Numpad8" => KeyCode::Numpad8,
|
|
||||||
"Numpad9" => KeyCode::Numpad9,
|
|
||||||
"NumpadAdd" => KeyCode::NumpadAdd,
|
|
||||||
"NumpadBackspace" => KeyCode::NumpadBackspace,
|
|
||||||
"NumpadClear" => KeyCode::NumpadClear,
|
|
||||||
"NumpadClearEntry" => KeyCode::NumpadClearEntry,
|
|
||||||
"NumpadComma" => KeyCode::NumpadComma,
|
|
||||||
"NumpadDecimal" => KeyCode::NumpadDecimal,
|
|
||||||
"NumpadDivide" => KeyCode::NumpadDivide,
|
|
||||||
"NumpadEnter" => KeyCode::NumpadEnter,
|
|
||||||
"NumpadEqual" => KeyCode::NumpadEqual,
|
|
||||||
"NumpadHash" => KeyCode::NumpadHash,
|
|
||||||
"NumpadMemoryAdd" => KeyCode::NumpadMemoryAdd,
|
|
||||||
"NumpadMemoryClear" => KeyCode::NumpadMemoryClear,
|
|
||||||
"NumpadMemoryRecall" => KeyCode::NumpadMemoryRecall,
|
|
||||||
"NumpadMemoryStore" => KeyCode::NumpadMemoryStore,
|
|
||||||
"NumpadMemorySubtract" => KeyCode::NumpadMemorySubtract,
|
|
||||||
"NumpadMultiply" => KeyCode::NumpadMultiply,
|
|
||||||
"NumpadParenLeft" => KeyCode::NumpadParenLeft,
|
|
||||||
"NumpadParenRight" => KeyCode::NumpadParenRight,
|
|
||||||
"NumpadStar" => KeyCode::NumpadStar,
|
|
||||||
"NumpadSubtract" => KeyCode::NumpadSubtract,
|
|
||||||
"Escape" => KeyCode::Escape,
|
|
||||||
"Fn" => KeyCode::Fn,
|
|
||||||
"FnLock" => KeyCode::FnLock,
|
|
||||||
"PrintScreen" => KeyCode::PrintScreen,
|
|
||||||
"ScrollLock" => KeyCode::ScrollLock,
|
|
||||||
"Pause" => KeyCode::Pause,
|
|
||||||
"BrowserBack" => KeyCode::BrowserBack,
|
|
||||||
"BrowserFavorites" => KeyCode::BrowserFavorites,
|
|
||||||
"BrowserForward" => KeyCode::BrowserForward,
|
|
||||||
"BrowserHome" => KeyCode::BrowserHome,
|
|
||||||
"BrowserRefresh" => KeyCode::BrowserRefresh,
|
|
||||||
"BrowserSearch" => KeyCode::BrowserSearch,
|
|
||||||
"BrowserStop" => KeyCode::BrowserStop,
|
|
||||||
"Eject" => KeyCode::Eject,
|
|
||||||
"LaunchApp1" => KeyCode::LaunchApp1,
|
|
||||||
"LaunchApp2" => KeyCode::LaunchApp2,
|
|
||||||
"LaunchMail" => KeyCode::LaunchMail,
|
|
||||||
"MediaPlayPause" => KeyCode::MediaPlayPause,
|
|
||||||
"MediaSelect" => KeyCode::MediaSelect,
|
|
||||||
"MediaStop" => KeyCode::MediaStop,
|
|
||||||
"MediaTrackNext" => KeyCode::MediaTrackNext,
|
|
||||||
"MediaTrackPrevious" => KeyCode::MediaTrackPrevious,
|
|
||||||
"Power" => KeyCode::Power,
|
|
||||||
"Sleep" => KeyCode::Sleep,
|
|
||||||
"AudioVolumeDown" => KeyCode::AudioVolumeDown,
|
|
||||||
"AudioVolumeMute" => KeyCode::AudioVolumeMute,
|
|
||||||
"AudioVolumeUp" => KeyCode::AudioVolumeUp,
|
|
||||||
"WakeUp" => KeyCode::WakeUp,
|
|
||||||
"Hyper" => KeyCode::Hyper,
|
|
||||||
"Turbo" => KeyCode::Turbo,
|
|
||||||
"Abort" => KeyCode::Abort,
|
|
||||||
"Resume" => KeyCode::Resume,
|
|
||||||
"Suspend" => KeyCode::Suspend,
|
|
||||||
"Again" => KeyCode::Again,
|
|
||||||
"Copy" => KeyCode::Copy,
|
|
||||||
"Cut" => KeyCode::Cut,
|
|
||||||
"Find" => KeyCode::Find,
|
|
||||||
"Open" => KeyCode::Open,
|
|
||||||
"Paste" => KeyCode::Paste,
|
|
||||||
"Props" => KeyCode::Props,
|
|
||||||
"Select" => KeyCode::Select,
|
|
||||||
"Undo" => KeyCode::Undo,
|
|
||||||
"Hiragana" => KeyCode::Hiragana,
|
|
||||||
"Katakana" => KeyCode::Katakana,
|
|
||||||
"F1" => KeyCode::F1,
|
|
||||||
"F2" => KeyCode::F2,
|
|
||||||
"F3" => KeyCode::F3,
|
|
||||||
"F4" => KeyCode::F4,
|
|
||||||
"F5" => KeyCode::F5,
|
|
||||||
"F6" => KeyCode::F6,
|
|
||||||
"F7" => KeyCode::F7,
|
|
||||||
"F8" => KeyCode::F8,
|
|
||||||
"F9" => KeyCode::F9,
|
|
||||||
"F10" => KeyCode::F10,
|
|
||||||
"F11" => KeyCode::F11,
|
|
||||||
"F12" => KeyCode::F12,
|
|
||||||
"F13" => KeyCode::F13,
|
|
||||||
"F14" => KeyCode::F14,
|
|
||||||
"F15" => KeyCode::F15,
|
|
||||||
"F16" => KeyCode::F16,
|
|
||||||
"F17" => KeyCode::F17,
|
|
||||||
"F18" => KeyCode::F18,
|
|
||||||
"F19" => KeyCode::F19,
|
|
||||||
"F20" => KeyCode::F20,
|
|
||||||
"F21" => KeyCode::F21,
|
|
||||||
"F22" => KeyCode::F22,
|
|
||||||
"F23" => KeyCode::F23,
|
|
||||||
"F24" => KeyCode::F24,
|
|
||||||
"F25" => KeyCode::F25,
|
|
||||||
"F26" => KeyCode::F26,
|
|
||||||
"F27" => KeyCode::F27,
|
|
||||||
"F28" => KeyCode::F28,
|
|
||||||
"F29" => KeyCode::F29,
|
|
||||||
"F30" => KeyCode::F30,
|
|
||||||
"F31" => KeyCode::F31,
|
|
||||||
"F32" => KeyCode::F32,
|
|
||||||
"F33" => KeyCode::F33,
|
|
||||||
"F34" => KeyCode::F34,
|
|
||||||
"F35" => KeyCode::F35,
|
|
||||||
_ => return PhysicalKey::Unidentified(NativeKeyCode::Unidentified),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
// Brief introduction to the internals of the Web backend:
|
|
||||||
// The Web backend used to support both wasm-bindgen and stdweb as methods of binding to the
|
|
||||||
// environment. Because they are both supporting the same underlying APIs, the actual Web bindings
|
|
||||||
// are cordoned off into backend abstractions, which present the thinnest unifying layer possible.
|
|
||||||
//
|
|
||||||
// When adding support for new events or interactions with the browser, first consult trusted
|
|
||||||
// documentation (such as MDN) to ensure it is well-standardised and supported across many browsers.
|
|
||||||
// Once you have decided on the relevant Web APIs, add support to both backends.
|
|
||||||
//
|
|
||||||
// The backend is used by the rest of the module to implement Winit's business logic, which forms
|
|
||||||
// the rest of the code. 'device', 'error', 'monitor', and 'window' define Web-specific structures
|
|
||||||
// for winit's cross-platform structures. They are all relatively simple translations.
|
|
||||||
//
|
|
||||||
// The event_loop module handles listening for and processing events. 'Proxy' implements
|
|
||||||
// EventLoopProxy and 'WindowTarget' implements ActiveEventLoop. WindowTarget also handles
|
|
||||||
// registering the event handlers. The 'Execution' struct in the 'runner' module handles taking
|
|
||||||
// incoming events (from the registered handlers) and ensuring they are passed to the user in a
|
|
||||||
// compliant way.
|
|
||||||
|
|
||||||
// TODO: FP, remove when <https://github.com/rust-lang/rust-clippy/issues/12377> is fixed.
|
|
||||||
#![allow(clippy::empty_docs)]
|
|
||||||
|
|
||||||
mod r#async;
|
|
||||||
mod cursor;
|
|
||||||
mod error;
|
|
||||||
mod event;
|
|
||||||
mod event_loop;
|
|
||||||
mod keyboard;
|
|
||||||
mod lock;
|
|
||||||
mod main_thread;
|
|
||||||
mod monitor;
|
|
||||||
mod web_sys;
|
|
||||||
mod window;
|
|
||||||
|
|
||||||
pub(crate) use cursor::{
|
|
||||||
CustomCursor as PlatformCustomCursor, CustomCursorFuture,
|
|
||||||
CustomCursorSource as PlatformCustomCursorSource,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub(crate) use self::event_loop::{
|
|
||||||
ActiveEventLoop, EventLoop, PlatformSpecificEventLoopAttributes,
|
|
||||||
};
|
|
||||||
pub(crate) use self::keyboard::KeyEventExtra;
|
|
||||||
pub(crate) use self::monitor::{
|
|
||||||
HasMonitorPermissionFuture, MonitorHandle, MonitorPermissionFuture, OrientationLockFuture,
|
|
||||||
VideoModeHandle,
|
|
||||||
};
|
|
||||||
use self::web_sys as backend;
|
|
||||||
pub use self::window::{PlatformSpecificWindowAttributes, Window};
|
|
||||||
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
|
||||||
@@ -1,137 +0,0 @@
|
|||||||
use smol_str::SmolStr;
|
|
||||||
use windows_sys::Win32::Foundation::HWND;
|
|
||||||
use windows_sys::Win32::UI::WindowsAndMessaging::{HMENU, WINDOW_LONG_PTR_INDEX};
|
|
||||||
|
|
||||||
pub(crate) use self::event_loop::{EventLoop, PlatformSpecificEventLoopAttributes};
|
|
||||||
pub use self::icon::WinIcon as PlatformIcon;
|
|
||||||
pub(crate) use self::icon::{SelectedCursor, WinCursor as PlatformCustomCursor, WinIcon};
|
|
||||||
pub(crate) use self::keyboard::{physicalkey_to_scancode, scancode_to_physicalkey};
|
|
||||||
pub(crate) use self::monitor::{MonitorHandle, VideoModeHandle};
|
|
||||||
pub(crate) use self::window::Window;
|
|
||||||
pub(crate) use crate::cursor::OnlyCursorImageSource as PlatformCustomCursorSource;
|
|
||||||
use crate::event::DeviceId;
|
|
||||||
use crate::icon::Icon;
|
|
||||||
use crate::keyboard::Key;
|
|
||||||
use crate::platform::windows::{BackdropType, Color, CornerPreference};
|
|
||||||
use crate::platform_impl::Fullscreen;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct PlatformSpecificWindowAttributes {
|
|
||||||
pub owner: Option<HWND>,
|
|
||||||
pub menu: Option<HMENU>,
|
|
||||||
pub taskbar_icon: Option<Icon>,
|
|
||||||
pub no_redirection_bitmap: bool,
|
|
||||||
pub drag_and_drop: bool,
|
|
||||||
pub skip_taskbar: bool,
|
|
||||||
pub class_name: String,
|
|
||||||
pub decoration_shadow: bool,
|
|
||||||
pub backdrop_type: BackdropType,
|
|
||||||
pub clip_children: bool,
|
|
||||||
pub border_color: Option<Color>,
|
|
||||||
pub title_background_color: Option<Color>,
|
|
||||||
pub title_text_color: Option<Color>,
|
|
||||||
pub corner_preference: Option<CornerPreference>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for PlatformSpecificWindowAttributes {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
owner: None,
|
|
||||||
menu: None,
|
|
||||||
taskbar_icon: None,
|
|
||||||
no_redirection_bitmap: false,
|
|
||||||
drag_and_drop: true,
|
|
||||||
skip_taskbar: false,
|
|
||||||
class_name: "Window Class".to_string(),
|
|
||||||
decoration_shadow: false,
|
|
||||||
backdrop_type: BackdropType::default(),
|
|
||||||
clip_children: true,
|
|
||||||
border_color: None,
|
|
||||||
title_background_color: None,
|
|
||||||
title_text_color: None,
|
|
||||||
corner_preference: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe impl Send for PlatformSpecificWindowAttributes {}
|
|
||||||
unsafe impl Sync for PlatformSpecificWindowAttributes {}
|
|
||||||
|
|
||||||
fn wrap_device_id(id: u32) -> DeviceId {
|
|
||||||
DeviceId::from_raw(id as i64)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
|
|
||||||
pub struct KeyEventExtra {
|
|
||||||
pub text_with_all_modifiers: Option<SmolStr>,
|
|
||||||
pub key_without_modifiers: Key,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
const fn get_xbutton_wparam(x: u32) -> u16 {
|
|
||||||
hiword(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
const fn get_x_lparam(x: u32) -> i16 {
|
|
||||||
loword(x) as _
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
const fn get_y_lparam(x: u32) -> i16 {
|
|
||||||
hiword(x) as _
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
pub(crate) const fn primarylangid(lgid: u16) -> u16 {
|
|
||||||
lgid & 0x3ff
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
pub(crate) const fn loword(x: u32) -> u16 {
|
|
||||||
(x & 0xffff) as u16
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
const fn hiword(x: u32) -> u16 {
|
|
||||||
((x >> 16) & 0xffff) as u16
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
unsafe fn get_window_long(hwnd: HWND, nindex: WINDOW_LONG_PTR_INDEX) -> isize {
|
|
||||||
#[cfg(target_pointer_width = "64")]
|
|
||||||
return unsafe { windows_sys::Win32::UI::WindowsAndMessaging::GetWindowLongPtrW(hwnd, nindex) };
|
|
||||||
#[cfg(target_pointer_width = "32")]
|
|
||||||
return unsafe {
|
|
||||||
windows_sys::Win32::UI::WindowsAndMessaging::GetWindowLongW(hwnd, nindex) as isize
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
unsafe fn set_window_long(hwnd: HWND, nindex: WINDOW_LONG_PTR_INDEX, dwnewlong: isize) -> isize {
|
|
||||||
#[cfg(target_pointer_width = "64")]
|
|
||||||
return unsafe {
|
|
||||||
windows_sys::Win32::UI::WindowsAndMessaging::SetWindowLongPtrW(hwnd, nindex, dwnewlong)
|
|
||||||
};
|
|
||||||
#[cfg(target_pointer_width = "32")]
|
|
||||||
return unsafe {
|
|
||||||
windows_sys::Win32::UI::WindowsAndMessaging::SetWindowLongW(hwnd, nindex, dwnewlong as i32)
|
|
||||||
as isize
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
#[macro_use]
|
|
||||||
mod util;
|
|
||||||
mod dark_mode;
|
|
||||||
mod definitions;
|
|
||||||
mod dpi;
|
|
||||||
mod drop_handler;
|
|
||||||
mod event_loop;
|
|
||||||
mod icon;
|
|
||||||
mod ime;
|
|
||||||
mod keyboard;
|
|
||||||
mod keyboard_layout;
|
|
||||||
mod monitor;
|
|
||||||
pub(crate) mod raw_input;
|
|
||||||
mod window;
|
|
||||||
mod window_state;
|
|
||||||
46
src/utils.rs
46
src/utils.rs
@@ -1,46 +0,0 @@
|
|||||||
// A poly-fill for `lazy_cell`
|
|
||||||
// Replace with std::sync::LazyLock when https://github.com/rust-lang/rust/issues/109736 is stabilized.
|
|
||||||
|
|
||||||
// This isn't used on every platform, which can come up as dead code warnings.
|
|
||||||
#![allow(dead_code)]
|
|
||||||
|
|
||||||
use std::any::Any;
|
|
||||||
use std::ops::Deref;
|
|
||||||
use std::sync::OnceLock;
|
|
||||||
|
|
||||||
pub(crate) struct Lazy<T> {
|
|
||||||
cell: OnceLock<T>,
|
|
||||||
init: fn() -> T,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Lazy<T> {
|
|
||||||
pub const fn new(f: fn() -> T) -> Self {
|
|
||||||
Self { cell: OnceLock::new(), init: f }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Deref for Lazy<T> {
|
|
||||||
type Target = T;
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn deref(&self) -> &'_ T {
|
|
||||||
self.cell.get_or_init(self.init)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait AsAny {
|
|
||||||
fn as_any(&self) -> &dyn Any;
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn Any;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: Any> AsAny for T {
|
|
||||||
#[inline(always)]
|
|
||||||
fn as_any(&self) -> &dyn Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline(always)]
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
35
winit-android/Cargo.toml
Normal file
35
winit-android/Cargo.toml
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
[package]
|
||||||
|
description = "Winit's Android backend"
|
||||||
|
documentation = "https://docs.rs/winit-android"
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
name = "winit-android"
|
||||||
|
repository.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
version.workspace = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
game-activity = ["android-activity/game-activity"]
|
||||||
|
native-activity = ["android-activity/native-activity"]
|
||||||
|
serde = ["dep:serde", "bitflags/serde", "smol_str/serde", "dpi/serde", "winit-core/serde"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
bitflags.workspace = true
|
||||||
|
dpi.workspace = true
|
||||||
|
rwh_06.workspace = true
|
||||||
|
serde = { workspace = true, optional = true }
|
||||||
|
smol_str.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
winit-core.workspace = true
|
||||||
|
|
||||||
|
# Platform-specific
|
||||||
|
[target.'cfg(target_os = "android")'.dependencies]
|
||||||
|
android-activity.workspace = true
|
||||||
|
ndk.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
winit.workspace = true
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
features = ["serde", "native-activity"]
|
||||||
|
targets = ["aarch64-linux-android"]
|
||||||
1
winit-android/LICENSE
Symbolic link
1
winit-android/LICENSE
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE
|
||||||
1
winit-android/README.md
Symbolic link
1
winit-android/README.md
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../README.md
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::cell::Cell;
|
use std::cell::Cell;
|
||||||
|
use std::fmt;
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
use std::num::{NonZeroU16, NonZeroU32};
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
@@ -9,32 +9,26 @@ use android_activity::input::{InputEvent, KeyAction, Keycode, MotionAction};
|
|||||||
use android_activity::{
|
use android_activity::{
|
||||||
AndroidApp, AndroidAppWaker, ConfigurationRef, InputStatus, MainEvent, Rect,
|
AndroidApp, AndroidAppWaker, ConfigurationRef, InputStatus, MainEvent, Rect,
|
||||||
};
|
};
|
||||||
|
use dpi::{PhysicalInsets, PhysicalPosition, PhysicalSize, Position, Size};
|
||||||
use tracing::{debug, trace, warn};
|
use tracing::{debug, trace, warn};
|
||||||
|
use winit_core::application::ApplicationHandler;
|
||||||
use crate::application::ApplicationHandler;
|
use winit_core::cursor::{Cursor, CustomCursor, CustomCursorSource};
|
||||||
use crate::cursor::Cursor;
|
use winit_core::error::{EventLoopError, NotSupportedError, RequestError};
|
||||||
use crate::dpi::{PhysicalInsets, PhysicalPosition, PhysicalSize, Position, Size};
|
use winit_core::event::{self, DeviceId, FingerId, Force, StartCause, SurfaceSizeWriter};
|
||||||
use crate::error::{EventLoopError, NotSupportedError, RequestError};
|
use winit_core::event_loop::pump_events::PumpStatus;
|
||||||
use crate::event::{self, DeviceId, FingerId, Force, StartCause, SurfaceSizeWriter};
|
use winit_core::event_loop::{
|
||||||
use crate::event_loop::{
|
|
||||||
ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents,
|
ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents,
|
||||||
EventLoopProxy as CoreEventLoopProxy, EventLoopProxyProvider,
|
EventLoopProxy as CoreEventLoopProxy, EventLoopProxyProvider,
|
||||||
OwnedDisplayHandle as CoreOwnedDisplayHandle,
|
OwnedDisplayHandle as CoreOwnedDisplayHandle,
|
||||||
};
|
};
|
||||||
use crate::monitor::MonitorHandle as RootMonitorHandle;
|
use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle};
|
||||||
use crate::platform::pump_events::PumpStatus;
|
use winit_core::window::{
|
||||||
use crate::window::{
|
self, CursorGrabMode, ImeCapabilities, ImePurpose, ImeRequest, ImeRequestError,
|
||||||
self, CursorGrabMode, CustomCursor, CustomCursorSource, Fullscreen, ImePurpose,
|
|
||||||
ResizeDirection, Theme, Window as CoreWindow, WindowAttributes, WindowButtons, WindowId,
|
ResizeDirection, Theme, Window as CoreWindow, WindowAttributes, WindowButtons, WindowId,
|
||||||
WindowLevel,
|
WindowLevel,
|
||||||
};
|
};
|
||||||
|
|
||||||
mod keycodes;
|
use crate::keycodes;
|
||||||
|
|
||||||
pub(crate) use crate::cursor::{
|
|
||||||
NoCustomCursor as PlatformCustomCursor, NoCustomCursor as PlatformCustomCursorSource,
|
|
||||||
};
|
|
||||||
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
|
||||||
|
|
||||||
static HAS_FOCUS: AtomicBool = AtomicBool::new(true);
|
static HAS_FOCUS: AtomicBool = AtomicBool::new(true);
|
||||||
|
|
||||||
@@ -45,16 +39,17 @@ fn min_timeout(a: Option<Duration>, b: Option<Duration>) -> Option<Duration> {
|
|||||||
a.map_or(b, |a_timeout| b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout))))
|
a.map_or(b, |a_timeout| b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout))))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone, Debug)]
|
||||||
struct SharedFlagSetter {
|
struct SharedFlagSetter {
|
||||||
flag: Arc<AtomicBool>,
|
flag: Arc<AtomicBool>,
|
||||||
}
|
}
|
||||||
impl SharedFlagSetter {
|
impl SharedFlagSetter {
|
||||||
pub fn set(&self) -> bool {
|
fn set(&self) -> bool {
|
||||||
self.flag.compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed).is_ok()
|
self.flag.compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed).is_ok()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
struct SharedFlag {
|
struct SharedFlag {
|
||||||
flag: Arc<AtomicBool>,
|
flag: Arc<AtomicBool>,
|
||||||
}
|
}
|
||||||
@@ -64,31 +59,37 @@ struct SharedFlag {
|
|||||||
// we just need to know at the start of a main loop iteration if a redraw
|
// we just need to know at the start of a main loop iteration if a redraw
|
||||||
// was queued and be able to read and clear the state atomically)
|
// was queued and be able to read and clear the state atomically)
|
||||||
impl SharedFlag {
|
impl SharedFlag {
|
||||||
pub fn new() -> Self {
|
fn new() -> Self {
|
||||||
Self { flag: Arc::new(AtomicBool::new(false)) }
|
Self { flag: Arc::new(AtomicBool::new(false)) }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn setter(&self) -> SharedFlagSetter {
|
fn setter(&self) -> SharedFlagSetter {
|
||||||
SharedFlagSetter { flag: self.flag.clone() }
|
SharedFlagSetter { flag: self.flag.clone() }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_and_reset(&self) -> bool {
|
fn get_and_reset(&self) -> bool {
|
||||||
self.flag.swap(false, std::sync::atomic::Ordering::AcqRel)
|
self.flag.swap(false, std::sync::atomic::Ordering::AcqRel)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct RedrawRequester {
|
struct RedrawRequester {
|
||||||
flag: SharedFlagSetter,
|
flag: SharedFlagSetter,
|
||||||
waker: AndroidAppWaker,
|
waker: AndroidAppWaker,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for RedrawRequester {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("RedrawRequester").field("flag", &self.flag).finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl RedrawRequester {
|
impl RedrawRequester {
|
||||||
fn new(flag: &SharedFlag, waker: AndroidAppWaker) -> Self {
|
fn new(flag: &SharedFlag, waker: AndroidAppWaker) -> Self {
|
||||||
RedrawRequester { flag: flag.setter(), waker }
|
RedrawRequester { flag: flag.setter(), waker }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn request_redraw(&self) {
|
fn request_redraw(&self) {
|
||||||
if self.flag.set() {
|
if self.flag.set() {
|
||||||
// Only explicitly try to wake up the main loop when the flag
|
// Only explicitly try to wake up the main loop when the flag
|
||||||
// value changes
|
// value changes
|
||||||
@@ -97,11 +98,9 @@ impl RedrawRequester {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
|
#[derive(Debug)]
|
||||||
pub struct KeyEventExtra {}
|
|
||||||
|
|
||||||
pub struct EventLoop {
|
pub struct EventLoop {
|
||||||
pub(crate) android_app: AndroidApp,
|
pub android_app: AndroidApp,
|
||||||
window_target: ActiveEventLoop,
|
window_target: ActiveEventLoop,
|
||||||
redraw_flag: SharedFlag,
|
redraw_flag: SharedFlag,
|
||||||
loop_running: bool, // Dispatched `NewEvents<Init>`
|
loop_running: bool, // Dispatched `NewEvents<Init>`
|
||||||
@@ -114,9 +113,9 @@ pub struct EventLoop {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
pub(crate) struct PlatformSpecificEventLoopAttributes {
|
pub struct PlatformSpecificEventLoopAttributes {
|
||||||
pub(crate) android_app: Option<AndroidApp>,
|
pub android_app: Option<AndroidApp>,
|
||||||
pub(crate) ignore_volume_keys: bool,
|
pub ignore_volume_keys: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for PlatformSpecificEventLoopAttributes {
|
impl Default for PlatformSpecificEventLoopAttributes {
|
||||||
@@ -129,9 +128,13 @@ impl Default for PlatformSpecificEventLoopAttributes {
|
|||||||
const GLOBAL_WINDOW: WindowId = WindowId::from_raw(0);
|
const GLOBAL_WINDOW: WindowId = WindowId::from_raw(0);
|
||||||
|
|
||||||
impl EventLoop {
|
impl EventLoop {
|
||||||
pub(crate) fn new(
|
pub fn new(attributes: &PlatformSpecificEventLoopAttributes) -> Result<Self, EventLoopError> {
|
||||||
attributes: &PlatformSpecificEventLoopAttributes,
|
static EVENT_LOOP_CREATED: AtomicBool = AtomicBool::new(false);
|
||||||
) -> Result<Self, EventLoopError> {
|
if EVENT_LOOP_CREATED.swap(true, Ordering::Relaxed) {
|
||||||
|
// For better cross-platformness.
|
||||||
|
return Err(EventLoopError::RecreationAttempt);
|
||||||
|
}
|
||||||
|
|
||||||
let android_app = attributes.android_app.as_ref().expect(
|
let android_app = attributes.android_app.as_ref().expect(
|
||||||
"An `AndroidApp` as passed to android_main() is required to create an `EventLoop` on \
|
"An `AndroidApp` as passed to android_main() is required to create an `EventLoop` on \
|
||||||
Android",
|
Android",
|
||||||
@@ -161,7 +164,7 @@ impl EventLoop {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn window_target(&self) -> &dyn RootActiveEventLoop {
|
pub fn window_target(&self) -> &dyn RootActiveEventLoop {
|
||||||
&self.window_target
|
&self.window_target
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -479,7 +482,8 @@ impl EventLoop {
|
|||||||
location: keycodes::to_location(keycode),
|
location: keycodes::to_location(keycode),
|
||||||
repeat: key.repeat_count() > 0,
|
repeat: key.repeat_count() > 0,
|
||||||
text: None,
|
text: None,
|
||||||
platform_specific: KeyEventExtra {},
|
text_with_all_modifiers: None,
|
||||||
|
key_without_modifiers: keycodes::to_logical(key_char, keycode),
|
||||||
},
|
},
|
||||||
is_synthetic: false,
|
is_synthetic: false,
|
||||||
};
|
};
|
||||||
@@ -546,8 +550,6 @@ impl EventLoop {
|
|||||||
if self.exiting() {
|
if self.exiting() {
|
||||||
self.loop_running = false;
|
self.loop_running = false;
|
||||||
|
|
||||||
app.exiting(&self.window_target);
|
|
||||||
|
|
||||||
PumpStatus::Exit(0)
|
PumpStatus::Exit(0)
|
||||||
} else {
|
} else {
|
||||||
PumpStatus::Continue
|
PumpStatus::Continue
|
||||||
@@ -642,6 +644,12 @@ pub struct EventLoopProxy {
|
|||||||
waker: AndroidAppWaker,
|
waker: AndroidAppWaker,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for EventLoopProxy {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("EventLoopProxy").field("wake_up", &self.wake_up).finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl EventLoopProxy {
|
impl EventLoopProxy {
|
||||||
fn new(waker: AndroidAppWaker) -> Self {
|
fn new(waker: AndroidAppWaker) -> Self {
|
||||||
Self { wake_up: AtomicBool::new(false), waker }
|
Self { wake_up: AtomicBool::new(false), waker }
|
||||||
@@ -655,6 +663,7 @@ impl EventLoopProxyProvider for EventLoopProxy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
pub struct ActiveEventLoop {
|
pub struct ActiveEventLoop {
|
||||||
pub(crate) app: AndroidApp,
|
pub(crate) app: AndroidApp,
|
||||||
control_flow: Cell<ControlFlow>,
|
control_flow: Cell<ControlFlow>,
|
||||||
@@ -688,11 +697,11 @@ impl RootActiveEventLoop for ActiveEventLoop {
|
|||||||
Err(NotSupportedError::new("create_custom_cursor is not supported").into())
|
Err(NotSupportedError::new("create_custom_cursor is not supported").into())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn available_monitors(&self) -> Box<dyn Iterator<Item = RootMonitorHandle>> {
|
fn available_monitors(&self) -> Box<dyn Iterator<Item = CoreMonitorHandle>> {
|
||||||
Box::new(std::iter::empty())
|
Box::new(std::iter::empty())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn primary_monitor(&self) -> Option<RootMonitorHandle> {
|
fn primary_monitor(&self) -> Option<CoreMonitorHandle> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -747,8 +756,10 @@ impl rwh_06::HasDisplayHandle for OwnedDisplayHandle {
|
|||||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||||
pub struct PlatformSpecificWindowAttributes;
|
pub struct PlatformSpecificWindowAttributes;
|
||||||
|
|
||||||
pub(crate) struct Window {
|
#[derive(Debug)]
|
||||||
|
pub struct Window {
|
||||||
app: AndroidApp,
|
app: AndroidApp,
|
||||||
|
ime_capabilities: Mutex<Option<ImeCapabilities>>,
|
||||||
redraw_requester: RedrawRequester,
|
redraw_requester: RedrawRequester,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -759,14 +770,18 @@ impl Window {
|
|||||||
) -> Result<Self, RequestError> {
|
) -> Result<Self, RequestError> {
|
||||||
// FIXME this ignores requested window attributes
|
// FIXME this ignores requested window attributes
|
||||||
|
|
||||||
Ok(Self { app: el.app.clone(), redraw_requester: el.redraw_requester.clone() })
|
Ok(Self {
|
||||||
|
app: el.app.clone(),
|
||||||
|
ime_capabilities: Default::default(),
|
||||||
|
redraw_requester: el.redraw_requester.clone(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn config(&self) -> ConfigurationRef {
|
pub(crate) fn config(&self) -> ConfigurationRef {
|
||||||
self.app.config()
|
self.app.config()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn content_rect(&self) -> Rect {
|
pub(crate) fn content_rect(&self) -> Rect {
|
||||||
self.app.content_rect()
|
self.app.content_rect()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -811,15 +826,15 @@ impl CoreWindow for Window {
|
|||||||
GLOBAL_WINDOW
|
GLOBAL_WINDOW
|
||||||
}
|
}
|
||||||
|
|
||||||
fn primary_monitor(&self) -> Option<RootMonitorHandle> {
|
fn primary_monitor(&self) -> Option<CoreMonitorHandle> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
fn available_monitors(&self) -> Box<dyn Iterator<Item = RootMonitorHandle>> {
|
fn available_monitors(&self) -> Box<dyn Iterator<Item = CoreMonitorHandle>> {
|
||||||
Box::new(std::iter::empty())
|
Box::new(std::iter::empty())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn current_monitor(&self) -> Option<RootMonitorHandle> {
|
fn current_monitor(&self) -> Option<CoreMonitorHandle> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -923,16 +938,37 @@ impl CoreWindow for Window {
|
|||||||
|
|
||||||
fn set_window_level(&self, _level: WindowLevel) {}
|
fn set_window_level(&self, _level: WindowLevel) {}
|
||||||
|
|
||||||
fn set_window_icon(&self, _window_icon: Option<crate::icon::Icon>) {}
|
fn set_window_icon(&self, _window_icon: Option<winit_core::icon::Icon>) {}
|
||||||
|
|
||||||
fn set_ime_cursor_area(&self, _position: Position, _size: Size) {}
|
fn set_ime_cursor_area(&self, _position: Position, _size: Size) {}
|
||||||
|
|
||||||
fn set_ime_allowed(&self, allowed: bool) {
|
fn request_ime_update(&self, request: ImeRequest) -> Result<(), ImeRequestError> {
|
||||||
if allowed {
|
let mut current_caps = self.ime_capabilities.lock().unwrap();
|
||||||
self.app.show_soft_input(true);
|
match request {
|
||||||
} else {
|
ImeRequest::Enable(enable) => {
|
||||||
self.app.hide_soft_input(true);
|
let (capabilities, _) = enable.into_raw();
|
||||||
|
if current_caps.is_some() {
|
||||||
|
return Err(ImeRequestError::AlreadyEnabled);
|
||||||
|
}
|
||||||
|
*current_caps = Some(capabilities);
|
||||||
|
self.app.show_soft_input(true);
|
||||||
|
},
|
||||||
|
ImeRequest::Update(_) => {
|
||||||
|
if current_caps.is_none() {
|
||||||
|
return Err(ImeRequestError::NotEnabled);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
ImeRequest::Disable => {
|
||||||
|
*current_caps = None;
|
||||||
|
self.app.hide_soft_input(true);
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ime_capabilities(&self) -> Option<ImeCapabilities> {
|
||||||
|
*self.ime_capabilities.lock().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_ime_purpose(&self, _purpose: ImePurpose) {}
|
fn set_ime_purpose(&self, _purpose: ImePurpose) {}
|
||||||
@@ -995,62 +1031,6 @@ impl CoreWindow for Window {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default, Clone, Debug)]
|
|
||||||
pub struct OsError;
|
|
||||||
|
|
||||||
use std::fmt::{self, Display, Formatter};
|
|
||||||
impl Display for OsError {
|
|
||||||
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> {
|
|
||||||
write!(fmt, "Android OS Error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub struct MonitorHandle;
|
|
||||||
|
|
||||||
impl MonitorHandle {
|
|
||||||
pub fn name(&self) -> Option<String> {
|
|
||||||
unreachable!()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn position(&self) -> Option<PhysicalPosition<i32>> {
|
|
||||||
unreachable!()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn scale_factor(&self) -> f64 {
|
|
||||||
unreachable!()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn current_video_mode(&self) -> Option<VideoModeHandle> {
|
|
||||||
unreachable!()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn video_modes(&self) -> std::iter::Empty<VideoModeHandle> {
|
|
||||||
unreachable!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
|
||||||
pub struct VideoModeHandle;
|
|
||||||
|
|
||||||
impl VideoModeHandle {
|
|
||||||
pub fn size(&self) -> PhysicalSize<u32> {
|
|
||||||
unreachable!()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn bit_depth(&self) -> Option<NonZeroU16> {
|
|
||||||
unreachable!()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refresh_rate_millihertz(&self) -> Option<NonZeroU32> {
|
|
||||||
unreachable!()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn monitor(&self) -> MonitorHandle {
|
|
||||||
unreachable!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn screen_size(app: &AndroidApp) -> PhysicalSize<u32> {
|
fn screen_size(app: &AndroidApp) -> PhysicalSize<u32> {
|
||||||
if let Some(native_window) = app.native_window() {
|
if let Some(native_window) = app.native_window() {
|
||||||
PhysicalSize::new(native_window.width() as _, native_window.height() as _)
|
PhysicalSize::new(native_window.width() as _, native_window.height() as _)
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
use android_activity::input::{KeyAction, KeyEvent, KeyMapChar, Keycode};
|
use android_activity::input::{KeyAction, KeyEvent, KeyMapChar, Keycode};
|
||||||
use android_activity::AndroidApp;
|
use android_activity::AndroidApp;
|
||||||
|
use winit_core::keyboard::{
|
||||||
use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey};
|
Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey,
|
||||||
|
};
|
||||||
|
|
||||||
pub fn to_physical_key(keycode: Keycode) -> PhysicalKey {
|
pub fn to_physical_key(keycode: Keycode) -> PhysicalKey {
|
||||||
PhysicalKey::Code(match keycode {
|
PhysicalKey::Code(match keycode {
|
||||||
@@ -143,8 +144,8 @@ pub fn to_physical_key(keycode: Keycode) -> PhysicalKey {
|
|||||||
Keycode::AltLeft => KeyCode::AltLeft,
|
Keycode::AltLeft => KeyCode::AltLeft,
|
||||||
Keycode::AltRight => KeyCode::AltRight,
|
Keycode::AltRight => KeyCode::AltRight,
|
||||||
|
|
||||||
Keycode::MetaLeft => KeyCode::SuperLeft,
|
Keycode::MetaLeft => KeyCode::MetaLeft,
|
||||||
Keycode::MetaRight => KeyCode::SuperRight,
|
Keycode::MetaRight => KeyCode::MetaRight,
|
||||||
|
|
||||||
Keycode::LeftBracket => KeyCode::BracketLeft,
|
Keycode::LeftBracket => KeyCode::BracketLeft,
|
||||||
Keycode::RightBracket => KeyCode::BracketRight,
|
Keycode::RightBracket => KeyCode::BracketRight,
|
||||||
@@ -309,7 +310,7 @@ pub fn to_logical(key_char: Option<KeyMapChar>, keycode: Keycode) -> Key {
|
|||||||
ShiftLeft => Key::Named(NamedKey::Shift),
|
ShiftLeft => Key::Named(NamedKey::Shift),
|
||||||
ShiftRight => Key::Named(NamedKey::Shift),
|
ShiftRight => Key::Named(NamedKey::Shift),
|
||||||
Tab => Key::Named(NamedKey::Tab),
|
Tab => Key::Named(NamedKey::Tab),
|
||||||
Space => Key::Named(NamedKey::Space),
|
Space => Key::Character(" ".into()),
|
||||||
Sym => Key::Named(NamedKey::Symbol),
|
Sym => Key::Named(NamedKey::Symbol),
|
||||||
Explorer => Key::Named(NamedKey::LaunchWebBrowser),
|
Explorer => Key::Named(NamedKey::LaunchWebBrowser),
|
||||||
Envelope => Key::Named(NamedKey::LaunchMail),
|
Envelope => Key::Named(NamedKey::LaunchMail),
|
||||||
@@ -340,8 +341,8 @@ pub fn to_logical(key_char: Option<KeyMapChar>, keycode: Keycode) -> Key {
|
|||||||
CtrlRight => Key::Named(NamedKey::Control),
|
CtrlRight => Key::Named(NamedKey::Control),
|
||||||
CapsLock => Key::Named(NamedKey::CapsLock),
|
CapsLock => Key::Named(NamedKey::CapsLock),
|
||||||
ScrollLock => Key::Named(NamedKey::ScrollLock),
|
ScrollLock => Key::Named(NamedKey::ScrollLock),
|
||||||
MetaLeft => Key::Named(NamedKey::Super),
|
MetaLeft => Key::Named(NamedKey::Meta),
|
||||||
MetaRight => Key::Named(NamedKey::Super),
|
MetaRight => Key::Named(NamedKey::Meta),
|
||||||
Function => Key::Named(NamedKey::Fn),
|
Function => Key::Named(NamedKey::Fn),
|
||||||
Sysrq => Key::Named(NamedKey::PrintScreen),
|
Sysrq => Key::Named(NamedKey::PrintScreen),
|
||||||
Break => Key::Named(NamedKey::Pause),
|
Break => Key::Named(NamedKey::Pause),
|
||||||
@@ -62,17 +62,26 @@
|
|||||||
//! If your application is currently based on `NativeActivity` via the `ndk-glue` crate and building
|
//! If your application is currently based on `NativeActivity` via the `ndk-glue` crate and building
|
||||||
//! with `cargo apk`, then the minimal changes would be:
|
//! with `cargo apk`, then the minimal changes would be:
|
||||||
//! 1. Remove `ndk-glue` from your `Cargo.toml`
|
//! 1. Remove `ndk-glue` from your `Cargo.toml`
|
||||||
//! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.30.5",
|
//! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.30.12",
|
||||||
//! features = [ "android-native-activity" ] }`
|
//! features = [ "android-native-activity" ] }`
|
||||||
//! 3. Add an `android_main` entrypoint (as above), instead of using the '`[ndk_glue::main]` proc
|
//! 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
|
//! macro from `ndk-macros` (optionally add a dependency on `android_logger` and initialize
|
||||||
//! logging as above).
|
//! logging as above).
|
||||||
//! 4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your
|
//! 4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your
|
||||||
//! event loop (as shown above).
|
//! event loop (as shown above).
|
||||||
|
#![cfg(target_os = "android")]
|
||||||
|
|
||||||
|
mod event_loop;
|
||||||
|
mod keycodes;
|
||||||
|
|
||||||
|
use winit_core::event_loop::ActiveEventLoop as CoreActiveEventLoop;
|
||||||
|
use winit_core::window::Window as CoreWindow;
|
||||||
|
|
||||||
use self::activity::{AndroidApp, ConfigurationRef, Rect};
|
use self::activity::{AndroidApp, ConfigurationRef, Rect};
|
||||||
use crate::event_loop::{ActiveEventLoop, EventLoop, EventLoopBuilder};
|
pub use crate::event_loop::{
|
||||||
use crate::window::{Window, WindowAttributes};
|
ActiveEventLoop, EventLoop, EventLoopProxy, PlatformSpecificEventLoopAttributes,
|
||||||
|
PlatformSpecificWindowAttributes, Window,
|
||||||
|
};
|
||||||
|
|
||||||
/// Additional methods on [`EventLoop`] that are specific to Android.
|
/// Additional methods on [`EventLoop`] that are specific to Android.
|
||||||
pub trait EventLoopExtAndroid {
|
pub trait EventLoopExtAndroid {
|
||||||
@@ -80,12 +89,6 @@ pub trait EventLoopExtAndroid {
|
|||||||
fn android_app(&self) -> &AndroidApp;
|
fn android_app(&self) -> &AndroidApp;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventLoopExtAndroid for EventLoop {
|
|
||||||
fn android_app(&self) -> &AndroidApp {
|
|
||||||
&self.event_loop.android_app
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on [`ActiveEventLoop`] that are specific to Android.
|
/// Additional methods on [`ActiveEventLoop`] that are specific to Android.
|
||||||
pub trait ActiveEventLoopExtAndroid {
|
pub trait ActiveEventLoopExtAndroid {
|
||||||
/// Get the [`AndroidApp`] which was used to create this event loop.
|
/// Get the [`AndroidApp`] which was used to create this event loop.
|
||||||
@@ -99,31 +102,25 @@ pub trait WindowExtAndroid {
|
|||||||
fn config(&self) -> ConfigurationRef;
|
fn config(&self) -> ConfigurationRef;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowExtAndroid for dyn Window + '_ {
|
impl WindowExtAndroid for dyn CoreWindow + '_ {
|
||||||
fn content_rect(&self) -> Rect {
|
fn content_rect(&self) -> Rect {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<Window>().unwrap();
|
||||||
window.content_rect()
|
window.content_rect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn config(&self) -> ConfigurationRef {
|
fn config(&self) -> ConfigurationRef {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<Window>().unwrap();
|
||||||
window.config()
|
window.config()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ActiveEventLoopExtAndroid for dyn ActiveEventLoop + '_ {
|
impl ActiveEventLoopExtAndroid for dyn CoreActiveEventLoop + '_ {
|
||||||
fn android_app(&self) -> &AndroidApp {
|
fn android_app(&self) -> &AndroidApp {
|
||||||
let event_loop =
|
let event_loop = self.cast_ref::<ActiveEventLoop>().unwrap();
|
||||||
self.as_any().downcast_ref::<crate::platform_impl::ActiveEventLoop>().unwrap();
|
|
||||||
&event_loop.app
|
&event_loop.app
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Additional methods on [`WindowAttributes`] that are specific to Android.
|
|
||||||
pub trait WindowAttributesExtAndroid {}
|
|
||||||
|
|
||||||
impl WindowAttributesExtAndroid for WindowAttributes {}
|
|
||||||
|
|
||||||
pub trait EventLoopBuilderExtAndroid {
|
pub trait EventLoopBuilderExtAndroid {
|
||||||
/// Associates the [`AndroidApp`] that was passed to `android_main()` with the event loop
|
/// Associates the [`AndroidApp`] that was passed to `android_main()` with the event loop
|
||||||
///
|
///
|
||||||
@@ -136,18 +133,6 @@ pub trait EventLoopBuilderExtAndroid {
|
|||||||
fn handle_volume_keys(&mut self) -> &mut Self;
|
fn handle_volume_keys(&mut self) -> &mut Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventLoopBuilderExtAndroid for EventLoopBuilder {
|
|
||||||
fn with_android_app(&mut self, app: AndroidApp) -> &mut Self {
|
|
||||||
self.platform_specific.android_app = Some(app);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn handle_volume_keys(&mut self) -> &mut Self {
|
|
||||||
self.platform_specific.ignore_volume_keys = false;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Re-export of the `android_activity` API
|
/// Re-export of the `android_activity` API
|
||||||
///
|
///
|
||||||
/// Winit re-exports the `android_activity` API for convenience so that most
|
/// Winit re-exports the `android_activity` API for convenience so that most
|
||||||
@@ -176,16 +161,5 @@ pub mod activity {
|
|||||||
// feature enabled, so we avoid inlining it so that they're forced to view
|
// feature enabled, so we avoid inlining it so that they're forced to view
|
||||||
// it on the crate's own docs.rs page.
|
// it on the crate's own docs.rs page.
|
||||||
#[doc(no_inline)]
|
#[doc(no_inline)]
|
||||||
#[cfg(android_platform)]
|
|
||||||
pub use android_activity::*;
|
pub use android_activity::*;
|
||||||
|
|
||||||
#[cfg(not(android_platform))]
|
|
||||||
#[doc(hidden)]
|
|
||||||
pub struct Rect;
|
|
||||||
#[cfg(not(android_platform))]
|
|
||||||
#[doc(hidden)]
|
|
||||||
pub struct ConfigurationRef;
|
|
||||||
#[cfg(not(android_platform))]
|
|
||||||
#[doc(hidden)]
|
|
||||||
pub struct AndroidApp;
|
|
||||||
}
|
}
|
||||||
116
winit-appkit/Cargo.toml
Normal file
116
winit-appkit/Cargo.toml
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
[package]
|
||||||
|
description = "Winit's Appkit / macOS backend"
|
||||||
|
documentation = "https://docs.rs/winit-appkit"
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
name = "winit-appkit"
|
||||||
|
repository.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
version.workspace = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
serde = ["dep:serde", "bitflags/serde", "smol_str/serde", "dpi/serde"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
bitflags.workspace = true
|
||||||
|
dpi.workspace = true
|
||||||
|
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
|
||||||
|
[target.'cfg(target_vendor = "apple")'.dependencies]
|
||||||
|
block2.workspace = true
|
||||||
|
dispatch2 = { workspace = true, features = ["std", "objc2"] }
|
||||||
|
objc2.workspace = true
|
||||||
|
objc2-app-kit = { workspace = true, features = [
|
||||||
|
"std",
|
||||||
|
"objc2-core-foundation",
|
||||||
|
"NSAppearance",
|
||||||
|
"NSApplication",
|
||||||
|
"NSBitmapImageRep",
|
||||||
|
"NSButton",
|
||||||
|
"NSColor",
|
||||||
|
"NSControl",
|
||||||
|
"NSCursor",
|
||||||
|
"NSDragging",
|
||||||
|
"NSEvent",
|
||||||
|
"NSGraphics",
|
||||||
|
"NSGraphicsContext",
|
||||||
|
"NSImage",
|
||||||
|
"NSImageRep",
|
||||||
|
"NSMenu",
|
||||||
|
"NSMenuItem",
|
||||||
|
"NSOpenGLView",
|
||||||
|
"NSPanel",
|
||||||
|
"NSPasteboard",
|
||||||
|
"NSResponder",
|
||||||
|
"NSRunningApplication",
|
||||||
|
"NSScreen",
|
||||||
|
"NSTextInputClient",
|
||||||
|
"NSTextInputContext",
|
||||||
|
"NSToolbar",
|
||||||
|
"NSView",
|
||||||
|
"NSWindow",
|
||||||
|
"NSWindowScripting",
|
||||||
|
"NSWindowTabGroup",
|
||||||
|
] }
|
||||||
|
objc2-core-foundation = { workspace = true, features = [
|
||||||
|
"std",
|
||||||
|
"block2",
|
||||||
|
"CFBase",
|
||||||
|
"CFCGTypes",
|
||||||
|
"CFData",
|
||||||
|
"CFRunLoop",
|
||||||
|
"CFString",
|
||||||
|
"CFUUID",
|
||||||
|
] }
|
||||||
|
objc2-core-graphics = { workspace = true, features = [
|
||||||
|
"std",
|
||||||
|
"libc",
|
||||||
|
"CGDirectDisplay",
|
||||||
|
"CGDisplayConfiguration",
|
||||||
|
"CGDisplayFade",
|
||||||
|
"CGError",
|
||||||
|
"CGRemoteOperation",
|
||||||
|
"CGWindowLevel",
|
||||||
|
] }
|
||||||
|
objc2-core-video = { workspace = true, features = [
|
||||||
|
"std",
|
||||||
|
"objc2-core-graphics",
|
||||||
|
"CVBase",
|
||||||
|
"CVReturn",
|
||||||
|
"CVDisplayLink",
|
||||||
|
] }
|
||||||
|
objc2-foundation = { workspace = true, features = [
|
||||||
|
"std",
|
||||||
|
"block2",
|
||||||
|
"objc2-core-foundation",
|
||||||
|
"NSArray",
|
||||||
|
"NSAttributedString",
|
||||||
|
"NSData",
|
||||||
|
"NSDictionary",
|
||||||
|
"NSDistributedNotificationCenter",
|
||||||
|
"NSEnumerator",
|
||||||
|
"NSGeometry",
|
||||||
|
"NSKeyValueObserving",
|
||||||
|
"NSNotification",
|
||||||
|
"NSObjCRuntime",
|
||||||
|
"NSOperation",
|
||||||
|
"NSPathUtilities",
|
||||||
|
"NSProcessInfo",
|
||||||
|
"NSRunLoop",
|
||||||
|
"NSString",
|
||||||
|
"NSThread",
|
||||||
|
"NSValue",
|
||||||
|
] }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
winit.workspace = true
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
all-features = true
|
||||||
|
targets = ["aarch64-apple-darwin", "x86_64-apple-darwin"]
|
||||||
1
winit-appkit/LICENSE
Symbolic link
1
winit-appkit/LICENSE
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE
|
||||||
1
winit-appkit/README.md
Symbolic link
1
winit-appkit/README.md
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../README.md
|
||||||
188
winit-appkit/src/app.rs
Normal file
188
winit-appkit/src/app.rs
Normal file
@@ -0,0 +1,188 @@
|
|||||||
|
#![allow(clippy::unnecessary_cast)]
|
||||||
|
|
||||||
|
use std::cell::Cell;
|
||||||
|
use std::mem;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
|
use dispatch2::MainThreadBound;
|
||||||
|
use objc2::runtime::{Imp, Sel};
|
||||||
|
use objc2::sel;
|
||||||
|
use objc2_app_kit::{NSApplication, NSEvent, NSEventModifierFlags, NSEventType};
|
||||||
|
use objc2_foundation::MainThreadMarker;
|
||||||
|
use winit_core::event::{DeviceEvent, ElementState};
|
||||||
|
|
||||||
|
use super::app_state::AppState;
|
||||||
|
|
||||||
|
type SendEvent = extern "C-unwind" fn(&NSApplication, Sel, &NSEvent);
|
||||||
|
|
||||||
|
static ORIGINAL: MainThreadBound<Cell<Option<SendEvent>>> = {
|
||||||
|
// SAFETY: Creating in a `const` context, where there is no concept of the main thread.
|
||||||
|
MainThreadBound::new(Cell::new(None), unsafe { MainThreadMarker::new_unchecked() })
|
||||||
|
};
|
||||||
|
|
||||||
|
extern "C-unwind" fn send_event(app: &NSApplication, sel: Sel, event: &NSEvent) {
|
||||||
|
let mtm = MainThreadMarker::from(app);
|
||||||
|
|
||||||
|
// Normally, holding Cmd + any key never sends us a `keyUp` event for that key.
|
||||||
|
// Overriding `sendEvent:` fixes that. (https://stackoverflow.com/a/15294196)
|
||||||
|
// Fun fact: Firefox still has this bug! (https://bugzilla.mozilla.org/show_bug.cgi?id=1299553)
|
||||||
|
//
|
||||||
|
// For posterity, there are some undocumented event types
|
||||||
|
// (https://github.com/servo/cocoa-rs/issues/155)
|
||||||
|
// but that doesn't really matter here.
|
||||||
|
let event_type = unsafe { event.r#type() };
|
||||||
|
let modifier_flags = unsafe { event.modifierFlags() };
|
||||||
|
if event_type == NSEventType::KeyUp && modifier_flags.contains(NSEventModifierFlags::Command) {
|
||||||
|
if let Some(key_window) = app.keyWindow() {
|
||||||
|
key_window.sendEvent(event);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Events are generally scoped to the window level, so the best way
|
||||||
|
// to get device events is to listen for them on NSApplication.
|
||||||
|
let app_state = AppState::get(mtm);
|
||||||
|
maybe_dispatch_device_event(&app_state, event);
|
||||||
|
|
||||||
|
let original = ORIGINAL.get(mtm).get().expect("no existing sendEvent: handler set");
|
||||||
|
original(app, sel, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Override the [`sendEvent:`][NSApplication::sendEvent] method on the given application class.
|
||||||
|
///
|
||||||
|
/// The previous implementation created a subclass of [`NSApplication`], however we would like to
|
||||||
|
/// give the user full control over their `NSApplication`, so we override the method here using
|
||||||
|
/// method swizzling instead.
|
||||||
|
///
|
||||||
|
/// This _should_ also allow two versions of Winit to exist in the same application.
|
||||||
|
///
|
||||||
|
/// See the following links for more info on method swizzling:
|
||||||
|
/// - <https://nshipster.com/method-swizzling/>
|
||||||
|
/// - <https://spin.atomicobject.com/method-swizzling-objective-c/>
|
||||||
|
/// - <https://web.archive.org/web/20130308110627/http://cocoadev.com/wiki/MethodSwizzling>
|
||||||
|
///
|
||||||
|
/// NOTE: This function assumes that the passed in application object is the one returned from
|
||||||
|
/// [`NSApplication::sharedApplication`], i.e. the one and only global shared application object.
|
||||||
|
/// For testing though, we allow it to be a different object.
|
||||||
|
pub(crate) fn override_send_event(global_app: &NSApplication) {
|
||||||
|
let mtm = MainThreadMarker::from(global_app);
|
||||||
|
let class = global_app.class();
|
||||||
|
|
||||||
|
let method =
|
||||||
|
class.instance_method(sel!(sendEvent:)).expect("NSApplication must have sendEvent: method");
|
||||||
|
|
||||||
|
// SAFETY: Converting our `sendEvent:` implementation to an IMP.
|
||||||
|
let overridden = unsafe { mem::transmute::<SendEvent, Imp>(send_event) };
|
||||||
|
|
||||||
|
// If we've already overridden the method, don't do anything.
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// SAFETY: Our implementation has:
|
||||||
|
// 1. The same signature as `sendEvent:`.
|
||||||
|
// 2. Does not impose extra safety requirements on callers.
|
||||||
|
let original = unsafe { method.set_implementation(overridden) };
|
||||||
|
|
||||||
|
// SAFETY: This is the actual signature of `sendEvent:`.
|
||||||
|
let original = unsafe { mem::transmute::<Imp, SendEvent>(original) };
|
||||||
|
|
||||||
|
// NOTE: If NSApplication was safe to use from multiple threads, then this would potentially be
|
||||||
|
// a (checked) race-condition, since one could call `sendEvent:` before the original had been
|
||||||
|
// stored here.
|
||||||
|
//
|
||||||
|
// It is only usable from the main thread, however, so we're good!
|
||||||
|
ORIGINAL.get(mtm).set(Some(original));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn maybe_dispatch_device_event(app_state: &Rc<AppState>, event: &NSEvent) {
|
||||||
|
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 = 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| {
|
||||||
|
app.device_event(event_loop, None, DeviceEvent::PointerMotion {
|
||||||
|
delta: (delta_x, delta_y),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
NSEventType::LeftMouseDown | NSEventType::RightMouseDown | NSEventType::OtherMouseDown => {
|
||||||
|
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,
|
||||||
|
state: ElementState::Pressed,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
NSEventType::LeftMouseUp | NSEventType::RightMouseUp | NSEventType::OtherMouseUp => {
|
||||||
|
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,
|
||||||
|
state: ElementState::Released,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use objc2::rc::Retained;
|
||||||
|
use objc2::{define_class, msg_send, ClassType};
|
||||||
|
use objc2_app_kit::NSResponder;
|
||||||
|
use objc2_foundation::NSObject;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_override() {
|
||||||
|
// FIXME(madsmtm): Ensure this always runs (maybe use cargo-nextest or `--test-threads=1`?)
|
||||||
|
let Some(mtm) = MainThreadMarker::new() else { return };
|
||||||
|
|
||||||
|
// Create a new application, without making it the shared application.
|
||||||
|
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.
|
||||||
|
// unsafe {
|
||||||
|
// let event = super::super::event::dummy_event().unwrap();
|
||||||
|
// app.sendEvent(&event)
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_custom_class() {
|
||||||
|
let Some(_mtm) = MainThreadMarker::new() else { return };
|
||||||
|
|
||||||
|
define_class!(
|
||||||
|
#[unsafe(super(NSApplication, NSResponder, NSObject))]
|
||||||
|
#[name = "TestApplication"]
|
||||||
|
pub(super) struct TestApplication;
|
||||||
|
|
||||||
|
impl TestApplication {
|
||||||
|
#[unsafe(method(sendEvent:))]
|
||||||
|
fn send_event(&self, _event: &NSEvent) {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
let app: Retained<TestApplication> = unsafe { msg_send![TestApplication::class(), new] };
|
||||||
|
override_send_event(&app);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,21 +1,23 @@
|
|||||||
use std::cell::{Cell, OnceCell, RefCell};
|
use std::cell::{Cell, OnceCell, RefCell};
|
||||||
use std::mem;
|
use std::mem;
|
||||||
use std::rc::{Rc, Weak};
|
use std::rc::Rc;
|
||||||
use std::sync::atomic::Ordering as AtomicOrdering;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use dispatch2::MainThreadBound;
|
||||||
|
use objc2::MainThreadMarker;
|
||||||
use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy, NSRunningApplication};
|
use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy, NSRunningApplication};
|
||||||
use objc2_foundation::{MainThreadMarker, NSNotification};
|
use objc2_foundation::NSNotification;
|
||||||
|
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::super::event_handler::EventHandler;
|
use super::event_loop::{notify_windows_of_exit, stop_app_immediately, ActiveEventLoop};
|
||||||
use super::event_loop::{stop_app_immediately, ActiveEventLoop, EventLoopProxy, PanicInfo};
|
|
||||||
use super::menu;
|
use super::menu;
|
||||||
use super::observer::{EventLoopWaker, RunLoop};
|
use super::observer::{EventLoopWaker, RunLoop};
|
||||||
use crate::application::ApplicationHandler;
|
|
||||||
use crate::event::{StartCause, WindowEvent};
|
|
||||||
use crate::event_loop::ControlFlow;
|
|
||||||
use crate::window::WindowId;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub(super) struct AppState {
|
pub(super) struct AppState {
|
||||||
@@ -45,22 +47,10 @@ pub(super) struct AppState {
|
|||||||
// as such should be careful to not add fields that, in turn, strongly reference those.
|
// as such should be careful to not add fields that, in turn, strongly reference those.
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO(madsmtm): Use `MainThreadBound` once that is possible in `static`s.
|
// SAFETY: Creating `MainThreadBound` in a `const` context, where there is no concept of the
|
||||||
struct StaticMainThreadBound<T>(T);
|
|
||||||
|
|
||||||
impl<T> StaticMainThreadBound<T> {
|
|
||||||
const fn get(&self, _mtm: MainThreadMarker) -> &T {
|
|
||||||
&self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe impl<T> Send for StaticMainThreadBound<T> {}
|
|
||||||
unsafe impl<T> Sync for StaticMainThreadBound<T> {}
|
|
||||||
|
|
||||||
// SAFETY: Creating `StaticMainThreadBound` in a `const` context, where there is no concept of the
|
|
||||||
// main thread.
|
// main thread.
|
||||||
static GLOBAL: StaticMainThreadBound<OnceCell<Rc<AppState>>> =
|
static GLOBAL: MainThreadBound<OnceCell<Rc<AppState>>> =
|
||||||
StaticMainThreadBound(OnceCell::new());
|
MainThreadBound::new(OnceCell::new(), unsafe { MainThreadMarker::new_unchecked() });
|
||||||
|
|
||||||
impl AppState {
|
impl AppState {
|
||||||
pub(super) fn setup_global(
|
pub(super) fn setup_global(
|
||||||
@@ -68,14 +58,18 @@ impl AppState {
|
|||||||
activation_policy: Option<NSApplicationActivationPolicy>,
|
activation_policy: Option<NSApplicationActivationPolicy>,
|
||||||
default_menu: bool,
|
default_menu: bool,
|
||||||
activate_ignoring_other_apps: bool,
|
activate_ignoring_other_apps: bool,
|
||||||
) -> Rc<Self> {
|
) -> Option<Rc<Self>> {
|
||||||
let this = Rc::new(AppState {
|
let event_loop_proxy = Arc::new(EventLoopProxy::new(mtm, move || {
|
||||||
|
Self::get(mtm).with_handler(|app, event_loop| app.proxy_wake_up(event_loop));
|
||||||
|
}));
|
||||||
|
|
||||||
|
let this = Rc::new(Self {
|
||||||
mtm,
|
mtm,
|
||||||
activation_policy,
|
activation_policy,
|
||||||
event_loop_proxy: Arc::new(EventLoopProxy::new()),
|
|
||||||
default_menu,
|
default_menu,
|
||||||
activate_ignoring_other_apps,
|
activate_ignoring_other_apps,
|
||||||
run_loop: RunLoop::main(mtm),
|
run_loop: RunLoop::main(mtm),
|
||||||
|
event_loop_proxy,
|
||||||
event_handler: EventHandler::new(),
|
event_handler: EventHandler::new(),
|
||||||
stop_on_launch: Cell::new(false),
|
stop_on_launch: Cell::new(false),
|
||||||
stop_before_wait: Cell::new(false),
|
stop_before_wait: Cell::new(false),
|
||||||
@@ -91,8 +85,7 @@ impl AppState {
|
|||||||
pending_redraw: RefCell::new(vec![]),
|
pending_redraw: RefCell::new(vec![]),
|
||||||
});
|
});
|
||||||
|
|
||||||
GLOBAL.get(mtm).set(this.clone()).expect("application state can only be set once");
|
GLOBAL.get(mtm).set(this.clone()).ok().and(Some(this))
|
||||||
this
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get(mtm: MainThreadMarker) -> Rc<Self> {
|
pub fn get(mtm: MainThreadMarker) -> Rc<Self> {
|
||||||
@@ -162,7 +155,9 @@ impl AppState {
|
|||||||
|
|
||||||
pub fn will_terminate(self: &Rc<Self>, _notification: &NSNotification) {
|
pub fn will_terminate(self: &Rc<Self>, _notification: &NSNotification) {
|
||||||
trace_scope!("NSApplicationWillTerminateNotification");
|
trace_scope!("NSApplicationWillTerminateNotification");
|
||||||
// TODO: Notify every window that it will be destroyed, like done in iOS?
|
let app = NSApplication::sharedApplication(self.mtm);
|
||||||
|
notify_windows_of_exit(&app);
|
||||||
|
self.event_handler.terminate();
|
||||||
self.internal_exit();
|
self.internal_exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -170,10 +165,10 @@ impl AppState {
|
|||||||
/// of the given closure.
|
/// of the given closure.
|
||||||
pub fn set_event_handler<R>(
|
pub fn set_event_handler<R>(
|
||||||
&self,
|
&self,
|
||||||
handler: &mut dyn ApplicationHandler,
|
handler: impl ApplicationHandler,
|
||||||
closure: impl FnOnce() -> R,
|
closure: impl FnOnce() -> R,
|
||||||
) -> R {
|
) -> R {
|
||||||
self.event_handler.set(handler, closure)
|
self.event_handler.set(Box::new(handler), closure)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn event_loop_proxy(&self) -> &Arc<EventLoopProxy> {
|
pub fn event_loop_proxy(&self) -> &Arc<EventLoopProxy> {
|
||||||
@@ -208,10 +203,6 @@ impl AppState {
|
|||||||
/// NOTE: that if the `NSApplication` has been launched then that state is preserved,
|
/// NOTE: that if the `NSApplication` has been launched then that state is preserved,
|
||||||
/// and we won't need to re-launch the app if subsequent EventLoops are run.
|
/// and we won't need to re-launch the app if subsequent EventLoops are run.
|
||||||
pub fn internal_exit(self: &Rc<Self>) {
|
pub fn internal_exit(self: &Rc<Self>) {
|
||||||
self.with_handler(|app, event_loop| {
|
|
||||||
app.exiting(event_loop);
|
|
||||||
});
|
|
||||||
|
|
||||||
self.set_is_running(false);
|
self.set_is_running(false);
|
||||||
self.set_stop_on_redraw(false);
|
self.set_stop_on_redraw(false);
|
||||||
self.set_stop_before_wait(false);
|
self.set_stop_before_wait(false);
|
||||||
@@ -317,13 +308,9 @@ impl AppState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Called by RunLoopObserver after finishing waiting for new events
|
// Called by RunLoopObserver after finishing waiting for new events
|
||||||
pub fn wakeup(self: &Rc<Self>, panic_info: Weak<PanicInfo>) {
|
pub fn wakeup(self: &Rc<Self>) {
|
||||||
let panic_info = panic_info
|
|
||||||
.upgrade()
|
|
||||||
.expect("The panic info must exist here. This failure indicates a developer error.");
|
|
||||||
|
|
||||||
// Return when in event handler due to https://github.com/rust-windowing/winit/issues/1779
|
// Return when in event handler due to https://github.com/rust-windowing/winit/issues/1779
|
||||||
if panic_info.is_panicking() || !self.event_handler.ready() || !self.is_running() {
|
if !self.event_handler.ready() || !self.is_running() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -349,22 +336,14 @@ impl AppState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Called by RunLoopObserver before waiting for new events
|
// Called by RunLoopObserver before waiting for new events
|
||||||
pub fn cleared(self: &Rc<Self>, panic_info: Weak<PanicInfo>) {
|
pub fn cleared(self: &Rc<Self>) {
|
||||||
let panic_info = panic_info
|
|
||||||
.upgrade()
|
|
||||||
.expect("The panic info must exist here. This failure indicates a developer error.");
|
|
||||||
|
|
||||||
// Return when in event handler due to https://github.com/rust-windowing/winit/issues/1779
|
// Return when in event handler due to https://github.com/rust-windowing/winit/issues/1779
|
||||||
// XXX: how does it make sense that `event_handler.ready()` can ever return `false` here if
|
// 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?
|
// we're about to return to the `CFRunLoop` to poll for new events?
|
||||||
if panic_info.is_panicking() || !self.event_handler.ready() || !self.is_running() {
|
if !self.event_handler.ready() || !self.is_running() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.event_loop_proxy.wake_up.swap(false, AtomicOrdering::Relaxed) {
|
|
||||||
self.with_handler(|app, event_loop| app.proxy_wake_up(event_loop));
|
|
||||||
}
|
|
||||||
|
|
||||||
let redraw = mem::take(&mut *self.pending_redraw.borrow_mut());
|
let redraw = mem::take(&mut *self.pending_redraw.borrow_mut());
|
||||||
for window_id in redraw {
|
for window_id in redraw {
|
||||||
self.with_handler(|app, event_loop| {
|
self.with_handler(|app, event_loop| {
|
||||||
@@ -378,6 +357,7 @@ impl AppState {
|
|||||||
if self.exiting() {
|
if self.exiting() {
|
||||||
let app = NSApplication::sharedApplication(self.mtm);
|
let app = NSApplication::sharedApplication(self.mtm);
|
||||||
stop_app_immediately(&app);
|
stop_app_immediately(&app);
|
||||||
|
notify_windows_of_exit(&app);
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.stop_before_wait.get() {
|
if self.stop_before_wait.get() {
|
||||||
@@ -4,34 +4,44 @@ use std::sync::OnceLock;
|
|||||||
|
|
||||||
use objc2::rc::Retained;
|
use objc2::rc::Retained;
|
||||||
use objc2::runtime::Sel;
|
use objc2::runtime::Sel;
|
||||||
use objc2::{msg_send_id, sel, ClassType};
|
use objc2::{available, msg_send, sel, AllocAnyThread, ClassType};
|
||||||
use objc2_app_kit::{NSBitmapImageRep, NSCursor, NSDeviceRGBColorSpace, NSImage};
|
use objc2_app_kit::{NSBitmapImageRep, NSCursor, NSDeviceRGBColorSpace, NSImage};
|
||||||
use objc2_foundation::{
|
use objc2_foundation::{
|
||||||
ns_string, NSData, NSDictionary, NSNumber, NSObject, NSObjectProtocol, NSPoint, NSSize,
|
ns_string, NSData, NSDictionary, NSNumber, NSObject, NSPoint, NSSize, NSString,
|
||||||
NSString,
|
|
||||||
};
|
};
|
||||||
|
use winit_core::cursor::{CursorIcon, CursorImage, CustomCursorProvider, CustomCursorSource};
|
||||||
use crate::cursor::{CursorImage, OnlyCursorImageSource};
|
use winit_core::error::{NotSupportedError, RequestError};
|
||||||
use crate::error::RequestError;
|
|
||||||
use crate::window::CursorIcon;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||||
pub struct CustomCursor(pub(crate) Retained<NSCursor>);
|
pub struct CustomCursor(pub(crate) Retained<NSCursor>);
|
||||||
|
|
||||||
|
impl CustomCursorProvider for CustomCursor {
|
||||||
|
fn is_animated(&self) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// SAFETY: NSCursor is immutable and thread-safe
|
// SAFETY: NSCursor is immutable and thread-safe
|
||||||
// TODO(madsmtm): Put this logic in objc2-app-kit itself
|
// TODO(madsmtm): Put this logic in objc2-app-kit itself
|
||||||
unsafe impl Send for CustomCursor {}
|
unsafe impl Send for CustomCursor {}
|
||||||
unsafe impl Sync for CustomCursor {}
|
unsafe impl Sync for CustomCursor {}
|
||||||
|
|
||||||
impl CustomCursor {
|
impl CustomCursor {
|
||||||
pub(crate) fn new(cursor: OnlyCursorImageSource) -> Result<CustomCursor, RequestError> {
|
pub(crate) fn new(cursor: CustomCursorSource) -> Result<CustomCursor, RequestError> {
|
||||||
cursor_from_image(&cursor.0).map(Self)
|
let cursor = match cursor {
|
||||||
|
CustomCursorSource::Image(cursor_image) => cursor_image,
|
||||||
|
CustomCursorSource::Animation { .. } | CustomCursorSource::Url { .. } => {
|
||||||
|
return Err(NotSupportedError::new("unsupported cursor kind").into())
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
cursor_from_image(&cursor).map(Self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn cursor_from_image(cursor: &CursorImage) -> Result<Retained<NSCursor>, RequestError> {
|
pub(crate) fn cursor_from_image(cursor: &CursorImage) -> Result<Retained<NSCursor>, RequestError> {
|
||||||
let width = cursor.width;
|
let width = cursor.width();
|
||||||
let height = cursor.height;
|
let height = cursor.height();
|
||||||
|
|
||||||
let bitmap = unsafe {
|
let bitmap = unsafe {
|
||||||
NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
|
NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
|
||||||
@@ -48,15 +58,16 @@ pub(crate) fn cursor_from_image(cursor: &CursorImage) -> Result<Retained<NSCurso
|
|||||||
32,
|
32,
|
||||||
)
|
)
|
||||||
}.ok_or_else(|| os_error!("parent view should be installed in a window"))?;
|
}.ok_or_else(|| os_error!("parent view should be installed in a window"))?;
|
||||||
let bitmap_data = unsafe { slice::from_raw_parts_mut(bitmap.bitmapData(), cursor.rgba.len()) };
|
let bitmap_data =
|
||||||
bitmap_data.copy_from_slice(&cursor.rgba);
|
unsafe { slice::from_raw_parts_mut(bitmap.bitmapData(), cursor.buffer().len()) };
|
||||||
|
bitmap_data.copy_from_slice(cursor.buffer());
|
||||||
|
|
||||||
let image = unsafe {
|
let image = unsafe {
|
||||||
NSImage::initWithSize(NSImage::alloc(), NSSize::new(width.into(), height.into()))
|
NSImage::initWithSize(NSImage::alloc(), NSSize::new(width.into(), height.into()))
|
||||||
};
|
};
|
||||||
unsafe { image.addRepresentation(&bitmap) };
|
unsafe { image.addRepresentation(&bitmap) };
|
||||||
|
|
||||||
let hotspot = NSPoint::new(cursor.hotspot_x as f64, cursor.hotspot_y as f64);
|
let hotspot = NSPoint::new(cursor.hotspot_x() as f64, cursor.hotspot_y() as f64);
|
||||||
|
|
||||||
Ok(NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot))
|
Ok(NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot))
|
||||||
}
|
}
|
||||||
@@ -67,8 +78,8 @@ pub(crate) fn default_cursor() -> Retained<NSCursor> {
|
|||||||
|
|
||||||
unsafe fn try_cursor_from_selector(sel: Sel) -> Option<Retained<NSCursor>> {
|
unsafe fn try_cursor_from_selector(sel: Sel) -> Option<Retained<NSCursor>> {
|
||||||
let cls = NSCursor::class();
|
let cls = NSCursor::class();
|
||||||
if cls.responds_to(sel) {
|
if unsafe { msg_send![cls, respondsToSelector: sel] } {
|
||||||
let cursor: Retained<NSCursor> = unsafe { msg_send_id![cls, performSelector: sel] };
|
let cursor: Retained<NSCursor> = unsafe { msg_send![cls, performSelector: sel] };
|
||||||
Some(cursor)
|
Some(cursor)
|
||||||
} else {
|
} else {
|
||||||
tracing::warn!("cursor `{sel}` appears to be invalid");
|
tracing::warn!("cursor `{sel}` appears to be invalid");
|
||||||
@@ -130,25 +141,21 @@ unsafe fn load_webkit_cursor(name: &NSString) -> Retained<NSCursor> {
|
|||||||
// TODO: Handle PLists better
|
// TODO: Handle PLists better
|
||||||
let info_path = cursor_path.stringByAppendingPathComponent(ns_string!("info.plist"));
|
let info_path = cursor_path.stringByAppendingPathComponent(ns_string!("info.plist"));
|
||||||
let info: Retained<NSDictionary<NSObject, NSObject>> = unsafe {
|
let info: Retained<NSDictionary<NSObject, NSObject>> = unsafe {
|
||||||
msg_send_id![
|
msg_send![
|
||||||
<NSDictionary<NSObject, NSObject>>::class(),
|
<NSDictionary<NSObject, NSObject>>::class(),
|
||||||
dictionaryWithContentsOfFile: &*info_path,
|
dictionaryWithContentsOfFile: &*info_path,
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
let mut x = 0.0;
|
let mut x = 0.0;
|
||||||
if let Some(n) = info.get(&*ns_string!("hotx")) {
|
if let Some(n) = info.objectForKey(ns_string!("hotx")) {
|
||||||
if n.is_kind_of::<NSNumber>() {
|
if let Ok(n) = n.downcast::<NSNumber>() {
|
||||||
let ptr: *const NSObject = n;
|
x = n.as_cgfloat();
|
||||||
let ptr: *const NSNumber = ptr.cast();
|
|
||||||
x = unsafe { &*ptr }.as_cgfloat()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let mut y = 0.0;
|
let mut y = 0.0;
|
||||||
if let Some(n) = info.get(&*ns_string!("hotx")) {
|
if let Some(n) = info.objectForKey(ns_string!("hoty")) {
|
||||||
if n.is_kind_of::<NSNumber>() {
|
if let Ok(n) = n.downcast::<NSNumber>() {
|
||||||
let ptr: *const NSObject = n;
|
y = n.as_cgfloat();
|
||||||
let ptr: *const NSNumber = ptr.cast();
|
|
||||||
y = unsafe { &*ptr }.as_cgfloat()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -188,6 +195,7 @@ pub(crate) fn invisible_cursor() -> Retained<NSCursor> {
|
|||||||
CURSOR.get_or_init(|| CustomCursor(new_invisible())).0.clone()
|
CURSOR.get_or_init(|| CustomCursor(new_invisible())).0.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(deprecated)]
|
||||||
pub(crate) fn cursor_from_icon(icon: CursorIcon) -> Retained<NSCursor> {
|
pub(crate) fn cursor_from_icon(icon: CursorIcon) -> Retained<NSCursor> {
|
||||||
match icon {
|
match icon {
|
||||||
CursorIcon::Default => default_cursor(),
|
CursorIcon::Default => default_cursor(),
|
||||||
@@ -208,7 +216,9 @@ pub(crate) fn cursor_from_icon(icon: CursorIcon) -> Retained<NSCursor> {
|
|||||||
CursorIcon::EwResize | CursorIcon::ColResize => NSCursor::resizeLeftRightCursor(),
|
CursorIcon::EwResize | CursorIcon::ColResize => NSCursor::resizeLeftRightCursor(),
|
||||||
CursorIcon::NsResize | CursorIcon::RowResize => NSCursor::resizeUpDownCursor(),
|
CursorIcon::NsResize | CursorIcon::RowResize => NSCursor::resizeUpDownCursor(),
|
||||||
CursorIcon::Help => _helpCursor(),
|
CursorIcon::Help => _helpCursor(),
|
||||||
|
CursorIcon::ZoomIn if available!(macos = 15.0) => unsafe { NSCursor::zoomInCursor() },
|
||||||
CursorIcon::ZoomIn => _zoomInCursor(),
|
CursorIcon::ZoomIn => _zoomInCursor(),
|
||||||
|
CursorIcon::ZoomOut if available!(macos = 15.0) => unsafe { NSCursor::zoomOutCursor() },
|
||||||
CursorIcon::ZoomOut => _zoomOutCursor(),
|
CursorIcon::ZoomOut => _zoomOutCursor(),
|
||||||
CursorIcon::NeResize => _windowResizeNorthEastCursor(),
|
CursorIcon::NeResize => _windowResizeNorthEastCursor(),
|
||||||
CursorIcon::NwResize => _windowResizeNorthWestCursor(),
|
CursorIcon::NwResize => _windowResizeNorthWestCursor(),
|
||||||
@@ -1,50 +1,42 @@
|
|||||||
use std::ffi::c_void;
|
use std::ptr::NonNull;
|
||||||
|
|
||||||
use core_foundation::base::CFRelease;
|
use dispatch2::run_on_main;
|
||||||
use core_foundation::data::{CFDataGetBytePtr, CFDataRef};
|
|
||||||
use objc2::rc::Retained;
|
use objc2::rc::Retained;
|
||||||
use objc2_app_kit::{NSEvent, NSEventModifierFlags, NSEventSubtype, NSEventType};
|
use objc2_app_kit::{NSEvent, NSEventModifierFlags, NSEventSubtype, NSEventType};
|
||||||
use objc2_foundation::{run_on_main, NSPoint};
|
use objc2_core_foundation::{CFData, CFRetained};
|
||||||
|
use objc2_foundation::NSPoint;
|
||||||
use smol_str::SmolStr;
|
use smol_str::SmolStr;
|
||||||
|
use winit_core::event::{ElementState, KeyEvent, Modifiers};
|
||||||
use super::ffi;
|
use winit_core::keyboard::{
|
||||||
use crate::event::{ElementState, KeyEvent, Modifiers};
|
|
||||||
use crate::keyboard::{
|
|
||||||
Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey, NativeKeyCode,
|
Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey, NativeKeyCode,
|
||||||
PhysicalKey,
|
PhysicalKey,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
use super::ffi;
|
||||||
pub struct KeyEventExtra {
|
|
||||||
pub text_with_all_modifiers: Option<SmolStr>,
|
|
||||||
pub key_without_modifiers: Key,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Ignores ALL modifiers.
|
/// Ignores ALL modifiers.
|
||||||
pub fn get_modifierless_char(scancode: u16) -> Key {
|
pub fn get_modifierless_char(scancode: u16) -> Key {
|
||||||
let mut string = [0; 16];
|
let Some(ptr) = NonNull::new(unsafe { ffi::TISCopyCurrentKeyboardLayoutInputSource() }) else {
|
||||||
let input_source;
|
tracing::error!("`TISCopyCurrentKeyboardLayoutInputSource` returned null ptr");
|
||||||
let layout;
|
return Key::Unidentified(NativeKey::MacOS(scancode));
|
||||||
unsafe {
|
};
|
||||||
input_source = ffi::TISCopyCurrentKeyboardLayoutInputSource();
|
let input_source = unsafe { CFRetained::from_raw(ptr) };
|
||||||
if input_source.is_null() {
|
|
||||||
tracing::error!("`TISCopyCurrentKeyboardLayoutInputSource` returned null ptr");
|
let layout_data = unsafe {
|
||||||
return Key::Unidentified(NativeKey::MacOS(scancode));
|
ffi::TISGetInputSourceProperty(&input_source, ffi::kTISPropertyUnicodeKeyLayoutData)
|
||||||
}
|
};
|
||||||
let layout_data =
|
let Some(layout_data) = (unsafe { layout_data.cast::<CFData>().as_ref() }) else {
|
||||||
ffi::TISGetInputSourceProperty(input_source, ffi::kTISPropertyUnicodeKeyLayoutData);
|
tracing::error!("`TISGetInputSourceProperty` returned null ptr");
|
||||||
if layout_data.is_null() {
|
return Key::Unidentified(NativeKey::MacOS(scancode));
|
||||||
CFRelease(input_source as *mut c_void);
|
};
|
||||||
tracing::error!("`TISGetInputSourceProperty` returned null ptr");
|
|
||||||
return Key::Unidentified(NativeKey::MacOS(scancode));
|
let layout = layout_data.byte_ptr().cast();
|
||||||
}
|
|
||||||
layout = CFDataGetBytePtr(layout_data as CFDataRef) as *const ffi::UCKeyboardLayout;
|
|
||||||
}
|
|
||||||
let keyboard_type = run_on_main(|_mtm| unsafe { ffi::LMGetKbdType() });
|
let keyboard_type = run_on_main(|_mtm| unsafe { ffi::LMGetKbdType() });
|
||||||
|
|
||||||
let mut result_len = 0;
|
let mut result_len = 0;
|
||||||
let mut dead_keys = 0;
|
let mut dead_keys = 0;
|
||||||
let modifiers = 0;
|
let modifiers = 0;
|
||||||
|
let mut string = [0; 16];
|
||||||
let translate_result = unsafe {
|
let translate_result = unsafe {
|
||||||
ffi::UCKeyTranslate(
|
ffi::UCKeyTranslate(
|
||||||
layout,
|
layout,
|
||||||
@@ -59,9 +51,6 @@ pub fn get_modifierless_char(scancode: u16) -> Key {
|
|||||||
string.as_mut_ptr(),
|
string.as_mut_ptr(),
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
unsafe {
|
|
||||||
CFRelease(input_source as *mut c_void);
|
|
||||||
}
|
|
||||||
if translate_result != 0 {
|
if translate_result != 0 {
|
||||||
tracing::error!("`UCKeyTranslate` returned with the non-zero value: {}", translate_result);
|
tracing::error!("`UCKeyTranslate` returned with the non-zero value: {}", translate_result);
|
||||||
return Key::Unidentified(NativeKey::MacOS(scancode));
|
return Key::Unidentified(NativeKey::MacOS(scancode));
|
||||||
@@ -123,8 +112,8 @@ pub(crate) fn create_key_event(ns_event: &NSEvent, is_press: bool, is_repeat: bo
|
|||||||
let key_without_modifiers = get_modifierless_char(scancode);
|
let key_without_modifiers = get_modifierless_char(scancode);
|
||||||
|
|
||||||
let modifiers = unsafe { ns_event.modifierFlags() };
|
let modifiers = unsafe { ns_event.modifierFlags() };
|
||||||
let has_ctrl = modifiers.contains(NSEventModifierFlags::NSEventModifierFlagControl);
|
let has_ctrl = modifiers.contains(NSEventModifierFlags::Control);
|
||||||
let has_cmd = modifiers.contains(NSEventModifierFlags::NSEventModifierFlagCommand);
|
let has_cmd = modifiers.contains(NSEventModifierFlags::Command);
|
||||||
|
|
||||||
let logical_key = match text_with_all_modifiers.as_ref() {
|
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
|
// Only checking for ctrl and cmd here, not checking for alt because we DO want to
|
||||||
@@ -162,7 +151,8 @@ pub(crate) fn create_key_event(ns_event: &NSEvent, is_press: bool, is_repeat: bo
|
|||||||
repeat: is_repeat,
|
repeat: is_repeat,
|
||||||
state,
|
state,
|
||||||
text,
|
text,
|
||||||
platform_specific: KeyEventExtra { text_with_all_modifiers, key_without_modifiers },
|
text_with_all_modifiers,
|
||||||
|
key_without_modifiers,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,28 +162,34 @@ pub fn code_to_key(key: PhysicalKey, scancode: u16) -> Key {
|
|||||||
PhysicalKey::Unidentified(code) => return Key::Unidentified(code.into()),
|
PhysicalKey::Unidentified(code) => return Key::Unidentified(code.into()),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Roughly same handling as Firefox and Chromium:
|
||||||
|
// https://searchfox.org/mozilla-central/rev/c597e9c789ad36af84a0370d395be066b7dc94f4/widget/NativeKeyToDOMKeyName.h
|
||||||
|
// https://chromium.googlesource.com/chromium/src.git/+/010a75a426c4a2292955a52f480e9251cacf750e/ui/events/keycodes/keyboard_code_conversion_mac.mm#100
|
||||||
Key::Named(match code {
|
Key::Named(match code {
|
||||||
KeyCode::Enter => NamedKey::Enter,
|
KeyCode::Enter => NamedKey::Enter,
|
||||||
KeyCode::Tab => NamedKey::Tab,
|
KeyCode::Tab => NamedKey::Tab,
|
||||||
KeyCode::Space => NamedKey::Space,
|
KeyCode::Space => return Key::Character(" ".into()),
|
||||||
KeyCode::Backspace => NamedKey::Backspace,
|
KeyCode::Backspace => NamedKey::Backspace,
|
||||||
KeyCode::Escape => NamedKey::Escape,
|
KeyCode::Escape => NamedKey::Escape,
|
||||||
KeyCode::SuperRight => NamedKey::Super,
|
KeyCode::MetaRight => NamedKey::Meta,
|
||||||
KeyCode::SuperLeft => NamedKey::Super,
|
KeyCode::MetaLeft => NamedKey::Meta,
|
||||||
KeyCode::ShiftLeft => NamedKey::Shift,
|
KeyCode::ShiftLeft => NamedKey::Shift,
|
||||||
KeyCode::AltLeft => NamedKey::Alt,
|
KeyCode::AltLeft => NamedKey::Alt,
|
||||||
KeyCode::ControlLeft => NamedKey::Control,
|
KeyCode::ControlLeft => NamedKey::Control,
|
||||||
KeyCode::ShiftRight => NamedKey::Shift,
|
KeyCode::ShiftRight => NamedKey::Shift,
|
||||||
KeyCode::AltRight => NamedKey::Alt,
|
KeyCode::AltRight => NamedKey::Alt,
|
||||||
KeyCode::ControlRight => NamedKey::Control,
|
KeyCode::ControlRight => NamedKey::Control,
|
||||||
|
KeyCode::CapsLock => NamedKey::CapsLock,
|
||||||
|
|
||||||
KeyCode::NumLock => NamedKey::NumLock,
|
KeyCode::NumLock => NamedKey::NumLock,
|
||||||
KeyCode::AudioVolumeUp => NamedKey::AudioVolumeUp,
|
KeyCode::AudioVolumeUp => NamedKey::AudioVolumeUp,
|
||||||
KeyCode::AudioVolumeDown => NamedKey::AudioVolumeDown,
|
KeyCode::AudioVolumeDown => NamedKey::AudioVolumeDown,
|
||||||
|
KeyCode::AudioVolumeMute => NamedKey::AudioVolumeMute,
|
||||||
|
|
||||||
// Other numpad keys all generate text on macOS (if I understand correctly)
|
// Other numpad keys all generate text on macOS (if I understand correctly)
|
||||||
KeyCode::NumpadEnter => NamedKey::Enter,
|
KeyCode::NumpadEnter => NamedKey::Enter,
|
||||||
|
|
||||||
|
KeyCode::Fn => NamedKey::Fn,
|
||||||
KeyCode::F1 => NamedKey::F1,
|
KeyCode::F1 => NamedKey::F1,
|
||||||
KeyCode::F2 => NamedKey::F2,
|
KeyCode::F2 => NamedKey::F2,
|
||||||
KeyCode::F3 => NamedKey::F3,
|
KeyCode::F3 => NamedKey::F3,
|
||||||
@@ -214,17 +210,27 @@ pub fn code_to_key(key: PhysicalKey, scancode: u16) -> Key {
|
|||||||
KeyCode::F18 => NamedKey::F18,
|
KeyCode::F18 => NamedKey::F18,
|
||||||
KeyCode::F19 => NamedKey::F19,
|
KeyCode::F19 => NamedKey::F19,
|
||||||
KeyCode::F20 => NamedKey::F20,
|
KeyCode::F20 => NamedKey::F20,
|
||||||
|
KeyCode::F21 => NamedKey::F21,
|
||||||
|
KeyCode::F22 => NamedKey::F22,
|
||||||
|
KeyCode::F23 => NamedKey::F23,
|
||||||
|
KeyCode::F24 => NamedKey::F24,
|
||||||
|
|
||||||
KeyCode::Insert => NamedKey::Insert,
|
KeyCode::Insert => NamedKey::Insert,
|
||||||
KeyCode::Home => NamedKey::Home,
|
KeyCode::Home => NamedKey::Home,
|
||||||
KeyCode::PageUp => NamedKey::PageUp,
|
KeyCode::PageUp => NamedKey::PageUp,
|
||||||
KeyCode::Delete => NamedKey::Delete,
|
KeyCode::Delete => NamedKey::Delete,
|
||||||
KeyCode::End => NamedKey::End,
|
KeyCode::End => NamedKey::End,
|
||||||
|
KeyCode::Help => NamedKey::Help,
|
||||||
KeyCode::PageDown => NamedKey::PageDown,
|
KeyCode::PageDown => NamedKey::PageDown,
|
||||||
KeyCode::ArrowLeft => NamedKey::ArrowLeft,
|
KeyCode::ArrowLeft => NamedKey::ArrowLeft,
|
||||||
KeyCode::ArrowRight => NamedKey::ArrowRight,
|
KeyCode::ArrowRight => NamedKey::ArrowRight,
|
||||||
KeyCode::ArrowDown => NamedKey::ArrowDown,
|
KeyCode::ArrowDown => NamedKey::ArrowDown,
|
||||||
KeyCode::ArrowUp => NamedKey::ArrowUp,
|
KeyCode::ArrowUp => NamedKey::ArrowUp,
|
||||||
|
KeyCode::ContextMenu => NamedKey::ContextMenu,
|
||||||
|
|
||||||
|
KeyCode::Lang2 => NamedKey::Eisu,
|
||||||
|
KeyCode::Lang1 => NamedKey::KanjiMode,
|
||||||
|
|
||||||
_ => return Key::Unidentified(NativeKey::MacOS(scancode)),
|
_ => return Key::Unidentified(NativeKey::MacOS(scancode)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -236,8 +242,8 @@ pub fn code_to_location(key: PhysicalKey) -> KeyLocation {
|
|||||||
};
|
};
|
||||||
|
|
||||||
match code {
|
match code {
|
||||||
KeyCode::SuperRight => KeyLocation::Right,
|
KeyCode::MetaRight => KeyLocation::Right,
|
||||||
KeyCode::SuperLeft => KeyLocation::Left,
|
KeyCode::MetaLeft => KeyLocation::Left,
|
||||||
KeyCode::ShiftLeft => KeyLocation::Left,
|
KeyCode::ShiftLeft => KeyLocation::Left,
|
||||||
KeyCode::AltLeft => KeyLocation::Left,
|
KeyCode::AltLeft => KeyLocation::Left,
|
||||||
KeyCode::ControlLeft => KeyLocation::Left,
|
KeyCode::ControlLeft => KeyLocation::Left,
|
||||||
@@ -308,30 +314,23 @@ pub(super) fn event_mods(event: &NSEvent) -> Modifiers {
|
|||||||
let mut state = ModifiersState::empty();
|
let mut state = ModifiersState::empty();
|
||||||
let mut pressed_mods = ModifiersKeys::empty();
|
let mut pressed_mods = ModifiersKeys::empty();
|
||||||
|
|
||||||
state
|
state.set(ModifiersState::SHIFT, flags.contains(NSEventModifierFlags::Shift));
|
||||||
.set(ModifiersState::SHIFT, flags.contains(NSEventModifierFlags::NSEventModifierFlagShift));
|
|
||||||
pressed_mods.set(ModifiersKeys::LSHIFT, flags.contains(NX_DEVICELSHIFTKEYMASK));
|
pressed_mods.set(ModifiersKeys::LSHIFT, flags.contains(NX_DEVICELSHIFTKEYMASK));
|
||||||
pressed_mods.set(ModifiersKeys::RSHIFT, flags.contains(NX_DEVICERSHIFTKEYMASK));
|
pressed_mods.set(ModifiersKeys::RSHIFT, flags.contains(NX_DEVICERSHIFTKEYMASK));
|
||||||
|
|
||||||
state.set(
|
state.set(ModifiersState::CONTROL, flags.contains(NSEventModifierFlags::Control));
|
||||||
ModifiersState::CONTROL,
|
|
||||||
flags.contains(NSEventModifierFlags::NSEventModifierFlagControl),
|
|
||||||
);
|
|
||||||
pressed_mods.set(ModifiersKeys::LCONTROL, flags.contains(NX_DEVICELCTLKEYMASK));
|
pressed_mods.set(ModifiersKeys::LCONTROL, flags.contains(NX_DEVICELCTLKEYMASK));
|
||||||
pressed_mods.set(ModifiersKeys::RCONTROL, flags.contains(NX_DEVICERCTLKEYMASK));
|
pressed_mods.set(ModifiersKeys::RCONTROL, flags.contains(NX_DEVICERCTLKEYMASK));
|
||||||
|
|
||||||
state.set(ModifiersState::ALT, flags.contains(NSEventModifierFlags::NSEventModifierFlagOption));
|
state.set(ModifiersState::ALT, flags.contains(NSEventModifierFlags::Option));
|
||||||
pressed_mods.set(ModifiersKeys::LALT, flags.contains(NX_DEVICELALTKEYMASK));
|
pressed_mods.set(ModifiersKeys::LALT, flags.contains(NX_DEVICELALTKEYMASK));
|
||||||
pressed_mods.set(ModifiersKeys::RALT, flags.contains(NX_DEVICERALTKEYMASK));
|
pressed_mods.set(ModifiersKeys::RALT, flags.contains(NX_DEVICERALTKEYMASK));
|
||||||
|
|
||||||
state.set(
|
state.set(ModifiersState::META, flags.contains(NSEventModifierFlags::Command));
|
||||||
ModifiersState::SUPER,
|
pressed_mods.set(ModifiersKeys::LMETA, flags.contains(NX_DEVICELCMDKEYMASK));
|
||||||
flags.contains(NSEventModifierFlags::NSEventModifierFlagCommand),
|
pressed_mods.set(ModifiersKeys::RMETA, flags.contains(NX_DEVICERCMDKEYMASK));
|
||||||
);
|
|
||||||
pressed_mods.set(ModifiersKeys::LSUPER, flags.contains(NX_DEVICELCMDKEYMASK));
|
|
||||||
pressed_mods.set(ModifiersKeys::RSUPER, flags.contains(NX_DEVICERCMDKEYMASK));
|
|
||||||
|
|
||||||
Modifiers { state, pressed_mods }
|
Modifiers::new(state, pressed_mods)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn dummy_event() -> Option<Retained<NSEvent>> {
|
pub(super) fn dummy_event() -> Option<Retained<NSEvent>> {
|
||||||
@@ -350,7 +349,7 @@ pub(super) fn dummy_event() -> Option<Retained<NSEvent>> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32> {
|
pub fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32> {
|
||||||
let code = match physical_key {
|
let code = match physical_key {
|
||||||
PhysicalKey::Code(code) => code,
|
PhysicalKey::Code(code) => code,
|
||||||
PhysicalKey::Unidentified(_) => return None,
|
PhysicalKey::Unidentified(_) => return None,
|
||||||
@@ -410,8 +409,8 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
|
|||||||
KeyCode::Backquote => Some(0x32),
|
KeyCode::Backquote => Some(0x32),
|
||||||
KeyCode::Backspace => Some(0x33),
|
KeyCode::Backspace => Some(0x33),
|
||||||
KeyCode::Escape => Some(0x35),
|
KeyCode::Escape => Some(0x35),
|
||||||
KeyCode::SuperRight => Some(0x36),
|
KeyCode::MetaRight => Some(0x36),
|
||||||
KeyCode::SuperLeft => Some(0x37),
|
KeyCode::MetaLeft => Some(0x37),
|
||||||
KeyCode::ShiftLeft => Some(0x38),
|
KeyCode::ShiftLeft => Some(0x38),
|
||||||
KeyCode::CapsLock => Some(0x39),
|
KeyCode::CapsLock => Some(0x39),
|
||||||
KeyCode::AltLeft => Some(0x3a),
|
KeyCode::AltLeft => Some(0x3a),
|
||||||
@@ -482,7 +481,7 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
||||||
// Follows what Chromium and Firefox do:
|
// Follows what Chromium and Firefox do:
|
||||||
// https://chromium.googlesource.com/chromium/src.git/+/3e1a26c44c024d97dc9a4c09bbc6a2365398ca2c/ui/events/keycodes/dom/dom_code_data.inc
|
// https://chromium.googlesource.com/chromium/src.git/+/3e1a26c44c024d97dc9a4c09bbc6a2365398ca2c/ui/events/keycodes/dom/dom_code_data.inc
|
||||||
// https://searchfox.org/mozilla-central/rev/c597e9c789ad36af84a0370d395be066b7dc94f4/widget/NativeKeyToDOMCodeName.h
|
// https://searchfox.org/mozilla-central/rev/c597e9c789ad36af84a0370d395be066b7dc94f4/widget/NativeKeyToDOMCodeName.h
|
||||||
@@ -556,8 +555,8 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
0x33 => KeyCode::Backspace,
|
0x33 => KeyCode::Backspace,
|
||||||
// 0x34 => unknown, // kVK_Powerbook_KeypadEnter
|
// 0x34 => unknown, // kVK_Powerbook_KeypadEnter
|
||||||
0x35 => KeyCode::Escape,
|
0x35 => KeyCode::Escape,
|
||||||
0x36 => KeyCode::SuperRight,
|
0x36 => KeyCode::MetaRight,
|
||||||
0x37 => KeyCode::SuperLeft,
|
0x37 => KeyCode::MetaLeft,
|
||||||
0x38 => KeyCode::ShiftLeft,
|
0x38 => KeyCode::ShiftLeft,
|
||||||
0x39 => KeyCode::CapsLock,
|
0x39 => KeyCode::CapsLock,
|
||||||
0x3a => KeyCode::AltLeft,
|
0x3a => KeyCode::AltLeft,
|
||||||
@@ -1,76 +1,36 @@
|
|||||||
use std::any::Any;
|
use std::rc::Rc;
|
||||||
use std::cell::Cell;
|
|
||||||
use std::os::raw::c_void;
|
|
||||||
use std::panic::{catch_unwind, resume_unwind, RefUnwindSafe, UnwindSafe};
|
|
||||||
use std::ptr;
|
|
||||||
use std::rc::{Rc, Weak};
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use core_foundation::base::{CFIndex, CFRelease};
|
|
||||||
use core_foundation::runloop::{
|
|
||||||
kCFRunLoopCommonModes, CFRunLoopAddSource, CFRunLoopGetMain, CFRunLoopSourceContext,
|
|
||||||
CFRunLoopSourceCreate, CFRunLoopSourceRef, CFRunLoopSourceSignal, CFRunLoopWakeUp,
|
|
||||||
};
|
|
||||||
use objc2::rc::{autoreleasepool, Retained};
|
use objc2::rc::{autoreleasepool, Retained};
|
||||||
use objc2::{msg_send_id, sel, ClassType};
|
use objc2::runtime::ProtocolObject;
|
||||||
|
use objc2::{available, MainThreadMarker};
|
||||||
use objc2_app_kit::{
|
use objc2_app_kit::{
|
||||||
NSApplication, NSApplicationActivationPolicy, NSApplicationDidFinishLaunchingNotification,
|
NSApplication, NSApplicationActivationPolicy, NSApplicationDidFinishLaunchingNotification,
|
||||||
NSApplicationWillTerminateNotification, NSWindow,
|
NSApplicationWillTerminateNotification, NSWindow,
|
||||||
};
|
};
|
||||||
use objc2_foundation::{MainThreadMarker, NSNotificationCenter, NSObject, NSObjectProtocol};
|
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol};
|
||||||
use rwh_06::HasDisplayHandle;
|
use rwh_06::HasDisplayHandle;
|
||||||
|
use winit_core::application::ApplicationHandler;
|
||||||
|
use winit_core::cursor::{CustomCursor as CoreCustomCursor, CustomCursorSource};
|
||||||
|
use winit_core::error::{EventLoopError, RequestError};
|
||||||
|
use winit_core::event_loop::pump_events::PumpStatus;
|
||||||
|
use winit_core::event_loop::{
|
||||||
|
ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents,
|
||||||
|
EventLoopProxy as CoreEventLoopProxy, OwnedDisplayHandle as CoreOwnedDisplayHandle,
|
||||||
|
};
|
||||||
|
use winit_core::monitor::MonitorHandle as CoreMonitorHandle;
|
||||||
|
use winit_core::window::Theme;
|
||||||
|
|
||||||
use super::super::notification_center::create_observer;
|
use super::app::override_send_event;
|
||||||
use super::app::WinitApplication;
|
|
||||||
use super::app_state::AppState;
|
use super::app_state::AppState;
|
||||||
use super::cursor::CustomCursor;
|
use super::cursor::CustomCursor;
|
||||||
use super::event::dummy_event;
|
use super::event::dummy_event;
|
||||||
use super::monitor;
|
use super::monitor;
|
||||||
|
use super::notification_center::create_observer;
|
||||||
use super::observer::setup_control_flow_observers;
|
use super::observer::setup_control_flow_observers;
|
||||||
use crate::application::ApplicationHandler;
|
use crate::window::Window;
|
||||||
use crate::error::{EventLoopError, RequestError};
|
use crate::ActivationPolicy;
|
||||||
use crate::event_loop::{
|
|
||||||
ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents,
|
|
||||||
EventLoopProxy as CoreEventLoopProxy, EventLoopProxyProvider,
|
|
||||||
OwnedDisplayHandle as CoreOwnedDisplayHandle,
|
|
||||||
};
|
|
||||||
use crate::monitor::MonitorHandle as RootMonitorHandle;
|
|
||||||
use crate::platform::macos::ActivationPolicy;
|
|
||||||
use crate::platform::pump_events::PumpStatus;
|
|
||||||
use crate::platform_impl::Window;
|
|
||||||
use crate::window::{CustomCursor as RootCustomCursor, CustomCursorSource, Theme};
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub struct PanicInfo {
|
|
||||||
inner: Cell<Option<Box<dyn Any + Send + 'static>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
// WARNING:
|
|
||||||
// As long as this struct is used through its `impl`, it is UnwindSafe.
|
|
||||||
// (If `get_mut` is called on `inner`, unwind safety may get broken.)
|
|
||||||
impl UnwindSafe for PanicInfo {}
|
|
||||||
impl RefUnwindSafe for PanicInfo {}
|
|
||||||
impl PanicInfo {
|
|
||||||
pub fn is_panicking(&self) -> bool {
|
|
||||||
let inner = self.inner.take();
|
|
||||||
let result = inner.is_some();
|
|
||||||
self.inner.set(inner);
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Overwrites the current state if the current state is not panicking
|
|
||||||
pub fn set_panic(&self, p: Box<dyn Any + Send + 'static>) {
|
|
||||||
if !self.is_panicking() {
|
|
||||||
self.inner.set(Some(p));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn take(&self) -> Option<Box<dyn Any + Send + 'static>> {
|
|
||||||
self.inner.take()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct ActiveEventLoop {
|
pub struct ActiveEventLoop {
|
||||||
@@ -103,25 +63,29 @@ impl RootActiveEventLoop for ActiveEventLoop {
|
|||||||
|
|
||||||
fn create_window(
|
fn create_window(
|
||||||
&self,
|
&self,
|
||||||
window_attributes: crate::window::WindowAttributes,
|
window_attributes: winit_core::window::WindowAttributes,
|
||||||
) -> Result<Box<dyn crate::window::Window>, RequestError> {
|
) -> Result<Box<dyn winit_core::window::Window>, RequestError> {
|
||||||
Ok(Box::new(Window::new(self, window_attributes)?))
|
Ok(Box::new(Window::new(self, window_attributes)?))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_custom_cursor(
|
fn create_custom_cursor(
|
||||||
&self,
|
&self,
|
||||||
source: CustomCursorSource,
|
source: CustomCursorSource,
|
||||||
) -> Result<RootCustomCursor, RequestError> {
|
) -> Result<CoreCustomCursor, RequestError> {
|
||||||
Ok(RootCustomCursor { inner: CustomCursor::new(source.inner)? })
|
Ok(CoreCustomCursor(Arc::new(CustomCursor::new(source)?)))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn available_monitors(&self) -> Box<dyn Iterator<Item = RootMonitorHandle>> {
|
fn available_monitors(&self) -> Box<dyn Iterator<Item = CoreMonitorHandle>> {
|
||||||
Box::new(monitor::available_monitors().into_iter().map(|inner| RootMonitorHandle { inner }))
|
Box::new(
|
||||||
|
monitor::available_monitors()
|
||||||
|
.into_iter()
|
||||||
|
.map(|monitor| CoreMonitorHandle(Arc::new(monitor))),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn primary_monitor(&self) -> Option<crate::monitor::MonitorHandle> {
|
fn primary_monitor(&self) -> Option<winit_core::monitor::MonitorHandle> {
|
||||||
let monitor = monitor::primary_monitor();
|
let monitor = monitor::primary_monitor();
|
||||||
Some(RootMonitorHandle { inner: monitor })
|
Some(CoreMonitorHandle(Arc::new(monitor)))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn listen_device_events(&self, _allowed: DeviceEvents) {}
|
fn listen_device_events(&self, _allowed: DeviceEvents) {}
|
||||||
@@ -129,7 +93,8 @@ impl RootActiveEventLoop for ActiveEventLoop {
|
|||||||
fn system_theme(&self) -> Option<Theme> {
|
fn system_theme(&self) -> Option<Theme> {
|
||||||
let app = NSApplication::sharedApplication(self.mtm);
|
let app = NSApplication::sharedApplication(self.mtm);
|
||||||
|
|
||||||
if app.respondsToSelector(sel!(effectiveAppearance)) {
|
// Dark appearance was introduced in macOS 10.14
|
||||||
|
if available!(macos = 10.14) {
|
||||||
Some(super::window_delegate::appearance_to_theme(&app.effectiveAppearance()))
|
Some(super::window_delegate::appearance_to_theme(&app.effectiveAppearance()))
|
||||||
} else {
|
} else {
|
||||||
Some(Theme::Light)
|
Some(Theme::Light)
|
||||||
@@ -168,6 +133,7 @@ impl rwh_06::HasDisplayHandle for ActiveEventLoop {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
pub struct EventLoop {
|
pub struct EventLoop {
|
||||||
/// Store a reference to the application for convenience.
|
/// Store a reference to the application for convenience.
|
||||||
///
|
///
|
||||||
@@ -177,21 +143,20 @@ pub struct EventLoop {
|
|||||||
app_state: Rc<AppState>,
|
app_state: Rc<AppState>,
|
||||||
|
|
||||||
window_target: ActiveEventLoop,
|
window_target: ActiveEventLoop,
|
||||||
panic_info: Rc<PanicInfo>,
|
|
||||||
|
|
||||||
// Since macOS 10.11, we no longer need to remove the observers before they are deallocated;
|
// Since macOS 10.11, we no longer need to remove the observers before they are deallocated;
|
||||||
// the system instead cleans it up next time it would have posted a notification to it.
|
// the system instead cleans it up next time it would have posted a notification to it.
|
||||||
//
|
//
|
||||||
// Though we do still need to keep the observers around to prevent them from being deallocated.
|
// Though we do still need to keep the observers around to prevent them from being deallocated.
|
||||||
_did_finish_launching_observer: Retained<NSObject>,
|
_did_finish_launching_observer: Retained<ProtocolObject<dyn NSObjectProtocol>>,
|
||||||
_will_terminate_observer: Retained<NSObject>,
|
_will_terminate_observer: Retained<ProtocolObject<dyn NSObjectProtocol>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||||
pub(crate) struct PlatformSpecificEventLoopAttributes {
|
pub struct PlatformSpecificEventLoopAttributes {
|
||||||
pub(crate) activation_policy: Option<ActivationPolicy>,
|
pub activation_policy: Option<ActivationPolicy>,
|
||||||
pub(crate) default_menu: bool,
|
pub default_menu: bool,
|
||||||
pub(crate) activate_ignoring_other_apps: bool,
|
pub activate_ignoring_other_apps: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for PlatformSpecificEventLoopAttributes {
|
impl Default for PlatformSpecificEventLoopAttributes {
|
||||||
@@ -201,22 +166,10 @@ impl Default for PlatformSpecificEventLoopAttributes {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl EventLoop {
|
impl EventLoop {
|
||||||
pub(crate) fn new(
|
pub fn new(attributes: &PlatformSpecificEventLoopAttributes) -> Result<Self, EventLoopError> {
|
||||||
attributes: &PlatformSpecificEventLoopAttributes,
|
|
||||||
) -> Result<Self, EventLoopError> {
|
|
||||||
let mtm = MainThreadMarker::new()
|
let mtm = MainThreadMarker::new()
|
||||||
.expect("on macOS, `EventLoop` must be created on the main thread!");
|
.expect("on macOS, `EventLoop` must be created on the main thread!");
|
||||||
|
|
||||||
let app: Retained<NSApplication> =
|
|
||||||
unsafe { msg_send_id![WinitApplication::class(), sharedApplication] };
|
|
||||||
|
|
||||||
if !app.is_kind_of::<WinitApplication>() {
|
|
||||||
panic!(
|
|
||||||
"`winit` requires control over the principal class. You must create the event \
|
|
||||||
loop before other parts of your application initialize NSApplication"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let activation_policy = match attributes.activation_policy {
|
let activation_policy = match attributes.activation_policy {
|
||||||
None => None,
|
None => None,
|
||||||
Some(ActivationPolicy::Regular) => Some(NSApplicationActivationPolicy::Regular),
|
Some(ActivationPolicy::Regular) => Some(NSApplicationActivationPolicy::Regular),
|
||||||
@@ -229,7 +182,14 @@ impl EventLoop {
|
|||||||
activation_policy,
|
activation_policy,
|
||||||
attributes.default_menu,
|
attributes.default_menu,
|
||||||
attributes.activate_ignoring_other_apps,
|
attributes.activate_ignoring_other_apps,
|
||||||
);
|
)
|
||||||
|
.ok_or_else(|| EventLoopError::RecreationAttempt)?;
|
||||||
|
|
||||||
|
// Initialize the application (if it has not already been).
|
||||||
|
let app = NSApplication::sharedApplication(mtm);
|
||||||
|
|
||||||
|
// Override `sendEvent:` on the application to forward to our application state.
|
||||||
|
override_send_event(&app);
|
||||||
|
|
||||||
let center = unsafe { NSNotificationCenter::defaultCenter() };
|
let center = unsafe { NSNotificationCenter::defaultCenter() };
|
||||||
|
|
||||||
@@ -257,14 +217,12 @@ impl EventLoop {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
let panic_info: Rc<PanicInfo> = Default::default();
|
setup_control_flow_observers(mtm);
|
||||||
setup_control_flow_observers(mtm, Rc::downgrade(&panic_info));
|
|
||||||
|
|
||||||
Ok(EventLoop {
|
Ok(EventLoop {
|
||||||
app,
|
app,
|
||||||
app_state: app_state.clone(),
|
app_state: app_state.clone(),
|
||||||
window_target: ActiveEventLoop { app_state, mtm },
|
window_target: ActiveEventLoop { app_state, mtm },
|
||||||
panic_info,
|
|
||||||
_did_finish_launching_observer,
|
_did_finish_launching_observer,
|
||||||
_will_terminate_observer,
|
_will_terminate_observer,
|
||||||
})
|
})
|
||||||
@@ -284,10 +242,10 @@ impl EventLoop {
|
|||||||
// redundant wake ups.
|
// redundant wake ups.
|
||||||
pub fn run_app_on_demand<A: ApplicationHandler>(
|
pub fn run_app_on_demand<A: ApplicationHandler>(
|
||||||
&mut self,
|
&mut self,
|
||||||
mut app: A,
|
app: A,
|
||||||
) -> Result<(), EventLoopError> {
|
) -> Result<(), EventLoopError> {
|
||||||
self.app_state.clear_exit();
|
self.app_state.clear_exit();
|
||||||
self.app_state.set_event_handler(&mut app, || {
|
self.app_state.set_event_handler(app, || {
|
||||||
autoreleasepool(|_| {
|
autoreleasepool(|_| {
|
||||||
// clear / normalize pump_events state
|
// clear / normalize pump_events state
|
||||||
self.app_state.set_wait_timeout(None);
|
self.app_state.set_wait_timeout(None);
|
||||||
@@ -301,17 +259,8 @@ impl EventLoop {
|
|||||||
self.app_state.dispatch_init_events();
|
self.app_state.dispatch_init_events();
|
||||||
}
|
}
|
||||||
|
|
||||||
// SAFETY: We do not run the application re-entrantly
|
// NOTE: Make sure to not run the application re-entrantly, as that'd be confusing.
|
||||||
unsafe { self.app.run() };
|
self.app.run();
|
||||||
|
|
||||||
// While the app is running it's possible that we catch a panic
|
|
||||||
// to avoid unwinding across an objective-c ffi boundary, which
|
|
||||||
// will lead to us stopping the `NSApplication` and saving the
|
|
||||||
// `PanicInfo` so that we can resume the unwind at a controlled,
|
|
||||||
// safe point in time.
|
|
||||||
if let Some(panic) = self.panic_info.take() {
|
|
||||||
resume_unwind(panic);
|
|
||||||
}
|
|
||||||
|
|
||||||
self.app_state.internal_exit()
|
self.app_state.internal_exit()
|
||||||
})
|
})
|
||||||
@@ -323,9 +272,9 @@ impl EventLoop {
|
|||||||
pub fn pump_app_events<A: ApplicationHandler>(
|
pub fn pump_app_events<A: ApplicationHandler>(
|
||||||
&mut self,
|
&mut self,
|
||||||
timeout: Option<Duration>,
|
timeout: Option<Duration>,
|
||||||
mut app: A,
|
app: A,
|
||||||
) -> PumpStatus {
|
) -> PumpStatus {
|
||||||
self.app_state.set_event_handler(&mut app, || {
|
self.app_state.set_event_handler(app, || {
|
||||||
autoreleasepool(|_| {
|
autoreleasepool(|_| {
|
||||||
// As a special case, if the application hasn't been launched yet then we at least
|
// As a special case, if the application hasn't been launched yet then we at least
|
||||||
// run the loop until it has fully launched.
|
// run the loop until it has fully launched.
|
||||||
@@ -333,8 +282,7 @@ impl EventLoop {
|
|||||||
debug_assert!(!self.app_state.is_running());
|
debug_assert!(!self.app_state.is_running());
|
||||||
|
|
||||||
self.app_state.set_stop_on_launch();
|
self.app_state.set_stop_on_launch();
|
||||||
// SAFETY: We do not run the application re-entrantly
|
self.app.run();
|
||||||
unsafe { self.app.run() };
|
|
||||||
|
|
||||||
// Note: we dispatch `NewEvents(Init)` + `Resumed` events after the application
|
// Note: we dispatch `NewEvents(Init)` + `Resumed` events after the application
|
||||||
// has launched
|
// has launched
|
||||||
@@ -366,17 +314,7 @@ impl EventLoop {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
self.app_state.set_stop_on_redraw(true);
|
self.app_state.set_stop_on_redraw(true);
|
||||||
// SAFETY: We do not run the application re-entrantly
|
self.app.run();
|
||||||
unsafe { self.app.run() };
|
|
||||||
}
|
|
||||||
|
|
||||||
// While the app is running it's possible that we catch a panic
|
|
||||||
// to avoid unwinding across an objective-c ffi boundary, which
|
|
||||||
// will lead to us stopping the application and saving the
|
|
||||||
// `PanicInfo` so that we can resume the unwind at a controlled,
|
|
||||||
// safe point in time.
|
|
||||||
if let Some(panic) = self.panic_info.take() {
|
|
||||||
resume_unwind(panic);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.app_state.exiting() {
|
if self.app_state.exiting() {
|
||||||
@@ -408,87 +346,18 @@ pub(super) fn stop_app_immediately(app: &NSApplication) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Catches panics that happen inside `f` and when a panic
|
/// Tell all windows to close.
|
||||||
/// happens, stops the `sharedApplication`
|
///
|
||||||
#[inline]
|
/// This will synchronously trigger `WindowEvent::Destroyed` within
|
||||||
pub fn stop_app_on_panic<F: FnOnce() -> R + UnwindSafe, R>(
|
/// `windowWillClose:`, giving the application one last chance to handle
|
||||||
mtm: MainThreadMarker,
|
/// those events. It doesn't matter if the user also ends up closing the
|
||||||
panic_info: Weak<PanicInfo>,
|
/// windows in `Window`'s `Drop` impl, once a window has been closed once, it
|
||||||
f: F,
|
/// stays closed.
|
||||||
) -> Option<R> {
|
///
|
||||||
match catch_unwind(f) {
|
/// This ensures that no windows linger on after the event loop has exited,
|
||||||
Ok(r) => Some(r),
|
/// see <https://github.com/rust-windowing/winit/issues/4135>.
|
||||||
Err(e) => {
|
pub(super) fn notify_windows_of_exit(app: &NSApplication) {
|
||||||
// It's important that we set the panic before requesting a `stop`
|
for window in app.windows() {
|
||||||
// because some callback are still called during the `stop` message
|
window.close();
|
||||||
// and we need to know in those callbacks if the application is currently
|
|
||||||
// panicking
|
|
||||||
{
|
|
||||||
let panic_info = panic_info.upgrade().unwrap();
|
|
||||||
panic_info.set_panic(e);
|
|
||||||
}
|
|
||||||
let app = NSApplication::sharedApplication(mtm);
|
|
||||||
stop_app_immediately(&app);
|
|
||||||
None
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct EventLoopProxy {
|
|
||||||
pub(crate) wake_up: AtomicBool,
|
|
||||||
source: CFRunLoopSourceRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe impl Send for EventLoopProxy {}
|
|
||||||
unsafe impl Sync for EventLoopProxy {}
|
|
||||||
|
|
||||||
impl Drop for EventLoopProxy {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
unsafe {
|
|
||||||
CFRelease(self.source as _);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventLoopProxy {
|
|
||||||
pub(crate) fn new() -> Self {
|
|
||||||
unsafe {
|
|
||||||
// just wake up the eventloop
|
|
||||||
extern "C" fn event_loop_proxy_handler(_: *const c_void) {}
|
|
||||||
|
|
||||||
// adding a Source to the main CFRunLoop lets us wake it up and
|
|
||||||
// process user events through the normal OS EventLoop mechanisms.
|
|
||||||
let rl = CFRunLoopGetMain();
|
|
||||||
let mut context = CFRunLoopSourceContext {
|
|
||||||
version: 0,
|
|
||||||
info: ptr::null_mut(),
|
|
||||||
retain: None,
|
|
||||||
release: None,
|
|
||||||
copyDescription: None,
|
|
||||||
equal: None,
|
|
||||||
hash: None,
|
|
||||||
schedule: None,
|
|
||||||
cancel: None,
|
|
||||||
perform: event_loop_proxy_handler,
|
|
||||||
};
|
|
||||||
let source = CFRunLoopSourceCreate(ptr::null_mut(), CFIndex::MAX - 1, &mut context);
|
|
||||||
CFRunLoopAddSource(rl, source, kCFRunLoopCommonModes);
|
|
||||||
CFRunLoopWakeUp(rl);
|
|
||||||
|
|
||||||
EventLoopProxy { wake_up: AtomicBool::new(false), source }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventLoopProxyProvider for EventLoopProxy {
|
|
||||||
fn wake_up(&self) {
|
|
||||||
self.wake_up.store(true, AtomicOrdering::Relaxed);
|
|
||||||
unsafe {
|
|
||||||
// Let the main thread know there's a new event.
|
|
||||||
CFRunLoopSourceSignal(self.source);
|
|
||||||
let rl = CFRunLoopGetMain();
|
|
||||||
CFRunLoopWakeUp(rl);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
89
winit-appkit/src/ffi.rs
Normal file
89
winit-appkit/src/ffi.rs
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
// TODO: Upstream these
|
||||||
|
|
||||||
|
#![allow(non_upper_case_globals)]
|
||||||
|
|
||||||
|
use std::ffi::c_void;
|
||||||
|
|
||||||
|
use objc2::ffi::NSInteger;
|
||||||
|
use objc2::runtime::AnyObject;
|
||||||
|
use objc2_core_foundation::{cf_type, CFString, CFUUID};
|
||||||
|
use objc2_core_graphics::CGDirectDisplayID;
|
||||||
|
|
||||||
|
pub const IO16BitDirectPixels: &str = "-RRRRRGGGGGBBBBB";
|
||||||
|
pub const IO32BitDirectPixels: &str = "--------RRRRRRRRGGGGGGGGBBBBBBBB";
|
||||||
|
pub const kIO30BitDirectPixels: &str = "--RRRRRRRRRRGGGGGGGGGGBBBBBBBBBB";
|
||||||
|
pub const kIO64BitDirectPixels: &str = "-16R16G16B16";
|
||||||
|
|
||||||
|
// `CGDisplayCreateUUIDFromDisplayID` comes from the `ColorSync` framework.
|
||||||
|
// However, that framework was only introduced "publicly" in macOS 10.13.
|
||||||
|
//
|
||||||
|
// Since we want to support older versions, we can't link to `ColorSync`
|
||||||
|
// directly. Fortunately, it has always been available as a subframework of
|
||||||
|
// `ApplicationServices`, see:
|
||||||
|
// https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/OSX_Technology_Overview/SystemFrameworks/SystemFrameworks.html#//apple_ref/doc/uid/TP40001067-CH210-BBCFFIEG
|
||||||
|
#[link(name = "ApplicationServices", kind = "framework")]
|
||||||
|
extern "C" {
|
||||||
|
pub fn CGDisplayCreateUUIDFromDisplayID(display: CGDirectDisplayID) -> *mut CFUUID;
|
||||||
|
|
||||||
|
pub fn CGDisplayGetDisplayIDFromUUID(uuid: &CFUUID) -> CGDirectDisplayID;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[link(name = "CoreGraphics", kind = "framework")]
|
||||||
|
extern "C" {
|
||||||
|
// Wildly used private APIs; Apple uses them for their Terminal.app.
|
||||||
|
pub fn CGSMainConnectionID() -> *mut AnyObject;
|
||||||
|
pub fn CGSSetWindowBackgroundBlurRadius(
|
||||||
|
connection_id: *mut AnyObject,
|
||||||
|
window_id: NSInteger,
|
||||||
|
radius: i64,
|
||||||
|
) -> i32;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(transparent)]
|
||||||
|
pub struct TISInputSource(std::ffi::c_void);
|
||||||
|
|
||||||
|
cf_type!(
|
||||||
|
unsafe impl TISInputSource {}
|
||||||
|
);
|
||||||
|
|
||||||
|
#[repr(transparent)]
|
||||||
|
pub struct UCKeyboardLayout(std::ffi::c_void);
|
||||||
|
|
||||||
|
pub type OptionBits = u32;
|
||||||
|
pub type UniCharCount = std::os::raw::c_ulong;
|
||||||
|
pub type UniChar = std::os::raw::c_ushort;
|
||||||
|
pub type OSStatus = i32;
|
||||||
|
|
||||||
|
#[allow(non_upper_case_globals)]
|
||||||
|
pub const kUCKeyActionDisplay: u16 = 3;
|
||||||
|
#[allow(non_upper_case_globals)]
|
||||||
|
pub const kUCKeyTranslateNoDeadKeysMask: OptionBits = 1;
|
||||||
|
|
||||||
|
#[link(name = "Carbon", kind = "framework")]
|
||||||
|
extern "C" {
|
||||||
|
pub static kTISPropertyUnicodeKeyLayoutData: &'static CFString;
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
pub fn TISGetInputSourceProperty(
|
||||||
|
inputSource: &TISInputSource,
|
||||||
|
propertyKey: &CFString,
|
||||||
|
) -> *mut c_void;
|
||||||
|
|
||||||
|
pub fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut TISInputSource;
|
||||||
|
|
||||||
|
pub fn LMGetKbdType() -> u8;
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
pub fn UCKeyTranslate(
|
||||||
|
keyLayoutPtr: *const UCKeyboardLayout,
|
||||||
|
virtualKeyCode: u16,
|
||||||
|
keyAction: u16,
|
||||||
|
modifierKeyState: u32,
|
||||||
|
keyboardType: u32,
|
||||||
|
keyTranslateOptions: OptionBits,
|
||||||
|
deadKeyState: *mut u32,
|
||||||
|
maxStringLength: UniCharCount,
|
||||||
|
actualStringLength: *mut UniCharCount,
|
||||||
|
unicodeString: *mut UniChar,
|
||||||
|
) -> OSStatus;
|
||||||
|
}
|
||||||
@@ -17,30 +17,24 @@
|
|||||||
//! Instead, Winit guarantees that it will not register an application delegate, so the solution is
|
//! Instead, Winit guarantees that it will not register an application delegate, so the solution is
|
||||||
//! to register your own application delegate, as outlined in the following example (see
|
//! to register your own application delegate, as outlined in the following example (see
|
||||||
//! `objc2-app-kit` for more detailed information).
|
//! `objc2-app-kit` for more detailed information).
|
||||||
#![cfg_attr(target_os = "macos", doc = "```")]
|
//! ```
|
||||||
#![cfg_attr(not(target_os = "macos"), doc = "```ignore")]
|
|
||||||
//! use objc2::rc::Retained;
|
//! use objc2::rc::Retained;
|
||||||
//! use objc2::runtime::ProtocolObject;
|
//! use objc2::runtime::ProtocolObject;
|
||||||
//! use objc2::{declare_class, msg_send_id, mutability, ClassType, DeclaredClass};
|
//! use objc2::{define_class, msg_send, DefinedClass, MainThreadMarker, MainThreadOnly};
|
||||||
//! use objc2_app_kit::{NSApplication, NSApplicationDelegate};
|
//! use objc2_app_kit::{NSApplication, NSApplicationDelegate};
|
||||||
//! use objc2_foundation::{NSArray, NSURL, MainThreadMarker, NSObject, NSObjectProtocol};
|
//! use objc2_foundation::{NSArray, NSObject, NSObjectProtocol, NSURL};
|
||||||
//! use winit::event_loop::EventLoop;
|
//! use winit::event_loop::EventLoop;
|
||||||
//!
|
//!
|
||||||
//! declare_class!(
|
//! define_class!(
|
||||||
|
//! #[unsafe(super(NSObject))]
|
||||||
|
//! #[thread_kind = MainThreadOnly]
|
||||||
|
//! #[name = "AppDelegate"]
|
||||||
//! struct AppDelegate;
|
//! struct AppDelegate;
|
||||||
//!
|
//!
|
||||||
//! unsafe impl ClassType for AppDelegate {
|
|
||||||
//! type Super = NSObject;
|
|
||||||
//! type Mutability = mutability::MainThreadOnly;
|
|
||||||
//! const NAME: &'static str = "MyAppDelegate";
|
|
||||||
//! }
|
|
||||||
//!
|
|
||||||
//! impl DeclaredClass for AppDelegate {}
|
|
||||||
//!
|
|
||||||
//! unsafe impl NSObjectProtocol for AppDelegate {}
|
//! unsafe impl NSObjectProtocol for AppDelegate {}
|
||||||
//!
|
//!
|
||||||
//! unsafe impl NSApplicationDelegate for AppDelegate {
|
//! unsafe impl NSApplicationDelegate for AppDelegate {
|
||||||
//! #[method(application:openURLs:)]
|
//! #[unsafe(method(application:openURLs:))]
|
||||||
//! fn application_openURLs(&self, application: &NSApplication, urls: &NSArray<NSURL>) {
|
//! fn application_openURLs(&self, application: &NSApplication, urls: &NSArray<NSURL>) {
|
||||||
//! // Note: To specifically get `application:openURLs:` to work, you _might_
|
//! // Note: To specifically get `application:openURLs:` to work, you _might_
|
||||||
//! // have to bundle your application. This is not done in this example.
|
//! // have to bundle your application. This is not done in this example.
|
||||||
@@ -51,7 +45,7 @@
|
|||||||
//!
|
//!
|
||||||
//! impl AppDelegate {
|
//! impl AppDelegate {
|
||||||
//! fn new(mtm: MainThreadMarker) -> Retained<Self> {
|
//! fn new(mtm: MainThreadMarker) -> Retained<Self> {
|
||||||
//! unsafe { msg_send_id![super(mtm.alloc().set_ivars(())), init] }
|
//! unsafe { msg_send![super(Self::alloc(mtm).set_ivars(())), init] }
|
||||||
//! }
|
//! }
|
||||||
//! }
|
//! }
|
||||||
//!
|
//!
|
||||||
@@ -69,16 +63,40 @@
|
|||||||
//! Ok(())
|
//! Ok(())
|
||||||
//! }
|
//! }
|
||||||
//! ```
|
//! ```
|
||||||
|
#![cfg(target_vendor = "apple")] // TODO: Remove once `objc2` allows compiling on all platforms
|
||||||
|
|
||||||
|
#[macro_use]
|
||||||
|
mod util;
|
||||||
|
|
||||||
|
mod app;
|
||||||
|
mod app_state;
|
||||||
|
mod cursor;
|
||||||
|
mod event;
|
||||||
|
mod event_loop;
|
||||||
|
mod ffi;
|
||||||
|
mod menu;
|
||||||
|
mod monitor;
|
||||||
|
mod notification_center;
|
||||||
|
mod observer;
|
||||||
|
mod view;
|
||||||
|
mod window;
|
||||||
|
mod window_delegate;
|
||||||
|
|
||||||
use std::os::raw::c_void;
|
use std::os::raw::c_void;
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
#[doc(inline)]
|
||||||
|
pub use winit_core::application::macos::ApplicationHandlerExtMacOS;
|
||||||
|
use winit_core::event_loop::ActiveEventLoop;
|
||||||
|
use winit_core::monitor::MonitorHandle;
|
||||||
|
use winit_core::window::{PlatformWindowAttributes, Window};
|
||||||
|
|
||||||
use crate::application::ApplicationHandler;
|
pub use self::event::{physicalkey_to_scancode, scancode_to_physicalkey};
|
||||||
use crate::event_loop::{ActiveEventLoop, EventLoopBuilder};
|
use self::event_loop::ActiveEventLoop as AppKitActiveEventLoop;
|
||||||
use crate::monitor::MonitorHandle;
|
pub use self::event_loop::{EventLoop, PlatformSpecificEventLoopAttributes};
|
||||||
use crate::window::{Window, WindowAttributes, WindowId};
|
use self::monitor::MonitorHandle as AppKitMonitorHandle;
|
||||||
|
use self::window::Window as AppKitWindow;
|
||||||
|
|
||||||
/// Additional methods on [`Window`] that are specific to MacOS.
|
/// Additional methods on [`Window`] that are specific to MacOS.
|
||||||
pub trait WindowExtMacOS {
|
pub trait WindowExtMacOS {
|
||||||
@@ -155,7 +173,9 @@ pub trait WindowExtMacOS {
|
|||||||
/// Getter for the [`WindowExtMacOS::set_option_as_alt`].
|
/// Getter for the [`WindowExtMacOS::set_option_as_alt`].
|
||||||
fn option_as_alt(&self) -> OptionAsAlt;
|
fn option_as_alt(&self) -> OptionAsAlt;
|
||||||
|
|
||||||
/// Disable the Menu Bar and Dock in Borderless Fullscreen mode. Useful for games.
|
/// Disable the Menu Bar and Dock in Simple or Borderless Fullscreen mode. Useful for games.
|
||||||
|
/// The effect is applied when [`WindowExtMacOS::set_simple_fullscreen`] or
|
||||||
|
/// [`Window::set_fullscreen`] is called.
|
||||||
fn set_borderless_game(&self, borderless_game: bool);
|
fn set_borderless_game(&self, borderless_game: bool);
|
||||||
|
|
||||||
/// Getter for the [`WindowExtMacOS::set_borderless_game`].
|
/// Getter for the [`WindowExtMacOS::set_borderless_game`].
|
||||||
@@ -172,109 +192,109 @@ pub trait WindowExtMacOS {
|
|||||||
impl WindowExtMacOS for dyn Window + '_ {
|
impl WindowExtMacOS for dyn Window + '_ {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn simple_fullscreen(&self) -> bool {
|
fn simple_fullscreen(&self) -> bool {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(|w| w.simple_fullscreen())
|
window.maybe_wait_on_main(|w| w.simple_fullscreen())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool {
|
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(move |w| w.set_simple_fullscreen(fullscreen))
|
window.maybe_wait_on_main(move |w| w.set_simple_fullscreen(fullscreen))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn has_shadow(&self) -> bool {
|
fn has_shadow(&self) -> bool {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(|w| w.has_shadow())
|
window.maybe_wait_on_main(|w| w.has_shadow())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_has_shadow(&self, has_shadow: bool) {
|
fn set_has_shadow(&self, has_shadow: bool) {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(move |w| w.set_has_shadow(has_shadow));
|
window.maybe_wait_on_main(move |w| w.set_has_shadow(has_shadow));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_tabbing_identifier(&self, identifier: &str) {
|
fn set_tabbing_identifier(&self, identifier: &str) {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(|w| w.set_tabbing_identifier(identifier))
|
window.maybe_wait_on_main(|w| w.set_tabbing_identifier(identifier))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn tabbing_identifier(&self) -> String {
|
fn tabbing_identifier(&self) -> String {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(|w| w.tabbing_identifier())
|
window.maybe_wait_on_main(|w| w.tabbing_identifier())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn select_next_tab(&self) {
|
fn select_next_tab(&self) {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(|w| w.select_next_tab());
|
window.maybe_wait_on_main(|w| w.select_next_tab());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn select_previous_tab(&self) {
|
fn select_previous_tab(&self) {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(|w| w.select_previous_tab());
|
window.maybe_wait_on_main(|w| w.select_previous_tab());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn select_tab_at_index(&self, index: usize) {
|
fn select_tab_at_index(&self, index: usize) {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(move |w| w.select_tab_at_index(index));
|
window.maybe_wait_on_main(move |w| w.select_tab_at_index(index));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn num_tabs(&self) -> usize {
|
fn num_tabs(&self) -> usize {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(|w| w.num_tabs())
|
window.maybe_wait_on_main(|w| w.num_tabs())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn is_document_edited(&self) -> bool {
|
fn is_document_edited(&self) -> bool {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(|w| w.is_document_edited())
|
window.maybe_wait_on_main(|w| w.is_document_edited())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_document_edited(&self, edited: bool) {
|
fn set_document_edited(&self, edited: bool) {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(move |w| w.set_document_edited(edited));
|
window.maybe_wait_on_main(move |w| w.set_document_edited(edited));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) {
|
fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(move |w| w.set_option_as_alt(option_as_alt));
|
window.maybe_wait_on_main(move |w| w.set_option_as_alt(option_as_alt));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn option_as_alt(&self) -> OptionAsAlt {
|
fn option_as_alt(&self) -> OptionAsAlt {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(|w| w.option_as_alt())
|
window.maybe_wait_on_main(|w| w.option_as_alt())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_borderless_game(&self, borderless_game: bool) {
|
fn set_borderless_game(&self, borderless_game: bool) {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(|w| w.set_borderless_game(borderless_game))
|
window.maybe_wait_on_main(|w| w.set_borderless_game(borderless_game))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn is_borderless_game(&self) -> bool {
|
fn is_borderless_game(&self) -> bool {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(|w| w.is_borderless_game())
|
window.maybe_wait_on_main(|w| w.is_borderless_game())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_unified_titlebar(&self, unified_titlebar: bool) {
|
fn set_unified_titlebar(&self, unified_titlebar: bool) {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(|w| w.set_unified_titlebar(unified_titlebar))
|
window.maybe_wait_on_main(|w| w.set_unified_titlebar(unified_titlebar))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn unified_titlebar(&self) -> bool {
|
fn unified_titlebar(&self) -> bool {
|
||||||
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
window.maybe_wait_on_main(|w| w.unified_titlebar())
|
window.maybe_wait_on_main(|w| w.unified_titlebar())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -294,7 +314,7 @@ pub enum ActivationPolicy {
|
|||||||
Prohibited,
|
Prohibited,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Additional methods on [`WindowAttributes`] that are specific to MacOS.
|
/// Window attributes that are specific to MacOS.
|
||||||
///
|
///
|
||||||
/// **Note:** Properties dealing with the titlebar will be overwritten by the
|
/// **Note:** Properties dealing with the titlebar will be overwritten by the
|
||||||
/// [`WindowAttributes::with_decorations`] method:
|
/// [`WindowAttributes::with_decorations`] method:
|
||||||
@@ -303,114 +323,158 @@ pub enum ActivationPolicy {
|
|||||||
/// - `with_titlebar_hidden`
|
/// - `with_titlebar_hidden`
|
||||||
/// - `with_titlebar_buttons_hidden`
|
/// - `with_titlebar_buttons_hidden`
|
||||||
/// - `with_fullsize_content_view`
|
/// - `with_fullsize_content_view`
|
||||||
pub trait WindowAttributesExtMacOS {
|
///
|
||||||
|
/// [`WindowAttributes::with_decorations`]: crate::window::WindowAttributes::with_decorations
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct WindowAttributesMacOS {
|
||||||
|
pub(crate) movable_by_window_background: bool,
|
||||||
|
pub(crate) titlebar_transparent: bool,
|
||||||
|
pub(crate) title_hidden: bool,
|
||||||
|
pub(crate) titlebar_hidden: bool,
|
||||||
|
pub(crate) titlebar_buttons_hidden: bool,
|
||||||
|
pub(crate) fullsize_content_view: bool,
|
||||||
|
pub(crate) disallow_hidpi: bool,
|
||||||
|
pub(crate) has_shadow: bool,
|
||||||
|
pub(crate) accepts_first_mouse: bool,
|
||||||
|
pub(crate) tabbing_identifier: Option<String>,
|
||||||
|
pub(crate) option_as_alt: OptionAsAlt,
|
||||||
|
pub(crate) borderless_game: bool,
|
||||||
|
pub(crate) unified_titlebar: bool,
|
||||||
|
pub(crate) panel: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowAttributesMacOS {
|
||||||
/// Enables click-and-drag behavior for the entire window, not just the titlebar.
|
/// Enables click-and-drag behavior for the entire window, not just the titlebar.
|
||||||
fn with_movable_by_window_background(self, movable_by_window_background: bool) -> Self;
|
#[inline]
|
||||||
|
pub fn with_movable_by_window_background(mut self, movable_by_window_background: bool) -> Self {
|
||||||
|
self.movable_by_window_background = movable_by_window_background;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Makes the titlebar transparent and allows the content to appear behind it.
|
/// Makes the titlebar transparent and allows the content to appear behind it.
|
||||||
fn with_titlebar_transparent(self, titlebar_transparent: bool) -> Self;
|
#[inline]
|
||||||
/// Hides the window title.
|
pub fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> Self {
|
||||||
fn with_title_hidden(self, title_hidden: bool) -> Self;
|
self.titlebar_transparent = titlebar_transparent;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Hides the window titlebar.
|
/// Hides the window titlebar.
|
||||||
fn with_titlebar_hidden(self, titlebar_hidden: bool) -> Self;
|
#[inline]
|
||||||
|
pub fn with_titlebar_hidden(mut self, titlebar_hidden: bool) -> Self {
|
||||||
|
self.titlebar_hidden = titlebar_hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Hides the window titlebar buttons.
|
/// Hides the window titlebar buttons.
|
||||||
fn with_titlebar_buttons_hidden(self, titlebar_buttons_hidden: bool) -> Self;
|
#[inline]
|
||||||
|
pub fn with_titlebar_buttons_hidden(mut self, titlebar_buttons_hidden: bool) -> Self {
|
||||||
|
self.titlebar_buttons_hidden = titlebar_buttons_hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hides the window title.
|
||||||
|
#[inline]
|
||||||
|
pub fn with_title_hidden(mut self, title_hidden: bool) -> Self {
|
||||||
|
self.title_hidden = title_hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Makes the window content appear behind the titlebar.
|
/// Makes the window content appear behind the titlebar.
|
||||||
fn with_fullsize_content_view(self, fullsize_content_view: bool) -> Self;
|
#[inline]
|
||||||
fn with_disallow_hidpi(self, disallow_hidpi: bool) -> Self;
|
pub fn with_fullsize_content_view(mut self, fullsize_content_view: bool) -> Self {
|
||||||
fn with_has_shadow(self, has_shadow: bool) -> Self;
|
self.fullsize_content_view = fullsize_content_view;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn with_disallow_hidpi(mut self, disallow_hidpi: bool) -> Self {
|
||||||
|
self.disallow_hidpi = disallow_hidpi;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn with_has_shadow(mut self, has_shadow: bool) -> Self {
|
||||||
|
self.has_shadow = has_shadow;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Window accepts click-through mouse events.
|
/// Window accepts click-through mouse events.
|
||||||
fn with_accepts_first_mouse(self, accepts_first_mouse: bool) -> Self;
|
#[inline]
|
||||||
|
pub fn with_accepts_first_mouse(mut self, accepts_first_mouse: bool) -> Self {
|
||||||
|
self.accepts_first_mouse = accepts_first_mouse;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Defines the window tabbing identifier.
|
/// Defines the window tabbing identifier.
|
||||||
///
|
///
|
||||||
/// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
|
/// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
|
||||||
fn with_tabbing_identifier(self, identifier: &str) -> Self;
|
#[inline]
|
||||||
|
pub fn with_tabbing_identifier(mut self, tabbing_identifier: &str) -> Self {
|
||||||
|
self.tabbing_identifier.replace(tabbing_identifier.to_string());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Set how the <kbd>Option</kbd> keys are interpreted.
|
/// Set how the <kbd>Option</kbd> keys are interpreted.
|
||||||
///
|
///
|
||||||
/// See [`WindowExtMacOS::set_option_as_alt`] for details on what this means if set.
|
/// See [`WindowExtMacOS::set_option_as_alt`] for details on what this means if set.
|
||||||
fn with_option_as_alt(self, option_as_alt: OptionAsAlt) -> Self;
|
#[inline]
|
||||||
|
pub fn with_option_as_alt(mut self, option_as_alt: OptionAsAlt) -> Self {
|
||||||
|
self.option_as_alt = option_as_alt;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// See [`WindowExtMacOS::set_borderless_game`] for details on what this means if set.
|
/// See [`WindowExtMacOS::set_borderless_game`] for details on what this means if set.
|
||||||
fn with_borderless_game(self, borderless_game: bool) -> Self;
|
#[inline]
|
||||||
|
pub fn with_borderless_game(mut self, borderless_game: bool) -> Self {
|
||||||
|
self.borderless_game = borderless_game;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// See [`WindowExtMacOS::set_unified_titlebar`] for details on what this means if set.
|
/// See [`WindowExtMacOS::set_unified_titlebar`] for details on what this means if set.
|
||||||
fn with_unified_titlebar(self, unified_titlebar: bool) -> Self;
|
#[inline]
|
||||||
|
pub fn with_unified_titlebar(mut self, unified_titlebar: bool) -> Self {
|
||||||
|
self.unified_titlebar = unified_titlebar;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Use [`NSPanel`] window with [`NonactivatingPanel`] window style mask instead of
|
||||||
|
/// [`NSWindow`].
|
||||||
|
///
|
||||||
|
/// [`NSWindow`]: https://developer.apple.com/documentation/appkit/NSWindow?language=objc
|
||||||
|
/// [`NSPanel`]: https://developer.apple.com/documentation/appkit/NSPanel?language=objc
|
||||||
|
/// [`NonactivatingPanel`]: https://developer.apple.com/documentation/appkit/nswindow/stylemask-swift.struct/nonactivatingpanel?language=objc
|
||||||
|
#[inline]
|
||||||
|
pub fn with_panel(mut self, panel: bool) -> Self {
|
||||||
|
self.panel = panel;
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowAttributesExtMacOS for WindowAttributes {
|
impl Default for WindowAttributesMacOS {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_movable_by_window_background(mut self, movable_by_window_background: bool) -> Self {
|
fn default() -> Self {
|
||||||
self.platform_specific.movable_by_window_background = movable_by_window_background;
|
Self {
|
||||||
self
|
movable_by_window_background: false,
|
||||||
|
titlebar_transparent: false,
|
||||||
|
title_hidden: false,
|
||||||
|
titlebar_hidden: false,
|
||||||
|
titlebar_buttons_hidden: false,
|
||||||
|
fullsize_content_view: false,
|
||||||
|
disallow_hidpi: false,
|
||||||
|
has_shadow: true,
|
||||||
|
accepts_first_mouse: true,
|
||||||
|
tabbing_identifier: None,
|
||||||
|
option_as_alt: Default::default(),
|
||||||
|
borderless_game: false,
|
||||||
|
unified_titlebar: false,
|
||||||
|
panel: false,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
impl PlatformWindowAttributes for WindowAttributesMacOS {
|
||||||
fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> Self {
|
fn box_clone(&self) -> Box<dyn PlatformWindowAttributes> {
|
||||||
self.platform_specific.titlebar_transparent = titlebar_transparent;
|
Box::from(self.clone())
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_titlebar_hidden(mut self, titlebar_hidden: bool) -> Self {
|
|
||||||
self.platform_specific.titlebar_hidden = titlebar_hidden;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_titlebar_buttons_hidden(mut self, titlebar_buttons_hidden: bool) -> Self {
|
|
||||||
self.platform_specific.titlebar_buttons_hidden = titlebar_buttons_hidden;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_title_hidden(mut self, title_hidden: bool) -> Self {
|
|
||||||
self.platform_specific.title_hidden = title_hidden;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_fullsize_content_view(mut self, fullsize_content_view: bool) -> Self {
|
|
||||||
self.platform_specific.fullsize_content_view = fullsize_content_view;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_disallow_hidpi(mut self, disallow_hidpi: bool) -> Self {
|
|
||||||
self.platform_specific.disallow_hidpi = disallow_hidpi;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_has_shadow(mut self, has_shadow: bool) -> Self {
|
|
||||||
self.platform_specific.has_shadow = has_shadow;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_accepts_first_mouse(mut self, accepts_first_mouse: bool) -> Self {
|
|
||||||
self.platform_specific.accepts_first_mouse = accepts_first_mouse;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_tabbing_identifier(mut self, tabbing_identifier: &str) -> Self {
|
|
||||||
self.platform_specific.tabbing_identifier.replace(tabbing_identifier.to_string());
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_option_as_alt(mut self, option_as_alt: OptionAsAlt) -> Self {
|
|
||||||
self.platform_specific.option_as_alt = option_as_alt;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_borderless_game(mut self, borderless_game: bool) -> Self {
|
|
||||||
self.platform_specific.borderless_game = borderless_game;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_unified_titlebar(mut self, unified_titlebar: bool) -> Self {
|
|
||||||
self.platform_specific.unified_titlebar = unified_titlebar;
|
|
||||||
self
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -469,44 +533,18 @@ pub trait EventLoopBuilderExtMacOS {
|
|||||||
fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self;
|
fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventLoopBuilderExtMacOS for EventLoopBuilder {
|
|
||||||
#[inline]
|
|
||||||
fn with_activation_policy(&mut self, activation_policy: ActivationPolicy) -> &mut Self {
|
|
||||||
self.platform_specific.activation_policy = Some(activation_policy);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_default_menu(&mut self, enable: bool) -> &mut Self {
|
|
||||||
self.platform_specific.default_menu = enable;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self {
|
|
||||||
self.platform_specific.activate_ignoring_other_apps = ignore;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on [`MonitorHandle`] that are specific to MacOS.
|
/// Additional methods on [`MonitorHandle`] that are specific to MacOS.
|
||||||
pub trait MonitorHandleExtMacOS {
|
pub trait MonitorHandleExtMacOS {
|
||||||
/// Returns the identifier of the monitor for Cocoa.
|
|
||||||
fn native_id(&self) -> u32;
|
|
||||||
/// Returns a pointer to the NSScreen representing this monitor.
|
/// Returns a pointer to the NSScreen representing this monitor.
|
||||||
fn ns_screen(&self) -> Option<*mut c_void>;
|
fn ns_screen(&self) -> Option<*mut c_void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MonitorHandleExtMacOS for MonitorHandle {
|
impl MonitorHandleExtMacOS for MonitorHandle {
|
||||||
#[inline]
|
|
||||||
fn native_id(&self) -> u32 {
|
|
||||||
self.inner.native_identifier()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ns_screen(&self) -> Option<*mut c_void> {
|
fn ns_screen(&self) -> Option<*mut c_void> {
|
||||||
|
let monitor = self.cast_ref::<AppKitMonitorHandle>().unwrap();
|
||||||
// SAFETY: We only use the marker to get a pointer
|
// SAFETY: We only use the marker to get a pointer
|
||||||
let mtm = unsafe { objc2_foundation::MainThreadMarker::new_unchecked() };
|
let mtm = unsafe { objc2::MainThreadMarker::new_unchecked() };
|
||||||
self.inner.ns_screen(mtm).map(|s| objc2::rc::Retained::as_ptr(&s) as _)
|
monitor.ns_screen(mtm).map(|s| objc2::rc::Retained::as_ptr(&s) as _)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -528,34 +566,26 @@ pub trait ActiveEventLoopExtMacOS {
|
|||||||
|
|
||||||
impl ActiveEventLoopExtMacOS for dyn ActiveEventLoop + '_ {
|
impl ActiveEventLoopExtMacOS for dyn ActiveEventLoop + '_ {
|
||||||
fn hide_application(&self) {
|
fn hide_application(&self) {
|
||||||
let event_loop = self
|
let event_loop =
|
||||||
.as_any()
|
self.cast_ref::<AppKitActiveEventLoop>().expect("non macOS event loop on macOS");
|
||||||
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
|
||||||
.expect("non macOS event loop on macOS");
|
|
||||||
event_loop.hide_application()
|
event_loop.hide_application()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn hide_other_applications(&self) {
|
fn hide_other_applications(&self) {
|
||||||
let event_loop = self
|
let event_loop =
|
||||||
.as_any()
|
self.cast_ref::<AppKitActiveEventLoop>().expect("non macOS event loop on macOS");
|
||||||
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
|
||||||
.expect("non macOS event loop on macOS");
|
|
||||||
event_loop.hide_other_applications()
|
event_loop.hide_other_applications()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_allows_automatic_window_tabbing(&self, enabled: bool) {
|
fn set_allows_automatic_window_tabbing(&self, enabled: bool) {
|
||||||
let event_loop = self
|
let event_loop =
|
||||||
.as_any()
|
self.cast_ref::<AppKitActiveEventLoop>().expect("non macOS event loop on macOS");
|
||||||
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
|
||||||
.expect("non macOS event loop on macOS");
|
|
||||||
event_loop.set_allows_automatic_window_tabbing(enabled);
|
event_loop.set_allows_automatic_window_tabbing(enabled);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn allows_automatic_window_tabbing(&self) -> bool {
|
fn allows_automatic_window_tabbing(&self) -> bool {
|
||||||
let event_loop = self
|
let event_loop =
|
||||||
.as_any()
|
self.cast_ref::<AppKitActiveEventLoop>().expect("non macOS event loop on macOS");
|
||||||
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
|
||||||
.expect("non macOS event loop on macOS");
|
|
||||||
event_loop.allows_automatic_window_tabbing()
|
event_loop.allows_automatic_window_tabbing()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -579,52 +609,3 @@ pub enum OptionAsAlt {
|
|||||||
#[default]
|
#[default]
|
||||||
None,
|
None,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Additional events on [`ApplicationHandler`] that are specific to macOS.
|
|
||||||
///
|
|
||||||
/// This can be registered with [`ApplicationHandler::macos_handler`].
|
|
||||||
pub trait ApplicationHandlerExtMacOS: ApplicationHandler {
|
|
||||||
/// The system interpreted a keypress as a standard key binding command.
|
|
||||||
///
|
|
||||||
/// Examples include inserting tabs and newlines, or moving the insertion point, see
|
|
||||||
/// [`NSStandardKeyBindingResponding`] for the full list of key bindings. They are often text
|
|
||||||
/// editing related.
|
|
||||||
///
|
|
||||||
/// This corresponds to the [`doCommandBySelector:`] method on `NSTextInputClient`.
|
|
||||||
///
|
|
||||||
/// The `action` parameter contains the string representation of the selector. Examples include
|
|
||||||
/// `"insertBacktab:"`, `"indent:"` and `"noop:"`.
|
|
||||||
///
|
|
||||||
/// # Example
|
|
||||||
///
|
|
||||||
/// ```ignore
|
|
||||||
/// impl ApplicationHandlerExtMacOS for App {
|
|
||||||
/// fn standard_key_binding(
|
|
||||||
/// &mut self,
|
|
||||||
/// event_loop: &dyn ActiveEventLoop,
|
|
||||||
/// window_id: WindowId,
|
|
||||||
/// action: &str,
|
|
||||||
/// ) {
|
|
||||||
/// match action {
|
|
||||||
/// "moveBackward:" => self.cursor.position -= 1,
|
|
||||||
/// "moveForward:" => self.cursor.position += 1,
|
|
||||||
/// _ => {} // Ignore other actions
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// [`NSStandardKeyBindingResponding`]: https://developer.apple.com/documentation/appkit/nsstandardkeybindingresponding?language=objc
|
|
||||||
/// [`doCommandBySelector:`]: https://developer.apple.com/documentation/appkit/nstextinputclient/1438256-docommandbyselector?language=objc
|
|
||||||
#[doc(alias = "doCommandBySelector:")]
|
|
||||||
fn standard_key_binding(
|
|
||||||
&mut self,
|
|
||||||
event_loop: &dyn ActiveEventLoop,
|
|
||||||
window_id: WindowId,
|
|
||||||
action: &str,
|
|
||||||
) {
|
|
||||||
let _ = event_loop;
|
|
||||||
let _ = window_id;
|
|
||||||
let _ = action;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
use objc2::rc::Retained;
|
use objc2::rc::Retained;
|
||||||
use objc2::runtime::Sel;
|
use objc2::runtime::Sel;
|
||||||
use objc2::sel;
|
use objc2::{sel, MainThreadMarker};
|
||||||
use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSMenu, NSMenuItem};
|
use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSMenu, NSMenuItem};
|
||||||
use objc2_foundation::{ns_string, MainThreadMarker, NSProcessInfo, NSString};
|
use objc2_foundation::{ns_string, NSBundle, NSProcessInfo, NSString};
|
||||||
|
|
||||||
struct KeyEquivalent<'a> {
|
struct KeyEquivalent<'a> {
|
||||||
key: &'a NSString,
|
key: &'a NSString,
|
||||||
@@ -16,7 +16,10 @@ pub fn initialize(app: &NSApplication) {
|
|||||||
menubar.addItem(&app_menu_item);
|
menubar.addItem(&app_menu_item);
|
||||||
|
|
||||||
let app_menu = NSMenu::new(mtm);
|
let app_menu = NSMenu::new(mtm);
|
||||||
let process_name = NSProcessInfo::processInfo().processName();
|
let process_name = match NSBundle::mainBundle().name() {
|
||||||
|
Some(bundle_name) => bundle_name,
|
||||||
|
None => NSProcessInfo::processInfo().processName(),
|
||||||
|
};
|
||||||
|
|
||||||
// About menu item
|
// About menu item
|
||||||
let about_item_title = ns_string!("About ").stringByAppendingString(&process_name);
|
let about_item_title = ns_string!("About ").stringByAppendingString(&process_name);
|
||||||
@@ -48,10 +51,7 @@ pub fn initialize(app: &NSApplication) {
|
|||||||
Some(sel!(hideOtherApplications:)),
|
Some(sel!(hideOtherApplications:)),
|
||||||
Some(KeyEquivalent {
|
Some(KeyEquivalent {
|
||||||
key: ns_string!("h"),
|
key: ns_string!("h"),
|
||||||
masks: Some(
|
masks: Some(NSEventModifierFlags::Option | NSEventModifierFlags::Command),
|
||||||
NSEventModifierFlags::NSEventModifierFlagOption
|
|
||||||
| NSEventModifierFlags::NSEventModifierFlagCommand,
|
|
||||||
),
|
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
403
winit-appkit/src/monitor.rs
Normal file
403
winit-appkit/src/monitor.rs
Normal file
@@ -0,0 +1,403 @@
|
|||||||
|
#![allow(clippy::unnecessary_cast)]
|
||||||
|
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
use std::num::{NonZeroU16, NonZeroU32};
|
||||||
|
use std::ptr::NonNull;
|
||||||
|
use std::{fmt, ptr};
|
||||||
|
|
||||||
|
use dispatch2::run_on_main;
|
||||||
|
use dpi::{LogicalPosition, PhysicalPosition, PhysicalSize};
|
||||||
|
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::{kCVReturnSuccess, CVDisplayLink, CVTimeFlags};
|
||||||
|
use objc2_foundation::{ns_string, NSNumber, NSPoint, NSRect};
|
||||||
|
use tracing::warn;
|
||||||
|
use winit_core::monitor::{MonitorHandleProvider, VideoMode};
|
||||||
|
|
||||||
|
use super::ffi;
|
||||||
|
use super::util::cgerr;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct VideoModeHandle {
|
||||||
|
pub(crate) mode: VideoMode,
|
||||||
|
pub(crate) monitor: MonitorHandle,
|
||||||
|
pub(crate) native_mode: NativeDisplayMode,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for VideoModeHandle {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.monitor == other.monitor && self.mode == other.mode
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Eq for VideoModeHandle {}
|
||||||
|
|
||||||
|
impl std::hash::Hash for VideoModeHandle {
|
||||||
|
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||||
|
self.monitor.hash(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for VideoModeHandle {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("VideoModeHandle")
|
||||||
|
.field("mode", &self.mode)
|
||||||
|
.field("monitor", &self.monitor)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub struct NativeDisplayMode(pub CFRetained<CGDisplayMode>);
|
||||||
|
|
||||||
|
unsafe impl Send for NativeDisplayMode {}
|
||||||
|
unsafe impl Sync for NativeDisplayMode {}
|
||||||
|
|
||||||
|
impl VideoModeHandle {
|
||||||
|
fn new(
|
||||||
|
monitor: MonitorHandle,
|
||||||
|
native_mode: NativeDisplayMode,
|
||||||
|
refresh_rate_millihertz: Option<NonZeroU32>,
|
||||||
|
) -> Self {
|
||||||
|
unsafe {
|
||||||
|
// The bit-depth is basically always 32 since macOS 10.12.
|
||||||
|
#[allow(deprecated)]
|
||||||
|
let pixel_encoding =
|
||||||
|
CGDisplayMode::pixel_encoding(Some(&native_mode.0)).unwrap().to_string();
|
||||||
|
let bit_depth = if pixel_encoding.eq_ignore_ascii_case(ffi::IO32BitDirectPixels) {
|
||||||
|
NonZeroU16::new(32)
|
||||||
|
} else if pixel_encoding.eq_ignore_ascii_case(ffi::IO16BitDirectPixels) {
|
||||||
|
NonZeroU16::new(16)
|
||||||
|
} else if pixel_encoding.eq_ignore_ascii_case(ffi::kIO30BitDirectPixels) {
|
||||||
|
NonZeroU16::new(30)
|
||||||
|
} else if pixel_encoding.eq_ignore_ascii_case(ffi::kIO64BitDirectPixels) {
|
||||||
|
NonZeroU16::new(64)
|
||||||
|
} else {
|
||||||
|
warn!(?pixel_encoding, "unknown bit depth");
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let mode = VideoMode::new(
|
||||||
|
PhysicalSize::new(
|
||||||
|
CGDisplayMode::pixel_width(Some(&native_mode.0)) as u32,
|
||||||
|
CGDisplayMode::pixel_height(Some(&native_mode.0)) as u32,
|
||||||
|
),
|
||||||
|
bit_depth,
|
||||||
|
refresh_rate_millihertz,
|
||||||
|
);
|
||||||
|
|
||||||
|
VideoModeHandle { mode, monitor: monitor.clone(), native_mode }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `CGDirectDisplayID` is documented as:
|
||||||
|
/// > a framebuffer, a color correction (gamma) table, and possibly an attached monitor.
|
||||||
|
///
|
||||||
|
/// That is, it doesn't actually represent the monitor itself. Instead, we use the UUID of the
|
||||||
|
/// monitor, as retrieved from `CGDisplayCreateUUIDFromDisplayID` (this makes the monitor ID stable,
|
||||||
|
/// even across reboots and video mode changes).
|
||||||
|
///
|
||||||
|
/// NOTE: I'd be perfectly valid to store `[u8; 16]` in here instead, we only store `CFUUID` to
|
||||||
|
/// avoid having to re-create it when we want to fetch the display ID.
|
||||||
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub struct MonitorHandle(CFRetained<CFUUID>);
|
||||||
|
|
||||||
|
impl MonitorHandle {
|
||||||
|
/// Internal comparisons of [`MonitorHandle`]s are done first requesting a UUID for the handle.
|
||||||
|
fn uuid(&self) -> u128 {
|
||||||
|
u128::from_ne_bytes(self.0.uuid_bytes().into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn display_id(&self) -> CGDirectDisplayID {
|
||||||
|
unsafe { ffi::CGDisplayGetDisplayIDFromUUID(&self.0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[track_caller]
|
||||||
|
pub(crate) fn new(display_id: CGDirectDisplayID) -> Option<Self> {
|
||||||
|
// kCGNullDirectDisplay
|
||||||
|
if display_id == 0 {
|
||||||
|
// `CGDisplayCreateUUIDFromDisplayID` checks kCGNullDirectDisplay internally.
|
||||||
|
warn!("constructing monitor from invalid display ID 0; falling back to main monitor");
|
||||||
|
}
|
||||||
|
// SAFETY: Valid to call.
|
||||||
|
let ptr = unsafe { ffi::CGDisplayCreateUUIDFromDisplayID(display_id) };
|
||||||
|
let ptr = NonNull::new(ptr)?;
|
||||||
|
// SAFETY: `CGDisplayCreateUUIDFromDisplayID` is a "create" function, so the pointer has
|
||||||
|
// +1 retain count.
|
||||||
|
let uuid = unsafe { CFRetained::from_raw(ptr) };
|
||||||
|
Some(Self(uuid))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refresh_rate_millihertz(&self) -> Option<NonZeroU32> {
|
||||||
|
let current_display_mode =
|
||||||
|
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> {
|
||||||
|
let refresh_rate_millihertz = self.refresh_rate_millihertz();
|
||||||
|
let monitor = self.clone();
|
||||||
|
|
||||||
|
let array = unsafe { CGDisplayCopyAllDisplayModes(self.display_id(), None) };
|
||||||
|
let modes = if let Some(array) = array {
|
||||||
|
// SAFETY: `CGDisplayCopyAllDisplayModes` is documented to return an array of
|
||||||
|
// display modes.
|
||||||
|
unsafe { CFRetained::cast_unchecked::<CFArray<CGDisplayMode>>(array) }
|
||||||
|
} else {
|
||||||
|
// Occasionally, certain CalDigit Thunderbolt Hubs report a spurious monitor during
|
||||||
|
// sleep/wake/cycling monitors. It tends to have null or 1 video mode only.
|
||||||
|
// See <https://github.com/bevyengine/bevy/issues/17827>.
|
||||||
|
warn!(monitor = ?self, "failed to get a list of display modes");
|
||||||
|
CFArray::empty()
|
||||||
|
};
|
||||||
|
|
||||||
|
modes.into_iter().map(move |mode| {
|
||||||
|
let cg_refresh_rate_hertz = unsafe { CGDisplayMode::refresh_rate(Some(&mode)) };
|
||||||
|
|
||||||
|
// CGDisplayModeGetRefreshRate returns 0.0 for any display that
|
||||||
|
// isn't a CRT
|
||||||
|
let refresh_rate_millihertz = if cg_refresh_rate_hertz > 0.0 {
|
||||||
|
NonZeroU32::new((cg_refresh_rate_hertz * 1000.0).round() as u32)
|
||||||
|
} else {
|
||||||
|
refresh_rate_millihertz
|
||||||
|
};
|
||||||
|
|
||||||
|
VideoModeHandle::new(monitor.clone(), NativeDisplayMode(mode), refresh_rate_millihertz)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn ns_screen(&self, mtm: MainThreadMarker) -> Option<Retained<NSScreen>> {
|
||||||
|
let uuid = self.uuid();
|
||||||
|
NSScreen::screens(mtm).into_iter().find(|screen| {
|
||||||
|
let other_native_id = get_display_id(screen);
|
||||||
|
if let Some(other) = MonitorHandle::new(other_native_id) {
|
||||||
|
uuid == other.uuid()
|
||||||
|
} else {
|
||||||
|
// Display ID was just fetched from live NSScreen, but can still result in `None`
|
||||||
|
// with certain Thunderbolt docked monitors.
|
||||||
|
warn!(other_native_id, "comparing against screen with invalid display ID");
|
||||||
|
false
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonitorHandleProvider for MonitorHandle {
|
||||||
|
fn id(&self) -> u128 {
|
||||||
|
self.uuid()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn native_id(&self) -> u64 {
|
||||||
|
self.display_id() as _
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Be smarter about this:
|
||||||
|
//
|
||||||
|
// <https://github.com/glfw/glfw/blob/57cbded0760a50b9039ee0cb3f3c14f60145567c/src/cocoa_monitor.m#L44-L126>
|
||||||
|
fn name(&self) -> Option<std::borrow::Cow<'_, str>> {
|
||||||
|
let screen_num = unsafe { CGDisplayModelNumber(self.display_id()) };
|
||||||
|
Some(format!("Monitor #{screen_num}").into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn position(&self) -> Option<PhysicalPosition<i32>> {
|
||||||
|
// This is already in screen coordinates. If we were using `NSScreen`,
|
||||||
|
// then a conversion would've been needed:
|
||||||
|
// flip_window_screen_coordinates(self.ns_screen(mtm)?.frame())
|
||||||
|
let bounds = unsafe { CGDisplayBounds(self.display_id()) };
|
||||||
|
let position = LogicalPosition::new(bounds.origin.x, bounds.origin.y);
|
||||||
|
Some(position.to_physical(self.scale_factor()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scale_factor(&self) -> f64 {
|
||||||
|
run_on_main(|mtm| {
|
||||||
|
match self.ns_screen(mtm) {
|
||||||
|
Some(screen) => screen.backingScaleFactor() as f64,
|
||||||
|
None => 1.0, // default to 1.0 when we can't find the screen
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current_video_mode(&self) -> Option<VideoMode> {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn video_modes(&self) -> Box<dyn Iterator<Item = VideoMode>> {
|
||||||
|
Box::new(self.video_mode_handles().map(|mode| mode.mode))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn available_monitors() -> VecDeque<MonitorHandle> {
|
||||||
|
let mut expected_count = 0;
|
||||||
|
let res = cgerr(unsafe { CGGetActiveDisplayList(0, ptr::null_mut(), &mut expected_count) });
|
||||||
|
if res.is_err() {
|
||||||
|
return VecDeque::with_capacity(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut displays: Vec<CGDirectDisplayID> = vec![0; expected_count as usize];
|
||||||
|
let mut actual_count = 0;
|
||||||
|
let res = cgerr(unsafe {
|
||||||
|
CGGetActiveDisplayList(expected_count, displays.as_mut_ptr(), &mut actual_count)
|
||||||
|
});
|
||||||
|
displays.truncate(actual_count as usize);
|
||||||
|
|
||||||
|
if res.is_err() {
|
||||||
|
return VecDeque::with_capacity(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut monitors = VecDeque::with_capacity(displays.len());
|
||||||
|
for display in displays {
|
||||||
|
// Display ID just fetched from `CGGetActiveDisplayList`, should be fine to unwrap.
|
||||||
|
monitors.push_back(MonitorHandle::new(display).expect("invalid display ID"));
|
||||||
|
}
|
||||||
|
monitors
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn primary_monitor() -> MonitorHandle {
|
||||||
|
// Display ID just fetched from `CGMainDisplayID`, should be fine to unwrap.
|
||||||
|
MonitorHandle::new(unsafe { CGMainDisplayID() }).expect("invalid display ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for MonitorHandle {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("MonitorHandle")
|
||||||
|
.field("name", &self.name())
|
||||||
|
.field("uuid", &self.uuid())
|
||||||
|
.field("display_id", &self.display_id())
|
||||||
|
.field("position", &self.position())
|
||||||
|
.field("scale_factor", &self.scale_factor())
|
||||||
|
.finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn get_display_id(screen: &NSScreen) -> u32 {
|
||||||
|
let key = ns_string!("NSScreenNumber");
|
||||||
|
|
||||||
|
objc2::rc::autoreleasepool(|_| {
|
||||||
|
let device_description = screen.deviceDescription();
|
||||||
|
|
||||||
|
// Retrieve the CGDirectDisplayID associated with this screen
|
||||||
|
//
|
||||||
|
// The value from @"NSScreenNumber" in deviceDescription is guaranteed
|
||||||
|
// to be an NSNumber. See documentation for details:
|
||||||
|
// <https://developer.apple.com/documentation/appkit/nsscreen/1388360-devicedescription?language=objc>
|
||||||
|
let obj = device_description
|
||||||
|
.objectForKey(key)
|
||||||
|
.expect("failed getting screen display id from device description")
|
||||||
|
.downcast::<NSNumber>()
|
||||||
|
.expect("NSScreenNumber must be NSNumber");
|
||||||
|
|
||||||
|
obj.as_u32()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Core graphics screen coordinates are relative to the top-left corner of
|
||||||
|
/// the so-called "main" display, with y increasing downwards - which is
|
||||||
|
/// exactly what we want in Winit.
|
||||||
|
///
|
||||||
|
/// However, `NSWindow` and `NSScreen` changes these coordinates to:
|
||||||
|
/// 1. Be relative to the bottom-left corner of the "main" screen.
|
||||||
|
/// 2. Be relative to the bottom-left corner of the window/screen itself.
|
||||||
|
/// 3. Have y increasing upwards.
|
||||||
|
///
|
||||||
|
/// This conversion happens to be symmetric, so we only need this one function
|
||||||
|
/// to convert between the two coordinate systems.
|
||||||
|
pub(crate) fn flip_window_screen_coordinates(frame: NSRect) -> NSPoint {
|
||||||
|
// It is intentional that we use `CGMainDisplayID` (as opposed to
|
||||||
|
// `NSScreen::mainScreen`), because that's what the screen coordinates
|
||||||
|
// are relative to, no matter which display the window is currently on.
|
||||||
|
let main_screen_height = unsafe { CGDisplayBounds(CGMainDisplayID()) }.size.height;
|
||||||
|
|
||||||
|
let y = main_screen_height - frame.size.height - frame.origin.y;
|
||||||
|
NSPoint::new(frame.origin.x, y)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refresh_rate_millihertz(id: CGDirectDisplayID, mode: &NativeDisplayMode) -> Option<NonZeroU32> {
|
||||||
|
unsafe {
|
||||||
|
let refresh_rate = CGDisplayMode::refresh_rate(Some(&mode.0));
|
||||||
|
if refresh_rate > 0.0 {
|
||||||
|
return NonZeroU32::new((refresh_rate * 1000.0).round() as u32);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut display_link = std::ptr::null_mut();
|
||||||
|
#[allow(deprecated)]
|
||||||
|
if CVDisplayLink::create_with_cg_display(id, NonNull::from(&mut display_link))
|
||||||
|
!= kCVReturnSuccess
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let display_link = CFRetained::from_raw(NonNull::new(display_link).unwrap());
|
||||||
|
#[allow(deprecated)]
|
||||||
|
let time = display_link.nominal_output_video_refresh_period();
|
||||||
|
|
||||||
|
// This value is indefinite if an invalid display link was specified
|
||||||
|
if time.flags & CVTimeFlags::IsIndefinite.0 != 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
(time.timeScale as i64)
|
||||||
|
.checked_div(time.timeValue)
|
||||||
|
.map(|v| (v * 1000) as u32)
|
||||||
|
.and_then(NonZeroU32::new)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn uuid_stable() {
|
||||||
|
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());
|
||||||
|
|
||||||
|
let handle_a = primary_monitor();
|
||||||
|
let handle_b = primary_monitor();
|
||||||
|
assert_eq!(handle_a, handle_b);
|
||||||
|
assert_eq!(handle_a.display_id(), handle_b.display_id());
|
||||||
|
assert_eq!(handle_a.uuid(), handle_b.uuid());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Test the MonitorHandle::new fallback.
|
||||||
|
#[test]
|
||||||
|
fn monitorhandle_from_zero() {
|
||||||
|
let handle0 = MonitorHandle::new(0).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());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn from_invalid_id() {
|
||||||
|
// Assume there are never this many monitors connected.
|
||||||
|
assert!(MonitorHandle::new(10000).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Test that calling `CGDisplayGetDisplayIDFromUUID` on an invalid UUID returns an invalid
|
||||||
|
/// display ID.
|
||||||
|
#[test]
|
||||||
|
fn invalid_monitor_handle() {
|
||||||
|
// `CGMainDisplayID` must be called to avoid:
|
||||||
|
// ```
|
||||||
|
// Assertion failed: (did_initialize), function CGS_REQUIRE_INIT, file CGInitialization.c, line 44.
|
||||||
|
// ```
|
||||||
|
// See https://github.com/JXA-Cookbook/JXA-Cookbook/issues/27#issuecomment-277517668
|
||||||
|
let _ = unsafe { CGMainDisplayID() };
|
||||||
|
|
||||||
|
let handle = MonitorHandle(CFUUID::new(None).unwrap());
|
||||||
|
assert_eq!(handle.display_id(), 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,18 +1,22 @@
|
|||||||
|
// NOTE: This is symlinked to be contained in both the AppKit and UIKit implementations.
|
||||||
use std::ptr::NonNull;
|
use std::ptr::NonNull;
|
||||||
|
|
||||||
use block2::RcBlock;
|
use block2::RcBlock;
|
||||||
use objc2::rc::Retained;
|
use objc2::rc::Retained;
|
||||||
use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName, NSObject};
|
use objc2::runtime::ProtocolObject;
|
||||||
|
use objc2_foundation::{
|
||||||
|
NSNotification, NSNotificationCenter, NSNotificationName, NSObjectProtocol,
|
||||||
|
};
|
||||||
|
|
||||||
/// Observe the given notification.
|
/// Observe the given notification.
|
||||||
///
|
///
|
||||||
/// This is used in Winit as an alternative to declaring an application delegate, as we want to
|
/// This is used in Winit as an alternative to declaring an application delegate, as we want to
|
||||||
/// give the user full control over those.
|
/// give the user full control over those.
|
||||||
pub fn create_observer(
|
pub(crate) fn create_observer(
|
||||||
center: &NSNotificationCenter,
|
center: &NSNotificationCenter,
|
||||||
name: &NSNotificationName,
|
name: &NSNotificationName,
|
||||||
handler: impl Fn(&NSNotification) + 'static,
|
handler: impl Fn(&NSNotification) + 'static,
|
||||||
) -> Retained<NSObject> {
|
) -> Retained<ProtocolObject<dyn NSObjectProtocol>> {
|
||||||
let block = RcBlock::new(move |notification: NonNull<NSNotification>| {
|
let block = RcBlock::new(move |notification: NonNull<NSNotification>| {
|
||||||
handler(unsafe { notification.as_ref() });
|
handler(unsafe { notification.as_ref() });
|
||||||
});
|
});
|
||||||
@@ -4,132 +4,76 @@
|
|||||||
//! <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html>
|
//! <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html>
|
||||||
use std::cell::Cell;
|
use std::cell::Cell;
|
||||||
use std::ffi::c_void;
|
use std::ffi::c_void;
|
||||||
use std::panic::{AssertUnwindSafe, UnwindSafe};
|
|
||||||
use std::ptr;
|
use std::ptr;
|
||||||
use std::rc::Weak;
|
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
use block2::Block;
|
use objc2::MainThreadMarker;
|
||||||
use core_foundation::base::{CFIndex, CFOptionFlags, CFRelease, CFTypeRef};
|
use objc2_core_foundation::{
|
||||||
use core_foundation::date::CFAbsoluteTimeGetCurrent;
|
kCFRunLoopCommonModes, kCFRunLoopDefaultMode, CFAbsoluteTimeGetCurrent, CFIndex, CFRetained,
|
||||||
use core_foundation::runloop::{
|
CFRunLoop, CFRunLoopActivity, CFRunLoopObserver, CFRunLoopObserverCallBack,
|
||||||
kCFRunLoopAfterWaiting, kCFRunLoopBeforeWaiting, kCFRunLoopCommonModes, kCFRunLoopDefaultMode,
|
CFRunLoopObserverContext, CFRunLoopTimer,
|
||||||
kCFRunLoopExit, CFRunLoopActivity, CFRunLoopAddObserver, CFRunLoopAddTimer, CFRunLoopGetMain,
|
|
||||||
CFRunLoopObserverCallBack, CFRunLoopObserverContext, CFRunLoopObserverCreate,
|
|
||||||
CFRunLoopObserverRef, CFRunLoopRef, CFRunLoopTimerCreate, CFRunLoopTimerInvalidate,
|
|
||||||
CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate, CFRunLoopWakeUp,
|
|
||||||
};
|
};
|
||||||
use objc2_foundation::MainThreadMarker;
|
|
||||||
use tracing::error;
|
use tracing::error;
|
||||||
|
|
||||||
use super::app_state::AppState;
|
use super::app_state::AppState;
|
||||||
use super::event_loop::{stop_app_on_panic, PanicInfo};
|
|
||||||
use super::ffi;
|
|
||||||
|
|
||||||
unsafe fn control_flow_handler<F>(panic_info: *mut c_void, f: F)
|
|
||||||
where
|
|
||||||
F: FnOnce(Weak<PanicInfo>) + UnwindSafe,
|
|
||||||
{
|
|
||||||
let info_from_raw = unsafe { Weak::from_raw(panic_info as *mut PanicInfo) };
|
|
||||||
// Asserting unwind safety on this type should be fine because `PanicInfo` is
|
|
||||||
// `RefUnwindSafe` and `Rc<T>` is `UnwindSafe` if `T` is `RefUnwindSafe`.
|
|
||||||
let panic_info = AssertUnwindSafe(Weak::clone(&info_from_raw));
|
|
||||||
// `from_raw` takes ownership of the data behind the pointer.
|
|
||||||
// But if this scope takes ownership of the weak pointer, then
|
|
||||||
// the weak pointer will get free'd at the end of the scope.
|
|
||||||
// However we want to keep that weak reference around after the function.
|
|
||||||
std::mem::forget(info_from_raw);
|
|
||||||
|
|
||||||
let mtm = MainThreadMarker::new().unwrap();
|
|
||||||
stop_app_on_panic(mtm, Weak::clone(&panic_info), move || {
|
|
||||||
let _ = &panic_info;
|
|
||||||
f(panic_info.0)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// begin is queued with the highest priority to ensure it is processed before other observers
|
// begin is queued with the highest priority to ensure it is processed before other observers
|
||||||
extern "C" fn control_flow_begin_handler(
|
extern "C-unwind" fn control_flow_begin_handler(
|
||||||
_: CFRunLoopObserverRef,
|
_: *mut CFRunLoopObserver,
|
||||||
activity: CFRunLoopActivity,
|
activity: CFRunLoopActivity,
|
||||||
panic_info: *mut c_void,
|
_info: *mut c_void,
|
||||||
) {
|
) {
|
||||||
unsafe {
|
match activity {
|
||||||
control_flow_handler(panic_info, |panic_info| {
|
CFRunLoopActivity::AfterWaiting => {
|
||||||
#[allow(non_upper_case_globals)]
|
AppState::get(MainThreadMarker::new().unwrap()).wakeup();
|
||||||
match activity {
|
},
|
||||||
kCFRunLoopAfterWaiting => {
|
_ => unreachable!(),
|
||||||
// trace!("Triggered `CFRunLoopAfterWaiting`");
|
|
||||||
AppState::get(MainThreadMarker::new().unwrap()).wakeup(panic_info);
|
|
||||||
// trace!("Completed `CFRunLoopAfterWaiting`");
|
|
||||||
},
|
|
||||||
_ => unreachable!(),
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// end is queued with the lowest priority to ensure it is processed after other observers
|
// end is queued with the lowest priority to ensure it is processed after other observers
|
||||||
// without that, LoopExiting would get sent after AboutToWait
|
// without that, LoopExiting would get sent after AboutToWait
|
||||||
extern "C" fn control_flow_end_handler(
|
extern "C-unwind" fn control_flow_end_handler(
|
||||||
_: CFRunLoopObserverRef,
|
_: *mut CFRunLoopObserver,
|
||||||
activity: CFRunLoopActivity,
|
activity: CFRunLoopActivity,
|
||||||
panic_info: *mut c_void,
|
_info: *mut c_void,
|
||||||
) {
|
) {
|
||||||
unsafe {
|
match activity {
|
||||||
control_flow_handler(panic_info, |panic_info| {
|
CFRunLoopActivity::BeforeWaiting => {
|
||||||
#[allow(non_upper_case_globals)]
|
AppState::get(MainThreadMarker::new().unwrap()).cleared();
|
||||||
match activity {
|
},
|
||||||
kCFRunLoopBeforeWaiting => {
|
CFRunLoopActivity::Exit => (), // unimplemented!(), // not expected to ever happen
|
||||||
// trace!("Triggered `CFRunLoopBeforeWaiting`");
|
_ => unreachable!(),
|
||||||
AppState::get(MainThreadMarker::new().unwrap()).cleared(panic_info);
|
|
||||||
// trace!("Completed `CFRunLoopBeforeWaiting`");
|
|
||||||
},
|
|
||||||
kCFRunLoopExit => (), // unimplemented!(), // not expected to ever happen
|
|
||||||
_ => unreachable!(),
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct RunLoop(CFRunLoopRef);
|
pub struct RunLoop(CFRetained<CFRunLoop>);
|
||||||
|
|
||||||
impl Default for RunLoop {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self(ptr::null_mut())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RunLoop {
|
impl RunLoop {
|
||||||
pub fn main(mtm: MainThreadMarker) -> Self {
|
pub fn main(mtm: MainThreadMarker) -> Self {
|
||||||
// SAFETY: We have a MainThreadMarker here, which means we know we're on the main thread, so
|
// 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.
|
// scheduling (and scheduling a non-`Send` block) to that thread is allowed.
|
||||||
let _ = mtm;
|
let _ = mtm;
|
||||||
RunLoop(unsafe { CFRunLoopGetMain() })
|
RunLoop(CFRunLoop::main().unwrap())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn wakeup(&self) {
|
pub fn wakeup(&self) {
|
||||||
unsafe { CFRunLoopWakeUp(self.0) }
|
self.0.wake_up();
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe fn add_observer(
|
unsafe fn add_observer(
|
||||||
&self,
|
&self,
|
||||||
flags: CFOptionFlags,
|
flags: CFRunLoopActivity,
|
||||||
|
// The lower the value, the sooner this will run
|
||||||
priority: CFIndex,
|
priority: CFIndex,
|
||||||
handler: CFRunLoopObserverCallBack,
|
handler: CFRunLoopObserverCallBack,
|
||||||
context: *mut CFRunLoopObserverContext,
|
context: *mut CFRunLoopObserverContext,
|
||||||
) {
|
) {
|
||||||
let observer = unsafe {
|
let observer =
|
||||||
CFRunLoopObserverCreate(
|
unsafe { CFRunLoopObserver::new(None, flags.0, true, priority, handler, context) }
|
||||||
ptr::null_mut(),
|
.unwrap();
|
||||||
flags,
|
self.0.add_observer(Some(&observer), unsafe { kCFRunLoopCommonModes });
|
||||||
ffi::TRUE, // Indicates we want this to run repeatedly
|
|
||||||
priority, // The lower the value, the sooner this will run
|
|
||||||
handler,
|
|
||||||
context,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
unsafe { CFRunLoopAddObserver(self.0, observer, kCFRunLoopCommonModes) };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Submit a closure to run on the main thread as the next step in the run loop, before other
|
/// Submit a closure to run on the main thread as the next step in the run loop, before other
|
||||||
@@ -166,10 +110,6 @@ impl RunLoop {
|
|||||||
/// put the event at the very front of the queue, to be handled as soon as possible after
|
/// 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.
|
/// handling whatever event it's currently handling.
|
||||||
pub fn queue_closure(&self, closure: impl FnOnce() + 'static) {
|
pub fn queue_closure(&self, closure: impl FnOnce() + 'static) {
|
||||||
extern "C" {
|
|
||||||
fn CFRunLoopPerformBlock(rl: CFRunLoopRef, mode: CFTypeRef, block: &Block<dyn Fn()>);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert `FnOnce()` to `Block<dyn Fn()>`.
|
// Convert `FnOnce()` to `Block<dyn Fn()>`.
|
||||||
let closure = Cell::new(Some(closure));
|
let closure = Cell::new(Some(closure));
|
||||||
let block = block2::RcBlock::new(move || {
|
let block = block2::RcBlock::new(move || {
|
||||||
@@ -195,33 +135,33 @@ impl RunLoop {
|
|||||||
// and be delivered to the application afterwards.
|
// and be delivered to the application afterwards.
|
||||||
//
|
//
|
||||||
// [#1779]: https://github.com/rust-windowing/winit/issues/1779
|
// [#1779]: https://github.com/rust-windowing/winit/issues/1779
|
||||||
let mode = unsafe { kCFRunLoopDefaultMode as CFTypeRef };
|
let mode = unsafe { kCFRunLoopDefaultMode.unwrap() };
|
||||||
|
|
||||||
// SAFETY: The runloop is valid, the mode is a `CFStringRef`, and the block is `'static`.
|
// SAFETY: The runloop is valid, the mode is a `CFStringRef`, and the block is `'static`.
|
||||||
unsafe { CFRunLoopPerformBlock(self.0, mode, &block) }
|
unsafe { self.0.perform_block(Some(mode), Some(&block)) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn setup_control_flow_observers(mtm: MainThreadMarker, panic_info: Weak<PanicInfo>) {
|
pub fn setup_control_flow_observers(mtm: MainThreadMarker) {
|
||||||
let run_loop = RunLoop::main(mtm);
|
let run_loop = RunLoop::main(mtm);
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut context = CFRunLoopObserverContext {
|
let mut context = CFRunLoopObserverContext {
|
||||||
info: Weak::into_raw(panic_info) as *mut _,
|
info: ptr::null_mut(),
|
||||||
version: 0,
|
version: 0,
|
||||||
retain: None,
|
retain: None,
|
||||||
release: None,
|
release: None,
|
||||||
copyDescription: None,
|
copyDescription: None,
|
||||||
};
|
};
|
||||||
run_loop.add_observer(
|
run_loop.add_observer(
|
||||||
kCFRunLoopAfterWaiting,
|
CFRunLoopActivity::AfterWaiting,
|
||||||
CFIndex::MIN,
|
CFIndex::MIN,
|
||||||
control_flow_begin_handler,
|
Some(control_flow_begin_handler),
|
||||||
&mut context as *mut _,
|
&mut context as *mut _,
|
||||||
);
|
);
|
||||||
run_loop.add_observer(
|
run_loop.add_observer(
|
||||||
kCFRunLoopExit | kCFRunLoopBeforeWaiting,
|
CFRunLoopActivity::Exit | CFRunLoopActivity::BeforeWaiting,
|
||||||
CFIndex::MAX,
|
CFIndex::MAX,
|
||||||
control_flow_end_handler,
|
Some(control_flow_end_handler),
|
||||||
&mut context as *mut _,
|
&mut context as *mut _,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -229,7 +169,7 @@ pub fn setup_control_flow_observers(mtm: MainThreadMarker, panic_info: Weak<Pani
|
|||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct EventLoopWaker {
|
pub struct EventLoopWaker {
|
||||||
timer: CFRunLoopTimerRef,
|
timer: CFRetained<CFRunLoopTimer>,
|
||||||
|
|
||||||
/// An arbitrary instant in the past, that will trigger an immediate wake
|
/// An arbitrary instant in the past, that will trigger an immediate wake
|
||||||
/// We save this as the `next_fire_date` for consistency so we can
|
/// We save this as the `next_fire_date` for consistency so we can
|
||||||
@@ -244,30 +184,28 @@ pub struct EventLoopWaker {
|
|||||||
|
|
||||||
impl Drop for EventLoopWaker {
|
impl Drop for EventLoopWaker {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
unsafe {
|
self.timer.invalidate();
|
||||||
CFRunLoopTimerInvalidate(self.timer);
|
|
||||||
CFRelease(self.timer as _);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventLoopWaker {
|
impl EventLoopWaker {
|
||||||
pub(crate) fn new() -> Self {
|
pub(crate) fn new() -> Self {
|
||||||
extern "C" fn wakeup_main_loop(_timer: CFRunLoopTimerRef, _info: *mut c_void) {}
|
extern "C-unwind" fn wakeup_main_loop(_timer: *mut CFRunLoopTimer, _info: *mut c_void) {}
|
||||||
unsafe {
|
unsafe {
|
||||||
// Create a timer with a 0.1µs interval (1ns does not work) to mimic polling.
|
// Create a timer with a 0.1µs interval (1ns does not work) to mimic polling.
|
||||||
// It is initially setup with a first fire time really far into the
|
// It is initially setup with a first fire time really far into the
|
||||||
// future, but that gets changed to fire immediately in did_finish_launching
|
// future, but that gets changed to fire immediately in did_finish_launching
|
||||||
let timer = CFRunLoopTimerCreate(
|
let timer = CFRunLoopTimer::new(
|
||||||
ptr::null_mut(),
|
None,
|
||||||
f64::MAX,
|
f64::MAX,
|
||||||
0.000_000_1,
|
0.000_000_1,
|
||||||
0,
|
0,
|
||||||
0,
|
0,
|
||||||
wakeup_main_loop,
|
Some(wakeup_main_loop),
|
||||||
ptr::null_mut(),
|
ptr::null_mut(),
|
||||||
);
|
)
|
||||||
CFRunLoopAddTimer(CFRunLoopGetMain(), timer, kCFRunLoopCommonModes);
|
.unwrap();
|
||||||
|
CFRunLoop::main().unwrap().add_timer(Some(&timer), kCFRunLoopCommonModes);
|
||||||
Self { timer, start_instant: Instant::now(), next_fire_date: None }
|
Self { timer, start_instant: Instant::now(), next_fire_date: None }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -275,14 +213,14 @@ impl EventLoopWaker {
|
|||||||
pub fn stop(&mut self) {
|
pub fn stop(&mut self) {
|
||||||
if self.next_fire_date.is_some() {
|
if self.next_fire_date.is_some() {
|
||||||
self.next_fire_date = None;
|
self.next_fire_date = None;
|
||||||
unsafe { CFRunLoopTimerSetNextFireDate(self.timer, f64::MAX) }
|
self.timer.set_next_fire_date(f64::MAX);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn start(&mut self) {
|
pub fn start(&mut self) {
|
||||||
if self.next_fire_date != Some(self.start_instant) {
|
if self.next_fire_date != Some(self.start_instant) {
|
||||||
self.next_fire_date = Some(self.start_instant);
|
self.next_fire_date = Some(self.start_instant);
|
||||||
unsafe { CFRunLoopTimerSetNextFireDate(self.timer, f64::MIN) }
|
self.timer.set_next_fire_date(f64::MIN);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -295,13 +233,11 @@ impl EventLoopWaker {
|
|||||||
Some(instant) => {
|
Some(instant) => {
|
||||||
if self.next_fire_date != Some(instant) {
|
if self.next_fire_date != Some(instant) {
|
||||||
self.next_fire_date = Some(instant);
|
self.next_fire_date = Some(instant);
|
||||||
unsafe {
|
let current = CFAbsoluteTimeGetCurrent();
|
||||||
let current = CFAbsoluteTimeGetCurrent();
|
let duration = instant - now;
|
||||||
let duration = instant - now;
|
let fsecs = duration.subsec_nanos() as f64 / 1_000_000_000.0
|
||||||
let fsecs = duration.subsec_nanos() as f64 / 1_000_000_000.0
|
+ duration.as_secs() as f64;
|
||||||
+ duration.as_secs() as f64;
|
self.timer.set_next_fire_date(current + fsecs);
|
||||||
CFRunLoopTimerSetNextFireDate(self.timer, current + fsecs)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
None => {
|
None => {
|
||||||
@@ -1,9 +1,16 @@
|
|||||||
|
use objc2_core_graphics::CGError;
|
||||||
use tracing::trace;
|
use tracing::trace;
|
||||||
|
use winit_core::error::OsError;
|
||||||
|
|
||||||
|
macro_rules! os_error {
|
||||||
|
($error:expr) => {{
|
||||||
|
winit_core::error::OsError::new(line!(), file!(), $error)
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
macro_rules! trace_scope {
|
macro_rules! trace_scope {
|
||||||
($s:literal) => {
|
($s:literal) => {
|
||||||
let _crate =
|
let _crate = $crate::util::TraceGuard::new(module_path!(), $s);
|
||||||
$crate::platform_impl::platform::appkit::util::TraceGuard::new(module_path!(), $s);
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,3 +33,12 @@ impl Drop for TraceGuard {
|
|||||||
trace!(target = self.module_path, "Completed `{}`", self.called_from_fn);
|
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:?}")))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,33 +4,34 @@ use std::collections::{HashMap, VecDeque};
|
|||||||
use std::ptr;
|
use std::ptr;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
|
use dpi::{LogicalPosition, LogicalSize};
|
||||||
use objc2::rc::Retained;
|
use objc2::rc::Retained;
|
||||||
use objc2::runtime::{AnyObject, Sel};
|
use objc2::runtime::{AnyObject, Sel};
|
||||||
use objc2::{declare_class, msg_send_id, mutability, ClassType, DeclaredClass};
|
use objc2::{define_class, msg_send, DefinedClass, MainThreadMarker};
|
||||||
use objc2_app_kit::{
|
use objc2_app_kit::{
|
||||||
NSApplication, NSCursor, NSEvent, NSEventPhase, NSResponder, NSTextInputClient,
|
NSApplication, NSCursor, NSEvent, NSEventPhase, NSResponder, NSTextInputClient,
|
||||||
NSTrackingRectTag, NSView,
|
NSTrackingRectTag, NSView, NSWindow,
|
||||||
};
|
};
|
||||||
|
use objc2_core_foundation::CGRect;
|
||||||
use objc2_foundation::{
|
use objc2_foundation::{
|
||||||
MainThreadMarker, NSArray, NSAttributedString, NSAttributedStringKey, NSCopying,
|
NSArray, NSAttributedString, NSAttributedStringKey, NSCopying, NSMutableAttributedString,
|
||||||
NSMutableAttributedString, NSNotFound, NSObject, NSObjectProtocol, NSPoint, NSRange, NSRect,
|
NSNotFound, NSObject, NSPoint, NSRange, NSRect, NSSize, NSString, NSUInteger,
|
||||||
NSSize, NSString, NSUInteger,
|
|
||||||
};
|
};
|
||||||
|
use winit_core::event::{
|
||||||
|
DeviceEvent, ElementState, Ime, KeyEvent, Modifiers, MouseButton, MouseScrollDelta,
|
||||||
|
PointerKind, PointerSource, TouchPhase, WindowEvent,
|
||||||
|
};
|
||||||
|
use winit_core::keyboard::{Key, KeyCode, KeyLocation, ModifiersState, NamedKey};
|
||||||
|
use winit_core::window::ImeCapabilities;
|
||||||
|
|
||||||
use super::app_state::AppState;
|
use super::app_state::AppState;
|
||||||
use super::cursor::{default_cursor, invisible_cursor};
|
use super::cursor::{default_cursor, invisible_cursor};
|
||||||
use super::event::{
|
use super::event::{
|
||||||
code_to_key, code_to_location, create_key_event, event_mods, lalt_pressed, ralt_pressed,
|
code_to_key, code_to_location, create_key_event, event_mods, lalt_pressed, ralt_pressed,
|
||||||
scancode_to_physicalkey, KeyEventExtra,
|
scancode_to_physicalkey,
|
||||||
};
|
};
|
||||||
use super::window::WinitWindow;
|
use super::window::window_id;
|
||||||
use crate::dpi::{LogicalPosition, LogicalSize};
|
use crate::OptionAsAlt;
|
||||||
use crate::event::{
|
|
||||||
DeviceEvent, ElementState, Ime, KeyEvent, Modifiers, MouseButton, MouseScrollDelta,
|
|
||||||
PointerKind, PointerSource, TouchPhase, WindowEvent,
|
|
||||||
};
|
|
||||||
use crate::keyboard::{Key, KeyCode, KeyLocation, ModifiersState, NamedKey};
|
|
||||||
use crate::platform::macos::OptionAsAlt;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct CursorState {
|
struct CursorState {
|
||||||
@@ -82,7 +83,7 @@ fn key_to_modifier(key: &Key) -> Option<ModifiersState> {
|
|||||||
match key {
|
match key {
|
||||||
Key::Named(NamedKey::Alt) => Some(ModifiersState::ALT),
|
Key::Named(NamedKey::Alt) => Some(ModifiersState::ALT),
|
||||||
Key::Named(NamedKey::Control) => Some(ModifiersState::CONTROL),
|
Key::Named(NamedKey::Control) => Some(ModifiersState::CONTROL),
|
||||||
Key::Named(NamedKey::Super) => Some(ModifiersState::SUPER),
|
Key::Named(NamedKey::Meta) => Some(ModifiersState::META),
|
||||||
Key::Named(NamedKey::Shift) => Some(ModifiersState::SHIFT),
|
Key::Named(NamedKey::Shift) => Some(ModifiersState::SHIFT),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
@@ -93,7 +94,7 @@ fn get_right_modifier_code(key: &Key) -> KeyCode {
|
|||||||
Key::Named(NamedKey::Alt) => KeyCode::AltRight,
|
Key::Named(NamedKey::Alt) => KeyCode::AltRight,
|
||||||
Key::Named(NamedKey::Control) => KeyCode::ControlRight,
|
Key::Named(NamedKey::Control) => KeyCode::ControlRight,
|
||||||
Key::Named(NamedKey::Shift) => KeyCode::ShiftRight,
|
Key::Named(NamedKey::Shift) => KeyCode::ShiftRight,
|
||||||
Key::Named(NamedKey::Super) => KeyCode::SuperRight,
|
Key::Named(NamedKey::Meta) => KeyCode::MetaRight,
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -103,7 +104,7 @@ fn get_left_modifier_code(key: &Key) -> KeyCode {
|
|||||||
Key::Named(NamedKey::Alt) => KeyCode::AltLeft,
|
Key::Named(NamedKey::Alt) => KeyCode::AltLeft,
|
||||||
Key::Named(NamedKey::Control) => KeyCode::ControlLeft,
|
Key::Named(NamedKey::Control) => KeyCode::ControlLeft,
|
||||||
Key::Named(NamedKey::Shift) => KeyCode::ShiftLeft,
|
Key::Named(NamedKey::Shift) => KeyCode::ShiftLeft,
|
||||||
Key::Named(NamedKey::Super) => KeyCode::SuperLeft,
|
Key::Named(NamedKey::Meta) => KeyCode::MetaLeft,
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -125,7 +126,7 @@ pub struct ViewState {
|
|||||||
/// True iff the application wants IME events.
|
/// True iff the application wants IME events.
|
||||||
///
|
///
|
||||||
/// Can be set using `set_ime_allowed`
|
/// Can be set using `set_ime_allowed`
|
||||||
ime_allowed: Cell<bool>,
|
ime_capabilities: Cell<Option<ImeCapabilities>>,
|
||||||
|
|
||||||
/// True if the current key event should be forwarded
|
/// True if the current key event should be forwarded
|
||||||
/// to the application, even during IME
|
/// to the application, even during IME
|
||||||
@@ -138,28 +139,21 @@ pub struct ViewState {
|
|||||||
option_as_alt: Cell<OptionAsAlt>,
|
option_as_alt: Cell<OptionAsAlt>,
|
||||||
}
|
}
|
||||||
|
|
||||||
declare_class!(
|
define_class!(
|
||||||
|
#[unsafe(super(NSView, NSResponder, NSObject))]
|
||||||
|
#[ivars = ViewState]
|
||||||
|
#[name = "WinitView"]
|
||||||
pub(super) struct WinitView;
|
pub(super) struct WinitView;
|
||||||
|
|
||||||
unsafe impl ClassType for WinitView {
|
/// This documentation attribute makes rustfmt work for some reason?
|
||||||
#[inherits(NSResponder, NSObject)]
|
impl WinitView {
|
||||||
type Super = NSView;
|
#[unsafe(method(isFlipped))]
|
||||||
type Mutability = mutability::MainThreadOnly;
|
|
||||||
const NAME: &'static str = "WinitView";
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DeclaredClass for WinitView {
|
|
||||||
type Ivars = ViewState;
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe impl WinitView {
|
|
||||||
#[method(isFlipped)]
|
|
||||||
fn is_flipped(&self) -> bool {
|
fn is_flipped(&self) -> bool {
|
||||||
// `winit` uses the upper-left corner as the origin.
|
// `winit` uses the upper-left corner as the origin.
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(viewDidMoveToWindow)]
|
#[unsafe(method(viewDidMoveToWindow))]
|
||||||
fn view_did_move_to_window(&self) {
|
fn view_did_move_to_window(&self) {
|
||||||
trace_scope!("viewDidMoveToWindow");
|
trace_scope!("viewDidMoveToWindow");
|
||||||
if let Some(tracking_rect) = self.ivars().tracking_rect.take() {
|
if let Some(tracking_rect) = self.ivars().tracking_rect.take() {
|
||||||
@@ -175,7 +169,7 @@ declare_class!(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Not a normal method on `NSView`, it's triggered by `NSViewFrameDidChangeNotification`.
|
// Not a normal method on `NSView`, it's triggered by `NSViewFrameDidChangeNotification`.
|
||||||
#[method(viewFrameDidChangeNotification:)]
|
#[unsafe(method(viewFrameDidChangeNotification:))]
|
||||||
fn frame_did_change(&self, _notification: Option<&AnyObject>) {
|
fn frame_did_change(&self, _notification: Option<&AnyObject>) {
|
||||||
trace_scope!("NSViewFrameDidChangeNotification");
|
trace_scope!("NSViewFrameDidChangeNotification");
|
||||||
if let Some(tracking_rect) = self.ivars().tracking_rect.take() {
|
if let Some(tracking_rect) = self.ivars().tracking_rect.take() {
|
||||||
@@ -190,38 +184,45 @@ declare_class!(
|
|||||||
self.ivars().tracking_rect.set(Some(tracking_rect));
|
self.ivars().tracking_rect.set(Some(tracking_rect));
|
||||||
|
|
||||||
// Emit resize event here rather than from windowDidResize because:
|
// 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.
|
// 1. When a new window is created as a tab, the frame size may change without a window
|
||||||
// 2. Even when a window resize does occur on a new tabbed window, it contains the wrong size (includes tab height).
|
// resize occurring.
|
||||||
|
// 2. Even when a window resize does occur on a new tabbed window, it contains the wrong
|
||||||
|
// size (includes tab height).
|
||||||
let logical_size = LogicalSize::new(rect.size.width as f64, rect.size.height as f64);
|
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());
|
let size = logical_size.to_physical::<u32>(self.scale_factor());
|
||||||
self.queue_event(WindowEvent::SurfaceResized(size));
|
self.queue_event(WindowEvent::SurfaceResized(size));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(drawRect:)]
|
#[unsafe(method(drawRect:))]
|
||||||
fn draw_rect(&self, _rect: NSRect) {
|
fn draw_rect(&self, _rect: NSRect) {
|
||||||
trace_scope!("drawRect:");
|
trace_scope!("drawRect:");
|
||||||
|
|
||||||
self.ivars().app_state.handle_redraw(self.window().id());
|
self.ivars().app_state.handle_redraw(window_id(&self.window()));
|
||||||
|
|
||||||
// This is a direct subclass of NSView, no need to call superclass' drawRect:
|
// This is a direct subclass of NSView, no need to call superclass' drawRect:
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(acceptsFirstResponder)]
|
#[unsafe(method(acceptsFirstResponder))]
|
||||||
fn accepts_first_responder(&self) -> bool {
|
fn accepts_first_responder(&self) -> bool {
|
||||||
trace_scope!("acceptsFirstResponder");
|
trace_scope!("acceptsFirstResponder");
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
// This is necessary to prevent a beefy terminal error on MacBook Pros:
|
// This is necessary to prevent a beefy terminal error on MacBook Pros:
|
||||||
// IMKInputSession [0x7fc573576ff0 presentFunctionRowItemTextInputViewWithEndpoint:completionHandler:] : [self textInputContext]=0x7fc573558e10 *NO* NSRemoteViewController to client, NSError=Error Domain=NSCocoaErrorDomain Code=4099 "The connection from pid 0 was invalidated from this process." UserInfo={NSDebugDescription=The connection from pid 0 was invalidated from this process.}, com.apple.inputmethod.EmojiFunctionRowItem
|
// IMKInputSession [0x7fc573576ff0
|
||||||
// TODO: Add an API extension for using `NSTouchBar`
|
// presentFunctionRowItemTextInputViewWithEndpoint:completionHandler:] : [self
|
||||||
#[method_id(touchBar)]
|
// textInputContext]=0x7fc573558e10 *NO* NSRemoteViewController to client, NSError=Error
|
||||||
|
// Domain=NSCocoaErrorDomain Code=4099 "The connection from pid 0 was invalidated from this
|
||||||
|
// process." UserInfo={NSDebugDescription=The connection from pid 0 was invalidated from
|
||||||
|
// this process.}, com.apple.inputmethod.EmojiFunctionRowItem TODO: Add an API
|
||||||
|
// extension for using `NSTouchBar`
|
||||||
|
#[unsafe(method_id(touchBar))]
|
||||||
fn touch_bar(&self) -> Option<Retained<NSObject>> {
|
fn touch_bar(&self) -> Option<Retained<NSObject>> {
|
||||||
trace_scope!("touchBar");
|
trace_scope!("touchBar");
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(resetCursorRects)]
|
#[unsafe(method(resetCursorRects))]
|
||||||
fn reset_cursor_rects(&self) {
|
fn reset_cursor_rects(&self) {
|
||||||
trace_scope!("resetCursorRects");
|
trace_scope!("resetCursorRects");
|
||||||
let bounds = self.bounds();
|
let bounds = self.bounds();
|
||||||
@@ -236,13 +237,13 @@ declare_class!(
|
|||||||
}
|
}
|
||||||
|
|
||||||
unsafe impl NSTextInputClient for WinitView {
|
unsafe impl NSTextInputClient for WinitView {
|
||||||
#[method(hasMarkedText)]
|
#[unsafe(method(hasMarkedText))]
|
||||||
fn has_marked_text(&self) -> bool {
|
fn has_marked_text(&self) -> bool {
|
||||||
trace_scope!("hasMarkedText");
|
trace_scope!("hasMarkedText");
|
||||||
self.ivars().marked_text.borrow().length() > 0
|
self.ivars().marked_text.borrow().length() > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(markedRange)]
|
#[unsafe(method(markedRange))]
|
||||||
fn marked_range(&self) -> NSRange {
|
fn marked_range(&self) -> NSRange {
|
||||||
trace_scope!("markedRange");
|
trace_scope!("markedRange");
|
||||||
let length = self.ivars().marked_text.borrow().length();
|
let length = self.ivars().marked_text.borrow().length();
|
||||||
@@ -254,14 +255,14 @@ declare_class!(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(selectedRange)]
|
#[unsafe(method(selectedRange))]
|
||||||
fn selected_range(&self) -> NSRange {
|
fn selected_range(&self) -> NSRange {
|
||||||
trace_scope!("selectedRange");
|
trace_scope!("selectedRange");
|
||||||
// Documented to return `{NSNotFound, 0}` if there is no selection.
|
// Documented to return `{NSNotFound, 0}` if there is no selection.
|
||||||
NSRange::new(NSNotFound as NSUInteger, 0)
|
NSRange::new(NSNotFound as NSUInteger, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(setMarkedText:selectedRange:replacementRange:)]
|
#[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
|
||||||
fn set_marked_text(
|
fn set_marked_text(
|
||||||
&self,
|
&self,
|
||||||
string: &NSObject,
|
string: &NSObject,
|
||||||
@@ -271,23 +272,15 @@ declare_class!(
|
|||||||
// TODO: Use _replacement_range, requires changing the event to report surrounding text.
|
// TODO: Use _replacement_range, requires changing the event to report surrounding text.
|
||||||
trace_scope!("setMarkedText:selectedRange:replacementRange:");
|
trace_scope!("setMarkedText:selectedRange:replacementRange:");
|
||||||
|
|
||||||
// SAFETY: This method is guaranteed to get either a `NSString` or a `NSAttributedString`.
|
let (marked_text, string) = if let Some(string) =
|
||||||
let (marked_text, string) = if string.is_kind_of::<NSAttributedString>() {
|
string.downcast_ref::<NSAttributedString>()
|
||||||
let string: *const NSObject = string;
|
{
|
||||||
let string: *const NSAttributedString = string.cast();
|
(NSMutableAttributedString::from_attributed_nsstring(string), string.string())
|
||||||
let string = unsafe { &*string };
|
} else if let Some(string) = string.downcast_ref::<NSString>() {
|
||||||
(
|
(NSMutableAttributedString::from_nsstring(string), string.copy())
|
||||||
NSMutableAttributedString::from_attributed_nsstring(string),
|
|
||||||
string.string(),
|
|
||||||
)
|
|
||||||
} else {
|
} else {
|
||||||
let string: *const NSObject = string;
|
// This method is guaranteed to get either a `NSString` or a `NSAttributedString`.
|
||||||
let string: *const NSString = string.cast();
|
panic!("unexpected text {string:?}")
|
||||||
let string = unsafe { &*string };
|
|
||||||
(
|
|
||||||
NSMutableAttributedString::from_nsstring(string),
|
|
||||||
string.copy(),
|
|
||||||
)
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Update marked text.
|
// Update marked text.
|
||||||
@@ -323,7 +316,7 @@ declare_class!(
|
|||||||
self.queue_event(WindowEvent::Ime(Ime::Preedit(string.to_string(), cursor_range)));
|
self.queue_event(WindowEvent::Ime(Ime::Preedit(string.to_string(), cursor_range)));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(unmarkText)]
|
#[unsafe(method(unmarkText))]
|
||||||
fn unmark_text(&self) {
|
fn unmark_text(&self) {
|
||||||
trace_scope!("unmarkText");
|
trace_scope!("unmarkText");
|
||||||
*self.ivars().marked_text.borrow_mut() = NSMutableAttributedString::new();
|
*self.ivars().marked_text.borrow_mut() = NSMutableAttributedString::new();
|
||||||
@@ -340,13 +333,13 @@ declare_class!(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method_id(validAttributesForMarkedText)]
|
#[unsafe(method_id(validAttributesForMarkedText))]
|
||||||
fn valid_attributes_for_marked_text(&self) -> Retained<NSArray<NSAttributedStringKey>> {
|
fn valid_attributes_for_marked_text(&self) -> Retained<NSArray<NSAttributedStringKey>> {
|
||||||
trace_scope!("validAttributesForMarkedText");
|
trace_scope!("validAttributesForMarkedText");
|
||||||
NSArray::new()
|
NSArray::new()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method_id(attributedSubstringForProposedRange:actualRange:)]
|
#[unsafe(method_id(attributedSubstringForProposedRange:actualRange:))]
|
||||||
fn attributed_substring_for_proposed_range(
|
fn attributed_substring_for_proposed_range(
|
||||||
&self,
|
&self,
|
||||||
_range: NSRange,
|
_range: NSRange,
|
||||||
@@ -356,42 +349,43 @@ declare_class!(
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(characterIndexForPoint:)]
|
#[unsafe(method(characterIndexForPoint:))]
|
||||||
fn character_index_for_point(&self, _point: NSPoint) -> NSUInteger {
|
fn character_index_for_point(&self, _point: NSPoint) -> NSUInteger {
|
||||||
trace_scope!("characterIndexForPoint:");
|
trace_scope!("characterIndexForPoint:");
|
||||||
0
|
0
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(firstRectForCharacterRange:actualRange:)]
|
#[unsafe(method(firstRectForCharacterRange:actualRange:))]
|
||||||
fn first_rect_for_character_range(
|
fn first_rect_for_character_range(
|
||||||
&self,
|
&self,
|
||||||
_range: NSRange,
|
_range: NSRange,
|
||||||
_actual_range: *mut NSRange,
|
_actual_range: *mut NSRange,
|
||||||
) -> NSRect {
|
) -> NSRect {
|
||||||
trace_scope!("firstRectForCharacterRange:actualRange:");
|
trace_scope!("firstRectForCharacterRange:actualRange:");
|
||||||
let rect = NSRect::new(
|
|
||||||
self.ivars().ime_position.get(),
|
// Guard when the view is no longer in a window during teardown.
|
||||||
self.ivars().ime_size.get()
|
let Some(window) = (**self).window() else {
|
||||||
);
|
return CGRect::ZERO;
|
||||||
// Return value is expected to be in screen coordinates, so we need a conversion here
|
};
|
||||||
self.window()
|
|
||||||
.convertRectToScreen(self.convertRect_toView(rect, None))
|
// Return value is expected to be in screen coordinates, so we need a conversion
|
||||||
|
let rect = NSRect::new(self.ivars().ime_position.get(), self.ivars().ime_size.get());
|
||||||
|
let view_rect = self.convertRect_toView(rect, None);
|
||||||
|
window.convertRectToScreen(view_rect)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(insertText:replacementRange:)]
|
#[unsafe(method(insertText:replacementRange:))]
|
||||||
fn insert_text(&self, string: &NSObject, _replacement_range: NSRange) {
|
fn insert_text(&self, string: &NSObject, _replacement_range: NSRange) {
|
||||||
// TODO: Use _replacement_range, requires changing the event to report surrounding text.
|
// TODO: Use _replacement_range, requires changing the event to report surrounding text.
|
||||||
trace_scope!("insertText:replacementRange:");
|
trace_scope!("insertText:replacementRange:");
|
||||||
|
|
||||||
// SAFETY: This method is guaranteed to get either a `NSString` or a `NSAttributedString`.
|
let string = if let Some(string) = string.downcast_ref::<NSAttributedString>() {
|
||||||
let string = if string.is_kind_of::<NSAttributedString>() {
|
string.string().to_string()
|
||||||
let string: *const NSObject = string;
|
} else if let Some(string) = string.downcast_ref::<NSString>() {
|
||||||
let string: *const NSAttributedString = string.cast();
|
string.to_string()
|
||||||
unsafe { &*string }.string().to_string()
|
|
||||||
} else {
|
} else {
|
||||||
let string: *const NSObject = string;
|
// This method is guaranteed to get either a `NSString` or a `NSAttributedString`.
|
||||||
let string: *const NSString = string.cast();
|
panic!("unexpected text {string:?}")
|
||||||
unsafe { &*string }.to_string()
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let is_control = string.chars().next().is_some_and(|c| c.is_control());
|
let is_control = string.chars().next().is_some_and(|c| c.is_control());
|
||||||
@@ -404,15 +398,16 @@ declare_class!(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Basically, we're sent this message whenever a keyboard event that doesn't generate a "human
|
// Basically, we're sent this message whenever a keyboard event that doesn't generate a
|
||||||
// readable" character happens, i.e. newlines, tabs, and Ctrl+C.
|
// "human readable" character happens, i.e. newlines, tabs, and Ctrl+C.
|
||||||
#[method(doCommandBySelector:)]
|
#[unsafe(method(doCommandBySelector:))]
|
||||||
fn do_command_by_selector(&self, command: Sel) {
|
fn do_command_by_selector(&self, command: Sel) {
|
||||||
trace_scope!("doCommandBySelector:");
|
trace_scope!("doCommandBySelector:");
|
||||||
|
|
||||||
// We shouldn't forward any character from just committed text, since we'll end up sending
|
// We shouldn't forward any character from just committed text, since we'll end up
|
||||||
// it twice with some IMEs like Korean one. We'll also always send `Enter` in that case,
|
// sending it twice with some IMEs like Korean one. We'll also always send
|
||||||
// which is not desired given it was used to confirm IME input.
|
// `Enter` in that case, which is not desired given it was used to confirm
|
||||||
|
// IME input.
|
||||||
if self.ivars().ime_state.get() == ImeState::Committed {
|
if self.ivars().ime_state.get() == ImeState::Committed {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -426,10 +421,14 @@ declare_class!(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Send command action to user if they requested it.
|
// Send command action to user if they requested it.
|
||||||
let window_id = self.window().id();
|
let window_id = window_id(&self.window());
|
||||||
self.ivars().app_state.maybe_queue_with_handler(move |app, event_loop| {
|
self.ivars().app_state.maybe_queue_with_handler(move |app, event_loop| {
|
||||||
if let Some(handler) = app.macos_handler() {
|
if let Some(handler) = app.macos_handler() {
|
||||||
handler.standard_key_binding(event_loop, window_id, command.name());
|
handler.standard_key_binding(
|
||||||
|
event_loop,
|
||||||
|
window_id,
|
||||||
|
command.name().to_str().unwrap(),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -439,8 +438,9 @@ declare_class!(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe impl WinitView {
|
/// This documentation attribute makes rustfmt work for some reason?
|
||||||
#[method(keyDown:)]
|
impl WinitView {
|
||||||
|
#[unsafe(method(keyDown:))]
|
||||||
fn key_down(&self, event: &NSEvent) {
|
fn key_down(&self, event: &NSEvent) {
|
||||||
trace_scope!("keyDown:");
|
trace_scope!("keyDown:");
|
||||||
{
|
{
|
||||||
@@ -465,7 +465,7 @@ declare_class!(
|
|||||||
// we must send the `KeyboardInput` event during IME if it triggered
|
// we must send the `KeyboardInput` event during IME if it triggered
|
||||||
// `doCommandBySelector`. (doCommandBySelector means that the keyboard input
|
// `doCommandBySelector`. (doCommandBySelector means that the keyboard input
|
||||||
// is not handled by IME and should be handled by the application)
|
// is not handled by IME and should be handled by the application)
|
||||||
if self.ivars().ime_allowed.get() {
|
if self.ivars().ime_capabilities.get().is_some() {
|
||||||
let events_for_nsview = NSArray::from_slice(&[&*event]);
|
let events_for_nsview = NSArray::from_slice(&[&*event]);
|
||||||
unsafe { self.interpretKeyEvents(&events_for_nsview) };
|
unsafe { self.interpretKeyEvents(&events_for_nsview) };
|
||||||
|
|
||||||
@@ -483,7 +483,7 @@ declare_class!(
|
|||||||
// Allow normal input after the commit.
|
// Allow normal input after the commit.
|
||||||
self.ivars().ime_state.set(ImeState::Ground);
|
self.ivars().ime_state.set(ImeState::Ground);
|
||||||
true
|
true
|
||||||
}
|
},
|
||||||
ImeState::Preedit => true,
|
ImeState::Preedit => true,
|
||||||
// `key_down` could result in preedit clear, so compare old and current state.
|
// `key_down` could result in preedit clear, so compare old and current state.
|
||||||
_ => old_ime_state != self.ivars().ime_state.get(),
|
_ => old_ime_state != self.ivars().ime_state.get(),
|
||||||
@@ -499,7 +499,7 @@ declare_class!(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(keyUp:)]
|
#[unsafe(method(keyUp:))]
|
||||||
fn key_up(&self, event: &NSEvent) {
|
fn key_up(&self, event: &NSEvent) {
|
||||||
trace_scope!("keyUp:");
|
trace_scope!("keyUp:");
|
||||||
|
|
||||||
@@ -507,10 +507,7 @@ declare_class!(
|
|||||||
self.update_modifiers(&event, false);
|
self.update_modifiers(&event, false);
|
||||||
|
|
||||||
// We want to send keyboard input when we are currently in the ground state.
|
// We want to send keyboard input when we are currently in the ground state.
|
||||||
if matches!(
|
if matches!(self.ivars().ime_state.get(), ImeState::Ground | ImeState::Disabled) {
|
||||||
self.ivars().ime_state.get(),
|
|
||||||
ImeState::Ground | ImeState::Disabled
|
|
||||||
) {
|
|
||||||
self.queue_event(WindowEvent::KeyboardInput {
|
self.queue_event(WindowEvent::KeyboardInput {
|
||||||
device_id: None,
|
device_id: None,
|
||||||
event: create_key_event(&event, false, false),
|
event: create_key_event(&event, false, false),
|
||||||
@@ -519,14 +516,14 @@ declare_class!(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(flagsChanged:)]
|
#[unsafe(method(flagsChanged:))]
|
||||||
fn flags_changed(&self, event: &NSEvent) {
|
fn flags_changed(&self, event: &NSEvent) {
|
||||||
trace_scope!("flagsChanged:");
|
trace_scope!("flagsChanged:");
|
||||||
|
|
||||||
self.update_modifiers(event, true);
|
self.update_modifiers(event, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(insertTab:)]
|
#[unsafe(method(insertTab:))]
|
||||||
fn insert_tab(&self, _sender: Option<&AnyObject>) {
|
fn insert_tab(&self, _sender: Option<&AnyObject>) {
|
||||||
trace_scope!("insertTab:");
|
trace_scope!("insertTab:");
|
||||||
let window = self.window();
|
let window = self.window();
|
||||||
@@ -537,7 +534,7 @@ declare_class!(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(insertBackTab:)]
|
#[unsafe(method(insertBackTab:))]
|
||||||
fn insert_back_tab(&self, _sender: Option<&AnyObject>) {
|
fn insert_back_tab(&self, _sender: Option<&AnyObject>) {
|
||||||
trace_scope!("insertBackTab:");
|
trace_scope!("insertBackTab:");
|
||||||
let window = self.window();
|
let window = self.window();
|
||||||
@@ -550,7 +547,7 @@ declare_class!(
|
|||||||
|
|
||||||
// Allows us to receive Cmd-. (the shortcut for closing a dialog)
|
// Allows us to receive Cmd-. (the shortcut for closing a dialog)
|
||||||
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
|
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
|
||||||
#[method(cancelOperation:)]
|
#[unsafe(method(cancelOperation:))]
|
||||||
fn cancel_operation(&self, _sender: Option<&AnyObject>) {
|
fn cancel_operation(&self, _sender: Option<&AnyObject>) {
|
||||||
let mtm = MainThreadMarker::from(self);
|
let mtm = MainThreadMarker::from(self);
|
||||||
trace_scope!("cancelOperation:");
|
trace_scope!("cancelOperation:");
|
||||||
@@ -580,42 +577,42 @@ declare_class!(
|
|||||||
//
|
//
|
||||||
// See https://github.com/rust-windowing/winit/pull/1490 for history.
|
// See https://github.com/rust-windowing/winit/pull/1490 for history.
|
||||||
|
|
||||||
#[method(mouseDown:)]
|
#[unsafe(method(mouseDown:))]
|
||||||
fn mouse_down(&self, event: &NSEvent) {
|
fn mouse_down(&self, event: &NSEvent) {
|
||||||
trace_scope!("mouseDown:");
|
trace_scope!("mouseDown:");
|
||||||
self.mouse_motion(event);
|
self.mouse_motion(event);
|
||||||
self.mouse_click(event, ElementState::Pressed);
|
self.mouse_click(event, ElementState::Pressed);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(mouseUp:)]
|
#[unsafe(method(mouseUp:))]
|
||||||
fn mouse_up(&self, event: &NSEvent) {
|
fn mouse_up(&self, event: &NSEvent) {
|
||||||
trace_scope!("mouseUp:");
|
trace_scope!("mouseUp:");
|
||||||
self.mouse_motion(event);
|
self.mouse_motion(event);
|
||||||
self.mouse_click(event, ElementState::Released);
|
self.mouse_click(event, ElementState::Released);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(rightMouseDown:)]
|
#[unsafe(method(rightMouseDown:))]
|
||||||
fn right_mouse_down(&self, event: &NSEvent) {
|
fn right_mouse_down(&self, event: &NSEvent) {
|
||||||
trace_scope!("rightMouseDown:");
|
trace_scope!("rightMouseDown:");
|
||||||
self.mouse_motion(event);
|
self.mouse_motion(event);
|
||||||
self.mouse_click(event, ElementState::Pressed);
|
self.mouse_click(event, ElementState::Pressed);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(rightMouseUp:)]
|
#[unsafe(method(rightMouseUp:))]
|
||||||
fn right_mouse_up(&self, event: &NSEvent) {
|
fn right_mouse_up(&self, event: &NSEvent) {
|
||||||
trace_scope!("rightMouseUp:");
|
trace_scope!("rightMouseUp:");
|
||||||
self.mouse_motion(event);
|
self.mouse_motion(event);
|
||||||
self.mouse_click(event, ElementState::Released);
|
self.mouse_click(event, ElementState::Released);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(otherMouseDown:)]
|
#[unsafe(method(otherMouseDown:))]
|
||||||
fn other_mouse_down(&self, event: &NSEvent) {
|
fn other_mouse_down(&self, event: &NSEvent) {
|
||||||
trace_scope!("otherMouseDown:");
|
trace_scope!("otherMouseDown:");
|
||||||
self.mouse_motion(event);
|
self.mouse_motion(event);
|
||||||
self.mouse_click(event, ElementState::Pressed);
|
self.mouse_click(event, ElementState::Pressed);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(otherMouseUp:)]
|
#[unsafe(method(otherMouseUp:))]
|
||||||
fn other_mouse_up(&self, event: &NSEvent) {
|
fn other_mouse_up(&self, event: &NSEvent) {
|
||||||
trace_scope!("otherMouseUp:");
|
trace_scope!("otherMouseUp:");
|
||||||
self.mouse_motion(event);
|
self.mouse_motion(event);
|
||||||
@@ -624,27 +621,27 @@ declare_class!(
|
|||||||
|
|
||||||
// No tracing on these because that would be overly verbose
|
// No tracing on these because that would be overly verbose
|
||||||
|
|
||||||
#[method(mouseMoved:)]
|
#[unsafe(method(mouseMoved:))]
|
||||||
fn mouse_moved(&self, event: &NSEvent) {
|
fn mouse_moved(&self, event: &NSEvent) {
|
||||||
self.mouse_motion(event);
|
self.mouse_motion(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(mouseDragged:)]
|
#[unsafe(method(mouseDragged:))]
|
||||||
fn mouse_dragged(&self, event: &NSEvent) {
|
fn mouse_dragged(&self, event: &NSEvent) {
|
||||||
self.mouse_motion(event);
|
self.mouse_motion(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(rightMouseDragged:)]
|
#[unsafe(method(rightMouseDragged:))]
|
||||||
fn right_mouse_dragged(&self, event: &NSEvent) {
|
fn right_mouse_dragged(&self, event: &NSEvent) {
|
||||||
self.mouse_motion(event);
|
self.mouse_motion(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(otherMouseDragged:)]
|
#[unsafe(method(otherMouseDragged:))]
|
||||||
fn other_mouse_dragged(&self, event: &NSEvent) {
|
fn other_mouse_dragged(&self, event: &NSEvent) {
|
||||||
self.mouse_motion(event);
|
self.mouse_motion(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(mouseEntered:)]
|
#[unsafe(method(mouseEntered:))]
|
||||||
fn mouse_entered(&self, event: &NSEvent) {
|
fn mouse_entered(&self, event: &NSEvent) {
|
||||||
trace_scope!("mouseEntered:");
|
trace_scope!("mouseEntered:");
|
||||||
|
|
||||||
@@ -658,7 +655,7 @@ declare_class!(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(mouseExited:)]
|
#[unsafe(method(mouseExited:))]
|
||||||
fn mouse_exited(&self, event: &NSEvent) {
|
fn mouse_exited(&self, event: &NSEvent) {
|
||||||
trace_scope!("mouseExited:");
|
trace_scope!("mouseExited:");
|
||||||
|
|
||||||
@@ -672,7 +669,7 @@ declare_class!(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(scrollWheel:)]
|
#[unsafe(method(scrollWheel:))]
|
||||||
fn scroll_wheel(&self, event: &NSEvent) {
|
fn scroll_wheel(&self, event: &NSEvent) {
|
||||||
trace_scope!("scrollWheel:");
|
trace_scope!("scrollWheel:");
|
||||||
|
|
||||||
@@ -689,9 +686,9 @@ declare_class!(
|
|||||||
};
|
};
|
||||||
|
|
||||||
// The "momentum phase," if any, has higher priority than touch phase (the two should
|
// The "momentum phase," if any, has higher priority than touch phase (the two should
|
||||||
// be mutually exclusive anyhow, which is why the API is rather incoherent). If no momentum
|
// be mutually exclusive anyhow, which is why the API is rather incoherent). If no
|
||||||
// phase is recorded (or rather, the started/ended cases of the momentum phase) then we
|
// momentum phase is recorded (or rather, the started/ended cases of the
|
||||||
// report the touch phase.
|
// momentum phase) then we report the touch phase.
|
||||||
#[allow(non_upper_case_globals)]
|
#[allow(non_upper_case_globals)]
|
||||||
let phase = match unsafe { event.momentumPhase() } {
|
let phase = match unsafe { event.momentumPhase() } {
|
||||||
NSEventPhase::MayBegin | NSEventPhase::Began => TouchPhase::Started,
|
NSEventPhase::MayBegin | NSEventPhase::Began => TouchPhase::Started,
|
||||||
@@ -705,17 +702,13 @@ declare_class!(
|
|||||||
|
|
||||||
self.update_modifiers(event, false);
|
self.update_modifiers(event, false);
|
||||||
|
|
||||||
self.ivars().app_state.maybe_queue_with_handler(move |app, event_loop|
|
self.ivars().app_state.maybe_queue_with_handler(move |app, event_loop| {
|
||||||
app.device_event(event_loop, None, DeviceEvent::MouseWheel { delta })
|
app.device_event(event_loop, None, DeviceEvent::MouseWheel { delta })
|
||||||
);
|
|
||||||
self.queue_event(WindowEvent::MouseWheel {
|
|
||||||
device_id: None,
|
|
||||||
delta,
|
|
||||||
phase,
|
|
||||||
});
|
});
|
||||||
|
self.queue_event(WindowEvent::MouseWheel { device_id: None, delta, phase });
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(magnifyWithEvent:)]
|
#[unsafe(method(magnifyWithEvent:))]
|
||||||
fn magnify_with_event(&self, event: &NSEvent) {
|
fn magnify_with_event(&self, event: &NSEvent) {
|
||||||
trace_scope!("magnifyWithEvent:");
|
trace_scope!("magnifyWithEvent:");
|
||||||
|
|
||||||
@@ -737,18 +730,16 @@ declare_class!(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(smartMagnifyWithEvent:)]
|
#[unsafe(method(smartMagnifyWithEvent:))]
|
||||||
fn smart_magnify_with_event(&self, event: &NSEvent) {
|
fn smart_magnify_with_event(&self, event: &NSEvent) {
|
||||||
trace_scope!("smartMagnifyWithEvent:");
|
trace_scope!("smartMagnifyWithEvent:");
|
||||||
|
|
||||||
self.mouse_motion(event);
|
self.mouse_motion(event);
|
||||||
|
|
||||||
self.queue_event(WindowEvent::DoubleTapGesture {
|
self.queue_event(WindowEvent::DoubleTapGesture { device_id: None });
|
||||||
device_id: None,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(rotateWithEvent:)]
|
#[unsafe(method(rotateWithEvent:))]
|
||||||
fn rotate_with_event(&self, event: &NSEvent) {
|
fn rotate_with_event(&self, event: &NSEvent) {
|
||||||
trace_scope!("rotateWithEvent:");
|
trace_scope!("rotateWithEvent:");
|
||||||
|
|
||||||
@@ -770,7 +761,7 @@ declare_class!(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(pressureChangeWithEvent:)]
|
#[unsafe(method(pressureChangeWithEvent:))]
|
||||||
fn pressure_change_with_event(&self, event: &NSEvent) {
|
fn pressure_change_with_event(&self, event: &NSEvent) {
|
||||||
trace_scope!("pressureChangeWithEvent:");
|
trace_scope!("pressureChangeWithEvent:");
|
||||||
|
|
||||||
@@ -784,13 +775,13 @@ declare_class!(
|
|||||||
// Allows us to receive Ctrl-Tab and Ctrl-Esc.
|
// Allows us to receive Ctrl-Tab and Ctrl-Esc.
|
||||||
// Note that this *doesn't* help with any missing Cmd inputs.
|
// Note that this *doesn't* help with any missing Cmd inputs.
|
||||||
// https://github.com/chromium/chromium/blob/a86a8a6bcfa438fa3ac2eba6f02b3ad1f8e0756f/ui/views/cocoa/bridged_content_view.mm#L816
|
// https://github.com/chromium/chromium/blob/a86a8a6bcfa438fa3ac2eba6f02b3ad1f8e0756f/ui/views/cocoa/bridged_content_view.mm#L816
|
||||||
#[method(_wantsKeyDownForEvent:)]
|
#[unsafe(method(_wantsKeyDownForEvent:))]
|
||||||
fn wants_key_down_for_event(&self, _event: &NSEvent) -> bool {
|
fn wants_key_down_for_event(&self, _event: &NSEvent) -> bool {
|
||||||
trace_scope!("_wantsKeyDownForEvent:");
|
trace_scope!("_wantsKeyDownForEvent:");
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(acceptsFirstMouse:)]
|
#[unsafe(method(acceptsFirstMouse:))]
|
||||||
fn accepts_first_mouse(&self, _event: &NSEvent) -> bool {
|
fn accepts_first_mouse(&self, _event: &NSEvent) -> bool {
|
||||||
trace_scope!("acceptsFirstMouse:");
|
trace_scope!("acceptsFirstMouse:");
|
||||||
self.ivars().accepts_first_mouse
|
self.ivars().accepts_first_mouse
|
||||||
@@ -815,32 +806,25 @@ impl WinitView {
|
|||||||
tracking_rect: Default::default(),
|
tracking_rect: Default::default(),
|
||||||
ime_state: Default::default(),
|
ime_state: Default::default(),
|
||||||
input_source: Default::default(),
|
input_source: Default::default(),
|
||||||
ime_allowed: Default::default(),
|
ime_capabilities: Default::default(),
|
||||||
forward_key_to_app: Default::default(),
|
forward_key_to_app: Default::default(),
|
||||||
marked_text: Default::default(),
|
marked_text: Default::default(),
|
||||||
accepts_first_mouse,
|
accepts_first_mouse,
|
||||||
option_as_alt: Cell::new(option_as_alt),
|
option_as_alt: Cell::new(option_as_alt),
|
||||||
});
|
});
|
||||||
let this: Retained<Self> = unsafe { msg_send_id![super(this), init] };
|
let this: Retained<Self> = unsafe { msg_send![super(this), init] };
|
||||||
|
|
||||||
*this.ivars().input_source.borrow_mut() = this.current_input_source();
|
*this.ivars().input_source.borrow_mut() = this.current_input_source();
|
||||||
|
|
||||||
this
|
this
|
||||||
}
|
}
|
||||||
|
|
||||||
fn window(&self) -> Retained<WinitWindow> {
|
fn window(&self) -> Retained<NSWindow> {
|
||||||
let window = (**self).window().expect("view must be installed in a window");
|
(**self).window().expect("view must be installed in a window")
|
||||||
|
|
||||||
if !window.isKindOfClass(WinitWindow::class()) {
|
|
||||||
unreachable!("view installed in non-WinitWindow");
|
|
||||||
}
|
|
||||||
|
|
||||||
// SAFETY: Just checked that the window is `WinitWindow`
|
|
||||||
unsafe { Retained::cast(window) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn queue_event(&self, event: WindowEvent) {
|
fn queue_event(&self, event: WindowEvent) {
|
||||||
let window_id = self.window().id();
|
let window_id = window_id(&self.window());
|
||||||
self.ivars().app_state.maybe_queue_with_handler(move |app, event_loop| {
|
self.ivars().app_state.maybe_queue_with_handler(move |app, event_loop| {
|
||||||
app.window_event(event_loop, window_id, event);
|
app.window_event(event_loop, window_id, event);
|
||||||
});
|
});
|
||||||
@@ -884,12 +868,13 @@ impl WinitView {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn set_ime_allowed(&self, ime_allowed: bool) {
|
pub(super) fn set_ime_allowed(&self, capabilities: Option<ImeCapabilities>) {
|
||||||
if self.ivars().ime_allowed.get() == ime_allowed {
|
if self.ivars().ime_capabilities.get().is_some() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
self.ivars().ime_allowed.set(ime_allowed);
|
self.ivars().ime_capabilities.set(capabilities);
|
||||||
if self.ivars().ime_allowed.get() {
|
|
||||||
|
if capabilities.is_some() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -902,6 +887,10 @@ impl WinitView {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) fn ime_capabilities(&self) -> Option<ImeCapabilities> {
|
||||||
|
self.ivars().ime_capabilities.get()
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn set_ime_cursor_area(&self, position: NSPoint, size: NSSize) {
|
pub(super) fn set_ime_cursor_area(&self, position: NSPoint, size: NSSize) {
|
||||||
self.ivars().ime_position.set(position);
|
self.ivars().ime_position.set(position);
|
||||||
self.ivars().ime_size.set(size);
|
self.ivars().ime_size.set(size);
|
||||||
@@ -965,10 +954,8 @@ impl WinitView {
|
|||||||
// We'll correct this later.
|
// We'll correct this later.
|
||||||
state: Pressed,
|
state: Pressed,
|
||||||
text: None,
|
text: None,
|
||||||
platform_specific: KeyEventExtra {
|
text_with_all_modifiers: None,
|
||||||
text_with_all_modifiers: None,
|
key_without_modifiers: logical_key.clone(),
|
||||||
key_without_modifiers: logical_key.clone(),
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let location_mask = ModLocationMask::from_location(event.location);
|
let location_mask = ModLocationMask::from_location(event.location);
|
||||||
@@ -1123,14 +1110,14 @@ fn mouse_button(event: &NSEvent) -> MouseButton {
|
|||||||
// we're getting from the operating system, which makes it
|
// we're getting from the operating system, which makes it
|
||||||
// impossible to provide such events as extra in `KeyEvent`.
|
// impossible to provide such events as extra in `KeyEvent`.
|
||||||
fn replace_event(event: &NSEvent, option_as_alt: OptionAsAlt) -> Retained<NSEvent> {
|
fn replace_event(event: &NSEvent, option_as_alt: OptionAsAlt) -> Retained<NSEvent> {
|
||||||
let ev_mods = event_mods(event).state;
|
let ev_mods = event_mods(event).state();
|
||||||
let ignore_alt_characters = match option_as_alt {
|
let ignore_alt_characters = match option_as_alt {
|
||||||
OptionAsAlt::OnlyLeft if lalt_pressed(event) => true,
|
OptionAsAlt::OnlyLeft if lalt_pressed(event) => true,
|
||||||
OptionAsAlt::OnlyRight if ralt_pressed(event) => true,
|
OptionAsAlt::OnlyRight if ralt_pressed(event) => true,
|
||||||
OptionAsAlt::Both if ev_mods.alt_key() => true,
|
OptionAsAlt::Both if ev_mods.alt_key() => true,
|
||||||
_ => false,
|
_ => false,
|
||||||
} && !ev_mods.control_key()
|
} && !ev_mods.control_key()
|
||||||
&& !ev_mods.super_key();
|
&& !ev_mods.meta_key();
|
||||||
|
|
||||||
if ignore_alt_characters {
|
if ignore_alt_characters {
|
||||||
let ns_chars = unsafe {
|
let ns_chars = unsafe {
|
||||||
@@ -1,22 +1,28 @@
|
|||||||
#![allow(clippy::unnecessary_cast)]
|
#![allow(clippy::unnecessary_cast)]
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use dispatch2::MainThreadBound;
|
||||||
use dpi::{Position, Size};
|
use dpi::{Position, Size};
|
||||||
use objc2::rc::{autoreleasepool, Retained};
|
use objc2::rc::{autoreleasepool, Retained};
|
||||||
use objc2::{declare_class, mutability, ClassType, DeclaredClass};
|
use objc2::{define_class, MainThreadMarker, Message};
|
||||||
use objc2_app_kit::{NSResponder, NSWindow};
|
use objc2_app_kit::{NSPanel, NSResponder, NSWindow};
|
||||||
use objc2_foundation::{MainThreadBound, MainThreadMarker, NSObject};
|
use objc2_foundation::NSObject;
|
||||||
|
use winit_core::cursor::Cursor;
|
||||||
use super::event_loop::ActiveEventLoop;
|
use winit_core::error::RequestError;
|
||||||
use super::window_delegate::WindowDelegate;
|
use winit_core::icon::Icon;
|
||||||
use crate::error::RequestError;
|
use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle};
|
||||||
use crate::monitor::MonitorHandle as CoreMonitorHandle;
|
use winit_core::window::{
|
||||||
use crate::window::{
|
ImeCapabilities, ImeRequest, ImeRequestError, Theme, UserAttentionType, Window as CoreWindow,
|
||||||
Cursor, Fullscreen, Icon, ImePurpose, Theme, UserAttentionType, Window as CoreWindow,
|
|
||||||
WindowAttributes, WindowButtons, WindowId, WindowLevel,
|
WindowAttributes, WindowButtons, WindowId, WindowLevel,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use super::event_loop::ActiveEventLoop;
|
||||||
|
use super::window_delegate::WindowDelegate;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
pub(crate) struct Window {
|
pub(crate) struct Window {
|
||||||
window: MainThreadBound<Retained<WinitWindow>>,
|
window: MainThreadBound<Retained<NSWindow>>,
|
||||||
/// The window only keeps a weak reference to this, so we must keep it around here.
|
/// The window only keeps a weak reference to this, so we must keep it around here.
|
||||||
delegate: MainThreadBound<Retained<WindowDelegate>>,
|
delegate: MainThreadBound<Retained<WindowDelegate>>,
|
||||||
}
|
}
|
||||||
@@ -64,7 +70,7 @@ impl Window {
|
|||||||
impl Drop for Window {
|
impl Drop for Window {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
// Restore the video mode.
|
// Restore the video mode.
|
||||||
if matches!(self.fullscreen(), Some(Fullscreen::Exclusive(_))) {
|
if matches!(self.fullscreen(), Some(Fullscreen::Exclusive(_, _))) {
|
||||||
self.set_fullscreen(None);
|
self.set_fullscreen(None);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,7 +93,7 @@ impl rwh_06::HasWindowHandle for Window {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CoreWindow for Window {
|
impl CoreWindow for Window {
|
||||||
fn id(&self) -> crate::window::WindowId {
|
fn id(&self) -> winit_core::window::WindowId {
|
||||||
self.maybe_wait_on_main(|delegate| delegate.id())
|
self.maybe_wait_on_main(|delegate| delegate.id())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -204,11 +210,11 @@ impl CoreWindow for Window {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) {
|
fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) {
|
||||||
self.maybe_wait_on_main(|delegate| delegate.set_fullscreen(fullscreen.map(Into::into)))
|
self.maybe_wait_on_main(|delegate| delegate.set_fullscreen(fullscreen))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn fullscreen(&self) -> Option<Fullscreen> {
|
fn fullscreen(&self) -> Option<Fullscreen> {
|
||||||
self.maybe_wait_on_main(|delegate| delegate.fullscreen().map(Into::into))
|
self.maybe_wait_on_main(|delegate| delegate.fullscreen())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_decorations(&self, decorations: bool) {
|
fn set_decorations(&self, decorations: bool) {
|
||||||
@@ -227,16 +233,12 @@ impl CoreWindow for Window {
|
|||||||
self.maybe_wait_on_main(|delegate| delegate.set_window_icon(window_icon));
|
self.maybe_wait_on_main(|delegate| delegate.set_window_icon(window_icon));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_ime_cursor_area(&self, position: Position, size: Size) {
|
fn request_ime_update(&self, request: ImeRequest) -> Result<(), ImeRequestError> {
|
||||||
self.maybe_wait_on_main(|delegate| delegate.set_ime_cursor_area(position, size));
|
self.maybe_wait_on_main(|delegate| delegate.request_ime_update(request))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_ime_allowed(&self, allowed: bool) {
|
fn ime_capabilities(&self) -> Option<ImeCapabilities> {
|
||||||
self.maybe_wait_on_main(|delegate| delegate.set_ime_allowed(allowed));
|
self.maybe_wait_on_main(|delegate| delegate.ime_capabilities())
|
||||||
}
|
|
||||||
|
|
||||||
fn set_ime_purpose(&self, purpose: ImePurpose) {
|
|
||||||
self.maybe_wait_on_main(|delegate| delegate.set_ime_purpose(purpose));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn focus_window(&self) {
|
fn focus_window(&self) {
|
||||||
@@ -275,7 +277,10 @@ impl CoreWindow for Window {
|
|||||||
self.maybe_wait_on_main(|delegate| delegate.set_cursor_position(position))
|
self.maybe_wait_on_main(|delegate| delegate.set_cursor_position(position))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_cursor_grab(&self, mode: crate::window::CursorGrabMode) -> Result<(), RequestError> {
|
fn set_cursor_grab(
|
||||||
|
&self,
|
||||||
|
mode: winit_core::window::CursorGrabMode,
|
||||||
|
) -> Result<(), RequestError> {
|
||||||
self.maybe_wait_on_main(|delegate| delegate.set_cursor_grab(mode))
|
self.maybe_wait_on_main(|delegate| delegate.set_cursor_grab(mode))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -289,7 +294,7 @@ impl CoreWindow for Window {
|
|||||||
|
|
||||||
fn drag_resize_window(
|
fn drag_resize_window(
|
||||||
&self,
|
&self,
|
||||||
direction: crate::window::ResizeDirection,
|
direction: winit_core::window::ResizeDirection,
|
||||||
) -> Result<(), RequestError> {
|
) -> Result<(), RequestError> {
|
||||||
Ok(self.maybe_wait_on_main(|delegate| delegate.drag_resize_window(direction))?)
|
Ok(self.maybe_wait_on_main(|delegate| delegate.drag_resize_window(direction))?)
|
||||||
}
|
}
|
||||||
@@ -305,21 +310,24 @@ impl CoreWindow for Window {
|
|||||||
|
|
||||||
fn current_monitor(&self) -> Option<CoreMonitorHandle> {
|
fn current_monitor(&self) -> Option<CoreMonitorHandle> {
|
||||||
self.maybe_wait_on_main(|delegate| {
|
self.maybe_wait_on_main(|delegate| {
|
||||||
delegate.current_monitor().map(|inner| CoreMonitorHandle { inner })
|
delegate.current_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor)))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn available_monitors(&self) -> Box<dyn Iterator<Item = CoreMonitorHandle>> {
|
fn available_monitors(&self) -> Box<dyn Iterator<Item = CoreMonitorHandle>> {
|
||||||
self.maybe_wait_on_main(|delegate| {
|
self.maybe_wait_on_main(|delegate| {
|
||||||
Box::new(
|
Box::new(
|
||||||
delegate.available_monitors().into_iter().map(|inner| CoreMonitorHandle { inner }),
|
delegate
|
||||||
|
.available_monitors()
|
||||||
|
.into_iter()
|
||||||
|
.map(|monitor| CoreMonitorHandle(Arc::new(monitor))),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn primary_monitor(&self) -> Option<CoreMonitorHandle> {
|
fn primary_monitor(&self) -> Option<CoreMonitorHandle> {
|
||||||
self.maybe_wait_on_main(|delegate| {
|
self.maybe_wait_on_main(|delegate| {
|
||||||
delegate.primary_monitor().map(|inner| CoreMonitorHandle { inner })
|
delegate.primary_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor)))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -332,27 +340,21 @@ impl CoreWindow for Window {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
declare_class!(
|
define_class!(
|
||||||
|
#[unsafe(super(NSWindow, NSResponder, NSObject))]
|
||||||
|
#[name = "WinitWindow"]
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct WinitWindow;
|
pub struct WinitWindow;
|
||||||
|
|
||||||
unsafe impl ClassType for WinitWindow {
|
/// This documentation attribute makes rustfmt work for some reason?
|
||||||
#[inherits(NSResponder, NSObject)]
|
impl WinitWindow {
|
||||||
type Super = NSWindow;
|
#[unsafe(method(canBecomeMainWindow))]
|
||||||
type Mutability = mutability::MainThreadOnly;
|
|
||||||
const NAME: &'static str = "WinitWindow";
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DeclaredClass for WinitWindow {}
|
|
||||||
|
|
||||||
unsafe impl WinitWindow {
|
|
||||||
#[method(canBecomeMainWindow)]
|
|
||||||
fn can_become_main_window(&self) -> bool {
|
fn can_become_main_window(&self) -> bool {
|
||||||
trace_scope!("canBecomeMainWindow");
|
trace_scope!("canBecomeMainWindow");
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(canBecomeKeyWindow)]
|
#[unsafe(method(canBecomeKeyWindow))]
|
||||||
fn can_become_key_window(&self) -> bool {
|
fn can_become_key_window(&self) -> bool {
|
||||||
trace_scope!("canBecomeKeyWindow");
|
trace_scope!("canBecomeKeyWindow");
|
||||||
true
|
true
|
||||||
@@ -360,8 +362,24 @@ declare_class!(
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
impl WinitWindow {
|
define_class!(
|
||||||
pub(super) fn id(&self) -> WindowId {
|
#[unsafe(super(NSPanel, NSWindow, NSResponder, NSObject))]
|
||||||
WindowId::from_raw(self as *const Self as usize)
|
#[name = "WinitPanel"]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct WinitPanel;
|
||||||
|
|
||||||
|
/// This documentation attribute makes rustfmt work for some reason?
|
||||||
|
impl WinitPanel {
|
||||||
|
// although NSPanel can become key window
|
||||||
|
// it doesn't if window doesn't have NSWindowStyleMask::Titled
|
||||||
|
#[unsafe(method(canBecomeKeyWindow))]
|
||||||
|
fn can_become_key_window(&self) -> bool {
|
||||||
|
trace_scope!("canBecomeKeyWindow");
|
||||||
|
true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
pub(super) fn window_id(window: &NSWindow) -> WindowId {
|
||||||
|
WindowId::from_raw(window as *const _ as usize)
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
42
winit-common/Cargo.toml
Normal file
42
winit-common/Cargo.toml
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
[package]
|
||||||
|
description = "Winit implementation helpers"
|
||||||
|
documentation = "https://docs.rs/winit-common"
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
name = "winit-common"
|
||||||
|
repository.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
version.workspace = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
# Event Handler
|
||||||
|
event-handler = []
|
||||||
|
|
||||||
|
# XKB
|
||||||
|
wayland = ["dep:memmap2"]
|
||||||
|
x11 = ["xkbcommon-dl?/x11", "dep:x11-dl"]
|
||||||
|
xkb = ["dep:xkbcommon-dl", "dep:smol_str"]
|
||||||
|
|
||||||
|
# CoreFoundation
|
||||||
|
core-foundation = ["dep:objc2", "dep:objc2-core-foundation"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
smol_str = { workspace = true, optional = true }
|
||||||
|
tracing.workspace = true
|
||||||
|
winit-core.workspace = true
|
||||||
|
|
||||||
|
# XKB
|
||||||
|
memmap2 = { workspace = true, optional = true }
|
||||||
|
x11-dl = { workspace = true, optional = true }
|
||||||
|
xkbcommon-dl = { workspace = true, optional = true }
|
||||||
|
|
||||||
|
# CoreFoundation
|
||||||
|
objc2 = { workspace = true, optional = true }
|
||||||
|
objc2-core-foundation = { workspace = true, optional = true, features = [
|
||||||
|
"std",
|
||||||
|
"CFRunLoop",
|
||||||
|
"CFString",
|
||||||
|
] }
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
all-features = true
|
||||||
1
winit-common/LICENSE
Symbolic link
1
winit-common/LICENSE
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE
|
||||||
1
winit-common/README.md
Symbolic link
1
winit-common/README.md
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../README.md
|
||||||
175
winit-common/src/core_foundation/event_loop_proxy.rs
Normal file
175
winit-common/src/core_foundation/event_loop_proxy.rs
Normal file
@@ -0,0 +1,175 @@
|
|||||||
|
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::{
|
||||||
|
kCFRunLoopCommonModes, CFIndex, CFRetained, CFRunLoop, CFRunLoopSource, CFRunLoopSourceContext,
|
||||||
|
Type,
|
||||||
|
};
|
||||||
|
use winit_core::event_loop::EventLoopProxyProvider;
|
||||||
|
|
||||||
|
/// A waker that signals a `CFRunLoopSource` on the main thread.
|
||||||
|
///
|
||||||
|
/// We use this to integrate with the system as cleanly as possible (instead of e.g. keeping an
|
||||||
|
/// atomic around that we check on each iteration of the event loop).
|
||||||
|
///
|
||||||
|
/// See <https://developer.apple.com/documentation/corefoundation/cfrunloopsource?language=objc>.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub struct EventLoopProxy {
|
||||||
|
source: CFRetained<CFRunLoopSource>,
|
||||||
|
/// Cached value of `CFRunLoopGetMain`.
|
||||||
|
main_loop: CFRetained<CFRunLoop>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// FIXME(madsmtm): Mark `CFRunLoopSource` + `CFRunLoop` as `Send` + `Sync`.
|
||||||
|
unsafe impl Send for EventLoopProxy {}
|
||||||
|
unsafe impl Sync for EventLoopProxy {}
|
||||||
|
|
||||||
|
impl EventLoopProxy {
|
||||||
|
/// Create a new proxy, registering it to be performed on the main thread.
|
||||||
|
///
|
||||||
|
/// The provided closure should call `proxy_wake_up` on the application.
|
||||||
|
pub fn new<F: Fn() + 'static>(mtm: MainThreadMarker, signaller: F) -> Self {
|
||||||
|
// We use an `Arc` here to make sure that the reference-counting of the signal container is
|
||||||
|
// atomic (`Retained`/`CFRetained` would be valid alternatives too).
|
||||||
|
let signaller = Arc::new(signaller);
|
||||||
|
|
||||||
|
unsafe extern "C-unwind" fn retain<F>(info: *const c_void) -> *const c_void {
|
||||||
|
// SAFETY: The pointer was passed to `CFRunLoopSourceContext.info` below.
|
||||||
|
unsafe { Arc::increment_strong_count(info.cast::<F>()) };
|
||||||
|
info
|
||||||
|
}
|
||||||
|
unsafe extern "C-unwind" fn release<F>(info: *const c_void) {
|
||||||
|
// SAFETY: The pointer was passed to `CFRunLoopSourceContext.info` below.
|
||||||
|
unsafe { Arc::decrement_strong_count(info.cast::<F>()) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pointer equality / hashing.
|
||||||
|
extern "C-unwind" fn equal(info1: *const c_void, info2: *const c_void) -> u8 {
|
||||||
|
(info1 == info2) as u8
|
||||||
|
}
|
||||||
|
extern "C-unwind" fn hash(info: *const c_void) -> usize {
|
||||||
|
info as usize
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call the provided closure.
|
||||||
|
unsafe extern "C-unwind" fn perform<F: Fn()>(info: *mut c_void) {
|
||||||
|
// SAFETY: The pointer was passed to `CFRunLoopSourceContext.info` below.
|
||||||
|
let signaller = unsafe { &*info.cast::<F>() };
|
||||||
|
(signaller)();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fire last.
|
||||||
|
let order = CFIndex::MAX - 1;
|
||||||
|
|
||||||
|
// This is marked `mut` to match the signature of `CFRunLoopSourceCreate`, but the
|
||||||
|
// information is copied, and not actually mutated.
|
||||||
|
let mut context = CFRunLoopSourceContext {
|
||||||
|
version: 0,
|
||||||
|
// This is retained on creation.
|
||||||
|
info: Arc::as_ptr(&signaller) as *mut c_void,
|
||||||
|
retain: Some(retain::<F>),
|
||||||
|
release: Some(release::<F>),
|
||||||
|
copyDescription: None,
|
||||||
|
equal: Some(equal),
|
||||||
|
hash: Some(hash),
|
||||||
|
schedule: None,
|
||||||
|
cancel: None,
|
||||||
|
perform: Some(perform::<F>),
|
||||||
|
};
|
||||||
|
|
||||||
|
// SAFETY: The normal callbacks are thread-safe (`retain`/`release` use atomics, and
|
||||||
|
// `equal`/`hash` only access a pointer).
|
||||||
|
//
|
||||||
|
// Note that the `perform` callback isn't thread-safe (we don't have `F: Send + Sync`), but
|
||||||
|
// that's okay, since we are on the main thread, and the source is only added to the main
|
||||||
|
// run loop (below), and hence only performed there.
|
||||||
|
//
|
||||||
|
// Keeping the closure alive beyond this scope is fine, because `F: 'static`.
|
||||||
|
let source = unsafe {
|
||||||
|
let _ = mtm;
|
||||||
|
CFRunLoopSource::new(None, order, &mut context).unwrap()
|
||||||
|
};
|
||||||
|
|
||||||
|
// Register the source to be performed on the main thread.
|
||||||
|
let main_loop = CFRunLoop::main().unwrap();
|
||||||
|
unsafe { main_loop.add_source(Some(&source), kCFRunLoopCommonModes) };
|
||||||
|
|
||||||
|
Self { source, main_loop }
|
||||||
|
}
|
||||||
|
|
||||||
|
// FIXME(madsmtm): Use this on macOS too.
|
||||||
|
// More difficult there, since the user can re-start the event loop.
|
||||||
|
pub fn invalidate(&self) {
|
||||||
|
// NOTE: We do NOT fire this on `Drop`, since we want the proxy to be cloneable, such that
|
||||||
|
// we only need to register a single source even if there's multiple proxies in use.
|
||||||
|
self.source.invalidate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopProxyProvider for EventLoopProxy {
|
||||||
|
fn wake_up(&self) {
|
||||||
|
// 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.
|
||||||
|
self.source.signal();
|
||||||
|
|
||||||
|
// 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).
|
||||||
|
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)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
3
winit-common/src/core_foundation/mod.rs
Normal file
3
winit-common/src/core_foundation/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
mod event_loop_proxy;
|
||||||
|
|
||||||
|
pub use event_loop_proxy::*;
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
use std::{fmt, mem};
|
use std::{fmt, mem};
|
||||||
|
|
||||||
use crate::application::ApplicationHandler;
|
use winit_core::application::ApplicationHandler;
|
||||||
|
|
||||||
/// A helper type for storing a reference to `ApplicationHandler`, allowing interior mutable access
|
/// A helper type for storing a reference to `ApplicationHandler`, allowing interior mutable access
|
||||||
/// to it within the execution of a closure.
|
/// to it within the execution of a closure.
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub(crate) struct EventHandler {
|
pub struct EventHandler {
|
||||||
/// This can be in the following states:
|
/// This can be in the following states:
|
||||||
/// - Not registered by the event loop (None).
|
/// - Not registered by the event loop, or terminated (None).
|
||||||
/// - Present (Some(handler)).
|
/// - Present (Some(handler)).
|
||||||
/// - Currently executing the handler / in use (RefCell borrowed).
|
/// - Currently executing the handler / in use (RefCell borrowed).
|
||||||
inner: RefCell<Option<&'static mut dyn ApplicationHandler>>,
|
inner: RefCell<Option<Box<dyn ApplicationHandler + 'static>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Debug for EventHandler {
|
impl fmt::Debug for EventHandler {
|
||||||
@@ -26,7 +26,7 @@ impl fmt::Debug for EventHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl EventHandler {
|
impl EventHandler {
|
||||||
pub(crate) fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self { inner: RefCell::new(None) }
|
Self { inner: RefCell::new(None) }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,9 +35,9 @@ impl EventHandler {
|
|||||||
/// This is similar to using the `scoped-tls` or `scoped-tls-hkt` crates
|
/// This is similar to using the `scoped-tls` or `scoped-tls-hkt` crates
|
||||||
/// to store the handler in a thread local, such that it can be accessed
|
/// to store the handler in a thread local, such that it can be accessed
|
||||||
/// from within the closure.
|
/// from within the closure.
|
||||||
pub(crate) fn set<'handler, R>(
|
pub fn set<'handler, R>(
|
||||||
&self,
|
&self,
|
||||||
app: &'handler mut dyn ApplicationHandler,
|
app: Box<dyn ApplicationHandler + 'handler>,
|
||||||
closure: impl FnOnce() -> R,
|
closure: impl FnOnce() -> R,
|
||||||
) -> R {
|
) -> R {
|
||||||
// SAFETY: We extend the lifetime of the handler here so that we can
|
// SAFETY: We extend the lifetime of the handler here so that we can
|
||||||
@@ -48,8 +48,8 @@ impl EventHandler {
|
|||||||
// extended beyond `'handler`.
|
// extended beyond `'handler`.
|
||||||
let handler = unsafe {
|
let handler = unsafe {
|
||||||
mem::transmute::<
|
mem::transmute::<
|
||||||
&'handler mut dyn ApplicationHandler,
|
Box<dyn ApplicationHandler + 'handler>,
|
||||||
&'static mut dyn ApplicationHandler,
|
Box<dyn ApplicationHandler + 'static>,
|
||||||
>(app)
|
>(app)
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -71,10 +71,13 @@ impl EventHandler {
|
|||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
match self.0.inner.try_borrow_mut().as_deref_mut() {
|
match self.0.inner.try_borrow_mut().as_deref_mut() {
|
||||||
Ok(data @ Some(_)) => {
|
Ok(data @ Some(_)) => {
|
||||||
*data = None;
|
let handler = data.take();
|
||||||
|
// Explicitly `Drop` the application handler.
|
||||||
|
drop(handler);
|
||||||
},
|
},
|
||||||
Ok(None) => {
|
Ok(None) => {
|
||||||
tracing::error!("tried to clear handler, but no handler was set");
|
// Allowed, happens if the handler was cleared manually
|
||||||
|
// elsewhere (such as in `applicationWillTerminate:`).
|
||||||
},
|
},
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
// Note: This is not expected to ever happen, this
|
// Note: This is not expected to ever happen, this
|
||||||
@@ -101,25 +104,24 @@ impl EventHandler {
|
|||||||
// soundness.
|
// soundness.
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
pub fn in_use(&self) -> bool {
|
||||||
pub(crate) fn in_use(&self) -> bool {
|
|
||||||
self.inner.try_borrow().is_err()
|
self.inner.try_borrow().is_err()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn ready(&self) -> bool {
|
pub fn ready(&self) -> bool {
|
||||||
matches!(self.inner.try_borrow().as_deref(), Ok(Some(_)))
|
matches!(self.inner.try_borrow().as_deref(), Ok(Some(_)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn handle(&self, callback: impl FnOnce(&mut dyn ApplicationHandler)) {
|
pub fn handle(&self, callback: impl FnOnce(&mut (dyn ApplicationHandler + '_))) {
|
||||||
match self.inner.try_borrow_mut().as_deref_mut() {
|
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,
|
// It is important that we keep the reference borrowed here,
|
||||||
// so that `in_use` can properly detect that the handler is
|
// so that `in_use` can properly detect that the handler is
|
||||||
// still in use.
|
// still in use.
|
||||||
//
|
//
|
||||||
// If the handler unwinds, the `RefMut` will ensure that the
|
// If the handler unwinds, the `RefMut` will ensure that the
|
||||||
// handler is no longer borrowed.
|
// handler is no longer borrowed.
|
||||||
callback(*user_app);
|
callback(&mut **user_app);
|
||||||
},
|
},
|
||||||
Ok(None) => {
|
Ok(None) => {
|
||||||
// `NSApplication`, our app state and this handler are all
|
// `NSApplication`, our app state and this handler are all
|
||||||
@@ -133,4 +135,21 @@ impl EventHandler {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn terminate(&self) {
|
||||||
|
match self.inner.try_borrow_mut().as_deref_mut() {
|
||||||
|
Ok(data @ Some(_)) => {
|
||||||
|
let handler = data.take();
|
||||||
|
// Explicitly `Drop` the application handler.
|
||||||
|
drop(handler);
|
||||||
|
},
|
||||||
|
Ok(None) => {
|
||||||
|
// When terminating, we expect the application handler to still be registered.
|
||||||
|
tracing::error!("tried to clear handler, but no handler was set");
|
||||||
|
},
|
||||||
|
Err(_) => {
|
||||||
|
panic!("tried to clear handler while an event is currently being handled");
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
8
winit-common/src/lib.rs
Normal file
8
winit-common/src/lib.rs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
//! Winit implementation helpers.
|
||||||
|
|
||||||
|
#[cfg(feature = "core-foundation")]
|
||||||
|
pub mod core_foundation;
|
||||||
|
#[cfg(feature = "event-handler")]
|
||||||
|
pub mod event_handler;
|
||||||
|
#[cfg(feature = "xkb")]
|
||||||
|
pub mod xkb;
|
||||||
@@ -4,20 +4,22 @@ use std::ffi::c_char;
|
|||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
use std::ptr::{self, NonNull};
|
use std::ptr::{self, NonNull};
|
||||||
|
|
||||||
#[cfg(x11_platform)]
|
use winit_core::keyboard::{
|
||||||
|
Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey,
|
||||||
|
};
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
use x11_dl::xlib_xcb::xcb_connection_t;
|
use x11_dl::xlib_xcb::xcb_connection_t;
|
||||||
use xkb::XKB_MOD_INVALID;
|
use xkb::XKB_MOD_INVALID;
|
||||||
use xkbcommon_dl::{
|
use xkbcommon_dl::{
|
||||||
self as xkb, xkb_keycode_t, xkb_keymap, xkb_keymap_compile_flags, xkb_keysym_t,
|
self as xkb, xkb_keycode_t, xkb_keymap, xkb_keymap_compile_flags, xkb_keysym_t,
|
||||||
xkb_layout_index_t, xkb_mod_index_t,
|
xkb_layout_index_t, xkb_mod_index_t,
|
||||||
};
|
};
|
||||||
#[cfg(wayland_platform)]
|
#[cfg(feature = "wayland")]
|
||||||
use {memmap2::MmapOptions, std::os::unix::io::OwnedFd};
|
use {memmap2::MmapOptions, std::os::unix::io::OwnedFd};
|
||||||
|
|
||||||
use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey};
|
#[cfg(feature = "x11")]
|
||||||
#[cfg(x11_platform)]
|
use super::XKBXH;
|
||||||
use crate::platform_impl::common::xkb::XKBXH;
|
use super::{XkbContext, XKBH};
|
||||||
use crate::platform_impl::common::xkb::{XkbContext, XKBH};
|
|
||||||
|
|
||||||
/// Map the raw X11-style keycode to the `KeyCode` enum.
|
/// Map the raw X11-style keycode to the `KeyCode` enum.
|
||||||
///
|
///
|
||||||
@@ -166,8 +168,8 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
122 => KeyCode::Lang1,
|
122 => KeyCode::Lang1,
|
||||||
123 => KeyCode::Lang2,
|
123 => KeyCode::Lang2,
|
||||||
124 => KeyCode::IntlYen,
|
124 => KeyCode::IntlYen,
|
||||||
125 => KeyCode::SuperLeft,
|
125 => KeyCode::MetaLeft,
|
||||||
126 => KeyCode::SuperRight,
|
126 => KeyCode::MetaRight,
|
||||||
127 => KeyCode::ContextMenu,
|
127 => KeyCode::ContextMenu,
|
||||||
128 => KeyCode::BrowserStop,
|
128 => KeyCode::BrowserStop,
|
||||||
129 => KeyCode::Again,
|
129 => KeyCode::Again,
|
||||||
@@ -419,8 +421,8 @@ pub fn physicalkey_to_scancode(key: PhysicalKey) -> Option<u32> {
|
|||||||
KeyCode::Lang1 => Some(122),
|
KeyCode::Lang1 => Some(122),
|
||||||
KeyCode::Lang2 => Some(123),
|
KeyCode::Lang2 => Some(123),
|
||||||
KeyCode::IntlYen => Some(124),
|
KeyCode::IntlYen => Some(124),
|
||||||
KeyCode::SuperLeft => Some(125),
|
KeyCode::MetaLeft => Some(125),
|
||||||
KeyCode::SuperRight => Some(126),
|
KeyCode::MetaRight => Some(126),
|
||||||
KeyCode::ContextMenu => Some(127),
|
KeyCode::ContextMenu => Some(127),
|
||||||
KeyCode::BrowserStop => Some(128),
|
KeyCode::BrowserStop => Some(128),
|
||||||
KeyCode::Again => Some(129),
|
KeyCode::Again => Some(129),
|
||||||
@@ -622,16 +624,20 @@ pub fn keysym_to_key(keysym: u32) -> Key {
|
|||||||
keysyms::Control_R => NamedKey::Control,
|
keysyms::Control_R => NamedKey::Control,
|
||||||
keysyms::Caps_Lock => NamedKey::CapsLock,
|
keysyms::Caps_Lock => NamedKey::CapsLock,
|
||||||
// keysyms::Shift_Lock => NamedKey::ShiftLock,
|
// keysyms::Shift_Lock => NamedKey::ShiftLock,
|
||||||
|
|
||||||
// keysyms::Meta_L => NamedKey::Meta,
|
|
||||||
// keysyms::Meta_R => NamedKey::Meta,
|
|
||||||
keysyms::Alt_L => NamedKey::Alt,
|
keysyms::Alt_L => NamedKey::Alt,
|
||||||
keysyms::Alt_R => NamedKey::Alt,
|
keysyms::Alt_R => NamedKey::Alt,
|
||||||
keysyms::Super_L => NamedKey::Super,
|
#[allow(deprecated)]
|
||||||
keysyms::Super_R => NamedKey::Super,
|
|
||||||
keysyms::Hyper_L => NamedKey::Hyper,
|
keysyms::Hyper_L => NamedKey::Hyper,
|
||||||
|
#[allow(deprecated)]
|
||||||
keysyms::Hyper_R => NamedKey::Hyper,
|
keysyms::Hyper_R => NamedKey::Hyper,
|
||||||
|
|
||||||
|
// Browsers map X11's Super keys to Meta, so we do that as well.
|
||||||
|
keysyms::Super_L => NamedKey::Meta,
|
||||||
|
keysyms::Super_R => NamedKey::Meta,
|
||||||
|
// The actual Meta keys do not seem to be used by browsers, so we don't do that either.
|
||||||
|
// keysyms::Meta_L => NamedKey::Super,
|
||||||
|
// keysyms::Meta_R => NamedKey::Super,
|
||||||
|
|
||||||
// XKB function and modifier keys
|
// XKB function and modifier keys
|
||||||
// keysyms::ISO_Lock => NamedKey::IsoLock,
|
// keysyms::ISO_Lock => NamedKey::IsoLock,
|
||||||
// keysyms::ISO_Level2_Latch => NamedKey::IsoLevel2Latch,
|
// keysyms::ISO_Level2_Latch => NamedKey::IsoLevel2Latch,
|
||||||
@@ -724,7 +730,7 @@ pub fn keysym_to_key(keysym: u32) -> Key {
|
|||||||
keysyms::_3270_PrintScreen => NamedKey::PrintScreen,
|
keysyms::_3270_PrintScreen => NamedKey::PrintScreen,
|
||||||
keysyms::_3270_Enter => NamedKey::Enter,
|
keysyms::_3270_Enter => NamedKey::Enter,
|
||||||
|
|
||||||
keysyms::space => NamedKey::Space,
|
keysyms::space => return Key::Character(" ".into()),
|
||||||
// exclam..Sinh_kunddaliya
|
// exclam..Sinh_kunddaliya
|
||||||
|
|
||||||
// XFree86
|
// XFree86
|
||||||
@@ -941,7 +947,7 @@ pub struct XkbKeymap {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl XkbKeymap {
|
impl XkbKeymap {
|
||||||
#[cfg(wayland_platform)]
|
#[cfg(feature = "wayland")]
|
||||||
pub fn from_fd(context: &XkbContext, fd: OwnedFd, size: usize) -> Option<Self> {
|
pub fn from_fd(context: &XkbContext, fd: OwnedFd, size: usize) -> Option<Self> {
|
||||||
let map = unsafe { MmapOptions::new().len(size).map_copy_read_only(&fd).ok()? };
|
let map = unsafe { MmapOptions::new().len(size).map_copy_read_only(&fd).ok()? };
|
||||||
|
|
||||||
@@ -958,7 +964,7 @@ impl XkbKeymap {
|
|||||||
Some(Self::new_inner(keymap, 0))
|
Some(Self::new_inner(keymap, 0))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(x11_platform)]
|
#[cfg(feature = "x11")]
|
||||||
pub fn from_x11_keymap(
|
pub fn from_x11_keymap(
|
||||||
context: &XkbContext,
|
context: &XkbContext,
|
||||||
xcb: *mut xcb_connection_t,
|
xcb: *mut xcb_connection_t,
|
||||||
@@ -991,7 +997,7 @@ impl XkbKeymap {
|
|||||||
Self { keymap, _mods_indices: mods_indices, _core_keyboard_id }
|
Self { keymap, _mods_indices: mods_indices, _core_keyboard_id }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(x11_platform)]
|
#[cfg(feature = "x11")]
|
||||||
pub fn mods_indices(&self) -> ModsIndices {
|
pub fn mods_indices(&self) -> ModsIndices {
|
||||||
self._mods_indices
|
self._mods_indices
|
||||||
}
|
}
|
||||||
@@ -1043,7 +1049,7 @@ impl Deref for XkbKeymap {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Modifier index in the keymap.
|
/// Modifier index in the keymap.
|
||||||
#[cfg_attr(not(x11_platform), allow(dead_code))]
|
#[cfg_attr(not(feature = "x11"), allow(dead_code))]
|
||||||
#[derive(Default, Debug, Clone, Copy)]
|
#[derive(Default, Debug, Clone, Copy)]
|
||||||
pub struct ModsIndices {
|
pub struct ModsIndices {
|
||||||
pub shift: Option<xkb_mod_index_t>,
|
pub shift: Option<xkb_mod_index_t>,
|
||||||
@@ -1,30 +1,27 @@
|
|||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
use std::os::raw::c_char;
|
use std::os::raw::c_char;
|
||||||
#[cfg(wayland_platform)]
|
#[cfg(feature = "wayland")]
|
||||||
use std::os::unix::io::OwnedFd;
|
use std::os::unix::io::OwnedFd;
|
||||||
use std::ptr::{self, NonNull};
|
use std::ptr::{self, NonNull};
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::sync::LazyLock;
|
||||||
|
|
||||||
use smol_str::SmolStr;
|
use smol_str::SmolStr;
|
||||||
use tracing::warn;
|
use winit_core::event::{ElementState, KeyEvent};
|
||||||
|
use winit_core::keyboard::{Key, KeyLocation};
|
||||||
use xkbcommon_dl::{
|
use xkbcommon_dl::{
|
||||||
self as xkb, xkb_compose_status, xkb_context, xkb_context_flags, xkbcommon_compose_handle,
|
self as xkb, xkb_compose_status, xkb_context, xkb_context_flags, xkbcommon_compose_handle,
|
||||||
xkbcommon_handle, XkbCommon, XkbCommonCompose,
|
xkbcommon_handle, XkbCommon, XkbCommonCompose,
|
||||||
};
|
};
|
||||||
#[cfg(x11_platform)]
|
#[cfg(feature = "x11")]
|
||||||
use {x11_dl::xlib_xcb::xcb_connection_t, xkbcommon_dl::x11::xkbcommon_x11_handle};
|
use {x11_dl::xlib_xcb::xcb_connection_t, xkbcommon_dl::x11::xkbcommon_x11_handle};
|
||||||
|
|
||||||
use crate::event::{ElementState, KeyEvent};
|
|
||||||
use crate::keyboard::{Key, KeyLocation};
|
|
||||||
use crate::platform_impl::KeyEventExtra;
|
|
||||||
use crate::utils::Lazy;
|
|
||||||
|
|
||||||
mod compose;
|
mod compose;
|
||||||
mod keymap;
|
mod keymap;
|
||||||
mod state;
|
mod state;
|
||||||
|
|
||||||
use compose::{ComposeStatus, XkbComposeState, XkbComposeTable};
|
use compose::{ComposeStatus, XkbComposeState, XkbComposeTable};
|
||||||
#[cfg(x11_platform)]
|
#[cfg(feature = "x11")]
|
||||||
pub use keymap::raw_keycode_to_physicalkey;
|
pub use keymap::raw_keycode_to_physicalkey;
|
||||||
use keymap::XkbKeymap;
|
use keymap::XkbKeymap;
|
||||||
pub use keymap::{physicalkey_to_scancode, scancode_to_physicalkey};
|
pub use keymap::{physicalkey_to_scancode, scancode_to_physicalkey};
|
||||||
@@ -33,10 +30,10 @@ pub use state::XkbState;
|
|||||||
// TODO: Wire this up without using a static `AtomicBool`.
|
// TODO: Wire this up without using a static `AtomicBool`.
|
||||||
static RESET_DEAD_KEYS: AtomicBool = AtomicBool::new(false);
|
static RESET_DEAD_KEYS: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
static XKBH: Lazy<&'static XkbCommon> = Lazy::new(xkbcommon_handle);
|
static XKBH: LazyLock<&'static XkbCommon> = LazyLock::new(xkbcommon_handle);
|
||||||
static XKBCH: Lazy<&'static XkbCommonCompose> = Lazy::new(xkbcommon_compose_handle);
|
static XKBCH: LazyLock<&'static XkbCommonCompose> = LazyLock::new(xkbcommon_compose_handle);
|
||||||
#[cfg(feature = "x11")]
|
#[cfg(feature = "x11")]
|
||||||
static XKBXH: Lazy<&'static xkb::x11::XkbCommonX11> = Lazy::new(xkbcommon_x11_handle);
|
static XKBXH: LazyLock<&'static xkb::x11::XkbCommonX11> = LazyLock::new(xkbcommon_x11_handle);
|
||||||
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn reset_dead_keys() {
|
pub fn reset_dead_keys() {
|
||||||
@@ -52,7 +49,7 @@ pub enum Error {
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Context {
|
pub struct Context {
|
||||||
// NOTE: field order matters.
|
// NOTE: field order matters.
|
||||||
#[cfg(x11_platform)]
|
#[cfg(feature = "x11")]
|
||||||
pub core_keyboard_id: i32,
|
pub core_keyboard_id: i32,
|
||||||
state: Option<XkbState>,
|
state: Option<XkbState>,
|
||||||
keymap: Option<XkbKeymap>,
|
keymap: Option<XkbKeymap>,
|
||||||
@@ -86,7 +83,7 @@ impl Context {
|
|||||||
keymap: None,
|
keymap: None,
|
||||||
compose_state1,
|
compose_state1,
|
||||||
compose_state2,
|
compose_state2,
|
||||||
#[cfg(x11_platform)]
|
#[cfg(feature = "x11")]
|
||||||
core_keyboard_id: 0,
|
core_keyboard_id: 0,
|
||||||
_compose_table: compose_table,
|
_compose_table: compose_table,
|
||||||
context,
|
context,
|
||||||
@@ -127,23 +124,23 @@ impl Context {
|
|||||||
self.keymap.as_mut()
|
self.keymap.as_mut()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(wayland_platform)]
|
#[cfg(feature = "wayland")]
|
||||||
pub fn set_keymap_from_fd(&mut self, fd: OwnedFd, size: usize) {
|
pub fn set_keymap_from_fd(&mut self, fd: OwnedFd, size: usize) {
|
||||||
let keymap = XkbKeymap::from_fd(&self.context, fd, size);
|
let keymap = XkbKeymap::from_fd(&self.context, fd, size);
|
||||||
let state = keymap.as_ref().and_then(XkbState::new_wayland);
|
let state = keymap.as_ref().and_then(XkbState::new_wayland);
|
||||||
if keymap.is_none() || state.is_none() {
|
if keymap.is_none() || state.is_none() {
|
||||||
warn!("failed to update xkb keymap");
|
tracing::warn!("failed to update xkb keymap");
|
||||||
}
|
}
|
||||||
self.state = state;
|
self.state = state;
|
||||||
self.keymap = keymap;
|
self.keymap = keymap;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(x11_platform)]
|
#[cfg(feature = "x11")]
|
||||||
pub fn set_keymap_from_x11(&mut self, xcb: *mut xcb_connection_t) {
|
pub fn set_keymap_from_x11(&mut self, xcb: *mut xcb_connection_t) {
|
||||||
let keymap = XkbKeymap::from_x11_keymap(&self.context, xcb, self.core_keyboard_id);
|
let keymap = XkbKeymap::from_x11_keymap(&self.context, xcb, self.core_keyboard_id);
|
||||||
let state = keymap.as_ref().and_then(|keymap| XkbState::new_x11(xcb, keymap));
|
let state = keymap.as_ref().and_then(|keymap| XkbState::new_x11(xcb, keymap));
|
||||||
if keymap.is_none() || state.is_none() {
|
if keymap.is_none() || state.is_none() {
|
||||||
warn!("failed to update xkb keymap");
|
tracing::warn!("failed to update xkb keymap");
|
||||||
}
|
}
|
||||||
self.state = state;
|
self.state = state;
|
||||||
self.keymap = keymap;
|
self.keymap = keymap;
|
||||||
@@ -162,7 +159,7 @@ impl Context {
|
|||||||
/// Key builder context with the user provided xkb state.
|
/// Key builder context with the user provided xkb state.
|
||||||
///
|
///
|
||||||
/// Should be used when the original context must not be altered.
|
/// Should be used when the original context must not be altered.
|
||||||
#[cfg(x11_platform)]
|
#[cfg(feature = "x11")]
|
||||||
pub fn key_context_with_state<'a>(
|
pub fn key_context_with_state<'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
state: &'a mut XkbState,
|
state: &'a mut XkbState,
|
||||||
@@ -198,9 +195,16 @@ impl KeyContext<'_> {
|
|||||||
let (key_without_modifiers, _) = event.key_without_modifiers();
|
let (key_without_modifiers, _) = event.key_without_modifiers();
|
||||||
let text_with_all_modifiers = event.text_with_all_modifiers();
|
let text_with_all_modifiers = event.text_with_all_modifiers();
|
||||||
|
|
||||||
let platform_specific = KeyEventExtra { text_with_all_modifiers, key_without_modifiers };
|
KeyEvent {
|
||||||
|
physical_key,
|
||||||
KeyEvent { physical_key, logical_key, text, location, state, repeat, platform_specific }
|
logical_key,
|
||||||
|
text,
|
||||||
|
location,
|
||||||
|
state,
|
||||||
|
repeat,
|
||||||
|
text_with_all_modifiers,
|
||||||
|
key_without_modifiers,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn keysym_to_utf8_raw(&mut self, keysym: u32) -> Option<SmolStr> {
|
fn keysym_to_utf8_raw(&mut self, keysym: u32) -> Option<SmolStr> {
|
||||||
@@ -319,7 +323,7 @@ impl<'a, 'b> KeyEventResults<'a, 'b> {
|
|||||||
|
|
||||||
// The current behaviour makes it so composing a character overrides attempts to input a
|
// The current behaviour makes it so composing a character overrides attempts to input a
|
||||||
// control character with the `Ctrl` key. We can potentially add a configuration option
|
// control character with the `Ctrl` key. We can potentially add a configuration option
|
||||||
// if someone specifically wants the oppsite behaviour.
|
// if someone specifically wants the opposite behaviour.
|
||||||
pub fn text_with_all_modifiers(&mut self) -> Option<SmolStr> {
|
pub fn text_with_all_modifiers(&mut self) -> Option<SmolStr> {
|
||||||
match self.composed_text() {
|
match self.composed_text() {
|
||||||
Ok(text) => text,
|
Ok(text) => text,
|
||||||
@@ -4,16 +4,16 @@ use std::os::raw::c_char;
|
|||||||
use std::ptr::NonNull;
|
use std::ptr::NonNull;
|
||||||
|
|
||||||
use smol_str::SmolStr;
|
use smol_str::SmolStr;
|
||||||
#[cfg(x11_platform)]
|
#[cfg(feature = "x11")]
|
||||||
use x11_dl::xlib_xcb::xcb_connection_t;
|
use x11_dl::xlib_xcb::xcb_connection_t;
|
||||||
use xkbcommon_dl::{
|
use xkbcommon_dl::{
|
||||||
self as xkb, xkb_keycode_t, xkb_keysym_t, xkb_layout_index_t, xkb_state, xkb_state_component,
|
self as xkb, xkb_keycode_t, xkb_keysym_t, xkb_layout_index_t, xkb_state, xkb_state_component,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::platform_impl::common::xkb::keymap::XkbKeymap;
|
use super::keymap::XkbKeymap;
|
||||||
#[cfg(x11_platform)]
|
#[cfg(feature = "x11")]
|
||||||
use crate::platform_impl::common::xkb::XKBXH;
|
use super::XKBXH;
|
||||||
use crate::platform_impl::common::xkb::{make_string_with, XKBH};
|
use super::{make_string_with, XKBH};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct XkbState {
|
pub struct XkbState {
|
||||||
@@ -22,13 +22,13 @@ pub struct XkbState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl XkbState {
|
impl XkbState {
|
||||||
#[cfg(wayland_platform)]
|
#[cfg(feature = "wayland")]
|
||||||
pub fn new_wayland(keymap: &XkbKeymap) -> Option<Self> {
|
pub fn new_wayland(keymap: &XkbKeymap) -> Option<Self> {
|
||||||
let state = NonNull::new(unsafe { (XKBH.xkb_state_new)(keymap.as_ptr()) })?;
|
let state = NonNull::new(unsafe { (XKBH.xkb_state_new)(keymap.as_ptr()) })?;
|
||||||
Some(Self::new_inner(state))
|
Some(Self::new_inner(state))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(x11_platform)]
|
#[cfg(feature = "x11")]
|
||||||
pub fn new_x11(xcb: *mut xcb_connection_t, keymap: &XkbKeymap) -> Option<Self> {
|
pub fn new_x11(xcb: *mut xcb_connection_t, keymap: &XkbKeymap) -> Option<Self> {
|
||||||
let state = unsafe {
|
let state = unsafe {
|
||||||
(XKBXH.xkb_x11_state_new_from_device)(keymap.as_ptr(), xcb, keymap._core_keyboard_id)
|
(XKBXH.xkb_x11_state_new_from_device)(keymap.as_ptr(), xcb, keymap._core_keyboard_id)
|
||||||
@@ -52,7 +52,7 @@ impl XkbState {
|
|||||||
unsafe { (XKBH.xkb_state_key_get_layout)(self.state.as_ptr(), key) }
|
unsafe { (XKBH.xkb_state_key_get_layout)(self.state.as_ptr(), key) }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(x11_platform)]
|
#[cfg(feature = "x11")]
|
||||||
pub fn depressed_modifiers(&mut self) -> xkb::xkb_mod_mask_t {
|
pub fn depressed_modifiers(&mut self) -> xkb::xkb_mod_mask_t {
|
||||||
unsafe {
|
unsafe {
|
||||||
(XKBH.xkb_state_serialize_mods)(
|
(XKBH.xkb_state_serialize_mods)(
|
||||||
@@ -62,7 +62,7 @@ impl XkbState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(x11_platform)]
|
#[cfg(feature = "x11")]
|
||||||
pub fn latched_modifiers(&mut self) -> xkb::xkb_mod_mask_t {
|
pub fn latched_modifiers(&mut self) -> xkb::xkb_mod_mask_t {
|
||||||
unsafe {
|
unsafe {
|
||||||
(XKBH.xkb_state_serialize_mods)(
|
(XKBH.xkb_state_serialize_mods)(
|
||||||
@@ -72,7 +72,7 @@ impl XkbState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(x11_platform)]
|
#[cfg(feature = "x11")]
|
||||||
pub fn locked_modifiers(&mut self) -> xkb::xkb_mod_mask_t {
|
pub fn locked_modifiers(&mut self) -> xkb::xkb_mod_mask_t {
|
||||||
unsafe {
|
unsafe {
|
||||||
(XKBH.xkb_state_serialize_mods)(
|
(XKBH.xkb_state_serialize_mods)(
|
||||||
@@ -153,12 +153,13 @@ impl Drop for XkbState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Represents the current state of the keyboard modifiers
|
/// Represents the current logical state of the keyboard modifiers
|
||||||
///
|
///
|
||||||
/// Each field of this struct represents a modifier and is `true` if this modifier is active.
|
/// Each field of this struct represents a modifier and is `true` if this modifier is active.
|
||||||
///
|
///
|
||||||
/// For some modifiers, this means that the key is currently pressed, others are toggled
|
/// For some modifiers, this means that the key is logically pressed, others are toggled (like Caps
|
||||||
/// (like caps lock).
|
/// Lock). But physically the key can be in any state (for example, released Shift when
|
||||||
|
/// it's active as a sticky modifier or released Caps Lock when it's toggled on)
|
||||||
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
||||||
pub struct ModifiersState {
|
pub struct ModifiersState {
|
||||||
/// The "control" key
|
/// The "control" key
|
||||||
@@ -177,13 +178,13 @@ pub struct ModifiersState {
|
|||||||
pub num_lock: bool,
|
pub num_lock: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<ModifiersState> for crate::keyboard::ModifiersState {
|
impl From<ModifiersState> for winit_core::keyboard::ModifiersState {
|
||||||
fn from(mods: ModifiersState) -> crate::keyboard::ModifiersState {
|
fn from(mods: ModifiersState) -> winit_core::keyboard::ModifiersState {
|
||||||
let mut to_mods = crate::keyboard::ModifiersState::empty();
|
let mut to_mods = winit_core::keyboard::ModifiersState::empty();
|
||||||
to_mods.set(crate::keyboard::ModifiersState::SHIFT, mods.shift);
|
to_mods.set(winit_core::keyboard::ModifiersState::SHIFT, mods.shift);
|
||||||
to_mods.set(crate::keyboard::ModifiersState::CONTROL, mods.ctrl);
|
to_mods.set(winit_core::keyboard::ModifiersState::CONTROL, mods.ctrl);
|
||||||
to_mods.set(crate::keyboard::ModifiersState::ALT, mods.alt);
|
to_mods.set(winit_core::keyboard::ModifiersState::ALT, mods.alt);
|
||||||
to_mods.set(crate::keyboard::ModifiersState::SUPER, mods.logo);
|
to_mods.set(winit_core::keyboard::ModifiersState::META, mods.logo);
|
||||||
to_mods
|
to_mods
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
39
winit-core/Cargo.toml
Normal file
39
winit-core/Cargo.toml
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
[package]
|
||||||
|
authors = ["The winit contributors", "Kirill Chibisov <contact@kchibisov.com>"]
|
||||||
|
categories = ["gui"]
|
||||||
|
description = "winit core API."
|
||||||
|
documentation = "https://docs.rs/winit-core"
|
||||||
|
edition.workspace = true
|
||||||
|
keywords = ["windowing"]
|
||||||
|
license.workspace = true
|
||||||
|
name = "winit-core"
|
||||||
|
readme = "README.md"
|
||||||
|
repository.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
version.workspace = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
serde = [
|
||||||
|
"dep:serde",
|
||||||
|
"bitflags/serde",
|
||||||
|
"cursor-icon/serde",
|
||||||
|
"dpi/serde",
|
||||||
|
"keyboard-types/serde",
|
||||||
|
"smol_str/serde",
|
||||||
|
]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
bitflags.workspace = true
|
||||||
|
cursor-icon.workspace = true
|
||||||
|
dpi.workspace = true
|
||||||
|
keyboard-types.workspace = true
|
||||||
|
rwh_06.workspace = true
|
||||||
|
serde = { workspace = true, optional = true }
|
||||||
|
smol_str.workspace = true
|
||||||
|
|
||||||
|
# `wasm32-unknown-unknown` and `wasm32-none`, but not `wasm32-wasi`.
|
||||||
|
[target.'cfg(all(target_family = "wasm", any(target_os = "unknown", target_os = "none")))'.dependencies]
|
||||||
|
web-time.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
winit.workspace = true
|
||||||
1
winit-core/LICENSE
Symbolic link
1
winit-core/LICENSE
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE
|
||||||
1
winit-core/README.md
Symbolic link
1
winit-core/README.md
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../README.md
|
||||||
52
winit-core/src/application/macos.rs
Normal file
52
winit-core/src/application/macos.rs
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
use crate::application::ApplicationHandler;
|
||||||
|
use crate::event_loop::ActiveEventLoop;
|
||||||
|
use crate::window::WindowId;
|
||||||
|
|
||||||
|
/// Additional events on [`ApplicationHandler`] that are specific to macOS.
|
||||||
|
///
|
||||||
|
/// This can be registered with [`ApplicationHandler::macos_handler`].
|
||||||
|
pub trait ApplicationHandlerExtMacOS: ApplicationHandler {
|
||||||
|
/// The system interpreted a keypress as a standard key binding command.
|
||||||
|
///
|
||||||
|
/// Examples include inserting tabs and newlines, or moving the insertion point, see
|
||||||
|
/// [`NSStandardKeyBindingResponding`] for the full list of key bindings. They are often text
|
||||||
|
/// editing related.
|
||||||
|
///
|
||||||
|
/// This corresponds to the [`doCommandBySelector:`] method on `NSTextInputClient`.
|
||||||
|
///
|
||||||
|
/// The `action` parameter contains the string representation of the selector. Examples include
|
||||||
|
/// `"insertBacktab:"`, `"indent:"` and `"noop:"`.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```ignore
|
||||||
|
/// impl ApplicationHandlerExtMacOS for App {
|
||||||
|
/// fn standard_key_binding(
|
||||||
|
/// &mut self,
|
||||||
|
/// event_loop: &dyn ActiveEventLoop,
|
||||||
|
/// window_id: WindowId,
|
||||||
|
/// action: &str,
|
||||||
|
/// ) {
|
||||||
|
/// match action {
|
||||||
|
/// "moveBackward:" => self.cursor.position -= 1,
|
||||||
|
/// "moveForward:" => self.cursor.position += 1,
|
||||||
|
/// _ => {} // Ignore other actions
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// [`NSStandardKeyBindingResponding`]: https://developer.apple.com/documentation/appkit/nsstandardkeybindingresponding?language=objc
|
||||||
|
/// [`doCommandBySelector:`]: https://developer.apple.com/documentation/appkit/nstextinputclient/1438256-docommandbyselector?language=objc
|
||||||
|
#[doc(alias = "doCommandBySelector:")]
|
||||||
|
fn standard_key_binding(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
window_id: WindowId,
|
||||||
|
action: &str,
|
||||||
|
) {
|
||||||
|
let _ = event_loop;
|
||||||
|
let _ = window_id;
|
||||||
|
let _ = action;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
use crate::event::{DeviceEvent, DeviceId, StartCause, WindowEvent};
|
use crate::event::{DeviceEvent, DeviceId, StartCause, WindowEvent};
|
||||||
use crate::event_loop::ActiveEventLoop;
|
use crate::event_loop::ActiveEventLoop;
|
||||||
#[cfg(any(docsrs, macos_platform))]
|
|
||||||
use crate::platform::macos::ApplicationHandlerExtMacOS;
|
|
||||||
use crate::window::WindowId;
|
use crate::window::WindowId;
|
||||||
|
|
||||||
/// The handler of the application events.
|
pub mod macos;
|
||||||
|
|
||||||
|
/// The handler of application-level events.
|
||||||
pub trait ApplicationHandler {
|
pub trait ApplicationHandler {
|
||||||
/// Emitted when new events arrive from the OS to be processed.
|
/// Emitted when new events arrive from the OS to be processed.
|
||||||
///
|
///
|
||||||
@@ -57,7 +57,6 @@ pub trait ApplicationHandler {
|
|||||||
///
|
///
|
||||||
/// [`resumed()`]: Self::resumed()
|
/// [`resumed()`]: Self::resumed()
|
||||||
/// [`suspended()`]: Self::suspended()
|
/// [`suspended()`]: Self::suspended()
|
||||||
/// [`exiting()`]: Self::exiting()
|
|
||||||
fn resumed(&mut self, event_loop: &dyn ActiveEventLoop) {
|
fn resumed(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
let _ = event_loop;
|
let _ = event_loop;
|
||||||
}
|
}
|
||||||
@@ -126,8 +125,9 @@ pub trait ApplicationHandler {
|
|||||||
/// use std::thread;
|
/// use std::thread;
|
||||||
/// use std::time::Duration;
|
/// use std::time::Duration;
|
||||||
///
|
///
|
||||||
/// use winit::application::ApplicationHandler;
|
/// use winit::event_loop::EventLoop;
|
||||||
/// use winit::event_loop::{ActiveEventLoop, EventLoop};
|
/// use winit_core::application::ApplicationHandler;
|
||||||
|
/// use winit_core::event_loop::ActiveEventLoop;
|
||||||
///
|
///
|
||||||
/// struct MyApp {
|
/// struct MyApp {
|
||||||
/// receiver: mpsc::Receiver<u64>,
|
/// receiver: mpsc::Receiver<u64>,
|
||||||
@@ -162,8 +162,6 @@ pub trait ApplicationHandler {
|
|||||||
///
|
///
|
||||||
/// let (sender, receiver) = mpsc::channel();
|
/// let (sender, receiver) = mpsc::channel();
|
||||||
///
|
///
|
||||||
/// let mut app = MyApp { receiver };
|
|
||||||
///
|
|
||||||
/// // Send an event in a loop
|
/// // Send an event in a loop
|
||||||
/// let proxy = event_loop.create_proxy();
|
/// let proxy = event_loop.create_proxy();
|
||||||
/// let background_thread = thread::spawn(move || {
|
/// let background_thread = thread::spawn(move || {
|
||||||
@@ -171,7 +169,7 @@ pub trait ApplicationHandler {
|
|||||||
/// loop {
|
/// loop {
|
||||||
/// println!("sending: {i}");
|
/// println!("sending: {i}");
|
||||||
/// if sender.send(i).is_err() {
|
/// if sender.send(i).is_err() {
|
||||||
/// // Stop sending once `MyApp` is dropped
|
/// // Stop sending once the receiver is dropped
|
||||||
/// break;
|
/// break;
|
||||||
/// }
|
/// }
|
||||||
/// // Trigger the wake-up _after_ we placed the event in the channel.
|
/// // Trigger the wake-up _after_ we placed the event in the channel.
|
||||||
@@ -182,9 +180,8 @@ pub trait ApplicationHandler {
|
|||||||
/// }
|
/// }
|
||||||
/// });
|
/// });
|
||||||
///
|
///
|
||||||
/// event_loop.run_app(&mut app)?;
|
/// event_loop.run_app(MyApp { receiver })?;
|
||||||
///
|
///
|
||||||
/// drop(app);
|
|
||||||
/// background_thread.join().unwrap();
|
/// background_thread.join().unwrap();
|
||||||
///
|
///
|
||||||
/// Ok(())
|
/// Ok(())
|
||||||
@@ -203,6 +200,8 @@ pub trait ApplicationHandler {
|
|||||||
);
|
);
|
||||||
|
|
||||||
/// Emitted when the OS sends an event to a device.
|
/// Emitted when the OS sends an event to a device.
|
||||||
|
///
|
||||||
|
/// Whether device events are delivered depends on the backend in use.
|
||||||
fn device_event(
|
fn device_event(
|
||||||
&mut self,
|
&mut self,
|
||||||
event_loop: &dyn ActiveEventLoop,
|
event_loop: &dyn ActiveEventLoop,
|
||||||
@@ -258,7 +257,7 @@ pub trait ApplicationHandler {
|
|||||||
/// to the user. This is a good place to stop refreshing UI, running animations and other visual
|
/// to the user. This is a good place to stop refreshing UI, running animations and other visual
|
||||||
/// things. It is driven by Android's [`onStop()`] method.
|
/// things. It is driven by Android's [`onStop()`] method.
|
||||||
///
|
///
|
||||||
/// After this event the application either receives [`resumed()`] again, or [`exiting()`].
|
/// After this event the application either receives [`resumed()`] again, or will exit.
|
||||||
///
|
///
|
||||||
/// [`onStop()`]: https://developer.android.com/reference/android/app/Activity#onStop()
|
/// [`onStop()`]: https://developer.android.com/reference/android/app/Activity#onStop()
|
||||||
///
|
///
|
||||||
@@ -268,7 +267,6 @@ pub trait ApplicationHandler {
|
|||||||
///
|
///
|
||||||
/// [`resumed()`]: Self::resumed()
|
/// [`resumed()`]: Self::resumed()
|
||||||
/// [`suspended()`]: Self::suspended()
|
/// [`suspended()`]: Self::suspended()
|
||||||
/// [`exiting()`]: Self::exiting()
|
|
||||||
fn suspended(&mut self, event_loop: &dyn ActiveEventLoop) {
|
fn suspended(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
let _ = event_loop;
|
let _ = event_loop;
|
||||||
}
|
}
|
||||||
@@ -310,14 +308,6 @@ pub trait ApplicationHandler {
|
|||||||
let _ = event_loop;
|
let _ = event_loop;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Emitted when the event loop is being shut down.
|
|
||||||
///
|
|
||||||
/// This is irreversible - if this method is called, it is guaranteed that the event loop
|
|
||||||
/// will exit right after.
|
|
||||||
fn exiting(&mut self, event_loop: &dyn ActiveEventLoop) {
|
|
||||||
let _ = event_loop;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Emitted when the application has received a memory warning.
|
/// Emitted when the application has received a memory warning.
|
||||||
///
|
///
|
||||||
/// ## Platform-specific
|
/// ## Platform-specific
|
||||||
@@ -349,9 +339,8 @@ pub trait ApplicationHandler {
|
|||||||
/// The macOS-specific handler.
|
/// The macOS-specific handler.
|
||||||
///
|
///
|
||||||
/// The return value from this should not change at runtime.
|
/// The return value from this should not change at runtime.
|
||||||
#[cfg(any(docsrs, macos_platform))]
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn macos_handler(&mut self) -> Option<&mut dyn ApplicationHandlerExtMacOS> {
|
fn macos_handler(&mut self) -> Option<&mut dyn macos::ApplicationHandlerExtMacOS> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -413,19 +402,13 @@ impl<A: ?Sized + ApplicationHandler> ApplicationHandler for &mut A {
|
|||||||
(**self).destroy_surfaces(event_loop);
|
(**self).destroy_surfaces(event_loop);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn exiting(&mut self, event_loop: &dyn ActiveEventLoop) {
|
|
||||||
(**self).exiting(event_loop);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn memory_warning(&mut self, event_loop: &dyn ActiveEventLoop) {
|
fn memory_warning(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
(**self).memory_warning(event_loop);
|
(**self).memory_warning(event_loop);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(docsrs, macos_platform))]
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn macos_handler(&mut self) -> Option<&mut dyn ApplicationHandlerExtMacOS> {
|
fn macos_handler(&mut self) -> Option<&mut dyn macos::ApplicationHandlerExtMacOS> {
|
||||||
(**self).macos_handler()
|
(**self).macos_handler()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -487,19 +470,13 @@ impl<A: ?Sized + ApplicationHandler> ApplicationHandler for Box<A> {
|
|||||||
(**self).destroy_surfaces(event_loop);
|
(**self).destroy_surfaces(event_loop);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn exiting(&mut self, event_loop: &dyn ActiveEventLoop) {
|
|
||||||
(**self).exiting(event_loop);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn memory_warning(&mut self, event_loop: &dyn ActiveEventLoop) {
|
fn memory_warning(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
(**self).memory_warning(event_loop);
|
(**self).memory_warning(event_loop);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(docsrs, macos_platform))]
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn macos_handler(&mut self) -> Option<&mut dyn ApplicationHandlerExtMacOS> {
|
fn macos_handler(&mut self) -> Option<&mut dyn macos::ApplicationHandlerExtMacOS> {
|
||||||
(**self).macos_handler()
|
(**self).macos_handler()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
92
winit-core/src/as_any.rs
Normal file
92
winit-core/src/as_any.rs
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
use std::any::Any;
|
||||||
|
|
||||||
|
// NOTE: This is `pub`, but isn't actually exposed outside the crate.
|
||||||
|
// NOTE: Marked as `#[doc(hidden)]` and underscored, because they can be quite difficult to use
|
||||||
|
// correctly, see discussion in #4160.
|
||||||
|
// FIXME: Remove and replace with a coercion once rust-lang/rust#65991 is in MSRV (1.86).
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub trait AsAny: Any {
|
||||||
|
#[doc(hidden)]
|
||||||
|
fn __as_any(&self) -> &dyn Any;
|
||||||
|
#[doc(hidden)]
|
||||||
|
fn __as_any_mut(&mut self) -> &mut dyn Any;
|
||||||
|
#[doc(hidden)]
|
||||||
|
fn __into_any(self: Box<Self>) -> Box<dyn Any>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Any> AsAny for T {
|
||||||
|
#[inline(always)]
|
||||||
|
fn __as_any(&self) -> &dyn Any {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline(always)]
|
||||||
|
fn __as_any_mut(&mut self) -> &mut dyn Any {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline(always)]
|
||||||
|
fn __into_any(self: Box<Self>) -> Box<dyn Any> {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! impl_dyn_casting {
|
||||||
|
($trait:ident) => {
|
||||||
|
impl dyn $trait + '_ {
|
||||||
|
/// Downcast to the backend concrete type.
|
||||||
|
///
|
||||||
|
/// Returns `None` if the object was not from that backend.
|
||||||
|
pub fn cast_ref<T: $trait>(&self) -> Option<&T> {
|
||||||
|
let this: &dyn std::any::Any = self.__as_any();
|
||||||
|
this.downcast_ref::<T>()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mutable downcast to the backend concrete type.
|
||||||
|
///
|
||||||
|
/// Returns `None` if the object was not from that backend.
|
||||||
|
pub fn cast_mut<T: $trait>(&mut self) -> Option<&mut T> {
|
||||||
|
let this: &mut dyn std::any::Any = self.__as_any_mut();
|
||||||
|
this.downcast_mut::<T>()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Owned downcast to the backend concrete type.
|
||||||
|
///
|
||||||
|
/// Returns `Err` with `self` if the object was not from that backend.
|
||||||
|
pub fn cast<T: $trait>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
|
||||||
|
if self.cast_ref::<T>().is_some() {
|
||||||
|
let this: Box<dyn std::any::Any> = self.__into_any();
|
||||||
|
// Unwrap is okay, we just checked the type of `self` is `T`.
|
||||||
|
Ok(this.downcast::<T>().unwrap())
|
||||||
|
} else {
|
||||||
|
Err(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub use impl_dyn_casting;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::AsAny;
|
||||||
|
|
||||||
|
struct Foo;
|
||||||
|
trait FooTrait: AsAny {}
|
||||||
|
impl FooTrait for Foo {}
|
||||||
|
impl_dyn_casting!(FooTrait);
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dyn_casting() {
|
||||||
|
let foo_owned: Box<dyn FooTrait> = Box::new(Foo);
|
||||||
|
assert!(foo_owned.cast::<Foo>().is_ok());
|
||||||
|
|
||||||
|
let mut foo = Foo;
|
||||||
|
let foo_ref: &mut dyn FooTrait = &mut foo;
|
||||||
|
assert!((foo_ref).cast_ref::<Foo>().is_some());
|
||||||
|
assert!((&&&&foo_ref).cast_ref::<Foo>().is_some());
|
||||||
|
assert!(foo_ref.cast_mut::<Foo>().is_some());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,16 @@
|
|||||||
use core::fmt;
|
use core::fmt;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::hash::{Hash, Hasher};
|
use std::hash::Hash;
|
||||||
|
use std::ops::Deref;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
use cursor_icon::CursorIcon;
|
#[doc(inline)]
|
||||||
|
pub use cursor_icon::CursorIcon;
|
||||||
|
|
||||||
use crate::platform_impl::{PlatformCustomCursor, PlatformCustomCursorSource};
|
use crate::as_any::{impl_dyn_casting, AsAny};
|
||||||
|
|
||||||
/// The maximum width and height for a cursor when using [`CustomCursor::from_rgba`].
|
/// The maximum width and height for a cursor when using [`CustomCursorSource::from_rgba`].
|
||||||
pub const MAX_CURSOR_SIZE: u16 = 2048;
|
pub const MAX_CURSOR_SIZE: u16 = 2048;
|
||||||
|
|
||||||
const PIXEL_SIZE: usize = 4;
|
const PIXEL_SIZE: usize = 4;
|
||||||
@@ -48,22 +51,23 @@ impl From<CustomCursor> for Cursor {
|
|||||||
/// # Example
|
/// # Example
|
||||||
///
|
///
|
||||||
/// ```no_run
|
/// ```no_run
|
||||||
/// # use winit::event_loop::ActiveEventLoop;
|
/// # use winit_core::event_loop::ActiveEventLoop;
|
||||||
/// # use winit::window::Window;
|
/// # use winit_core::window::Window;
|
||||||
/// # fn scope(event_loop: &dyn ActiveEventLoop, window: &dyn Window) {
|
/// # fn scope(event_loop: &dyn ActiveEventLoop, window: &dyn Window) {
|
||||||
/// use winit::window::CustomCursor;
|
/// use winit_core::cursor::CustomCursorSource;
|
||||||
///
|
///
|
||||||
/// let w = 10;
|
/// let w = 10;
|
||||||
/// let h = 10;
|
/// let h = 10;
|
||||||
/// let rgba = vec![255; (w * h * 4) as usize];
|
/// let rgba = vec![255; (w * h * 4) as usize];
|
||||||
///
|
///
|
||||||
/// #[cfg(not(target_family = "wasm"))]
|
/// #[cfg(not(target_family = "wasm"))]
|
||||||
/// let source = CustomCursor::from_rgba(rgba, w, h, w / 2, h / 2).unwrap();
|
/// let source = CustomCursorSource::from_rgba(rgba, w, h, w / 2, h / 2).unwrap();
|
||||||
///
|
///
|
||||||
/// #[cfg(target_family = "wasm")]
|
/// #[cfg(target_family = "wasm")]
|
||||||
/// let source = {
|
/// let source = CustomCursorSource::Url {
|
||||||
/// use winit::platform::web::CustomCursorExtWeb;
|
/// url: String::from("http://localhost:3000/cursor.png"),
|
||||||
/// CustomCursor::from_url(String::from("http://localhost:3000/cursor.png"), 0, 0)
|
/// hotspot_x: 0,
|
||||||
|
/// hotspot_y: 0,
|
||||||
/// };
|
/// };
|
||||||
///
|
///
|
||||||
/// if let Ok(custom_cursor) = event_loop.create_custom_cursor(source) {
|
/// if let Ok(custom_cursor) = event_loop.create_custom_cursor(source) {
|
||||||
@@ -71,50 +75,96 @@ impl From<CustomCursor> for Cursor {
|
|||||||
/// }
|
/// }
|
||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct CustomCursor {
|
pub struct CustomCursor(pub Arc<dyn CustomCursorProvider>);
|
||||||
/// Platforms should make sure this is cheap to clone.
|
|
||||||
pub(crate) inner: PlatformCustomCursor,
|
pub trait CustomCursorProvider: AsAny + fmt::Debug + Send + Sync {
|
||||||
|
/// Whether a cursor was backed by animation.
|
||||||
|
fn is_animated(&self) -> bool;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CustomCursor {
|
impl PartialEq for CustomCursor {
|
||||||
/// Creates a new cursor from an rgba buffer.
|
fn eq(&self, other: &Self) -> bool {
|
||||||
///
|
Arc::ptr_eq(&self.0, &other.0)
|
||||||
/// The alpha channel is assumed to be **not** premultiplied.
|
|
||||||
pub fn from_rgba(
|
|
||||||
rgba: impl Into<Vec<u8>>,
|
|
||||||
width: u16,
|
|
||||||
height: u16,
|
|
||||||
hotspot_x: u16,
|
|
||||||
hotspot_y: u16,
|
|
||||||
) -> Result<CustomCursorSource, BadImage> {
|
|
||||||
let _span =
|
|
||||||
tracing::debug_span!("winit::Cursor::from_rgba", width, height, hotspot_x, hotspot_y)
|
|
||||||
.entered();
|
|
||||||
|
|
||||||
Ok(CustomCursorSource {
|
|
||||||
inner: PlatformCustomCursorSource::from_rgba(
|
|
||||||
rgba.into(),
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
hotspot_x,
|
|
||||||
hotspot_y,
|
|
||||||
)?,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Eq for CustomCursor {}
|
||||||
|
|
||||||
|
impl Hash for CustomCursor {
|
||||||
|
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||||
|
Arc::as_ptr(&self.0).hash(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deref for CustomCursor {
|
||||||
|
type Target = dyn CustomCursorProvider;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
self.0.deref()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl_dyn_casting!(CustomCursorProvider);
|
||||||
|
|
||||||
/// Source for [`CustomCursor`].
|
/// Source for [`CustomCursor`].
|
||||||
///
|
///
|
||||||
/// See [`CustomCursor`] for more details.
|
/// See [`CustomCursor`] for more details.
|
||||||
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
||||||
pub struct CustomCursorSource {
|
pub enum CustomCursorSource {
|
||||||
// Some platforms don't support custom cursors.
|
/// Cursor that is backed by RGBA image.
|
||||||
#[allow(dead_code)]
|
///
|
||||||
pub(crate) inner: PlatformCustomCursorSource,
|
/// See [CustomCursorSource::from_rgba] for more.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **iOS / Android / Orbital:** Unsupported
|
||||||
|
Image(CursorImage),
|
||||||
|
/// Animated cursor.
|
||||||
|
///
|
||||||
|
/// See [CustomCursorSource::from_animation] for more.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **iOS / Android / Wayland / Windows / X11 / macOS / Orbital:** Unsupported
|
||||||
|
Animation(CursorAnimation),
|
||||||
|
/// Creates a new cursor from a URL pointing to an image.
|
||||||
|
/// It uses the [url css function](https://developer.mozilla.org/en-US/docs/Web/CSS/url),
|
||||||
|
/// but browser support for image formats is inconsistent. Using [PNG] is recommended.
|
||||||
|
///
|
||||||
|
/// [PNG]: https://en.wikipedia.org/wiki/PNG
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **iOS / Android / Wayland / Windows / X11 / macOS / Orbital:** Unsupported
|
||||||
|
Url { hotspot_x: u16, hotspot_y: u16, url: String },
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An error produced when using [`CustomCursor::from_rgba`] with invalid arguments.
|
impl CustomCursorSource {
|
||||||
|
/// Creates a new cursor from an rgba buffer.
|
||||||
|
///
|
||||||
|
/// The alpha channel is assumed to be **not** premultiplied.
|
||||||
|
pub fn from_rgba(
|
||||||
|
rgba: Vec<u8>,
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
hotspot_x: u16,
|
||||||
|
hotspot_y: u16,
|
||||||
|
) -> Result<Self, BadImage> {
|
||||||
|
CursorImage::from_rgba(rgba, width, height, hotspot_x, hotspot_y).map(Self::Image)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Crates a new animated cursor from multiple [`CustomCursor`]s
|
||||||
|
/// Supplied `cursors` can't be empty or other animations.
|
||||||
|
pub fn from_animation(
|
||||||
|
duration: Duration,
|
||||||
|
cursors: Vec<CustomCursor>,
|
||||||
|
) -> Result<Self, BadAnimation> {
|
||||||
|
CursorAnimation::new(duration, cursors).map(Self::Animation)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An error produced when using [`CustomCursorSource::from_rgba`] with invalid arguments.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
pub enum BadImage {
|
pub enum BadImage {
|
||||||
@@ -164,47 +214,29 @@ impl fmt::Display for BadImage {
|
|||||||
|
|
||||||
impl Error for BadImage {}
|
impl Error for BadImage {}
|
||||||
|
|
||||||
/// Platforms export this directly as `PlatformCustomCursorSource` if they need to only work with
|
/// An error produced when using [`CustomCursorSource::from_animation`] with invalid arguments.
|
||||||
/// images.
|
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||||
#[allow(dead_code)]
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
pub enum BadAnimation {
|
||||||
pub(crate) struct OnlyCursorImageSource(pub(crate) CursorImage);
|
/// Produced when no cursors were supplied.
|
||||||
|
Empty,
|
||||||
|
/// Produced when a supplied cursor is an animation.
|
||||||
|
Animation,
|
||||||
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
impl fmt::Display for BadAnimation {
|
||||||
impl OnlyCursorImageSource {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
pub(crate) fn from_rgba(
|
match self {
|
||||||
rgba: Vec<u8>,
|
Self::Empty => write!(f, "No cursors supplied"),
|
||||||
width: u16,
|
Self::Animation => write!(f, "A supplied cursor is an animation"),
|
||||||
height: u16,
|
}
|
||||||
hotspot_x: u16,
|
|
||||||
hotspot_y: u16,
|
|
||||||
) -> Result<Self, BadImage> {
|
|
||||||
CursorImage::from_rgba(rgba, width, height, hotspot_x, hotspot_y).map(Self)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Platforms export this directly as `PlatformCustomCursor` if they don't implement caching.
|
impl Error for BadAnimation {}
|
||||||
#[allow(dead_code)]
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub(crate) struct OnlyCursorImage(pub(crate) Arc<CursorImage>);
|
|
||||||
|
|
||||||
impl Hash for OnlyCursorImage {
|
|
||||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
|
||||||
Arc::as_ptr(&self.0).hash(state);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PartialEq for OnlyCursorImage {
|
|
||||||
fn eq(&self, other: &Self) -> bool {
|
|
||||||
Arc::ptr_eq(&self.0, &other.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Eq for OnlyCursorImage {}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
||||||
#[allow(dead_code)]
|
pub struct CursorImage {
|
||||||
pub(crate) struct CursorImage {
|
|
||||||
pub(crate) rgba: Vec<u8>,
|
pub(crate) rgba: Vec<u8>,
|
||||||
pub(crate) width: u16,
|
pub(crate) width: u16,
|
||||||
pub(crate) height: u16,
|
pub(crate) height: u16,
|
||||||
@@ -245,22 +277,60 @@ impl CursorImage {
|
|||||||
|
|
||||||
Ok(CursorImage { rgba, width, height, hotspot_x, hotspot_y })
|
Ok(CursorImage { rgba, width, height, hotspot_x, hotspot_y })
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Platforms that don't support cursors will export this as `PlatformCustomCursor`.
|
pub fn buffer(&self) -> &[u8] {
|
||||||
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
|
self.rgba.as_slice()
|
||||||
pub(crate) struct NoCustomCursor;
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
pub fn buffer_mut(&mut self) -> &mut [u8] {
|
||||||
impl NoCustomCursor {
|
self.rgba.as_mut_slice()
|
||||||
pub(crate) fn from_rgba(
|
}
|
||||||
rgba: Vec<u8>,
|
|
||||||
width: u16,
|
pub fn width(&self) -> u16 {
|
||||||
height: u16,
|
self.width
|
||||||
hotspot_x: u16,
|
}
|
||||||
hotspot_y: u16,
|
|
||||||
) -> Result<Self, BadImage> {
|
pub fn height(&self) -> u16 {
|
||||||
CursorImage::from_rgba(rgba, width, height, hotspot_x, hotspot_y)?;
|
self.height
|
||||||
Ok(Self)
|
}
|
||||||
|
|
||||||
|
pub fn hotspot_x(&self) -> u16 {
|
||||||
|
self.hotspot_x
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hotspot_y(&self) -> u16 {
|
||||||
|
self.hotspot_y
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub struct CursorAnimation {
|
||||||
|
pub(crate) duration: Duration,
|
||||||
|
pub(crate) cursors: Vec<CustomCursor>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CursorAnimation {
|
||||||
|
pub fn new(duration: Duration, cursors: Vec<CustomCursor>) -> Result<Self, BadAnimation> {
|
||||||
|
if cursors.is_empty() {
|
||||||
|
return Err(BadAnimation::Empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
if cursors.iter().any(|cursor| cursor.is_animated()) {
|
||||||
|
return Err(BadAnimation::Animation);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self { duration, cursors })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn duration(&self) -> Duration {
|
||||||
|
self.duration
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cursors(&self) -> &[CustomCursor] {
|
||||||
|
self.cursors.as_slice()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn into_raw(self) -> (Duration, Vec<CustomCursor>) {
|
||||||
|
(self.duration, self.cursors)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user