mirror of
https://github.com/rust-windowing/winit.git
synced 2026-06-26 22:53:15 -04:00
Compare commits
346 Commits
v0.30.8
...
v0.31.0-be
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f98ccf8efc | ||
|
|
b961e8e941 | ||
|
|
4c5bf0ee08 | ||
|
|
f69b601abb | ||
|
|
e8bccfff4f | ||
|
|
0a59e4b905 | ||
|
|
d837c88855 | ||
|
|
82eab465e0 | ||
|
|
a9c189a423 | ||
|
|
9d9d21cfdb | ||
|
|
779f52a21f | ||
|
|
7a21858d29 | ||
|
|
a3f7e6566a | ||
|
|
f41897cfa4 | ||
|
|
bd6fef1d80 | ||
|
|
42d256e926 | ||
|
|
03dad26c43 | ||
|
|
1e7ab0cd25 | ||
|
|
c333003514 | ||
|
|
10f21090ce | ||
|
|
5575f51483 | ||
|
|
2ede84ab2f | ||
|
|
f046e778aa | ||
|
|
ffcdf80192 | ||
|
|
b811e9d878 | ||
|
|
d815bc089c | ||
|
|
66283a79bd | ||
|
|
3be30affe4 | ||
|
|
a68f1a664b | ||
|
|
6de5041a94 | ||
|
|
014fb68a26 | ||
|
|
9a03dacbde | ||
|
|
4d9302b33c | ||
|
|
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 | ||
|
|
e47081e385 | ||
|
|
171d53c042 | ||
|
|
35379f305a | ||
|
|
4d2a0dd2b3 | ||
|
|
4a8b659228 | ||
|
|
f314cd2b9a | ||
|
|
3657506f6e | ||
|
|
edca3ebc41 | ||
|
|
ca46e29203 | ||
|
|
132fbe14d5 | ||
|
|
164bf85b5b | ||
|
|
cfa8f027cc | ||
|
|
2e5db75101 | ||
|
|
19e5bee3d1 | ||
|
|
fc6cf89ac0 | ||
|
|
dbcdb6f1b4 | ||
|
|
d0c6c34eaa | ||
|
|
f2688d94ea | ||
|
|
f6b20852bf | ||
|
|
59b1eb5410 | ||
|
|
f781e13166 | ||
|
|
9f8ac8feb5 | ||
|
|
74958ecc6f | ||
|
|
3a60cbaba5 | ||
|
|
ae4c449670 | ||
|
|
b2896d7408 | ||
|
|
edfb4b03f4 | ||
|
|
c8c1eca3c7 | ||
|
|
d3207a8d76 | ||
|
|
9d347b72d9 | ||
|
|
13bb51c7e0 | ||
|
|
bb4aa22cf9 | ||
|
|
3e9b80d47a | ||
|
|
c913cdab0b | ||
|
|
a5f5ce6a3d | ||
|
|
fb6b1d487b | ||
|
|
7d77ccfad3 | ||
|
|
c23bed20b8 | ||
|
|
8fe2b62adf | ||
|
|
4e3165f3d8 | ||
|
|
da2268ae22 | ||
|
|
eccd9e415d | ||
|
|
32cd1ad9a7 | ||
|
|
6e1b9fa24d | ||
|
|
380eea0072 | ||
|
|
a18658284c | ||
|
|
8ddd10a7f9 | ||
|
|
4f1c5b6129 | ||
|
|
7e819bb2ce | ||
|
|
dfea49f488 | ||
|
|
b674d20edf | ||
|
|
8db3e0e043 | ||
|
|
d37c591378 | ||
|
|
9419e4e1a7 | ||
|
|
241b7a80bb | ||
|
|
e716adcc0a | ||
|
|
aee95114db | ||
|
|
8f4a8efa99 | ||
|
|
1e1f0fd7e9 | ||
|
|
6e008b39e9 | ||
|
|
6c4da19197 | ||
|
|
a61e7bb4f4 | ||
|
|
7fbc2118b6 | ||
|
|
a96491f302 | ||
|
|
d96fd02f33 | ||
|
|
92e9bfe0fc | ||
|
|
3392e9c1de | ||
|
|
038ef5c3ad | ||
|
|
70c54ee0ff | ||
|
|
3bab4ef4fb | ||
|
|
58142680ce | ||
|
|
0ffcfd8a3a | ||
|
|
2e53533cc1 | ||
|
|
1168cd4113 | ||
|
|
9dff801f93 | ||
|
|
f07153b8e0 | ||
|
|
f5304815a1 | ||
|
|
29e1041987 | ||
|
|
15b79b18e1 | ||
|
|
54ff9c3bb5 | ||
|
|
546962c904 | ||
|
|
b7a7f59298 | ||
|
|
586255ac0a | ||
|
|
42ba0a74e0 | ||
|
|
34a37b8747 | ||
|
|
02a0a91a94 | ||
|
|
e3fbfb81d7 | ||
|
|
0909bf3d9d | ||
|
|
3398ebe467 | ||
|
|
21c121f9b3 | ||
|
|
ce0d1dfe1b | ||
|
|
7892e86731 | ||
|
|
7b0104b54c | ||
|
|
facb809f12 | ||
|
|
4e2e764e4a | ||
|
|
a0bc3e5dc8 | ||
|
|
2e97ab3d4f | ||
|
|
ef580b817d | ||
|
|
5ec934b1b0 | ||
|
|
c9c260ca08 | ||
|
|
b6109d4a17 | ||
|
|
eef2848c98 | ||
|
|
73c01fff96 | ||
|
|
88bbdb33da | ||
|
|
652ff7576c | ||
|
|
d741c58ac3 | ||
|
|
944ab60eda | ||
|
|
8e23d1608a | ||
|
|
dc99920612 | ||
|
|
ee3ab33a7c | ||
|
|
5b8f5cb54a | ||
|
|
bf97def398 | ||
|
|
d5fd8682eb | ||
|
|
39a7d5b738 | ||
|
|
2665c12098 | ||
|
|
936da131c2 | ||
|
|
850dd97177 | ||
|
|
1170554dbd | ||
|
|
75ce71f05a | ||
|
|
a0d69c782a | ||
|
|
2e93e48a3b | ||
|
|
82d9bbe559 | ||
|
|
8bdd4d620e | ||
|
|
9d5412ffe1 | ||
|
|
ecb887e5c3 | ||
|
|
7d1287958f | ||
|
|
c0c14aaf00 | ||
|
|
10dc0674bb | ||
|
|
4f59796e8a | ||
|
|
32097d75c7 | ||
|
|
c6c4395c3b | ||
|
|
38e6f9ad84 | ||
|
|
3e6092b8ed | ||
|
|
b4e83a5966 | ||
|
|
db2c97a995 | ||
|
|
1552eb21f7 | ||
|
|
d8ffd4bb26 | ||
|
|
34c15608e0 | ||
|
|
eef6977f45 | ||
|
|
078b46720b | ||
|
|
3b4e064a07 | ||
|
|
39bc139500 | ||
|
|
9522670081 | ||
|
|
9a1ef49dc3 | ||
|
|
3a624e0f52 | ||
|
|
279e3edc54 | ||
|
|
0e74d37ff5 | ||
|
|
2d1382f7d6 | ||
|
|
5d8091fc7f | ||
|
|
d7abe0316e | ||
|
|
5ea20fc905 | ||
|
|
e108fa2fbf | ||
|
|
fff6788c12 | ||
|
|
3e8fa41073 | ||
|
|
2b1c8cea1b | ||
|
|
ab33fb8eda | ||
|
|
b0b64a9a15 | ||
|
|
d5d202d60e | ||
|
|
cb39ab29f4 | ||
|
|
0a3cacd577 | ||
|
|
16fd2baba0 | ||
|
|
7f8771a362 | ||
|
|
337d50779c | ||
|
|
fd477986de | ||
|
|
94664ff687 | ||
|
|
0fc8c37721 | ||
|
|
ec29c81ad2 | ||
|
|
304a585493 |
@@ -2,5 +2,8 @@
|
||||
#
|
||||
# Note that these flags are (intentionally) not included when building from the downloaded crate.
|
||||
[build]
|
||||
rustflags = ["--cfg=unreleased_changelogs"]
|
||||
rustdocflags = ["--cfg=unreleased_changelogs"]
|
||||
rustflags = ["--cfg=unreleased_changelogs"]
|
||||
|
||||
[target.wasm32-unknown-unknown]
|
||||
runner = "wasm-bindgen-test-runner"
|
||||
|
||||
@@ -2,3 +2,7 @@
|
||||
|
||||
# chore(rustfmt): use nightly
|
||||
7b0c7b6cb2c62767ca0c73c857b299883f55a883
|
||||
# Rustfmt: use `group_imports`
|
||||
2665c120981af548433645c6383b3580dd8f8fc4
|
||||
# Use Taplo for TOML formatting
|
||||
3398ebe467c43ccfd91916c5b81ff3c68f598556
|
||||
|
||||
36
.github/CODEOWNERS
vendored
36
.github/CODEOWNERS
vendored
@@ -1,34 +1,26 @@
|
||||
# Android
|
||||
/src/platform/android.rs @MarijnS95
|
||||
/src/platform_impl/android @MarijnS95
|
||||
/winit-android @MarijnS95
|
||||
|
||||
# iOS
|
||||
/src/platform/ios.rs @madsmtm
|
||||
/src/platform_impl/ios @madsmtm
|
||||
# Apple (AppKit + UIKit)
|
||||
/winit-appkit @madsmtm
|
||||
/winit-uikit @madsmtm
|
||||
/winit-common/src/core_foundation @madsmtm
|
||||
/winit-common/src/event_handler.rs @madsmtm
|
||||
|
||||
# Unix
|
||||
/src/platform_impl/linux/mod.rs @kchibisov
|
||||
# XKB
|
||||
/winit-common/src/xkb @kchibisov
|
||||
|
||||
# Wayland
|
||||
/src/platform/wayland.rs @kchibisov
|
||||
/src/platform_impl/linux/wayland @kchibisov
|
||||
/winit-wayland @kchibisov
|
||||
|
||||
# X11
|
||||
/src/platform/x11.rs @kchibisov @notgull
|
||||
/src/platform_impl/linux/x11 @kchibisov @notgull
|
||||
|
||||
# macOS
|
||||
/src/platform/macos.rs @madsmtm
|
||||
/src/platform_impl/macos @madsmtm
|
||||
/winit-x11 @kchibisov
|
||||
|
||||
# Web
|
||||
/src/platform/web.rs @daxpedda
|
||||
/src/platform_impl/web @daxpedda
|
||||
/winit-web @daxpedda
|
||||
|
||||
# Windows
|
||||
/src/platform/windows.rs @notgull
|
||||
/src/platform_impl/windows @notgull
|
||||
# Windows (Win32) (UNOWNED)
|
||||
#/winit-win32
|
||||
|
||||
# Orbital (Redox OS)
|
||||
/src/platform/orbital.rs @jackpot51
|
||||
/src/platform_impl/orbital @jackpot51
|
||||
/winit-orbital @jackpot51
|
||||
|
||||
2
.github/ISSUE_TEMPLATE/bug_web.yml
vendored
2
.github/ISSUE_TEMPLATE/bug_web.yml
vendored
@@ -1,5 +1,5 @@
|
||||
name: Web bug
|
||||
description: Create a web-specific bug report
|
||||
description: Create a Web-specific bug report
|
||||
labels:
|
||||
- B - bug
|
||||
- DS - web
|
||||
|
||||
1
.github/PULL_REQUEST_TEMPLATE.md
vendored
1
.github/PULL_REQUEST_TEMPLATE.md
vendored
@@ -2,4 +2,3 @@
|
||||
- [ ] Added an entry to the `changelog` module if knowledge of this change could be valuable to users
|
||||
- [ ] Updated documentation to reflect any user-facing changes, including notes of platform-specific behavior
|
||||
- [ ] Created or updated an example program if it would help users understand this functionality
|
||||
- [ ] Updated [feature matrix](https://github.com/rust-windowing/winit/blob/master/FEATURES.md), if new features were added or implemented
|
||||
|
||||
22
.github/dependabot.yaml
vendored
Normal file
22
.github/dependabot.yaml
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
version: 2
|
||||
|
||||
updates:
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: daily
|
||||
groups:
|
||||
github-actions:
|
||||
patterns:
|
||||
- "*"
|
||||
|
||||
- package-ecosystem: npm
|
||||
directory: src/platform_impl/web/script
|
||||
schedule:
|
||||
interval: daily
|
||||
groups:
|
||||
github-actions:
|
||||
patterns:
|
||||
- '*'
|
||||
labels:
|
||||
- "DS - web"
|
||||
174
.github/workflows/ci.yml
vendored
174
.github/workflows/ci.yml
vendored
@@ -17,6 +17,19 @@ jobs:
|
||||
- name: Check Formatting
|
||||
run: cargo fmt -- --check
|
||||
|
||||
taplo:
|
||||
name: Taplo
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: taiki-e/checkout-action@v1
|
||||
- name: Install Taplo
|
||||
uses: taiki-e/install-action@v2
|
||||
with:
|
||||
tool: taplo-cli
|
||||
- name: Run Taplo
|
||||
run: taplo fmt --check
|
||||
|
||||
typos:
|
||||
name: Check for typos
|
||||
runs-on: ubuntu-latest
|
||||
@@ -42,7 +55,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
toolchain: [stable, nightly, '1.70.0']
|
||||
toolchain: [stable, nightly, '1.85']
|
||||
platform:
|
||||
# Note: Make sure that we test all the `docs.rs` targets defined in Cargo.toml!
|
||||
- { name: 'Windows 64bit MSVC', target: x86_64-pc-windows-msvc, os: windows-latest, }
|
||||
@@ -53,27 +66,41 @@ jobs:
|
||||
- { 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: '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: 'macOS', 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: 'iOS x86_64', target: x86_64-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:
|
||||
# Web on nightly needs extra arguments
|
||||
|
||||
- toolchain: nightly
|
||||
platform: { name: 'Web' }
|
||||
# Rustup is broken.
|
||||
- toolchain: nightly
|
||||
platform: { name: 'Windows 32bit GNU' }
|
||||
# Android is tested on stable-3
|
||||
- toolchain: '1.70.0'
|
||||
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
||||
- toolchain: '1.85'
|
||||
platform: { name: 'Android' }
|
||||
# Redox OS doesn't follow MSRV
|
||||
- toolchain: '1.85'
|
||||
platform: { name: 'Redox OS' }
|
||||
include:
|
||||
- toolchain: '1.70.0'
|
||||
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
||||
- toolchain: '1.85'
|
||||
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package winit --features=android-native-activity', cmd: 'apk -- ' }
|
||||
- toolchain: 'nightly'
|
||||
platform: { name: 'Web', target: wasm32-unknown-unknown, os: ubuntu-latest, test-options: -Zdoctest-xcompile }
|
||||
- toolchain: 'nightly'
|
||||
platform: {
|
||||
name: 'web Atomic',
|
||||
target: wasm32-unknown-unknown,
|
||||
os: ubuntu-latest,
|
||||
options: '-Zbuild-std=panic_abort,std',
|
||||
rustflags: '-Ctarget-feature=+atomics,+bulk-memory',
|
||||
components: rust-src,
|
||||
name: 'Web Atomic',
|
||||
target: wasm32-unknown-unknown,
|
||||
os: ubuntu-latest,
|
||||
options: '-Zbuild-std=panic_abort,std',
|
||||
test-options: -Zdoctest-xcompile,
|
||||
rustflags: '-Ctarget-feature=+atomics,+bulk-memory',
|
||||
components: rust-src,
|
||||
}
|
||||
|
||||
env:
|
||||
@@ -83,8 +110,10 @@ jobs:
|
||||
|
||||
# Faster compilation and error on warnings
|
||||
RUSTFLAGS: '--codegen=debuginfo=0 --deny=warnings ${{ matrix.platform.rustflags }}'
|
||||
RUSTDOCFLAGS: ${{ matrix.platform.rustflags }}
|
||||
|
||||
OPTIONS: --target=${{ matrix.platform.target }} ${{ matrix.platform.options }}
|
||||
TEST_OPTIONS: ${{ matrix.platform.test-options }}
|
||||
CMD: ${{ matrix.platform.cmd }}
|
||||
|
||||
steps:
|
||||
@@ -95,7 +124,7 @@ jobs:
|
||||
# the cache has been downloaded.
|
||||
#
|
||||
# This could be avoided if we added Cargo.lock to the repository.
|
||||
uses: actions/cache/restore@v3
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
# https://doc.rust-lang.org/cargo/guide/cargo-home.html#caching-the-cargo-home-in-ci
|
||||
path: |
|
||||
@@ -107,7 +136,7 @@ jobs:
|
||||
|
||||
- name: Generate lockfile
|
||||
# Also updates the crates.io index
|
||||
run: cargo generate-lockfile && cargo update -p ahash --precise 0.8.7 && cargo update -p bumpalo --precise 3.14.0
|
||||
run: cargo generate-lockfile && cargo update -p smol_str --precise 0.3.2
|
||||
|
||||
- name: Install GCC Multilib
|
||||
if: (matrix.platform.os == 'ubuntu-latest') && contains(matrix.platform.target, 'i686')
|
||||
@@ -116,7 +145,7 @@ jobs:
|
||||
- name: Cache cargo-apk
|
||||
if: contains(matrix.platform.target, 'android')
|
||||
id: cargo-apk-cache
|
||||
uses: actions/cache@v3
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cargo/bin/cargo-apk
|
||||
# Change this key if we update the required cargo-apk version
|
||||
@@ -131,6 +160,11 @@ jobs:
|
||||
if: contains(matrix.platform.target, 'android') && (steps.cargo-apk-cache.outputs.cache-hit != 'true')
|
||||
run: cargo install cargo-apk --version=^0.9.7 --locked
|
||||
|
||||
- uses: taiki-e/cache-cargo-install-action@v2
|
||||
if: contains(matrix.platform.target, 'wasm32') && matrix.toolchain == 'nightly'
|
||||
with:
|
||||
tool: wasm-bindgen-cli
|
||||
|
||||
- uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: ${{ matrix.toolchain }}${{ matrix.platform.host }}
|
||||
@@ -145,56 +179,109 @@ jobs:
|
||||
- name: Build crate
|
||||
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.
|
||||
- name: Test dpi crate
|
||||
if: >
|
||||
contains(matrix.platform.name, 'Linux 64bit') &&
|
||||
matrix.toolchain != '1.70.0'
|
||||
matrix.toolchain != '1.85'
|
||||
run: cargo test -p dpi
|
||||
|
||||
- name: Check dpi crate (no_std)
|
||||
if: >
|
||||
contains(matrix.platform.name, 'Linux 64bit') &&
|
||||
matrix.toolchain != '1.85'
|
||||
run: cargo check -p dpi --no-default-features
|
||||
|
||||
- name: Build tests
|
||||
if: >
|
||||
!contains(matrix.platform.target, 'redox') &&
|
||||
matrix.toolchain != '1.70.0'
|
||||
matrix.toolchain != '1.85'
|
||||
run: cargo $CMD test --no-run $OPTIONS
|
||||
|
||||
- name: Run tests
|
||||
if: >
|
||||
!contains(matrix.platform.target, 'android') &&
|
||||
!contains(matrix.platform.target, 'ios') &&
|
||||
!contains(matrix.platform.target, 'wasm32') &&
|
||||
(!contains(matrix.platform.target, 'wasm32') || matrix.toolchain == 'nightly') &&
|
||||
!contains(matrix.platform.target, 'redox') &&
|
||||
matrix.toolchain != '1.70.0'
|
||||
matrix.toolchain != '1.85'
|
||||
run: cargo $CMD test $OPTIONS
|
||||
|
||||
- name: Lint with clippy
|
||||
if: (matrix.toolchain == 'stable') && !contains(matrix.platform.options, '--no-default-features')
|
||||
run: cargo clippy --all-targets $OPTIONS -- -Dwarnings
|
||||
run: cargo clippy --all-targets $OPTIONS $TEST_OPTIONS -- -Dwarnings
|
||||
|
||||
- name: Build tests with serde enabled
|
||||
if: >
|
||||
!contains(matrix.platform.target, 'redox') &&
|
||||
matrix.toolchain != '1.70.0'
|
||||
run: cargo $CMD test --no-run $OPTIONS --features serde
|
||||
matrix.toolchain != '1.85'
|
||||
run: cargo $CMD test --no-run $OPTIONS $TEST_OPTIONS --features serde
|
||||
|
||||
- name: Run tests with serde enabled
|
||||
if: >
|
||||
!contains(matrix.platform.target, 'android') &&
|
||||
!contains(matrix.platform.target, 'ios') &&
|
||||
!contains(matrix.platform.target, 'wasm32') &&
|
||||
(!contains(matrix.platform.target, 'wasm32') || matrix.toolchain == 'nightly') &&
|
||||
!contains(matrix.platform.target, 'redox') &&
|
||||
matrix.toolchain != '1.70.0'
|
||||
run: cargo $CMD test $OPTIONS --features serde
|
||||
matrix.toolchain != '1.85'
|
||||
run: cargo $CMD test $OPTIONS $TEST_OPTIONS --features serde
|
||||
|
||||
- name: Check docs.rs documentation
|
||||
if: matrix.toolchain == 'nightly'
|
||||
run: cargo doc --no-deps $OPTIONS --features=rwh_04,rwh_05,rwh_06,serde,mint,android-native-activity
|
||||
run: cargo doc --no-deps $OPTIONS --features=serde,mint,android-native-activity
|
||||
env:
|
||||
RUSTDOCFLAGS: '--deny=warnings ${{ matrix.platform.rustflags }} --cfg=docsrs --cfg=unreleased_changelogs'
|
||||
|
||||
# See restore step above
|
||||
- name: Save cache of cargo folder
|
||||
uses: actions/cache/save@v3
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry/index/
|
||||
@@ -214,10 +301,11 @@ jobs:
|
||||
- { name: 'Android', target: aarch64-linux-android }
|
||||
- { name: 'iOS', target: aarch64-apple-ios }
|
||||
- { name: 'Linux', target: x86_64-unknown-linux-gnu }
|
||||
- { name: 'macOS', target: x86_64-apple-darwin }
|
||||
- { name: 'macOS', target: aarch64-apple-darwin }
|
||||
- { name: 'Redox OS', target: x86_64-unknown-redox }
|
||||
- { name: 'web', target: wasm32-unknown-unknown }
|
||||
- { name: 'Windows', target: x86_64-pc-windows-gnu }
|
||||
- { name: 'Web', target: wasm32-unknown-unknown }
|
||||
- { name: 'Windows GNU', target: x86_64-pc-windows-gnu }
|
||||
- { name: 'Windows MSVC', target: x86_64-pc-windows-msvc }
|
||||
|
||||
steps:
|
||||
- uses: taiki-e/checkout-action@v1
|
||||
@@ -225,11 +313,31 @@ jobs:
|
||||
with:
|
||||
command: check
|
||||
log-level: error
|
||||
manifest-path: winit/Cargo.toml
|
||||
arguments: --all-features --target ${{ matrix.platform.target }}
|
||||
|
||||
eslint:
|
||||
name: ESLint
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ./winit-web/src/script
|
||||
|
||||
steps:
|
||||
- uses: taiki-e/checkout-action@v1
|
||||
- name: Setup NPM
|
||||
run: npm install
|
||||
- name: Run ESLint
|
||||
run: npx eslint@9.38.0
|
||||
|
||||
swc:
|
||||
name: Minimize JavaScript
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ./winit-web/src/script
|
||||
|
||||
steps:
|
||||
- uses: taiki-e/checkout-action@v1
|
||||
@@ -237,7 +345,7 @@ jobs:
|
||||
run: sudo npm i -g @swc/cli
|
||||
- name: Run SWC
|
||||
run: |
|
||||
swc src/platform_impl/web/web_sys/worker.js -o src/platform_impl/web/web_sys/worker.min.js
|
||||
swc . --ignore node_modules,**/*.d.ts --only **/*.ts -d . --out-file-extension min.js
|
||||
- name: Check for diff
|
||||
run: |
|
||||
[[ -z $(git status -s) ]]
|
||||
|
||||
8
.github/workflows/docs.yml
vendored
8
.github/workflows/docs.yml
vendored
@@ -19,7 +19,7 @@ jobs:
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
@@ -29,10 +29,10 @@ jobs:
|
||||
env:
|
||||
RUSTDOCFLAGS: --crate-version master --cfg=docsrs --cfg=unreleased_changelogs
|
||||
run: |
|
||||
cargo doc --no-deps -Z rustdoc-map -Z rustdoc-scrape-examples --features=rwh_04,rwh_05,rwh_06,serde,mint,android-native-activity
|
||||
cargo doc --no-deps -Z rustdoc-map -Z rustdoc-scrape-examples --features=serde,mint,android-native-activity
|
||||
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@v4
|
||||
uses: actions/configure-pages@v5
|
||||
|
||||
- name: Fix permissions
|
||||
run: |
|
||||
@@ -41,7 +41,7 @@ jobs:
|
||||
done
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
uses: actions/upload-pages-artifact@v4
|
||||
with:
|
||||
path: target/doc
|
||||
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -5,3 +5,6 @@ rls/
|
||||
*~
|
||||
#*#
|
||||
.DS_Store
|
||||
# NPM package used to run ESLint.
|
||||
/src/platform_impl/web/script/node_modules
|
||||
/src/platform_impl/web/script/package-lock.json
|
||||
|
||||
@@ -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
|
||||
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
|
||||
[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
|
||||
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
|
||||
|
||||
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
|
||||
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
|
||||
|
||||
During the review process certain events could require an action from your side,
|
||||
|
||||
418
Cargo.toml
418
Cargo.toml
@@ -1,376 +1,96 @@
|
||||
[package]
|
||||
name = "winit"
|
||||
version = "0.30.8"
|
||||
authors = [
|
||||
"The winit contributors",
|
||||
"Pierre Krieger <pierre.krieger1708@gmail.com>",
|
||||
]
|
||||
description = "Cross-platform window creation library."
|
||||
keywords = ["windowing"]
|
||||
readme = "README.md"
|
||||
documentation = "https://docs.rs/winit"
|
||||
categories = ["gui"]
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
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",
|
||||
]
|
||||
[workspace]
|
||||
default-members = ["winit"]
|
||||
members = ["dpi", "winit*"]
|
||||
resolver = "2"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = [
|
||||
"rwh_04",
|
||||
"rwh_05",
|
||||
"rwh_06",
|
||||
"serde",
|
||||
"mint",
|
||||
# Enabled to get docs to compile
|
||||
"android-native-activity",
|
||||
]
|
||||
# These are all tested in CI
|
||||
targets = [
|
||||
# Windows
|
||||
"i686-pc-windows-msvc",
|
||||
"x86_64-pc-windows-msvc",
|
||||
# macOS
|
||||
"x86_64-apple-darwin",
|
||||
# Unix (X11 & Wayland)
|
||||
"i686-unknown-linux-gnu",
|
||||
"x86_64-unknown-linux-gnu",
|
||||
# iOS
|
||||
"x86_64-apple-ios",
|
||||
# Android
|
||||
"aarch64-linux-android",
|
||||
# Web
|
||||
"wasm32-unknown-unknown",
|
||||
]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
license = "Apache-2.0"
|
||||
repository = "https://github.com/rust-windowing/winit"
|
||||
rust-version = "1.85"
|
||||
version = "0.31.0-beta.2"
|
||||
|
||||
# Features are documented in either `lib.rs` or under `winit::platform`.
|
||||
[features]
|
||||
default = ["rwh_06", "x11", "wayland", "wayland-dlopen", "wayland-csd-adwaita"]
|
||||
x11 = ["x11-dl", "bytemuck", "percent-encoding", "xkbcommon-dl/x11", "x11rb"]
|
||||
wayland = [
|
||||
"wayland-client",
|
||||
"wayland-backend",
|
||||
"wayland-protocols",
|
||||
"wayland-protocols-plasma",
|
||||
"sctk",
|
||||
"ahash",
|
||||
"memmap2",
|
||||
]
|
||||
wayland-dlopen = ["wayland-backend/dlopen"]
|
||||
wayland-csd-adwaita = ["sctk-adwaita", "sctk-adwaita/ab_glyph"]
|
||||
wayland-csd-adwaita-crossfont = ["sctk-adwaita", "sctk-adwaita/crossfont"]
|
||||
wayland-csd-adwaita-notitle = ["sctk-adwaita"]
|
||||
android-native-activity = ["android-activity/native-activity"]
|
||||
android-game-activity = ["android-activity/game-activity"]
|
||||
serde = ["dep:serde", "cursor-icon/serde", "smol_str/serde", "dpi/serde"]
|
||||
mint = ["dpi/mint"]
|
||||
rwh_04 = ["dep:rwh_04", "ndk/rwh_04"]
|
||||
rwh_05 = ["dep:rwh_05", "ndk/rwh_05"]
|
||||
rwh_06 = ["dep:rwh_06", "ndk/rwh_06"]
|
||||
[workspace.dependencies]
|
||||
# Workspace dependencies.
|
||||
# `winit` has no version here to allow using it in dev deps for docs.
|
||||
winit = { path = "winit" }
|
||||
winit-android = { version = "=0.31.0-beta.2", path = "winit-android" }
|
||||
winit-appkit = { version = "=0.31.0-beta.2", path = "winit-appkit" }
|
||||
winit-common = { version = "=0.31.0-beta.2", path = "winit-common" }
|
||||
winit-core = { version = "=0.31.0-beta.2", path = "winit-core" }
|
||||
winit-orbital = { version = "=0.31.0-beta.2", path = "winit-orbital" }
|
||||
winit-uikit = { version = "=0.31.0-beta.2", path = "winit-uikit" }
|
||||
winit-wayland = { version = "=0.31.0-beta.2", path = "winit-wayland", default-features = false }
|
||||
winit-web = { version = "=0.31.0-beta.2", path = "winit-web" }
|
||||
winit-win32 = { version = "=0.31.0-beta.2", path = "winit-win32" }
|
||||
winit-x11 = { version = "=0.31.0-beta.2", path = "winit-x11" }
|
||||
|
||||
[build-dependencies]
|
||||
cfg_aliases = "0.2.1"
|
||||
|
||||
[dependencies]
|
||||
# Core dependencies.
|
||||
bitflags = "2"
|
||||
cfg_aliases = "0.2.1"
|
||||
cursor-icon = "1.1.0"
|
||||
dpi = { version = "0.1.1", path = "dpi" }
|
||||
rwh_04 = { package = "raw-window-handle", version = "0.4", optional = true }
|
||||
rwh_05 = { package = "raw-window-handle", version = "0.5.2", features = [
|
||||
"std",
|
||||
], optional = true }
|
||||
rwh_06 = { package = "raw-window-handle", version = "0.6", features = [
|
||||
"std",
|
||||
], optional = true }
|
||||
serde = { workspace = true, optional = true }
|
||||
smol_str = "0.2.0"
|
||||
dpi = { version = "0.1.2", path = "dpi" }
|
||||
keyboard-types = "0.8.0"
|
||||
mint = "0.5.6"
|
||||
rwh_06 = { package = "raw-window-handle", version = "0.6", features = ["std"] }
|
||||
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, features = ["png"] }
|
||||
tracing = { version = "0.1.40", default-features = false, features = ["log"] }
|
||||
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
|
||||
winit = { path = ".", features = ["rwh_05"] }
|
||||
|
||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dev-dependencies]
|
||||
softbuffer = { version = "0.4.0", default-features = false, features = [
|
||||
# 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"
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
# Android dependencies.
|
||||
android-activity = "0.6.0"
|
||||
ndk = { version = "0.9.0", default-features = false }
|
||||
ndk = { version = "0.9.0", features = ["rwh_06"], default-features = false }
|
||||
|
||||
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
|
||||
core-foundation = "0.9.3"
|
||||
objc2 = "0.5.2"
|
||||
# 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.2", default-features = false }
|
||||
objc2-core-foundation = { version = "0.3.2", default-features = false }
|
||||
objc2-core-graphics = { version = "0.3.2", default-features = false }
|
||||
objc2-core-video = { version = "0.3.2", default-features = false }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false }
|
||||
objc2-ui-kit = { version = "0.3.2", default-features = false }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
core-graphics = "0.23.1"
|
||||
block2 = "0.5.1"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies.objc2-foundation]
|
||||
version = "0.2.2"
|
||||
features = [
|
||||
"block2",
|
||||
"dispatch",
|
||||
"NSArray",
|
||||
"NSAttributedString",
|
||||
"NSData",
|
||||
"NSDictionary",
|
||||
"NSDistributedNotificationCenter",
|
||||
"NSEnumerator",
|
||||
"NSKeyValueObserving",
|
||||
"NSNotification",
|
||||
"NSObjCRuntime",
|
||||
"NSPathUtilities",
|
||||
"NSProcessInfo",
|
||||
"NSRunLoop",
|
||||
"NSString",
|
||||
"NSThread",
|
||||
"NSValue",
|
||||
]
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies.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",
|
||||
"NSView",
|
||||
"NSWindow",
|
||||
"NSWindowScripting",
|
||||
"NSWindowTabGroup",
|
||||
]
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies.objc2-foundation]
|
||||
version = "0.2.2"
|
||||
features = [
|
||||
"dispatch",
|
||||
"NSArray",
|
||||
"NSEnumerator",
|
||||
"NSGeometry",
|
||||
"NSObjCRuntime",
|
||||
"NSString",
|
||||
"NSProcessInfo",
|
||||
"NSThread",
|
||||
"NSSet",
|
||||
]
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies.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",
|
||||
]
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
# Windows dependencies.
|
||||
unicode-segmentation = "1.7.1"
|
||||
windows-sys = "0.59.0"
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies.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",
|
||||
]
|
||||
|
||||
[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.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"
|
||||
# Linux dependencies.
|
||||
ahash = { version = "0.8.7", features = ["no-rng"] }
|
||||
bytemuck = { version = "1.13.1", default-features = false }
|
||||
calloop = "0.14.3"
|
||||
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",
|
||||
"dl-libxcb",
|
||||
"randr",
|
||||
"resource_manager",
|
||||
"xinput",
|
||||
"xkb",
|
||||
], optional = true }
|
||||
memmap2 = "0.9.0"
|
||||
percent-encoding = "2.0"
|
||||
rustix = { version = "1.0.7", default-features = false }
|
||||
x11-dl = "2.19.1"
|
||||
x11rb = { version = "0.13.0", default-features = false }
|
||||
xkbcommon-dl = "0.4.2"
|
||||
|
||||
[target.'cfg(target_os = "redox")'.dependencies]
|
||||
# Orbital dependencies.
|
||||
orbclient = { version = "0.3.47", default-features = false }
|
||||
redox_syscall = "0.4.1"
|
||||
redox_syscall = "0.5.7"
|
||||
|
||||
[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",
|
||||
"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]
|
||||
# Web dependencies.
|
||||
atomic-waker = "1"
|
||||
concurrent-queue = { version = "2", default-features = false }
|
||||
|
||||
[target.'cfg(target_family = "wasm")'.dev-dependencies]
|
||||
console_error_panic_hook = "0.1"
|
||||
js-sys = "0.3.70"
|
||||
pin-project = "1"
|
||||
tracing-web = "0.1"
|
||||
|
||||
[[example]]
|
||||
doc-scrape-examples = true
|
||||
name = "window"
|
||||
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["dpi"]
|
||||
|
||||
[workspace.package]
|
||||
rust-version = "1.70.0"
|
||||
repository = "https://github.com/rust-windowing/winit"
|
||||
license = "Apache-2.0"
|
||||
edition = "2021"
|
||||
|
||||
[workspace.dependencies]
|
||||
serde = { version = "1", features = ["serde_derive"] }
|
||||
mint = "0.5.6"
|
||||
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" }
|
||||
|
||||
199
FEATURES.md
199
FEATURES.md
@@ -47,202 +47,3 @@ through the implementation work necessary to function on all platforms. When one
|
||||
gets implemented across all platforms, a PR can be opened to upgrade the feature to a core feature.
|
||||
If that gets accepted, the platform-specific functions get deprecated and become permanently
|
||||
exposed through the core, cross-platform API.
|
||||
|
||||
# Features
|
||||
|
||||
## Extending this section
|
||||
|
||||
If your PR makes notable changes to Winit's features, please update this section as follows:
|
||||
|
||||
- If your PR adds a new feature, add a brief description to the relevant section. If the feature is a core
|
||||
feature, add a row to the feature matrix and describe what platforms the feature has been implemented on.
|
||||
|
||||
- If your PR begins a new API rework, add a row to the `Pending API Reworks` table. If the PR implements the
|
||||
API rework on all relevant platforms, please move it to the `Completed API Reworks` table.
|
||||
|
||||
- If your PR implements an already-existing feature on a new platform, either mark the feature as *completed*,
|
||||
or mark it as *mostly completed* and link to an issue describing the problems with the implementation.
|
||||
|
||||
## Core
|
||||
|
||||
### Windowing
|
||||
- **Window initialization**: Winit allows the creation of a window
|
||||
- **Providing pointer to init OpenGL**: Winit provides the necessary pointers to initialize a working opengl context
|
||||
- **Providing pointer to init Vulkan**: Same as OpenGL but for Vulkan
|
||||
- **Window decorations**: The windows created by winit are properly decorated, and the decorations can
|
||||
be deactivated
|
||||
- **Window decorations toggle**: Decorations can be turned on or off after window creation
|
||||
- **Window resizing**: The windows created by winit can be resized and generate the appropriate events
|
||||
when they are. The application can precisely control its window size if desired.
|
||||
- **Window resize increments**: When the window gets resized, the application can choose to snap the window's
|
||||
size to specific values.
|
||||
- **Window transparency**: Winit allows the creation of windows with a transparent background.
|
||||
- **Window maximization**: The windows created by winit can be maximized upon creation.
|
||||
- **Window maximization toggle**: The windows created by winit can be maximized and unmaximized after
|
||||
creation.
|
||||
- **Window minimization**: The windows created by winit can be minimized after creation.
|
||||
- **Fullscreen**: The windows created by winit can be put into fullscreen mode.
|
||||
- **Fullscreen toggle**: The windows created by winit can be switched to and from fullscreen after
|
||||
creation.
|
||||
- **Exclusive fullscreen**: Winit allows changing the video mode of the monitor
|
||||
for fullscreen windows and, if applicable, captures the monitor for exclusive
|
||||
use by this application.
|
||||
- **HiDPI support**: Winit assists developers in appropriately scaling HiDPI content.
|
||||
- **Popup / modal windows**: Windows can be created relative to the client area of other windows, and parent
|
||||
windows can be disabled in favor of popup windows. This feature also guarantees that popup windows
|
||||
get drawn above their owner.
|
||||
|
||||
|
||||
### System Information
|
||||
- **Monitor list**: Retrieve the list of monitors and their metadata, including which one is primary.
|
||||
- **Video mode query**: Monitors can be queried for their supported fullscreen video modes (consisting of resolution, refresh rate, and bit depth).
|
||||
|
||||
### Input Handling
|
||||
- **Mouse events**: Generating mouse events associated with pointer motion, click, and scrolling events.
|
||||
- **Mouse set location**: Forcibly changing the location of the pointer.
|
||||
- **Cursor locking**: Locking the cursor inside the window so it cannot move.
|
||||
- **Cursor confining**: Confining the cursor to the window bounds so it cannot leave them.
|
||||
- **Cursor icon**: Changing the cursor icon or hiding the cursor.
|
||||
- **Cursor image**: Changing the cursor to your own image.
|
||||
- **Cursor hittest**: Handle or ignore mouse events for a window.
|
||||
- **Touch events**: Single-touch events.
|
||||
- **Touch pressure**: Touch events contain information about the amount of force being applied.
|
||||
- **Multitouch**: Multi-touch events, including cancellation of a gesture.
|
||||
- **Keyboard events**: Properly processing keyboard events using the user-specified keymap and
|
||||
translating keypresses into UTF-8 characters, handling dead keys and IMEs.
|
||||
- **Drag & Drop**: Dragging content into winit, detecting when content enters, drops, or if the drop is cancelled.
|
||||
- **Raw Device Events**: Capturing input from input devices without any OS filtering.
|
||||
- **Gamepad/Joystick events**: Capturing input from gamepads and joysticks.
|
||||
- **Device movement events**: Capturing input from the device gyroscope and accelerometer.
|
||||
|
||||
## Platform
|
||||
### Windows
|
||||
* Setting the name of the internal window class
|
||||
* Setting the taskbar icon
|
||||
* Setting the parent window
|
||||
* Setting a menu bar
|
||||
* `WS_EX_NOREDIRECTIONBITMAP` support
|
||||
* Theme the title bar according to Windows 10 Dark Mode setting or set a preferred theme
|
||||
* Changing a system-drawn backdrop
|
||||
* Setting the window border color
|
||||
* Setting the title bar background color
|
||||
* Setting the title color
|
||||
* Setting the corner rounding preference
|
||||
|
||||
### macOS
|
||||
* Window activation policy
|
||||
* Window movable by background
|
||||
* Transparent titlebar
|
||||
* Hidden titlebar
|
||||
* Hidden titlebar buttons
|
||||
* Full-size content view
|
||||
* Accepts first mouse
|
||||
* Set a preferred theme and get current theme.
|
||||
|
||||
### Unix
|
||||
* Window urgency
|
||||
* X11 Window Class
|
||||
* X11 Override Redirect Flag
|
||||
* GTK Theme Variant
|
||||
* Base window size
|
||||
* Setting the X11 parent window
|
||||
|
||||
### iOS
|
||||
* Get the `UIScreen` object pointer
|
||||
* Setting the `UIView` hidpi factor
|
||||
* Valid orientations
|
||||
* Home indicator visibility
|
||||
* Status bar visibility and style
|
||||
* Deferring system gestures
|
||||
* Getting the device idiom
|
||||
* Getting the preferred video mode
|
||||
|
||||
### Web
|
||||
* Get if the systems preferred color scheme is "dark"
|
||||
|
||||
## Compatibility Matrix
|
||||
|
||||
Legend:
|
||||
|
||||
- ✔️: Works as intended
|
||||
- ▢: Mostly works, but some bugs are known
|
||||
- ❌: Missing feature or large bugs making it unusable
|
||||
- **N/A**: Not applicable for this platform
|
||||
- ❓: Unknown status
|
||||
|
||||
### Windowing
|
||||
|Feature |Windows|MacOS |Linux x11 |Linux Wayland |Android|iOS |Web |Redox OS|
|
||||
|-------------------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
||||
|Window initialization |✔️ |✔️ |▢[#5] |✔️ |▢[#33]|▢[#33] |✔️ |✔️ |
|
||||
|Providing pointer to init OpenGL |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |
|
||||
|Providing pointer to init Vulkan |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |**N/A**|**N/A** |
|
||||
|Window decorations |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|✔️ |
|
||||
|Window decorations toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||
|Window resizing |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |✔️ |
|
||||
|Window resize increments |✔️ |✔️ |✔️ |❌ |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||
|Window transparency |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|N/A |✔️ |
|
||||
|Window blur |❌ |❌ |❌ |✔️ |**N/A**|**N/A**|N/A |❌ |
|
||||
|Window maximization |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||
|Window maximization toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||
|Window minimization |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||
|Fullscreen |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |✔️ |**N/A** |
|
||||
|Fullscreen toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |✔️ |**N/A** |
|
||||
|Exclusive fullscreen |✔️ |✔️ |✔️ |**N/A** |❌ |✔️ |**N/A**|**N/A** |
|
||||
|HiDPI support |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |
|
||||
|Popup windows |❌ |❌ |❌ |❌ |❌ |❌ |**N/A**|**N/A** |
|
||||
|
||||
### System information
|
||||
|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
||||
|---------------- | ----- | ---- | ------- | ----------- | ----- | ------- | -------- | ------ |
|
||||
|Monitor list |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|❌ |
|
||||
|Video mode query |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|❌ |
|
||||
|
||||
### Input handling
|
||||
|Feature |Windows |MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
||||
|----------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
||||
|Mouse events |✔️ |▢[#63] |✔️ |✔️ |**N/A**|**N/A**|✔️ |✔️ |
|
||||
|Mouse set location |✔️ |✔️ |✔️ |✔️(when locked) |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||
|Cursor locking |❌ |✔️ |❌ |✔️ |**N/A**|**N/A**|✔️ |❌ |
|
||||
|Cursor confining |✔️ |❌ |✔️ |✔️ |**N/A**|**N/A**|❌ |❌ |
|
||||
|Cursor icon |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |**N/A** |
|
||||
|Cursor image |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |**N/A** |
|
||||
|Cursor hittest |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|❌ |❌ |
|
||||
|Touch events |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A** |
|
||||
|Touch pressure |✔️ |❌ |❌ |❌ |❌ |✔️ |✔️ |**N/A** |
|
||||
|Multitouch |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |❌ |**N/A** |
|
||||
|Keyboard events |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |✔️ |✔️ |
|
||||
|Drag & Drop |▢[#720] |▢[#720] |▢[#720] |▢[#720] |**N/A**|**N/A**|❓ |**N/A** |
|
||||
|Raw Device Events |▢[#750] |▢[#750] |▢[#750] |❌ |❌ |❌ |❓ |**N/A** |
|
||||
|Gamepad/Joystick events |❌[#804] |❌ |❌ |❌ |❌ |❌ |❓ |**N/A** |
|
||||
|Device movement events |❓ |❓ |❓ |❓ |❌ |❌ |❓ |**N/A** |
|
||||
|Drag window with cursor |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A** |**N/A** |
|
||||
|Resize with cursor |✔️ |❌ |✔️ |✔️ |**N/A**|**N/A**|**N/A** |**N/A** |
|
||||
|
||||
### Pending API Reworks
|
||||
Changes in the API that have been agreed upon but aren't implemented across all platforms.
|
||||
|
||||
|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
||||
|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
||||
|New API for HiDPI ([#315] [#319]) |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |❓ |
|
||||
|Event Loop 2.0 ([#459]) |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |✔️ |
|
||||
|Keyboard Input 2.0 ([#753]) |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |✔️ |✔️ |
|
||||
|
||||
### Completed API Reworks
|
||||
|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
||||
|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
||||
|
||||
[#165]: https://github.com/rust-windowing/winit/issues/165
|
||||
[#219]: https://github.com/rust-windowing/winit/issues/219
|
||||
[#242]: https://github.com/rust-windowing/winit/issues/242
|
||||
[#306]: https://github.com/rust-windowing/winit/issues/306
|
||||
[#315]: https://github.com/rust-windowing/winit/issues/315
|
||||
[#319]: https://github.com/rust-windowing/winit/issues/319
|
||||
[#33]: https://github.com/rust-windowing/winit/issues/33
|
||||
[#459]: https://github.com/rust-windowing/winit/issues/459
|
||||
[#5]: https://github.com/rust-windowing/winit/issues/5
|
||||
[#63]: https://github.com/rust-windowing/winit/issues/63
|
||||
[#720]: https://github.com/rust-windowing/winit/issues/720
|
||||
[#721]: https://github.com/rust-windowing/winit/issues/721
|
||||
[#750]: https://github.com/rust-windowing/winit/issues/750
|
||||
[#753]: https://github.com/rust-windowing/winit/issues/753
|
||||
[#804]: https://github.com/rust-windowing/winit/issues/804
|
||||
|
||||
23
README.md
23
README.md
@@ -2,13 +2,13 @@
|
||||
|
||||
[](https://crates.io/crates/winit)
|
||||
[](https://docs.rs/winit)
|
||||
[](https://rust-windowing.github.io/winit/winit/index.html)
|
||||
[](https://github.com/rust-windowing/winit/actions)
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
winit = "0.30.8"
|
||||
winit = "0.31.0-beta.2"
|
||||
```
|
||||
|
||||
## [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
|
||||
another library.
|
||||
|
||||
## CONTRIBUTING
|
||||
|
||||
For contributing guidelines see [CONTRIBUTING.md](./CONTRIBUTING.md).
|
||||
|
||||
## MSRV Policy
|
||||
|
||||
This crate's Minimum Supported Rust Version (MSRV) is **1.70**. Changes to
|
||||
This crate's Minimum Supported Rust Version (MSRV) is **1.85**. Changes to
|
||||
the MSRV will be accompanied by a minor version bump.
|
||||
|
||||
As a **tentative** policy, the upper bound of the MSRV is given by the following
|
||||
@@ -50,12 +54,15 @@ Where `sid` is the current version of `rustc` provided by [Debian Sid], and
|
||||
|
||||
[Debian Sid]: https://packages.debian.org/sid/rustc
|
||||
|
||||
The exception is for the Android platform, where a higher Rust version
|
||||
An exception is made for the Android platform, where a higher Rust version
|
||||
must be used for certain Android features. In this case, the MSRV will be
|
||||
capped at the latest stable version of Rust minus three. This inconsistency is
|
||||
not reflected in Cargo metadata, as it is not powerful enough to expose this
|
||||
restriction.
|
||||
|
||||
Redox OS is also not covered by this MSRV policy, as it requires a Rust nightly
|
||||
toolchain to compile.
|
||||
|
||||
All crates in the [`rust-windowing`] organizations have the
|
||||
same MSRV policy.
|
||||
|
||||
@@ -63,4 +70,10 @@ same MSRV policy.
|
||||
|
||||
### Platform-specific usage
|
||||
|
||||
Check out the [`winit::platform`](https://rust-windowing.github.io/winit/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 -->
|
||||
|
||||
31
clippy.toml
31
clippy.toml
@@ -1,15 +1,20 @@
|
||||
# Using allow-invalid because this is platform-specific code
|
||||
disallowed-methods = [
|
||||
{ path = "web_sys::window", reason = "is not available in every context" },
|
||||
{ path = "web_sys::HtmlCanvasElement::width", reason = "Winit shouldn't touch the internal canvas size" },
|
||||
{ path = "web_sys::HtmlCanvasElement::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" },
|
||||
{ path = "web_sys::HtmlCanvasElement::set_height", reason = "Winit shouldn't touch the internal canvas size" },
|
||||
{ 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" },
|
||||
{ path = "web_sys::HtmlElement::style", reason = "cache this to reduce calls to JS" },
|
||||
{ path = "web_sys::Element::request_fullscreen", reason = "Doesn't account for compatibility with Safari" },
|
||||
{ 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" },
|
||||
{ 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::NSView::visibleRect", reason = "We expose a render target to the user, and visibility is not really relevant to that (and can break if you don't use the rectangle position as well). Use `frame` instead." },
|
||||
{ allow-invalid = true, path = "objc2_app_kit::NSWindow::setFrameTopLeftPoint", reason = "Not sufficient when working with Winit's coordinate system, use `flip_window_screen_coordinates` instead" },
|
||||
{ allow-invalid = true, path = "web_sys::Document::exit_fullscreen", 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" },
|
||||
{ allow-invalid = true, path = "web_sys::Element::request_fullscreen", reason = "Doesn't account for compatibility with Safari" },
|
||||
{ allow-invalid = true, path = "web_sys::HtmlCanvasElement::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" },
|
||||
{ allow-invalid = true, path = "web_sys::HtmlCanvasElement::set_width", reason = "Winit shouldn't touch the internal canvas size" },
|
||||
{ allow-invalid = true, path = "web_sys::HtmlCanvasElement::width", reason = "Winit shouldn't touch the internal canvas size" },
|
||||
{ allow-invalid = true, path = "web_sys::HtmlElement::style", reason = "cache this to reduce calls to JS" },
|
||||
{ allow-invalid = true, path = "web_sys::MouseEvent::buttons", reason = "Use `backend::event::cursor_buttons()` to avoid wrong conversions" },
|
||||
{ allow-invalid = true, path = "web_sys::MouseEvent::button", reason = "Use `backend::event::cursor_button()` to avoid wrong conversions" },
|
||||
{ allow-invalid = true, path = "web_sys::PointerEvent::pointer_type", reason = "Use `WebPointerType` to emit warnings" },
|
||||
{ allow-invalid = true, path = "web_sys::Window::document", reason = "cache this to reduce calls to JS" },
|
||||
{ allow-invalid = true, path = "web_sys::Window::get_computed_style", reason = "cache this to reduce calls to JS" },
|
||||
{ allow-invalid = true, path = "web_sys::Window::navigator", reason = "cache this to reduce calls to JS" },
|
||||
{ allow-invalid = true, path = "web_sys::window", reason = "is not available in every context" },
|
||||
]
|
||||
|
||||
14
deny.toml
14
deny.toml
@@ -7,6 +7,7 @@
|
||||
all-features = true
|
||||
exclude-dev = true
|
||||
targets = [
|
||||
{ triple = "aarch64-apple-darwin" },
|
||||
{ triple = "aarch64-apple-ios" },
|
||||
{ triple = "aarch64-linux-android" },
|
||||
{ triple = "i686-pc-windows-gnu" },
|
||||
@@ -38,10 +39,11 @@ private = { ignore = true }
|
||||
[bans]
|
||||
multiple-versions = "deny"
|
||||
skip = [
|
||||
{ crate = "raw-window-handle", reason = "we depend on multiple behind features" },
|
||||
{ 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
|
||||
wildcards = "allow" # at least until https://github.com/EmbarkStudios/cargo-deny/issues/241 is fixed
|
||||
|
||||
[bans.build]
|
||||
include-archives = true
|
||||
@@ -53,6 +55,14 @@ allow = [
|
||||
]
|
||||
crate = "android-activity"
|
||||
|
||||
[[bans.build.bypass]]
|
||||
allow-globs = ["ci/*", "githooks/*"]
|
||||
crate = "zerocopy"
|
||||
|
||||
[[bans.build.bypass]]
|
||||
allow-globs = ["cherry-pick-stable.sh"]
|
||||
crate = "libc"
|
||||
|
||||
[[bans.build.bypass]]
|
||||
allow-globs = ["freetype2/*"]
|
||||
crate = "freetype-sys"
|
||||
|
||||
@@ -1,11 +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.
|
||||
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,6 +11,11 @@ Unreleased` header.
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 0.1.2
|
||||
|
||||
- Added `Insets`, `LogicalInsets` and `PhysicalInsets` types.
|
||||
- Make `no_std` compatible. If you use this functionality, DPI's license has changed.
|
||||
|
||||
## 0.1.1
|
||||
|
||||
- Derive `Debug`, `Copy`, `Clone`, `PartialEq`, `Serialize`, `Deserialize` traits for `PixelUnit`.
|
||||
|
||||
@@ -1,39 +1,46 @@
|
||||
[package]
|
||||
name = "dpi"
|
||||
version = "0.1.1"
|
||||
description = "Types for handling UI scaling"
|
||||
keywords = ["DPI", "HiDPI", "scale-factor"]
|
||||
categories = ["gui"]
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
description = "Types for handling UI scaling"
|
||||
edition.workspace = true
|
||||
keywords = ["DPI", "HiDPI", "scale-factor"]
|
||||
# N.B. This is "AND", because of the imported libm code.
|
||||
license = "Apache-2.0 AND MIT"
|
||||
name = "dpi"
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
version = "0.1.2"
|
||||
|
||||
[features]
|
||||
serde = ["dep:serde"]
|
||||
default = ["std"]
|
||||
|
||||
mint = ["dep:mint"]
|
||||
serde = ["dep:serde"]
|
||||
|
||||
# Access mathematical functions using the standard library implementations
|
||||
std = []
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true, optional = true }
|
||||
mint = { workspace = true, optional = true }
|
||||
serde = { workspace = true, optional = true }
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["serde", "mint"]
|
||||
features = ["mint", "serde"]
|
||||
# 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
|
||||
"x86_64-apple-ios",
|
||||
"aarch64-apple-ios",
|
||||
# Android
|
||||
"aarch64-linux-android",
|
||||
# Web
|
||||
"wasm32-unknown-unknown",
|
||||
]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
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.
|
||||
196
dpi/src/lib.rs
196
dpi/src/lib.rs
@@ -54,13 +54,25 @@
|
||||
//!
|
||||
//! * `serde`: Enables serialization/deserialization of certain types with [Serde](https://crates.io/crates/serde).
|
||||
//! * `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)
|
||||
//! [picas]: https://en.wikipedia.org/wiki/Pica_(typography)
|
||||
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide), doc(cfg_hide(doc, docsrs)))]
|
||||
#![forbid(unsafe_code)]
|
||||
#![cfg_attr(docsrs, feature(doc_cfg), doc(auto_cfg(hide(doc, docsrs))))]
|
||||
#![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")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -74,32 +86,32 @@ pub trait Pixel: Copy + Into<f64> {
|
||||
|
||||
impl Pixel for u8 {
|
||||
fn from_f64(f: f64) -> Self {
|
||||
f.round() as u8
|
||||
round(f) as u8
|
||||
}
|
||||
}
|
||||
impl Pixel for u16 {
|
||||
fn from_f64(f: f64) -> Self {
|
||||
f.round() as u16
|
||||
round(f) as u16
|
||||
}
|
||||
}
|
||||
impl Pixel for u32 {
|
||||
fn from_f64(f: f64) -> Self {
|
||||
f.round() as u32
|
||||
round(f) as u32
|
||||
}
|
||||
}
|
||||
impl Pixel for i8 {
|
||||
fn from_f64(f: f64) -> Self {
|
||||
f.round() as i8
|
||||
round(f) as i8
|
||||
}
|
||||
}
|
||||
impl Pixel for i16 {
|
||||
fn from_f64(f: f64) -> Self {
|
||||
f.round() as i16
|
||||
round(f) as i16
|
||||
}
|
||||
}
|
||||
impl Pixel for i32 {
|
||||
fn from_f64(f: f64) -> Self {
|
||||
f.round() as i32
|
||||
round(f) as i32
|
||||
}
|
||||
}
|
||||
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`.
|
||||
///
|
||||
/// All functions that take a scale factor assert that this will return `true`. If you're sourcing
|
||||
@@ -759,11 +780,156 @@ impl<P: Pixel> From<LogicalPosition<P>> for Position {
|
||||
}
|
||||
}
|
||||
|
||||
/// The logical distance between the edges of two rectangles.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct LogicalInsets<P> {
|
||||
/// The distance to the top edge.
|
||||
pub top: P,
|
||||
/// The distance to the left edge.
|
||||
pub left: P,
|
||||
/// The distance to the bottom edge.
|
||||
pub bottom: P,
|
||||
/// The distance to the right edge.
|
||||
pub right: P,
|
||||
}
|
||||
|
||||
impl<P> LogicalInsets<P> {
|
||||
#[inline]
|
||||
pub const fn new(top: P, left: P, bottom: P, right: P) -> Self {
|
||||
Self { top, left, bottom, right }
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> LogicalInsets<P> {
|
||||
#[inline]
|
||||
pub fn from_physical<T: Into<PhysicalInsets<X>>, X: Pixel>(
|
||||
physical: T,
|
||||
scale_factor: f64,
|
||||
) -> Self {
|
||||
physical.into().to_logical(scale_factor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_physical<X: Pixel>(&self, scale_factor: f64) -> PhysicalInsets<X> {
|
||||
assert!(validate_scale_factor(scale_factor));
|
||||
let top = self.top.into() * scale_factor;
|
||||
let left = self.left.into() * scale_factor;
|
||||
let bottom = self.bottom.into() * scale_factor;
|
||||
let right = self.right.into() * scale_factor;
|
||||
PhysicalInsets::new(top, left, bottom, right).cast()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn cast<X: Pixel>(&self) -> LogicalInsets<X> {
|
||||
LogicalInsets {
|
||||
top: self.top.cast(),
|
||||
left: self.left.cast(),
|
||||
bottom: self.bottom.cast(),
|
||||
right: self.right.cast(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The physical distance between the edges of two rectangles.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct PhysicalInsets<P> {
|
||||
/// The distance to the top edge.
|
||||
pub top: P,
|
||||
/// The distance to the left edge.
|
||||
pub left: P,
|
||||
/// The distance to the bottom edge.
|
||||
pub bottom: P,
|
||||
/// The distance to the right edge.
|
||||
pub right: P,
|
||||
}
|
||||
|
||||
impl<P> PhysicalInsets<P> {
|
||||
#[inline]
|
||||
pub const fn new(top: P, left: P, bottom: P, right: P) -> Self {
|
||||
Self { top, left, bottom, right }
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> PhysicalInsets<P> {
|
||||
#[inline]
|
||||
pub fn from_logical<T: Into<LogicalInsets<X>>, X: Pixel>(
|
||||
logical: T,
|
||||
scale_factor: f64,
|
||||
) -> Self {
|
||||
logical.into().to_physical(scale_factor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_logical<X: Pixel>(&self, scale_factor: f64) -> LogicalInsets<X> {
|
||||
assert!(validate_scale_factor(scale_factor));
|
||||
let top = self.top.into() / scale_factor;
|
||||
let left = self.left.into() / scale_factor;
|
||||
let bottom = self.bottom.into() / scale_factor;
|
||||
let right = self.right.into() / scale_factor;
|
||||
LogicalInsets::new(top, left, bottom, right).cast()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn cast<X: Pixel>(&self) -> PhysicalInsets<X> {
|
||||
PhysicalInsets {
|
||||
top: self.top.cast(),
|
||||
left: self.left.cast(),
|
||||
bottom: self.bottom.cast(),
|
||||
right: self.right.cast(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Insets that are either physical or logical.
|
||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub enum Insets {
|
||||
Physical(PhysicalInsets<u32>),
|
||||
Logical(LogicalInsets<f64>),
|
||||
}
|
||||
|
||||
impl Insets {
|
||||
pub fn new<S: Into<Self>>(insets: S) -> Self {
|
||||
insets.into()
|
||||
}
|
||||
|
||||
pub fn to_logical<P: Pixel>(&self, scale_factor: f64) -> LogicalInsets<P> {
|
||||
match *self {
|
||||
Self::Physical(insets) => insets.to_logical(scale_factor),
|
||||
Self::Logical(insets) => insets.cast(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_physical<P: Pixel>(&self, scale_factor: f64) -> PhysicalInsets<P> {
|
||||
match *self {
|
||||
Self::Physical(insets) => insets.cast(),
|
||||
Self::Logical(insets) => insets.to_physical(scale_factor),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<PhysicalInsets<P>> for Insets {
|
||||
#[inline]
|
||||
fn from(insets: PhysicalInsets<P>) -> Self {
|
||||
Self::Physical(insets.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> From<LogicalInsets<P>> for Insets {
|
||||
#[inline]
|
||||
fn from(insets: LogicalInsets<P>) -> Self {
|
||||
Self::Logical(insets.cast())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::*;
|
||||
|
||||
macro_rules! test_pixel_int_impl {
|
||||
($($name:ident => $ty:ty),*) => {$(
|
||||
#[test]
|
||||
@@ -1125,20 +1291,20 @@ mod tests {
|
||||
// Eat coverage for the Debug impls et al
|
||||
#[test]
|
||||
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());
|
||||
|
||||
let _ = format!("{:?}", PhysicalPosition::<u32>::default().clone());
|
||||
let _ = std::format!("{:?}", PhysicalPosition::<u32>::default().clone());
|
||||
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());
|
||||
|
||||
let _ = format!("{:?}", PhysicalSize::<u32>::default().clone());
|
||||
let _ = std::format!("{:?}", PhysicalSize::<u32>::default().clone());
|
||||
HashSet::new().insert(PhysicalSize::<u32>::default());
|
||||
|
||||
let _ = format!("{:?}", Size::Physical((1, 2).into()).clone());
|
||||
let _ = format!("{:?}", Position::Physical((1, 2).into()).clone());
|
||||
let _ = std::format!("{:?}", Size::Physical((1, 2).into()).clone());
|
||||
let _ = std::format!("{:?}", Position::Physical((1, 2).into()).clone());
|
||||
}
|
||||
|
||||
#[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)
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
#[cfg(all(feature = "rwh_06", any(x11_platform, macos_platform, windows_platform)))]
|
||||
#[allow(deprecated)]
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use winit::dpi::{LogicalPosition, LogicalSize, Position};
|
||||
use winit::event::{ElementState, Event, KeyEvent, WindowEvent};
|
||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||
use winit::raw_window_handle::HasRawWindowHandle;
|
||||
use winit::window::Window;
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn spawn_child_window(parent: &Window, event_loop: &ActiveEventLoop) -> Window {
|
||||
let parent = parent.raw_window_handle().unwrap();
|
||||
let mut window_attributes = Window::default_attributes()
|
||||
.with_title("child window")
|
||||
.with_inner_size(LogicalSize::new(200.0f32, 200.0f32))
|
||||
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
||||
.with_visible(true);
|
||||
// `with_parent_window` is unsafe. Parent window must be a valid window.
|
||||
window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) };
|
||||
|
||||
event_loop.create_window(window_attributes).unwrap()
|
||||
}
|
||||
|
||||
let mut windows = HashMap::new();
|
||||
|
||||
let event_loop: EventLoop<()> = EventLoop::new().unwrap();
|
||||
let mut parent_window_id = None;
|
||||
|
||||
event_loop.run(move |event: Event<()>, event_loop| {
|
||||
match event {
|
||||
Event::Resumed => {
|
||||
let attributes = Window::default_attributes()
|
||||
.with_title("parent window")
|
||||
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
||||
.with_inner_size(LogicalSize::new(640.0f32, 480.0f32));
|
||||
let window = event_loop.create_window(attributes).unwrap();
|
||||
|
||||
parent_window_id = Some(window.id());
|
||||
|
||||
println!("Parent window id: {parent_window_id:?})");
|
||||
windows.insert(window.id(), window);
|
||||
},
|
||||
Event::WindowEvent { window_id, event } => match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
windows.clear();
|
||||
event_loop.exit();
|
||||
},
|
||||
WindowEvent::CursorEntered { device_id: _ } => {
|
||||
// On x11, println when the cursor entered in a window even if the child window
|
||||
// is created by some key inputs.
|
||||
// the child windows are always placed at (0, 0) with size (200, 200) in the
|
||||
// parent window, so we also can see this log when we move
|
||||
// the cursor around (200, 200) in parent window.
|
||||
println!("cursor entered in the window {window_id:?}");
|
||||
},
|
||||
WindowEvent::KeyboardInput {
|
||||
event: KeyEvent { state: ElementState::Pressed, .. },
|
||||
..
|
||||
} => {
|
||||
let parent_window = windows.get(&parent_window_id.unwrap()).unwrap();
|
||||
let child_window = spawn_child_window(parent_window, event_loop);
|
||||
let child_id = child_window.id();
|
||||
println!("Child window created with id: {child_id:?}");
|
||||
windows.insert(child_id, child_window);
|
||||
},
|
||||
WindowEvent::RedrawRequested => {
|
||||
if let Some(window) = windows.get(&window_id) {
|
||||
fill::fill_window(window);
|
||||
}
|
||||
},
|
||||
_ => (),
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "rwh_06", not(any(x11_platform, macos_platform, windows_platform))))]
|
||||
fn main() {
|
||||
panic!(
|
||||
"This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature \
|
||||
enabled."
|
||||
);
|
||||
}
|
||||
27
rustfmt.toml
27
rustfmt.toml
@@ -1,19 +1,20 @@
|
||||
format_code_in_doc_comments = true
|
||||
match_block_trailing_comma = true
|
||||
comment_width = 100
|
||||
condense_wildcard_suffixes = true
|
||||
use_field_init_shorthand = true
|
||||
error_on_unformatted = true
|
||||
format_code_in_doc_comments = true
|
||||
format_macro_bodies = true
|
||||
format_macro_matchers = true
|
||||
format_strings = true
|
||||
group_imports = "StdExternalCrate"
|
||||
hex_literal_case = "Lower"
|
||||
imports_granularity = "Module"
|
||||
match_block_trailing_comma = true
|
||||
newline_style = "Unix"
|
||||
normalize_comments = true
|
||||
normalize_doc_attributes = true
|
||||
overflow_delimited_expr = true
|
||||
imports_granularity = "Module"
|
||||
use_small_heuristics = "Max"
|
||||
format_macro_matchers = true
|
||||
error_on_unformatted = true
|
||||
format_macro_bodies = true
|
||||
hex_literal_case = "Lower"
|
||||
normalize_comments = true
|
||||
# Some macros break with this.
|
||||
reorder_impl_items = false
|
||||
newline_style = "Unix"
|
||||
format_strings = true
|
||||
use_field_init_shorthand = true
|
||||
use_small_heuristics = "Max"
|
||||
wrap_comments = true
|
||||
comment_width = 100
|
||||
|
||||
@@ -1,339 +0,0 @@
|
||||
//! End user application handling.
|
||||
|
||||
use crate::event::{DeviceEvent, DeviceId, StartCause, WindowEvent};
|
||||
use crate::event_loop::ActiveEventLoop;
|
||||
use crate::window::WindowId;
|
||||
|
||||
/// The handler of the application events.
|
||||
pub trait ApplicationHandler<T: 'static = ()> {
|
||||
/// Emitted when new events arrive from the OS to be processed.
|
||||
///
|
||||
/// This is a useful place to put code that should be done before you start processing
|
||||
/// events, such as updating frame timing information for benchmarking or checking the
|
||||
/// [`StartCause`] to see if a timer set by
|
||||
/// [`ControlFlow::WaitUntil`][crate::event_loop::ControlFlow::WaitUntil] has elapsed.
|
||||
fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
|
||||
let _ = (event_loop, cause);
|
||||
}
|
||||
|
||||
/// Emitted when the application has been resumed.
|
||||
///
|
||||
/// For consistency, all platforms emit a `Resumed` event even if they don't themselves have a
|
||||
/// formal suspend/resume lifecycle. For systems without a formal suspend/resume lifecycle
|
||||
/// the `Resumed` event is always emitted after the
|
||||
/// [`NewEvents(StartCause::Init)`][StartCause::Init] event.
|
||||
///
|
||||
/// # Portability
|
||||
///
|
||||
/// It's recommended that applications should only initialize their graphics context and create
|
||||
/// a window after they have received their first `Resumed` event. Some systems
|
||||
/// (specifically Android) won't allow applications to create a render surface until they are
|
||||
/// resumed.
|
||||
///
|
||||
/// Considering that the implementation of [`Suspended`] and `Resumed` events may be internally
|
||||
/// driven by multiple platform-specific events, and that there may be subtle differences across
|
||||
/// platforms with how these internal events are delivered, it's recommended that applications
|
||||
/// be able to gracefully handle redundant (i.e. back-to-back) [`Suspended`] or `Resumed`
|
||||
/// events.
|
||||
///
|
||||
/// Also see [`Suspended`] notes.
|
||||
///
|
||||
/// ## Android
|
||||
///
|
||||
/// On Android, the `Resumed` event is sent when a new [`SurfaceView`] has been created. This is
|
||||
/// expected to closely correlate with the [`onResume`] lifecycle event but there may
|
||||
/// technically be a discrepancy.
|
||||
///
|
||||
/// [`onResume`]: https://developer.android.com/reference/android/app/Activity#onResume()
|
||||
///
|
||||
/// Applications that need to run on Android must wait until they have been `Resumed`
|
||||
/// before they will be able to create a render surface (such as an `EGLSurface`,
|
||||
/// [`VkSurfaceKHR`] or [`wgpu::Surface`]) which depend on having a
|
||||
/// [`SurfaceView`]. Applications must also assume that if they are [`Suspended`], then their
|
||||
/// render surfaces are invalid and should be dropped.
|
||||
///
|
||||
/// Also see [`Suspended`] notes.
|
||||
///
|
||||
/// [`SurfaceView`]: https://developer.android.com/reference/android/view/SurfaceView
|
||||
/// [Activity lifecycle]: https://developer.android.com/guide/components/activities/activity-lifecycle
|
||||
/// [`VkSurfaceKHR`]: https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/VkSurfaceKHR.html
|
||||
/// [`wgpu::Surface`]: https://docs.rs/wgpu/latest/wgpu/struct.Surface.html
|
||||
///
|
||||
/// ## iOS
|
||||
///
|
||||
/// On iOS, the `Resumed` event is emitted in response to an [`applicationDidBecomeActive`]
|
||||
/// callback which means the application is "active" (according to the
|
||||
/// [iOS application lifecycle]).
|
||||
///
|
||||
/// [`applicationDidBecomeActive`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622956-applicationdidbecomeactive
|
||||
/// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle
|
||||
///
|
||||
/// ## Web
|
||||
///
|
||||
/// On Web, the `Resumed` event is emitted in response to a [`pageshow`] event
|
||||
/// with the property [`persisted`] being true, which means that the page is being
|
||||
/// restored from the [`bfcache`] (back/forward cache) - an in-memory cache that
|
||||
/// stores a complete snapshot of a page (including the JavaScript heap) as the
|
||||
/// user is navigating away.
|
||||
///
|
||||
/// [`pageshow`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event
|
||||
/// [`persisted`]: https://developer.mozilla.org/en-US/docs/Web/API/PageTransitionEvent/persisted
|
||||
/// [`bfcache`]: https://web.dev/bfcache/
|
||||
/// [`Suspended`]: Self::suspended
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop);
|
||||
|
||||
/// Emitted when an event is sent from [`EventLoopProxy::send_event`].
|
||||
///
|
||||
/// [`EventLoopProxy::send_event`]: crate::event_loop::EventLoopProxy::send_event
|
||||
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: T) {
|
||||
let _ = (event_loop, event);
|
||||
}
|
||||
|
||||
/// Emitted when the OS sends an event to a winit window.
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
);
|
||||
|
||||
/// Emitted when the OS sends an event to a device.
|
||||
fn device_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
device_id: DeviceId,
|
||||
event: DeviceEvent,
|
||||
) {
|
||||
let _ = (event_loop, device_id, event);
|
||||
}
|
||||
|
||||
/// Emitted when the event loop is about to block and wait for new events.
|
||||
///
|
||||
/// Most applications shouldn't need to hook into this event since there is no real relationship
|
||||
/// between how often the event loop needs to wake up and the dispatching of any specific
|
||||
/// events.
|
||||
///
|
||||
/// High frequency event sources, such as input devices could potentially lead to lots of wake
|
||||
/// ups and also lots of corresponding `AboutToWait` events.
|
||||
///
|
||||
/// This is not an ideal event to drive application rendering from and instead applications
|
||||
/// should render in response to [`WindowEvent::RedrawRequested`] events.
|
||||
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let _ = event_loop;
|
||||
}
|
||||
|
||||
/// Emitted when the application has been suspended.
|
||||
///
|
||||
/// # Portability
|
||||
///
|
||||
/// Not all platforms support the notion of suspending applications, and there may be no
|
||||
/// technical way to guarantee being able to emit a `Suspended` event if the OS has
|
||||
/// no formal application lifecycle (currently only Android, iOS, and Web do). For this reason,
|
||||
/// Winit does not currently try to emit pseudo `Suspended` events before the application
|
||||
/// quits on platforms without an application lifecycle.
|
||||
///
|
||||
/// Considering that the implementation of `Suspended` and [`Resumed`] events may be internally
|
||||
/// driven by multiple platform-specific events, and that there may be subtle differences across
|
||||
/// platforms with how these internal events are delivered, it's recommended that applications
|
||||
/// be able to gracefully handle redundant (i.e. back-to-back) `Suspended` or [`Resumed`]
|
||||
/// events.
|
||||
///
|
||||
/// Also see [`Resumed`] notes.
|
||||
///
|
||||
/// ## Android
|
||||
///
|
||||
/// On Android, the `Suspended` event is only sent when the application's associated
|
||||
/// [`SurfaceView`] is destroyed. This is expected to closely correlate with the [`onPause`]
|
||||
/// lifecycle event but there may technically be a discrepancy.
|
||||
///
|
||||
/// [`onPause`]: https://developer.android.com/reference/android/app/Activity#onPause()
|
||||
///
|
||||
/// Applications that need to run on Android should assume their [`SurfaceView`] has been
|
||||
/// destroyed, which indirectly invalidates any existing render surfaces that may have been
|
||||
/// created outside of Winit (such as an `EGLSurface`, [`VkSurfaceKHR`] or [`wgpu::Surface`]).
|
||||
///
|
||||
/// After being `Suspended` on Android applications must drop all render surfaces before
|
||||
/// the event callback completes, which may be re-created when the application is next
|
||||
/// [`Resumed`].
|
||||
///
|
||||
/// [`SurfaceView`]: https://developer.android.com/reference/android/view/SurfaceView
|
||||
/// [Activity lifecycle]: https://developer.android.com/guide/components/activities/activity-lifecycle
|
||||
/// [`VkSurfaceKHR`]: https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/VkSurfaceKHR.html
|
||||
/// [`wgpu::Surface`]: https://docs.rs/wgpu/latest/wgpu/struct.Surface.html
|
||||
///
|
||||
/// ## iOS
|
||||
///
|
||||
/// On iOS, the `Suspended` event is currently emitted in response to an
|
||||
/// [`applicationWillResignActive`] callback which means that the application is
|
||||
/// about to transition from the active to inactive state (according to the
|
||||
/// [iOS application lifecycle]).
|
||||
///
|
||||
/// [`applicationWillResignActive`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622950-applicationwillresignactive
|
||||
/// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle
|
||||
///
|
||||
/// ## Web
|
||||
///
|
||||
/// On Web, the `Suspended` event is emitted in response to a [`pagehide`] event
|
||||
/// with the property [`persisted`] being true, which means that the page is being
|
||||
/// put in the [`bfcache`] (back/forward cache) - an in-memory cache that stores a
|
||||
/// complete snapshot of a page (including the JavaScript heap) as the user is
|
||||
/// navigating away.
|
||||
///
|
||||
/// [`pagehide`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event
|
||||
/// [`persisted`]: https://developer.mozilla.org/en-US/docs/Web/API/PageTransitionEvent/persisted
|
||||
/// [`bfcache`]: https://web.dev/bfcache/
|
||||
/// [`Resumed`]: Self::resumed
|
||||
fn suspended(&mut self, event_loop: &ActiveEventLoop) {
|
||||
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: &ActiveEventLoop) {
|
||||
let _ = event_loop;
|
||||
}
|
||||
|
||||
/// Emitted when the application has received a memory warning.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// ### Android
|
||||
///
|
||||
/// On Android, the `MemoryWarning` event is sent when [`onLowMemory`] was called. The
|
||||
/// application must [release memory] or risk being killed.
|
||||
///
|
||||
/// [`onLowMemory`]: https://developer.android.com/reference/android/app/Application.html#onLowMemory()
|
||||
/// [release memory]: https://developer.android.com/topic/performance/memory#release
|
||||
///
|
||||
/// ### iOS
|
||||
///
|
||||
/// On iOS, the `MemoryWarning` event is emitted in response to an
|
||||
/// [`applicationDidReceiveMemoryWarning`] callback. The application must free as much
|
||||
/// memory as possible or risk being terminated, see [how to respond to memory warnings].
|
||||
///
|
||||
/// [`applicationDidReceiveMemoryWarning`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623063-applicationdidreceivememorywarni
|
||||
/// [how to respond to memory warnings]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle/responding_to_memory_warnings
|
||||
///
|
||||
/// ### Others
|
||||
///
|
||||
/// - **macOS / Orbital / Wayland / Web / Windows:** Unsupported.
|
||||
fn memory_warning(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let _ = event_loop;
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: ?Sized + ApplicationHandler<T>, T: 'static> ApplicationHandler<T> for &mut A {
|
||||
#[inline]
|
||||
fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
|
||||
(**self).new_events(event_loop, cause);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
(**self).resumed(event_loop);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: T) {
|
||||
(**self).user_event(event_loop, event);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
(**self).window_event(event_loop, window_id, event);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn device_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
device_id: DeviceId,
|
||||
event: DeviceEvent,
|
||||
) {
|
||||
(**self).device_event(event_loop, device_id, event);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||
(**self).about_to_wait(event_loop);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn suspended(&mut self, event_loop: &ActiveEventLoop) {
|
||||
(**self).suspended(event_loop);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn exiting(&mut self, event_loop: &ActiveEventLoop) {
|
||||
(**self).exiting(event_loop);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn memory_warning(&mut self, event_loop: &ActiveEventLoop) {
|
||||
(**self).memory_warning(event_loop);
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: ?Sized + ApplicationHandler<T>, T: 'static> ApplicationHandler<T> for Box<A> {
|
||||
#[inline]
|
||||
fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
|
||||
(**self).new_events(event_loop, cause);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
(**self).resumed(event_loop);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: T) {
|
||||
(**self).user_event(event_loop, event);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
(**self).window_event(event_loop, window_id, event);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn device_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
device_id: DeviceId,
|
||||
event: DeviceEvent,
|
||||
) {
|
||||
(**self).device_event(event_loop, device_id, event);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||
(**self).about_to_wait(event_loop);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn suspended(&mut self, event_loop: &ActiveEventLoop) {
|
||||
(**self).suspended(event_loop);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn exiting(&mut self, event_loop: &ActiveEventLoop) {
|
||||
(**self).exiting(event_loop);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn memory_warning(&mut self, event_loop: &ActiveEventLoop) {
|
||||
(**self).memory_warning(event_loop);
|
||||
}
|
||||
}
|
||||
131
src/error.rs
131
src/error.rs
@@ -1,131 +0,0 @@
|
||||
use std::{error, fmt};
|
||||
|
||||
use crate::platform_impl;
|
||||
|
||||
// TODO: Rename
|
||||
/// An error that may be generated when requesting Winit state
|
||||
#[derive(Debug)]
|
||||
pub enum ExternalError {
|
||||
/// The operation is not supported by the backend.
|
||||
NotSupported(NotSupportedError),
|
||||
/// The operation was ignored.
|
||||
Ignored,
|
||||
/// The OS cannot perform the operation.
|
||||
Os(OsError),
|
||||
}
|
||||
|
||||
/// The error type for when the requested operation is not supported by the backend.
|
||||
#[derive(Clone)]
|
||||
pub struct NotSupportedError {
|
||||
_marker: (),
|
||||
}
|
||||
|
||||
/// The error type for when the OS cannot perform the requested operation.
|
||||
#[derive(Debug)]
|
||||
pub struct OsError {
|
||||
line: u32,
|
||||
file: &'static str,
|
||||
error: platform_impl::OsError,
|
||||
}
|
||||
|
||||
/// A general error that may occur while running the Winit event loop
|
||||
#[derive(Debug)]
|
||||
pub enum EventLoopError {
|
||||
/// The operation is not supported by the backend.
|
||||
NotSupported(NotSupportedError),
|
||||
/// The OS cannot perform the operation.
|
||||
Os(OsError),
|
||||
/// The event loop can't be re-created.
|
||||
RecreationAttempt,
|
||||
/// Application has exit with an error status.
|
||||
ExitFailure(i32),
|
||||
}
|
||||
|
||||
impl From<OsError> for EventLoopError {
|
||||
fn from(value: OsError) -> Self {
|
||||
Self::Os(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl NotSupportedError {
|
||||
#[inline]
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn new() -> NotSupportedError {
|
||||
NotSupportedError { _marker: () }
|
||||
}
|
||||
}
|
||||
|
||||
impl OsError {
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn new(line: u32, file: &'static str, error: platform_impl::OsError) -> OsError {
|
||||
OsError { line, file, error }
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(unused_macros)]
|
||||
macro_rules! os_error {
|
||||
($error:expr) => {{
|
||||
crate::error::OsError::new(line!(), file!(), $error)
|
||||
}};
|
||||
}
|
||||
|
||||
impl fmt::Display for OsError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||
f.pad(&format!("os error at {}:{}: {}", self.file, self.line, self.error))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ExternalError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||
match self {
|
||||
ExternalError::NotSupported(e) => e.fmt(f),
|
||||
ExternalError::Ignored => write!(f, "Operation was ignored"),
|
||||
ExternalError::Os(e) => e.fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for NotSupportedError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||
f.debug_struct("NotSupportedError").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for NotSupportedError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||
f.pad("the requested operation is not supported by Winit")
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for EventLoopError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||
match self {
|
||||
EventLoopError::RecreationAttempt => write!(f, "EventLoop can't be recreated"),
|
||||
EventLoopError::NotSupported(e) => e.fmt(f),
|
||||
EventLoopError::Os(e) => e.fmt(f),
|
||||
EventLoopError::ExitFailure(status) => write!(f, "Exit Failure: {status}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl error::Error for OsError {}
|
||||
impl error::Error for ExternalError {}
|
||||
impl error::Error for NotSupportedError {}
|
||||
impl error::Error for EventLoopError {}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::redundant_clone)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Eat attributes for testing
|
||||
#[test]
|
||||
fn ensure_fmt_does_not_panic() {
|
||||
let _ = format!("{:?}, {}", NotSupportedError::new(), NotSupportedError::new().clone());
|
||||
let _ = format!(
|
||||
"{:?}, {}",
|
||||
ExternalError::NotSupported(NotSupportedError::new()),
|
||||
ExternalError::NotSupported(NotSupportedError::new())
|
||||
);
|
||||
}
|
||||
}
|
||||
1183
src/event.rs
1183
src/event.rs
File diff suppressed because it is too large
Load Diff
@@ -1,651 +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
|
||||
//! [`send_event`][EventLoopProxy::send_event] method.
|
||||
//!
|
||||
//! See the root-level documentation for information on how to create and use an event loop to
|
||||
//! handle events.
|
||||
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::{error, fmt};
|
||||
|
||||
#[cfg(not(web_platform))]
|
||||
use std::time::{Duration, Instant};
|
||||
#[cfg(web_platform)]
|
||||
use web_time::{Duration, Instant};
|
||||
|
||||
use crate::application::ApplicationHandler;
|
||||
use crate::error::{EventLoopError, OsError};
|
||||
use crate::event::Event;
|
||||
use crate::monitor::MonitorHandle;
|
||||
use crate::platform_impl;
|
||||
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<T: 'static> {
|
||||
pub(crate) event_loop: platform_impl::EventLoop<T>,
|
||||
pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync
|
||||
}
|
||||
|
||||
/// Target that associates windows with an [`EventLoop`].
|
||||
///
|
||||
/// This type exists to allow you to create new windows while Winit executes
|
||||
/// your callback.
|
||||
pub struct ActiveEventLoop {
|
||||
pub(crate) p: platform_impl::ActiveEventLoop,
|
||||
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::new`] or [`EventLoop::with_user_event`].
|
||||
#[derive(Default)]
|
||||
pub struct EventLoopBuilder<T: 'static> {
|
||||
pub(crate) platform_specific: platform_impl::PlatformSpecificEventLoopAttributes,
|
||||
_p: PhantomData<T>,
|
||||
}
|
||||
|
||||
static EVENT_LOOP_CREATED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
impl EventLoopBuilder<()> {
|
||||
/// Start building a new event loop.
|
||||
#[inline]
|
||||
#[deprecated = "use `EventLoop::builder` instead"]
|
||||
pub fn new() -> Self {
|
||||
EventLoop::builder()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> EventLoopBuilder<T> {
|
||||
/// 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::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<T>, 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<T> fmt::Debug for EventLoop<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.pad("EventLoop { .. }")
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ActiveEventLoop {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.pad("ActiveEventLoop { .. }")
|
||||
}
|
||||
}
|
||||
|
||||
/// Set through [`ActiveEventLoop::set_control_flow()`].
|
||||
///
|
||||
/// Indicates the desired behavior of the event loop after [`Event::AboutToWait`] is emitted.
|
||||
///
|
||||
/// Defaults to [`Wait`].
|
||||
///
|
||||
/// [`Wait`]: Self::Wait
|
||||
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
||||
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<()> {
|
||||
Self::with_user_event()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> EventLoop<T> {
|
||||
/// Start building a new event loop, with the given type as the user event
|
||||
/// type.
|
||||
pub fn with_user_event() -> EventLoopBuilder<T> {
|
||||
EventLoopBuilder { platform_specific: Default::default(), _p: PhantomData }
|
||||
}
|
||||
|
||||
/// See [`run_app`].
|
||||
///
|
||||
/// [`run_app`]: Self::run_app
|
||||
#[inline]
|
||||
#[deprecated = "use `EventLoop::run_app` instead"]
|
||||
#[cfg(not(all(web_platform, target_feature = "exception-handling")))]
|
||||
pub fn run<F>(self, event_handler: F) -> Result<(), EventLoopError>
|
||||
where
|
||||
F: FnMut(Event<T>, &ActiveEventLoop),
|
||||
{
|
||||
let _span = tracing::debug_span!("winit::EventLoop::run").entered();
|
||||
|
||||
self.event_loop.run(event_handler)
|
||||
}
|
||||
|
||||
/// 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(
|
||||
web_platform,
|
||||
doc = "[`EventLoopExtWebSys::spawn_app()`][crate::platform::web::EventLoopExtWebSys::spawn_app()]"
|
||||
)]
|
||||
#[cfg_attr(not(web_platform), doc = "`EventLoopExtWebSys::spawn()`")]
|
||||
/// [^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"`.
|
||||
///
|
||||
/// [`set_control_flow()`]: ActiveEventLoop::set_control_flow()
|
||||
/// [`run_app()`]: Self::run_app()
|
||||
/// [^1]: `EventLoopExtWebSys::spawn_app()` is only available on Web.
|
||||
#[inline]
|
||||
#[cfg(not(all(web_platform, target_feature = "exception-handling")))]
|
||||
pub fn run_app<A: ApplicationHandler<T>>(self, app: &mut A) -> Result<(), EventLoopError> {
|
||||
self.event_loop.run(|event, event_loop| dispatch_event_for_app(app, event_loop, event))
|
||||
}
|
||||
|
||||
/// 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<T> {
|
||||
EventLoopProxy { event_loop_proxy: self.event_loop.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 {
|
||||
OwnedDisplayHandle { platform: self.event_loop.window_target().p.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().p.listen_device_events(allowed);
|
||||
}
|
||||
|
||||
/// Sets the [`ControlFlow`].
|
||||
pub fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||
self.event_loop.window_target().p.set_control_flow(control_flow)
|
||||
}
|
||||
|
||||
/// Create a window.
|
||||
///
|
||||
/// Creating window without event loop running often leads to improper window creation;
|
||||
/// use [`ActiveEventLoop::create_window`] instead.
|
||||
#[deprecated = "use `ActiveEventLoop::create_window` instead"]
|
||||
#[inline]
|
||||
pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> {
|
||||
let _span = tracing::debug_span!(
|
||||
"winit::EventLoop::create_window",
|
||||
window_attributes = ?window_attributes
|
||||
)
|
||||
.entered();
|
||||
|
||||
let window =
|
||||
platform_impl::Window::new(&self.event_loop.window_target().p, window_attributes)?;
|
||||
Ok(Window { window })
|
||||
}
|
||||
|
||||
/// Create custom cursor.
|
||||
pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor {
|
||||
self.event_loop.window_target().p.create_custom_cursor(custom_cursor)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
impl<T> rwh_06::HasDisplayHandle for EventLoop<T> {
|
||||
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||
rwh_06::HasDisplayHandle::display_handle(self.event_loop.window_target())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_05")]
|
||||
unsafe impl<T> rwh_05::HasRawDisplayHandle for EventLoop<T> {
|
||||
/// Returns a [`rwh_05::RawDisplayHandle`] for the event loop.
|
||||
fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
|
||||
rwh_05::HasRawDisplayHandle::raw_display_handle(self.event_loop.window_target())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(x11_platform, wayland_platform))]
|
||||
impl<T> AsFd for EventLoop<T> {
|
||||
/// 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<T> AsRawFd for EventLoop<T> {
|
||||
/// 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()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveEventLoop {
|
||||
/// 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.
|
||||
#[inline]
|
||||
pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> {
|
||||
let _span = tracing::debug_span!(
|
||||
"winit::ActiveEventLoop::create_window",
|
||||
window_attributes = ?window_attributes
|
||||
)
|
||||
.entered();
|
||||
|
||||
let window = platform_impl::Window::new(&self.p, window_attributes)?;
|
||||
Ok(Window { window })
|
||||
}
|
||||
|
||||
/// Create custom cursor.
|
||||
pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor {
|
||||
let _span = tracing::debug_span!("winit::ActiveEventLoop::create_custom_cursor",).entered();
|
||||
|
||||
self.p.create_custom_cursor(custom_cursor)
|
||||
}
|
||||
|
||||
/// Returns the list of all the monitors available on the system.
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
|
||||
let _span = tracing::debug_span!("winit::ActiveEventLoop::available_monitors",).entered();
|
||||
|
||||
#[allow(clippy::useless_conversion)] // false positive on some platforms
|
||||
self.p.available_monitors().into_iter().map(|inner| MonitorHandle { inner })
|
||||
}
|
||||
|
||||
/// Returns the primary monitor of the system.
|
||||
///
|
||||
/// Returns `None` if it can't identify any monitor as a primary one.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// **Wayland / Web:** Always returns `None`.
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||
let _span = tracing::debug_span!("winit::ActiveEventLoop::primary_monitor",).entered();
|
||||
|
||||
self.p.primary_monitor().map(|inner| MonitorHandle { inner })
|
||||
}
|
||||
|
||||
/// 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
|
||||
pub fn listen_device_events(&self, allowed: DeviceEvents) {
|
||||
let _span = tracing::debug_span!(
|
||||
"winit::ActiveEventLoop::listen_device_events",
|
||||
allowed = ?allowed
|
||||
)
|
||||
.entered();
|
||||
|
||||
self.p.listen_device_events(allowed);
|
||||
}
|
||||
|
||||
/// Returns the current system theme.
|
||||
///
|
||||
/// Returns `None` if it cannot be determined on the current platform.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **iOS / Android / Wayland / x11 / Orbital:** Unsupported.
|
||||
pub fn system_theme(&self) -> Option<Theme> {
|
||||
self.p.system_theme()
|
||||
}
|
||||
|
||||
/// Sets the [`ControlFlow`].
|
||||
pub fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||
self.p.set_control_flow(control_flow)
|
||||
}
|
||||
|
||||
/// Gets the current [`ControlFlow`].
|
||||
pub fn control_flow(&self) -> ControlFlow {
|
||||
self.p.control_flow()
|
||||
}
|
||||
|
||||
/// This exits the event loop.
|
||||
///
|
||||
/// See [`LoopExiting`][Event::LoopExiting].
|
||||
pub fn exit(&self) {
|
||||
let _span = tracing::debug_span!("winit::ActiveEventLoop::exit",).entered();
|
||||
|
||||
self.p.exit()
|
||||
}
|
||||
|
||||
/// Returns if the [`EventLoop`] is about to stop.
|
||||
///
|
||||
/// See [`exit()`][Self::exit].
|
||||
pub fn exiting(&self) -> bool {
|
||||
self.p.exiting()
|
||||
}
|
||||
|
||||
/// Gets a persistent reference to the underlying platform display.
|
||||
///
|
||||
/// See the [`OwnedDisplayHandle`] type for more information.
|
||||
pub fn owned_display_handle(&self) -> OwnedDisplayHandle {
|
||||
OwnedDisplayHandle { platform: self.p.owned_display_handle() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
impl rwh_06::HasDisplayHandle for ActiveEventLoop {
|
||||
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||
let raw = self.p.raw_display_handle_rwh_06()?;
|
||||
// SAFETY: The display will never be deallocated while the event loop is alive.
|
||||
Ok(unsafe { rwh_06::DisplayHandle::borrow_raw(raw) })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_05")]
|
||||
unsafe impl rwh_05::HasRawDisplayHandle for ActiveEventLoop {
|
||||
/// Returns a [`rwh_05::RawDisplayHandle`] for the event loop.
|
||||
fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
|
||||
self.p.raw_display_handle_rwh_05()
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
#[cfg_attr(not(any(feature = "rwh_05", feature = "rwh_06")), allow(dead_code))]
|
||||
platform: platform_impl::OwnedDisplayHandle,
|
||||
}
|
||||
|
||||
impl fmt::Debug for OwnedDisplayHandle {
|
||||
#[inline]
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("OwnedDisplayHandle").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
impl rwh_06::HasDisplayHandle for OwnedDisplayHandle {
|
||||
#[inline]
|
||||
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||
let raw = self.platform.raw_display_handle_rwh_06()?;
|
||||
|
||||
// SAFETY: The underlying display handle should be safe.
|
||||
let handle = unsafe { rwh_06::DisplayHandle::borrow_raw(raw) };
|
||||
|
||||
Ok(handle)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_05")]
|
||||
unsafe impl rwh_05::HasRawDisplayHandle for OwnedDisplayHandle {
|
||||
#[inline]
|
||||
fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
|
||||
self.platform.raw_display_handle_rwh_05()
|
||||
}
|
||||
}
|
||||
|
||||
/// Used to send custom events to [`EventLoop`].
|
||||
pub struct EventLoopProxy<T: 'static> {
|
||||
event_loop_proxy: platform_impl::EventLoopProxy<T>,
|
||||
}
|
||||
|
||||
impl<T: 'static> Clone for EventLoopProxy<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self { event_loop_proxy: self.event_loop_proxy.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> EventLoopProxy<T> {
|
||||
/// Send an event to the [`EventLoop`] from which this proxy was created. This emits a
|
||||
/// `UserEvent(event)` event in the event loop, where `event` is the value passed to this
|
||||
/// function.
|
||||
///
|
||||
/// Returns an `Err` if the associated [`EventLoop`] no longer exists.
|
||||
///
|
||||
/// [`UserEvent(event)`]: Event::UserEvent
|
||||
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
|
||||
let _span = tracing::debug_span!("winit::EventLoopProxy::send_event",).entered();
|
||||
|
||||
self.event_loop_proxy.send_event(event)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> fmt::Debug for EventLoopProxy<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.pad("EventLoopProxy { .. }")
|
||||
}
|
||||
}
|
||||
|
||||
/// The error that is returned when an [`EventLoopProxy`] attempts to wake up an [`EventLoop`] that
|
||||
/// no longer exists.
|
||||
///
|
||||
/// Contains the original event given to [`EventLoopProxy::send_event`].
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct EventLoopClosed<T>(pub T);
|
||||
|
||||
impl<T> fmt::Display for EventLoopClosed<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("Tried to wake up a closed `EventLoop`")
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Debug> error::Error for EventLoopClosed<T> {}
|
||||
|
||||
/// Control when device events are captured.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
|
||||
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)]
|
||||
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 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Shim for various run APIs.
|
||||
#[inline(always)]
|
||||
pub(crate) fn dispatch_event_for_app<T: 'static, A: ApplicationHandler<T>>(
|
||||
app: &mut A,
|
||||
event_loop: &ActiveEventLoop,
|
||||
event: Event<T>,
|
||||
) {
|
||||
match event {
|
||||
Event::NewEvents(cause) => app.new_events(event_loop, cause),
|
||||
Event::WindowEvent { window_id, event } => app.window_event(event_loop, window_id, event),
|
||||
Event::DeviceEvent { device_id, event } => app.device_event(event_loop, device_id, event),
|
||||
Event::UserEvent(event) => app.user_event(event_loop, event),
|
||||
Event::Suspended => app.suspended(event_loop),
|
||||
Event::Resumed => app.resumed(event_loop),
|
||||
Event::AboutToWait => app.about_to_wait(event_loop),
|
||||
Event::LoopExiting => app.exiting(event_loop),
|
||||
Event::MemoryWarning => app.memory_warning(event_loop),
|
||||
}
|
||||
}
|
||||
117
src/icon.rs
117
src/icon.rs
@@ -1,117 +0,0 @@
|
||||
use crate::platform_impl::PlatformIcon;
|
||||
use std::error::Error;
|
||||
use std::{fmt, io, mem};
|
||||
|
||||
#[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)]
|
||||
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)]
|
||||
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)]
|
||||
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)? })
|
||||
}
|
||||
}
|
||||
1804
src/keyboard.rs
1804
src/keyboard.rs
File diff suppressed because it is too large
Load Diff
215
src/lib.rs
215
src/lib.rs
@@ -1,215 +0,0 @@
|
||||
//! Winit is a cross-platform window creation and event loop management library.
|
||||
//!
|
||||
//! # Building windows
|
||||
//!
|
||||
//! Before you can create a [`Window`], you first need to build an [`EventLoop`]. This is done with
|
||||
//! the [`EventLoop::new()`] function.
|
||||
//!
|
||||
//! ```no_run
|
||||
//! use winit::event_loop::EventLoop;
|
||||
//!
|
||||
//! # // Intentionally use `fn main` for clarity
|
||||
//! fn main() {
|
||||
//! let event_loop = EventLoop::new().unwrap();
|
||||
//! // ...
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! Then you create a [`Window`] with [`create_window`].
|
||||
//!
|
||||
//! # Event handling
|
||||
//!
|
||||
//! Once a [`Window`] has been created, it will generate different *events*. A [`Window`] object can
|
||||
//! generate [`WindowEvent`]s when certain input events occur, such as a cursor moving over the
|
||||
//! window or a key getting pressed while the window is focused. Devices can generate
|
||||
//! [`DeviceEvent`]s, which contain unfiltered event data that isn't specific to a certain window.
|
||||
//! Some user activity, like mouse movement, can generate both a [`WindowEvent`] *and* a
|
||||
//! [`DeviceEvent`]. You can also create and handle your own custom [`Event::UserEvent`]s, if
|
||||
//! desired.
|
||||
//!
|
||||
//! You can retrieve events by calling [`EventLoop::run_app()`]. This function will
|
||||
//! dispatch events for every [`Window`] that was created with that particular [`EventLoop`], and
|
||||
//! will run until [`exit()`] is used, at which point [`Event::LoopExiting`].
|
||||
//!
|
||||
//! Winit no longer uses a `EventLoop::poll_events() -> impl Iterator<Event>`-based event loop
|
||||
//! model, since that can't be implemented properly on some platforms (e.g web, iOS) and works
|
||||
//! poorly on most other platforms. However, this model can be re-implemented to an extent with
|
||||
#![cfg_attr(
|
||||
any(windows_platform, macos_platform, android_platform, x11_platform, wayland_platform),
|
||||
doc = "[`EventLoopExtPumpEvents::pump_app_events()`][platform::pump_events::EventLoopExtPumpEvents::pump_app_events()]"
|
||||
)]
|
||||
#![cfg_attr(
|
||||
not(any(windows_platform, macos_platform, android_platform, x11_platform, wayland_platform)),
|
||||
doc = "`EventLoopExtPumpEvents::pump_app_events()`"
|
||||
)]
|
||||
//! [^1]. See that method's documentation for more reasons about why
|
||||
//! it's discouraged beyond compatibility reasons.
|
||||
//!
|
||||
//!
|
||||
//! ```no_run
|
||||
//! use winit::application::ApplicationHandler;
|
||||
//! use winit::event::WindowEvent;
|
||||
//! use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||
//! use winit::window::{Window, WindowId};
|
||||
//!
|
||||
//! #[derive(Default)]
|
||||
//! struct App {
|
||||
//! window: Option<Window>,
|
||||
//! }
|
||||
//!
|
||||
//! impl ApplicationHandler for App {
|
||||
//! fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
//! self.window = Some(event_loop.create_window(Window::default_attributes()).unwrap());
|
||||
//! }
|
||||
//!
|
||||
//! fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
|
||||
//! match event {
|
||||
//! WindowEvent::CloseRequested => {
|
||||
//! println!("The close button was pressed; stopping");
|
||||
//! event_loop.exit();
|
||||
//! },
|
||||
//! WindowEvent::RedrawRequested => {
|
||||
//! // Redraw the application.
|
||||
//! //
|
||||
//! // It's preferable for applications that do not render continuously to render in
|
||||
//! // this event rather than in AboutToWait, since rendering in here allows
|
||||
//! // the program to gracefully handle redraws requested by the OS.
|
||||
//!
|
||||
//! // Draw.
|
||||
//!
|
||||
//! // Queue a RedrawRequested event.
|
||||
//! //
|
||||
//! // You only need to call this if you've determined that you need to redraw in
|
||||
//! // applications which do not always need to. Applications that redraw continuously
|
||||
//! // can render here instead.
|
||||
//! self.window.as_ref().unwrap().request_redraw();
|
||||
//! }
|
||||
//! _ => (),
|
||||
//! }
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! # // Intentionally use `fn main` for clarity
|
||||
//! fn main() {
|
||||
//! let event_loop = EventLoop::new().unwrap();
|
||||
//!
|
||||
//! // ControlFlow::Poll continuously runs the event loop, even if the OS hasn't
|
||||
//! // dispatched any events. This is ideal for games and similar applications.
|
||||
//! event_loop.set_control_flow(ControlFlow::Poll);
|
||||
//!
|
||||
//! // ControlFlow::Wait pauses the event loop if no events are available to process.
|
||||
//! // This is ideal for non-game applications that only update in response to user
|
||||
//! // input, and uses significantly less power/CPU time than ControlFlow::Poll.
|
||||
//! event_loop.set_control_flow(ControlFlow::Wait);
|
||||
//!
|
||||
//! let mut app = App::default();
|
||||
//! event_loop.run_app(&mut app);
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! [`WindowEvent`] has a [`WindowId`] member. In multi-window environments, it should be
|
||||
//! compared to the value returned by [`Window::id()`] to determine which [`Window`]
|
||||
//! dispatched the event.
|
||||
//!
|
||||
//! # Drawing on the window
|
||||
//!
|
||||
//! Winit doesn't directly provide any methods for drawing on a [`Window`]. However, it allows you
|
||||
//! to retrieve the raw handle of the window and display (see the [`platform`] module and/or the
|
||||
//! [`raw_window_handle`] and [`raw_display_handle`] methods), which in turn allows
|
||||
//! you to create an OpenGL/Vulkan/DirectX/Metal/etc. context that can be used to render graphics.
|
||||
//!
|
||||
//! Note that many platforms will display garbage data in the window's client area if the
|
||||
//! application doesn't render anything to the window by the time the desktop compositor is ready to
|
||||
//! display the window to the user. If you notice this happening, you should create the window with
|
||||
//! [`visible` set to `false`][crate::window::WindowAttributes::with_visible] and explicitly make
|
||||
//! the window visible only once you're ready to render into it.
|
||||
//!
|
||||
//! # UI scaling
|
||||
//!
|
||||
//! UI scaling is important, go read the docs for the [`dpi`] crate for an
|
||||
//! introduction.
|
||||
//!
|
||||
//! All of Winit's functions return physical types, but can take either logical or physical
|
||||
//! coordinates as input, allowing you to use the most convenient coordinate system for your
|
||||
//! particular application.
|
||||
//!
|
||||
//! Winit will dispatch a [`ScaleFactorChanged`] event whenever a window's scale factor has changed.
|
||||
//! This can happen if the user drags their window from a standard-resolution monitor to a high-DPI
|
||||
//! monitor or if the user changes their DPI settings. This allows you to rescale your application's
|
||||
//! UI elements and adjust how the platform changes the window's size to reflect the new scale
|
||||
//! factor. If a window hasn't received a [`ScaleFactorChanged`] event, its scale factor
|
||||
//! can be found by calling [`window.scale_factor()`].
|
||||
//!
|
||||
//! [`ScaleFactorChanged`]: event::WindowEvent::ScaleFactorChanged
|
||||
//! [`window.scale_factor()`]: window::Window::scale_factor
|
||||
//!
|
||||
//! # Cargo Features
|
||||
//!
|
||||
//! Winit provides the following Cargo features:
|
||||
//!
|
||||
//! * `x11` (enabled by default): On Unix platforms, enables the X11 backend.
|
||||
//! * `wayland` (enabled by default): On Unix platforms, enables the Wayland backend.
|
||||
//! * `rwh_04`: Implement `raw-window-handle v0.4` traits.
|
||||
//! * `rwh_05`: Implement `raw-window-handle v0.5` traits.
|
||||
//! * `rwh_06`: Implement `raw-window-handle v0.6` traits.
|
||||
//! * `serde`: Enables serialization/deserialization of certain types with [Serde](https://crates.io/crates/serde).
|
||||
//! * `mint`: Enables mint (math interoperability standard types) conversions.
|
||||
//!
|
||||
//! See the [`platform`] module for documentation on platform-specific cargo
|
||||
//! features.
|
||||
//!
|
||||
//! [`EventLoop`]: event_loop::EventLoop
|
||||
//! [`EventLoop::new()`]: event_loop::EventLoop::new
|
||||
//! [`EventLoop::run_app()`]: event_loop::EventLoop::run_app
|
||||
//! [`exit()`]: event_loop::ActiveEventLoop::exit
|
||||
//! [`Window`]: window::Window
|
||||
//! [`WindowId`]: window::WindowId
|
||||
//! [`WindowAttributes`]: window::WindowAttributes
|
||||
//! [window_new]: window::Window::new
|
||||
//! [`create_window`]: event_loop::ActiveEventLoop::create_window
|
||||
//! [`Window::id()`]: window::Window::id
|
||||
//! [`WindowEvent`]: event::WindowEvent
|
||||
//! [`DeviceEvent`]: event::DeviceEvent
|
||||
//! [`Event::UserEvent`]: event::Event::UserEvent
|
||||
//! [`Event::LoopExiting`]: event::Event::LoopExiting
|
||||
//! [`raw_window_handle`]: ./window/struct.Window.html#method.raw_window_handle
|
||||
//! [`raw_display_handle`]: ./window/struct.Window.html#method.raw_display_handle
|
||||
//! [^1]: `EventLoopExtPumpEvents::pump_app_events()` is only available on Windows, macOS, Android, X11 and Wayland.
|
||||
|
||||
#![deny(rust_2018_idioms)]
|
||||
#![deny(rustdoc::broken_intra_doc_links)]
|
||||
#![deny(clippy::all)]
|
||||
#![deny(unsafe_op_in_unsafe_fn)]
|
||||
#![cfg_attr(clippy, deny(warnings))]
|
||||
// Doc feature labels can be tested locally by running RUSTDOCFLAGS="--cfg=docsrs" cargo +nightly
|
||||
// doc
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide), doc(cfg_hide(doc, docsrs)))]
|
||||
#![allow(clippy::missing_safety_doc)]
|
||||
|
||||
#[cfg(feature = "rwh_04")]
|
||||
pub use rwh_04 as raw_window_handle_04;
|
||||
#[cfg(feature = "rwh_05")]
|
||||
pub use rwh_05 as raw_window_handle_05;
|
||||
#[cfg(feature = "rwh_06")]
|
||||
pub use rwh_06 as raw_window_handle;
|
||||
|
||||
// Re-export DPI types so that users don't have to put it in Cargo.toml.
|
||||
#[doc(inline)]
|
||||
pub use dpi;
|
||||
|
||||
pub mod application;
|
||||
#[cfg(any(doc, doctest, test))]
|
||||
pub mod changelog;
|
||||
#[macro_use]
|
||||
pub mod error;
|
||||
mod cursor;
|
||||
pub mod event;
|
||||
pub mod event_loop;
|
||||
mod icon;
|
||||
pub mod keyboard;
|
||||
pub mod monitor;
|
||||
mod platform_impl;
|
||||
mod utils;
|
||||
pub mod window;
|
||||
|
||||
pub mod platform;
|
||||
167
src/monitor.rs
167
src/monitor.rs
@@ -1,167 +0,0 @@
|
||||
//! Types useful for interacting with a user's monitors.
|
||||
//!
|
||||
//! If you want to get basic information about a monitor, you can use the
|
||||
//! [`MonitorHandle`] type. This is retrieved from one of the following
|
||||
//! methods, which return an iterator of [`MonitorHandle`]:
|
||||
//! - [`ActiveEventLoop::available_monitors`][crate::event_loop::ActiveEventLoop::available_monitors].
|
||||
//! - [`Window::available_monitors`][crate::window::Window::available_monitors].
|
||||
use crate::dpi::{PhysicalPosition, PhysicalSize};
|
||||
use crate::platform_impl;
|
||||
|
||||
/// Deprecated! Use `VideoModeHandle` instead.
|
||||
#[deprecated = "Renamed to `VideoModeHandle`"]
|
||||
pub type VideoMode = VideoModeHandle;
|
||||
|
||||
/// Describes a fullscreen video mode of a monitor.
|
||||
///
|
||||
/// 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.
|
||||
#[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.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **Wayland / Orbital:** Always returns 32.
|
||||
/// - **iOS:** Always returns 32.
|
||||
#[inline]
|
||||
pub fn bit_depth(&self) -> u16 {
|
||||
self.video_mode.bit_depth()
|
||||
}
|
||||
|
||||
/// Returns the refresh rate of this video mode in mHz.
|
||||
#[inline]
|
||||
pub fn refresh_rate_millihertz(&self) -> u32 {
|
||||
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{} @ {} mHz ({} bpp)",
|
||||
self.size().width,
|
||||
self.size().height,
|
||||
self.refresh_rate_millihertz(),
|
||||
self.bit_depth()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle to a monitor.
|
||||
///
|
||||
/// Allows you to retrieve information about a given monitor and can be used in [`Window`] creation.
|
||||
///
|
||||
/// [`Window`]: crate::window::Window
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct MonitorHandle {
|
||||
pub(crate) inner: platform_impl::MonitorHandle,
|
||||
}
|
||||
|
||||
impl MonitorHandle {
|
||||
/// Returns a human-readable name of the monitor.
|
||||
///
|
||||
/// Returns `None` if the monitor doesn't exist anymore.
|
||||
#[inline]
|
||||
pub fn name(&self) -> Option<String> {
|
||||
self.inner.name()
|
||||
}
|
||||
|
||||
/// Returns the monitor's resolution.
|
||||
#[inline]
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
self.inner.size()
|
||||
}
|
||||
|
||||
/// Returns the top-left corner position of the monitor relative to the larger full
|
||||
/// screen area.
|
||||
#[inline]
|
||||
pub fn position(&self) -> PhysicalPosition<i32> {
|
||||
self.inner.position()
|
||||
}
|
||||
|
||||
/// The monitor refresh rate used by the system.
|
||||
///
|
||||
/// Return `Some` if succeed, or `None` if failed, which usually happens when the monitor
|
||||
/// the window is on is removed.
|
||||
///
|
||||
/// When using exclusive fullscreen, the refresh rate of the [`VideoModeHandle`] that was
|
||||
/// used to enter fullscreen should be used instead.
|
||||
#[inline]
|
||||
pub fn refresh_rate_millihertz(&self) -> Option<u32> {
|
||||
self.inner.refresh_rate_millihertz()
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// [`Window::scale_factor`]: crate::window::Window::scale_factor
|
||||
#[inline]
|
||||
pub fn scale_factor(&self) -> f64 {
|
||||
self.inner.scale_factor()
|
||||
}
|
||||
|
||||
/// Returns all fullscreen video modes supported by this monitor.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **Web:** Always returns an empty iterator
|
||||
#[inline]
|
||||
pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> {
|
||||
self.inner.video_modes().map(|video_mode| VideoModeHandle { video_mode })
|
||||
}
|
||||
}
|
||||
@@ -1,461 +0,0 @@
|
||||
//! # macOS / AppKit
|
||||
//!
|
||||
//! Winit has an OS requirement of macOS 10.11 or higher (same as Rust
|
||||
//! itself), and is regularly tested on macOS 10.14.
|
||||
//!
|
||||
//! A lot of functionality expects the application to be ready before you
|
||||
//! start doing anything; this includes creating windows, fetching monitors,
|
||||
//! drawing, and so on, see issues [#2238], [#2051] and [#2087].
|
||||
//!
|
||||
//! If you encounter problems, you should try doing your initialization inside
|
||||
//! `Event::Resumed`.
|
||||
//!
|
||||
//! [#2238]: https://github.com/rust-windowing/winit/issues/2238
|
||||
//! [#2051]: https://github.com/rust-windowing/winit/issues/2051
|
||||
//! [#2087]: https://github.com/rust-windowing/winit/issues/2087
|
||||
|
||||
use std::os::raw::c_void;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::event_loop::{ActiveEventLoop, EventLoopBuilder};
|
||||
use crate::monitor::MonitorHandle;
|
||||
use crate::window::{Window, WindowAttributes};
|
||||
|
||||
/// Additional methods on [`Window`] that are specific to MacOS.
|
||||
pub trait WindowExtMacOS {
|
||||
/// Returns whether or not the window is in simple fullscreen mode.
|
||||
fn simple_fullscreen(&self) -> bool;
|
||||
|
||||
/// Toggles a fullscreen mode that doesn't require a new macOS space.
|
||||
/// Returns a boolean indicating whether the transition was successful (this
|
||||
/// won't work if the window was already in the native fullscreen).
|
||||
///
|
||||
/// This is how fullscreen used to work on macOS in versions before Lion.
|
||||
/// And allows the user to have a fullscreen window without using another
|
||||
/// space or taking control over the entire monitor.
|
||||
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool;
|
||||
|
||||
/// Returns whether or not the window has shadow.
|
||||
fn has_shadow(&self) -> bool;
|
||||
|
||||
/// Sets whether or not the window has shadow.
|
||||
fn set_has_shadow(&self, has_shadow: bool);
|
||||
|
||||
/// Group windows together by using the same tabbing identifier.
|
||||
///
|
||||
/// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
|
||||
fn set_tabbing_identifier(&self, identifier: &str);
|
||||
|
||||
/// Returns the window's tabbing identifier.
|
||||
fn tabbing_identifier(&self) -> String;
|
||||
|
||||
/// Select next tab.
|
||||
fn select_next_tab(&self);
|
||||
|
||||
/// Select previous tab.
|
||||
fn select_previous_tab(&self);
|
||||
|
||||
/// Select the tab with the given index.
|
||||
///
|
||||
/// Will no-op when the index is out of bounds.
|
||||
fn select_tab_at_index(&self, index: usize);
|
||||
|
||||
/// Get the number of tabs in the window tab group.
|
||||
fn num_tabs(&self) -> usize;
|
||||
|
||||
/// Get the window's edit state.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```ignore
|
||||
/// WindowEvent::CloseRequested => {
|
||||
/// if window.is_document_edited() {
|
||||
/// // Show the user a save pop-up or similar
|
||||
/// } else {
|
||||
/// // Close the window
|
||||
/// drop(window);
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
fn is_document_edited(&self) -> bool;
|
||||
|
||||
/// Put the window in a state which indicates a file save is required.
|
||||
fn set_document_edited(&self, edited: bool);
|
||||
|
||||
/// Set option as alt behavior as described in [`OptionAsAlt`].
|
||||
///
|
||||
/// This will ignore diacritical marks and accent characters from
|
||||
/// being processed as received characters. Instead, the input
|
||||
/// device's raw character will be placed in event queues with the
|
||||
/// Alt modifier set.
|
||||
fn set_option_as_alt(&self, option_as_alt: OptionAsAlt);
|
||||
|
||||
/// Getter for the [`WindowExtMacOS::set_option_as_alt`].
|
||||
fn option_as_alt(&self) -> OptionAsAlt;
|
||||
|
||||
/// Disable the Menu Bar and Dock in Borderless Fullscreen mode. Useful for games.
|
||||
fn set_borderless_game(&self, borderless_game: bool);
|
||||
|
||||
/// Getter for the [`WindowExtMacOS::set_borderless_game`].
|
||||
fn is_borderless_game(&self) -> bool;
|
||||
}
|
||||
|
||||
impl WindowExtMacOS for Window {
|
||||
#[inline]
|
||||
fn simple_fullscreen(&self) -> bool {
|
||||
self.window.maybe_wait_on_main(|w| w.simple_fullscreen())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool {
|
||||
self.window.maybe_wait_on_main(move |w| w.set_simple_fullscreen(fullscreen))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn has_shadow(&self) -> bool {
|
||||
self.window.maybe_wait_on_main(|w| w.has_shadow())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_has_shadow(&self, has_shadow: bool) {
|
||||
self.window.maybe_queue_on_main(move |w| w.set_has_shadow(has_shadow))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_tabbing_identifier(&self, identifier: &str) {
|
||||
self.window.maybe_wait_on_main(|w| w.set_tabbing_identifier(identifier))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn tabbing_identifier(&self) -> String {
|
||||
self.window.maybe_wait_on_main(|w| w.tabbing_identifier())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn select_next_tab(&self) {
|
||||
self.window.maybe_queue_on_main(|w| w.select_next_tab())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn select_previous_tab(&self) {
|
||||
self.window.maybe_queue_on_main(|w| w.select_previous_tab())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn select_tab_at_index(&self, index: usize) {
|
||||
self.window.maybe_queue_on_main(move |w| w.select_tab_at_index(index))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn num_tabs(&self) -> usize {
|
||||
self.window.maybe_wait_on_main(|w| w.num_tabs())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_document_edited(&self) -> bool {
|
||||
self.window.maybe_wait_on_main(|w| w.is_document_edited())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_document_edited(&self, edited: bool) {
|
||||
self.window.maybe_queue_on_main(move |w| w.set_document_edited(edited))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) {
|
||||
self.window.maybe_queue_on_main(move |w| w.set_option_as_alt(option_as_alt))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn option_as_alt(&self) -> OptionAsAlt {
|
||||
self.window.maybe_wait_on_main(|w| w.option_as_alt())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_borderless_game(&self, borderless_game: bool) {
|
||||
self.window.maybe_wait_on_main(|w| w.set_borderless_game(borderless_game))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_borderless_game(&self) -> bool {
|
||||
self.window.maybe_wait_on_main(|w| w.is_borderless_game())
|
||||
}
|
||||
}
|
||||
|
||||
/// Corresponds to `NSApplicationActivationPolicy`.
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum ActivationPolicy {
|
||||
/// Corresponds to `NSApplicationActivationPolicyRegular`.
|
||||
#[default]
|
||||
Regular,
|
||||
|
||||
/// Corresponds to `NSApplicationActivationPolicyAccessory`.
|
||||
Accessory,
|
||||
|
||||
/// Corresponds to `NSApplicationActivationPolicyProhibited`.
|
||||
Prohibited,
|
||||
}
|
||||
|
||||
/// Additional methods on [`WindowAttributes`] that are specific to MacOS.
|
||||
///
|
||||
/// **Note:** Properties dealing with the titlebar will be overwritten by the
|
||||
/// [`WindowAttributes::with_decorations`] method:
|
||||
/// - `with_titlebar_transparent`
|
||||
/// - `with_title_hidden`
|
||||
/// - `with_titlebar_hidden`
|
||||
/// - `with_titlebar_buttons_hidden`
|
||||
/// - `with_fullsize_content_view`
|
||||
pub trait WindowAttributesExtMacOS {
|
||||
/// 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;
|
||||
/// Makes the titlebar transparent and allows the content to appear behind it.
|
||||
fn with_titlebar_transparent(self, titlebar_transparent: bool) -> Self;
|
||||
/// Hides the window title.
|
||||
fn with_title_hidden(self, title_hidden: bool) -> Self;
|
||||
/// Hides the window titlebar.
|
||||
fn with_titlebar_hidden(self, titlebar_hidden: bool) -> Self;
|
||||
/// Hides the window titlebar buttons.
|
||||
fn with_titlebar_buttons_hidden(self, titlebar_buttons_hidden: bool) -> Self;
|
||||
/// Makes the window content appear behind the titlebar.
|
||||
fn with_fullsize_content_view(self, fullsize_content_view: bool) -> Self;
|
||||
fn with_disallow_hidpi(self, disallow_hidpi: bool) -> Self;
|
||||
fn with_has_shadow(self, has_shadow: bool) -> Self;
|
||||
/// Window accepts click-through mouse events.
|
||||
fn with_accepts_first_mouse(self, accepts_first_mouse: bool) -> Self;
|
||||
/// Defines the window tabbing identifier.
|
||||
///
|
||||
/// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
|
||||
fn with_tabbing_identifier(self, identifier: &str) -> Self;
|
||||
/// Set how the <kbd>Option</kbd> keys are interpreted.
|
||||
///
|
||||
/// 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;
|
||||
/// See [`WindowExtMacOS::set_borderless_game`] for details on what this means if set.
|
||||
fn with_borderless_game(self, borderless_game: bool) -> Self;
|
||||
}
|
||||
|
||||
impl WindowAttributesExtMacOS for WindowAttributes {
|
||||
#[inline]
|
||||
fn with_movable_by_window_background(mut self, movable_by_window_background: bool) -> Self {
|
||||
self.platform_specific.movable_by_window_background = movable_by_window_background;
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> Self {
|
||||
self.platform_specific.titlebar_transparent = titlebar_transparent;
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
pub trait EventLoopBuilderExtMacOS {
|
||||
/// Sets the activation policy for the application. If used, this will override
|
||||
/// any relevant settings provided in the package manifest.
|
||||
/// For instance, `with_activation_policy(ActivationPolicy::Regular)` will prevent
|
||||
/// the application from running as an "agent", even if LSUIElement is set to true.
|
||||
///
|
||||
/// If unused, the Winit will honor the package manifest.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// Set the activation policy to "accessory".
|
||||
///
|
||||
/// ```
|
||||
/// use winit::event_loop::EventLoopBuilder;
|
||||
/// #[cfg(target_os = "macos")]
|
||||
/// use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS};
|
||||
///
|
||||
/// let mut builder = EventLoopBuilder::new();
|
||||
/// #[cfg(target_os = "macos")]
|
||||
/// builder.with_activation_policy(ActivationPolicy::Accessory);
|
||||
/// # if false { // We can't test this part
|
||||
/// let event_loop = builder.build();
|
||||
/// # }
|
||||
/// ```
|
||||
fn with_activation_policy(&mut self, activation_policy: ActivationPolicy) -> &mut Self;
|
||||
|
||||
/// Used to control whether a default menubar menu is created.
|
||||
///
|
||||
/// Menu creation is enabled by default.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// Disable creating a default menubar.
|
||||
///
|
||||
/// ```
|
||||
/// use winit::event_loop::EventLoopBuilder;
|
||||
/// #[cfg(target_os = "macos")]
|
||||
/// use winit::platform::macos::EventLoopBuilderExtMacOS;
|
||||
///
|
||||
/// let mut builder = EventLoopBuilder::new();
|
||||
/// #[cfg(target_os = "macos")]
|
||||
/// builder.with_default_menu(false);
|
||||
/// # if false { // We can't test this part
|
||||
/// let event_loop = builder.build();
|
||||
/// # }
|
||||
/// ```
|
||||
fn with_default_menu(&mut self, enable: bool) -> &mut Self;
|
||||
|
||||
/// Used to prevent the application from automatically activating when launched if
|
||||
/// another application is already active.
|
||||
///
|
||||
/// The default behavior is to ignore other applications and activate when launched.
|
||||
fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self;
|
||||
}
|
||||
|
||||
impl<T> EventLoopBuilderExtMacOS for EventLoopBuilder<T> {
|
||||
#[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.
|
||||
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.
|
||||
fn ns_screen(&self) -> Option<*mut c_void>;
|
||||
}
|
||||
|
||||
impl MonitorHandleExtMacOS for MonitorHandle {
|
||||
#[inline]
|
||||
fn native_id(&self) -> u32 {
|
||||
self.inner.native_identifier()
|
||||
}
|
||||
|
||||
fn ns_screen(&self) -> Option<*mut c_void> {
|
||||
// SAFETY: We only use the marker to get a pointer
|
||||
let mtm = unsafe { objc2_foundation::MainThreadMarker::new_unchecked() };
|
||||
self.inner.ns_screen(mtm).map(|s| objc2::rc::Retained::as_ptr(&s) as _)
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional methods on [`ActiveEventLoop`] that are specific to macOS.
|
||||
pub trait ActiveEventLoopExtMacOS {
|
||||
/// Hide the entire application. In most applications this is typically triggered with
|
||||
/// Command-H.
|
||||
fn hide_application(&self);
|
||||
/// Hide the other applications. In most applications this is typically triggered with
|
||||
/// Command+Option-H.
|
||||
fn hide_other_applications(&self);
|
||||
/// Set whether the system can automatically organize windows into tabs.
|
||||
///
|
||||
/// <https://developer.apple.com/documentation/appkit/nswindow/1646657-allowsautomaticwindowtabbing>
|
||||
fn set_allows_automatic_window_tabbing(&self, enabled: bool);
|
||||
/// Returns whether the system can automatically organize windows into tabs.
|
||||
fn allows_automatic_window_tabbing(&self) -> bool;
|
||||
}
|
||||
|
||||
impl ActiveEventLoopExtMacOS for ActiveEventLoop {
|
||||
fn hide_application(&self) {
|
||||
self.p.hide_application()
|
||||
}
|
||||
|
||||
fn hide_other_applications(&self) {
|
||||
self.p.hide_other_applications()
|
||||
}
|
||||
|
||||
fn set_allows_automatic_window_tabbing(&self, enabled: bool) {
|
||||
self.p.set_allows_automatic_window_tabbing(enabled);
|
||||
}
|
||||
|
||||
fn allows_automatic_window_tabbing(&self) -> bool {
|
||||
self.p.allows_automatic_window_tabbing()
|
||||
}
|
||||
}
|
||||
|
||||
/// Option as alt behavior.
|
||||
///
|
||||
/// The default is `None`.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub enum OptionAsAlt {
|
||||
/// The left `Option` key is treated as `Alt`.
|
||||
OnlyLeft,
|
||||
|
||||
/// The right `Option` key is treated as `Alt`.
|
||||
OnlyRight,
|
||||
|
||||
/// Both `Option` keys are treated as `Alt`.
|
||||
Both,
|
||||
|
||||
/// No special handling is applied for `Option` key.
|
||||
#[default]
|
||||
None,
|
||||
}
|
||||
@@ -1,55 +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;
|
||||
|
||||
#[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,111 +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;
|
||||
use crate::window::{Window, WindowAttributes};
|
||||
|
||||
pub use crate::window::Theme;
|
||||
|
||||
/// 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 ActiveEventLoop {
|
||||
#[inline]
|
||||
fn is_wayland(&self) -> bool {
|
||||
self.p.is_wayland()
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional methods on [`EventLoop`] that are specific to Wayland.
|
||||
pub trait EventLoopExtWayland {
|
||||
/// True if the [`EventLoop`] uses Wayland.
|
||||
fn is_wayland(&self) -> bool;
|
||||
}
|
||||
|
||||
impl<T: 'static> EventLoopExtWayland for EventLoop<T> {
|
||||
#[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<T> EventLoopBuilderExtWayland for EventLoopBuilder<T> {
|
||||
#[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.
|
||||
pub trait WindowExtWayland {}
|
||||
|
||||
impl WindowExtWayland for Window {}
|
||||
|
||||
/// 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,465 +0,0 @@
|
||||
//! # Web
|
||||
//!
|
||||
//! The officially supported browsers are Chrome, Firefox and Safari 13.1+,
|
||||
//! though forks of these should work fine.
|
||||
//!
|
||||
//! Winit supports compiling to the `wasm32-unknown-unknown` target with
|
||||
//! `web-sys`.
|
||||
//!
|
||||
//! On the web platform, a Winit window is backed by a `<canvas>` element. You
|
||||
//! can either [provide Winit with a `<canvas>` element][with_canvas], or
|
||||
//! [let Winit create a `<canvas>` element which you can then retrieve][get]
|
||||
//! and insert it into the DOM yourself.
|
||||
//!
|
||||
//! Currently, there is no example code using Winit on Web, see [#3473]. For
|
||||
//! information on using Rust on WebAssembly, check out the [Rust and
|
||||
//! WebAssembly book].
|
||||
//!
|
||||
//! [with_canvas]: WindowAttributesExtWebSys::with_canvas
|
||||
//! [get]: WindowExtWebSys::canvas
|
||||
//! [#3473]: https://github.com/rust-windowing/winit/issues/3473
|
||||
//! [Rust and WebAssembly book]: https://rustwasm.github.io/book/
|
||||
//!
|
||||
//! ## CSS properties
|
||||
//!
|
||||
//! It is recommended **not** to apply certain CSS properties to the canvas:
|
||||
//! - [`transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform)
|
||||
//! - [`border`](https://developer.mozilla.org/en-US/docs/Web/CSS/border)
|
||||
//! - [`padding`](https://developer.mozilla.org/en-US/docs/Web/CSS/padding)
|
||||
//!
|
||||
//! The following APIs can't take them into account and will therefore provide inaccurate results:
|
||||
//! - [`WindowEvent::Resized`] and [`Window::(set_)inner_size()`]
|
||||
//! - [`WindowEvent::Occluded`]
|
||||
//! - [`WindowEvent::CursorMoved`], [`WindowEvent::CursorEntered`], [`WindowEvent::CursorLeft`], and
|
||||
//! [`WindowEvent::Touch`].
|
||||
//! - [`Window::set_outer_position()`]
|
||||
//!
|
||||
//! [`WindowEvent::Resized`]: crate::event::WindowEvent::Resized
|
||||
//! [`Window::(set_)inner_size()`]: crate::window::Window::inner_size
|
||||
//! [`WindowEvent::Occluded`]: crate::event::WindowEvent::Occluded
|
||||
//! [`WindowEvent::CursorMoved`]: crate::event::WindowEvent::CursorMoved
|
||||
//! [`WindowEvent::CursorEntered`]: crate::event::WindowEvent::CursorEntered
|
||||
//! [`WindowEvent::CursorLeft`]: crate::event::WindowEvent::CursorLeft
|
||||
//! [`WindowEvent::Touch`]: crate::event::WindowEvent::Touch
|
||||
//! [`Window::set_outer_position()`]: crate::window::Window::set_outer_position
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Duration;
|
||||
|
||||
#[cfg(web_platform)]
|
||||
use web_sys::HtmlCanvasElement;
|
||||
|
||||
use crate::application::ApplicationHandler;
|
||||
use crate::cursor::CustomCursorSource;
|
||||
use crate::event::Event;
|
||||
use crate::event_loop::{self, ActiveEventLoop, EventLoop};
|
||||
#[cfg(web_platform)]
|
||||
use crate::platform_impl::CustomCursorFuture as PlatformCustomCursorFuture;
|
||||
use crate::platform_impl::PlatformCustomCursorSource;
|
||||
use crate::window::{CustomCursor, Window, WindowAttributes};
|
||||
|
||||
#[cfg(not(web_platform))]
|
||||
#[doc(hidden)]
|
||||
pub struct HtmlCanvasElement;
|
||||
|
||||
pub trait WindowExtWebSys {
|
||||
/// Only returns the canvas if called from inside the window context (the
|
||||
/// main thread).
|
||||
fn canvas(&self) -> Option<HtmlCanvasElement>;
|
||||
|
||||
/// Returns [`true`] if calling `event.preventDefault()` is enabled.
|
||||
///
|
||||
/// See [`Window::set_prevent_default()`] for more details.
|
||||
fn prevent_default(&self) -> bool;
|
||||
|
||||
/// Sets whether `event.preventDefault()` should be called on events on the
|
||||
/// canvas that have side effects.
|
||||
///
|
||||
/// For example, by default using the mouse wheel would cause the page to scroll, enabling this
|
||||
/// would prevent that.
|
||||
///
|
||||
/// Some events are impossible to prevent. E.g. Firefox allows to access the native browser
|
||||
/// context menu with Shift+Rightclick.
|
||||
fn set_prevent_default(&self, prevent_default: bool);
|
||||
}
|
||||
|
||||
impl WindowExtWebSys for Window {
|
||||
#[inline]
|
||||
fn canvas(&self) -> Option<HtmlCanvasElement> {
|
||||
self.window.canvas()
|
||||
}
|
||||
|
||||
fn prevent_default(&self) -> bool {
|
||||
self.window.prevent_default()
|
||||
}
|
||||
|
||||
fn set_prevent_default(&self, prevent_default: bool) {
|
||||
self.window.set_prevent_default(prevent_default)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait WindowAttributesExtWebSys {
|
||||
/// Pass an [`HtmlCanvasElement`] to be used for this [`Window`]. If [`None`],
|
||||
/// [`WindowAttributes::default()`] will create one.
|
||||
///
|
||||
/// In any case, the canvas won't be automatically inserted into the web page.
|
||||
///
|
||||
/// [`None`] by default.
|
||||
#[cfg_attr(not(web_platform), doc = "", doc = "[`HtmlCanvasElement`]: #only-available-on-wasm")]
|
||||
fn with_canvas(self, canvas: Option<HtmlCanvasElement>) -> Self;
|
||||
|
||||
/// Sets whether `event.preventDefault()` should be called on events on the
|
||||
/// canvas that have side effects.
|
||||
///
|
||||
/// See [`Window::set_prevent_default()`] for more details.
|
||||
///
|
||||
/// Enabled by default.
|
||||
fn with_prevent_default(self, prevent_default: bool) -> Self;
|
||||
|
||||
/// Whether the canvas should be focusable using the tab key. This is necessary to capture
|
||||
/// canvas keyboard events.
|
||||
///
|
||||
/// Enabled by default.
|
||||
fn with_focusable(self, focusable: bool) -> Self;
|
||||
|
||||
/// On window creation, append the canvas element to the web page if it isn't already.
|
||||
///
|
||||
/// Disabled by default.
|
||||
fn with_append(self, append: bool) -> Self;
|
||||
}
|
||||
|
||||
impl WindowAttributesExtWebSys for WindowAttributes {
|
||||
fn with_canvas(mut self, canvas: Option<HtmlCanvasElement>) -> Self {
|
||||
self.platform_specific.set_canvas(canvas);
|
||||
self
|
||||
}
|
||||
|
||||
fn with_prevent_default(mut self, prevent_default: bool) -> Self {
|
||||
self.platform_specific.prevent_default = prevent_default;
|
||||
self
|
||||
}
|
||||
|
||||
fn with_focusable(mut self, focusable: bool) -> Self {
|
||||
self.platform_specific.focusable = focusable;
|
||||
self
|
||||
}
|
||||
|
||||
fn with_append(mut self, append: bool) -> Self {
|
||||
self.platform_specific.append = append;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional methods on `EventLoop` that are specific to the web.
|
||||
pub trait EventLoopExtWebSys {
|
||||
/// A type provided by the user that can be passed through `Event::UserEvent`.
|
||||
type UserEvent: 'static;
|
||||
|
||||
/// Initializes the winit event loop.
|
||||
///
|
||||
/// Unlike
|
||||
#[cfg_attr(all(web_platform, target_feature = "exception-handling"), doc = "`run_app()`")]
|
||||
#[cfg_attr(
|
||||
not(all(web_platform, target_feature = "exception-handling")),
|
||||
doc = "[`run_app()`]"
|
||||
)]
|
||||
/// [^1], this returns immediately, and doesn't throw an exception in order to
|
||||
/// satisfy its [`!`] return type.
|
||||
///
|
||||
/// Once the event loop has been destroyed, it's possible to reinitialize another event loop
|
||||
/// by calling this function again. This can be useful if you want to recreate the event loop
|
||||
/// while the WebAssembly module is still loaded. For example, this can be used to recreate the
|
||||
/// event loop when switching between tabs on a single page application.
|
||||
#[rustfmt::skip]
|
||||
///
|
||||
#[cfg_attr(
|
||||
not(all(web_platform, target_feature = "exception-handling")),
|
||||
doc = "[`run_app()`]: EventLoop::run_app()"
|
||||
)]
|
||||
/// [^1]: `run_app()` is _not_ available on WASM when the target supports `exception-handling`.
|
||||
fn spawn_app<A: ApplicationHandler<Self::UserEvent> + 'static>(self, app: A);
|
||||
|
||||
/// See [`spawn_app`].
|
||||
///
|
||||
/// [`spawn_app`]: Self::spawn_app
|
||||
#[deprecated = "use EventLoopExtWebSys::spawn_app"]
|
||||
fn spawn<F>(self, event_handler: F)
|
||||
where
|
||||
F: 'static + FnMut(Event<Self::UserEvent>, &ActiveEventLoop);
|
||||
|
||||
/// Sets the strategy for [`ControlFlow::Poll`].
|
||||
///
|
||||
/// See [`PollStrategy`].
|
||||
///
|
||||
/// [`ControlFlow::Poll`]: crate::event_loop::ControlFlow::Poll
|
||||
fn set_poll_strategy(&self, strategy: PollStrategy);
|
||||
|
||||
/// Gets the strategy for [`ControlFlow::Poll`].
|
||||
///
|
||||
/// See [`PollStrategy`].
|
||||
///
|
||||
/// [`ControlFlow::Poll`]: crate::event_loop::ControlFlow::Poll
|
||||
fn poll_strategy(&self) -> PollStrategy;
|
||||
|
||||
/// Sets the strategy for [`ControlFlow::WaitUntil`].
|
||||
///
|
||||
/// See [`WaitUntilStrategy`].
|
||||
///
|
||||
/// [`ControlFlow::WaitUntil`]: crate::event_loop::ControlFlow::WaitUntil
|
||||
fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy);
|
||||
|
||||
/// Gets the strategy for [`ControlFlow::WaitUntil`].
|
||||
///
|
||||
/// See [`WaitUntilStrategy`].
|
||||
///
|
||||
/// [`ControlFlow::WaitUntil`]: crate::event_loop::ControlFlow::WaitUntil
|
||||
fn wait_until_strategy(&self) -> WaitUntilStrategy;
|
||||
}
|
||||
|
||||
impl<T> EventLoopExtWebSys for EventLoop<T> {
|
||||
type UserEvent = T;
|
||||
|
||||
fn spawn_app<A: ApplicationHandler<Self::UserEvent> + 'static>(self, mut app: A) {
|
||||
self.event_loop.spawn(move |event, event_loop| {
|
||||
event_loop::dispatch_event_for_app(&mut app, event_loop, event)
|
||||
});
|
||||
}
|
||||
|
||||
fn spawn<F>(self, event_handler: F)
|
||||
where
|
||||
F: 'static + FnMut(Event<Self::UserEvent>, &ActiveEventLoop),
|
||||
{
|
||||
self.event_loop.spawn(event_handler)
|
||||
}
|
||||
|
||||
fn set_poll_strategy(&self, strategy: PollStrategy) {
|
||||
self.event_loop.set_poll_strategy(strategy);
|
||||
}
|
||||
|
||||
fn poll_strategy(&self) -> PollStrategy {
|
||||
self.event_loop.poll_strategy()
|
||||
}
|
||||
|
||||
fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy) {
|
||||
self.event_loop.set_wait_until_strategy(strategy);
|
||||
}
|
||||
|
||||
fn wait_until_strategy(&self) -> WaitUntilStrategy {
|
||||
self.event_loop.wait_until_strategy()
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ActiveEventLoopExtWebSys {
|
||||
/// Sets the strategy for [`ControlFlow::Poll`].
|
||||
///
|
||||
/// See [`PollStrategy`].
|
||||
///
|
||||
/// [`ControlFlow::Poll`]: crate::event_loop::ControlFlow::Poll
|
||||
fn set_poll_strategy(&self, strategy: PollStrategy);
|
||||
|
||||
/// Gets the strategy for [`ControlFlow::Poll`].
|
||||
///
|
||||
/// See [`PollStrategy`].
|
||||
///
|
||||
/// [`ControlFlow::Poll`]: crate::event_loop::ControlFlow::Poll
|
||||
fn poll_strategy(&self) -> PollStrategy;
|
||||
|
||||
/// Sets the strategy for [`ControlFlow::WaitUntil`].
|
||||
///
|
||||
/// See [`WaitUntilStrategy`].
|
||||
///
|
||||
/// [`ControlFlow::WaitUntil`]: crate::event_loop::ControlFlow::WaitUntil
|
||||
fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy);
|
||||
|
||||
/// Gets the strategy for [`ControlFlow::WaitUntil`].
|
||||
///
|
||||
/// See [`WaitUntilStrategy`].
|
||||
///
|
||||
/// [`ControlFlow::WaitUntil`]: crate::event_loop::ControlFlow::WaitUntil
|
||||
fn wait_until_strategy(&self) -> WaitUntilStrategy;
|
||||
|
||||
/// Async version of [`ActiveEventLoop::create_custom_cursor()`] which waits until the
|
||||
/// cursor has completely finished loading.
|
||||
fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture;
|
||||
}
|
||||
|
||||
impl ActiveEventLoopExtWebSys for ActiveEventLoop {
|
||||
#[inline]
|
||||
fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture {
|
||||
self.p.create_custom_cursor_async(source)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_poll_strategy(&self, strategy: PollStrategy) {
|
||||
self.p.set_poll_strategy(strategy);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn poll_strategy(&self) -> PollStrategy {
|
||||
self.p.poll_strategy()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy) {
|
||||
self.p.set_wait_until_strategy(strategy);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn wait_until_strategy(&self) -> WaitUntilStrategy {
|
||||
self.p.wait_until_strategy()
|
||||
}
|
||||
}
|
||||
|
||||
/// Strategy used for [`ControlFlow::Poll`][crate::event_loop::ControlFlow::Poll].
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum PollStrategy {
|
||||
/// Uses [`Window.requestIdleCallback()`] to queue the next event loop. If not available
|
||||
/// this will fallback to [`setTimeout()`].
|
||||
///
|
||||
/// This strategy will wait for the browser to enter an idle period before running and might
|
||||
/// be affected by browser throttling.
|
||||
///
|
||||
/// [`Window.requestIdleCallback()`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback
|
||||
/// [`setTimeout()`]: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
|
||||
IdleCallback,
|
||||
/// Uses the [Prioritized Task Scheduling API] to queue the next event loop. If not available
|
||||
/// this will fallback to [`setTimeout()`].
|
||||
///
|
||||
/// This strategy will run as fast as possible without disturbing users from interacting with
|
||||
/// the page and is not affected by browser throttling.
|
||||
///
|
||||
/// This is the default strategy.
|
||||
///
|
||||
/// [Prioritized Task Scheduling API]: https://developer.mozilla.org/en-US/docs/Web/API/Prioritized_Task_Scheduling_API
|
||||
/// [`setTimeout()`]: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
|
||||
#[default]
|
||||
Scheduler,
|
||||
}
|
||||
|
||||
/// Strategy used for [`ControlFlow::WaitUntil`][crate::event_loop::ControlFlow::WaitUntil].
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum WaitUntilStrategy {
|
||||
/// Uses the [Prioritized Task Scheduling API] to queue the next event loop. If not available
|
||||
/// this will fallback to [`setTimeout()`].
|
||||
///
|
||||
/// This strategy is commonly not affected by browser throttling unless the window is not
|
||||
/// focused.
|
||||
///
|
||||
/// This is the default strategy.
|
||||
///
|
||||
/// [Prioritized Task Scheduling API]: https://developer.mozilla.org/en-US/docs/Web/API/Prioritized_Task_Scheduling_API
|
||||
/// [`setTimeout()`]: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
|
||||
#[default]
|
||||
Scheduler,
|
||||
/// Equal to [`Scheduler`][Self::Scheduler] but wakes up the event loop from a [worker].
|
||||
///
|
||||
/// This strategy is commonly not affected by browser throttling regardless of window focus.
|
||||
///
|
||||
/// [worker]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API
|
||||
Worker,
|
||||
}
|
||||
|
||||
pub trait CustomCursorExtWebSys {
|
||||
/// Returns if this cursor is an animation.
|
||||
fn is_animation(&self) -> bool;
|
||||
|
||||
/// 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
|
||||
fn from_url(url: String, hotspot_x: u16, hotspot_y: u16) -> CustomCursorSource;
|
||||
|
||||
/// Crates a new animated cursor from multiple [`CustomCursor`]s.
|
||||
/// Supplied `cursors` can't be empty or other animations.
|
||||
fn from_animation(
|
||||
duration: Duration,
|
||||
cursors: Vec<CustomCursor>,
|
||||
) -> Result<CustomCursorSource, BadAnimation>;
|
||||
}
|
||||
|
||||
impl CustomCursorExtWebSys for CustomCursor {
|
||||
fn is_animation(&self) -> bool {
|
||||
self.inner.animation
|
||||
}
|
||||
|
||||
fn from_url(url: String, hotspot_x: u16, hotspot_y: u16) -> CustomCursorSource {
|
||||
CustomCursorSource { inner: PlatformCustomCursorSource::Url { url, hotspot_x, hotspot_y } }
|
||||
}
|
||||
|
||||
fn from_animation(
|
||||
duration: Duration,
|
||||
cursors: Vec<CustomCursor>,
|
||||
) -> Result<CustomCursorSource, BadAnimation> {
|
||||
if cursors.is_empty() {
|
||||
return Err(BadAnimation::Empty);
|
||||
}
|
||||
|
||||
if cursors.iter().any(CustomCursor::is_animation) {
|
||||
return Err(BadAnimation::Animation);
|
||||
}
|
||||
|
||||
Ok(CustomCursorSource {
|
||||
inner: PlatformCustomCursorSource::Animation { duration, cursors },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An error produced when using [`CustomCursor::from_animation`] with invalid arguments.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum BadAnimation {
|
||||
/// Produced when no cursors were supplied.
|
||||
Empty,
|
||||
/// Produced when a supplied cursor is an animation.
|
||||
Animation,
|
||||
}
|
||||
|
||||
impl fmt::Display for BadAnimation {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Empty => write!(f, "No cursors supplied"),
|
||||
Self::Animation => write!(f, "A supplied cursor is an animation"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for BadAnimation {}
|
||||
|
||||
#[cfg(not(web_platform))]
|
||||
struct PlatformCustomCursorFuture;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CustomCursorFuture(pub(crate) PlatformCustomCursorFuture);
|
||||
|
||||
impl Future for CustomCursorFuture {
|
||||
type Output = Result<CustomCursor, CustomCursorError>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
Pin::new(&mut self.0).poll(cx).map_ok(|cursor| CustomCursor { inner: cursor })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum CustomCursorError {
|
||||
Blob,
|
||||
Decode(String),
|
||||
Animation,
|
||||
}
|
||||
|
||||
impl Display for CustomCursorError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Blob => write!(f, "failed to create `Blob`"),
|
||||
Self::Decode(error) => write!(f, "failed to decode image: {error}"),
|
||||
Self::Animation => {
|
||||
write!(f, "found `CustomCursor` that is an animation when building an animation")
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for CustomCursorError {}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,60 +0,0 @@
|
||||
use objc2::{declare_class, mutability, ClassType, DeclaredClass};
|
||||
use objc2_foundation::{MainThreadMarker, NSObject};
|
||||
use objc2_ui_kit::UIApplication;
|
||||
|
||||
use super::app_state::{self, send_occluded_event_for_all_windows, EventWrapper};
|
||||
use crate::event::Event;
|
||||
|
||||
declare_class!(
|
||||
pub struct AppDelegate;
|
||||
|
||||
unsafe impl ClassType for AppDelegate {
|
||||
type Super = NSObject;
|
||||
type Mutability = mutability::InteriorMutable;
|
||||
const NAME: &'static str = "WinitApplicationDelegate";
|
||||
}
|
||||
|
||||
impl DeclaredClass for AppDelegate {}
|
||||
|
||||
// UIApplicationDelegate protocol
|
||||
unsafe impl AppDelegate {
|
||||
#[method(application:didFinishLaunchingWithOptions:)]
|
||||
fn did_finish_launching(&self, _application: &UIApplication, _: *mut NSObject) -> bool {
|
||||
app_state::did_finish_launching(MainThreadMarker::new().unwrap());
|
||||
true
|
||||
}
|
||||
|
||||
#[method(applicationDidBecomeActive:)]
|
||||
fn did_become_active(&self, _application: &UIApplication) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(mtm, EventWrapper::StaticEvent(Event::Resumed))
|
||||
}
|
||||
|
||||
#[method(applicationWillResignActive:)]
|
||||
fn will_resign_active(&self, _application: &UIApplication) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(mtm, EventWrapper::StaticEvent(Event::Suspended))
|
||||
}
|
||||
|
||||
#[method(applicationWillEnterForeground:)]
|
||||
fn will_enter_foreground(&self, application: &UIApplication) {
|
||||
send_occluded_event_for_all_windows(application, false);
|
||||
}
|
||||
|
||||
#[method(applicationDidEnterBackground:)]
|
||||
fn did_enter_background(&self, application: &UIApplication) {
|
||||
send_occluded_event_for_all_windows(application, true);
|
||||
}
|
||||
|
||||
#[method(applicationWillTerminate:)]
|
||||
fn will_terminate(&self, application: &UIApplication) {
|
||||
app_state::terminated(application);
|
||||
}
|
||||
|
||||
#[method(applicationDidReceiveMemoryWarning:)]
|
||||
fn did_receive_memory_warning(&self, _application: &UIApplication) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(mtm, EventWrapper::StaticEvent(Event::MemoryWarning))
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -1,924 +0,0 @@
|
||||
#![deny(unused_results)]
|
||||
|
||||
use std::cell::{RefCell, RefMut};
|
||||
use std::collections::HashSet;
|
||||
use std::os::raw::c_void;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::Instant;
|
||||
use std::{fmt, 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::runtime::AnyObject;
|
||||
use objc2::{msg_send, sel};
|
||||
use objc2_foundation::{
|
||||
CGRect, CGSize, MainThreadMarker, NSInteger, NSObjectProtocol, NSOperatingSystemVersion,
|
||||
NSProcessInfo,
|
||||
};
|
||||
use objc2_ui_kit::{UIApplication, UICoordinateSpace, UIView, UIWindow};
|
||||
|
||||
use super::window::WinitUIWindow;
|
||||
use crate::dpi::PhysicalSize;
|
||||
use crate::event::{Event, InnerSizeWriter, StartCause, WindowEvent};
|
||||
use crate::event_loop::{ActiveEventLoop as RootActiveEventLoop, ControlFlow};
|
||||
use crate::window::WindowId as RootWindowId;
|
||||
|
||||
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)*))
|
||||
};
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct HandlePendingUserEvents;
|
||||
|
||||
pub(crate) struct EventLoopHandler {
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub(crate) handler: Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop)>,
|
||||
pub(crate) event_loop: RootActiveEventLoop,
|
||||
}
|
||||
|
||||
impl fmt::Debug for EventLoopHandler {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("EventLoopHandler")
|
||||
.field("handler", &"...")
|
||||
.field("event_loop", &self.event_loop)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl EventLoopHandler {
|
||||
fn handle_event(&mut self, event: Event<HandlePendingUserEvents>) {
|
||||
(self.handler)(event, &self.event_loop)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum EventWrapper {
|
||||
StaticEvent(Event<HandlePendingUserEvents>),
|
||||
ScaleFactorChanged(ScaleFactorChanged),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ScaleFactorChanged {
|
||||
pub(super) window: Retained<WinitUIWindow>,
|
||||
pub(super) suggested_size: PhysicalSize<u32>,
|
||||
pub(super) scale_factor: f64,
|
||||
}
|
||||
|
||||
enum UserCallbackTransitionResult<'a> {
|
||||
Success {
|
||||
handler: EventLoopHandler,
|
||||
active_control_flow: ControlFlow,
|
||||
processing_redraws: bool,
|
||||
},
|
||||
ReentrancyPrevented {
|
||||
queued_events: &'a mut Vec<EventWrapper>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Event<HandlePendingUserEvents> {
|
||||
fn is_redraw(&self) -> bool {
|
||||
matches!(self, Event::WindowEvent { 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 {
|
||||
NotLaunched {
|
||||
queued_windows: Vec<Retained<WinitUIWindow>>,
|
||||
queued_events: Vec<EventWrapper>,
|
||||
queued_gpu_redraws: HashSet<Retained<WinitUIWindow>>,
|
||||
},
|
||||
Launching {
|
||||
queued_windows: Vec<Retained<WinitUIWindow>>,
|
||||
queued_events: Vec<EventWrapper>,
|
||||
queued_handler: EventLoopHandler,
|
||||
queued_gpu_redraws: HashSet<Retained<WinitUIWindow>>,
|
||||
},
|
||||
ProcessingEvents {
|
||||
handler: EventLoopHandler,
|
||||
queued_gpu_redraws: HashSet<Retained<WinitUIWindow>>,
|
||||
active_control_flow: ControlFlow,
|
||||
},
|
||||
// special state to deal with reentrancy and prevent mutable aliasing.
|
||||
InUserCallback {
|
||||
queued_events: Vec<EventWrapper>,
|
||||
queued_gpu_redraws: HashSet<Retained<WinitUIWindow>>,
|
||||
},
|
||||
ProcessingRedraws {
|
||||
handler: EventLoopHandler,
|
||||
active_control_flow: ControlFlow,
|
||||
},
|
||||
Waiting {
|
||||
waiting_handler: EventLoopHandler,
|
||||
start: Instant,
|
||||
},
|
||||
PollFinished {
|
||||
waiting_handler: EventLoopHandler,
|
||||
},
|
||||
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,
|
||||
}
|
||||
|
||||
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::NotLaunched {
|
||||
queued_windows: Vec::new(),
|
||||
queued_events: Vec::new(),
|
||||
queued_gpu_redraws: HashSet::new(),
|
||||
}),
|
||||
control_flow: ControlFlow::default(),
|
||||
waker,
|
||||
});
|
||||
}
|
||||
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::NotLaunched { .. } | AppStateImpl::Launching { .. })
|
||||
}
|
||||
|
||||
fn has_terminated(&self) -> bool {
|
||||
matches!(self.state(), AppStateImpl::Terminated)
|
||||
}
|
||||
|
||||
fn will_launch_transition(&mut self, queued_handler: EventLoopHandler) {
|
||||
let (queued_windows, queued_events, queued_gpu_redraws) = match self.take_state() {
|
||||
AppStateImpl::NotLaunched { queued_windows, queued_events, queued_gpu_redraws } => {
|
||||
(queued_windows, queued_events, queued_gpu_redraws)
|
||||
},
|
||||
s => bug!("unexpected state {:?}", s),
|
||||
};
|
||||
self.set_state(AppStateImpl::Launching {
|
||||
queued_windows,
|
||||
queued_events,
|
||||
queued_handler,
|
||||
queued_gpu_redraws,
|
||||
});
|
||||
}
|
||||
|
||||
fn did_finish_launching_transition(
|
||||
&mut self,
|
||||
) -> (Vec<Retained<WinitUIWindow>>, Vec<EventWrapper>) {
|
||||
let (windows, events, handler, queued_gpu_redraws) = match self.take_state() {
|
||||
AppStateImpl::Launching {
|
||||
queued_windows,
|
||||
queued_events,
|
||||
queued_handler,
|
||||
queued_gpu_redraws,
|
||||
} => (queued_windows, queued_events, queued_handler, queued_gpu_redraws),
|
||||
s => bug!("unexpected state {:?}", s),
|
||||
};
|
||||
self.set_state(AppStateImpl::ProcessingEvents {
|
||||
handler,
|
||||
active_control_flow: self.control_flow,
|
||||
queued_gpu_redraws,
|
||||
});
|
||||
(windows, events)
|
||||
}
|
||||
|
||||
fn wakeup_transition(&mut self) -> Option<EventWrapper> {
|
||||
// before `AppState::did_finish_launching` is called, pretend there is no running
|
||||
// event loop.
|
||||
if !self.has_launched() || self.has_terminated() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (handler, event) = match (self.control_flow, self.take_state()) {
|
||||
(ControlFlow::Poll, AppStateImpl::PollFinished { waiting_handler }) => {
|
||||
(waiting_handler, EventWrapper::StaticEvent(Event::NewEvents(StartCause::Poll)))
|
||||
},
|
||||
(ControlFlow::Wait, AppStateImpl::Waiting { waiting_handler, start }) => (
|
||||
waiting_handler,
|
||||
EventWrapper::StaticEvent(Event::NewEvents(StartCause::WaitCancelled {
|
||||
start,
|
||||
requested_resume: None,
|
||||
})),
|
||||
),
|
||||
(
|
||||
ControlFlow::WaitUntil(requested_resume),
|
||||
AppStateImpl::Waiting { waiting_handler, start },
|
||||
) => {
|
||||
let event = if Instant::now() >= requested_resume {
|
||||
EventWrapper::StaticEvent(Event::NewEvents(StartCause::ResumeTimeReached {
|
||||
start,
|
||||
requested_resume,
|
||||
}))
|
||||
} else {
|
||||
EventWrapper::StaticEvent(Event::NewEvents(StartCause::WaitCancelled {
|
||||
start,
|
||||
requested_resume: Some(requested_resume),
|
||||
}))
|
||||
};
|
||||
(waiting_handler, event)
|
||||
},
|
||||
s => bug!("`EventHandler` unexpectedly woke up {:?}", s),
|
||||
};
|
||||
|
||||
self.set_state(AppStateImpl::ProcessingEvents {
|
||||
handler,
|
||||
queued_gpu_redraws: Default::default(),
|
||||
active_control_flow: self.control_flow,
|
||||
});
|
||||
Some(event)
|
||||
}
|
||||
|
||||
fn try_user_callback_transition(&mut self) -> UserCallbackTransitionResult<'_> {
|
||||
// If we're not able to process an event due to recursion or `Init` not having been sent out
|
||||
// yet, then queue the events up.
|
||||
match self.state_mut() {
|
||||
&mut AppStateImpl::Launching { ref mut queued_events, .. }
|
||||
| &mut AppStateImpl::NotLaunched { ref mut queued_events, .. }
|
||||
| &mut AppStateImpl::InUserCallback { ref mut queued_events, .. } => {
|
||||
// A lifetime cast: early returns are not currently handled well with NLL, but
|
||||
// polonius handles them well. This transmute is a safe workaround.
|
||||
return unsafe {
|
||||
mem::transmute::<
|
||||
UserCallbackTransitionResult<'_>,
|
||||
UserCallbackTransitionResult<'_>,
|
||||
>(UserCallbackTransitionResult::ReentrancyPrevented {
|
||||
queued_events,
|
||||
})
|
||||
};
|
||||
},
|
||||
|
||||
&mut AppStateImpl::ProcessingEvents { .. }
|
||||
| &mut AppStateImpl::ProcessingRedraws { .. } => {},
|
||||
|
||||
s @ &mut AppStateImpl::PollFinished { .. }
|
||||
| s @ &mut AppStateImpl::Waiting { .. }
|
||||
| s @ &mut AppStateImpl::Terminated => {
|
||||
bug!("unexpected attempted to process an event {:?}", s)
|
||||
},
|
||||
}
|
||||
|
||||
let (handler, queued_gpu_redraws, active_control_flow, processing_redraws) = match self
|
||||
.take_state()
|
||||
{
|
||||
AppStateImpl::Launching { .. }
|
||||
| AppStateImpl::NotLaunched { .. }
|
||||
| AppStateImpl::InUserCallback { .. } => unreachable!(),
|
||||
AppStateImpl::ProcessingEvents { handler, queued_gpu_redraws, active_control_flow } => {
|
||||
(handler, queued_gpu_redraws, active_control_flow, false)
|
||||
},
|
||||
AppStateImpl::ProcessingRedraws { handler, active_control_flow } => {
|
||||
(handler, Default::default(), active_control_flow, true)
|
||||
},
|
||||
AppStateImpl::PollFinished { .. }
|
||||
| AppStateImpl::Waiting { .. }
|
||||
| AppStateImpl::Terminated => unreachable!(),
|
||||
};
|
||||
self.set_state(AppStateImpl::InUserCallback {
|
||||
queued_events: Vec::new(),
|
||||
queued_gpu_redraws,
|
||||
});
|
||||
UserCallbackTransitionResult::Success { handler, active_control_flow, processing_redraws }
|
||||
}
|
||||
|
||||
fn main_events_cleared_transition(&mut self) -> HashSet<Retained<WinitUIWindow>> {
|
||||
let (handler, queued_gpu_redraws, active_control_flow) = match self.take_state() {
|
||||
AppStateImpl::ProcessingEvents { handler, queued_gpu_redraws, active_control_flow } => {
|
||||
(handler, queued_gpu_redraws, active_control_flow)
|
||||
},
|
||||
s => bug!("unexpected state {:?}", s),
|
||||
};
|
||||
self.set_state(AppStateImpl::ProcessingRedraws { handler, active_control_flow });
|
||||
queued_gpu_redraws
|
||||
}
|
||||
|
||||
fn events_cleared_transition(&mut self) {
|
||||
if !self.has_launched() || self.has_terminated() {
|
||||
return;
|
||||
}
|
||||
let (waiting_handler, old) = match self.take_state() {
|
||||
AppStateImpl::ProcessingRedraws { handler, active_control_flow } => {
|
||||
(handler, 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 { waiting_handler, start });
|
||||
},
|
||||
(ControlFlow::WaitUntil(old_instant), ControlFlow::WaitUntil(new_instant))
|
||||
if old_instant == new_instant =>
|
||||
{
|
||||
let start = Instant::now();
|
||||
self.set_state(AppStateImpl::Waiting { waiting_handler, start });
|
||||
},
|
||||
(_, ControlFlow::Wait) => {
|
||||
let start = Instant::now();
|
||||
self.set_state(AppStateImpl::Waiting { waiting_handler, start });
|
||||
self.waker.stop()
|
||||
},
|
||||
(_, ControlFlow::WaitUntil(new_instant)) => {
|
||||
let start = Instant::now();
|
||||
self.set_state(AppStateImpl::Waiting { waiting_handler, 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 { waiting_handler });
|
||||
self.waker.start()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn terminated_transition(&mut self) -> EventLoopHandler {
|
||||
match self.replace_state(AppStateImpl::Terminated) {
|
||||
AppStateImpl::ProcessingEvents { handler, .. } => handler,
|
||||
s => bug!("`LoopExiting` happened while not processing events {:?}", s),
|
||||
}
|
||||
}
|
||||
|
||||
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 set_key_window(mtm: MainThreadMarker, window: &Retained<WinitUIWindow>) {
|
||||
let mut this = AppState::get_mut(mtm);
|
||||
match this.state_mut() {
|
||||
&mut AppStateImpl::NotLaunched { ref mut queued_windows, .. } => {
|
||||
return queued_windows.push(window.clone())
|
||||
},
|
||||
&mut AppStateImpl::ProcessingEvents { .. }
|
||||
| &mut AppStateImpl::InUserCallback { .. }
|
||||
| &mut AppStateImpl::ProcessingRedraws { .. } => {},
|
||||
s @ &mut AppStateImpl::Launching { .. }
|
||||
| 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")
|
||||
},
|
||||
}
|
||||
drop(this);
|
||||
window.makeKeyAndVisible();
|
||||
}
|
||||
|
||||
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::NotLaunched { ref mut queued_gpu_redraws, .. }
|
||||
| &mut AppStateImpl::Launching { ref mut queued_gpu_redraws, .. }
|
||||
| &mut AppStateImpl::ProcessingEvents { ref mut queued_gpu_redraws, .. }
|
||||
| &mut AppStateImpl::InUserCallback { 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 will_launch(mtm: MainThreadMarker, queued_handler: EventLoopHandler) {
|
||||
AppState::get_mut(mtm).will_launch_transition(queued_handler)
|
||||
}
|
||||
|
||||
pub fn did_finish_launching(mtm: MainThreadMarker) {
|
||||
let mut this = AppState::get_mut(mtm);
|
||||
let windows = match this.state_mut() {
|
||||
AppStateImpl::Launching { queued_windows, .. } => mem::take(queued_windows),
|
||||
s => bug!("unexpected state {:?}", s),
|
||||
};
|
||||
|
||||
this.waker.start();
|
||||
|
||||
// have to drop RefMut because the window setup code below can trigger new events
|
||||
drop(this);
|
||||
|
||||
for window in windows {
|
||||
// Do a little screen dance here to account for windows being created before
|
||||
// `UIApplicationMain` is called. This fixes visual issues such as being
|
||||
// offcenter and sized incorrectly. Additionally, to fix orientation issues, we
|
||||
// gotta reset the `rootViewController`.
|
||||
//
|
||||
// relevant iOS log:
|
||||
// ```
|
||||
// [ApplicationLifecycle] Windows were created before application initialization
|
||||
// completed. This may result in incorrect visual appearance.
|
||||
// ```
|
||||
let screen = window.screen();
|
||||
let _: () = unsafe { msg_send![&window, setScreen: ptr::null::<AnyObject>()] };
|
||||
window.setScreen(&screen);
|
||||
|
||||
let controller = window.rootViewController();
|
||||
window.setRootViewController(None);
|
||||
window.setRootViewController(controller.as_deref());
|
||||
|
||||
window.makeKeyAndVisible();
|
||||
}
|
||||
|
||||
let (windows, events) = AppState::get_mut(mtm).did_finish_launching_transition();
|
||||
|
||||
let events = std::iter::once(EventWrapper::StaticEvent(Event::NewEvents(StartCause::Init)))
|
||||
.chain(events);
|
||||
handle_nonuser_events(mtm, events);
|
||||
|
||||
// the above window dance hack, could possibly trigger new windows to be created.
|
||||
// we can just set those windows up normally, as they were created after didFinishLaunching
|
||||
for window in windows {
|
||||
window.makeKeyAndVisible();
|
||||
}
|
||||
}
|
||||
|
||||
// AppState::did_finish_launching handles the special transition `Init`
|
||||
pub fn handle_wakeup_transition(mtm: MainThreadMarker) {
|
||||
let mut this = AppState::get_mut(mtm);
|
||||
let wakeup_event = match this.wakeup_transition() {
|
||||
None => return,
|
||||
Some(wakeup_event) => wakeup_event,
|
||||
};
|
||||
drop(this);
|
||||
|
||||
handle_nonuser_event(mtm, wakeup_event)
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
let (mut handler, active_control_flow, processing_redraws) =
|
||||
match this.try_user_callback_transition() {
|
||||
UserCallbackTransitionResult::ReentrancyPrevented { queued_events } => {
|
||||
queued_events.extend(events);
|
||||
return;
|
||||
},
|
||||
UserCallbackTransitionResult::Success {
|
||||
handler,
|
||||
active_control_flow,
|
||||
processing_redraws,
|
||||
} => (handler, active_control_flow, processing_redraws),
|
||||
};
|
||||
drop(this);
|
||||
|
||||
for wrapper in events {
|
||||
match wrapper {
|
||||
EventWrapper::StaticEvent(event) => {
|
||||
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
|
||||
);
|
||||
}
|
||||
handler.handle_event(event)
|
||||
},
|
||||
EventWrapper::ScaleFactorChanged(event) => handle_hidpi_proxy(&mut handler, event),
|
||||
}
|
||||
}
|
||||
|
||||
loop {
|
||||
let mut this = AppState::get_mut(mtm);
|
||||
let queued_events = match this.state_mut() {
|
||||
&mut AppStateImpl::InUserCallback { ref mut queued_events, queued_gpu_redraws: _ } => {
|
||||
mem::take(queued_events)
|
||||
},
|
||||
s => bug!("unexpected state {:?}", s),
|
||||
};
|
||||
if queued_events.is_empty() {
|
||||
let queued_gpu_redraws = match this.take_state() {
|
||||
AppStateImpl::InUserCallback { queued_events: _, queued_gpu_redraws } => {
|
||||
queued_gpu_redraws
|
||||
},
|
||||
_ => unreachable!(),
|
||||
};
|
||||
this.app_state = Some(if processing_redraws {
|
||||
bug_assert!(
|
||||
queued_gpu_redraws.is_empty(),
|
||||
"redraw queued while processing redraws"
|
||||
);
|
||||
AppStateImpl::ProcessingRedraws { handler, active_control_flow }
|
||||
} else {
|
||||
AppStateImpl::ProcessingEvents { handler, queued_gpu_redraws, active_control_flow }
|
||||
});
|
||||
break;
|
||||
}
|
||||
drop(this);
|
||||
|
||||
for wrapper in queued_events {
|
||||
match wrapper {
|
||||
EventWrapper::StaticEvent(event) => {
|
||||
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
|
||||
);
|
||||
}
|
||||
handler.handle_event(event)
|
||||
},
|
||||
EventWrapper::ScaleFactorChanged(event) => handle_hidpi_proxy(&mut handler, event),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_user_events(mtm: MainThreadMarker) {
|
||||
let mut this = AppState::get_mut(mtm);
|
||||
let (mut handler, active_control_flow, processing_redraws) =
|
||||
match this.try_user_callback_transition() {
|
||||
UserCallbackTransitionResult::ReentrancyPrevented { .. } => {
|
||||
bug!("unexpected attempted to process an event")
|
||||
},
|
||||
UserCallbackTransitionResult::Success {
|
||||
handler,
|
||||
active_control_flow,
|
||||
processing_redraws,
|
||||
} => (handler, active_control_flow, processing_redraws),
|
||||
};
|
||||
if processing_redraws {
|
||||
bug!("user events attempted to be sent out while `ProcessingRedraws`");
|
||||
}
|
||||
drop(this);
|
||||
|
||||
handler.handle_event(Event::UserEvent(HandlePendingUserEvents));
|
||||
|
||||
loop {
|
||||
let mut this = AppState::get_mut(mtm);
|
||||
let queued_events = match this.state_mut() {
|
||||
&mut AppStateImpl::InUserCallback { ref mut queued_events, queued_gpu_redraws: _ } => {
|
||||
mem::take(queued_events)
|
||||
},
|
||||
s => bug!("unexpected state {:?}", s),
|
||||
};
|
||||
if queued_events.is_empty() {
|
||||
let queued_gpu_redraws = match this.take_state() {
|
||||
AppStateImpl::InUserCallback { queued_events: _, queued_gpu_redraws } => {
|
||||
queued_gpu_redraws
|
||||
},
|
||||
_ => unreachable!(),
|
||||
};
|
||||
this.app_state = Some(AppStateImpl::ProcessingEvents {
|
||||
handler,
|
||||
queued_gpu_redraws,
|
||||
active_control_flow,
|
||||
});
|
||||
break;
|
||||
}
|
||||
drop(this);
|
||||
|
||||
for wrapper in queued_events {
|
||||
match wrapper {
|
||||
EventWrapper::StaticEvent(event) => handler.handle_event(event),
|
||||
EventWrapper::ScaleFactorChanged(event) => handle_hidpi_proxy(&mut handler, event),
|
||||
}
|
||||
}
|
||||
|
||||
handler.handle_event(Event::UserEvent(HandlePendingUserEvents));
|
||||
}
|
||||
}
|
||||
|
||||
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::StaticEvent(Event::WindowEvent {
|
||||
window_id: RootWindowId(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::StaticEvent(Event::WindowEvent {
|
||||
window_id: RootWindowId(window.id()),
|
||||
event: WindowEvent::RedrawRequested,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
drop(this);
|
||||
|
||||
handle_nonuser_events(mtm, redraw_events);
|
||||
handle_nonuser_event(mtm, EventWrapper::StaticEvent(Event::AboutToWait));
|
||||
}
|
||||
|
||||
pub fn handle_events_cleared(mtm: MainThreadMarker) {
|
||||
AppState::get_mut(mtm).events_cleared_transition();
|
||||
}
|
||||
|
||||
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::StaticEvent(Event::WindowEvent {
|
||||
window_id: RootWindowId(window.id()),
|
||||
event: WindowEvent::Destroyed,
|
||||
}));
|
||||
}
|
||||
}
|
||||
handle_nonuser_events(mtm, events);
|
||||
|
||||
let mut this = AppState::get_mut(mtm);
|
||||
let mut handler = this.terminated_transition();
|
||||
drop(this);
|
||||
|
||||
handler.handle_event(Event::LoopExiting)
|
||||
}
|
||||
|
||||
fn handle_hidpi_proxy(handler: &mut EventLoopHandler, event: ScaleFactorChanged) {
|
||||
let ScaleFactorChanged { suggested_size, scale_factor, window } = event;
|
||||
let new_inner_size = Arc::new(Mutex::new(suggested_size));
|
||||
let event = Event::WindowEvent {
|
||||
window_id: RootWindowId(window.id()),
|
||||
event: WindowEvent::ScaleFactorChanged {
|
||||
scale_factor,
|
||||
inner_size_writer: InnerSizeWriter::new(Arc::downgrade(&new_inner_size)),
|
||||
},
|
||||
};
|
||||
handler.handle_event(event);
|
||||
let (view, screen_frame) = get_view_and_screen_frame(&window);
|
||||
let physical_size = *new_inner_size.lock().unwrap();
|
||||
drop(new_inner_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,391 +0,0 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::ffi::{c_char, c_int, c_void};
|
||||
use std::marker::PhantomData;
|
||||
use std::ptr::{self, NonNull};
|
||||
use std::sync::mpsc::{self, Receiver, Sender};
|
||||
|
||||
use core_foundation::base::{CFIndex, CFRelease};
|
||||
use core_foundation::runloop::{
|
||||
kCFRunLoopAfterWaiting, kCFRunLoopBeforeWaiting, kCFRunLoopCommonModes, kCFRunLoopDefaultMode,
|
||||
kCFRunLoopExit, CFRunLoopActivity, CFRunLoopAddObserver, CFRunLoopAddSource, CFRunLoopGetMain,
|
||||
CFRunLoopObserverCreate, CFRunLoopObserverRef, CFRunLoopSourceContext, CFRunLoopSourceCreate,
|
||||
CFRunLoopSourceInvalidate, CFRunLoopSourceRef, CFRunLoopSourceSignal, CFRunLoopWakeUp,
|
||||
};
|
||||
use objc2::rc::Retained;
|
||||
use objc2::{msg_send_id, ClassType};
|
||||
use objc2_foundation::{MainThreadMarker, NSString};
|
||||
use objc2_ui_kit::{UIApplication, UIApplicationMain, UIDevice, UIScreen, UIUserInterfaceIdiom};
|
||||
|
||||
use crate::error::EventLoopError;
|
||||
use crate::event::Event;
|
||||
use crate::event_loop::{
|
||||
ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents, EventLoopClosed,
|
||||
};
|
||||
use crate::platform::ios::Idiom;
|
||||
use crate::platform_impl::ios::app_state::{EventLoopHandler, HandlePendingUserEvents};
|
||||
use crate::window::{CustomCursor, CustomCursorSource, Theme};
|
||||
|
||||
use super::app_delegate::AppDelegate;
|
||||
use super::app_state::AppState;
|
||||
use super::{app_state, monitor, MonitorHandle};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ActiveEventLoop {
|
||||
pub(super) mtm: MainThreadMarker,
|
||||
}
|
||||
|
||||
impl ActiveEventLoop {
|
||||
pub fn create_custom_cursor(&self, source: CustomCursorSource) -> CustomCursor {
|
||||
let _ = source.inner;
|
||||
CustomCursor { inner: super::PlatformCustomCursor }
|
||||
}
|
||||
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
monitor::uiscreens(self.mtm)
|
||||
}
|
||||
|
||||
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||
#[allow(deprecated)]
|
||||
Some(MonitorHandle::new(UIScreen::mainScreen(self.mtm)))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn listen_device_events(&self, _allowed: DeviceEvents) {}
|
||||
|
||||
#[cfg(feature = "rwh_05")]
|
||||
#[inline]
|
||||
pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
|
||||
rwh_05::RawDisplayHandle::UiKit(rwh_05::UiKitDisplayHandle::empty())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn system_theme(&self) -> Option<Theme> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
#[inline]
|
||||
pub fn raw_display_handle_rwh_06(
|
||||
&self,
|
||||
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
|
||||
Ok(rwh_06::RawDisplayHandle::UiKit(rwh_06::UiKitDisplayHandle::new()))
|
||||
}
|
||||
|
||||
pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||
AppState::get_mut(self.mtm).set_control_flow(control_flow)
|
||||
}
|
||||
|
||||
pub(crate) fn control_flow(&self) -> ControlFlow {
|
||||
AppState::get_mut(self.mtm).control_flow()
|
||||
}
|
||||
|
||||
pub(crate) fn exit(&self) {
|
||||
// https://developer.apple.com/library/archive/qa/qa1561/_index.html
|
||||
// it is not possible to quit an iOS app gracefully and programmatically
|
||||
tracing::warn!("`ControlFlow::Exit` ignored on iOS");
|
||||
}
|
||||
|
||||
pub(crate) fn exiting(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn owned_display_handle(&self) -> OwnedDisplayHandle {
|
||||
OwnedDisplayHandle
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct OwnedDisplayHandle;
|
||||
|
||||
impl OwnedDisplayHandle {
|
||||
#[cfg(feature = "rwh_05")]
|
||||
#[inline]
|
||||
pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
|
||||
rwh_05::UiKitDisplayHandle::empty().into()
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
#[inline]
|
||||
pub fn raw_display_handle_rwh_06(
|
||||
&self,
|
||||
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
|
||||
Ok(rwh_06::UiKitDisplayHandle::new().into())
|
||||
}
|
||||
}
|
||||
|
||||
fn map_user_event<T: 'static>(
|
||||
mut handler: impl FnMut(Event<T>, &RootActiveEventLoop),
|
||||
receiver: mpsc::Receiver<T>,
|
||||
) -> impl FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop) {
|
||||
move |event, window_target| match event.map_nonuser_event() {
|
||||
Ok(event) => (handler)(event, window_target),
|
||||
Err(_) => {
|
||||
for event in receiver.try_iter() {
|
||||
(handler)(Event::UserEvent(event), window_target);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EventLoop<T: 'static> {
|
||||
mtm: MainThreadMarker,
|
||||
sender: Sender<T>,
|
||||
receiver: Receiver<T>,
|
||||
window_target: RootActiveEventLoop,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct PlatformSpecificEventLoopAttributes {}
|
||||
|
||||
impl<T: 'static> EventLoop<T> {
|
||||
pub(crate) fn new(
|
||||
_: &PlatformSpecificEventLoopAttributes,
|
||||
) -> Result<EventLoop<T>, EventLoopError> {
|
||||
let mtm = MainThreadMarker::new()
|
||||
.expect("On iOS, `EventLoop` must be created on the main thread");
|
||||
|
||||
static mut SINGLETON_INIT: bool = false;
|
||||
unsafe {
|
||||
assert!(
|
||||
!SINGLETON_INIT,
|
||||
"Only one `EventLoop` is supported on iOS. `EventLoopProxy` might be helpful"
|
||||
);
|
||||
SINGLETON_INIT = true;
|
||||
}
|
||||
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
|
||||
// this line sets up the main run loop before `UIApplicationMain`
|
||||
setup_control_flow_observers();
|
||||
|
||||
Ok(EventLoop {
|
||||
mtm,
|
||||
sender,
|
||||
receiver,
|
||||
window_target: RootActiveEventLoop { p: ActiveEventLoop { mtm }, _marker: PhantomData },
|
||||
})
|
||||
}
|
||||
|
||||
pub fn run<F>(self, handler: F) -> !
|
||||
where
|
||||
F: FnMut(Event<T>, &RootActiveEventLoop),
|
||||
{
|
||||
let application: Option<Retained<UIApplication>> =
|
||||
unsafe { msg_send_id![UIApplication::class(), sharedApplication] };
|
||||
assert!(
|
||||
application.is_none(),
|
||||
"\
|
||||
`EventLoop` cannot be `run` after a call to `UIApplicationMain` on iOS\nNote: \
|
||||
`EventLoop::run_app` calls `UIApplicationMain` on iOS",
|
||||
);
|
||||
|
||||
let handler = map_user_event(handler, self.receiver);
|
||||
|
||||
let handler = unsafe {
|
||||
std::mem::transmute::<
|
||||
Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop)>,
|
||||
Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop)>,
|
||||
>(Box::new(handler))
|
||||
};
|
||||
|
||||
let handler = EventLoopHandler { handler, event_loop: self.window_target };
|
||||
|
||||
app_state::will_launch(self.mtm, handler);
|
||||
|
||||
// Ensure application delegate is initialized
|
||||
let _ = AppDelegate::class();
|
||||
|
||||
extern "C" {
|
||||
// These functions are in crt_externs.h.
|
||||
fn _NSGetArgc() -> *mut c_int;
|
||||
fn _NSGetArgv() -> *mut *mut *mut c_char;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
UIApplicationMain(
|
||||
*_NSGetArgc(),
|
||||
NonNull::new(*_NSGetArgv()).unwrap(),
|
||||
None,
|
||||
Some(&NSString::from_str(AppDelegate::NAME)),
|
||||
)
|
||||
};
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
pub fn create_proxy(&self) -> EventLoopProxy<T> {
|
||||
EventLoopProxy::new(self.sender.clone())
|
||||
}
|
||||
|
||||
pub fn window_target(&self) -> &RootActiveEventLoop {
|
||||
&self.window_target
|
||||
}
|
||||
}
|
||||
|
||||
// EventLoopExtIOS
|
||||
impl<T: 'static> EventLoop<T> {
|
||||
pub fn idiom(&self) -> Idiom {
|
||||
match UIDevice::currentDevice(self.mtm).userInterfaceIdiom() {
|
||||
UIUserInterfaceIdiom::Unspecified => Idiom::Unspecified,
|
||||
UIUserInterfaceIdiom::Phone => Idiom::Phone,
|
||||
UIUserInterfaceIdiom::Pad => Idiom::Pad,
|
||||
UIUserInterfaceIdiom::TV => Idiom::TV,
|
||||
UIUserInterfaceIdiom::CarPlay => Idiom::CarPlay,
|
||||
_ => Idiom::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EventLoopProxy<T> {
|
||||
sender: Sender<T>,
|
||||
source: CFRunLoopSourceRef,
|
||||
}
|
||||
|
||||
unsafe impl<T: Send> Send for EventLoopProxy<T> {}
|
||||
unsafe impl<T: Send> Sync for EventLoopProxy<T> {}
|
||||
|
||||
impl<T> Clone for EventLoopProxy<T> {
|
||||
fn clone(&self) -> EventLoopProxy<T> {
|
||||
EventLoopProxy::new(self.sender.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for EventLoopProxy<T> {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
CFRunLoopSourceInvalidate(self.source);
|
||||
CFRelease(self.source as _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> EventLoopProxy<T> {
|
||||
fn new(sender: Sender<T>) -> EventLoopProxy<T> {
|
||||
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 { sender, source }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
|
||||
self.sender.send(event).map_err(|::std::sync::mpsc::SendError(x)| EventLoopClosed(x))?;
|
||||
unsafe {
|
||||
// let the main thread know there's a new event
|
||||
CFRunLoopSourceSignal(self.source);
|
||||
let rl = CFRunLoopGetMain();
|
||||
CFRunLoopWakeUp(rl);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn setup_control_flow_observers() {
|
||||
unsafe {
|
||||
// begin is queued with the highest priority to ensure it is processed before other
|
||||
// observers
|
||||
extern "C" fn control_flow_begin_handler(
|
||||
_: CFRunLoopObserverRef,
|
||||
activity: CFRunLoopActivity,
|
||||
_: *mut c_void,
|
||||
) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
#[allow(non_upper_case_globals)]
|
||||
match activity {
|
||||
kCFRunLoopAfterWaiting => app_state::handle_wakeup_transition(mtm),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
// Core Animation registers its `CFRunLoopObserver` that performs drawing operations in
|
||||
// `CA::Transaction::ensure_implicit` with a priority of `0x1e8480`. We set the main_end
|
||||
// priority to be 0, in order to send AboutToWait before RedrawRequested. This value was
|
||||
// chosen conservatively to guard against apple using different priorities for their redraw
|
||||
// observers in different OS's or on different devices. If it so happens that it's too
|
||||
// conservative, the main symptom would be non-redraw events coming in after `AboutToWait`.
|
||||
//
|
||||
// The value of `0x1e8480` was determined by inspecting stack traces and the associated
|
||||
// registers for every `CFRunLoopAddObserver` call on an iPad Air 2 running iOS 11.4.
|
||||
//
|
||||
// Also tested to be `0x1e8480` on iPhone 8, iOS 13 beta 4.
|
||||
extern "C" fn control_flow_main_end_handler(
|
||||
_: CFRunLoopObserverRef,
|
||||
activity: CFRunLoopActivity,
|
||||
_: *mut c_void,
|
||||
) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
#[allow(non_upper_case_globals)]
|
||||
match activity {
|
||||
kCFRunLoopBeforeWaiting => app_state::handle_main_events_cleared(mtm),
|
||||
kCFRunLoopExit => {}, // may happen when running on macOS
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
// end is queued with the lowest priority to ensure it is processed after other observers
|
||||
extern "C" fn control_flow_end_handler(
|
||||
_: CFRunLoopObserverRef,
|
||||
activity: CFRunLoopActivity,
|
||||
_: *mut c_void,
|
||||
) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
#[allow(non_upper_case_globals)]
|
||||
match activity {
|
||||
kCFRunLoopBeforeWaiting => app_state::handle_events_cleared(mtm),
|
||||
kCFRunLoopExit => {}, // may happen when running on macOS
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
let main_loop = CFRunLoopGetMain();
|
||||
|
||||
let begin_observer = CFRunLoopObserverCreate(
|
||||
ptr::null_mut(),
|
||||
kCFRunLoopAfterWaiting,
|
||||
1, // repeat = true
|
||||
CFIndex::MIN,
|
||||
control_flow_begin_handler,
|
||||
ptr::null_mut(),
|
||||
);
|
||||
CFRunLoopAddObserver(main_loop, begin_observer, kCFRunLoopDefaultMode);
|
||||
|
||||
let main_end_observer = CFRunLoopObserverCreate(
|
||||
ptr::null_mut(),
|
||||
kCFRunLoopExit | kCFRunLoopBeforeWaiting,
|
||||
1, // repeat = true
|
||||
0, // see comment on `control_flow_main_end_handler`
|
||||
control_flow_main_end_handler,
|
||||
ptr::null_mut(),
|
||||
);
|
||||
CFRunLoopAddObserver(main_loop, main_end_observer, kCFRunLoopDefaultMode);
|
||||
|
||||
let end_observer = CFRunLoopObserverCreate(
|
||||
ptr::null_mut(),
|
||||
kCFRunLoopExit | kCFRunLoopBeforeWaiting,
|
||||
1, // repeat = true
|
||||
CFIndex::MAX,
|
||||
control_flow_end_handler,
|
||||
ptr::null_mut(),
|
||||
);
|
||||
CFRunLoopAddObserver(main_loop, end_observer, kCFRunLoopDefaultMode);
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
#![allow(clippy::let_unit_value)]
|
||||
|
||||
mod app_delegate;
|
||||
mod app_state;
|
||||
mod event_loop;
|
||||
mod monitor;
|
||||
mod view;
|
||||
mod view_controller;
|
||||
mod window;
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use crate::event::DeviceId as RootDeviceId;
|
||||
|
||||
pub(crate) use self::event_loop::{
|
||||
ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle,
|
||||
PlatformSpecificEventLoopAttributes,
|
||||
};
|
||||
pub(crate) use self::monitor::{MonitorHandle, VideoModeHandle};
|
||||
pub(crate) use self::window::{PlatformSpecificWindowAttributes, Window, WindowId};
|
||||
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;
|
||||
|
||||
/// There is no way to detect which device that performed a certain event in
|
||||
/// UIKit (i.e. you can't differentiate between different external keyboards,
|
||||
/// or whether it was the main touchscreen, assistive technologies, or some
|
||||
/// other pointer device that caused a touch event).
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DeviceId;
|
||||
|
||||
impl DeviceId {
|
||||
pub const fn dummy() -> Self {
|
||||
DeviceId
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const DEVICE_ID: RootDeviceId = RootDeviceId(DeviceId);
|
||||
|
||||
#[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,750 +0,0 @@
|
||||
#![allow(clippy::unnecessary_cast)]
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::{AnyObject, NSObject};
|
||||
use objc2::{class, declare_class, msg_send, msg_send_id, mutability, ClassType, DeclaredClass};
|
||||
use objc2_foundation::{
|
||||
CGFloat, CGPoint, CGRect, CGSize, MainThreadBound, MainThreadMarker, NSObjectProtocol,
|
||||
};
|
||||
use objc2_ui_kit::{
|
||||
UIApplication, UICoordinateSpace, UIResponder, UIScreen, UIScreenOverscanCompensation,
|
||||
UIViewController, UIWindow,
|
||||
};
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use super::app_state::EventWrapper;
|
||||
use super::view::WinitView;
|
||||
use super::view_controller::WinitViewController;
|
||||
use crate::cursor::Cursor;
|
||||
use crate::dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size};
|
||||
use crate::error::{ExternalError, NotSupportedError, OsError as RootOsError};
|
||||
use crate::event::{Event, WindowEvent};
|
||||
use crate::icon::Icon;
|
||||
use crate::platform::ios::{ScreenEdge, StatusBarStyle, ValidOrientations};
|
||||
use crate::platform_impl::platform::{
|
||||
app_state, monitor, ActiveEventLoop, Fullscreen, MonitorHandle,
|
||||
};
|
||||
use crate::window::{
|
||||
CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes,
|
||||
WindowButtons, WindowId as RootWindowId, WindowLevel,
|
||||
};
|
||||
|
||||
declare_class!(
|
||||
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct WinitUIWindow;
|
||||
|
||||
unsafe impl ClassType for WinitUIWindow {
|
||||
#[inherits(UIResponder, NSObject)]
|
||||
type Super = UIWindow;
|
||||
type Mutability = mutability::MainThreadOnly;
|
||||
const NAME: &'static str = "WinitUIWindow";
|
||||
}
|
||||
|
||||
impl DeclaredClass for WinitUIWindow {}
|
||||
|
||||
unsafe impl WinitUIWindow {
|
||||
#[method(becomeKeyWindow)]
|
||||
fn become_key_window(&self) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(
|
||||
mtm,
|
||||
EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: RootWindowId(self.id()),
|
||||
event: WindowEvent::Focused(true),
|
||||
}),
|
||||
);
|
||||
let _: () = unsafe { msg_send![super(self), becomeKeyWindow] };
|
||||
}
|
||||
|
||||
#[method(resignKeyWindow)]
|
||||
fn resign_key_window(&self) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(
|
||||
mtm,
|
||||
EventWrapper::StaticEvent(Event::WindowEvent {
|
||||
window_id: RootWindowId(self.id()),
|
||||
event: WindowEvent::Focused(false),
|
||||
}),
|
||||
);
|
||||
let _: () = unsafe { msg_send![super(self), resignKeyWindow] };
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl WinitUIWindow {
|
||||
pub(crate) fn new(
|
||||
mtm: MainThreadMarker,
|
||||
window_attributes: &WindowAttributes,
|
||||
frame: CGRect,
|
||||
view_controller: &UIViewController,
|
||||
) -> Retained<Self> {
|
||||
let this: Retained<Self> = unsafe { msg_send_id![mtm.alloc(), initWithFrame: frame] };
|
||||
|
||||
this.setRootViewController(Some(view_controller));
|
||||
|
||||
match window_attributes.fullscreen.clone().map(Into::into) {
|
||||
Some(Fullscreen::Exclusive(ref video_mode)) => {
|
||||
let monitor = video_mode.monitor();
|
||||
let screen = monitor.ui_screen(mtm);
|
||||
screen.setCurrentMode(Some(video_mode.screen_mode(mtm)));
|
||||
this.setScreen(screen);
|
||||
},
|
||||
Some(Fullscreen::Borderless(Some(ref monitor))) => {
|
||||
let screen = monitor.ui_screen(mtm);
|
||||
this.setScreen(screen);
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
|
||||
this
|
||||
}
|
||||
|
||||
pub(crate) fn id(&self) -> WindowId {
|
||||
(self as *const Self as usize as u64).into()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Inner {
|
||||
window: Retained<WinitUIWindow>,
|
||||
view_controller: Retained<WinitViewController>,
|
||||
view: Retained<WinitView>,
|
||||
gl_or_metal_backed: bool,
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
pub fn set_title(&self, _title: &str) {
|
||||
debug!("`Window::set_title` is ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn set_transparent(&self, _transparent: bool) {
|
||||
debug!("`Window::set_transparent` is ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn set_blur(&self, _blur: bool) {
|
||||
debug!("`Window::set_blur` is ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn set_visible(&self, visible: bool) {
|
||||
self.window.setHidden(!visible)
|
||||
}
|
||||
|
||||
pub fn is_visible(&self) -> Option<bool> {
|
||||
warn!("`Window::is_visible` is ignored on iOS");
|
||||
None
|
||||
}
|
||||
|
||||
pub fn request_redraw(&self) {
|
||||
if self.gl_or_metal_backed {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
// `setNeedsDisplay` does nothing on UIViews which are directly backed by CAEAGLLayer or
|
||||
// CAMetalLayer. Ordinarily the OS sets up a bunch of UIKit state before
|
||||
// calling drawRect: on a UIView, but when using raw or gl/metal for drawing
|
||||
// this work is completely avoided.
|
||||
//
|
||||
// The docs for `setNeedsDisplay` don't mention `CAMetalLayer`; however, this has been
|
||||
// confirmed via testing.
|
||||
//
|
||||
// https://developer.apple.com/documentation/uikit/uiview/1622437-setneedsdisplay?language=objc
|
||||
app_state::queue_gl_or_metal_redraw(mtm, self.window.clone());
|
||||
} else {
|
||||
self.view.setNeedsDisplay();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pre_present_notify(&self) {}
|
||||
|
||||
pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
|
||||
let safe_area = self.safe_area_screen_space();
|
||||
let position =
|
||||
LogicalPosition { x: safe_area.origin.x as f64, y: safe_area.origin.y as f64 };
|
||||
let scale_factor = self.scale_factor();
|
||||
Ok(position.to_physical(scale_factor))
|
||||
}
|
||||
|
||||
pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
|
||||
let screen_frame = self.screen_frame();
|
||||
let position =
|
||||
LogicalPosition { x: screen_frame.origin.x as f64, y: screen_frame.origin.y as f64 };
|
||||
let scale_factor = self.scale_factor();
|
||||
Ok(position.to_physical(scale_factor))
|
||||
}
|
||||
|
||||
pub fn set_outer_position(&self, physical_position: Position) {
|
||||
let scale_factor = self.scale_factor();
|
||||
let position = physical_position.to_logical::<f64>(scale_factor);
|
||||
let screen_frame = self.screen_frame();
|
||||
let new_screen_frame = CGRect {
|
||||
origin: CGPoint { x: position.x as _, y: position.y as _ },
|
||||
size: screen_frame.size,
|
||||
};
|
||||
let bounds = self.rect_from_screen_space(new_screen_frame);
|
||||
self.window.setBounds(bounds);
|
||||
}
|
||||
|
||||
pub fn inner_size(&self) -> PhysicalSize<u32> {
|
||||
let scale_factor = self.scale_factor();
|
||||
let safe_area = self.safe_area_screen_space();
|
||||
let size = LogicalSize {
|
||||
width: safe_area.size.width as f64,
|
||||
height: safe_area.size.height as f64,
|
||||
};
|
||||
size.to_physical(scale_factor)
|
||||
}
|
||||
|
||||
pub fn outer_size(&self) -> PhysicalSize<u32> {
|
||||
let scale_factor = self.scale_factor();
|
||||
let screen_frame = self.screen_frame();
|
||||
let size = LogicalSize {
|
||||
width: screen_frame.size.width as f64,
|
||||
height: screen_frame.size.height as f64,
|
||||
};
|
||||
size.to_physical(scale_factor)
|
||||
}
|
||||
|
||||
pub fn request_inner_size(&self, _size: Size) -> Option<PhysicalSize<u32>> {
|
||||
Some(self.inner_size())
|
||||
}
|
||||
|
||||
pub fn set_min_inner_size(&self, _dimensions: Option<Size>) {
|
||||
warn!("`Window::set_min_inner_size` is ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn set_max_inner_size(&self, _dimensions: Option<Size>) {
|
||||
warn!("`Window::set_max_inner_size` is ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> {
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_resize_increments(&self, _increments: Option<Size>) {
|
||||
warn!("`Window::set_resize_increments` is ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn set_resizable(&self, _resizable: bool) {
|
||||
warn!("`Window::set_resizable` is ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn is_resizable(&self) -> bool {
|
||||
warn!("`Window::is_resizable` is ignored on iOS");
|
||||
false
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_enabled_buttons(&self, _buttons: WindowButtons) {
|
||||
warn!("`Window::set_enabled_buttons` is ignored on iOS");
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn enabled_buttons(&self) -> WindowButtons {
|
||||
warn!("`Window::enabled_buttons` is ignored on iOS");
|
||||
WindowButtons::all()
|
||||
}
|
||||
|
||||
pub fn scale_factor(&self) -> f64 {
|
||||
self.view.contentScaleFactor() as _
|
||||
}
|
||||
|
||||
pub fn set_cursor(&self, _cursor: Cursor) {
|
||||
debug!("`Window::set_cursor` ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn set_cursor_position(&self, _position: Position) -> Result<(), ExternalError> {
|
||||
Err(ExternalError::NotSupported(NotSupportedError::new()))
|
||||
}
|
||||
|
||||
pub fn set_cursor_grab(&self, _: CursorGrabMode) -> Result<(), ExternalError> {
|
||||
Err(ExternalError::NotSupported(NotSupportedError::new()))
|
||||
}
|
||||
|
||||
pub fn set_cursor_visible(&self, _visible: bool) {
|
||||
debug!("`Window::set_cursor_visible` is ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn drag_window(&self) -> Result<(), ExternalError> {
|
||||
Err(ExternalError::NotSupported(NotSupportedError::new()))
|
||||
}
|
||||
|
||||
pub fn drag_resize_window(&self, _direction: ResizeDirection) -> Result<(), ExternalError> {
|
||||
Err(ExternalError::NotSupported(NotSupportedError::new()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn show_window_menu(&self, _position: Position) {}
|
||||
|
||||
pub fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), ExternalError> {
|
||||
Err(ExternalError::NotSupported(NotSupportedError::new()))
|
||||
}
|
||||
|
||||
pub fn set_minimized(&self, _minimized: bool) {
|
||||
warn!("`Window::set_minimized` is ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn is_minimized(&self) -> Option<bool> {
|
||||
warn!("`Window::is_minimized` is ignored on iOS");
|
||||
None
|
||||
}
|
||||
|
||||
pub fn set_maximized(&self, _maximized: bool) {
|
||||
warn!("`Window::set_maximized` is ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn is_maximized(&self) -> bool {
|
||||
warn!("`Window::is_maximized` is ignored on iOS");
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn set_fullscreen(&self, monitor: Option<Fullscreen>) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
let uiscreen = match &monitor {
|
||||
Some(Fullscreen::Exclusive(video_mode)) => {
|
||||
let uiscreen = video_mode.monitor.ui_screen(mtm);
|
||||
uiscreen.setCurrentMode(Some(video_mode.screen_mode(mtm)));
|
||||
uiscreen.clone()
|
||||
},
|
||||
Some(Fullscreen::Borderless(Some(monitor))) => monitor.ui_screen(mtm).clone(),
|
||||
Some(Fullscreen::Borderless(None)) => {
|
||||
self.current_monitor_inner().ui_screen(mtm).clone()
|
||||
},
|
||||
None => {
|
||||
warn!("`Window::set_fullscreen(None)` ignored on iOS");
|
||||
return;
|
||||
},
|
||||
};
|
||||
|
||||
// this is pretty slow on iOS, so avoid doing it if we can
|
||||
let current = self.window.screen();
|
||||
if uiscreen != current {
|
||||
self.window.setScreen(&uiscreen);
|
||||
}
|
||||
|
||||
let bounds = uiscreen.bounds();
|
||||
self.window.setFrame(bounds);
|
||||
|
||||
// For external displays, we must disable overscan compensation or
|
||||
// the displayed image will have giant black bars surrounding it on
|
||||
// each side
|
||||
uiscreen.setOverscanCompensation(UIScreenOverscanCompensation::None);
|
||||
}
|
||||
|
||||
pub(crate) fn fullscreen(&self) -> Option<Fullscreen> {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
let monitor = self.current_monitor_inner();
|
||||
let uiscreen = monitor.ui_screen(mtm);
|
||||
let screen_space_bounds = self.screen_frame();
|
||||
let screen_bounds = uiscreen.bounds();
|
||||
|
||||
// TODO: track fullscreen instead of relying on brittle float comparisons
|
||||
if screen_space_bounds.origin.x == screen_bounds.origin.x
|
||||
&& screen_space_bounds.origin.y == screen_bounds.origin.y
|
||||
&& screen_space_bounds.size.width == screen_bounds.size.width
|
||||
&& screen_space_bounds.size.height == screen_bounds.size.height
|
||||
{
|
||||
Some(Fullscreen::Borderless(Some(monitor)))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_decorations(&self, _decorations: bool) {}
|
||||
|
||||
pub fn is_decorated(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub fn set_window_level(&self, _level: WindowLevel) {
|
||||
warn!("`Window::set_window_level` is ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn set_window_icon(&self, _icon: Option<Icon>) {
|
||||
warn!("`Window::set_window_icon` is ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn set_ime_cursor_area(&self, _position: Position, _size: Size) {
|
||||
warn!("`Window::set_ime_cursor_area` is ignored on iOS")
|
||||
}
|
||||
|
||||
/// Show / hide the keyboard. To show the keyboard, we call `becomeFirstResponder`,
|
||||
/// requesting focus for the [WinitView]. Since [WinitView] implements
|
||||
/// [objc2_ui_kit::UIKeyInput], the keyboard will be shown.
|
||||
/// <https://developer.apple.com/documentation/uikit/uiresponder/1621113-becomefirstresponder>
|
||||
pub fn set_ime_allowed(&self, allowed: bool) {
|
||||
if allowed {
|
||||
unsafe {
|
||||
self.view.becomeFirstResponder();
|
||||
}
|
||||
} else {
|
||||
unsafe {
|
||||
self.view.resignFirstResponder();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_ime_purpose(&self, _purpose: ImePurpose) {
|
||||
warn!("`Window::set_ime_purpose` is ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn focus_window(&self) {
|
||||
warn!("`Window::set_focus` is ignored on iOS")
|
||||
}
|
||||
|
||||
pub fn request_user_attention(&self, _request_type: Option<UserAttentionType>) {
|
||||
warn!("`Window::request_user_attention` is ignored on iOS")
|
||||
}
|
||||
|
||||
// Allow directly accessing the current monitor internally without unwrapping.
|
||||
fn current_monitor_inner(&self) -> MonitorHandle {
|
||||
MonitorHandle::new(self.window.screen())
|
||||
}
|
||||
|
||||
pub fn current_monitor(&self) -> Option<MonitorHandle> {
|
||||
Some(self.current_monitor_inner())
|
||||
}
|
||||
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
monitor::uiscreens(MainThreadMarker::new().unwrap())
|
||||
}
|
||||
|
||||
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||
#[allow(deprecated)]
|
||||
Some(MonitorHandle::new(UIScreen::mainScreen(MainThreadMarker::new().unwrap())))
|
||||
}
|
||||
|
||||
pub fn id(&self) -> WindowId {
|
||||
self.window.id()
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_04")]
|
||||
pub fn raw_window_handle_rwh_04(&self) -> rwh_04::RawWindowHandle {
|
||||
let mut window_handle = rwh_04::UiKitHandle::empty();
|
||||
window_handle.ui_window = Retained::as_ptr(&self.window) as _;
|
||||
window_handle.ui_view = Retained::as_ptr(&self.view) as _;
|
||||
window_handle.ui_view_controller = Retained::as_ptr(&self.view_controller) as _;
|
||||
rwh_04::RawWindowHandle::UiKit(window_handle)
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_05")]
|
||||
pub fn raw_window_handle_rwh_05(&self) -> rwh_05::RawWindowHandle {
|
||||
let mut window_handle = rwh_05::UiKitWindowHandle::empty();
|
||||
window_handle.ui_window = Retained::as_ptr(&self.window) as _;
|
||||
window_handle.ui_view = Retained::as_ptr(&self.view) as _;
|
||||
window_handle.ui_view_controller = Retained::as_ptr(&self.view_controller) as _;
|
||||
rwh_05::RawWindowHandle::UiKit(window_handle)
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_05")]
|
||||
pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
|
||||
rwh_05::RawDisplayHandle::UiKit(rwh_05::UiKitDisplayHandle::empty())
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
pub fn raw_window_handle_rwh_06(&self) -> rwh_06::RawWindowHandle {
|
||||
let mut window_handle = rwh_06::UiKitWindowHandle::new({
|
||||
let ui_view = Retained::as_ptr(&self.view) as _;
|
||||
std::ptr::NonNull::new(ui_view).expect("Retained<T> should never be null")
|
||||
});
|
||||
window_handle.ui_view_controller =
|
||||
std::ptr::NonNull::new(Retained::as_ptr(&self.view_controller) as _);
|
||||
rwh_06::RawWindowHandle::UiKit(window_handle)
|
||||
}
|
||||
|
||||
pub fn theme(&self) -> Option<Theme> {
|
||||
warn!("`Window::theme` is ignored on iOS");
|
||||
None
|
||||
}
|
||||
|
||||
pub fn set_content_protected(&self, _protected: bool) {}
|
||||
|
||||
pub fn has_focus(&self) -> bool {
|
||||
self.window.isKeyWindow()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_theme(&self, _theme: Option<Theme>) {
|
||||
warn!("`Window::set_theme` is ignored on iOS");
|
||||
}
|
||||
|
||||
pub fn title(&self) -> String {
|
||||
warn!("`Window::title` is ignored on iOS");
|
||||
String::new()
|
||||
}
|
||||
|
||||
pub fn reset_dead_keys(&self) {
|
||||
// Noop
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Window {
|
||||
inner: MainThreadBound<Inner>,
|
||||
}
|
||||
|
||||
impl Window {
|
||||
pub(crate) fn new(
|
||||
event_loop: &ActiveEventLoop,
|
||||
window_attributes: WindowAttributes,
|
||||
) -> Result<Window, RootOsError> {
|
||||
let mtm = event_loop.mtm;
|
||||
|
||||
if window_attributes.min_inner_size.is_some() {
|
||||
warn!("`WindowAttributes::min_inner_size` is ignored on iOS");
|
||||
}
|
||||
if window_attributes.max_inner_size.is_some() {
|
||||
warn!("`WindowAttributes::max_inner_size` is ignored on iOS");
|
||||
}
|
||||
|
||||
// TODO: transparency, visible
|
||||
|
||||
#[allow(deprecated)]
|
||||
let main_screen = UIScreen::mainScreen(mtm);
|
||||
let fullscreen = window_attributes.fullscreen.clone().map(Into::into);
|
||||
let screen = match fullscreen {
|
||||
Some(Fullscreen::Exclusive(ref video_mode)) => video_mode.monitor.ui_screen(mtm),
|
||||
Some(Fullscreen::Borderless(Some(ref monitor))) => monitor.ui_screen(mtm),
|
||||
Some(Fullscreen::Borderless(None)) | None => &main_screen,
|
||||
};
|
||||
|
||||
let screen_bounds = screen.bounds();
|
||||
|
||||
let frame = match window_attributes.inner_size {
|
||||
Some(dim) => {
|
||||
let scale_factor = screen.scale();
|
||||
let size = dim.to_logical::<f64>(scale_factor as f64);
|
||||
CGRect {
|
||||
origin: screen_bounds.origin,
|
||||
size: CGSize { width: size.width as _, height: size.height as _ },
|
||||
}
|
||||
},
|
||||
None => screen_bounds,
|
||||
};
|
||||
|
||||
let view = WinitView::new(mtm, &window_attributes, frame);
|
||||
|
||||
let gl_or_metal_backed =
|
||||
view.isKindOfClass(class!(CAMetalLayer)) || view.isKindOfClass(class!(CAEAGLLayer));
|
||||
|
||||
let view_controller = WinitViewController::new(mtm, &window_attributes, &view);
|
||||
let window = WinitUIWindow::new(mtm, &window_attributes, frame, &view_controller);
|
||||
|
||||
app_state::set_key_window(mtm, &window);
|
||||
|
||||
// Like the Windows and macOS backends, we send a `ScaleFactorChanged` and `Resized`
|
||||
// event on window creation if the DPI factor != 1.0
|
||||
let scale_factor = view.contentScaleFactor();
|
||||
let scale_factor = scale_factor as f64;
|
||||
if scale_factor != 1.0 {
|
||||
let bounds = view.bounds();
|
||||
let screen = window.screen();
|
||||
let screen_space = screen.coordinateSpace();
|
||||
let screen_frame = view.convertRect_toCoordinateSpace(bounds, &screen_space);
|
||||
let size = LogicalSize {
|
||||
width: screen_frame.size.width as f64,
|
||||
height: screen_frame.size.height as f64,
|
||||
};
|
||||
let window_id = RootWindowId(window.id());
|
||||
app_state::handle_nonuser_events(
|
||||
mtm,
|
||||
std::iter::once(EventWrapper::ScaleFactorChanged(app_state::ScaleFactorChanged {
|
||||
window: window.clone(),
|
||||
scale_factor,
|
||||
suggested_size: size.to_physical(scale_factor),
|
||||
}))
|
||||
.chain(std::iter::once(EventWrapper::StaticEvent(
|
||||
Event::WindowEvent {
|
||||
window_id,
|
||||
event: WindowEvent::Resized(size.to_physical(scale_factor)),
|
||||
},
|
||||
))),
|
||||
);
|
||||
}
|
||||
|
||||
let inner = Inner { window, view_controller, view, gl_or_metal_backed };
|
||||
Ok(Window { inner: MainThreadBound::new(inner, mtm) })
|
||||
}
|
||||
|
||||
pub(crate) fn maybe_queue_on_main(&self, f: impl FnOnce(&Inner) + Send + 'static) {
|
||||
// For now, don't actually do queuing, since it may be less predictable
|
||||
self.maybe_wait_on_main(f)
|
||||
}
|
||||
|
||||
pub(crate) fn maybe_wait_on_main<R: Send>(&self, f: impl FnOnce(&Inner) -> R + Send) -> R {
|
||||
self.inner.get_on_main(|inner| f(inner))
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
#[inline]
|
||||
pub(crate) fn raw_window_handle_rwh_06(
|
||||
&self,
|
||||
) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> {
|
||||
if let Some(mtm) = MainThreadMarker::new() {
|
||||
Ok(self.inner.get(mtm).raw_window_handle_rwh_06())
|
||||
} else {
|
||||
Err(rwh_06::HandleError::Unavailable)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
#[inline]
|
||||
pub(crate) fn raw_display_handle_rwh_06(
|
||||
&self,
|
||||
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
|
||||
Ok(rwh_06::RawDisplayHandle::UiKit(rwh_06::UiKitDisplayHandle::new()))
|
||||
}
|
||||
}
|
||||
|
||||
// WindowExtIOS
|
||||
impl Inner {
|
||||
pub fn set_scale_factor(&self, scale_factor: f64) {
|
||||
assert!(
|
||||
dpi::validate_scale_factor(scale_factor),
|
||||
"`WindowExtIOS::set_scale_factor` received an invalid hidpi factor"
|
||||
);
|
||||
let scale_factor = scale_factor as CGFloat;
|
||||
self.view.setContentScaleFactor(scale_factor);
|
||||
}
|
||||
|
||||
pub fn set_valid_orientations(&self, valid_orientations: ValidOrientations) {
|
||||
self.view_controller.set_supported_interface_orientations(
|
||||
MainThreadMarker::new().unwrap(),
|
||||
valid_orientations,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn set_prefers_home_indicator_hidden(&self, hidden: bool) {
|
||||
self.view_controller.set_prefers_home_indicator_auto_hidden(hidden);
|
||||
}
|
||||
|
||||
pub fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge) {
|
||||
self.view_controller.set_preferred_screen_edges_deferring_system_gestures(edges);
|
||||
}
|
||||
|
||||
pub fn set_prefers_status_bar_hidden(&self, hidden: bool) {
|
||||
self.view_controller.set_prefers_status_bar_hidden(hidden);
|
||||
}
|
||||
|
||||
pub fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle) {
|
||||
self.view_controller.set_preferred_status_bar_style(status_bar_style);
|
||||
}
|
||||
|
||||
pub fn recognize_pinch_gesture(&self, should_recognize: bool) {
|
||||
self.view.recognize_pinch_gesture(should_recognize);
|
||||
}
|
||||
|
||||
pub fn recognize_pan_gesture(
|
||||
&self,
|
||||
should_recognize: bool,
|
||||
minimum_number_of_touches: u8,
|
||||
maximum_number_of_touches: u8,
|
||||
) {
|
||||
self.view.recognize_pan_gesture(
|
||||
should_recognize,
|
||||
minimum_number_of_touches,
|
||||
maximum_number_of_touches,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn recognize_doubletap_gesture(&self, should_recognize: bool) {
|
||||
self.view.recognize_doubletap_gesture(should_recognize);
|
||||
}
|
||||
|
||||
pub fn recognize_rotation_gesture(&self, should_recognize: bool) {
|
||||
self.view.recognize_rotation_gesture(should_recognize);
|
||||
}
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
fn screen_frame(&self) -> CGRect {
|
||||
self.rect_to_screen_space(self.window.bounds())
|
||||
}
|
||||
|
||||
fn rect_to_screen_space(&self, rect: CGRect) -> CGRect {
|
||||
let screen_space = self.window.screen().coordinateSpace();
|
||||
self.window.convertRect_toCoordinateSpace(rect, &screen_space)
|
||||
}
|
||||
|
||||
fn rect_from_screen_space(&self, rect: CGRect) -> CGRect {
|
||||
let screen_space = self.window.screen().coordinateSpace();
|
||||
self.window.convertRect_fromCoordinateSpace(rect, &screen_space)
|
||||
}
|
||||
|
||||
fn safe_area_screen_space(&self) -> CGRect {
|
||||
let bounds = self.window.bounds();
|
||||
if app_state::os_capabilities().safe_area {
|
||||
let safe_area = self.window.safeAreaInsets();
|
||||
let safe_bounds = CGRect {
|
||||
origin: CGPoint {
|
||||
x: bounds.origin.x + safe_area.left,
|
||||
y: bounds.origin.y + safe_area.top,
|
||||
},
|
||||
size: CGSize {
|
||||
width: bounds.size.width - safe_area.left - safe_area.right,
|
||||
height: bounds.size.height - safe_area.top - safe_area.bottom,
|
||||
},
|
||||
};
|
||||
self.rect_to_screen_space(safe_bounds)
|
||||
} else {
|
||||
let screen_frame = self.rect_to_screen_space(bounds);
|
||||
let status_bar_frame = {
|
||||
let app = UIApplication::sharedApplication(MainThreadMarker::new().unwrap());
|
||||
#[allow(deprecated)]
|
||||
app.statusBarFrame()
|
||||
};
|
||||
let (y, height) = if screen_frame.origin.y > status_bar_frame.size.height {
|
||||
(screen_frame.origin.y, screen_frame.size.height)
|
||||
} else {
|
||||
let y = status_bar_frame.size.height;
|
||||
let height = screen_frame.size.height
|
||||
- (status_bar_frame.size.height - screen_frame.origin.y);
|
||||
(y, height)
|
||||
};
|
||||
CGRect {
|
||||
origin: CGPoint { x: screen_frame.origin.x, y },
|
||||
size: CGSize { width: screen_frame.size.width, height },
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct WindowId {
|
||||
window: *mut WinitUIWindow,
|
||||
}
|
||||
|
||||
impl WindowId {
|
||||
pub const fn dummy() -> Self {
|
||||
WindowId { window: std::ptr::null_mut() }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WindowId> for u64 {
|
||||
fn from(window_id: WindowId) -> Self {
|
||||
window_id.window as u64
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u64> for WindowId {
|
||||
fn from(raw_id: u64) -> Self {
|
||||
Self { window: raw_id as _ }
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for WindowId {}
|
||||
unsafe impl Sync for WindowId {}
|
||||
|
||||
impl From<&AnyObject> for WindowId {
|
||||
fn from(window: &AnyObject) -> WindowId {
|
||||
WindowId { window: window as *const _ as _ }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PlatformSpecificWindowAttributes {
|
||||
pub scale_factor: Option<f64>,
|
||||
pub valid_orientations: ValidOrientations,
|
||||
pub prefers_home_indicator_hidden: bool,
|
||||
pub prefers_status_bar_hidden: bool,
|
||||
pub preferred_status_bar_style: StatusBarStyle,
|
||||
pub preferred_screen_edges_deferring_system_gestures: ScreenEdge,
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
pub mod xkb;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,28 +0,0 @@
|
||||
//! An event loop proxy.
|
||||
|
||||
use std::sync::mpsc::SendError;
|
||||
|
||||
use sctk::reexports::calloop::channel::Sender;
|
||||
|
||||
use crate::event_loop::EventLoopClosed;
|
||||
|
||||
/// A handle that can be sent across the threads and used to wake up the `EventLoop`.
|
||||
pub struct EventLoopProxy<T: 'static> {
|
||||
user_events_sender: Sender<T>,
|
||||
}
|
||||
|
||||
impl<T: 'static> Clone for EventLoopProxy<T> {
|
||||
fn clone(&self) -> Self {
|
||||
EventLoopProxy { user_events_sender: self.user_events_sender.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> EventLoopProxy<T> {
|
||||
pub fn new(user_events_sender: Sender<T>) -> Self {
|
||||
Self { user_events_sender }
|
||||
}
|
||||
|
||||
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
|
||||
self.user_events_sender.send(event).map_err(|SendError(error)| EventLoopClosed(error))
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
//! Winit's Wayland backend.
|
||||
|
||||
use std::fmt::Display;
|
||||
use std::sync::Arc;
|
||||
|
||||
use sctk::reexports::client::globals::{BindError, GlobalError};
|
||||
use sctk::reexports::client::protocol::wl_surface::WlSurface;
|
||||
use sctk::reexports::client::{self, ConnectError, DispatchError, Proxy};
|
||||
|
||||
pub(super) use crate::cursor::OnlyCursorImage as CustomCursor;
|
||||
use crate::dpi::{LogicalSize, PhysicalSize};
|
||||
pub use crate::platform_impl::platform::{OsError, WindowId};
|
||||
pub use event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy};
|
||||
pub use output::{MonitorHandle, VideoModeHandle};
|
||||
pub use window::Window;
|
||||
|
||||
mod event_loop;
|
||||
mod output;
|
||||
mod seat;
|
||||
mod state;
|
||||
mod types;
|
||||
mod window;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum WaylandError {
|
||||
/// Error connecting to the socket.
|
||||
Connection(ConnectError),
|
||||
|
||||
/// Error binding the global.
|
||||
Global(GlobalError),
|
||||
|
||||
// Bind error.
|
||||
Bind(BindError),
|
||||
|
||||
/// Error during the dispatching the event queue.
|
||||
Dispatch(DispatchError),
|
||||
|
||||
/// Calloop error.
|
||||
Calloop(calloop::Error),
|
||||
|
||||
/// Wayland
|
||||
Wire(client::backend::WaylandError),
|
||||
}
|
||||
|
||||
impl Display for WaylandError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
WaylandError::Connection(error) => error.fmt(f),
|
||||
WaylandError::Global(error) => error.fmt(f),
|
||||
WaylandError::Bind(error) => error.fmt(f),
|
||||
WaylandError::Dispatch(error) => error.fmt(f),
|
||||
WaylandError::Calloop(error) => error.fmt(f),
|
||||
WaylandError::Wire(error) => error.fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WaylandError> for OsError {
|
||||
fn from(value: WaylandError) -> Self {
|
||||
Self::WaylandError(Arc::new(value))
|
||||
}
|
||||
}
|
||||
|
||||
/// Dummy device id, since Wayland doesn't have device events.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DeviceId;
|
||||
|
||||
impl DeviceId {
|
||||
pub const fn dummy() -> Self {
|
||||
DeviceId
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the WindowId out of the surface.
|
||||
#[inline]
|
||||
fn make_wid(surface: &WlSurface) -> WindowId {
|
||||
WindowId(surface.id().as_ptr() as u64)
|
||||
}
|
||||
|
||||
/// 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,163 +0,0 @@
|
||||
use sctk::reexports::client::protocol::wl_output::WlOutput;
|
||||
use sctk::reexports::client::Proxy;
|
||||
|
||||
use sctk::output::OutputData;
|
||||
|
||||
use crate::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize};
|
||||
use crate::platform_impl::platform::VideoModeHandle as PlatformVideoModeHandle;
|
||||
|
||||
use super::event_loop::ActiveEventLoop;
|
||||
|
||||
impl ActiveEventLoop {
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
|
||||
self.state.borrow().output_state.outputs().map(MonitorHandle::new)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||
// There's no primary monitor on Wayland.
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[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 size(&self) -> PhysicalSize<u32> {
|
||||
let output_data = self.proxy.data::<OutputData>().unwrap();
|
||||
let dimensions = output_data.with_output_info(|info| {
|
||||
info.modes.iter().find_map(|mode| mode.current.then_some(mode.dimensions))
|
||||
});
|
||||
|
||||
match dimensions {
|
||||
Some((width, height)) => (width as u32, height as u32),
|
||||
_ => (0, 0),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn position(&self) -> PhysicalPosition<i32> {
|
||||
let output_data = self.proxy.data::<OutputData>().unwrap();
|
||||
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 refresh_rate_millihertz(&self) -> Option<u32> {
|
||||
let output_data = self.proxy.data::<OutputData>().unwrap();
|
||||
output_data.with_output_info(|info| {
|
||||
info.modes.iter().find_map(|mode| mode.current.then_some(mode.refresh_rate as u32))
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn scale_factor(&self) -> i32 {
|
||||
let output_data = self.proxy.data::<OutputData>().unwrap();
|
||||
output_data.scale_factor()
|
||||
}
|
||||
|
||||
#[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 {
|
||||
size: (mode.dimensions.0 as u32, mode.dimensions.1 as u32).into(),
|
||||
refresh_rate_millihertz: mode.refresh_rate as u32,
|
||||
bit_depth: 32,
|
||||
monitor: monitor.clone(),
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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) bit_depth: u16,
|
||||
pub(crate) refresh_rate_millihertz: u32,
|
||||
pub(crate) monitor: MonitorHandle,
|
||||
}
|
||||
|
||||
impl VideoModeHandle {
|
||||
#[inline]
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
self.size
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn bit_depth(&self) -> u16 {
|
||||
self.bit_depth
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn refresh_rate_millihertz(&self) -> u32 {
|
||||
self.refresh_rate_millihertz
|
||||
}
|
||||
|
||||
pub fn monitor(&self) -> MonitorHandle {
|
||||
self.monitor.clone()
|
||||
}
|
||||
}
|
||||
@@ -1,197 +0,0 @@
|
||||
use std::ops::Deref;
|
||||
|
||||
use sctk::globals::GlobalData;
|
||||
use sctk::reexports::client::{Connection, Proxy, QueueHandle};
|
||||
|
||||
use sctk::reexports::client::globals::{BindError, GlobalList};
|
||||
use sctk::reexports::client::protocol::wl_surface::WlSurface;
|
||||
use sctk::reexports::client::{delegate_dispatch, Dispatch};
|
||||
use sctk::reexports::protocols::wp::text_input::zv3::client::zwp_text_input_manager_v3::ZwpTextInputManagerV3;
|
||||
use sctk::reexports::protocols::wp::text_input::zv3::client::zwp_text_input_v3::{
|
||||
ContentHint, ContentPurpose, Event as TextInputEvent, ZwpTextInputV3,
|
||||
};
|
||||
|
||||
use 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,59 +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,174 +0,0 @@
|
||||
use std::ffi::CString;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
use std::{iter, slice};
|
||||
|
||||
use x11rb::connection::Connection;
|
||||
|
||||
use crate::platform_impl::PlatformCustomCursorSource;
|
||||
use crate::window::CursorIcon;
|
||||
|
||||
use super::super::ActiveEventLoop;
|
||||
use super::*;
|
||||
|
||||
impl XConnection {
|
||||
pub fn set_cursor_icon(&self, window: xproto::Window, cursor: Option<CursorIcon>) {
|
||||
let cursor = *self
|
||||
.cursor_cache
|
||||
.lock()
|
||||
.unwrap()
|
||||
.entry(cursor)
|
||||
.or_insert_with(|| self.get_cursor(cursor));
|
||||
|
||||
self.update_cursor(window, cursor).expect("Failed to set cursor");
|
||||
}
|
||||
|
||||
pub(crate) fn set_custom_cursor(&self, window: xproto::Window, cursor: &CustomCursor) {
|
||||
self.update_cursor(window, cursor.inner.cursor).expect("Failed to set cursor");
|
||||
}
|
||||
|
||||
fn create_empty_cursor(&self) -> ffi::Cursor {
|
||||
let data = 0;
|
||||
let pixmap = unsafe {
|
||||
let screen = (self.xlib.XDefaultScreen)(self.display);
|
||||
let window = (self.xlib.XRootWindow)(self.display, screen);
|
||||
(self.xlib.XCreateBitmapFromData)(self.display, window, &data, 1, 1)
|
||||
};
|
||||
|
||||
if pixmap == 0 {
|
||||
panic!("failed to allocate pixmap for cursor");
|
||||
}
|
||||
|
||||
unsafe {
|
||||
// We don't care about this color, since it only fills bytes
|
||||
// in the pixmap which are not 0 in the mask.
|
||||
let mut dummy_color = MaybeUninit::uninit();
|
||||
let cursor = (self.xlib.XCreatePixmapCursor)(
|
||||
self.display,
|
||||
pixmap,
|
||||
pixmap,
|
||||
dummy_color.as_mut_ptr(),
|
||||
dummy_color.as_mut_ptr(),
|
||||
0,
|
||||
0,
|
||||
);
|
||||
(self.xlib.XFreePixmap)(self.display, pixmap);
|
||||
|
||||
cursor
|
||||
}
|
||||
}
|
||||
|
||||
fn get_cursor(&self, cursor: Option<CursorIcon>) -> ffi::Cursor {
|
||||
let cursor = match cursor {
|
||||
Some(cursor) => cursor,
|
||||
None => return self.create_empty_cursor(),
|
||||
};
|
||||
|
||||
let mut xcursor = 0;
|
||||
for &name in iter::once(&cursor.name()).chain(cursor.alt_names().iter()) {
|
||||
let name = CString::new(name).unwrap();
|
||||
xcursor = unsafe {
|
||||
(self.xcursor.XcursorLibraryLoadCursor)(
|
||||
self.display,
|
||||
name.as_ptr() as *const c_char,
|
||||
)
|
||||
};
|
||||
|
||||
if xcursor != 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
xcursor
|
||||
}
|
||||
|
||||
fn update_cursor(&self, window: xproto::Window, cursor: ffi::Cursor) -> Result<(), X11Error> {
|
||||
self.xcb_connection()
|
||||
.change_window_attributes(
|
||||
window,
|
||||
&xproto::ChangeWindowAttributesAux::new().cursor(cursor as xproto::Cursor),
|
||||
)?
|
||||
.ignore_error();
|
||||
|
||||
self.xcb_connection().flush()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum SelectedCursor {
|
||||
Custom(CustomCursor),
|
||||
Named(CursorIcon),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CustomCursor {
|
||||
inner: Arc<CustomCursorInner>,
|
||||
}
|
||||
|
||||
impl Hash for CustomCursor {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
Arc::as_ptr(&self.inner).hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for CustomCursor {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
Arc::ptr_eq(&self.inner, &other.inner)
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for CustomCursor {}
|
||||
|
||||
impl CustomCursor {
|
||||
pub(crate) fn new(
|
||||
event_loop: &ActiveEventLoop,
|
||||
cursor: PlatformCustomCursorSource,
|
||||
) -> CustomCursor {
|
||||
unsafe {
|
||||
let ximage = (event_loop.xconn.xcursor.XcursorImageCreate)(
|
||||
cursor.0.width as i32,
|
||||
cursor.0.height as i32,
|
||||
);
|
||||
if ximage.is_null() {
|
||||
panic!("failed to allocate cursor image");
|
||||
}
|
||||
(*ximage).xhot = cursor.0.hotspot_x as u32;
|
||||
(*ximage).yhot = cursor.0.hotspot_y as u32;
|
||||
(*ximage).delay = 0;
|
||||
|
||||
let dst = slice::from_raw_parts_mut((*ximage).pixels, cursor.0.rgba.len() / 4);
|
||||
for (dst, chunk) in dst.iter_mut().zip(cursor.0.rgba.chunks_exact(4)) {
|
||||
*dst = (chunk[0] as u32) << 16
|
||||
| (chunk[1] as u32) << 8
|
||||
| (chunk[2] as u32)
|
||||
| (chunk[3] as u32) << 24;
|
||||
}
|
||||
|
||||
let cursor =
|
||||
(event_loop.xconn.xcursor.XcursorImageLoadCursor)(event_loop.xconn.display, ximage);
|
||||
(event_loop.xconn.xcursor.XcursorImageDestroy)(ximage);
|
||||
Self { inner: Arc::new(CustomCursorInner { xconn: event_loop.xconn.clone(), cursor }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CustomCursorInner {
|
||||
xconn: Arc<XConnection>,
|
||||
cursor: ffi::Cursor,
|
||||
}
|
||||
|
||||
impl Drop for CustomCursorInner {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
(self.xconn.xlib.XFreeCursor)(self.xconn.display, self.cursor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for SelectedCursor {
|
||||
fn default() -> Self {
|
||||
SelectedCursor::Named(Default::default())
|
||||
}
|
||||
}
|
||||
@@ -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,87 +0,0 @@
|
||||
#![allow(clippy::unnecessary_cast)]
|
||||
|
||||
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::ApplicationDelegate;
|
||||
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 delegate = ApplicationDelegate::get(MainThreadMarker::from(self));
|
||||
maybe_dispatch_device_event(&delegate, event);
|
||||
unsafe { msg_send![super(self), sendEvent: event] }
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
fn maybe_dispatch_device_event(delegate: &ApplicationDelegate, 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 {
|
||||
delegate.maybe_queue_device_event(DeviceEvent::Motion { axis: 0, value: delta_x });
|
||||
}
|
||||
|
||||
if delta_y != 0.0 {
|
||||
delegate.maybe_queue_device_event(DeviceEvent::Motion { axis: 1, value: delta_y })
|
||||
}
|
||||
|
||||
if delta_x != 0.0 || delta_y != 0.0 {
|
||||
delegate.maybe_queue_device_event(DeviceEvent::MouseMotion {
|
||||
delta: (delta_x, delta_y),
|
||||
});
|
||||
}
|
||||
},
|
||||
NSEventType::LeftMouseDown | NSEventType::RightMouseDown | NSEventType::OtherMouseDown => {
|
||||
delegate.maybe_queue_device_event(DeviceEvent::Button {
|
||||
button: unsafe { event.buttonNumber() } as u32,
|
||||
state: ElementState::Pressed,
|
||||
});
|
||||
},
|
||||
NSEventType::LeftMouseUp | NSEventType::RightMouseUp | NSEventType::OtherMouseUp => {
|
||||
delegate.maybe_queue_device_event(DeviceEvent::Button {
|
||||
button: unsafe { event.buttonNumber() } as u32,
|
||||
state: ElementState::Released,
|
||||
});
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
@@ -1,443 +0,0 @@
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::mem;
|
||||
use std::rc::Weak;
|
||||
use std::time::Instant;
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2::{declare_class, msg_send_id, mutability, ClassType, DeclaredClass};
|
||||
use objc2_app_kit::{
|
||||
NSApplication, NSApplicationActivationPolicy, NSApplicationDelegate, NSRunningApplication,
|
||||
};
|
||||
use objc2_foundation::{MainThreadMarker, NSNotification, NSObject, NSObjectProtocol};
|
||||
|
||||
use super::event_handler::EventHandler;
|
||||
use super::event_loop::{stop_app_immediately, ActiveEventLoop, PanicInfo};
|
||||
use super::observer::{EventLoopWaker, RunLoop};
|
||||
use super::{menu, WindowId, DEVICE_ID};
|
||||
use crate::event::{DeviceEvent, Event, StartCause, WindowEvent};
|
||||
use crate::event_loop::{ActiveEventLoop as RootActiveEventLoop, ControlFlow};
|
||||
use crate::window::WindowId as RootWindowId;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct AppState {
|
||||
activation_policy: Option<NSApplicationActivationPolicy>,
|
||||
default_menu: bool,
|
||||
activate_ignoring_other_apps: bool,
|
||||
run_loop: RunLoop,
|
||||
event_handler: EventHandler,
|
||||
stop_on_launch: Cell<bool>,
|
||||
stop_before_wait: Cell<bool>,
|
||||
stop_after_wait: Cell<bool>,
|
||||
stop_on_redraw: Cell<bool>,
|
||||
/// Whether `applicationDidFinishLaunching:` has been run or not.
|
||||
is_launched: Cell<bool>,
|
||||
/// Whether an `EventLoop` is currently running.
|
||||
is_running: Cell<bool>,
|
||||
/// Whether the user has requested the event loop to exit.
|
||||
exit: Cell<bool>,
|
||||
control_flow: Cell<ControlFlow>,
|
||||
waker: RefCell<EventLoopWaker>,
|
||||
start_time: Cell<Option<Instant>>,
|
||||
wait_timeout: Cell<Option<Instant>>,
|
||||
pending_redraw: RefCell<Vec<WindowId>>,
|
||||
// NOTE: This is strongly referenced by our `NSWindowDelegate` and our `NSView` subclass, and
|
||||
// as such should be careful to not add fields that, in turn, strongly reference those.
|
||||
}
|
||||
|
||||
declare_class!(
|
||||
#[derive(Debug)]
|
||||
pub(super) struct ApplicationDelegate;
|
||||
|
||||
unsafe impl ClassType for ApplicationDelegate {
|
||||
type Super = NSObject;
|
||||
type Mutability = mutability::MainThreadOnly;
|
||||
const NAME: &'static str = "WinitApplicationDelegate";
|
||||
}
|
||||
|
||||
impl DeclaredClass for ApplicationDelegate {
|
||||
type Ivars = AppState;
|
||||
}
|
||||
|
||||
unsafe impl NSObjectProtocol for ApplicationDelegate {}
|
||||
|
||||
unsafe impl NSApplicationDelegate for ApplicationDelegate {
|
||||
#[method(applicationDidFinishLaunching:)]
|
||||
fn app_did_finish_launching(&self, notification: &NSNotification) {
|
||||
self.did_finish_launching(notification)
|
||||
}
|
||||
|
||||
#[method(applicationWillTerminate:)]
|
||||
fn app_will_terminate(&self, notification: &NSNotification) {
|
||||
self.will_terminate(notification)
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl ApplicationDelegate {
|
||||
pub(super) fn new(
|
||||
mtm: MainThreadMarker,
|
||||
activation_policy: Option<NSApplicationActivationPolicy>,
|
||||
default_menu: bool,
|
||||
activate_ignoring_other_apps: bool,
|
||||
) -> Retained<Self> {
|
||||
let this = mtm.alloc().set_ivars(AppState {
|
||||
activation_policy,
|
||||
default_menu,
|
||||
activate_ignoring_other_apps,
|
||||
run_loop: RunLoop::main(mtm),
|
||||
event_handler: EventHandler::new(),
|
||||
stop_on_launch: Cell::new(false),
|
||||
stop_before_wait: Cell::new(false),
|
||||
stop_after_wait: Cell::new(false),
|
||||
stop_on_redraw: Cell::new(false),
|
||||
is_launched: Cell::new(false),
|
||||
is_running: Cell::new(false),
|
||||
exit: Cell::new(false),
|
||||
control_flow: Cell::new(ControlFlow::default()),
|
||||
waker: RefCell::new(EventLoopWaker::new()),
|
||||
start_time: Cell::new(None),
|
||||
wait_timeout: Cell::new(None),
|
||||
pending_redraw: RefCell::new(vec![]),
|
||||
});
|
||||
unsafe { msg_send_id![super(this), init] }
|
||||
}
|
||||
|
||||
// NOTE: This will, globally, only be run once, no matter how many
|
||||
// `EventLoop`s the user creates.
|
||||
fn did_finish_launching(&self, _notification: &NSNotification) {
|
||||
trace_scope!("applicationDidFinishLaunching:");
|
||||
self.ivars().is_launched.set(true);
|
||||
|
||||
let mtm = MainThreadMarker::from(self);
|
||||
let app = NSApplication::sharedApplication(mtm);
|
||||
// We need to delay setting the activation policy and activating the app
|
||||
// until `applicationDidFinishLaunching` has been called. Otherwise the
|
||||
// menu bar is initially unresponsive on macOS 10.15.
|
||||
// If no activation policy is explicitly provided, do not set it at all
|
||||
// to allow the package manifest to define behavior via LSUIElement.
|
||||
if let Some(activation_policy) = self.ivars().activation_policy {
|
||||
app.setActivationPolicy(activation_policy);
|
||||
} else {
|
||||
// If no activation policy is explicitly provided, and the application
|
||||
// is bundled, do not set the activation policy at all, to allow the
|
||||
// package manifest to define the behavior via LSUIElement.
|
||||
//
|
||||
// See:
|
||||
// - https://github.com/rust-windowing/winit/issues/261
|
||||
// - https://github.com/rust-windowing/winit/issues/3958
|
||||
let is_bundled =
|
||||
unsafe { NSRunningApplication::currentApplication().bundleIdentifier().is_some() };
|
||||
if !is_bundled {
|
||||
app.setActivationPolicy(NSApplicationActivationPolicy::Regular);
|
||||
}
|
||||
}
|
||||
|
||||
window_activation_hack(&app);
|
||||
#[allow(deprecated)]
|
||||
app.activateIgnoringOtherApps(self.ivars().activate_ignoring_other_apps);
|
||||
|
||||
if self.ivars().default_menu {
|
||||
// The menubar initialization should be before the `NewEvents` event, to allow
|
||||
// overriding of the default menu even if it's created
|
||||
menu::initialize(&app);
|
||||
}
|
||||
|
||||
self.ivars().waker.borrow_mut().start();
|
||||
|
||||
self.set_is_running(true);
|
||||
self.dispatch_init_events();
|
||||
|
||||
// If the application is being launched via `EventLoop::pump_app_events()` then we'll
|
||||
// want to stop the app once it is launched (and return to the external loop)
|
||||
//
|
||||
// In this case we still want to consider Winit's `EventLoop` to be "running",
|
||||
// so we call `start_running()` above.
|
||||
if self.ivars().stop_on_launch.get() {
|
||||
// NOTE: the original idea had been to only stop the underlying `RunLoop`
|
||||
// for the app but that didn't work as expected (`-[NSApplication run]`
|
||||
// effectively ignored the attempt to stop the RunLoop and re-started it).
|
||||
//
|
||||
// So we return from `pump_events` by stopping the application.
|
||||
let app = NSApplication::sharedApplication(mtm);
|
||||
stop_app_immediately(&app);
|
||||
}
|
||||
}
|
||||
|
||||
fn will_terminate(&self, _notification: &NSNotification) {
|
||||
trace_scope!("applicationWillTerminate:");
|
||||
// TODO: Notify every window that it will be destroyed, like done in iOS?
|
||||
self.internal_exit();
|
||||
}
|
||||
|
||||
pub fn get(mtm: MainThreadMarker) -> Retained<Self> {
|
||||
let app = NSApplication::sharedApplication(mtm);
|
||||
let delegate =
|
||||
unsafe { app.delegate() }.expect("a delegate was not configured on the application");
|
||||
if delegate.is_kind_of::<Self>() {
|
||||
// SAFETY: Just checked that the delegate is an instance of `ApplicationDelegate`
|
||||
unsafe { Retained::cast(delegate) }
|
||||
} else {
|
||||
panic!("tried to get a delegate that was not the one Winit has registered")
|
||||
}
|
||||
}
|
||||
|
||||
/// Place the event handler in the application delegate for the duration
|
||||
/// of the given closure.
|
||||
pub fn set_event_handler<R>(
|
||||
&self,
|
||||
handler: impl FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop),
|
||||
closure: impl FnOnce() -> R,
|
||||
) -> R {
|
||||
self.ivars().event_handler.set(handler, closure)
|
||||
}
|
||||
|
||||
/// If `pump_events` is called to progress the event loop then we
|
||||
/// bootstrap the event loop via `-[NSApplication run]` but will use
|
||||
/// `CFRunLoopRunInMode` for subsequent calls to `pump_events`.
|
||||
pub fn set_stop_on_launch(&self) {
|
||||
self.ivars().stop_on_launch.set(true);
|
||||
}
|
||||
|
||||
pub fn set_stop_before_wait(&self, value: bool) {
|
||||
self.ivars().stop_before_wait.set(value)
|
||||
}
|
||||
|
||||
pub fn set_stop_after_wait(&self, value: bool) {
|
||||
self.ivars().stop_after_wait.set(value)
|
||||
}
|
||||
|
||||
pub fn set_stop_on_redraw(&self, value: bool) {
|
||||
self.ivars().stop_on_redraw.set(value)
|
||||
}
|
||||
|
||||
pub fn set_wait_timeout(&self, value: Option<Instant>) {
|
||||
self.ivars().wait_timeout.set(value)
|
||||
}
|
||||
|
||||
/// Clears the `running` state and resets the `control_flow` state when an `EventLoop` exits.
|
||||
///
|
||||
/// 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.
|
||||
pub fn internal_exit(&self) {
|
||||
self.handle_event(Event::LoopExiting);
|
||||
|
||||
self.set_is_running(false);
|
||||
self.set_stop_on_redraw(false);
|
||||
self.set_stop_before_wait(false);
|
||||
self.set_stop_after_wait(false);
|
||||
self.set_wait_timeout(None);
|
||||
}
|
||||
|
||||
pub fn is_launched(&self) -> bool {
|
||||
self.ivars().is_launched.get()
|
||||
}
|
||||
|
||||
pub fn set_is_running(&self, value: bool) {
|
||||
self.ivars().is_running.set(value)
|
||||
}
|
||||
|
||||
pub fn is_running(&self) -> bool {
|
||||
self.ivars().is_running.get()
|
||||
}
|
||||
|
||||
pub fn exit(&self) {
|
||||
self.ivars().exit.set(true)
|
||||
}
|
||||
|
||||
pub fn clear_exit(&self) {
|
||||
self.ivars().exit.set(false)
|
||||
}
|
||||
|
||||
pub fn exiting(&self) -> bool {
|
||||
self.ivars().exit.get()
|
||||
}
|
||||
|
||||
pub fn set_control_flow(&self, value: ControlFlow) {
|
||||
self.ivars().control_flow.set(value)
|
||||
}
|
||||
|
||||
pub fn control_flow(&self) -> ControlFlow {
|
||||
self.ivars().control_flow.get()
|
||||
}
|
||||
|
||||
pub fn maybe_queue_window_event(&self, window_id: WindowId, event: WindowEvent) {
|
||||
self.maybe_queue_event(Event::WindowEvent { window_id: RootWindowId(window_id), event });
|
||||
}
|
||||
|
||||
pub fn handle_window_event(&self, window_id: WindowId, event: WindowEvent) {
|
||||
self.handle_event(Event::WindowEvent { window_id: RootWindowId(window_id), event });
|
||||
}
|
||||
|
||||
pub fn maybe_queue_device_event(&self, event: DeviceEvent) {
|
||||
self.maybe_queue_event(Event::DeviceEvent { device_id: DEVICE_ID, event });
|
||||
}
|
||||
|
||||
pub fn handle_redraw(&self, window_id: WindowId) {
|
||||
let mtm = MainThreadMarker::from(self);
|
||||
// Redraw request might come out of order from the OS.
|
||||
// -> Don't go back into the event handler when our callstack originates from there
|
||||
if !self.ivars().event_handler.in_use() {
|
||||
self.handle_event(Event::WindowEvent {
|
||||
window_id: RootWindowId(window_id),
|
||||
event: WindowEvent::RedrawRequested,
|
||||
});
|
||||
|
||||
// `pump_events` will request to stop immediately _after_ dispatching RedrawRequested
|
||||
// events as a way to ensure that `pump_events` can't block an external loop
|
||||
// indefinitely
|
||||
if self.ivars().stop_on_redraw.get() {
|
||||
let app = NSApplication::sharedApplication(mtm);
|
||||
stop_app_immediately(&app);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn queue_redraw(&self, window_id: WindowId) {
|
||||
let mut pending_redraw = self.ivars().pending_redraw.borrow_mut();
|
||||
if !pending_redraw.contains(&window_id) {
|
||||
pending_redraw.push(window_id);
|
||||
}
|
||||
self.ivars().run_loop.wakeup();
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn maybe_queue_event(&self, event: Event<HandlePendingUserEvents>) {
|
||||
// Most programmer actions in AppKit (e.g. change window fullscreen, set focused, etc.)
|
||||
// result in an event being queued, and applied at a later point.
|
||||
//
|
||||
// However, it is not documented which actions do this, and which ones are done immediately,
|
||||
// so to make sure that we don't encounter re-entrancy issues, we first check if we're
|
||||
// currently handling another event, and if we are, we queue the event instead.
|
||||
if !self.ivars().event_handler.in_use() {
|
||||
self.handle_event(event);
|
||||
} else {
|
||||
tracing::debug!(?event, "had to queue event since another is currently being handled");
|
||||
let this = self.retain();
|
||||
self.ivars().run_loop.queue_closure(move || this.handle_event(event));
|
||||
}
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn handle_event(&self, event: Event<HandlePendingUserEvents>) {
|
||||
self.ivars().event_handler.handle_event(event, &ActiveEventLoop::new_root(self.retain()))
|
||||
}
|
||||
|
||||
/// dispatch `NewEvents(Init)` + `Resumed`
|
||||
pub fn dispatch_init_events(&self) {
|
||||
self.handle_event(Event::NewEvents(StartCause::Init));
|
||||
// NB: For consistency all platforms must emit a 'resumed' event even though macOS
|
||||
// applications don't themselves have a formal suspend/resume lifecycle.
|
||||
self.handle_event(Event::Resumed);
|
||||
}
|
||||
|
||||
// Called by RunLoopObserver after finishing waiting for new events
|
||||
pub fn wakeup(&self, panic_info: Weak<PanicInfo>) {
|
||||
let mtm = MainThreadMarker::from(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
|
||||
if panic_info.is_panicking() || !self.ivars().event_handler.ready() || !self.is_running() {
|
||||
return;
|
||||
}
|
||||
|
||||
if self.ivars().stop_after_wait.get() {
|
||||
let app = NSApplication::sharedApplication(mtm);
|
||||
stop_app_immediately(&app);
|
||||
}
|
||||
|
||||
let start = self.ivars().start_time.get().unwrap();
|
||||
let cause = match self.control_flow() {
|
||||
ControlFlow::Poll => StartCause::Poll,
|
||||
ControlFlow::Wait => StartCause::WaitCancelled { start, requested_resume: None },
|
||||
ControlFlow::WaitUntil(requested_resume) => {
|
||||
if Instant::now() >= requested_resume {
|
||||
StartCause::ResumeTimeReached { start, requested_resume }
|
||||
} else {
|
||||
StartCause::WaitCancelled { start, requested_resume: Some(requested_resume) }
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
self.handle_event(Event::NewEvents(cause));
|
||||
}
|
||||
|
||||
// Called by RunLoopObserver before waiting for new events
|
||||
pub fn cleared(&self, panic_info: Weak<PanicInfo>) {
|
||||
let mtm = MainThreadMarker::from(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
|
||||
// XXX: how does it make sense that `event_handler.ready()` can ever return `false` here if
|
||||
// we're about to return to the `CFRunLoop` to poll for new events?
|
||||
if panic_info.is_panicking() || !self.ivars().event_handler.ready() || !self.is_running() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.handle_event(Event::UserEvent(HandlePendingUserEvents));
|
||||
|
||||
let redraw = mem::take(&mut *self.ivars().pending_redraw.borrow_mut());
|
||||
for window_id in redraw {
|
||||
self.handle_event(Event::WindowEvent {
|
||||
window_id: RootWindowId(window_id),
|
||||
event: WindowEvent::RedrawRequested,
|
||||
});
|
||||
}
|
||||
|
||||
self.handle_event(Event::AboutToWait);
|
||||
|
||||
if self.exiting() {
|
||||
let app = NSApplication::sharedApplication(mtm);
|
||||
stop_app_immediately(&app);
|
||||
}
|
||||
|
||||
if self.ivars().stop_before_wait.get() {
|
||||
let app = NSApplication::sharedApplication(mtm);
|
||||
stop_app_immediately(&app);
|
||||
}
|
||||
self.ivars().start_time.set(Some(Instant::now()));
|
||||
let wait_timeout = self.ivars().wait_timeout.get(); // configured by pump_events
|
||||
let app_timeout = match self.control_flow() {
|
||||
ControlFlow::Wait => None,
|
||||
ControlFlow::Poll => Some(Instant::now()),
|
||||
ControlFlow::WaitUntil(instant) => Some(instant),
|
||||
};
|
||||
self.ivars().waker.borrow_mut().start_at(min_timeout(wait_timeout, app_timeout));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct HandlePendingUserEvents;
|
||||
|
||||
/// Returns the minimum `Option<Instant>`, 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<Instant>, b: Option<Instant>) -> Option<Instant> {
|
||||
a.map_or(b, |a_timeout| b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout))))
|
||||
}
|
||||
|
||||
/// A hack to make activation of multiple windows work when creating them before
|
||||
/// `applicationDidFinishLaunching:` / `Event::Event::NewEvents(StartCause::Init)`.
|
||||
///
|
||||
/// Alternative to this would be the user calling `window.set_visible(true)` in
|
||||
/// `StartCause::Init`.
|
||||
///
|
||||
/// If this becomes too bothersome to maintain, it can probably be removed
|
||||
/// without too much damage.
|
||||
fn window_activation_hack(app: &NSApplication) {
|
||||
// TODO: Proper ordering of the windows
|
||||
app.windows().into_iter().for_each(|window| {
|
||||
// Call `makeKeyAndOrderFront` if it was called on the window in `WinitWindow::new`
|
||||
// This way we preserve the user's desired initial visibility status
|
||||
// TODO: Also filter on the type/"level" of the window, and maybe other things?
|
||||
if window.isVisible() {
|
||||
tracing::trace!("Activating visible window");
|
||||
window.makeKeyAndOrderFront(None);
|
||||
} else {
|
||||
tracing::trace!("Skipping activating invisible window");
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,511 +0,0 @@
|
||||
use std::any::Any;
|
||||
use std::cell::Cell;
|
||||
use std::collections::VecDeque;
|
||||
use std::marker::PhantomData;
|
||||
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::mpsc;
|
||||
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::runtime::ProtocolObject;
|
||||
use objc2::{msg_send_id, sel, ClassType};
|
||||
use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy, NSWindow};
|
||||
use objc2_foundation::{MainThreadMarker, NSObjectProtocol};
|
||||
|
||||
use super::app::WinitApplication;
|
||||
use super::app_state::{ApplicationDelegate, HandlePendingUserEvents};
|
||||
use super::event::dummy_event;
|
||||
use super::monitor::{self, MonitorHandle};
|
||||
use super::observer::setup_control_flow_observers;
|
||||
use crate::error::EventLoopError;
|
||||
use crate::event::Event;
|
||||
use crate::event_loop::{
|
||||
ActiveEventLoop as RootWindowTarget, ControlFlow, DeviceEvents, EventLoopClosed,
|
||||
};
|
||||
use crate::platform::macos::ActivationPolicy;
|
||||
use crate::platform::pump_events::PumpStatus;
|
||||
use crate::platform_impl::platform::cursor::CustomCursor;
|
||||
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)]
|
||||
pub struct ActiveEventLoop {
|
||||
delegate: Retained<ApplicationDelegate>,
|
||||
pub(super) mtm: MainThreadMarker,
|
||||
}
|
||||
|
||||
impl ActiveEventLoop {
|
||||
pub(super) fn new_root(delegate: Retained<ApplicationDelegate>) -> RootWindowTarget {
|
||||
let mtm = MainThreadMarker::from(&*delegate);
|
||||
let p = Self { delegate, mtm };
|
||||
RootWindowTarget { p, _marker: PhantomData }
|
||||
}
|
||||
|
||||
pub(super) fn app_delegate(&self) -> &ApplicationDelegate {
|
||||
&self.delegate
|
||||
}
|
||||
|
||||
pub fn create_custom_cursor(&self, source: CustomCursorSource) -> RootCustomCursor {
|
||||
RootCustomCursor { inner: CustomCursor::new(source.inner) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
monitor::available_monitors()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||
let monitor = monitor::primary_monitor();
|
||||
Some(monitor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn listen_device_events(&self, _allowed: DeviceEvents) {}
|
||||
|
||||
#[cfg(feature = "rwh_05")]
|
||||
#[inline]
|
||||
pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
|
||||
rwh_05::RawDisplayHandle::AppKit(rwh_05::AppKitDisplayHandle::empty())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn system_theme(&self) -> Option<Theme> {
|
||||
let app = NSApplication::sharedApplication(self.mtm);
|
||||
|
||||
if app.respondsToSelector(sel!(effectiveAppearance)) {
|
||||
Some(super::window_delegate::appearance_to_theme(&app.effectiveAppearance()))
|
||||
} else {
|
||||
Some(Theme::Light)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
#[inline]
|
||||
pub fn raw_display_handle_rwh_06(
|
||||
&self,
|
||||
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
|
||||
Ok(rwh_06::RawDisplayHandle::AppKit(rwh_06::AppKitDisplayHandle::new()))
|
||||
}
|
||||
|
||||
pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||
self.delegate.set_control_flow(control_flow)
|
||||
}
|
||||
|
||||
pub(crate) fn control_flow(&self) -> ControlFlow {
|
||||
self.delegate.control_flow()
|
||||
}
|
||||
|
||||
pub(crate) fn exit(&self) {
|
||||
self.delegate.exit()
|
||||
}
|
||||
|
||||
pub(crate) fn clear_exit(&self) {
|
||||
self.delegate.clear_exit()
|
||||
}
|
||||
|
||||
pub(crate) fn exiting(&self) -> bool {
|
||||
self.delegate.exiting()
|
||||
}
|
||||
|
||||
pub(crate) fn owned_display_handle(&self) -> OwnedDisplayHandle {
|
||||
OwnedDisplayHandle
|
||||
}
|
||||
|
||||
pub(crate) fn hide_application(&self) {
|
||||
NSApplication::sharedApplication(self.mtm).hide(None)
|
||||
}
|
||||
|
||||
pub(crate) fn hide_other_applications(&self) {
|
||||
NSApplication::sharedApplication(self.mtm).hideOtherApplications(None)
|
||||
}
|
||||
|
||||
pub(crate) fn set_allows_automatic_window_tabbing(&self, enabled: bool) {
|
||||
NSWindow::setAllowsAutomaticWindowTabbing(enabled, self.mtm)
|
||||
}
|
||||
|
||||
pub(crate) fn allows_automatic_window_tabbing(&self) -> bool {
|
||||
NSWindow::allowsAutomaticWindowTabbing(self.mtm)
|
||||
}
|
||||
}
|
||||
|
||||
fn map_user_event<T: 'static>(
|
||||
mut handler: impl FnMut(Event<T>, &RootWindowTarget),
|
||||
receiver: Rc<mpsc::Receiver<T>>,
|
||||
) -> impl FnMut(Event<HandlePendingUserEvents>, &RootWindowTarget) {
|
||||
move |event, window_target| match event.map_nonuser_event() {
|
||||
Ok(event) => (handler)(event, window_target),
|
||||
Err(_) => {
|
||||
for event in receiver.try_iter() {
|
||||
(handler)(Event::UserEvent(event), window_target);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EventLoop<T: 'static> {
|
||||
/// Store a reference to the application for convenience.
|
||||
///
|
||||
/// We intentionally don't store `WinitApplication` since we want to have
|
||||
/// the possibility of swapping that out at some point.
|
||||
app: Retained<NSApplication>,
|
||||
/// The application delegate that we've registered.
|
||||
///
|
||||
/// The delegate is only weakly referenced by NSApplication, so we must
|
||||
/// keep it around here as well.
|
||||
delegate: Retained<ApplicationDelegate>,
|
||||
|
||||
// Event sender and receiver, used for EventLoopProxy.
|
||||
sender: mpsc::Sender<T>,
|
||||
receiver: Rc<mpsc::Receiver<T>>,
|
||||
|
||||
window_target: RootWindowTarget,
|
||||
panic_info: Rc<PanicInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct PlatformSpecificEventLoopAttributes {
|
||||
pub(crate) activation_policy: Option<ActivationPolicy>,
|
||||
pub(crate) default_menu: bool,
|
||||
pub(crate) activate_ignoring_other_apps: bool,
|
||||
}
|
||||
|
||||
impl Default for PlatformSpecificEventLoopAttributes {
|
||||
fn default() -> Self {
|
||||
Self { activation_policy: None, default_menu: true, activate_ignoring_other_apps: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> EventLoop<T> {
|
||||
pub(crate) fn new(
|
||||
attributes: &PlatformSpecificEventLoopAttributes,
|
||||
) -> Result<Self, EventLoopError> {
|
||||
let mtm = MainThreadMarker::new()
|
||||
.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 {
|
||||
None => None,
|
||||
Some(ActivationPolicy::Regular) => Some(NSApplicationActivationPolicy::Regular),
|
||||
Some(ActivationPolicy::Accessory) => Some(NSApplicationActivationPolicy::Accessory),
|
||||
Some(ActivationPolicy::Prohibited) => Some(NSApplicationActivationPolicy::Prohibited),
|
||||
};
|
||||
let delegate = ApplicationDelegate::new(
|
||||
mtm,
|
||||
activation_policy,
|
||||
attributes.default_menu,
|
||||
attributes.activate_ignoring_other_apps,
|
||||
);
|
||||
|
||||
autoreleasepool(|_| {
|
||||
app.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
|
||||
});
|
||||
|
||||
let panic_info: Rc<PanicInfo> = Default::default();
|
||||
setup_control_flow_observers(mtm, Rc::downgrade(&panic_info));
|
||||
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
Ok(EventLoop {
|
||||
app,
|
||||
delegate: delegate.clone(),
|
||||
sender,
|
||||
receiver: Rc::new(receiver),
|
||||
window_target: RootWindowTarget {
|
||||
p: ActiveEventLoop { delegate, mtm },
|
||||
_marker: PhantomData,
|
||||
},
|
||||
panic_info,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn window_target(&self) -> &RootWindowTarget {
|
||||
&self.window_target
|
||||
}
|
||||
|
||||
pub fn run<F>(mut self, handler: F) -> Result<(), EventLoopError>
|
||||
where
|
||||
F: FnMut(Event<T>, &RootWindowTarget),
|
||||
{
|
||||
self.run_on_demand(handler)
|
||||
}
|
||||
|
||||
// NB: we don't base this on `pump_events` because for `MacOs` we can't support
|
||||
// `pump_events` elegantly (we just ask to run the loop for a "short" amount of
|
||||
// time and so a layered implementation would end up using a lot of CPU due to
|
||||
// redundant wake ups.
|
||||
pub fn run_on_demand<F>(&mut self, handler: F) -> Result<(), EventLoopError>
|
||||
where
|
||||
F: FnMut(Event<T>, &RootWindowTarget),
|
||||
{
|
||||
let handler = map_user_event(handler, self.receiver.clone());
|
||||
|
||||
self.delegate.set_event_handler(handler, || {
|
||||
autoreleasepool(|_| {
|
||||
// clear / normalize pump_events state
|
||||
self.delegate.set_wait_timeout(None);
|
||||
self.delegate.set_stop_before_wait(false);
|
||||
self.delegate.set_stop_after_wait(false);
|
||||
self.delegate.set_stop_on_redraw(false);
|
||||
|
||||
if self.delegate.is_launched() {
|
||||
debug_assert!(!self.delegate.is_running());
|
||||
self.delegate.set_is_running(true);
|
||||
self.delegate.dispatch_init_events();
|
||||
}
|
||||
|
||||
// SAFETY: We do not run the application re-entrantly
|
||||
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 `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.delegate.internal_exit()
|
||||
})
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn pump_events<F>(&mut self, timeout: Option<Duration>, handler: F) -> PumpStatus
|
||||
where
|
||||
F: FnMut(Event<T>, &RootWindowTarget),
|
||||
{
|
||||
let handler = map_user_event(handler, self.receiver.clone());
|
||||
|
||||
self.delegate.set_event_handler(handler, || {
|
||||
autoreleasepool(|_| {
|
||||
// As a special case, if the application hasn't been launched yet then we at least
|
||||
// run the loop until it has fully launched.
|
||||
if !self.delegate.is_launched() {
|
||||
debug_assert!(!self.delegate.is_running());
|
||||
|
||||
self.delegate.set_stop_on_launch();
|
||||
// SAFETY: We do not run the application re-entrantly
|
||||
unsafe { self.app.run() };
|
||||
|
||||
// Note: we dispatch `NewEvents(Init)` + `Resumed` events after the application
|
||||
// has launched
|
||||
} else if !self.delegate.is_running() {
|
||||
// Even though the application may have been launched, it's possible we aren't
|
||||
// running if the `EventLoop` was run before and has since
|
||||
// exited. This indicates that we just starting to re-run
|
||||
// the same `EventLoop` again.
|
||||
self.delegate.set_is_running(true);
|
||||
self.delegate.dispatch_init_events();
|
||||
} else {
|
||||
// Only run for as long as the given `Duration` allows so we don't block the
|
||||
// external loop.
|
||||
match timeout {
|
||||
Some(Duration::ZERO) => {
|
||||
self.delegate.set_wait_timeout(None);
|
||||
self.delegate.set_stop_before_wait(true);
|
||||
},
|
||||
Some(duration) => {
|
||||
self.delegate.set_stop_before_wait(false);
|
||||
let timeout = Instant::now() + duration;
|
||||
self.delegate.set_wait_timeout(Some(timeout));
|
||||
self.delegate.set_stop_after_wait(true);
|
||||
},
|
||||
None => {
|
||||
self.delegate.set_wait_timeout(None);
|
||||
self.delegate.set_stop_before_wait(false);
|
||||
self.delegate.set_stop_after_wait(true);
|
||||
},
|
||||
}
|
||||
self.delegate.set_stop_on_redraw(true);
|
||||
// SAFETY: We do not run the application re-entrantly
|
||||
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.delegate.exiting() {
|
||||
self.delegate.internal_exit();
|
||||
PumpStatus::Exit(0)
|
||||
} else {
|
||||
PumpStatus::Continue
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn create_proxy(&self) -> EventLoopProxy<T> {
|
||||
EventLoopProxy::new(self.sender.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct OwnedDisplayHandle;
|
||||
|
||||
impl OwnedDisplayHandle {
|
||||
#[cfg(feature = "rwh_05")]
|
||||
#[inline]
|
||||
pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
|
||||
rwh_05::AppKitDisplayHandle::empty().into()
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
#[inline]
|
||||
pub fn raw_display_handle_rwh_06(
|
||||
&self,
|
||||
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
|
||||
Ok(rwh_06::AppKitDisplayHandle::new().into())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn stop_app_immediately(app: &NSApplication) {
|
||||
autoreleasepool(|_| {
|
||||
app.stop(None);
|
||||
// To stop event loop immediately, we need to post some event here.
|
||||
// See: https://stackoverflow.com/questions/48041279/stopping-the-nsapplication-main-event-loop/48064752#48064752
|
||||
app.postEvent_atStart(&dummy_event().unwrap(), true);
|
||||
});
|
||||
}
|
||||
|
||||
/// Catches panics that happen inside `f` and when a panic
|
||||
/// happens, stops the `sharedApplication`
|
||||
#[inline]
|
||||
pub fn stop_app_on_panic<F: FnOnce() -> R + UnwindSafe, R>(
|
||||
mtm: MainThreadMarker,
|
||||
panic_info: Weak<PanicInfo>,
|
||||
f: F,
|
||||
) -> Option<R> {
|
||||
match catch_unwind(f) {
|
||||
Ok(r) => Some(r),
|
||||
Err(e) => {
|
||||
// It's important that we set the panic before requesting a `stop`
|
||||
// because some callback are still called during the `stop` message
|
||||
// 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
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EventLoopProxy<T> {
|
||||
sender: mpsc::Sender<T>,
|
||||
source: CFRunLoopSourceRef,
|
||||
}
|
||||
|
||||
unsafe impl<T: Send> Send for EventLoopProxy<T> {}
|
||||
unsafe impl<T: Send> Sync for EventLoopProxy<T> {}
|
||||
|
||||
impl<T> Drop for EventLoopProxy<T> {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
CFRelease(self.source as _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for EventLoopProxy<T> {
|
||||
fn clone(&self) -> Self {
|
||||
EventLoopProxy::new(self.sender.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> EventLoopProxy<T> {
|
||||
fn new(sender: mpsc::Sender<T>) -> 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 { sender, source }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
|
||||
self.sender.send(event).map_err(|mpsc::SendError(x)| EventLoopClosed(x))?;
|
||||
unsafe {
|
||||
// let the main thread know there's a new event
|
||||
CFRunLoopSourceSignal(self.source);
|
||||
let rl = CFRunLoopGetMain();
|
||||
CFRunLoopWakeUp(rl);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -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,61 +0,0 @@
|
||||
#[macro_use]
|
||||
mod util;
|
||||
|
||||
mod app;
|
||||
mod app_state;
|
||||
mod cursor;
|
||||
mod event;
|
||||
mod event_handler;
|
||||
mod event_loop;
|
||||
mod ffi;
|
||||
mod menu;
|
||||
mod monitor;
|
||||
mod observer;
|
||||
mod view;
|
||||
mod window;
|
||||
mod window_delegate;
|
||||
|
||||
use std::fmt;
|
||||
|
||||
pub(crate) use self::event::{physicalkey_to_scancode, scancode_to_physicalkey, KeyEventExtra};
|
||||
pub(crate) use self::event_loop::{
|
||||
ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle,
|
||||
PlatformSpecificEventLoopAttributes,
|
||||
};
|
||||
pub(crate) use self::monitor::{MonitorHandle, VideoModeHandle};
|
||||
pub(crate) use self::window::WindowId;
|
||||
pub(crate) use self::window_delegate::PlatformSpecificWindowAttributes;
|
||||
use crate::event::DeviceId as RootDeviceId;
|
||||
|
||||
pub(crate) use self::cursor::CustomCursor as PlatformCustomCursor;
|
||||
pub(crate) use self::window::Window;
|
||||
pub(crate) use crate::cursor::OnlyCursorImageSource as PlatformCustomCursorSource;
|
||||
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
||||
pub(crate) use crate::platform_impl::Fullscreen;
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DeviceId;
|
||||
|
||||
impl DeviceId {
|
||||
pub const fn dummy() -> Self {
|
||||
DeviceId
|
||||
}
|
||||
}
|
||||
|
||||
// Constant device ID; to be removed when if backend is updated to report real device IDs.
|
||||
pub(crate) const DEVICE_ID: RootDeviceId = RootDeviceId(DeviceId);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum OsError {
|
||||
CGError(core_graphics::base::CGError),
|
||||
CreationError(&'static str),
|
||||
}
|
||||
|
||||
impl fmt::Display for OsError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
OsError::CGError(e) => f.pad(&format!("CGError {e}")),
|
||||
OsError::CreationError(e) => f.pad(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,351 +0,0 @@
|
||||
#![allow(clippy::unnecessary_cast)]
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::fmt;
|
||||
|
||||
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: u16,
|
||||
refresh_rate_millihertz: u32,
|
||||
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 {
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
self.size
|
||||
}
|
||||
|
||||
pub fn bit_depth(&self) -> u16 {
|
||||
self.bit_depth
|
||||
}
|
||||
|
||||
pub fn refresh_rate_millihertz(&self) -> u32 {
|
||||
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("size", &self.size())
|
||||
.field("position", &self.position())
|
||||
.field("scale_factor", &self.scale_factor())
|
||||
.field("refresh_rate_millihertz", &self.refresh_rate_millihertz())
|
||||
.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
|
||||
}
|
||||
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
let MonitorHandle(display_id) = *self;
|
||||
let display = CGDisplay::new(display_id);
|
||||
let height = display.pixels_high();
|
||||
let width = display.pixels_wide();
|
||||
PhysicalSize::from_logical::<_, f64>((width as f64, height as f64), self.scale_factor())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn position(&self) -> 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);
|
||||
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
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn refresh_rate_millihertz(&self) -> Option<u32> {
|
||||
unsafe {
|
||||
let current_display_mode = NativeDisplayMode(CGDisplayCopyDisplayMode(self.0) as _);
|
||||
let refresh_rate = ffi::CGDisplayModeGetRefreshRate(current_display_mode.0);
|
||||
if refresh_rate > 0.0 {
|
||||
return Some((refresh_rate * 1000.0).round() as u32);
|
||||
}
|
||||
|
||||
let mut display_link = std::ptr::null_mut();
|
||||
if ffi::CVDisplayLinkCreateWithCGDisplay(self.0, &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)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> {
|
||||
let refresh_rate_millihertz = self.refresh_rate_millihertz().unwrap_or(0);
|
||||
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 {
|
||||
(cg_refresh_rate_hertz * 1000) as u32
|
||||
} else {
|
||||
refresh_rate_millihertz
|
||||
};
|
||||
|
||||
let pixel_encoding =
|
||||
CFString::wrap_under_create_rule(ffi::CGDisplayModeCopyPixelEncoding(mode))
|
||||
.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) as u32,
|
||||
ffi::CGDisplayModeGetPixelHeight(mode) as u32,
|
||||
),
|
||||
refresh_rate_millihertz,
|
||||
bit_depth,
|
||||
monitor: monitor.clone(),
|
||||
native_mode: NativeDisplayMode(mode),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
#![allow(clippy::unnecessary_cast)]
|
||||
|
||||
use objc2::rc::{autoreleasepool, Retained};
|
||||
use objc2::{declare_class, mutability, ClassType, DeclaredClass};
|
||||
use objc2_app_kit::{NSResponder, NSWindow};
|
||||
use objc2_foundation::{MainThreadBound, MainThreadMarker, NSObject};
|
||||
|
||||
use super::event_loop::ActiveEventLoop;
|
||||
use super::window_delegate::WindowDelegate;
|
||||
use crate::error::OsError as RootOsError;
|
||||
use crate::window::WindowAttributes;
|
||||
|
||||
pub(crate) struct Window {
|
||||
window: MainThreadBound<Retained<WinitWindow>>,
|
||||
/// The window only keeps a weak reference to this, so we must keep it around here.
|
||||
delegate: MainThreadBound<Retained<WindowDelegate>>,
|
||||
}
|
||||
|
||||
impl Drop for Window {
|
||||
fn drop(&mut self) {
|
||||
self.window.get_on_main(|window| autoreleasepool(|_| window.close()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Window {
|
||||
pub(crate) fn new(
|
||||
window_target: &ActiveEventLoop,
|
||||
attributes: WindowAttributes,
|
||||
) -> Result<Self, RootOsError> {
|
||||
let mtm = window_target.mtm;
|
||||
let delegate = autoreleasepool(|_| {
|
||||
WindowDelegate::new(window_target.app_delegate(), attributes, mtm)
|
||||
})?;
|
||||
Ok(Window {
|
||||
window: MainThreadBound::new(delegate.window().retain(), mtm),
|
||||
delegate: MainThreadBound::new(delegate, mtm),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn maybe_queue_on_main(&self, f: impl FnOnce(&WindowDelegate) + Send + 'static) {
|
||||
// For now, don't actually do queuing, since it may be less predictable
|
||||
self.maybe_wait_on_main(f)
|
||||
}
|
||||
|
||||
pub(crate) fn maybe_wait_on_main<R: Send>(
|
||||
&self,
|
||||
f: impl FnOnce(&WindowDelegate) -> R + Send,
|
||||
) -> R {
|
||||
self.delegate.get_on_main(|delegate| f(delegate))
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
#[inline]
|
||||
pub(crate) fn raw_window_handle_rwh_06(
|
||||
&self,
|
||||
) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> {
|
||||
if let Some(mtm) = MainThreadMarker::new() {
|
||||
Ok(self.delegate.get(mtm).raw_window_handle_rwh_06())
|
||||
} else {
|
||||
Err(rwh_06::HandleError::Unavailable)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
#[inline]
|
||||
pub(crate) fn raw_display_handle_rwh_06(
|
||||
&self,
|
||||
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
|
||||
Ok(rwh_06::RawDisplayHandle::AppKit(rwh_06::AppKitDisplayHandle::new()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct WindowId(pub usize);
|
||||
|
||||
impl WindowId {
|
||||
pub const fn dummy() -> Self {
|
||||
Self(0)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WindowId> for u64 {
|
||||
fn from(window_id: WindowId) -> Self {
|
||||
window_id.0 as u64
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u64> for WindowId {
|
||||
fn from(raw_id: u64) -> Self {
|
||||
Self(raw_id as usize)
|
||||
}
|
||||
}
|
||||
|
||||
declare_class!(
|
||||
#[derive(Debug)]
|
||||
pub struct WinitWindow;
|
||||
|
||||
unsafe impl ClassType for WinitWindow {
|
||||
#[inherits(NSResponder, NSObject)]
|
||||
type Super = NSWindow;
|
||||
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 {
|
||||
trace_scope!("canBecomeMainWindow");
|
||||
true
|
||||
}
|
||||
|
||||
#[method(canBecomeKeyWindow)]
|
||||
fn can_become_key_window(&self) -> bool {
|
||||
trace_scope!("canBecomeKeyWindow");
|
||||
true
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl WinitWindow {
|
||||
pub(super) fn id(&self) -> WindowId {
|
||||
WindowId(self as *const Self as usize)
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
use crate::monitor::{MonitorHandle as RootMonitorHandle, VideoModeHandle as RootVideoModeHandle};
|
||||
use crate::window::Fullscreen as RootFullscreen;
|
||||
|
||||
#[cfg(android_platform)]
|
||||
mod android;
|
||||
#[cfg(ios_platform)]
|
||||
mod ios;
|
||||
#[cfg(any(x11_platform, wayland_platform))]
|
||||
mod linux;
|
||||
#[cfg(macos_platform)]
|
||||
mod macos;
|
||||
#[cfg(orbital_platform)]
|
||||
mod orbital;
|
||||
#[cfg(web_platform)]
|
||||
mod web;
|
||||
#[cfg(windows_platform)]
|
||||
mod windows;
|
||||
|
||||
#[cfg(android_platform)]
|
||||
use android as platform;
|
||||
#[cfg(ios_platform)]
|
||||
use ios as platform;
|
||||
#[cfg(any(x11_platform, wayland_platform))]
|
||||
use linux as platform;
|
||||
#[cfg(macos_platform)]
|
||||
use macos as platform;
|
||||
#[cfg(orbital_platform)]
|
||||
use orbital as platform;
|
||||
#[cfg(web_platform)]
|
||||
use web as platform;
|
||||
#[cfg(windows_platform)]
|
||||
use windows as platform;
|
||||
|
||||
pub use self::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,255 +0,0 @@
|
||||
#![cfg(target_os = "redox")]
|
||||
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
use std::str;
|
||||
use std::sync::Arc;
|
||||
|
||||
use smol_str::SmolStr;
|
||||
|
||||
use crate::dpi::{PhysicalPosition, PhysicalSize};
|
||||
use crate::keyboard::Key;
|
||||
|
||||
pub(crate) use self::event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle};
|
||||
mod event_loop;
|
||||
|
||||
pub use self::window::Window;
|
||||
mod window;
|
||||
|
||||
struct RedoxSocket {
|
||||
fd: usize,
|
||||
}
|
||||
|
||||
impl RedoxSocket {
|
||||
fn event() -> syscall::Result<Self> {
|
||||
Self::open_raw("event:")
|
||||
}
|
||||
|
||||
fn orbital(properties: &WindowProperties<'_>) -> syscall::Result<Self> {
|
||||
Self::open_raw(&format!("{properties}"))
|
||||
}
|
||||
|
||||
// Paths should be checked to ensure they are actually sockets and not normal files. If a
|
||||
// non-socket path is used, it could cause read and write to not function as expected. For
|
||||
// example, the seek would change in a potentially unpredictable way if either read or write
|
||||
// were called at the same time by multiple threads.
|
||||
fn open_raw(path: &str) -> syscall::Result<Self> {
|
||||
let fd = syscall::open(path, syscall::O_RDWR | syscall::O_CLOEXEC)?;
|
||||
Ok(Self { fd })
|
||||
}
|
||||
|
||||
fn read(&self, buf: &mut [u8]) -> syscall::Result<()> {
|
||||
let count = syscall::read(self.fd, buf)?;
|
||||
if count == buf.len() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(syscall::Error::new(syscall::EINVAL))
|
||||
}
|
||||
}
|
||||
|
||||
fn write(&self, buf: &[u8]) -> syscall::Result<()> {
|
||||
let count = syscall::write(self.fd, buf)?;
|
||||
if count == buf.len() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(syscall::Error::new(syscall::EINVAL))
|
||||
}
|
||||
}
|
||||
|
||||
fn fpath<'a>(&self, buf: &'a mut [u8]) -> syscall::Result<&'a str> {
|
||||
let count = syscall::fpath(self.fd, buf)?;
|
||||
str::from_utf8(&buf[..count]).map_err(|_err| syscall::Error::new(syscall::EINVAL))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RedoxSocket {
|
||||
fn drop(&mut self) {
|
||||
let _ = syscall::close(self.fd);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TimeSocket(RedoxSocket);
|
||||
|
||||
impl TimeSocket {
|
||||
fn open() -> syscall::Result<Self> {
|
||||
RedoxSocket::open_raw("time:4").map(Self)
|
||||
}
|
||||
|
||||
// Read current time.
|
||||
fn current_time(&self) -> syscall::Result<syscall::TimeSpec> {
|
||||
let mut timespec = syscall::TimeSpec::default();
|
||||
self.0.read(&mut timespec)?;
|
||||
Ok(timespec)
|
||||
}
|
||||
|
||||
// Write a timeout.
|
||||
fn timeout(&self, timespec: &syscall::TimeSpec) -> syscall::Result<()> {
|
||||
self.0.write(timespec)
|
||||
}
|
||||
|
||||
// Wake immediately.
|
||||
fn wake(&self) -> syscall::Result<()> {
|
||||
// Writing a default TimeSpec will always trigger a time event.
|
||||
self.timeout(&syscall::TimeSpec::default())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct PlatformSpecificEventLoopAttributes {}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct WindowId {
|
||||
fd: u64,
|
||||
}
|
||||
|
||||
impl WindowId {
|
||||
pub const fn dummy() -> Self {
|
||||
WindowId { fd: u64::MAX }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WindowId> for u64 {
|
||||
fn from(id: WindowId) -> Self {
|
||||
id.fd
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u64> for WindowId {
|
||||
fn from(fd: u64) -> Self {
|
||||
Self { fd }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct DeviceId;
|
||||
|
||||
impl DeviceId {
|
||||
pub const fn dummy() -> Self {
|
||||
DeviceId
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub struct PlatformSpecificWindowAttributes;
|
||||
|
||||
struct WindowProperties<'a> {
|
||||
flags: &'a str,
|
||||
x: i32,
|
||||
y: i32,
|
||||
w: u32,
|
||||
h: u32,
|
||||
title: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> WindowProperties<'a> {
|
||||
fn new(path: &'a str) -> Self {
|
||||
// orbital:flags/x/y/w/h/t
|
||||
let mut parts = path.splitn(6, '/');
|
||||
let flags = parts.next().unwrap_or("");
|
||||
let x = parts.next().map_or(0, |part| part.parse::<i32>().unwrap_or(0));
|
||||
let y = parts.next().map_or(0, |part| part.parse::<i32>().unwrap_or(0));
|
||||
let w = parts.next().map_or(0, |part| part.parse::<u32>().unwrap_or(0));
|
||||
let h = parts.next().map_or(0, |part| part.parse::<u32>().unwrap_or(0));
|
||||
let title = parts.next().unwrap_or("");
|
||||
Self { flags, x, y, w, h, title }
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for WindowProperties<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"orbital:{}/{}/{}/{}/{}/{}",
|
||||
self.flags, self.x, self.y, self.w, self.h, self.title
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OsError(Arc<syscall::Error>);
|
||||
|
||||
impl OsError {
|
||||
fn new(error: syscall::Error) -> Self {
|
||||
Self(Arc::new(error))
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for OsError {
|
||||
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> {
|
||||
self.0.fmt(fmt)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) use crate::cursor::{
|
||||
NoCustomCursor as PlatformCustomCursor, NoCustomCursor as PlatformCustomCursorSource,
|
||||
};
|
||||
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct MonitorHandle;
|
||||
|
||||
impl MonitorHandle {
|
||||
pub fn name(&self) -> Option<String> {
|
||||
Some("Redox Device".to_owned())
|
||||
}
|
||||
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
PhysicalSize::new(0, 0) // TODO
|
||||
}
|
||||
|
||||
pub fn position(&self) -> PhysicalPosition<i32> {
|
||||
(0, 0).into()
|
||||
}
|
||||
|
||||
pub fn scale_factor(&self) -> f64 {
|
||||
1.0 // TODO
|
||||
}
|
||||
|
||||
pub fn refresh_rate_millihertz(&self) -> Option<u32> {
|
||||
// FIXME no way to get real refresh rate for now.
|
||||
None
|
||||
}
|
||||
|
||||
pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> {
|
||||
let size = self.size().into();
|
||||
// FIXME this is not the real refresh rate
|
||||
// (it is guaranteed to support 32 bit color though)
|
||||
std::iter::once(VideoModeHandle {
|
||||
size,
|
||||
bit_depth: 32,
|
||||
refresh_rate_millihertz: 60000,
|
||||
monitor: self.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||
pub struct VideoModeHandle {
|
||||
size: (u32, u32),
|
||||
bit_depth: u16,
|
||||
refresh_rate_millihertz: u32,
|
||||
monitor: MonitorHandle,
|
||||
}
|
||||
|
||||
impl VideoModeHandle {
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
self.size.into()
|
||||
}
|
||||
|
||||
pub fn bit_depth(&self) -> u16 {
|
||||
self.bit_depth
|
||||
}
|
||||
|
||||
pub fn refresh_rate_millihertz(&self) -> u32 {
|
||||
self.refresh_rate_millihertz
|
||||
}
|
||||
|
||||
pub fn monitor(&self) -> MonitorHandle {
|
||||
self.monitor.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
|
||||
pub struct KeyEventExtra {
|
||||
pub key_without_modifiers: Key,
|
||||
pub text_with_all_modifiers: Option<SmolStr>,
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
use std::future;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::task::Poll;
|
||||
|
||||
use super::super::main_thread::MainThreadMarker;
|
||||
use super::{AtomicWaker, Wrapper};
|
||||
|
||||
pub struct WakerSpawner<T: 'static>(Wrapper<Handler<T>, Sender, NonZeroUsize>);
|
||||
|
||||
pub struct Waker<T: 'static>(Wrapper<Handler<T>, Sender, NonZeroUsize>);
|
||||
|
||||
struct Handler<T> {
|
||||
value: T,
|
||||
handler: fn(&T, NonZeroUsize, bool),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Sender(Arc<Inner>);
|
||||
|
||||
impl<T> WakerSpawner<T> {
|
||||
#[track_caller]
|
||||
pub fn new(
|
||||
main_thread: MainThreadMarker,
|
||||
value: T,
|
||||
handler: fn(&T, NonZeroUsize, bool),
|
||||
) -> Option<Self> {
|
||||
let inner = Arc::new(Inner {
|
||||
counter: AtomicUsize::new(0),
|
||||
waker: AtomicWaker::new(),
|
||||
closed: AtomicBool::new(false),
|
||||
});
|
||||
|
||||
let handler = Handler { value, handler };
|
||||
|
||||
let sender = Sender(Arc::clone(&inner));
|
||||
|
||||
let wrapper = Wrapper::new(
|
||||
main_thread,
|
||||
handler,
|
||||
|handler, count| {
|
||||
let handler = handler.borrow();
|
||||
let handler = handler.as_ref().unwrap();
|
||||
(handler.handler)(&handler.value, count, true);
|
||||
},
|
||||
{
|
||||
let inner = Arc::clone(&inner);
|
||||
|
||||
move |handler| async move {
|
||||
while let Some(count) = future::poll_fn(|cx| {
|
||||
let count = inner.counter.swap(0, Ordering::Relaxed);
|
||||
|
||||
match NonZeroUsize::new(count) {
|
||||
Some(count) => Poll::Ready(Some(count)),
|
||||
None => {
|
||||
inner.waker.register(cx.waker());
|
||||
|
||||
let count = inner.counter.swap(0, Ordering::Relaxed);
|
||||
|
||||
match NonZeroUsize::new(count) {
|
||||
Some(count) => Poll::Ready(Some(count)),
|
||||
None => {
|
||||
if inner.closed.load(Ordering::Relaxed) {
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
|
||||
Poll::Pending
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
.await
|
||||
{
|
||||
let handler = handler.borrow();
|
||||
let handler = handler.as_ref().unwrap();
|
||||
(handler.handler)(&handler.value, count, false);
|
||||
}
|
||||
}
|
||||
},
|
||||
sender,
|
||||
|inner, _| {
|
||||
inner.0.counter.fetch_add(1, Ordering::Relaxed);
|
||||
inner.0.waker.wake();
|
||||
},
|
||||
)?;
|
||||
|
||||
Some(Self(wrapper))
|
||||
}
|
||||
|
||||
pub fn waker(&self) -> Waker<T> {
|
||||
Waker(self.0.clone())
|
||||
}
|
||||
|
||||
pub fn fetch(&self) -> usize {
|
||||
debug_assert!(
|
||||
MainThreadMarker::new().is_some(),
|
||||
"this should only be called from the main thread"
|
||||
);
|
||||
|
||||
self.0.with_sender_data(|inner| inner.0.counter.swap(0, Ordering::Relaxed))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for WakerSpawner<T> {
|
||||
fn drop(&mut self) {
|
||||
self.0.with_sender_data(|inner| {
|
||||
inner.0.closed.store(true, Ordering::Relaxed);
|
||||
inner.0.waker.wake();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Waker<T> {
|
||||
pub fn wake(&self) {
|
||||
self.0.send(NonZeroUsize::MIN)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for Waker<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
counter: AtomicUsize,
|
||||
waker: AtomicWaker,
|
||||
closed: AtomicBool,
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DeviceId(pub i32);
|
||||
|
||||
impl DeviceId {
|
||||
pub const fn dummy() -> Self {
|
||||
Self(0)
|
||||
}
|
||||
}
|
||||
@@ -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,119 +0,0 @@
|
||||
use std::marker::PhantomData;
|
||||
use std::sync::mpsc::{self, Receiver, Sender};
|
||||
|
||||
use crate::error::EventLoopError;
|
||||
use crate::event::Event;
|
||||
use crate::event_loop::ActiveEventLoop as RootActiveEventLoop;
|
||||
use crate::platform::web::{ActiveEventLoopExtWebSys, PollStrategy, WaitUntilStrategy};
|
||||
|
||||
use super::{backend, device, window};
|
||||
|
||||
mod proxy;
|
||||
pub(crate) mod runner;
|
||||
mod state;
|
||||
mod window_target;
|
||||
|
||||
pub(crate) use proxy::EventLoopProxy;
|
||||
pub(crate) use window_target::{ActiveEventLoop, OwnedDisplayHandle};
|
||||
|
||||
pub struct EventLoop<T: 'static> {
|
||||
elw: RootActiveEventLoop,
|
||||
user_event_sender: Sender<T>,
|
||||
user_event_receiver: Receiver<T>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct PlatformSpecificEventLoopAttributes {}
|
||||
|
||||
impl<T> EventLoop<T> {
|
||||
pub(crate) fn new(_: &PlatformSpecificEventLoopAttributes) -> Result<Self, EventLoopError> {
|
||||
let (user_event_sender, user_event_receiver) = mpsc::channel();
|
||||
let elw = RootActiveEventLoop { p: ActiveEventLoop::new(), _marker: PhantomData };
|
||||
Ok(EventLoop { elw, user_event_sender, user_event_receiver })
|
||||
}
|
||||
|
||||
pub fn run<F>(self, mut event_handler: F) -> !
|
||||
where
|
||||
F: FnMut(Event<T>, &RootActiveEventLoop),
|
||||
{
|
||||
let target = RootActiveEventLoop { p: self.elw.p.clone(), _marker: PhantomData };
|
||||
|
||||
// SAFETY: Don't use `move` to make sure we leak the `event_handler` and `target`.
|
||||
let handler: Box<dyn FnMut(Event<()>)> = Box::new(|event| {
|
||||
let event = match event.map_nonuser_event() {
|
||||
Ok(event) => event,
|
||||
Err(Event::UserEvent(())) => Event::UserEvent(
|
||||
self.user_event_receiver
|
||||
.try_recv()
|
||||
.expect("handler woken up without user event"),
|
||||
),
|
||||
Err(_) => unreachable!(),
|
||||
};
|
||||
event_handler(event, &target)
|
||||
});
|
||||
// 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.p.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<F>(self, mut event_handler: F)
|
||||
where
|
||||
F: 'static + FnMut(Event<T>, &RootActiveEventLoop),
|
||||
{
|
||||
let target = RootActiveEventLoop { p: self.elw.p.clone(), _marker: PhantomData };
|
||||
|
||||
self.elw.p.run(
|
||||
Box::new(move |event| {
|
||||
let event = match event.map_nonuser_event() {
|
||||
Ok(event) => event,
|
||||
Err(Event::UserEvent(())) => Event::UserEvent(
|
||||
self.user_event_receiver
|
||||
.try_recv()
|
||||
.expect("handler woken up without user event"),
|
||||
),
|
||||
Err(_) => unreachable!(),
|
||||
};
|
||||
event_handler(event, &target)
|
||||
}),
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn create_proxy(&self) -> EventLoopProxy<T> {
|
||||
EventLoopProxy::new(self.elw.p.waker(), self.user_event_sender.clone())
|
||||
}
|
||||
|
||||
pub fn window_target(&self) -> &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()
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
use std::rc::Weak;
|
||||
use std::sync::mpsc::{SendError, Sender};
|
||||
|
||||
use super::runner::Execution;
|
||||
use crate::event_loop::EventLoopClosed;
|
||||
use crate::platform_impl::platform::r#async::Waker;
|
||||
|
||||
pub struct EventLoopProxy<T: 'static> {
|
||||
runner: Waker<Weak<Execution>>,
|
||||
sender: Sender<T>,
|
||||
}
|
||||
|
||||
impl<T: 'static> EventLoopProxy<T> {
|
||||
pub fn new(runner: Waker<Weak<Execution>>, sender: Sender<T>) -> Self {
|
||||
Self { runner, sender }
|
||||
}
|
||||
|
||||
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
|
||||
self.sender.send(event).map_err(|SendError(event)| EventLoopClosed(event))?;
|
||||
self.runner.wake();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> Clone for EventLoopProxy<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self { runner: self.runner.clone(), sender: self.sender.clone() }
|
||||
}
|
||||
}
|
||||
@@ -1,685 +0,0 @@
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::clone::Clone;
|
||||
use std::collections::vec_deque::IntoIter as VecDequeIter;
|
||||
use std::collections::VecDeque;
|
||||
use std::iter;
|
||||
use std::rc::{Rc, Weak};
|
||||
|
||||
use web_sys::Element;
|
||||
|
||||
use super::super::monitor::MonitorHandle;
|
||||
use super::super::KeyEventExtra;
|
||||
use super::device::DeviceId;
|
||||
use super::runner::{EventWrapper, Execution};
|
||||
use super::window::WindowId;
|
||||
use super::{backend, runner};
|
||||
use crate::event::{
|
||||
DeviceId as RootDeviceId, ElementState, Event, KeyEvent, Touch, TouchPhase, WindowEvent,
|
||||
};
|
||||
use crate::event_loop::{ControlFlow, DeviceEvents};
|
||||
use crate::keyboard::ModifiersState;
|
||||
use crate::platform::web::{CustomCursorFuture, PollStrategy, WaitUntilStrategy};
|
||||
use crate::platform_impl::platform::cursor::CustomCursor;
|
||||
use crate::platform_impl::platform::r#async::Waker;
|
||||
use crate::window::{
|
||||
CustomCursor as RootCustomCursor, CustomCursorSource, Theme, WindowId as RootWindowId,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
struct ModifiersShared(Rc<Cell<ModifiersState>>);
|
||||
|
||||
impl ModifiersShared {
|
||||
fn set(&self, new: ModifiersState) {
|
||||
self.0.set(new)
|
||||
}
|
||||
|
||||
fn get(&self) -> ModifiersState {
|
||||
self.0.get()
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for ModifiersShared {
|
||||
fn clone(&self) -> Self {
|
||||
Self(Rc::clone(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ActiveEventLoop {
|
||||
pub(crate) runner: runner::Shared,
|
||||
modifiers: ModifiersShared,
|
||||
}
|
||||
|
||||
impl ActiveEventLoop {
|
||||
pub fn new() -> Self {
|
||||
Self { runner: runner::Shared::new(), modifiers: ModifiersShared::default() }
|
||||
}
|
||||
|
||||
pub fn run(&self, event_handler: Box<runner::EventHandler>, event_loop_recreation: bool) {
|
||||
self.runner.event_loop_recreation(event_loop_recreation);
|
||||
self.runner.set_listener(event_handler);
|
||||
}
|
||||
|
||||
pub fn generate_id(&self) -> WindowId {
|
||||
WindowId(self.runner.generate_id())
|
||||
}
|
||||
|
||||
pub fn create_custom_cursor(&self, source: CustomCursorSource) -> RootCustomCursor {
|
||||
RootCustomCursor { inner: CustomCursor::new(self, source.inner) }
|
||||
}
|
||||
|
||||
pub fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture {
|
||||
CustomCursorFuture(CustomCursor::new_async(self, source.inner))
|
||||
}
|
||||
|
||||
pub fn register(&self, canvas: &Rc<RefCell<backend::Canvas>>, id: WindowId) {
|
||||
let canvas_clone = canvas.clone();
|
||||
let mut canvas = canvas.borrow_mut();
|
||||
#[cfg(any(feature = "rwh_04", feature = "rwh_05"))]
|
||||
canvas.set_attribute("data-raw-handle", &id.0.to_string());
|
||||
|
||||
canvas.on_touch_start();
|
||||
|
||||
let runner = self.runner.clone();
|
||||
let has_focus = canvas.has_focus.clone();
|
||||
let modifiers = self.modifiers.clone();
|
||||
canvas.on_blur(move || {
|
||||
has_focus.set(false);
|
||||
|
||||
let clear_modifiers = (!modifiers.get().is_empty()).then(|| {
|
||||
modifiers.set(ModifiersState::empty());
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::ModifiersChanged(ModifiersState::empty().into()),
|
||||
}
|
||||
});
|
||||
|
||||
runner.send_events(clear_modifiers.into_iter().chain(iter::once(Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::Focused(false),
|
||||
})));
|
||||
});
|
||||
|
||||
let runner = self.runner.clone();
|
||||
let has_focus = canvas.has_focus.clone();
|
||||
canvas.on_focus(move || {
|
||||
if !has_focus.replace(true) {
|
||||
runner.send_event(Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::Focused(true),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// It is possible that at this point the canvas has
|
||||
// been focused before the callback can be called.
|
||||
let focused = canvas
|
||||
.document()
|
||||
.active_element()
|
||||
.filter(|element| {
|
||||
let canvas: &Element = canvas.raw();
|
||||
element == canvas
|
||||
})
|
||||
.is_some();
|
||||
|
||||
if focused {
|
||||
canvas.has_focus.set(true);
|
||||
self.runner.send_event(Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::Focused(true),
|
||||
})
|
||||
}
|
||||
|
||||
let runner = self.runner.clone();
|
||||
let modifiers = self.modifiers.clone();
|
||||
canvas.on_keyboard_press(
|
||||
move |physical_key, logical_key, text, location, repeat, active_modifiers| {
|
||||
let modifiers_changed = (modifiers.get() != active_modifiers).then(|| {
|
||||
modifiers.set(active_modifiers);
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::ModifiersChanged(active_modifiers.into()),
|
||||
}
|
||||
});
|
||||
|
||||
let device_id = RootDeviceId(DeviceId::dummy());
|
||||
|
||||
runner.send_events(
|
||||
iter::once(Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::KeyboardInput {
|
||||
device_id,
|
||||
event: KeyEvent {
|
||||
physical_key,
|
||||
logical_key,
|
||||
text,
|
||||
location,
|
||||
state: ElementState::Pressed,
|
||||
repeat,
|
||||
platform_specific: KeyEventExtra,
|
||||
},
|
||||
is_synthetic: false,
|
||||
},
|
||||
})
|
||||
.chain(modifiers_changed),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
let runner = self.runner.clone();
|
||||
let modifiers = self.modifiers.clone();
|
||||
canvas.on_keyboard_release(
|
||||
move |physical_key, logical_key, text, location, repeat, active_modifiers| {
|
||||
let modifiers_changed = (modifiers.get() != active_modifiers).then(|| {
|
||||
modifiers.set(active_modifiers);
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::ModifiersChanged(active_modifiers.into()),
|
||||
}
|
||||
});
|
||||
|
||||
let device_id = RootDeviceId(DeviceId::dummy());
|
||||
|
||||
runner.send_events(
|
||||
iter::once(Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::KeyboardInput {
|
||||
device_id,
|
||||
event: KeyEvent {
|
||||
physical_key,
|
||||
logical_key,
|
||||
text,
|
||||
location,
|
||||
state: ElementState::Released,
|
||||
repeat,
|
||||
platform_specific: KeyEventExtra,
|
||||
},
|
||||
is_synthetic: false,
|
||||
},
|
||||
})
|
||||
.chain(modifiers_changed),
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
let has_focus = canvas.has_focus.clone();
|
||||
canvas.on_cursor_leave({
|
||||
let runner = self.runner.clone();
|
||||
let has_focus = has_focus.clone();
|
||||
let modifiers = self.modifiers.clone();
|
||||
|
||||
move |active_modifiers, pointer_id| {
|
||||
let focus = (has_focus.get() && modifiers.get() != active_modifiers).then(|| {
|
||||
modifiers.set(active_modifiers);
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::ModifiersChanged(active_modifiers.into()),
|
||||
}
|
||||
});
|
||||
|
||||
let pointer = pointer_id.map(|pointer_id| Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::CursorLeft {
|
||||
device_id: RootDeviceId(DeviceId(pointer_id)),
|
||||
},
|
||||
});
|
||||
|
||||
if focus.is_some() || pointer.is_some() {
|
||||
runner.send_events(focus.into_iter().chain(pointer))
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
canvas.on_cursor_enter({
|
||||
let runner = self.runner.clone();
|
||||
let has_focus = has_focus.clone();
|
||||
let modifiers = self.modifiers.clone();
|
||||
|
||||
move |active_modifiers, pointer_id| {
|
||||
let focus = (has_focus.get() && modifiers.get() != active_modifiers).then(|| {
|
||||
modifiers.set(active_modifiers);
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::ModifiersChanged(active_modifiers.into()),
|
||||
}
|
||||
});
|
||||
|
||||
let pointer = pointer_id.map(|pointer_id| Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::CursorEntered {
|
||||
device_id: RootDeviceId(DeviceId(pointer_id)),
|
||||
},
|
||||
});
|
||||
|
||||
if focus.is_some() || pointer.is_some() {
|
||||
runner.send_events(focus.into_iter().chain(pointer))
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
canvas.on_cursor_move(
|
||||
{
|
||||
let runner = self.runner.clone();
|
||||
let has_focus = has_focus.clone();
|
||||
let modifiers = self.modifiers.clone();
|
||||
|
||||
move |active_modifiers, pointer_id, events| {
|
||||
let modifiers =
|
||||
(has_focus.get() && modifiers.get() != active_modifiers).then(|| {
|
||||
modifiers.set(active_modifiers);
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::ModifiersChanged(active_modifiers.into()),
|
||||
}
|
||||
});
|
||||
|
||||
runner.send_events(modifiers.into_iter().chain(events.flat_map(|position| {
|
||||
let device_id = RootDeviceId(DeviceId(pointer_id));
|
||||
|
||||
iter::once(Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::CursorMoved { device_id, position },
|
||||
})
|
||||
})));
|
||||
}
|
||||
},
|
||||
{
|
||||
let runner = self.runner.clone();
|
||||
let has_focus = has_focus.clone();
|
||||
let modifiers = self.modifiers.clone();
|
||||
|
||||
move |active_modifiers, device_id, events| {
|
||||
let modifiers =
|
||||
(has_focus.get() && modifiers.get() != active_modifiers).then(|| {
|
||||
modifiers.set(active_modifiers);
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::ModifiersChanged(active_modifiers.into()),
|
||||
}
|
||||
});
|
||||
|
||||
runner.send_events(modifiers.into_iter().chain(events.map(
|
||||
|(location, force)| Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::Touch(Touch {
|
||||
id: device_id as u64,
|
||||
device_id: RootDeviceId(DeviceId(device_id)),
|
||||
phase: TouchPhase::Moved,
|
||||
force: Some(force),
|
||||
location,
|
||||
}),
|
||||
},
|
||||
)));
|
||||
}
|
||||
},
|
||||
{
|
||||
let runner = self.runner.clone();
|
||||
let has_focus = has_focus.clone();
|
||||
let modifiers = self.modifiers.clone();
|
||||
|
||||
move |active_modifiers,
|
||||
pointer_id,
|
||||
position: crate::dpi::PhysicalPosition<f64>,
|
||||
buttons,
|
||||
button| {
|
||||
let modifiers =
|
||||
(has_focus.get() && modifiers.get() != active_modifiers).then(|| {
|
||||
modifiers.set(active_modifiers);
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::ModifiersChanged(active_modifiers.into()),
|
||||
}
|
||||
});
|
||||
|
||||
let device_id = RootDeviceId(DeviceId(pointer_id));
|
||||
|
||||
let state = if buttons.contains(button.into()) {
|
||||
ElementState::Pressed
|
||||
} else {
|
||||
ElementState::Released
|
||||
};
|
||||
|
||||
// A chorded button event may come in without any prior CursorMoved events,
|
||||
// therefore we should send a CursorMoved event to make sure that the
|
||||
// user code has the correct cursor position.
|
||||
runner.send_events(modifiers.into_iter().chain([
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::CursorMoved { device_id, position },
|
||||
},
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::MouseInput { device_id, state, button },
|
||||
},
|
||||
]));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
canvas.on_mouse_press(
|
||||
{
|
||||
let runner = self.runner.clone();
|
||||
let modifiers = self.modifiers.clone();
|
||||
|
||||
move |active_modifiers, pointer_id, position, button| {
|
||||
let modifiers = (modifiers.get() != active_modifiers).then(|| {
|
||||
modifiers.set(active_modifiers);
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::ModifiersChanged(active_modifiers.into()),
|
||||
}
|
||||
});
|
||||
|
||||
let device_id: RootDeviceId = RootDeviceId(DeviceId(pointer_id));
|
||||
|
||||
// A mouse down event may come in without any prior CursorMoved events,
|
||||
// therefore we should send a CursorMoved event to make sure that the
|
||||
// user code has the correct cursor position.
|
||||
runner.send_events(modifiers.into_iter().chain([
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::CursorMoved { device_id, position },
|
||||
},
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::MouseInput {
|
||||
device_id,
|
||||
state: ElementState::Pressed,
|
||||
button,
|
||||
},
|
||||
},
|
||||
]));
|
||||
}
|
||||
},
|
||||
{
|
||||
let runner = self.runner.clone();
|
||||
let modifiers = self.modifiers.clone();
|
||||
|
||||
move |active_modifiers, device_id, location, force| {
|
||||
let modifiers = (modifiers.get() != active_modifiers).then(|| {
|
||||
modifiers.set(active_modifiers);
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::ModifiersChanged(active_modifiers.into()),
|
||||
}
|
||||
});
|
||||
|
||||
runner.send_events(modifiers.into_iter().chain(iter::once(
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::Touch(Touch {
|
||||
id: device_id as u64,
|
||||
device_id: RootDeviceId(DeviceId(device_id)),
|
||||
phase: TouchPhase::Started,
|
||||
force: Some(force),
|
||||
location,
|
||||
}),
|
||||
},
|
||||
)))
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
canvas.on_mouse_release(
|
||||
{
|
||||
let runner = self.runner.clone();
|
||||
let has_focus = has_focus.clone();
|
||||
let modifiers = self.modifiers.clone();
|
||||
|
||||
move |active_modifiers, pointer_id, position, button| {
|
||||
let modifiers =
|
||||
(has_focus.get() && modifiers.get() != active_modifiers).then(|| {
|
||||
modifiers.set(active_modifiers);
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::ModifiersChanged(active_modifiers.into()),
|
||||
}
|
||||
});
|
||||
|
||||
let device_id: RootDeviceId = RootDeviceId(DeviceId(pointer_id));
|
||||
|
||||
// A mouse up event may come in without any prior CursorMoved events,
|
||||
// therefore we should send a CursorMoved event to make sure that the
|
||||
// user code has the correct cursor position.
|
||||
runner.send_events(modifiers.into_iter().chain([
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::CursorMoved { device_id, position },
|
||||
},
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::MouseInput {
|
||||
device_id,
|
||||
state: ElementState::Released,
|
||||
button,
|
||||
},
|
||||
},
|
||||
]));
|
||||
}
|
||||
},
|
||||
{
|
||||
let runner_touch = self.runner.clone();
|
||||
let has_focus = has_focus.clone();
|
||||
let modifiers = self.modifiers.clone();
|
||||
|
||||
move |active_modifiers, device_id, location, force| {
|
||||
let modifiers =
|
||||
(has_focus.get() && modifiers.get() != active_modifiers).then(|| {
|
||||
modifiers.set(active_modifiers);
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::ModifiersChanged(active_modifiers.into()),
|
||||
}
|
||||
});
|
||||
|
||||
runner_touch.send_events(modifiers.into_iter().chain(iter::once(
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::Touch(Touch {
|
||||
id: device_id as u64,
|
||||
device_id: RootDeviceId(DeviceId(device_id)),
|
||||
phase: TouchPhase::Ended,
|
||||
force: Some(force),
|
||||
location,
|
||||
}),
|
||||
},
|
||||
)));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
let runner = self.runner.clone();
|
||||
let modifiers = self.modifiers.clone();
|
||||
canvas.on_mouse_wheel(move |pointer_id, delta, active_modifiers| {
|
||||
let modifiers_changed =
|
||||
(has_focus.get() && modifiers.get() != active_modifiers).then(|| {
|
||||
modifiers.set(active_modifiers);
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::ModifiersChanged(active_modifiers.into()),
|
||||
}
|
||||
});
|
||||
|
||||
runner.send_events(modifiers_changed.into_iter().chain(iter::once(
|
||||
Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::MouseWheel {
|
||||
device_id: RootDeviceId(DeviceId(pointer_id)),
|
||||
delta,
|
||||
phase: TouchPhase::Moved,
|
||||
},
|
||||
},
|
||||
)));
|
||||
});
|
||||
|
||||
let runner = self.runner.clone();
|
||||
canvas.on_touch_cancel(move |device_id, location, force| {
|
||||
runner.send_event(Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::Touch(Touch {
|
||||
id: device_id as u64,
|
||||
device_id: RootDeviceId(DeviceId(device_id)),
|
||||
phase: TouchPhase::Cancelled,
|
||||
force: Some(force),
|
||||
location,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
let runner = self.runner.clone();
|
||||
canvas.on_dark_mode(move |is_dark_mode| {
|
||||
let theme = if is_dark_mode { Theme::Dark } else { Theme::Light };
|
||||
runner.send_event(Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::ThemeChanged(theme),
|
||||
});
|
||||
});
|
||||
|
||||
canvas.on_resize_scale(
|
||||
{
|
||||
let runner = self.runner.clone();
|
||||
let canvas = canvas_clone.clone();
|
||||
|
||||
move |size, scale| {
|
||||
runner.send_event(EventWrapper::ScaleChange {
|
||||
canvas: Rc::downgrade(&canvas),
|
||||
size,
|
||||
scale,
|
||||
})
|
||||
}
|
||||
},
|
||||
{
|
||||
let runner = self.runner.clone();
|
||||
let canvas = canvas_clone.clone();
|
||||
|
||||
move |new_size| {
|
||||
let canvas = canvas.borrow();
|
||||
canvas.set_current_size(new_size);
|
||||
if canvas.old_size() != new_size {
|
||||
canvas.set_old_size(new_size);
|
||||
runner.send_event(Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::Resized(new_size),
|
||||
});
|
||||
canvas.request_animation_frame();
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
let runner = self.runner.clone();
|
||||
canvas.on_intersection(move |is_intersecting| {
|
||||
// only fire if visible while skipping the first event if it's intersecting
|
||||
if backend::is_visible(runner.document())
|
||||
&& !(is_intersecting && canvas_clone.borrow().is_intersecting.is_none())
|
||||
{
|
||||
runner.send_event(Event::WindowEvent {
|
||||
window_id: RootWindowId(id),
|
||||
event: WindowEvent::Occluded(!is_intersecting),
|
||||
});
|
||||
}
|
||||
|
||||
canvas_clone.borrow_mut().is_intersecting = Some(is_intersecting);
|
||||
});
|
||||
|
||||
let runner = self.runner.clone();
|
||||
canvas.on_animation_frame(move || runner.request_redraw(RootWindowId(id)));
|
||||
|
||||
canvas.on_context_menu();
|
||||
}
|
||||
|
||||
pub fn available_monitors(&self) -> VecDequeIter<MonitorHandle> {
|
||||
VecDeque::new().into_iter()
|
||||
}
|
||||
|
||||
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_05")]
|
||||
#[inline]
|
||||
pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
|
||||
rwh_05::RawDisplayHandle::Web(rwh_05::WebDisplayHandle::empty())
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
#[inline]
|
||||
pub fn raw_display_handle_rwh_06(
|
||||
&self,
|
||||
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
|
||||
Ok(rwh_06::RawDisplayHandle::Web(rwh_06::WebDisplayHandle::new()))
|
||||
}
|
||||
|
||||
pub fn listen_device_events(&self, allowed: DeviceEvents) {
|
||||
self.runner.listen_device_events(allowed)
|
||||
}
|
||||
|
||||
pub fn system_theme(&self) -> Option<Theme> {
|
||||
backend::is_dark_mode(self.runner.window()).map(|is_dark_mode| {
|
||||
if is_dark_mode {
|
||||
Theme::Dark
|
||||
} else {
|
||||
Theme::Light
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||
self.runner.set_control_flow(control_flow)
|
||||
}
|
||||
|
||||
pub(crate) fn control_flow(&self) -> ControlFlow {
|
||||
self.runner.control_flow()
|
||||
}
|
||||
|
||||
pub(crate) fn exit(&self) {
|
||||
self.runner.exit()
|
||||
}
|
||||
|
||||
pub(crate) fn exiting(&self) -> bool {
|
||||
self.runner.exiting()
|
||||
}
|
||||
|
||||
pub(crate) fn set_poll_strategy(&self, strategy: PollStrategy) {
|
||||
self.runner.set_poll_strategy(strategy)
|
||||
}
|
||||
|
||||
pub(crate) fn poll_strategy(&self) -> PollStrategy {
|
||||
self.runner.poll_strategy()
|
||||
}
|
||||
|
||||
pub(crate) fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy) {
|
||||
self.runner.set_wait_until_strategy(strategy)
|
||||
}
|
||||
|
||||
pub(crate) fn wait_until_strategy(&self) -> WaitUntilStrategy {
|
||||
self.runner.wait_until_strategy()
|
||||
}
|
||||
|
||||
pub(crate) fn waker(&self) -> Waker<Weak<Execution>> {
|
||||
self.runner.waker()
|
||||
}
|
||||
|
||||
pub(crate) fn owned_display_handle(&self) -> OwnedDisplayHandle {
|
||||
OwnedDisplayHandle
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct OwnedDisplayHandle;
|
||||
|
||||
impl OwnedDisplayHandle {
|
||||
#[cfg(feature = "rwh_05")]
|
||||
#[inline]
|
||||
pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
|
||||
rwh_05::WebDisplayHandle::empty().into()
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
#[inline]
|
||||
pub fn raw_display_handle_rwh_06(
|
||||
&self,
|
||||
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
|
||||
Ok(rwh_06::WebDisplayHandle::new().into())
|
||||
}
|
||||
}
|
||||
@@ -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 device;
|
||||
mod error;
|
||||
mod event_loop;
|
||||
mod keyboard;
|
||||
mod main_thread;
|
||||
mod monitor;
|
||||
mod web_sys;
|
||||
mod window;
|
||||
|
||||
pub use self::device::DeviceId;
|
||||
pub use self::error::OsError;
|
||||
pub(crate) use self::event_loop::{
|
||||
ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle,
|
||||
PlatformSpecificEventLoopAttributes,
|
||||
};
|
||||
pub use self::monitor::{MonitorHandle, VideoModeHandle};
|
||||
pub use self::window::{PlatformSpecificWindowAttributes, Window, WindowId};
|
||||
|
||||
pub(crate) use self::keyboard::KeyEventExtra;
|
||||
use self::web_sys as backend;
|
||||
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
||||
pub(crate) use crate::platform_impl::Fullscreen;
|
||||
pub(crate) use cursor::{
|
||||
CustomCursor as PlatformCustomCursor, CustomCursorFuture,
|
||||
CustomCursorSource as PlatformCustomCursorSource,
|
||||
};
|
||||
@@ -1,53 +0,0 @@
|
||||
use std::iter::Empty;
|
||||
|
||||
use crate::dpi::{PhysicalPosition, PhysicalSize};
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct MonitorHandle;
|
||||
|
||||
impl MonitorHandle {
|
||||
pub fn scale_factor(&self) -> f64 {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
pub fn position(&self) -> PhysicalPosition<i32> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
pub fn name(&self) -> Option<String> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
pub fn refresh_rate_millihertz(&self) -> Option<u32> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
pub fn video_modes(&self) -> Empty<VideoModeHandle> {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct VideoModeHandle;
|
||||
|
||||
impl VideoModeHandle {
|
||||
pub fn size(&self) -> PhysicalSize<u32> {
|
||||
unreachable!();
|
||||
}
|
||||
|
||||
pub fn bit_depth(&self) -> u16 {
|
||||
unreachable!();
|
||||
}
|
||||
|
||||
pub fn refresh_rate_millihertz(&self) -> u32 {
|
||||
unreachable!();
|
||||
}
|
||||
|
||||
pub fn monitor(&self) -> MonitorHandle {
|
||||
unreachable!();
|
||||
}
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::canvas::Common;
|
||||
use super::event;
|
||||
use super::event_handle::EventListenerHandle;
|
||||
use crate::dpi::PhysicalPosition;
|
||||
use crate::event::{Force, MouseButton};
|
||||
use crate::keyboard::ModifiersState;
|
||||
|
||||
use event::ButtonsState;
|
||||
use web_sys::PointerEvent;
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(super) struct PointerHandler {
|
||||
on_cursor_leave: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>,
|
||||
on_cursor_enter: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>,
|
||||
on_cursor_move: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>,
|
||||
on_pointer_press: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>,
|
||||
on_pointer_release: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>,
|
||||
on_touch_cancel: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>,
|
||||
}
|
||||
|
||||
impl PointerHandler {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
on_cursor_leave: None,
|
||||
on_cursor_enter: None,
|
||||
on_cursor_move: None,
|
||||
on_pointer_press: None,
|
||||
on_pointer_release: None,
|
||||
on_touch_cancel: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_cursor_leave<F>(&mut self, canvas_common: &Common, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(ModifiersState, Option<i32>),
|
||||
{
|
||||
self.on_cursor_leave =
|
||||
Some(canvas_common.add_event("pointerout", move |event: PointerEvent| {
|
||||
let modifiers = event::mouse_modifiers(&event);
|
||||
|
||||
// touch events are handled separately
|
||||
// handling them here would produce duplicate mouse events, inconsistent with
|
||||
// other platforms.
|
||||
let pointer_id = (event.pointer_type() != "touch").then(|| event.pointer_id());
|
||||
|
||||
handler(modifiers, pointer_id);
|
||||
}));
|
||||
}
|
||||
|
||||
pub fn on_cursor_enter<F>(&mut self, canvas_common: &Common, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(ModifiersState, Option<i32>),
|
||||
{
|
||||
self.on_cursor_enter =
|
||||
Some(canvas_common.add_event("pointerover", move |event: PointerEvent| {
|
||||
let modifiers = event::mouse_modifiers(&event);
|
||||
|
||||
// touch events are handled separately
|
||||
// handling them here would produce duplicate mouse events, inconsistent with
|
||||
// other platforms.
|
||||
let pointer_id = (event.pointer_type() != "touch").then(|| event.pointer_id());
|
||||
|
||||
handler(modifiers, pointer_id);
|
||||
}));
|
||||
}
|
||||
|
||||
pub fn on_mouse_release<M, T>(
|
||||
&mut self,
|
||||
canvas_common: &Common,
|
||||
mut mouse_handler: M,
|
||||
mut touch_handler: T,
|
||||
) where
|
||||
M: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, MouseButton),
|
||||
T: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, Force),
|
||||
{
|
||||
let window = canvas_common.window.clone();
|
||||
self.on_pointer_release =
|
||||
Some(canvas_common.add_event("pointerup", move |event: PointerEvent| {
|
||||
let modifiers = event::mouse_modifiers(&event);
|
||||
|
||||
match event.pointer_type().as_str() {
|
||||
"touch" => touch_handler(
|
||||
modifiers,
|
||||
event.pointer_id(),
|
||||
event::mouse_position(&event).to_physical(super::scale_factor(&window)),
|
||||
Force::Normalized(event.pressure() as f64),
|
||||
),
|
||||
_ => mouse_handler(
|
||||
modifiers,
|
||||
event.pointer_id(),
|
||||
event::mouse_position(&event).to_physical(super::scale_factor(&window)),
|
||||
event::mouse_button(&event).expect("no mouse button released"),
|
||||
),
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
pub fn on_mouse_press<M, T>(
|
||||
&mut self,
|
||||
canvas_common: &Common,
|
||||
mut mouse_handler: M,
|
||||
mut touch_handler: T,
|
||||
prevent_default: Rc<Cell<bool>>,
|
||||
) where
|
||||
M: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, MouseButton),
|
||||
T: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, Force),
|
||||
{
|
||||
let window = canvas_common.window.clone();
|
||||
let canvas = canvas_common.raw().clone();
|
||||
self.on_pointer_press =
|
||||
Some(canvas_common.add_event("pointerdown", move |event: PointerEvent| {
|
||||
if prevent_default.get() {
|
||||
// prevent text selection
|
||||
event.prevent_default();
|
||||
// but still focus element
|
||||
let _ = canvas.focus();
|
||||
}
|
||||
|
||||
let modifiers = event::mouse_modifiers(&event);
|
||||
let pointer_type = &event.pointer_type();
|
||||
|
||||
match pointer_type.as_str() {
|
||||
"touch" => {
|
||||
touch_handler(
|
||||
modifiers,
|
||||
event.pointer_id(),
|
||||
event::mouse_position(&event).to_physical(super::scale_factor(&window)),
|
||||
Force::Normalized(event.pressure() as f64),
|
||||
);
|
||||
},
|
||||
_ => {
|
||||
mouse_handler(
|
||||
modifiers,
|
||||
event.pointer_id(),
|
||||
event::mouse_position(&event).to_physical(super::scale_factor(&window)),
|
||||
event::mouse_button(&event).expect("no mouse button pressed"),
|
||||
);
|
||||
|
||||
if pointer_type == "mouse" {
|
||||
// Error is swallowed here since the error would occur every time the
|
||||
// mouse is clicked when the cursor is
|
||||
// grabbed, and there is probably not a
|
||||
// situation where this could fail, that we
|
||||
// care if it fails.
|
||||
let _e = canvas.set_pointer_capture(event.pointer_id());
|
||||
}
|
||||
},
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
pub fn on_cursor_move<M, T, B>(
|
||||
&mut self,
|
||||
canvas_common: &Common,
|
||||
mut mouse_handler: M,
|
||||
mut touch_handler: T,
|
||||
mut button_handler: B,
|
||||
prevent_default: Rc<Cell<bool>>,
|
||||
) where
|
||||
M: 'static + FnMut(ModifiersState, i32, &mut dyn Iterator<Item = PhysicalPosition<f64>>),
|
||||
T: 'static
|
||||
+ FnMut(ModifiersState, i32, &mut dyn Iterator<Item = (PhysicalPosition<f64>, Force)>),
|
||||
B: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, ButtonsState, MouseButton),
|
||||
{
|
||||
let window = canvas_common.window.clone();
|
||||
let canvas = canvas_common.raw().clone();
|
||||
self.on_cursor_move =
|
||||
Some(canvas_common.add_event("pointermove", move |event: PointerEvent| {
|
||||
let modifiers = event::mouse_modifiers(&event);
|
||||
|
||||
let id = event.pointer_id();
|
||||
|
||||
// chorded button event
|
||||
if let Some(button) = event::mouse_button(&event) {
|
||||
if prevent_default.get() {
|
||||
// prevent text selection
|
||||
event.prevent_default();
|
||||
// but still focus element
|
||||
let _ = canvas.focus();
|
||||
}
|
||||
|
||||
button_handler(
|
||||
modifiers,
|
||||
id,
|
||||
event::mouse_position(&event).to_physical(super::scale_factor(&window)),
|
||||
event::mouse_buttons(&event),
|
||||
button,
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// pointer move event
|
||||
let scale = super::scale_factor(&window);
|
||||
match event.pointer_type().as_str() {
|
||||
"touch" => touch_handler(
|
||||
modifiers,
|
||||
id,
|
||||
&mut event::pointer_move_event(event).map(|event| {
|
||||
(
|
||||
event::mouse_position(&event).to_physical(scale),
|
||||
Force::Normalized(event.pressure() as f64),
|
||||
)
|
||||
}),
|
||||
),
|
||||
_ => mouse_handler(
|
||||
modifiers,
|
||||
id,
|
||||
&mut event::pointer_move_event(event)
|
||||
.map(|event| event::mouse_position(&event).to_physical(scale)),
|
||||
),
|
||||
};
|
||||
}));
|
||||
}
|
||||
|
||||
pub fn on_touch_cancel<F>(&mut self, canvas_common: &Common, mut handler: F)
|
||||
where
|
||||
F: 'static + FnMut(i32, PhysicalPosition<f64>, Force),
|
||||
{
|
||||
let window = canvas_common.window.clone();
|
||||
self.on_touch_cancel =
|
||||
Some(canvas_common.add_event("pointercancel", move |event: PointerEvent| {
|
||||
if event.pointer_type() == "touch" {
|
||||
handler(
|
||||
event.pointer_id(),
|
||||
event::mouse_position(&event).to_physical(super::scale_factor(&window)),
|
||||
Force::Normalized(event.pressure() as f64),
|
||||
);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
pub fn remove_listeners(&mut self) {
|
||||
self.on_cursor_leave = None;
|
||||
self.on_cursor_enter = None;
|
||||
self.on_cursor_move = None;
|
||||
self.on_pointer_press = None;
|
||||
self.on_pointer_release = None;
|
||||
self.on_touch_cancel = None;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
onmessage = event => {
|
||||
const [port, timeout] = event.data
|
||||
const f = () => port.postMessage(undefined)
|
||||
|
||||
if ('scheduler' in this) {
|
||||
scheduler.postTask(f, { delay: timeout })
|
||||
} else {
|
||||
setTimeout(f, timeout)
|
||||
}
|
||||
}
|
||||
1
src/platform_impl/web/web_sys/worker.min.js
vendored
1
src/platform_impl/web/web_sys/worker.min.js
vendored
@@ -1 +0,0 @@
|
||||
onmessage=e=>{let[s,t]=e.data,a=()=>s.postMessage(void 0);"scheduler"in this?scheduler.postTask(a,{delay:t}):setTimeout(a,t)};
|
||||
@@ -1,477 +0,0 @@
|
||||
use crate::dpi::{PhysicalPosition, PhysicalSize, Position, Size};
|
||||
use crate::error::{ExternalError, NotSupportedError, OsError as RootOE};
|
||||
use crate::icon::Icon;
|
||||
use crate::window::{
|
||||
Cursor, CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType,
|
||||
WindowAttributes, WindowButtons, WindowId as RootWI, WindowLevel,
|
||||
};
|
||||
|
||||
use super::main_thread::{MainThreadMarker, MainThreadSafe};
|
||||
use super::monitor::MonitorHandle;
|
||||
use super::r#async::Dispatcher;
|
||||
use super::{backend, ActiveEventLoop, Fullscreen};
|
||||
use web_sys::HtmlCanvasElement;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::VecDeque;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct Window {
|
||||
inner: Dispatcher<Inner>,
|
||||
}
|
||||
|
||||
pub struct Inner {
|
||||
id: WindowId,
|
||||
pub window: web_sys::Window,
|
||||
canvas: Rc<RefCell<backend::Canvas>>,
|
||||
destroy_fn: Option<Box<dyn FnOnce()>>,
|
||||
}
|
||||
|
||||
impl Window {
|
||||
pub(crate) fn new(
|
||||
target: &ActiveEventLoop,
|
||||
mut attr: WindowAttributes,
|
||||
) -> Result<Self, RootOE> {
|
||||
let id = target.generate_id();
|
||||
|
||||
let window = target.runner.window();
|
||||
let document = target.runner.document();
|
||||
let canvas = backend::Canvas::create(
|
||||
target.runner.main_thread(),
|
||||
id,
|
||||
window.clone(),
|
||||
document.clone(),
|
||||
&mut attr,
|
||||
)?;
|
||||
let canvas = Rc::new(RefCell::new(canvas));
|
||||
|
||||
target.register(&canvas, id);
|
||||
|
||||
let runner = target.runner.clone();
|
||||
let destroy_fn = Box::new(move || runner.notify_destroy_window(RootWI(id)));
|
||||
|
||||
let inner = Inner { id, window: window.clone(), canvas, destroy_fn: Some(destroy_fn) };
|
||||
|
||||
inner.set_title(&attr.title);
|
||||
inner.set_maximized(attr.maximized);
|
||||
inner.set_visible(attr.visible);
|
||||
inner.set_window_icon(attr.window_icon);
|
||||
inner.set_cursor(attr.cursor);
|
||||
|
||||
let canvas = Rc::downgrade(&inner.canvas);
|
||||
let (dispatcher, runner) = Dispatcher::new(target.runner.main_thread(), inner).unwrap();
|
||||
target.runner.add_canvas(RootWI(id), canvas, runner);
|
||||
|
||||
Ok(Window { inner: dispatcher })
|
||||
}
|
||||
|
||||
pub(crate) fn maybe_queue_on_main(&self, f: impl FnOnce(&Inner) + Send + 'static) {
|
||||
self.inner.dispatch(f)
|
||||
}
|
||||
|
||||
pub(crate) fn maybe_wait_on_main<R: Send>(&self, f: impl FnOnce(&Inner) -> R + Send) -> R {
|
||||
self.inner.queue(f)
|
||||
}
|
||||
|
||||
pub fn canvas(&self) -> Option<HtmlCanvasElement> {
|
||||
self.inner.value().map(|inner| inner.canvas.borrow().raw().clone())
|
||||
}
|
||||
|
||||
pub(crate) fn prevent_default(&self) -> bool {
|
||||
self.inner.queue(|inner| inner.canvas.borrow().prevent_default.get())
|
||||
}
|
||||
|
||||
pub(crate) fn set_prevent_default(&self, prevent_default: bool) {
|
||||
self.inner.dispatch(move |inner| inner.canvas.borrow().prevent_default.set(prevent_default))
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
#[inline]
|
||||
pub fn raw_window_handle_rwh_06(&self) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> {
|
||||
self.inner
|
||||
.value()
|
||||
.map(|inner| {
|
||||
let canvas = inner.canvas.borrow();
|
||||
// SAFETY: This will only work if the reference to `HtmlCanvasElement` stays valid.
|
||||
let canvas: &wasm_bindgen::JsValue = canvas.raw();
|
||||
let window_handle =
|
||||
rwh_06::WebCanvasWindowHandle::new(std::ptr::NonNull::from(canvas).cast());
|
||||
rwh_06::RawWindowHandle::WebCanvas(window_handle)
|
||||
})
|
||||
.ok_or(rwh_06::HandleError::Unavailable)
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_06")]
|
||||
#[inline]
|
||||
pub(crate) fn raw_display_handle_rwh_06(
|
||||
&self,
|
||||
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
|
||||
Ok(rwh_06::RawDisplayHandle::Web(rwh_06::WebDisplayHandle::new()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
pub fn set_title(&self, title: &str) {
|
||||
self.canvas.borrow().set_attribute("alt", title)
|
||||
}
|
||||
|
||||
pub fn set_transparent(&self, _transparent: bool) {}
|
||||
|
||||
pub fn set_blur(&self, _blur: bool) {}
|
||||
|
||||
pub fn set_visible(&self, _visible: bool) {
|
||||
// Intentionally a no-op
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_visible(&self) -> Option<bool> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn request_redraw(&self) {
|
||||
self.canvas.borrow().request_animation_frame();
|
||||
}
|
||||
|
||||
pub fn pre_present_notify(&self) {}
|
||||
|
||||
pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
|
||||
Ok(self.canvas.borrow().position().to_physical(self.scale_factor()))
|
||||
}
|
||||
|
||||
pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> {
|
||||
// Note: the canvas element has no window decorations, so this is equal to `outer_position`.
|
||||
self.outer_position()
|
||||
}
|
||||
|
||||
pub fn set_outer_position(&self, position: Position) {
|
||||
let canvas = self.canvas.borrow();
|
||||
let position = position.to_logical::<f64>(self.scale_factor());
|
||||
|
||||
backend::set_canvas_position(canvas.document(), canvas.raw(), canvas.style(), position)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn inner_size(&self) -> PhysicalSize<u32> {
|
||||
self.canvas.borrow().inner_size()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn outer_size(&self) -> PhysicalSize<u32> {
|
||||
// Note: the canvas element has no window decorations, so this is equal to `inner_size`.
|
||||
self.inner_size()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn request_inner_size(&self, size: Size) -> Option<PhysicalSize<u32>> {
|
||||
let size = size.to_logical(self.scale_factor());
|
||||
let canvas = self.canvas.borrow();
|
||||
backend::set_canvas_size(canvas.document(), canvas.raw(), canvas.style(), size);
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_min_inner_size(&self, dimensions: Option<Size>) {
|
||||
let dimensions = dimensions.map(|dimensions| dimensions.to_logical(self.scale_factor()));
|
||||
let canvas = self.canvas.borrow();
|
||||
backend::set_canvas_min_size(canvas.document(), canvas.raw(), canvas.style(), dimensions)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_max_inner_size(&self, dimensions: Option<Size>) {
|
||||
let dimensions = dimensions.map(|dimensions| dimensions.to_logical(self.scale_factor()));
|
||||
let canvas = self.canvas.borrow();
|
||||
backend::set_canvas_max_size(canvas.document(), canvas.raw(), canvas.style(), dimensions)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> {
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_resize_increments(&self, _increments: Option<Size>) {
|
||||
// Intentionally a no-op: users can't resize canvas elements
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_resizable(&self, _resizable: bool) {
|
||||
// Intentionally a no-op: users can't resize canvas elements
|
||||
}
|
||||
|
||||
pub fn is_resizable(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_enabled_buttons(&self, _buttons: WindowButtons) {}
|
||||
|
||||
#[inline]
|
||||
pub fn enabled_buttons(&self) -> WindowButtons {
|
||||
WindowButtons::all()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn scale_factor(&self) -> f64 {
|
||||
super::backend::scale_factor(&self.window)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor(&self, cursor: Cursor) {
|
||||
self.canvas.borrow_mut().cursor.set_cursor(cursor)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_position(&self, _position: Position) -> Result<(), ExternalError> {
|
||||
Err(ExternalError::NotSupported(NotSupportedError::new()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> {
|
||||
let lock = match mode {
|
||||
CursorGrabMode::None => false,
|
||||
CursorGrabMode::Locked => true,
|
||||
CursorGrabMode::Confined => {
|
||||
return Err(ExternalError::NotSupported(NotSupportedError::new()))
|
||||
},
|
||||
};
|
||||
|
||||
self.canvas.borrow().set_cursor_lock(lock).map_err(ExternalError::Os)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_visible(&self, visible: bool) {
|
||||
self.canvas.borrow_mut().cursor.set_cursor_visible(visible)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn drag_window(&self) -> Result<(), ExternalError> {
|
||||
Err(ExternalError::NotSupported(NotSupportedError::new()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn drag_resize_window(&self, _direction: ResizeDirection) -> Result<(), ExternalError> {
|
||||
Err(ExternalError::NotSupported(NotSupportedError::new()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn show_window_menu(&self, _position: Position) {}
|
||||
|
||||
#[inline]
|
||||
pub fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), ExternalError> {
|
||||
Err(ExternalError::NotSupported(NotSupportedError::new()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_minimized(&self, _minimized: bool) {
|
||||
// Intentionally a no-op, as canvases cannot be 'minimized'
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_minimized(&self) -> Option<bool> {
|
||||
// Canvas cannot be 'minimized'
|
||||
Some(false)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_maximized(&self, _maximized: bool) {
|
||||
// Intentionally a no-op, as canvases cannot be 'maximized'
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_maximized(&self) -> bool {
|
||||
// Canvas cannot be 'maximized'
|
||||
false
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn fullscreen(&self) -> Option<Fullscreen> {
|
||||
if self.canvas.borrow().is_fullscreen() {
|
||||
Some(Fullscreen::Borderless(None))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) {
|
||||
let canvas = &self.canvas.borrow();
|
||||
|
||||
if fullscreen.is_some() {
|
||||
canvas.request_fullscreen();
|
||||
} else {
|
||||
canvas.exit_fullscreen()
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_decorations(&self, _decorations: bool) {
|
||||
// Intentionally a no-op, no canvas decorations
|
||||
}
|
||||
|
||||
pub fn is_decorated(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_window_level(&self, _level: WindowLevel) {
|
||||
// Intentionally a no-op, no window ordering
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_window_icon(&self, _window_icon: Option<Icon>) {
|
||||
// Currently an intentional no-op
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_ime_cursor_area(&self, _position: Position, _size: Size) {
|
||||
// Currently a no-op as it does not seem there is good support for this on web
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_ime_allowed(&self, _allowed: bool) {
|
||||
// Currently not implemented
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_ime_purpose(&self, _purpose: ImePurpose) {
|
||||
// Currently not implemented
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn focus_window(&self) {
|
||||
let _ = self.canvas.borrow().raw().focus();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn request_user_attention(&self, _request_type: Option<UserAttentionType>) {
|
||||
// Currently an intentional no-op
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn current_monitor(&self) -> Option<MonitorHandle> {
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||
VecDeque::new()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn id(&self) -> WindowId {
|
||||
self.id
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_04")]
|
||||
#[inline]
|
||||
pub fn raw_window_handle_rwh_04(&self) -> rwh_04::RawWindowHandle {
|
||||
let mut window_handle = rwh_04::WebHandle::empty();
|
||||
window_handle.id = self.id.0;
|
||||
rwh_04::RawWindowHandle::Web(window_handle)
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_05")]
|
||||
#[inline]
|
||||
pub fn raw_window_handle_rwh_05(&self) -> rwh_05::RawWindowHandle {
|
||||
let mut window_handle = rwh_05::WebWindowHandle::empty();
|
||||
window_handle.id = self.id.0;
|
||||
rwh_05::RawWindowHandle::Web(window_handle)
|
||||
}
|
||||
|
||||
#[cfg(feature = "rwh_05")]
|
||||
#[inline]
|
||||
pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
|
||||
rwh_05::RawDisplayHandle::Web(rwh_05::WebDisplayHandle::empty())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn set_theme(&self, _theme: Option<Theme>) {}
|
||||
|
||||
#[inline]
|
||||
pub fn theme(&self) -> Option<Theme> {
|
||||
backend::is_dark_mode(&self.window).map(|is_dark_mode| {
|
||||
if is_dark_mode {
|
||||
Theme::Dark
|
||||
} else {
|
||||
Theme::Light
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_content_protected(&self, _protected: bool) {}
|
||||
|
||||
#[inline]
|
||||
pub fn has_focus(&self) -> bool {
|
||||
self.canvas.borrow().has_focus.get()
|
||||
}
|
||||
|
||||
pub fn title(&self) -> String {
|
||||
String::new()
|
||||
}
|
||||
|
||||
pub fn reset_dead_keys(&self) {
|
||||
// Not supported
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Inner {
|
||||
fn drop(&mut self) {
|
||||
if let Some(destroy_fn) = self.destroy_fn.take() {
|
||||
destroy_fn();
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct WindowId(pub(crate) u32);
|
||||
|
||||
impl WindowId {
|
||||
pub const fn dummy() -> Self {
|
||||
Self(0)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WindowId> for u64 {
|
||||
fn from(window_id: WindowId) -> Self {
|
||||
window_id.0 as u64
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u64> for WindowId {
|
||||
fn from(raw_id: u64) -> Self {
|
||||
Self(raw_id as u32)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PlatformSpecificWindowAttributes {
|
||||
pub(crate) canvas: Option<Arc<MainThreadSafe<backend::RawCanvasType>>>,
|
||||
pub(crate) prevent_default: bool,
|
||||
pub(crate) focusable: bool,
|
||||
pub(crate) append: bool,
|
||||
}
|
||||
|
||||
impl PlatformSpecificWindowAttributes {
|
||||
pub(crate) fn set_canvas(&mut self, canvas: Option<backend::RawCanvasType>) {
|
||||
let Some(canvas) = canvas else {
|
||||
self.canvas = None;
|
||||
return;
|
||||
};
|
||||
|
||||
let main_thread = MainThreadMarker::new()
|
||||
.expect("received a `HtmlCanvasElement` outside the window context");
|
||||
|
||||
self.canvas = Some(Arc::new(MainThreadSafe::new(main_thread, canvas)));
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PlatformSpecificWindowAttributes {
|
||||
fn default() -> Self {
|
||||
Self { canvas: None, prevent_default: true, focusable: true, append: false }
|
||||
}
|
||||
}
|
||||
@@ -1,196 +0,0 @@
|
||||
use smol_str::SmolStr;
|
||||
use windows_sys::Win32::Foundation::{HANDLE, HWND};
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{HMENU, WINDOW_LONG_PTR_INDEX};
|
||||
|
||||
pub(crate) use self::event_loop::{
|
||||
ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle,
|
||||
PlatformSpecificEventLoopAttributes,
|
||||
};
|
||||
pub(crate) use self::icon::{SelectedCursor, 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 self::icon::WinCursor as PlatformCustomCursor;
|
||||
pub use self::icon::WinIcon as PlatformIcon;
|
||||
pub(crate) use crate::cursor::OnlyCursorImageSource as PlatformCustomCursorSource;
|
||||
use crate::platform_impl::Fullscreen;
|
||||
|
||||
use crate::event::DeviceId as RootDeviceId;
|
||||
use crate::icon::Icon;
|
||||
use crate::keyboard::Key;
|
||||
use crate::platform::windows::{BackdropType, Color, CornerPreference};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
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 {}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct DeviceId(u32);
|
||||
|
||||
impl DeviceId {
|
||||
pub const fn dummy() -> Self {
|
||||
DeviceId(0)
|
||||
}
|
||||
}
|
||||
|
||||
impl DeviceId {
|
||||
pub fn persistent_identifier(&self) -> Option<String> {
|
||||
if self.0 != 0 {
|
||||
raw_input::get_raw_input_device_name(self.0 as HANDLE)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Constant device ID, to be removed when this backend is updated to report real device IDs.
|
||||
const DEVICE_ID: RootDeviceId = RootDeviceId(DeviceId(0));
|
||||
|
||||
fn wrap_device_id(id: u32) -> RootDeviceId {
|
||||
RootDeviceId(DeviceId(id))
|
||||
}
|
||||
|
||||
pub type OsError = std::io::Error;
|
||||
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
|
||||
pub struct KeyEventExtra {
|
||||
pub text_with_all_modifiers: Option<SmolStr>,
|
||||
pub key_without_modifiers: Key,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct WindowId(HWND);
|
||||
unsafe impl Send for WindowId {}
|
||||
unsafe impl Sync for WindowId {}
|
||||
|
||||
impl WindowId {
|
||||
pub const fn dummy() -> Self {
|
||||
WindowId(0)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WindowId> for u64 {
|
||||
fn from(window_id: WindowId) -> Self {
|
||||
window_id.0 as u64
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WindowId> for HWND {
|
||||
fn from(window_id: WindowId) -> Self {
|
||||
window_id.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u64> for WindowId {
|
||||
fn from(raw_id: u64) -> Self {
|
||||
Self(raw_id as HWND)
|
||||
}
|
||||
}
|
||||
|
||||
#[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;
|
||||
mod raw_input;
|
||||
mod window;
|
||||
mod window_state;
|
||||
28
src/utils.rs
28
src/utils.rs
@@ -1,28 +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::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)
|
||||
}
|
||||
}
|
||||
5
taplo.toml
Normal file
5
taplo.toml
Normal file
@@ -0,0 +1,5 @@
|
||||
[formatting]
|
||||
allowed_blank_lines = 1
|
||||
column_width = 100
|
||||
indent_string = ' '
|
||||
reorder_keys = true
|
||||
@@ -1,36 +0,0 @@
|
||||
#[allow(dead_code)]
|
||||
fn needs_send<T: Send>() {}
|
||||
|
||||
#[test]
|
||||
fn event_loop_proxy_send() {
|
||||
#[allow(dead_code)]
|
||||
fn is_send<T: 'static + Send>() {
|
||||
// ensures that `winit::EventLoopProxy<T: Send>` implements `Send`
|
||||
needs_send::<winit::event_loop::EventLoopProxy<T>>();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_send() {
|
||||
// ensures that `winit::Window` implements `Send`
|
||||
needs_send::<winit::window::Window>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_builder_send() {
|
||||
needs_send::<winit::window::WindowAttributes>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_send() {
|
||||
// ensures that the various `..Id` types implement `Send`
|
||||
needs_send::<winit::window::WindowId>();
|
||||
needs_send::<winit::event::DeviceId>();
|
||||
needs_send::<winit::monitor::MonitorHandle>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_cursor_send() {
|
||||
needs_send::<winit::window::CustomCursorSource>();
|
||||
needs_send::<winit::window::CustomCursor>();
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
#[allow(dead_code)]
|
||||
fn needs_sync<T: Sync>() {}
|
||||
|
||||
#[test]
|
||||
fn event_loop_proxy_send() {
|
||||
#[allow(dead_code)]
|
||||
fn is_send<T: 'static + Send>() {
|
||||
// ensures that `winit::EventLoopProxy<T: Send>` implements `Sync`
|
||||
needs_sync::<winit::event_loop::EventLoopProxy<T>>();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_sync() {
|
||||
// ensures that `winit::Window` implements `Sync`
|
||||
needs_sync::<winit::window::Window>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_builder_sync() {
|
||||
needs_sync::<winit::window::WindowAttributes>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_cursor_sync() {
|
||||
needs_sync::<winit::window::CustomCursorSource>();
|
||||
needs_sync::<winit::window::CustomCursor>();
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
# documentation: https://github.com/crate-ci/typos/blob/master/docs/reference.md
|
||||
|
||||
[default.extend-identifiers]
|
||||
ptd = "ptd" # From windows_sys::Win32::System::Com::FORMATETC { ptd, ..}
|
||||
TME_LEAVE = "TME_LEAVE" # From windows_sys::Win32::UI::Input::KeyboardAndMouse::TME_LEAVE
|
||||
requestor = "requestor" # From x11_dl::xlib::XSelectionEvent { requestor ..}
|
||||
XF86_Calculater = "XF86_Calculater" # From xkbcommon_dl::keysyms::XF86_Calculater
|
||||
ptd = "ptd" # From windows_sys::Win32::System::Com::FORMATETC { ptd, ..}
|
||||
requestor = "requestor" # From x11_dl::xlib::XSelectionEvent { requestor ..}
|
||||
|
||||
[files]
|
||||
extend-exclude = ["*.drawio"]
|
||||
|
||||
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
|
||||
1040
winit-android/src/event_loop.rs
Normal file
1040
winit-android/src/event_loop.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,8 @@
|
||||
use android_activity::input::{KeyAction, KeyEvent, KeyMapChar, Keycode};
|
||||
use android_activity::AndroidApp;
|
||||
|
||||
use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey};
|
||||
use android_activity::input::{KeyAction, KeyEvent, KeyMapChar, Keycode};
|
||||
use winit_core::keyboard::{
|
||||
Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey,
|
||||
};
|
||||
|
||||
pub fn to_physical_key(keycode: Keycode) -> PhysicalKey {
|
||||
PhysicalKey::Code(match keycode {
|
||||
@@ -143,8 +144,8 @@ pub fn to_physical_key(keycode: Keycode) -> PhysicalKey {
|
||||
Keycode::AltLeft => KeyCode::AltLeft,
|
||||
Keycode::AltRight => KeyCode::AltRight,
|
||||
|
||||
Keycode::MetaLeft => KeyCode::SuperLeft,
|
||||
Keycode::MetaRight => KeyCode::SuperRight,
|
||||
Keycode::MetaLeft => KeyCode::MetaLeft,
|
||||
Keycode::MetaRight => KeyCode::MetaRight,
|
||||
|
||||
Keycode::LeftBracket => KeyCode::BracketLeft,
|
||||
Keycode::RightBracket => KeyCode::BracketRight,
|
||||
@@ -309,7 +310,7 @@ pub fn to_logical(key_char: Option<KeyMapChar>, keycode: Keycode) -> Key {
|
||||
ShiftLeft => Key::Named(NamedKey::Shift),
|
||||
ShiftRight => Key::Named(NamedKey::Shift),
|
||||
Tab => Key::Named(NamedKey::Tab),
|
||||
Space => Key::Named(NamedKey::Space),
|
||||
Space => Key::Character(" ".into()),
|
||||
Sym => Key::Named(NamedKey::Symbol),
|
||||
Explorer => Key::Named(NamedKey::LaunchWebBrowser),
|
||||
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),
|
||||
CapsLock => Key::Named(NamedKey::CapsLock),
|
||||
ScrollLock => Key::Named(NamedKey::ScrollLock),
|
||||
MetaLeft => Key::Named(NamedKey::Super),
|
||||
MetaRight => Key::Named(NamedKey::Super),
|
||||
MetaLeft => Key::Named(NamedKey::Meta),
|
||||
MetaRight => Key::Named(NamedKey::Meta),
|
||||
Function => Key::Named(NamedKey::Fn),
|
||||
Sysrq => Key::Named(NamedKey::PrintScreen),
|
||||
Break => Key::Named(NamedKey::Pause),
|
||||
@@ -62,18 +62,26 @@
|
||||
//! If your application is currently based on `NativeActivity` via the `ndk-glue` crate and building
|
||||
//! with `cargo apk`, then the minimal changes would be:
|
||||
//! 1. Remove `ndk-glue` from your `Cargo.toml`
|
||||
//! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.30.8",
|
||||
//! features = [ "android-native-activity" ] }`
|
||||
//! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version =
|
||||
//! "0.31.0-beta.2", features = [ "android-native-activity" ] }`
|
||||
//! 3. Add an `android_main` entrypoint (as above), instead of using the '`[ndk_glue::main]` proc
|
||||
//! macro from `ndk-macros` (optionally add a dependency on `android_logger` and initialize
|
||||
//! logging as above).
|
||||
//! 4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your
|
||||
//! event loop (as shown above).
|
||||
#![cfg(target_os = "android")]
|
||||
|
||||
use crate::event_loop::{ActiveEventLoop, EventLoop, EventLoopBuilder};
|
||||
use crate::window::{Window, WindowAttributes};
|
||||
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};
|
||||
pub use crate::event_loop::{
|
||||
ActiveEventLoop, EventLoop, EventLoopProxy, PlatformSpecificEventLoopAttributes,
|
||||
PlatformSpecificWindowAttributes, Window,
|
||||
};
|
||||
|
||||
/// Additional methods on [`EventLoop`] that are specific to Android.
|
||||
pub trait EventLoopExtAndroid {
|
||||
@@ -81,12 +89,6 @@ pub trait EventLoopExtAndroid {
|
||||
fn android_app(&self) -> &AndroidApp;
|
||||
}
|
||||
|
||||
impl<T> EventLoopExtAndroid for EventLoop<T> {
|
||||
fn android_app(&self) -> &AndroidApp {
|
||||
&self.event_loop.android_app
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional methods on [`ActiveEventLoop`] that are specific to Android.
|
||||
pub trait ActiveEventLoopExtAndroid {
|
||||
/// Get the [`AndroidApp`] which was used to create this event loop.
|
||||
@@ -100,27 +102,25 @@ pub trait WindowExtAndroid {
|
||||
fn config(&self) -> ConfigurationRef;
|
||||
}
|
||||
|
||||
impl WindowExtAndroid for Window {
|
||||
impl WindowExtAndroid for dyn CoreWindow + '_ {
|
||||
fn content_rect(&self) -> Rect {
|
||||
self.window.content_rect()
|
||||
let window = self.cast_ref::<Window>().unwrap();
|
||||
window.content_rect()
|
||||
}
|
||||
|
||||
fn config(&self) -> ConfigurationRef {
|
||||
self.window.config()
|
||||
let window = self.cast_ref::<Window>().unwrap();
|
||||
window.config()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveEventLoopExtAndroid for ActiveEventLoop {
|
||||
impl ActiveEventLoopExtAndroid for dyn CoreActiveEventLoop + '_ {
|
||||
fn android_app(&self) -> &AndroidApp {
|
||||
&self.p.app
|
||||
let event_loop = self.cast_ref::<ActiveEventLoop>().unwrap();
|
||||
&event_loop.app
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional methods on [`WindowAttributes`] that are specific to Android.
|
||||
pub trait WindowAttributesExtAndroid {}
|
||||
|
||||
impl WindowAttributesExtAndroid for WindowAttributes {}
|
||||
|
||||
pub trait EventLoopBuilderExtAndroid {
|
||||
/// Associates the [`AndroidApp`] that was passed to `android_main()` with the event loop
|
||||
///
|
||||
@@ -133,18 +133,6 @@ pub trait EventLoopBuilderExtAndroid {
|
||||
fn handle_volume_keys(&mut self) -> &mut Self;
|
||||
}
|
||||
|
||||
impl<T> EventLoopBuilderExtAndroid for EventLoopBuilder<T> {
|
||||
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
|
||||
///
|
||||
/// Winit re-exports the `android_activity` API for convenience so that most
|
||||
@@ -173,16 +161,5 @@ pub mod activity {
|
||||
// feature enabled, so we avoid inlining it so that they're forced to view
|
||||
// it on the crate's own docs.rs page.
|
||||
#[doc(no_inline)]
|
||||
#[cfg(android_platform)]
|
||||
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-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",
|
||||
] }
|
||||
winit-common = { workspace = true, features = ["core-foundation", "event-handler"] }
|
||||
|
||||
[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
|
||||
186
winit-appkit/src/app.rs
Normal file
186
winit-appkit/src/app.rs
Normal file
@@ -0,0 +1,186 @@
|
||||
#![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 = event.r#type();
|
||||
let modifier_flags = event.modifierFlags();
|
||||
if event_type == NSEventType::KeyUp && modifier_flags.contains(NSEventModifierFlags::Command) {
|
||||
if let Some(key_window) = app.keyWindow() {
|
||||
key_window.sendEvent(event);
|
||||
}
|
||||
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 = event.r#type();
|
||||
#[allow(non_upper_case_globals)]
|
||||
match event_type {
|
||||
NSEventType::MouseMoved
|
||||
| NSEventType::LeftMouseDragged
|
||||
| NSEventType::OtherMouseDragged
|
||||
| NSEventType::RightMouseDragged => {
|
||||
let delta_x = event.deltaX() as f64;
|
||||
let delta_y = event.deltaY() as f64;
|
||||
|
||||
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 = 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 = 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::{ClassType, define_class, msg_send};
|
||||
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 = NSApplication::new(mtm);
|
||||
override_send_event(&app);
|
||||
// Test calling twice works.
|
||||
override_send_event(&app);
|
||||
|
||||
// FIXME(madsmtm): Can't test this yet, need some way to mock AppState.
|
||||
// let event = super::super::event::dummy_event().unwrap();
|
||||
// app.sendEvent(&event)
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
383
winit-appkit/src/app_state.rs
Normal file
383
winit-appkit/src/app_state.rs
Normal file
@@ -0,0 +1,383 @@
|
||||
use std::cell::{Cell, OnceCell, RefCell};
|
||||
use std::mem;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use dispatch2::MainThreadBound;
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy, NSRunningApplication};
|
||||
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::event_loop::{ActiveEventLoop, notify_windows_of_exit, stop_app_immediately};
|
||||
use super::menu;
|
||||
use super::observer::{EventLoopWaker, RunLoop};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct AppState {
|
||||
mtm: MainThreadMarker,
|
||||
activation_policy: Option<NSApplicationActivationPolicy>,
|
||||
default_menu: bool,
|
||||
activate_ignoring_other_apps: bool,
|
||||
run_loop: RunLoop,
|
||||
event_loop_proxy: Arc<EventLoopProxy>,
|
||||
event_handler: EventHandler,
|
||||
stop_on_launch: Cell<bool>,
|
||||
stop_before_wait: Cell<bool>,
|
||||
stop_after_wait: Cell<bool>,
|
||||
stop_on_redraw: Cell<bool>,
|
||||
/// Whether `applicationDidFinishLaunching:` has been run or not.
|
||||
is_launched: Cell<bool>,
|
||||
/// Whether an `EventLoop` is currently running.
|
||||
is_running: Cell<bool>,
|
||||
/// Whether the user has requested the event loop to exit.
|
||||
exit: Cell<bool>,
|
||||
control_flow: Cell<ControlFlow>,
|
||||
waker: RefCell<EventLoopWaker>,
|
||||
start_time: Cell<Option<Instant>>,
|
||||
wait_timeout: Cell<Option<Instant>>,
|
||||
pending_redraw: RefCell<Vec<WindowId>>,
|
||||
// NOTE: This is strongly referenced by our `NSWindowDelegate` and our `NSView` subclass, and
|
||||
// as such should be careful to not add fields that, in turn, strongly reference those.
|
||||
}
|
||||
|
||||
// SAFETY: Creating `MainThreadBound` in a `const` context, where there is no concept of the
|
||||
// main thread.
|
||||
static GLOBAL: MainThreadBound<OnceCell<Rc<AppState>>> =
|
||||
MainThreadBound::new(OnceCell::new(), unsafe { MainThreadMarker::new_unchecked() });
|
||||
|
||||
impl AppState {
|
||||
pub(super) fn setup_global(
|
||||
mtm: MainThreadMarker,
|
||||
activation_policy: Option<NSApplicationActivationPolicy>,
|
||||
default_menu: bool,
|
||||
activate_ignoring_other_apps: bool,
|
||||
) -> Option<Rc<Self>> {
|
||||
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,
|
||||
activation_policy,
|
||||
default_menu,
|
||||
activate_ignoring_other_apps,
|
||||
run_loop: RunLoop::main(mtm),
|
||||
event_loop_proxy,
|
||||
event_handler: EventHandler::new(),
|
||||
stop_on_launch: Cell::new(false),
|
||||
stop_before_wait: Cell::new(false),
|
||||
stop_after_wait: Cell::new(false),
|
||||
stop_on_redraw: Cell::new(false),
|
||||
is_launched: Cell::new(false),
|
||||
is_running: Cell::new(false),
|
||||
exit: Cell::new(false),
|
||||
control_flow: Cell::new(ControlFlow::default()),
|
||||
waker: RefCell::new(EventLoopWaker::new()),
|
||||
start_time: Cell::new(None),
|
||||
wait_timeout: Cell::new(None),
|
||||
pending_redraw: RefCell::new(vec![]),
|
||||
});
|
||||
|
||||
GLOBAL.get(mtm).set(this.clone()).ok().and(Some(this))
|
||||
}
|
||||
|
||||
pub fn get(mtm: MainThreadMarker) -> Rc<Self> {
|
||||
GLOBAL
|
||||
.get(mtm)
|
||||
.get()
|
||||
.expect("tried to get application state before it was registered")
|
||||
.clone()
|
||||
}
|
||||
|
||||
// NOTE: This notification will, globally, only be emitted once,
|
||||
// no matter how many `EventLoop`s the user creates.
|
||||
pub fn did_finish_launching(self: &Rc<Self>, _notification: &NSNotification) {
|
||||
trace_scope!("NSApplicationDidFinishLaunchingNotification");
|
||||
self.is_launched.set(true);
|
||||
|
||||
let app = NSApplication::sharedApplication(self.mtm);
|
||||
// We need to delay setting the activation policy and activating the app
|
||||
// until `applicationDidFinishLaunching` has been called. Otherwise the
|
||||
// menu bar is initially unresponsive on macOS 10.15.
|
||||
if let Some(activation_policy) = self.activation_policy {
|
||||
app.setActivationPolicy(activation_policy);
|
||||
} else {
|
||||
// If no activation policy is explicitly provided, and the application
|
||||
// is bundled, do not set the activation policy at all, to allow the
|
||||
// package manifest to define the behavior via LSUIElement.
|
||||
//
|
||||
// See:
|
||||
// - https://github.com/rust-windowing/winit/issues/261
|
||||
// - https://github.com/rust-windowing/winit/issues/3958
|
||||
let is_bundled =
|
||||
NSRunningApplication::currentApplication().bundleIdentifier().is_some();
|
||||
if !is_bundled {
|
||||
app.setActivationPolicy(NSApplicationActivationPolicy::Regular);
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(deprecated)]
|
||||
app.activateIgnoringOtherApps(self.activate_ignoring_other_apps);
|
||||
|
||||
if self.default_menu {
|
||||
// The menubar initialization should be before the `NewEvents` event, to allow
|
||||
// overriding of the default menu even if it's created
|
||||
menu::initialize(&app);
|
||||
}
|
||||
|
||||
self.waker.borrow_mut().start();
|
||||
|
||||
self.set_is_running(true);
|
||||
self.dispatch_init_events();
|
||||
|
||||
// If the application is being launched via `EventLoop::pump_app_events()` then we'll
|
||||
// want to stop the app once it is launched (and return to the external loop)
|
||||
//
|
||||
// In this case we still want to consider Winit's `EventLoop` to be "running",
|
||||
// so we call `start_running()` above.
|
||||
if self.stop_on_launch.get() {
|
||||
// NOTE: the original idea had been to only stop the underlying `RunLoop`
|
||||
// for the app but that didn't work as expected (`-[NSApplication run]`
|
||||
// effectively ignored the attempt to stop the RunLoop and re-started it).
|
||||
//
|
||||
// So we return from `pump_events` by stopping the application.
|
||||
let app = NSApplication::sharedApplication(self.mtm);
|
||||
stop_app_immediately(&app);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn will_terminate(self: &Rc<Self>, _notification: &NSNotification) {
|
||||
trace_scope!("NSApplicationWillTerminateNotification");
|
||||
let app = NSApplication::sharedApplication(self.mtm);
|
||||
notify_windows_of_exit(&app);
|
||||
self.event_handler.terminate();
|
||||
self.internal_exit();
|
||||
}
|
||||
|
||||
/// Place the event handler in the application state for the duration
|
||||
/// of the given closure.
|
||||
pub fn set_event_handler<R>(
|
||||
&self,
|
||||
handler: impl ApplicationHandler,
|
||||
closure: impl FnOnce() -> R,
|
||||
) -> R {
|
||||
self.event_handler.set(Box::new(handler), closure)
|
||||
}
|
||||
|
||||
pub fn event_loop_proxy(&self) -> &Arc<EventLoopProxy> {
|
||||
&self.event_loop_proxy
|
||||
}
|
||||
|
||||
/// If `pump_events` is called to progress the event loop then we
|
||||
/// bootstrap the event loop via `-[NSApplication run]` but will use
|
||||
/// `CFRunLoopRunInMode` for subsequent calls to `pump_events`.
|
||||
pub fn set_stop_on_launch(&self) {
|
||||
self.stop_on_launch.set(true);
|
||||
}
|
||||
|
||||
pub fn set_stop_before_wait(&self, value: bool) {
|
||||
self.stop_before_wait.set(value)
|
||||
}
|
||||
|
||||
pub fn set_stop_after_wait(&self, value: bool) {
|
||||
self.stop_after_wait.set(value)
|
||||
}
|
||||
|
||||
pub fn set_stop_on_redraw(&self, value: bool) {
|
||||
self.stop_on_redraw.set(value)
|
||||
}
|
||||
|
||||
pub fn set_wait_timeout(&self, value: Option<Instant>) {
|
||||
self.wait_timeout.set(value)
|
||||
}
|
||||
|
||||
/// Clears the `running` state and resets the `control_flow` state when an `EventLoop` exits.
|
||||
///
|
||||
/// 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.
|
||||
pub fn internal_exit(self: &Rc<Self>) {
|
||||
self.set_is_running(false);
|
||||
self.set_stop_on_redraw(false);
|
||||
self.set_stop_before_wait(false);
|
||||
self.set_stop_after_wait(false);
|
||||
self.set_wait_timeout(None);
|
||||
}
|
||||
|
||||
pub fn is_launched(&self) -> bool {
|
||||
self.is_launched.get()
|
||||
}
|
||||
|
||||
pub fn set_is_running(&self, value: bool) {
|
||||
self.is_running.set(value)
|
||||
}
|
||||
|
||||
pub fn is_running(&self) -> bool {
|
||||
self.is_running.get()
|
||||
}
|
||||
|
||||
pub fn exit(&self) {
|
||||
self.exit.set(true)
|
||||
}
|
||||
|
||||
pub fn clear_exit(&self) {
|
||||
self.exit.set(false)
|
||||
}
|
||||
|
||||
pub fn exiting(&self) -> bool {
|
||||
self.exit.get()
|
||||
}
|
||||
|
||||
pub fn set_control_flow(&self, value: ControlFlow) {
|
||||
self.control_flow.set(value)
|
||||
}
|
||||
|
||||
pub fn control_flow(&self) -> ControlFlow {
|
||||
self.control_flow.get()
|
||||
}
|
||||
|
||||
pub fn handle_redraw(self: &Rc<Self>, window_id: WindowId) {
|
||||
// Redraw request might come out of order from the OS.
|
||||
// -> Don't go back into the event handler when our callstack originates from there
|
||||
if !self.event_handler.in_use() {
|
||||
self.with_handler(|app, event_loop| {
|
||||
app.window_event(event_loop, window_id, WindowEvent::RedrawRequested);
|
||||
});
|
||||
|
||||
// `pump_events` will request to stop immediately _after_ dispatching RedrawRequested
|
||||
// events as a way to ensure that `pump_events` can't block an external loop
|
||||
// indefinitely
|
||||
if self.stop_on_redraw.get() {
|
||||
let app = NSApplication::sharedApplication(self.mtm);
|
||||
stop_app_immediately(&app);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn queue_redraw(&self, window_id: WindowId) {
|
||||
let mut pending_redraw = self.pending_redraw.borrow_mut();
|
||||
if !pending_redraw.contains(&window_id) {
|
||||
pending_redraw.push(window_id);
|
||||
}
|
||||
self.run_loop.wakeup();
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
pub fn maybe_queue_with_handler(
|
||||
self: &Rc<Self>,
|
||||
callback: impl FnOnce(&mut dyn ApplicationHandler, &ActiveEventLoop) + 'static,
|
||||
) {
|
||||
// Most programmer actions in AppKit (e.g. change window fullscreen, set focused, etc.)
|
||||
// result in an event being queued, and applied at a later point.
|
||||
//
|
||||
// However, it is not documented which actions do this, and which ones are done immediately,
|
||||
// so to make sure that we don't encounter re-entrancy issues, we first check if we're
|
||||
// currently handling another event, and if we are, we queue the event instead.
|
||||
if !self.event_handler.in_use() {
|
||||
self.with_handler(callback);
|
||||
} else {
|
||||
tracing::debug!("had to queue event since another is currently being handled");
|
||||
let this = Rc::clone(self);
|
||||
self.run_loop.queue_closure(move || {
|
||||
this.with_handler(callback);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn with_handler(
|
||||
self: &Rc<Self>,
|
||||
callback: impl FnOnce(&mut dyn ApplicationHandler, &ActiveEventLoop),
|
||||
) {
|
||||
let event_loop = ActiveEventLoop { app_state: Rc::clone(self), mtm: self.mtm };
|
||||
self.event_handler.handle(|app| callback(app, &event_loop));
|
||||
}
|
||||
|
||||
/// dispatch `NewEvents(Init)` + `Resumed`
|
||||
pub fn dispatch_init_events(self: &Rc<Self>) {
|
||||
self.with_handler(|app, event_loop| app.new_events(event_loop, StartCause::Init));
|
||||
// NB: For consistency all platforms must call `can_create_surfaces` even though macOS
|
||||
// applications don't themselves have a formal surface destroy/create lifecycle.
|
||||
self.with_handler(|app, event_loop| app.can_create_surfaces(event_loop));
|
||||
}
|
||||
|
||||
// Called by RunLoopObserver after finishing waiting for new events
|
||||
pub fn wakeup(self: &Rc<Self>) {
|
||||
// Return when in event handler due to https://github.com/rust-windowing/winit/issues/1779
|
||||
if !self.event_handler.ready() || !self.is_running() {
|
||||
return;
|
||||
}
|
||||
|
||||
if self.stop_after_wait.get() {
|
||||
let app = NSApplication::sharedApplication(self.mtm);
|
||||
stop_app_immediately(&app);
|
||||
}
|
||||
|
||||
let start = self.start_time.get().unwrap();
|
||||
let cause = match self.control_flow() {
|
||||
ControlFlow::Poll => StartCause::Poll,
|
||||
ControlFlow::Wait => StartCause::WaitCancelled { start, requested_resume: None },
|
||||
ControlFlow::WaitUntil(requested_resume) => {
|
||||
if Instant::now() >= requested_resume {
|
||||
StartCause::ResumeTimeReached { start, requested_resume }
|
||||
} else {
|
||||
StartCause::WaitCancelled { start, requested_resume: Some(requested_resume) }
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
self.with_handler(|app, event_loop| app.new_events(event_loop, cause));
|
||||
}
|
||||
|
||||
// Called by RunLoopObserver before waiting for new events
|
||||
pub fn cleared(self: &Rc<Self>) {
|
||||
// Return when in event handler due to https://github.com/rust-windowing/winit/issues/1779
|
||||
// XXX: how does it make sense that `event_handler.ready()` can ever return `false` here if
|
||||
// we're about to return to the `CFRunLoop` to poll for new events?
|
||||
if !self.event_handler.ready() || !self.is_running() {
|
||||
return;
|
||||
}
|
||||
|
||||
let redraw = mem::take(&mut *self.pending_redraw.borrow_mut());
|
||||
for window_id in redraw {
|
||||
self.with_handler(|app, event_loop| {
|
||||
app.window_event(event_loop, window_id, WindowEvent::RedrawRequested);
|
||||
});
|
||||
}
|
||||
self.with_handler(|app, event_loop| {
|
||||
app.about_to_wait(event_loop);
|
||||
});
|
||||
|
||||
if self.exiting() {
|
||||
let app = NSApplication::sharedApplication(self.mtm);
|
||||
stop_app_immediately(&app);
|
||||
notify_windows_of_exit(&app);
|
||||
}
|
||||
|
||||
if self.stop_before_wait.get() {
|
||||
let app = NSApplication::sharedApplication(self.mtm);
|
||||
stop_app_immediately(&app);
|
||||
}
|
||||
self.start_time.set(Some(Instant::now()));
|
||||
let wait_timeout = self.wait_timeout.get(); // configured by pump_events
|
||||
let app_timeout = match self.control_flow() {
|
||||
ControlFlow::Wait => None,
|
||||
ControlFlow::Poll => Some(Instant::now()),
|
||||
ControlFlow::WaitUntil(instant) => Some(instant),
|
||||
};
|
||||
self.waker.borrow_mut().start_at(min_timeout(wait_timeout, app_timeout));
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the minimum `Option<Instant>`, 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<Instant>, b: Option<Instant>) -> Option<Instant> {
|
||||
a.map_or(b, |a_timeout| b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout))))
|
||||
}
|
||||
@@ -4,33 +4,44 @@ use std::sync::OnceLock;
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::Sel;
|
||||
use objc2::{msg_send, msg_send_id, sel, ClassType};
|
||||
use objc2::{AllocAnyThread, ClassType, available, msg_send, sel};
|
||||
use objc2_app_kit::{NSBitmapImageRep, NSCursor, NSDeviceRGBColorSpace, NSImage};
|
||||
use objc2_foundation::{
|
||||
ns_string, NSData, NSDictionary, NSNumber, NSObject, NSObjectProtocol, NSPoint, NSSize,
|
||||
NSString,
|
||||
NSData, NSDictionary, NSNumber, NSObject, NSPoint, NSSize, NSString, ns_string,
|
||||
};
|
||||
|
||||
use crate::cursor::{CursorImage, OnlyCursorImageSource};
|
||||
use crate::window::CursorIcon;
|
||||
use winit_core::cursor::{CursorIcon, CursorImage, CustomCursorProvider, CustomCursorSource};
|
||||
use winit_core::error::{NotSupportedError, RequestError};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct CustomCursor(pub(crate) Retained<NSCursor>);
|
||||
|
||||
impl CustomCursorProvider for CustomCursor {
|
||||
fn is_animated(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: NSCursor is immutable and thread-safe
|
||||
// TODO(madsmtm): Put this logic in objc2-app-kit itself
|
||||
unsafe impl Send for CustomCursor {}
|
||||
unsafe impl Sync for CustomCursor {}
|
||||
|
||||
impl CustomCursor {
|
||||
pub(crate) fn new(cursor: OnlyCursorImageSource) -> CustomCursor {
|
||||
Self(cursor_from_image(&cursor.0))
|
||||
pub(crate) fn new(cursor: CustomCursorSource) -> Result<CustomCursor, RequestError> {
|
||||
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) -> Retained<NSCursor> {
|
||||
let width = cursor.width;
|
||||
let height = cursor.height;
|
||||
pub(crate) fn cursor_from_image(cursor: &CursorImage) -> Result<Retained<NSCursor>, RequestError> {
|
||||
let width = cursor.width();
|
||||
let height = cursor.height();
|
||||
|
||||
let bitmap = unsafe {
|
||||
NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
|
||||
@@ -45,19 +56,18 @@ pub(crate) fn cursor_from_image(cursor: &CursorImage) -> Retained<NSCursor> {
|
||||
NSDeviceRGBColorSpace,
|
||||
width as isize * 4,
|
||||
32,
|
||||
).unwrap()
|
||||
};
|
||||
let bitmap_data = unsafe { slice::from_raw_parts_mut(bitmap.bitmapData(), cursor.rgba.len()) };
|
||||
bitmap_data.copy_from_slice(&cursor.rgba);
|
||||
)
|
||||
}.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.buffer().len()) };
|
||||
bitmap_data.copy_from_slice(cursor.buffer());
|
||||
|
||||
let image = unsafe {
|
||||
NSImage::initWithSize(NSImage::alloc(), NSSize::new(width.into(), height.into()))
|
||||
};
|
||||
unsafe { image.addRepresentation(&bitmap) };
|
||||
let image = NSImage::initWithSize(NSImage::alloc(), NSSize::new(width.into(), height.into()));
|
||||
image.addRepresentation(&bitmap);
|
||||
|
||||
let hotspot = NSPoint::new(cursor.hotspot_x as f64, cursor.hotspot_y as f64);
|
||||
let hotspot = NSPoint::new(cursor.hotspot_x() as f64, cursor.hotspot_y() as f64);
|
||||
|
||||
NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot)
|
||||
Ok(NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot))
|
||||
}
|
||||
|
||||
pub(crate) fn default_cursor() -> Retained<NSCursor> {
|
||||
@@ -66,8 +76,8 @@ pub(crate) fn default_cursor() -> Retained<NSCursor> {
|
||||
|
||||
unsafe fn try_cursor_from_selector(sel: Sel) -> Option<Retained<NSCursor>> {
|
||||
let cls = NSCursor::class();
|
||||
if msg_send![cls, respondsToSelector: sel] {
|
||||
let cursor: Retained<NSCursor> = unsafe { msg_send_id![cls, performSelector: sel] };
|
||||
if unsafe { msg_send![cls, respondsToSelector: sel] } {
|
||||
let cursor: Retained<NSCursor> = unsafe { msg_send![cls, performSelector: sel] };
|
||||
Some(cursor)
|
||||
} else {
|
||||
tracing::warn!("cursor `{sel}` appears to be invalid");
|
||||
@@ -128,26 +138,19 @@ unsafe fn load_webkit_cursor(name: &NSString) -> Retained<NSCursor> {
|
||||
|
||||
// TODO: Handle PLists better
|
||||
let info_path = cursor_path.stringByAppendingPathComponent(ns_string!("info.plist"));
|
||||
let info: Retained<NSDictionary<NSObject, NSObject>> = unsafe {
|
||||
msg_send_id![
|
||||
<NSDictionary<NSObject, NSObject>>::class(),
|
||||
dictionaryWithContentsOfFile: &*info_path,
|
||||
]
|
||||
};
|
||||
#[allow(deprecated)]
|
||||
let info: Retained<NSDictionary<NSObject, NSObject>> =
|
||||
unsafe { NSDictionary::dictionaryWithContentsOfFile(&info_path) }.unwrap();
|
||||
let mut x = 0.0;
|
||||
if let Some(n) = info.get(&*ns_string!("hotx")) {
|
||||
if n.is_kind_of::<NSNumber>() {
|
||||
let ptr: *const NSObject = n;
|
||||
let ptr: *const NSNumber = ptr.cast();
|
||||
x = unsafe { &*ptr }.as_cgfloat()
|
||||
if let Some(n) = info.objectForKey(ns_string!("hotx")) {
|
||||
if let Ok(n) = n.downcast::<NSNumber>() {
|
||||
x = n.as_cgfloat();
|
||||
}
|
||||
}
|
||||
let mut y = 0.0;
|
||||
if let Some(n) = info.get(&*ns_string!("hotx")) {
|
||||
if n.is_kind_of::<NSNumber>() {
|
||||
let ptr: *const NSObject = n;
|
||||
let ptr: *const NSNumber = ptr.cast();
|
||||
y = unsafe { &*ptr }.as_cgfloat()
|
||||
if let Some(n) = info.objectForKey(ns_string!("hoty")) {
|
||||
if let Ok(n) = n.downcast::<NSNumber>() {
|
||||
y = n.as_cgfloat();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,6 +190,7 @@ pub(crate) fn invisible_cursor() -> Retained<NSCursor> {
|
||||
CURSOR.get_or_init(|| CustomCursor(new_invisible())).0.clone()
|
||||
}
|
||||
|
||||
#[allow(deprecated)]
|
||||
pub(crate) fn cursor_from_icon(icon: CursorIcon) -> Retained<NSCursor> {
|
||||
match icon {
|
||||
CursorIcon::Default => default_cursor(),
|
||||
@@ -207,7 +211,9 @@ pub(crate) fn cursor_from_icon(icon: CursorIcon) -> Retained<NSCursor> {
|
||||
CursorIcon::EwResize | CursorIcon::ColResize => NSCursor::resizeLeftRightCursor(),
|
||||
CursorIcon::NsResize | CursorIcon::RowResize => NSCursor::resizeUpDownCursor(),
|
||||
CursorIcon::Help => _helpCursor(),
|
||||
CursorIcon::ZoomIn if available!(macos = 15.0) => NSCursor::zoomInCursor(),
|
||||
CursorIcon::ZoomIn => _zoomInCursor(),
|
||||
CursorIcon::ZoomOut if available!(macos = 15.0) => NSCursor::zoomOutCursor(),
|
||||
CursorIcon::ZoomOut => _zoomOutCursor(),
|
||||
CursorIcon::NeResize => _windowResizeNorthEastCursor(),
|
||||
CursorIcon::NwResize => _windowResizeNorthWestCursor(),
|
||||
@@ -1,50 +1,42 @@
|
||||
use std::ffi::c_void;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use core_foundation::base::CFRelease;
|
||||
use core_foundation::data::{CFDataGetBytePtr, CFDataRef};
|
||||
use dispatch2::run_on_main;
|
||||
use objc2::rc::Retained;
|
||||
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 crate::event::{ElementState, KeyEvent, Modifiers};
|
||||
use crate::keyboard::{
|
||||
use winit_core::event::{ElementState, KeyEvent, Modifiers};
|
||||
use winit_core::keyboard::{
|
||||
Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey, NativeKeyCode,
|
||||
PhysicalKey,
|
||||
};
|
||||
use crate::platform_impl::platform::ffi;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct KeyEventExtra {
|
||||
pub text_with_all_modifiers: Option<SmolStr>,
|
||||
pub key_without_modifiers: Key,
|
||||
}
|
||||
use super::ffi;
|
||||
|
||||
/// Ignores ALL modifiers.
|
||||
pub fn get_modifierless_char(scancode: u16) -> Key {
|
||||
let mut string = [0; 16];
|
||||
let input_source;
|
||||
let layout;
|
||||
unsafe {
|
||||
input_source = ffi::TISCopyCurrentKeyboardLayoutInputSource();
|
||||
if input_source.is_null() {
|
||||
tracing::error!("`TISCopyCurrentKeyboardLayoutInputSource` returned null ptr");
|
||||
return Key::Unidentified(NativeKey::MacOS(scancode));
|
||||
}
|
||||
let layout_data =
|
||||
ffi::TISGetInputSourceProperty(input_source, ffi::kTISPropertyUnicodeKeyLayoutData);
|
||||
if layout_data.is_null() {
|
||||
CFRelease(input_source as *mut c_void);
|
||||
tracing::error!("`TISGetInputSourceProperty` returned null ptr");
|
||||
return Key::Unidentified(NativeKey::MacOS(scancode));
|
||||
}
|
||||
layout = CFDataGetBytePtr(layout_data as CFDataRef) as *const ffi::UCKeyboardLayout;
|
||||
}
|
||||
let Some(ptr) = NonNull::new(unsafe { ffi::TISCopyCurrentKeyboardLayoutInputSource() }) else {
|
||||
tracing::error!("`TISCopyCurrentKeyboardLayoutInputSource` returned null ptr");
|
||||
return Key::Unidentified(NativeKey::MacOS(scancode));
|
||||
};
|
||||
let input_source = unsafe { CFRetained::from_raw(ptr) };
|
||||
|
||||
let layout_data = unsafe {
|
||||
ffi::TISGetInputSourceProperty(&input_source, ffi::kTISPropertyUnicodeKeyLayoutData)
|
||||
};
|
||||
let Some(layout_data) = (unsafe { layout_data.cast::<CFData>().as_ref() }) else {
|
||||
tracing::error!("`TISGetInputSourceProperty` returned null ptr");
|
||||
return Key::Unidentified(NativeKey::MacOS(scancode));
|
||||
};
|
||||
|
||||
let layout = layout_data.byte_ptr().cast();
|
||||
let keyboard_type = run_on_main(|_mtm| unsafe { ffi::LMGetKbdType() });
|
||||
|
||||
let mut result_len = 0;
|
||||
let mut dead_keys = 0;
|
||||
let modifiers = 0;
|
||||
let mut string = [0; 16];
|
||||
let translate_result = unsafe {
|
||||
ffi::UCKeyTranslate(
|
||||
layout,
|
||||
@@ -59,9 +51,6 @@ pub fn get_modifierless_char(scancode: u16) -> Key {
|
||||
string.as_mut_ptr(),
|
||||
)
|
||||
};
|
||||
unsafe {
|
||||
CFRelease(input_source as *mut c_void);
|
||||
}
|
||||
if translate_result != 0 {
|
||||
tracing::error!("`UCKeyTranslate` returned with the non-zero value: {}", translate_result);
|
||||
return Key::Unidentified(NativeKey::MacOS(scancode));
|
||||
@@ -78,9 +67,7 @@ pub fn get_modifierless_char(scancode: u16) -> Key {
|
||||
|
||||
// Ignores all modifiers except for SHIFT (yes, even ALT is ignored).
|
||||
fn get_logical_key_char(ns_event: &NSEvent, modifierless_chars: &str) -> Key {
|
||||
let string = unsafe { ns_event.charactersIgnoringModifiers() }
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_default();
|
||||
let string = ns_event.charactersIgnoringModifiers().map(|s| s.to_string()).unwrap_or_default();
|
||||
if string.is_empty() {
|
||||
// Probably a dead key
|
||||
let first_char = modifierless_chars.chars().next();
|
||||
@@ -96,7 +83,7 @@ pub(crate) fn create_key_event(ns_event: &NSEvent, is_press: bool, is_repeat: bo
|
||||
use ElementState::{Pressed, Released};
|
||||
let state = if is_press { Pressed } else { Released };
|
||||
|
||||
let scancode = unsafe { ns_event.keyCode() };
|
||||
let scancode = ns_event.keyCode();
|
||||
let mut physical_key = scancode_to_physicalkey(scancode as u32);
|
||||
|
||||
// NOTE: The logical key should heed both SHIFT and ALT if possible.
|
||||
@@ -106,7 +93,7 @@ pub(crate) fn create_key_event(ns_event: &NSEvent, is_press: bool, is_repeat: bo
|
||||
// * Pressing CTRL SHIFT A: logical key should also be "A"
|
||||
// This is not easy to tease out of `NSEvent`, but we do our best.
|
||||
|
||||
let characters = unsafe { ns_event.characters() }.map(|s| s.to_string()).unwrap_or_default();
|
||||
let characters = ns_event.characters().map(|s| s.to_string()).unwrap_or_default();
|
||||
let text_with_all_modifiers = if characters.is_empty() {
|
||||
None
|
||||
} else {
|
||||
@@ -122,13 +109,13 @@ pub(crate) fn create_key_event(ns_event: &NSEvent, is_press: bool, is_repeat: bo
|
||||
// `get_modifierless_char/key_without_modifiers` ignores ALL modifiers.
|
||||
let key_without_modifiers = get_modifierless_char(scancode);
|
||||
|
||||
let modifiers = unsafe { ns_event.modifierFlags() };
|
||||
let has_ctrl = modifiers.contains(NSEventModifierFlags::NSEventModifierFlagControl);
|
||||
let has_cmd = modifiers.contains(NSEventModifierFlags::NSEventModifierFlagCommand);
|
||||
let modifiers = ns_event.modifierFlags();
|
||||
let has_ctrl = modifiers.contains(NSEventModifierFlags::Control);
|
||||
let has_cmd = modifiers.contains(NSEventModifierFlags::Command);
|
||||
|
||||
let logical_key = match text_with_all_modifiers.as_ref() {
|
||||
// Only checking for ctrl and cmd here, not checking for alt because we DO want to
|
||||
// include its effect in the key. For example if -on the Germay layout- one
|
||||
// include its effect in the key. For example if -on the German layout- one
|
||||
// presses alt+8, the logical key should be "{"
|
||||
// Also not checking if this is a release event because then this issue would
|
||||
// still affect the key release.
|
||||
@@ -162,7 +149,8 @@ pub(crate) fn create_key_event(ns_event: &NSEvent, is_press: bool, is_repeat: bo
|
||||
repeat: is_repeat,
|
||||
state,
|
||||
text,
|
||||
platform_specific: KeyEventExtra { text_with_all_modifiers, key_without_modifiers },
|
||||
text_with_all_modifiers,
|
||||
key_without_modifiers,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,28 +160,34 @@ pub fn code_to_key(key: PhysicalKey, scancode: u16) -> Key {
|
||||
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 {
|
||||
KeyCode::Enter => NamedKey::Enter,
|
||||
KeyCode::Tab => NamedKey::Tab,
|
||||
KeyCode::Space => NamedKey::Space,
|
||||
KeyCode::Space => return Key::Character(" ".into()),
|
||||
KeyCode::Backspace => NamedKey::Backspace,
|
||||
KeyCode::Escape => NamedKey::Escape,
|
||||
KeyCode::SuperRight => NamedKey::Super,
|
||||
KeyCode::SuperLeft => NamedKey::Super,
|
||||
KeyCode::MetaRight => NamedKey::Meta,
|
||||
KeyCode::MetaLeft => NamedKey::Meta,
|
||||
KeyCode::ShiftLeft => NamedKey::Shift,
|
||||
KeyCode::AltLeft => NamedKey::Alt,
|
||||
KeyCode::ControlLeft => NamedKey::Control,
|
||||
KeyCode::ShiftRight => NamedKey::Shift,
|
||||
KeyCode::AltRight => NamedKey::Alt,
|
||||
KeyCode::ControlRight => NamedKey::Control,
|
||||
KeyCode::CapsLock => NamedKey::CapsLock,
|
||||
|
||||
KeyCode::NumLock => NamedKey::NumLock,
|
||||
KeyCode::AudioVolumeUp => NamedKey::AudioVolumeUp,
|
||||
KeyCode::AudioVolumeDown => NamedKey::AudioVolumeDown,
|
||||
KeyCode::AudioVolumeMute => NamedKey::AudioVolumeMute,
|
||||
|
||||
// Other numpad keys all generate text on macOS (if I understand correctly)
|
||||
KeyCode::NumpadEnter => NamedKey::Enter,
|
||||
|
||||
KeyCode::Fn => NamedKey::Fn,
|
||||
KeyCode::F1 => NamedKey::F1,
|
||||
KeyCode::F2 => NamedKey::F2,
|
||||
KeyCode::F3 => NamedKey::F3,
|
||||
@@ -214,17 +208,27 @@ pub fn code_to_key(key: PhysicalKey, scancode: u16) -> Key {
|
||||
KeyCode::F18 => NamedKey::F18,
|
||||
KeyCode::F19 => NamedKey::F19,
|
||||
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::Home => NamedKey::Home,
|
||||
KeyCode::PageUp => NamedKey::PageUp,
|
||||
KeyCode::Delete => NamedKey::Delete,
|
||||
KeyCode::End => NamedKey::End,
|
||||
KeyCode::Help => NamedKey::Help,
|
||||
KeyCode::PageDown => NamedKey::PageDown,
|
||||
KeyCode::ArrowLeft => NamedKey::ArrowLeft,
|
||||
KeyCode::ArrowRight => NamedKey::ArrowRight,
|
||||
KeyCode::ArrowDown => NamedKey::ArrowDown,
|
||||
KeyCode::ArrowUp => NamedKey::ArrowUp,
|
||||
KeyCode::ContextMenu => NamedKey::ContextMenu,
|
||||
|
||||
KeyCode::Lang2 => NamedKey::Eisu,
|
||||
KeyCode::Lang1 => NamedKey::KanjiMode,
|
||||
|
||||
_ => return Key::Unidentified(NativeKey::MacOS(scancode)),
|
||||
})
|
||||
}
|
||||
@@ -236,8 +240,8 @@ pub fn code_to_location(key: PhysicalKey) -> KeyLocation {
|
||||
};
|
||||
|
||||
match code {
|
||||
KeyCode::SuperRight => KeyLocation::Right,
|
||||
KeyCode::SuperLeft => KeyLocation::Left,
|
||||
KeyCode::MetaRight => KeyLocation::Right,
|
||||
KeyCode::MetaLeft => KeyLocation::Left,
|
||||
KeyCode::ShiftLeft => KeyLocation::Left,
|
||||
KeyCode::AltLeft => KeyLocation::Left,
|
||||
KeyCode::ControlLeft => KeyLocation::Left,
|
||||
@@ -296,47 +300,39 @@ const NX_DEVICERALTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x000000
|
||||
const NX_DEVICERCTLKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00002000);
|
||||
|
||||
pub(super) fn lalt_pressed(event: &NSEvent) -> bool {
|
||||
unsafe { event.modifierFlags() }.contains(NX_DEVICELALTKEYMASK)
|
||||
event.modifierFlags().contains(NX_DEVICELALTKEYMASK)
|
||||
}
|
||||
|
||||
pub(super) fn ralt_pressed(event: &NSEvent) -> bool {
|
||||
unsafe { event.modifierFlags() }.contains(NX_DEVICERALTKEYMASK)
|
||||
event.modifierFlags().contains(NX_DEVICERALTKEYMASK)
|
||||
}
|
||||
|
||||
pub(super) fn event_mods(event: &NSEvent) -> Modifiers {
|
||||
let flags = unsafe { event.modifierFlags() };
|
||||
let flags = event.modifierFlags();
|
||||
let mut state = ModifiersState::empty();
|
||||
let mut pressed_mods = ModifiersKeys::empty();
|
||||
|
||||
state
|
||||
.set(ModifiersState::SHIFT, flags.contains(NSEventModifierFlags::NSEventModifierFlagShift));
|
||||
state.set(ModifiersState::SHIFT, flags.contains(NSEventModifierFlags::Shift));
|
||||
pressed_mods.set(ModifiersKeys::LSHIFT, flags.contains(NX_DEVICELSHIFTKEYMASK));
|
||||
pressed_mods.set(ModifiersKeys::RSHIFT, flags.contains(NX_DEVICERSHIFTKEYMASK));
|
||||
|
||||
state.set(
|
||||
ModifiersState::CONTROL,
|
||||
flags.contains(NSEventModifierFlags::NSEventModifierFlagControl),
|
||||
);
|
||||
state.set(ModifiersState::CONTROL, flags.contains(NSEventModifierFlags::Control));
|
||||
pressed_mods.set(ModifiersKeys::LCONTROL, flags.contains(NX_DEVICELCTLKEYMASK));
|
||||
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::RALT, flags.contains(NX_DEVICERALTKEYMASK));
|
||||
|
||||
state.set(
|
||||
ModifiersState::SUPER,
|
||||
flags.contains(NSEventModifierFlags::NSEventModifierFlagCommand),
|
||||
);
|
||||
pressed_mods.set(ModifiersKeys::LSUPER, flags.contains(NX_DEVICELCMDKEYMASK));
|
||||
pressed_mods.set(ModifiersKeys::RSUPER, flags.contains(NX_DEVICERCMDKEYMASK));
|
||||
state.set(ModifiersState::META, flags.contains(NSEventModifierFlags::Command));
|
||||
pressed_mods.set(ModifiersKeys::LMETA, flags.contains(NX_DEVICELCMDKEYMASK));
|
||||
pressed_mods.set(ModifiersKeys::RMETA, flags.contains(NX_DEVICERCMDKEYMASK));
|
||||
|
||||
Modifiers { state, pressed_mods }
|
||||
Modifiers::new(state, pressed_mods)
|
||||
}
|
||||
|
||||
pub(super) fn dummy_event() -> Option<Retained<NSEvent>> {
|
||||
unsafe {
|
||||
NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
|
||||
NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
|
||||
NSEventType::ApplicationDefined,
|
||||
NSPoint::new(0.0, 0.0),
|
||||
NSEventModifierFlags(0),
|
||||
@@ -347,10 +343,9 @@ pub(super) fn dummy_event() -> Option<Retained<NSEvent>> {
|
||||
0,
|
||||
0,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
PhysicalKey::Code(code) => code,
|
||||
PhysicalKey::Unidentified(_) => return None,
|
||||
@@ -367,6 +362,7 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
|
||||
KeyCode::KeyX => Some(0x07),
|
||||
KeyCode::KeyC => Some(0x08),
|
||||
KeyCode::KeyV => Some(0x09),
|
||||
KeyCode::IntlBackslash => Some(0x0a),
|
||||
KeyCode::KeyB => Some(0x0b),
|
||||
KeyCode::KeyQ => Some(0x0c),
|
||||
KeyCode::KeyW => Some(0x0d),
|
||||
@@ -409,21 +405,24 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
|
||||
KeyCode::Backquote => Some(0x32),
|
||||
KeyCode::Backspace => Some(0x33),
|
||||
KeyCode::Escape => Some(0x35),
|
||||
KeyCode::SuperRight => Some(0x36),
|
||||
KeyCode::SuperLeft => Some(0x37),
|
||||
KeyCode::MetaRight => Some(0x36),
|
||||
KeyCode::MetaLeft => Some(0x37),
|
||||
KeyCode::ShiftLeft => Some(0x38),
|
||||
KeyCode::CapsLock => Some(0x39),
|
||||
KeyCode::AltLeft => Some(0x3a),
|
||||
KeyCode::ControlLeft => Some(0x3b),
|
||||
KeyCode::ShiftRight => Some(0x3c),
|
||||
KeyCode::AltRight => Some(0x3d),
|
||||
KeyCode::ControlRight => Some(0x3e),
|
||||
KeyCode::Fn => Some(0x3f),
|
||||
KeyCode::F17 => Some(0x40),
|
||||
KeyCode::NumpadDecimal => Some(0x41),
|
||||
KeyCode::NumpadMultiply => Some(0x43),
|
||||
KeyCode::NumpadAdd => Some(0x45),
|
||||
KeyCode::NumLock => Some(0x47),
|
||||
KeyCode::AudioVolumeUp => Some(0x49),
|
||||
KeyCode::AudioVolumeDown => Some(0x4a),
|
||||
KeyCode::AudioVolumeUp => Some(0x48),
|
||||
KeyCode::AudioVolumeDown => Some(0x49),
|
||||
KeyCode::AudioVolumeMute => Some(0x4a),
|
||||
KeyCode::NumpadDivide => Some(0x4b),
|
||||
KeyCode::NumpadEnter => Some(0x4c),
|
||||
KeyCode::NumpadSubtract => Some(0x4e),
|
||||
@@ -442,17 +441,22 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
|
||||
KeyCode::Numpad8 => Some(0x5b),
|
||||
KeyCode::Numpad9 => Some(0x5c),
|
||||
KeyCode::IntlYen => Some(0x5d),
|
||||
KeyCode::IntlRo => Some(0x5e),
|
||||
KeyCode::NumpadComma => Some(0x5f),
|
||||
KeyCode::F5 => Some(0x60),
|
||||
KeyCode::F6 => Some(0x61),
|
||||
KeyCode::F7 => Some(0x62),
|
||||
KeyCode::F3 => Some(0x63),
|
||||
KeyCode::F8 => Some(0x64),
|
||||
KeyCode::F9 => Some(0x65),
|
||||
KeyCode::Lang2 => Some(0x66),
|
||||
KeyCode::F11 => Some(0x67),
|
||||
KeyCode::Lang1 => Some(0x68),
|
||||
KeyCode::F13 => Some(0x69),
|
||||
KeyCode::F16 => Some(0x6a),
|
||||
KeyCode::F14 => Some(0x6b),
|
||||
KeyCode::F10 => Some(0x6d),
|
||||
KeyCode::ContextMenu => Some(0x6e),
|
||||
KeyCode::F12 => Some(0x6f),
|
||||
KeyCode::F15 => Some(0x71),
|
||||
KeyCode::Insert => Some(0x72),
|
||||
@@ -468,11 +472,26 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
|
||||
KeyCode::ArrowRight => Some(0x7c),
|
||||
KeyCode::ArrowDown => Some(0x7d),
|
||||
KeyCode::ArrowUp => Some(0x7e),
|
||||
KeyCode::Power => Some(0x7f),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
||||
pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
||||
// Follows what Chromium and Firefox do:
|
||||
// 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
|
||||
//
|
||||
// See also:
|
||||
// Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h
|
||||
//
|
||||
// Also see https://developer.apple.com/documentation/appkit/function-key-unicode-values:
|
||||
//
|
||||
// > the system handles some function keys at a lower level and your app never sees them.
|
||||
// > Examples include the Volume Up key, Volume Down key, Volume Mute key, Eject key, and
|
||||
// > Function key found on many Macs.
|
||||
//
|
||||
// So the handling of some of these is mostly for show.
|
||||
PhysicalKey::Code(match scancode {
|
||||
0x00 => KeyCode::KeyA,
|
||||
0x01 => KeyCode::KeyS,
|
||||
@@ -484,7 +503,11 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
||||
0x07 => KeyCode::KeyX,
|
||||
0x08 => KeyCode::KeyC,
|
||||
0x09 => KeyCode::KeyV,
|
||||
// 0x0a => World 1,
|
||||
// This key is typically located near LeftShift key, roughly the same location as backquote
|
||||
// (`) on Windows' US layout.
|
||||
//
|
||||
// The keycap varies on international keyboards.
|
||||
0x0a => KeyCode::IntlBackslash,
|
||||
0x0b => KeyCode::KeyB,
|
||||
0x0c => KeyCode::KeyQ,
|
||||
0x0d => KeyCode::KeyW,
|
||||
@@ -526,10 +549,10 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
||||
0x31 => KeyCode::Space,
|
||||
0x32 => KeyCode::Backquote,
|
||||
0x33 => KeyCode::Backspace,
|
||||
// 0x34 => unknown,
|
||||
// 0x34 => unknown, // kVK_Powerbook_KeypadEnter
|
||||
0x35 => KeyCode::Escape,
|
||||
0x36 => KeyCode::SuperRight,
|
||||
0x37 => KeyCode::SuperLeft,
|
||||
0x36 => KeyCode::MetaRight,
|
||||
0x37 => KeyCode::MetaLeft,
|
||||
0x38 => KeyCode::ShiftLeft,
|
||||
0x39 => KeyCode::CapsLock,
|
||||
0x3a => KeyCode::AltLeft,
|
||||
@@ -545,15 +568,10 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
||||
// 0x44 => unknown,
|
||||
0x45 => KeyCode::NumpadAdd,
|
||||
// 0x46 => unknown,
|
||||
0x47 => KeyCode::NumLock,
|
||||
// 0x48 => KeyCode::NumpadClear,
|
||||
|
||||
// TODO: (Artur) for me, kVK_VolumeUp is 0x48
|
||||
// macOS 10.11
|
||||
// /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/
|
||||
// Versions/A/Headers/Events.h
|
||||
0x49 => KeyCode::AudioVolumeUp,
|
||||
0x4a => KeyCode::AudioVolumeDown,
|
||||
0x47 => KeyCode::NumLock, // kVK_ANSI_KeypadClear
|
||||
0x48 => KeyCode::AudioVolumeUp,
|
||||
0x49 => KeyCode::AudioVolumeDown,
|
||||
0x4a => KeyCode::AudioVolumeMute,
|
||||
0x4b => KeyCode::NumpadDivide,
|
||||
0x4c => KeyCode::NumpadEnter,
|
||||
// 0x4d => unknown,
|
||||
@@ -573,23 +591,23 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
||||
0x5b => KeyCode::Numpad8,
|
||||
0x5c => KeyCode::Numpad9,
|
||||
0x5d => KeyCode::IntlYen,
|
||||
// 0x5e => JIS Ro,
|
||||
// 0x5f => unknown,
|
||||
0x5e => KeyCode::IntlRo,
|
||||
0x5f => KeyCode::NumpadComma,
|
||||
0x60 => KeyCode::F5,
|
||||
0x61 => KeyCode::F6,
|
||||
0x62 => KeyCode::F7,
|
||||
0x63 => KeyCode::F3,
|
||||
0x64 => KeyCode::F8,
|
||||
0x65 => KeyCode::F9,
|
||||
// 0x66 => JIS Eisuu (macOS),
|
||||
0x66 => KeyCode::Lang2,
|
||||
0x67 => KeyCode::F11,
|
||||
// 0x68 => JIS Kanna (macOS),
|
||||
0x68 => KeyCode::Lang1,
|
||||
0x69 => KeyCode::F13,
|
||||
0x6a => KeyCode::F16,
|
||||
0x6b => KeyCode::F14,
|
||||
// 0x6c => unknown,
|
||||
0x6d => KeyCode::F10,
|
||||
// 0x6e => unknown,
|
||||
0x6e => KeyCode::ContextMenu,
|
||||
0x6f => KeyCode::F12,
|
||||
// 0x70 => unknown,
|
||||
0x71 => KeyCode::F15,
|
||||
@@ -606,11 +624,7 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
||||
0x7c => KeyCode::ArrowRight,
|
||||
0x7d => KeyCode::ArrowDown,
|
||||
0x7e => KeyCode::ArrowUp,
|
||||
// 0x7f => unknown,
|
||||
|
||||
// 0xA is the caret (^) an macOS's German QERTZ layout. This key is at the same location as
|
||||
// backquote (`) on Windows' US layout.
|
||||
0xa => KeyCode::Backquote,
|
||||
0x7f => KeyCode::Power, // On 10.7 and 10.8 only
|
||||
_ => return PhysicalKey::Unidentified(NativeKeyCode::MacOS(scancode as u16)),
|
||||
})
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user