mirror of
https://github.com/rust-windowing/winit.git
synced 2026-06-26 22:53:15 -04:00
Compare commits
199 Commits
it
...
notgull/in
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19477d3f03 | ||
|
|
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 | ||
|
|
1682703b5c | ||
|
|
bdd80c8af2 | ||
|
|
7b0c7b6cb2 | ||
|
|
7006c7ceca | ||
|
|
2491f2bbd6 | ||
|
|
babbb715c5 | ||
|
|
be79e8979a | ||
|
|
9ab4c03e89 | ||
|
|
4f47a4e793 | ||
|
|
c15fa6e433 | ||
|
|
24faacf497 | ||
|
|
080556f2c8 | ||
|
|
259e868c05 | ||
|
|
575d978202 | ||
|
|
7dd7dc1fc8 | ||
|
|
df7c496a5d | ||
|
|
0086d7153b | ||
|
|
b79acd8a5a | ||
|
|
c2951e0194 | ||
|
|
8998e36994 | ||
|
|
5a7169c7a6 | ||
|
|
4cd6877e8e | ||
|
|
44aabdddcc | ||
|
|
c4415009c0 | ||
|
|
63a7c02492 | ||
|
|
7b0ef160fc | ||
|
|
962241e2a0 | ||
|
|
3efa6d855d | ||
|
|
9067426dca | ||
|
|
ba10c35240 |
@@ -1,9 +1,9 @@
|
|||||||
[alias]
|
|
||||||
run-wasm = ["run", "--release", "--package", "run-wasm", "--"]
|
|
||||||
|
|
||||||
# Allow rust-analyzer and local `cargo doc` invocations to pick up unreleased changelog entries
|
# Allow rust-analyzer and local `cargo doc` invocations to pick up unreleased changelog entries
|
||||||
#
|
#
|
||||||
# Note that these flags are (intentionally) not included when building from the downloaded crate.
|
# Note that these flags are (intentionally) not included when building from the downloaded crate.
|
||||||
[build]
|
[build]
|
||||||
rustflags = ["--cfg=unreleased_changelogs"]
|
|
||||||
rustdocflags = ["--cfg=unreleased_changelogs"]
|
rustdocflags = ["--cfg=unreleased_changelogs"]
|
||||||
|
rustflags = ["--cfg=unreleased_changelogs"]
|
||||||
|
|
||||||
|
[target.wasm32-unknown-unknown]
|
||||||
|
runner = "wasm-bindgen-test-runner"
|
||||||
|
|||||||
8
.git-blame-ignore-revs
Normal file
8
.git-blame-ignore-revs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
# $ git config blame.ignoreRevsFile .git-blame-ignore-revs
|
||||||
|
|
||||||
|
# chore(rustfmt): use nightly
|
||||||
|
7b0c7b6cb2c62767ca0c73c857b299883f55a883
|
||||||
|
# Rustfmt: use `group_imports`
|
||||||
|
2665c120981af548433645c6383b3580dd8f8fc4
|
||||||
|
# Use Taplo for TOML formatting
|
||||||
|
3398ebe467c43ccfd91916c5b81ff3c68f598556
|
||||||
20
.github/CODEOWNERS
vendored
20
.github/CODEOWNERS
vendored
@@ -1,10 +1,11 @@
|
|||||||
# Android
|
# Android
|
||||||
/src/platform/android.rs @msiglreith @MarijnS95
|
/src/platform/android.rs @MarijnS95
|
||||||
/src/platform_impl/android @msiglreith @MarijnS95
|
/src/platform_impl/android @MarijnS95
|
||||||
|
|
||||||
# iOS
|
# Apple (AppKit + UIKit)
|
||||||
/src/platform/ios.rs @madsmtm
|
/src/platform/ios.rs @madsmtm
|
||||||
/src/platform_impl/ios @madsmtm
|
/src/platform/macos.rs @madsmtm
|
||||||
|
/src/platform_impl/apple @madsmtm
|
||||||
|
|
||||||
# Unix
|
# Unix
|
||||||
/src/platform_impl/linux/mod.rs @kchibisov
|
/src/platform_impl/linux/mod.rs @kchibisov
|
||||||
@@ -17,21 +18,14 @@
|
|||||||
/src/platform/x11.rs @kchibisov @notgull
|
/src/platform/x11.rs @kchibisov @notgull
|
||||||
/src/platform_impl/linux/x11 @kchibisov @notgull
|
/src/platform_impl/linux/x11 @kchibisov @notgull
|
||||||
|
|
||||||
# macOS
|
|
||||||
/src/platform/macos.rs @madsmtm
|
|
||||||
/src/platform_impl/macos @madsmtm
|
|
||||||
|
|
||||||
# Web
|
# Web
|
||||||
/src/platform/web.rs @daxpedda
|
/src/platform/web.rs @daxpedda
|
||||||
/src/platform_impl/web @daxpedda
|
/src/platform_impl/web @daxpedda
|
||||||
|
|
||||||
# Windows
|
# Windows
|
||||||
/src/platform/windows.rs @msiglreith
|
/src/platform/windows.rs @notgull
|
||||||
/src/platform_impl/windows @msiglreith
|
/src/platform_impl/windows @notgull
|
||||||
|
|
||||||
# Orbital (Redox OS)
|
# Orbital (Redox OS)
|
||||||
/src/platform/orbital.rs @jackpot51
|
/src/platform/orbital.rs @jackpot51
|
||||||
/src/platform_impl/orbital @jackpot51
|
/src/platform_impl/orbital @jackpot51
|
||||||
|
|
||||||
# Integration tests
|
|
||||||
/it @notgull
|
|
||||||
|
|||||||
2
.github/ISSUE_TEMPLATE/bug_web.yml
vendored
2
.github/ISSUE_TEMPLATE/bug_web.yml
vendored
@@ -1,5 +1,5 @@
|
|||||||
name: Web bug
|
name: Web bug
|
||||||
description: Create a web-specific bug report
|
description: Create a Web-specific bug report
|
||||||
labels:
|
labels:
|
||||||
- B - bug
|
- B - bug
|
||||||
- DS - web
|
- 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
|
- [ ] 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
|
- [ ] 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
|
- [ ] 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"
|
||||||
168
.github/workflows/ci.yml
vendored
168
.github/workflows/ci.yml
vendored
@@ -10,19 +10,32 @@ jobs:
|
|||||||
name: Check formatting
|
name: Check formatting
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: taiki-e/checkout-action@v1
|
||||||
- uses: dtolnay/rust-toolchain@stable
|
- uses: dtolnay/rust-toolchain@nightly
|
||||||
with:
|
with:
|
||||||
components: rustfmt
|
components: rustfmt
|
||||||
- name: Check Formatting
|
- name: Check Formatting
|
||||||
run: cargo fmt -- --check
|
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:
|
typos:
|
||||||
name: Check for typos
|
name: Check for typos
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 30
|
timeout-minutes: 30
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: taiki-e/checkout-action@v1
|
||||||
- uses: taiki-e/install-action@v2
|
- uses: taiki-e/install-action@v2
|
||||||
with:
|
with:
|
||||||
tool: typos-cli
|
tool: typos-cli
|
||||||
@@ -42,7 +55,7 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
toolchain: [stable, nightly, '1.70.0']
|
toolchain: [stable, nightly, '1.73']
|
||||||
platform:
|
platform:
|
||||||
# Note: Make sure that we test all the `docs.rs` targets defined in Cargo.toml!
|
# Note: Make sure that we test all the `docs.rs` targets defined in Cargo.toml!
|
||||||
- { name: 'Windows 64bit MSVC', target: x86_64-pc-windows-msvc, os: windows-latest, }
|
- { name: 'Windows 64bit MSVC', target: x86_64-pc-windows-msvc, os: windows-latest, }
|
||||||
@@ -55,25 +68,35 @@ jobs:
|
|||||||
- { name: 'Wayland', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: '--no-default-features --features=wayland,wayland-dlopen' }
|
- { name: 'Wayland', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: '--no-default-features --features=wayland,wayland-dlopen' }
|
||||||
- { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
- { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
||||||
- { name: 'Redox OS', target: x86_64-unknown-redox, os: ubuntu-latest, }
|
- { name: 'Redox OS', target: x86_64-unknown-redox, os: ubuntu-latest, }
|
||||||
- { name: 'macOS', 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 x86_64', target: x86_64-apple-ios, os: macos-latest, }
|
||||||
- { name: 'iOS Aarch64', target: aarch64-apple-ios, os: macos-latest, }
|
- { name: 'iOS Aarch64', target: aarch64-apple-ios, os: macos-latest, }
|
||||||
- { name: 'web', target: wasm32-unknown-unknown, os: ubuntu-latest, }
|
- { name: 'Web', target: wasm32-unknown-unknown, os: ubuntu-latest, }
|
||||||
exclude:
|
exclude:
|
||||||
|
# Web on nightly needs extra arguments
|
||||||
|
- toolchain: nightly
|
||||||
|
platform: { name: 'Web', target: wasm32-unknown-unknown, os: ubuntu-latest }
|
||||||
# Android is tested on stable-3
|
# Android is tested on stable-3
|
||||||
- toolchain: '1.70.0'
|
- toolchain: '1.73'
|
||||||
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
||||||
|
# Redox OS doesn't follow MSRV
|
||||||
|
- toolchain: '1.73'
|
||||||
|
platform: { name: 'Redox OS', target: x86_64-unknown-redox, os: ubuntu-latest }
|
||||||
include:
|
include:
|
||||||
- toolchain: '1.70.0'
|
- toolchain: '1.73'
|
||||||
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
||||||
|
- toolchain: 'nightly'
|
||||||
|
platform: { name: 'Web', target: wasm32-unknown-unknown, os: ubuntu-latest, test-options: -Zdoctest-xcompile }
|
||||||
- toolchain: 'nightly'
|
- toolchain: 'nightly'
|
||||||
platform: {
|
platform: {
|
||||||
name: 'web Atomic',
|
name: 'Web Atomic',
|
||||||
target: wasm32-unknown-unknown,
|
target: wasm32-unknown-unknown,
|
||||||
os: ubuntu-latest,
|
os: ubuntu-latest,
|
||||||
options: '-Zbuild-std=panic_abort,std',
|
options: '-Zbuild-std=panic_abort,std',
|
||||||
rustflags: '-Ctarget-feature=+atomics,+bulk-memory',
|
test-options: -Zdoctest-xcompile,
|
||||||
components: rust-src,
|
rustflags: '-Ctarget-feature=+atomics,+bulk-memory',
|
||||||
|
components: rust-src,
|
||||||
}
|
}
|
||||||
|
|
||||||
env:
|
env:
|
||||||
@@ -83,19 +106,21 @@ jobs:
|
|||||||
|
|
||||||
# Faster compilation and error on warnings
|
# Faster compilation and error on warnings
|
||||||
RUSTFLAGS: '--codegen=debuginfo=0 --deny=warnings ${{ matrix.platform.rustflags }}'
|
RUSTFLAGS: '--codegen=debuginfo=0 --deny=warnings ${{ matrix.platform.rustflags }}'
|
||||||
|
RUSTDOCFLAGS: ${{ matrix.platform.rustflags }}
|
||||||
|
|
||||||
OPTIONS: --target=${{ matrix.platform.target }} ${{ matrix.platform.options }}
|
OPTIONS: --target=${{ matrix.platform.target }} ${{ matrix.platform.options }}
|
||||||
|
TEST_OPTIONS: ${{ matrix.platform.test-options }}
|
||||||
CMD: ${{ matrix.platform.cmd }}
|
CMD: ${{ matrix.platform.cmd }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: taiki-e/checkout-action@v1
|
||||||
|
|
||||||
- name: Restore cache of cargo folder
|
- name: Restore cache of cargo folder
|
||||||
# We use `restore` and later `save`, so that we can create the key after
|
# We use `restore` and later `save`, so that we can create the key after
|
||||||
# the cache has been downloaded.
|
# the cache has been downloaded.
|
||||||
#
|
#
|
||||||
# This could be avoided if we added Cargo.lock to the repository.
|
# This could be avoided if we added Cargo.lock to the repository.
|
||||||
uses: actions/cache/restore@v3
|
uses: actions/cache/restore@v4
|
||||||
with:
|
with:
|
||||||
# https://doc.rust-lang.org/cargo/guide/cargo-home.html#caching-the-cargo-home-in-ci
|
# https://doc.rust-lang.org/cargo/guide/cargo-home.html#caching-the-cargo-home-in-ci
|
||||||
path: |
|
path: |
|
||||||
@@ -116,7 +141,7 @@ jobs:
|
|||||||
- name: Cache cargo-apk
|
- name: Cache cargo-apk
|
||||||
if: contains(matrix.platform.target, 'android')
|
if: contains(matrix.platform.target, 'android')
|
||||||
id: cargo-apk-cache
|
id: cargo-apk-cache
|
||||||
uses: actions/cache@v3
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
path: ~/.cargo/bin/cargo-apk
|
path: ~/.cargo/bin/cargo-apk
|
||||||
# Change this key if we update the required cargo-apk version
|
# Change this key if we update the required cargo-apk version
|
||||||
@@ -131,6 +156,11 @@ jobs:
|
|||||||
if: contains(matrix.platform.target, 'android') && (steps.cargo-apk-cache.outputs.cache-hit != 'true')
|
if: contains(matrix.platform.target, 'android') && (steps.cargo-apk-cache.outputs.cache-hit != 'true')
|
||||||
run: cargo install cargo-apk --version=^0.9.7 --locked
|
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
|
- uses: dtolnay/rust-toolchain@master
|
||||||
with:
|
with:
|
||||||
toolchain: ${{ matrix.toolchain }}${{ matrix.platform.host }}
|
toolchain: ${{ matrix.toolchain }}${{ matrix.platform.host }}
|
||||||
@@ -149,52 +179,52 @@ jobs:
|
|||||||
- name: Test dpi crate
|
- name: Test dpi crate
|
||||||
if: >
|
if: >
|
||||||
contains(matrix.platform.name, 'Linux 64bit') &&
|
contains(matrix.platform.name, 'Linux 64bit') &&
|
||||||
matrix.toolchain != '1.70.0'
|
matrix.toolchain != '1.73'
|
||||||
run: cargo test -p dpi
|
run: cargo test -p dpi
|
||||||
|
|
||||||
- name: Build tests
|
- name: Build tests
|
||||||
if: >
|
if: >
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.toolchain != '1.70.0'
|
matrix.toolchain != '1.73'
|
||||||
run: cargo $CMD test --no-run $OPTIONS
|
run: cargo $CMD test --no-run $OPTIONS
|
||||||
|
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
if: >
|
if: >
|
||||||
!contains(matrix.platform.target, 'android') &&
|
!contains(matrix.platform.target, 'android') &&
|
||||||
!contains(matrix.platform.target, 'ios') &&
|
!contains(matrix.platform.target, 'ios') &&
|
||||||
!contains(matrix.platform.target, 'wasm32') &&
|
(!contains(matrix.platform.target, 'wasm32') || matrix.toolchain == 'nightly') &&
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.toolchain != '1.70.0'
|
matrix.toolchain != '1.73'
|
||||||
run: cargo $CMD test $OPTIONS
|
run: cargo $CMD test $OPTIONS
|
||||||
|
|
||||||
- name: Lint with clippy
|
- name: Lint with clippy
|
||||||
if: (matrix.toolchain == 'stable') && !contains(matrix.platform.options, '--no-default-features')
|
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
|
- name: Build tests with serde enabled
|
||||||
if: >
|
if: >
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.toolchain != '1.70.0'
|
matrix.toolchain != '1.73'
|
||||||
run: cargo $CMD test --no-run $OPTIONS --features serde
|
run: cargo $CMD test --no-run $OPTIONS $TEST_OPTIONS --features serde
|
||||||
|
|
||||||
- name: Run tests with serde enabled
|
- name: Run tests with serde enabled
|
||||||
if: >
|
if: >
|
||||||
!contains(matrix.platform.target, 'android') &&
|
!contains(matrix.platform.target, 'android') &&
|
||||||
!contains(matrix.platform.target, 'ios') &&
|
!contains(matrix.platform.target, 'ios') &&
|
||||||
!contains(matrix.platform.target, 'wasm32') &&
|
(!contains(matrix.platform.target, 'wasm32') || matrix.toolchain == 'nightly') &&
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.toolchain != '1.70.0'
|
matrix.toolchain != '1.73'
|
||||||
run: cargo $CMD test $OPTIONS --features serde
|
run: cargo $CMD test $OPTIONS $TEST_OPTIONS --features serde
|
||||||
|
|
||||||
- name: Check docs.rs documentation
|
- name: Check docs.rs documentation
|
||||||
if: matrix.toolchain == 'nightly'
|
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:
|
env:
|
||||||
RUSTDOCFLAGS: '--deny=warnings ${{ matrix.platform.rustflags }} --cfg=docsrs --cfg=unreleased_changelogs'
|
RUSTDOCFLAGS: '--deny=warnings ${{ matrix.platform.rustflags }} --cfg=docsrs --cfg=unreleased_changelogs'
|
||||||
|
|
||||||
# See restore step above
|
# See restore step above
|
||||||
- name: Save cache of cargo folder
|
- name: Save cache of cargo folder
|
||||||
uses: actions/cache/save@v3
|
uses: actions/cache/save@v4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
~/.cargo/registry/index/
|
~/.cargo/registry/index/
|
||||||
@@ -202,41 +232,6 @@ jobs:
|
|||||||
~/.cargo/git/db/
|
~/.cargo/git/db/
|
||||||
key: cargo-${{ matrix.toolchain }}-${{ matrix.platform.name }}-${{ hashFiles('Cargo.lock') }}
|
key: cargo-${{ matrix.toolchain }}-${{ matrix.platform.name }}-${{ hashFiles('Cargo.lock') }}
|
||||||
|
|
||||||
it:
|
|
||||||
name: Run integration tests on ${{ matrix.platform.name }}
|
|
||||||
runs-on: ${{ matrix.platform.os }}
|
|
||||||
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
toolchain: [stable, nightly]
|
|
||||||
platform:
|
|
||||||
# Note: Make sure that we test all the `docs.rs` targets defined in Cargo.toml!
|
|
||||||
- { name: 'X11', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: '--no-default-features --features=x11' }
|
|
||||||
|
|
||||||
env:
|
|
||||||
# Set more verbose terminal output
|
|
||||||
CARGO_TERM_VERBOSE: true
|
|
||||||
RUST_BACKTRACE: 1
|
|
||||||
|
|
||||||
# Faster compilation and error on warnings
|
|
||||||
RUSTFLAGS: '--codegen=debuginfo=0 --deny=warnings ${{ matrix.platform.rustflags }}'
|
|
||||||
|
|
||||||
OPTIONS: --target=${{ matrix.platform.target }} ${{ matrix.platform.options }}
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
- uses: dtolnay/rust-toolchain@master
|
|
||||||
with:
|
|
||||||
toolchain: ${{ matrix.toolchain }}
|
|
||||||
|
|
||||||
- name: Log into GHCR
|
|
||||||
run: |
|
|
||||||
echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin
|
|
||||||
|
|
||||||
- name: Common tests
|
|
||||||
run: cargo run -p gui-test-runner -- common-tests ${{ matrix.platform.target }}
|
|
||||||
|
|
||||||
cargo-deny:
|
cargo-deny:
|
||||||
name: Run cargo-deny on ${{ matrix.platform.name }}
|
name: Run cargo-deny on ${{ matrix.platform.name }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -249,15 +244,50 @@ jobs:
|
|||||||
- { name: 'Android', target: aarch64-linux-android }
|
- { name: 'Android', target: aarch64-linux-android }
|
||||||
- { name: 'iOS', target: aarch64-apple-ios }
|
- { name: 'iOS', target: aarch64-apple-ios }
|
||||||
- { name: 'Linux', target: x86_64-unknown-linux-gnu }
|
- { 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: 'Redox OS', target: x86_64-unknown-redox }
|
||||||
- { name: 'web', target: wasm32-unknown-unknown }
|
- { name: 'Web', target: wasm32-unknown-unknown }
|
||||||
- { name: 'Windows', target: x86_64-pc-windows-gnu }
|
- { name: 'Windows GNU', target: x86_64-pc-windows-gnu }
|
||||||
|
- { name: 'Windows MSVC', target: x86_64-pc-windows-msvc }
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: taiki-e/checkout-action@v1
|
||||||
- uses: EmbarkStudios/cargo-deny-action@v1
|
- uses: EmbarkStudios/cargo-deny-action@v2
|
||||||
with:
|
with:
|
||||||
command: check
|
command: check
|
||||||
log-level: error
|
log-level: error
|
||||||
arguments: --all-features --target ${{ matrix.platform.target }}
|
arguments: --all-features --target ${{ matrix.platform.target }}
|
||||||
|
|
||||||
|
eslint:
|
||||||
|
name: ESLint
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: ./src/platform_impl/web/script
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: taiki-e/checkout-action@v1
|
||||||
|
- name: Setup NPM
|
||||||
|
run: npm install
|
||||||
|
- name: Run ESLint
|
||||||
|
run: npx eslint
|
||||||
|
|
||||||
|
swc:
|
||||||
|
name: Minimize JavaScript
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: ./src/platform_impl/web/script
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: taiki-e/checkout-action@v1
|
||||||
|
- name: Install SWC
|
||||||
|
run: sudo npm i -g @swc/cli
|
||||||
|
- name: Run SWC
|
||||||
|
run: |
|
||||||
|
swc . --ignore node_modules,**/*.d.ts --only **/*.ts -d . --out-file-extension min.js
|
||||||
|
- name: Check for diff
|
||||||
|
run: |
|
||||||
|
[[ -z $(git status -s) ]]
|
||||||
|
|||||||
6
.github/workflows/docs.yml
vendored
6
.github/workflows/docs.yml
vendored
@@ -19,7 +19,7 @@ jobs:
|
|||||||
id-token: write
|
id-token: write
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- uses: dtolnay/rust-toolchain@master
|
- uses: dtolnay/rust-toolchain@master
|
||||||
with:
|
with:
|
||||||
@@ -29,10 +29,10 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
RUSTDOCFLAGS: --crate-version master --cfg=docsrs --cfg=unreleased_changelogs
|
RUSTDOCFLAGS: --crate-version master --cfg=docsrs --cfg=unreleased_changelogs
|
||||||
run: |
|
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
|
- name: Setup Pages
|
||||||
uses: actions/configure-pages@v4
|
uses: actions/configure-pages@v5
|
||||||
|
|
||||||
- name: Fix permissions
|
- name: Fix permissions
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -3,8 +3,8 @@ target/
|
|||||||
rls/
|
rls/
|
||||||
.vscode/
|
.vscode/
|
||||||
*~
|
*~
|
||||||
*.wasm
|
|
||||||
*.ts
|
|
||||||
*.js
|
|
||||||
#*#
|
#*#
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
# NPM package used to run ESLint.
|
||||||
|
/src/platform_impl/web/script/node_modules
|
||||||
|
/src/platform_impl/web/script/package-lock.json
|
||||||
|
|||||||
143
CONTRIBUTING.md
143
CONTRIBUTING.md
@@ -1,52 +1,122 @@
|
|||||||
# Winit Contributing Guidelines
|
# Contribution Guidelines
|
||||||
|
|
||||||
## Scope
|
This document contains guidelines for contributing code to winit. It has to be
|
||||||
[See `FEATURES.md`](./FEATURES.md). When requesting or implementing a new Winit feature, you should
|
followed in order for your patch to be approved and applied.
|
||||||
consider whether or not it's directly related to window creation or input handling. If it isn't, it
|
|
||||||
may be worth creating a separate crate that extends Winit's API to add that functionality.
|
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
## Reporting an issue
|
Anyone can contribute to winit, however given that it's a cross platform
|
||||||
|
windowing toolkit getting certain changes incorporated could be challenging.
|
||||||
|
|
||||||
When reporting an issue, in order to help the maintainers understand what the problem is, please make
|
To save your time it's wise to check already opened [pull requests][prs] and
|
||||||
your description of the issue as detailed as possible:
|
[issues][issues]. In general, bug fixes and missing implementations are always
|
||||||
|
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.
|
||||||
|
|
||||||
- if it is a bug, please provide a clear explanation of what happens, what should happen, and how to
|
### Submitting your work and handling review
|
||||||
reproduce the issue, ideally by providing a minimal program exhibiting the problem
|
|
||||||
- if it is a feature request, please provide a clear argumentation about why you believe this feature
|
|
||||||
should be supported by winit
|
|
||||||
|
|
||||||
## Making a pull request
|
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.
|
||||||
|
|
||||||
When making a code contribution to winit, before opening your pull request, please make sure that:
|
#### Handling review
|
||||||
|
|
||||||
- your patch builds with Winit's minimal supported rust version - Rust 1.70.
|
During the review process certain events could require an action from your side,
|
||||||
- you tested your modifications on all the platforms impacted, or if not possible, detail which platforms
|
common patterns and reactions are described below.
|
||||||
were not tested, and what should be tested, so that a maintainer or another contributor can test them
|
|
||||||
- you updated any relevant documentation in winit
|
|
||||||
- you left comments in your code explaining any part that is not straightforward, so that the
|
|
||||||
maintainers and future contributors don't have to try to guess what your code is supposed to do
|
|
||||||
- your PR adds an entry to the current changelog if the introduced change is relevant to winit users.
|
|
||||||
|
|
||||||
You needn't worry about the added entry causing conflicts, the maintainer that merges the PR will
|
_Event:_ The CI fails to build, but it looks like it is not your fault. Not
|
||||||
handle those for you when merging (see below).
|
communicating so could result in maintainers not looking into your patch,
|
||||||
- if your PR affects the platform compatibility of one or more features or adds another feature, the
|
since they may assume that you're still working on it.\
|
||||||
relevant sections in [`FEATURES.md`](https://github.com/rust-windowing/winit/blob/master/FEATURES.md#features)
|
_Desired behaviour:_ Write a message saying roughly the following "The CI
|
||||||
should be updated.
|
failure is unrelated", so that the maintainers will fix it for you.
|
||||||
|
|
||||||
Once your PR is open, you can ask for a review by a maintainer of your platform. Winit's merging policy
|
_Event:_ Maintainer requested changes to your PR.\
|
||||||
is that a PR must be approved by at least two maintainers of winit before being merged, including
|
_Desired behavior:_ Once you address the request, you should re-request a review
|
||||||
at least a maintainer of the platform (a maintainer making a PR themselves counts as approving it).
|
with GitHub's UI. If you don't agree with what maintainer suggested, you
|
||||||
|
should state your objections and re-request the review. That will indicate that
|
||||||
|
the ball is on maintainer's side.
|
||||||
|
|
||||||
Once your PR is deemed ready, the merging maintainer will take care of resolving conflicts in the
|
_Event:_ You've opened a PR, but maintainer shortly after commented that they
|
||||||
`changelog` module (but you must resolve other conflicts yourself). Doing this requires that you check the
|
want to work on that themselves.\
|
||||||
"give contributors write access to the branch" checkbox when creating the PR.
|
_Desired behavior:_ Discuss with the maintainer regarding their plans if they
|
||||||
|
were not outlined in the initial response, because such response means that they
|
||||||
|
are not interested in reviewing your code. Such thing could happen when
|
||||||
|
underestimating complexity of the task you're solving or when your patch
|
||||||
|
mandate certain downstream designs. In general, the maintainer will likely
|
||||||
|
close your PR in order to prevent work being done on it.
|
||||||
|
|
||||||
|
[prs]: https://github.com/rust-windowing/winit/pulls
|
||||||
|
[issues]: https://github.com/rust-windowing/winit/issues
|
||||||
|
[matrix]: https://matrix.to/#/#rust-windowing:matrix.org
|
||||||
|
|
||||||
## Maintainers
|
## Maintainers
|
||||||
|
|
||||||
The current maintainers for each platform are listed in the [CODEOWNERS](.github/CODEOWNERS) file.
|
Winit has plenty of maintainers with different backgrounds, different time
|
||||||
|
available to work on Winit, and reasons to be winit maintainer in the first
|
||||||
|
place. To ensure that Winit's code quality does not decrease over time and to
|
||||||
|
make it easier to teach new maintainers the "winit way of doing things" the
|
||||||
|
common policies and routines are defined in this section.
|
||||||
|
|
||||||
## Release process
|
The current maintainers for each platform are listed in [this file][CODEOWNERS].
|
||||||
|
|
||||||
|
### Contributions handling
|
||||||
|
|
||||||
|
The maintainers must ensure that the external contributions meet Winit's
|
||||||
|
quality standards. If it's not, it **is the maintainer's responsibility** to
|
||||||
|
bring it on par, which includes:
|
||||||
|
|
||||||
|
- Ensure that formatting is consistent and `CHANGELOG` messages are clear
|
||||||
|
for the end users.
|
||||||
|
- Improve the commit message, so it'll be easier for other maintainers to
|
||||||
|
understand the motivation without going through all the discussions on the
|
||||||
|
particular patch/PR.
|
||||||
|
- Ensure that the proposed patch doesn't break platform parity. If the
|
||||||
|
breakage is desired by contributor, an issue should be opened to discuss
|
||||||
|
with other maintainers before merging.
|
||||||
|
- Always fix CI issues before merging if they don't originate from the
|
||||||
|
submitted work.
|
||||||
|
|
||||||
|
However, maintainers should give some leeway for external contributors, so they
|
||||||
|
don't feel discouraged contributing, for example:
|
||||||
|
|
||||||
|
- Suggest a patch to resolve style issues, if it's the only issue with the
|
||||||
|
submitted work. Keep in mind that pushing the resolution yourself is not
|
||||||
|
desired, because the contributor might not agree with what you did.
|
||||||
|
- Be more explicit on how things should be done if you don't like the
|
||||||
|
approach.
|
||||||
|
- Suggest to finish the PR for them if they're absent for a while and you need
|
||||||
|
the proposed changes to move forward with something. In such cases the
|
||||||
|
maintainer must preserve attribution with `Co-authored-by`, `Suggested-by`,
|
||||||
|
or keep the original committer.
|
||||||
|
- Rebase their work for them when massive changes to the Winit codebase were
|
||||||
|
introduced.
|
||||||
|
|
||||||
|
When reviewing code of other maintainers all of the above is on the maintainer
|
||||||
|
who submitted the patch. Interested maintainers could help push the work over
|
||||||
|
the finish line, but teaching other maintainers should be preferred.
|
||||||
|
|
||||||
|
For a _regular_ contributor to winit, the maintainer should slowly start
|
||||||
|
requiring contributor to match *maintainer* quality standards when writing
|
||||||
|
patches and commit messages.
|
||||||
|
|
||||||
|
### Contributing
|
||||||
|
|
||||||
|
When submitting a patch, the maintainer should follow the general contributing
|
||||||
|
guidelines, however greater attention to detail is expected in this case.
|
||||||
|
|
||||||
|
To make life simpler for other maintainers it's suggested to create your branch
|
||||||
|
under the project repository instead of your own fork. The naming scheme is
|
||||||
|
`github_user_name/branch_name`. Doing so will make your work easier to rebase
|
||||||
|
for other maintainers when you're absent.
|
||||||
|
|
||||||
|
### Administrative Actions
|
||||||
|
|
||||||
|
Some things (such as changing required CI steps, adding contributors, ...)
|
||||||
|
require administrative permissions. If you don't have those, ask about the
|
||||||
|
change in an issue. If you have the permissions, discuss it with at least one
|
||||||
|
other admin before making the change.
|
||||||
|
|
||||||
|
### Release process
|
||||||
|
|
||||||
Given that winit is a widely used library, we should be able to make a patch
|
Given that winit is a widely used library, we should be able to make a patch
|
||||||
releases at any time we want without blocking the development of new features.
|
releases at any time we want without blocking the development of new features.
|
||||||
@@ -58,7 +128,8 @@ The exact steps for an exemplary `0.2.0` release might look like this:
|
|||||||
1. Initially, the version on the latest master is `0.1.0`
|
1. Initially, the version on the latest master is `0.1.0`
|
||||||
2. A new `v0.2.x` branch is created for the release
|
2. A new `v0.2.x` branch is created for the release
|
||||||
3. Update released `cfg_attr` in `src/changelog/mod.rs` to `v0.2.md`
|
3. Update released `cfg_attr` in `src/changelog/mod.rs` to `v0.2.md`
|
||||||
4. Move entries from `src/changelog/unreleased.md` into `src/changelog/v0.2.md`
|
4. Move entries from `src/changelog/unreleased.md` into
|
||||||
|
`src/changelog/v0.2.md`
|
||||||
5. In the branch, the version is bumped to `v0.2.0`
|
5. In the branch, the version is bumped to `v0.2.0`
|
||||||
6. The new commit in the branch is tagged `v0.2.0`
|
6. The new commit in the branch is tagged `v0.2.0`
|
||||||
7. The version is pushed to crates.io
|
7. The version is pushed to crates.io
|
||||||
@@ -70,3 +141,5 @@ When doing a patch release, the process is similar:
|
|||||||
2. Checkout the `v0.2.x` branch
|
2. Checkout the `v0.2.x` branch
|
||||||
3. Cherry-pick the required non-breaking changes into the `v0.2.x`
|
3. Cherry-pick the required non-breaking changes into the `v0.2.x`
|
||||||
4. Follow steps 4-9 of the regular release example
|
4. Follow steps 4-9 of the regular release example
|
||||||
|
|
||||||
|
[CODEOWNERS]: .github/CODEOWNERS
|
||||||
|
|||||||
413
Cargo.toml
413
Cargo.toml
@@ -1,153 +1,209 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "winit"
|
|
||||||
version = "0.29.15"
|
|
||||||
authors = ["The winit contributors", "Pierre Krieger <pierre.krieger1708@gmail.com>"]
|
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"]
|
categories = ["gui"]
|
||||||
rust-version.workspace = true
|
description = "Cross-platform window creation library."
|
||||||
repository.workspace = true
|
documentation = "https://docs.rs/winit"
|
||||||
license.workspace = true
|
|
||||||
edition.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",
|
||||||
|
]
|
||||||
|
keywords = ["windowing"]
|
||||||
|
license.workspace = true
|
||||||
|
name = "winit"
|
||||||
|
readme = "README.md"
|
||||||
|
repository.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
version = "0.30.5"
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
features = [
|
features = [
|
||||||
"rwh_04",
|
|
||||||
"rwh_05",
|
|
||||||
"rwh_06",
|
|
||||||
"serde",
|
"serde",
|
||||||
"mint",
|
"mint",
|
||||||
# Enabled to get docs to compile
|
# Enabled to get docs to compile
|
||||||
"android-native-activity",
|
"android-native-activity",
|
||||||
]
|
]
|
||||||
# These are all tested in CI
|
# These are all tested in CI
|
||||||
|
rustdoc-args = ["--cfg", "docsrs"]
|
||||||
targets = [
|
targets = [
|
||||||
# Windows
|
# Windows
|
||||||
"i686-pc-windows-msvc",
|
"i686-pc-windows-msvc",
|
||||||
"x86_64-pc-windows-msvc",
|
"x86_64-pc-windows-msvc",
|
||||||
# macOS
|
# macOS
|
||||||
|
"aarch64-apple-darwin",
|
||||||
"x86_64-apple-darwin",
|
"x86_64-apple-darwin",
|
||||||
# Unix (X11 & Wayland)
|
# Unix (X11 & Wayland)
|
||||||
"i686-unknown-linux-gnu",
|
"i686-unknown-linux-gnu",
|
||||||
"x86_64-unknown-linux-gnu",
|
"x86_64-unknown-linux-gnu",
|
||||||
# iOS
|
# iOS
|
||||||
"x86_64-apple-ios",
|
"aarch64-apple-ios",
|
||||||
# Android
|
# Android
|
||||||
"aarch64-linux-android",
|
"aarch64-linux-android",
|
||||||
# Web
|
# Web
|
||||||
"wasm32-unknown-unknown",
|
"wasm32-unknown-unknown",
|
||||||
]
|
]
|
||||||
rustdoc-args = ["--cfg", "docsrs"]
|
|
||||||
|
|
||||||
# Features are documented in either `lib.rs` or under `winit::platform`.
|
# Features are documented in either `lib.rs` or under `winit::platform`.
|
||||||
[features]
|
[features]
|
||||||
default = ["rwh_06", "x11", "wayland", "wayland-dlopen", "wayland-csd-adwaita"]
|
android-game-activity = ["android-activity/game-activity"]
|
||||||
x11 = ["x11-dl", "bytemuck", "percent-encoding", "xkbcommon-dl/x11", "x11rb"]
|
android-native-activity = ["android-activity/native-activity"]
|
||||||
wayland = ["wayland-client", "wayland-backend", "wayland-protocols", "wayland-protocols-plasma", "sctk", "ahash", "memmap2"]
|
default = ["x11", "wayland", "wayland-dlopen", "wayland-csd-adwaita"]
|
||||||
wayland-dlopen = ["wayland-backend/dlopen"]
|
mint = ["dpi/mint"]
|
||||||
|
serde = ["dep:serde", "cursor-icon/serde", "smol_str/serde", "dpi/serde", "bitflags/serde"]
|
||||||
|
wayland = [
|
||||||
|
"wayland-client",
|
||||||
|
"wayland-backend",
|
||||||
|
"wayland-protocols",
|
||||||
|
"wayland-protocols-plasma",
|
||||||
|
"sctk",
|
||||||
|
"ahash",
|
||||||
|
"memmap2",
|
||||||
|
]
|
||||||
wayland-csd-adwaita = ["sctk-adwaita", "sctk-adwaita/ab_glyph"]
|
wayland-csd-adwaita = ["sctk-adwaita", "sctk-adwaita/ab_glyph"]
|
||||||
wayland-csd-adwaita-crossfont = ["sctk-adwaita", "sctk-adwaita/crossfont"]
|
wayland-csd-adwaita-crossfont = ["sctk-adwaita", "sctk-adwaita/crossfont"]
|
||||||
wayland-csd-adwaita-notitle = ["sctk-adwaita"]
|
wayland-csd-adwaita-notitle = ["sctk-adwaita"]
|
||||||
android-native-activity = ["android-activity/native-activity"]
|
wayland-dlopen = ["wayland-backend/dlopen"]
|
||||||
android-game-activity = ["android-activity/game-activity"]
|
x11 = ["x11-dl", "bytemuck", "percent-encoding", "xkbcommon-dl/x11", "x11rb"]
|
||||||
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"]
|
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
cfg_aliases = "0.2.0"
|
cfg_aliases = "0.2.1"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
bitflags = "2"
|
bitflags = "2"
|
||||||
cursor-icon = "1.1.0"
|
cursor-icon = "1.1.0"
|
||||||
dpi = { version = "0.1.1", path = "dpi" }
|
dpi = { version = "0.1.1", path = "dpi" }
|
||||||
rwh_04 = { package = "raw-window-handle", version = "0.4", optional = true }
|
rwh_06 = { package = "raw-window-handle", version = "0.6", features = ["std"] }
|
||||||
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 }
|
serde = { workspace = true, optional = true }
|
||||||
smol_str = "0.2.0"
|
smol_str = "0.3"
|
||||||
tracing = { version = "0.1.40", default_features = false }
|
tracing = { version = "0.1.40", default-features = false }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
image = { version = "0.24.0", default-features = false, features = ["png"] }
|
image = { version = "0.25.0", default-features = false, features = ["png"] }
|
||||||
tracing = { version = "0.1.40", default_features = false, features = ["log"] }
|
tracing = { version = "0.1.40", default-features = false, features = ["log"] }
|
||||||
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
|
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]
|
[target.'cfg(not(target_os = "android"))'.dev-dependencies]
|
||||||
softbuffer = { version = "0.3.0", default-features = false, features = ["x11", "x11-dlopen", "wayland", "wayland-dlopen"] }
|
softbuffer = { version = "0.4.6", default-features = false, features = [
|
||||||
|
"x11",
|
||||||
|
"x11-dlopen",
|
||||||
|
"wayland",
|
||||||
|
"wayland-dlopen",
|
||||||
|
] }
|
||||||
|
|
||||||
|
# Android
|
||||||
[target.'cfg(target_os = "android")'.dependencies]
|
[target.'cfg(target_os = "android")'.dependencies]
|
||||||
android-activity = "0.5.0"
|
android-activity = "0.6.0"
|
||||||
ndk = { version = "0.8.0", default-features = false }
|
ndk = { version = "0.9.0", features = ["rwh_06"], default-features = false }
|
||||||
ndk-sys = "0.5.0"
|
|
||||||
|
|
||||||
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
|
# AppKit or UIKit
|
||||||
|
[target.'cfg(target_vendor = "apple")'.dependencies]
|
||||||
|
block2 = "0.5.1"
|
||||||
core-foundation = "0.9.3"
|
core-foundation = "0.9.3"
|
||||||
objc2 = "0.5.0"
|
objc2 = "0.5.2"
|
||||||
|
|
||||||
|
# AppKit
|
||||||
[target.'cfg(target_os = "macos")'.dependencies]
|
[target.'cfg(target_os = "macos")'.dependencies]
|
||||||
core-graphics = "0.23.1"
|
core-graphics = "0.23.1"
|
||||||
|
objc2-app-kit = { version = "0.2.2", features = [
|
||||||
[target.'cfg(target_os = "macos")'.dependencies.icrate]
|
"NSAppearance",
|
||||||
version = "0.1.0"
|
"NSApplication",
|
||||||
features = [
|
"NSBitmapImageRep",
|
||||||
|
"NSButton",
|
||||||
|
"NSColor",
|
||||||
|
"NSControl",
|
||||||
|
"NSCursor",
|
||||||
|
"NSDragging",
|
||||||
|
"NSEvent",
|
||||||
|
"NSGraphics",
|
||||||
|
"NSGraphicsContext",
|
||||||
|
"NSImage",
|
||||||
|
"NSImageRep",
|
||||||
|
"NSMenu",
|
||||||
|
"NSMenuItem",
|
||||||
|
"NSOpenGLView",
|
||||||
|
"NSPasteboard",
|
||||||
|
"NSResponder",
|
||||||
|
"NSRunningApplication",
|
||||||
|
"NSScreen",
|
||||||
|
"NSTextInputClient",
|
||||||
|
"NSTextInputContext",
|
||||||
|
"NSToolbar",
|
||||||
|
"NSView",
|
||||||
|
"NSWindow",
|
||||||
|
"NSWindowScripting",
|
||||||
|
"NSWindowTabGroup",
|
||||||
|
] }
|
||||||
|
objc2-foundation = { version = "0.2.2", features = [
|
||||||
|
"block2",
|
||||||
"dispatch",
|
"dispatch",
|
||||||
"Foundation",
|
"NSArray",
|
||||||
"Foundation_NSArray",
|
"NSAttributedString",
|
||||||
"Foundation_NSAttributedString",
|
"NSData",
|
||||||
"Foundation_NSMutableAttributedString",
|
"NSDictionary",
|
||||||
"Foundation_NSData",
|
"NSDistributedNotificationCenter",
|
||||||
"Foundation_NSDictionary",
|
"NSEnumerator",
|
||||||
"Foundation_NSString",
|
"NSGeometry",
|
||||||
"Foundation_NSProcessInfo",
|
"NSKeyValueObserving",
|
||||||
"Foundation_NSThread",
|
"NSNotification",
|
||||||
"Foundation_NSNumber",
|
"NSObjCRuntime",
|
||||||
"AppKit",
|
"NSOperation",
|
||||||
"AppKit_NSAppearance",
|
"NSPathUtilities",
|
||||||
"AppKit_NSApplication",
|
"NSProcessInfo",
|
||||||
"AppKit_NSBitmapImageRep",
|
"NSRunLoop",
|
||||||
"AppKit_NSButton",
|
"NSString",
|
||||||
"AppKit_NSColor",
|
"NSThread",
|
||||||
"AppKit_NSControl",
|
"NSValue",
|
||||||
"AppKit_NSCursor",
|
] }
|
||||||
"AppKit_NSEvent",
|
|
||||||
"AppKit_NSGraphicsContext",
|
|
||||||
"AppKit_NSImage",
|
|
||||||
"AppKit_NSImageRep",
|
|
||||||
"AppKit_NSMenu",
|
|
||||||
"AppKit_NSMenuItem",
|
|
||||||
"AppKit_NSPasteboard",
|
|
||||||
"AppKit_NSResponder",
|
|
||||||
"AppKit_NSScreen",
|
|
||||||
"AppKit_NSTextInputContext",
|
|
||||||
"AppKit_NSView",
|
|
||||||
"AppKit_NSWindow",
|
|
||||||
"AppKit_NSWindowTabGroup",
|
|
||||||
]
|
|
||||||
|
|
||||||
[target.'cfg(target_os = "ios")'.dependencies.icrate]
|
# UIKit
|
||||||
version = "0.1.0"
|
[target.'cfg(all(target_vendor = "apple", not(target_os = "macos")))'.dependencies]
|
||||||
features = [
|
objc2-foundation = { version = "0.2.2", features = [
|
||||||
|
"block2",
|
||||||
"dispatch",
|
"dispatch",
|
||||||
"Foundation",
|
"NSArray",
|
||||||
"Foundation_NSArray",
|
"NSEnumerator",
|
||||||
"Foundation_NSString",
|
"NSGeometry",
|
||||||
"Foundation_NSProcessInfo",
|
"NSObjCRuntime",
|
||||||
"Foundation_NSThread",
|
"NSOperation",
|
||||||
"Foundation_NSSet",
|
"NSString",
|
||||||
]
|
"NSProcessInfo",
|
||||||
|
"NSThread",
|
||||||
|
"NSSet",
|
||||||
|
] }
|
||||||
|
objc2-ui-kit = { version = "0.2.2", features = [
|
||||||
|
"UIApplication",
|
||||||
|
"UIDevice",
|
||||||
|
"UIEvent",
|
||||||
|
"UIGeometry",
|
||||||
|
"UIGestureRecognizer",
|
||||||
|
"UITextInput",
|
||||||
|
"UITextInputTraits",
|
||||||
|
"UIOrientation",
|
||||||
|
"UIPanGestureRecognizer",
|
||||||
|
"UIPinchGestureRecognizer",
|
||||||
|
"UIResponder",
|
||||||
|
"UIRotationGestureRecognizer",
|
||||||
|
"UIScreen",
|
||||||
|
"UIScreenMode",
|
||||||
|
"UITapGestureRecognizer",
|
||||||
|
"UITouch",
|
||||||
|
"UITraitCollection",
|
||||||
|
"UIView",
|
||||||
|
"UIViewController",
|
||||||
|
"UIWindow",
|
||||||
|
] }
|
||||||
|
|
||||||
|
# Windows
|
||||||
[target.'cfg(target_os = "windows")'.dependencies]
|
[target.'cfg(target_os = "windows")'.dependencies]
|
||||||
unicode-segmentation = "1.7.1"
|
unicode-segmentation = "1.7.1"
|
||||||
|
windows-sys = { version = "0.52.0", features = [
|
||||||
[target.'cfg(target_os = "windows")'.dependencies.windows-sys]
|
|
||||||
version = "0.48"
|
|
||||||
features = [
|
|
||||||
"Win32_Devices_HumanInterfaceDevice",
|
"Win32_Devices_HumanInterfaceDevice",
|
||||||
"Win32_Foundation",
|
"Win32_Foundation",
|
||||||
"Win32_Globalization",
|
"Win32_Globalization",
|
||||||
@@ -158,6 +214,7 @@ features = [
|
|||||||
"Win32_System_Com",
|
"Win32_System_Com",
|
||||||
"Win32_System_LibraryLoader",
|
"Win32_System_LibraryLoader",
|
||||||
"Win32_System_Ole",
|
"Win32_System_Ole",
|
||||||
|
"Win32_Security",
|
||||||
"Win32_System_SystemInformation",
|
"Win32_System_SystemInformation",
|
||||||
"Win32_System_SystemServices",
|
"Win32_System_SystemServices",
|
||||||
"Win32_System_Threading",
|
"Win32_System_Threading",
|
||||||
@@ -172,114 +229,136 @@ features = [
|
|||||||
"Win32_UI_Shell",
|
"Win32_UI_Shell",
|
||||||
"Win32_UI_TextServices",
|
"Win32_UI_TextServices",
|
||||||
"Win32_UI_WindowsAndMessaging",
|
"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]
|
# Linux
|
||||||
|
[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_vendor = "apple"))))'.dependencies]
|
||||||
ahash = { version = "0.8.7", features = ["no-rng"], optional = true }
|
ahash = { version = "0.8.7", features = ["no-rng"], optional = true }
|
||||||
bytemuck = { version = "1.13.1", default-features = false, optional = true }
|
bytemuck = { version = "1.13.1", default-features = false, optional = true }
|
||||||
calloop = "0.12.3"
|
calloop = "0.13.0"
|
||||||
libc = "0.2.64"
|
libc = "0.2.64"
|
||||||
memmap2 = { version = "0.9.0", optional = true }
|
memmap2 = { version = "0.9.0", optional = true }
|
||||||
percent-encoding = { version = "2.0", optional = true }
|
percent-encoding = { version = "2.0", optional = true }
|
||||||
rustix = { version = "0.38.4", default-features = false, features = ["std", "system", "thread", "process"] }
|
rustix = { version = "0.38.4", default-features = false, features = [
|
||||||
sctk = { package = "smithay-client-toolkit", version = "0.18.0", default-features = false, features = ["calloop"], optional = true }
|
"std",
|
||||||
sctk-adwaita = { version = "0.8.0", default_features = false, optional = true }
|
"system",
|
||||||
wayland-backend = { version = "0.3.0", default_features = false, features = ["client_system"], optional = true }
|
"thread",
|
||||||
wayland-client = { version = "0.31.1", optional = true }
|
"process",
|
||||||
wayland-protocols = { version = "0.31.0", features = [ "staging"], optional = true }
|
] }
|
||||||
wayland-protocols-plasma = { version = "0.2.0", features = [ "client" ], optional = true }
|
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 }
|
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 }
|
x11rb = { version = "0.13.0", default-features = false, features = [
|
||||||
|
"allow-unsafe-code",
|
||||||
|
"cursor",
|
||||||
|
"dl-libxcb",
|
||||||
|
"randr",
|
||||||
|
"resource_manager",
|
||||||
|
"sync",
|
||||||
|
"xinput",
|
||||||
|
"xkb",
|
||||||
|
], optional = true }
|
||||||
xkbcommon-dl = "0.4.2"
|
xkbcommon-dl = "0.4.2"
|
||||||
|
|
||||||
|
# Orbital
|
||||||
[target.'cfg(target_os = "redox")'.dependencies]
|
[target.'cfg(target_os = "redox")'.dependencies]
|
||||||
orbclient = { version = "0.3.47", default-features = false }
|
orbclient = { version = "0.3.47", default-features = false }
|
||||||
redox_syscall = "0.4.1"
|
redox_syscall = "0.5.7"
|
||||||
|
|
||||||
[target.'cfg(target_family = "wasm")'.dependencies.web_sys]
|
|
||||||
package = "web-sys"
|
|
||||||
version = "0.3.64"
|
|
||||||
features = [
|
|
||||||
'AbortController',
|
|
||||||
'AbortSignal',
|
|
||||||
'Blob',
|
|
||||||
'console',
|
|
||||||
'CssStyleDeclaration',
|
|
||||||
'Document',
|
|
||||||
'DomException',
|
|
||||||
'DomRect',
|
|
||||||
'DomRectReadOnly',
|
|
||||||
'Element',
|
|
||||||
'Event',
|
|
||||||
'EventTarget',
|
|
||||||
'FocusEvent',
|
|
||||||
'HtmlCanvasElement',
|
|
||||||
'HtmlElement',
|
|
||||||
'HtmlImageElement',
|
|
||||||
'ImageBitmap',
|
|
||||||
'ImageBitmapOptions',
|
|
||||||
'ImageBitmapRenderingContext',
|
|
||||||
'ImageData',
|
|
||||||
'IntersectionObserver',
|
|
||||||
'IntersectionObserverEntry',
|
|
||||||
'KeyboardEvent',
|
|
||||||
'MediaQueryList',
|
|
||||||
'MessageChannel',
|
|
||||||
'MessagePort',
|
|
||||||
'Node',
|
|
||||||
'PageTransitionEvent',
|
|
||||||
'PointerEvent',
|
|
||||||
'PremultiplyAlpha',
|
|
||||||
'ResizeObserver',
|
|
||||||
'ResizeObserverBoxOptions',
|
|
||||||
'ResizeObserverEntry',
|
|
||||||
'ResizeObserverOptions',
|
|
||||||
'ResizeObserverSize',
|
|
||||||
'VisibilityState',
|
|
||||||
'Window',
|
|
||||||
'WheelEvent',
|
|
||||||
'Url',
|
|
||||||
]
|
|
||||||
|
|
||||||
|
# Web
|
||||||
[target.'cfg(target_family = "wasm")'.dependencies]
|
[target.'cfg(target_family = "wasm")'.dependencies]
|
||||||
js-sys = "0.3.64"
|
js-sys = "0.3.70"
|
||||||
pin-project = "1"
|
pin-project = "1"
|
||||||
wasm-bindgen = "0.2"
|
wasm-bindgen = "0.2.93"
|
||||||
wasm-bindgen-futures = "0.4"
|
wasm-bindgen-futures = "0.4.43"
|
||||||
web-time = "1"
|
web-time = "1"
|
||||||
|
web_sys = { package = "web-sys", version = "0.3.70", features = [
|
||||||
|
"AbortController",
|
||||||
|
"AbortSignal",
|
||||||
|
"Blob",
|
||||||
|
"BlobPropertyBag",
|
||||||
|
"console",
|
||||||
|
"CssStyleDeclaration",
|
||||||
|
"Document",
|
||||||
|
"DomException",
|
||||||
|
"DomRect",
|
||||||
|
"DomRectReadOnly",
|
||||||
|
"Element",
|
||||||
|
"Event",
|
||||||
|
"EventTarget",
|
||||||
|
"FocusEvent",
|
||||||
|
"HtmlCanvasElement",
|
||||||
|
"HtmlElement",
|
||||||
|
"HtmlHtmlElement",
|
||||||
|
"HtmlImageElement",
|
||||||
|
"ImageBitmap",
|
||||||
|
"ImageBitmapOptions",
|
||||||
|
"ImageBitmapRenderingContext",
|
||||||
|
"ImageData",
|
||||||
|
"IntersectionObserver",
|
||||||
|
"IntersectionObserverEntry",
|
||||||
|
"KeyboardEvent",
|
||||||
|
"MediaQueryList",
|
||||||
|
"MessageChannel",
|
||||||
|
"MessagePort",
|
||||||
|
"Navigator",
|
||||||
|
"Node",
|
||||||
|
"OrientationLockType",
|
||||||
|
"OrientationType",
|
||||||
|
"PageTransitionEvent",
|
||||||
|
"Permissions",
|
||||||
|
"PermissionState",
|
||||||
|
"PermissionStatus",
|
||||||
|
"PointerEvent",
|
||||||
|
"PremultiplyAlpha",
|
||||||
|
"ResizeObserver",
|
||||||
|
"ResizeObserverBoxOptions",
|
||||||
|
"ResizeObserverEntry",
|
||||||
|
"ResizeObserverOptions",
|
||||||
|
"ResizeObserverSize",
|
||||||
|
"Screen",
|
||||||
|
"ScreenOrientation",
|
||||||
|
"Url",
|
||||||
|
"VisibilityState",
|
||||||
|
"WheelEvent",
|
||||||
|
"Window",
|
||||||
|
"Worker",
|
||||||
|
] }
|
||||||
|
|
||||||
[target.'cfg(all(target_family = "wasm", target_feature = "atomics"))'.dependencies]
|
[target.'cfg(all(target_family = "wasm", target_feature = "atomics"))'.dependencies]
|
||||||
atomic-waker = "1"
|
atomic-waker = "1"
|
||||||
concurrent-queue = { version = "2", default-features = false }
|
concurrent-queue = { version = "2", default-features = false }
|
||||||
|
|
||||||
[target.'cfg(target_family = "wasm")'.dev-dependencies]
|
[target.'cfg(target_family = "wasm")'.dev-dependencies]
|
||||||
console_log = "1"
|
console_error_panic_hook = "0.1"
|
||||||
web-sys = { version = "0.3.22", features = ['CanvasRenderingContext2d'] }
|
tracing-web = "0.1"
|
||||||
|
wasm-bindgen-test = "0.3"
|
||||||
|
|
||||||
[[example]]
|
[[example]]
|
||||||
doc-scrape-examples = true
|
doc-scrape-examples = true
|
||||||
name = "window"
|
name = "window"
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
name = "child_window"
|
||||||
|
|
||||||
[workspace]
|
[workspace]
|
||||||
|
members = ["dpi"]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
members = [
|
|
||||||
"dpi",
|
|
||||||
"it/common-tests",
|
|
||||||
"it/gui-test",
|
|
||||||
"it/gui-test-runner",
|
|
||||||
"run-wasm",
|
|
||||||
]
|
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
rust-version = "1.70.0"
|
|
||||||
repository = "https://github.com/rust-windowing/winit"
|
|
||||||
license = "Apache-2.0"
|
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
license = "Apache-2.0"
|
||||||
|
repository = "https://github.com/rust-windowing/winit"
|
||||||
|
rust-version = "1.73"
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
async-io = "2.3.1"
|
|
||||||
gui-test = { path = "it/gui-test" }
|
|
||||||
mint = "0.5.6"
|
mint = "0.5.6"
|
||||||
serde = { version = "1", features = ["serde_derive"] }
|
serde = { version = "1", features = ["serde_derive"] }
|
||||||
serde_json = "1.0.114"
|
|
||||||
winit = { path = "." }
|
|
||||||
|
|||||||
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.
|
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
|
If that gets accepted, the platform-specific functions get deprecated and become permanently
|
||||||
exposed through the core, cross-platform API.
|
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
|
|
||||||
|
|||||||
15
README.md
15
README.md
@@ -2,13 +2,13 @@
|
|||||||
|
|
||||||
[](https://crates.io/crates/winit)
|
[](https://crates.io/crates/winit)
|
||||||
[](https://docs.rs/winit)
|
[](https://docs.rs/winit)
|
||||||
[](https://rust-windowing.github.io/winit/winit/index.html)
|
)](https://rust-windowing.github.io/winit/winit/index.html)
|
||||||
[](https://github.com/rust-windowing/winit/actions)
|
[](https://github.com/rust-windowing/winit/actions)
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[dependencies]
|
[dependencies]
|
||||||
winit = "0.29.15"
|
winit = "0.30.5"
|
||||||
```
|
```
|
||||||
|
|
||||||
## [Documentation](https://docs.rs/winit)
|
## [Documentation](https://docs.rs/winit)
|
||||||
@@ -19,7 +19,7 @@ For features _outside_ the scope of winit, see [Are we GUI Yet?](https://arewegu
|
|||||||
|
|
||||||
## Contact Us
|
## Contact Us
|
||||||
|
|
||||||
Join us in our [](https://matrix.to/#/#rust-windowing:matrix.org) room. If you don't get an answer there, try [](https://web.libera.chat/#winit).
|
Join us in our [](https://matrix.to/#/#rust-windowing:matrix.org) room.
|
||||||
|
|
||||||
The maintainers have a meeting every friday at UTC 15. The meeting notes can be found [here](https://hackmd.io/@winit-meetings).
|
The maintainers have a meeting every friday at UTC 15. The meeting notes can be found [here](https://hackmd.io/@winit-meetings).
|
||||||
|
|
||||||
@@ -35,7 +35,7 @@ another library.
|
|||||||
|
|
||||||
## MSRV Policy
|
## 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.73**. Changes to
|
||||||
the MSRV will be accompanied by a minor version bump.
|
the MSRV will be accompanied by a minor version bump.
|
||||||
|
|
||||||
As a **tentative** policy, the upper bound of the MSRV is given by the following
|
As a **tentative** policy, the upper bound of the MSRV is given by the following
|
||||||
@@ -50,12 +50,15 @@ Where `sid` is the current version of `rustc` provided by [Debian Sid], and
|
|||||||
|
|
||||||
[Debian Sid]: https://packages.debian.org/sid/rustc
|
[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
|
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
|
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
|
not reflected in Cargo metadata, as it is not powerful enough to expose this
|
||||||
restriction.
|
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
|
All crates in the [`rust-windowing`] organizations have the
|
||||||
same MSRV policy.
|
same MSRV policy.
|
||||||
|
|
||||||
@@ -63,4 +66,4 @@ same MSRV policy.
|
|||||||
|
|
||||||
### Platform-specific usage
|
### 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.
|
||||||
|
|||||||
12
build.rs
12
build.rs
@@ -1,19 +1,18 @@
|
|||||||
use cfg_aliases::cfg_aliases;
|
use cfg_aliases::cfg_aliases;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
// The script doesn't depend on our code
|
// The script doesn't depend on our code.
|
||||||
println!("cargo:rerun-if-changed=build.rs");
|
println!("cargo:rerun-if-changed=build.rs");
|
||||||
|
|
||||||
// Setup cfg aliases
|
// Setup cfg aliases.
|
||||||
cfg_aliases! {
|
cfg_aliases! {
|
||||||
// Systems.
|
// Systems.
|
||||||
android_platform: { target_os = "android" },
|
android_platform: { target_os = "android" },
|
||||||
web_platform: { all(target_family = "wasm", target_os = "unknown") },
|
web_platform: { all(target_family = "wasm", target_os = "unknown") },
|
||||||
macos_platform: { target_os = "macos" },
|
macos_platform: { target_os = "macos" },
|
||||||
ios_platform: { target_os = "ios" },
|
ios_platform: { all(target_vendor = "apple", not(target_os = "macos")) },
|
||||||
windows_platform: { target_os = "windows" },
|
windows_platform: { target_os = "windows" },
|
||||||
apple: { any(target_os = "ios", target_os = "macos") },
|
free_unix: { all(unix, not(target_vendor = "apple"), not(android_platform), not(target_os = "emscripten")) },
|
||||||
free_unix: { all(unix, not(apple), not(android_platform), not(target_os = "emscripten")) },
|
|
||||||
redox: { target_os = "redox" },
|
redox: { target_os = "redox" },
|
||||||
|
|
||||||
// Native displays.
|
// Native displays.
|
||||||
@@ -21,4 +20,7 @@ fn main() {
|
|||||||
wayland_platform: { all(feature = "wayland", free_unix, not(redox)) },
|
wayland_platform: { all(feature = "wayland", free_unix, not(redox)) },
|
||||||
orbital_platform: { redox },
|
orbital_platform: { redox },
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Winit defined cfgs.
|
||||||
|
println!("cargo:rustc-check-cfg=cfg(unreleased_changelogs)");
|
||||||
}
|
}
|
||||||
|
|||||||
23
clippy.toml
23
clippy.toml
@@ -1,15 +1,16 @@
|
|||||||
disallowed-methods = [
|
disallowed-methods = [
|
||||||
{ path = "web_sys::window", reason = "is not available in every context" },
|
{ 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 = "web_sys::HtmlCanvasElement::width", reason = "Winit shouldn't touch the internal canvas size" },
|
{ path = "objc2_app_kit::NSWindow::setFrameTopLeftPoint", reason = "Not sufficient when working with Winit's coordinate system, use `flip_window_screen_coordinates` instead" },
|
||||||
{ path = "web_sys::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::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 = "web_sys::Document::fullscreen_element", reason = "Doesn't account for compatibility with Safari" },
|
||||||
{ path = "icrate::AppKit::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 = "web_sys::Element::request_fullscreen", reason = "Doesn't account for compatibility with Safari" },
|
||||||
{ path = "icrate::AppKit::NSWindow::setFrameTopLeftPoint", reason = "Not sufficient when working with Winit's coordinate system, use `flip_window_screen_coordinates` instead" },
|
{ path = "web_sys::HtmlCanvasElement::height", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
|
{ path = "web_sys::HtmlCanvasElement::set_height", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
|
{ path = "web_sys::HtmlCanvasElement::set_width", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
|
{ path = "web_sys::HtmlCanvasElement::width", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
|
{ path = "web_sys::HtmlElement::style", reason = "cache this to reduce calls to JS" },
|
||||||
|
{ path = "web_sys::Window::document", reason = "cache this to reduce calls to JS" },
|
||||||
|
{ path = "web_sys::Window::get_computed_style", reason = "cache this to reduce calls to JS" },
|
||||||
|
{ path = "web_sys::Window::navigator", reason = "cache this to reduce calls to JS" },
|
||||||
|
{ path = "web_sys::window", reason = "is not available in every context" },
|
||||||
]
|
]
|
||||||
|
|||||||
87
deny.toml
87
deny.toml
@@ -1,15 +1,21 @@
|
|||||||
# https://embarkstudios.github.io/cargo-deny/
|
# https://embarkstudios.github.io/cargo-deny
|
||||||
# cargo install cargo-deny
|
# cargo install cargo-deny
|
||||||
# cargo update && cargo deny --all-features --log-level error --target aarch64-apple-ios check
|
# cargo update && cargo deny --target aarch64-apple-ios check
|
||||||
# Note: running just `cargo deny check` without a `--target` will result in
|
# Note: running just `cargo deny check` without a `--target` will result in
|
||||||
# false positives due to https://github.com/EmbarkStudios/cargo-deny/issues/324
|
# false positives due to https://github.com/EmbarkStudios/cargo-deny/issues/324
|
||||||
|
[graph]
|
||||||
|
all-features = true
|
||||||
|
exclude-dev = true
|
||||||
targets = [
|
targets = [
|
||||||
|
{ triple = "aarch64-apple-darwin" },
|
||||||
{ triple = "aarch64-apple-ios" },
|
{ triple = "aarch64-apple-ios" },
|
||||||
{ triple = "aarch64-linux-android" },
|
{ triple = "aarch64-linux-android" },
|
||||||
{ triple = "i686-pc-windows-gnu" },
|
{ triple = "i686-pc-windows-gnu" },
|
||||||
{ triple = "i686-pc-windows-msvc" },
|
{ triple = "i686-pc-windows-msvc" },
|
||||||
{ triple = "i686-unknown-linux-gnu" },
|
{ triple = "i686-unknown-linux-gnu" },
|
||||||
{ triple = "wasm32-unknown-unknown" },
|
{ triple = "wasm32-unknown-unknown", features = [
|
||||||
|
"atomics",
|
||||||
|
] },
|
||||||
{ triple = "x86_64-apple-darwin" },
|
{ triple = "x86_64-apple-darwin" },
|
||||||
{ triple = "x86_64-apple-ios" },
|
{ triple = "x86_64-apple-ios" },
|
||||||
{ triple = "x86_64-pc-windows-gnu" },
|
{ triple = "x86_64-pc-windows-gnu" },
|
||||||
@@ -18,46 +24,49 @@ targets = [
|
|||||||
{ triple = "x86_64-unknown-redox" },
|
{ triple = "x86_64-unknown-redox" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[licenses]
|
||||||
[advisories]
|
allow = [
|
||||||
vulnerability = "deny"
|
"Apache-2.0", # https://tldrlegal.com/license/apache-license-2.0-(apache-2.0)
|
||||||
unmaintained = "warn"
|
"BSD-2-Clause", # https://tldrlegal.com/license/bsd-2-clause-license-(freebsd)
|
||||||
yanked = "deny"
|
"BSD-3-Clause", # https://tldrlegal.com/license/bsd-3-clause-license-(revised)
|
||||||
ignore = []
|
"ISC", # https://tldrlegal.com/license/isc-license
|
||||||
|
"MIT", # https://tldrlegal.com/license/mit-license
|
||||||
|
"Unicode-3.0", # https://spdx.org/licenses/Unicode-3.0.html
|
||||||
|
]
|
||||||
|
confidence-threshold = 1.0
|
||||||
|
private = { ignore = true }
|
||||||
|
|
||||||
[bans]
|
[bans]
|
||||||
multiple-versions = "deny"
|
multiple-versions = "deny"
|
||||||
wildcards = "allow" # at least until https://github.com/EmbarkStudios/cargo-deny/issues/241 is fixed
|
skip = [{ crate = "bitflags@1", reason = "the ecosystem is in the process of migrating" }]
|
||||||
deny = []
|
wildcards = "allow" # at least until https://github.com/EmbarkStudios/cargo-deny/issues/241 is fixed
|
||||||
skip = [
|
|
||||||
{ name = "raw-window-handle" }, # we intentionally have multiple versions of this
|
|
||||||
{ name = "bitflags" }, # the ecosystem is in the process of migrating.
|
|
||||||
{ name = "libloading" }, # x11rb uses a different version until the next update
|
|
||||||
]
|
|
||||||
skip-tree = []
|
|
||||||
|
|
||||||
|
[bans.build]
|
||||||
|
include-archives = true
|
||||||
|
interpreted = "deny"
|
||||||
|
|
||||||
[licenses]
|
[[bans.build.bypass]]
|
||||||
private = { ignore = true }
|
|
||||||
unlicensed = "deny"
|
|
||||||
allow-osi-fsf-free = "neither"
|
|
||||||
confidence-threshold = 0.92 # We want really high confidence when inferring licenses from text
|
|
||||||
copyleft = "deny"
|
|
||||||
allow = [
|
allow = [
|
||||||
"Apache-2.0 WITH LLVM-exception", # https://spdx.org/licenses/LLVM-exception.html
|
{ path = "generate-bindings.sh", checksum = "268ec23248218d779e33853cdc60e2985e70214ff004716cd734270de1f6b561" },
|
||||||
"Apache-2.0", # https://tldrlegal.com/license/apache-license-2.0-(apache-2.0)
|
|
||||||
"BSD-2-Clause", # https://tldrlegal.com/license/bsd-2-clause-license-(freebsd)
|
|
||||||
"BSD-3-Clause", # https://tldrlegal.com/license/bsd-3-clause-license-(revised)
|
|
||||||
"BSL-1.0", # https://tldrlegal.com/license/boost-software-license-1.0-explained
|
|
||||||
"CC0-1.0", # https://creativecommons.org/publicdomain/zero/1.0/
|
|
||||||
"ISC", # https://tldrlegal.com/license/-isc-license
|
|
||||||
"LicenseRef-UFL-1.0", # https://tldrlegal.com/license/ubuntu-font-license,-1.0 - no official SPDX, see https://github.com/emilk/egui/issues/2321
|
|
||||||
"MIT-0", # https://choosealicense.com/licenses/mit-0/
|
|
||||||
"MIT", # https://tldrlegal.com/license/mit-license
|
|
||||||
"MPL-2.0", # https://www.mozilla.org/en-US/MPL/2.0/FAQ/ - see Q11. Used by webpki-roots on Linux.
|
|
||||||
"OFL-1.1", # https://spdx.org/licenses/OFL-1.1.html
|
|
||||||
"OpenSSL", # https://www.openssl.org/source/license.html - used on Linux
|
|
||||||
"Unicode-DFS-2016", # https://spdx.org/licenses/Unicode-DFS-2016.html
|
|
||||||
"Zlib", # https://tldrlegal.com/license/zlib-libpng-license-(zlib)
|
|
||||||
]
|
]
|
||||||
|
crate = "android-activity"
|
||||||
|
|
||||||
|
[[bans.build.bypass]]
|
||||||
|
allow-globs = ["freetype2/*"]
|
||||||
|
crate = "freetype-sys"
|
||||||
|
|
||||||
|
[[bans.build.bypass]]
|
||||||
|
allow-globs = ["lib/*.a"]
|
||||||
|
crate = "windows_i686_gnu"
|
||||||
|
|
||||||
|
[[bans.build.bypass]]
|
||||||
|
allow-globs = ["lib/*.lib"]
|
||||||
|
crate = "windows_i686_msvc"
|
||||||
|
|
||||||
|
[[bans.build.bypass]]
|
||||||
|
allow-globs = ["lib/*.a"]
|
||||||
|
crate = "windows_x86_64_gnu"
|
||||||
|
|
||||||
|
[[bans.build.bypass]]
|
||||||
|
allow-globs = ["lib/*.lib"]
|
||||||
|
crate = "windows_x86_64_msvc"
|
||||||
|
|||||||
@@ -1,40 +0,0 @@
|
|||||||
# syntax=docker/dockerfile:1
|
|
||||||
# Copyright 2024 The Winit Contributors
|
|
||||||
#
|
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
# you may not use this file except in compliance with the License.
|
|
||||||
# You may obtain a copy of the License at
|
|
||||||
#
|
|
||||||
# http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
#
|
|
||||||
# Unless required by applicable law or agreed to in writing, software
|
|
||||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
# See the License for the specific language governing permissions and
|
|
||||||
# limitations under the License.
|
|
||||||
|
|
||||||
ARG DISTRO=ubuntu
|
|
||||||
ARG DISTRO_VERSION=22.04
|
|
||||||
|
|
||||||
FROM "${DISTRO}":"${DISTRO_VERSION}"
|
|
||||||
SHELL ["/bin/bash", "-eEuxo", "pipefail", "-c"]
|
|
||||||
ARG DEBIAN_FRONTEND=noninteractive
|
|
||||||
|
|
||||||
RUN \
|
|
||||||
apt-get -o Acquire::Retries=10 -qq update && \
|
|
||||||
apt-get -o Acquire::Retries=10 -o Dpkg::Use-Pty=0 install -y --no-install-recommends \
|
|
||||||
cargo \
|
|
||||||
ca-certificates \
|
|
||||||
libx11-dev \
|
|
||||||
libxcursor-dev \
|
|
||||||
libxcb1-dev \
|
|
||||||
libxi-dev \
|
|
||||||
libxkbcommon-dev \
|
|
||||||
libxkbcommon-x11-dev \
|
|
||||||
xvfb && \
|
|
||||||
rm -rf \
|
|
||||||
/var/lib/apt/lists/* \
|
|
||||||
/var/cache/* \
|
|
||||||
/var/log/* \
|
|
||||||
/usr/share/{doc,man}
|
|
||||||
|
|
||||||
@@ -9,3 +9,10 @@ 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)
|
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),
|
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.
|
which have been released under the same license as a derivative work.
|
||||||
|
|
||||||
|
## `coordinate-systems*`
|
||||||
|
|
||||||
|
These files are created by [Mads Marquart](https://github.com/madsmtm) using
|
||||||
|
[draw.io](https://draw.io/), and compressed using [svgomg.net](https://svgomg.net/).
|
||||||
|
|
||||||
|
They are licensed under the [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/) license.
|
||||||
130
docs/coordinate-systems.drawio
Normal file
130
docs/coordinate-systems.drawio
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
<mxfile host="app.diagrams.net" agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:132.0) Gecko/20100101 Firefox/132.0" version="24.8.6" pages="2">
|
||||||
|
<diagram name="desktop" id="3DDum1nDijUk3y7wIDRm">
|
||||||
|
<mxGraphModel dx="1080" dy="707" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1000" pageHeight="500" math="0" shadow="0">
|
||||||
|
<root>
|
||||||
|
<mxCell id="0" />
|
||||||
|
<mxCell id="1" parent="0" />
|
||||||
|
<mxCell id="cRYnzpdCW-J0f_YpP3mc-1" value="" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#E8E8E8;fontColor=#333333;strokeColor=#666666;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="200" y="80" width="480" height="360" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="cRYnzpdCW-J0f_YpP3mc-4" value="" style="rounded=1;whiteSpace=wrap;html=1;shadow=0;fillColor=#d5e8d4;strokeColor=#666666;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="260" y="340" width="360" height="40" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="cRYnzpdCW-J0f_YpP3mc-2" value="" style="rounded=1;whiteSpace=wrap;html=1;shadow=0;fillColor=#dae8fc;strokeColor=#666666;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="260" y="140" width="360" height="80" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="cRYnzpdCW-J0f_YpP3mc-3" value="" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#DBDBDB;strokeColor=#666666;fontColor=#333333;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="200" y="60" width="480" height="20" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="cRYnzpdCW-J0f_YpP3mc-5" value="" style="rounded=0;whiteSpace=wrap;html=1;strokeColor=none;fillColor=#d5e8d4;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="260" y="180" width="360" height="180" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="cRYnzpdCW-J0f_YpP3mc-6" value="" style="endArrow=none;html=1;rounded=0;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;strokeColor=#666666;" parent="1" source="cRYnzpdCW-J0f_YpP3mc-4" target="cRYnzpdCW-J0f_YpP3mc-2" edge="1">
|
||||||
|
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||||
|
<mxPoint x="10" y="310" as="sourcePoint" />
|
||||||
|
<mxPoint x="60" y="260" as="targetPoint" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="cRYnzpdCW-J0f_YpP3mc-7" value="" style="endArrow=none;html=1;rounded=0;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=1;entryY=0.5;entryDx=0;entryDy=0;strokeColor=#666666;" parent="1" source="cRYnzpdCW-J0f_YpP3mc-4" target="cRYnzpdCW-J0f_YpP3mc-2" edge="1">
|
||||||
|
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||||
|
<mxPoint x="770" y="570" as="sourcePoint" />
|
||||||
|
<mxPoint x="770" y="210" as="targetPoint" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="cRYnzpdCW-J0f_YpP3mc-8" value="" style="endArrow=none;html=1;rounded=0;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=1;entryY=0;entryDx=0;entryDy=0;strokeColor=#666666;" parent="1" source="cRYnzpdCW-J0f_YpP3mc-2" target="cRYnzpdCW-J0f_YpP3mc-5" edge="1">
|
||||||
|
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||||
|
<mxPoint x="220.00000000000023" y="179.69" as="sourcePoint" />
|
||||||
|
<mxPoint x="740.0000000000002" y="179.69" as="targetPoint" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="cRYnzpdCW-J0f_YpP3mc-9" value="<font>outer_position</font>" style="endArrow=blockThin;html=1;strokeWidth=3;rounded=0;exitX=0;exitY=0;exitDx=0;exitDy=0;dashed=1;align=right;fontSize=20;fontFamily=monospace;fontColor=#6C8EBF;labelBackgroundColor=none;spacingLeft=0;spacingRight=15;spacing=0;fillColor=#dae8fc;strokeColor=#6C8EBF;endFill=1;startArrow=oval;startFill=1;endSize=6;targetPerimeterSpacing=0;entryX=0;entryY=0;entryDx=0;entryDy=0;" parent="1" source="cRYnzpdCW-J0f_YpP3mc-3" edge="1" target="cRYnzpdCW-J0f_YpP3mc-2">
|
||||||
|
<mxGeometry x="-0.36" y="-24" width="50" height="50" relative="1" as="geometry">
|
||||||
|
<mxPoint x="80" y="160" as="sourcePoint" />
|
||||||
|
<mxPoint x="240" y="160" as="targetPoint" />
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="cRYnzpdCW-J0f_YpP3mc-10" value="<font>outer_size</font>" style="endArrow=none;html=1;strokeWidth=3;rounded=0;dashed=1;align=left;fontSize=20;fontFamily=monospace;fontColor=#6C8EBF;labelBackgroundColor=none;spacingLeft=15;spacingRight=0;spacing=0;exitX=1;exitY=0;exitDx=0;exitDy=0;fillColor=#dae8fc;strokeColor=#6c8ebf;entryX=1;entryY=1;entryDx=0;entryDy=0;" parent="1" source="cRYnzpdCW-J0f_YpP3mc-2" edge="1" target="cRYnzpdCW-J0f_YpP3mc-4">
|
||||||
|
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||||
|
<mxPoint x="850" y="170" as="sourcePoint" />
|
||||||
|
<mxPoint x="760" y="420" as="targetPoint" />
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="860" y="140" />
|
||||||
|
<mxPoint x="860" y="380" />
|
||||||
|
</Array>
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="cRYnzpdCW-J0f_YpP3mc-11" value="<font>surface_size</font>" style="endArrow=none;html=1;strokeWidth=3;rounded=0;dashed=1;align=left;fontSize=20;fontFamily=monospace;fontColor=#82B366;labelBackgroundColor=none;spacingLeft=15;spacingRight=0;spacing=0;entryX=1;entryY=1;entryDx=0;entryDy=0;fillColor=#d5e8d4;strokeColor=#82B366;" parent="1" target="cRYnzpdCW-J0f_YpP3mc-4" edge="1">
|
||||||
|
<mxGeometry x="0.0526" width="50" height="50" relative="1" as="geometry">
|
||||||
|
<mxPoint x="600" y="180" as="sourcePoint" />
|
||||||
|
<mxPoint x="760" y="420" as="targetPoint" />
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="700" y="180" />
|
||||||
|
<mxPoint x="700" y="380" />
|
||||||
|
</Array>
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="cRYnzpdCW-J0f_YpP3mc-12" value="<font>surface_position</font>" style="endArrow=blockThin;html=1;strokeWidth=3;rounded=0;dashed=1;align=right;fontSize=20;fontFamily=monospace;fontColor=#82B366;labelBackgroundColor=none;spacingLeft=0;spacingRight=15;spacing=0;fillColor=#d5e8d4;strokeColor=#82b366;exitX=0;exitY=0;exitDx=0;exitDy=0;entryX=0;entryY=0;entryDx=0;entryDy=0;curved=1;startArrow=oval;startFill=1;endFill=1;" parent="1" source="cRYnzpdCW-J0f_YpP3mc-2" target="cRYnzpdCW-J0f_YpP3mc-5" edge="1">
|
||||||
|
<mxGeometry y="-50" width="50" height="50" relative="1" as="geometry">
|
||||||
|
<mxPoint x="140" y="140" as="sourcePoint" />
|
||||||
|
<mxPoint x="160" y="200" as="targetPoint" />
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="250" y="160" />
|
||||||
|
</Array>
|
||||||
|
<mxPoint x="-5" y="-22" as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
</root>
|
||||||
|
</mxGraphModel>
|
||||||
|
</diagram>
|
||||||
|
<diagram name="mobile" id="D5mAeJSS4Z33KEKjPCBt">
|
||||||
|
<mxGraphModel dx="1710" dy="1120" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="720" pageHeight="720" math="0" shadow="0">
|
||||||
|
<root>
|
||||||
|
<mxCell id="0" />
|
||||||
|
<mxCell id="1" parent="0" />
|
||||||
|
<mxCell id="RxwCrVmIsQwV7z5iJ9nY-1" value="" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#E8E8E8;fontColor=#333333;strokeColor=#666666;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="200" y="40" width="320" height="640" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="RxwCrVmIsQwV7z5iJ9nY-2" value="" style="rounded=1;whiteSpace=wrap;html=1;shadow=0;fillColor=#d5e8d4;strokeColor=#82b366;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="210" y="50" width="300" height="620" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="RxwCrVmIsQwV7z5iJ9nY-4" value="" style="rounded=0;whiteSpace=wrap;html=1;shadow=0;fillColor=#ffe6cc;strokeColor=#d79b00;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="210" y="90" width="300" height="540" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="RxwCrVmIsQwV7z5iJ9nY-20" value="" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#DBDBDB;strokeColor=#666666;fontColor=#333333;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="290" y="640" width="140" height="10" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="RxwCrVmIsQwV7z5iJ9nY-3" value="" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#DBDBDB;strokeColor=#666666;fontColor=#333333;" parent="1" vertex="1">
|
||||||
|
<mxGeometry x="300" y="50" width="120" height="30" as="geometry" />
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="RxwCrVmIsQwV7z5iJ9nY-12" value="<font>surface_size</font>" style="endArrow=none;html=1;strokeWidth=3;rounded=0;dashed=1;align=left;fontSize=20;fontFamily=monospace;fontColor=#82B366;labelBackgroundColor=none;spacingLeft=15;spacingRight=15;spacing=0;fillColor=#d5e8d4;strokeColor=#82b366;exitX=1;exitY=0;exitDx=0;exitDy=0;" parent="1" source="RxwCrVmIsQwV7z5iJ9nY-2" edge="1">
|
||||||
|
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||||
|
<mxPoint x="210" y="50" as="sourcePoint" />
|
||||||
|
<mxPoint x="510" y="670" as="targetPoint" />
|
||||||
|
<Array as="points">
|
||||||
|
<mxPoint x="560" y="50" />
|
||||||
|
<mxPoint x="560" y="670" />
|
||||||
|
</Array>
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="NrHAzeOh65jb3hkBOxW9-1" value="<div>safe_area.top</div>" style="endArrow=blockThin;html=1;strokeWidth=3;rounded=0;align=right;fontSize=20;fontFamily=monospace;fontColor=#D79B00;labelBackgroundColor=none;spacingLeft=0;spacingRight=15;spacing=0;fillColor=#ffe6cc;strokeColor=#d79b00;startArrow=blockThin;startFill=1;endFill=1;" edge="1" parent="1">
|
||||||
|
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||||
|
<mxPoint x="180" y="50" as="sourcePoint" />
|
||||||
|
<mxPoint x="180" y="90" as="targetPoint" />
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
<mxCell id="NrHAzeOh65jb3hkBOxW9-5" value="<div>safe_area.bottom</div>" style="endArrow=blockThin;html=1;strokeWidth=3;rounded=0;align=right;fontSize=20;fontFamily=monospace;fontColor=#D79B00;labelBackgroundColor=none;spacingLeft=0;spacingRight=15;spacing=0;fillColor=#ffe6cc;strokeColor=#d79b00;startArrow=blockThin;startFill=1;endFill=1;" edge="1" parent="1">
|
||||||
|
<mxGeometry width="50" height="50" relative="1" as="geometry">
|
||||||
|
<mxPoint x="180" y="670" as="sourcePoint" />
|
||||||
|
<mxPoint x="180" y="630" as="targetPoint" />
|
||||||
|
<mxPoint as="offset" />
|
||||||
|
</mxGeometry>
|
||||||
|
</mxCell>
|
||||||
|
</root>
|
||||||
|
</mxGraphModel>
|
||||||
|
</diagram>
|
||||||
|
</mxfile>
|
||||||
1
docs/res/coordinate-systems-desktop.svg
Normal file
1
docs/res/coordinate-systems-desktop.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 5.9 KiB |
1
docs/res/coordinate-systems-mobile.svg
Normal file
1
docs/res/coordinate-systems-mobile.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="720" height="720" viewBox="-0.5 -0.5 720 720" class="ge-export-svg-auto"><defs><style><![CDATA[@media (prefers-color-scheme:dark){svg.ge-export-svg-auto svg:not(mjx-container>svg),svg.ge-export-svg-auto:not(mjx-container>svg){filter:invert(100%) hue-rotate(180deg)}}]]></style></defs><g data-cell-id="0"><g data-cell-id="1"><rect x="200" y="40" width="320" height="640" rx="48" ry="48" fill="#e8e8e8" stroke="#666" pointer-events="all" data-cell-id="RxwCrVmIsQwV7z5iJ9nY-1"/><rect x="210" y="50" width="300" height="620" rx="45" ry="45" fill="#d5e8d4" stroke="#82b366" pointer-events="all" data-cell-id="RxwCrVmIsQwV7z5iJ9nY-2"/><path fill="#ffe6cc" stroke="#d79b00" pointer-events="all" d="M210 90h300v540H210z" data-cell-id="RxwCrVmIsQwV7z5iJ9nY-4"/><rect x="290" y="640" width="140" height="10" rx="1.5" ry="1.5" fill="#dbdbdb" stroke="#666" pointer-events="all" data-cell-id="RxwCrVmIsQwV7z5iJ9nY-20"/><rect x="300" y="50" width="120" height="30" rx="4.5" ry="4.5" fill="#dbdbdb" stroke="#666" pointer-events="all" data-cell-id="RxwCrVmIsQwV7z5iJ9nY-3"/><g data-cell-id="RxwCrVmIsQwV7z5iJ9nY-12"><path d="M510 50h50v620h-50" fill="none" stroke="#82b366" stroke-width="3" stroke-miterlimit="10" stroke-dasharray="9 9" pointer-events="stroke"/><switch transform="translate(-.5 -.5)"><foreignObject style="overflow:visible;text-align:left" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;align-items:unsafe center;justify-content:unsafe flex-start;width:1px;height:1px;padding-top:360px;margin-left:575px"><div style="box-sizing:border-box;font-size:0;text-align:left" data-drawio-colors="color: #82B366;"><div style="display:inline-block;font-size:20px;font-family:"monospace";color:#82b366;line-height:1.2;pointer-events:all;white-space:nowrap"><font>surface_size</font></div></div></div></foreignObject><text x="575" y="366" fill="#82B366" font-family=""monospace"" font-size="20">surfa...</text></switch></g><g data-cell-id="NrHAzeOh65jb3hkBOxW9-1"><path d="M180 62.35v15.3" fill="none" stroke="#d79b00" stroke-width="3" stroke-miterlimit="10" pointer-events="stroke"/><path d="m180 53.35 3 9h-6ZM180 86.65l-3-9h6Z" fill="#d79b00" stroke="#d79b00" stroke-width="3" stroke-miterlimit="10" pointer-events="all"/><switch transform="translate(-.5 -.5)"><foreignObject style="overflow:visible;text-align:left" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;align-items:unsafe center;justify-content:unsafe flex-end;width:1px;height:1px;padding-top:70px;margin-left:165px"><div style="box-sizing:border-box;font-size:0;text-align:right" data-drawio-colors="color: #D79B00;"><div style="display:inline-block;font-size:20px;font-family:"monospace";color:#d79b00;line-height:1.2;pointer-events:all;white-space:nowrap"><div>safe_area.top</div></div></div></div></foreignObject><text x="165" y="76" fill="#D79B00" font-family=""monospace"" font-size="20" text-anchor="end">safe_...</text></switch></g><g data-cell-id="NrHAzeOh65jb3hkBOxW9-5"><path d="M180 657.65v-15.3" fill="none" stroke="#d79b00" stroke-width="3" stroke-miterlimit="10" pointer-events="stroke"/><path d="m180 666.65-3-9h6ZM180 633.35l3 9h-6Z" fill="#d79b00" stroke="#d79b00" stroke-width="3" stroke-miterlimit="10" pointer-events="all"/><switch transform="translate(-.5 -.5)"><foreignObject style="overflow:visible;text-align:left" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display:flex;align-items:unsafe center;justify-content:unsafe flex-end;width:1px;height:1px;padding-top:650px;margin-left:165px"><div style="box-sizing:border-box;font-size:0;text-align:right" data-drawio-colors="color: #D79B00;"><div style="display:inline-block;font-size:20px;font-family:"monospace";color:#d79b00;line-height:1.2;pointer-events:all;white-space:nowrap"><div>safe_area.bottom</div></div></div></div></foreignObject><text x="165" y="656" fill="#D79B00" font-family=""monospace"" font-size="20" text-anchor="end">safe_...</text></switch></g></g></g></svg>
|
||||||
|
After Width: | Height: | Size: 4.3 KiB |
@@ -11,6 +11,8 @@ Unreleased` header.
|
|||||||
|
|
||||||
## Unreleased
|
## Unreleased
|
||||||
|
|
||||||
|
- Added `Insets`, `LogicalInsets` and `PhysicalInsets` types.
|
||||||
|
|
||||||
## 0.1.1
|
## 0.1.1
|
||||||
|
|
||||||
- Derive `Debug`, `Copy`, `Clone`, `PartialEq`, `Serialize`, `Deserialize` traits for `PixelUnit`.
|
- Derive `Debug`, `Copy`, `Clone`, `PartialEq`, `Serialize`, `Deserialize` traits for `PixelUnit`.
|
||||||
|
|||||||
@@ -1,39 +1,40 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "dpi"
|
|
||||||
version = "0.1.1"
|
|
||||||
description = "Types for handling UI scaling"
|
|
||||||
keywords = ["DPI", "HiDPI", "scale-factor"]
|
|
||||||
categories = ["gui"]
|
categories = ["gui"]
|
||||||
rust-version.workspace = true
|
description = "Types for handling UI scaling"
|
||||||
repository.workspace = true
|
|
||||||
license.workspace = true
|
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
|
keywords = ["DPI", "HiDPI", "scale-factor"]
|
||||||
|
license.workspace = true
|
||||||
|
name = "dpi"
|
||||||
|
repository.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
version = "0.1.1"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
serde = ["dep:serde"]
|
|
||||||
mint = ["dep:mint"]
|
mint = ["dep:mint"]
|
||||||
|
serde = ["dep:serde"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
serde = { workspace = true, optional = true }
|
|
||||||
mint = { workspace = true, optional = true }
|
mint = { workspace = true, optional = true }
|
||||||
|
serde = { workspace = true, optional = true }
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
features = ["serde", "mint"]
|
features = ["mint", "serde"]
|
||||||
# These are all tested in CI
|
# These are all tested in CI
|
||||||
|
rustdoc-args = ["--cfg", "docsrs"]
|
||||||
targets = [
|
targets = [
|
||||||
# Windows
|
# Windows
|
||||||
"i686-pc-windows-msvc",
|
"i686-pc-windows-msvc",
|
||||||
"x86_64-pc-windows-msvc",
|
"x86_64-pc-windows-msvc",
|
||||||
# macOS
|
# macOS
|
||||||
|
"aarch64-apple-darwin",
|
||||||
"x86_64-apple-darwin",
|
"x86_64-apple-darwin",
|
||||||
# Unix (X11 & Wayland)
|
# Unix (X11 & Wayland)
|
||||||
"i686-unknown-linux-gnu",
|
"i686-unknown-linux-gnu",
|
||||||
"x86_64-unknown-linux-gnu",
|
"x86_64-unknown-linux-gnu",
|
||||||
# iOS
|
# iOS
|
||||||
"x86_64-apple-ios",
|
"aarch64-apple-ios",
|
||||||
# Android
|
# Android
|
||||||
"aarch64-linux-android",
|
"aarch64-linux-android",
|
||||||
# Web
|
# Web
|
||||||
"wasm32-unknown-unknown",
|
"wasm32-unknown-unknown",
|
||||||
]
|
]
|
||||||
rustdoc-args = ["--cfg", "docsrs"]
|
|
||||||
|
|||||||
282
dpi/src/lib.rs
282
dpi/src/lib.rs
@@ -35,9 +35,9 @@
|
|||||||
//!
|
//!
|
||||||
//! ### Position and Size types
|
//! ### Position and Size types
|
||||||
//!
|
//!
|
||||||
//! The [`PhysicalPosition`] / [`PhysicalSize`] / [`PhysicalUnit`] types correspond with the actual pixels on the
|
//! The [`PhysicalPosition`] / [`PhysicalSize`] / [`PhysicalUnit`] types correspond with the actual
|
||||||
//! device, and the [`LogicalPosition`] / [`LogicalSize`] / [`LogicalUnit`] types correspond to the physical pixels
|
//! pixels on the device, and the [`LogicalPosition`] / [`LogicalSize`] / [`LogicalUnit`] types
|
||||||
//! divided by the scale factor.
|
//! correspond to the physical pixels divided by the scale factor.
|
||||||
//!
|
//!
|
||||||
//! The position and size types are generic over their exact pixel type, `P`, to allow the
|
//! The position and size types are generic over their exact pixel type, `P`, to allow the
|
||||||
//! API to have integer precision where appropriate (e.g. most window manipulation functions) and
|
//! API to have integer precision where appropriate (e.g. most window manipulation functions) and
|
||||||
@@ -52,19 +52,14 @@
|
|||||||
//!
|
//!
|
||||||
//! This crate provides the following Cargo features:
|
//! This crate provides the following Cargo features:
|
||||||
//!
|
//!
|
||||||
//! * `serde`: Enables serialization/deserialization of certain types with
|
//! * `serde`: Enables serialization/deserialization of certain types with [Serde](https://crates.io/crates/serde).
|
||||||
//! [Serde](https://crates.io/crates/serde).
|
|
||||||
//! * `mint`: Enables mint (math interoperability standard types) conversions.
|
//! * `mint`: Enables mint (math interoperability standard types) conversions.
|
||||||
//!
|
//!
|
||||||
//!
|
//!
|
||||||
//! [points]: https://en.wikipedia.org/wiki/Point_(typography)
|
//! [points]: https://en.wikipedia.org/wiki/Point_(typography)
|
||||||
//! [picas]: https://en.wikipedia.org/wiki/Pica_(typography)
|
//! [picas]: https://en.wikipedia.org/wiki/Pica_(typography)
|
||||||
|
|
||||||
#![cfg_attr(
|
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide), doc(cfg_hide(doc, docsrs)))]
|
||||||
docsrs,
|
|
||||||
feature(doc_auto_cfg, doc_cfg_hide),
|
|
||||||
doc(cfg_hide(doc, docsrs))
|
|
||||||
)]
|
|
||||||
#![forbid(unsafe_code)]
|
#![forbid(unsafe_code)]
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
@@ -120,9 +115,9 @@ impl Pixel for f64 {
|
|||||||
|
|
||||||
/// Checks that the scale factor is a normal positive `f64`.
|
/// Checks that the scale factor is a normal positive `f64`.
|
||||||
///
|
///
|
||||||
/// All functions that take a scale factor assert that this will return `true`. If you're sourcing scale factors from
|
/// All functions that take a scale factor assert that this will return `true`. If you're sourcing
|
||||||
/// anywhere other than winit, it's recommended to validate them using this function before passing them to winit;
|
/// scale factors from anywhere other than winit, it's recommended to validate them using this
|
||||||
/// otherwise, you risk panics.
|
/// function before passing them to winit; otherwise, you risk panics.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn validate_scale_factor(scale_factor: f64) -> bool {
|
pub fn validate_scale_factor(scale_factor: f64) -> bool {
|
||||||
scale_factor.is_sign_positive() && scale_factor.is_normal()
|
scale_factor.is_sign_positive() && scale_factor.is_normal()
|
||||||
@@ -134,12 +129,12 @@ pub fn validate_scale_factor(scale_factor: f64) -> bool {
|
|||||||
pub struct LogicalUnit<P>(pub P);
|
pub struct LogicalUnit<P>(pub P);
|
||||||
|
|
||||||
impl<P> LogicalUnit<P> {
|
impl<P> LogicalUnit<P> {
|
||||||
|
/// Represents a maximum logical unit that is equal to [`f64::MAX`].
|
||||||
|
pub const MAX: LogicalUnit<f64> = LogicalUnit::new(f64::MAX);
|
||||||
/// Represents a minimum logical unit of [`f64::MAX`].
|
/// Represents a minimum logical unit of [`f64::MAX`].
|
||||||
pub const MIN: LogicalUnit<f64> = LogicalUnit::new(f64::MIN);
|
pub const MIN: LogicalUnit<f64> = LogicalUnit::new(f64::MIN);
|
||||||
/// Represents a logical unit of `0_f64`.
|
/// Represents a logical unit of `0_f64`.
|
||||||
pub const ZERO: LogicalUnit<f64> = LogicalUnit::new(0.0);
|
pub const ZERO: LogicalUnit<f64> = LogicalUnit::new(0.0);
|
||||||
/// Represents a maximum logical unit that is equal to [`f64::MAX`].
|
|
||||||
pub const MAX: LogicalUnit<f64> = LogicalUnit::new(f64::MAX);
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub const fn new(v: P) -> Self {
|
pub const fn new(v: P) -> Self {
|
||||||
@@ -228,12 +223,12 @@ impl<P: Pixel> From<LogicalUnit<P>> for f64 {
|
|||||||
pub struct PhysicalUnit<P>(pub P);
|
pub struct PhysicalUnit<P>(pub P);
|
||||||
|
|
||||||
impl<P> PhysicalUnit<P> {
|
impl<P> PhysicalUnit<P> {
|
||||||
|
/// Represents a maximum physical unit that is equal to [`f64::MAX`].
|
||||||
|
pub const MAX: LogicalUnit<f64> = LogicalUnit::new(f64::MAX);
|
||||||
/// Represents a minimum physical unit of [`f64::MAX`].
|
/// Represents a minimum physical unit of [`f64::MAX`].
|
||||||
pub const MIN: LogicalUnit<f64> = LogicalUnit::new(f64::MIN);
|
pub const MIN: LogicalUnit<f64> = LogicalUnit::new(f64::MIN);
|
||||||
/// Represents a physical unit of `0_f64`.
|
/// Represents a physical unit of `0_f64`.
|
||||||
pub const ZERO: LogicalUnit<f64> = LogicalUnit::new(0.0);
|
pub const ZERO: LogicalUnit<f64> = LogicalUnit::new(0.0);
|
||||||
/// Represents a maximum physical unit that is equal to [`f64::MAX`].
|
|
||||||
pub const MAX: LogicalUnit<f64> = LogicalUnit::new(f64::MAX);
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub const fn new(v: P) -> Self {
|
pub const fn new(v: P) -> Self {
|
||||||
@@ -322,12 +317,12 @@ pub enum PixelUnit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PixelUnit {
|
impl PixelUnit {
|
||||||
|
/// Represents a maximum logical unit that is equal to [`f64::MAX`].
|
||||||
|
pub const MAX: PixelUnit = PixelUnit::Logical(LogicalUnit::new(f64::MAX));
|
||||||
/// Represents a minimum logical unit of [`f64::MAX`].
|
/// Represents a minimum logical unit of [`f64::MAX`].
|
||||||
pub const MIN: PixelUnit = PixelUnit::Logical(LogicalUnit::new(f64::MIN));
|
pub const MIN: PixelUnit = PixelUnit::Logical(LogicalUnit::new(f64::MIN));
|
||||||
/// Represents a logical unit of `0_f64`.
|
/// Represents a logical unit of `0_f64`.
|
||||||
pub const ZERO: PixelUnit = PixelUnit::Logical(LogicalUnit::new(0.0));
|
pub const ZERO: PixelUnit = PixelUnit::Logical(LogicalUnit::new(0.0));
|
||||||
/// Represents a maximum logical unit that is equal to [`f64::MAX`].
|
|
||||||
pub const MAX: PixelUnit = PixelUnit::Logical(LogicalUnit::new(f64::MAX));
|
|
||||||
|
|
||||||
pub fn new<S: Into<PixelUnit>>(unit: S) -> PixelUnit {
|
pub fn new<S: Into<PixelUnit>>(unit: S) -> PixelUnit {
|
||||||
unit.into()
|
unit.into()
|
||||||
@@ -400,10 +395,7 @@ impl<P: Pixel> LogicalPosition<P> {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn cast<X: Pixel>(&self) -> LogicalPosition<X> {
|
pub fn cast<X: Pixel>(&self) -> LogicalPosition<X> {
|
||||||
LogicalPosition {
|
LogicalPosition { x: self.x.cast(), y: self.y.cast() }
|
||||||
x: self.x.cast(),
|
|
||||||
y: self.y.cast(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -479,10 +471,7 @@ impl<P: Pixel> PhysicalPosition<P> {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn cast<X: Pixel>(&self) -> PhysicalPosition<X> {
|
pub fn cast<X: Pixel>(&self) -> PhysicalPosition<X> {
|
||||||
PhysicalPosition {
|
PhysicalPosition { x: self.x.cast(), y: self.y.cast() }
|
||||||
x: self.x.cast(),
|
|
||||||
y: self.y.cast(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -558,10 +547,7 @@ impl<P: Pixel> LogicalSize<P> {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn cast<X: Pixel>(&self) -> LogicalSize<X> {
|
pub fn cast<X: Pixel>(&self) -> LogicalSize<X> {
|
||||||
LogicalSize {
|
LogicalSize { width: self.width.cast(), height: self.height.cast() }
|
||||||
width: self.width.cast(),
|
|
||||||
height: self.height.cast(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -599,10 +585,7 @@ impl<P: Pixel> From<mint::Vector2<P>> for LogicalSize<P> {
|
|||||||
#[cfg(feature = "mint")]
|
#[cfg(feature = "mint")]
|
||||||
impl<P: Pixel> From<LogicalSize<P>> for mint::Vector2<P> {
|
impl<P: Pixel> From<LogicalSize<P>> for mint::Vector2<P> {
|
||||||
fn from(s: LogicalSize<P>) -> Self {
|
fn from(s: LogicalSize<P>) -> Self {
|
||||||
mint::Vector2 {
|
mint::Vector2 { x: s.width, y: s.height }
|
||||||
x: s.width,
|
|
||||||
y: s.height,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -637,10 +620,7 @@ impl<P: Pixel> PhysicalSize<P> {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn cast<X: Pixel>(&self) -> PhysicalSize<X> {
|
pub fn cast<X: Pixel>(&self) -> PhysicalSize<X> {
|
||||||
PhysicalSize {
|
PhysicalSize { width: self.width.cast(), height: self.height.cast() }
|
||||||
width: self.width.cast(),
|
|
||||||
height: self.height.cast(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -678,10 +658,7 @@ impl<P: Pixel> From<mint::Vector2<P>> for PhysicalSize<P> {
|
|||||||
#[cfg(feature = "mint")]
|
#[cfg(feature = "mint")]
|
||||||
impl<P: Pixel> From<PhysicalSize<P>> for mint::Vector2<P> {
|
impl<P: Pixel> From<PhysicalSize<P>> for mint::Vector2<P> {
|
||||||
fn from(s: PhysicalSize<P>) -> Self {
|
fn from(s: PhysicalSize<P>) -> Self {
|
||||||
mint::Vector2 {
|
mint::Vector2 { x: s.width, y: s.height }
|
||||||
x: s.width,
|
|
||||||
y: s.height,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -782,11 +759,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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
macro_rules! test_pixel_int_impl {
|
macro_rules! test_pixel_int_impl {
|
||||||
($($name:ident => $ty:ty),*) => {$(
|
($($name:ident => $ty:ty),*) => {$(
|
||||||
#[test]
|
#[test]
|
||||||
@@ -846,12 +968,7 @@ mod tests {
|
|||||||
|
|
||||||
macro_rules! assert_approx_eq {
|
macro_rules! assert_approx_eq {
|
||||||
($a:expr, $b:expr $(,)?) => {
|
($a:expr, $b:expr $(,)?) => {
|
||||||
assert!(
|
assert!(($a - $b).abs() < 0.001, "{} is not approximately equal to {}", $a, $b);
|
||||||
($a - $b).abs() < 0.001,
|
|
||||||
"{} is not approximately equal to {}",
|
|
||||||
$a,
|
|
||||||
$b
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -970,14 +1087,8 @@ mod tests {
|
|||||||
assert_eq!(log_unit.to_physical::<u32>(1.0), PhysicalUnit::new(1));
|
assert_eq!(log_unit.to_physical::<u32>(1.0), PhysicalUnit::new(1));
|
||||||
assert_eq!(log_unit.to_physical::<u32>(2.0), PhysicalUnit::new(2));
|
assert_eq!(log_unit.to_physical::<u32>(2.0), PhysicalUnit::new(2));
|
||||||
assert_eq!(log_unit.cast::<u32>(), LogicalUnit::new(1));
|
assert_eq!(log_unit.cast::<u32>(), LogicalUnit::new(1));
|
||||||
assert_eq!(
|
assert_eq!(log_unit, LogicalUnit::from_physical(PhysicalUnit::new(1.0), 1.0));
|
||||||
log_unit,
|
assert_eq!(log_unit, LogicalUnit::from_physical(PhysicalUnit::new(2.0), 2.0));
|
||||||
LogicalUnit::from_physical(PhysicalUnit::new(1.0), 1.0)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
log_unit,
|
|
||||||
LogicalUnit::from_physical(PhysicalUnit::new(2.0), 2.0)
|
|
||||||
);
|
|
||||||
assert_eq!(LogicalUnit::from(2.0), LogicalUnit::new(2.0));
|
assert_eq!(LogicalUnit::from(2.0), LogicalUnit::new(2.0));
|
||||||
|
|
||||||
let x: f64 = log_unit.into();
|
let x: f64 = log_unit.into();
|
||||||
@@ -986,14 +1097,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_physical_unit() {
|
fn test_physical_unit() {
|
||||||
assert_eq!(
|
assert_eq!(PhysicalUnit::from_logical(LogicalUnit::new(1.0), 1.0), PhysicalUnit::new(1));
|
||||||
PhysicalUnit::from_logical(LogicalUnit::new(1.0), 1.0),
|
assert_eq!(PhysicalUnit::from_logical(LogicalUnit::new(2.0), 0.5), PhysicalUnit::new(1));
|
||||||
PhysicalUnit::new(1)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
PhysicalUnit::from_logical(LogicalUnit::new(2.0), 0.5),
|
|
||||||
PhysicalUnit::new(1)
|
|
||||||
);
|
|
||||||
assert_eq!(PhysicalUnit::from(2.0), PhysicalUnit::new(2.0,));
|
assert_eq!(PhysicalUnit::from(2.0), PhysicalUnit::new(2.0,));
|
||||||
assert_eq!(PhysicalUnit::from(2.0), PhysicalUnit::new(2.0));
|
assert_eq!(PhysicalUnit::from(2.0), PhysicalUnit::new(2.0));
|
||||||
|
|
||||||
@@ -1007,22 +1112,10 @@ mod tests {
|
|||||||
assert_eq!(log_pos.to_physical::<u32>(1.0), PhysicalPosition::new(1, 2));
|
assert_eq!(log_pos.to_physical::<u32>(1.0), PhysicalPosition::new(1, 2));
|
||||||
assert_eq!(log_pos.to_physical::<u32>(2.0), PhysicalPosition::new(2, 4));
|
assert_eq!(log_pos.to_physical::<u32>(2.0), PhysicalPosition::new(2, 4));
|
||||||
assert_eq!(log_pos.cast::<u32>(), LogicalPosition::new(1, 2));
|
assert_eq!(log_pos.cast::<u32>(), LogicalPosition::new(1, 2));
|
||||||
assert_eq!(
|
assert_eq!(log_pos, LogicalPosition::from_physical(PhysicalPosition::new(1.0, 2.0), 1.0));
|
||||||
log_pos,
|
assert_eq!(log_pos, LogicalPosition::from_physical(PhysicalPosition::new(2.0, 4.0), 2.0));
|
||||||
LogicalPosition::from_physical(PhysicalPosition::new(1.0, 2.0), 1.0)
|
assert_eq!(LogicalPosition::from((2.0, 2.0)), LogicalPosition::new(2.0, 2.0));
|
||||||
);
|
assert_eq!(LogicalPosition::from([2.0, 3.0]), LogicalPosition::new(2.0, 3.0));
|
||||||
assert_eq!(
|
|
||||||
log_pos,
|
|
||||||
LogicalPosition::from_physical(PhysicalPosition::new(2.0, 4.0), 2.0)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
LogicalPosition::from((2.0, 2.0)),
|
|
||||||
LogicalPosition::new(2.0, 2.0)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
LogicalPosition::from([2.0, 3.0]),
|
|
||||||
LogicalPosition::new(2.0, 3.0)
|
|
||||||
);
|
|
||||||
|
|
||||||
let x: (f64, f64) = log_pos.into();
|
let x: (f64, f64) = log_pos.into();
|
||||||
assert_eq!(x, (1.0, 2.0));
|
assert_eq!(x, (1.0, 2.0));
|
||||||
@@ -1040,14 +1133,8 @@ mod tests {
|
|||||||
PhysicalPosition::from_logical(LogicalPosition::new(2.0, 4.0), 0.5),
|
PhysicalPosition::from_logical(LogicalPosition::new(2.0, 4.0), 0.5),
|
||||||
PhysicalPosition::new(1, 2)
|
PhysicalPosition::new(1, 2)
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(PhysicalPosition::from((2.0, 2.0)), PhysicalPosition::new(2.0, 2.0));
|
||||||
PhysicalPosition::from((2.0, 2.0)),
|
assert_eq!(PhysicalPosition::from([2.0, 3.0]), PhysicalPosition::new(2.0, 3.0));
|
||||||
PhysicalPosition::new(2.0, 2.0)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
PhysicalPosition::from([2.0, 3.0]),
|
|
||||||
PhysicalPosition::new(2.0, 3.0)
|
|
||||||
);
|
|
||||||
|
|
||||||
let x: (f64, f64) = PhysicalPosition::new(1, 2).into();
|
let x: (f64, f64) = PhysicalPosition::new(1, 2).into();
|
||||||
assert_eq!(x, (1.0, 2.0));
|
assert_eq!(x, (1.0, 2.0));
|
||||||
@@ -1061,14 +1148,8 @@ mod tests {
|
|||||||
assert_eq!(log_size.to_physical::<u32>(1.0), PhysicalSize::new(1, 2));
|
assert_eq!(log_size.to_physical::<u32>(1.0), PhysicalSize::new(1, 2));
|
||||||
assert_eq!(log_size.to_physical::<u32>(2.0), PhysicalSize::new(2, 4));
|
assert_eq!(log_size.to_physical::<u32>(2.0), PhysicalSize::new(2, 4));
|
||||||
assert_eq!(log_size.cast::<u32>(), LogicalSize::new(1, 2));
|
assert_eq!(log_size.cast::<u32>(), LogicalSize::new(1, 2));
|
||||||
assert_eq!(
|
assert_eq!(log_size, LogicalSize::from_physical(PhysicalSize::new(1.0, 2.0), 1.0));
|
||||||
log_size,
|
assert_eq!(log_size, LogicalSize::from_physical(PhysicalSize::new(2.0, 4.0), 2.0));
|
||||||
LogicalSize::from_physical(PhysicalSize::new(1.0, 2.0), 1.0)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
log_size,
|
|
||||||
LogicalSize::from_physical(PhysicalSize::new(2.0, 4.0), 2.0)
|
|
||||||
);
|
|
||||||
assert_eq!(LogicalSize::from((2.0, 2.0)), LogicalSize::new(2.0, 2.0));
|
assert_eq!(LogicalSize::from((2.0, 2.0)), LogicalSize::new(2.0, 2.0));
|
||||||
assert_eq!(LogicalSize::from([2.0, 3.0]), LogicalSize::new(2.0, 3.0));
|
assert_eq!(LogicalSize::from([2.0, 3.0]), LogicalSize::new(2.0, 3.0));
|
||||||
|
|
||||||
@@ -1099,10 +1180,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_size() {
|
fn test_size() {
|
||||||
assert_eq!(
|
assert_eq!(Size::new(PhysicalSize::new(1, 2)), Size::Physical(PhysicalSize::new(1, 2)));
|
||||||
Size::new(PhysicalSize::new(1, 2)),
|
|
||||||
Size::Physical(PhysicalSize::new(1, 2))
|
|
||||||
);
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
Size::new(LogicalSize::new(1.0, 2.0)),
|
Size::new(LogicalSize::new(1.0, 2.0)),
|
||||||
Size::Logical(LogicalSize::new(1.0, 2.0))
|
Size::Logical(LogicalSize::new(1.0, 2.0))
|
||||||
|
|||||||
@@ -1,25 +1,85 @@
|
|||||||
#[cfg(all(
|
#[cfg(any(x11_platform, macos_platform, windows_platform))]
|
||||||
feature = "rwh_06",
|
|
||||||
any(x11_platform, macos_platform, windows_platform)
|
|
||||||
))]
|
|
||||||
#[allow(deprecated)]
|
#[allow(deprecated)]
|
||||||
fn main() -> Result<(), impl std::error::Error> {
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use winit::application::ApplicationHandler;
|
||||||
use winit::dpi::{LogicalPosition, LogicalSize, Position};
|
use winit::dpi::{LogicalPosition, LogicalSize, Position};
|
||||||
use winit::event::{ElementState, Event, KeyEvent, WindowEvent};
|
use winit::event::{ElementState, KeyEvent, WindowEvent};
|
||||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
use winit::raw_window_handle::HasRawWindowHandle;
|
use winit::raw_window_handle::HasRawWindowHandle;
|
||||||
use winit::window::Window;
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
#[path = "util/fill.rs"]
|
#[path = "util/fill.rs"]
|
||||||
mod fill;
|
mod fill;
|
||||||
|
|
||||||
fn spawn_child_window(parent: &Window, event_loop: &ActiveEventLoop) -> Window {
|
#[derive(Default)]
|
||||||
|
struct Application {
|
||||||
|
parent_window_id: Option<WindowId>,
|
||||||
|
windows: HashMap<WindowId, Box<dyn Window>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for Application {
|
||||||
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
let attributes = WindowAttributes::default()
|
||||||
|
.with_title("parent window")
|
||||||
|
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
||||||
|
.with_surface_size(LogicalSize::new(640.0f32, 480.0f32));
|
||||||
|
let window = event_loop.create_window(attributes).unwrap();
|
||||||
|
|
||||||
|
println!("Parent window id: {:?})", window.id());
|
||||||
|
self.parent_window_id = Some(window.id());
|
||||||
|
|
||||||
|
self.windows.insert(window.id(), window);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
window_id: winit::window::WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
self.windows.clear();
|
||||||
|
event_loop.exit();
|
||||||
|
},
|
||||||
|
WindowEvent::PointerEntered { 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 = self.windows.get(&self.parent_window_id.unwrap()).unwrap();
|
||||||
|
let child_window = spawn_child_window(parent_window.as_ref(), event_loop);
|
||||||
|
let child_id = child_window.id();
|
||||||
|
println!("Child window created with id: {child_id:?}");
|
||||||
|
self.windows.insert(child_id, child_window);
|
||||||
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
if let Some(window) = self.windows.get(&window_id) {
|
||||||
|
fill::fill_window(window.as_ref());
|
||||||
|
}
|
||||||
|
},
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_child_window(
|
||||||
|
parent: &dyn Window,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
) -> Box<dyn Window> {
|
||||||
let parent = parent.raw_window_handle().unwrap();
|
let parent = parent.raw_window_handle().unwrap();
|
||||||
let mut window_attributes = Window::default_attributes()
|
let mut window_attributes = WindowAttributes::default()
|
||||||
.with_title("child window")
|
.with_title("child window")
|
||||||
.with_inner_size(LogicalSize::new(200.0f32, 200.0f32))
|
.with_surface_size(LogicalSize::new(200.0f32, 200.0f32))
|
||||||
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
||||||
.with_visible(true);
|
.with_visible(true);
|
||||||
// `with_parent_window` is unsafe. Parent window must be a valid window.
|
// `with_parent_window` is unsafe. Parent window must be a valid window.
|
||||||
@@ -28,67 +88,14 @@ fn main() -> Result<(), impl std::error::Error> {
|
|||||||
event_loop.create_window(window_attributes).unwrap()
|
event_loop.create_window(window_attributes).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut windows = HashMap::new();
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
event_loop.run_app(Application::default())
|
||||||
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(
|
#[cfg(not(any(x11_platform, macos_platform, windows_platform)))]
|
||||||
feature = "rwh_06",
|
|
||||||
not(any(x11_platform, macos_platform, windows_platform))
|
|
||||||
))]
|
|
||||||
fn main() {
|
fn main() {
|
||||||
panic!("This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature enabled.");
|
panic!(
|
||||||
|
"This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature \
|
||||||
|
enabled."
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,17 +4,19 @@ use std::thread;
|
|||||||
#[cfg(not(web_platform))]
|
#[cfg(not(web_platform))]
|
||||||
use std::time;
|
use std::time;
|
||||||
|
|
||||||
|
use ::tracing::{info, warn};
|
||||||
#[cfg(web_platform)]
|
#[cfg(web_platform)]
|
||||||
use web_time as time;
|
use web_time as time;
|
||||||
|
|
||||||
use winit::application::ApplicationHandler;
|
use winit::application::ApplicationHandler;
|
||||||
use winit::event::{ElementState, KeyEvent, StartCause, WindowEvent};
|
use winit::event::{ElementState, KeyEvent, StartCause, WindowEvent};
|
||||||
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||||
use winit::keyboard::{Key, NamedKey};
|
use winit::keyboard::{Key, NamedKey};
|
||||||
use winit::window::{Window, WindowId};
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
#[path = "util/fill.rs"]
|
#[path = "util/fill.rs"]
|
||||||
mod fill;
|
mod fill;
|
||||||
|
#[path = "util/tracing.rs"]
|
||||||
|
mod tracing;
|
||||||
|
|
||||||
const WAIT_TIME: time::Duration = time::Duration::from_millis(100);
|
const WAIT_TIME: time::Duration = time::Duration::from_millis(100);
|
||||||
const POLL_SLEEP_TIME: time::Duration = time::Duration::from_millis(100);
|
const POLL_SLEEP_TIME: time::Duration = time::Duration::from_millis(100);
|
||||||
@@ -28,18 +30,20 @@ enum Mode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() -> Result<(), impl std::error::Error> {
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
tracing_subscriber::fmt::init();
|
#[cfg(web_platform)]
|
||||||
|
console_error_panic_hook::set_once();
|
||||||
|
|
||||||
println!("Press '1' to switch to Wait mode.");
|
tracing::init();
|
||||||
println!("Press '2' to switch to WaitUntil mode.");
|
|
||||||
println!("Press '3' to switch to Poll mode.");
|
info!("Press '1' to switch to Wait mode.");
|
||||||
println!("Press 'R' to toggle request_redraw() calls.");
|
info!("Press '2' to switch to WaitUntil mode.");
|
||||||
println!("Press 'Esc' to close the window.");
|
info!("Press '3' to switch to Poll mode.");
|
||||||
|
info!("Press 'R' to toggle request_redraw() calls.");
|
||||||
|
info!("Press 'Esc' to close the window.");
|
||||||
|
|
||||||
let event_loop = EventLoop::new().unwrap();
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
let mut app = ControlFlowDemo::default();
|
event_loop.run_app(ControlFlowDemo::default())
|
||||||
event_loop.run_app(&mut app)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
@@ -48,12 +52,12 @@ struct ControlFlowDemo {
|
|||||||
request_redraw: bool,
|
request_redraw: bool,
|
||||||
wait_cancelled: bool,
|
wait_cancelled: bool,
|
||||||
close_requested: bool,
|
close_requested: bool,
|
||||||
window: Option<Window>,
|
window: Option<Box<dyn Window>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ApplicationHandler for ControlFlowDemo {
|
impl ApplicationHandler for ControlFlowDemo {
|
||||||
fn new_events(&mut self, _event_loop: &ActiveEventLoop, cause: StartCause) {
|
fn new_events(&mut self, _event_loop: &dyn ActiveEventLoop, cause: StartCause) {
|
||||||
println!("new_events: {cause:?}");
|
info!("new_events: {cause:?}");
|
||||||
|
|
||||||
self.wait_cancelled = match cause {
|
self.wait_cancelled = match cause {
|
||||||
StartCause::WaitCancelled { .. } => self.mode == Mode::WaitUntil,
|
StartCause::WaitCancelled { .. } => self.mode == Mode::WaitUntil,
|
||||||
@@ -61,8 +65,8 @@ impl ApplicationHandler for ControlFlowDemo {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
let window_attributes = Window::default_attributes().with_title(
|
let window_attributes = WindowAttributes::default().with_title(
|
||||||
"Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.",
|
"Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.",
|
||||||
);
|
);
|
||||||
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||||
@@ -70,58 +74,53 @@ impl ApplicationHandler for ControlFlowDemo {
|
|||||||
|
|
||||||
fn window_event(
|
fn window_event(
|
||||||
&mut self,
|
&mut self,
|
||||||
_event_loop: &ActiveEventLoop,
|
_event_loop: &dyn ActiveEventLoop,
|
||||||
_window_id: WindowId,
|
_window_id: WindowId,
|
||||||
event: WindowEvent,
|
event: WindowEvent,
|
||||||
) {
|
) {
|
||||||
println!("{event:?}");
|
info!("{event:?}");
|
||||||
|
|
||||||
match event {
|
match event {
|
||||||
WindowEvent::CloseRequested => {
|
WindowEvent::CloseRequested => {
|
||||||
self.close_requested = true;
|
self.close_requested = true;
|
||||||
}
|
},
|
||||||
WindowEvent::KeyboardInput {
|
WindowEvent::KeyboardInput {
|
||||||
event:
|
event: KeyEvent { logical_key: key, state: ElementState::Pressed, .. },
|
||||||
KeyEvent {
|
|
||||||
logical_key: key,
|
|
||||||
state: ElementState::Pressed,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
..
|
||||||
} => match key.as_ref() {
|
} => match key.as_ref() {
|
||||||
// WARNING: Consider using `key_without_modifiers()` if available on your platform.
|
// WARNING: Consider using `key_without_modifiers()` if available on your platform.
|
||||||
// See the `key_binding` example
|
// See the `key_binding` example
|
||||||
Key::Character("1") => {
|
Key::Character("1") => {
|
||||||
self.mode = Mode::Wait;
|
self.mode = Mode::Wait;
|
||||||
println!("\nmode: {:?}\n", self.mode);
|
warn!("mode: {:?}", self.mode);
|
||||||
}
|
},
|
||||||
Key::Character("2") => {
|
Key::Character("2") => {
|
||||||
self.mode = Mode::WaitUntil;
|
self.mode = Mode::WaitUntil;
|
||||||
println!("\nmode: {:?}\n", self.mode);
|
warn!("mode: {:?}", self.mode);
|
||||||
}
|
},
|
||||||
Key::Character("3") => {
|
Key::Character("3") => {
|
||||||
self.mode = Mode::Poll;
|
self.mode = Mode::Poll;
|
||||||
println!("\nmode: {:?}\n", self.mode);
|
warn!("mode: {:?}", self.mode);
|
||||||
}
|
},
|
||||||
Key::Character("r") => {
|
Key::Character("r") => {
|
||||||
self.request_redraw = !self.request_redraw;
|
self.request_redraw = !self.request_redraw;
|
||||||
println!("\nrequest_redraw: {}\n", self.request_redraw);
|
warn!("request_redraw: {}", self.request_redraw);
|
||||||
}
|
},
|
||||||
Key::Named(NamedKey::Escape) => {
|
Key::Named(NamedKey::Escape) => {
|
||||||
self.close_requested = true;
|
self.close_requested = true;
|
||||||
}
|
},
|
||||||
_ => (),
|
_ => (),
|
||||||
},
|
},
|
||||||
WindowEvent::RedrawRequested => {
|
WindowEvent::RedrawRequested => {
|
||||||
let window = self.window.as_ref().unwrap();
|
let window = self.window.as_ref().unwrap();
|
||||||
window.pre_present_notify();
|
window.pre_present_notify();
|
||||||
fill::fill_window(window);
|
fill::fill_window(window.as_ref());
|
||||||
}
|
},
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
fn about_to_wait(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
if self.request_redraw && !self.wait_cancelled && !self.close_requested {
|
if self.request_redraw && !self.wait_cancelled && !self.close_requested {
|
||||||
self.window.as_ref().unwrap().request_redraw();
|
self.window.as_ref().unwrap().request_redraw();
|
||||||
}
|
}
|
||||||
@@ -133,11 +132,11 @@ impl ApplicationHandler for ControlFlowDemo {
|
|||||||
event_loop
|
event_loop
|
||||||
.set_control_flow(ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME));
|
.set_control_flow(ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME));
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
Mode::Poll => {
|
Mode::Poll => {
|
||||||
thread::sleep(POLL_SLEEP_TIME);
|
thread::sleep(POLL_SLEEP_TIME);
|
||||||
event_loop.set_control_flow(ControlFlow::Poll);
|
event_loop.set_control_flow(ControlFlow::Poll);
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
if self.close_requested {
|
if self.close_requested {
|
||||||
|
|||||||
@@ -1,39 +1,35 @@
|
|||||||
#![allow(clippy::single_match)]
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
// Limit this example to only compatible platforms.
|
// Limit this example to only compatible platforms.
|
||||||
#[cfg(any(
|
#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform, android_platform,))]
|
||||||
windows_platform,
|
|
||||||
macos_platform,
|
|
||||||
x11_platform,
|
|
||||||
wayland_platform,
|
|
||||||
android_platform,
|
|
||||||
))]
|
|
||||||
fn main() -> std::process::ExitCode {
|
fn main() -> std::process::ExitCode {
|
||||||
use std::{process::ExitCode, thread::sleep, time::Duration};
|
use std::process::ExitCode;
|
||||||
|
use std::thread::sleep;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
use winit::application::ApplicationHandler;
|
use winit::application::ApplicationHandler;
|
||||||
use winit::event::WindowEvent;
|
use winit::event::WindowEvent;
|
||||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
use winit::platform::pump_events::{EventLoopExtPumpEvents, PumpStatus};
|
use winit::platform::pump_events::{EventLoopExtPumpEvents, PumpStatus};
|
||||||
use winit::window::{Window, WindowId};
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
#[path = "util/fill.rs"]
|
#[path = "util/fill.rs"]
|
||||||
mod fill;
|
mod fill;
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct PumpDemo {
|
struct PumpDemo {
|
||||||
window: Option<Window>,
|
window: Option<Box<dyn Window>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ApplicationHandler for PumpDemo {
|
impl ApplicationHandler for PumpDemo {
|
||||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
let window_attributes = Window::default_attributes().with_title("A fantastic window!");
|
let window_attributes = WindowAttributes::default().with_title("A fantastic window!");
|
||||||
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
fn window_event(
|
fn window_event(
|
||||||
&mut self,
|
&mut self,
|
||||||
event_loop: &ActiveEventLoop,
|
event_loop: &dyn ActiveEventLoop,
|
||||||
_window_id: WindowId,
|
_window_id: WindowId,
|
||||||
event: WindowEvent,
|
event: WindowEvent,
|
||||||
) {
|
) {
|
||||||
@@ -47,9 +43,9 @@ fn main() -> std::process::ExitCode {
|
|||||||
match event {
|
match event {
|
||||||
WindowEvent::CloseRequested => event_loop.exit(),
|
WindowEvent::CloseRequested => event_loop.exit(),
|
||||||
WindowEvent::RedrawRequested => {
|
WindowEvent::RedrawRequested => {
|
||||||
fill::fill_window(window);
|
fill::fill_window(window.as_ref());
|
||||||
window.request_redraw();
|
window.request_redraw();
|
||||||
}
|
},
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
use winit::event::WindowEvent;
|
use winit::event::WindowEvent;
|
||||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
use winit::platform::run_on_demand::EventLoopExtRunOnDemand;
|
use winit::platform::run_on_demand::EventLoopExtRunOnDemand;
|
||||||
use winit::window::{Window, WindowId};
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
#[path = "util/fill.rs"]
|
#[path = "util/fill.rs"]
|
||||||
mod fill;
|
mod fill;
|
||||||
@@ -18,20 +18,20 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
struct App {
|
struct App {
|
||||||
idx: usize,
|
idx: usize,
|
||||||
window_id: Option<WindowId>,
|
window_id: Option<WindowId>,
|
||||||
window: Option<Window>,
|
window: Option<Box<dyn Window>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ApplicationHandler for App {
|
impl ApplicationHandler for App {
|
||||||
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
|
fn about_to_wait(&mut self, _event_loop: &dyn ActiveEventLoop) {
|
||||||
if let Some(window) = self.window.as_ref() {
|
if let Some(window) = self.window.as_ref() {
|
||||||
window.request_redraw();
|
window.request_redraw();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
let window_attributes = Window::default_attributes()
|
let window_attributes = WindowAttributes::default()
|
||||||
.with_title("Fantastic window number one!")
|
.with_title("Fantastic window number one!")
|
||||||
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0));
|
.with_surface_size(winit::dpi::LogicalSize::new(128.0, 128.0));
|
||||||
let window = event_loop.create_window(window_attributes).unwrap();
|
let window = event_loop.create_window(window_attributes).unwrap();
|
||||||
self.window_id = Some(window.id());
|
self.window_id = Some(window.id());
|
||||||
self.window = Some(window);
|
self.window = Some(window);
|
||||||
@@ -39,7 +39,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
|
|
||||||
fn window_event(
|
fn window_event(
|
||||||
&mut self,
|
&mut self,
|
||||||
event_loop: &ActiveEventLoop,
|
event_loop: &dyn ActiveEventLoop,
|
||||||
window_id: WindowId,
|
window_id: WindowId,
|
||||||
event: WindowEvent,
|
event: WindowEvent,
|
||||||
) {
|
) {
|
||||||
@@ -60,13 +60,17 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
|
|
||||||
match event {
|
match event {
|
||||||
WindowEvent::CloseRequested => {
|
WindowEvent::CloseRequested => {
|
||||||
println!("--------------------------------------------------------- Window {} CloseRequested", self.idx);
|
println!(
|
||||||
fill::cleanup_window(window);
|
"--------------------------------------------------------- Window {} \
|
||||||
|
CloseRequested",
|
||||||
|
self.idx
|
||||||
|
);
|
||||||
|
fill::cleanup_window(window.as_ref());
|
||||||
self.window = None;
|
self.window = None;
|
||||||
}
|
},
|
||||||
WindowEvent::RedrawRequested => {
|
WindowEvent::RedrawRequested => {
|
||||||
fill::fill_window(window);
|
fill::fill_window(window.as_ref());
|
||||||
}
|
},
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -76,10 +80,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
|
|
||||||
let mut event_loop = EventLoop::new().unwrap();
|
let mut event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
let mut app = App {
|
let mut app = App { idx: 1, ..Default::default() };
|
||||||
idx: 1,
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
event_loop.run_app_on_demand(&mut app)?;
|
event_loop.run_app_on_demand(&mut app)?;
|
||||||
|
|
||||||
println!("--------------------------------------------------------- Finished first loop");
|
println!("--------------------------------------------------------- Finished first loop");
|
||||||
|
|||||||
@@ -11,16 +11,16 @@
|
|||||||
pub use platform::cleanup_window;
|
pub use platform::cleanup_window;
|
||||||
pub use platform::fill_window;
|
pub use platform::fill_window;
|
||||||
|
|
||||||
#[cfg(all(feature = "rwh_05", not(any(target_os = "android", target_os = "ios"))))]
|
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||||
mod platform {
|
mod platform {
|
||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
use std::mem;
|
||||||
use std::mem::ManuallyDrop;
|
use std::mem::ManuallyDrop;
|
||||||
use std::num::NonZeroU32;
|
use std::num::NonZeroU32;
|
||||||
|
|
||||||
use softbuffer::{Context, Surface};
|
use softbuffer::{Context, Surface};
|
||||||
use winit::window::Window;
|
use winit::window::{Window, WindowId};
|
||||||
use winit::window::WindowId;
|
|
||||||
|
|
||||||
thread_local! {
|
thread_local! {
|
||||||
// NOTE: You should never do things like that, create context and drop it before
|
// NOTE: You should never do things like that, create context and drop it before
|
||||||
@@ -34,35 +34,45 @@ mod platform {
|
|||||||
/// The graphics context used to draw to a window.
|
/// The graphics context used to draw to a window.
|
||||||
struct GraphicsContext {
|
struct GraphicsContext {
|
||||||
/// The global softbuffer context.
|
/// The global softbuffer context.
|
||||||
context: Context,
|
context: RefCell<Context<&'static dyn Window>>,
|
||||||
|
|
||||||
/// The hash map of window IDs to surfaces.
|
/// The hash map of window IDs to surfaces.
|
||||||
surfaces: HashMap<WindowId, Surface>,
|
surfaces: HashMap<WindowId, Surface<&'static dyn Window, &'static dyn Window>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GraphicsContext {
|
impl GraphicsContext {
|
||||||
fn new(w: &Window) -> Self {
|
fn new(w: &dyn Window) -> Self {
|
||||||
Self {
|
Self {
|
||||||
context: unsafe { Context::new(w) }.expect("Failed to create a softbuffer context"),
|
context: RefCell::new(
|
||||||
|
Context::new(unsafe {
|
||||||
|
mem::transmute::<&'_ dyn Window, &'static dyn Window>(w)
|
||||||
|
})
|
||||||
|
.expect("Failed to create a softbuffer context"),
|
||||||
|
),
|
||||||
surfaces: HashMap::new(),
|
surfaces: HashMap::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_surface(&mut self, window: &Window) -> &mut Surface {
|
fn create_surface(
|
||||||
|
&mut self,
|
||||||
|
window: &dyn Window,
|
||||||
|
) -> &mut Surface<&'static dyn Window, &'static dyn Window> {
|
||||||
self.surfaces.entry(window.id()).or_insert_with(|| {
|
self.surfaces.entry(window.id()).or_insert_with(|| {
|
||||||
unsafe { Surface::new(&self.context, window) }
|
Surface::new(&self.context.borrow(), unsafe {
|
||||||
.expect("Failed to create a softbuffer surface")
|
mem::transmute::<&'_ dyn Window, &'static dyn Window>(window)
|
||||||
|
})
|
||||||
|
.expect("Failed to create a softbuffer surface")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn destroy_surface(&mut self, window: &Window) {
|
fn destroy_surface(&mut self, window: &dyn Window) {
|
||||||
self.surfaces.remove(&window.id());
|
self.surfaces.remove(&window.id());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fill_window(window: &Window) {
|
pub fn fill_window(window: &dyn Window) {
|
||||||
GC.with(|gc| {
|
GC.with(|gc| {
|
||||||
let size = window.inner_size();
|
let size = window.surface_size();
|
||||||
let (Some(width), Some(height)) =
|
let (Some(width), Some(height)) =
|
||||||
(NonZeroU32::new(size.width), NonZeroU32::new(size.height))
|
(NonZeroU32::new(size.width), NonZeroU32::new(size.height))
|
||||||
else {
|
else {
|
||||||
@@ -71,29 +81,22 @@ mod platform {
|
|||||||
|
|
||||||
// Either get the last context used or create a new one.
|
// Either get the last context used or create a new one.
|
||||||
let mut gc = gc.borrow_mut();
|
let mut gc = gc.borrow_mut();
|
||||||
let surface = gc
|
let surface =
|
||||||
.get_or_insert_with(|| GraphicsContext::new(window))
|
gc.get_or_insert_with(|| GraphicsContext::new(window)).create_surface(window);
|
||||||
.create_surface(window);
|
|
||||||
|
|
||||||
// Fill a buffer with a solid color.
|
// Fill a buffer with a solid color.
|
||||||
const DARK_GRAY: u32 = 0xFF181818;
|
const DARK_GRAY: u32 = 0xff181818;
|
||||||
|
|
||||||
surface
|
surface.resize(width, height).expect("Failed to resize the softbuffer surface");
|
||||||
.resize(width, height)
|
|
||||||
.expect("Failed to resize the softbuffer surface");
|
|
||||||
|
|
||||||
let mut buffer = surface
|
let mut buffer = surface.buffer_mut().expect("Failed to get the softbuffer buffer");
|
||||||
.buffer_mut()
|
|
||||||
.expect("Failed to get the softbuffer buffer");
|
|
||||||
buffer.fill(DARK_GRAY);
|
buffer.fill(DARK_GRAY);
|
||||||
buffer
|
buffer.present().expect("Failed to present the softbuffer buffer");
|
||||||
.present()
|
|
||||||
.expect("Failed to present the softbuffer buffer");
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn cleanup_window(window: &Window) {
|
pub fn cleanup_window(window: &dyn Window) {
|
||||||
GC.with(|gc| {
|
GC.with(|gc| {
|
||||||
let mut gc = gc.borrow_mut();
|
let mut gc = gc.borrow_mut();
|
||||||
if let Some(context) = gc.as_mut() {
|
if let Some(context) = gc.as_mut() {
|
||||||
@@ -103,14 +106,14 @@ mod platform {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(all(feature = "rwh_05", not(any(target_os = "android", target_os = "ios")))))]
|
#[cfg(any(target_os = "android", target_os = "ios"))]
|
||||||
mod platform {
|
mod platform {
|
||||||
pub fn fill_window(_window: &winit::window::Window) {
|
pub fn fill_window(_window: &dyn winit::window::Window) {
|
||||||
// No-op on mobile platforms.
|
// No-op on mobile platforms.
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn cleanup_window(_window: &winit::window::Window) {
|
pub fn cleanup_window(_window: &dyn winit::window::Window) {
|
||||||
// No-op on mobile platforms.
|
// No-op on mobile platforms.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
25
examples/util/tracing.rs
Normal file
25
examples/util/tracing.rs
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
#[cfg(not(web_platform))]
|
||||||
|
pub fn init() {
|
||||||
|
use tracing_subscriber::filter::{EnvFilter, LevelFilter};
|
||||||
|
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_env_filter(
|
||||||
|
EnvFilter::builder().with_default_directive(LevelFilter::INFO.into()).from_env_lossy(),
|
||||||
|
)
|
||||||
|
.init();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
pub fn init() {
|
||||||
|
use tracing_subscriber::layer::SubscriberExt;
|
||||||
|
use tracing_subscriber::util::SubscriberInitExt;
|
||||||
|
|
||||||
|
tracing_subscriber::registry()
|
||||||
|
.with(
|
||||||
|
tracing_subscriber::fmt::layer()
|
||||||
|
.with_ansi(false)
|
||||||
|
.without_time()
|
||||||
|
.with_writer(tracing_web::MakeWebConsoleWriter::new()),
|
||||||
|
)
|
||||||
|
.init();
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -7,21 +7,21 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
use winit::event::WindowEvent;
|
use winit::event::WindowEvent;
|
||||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
use winit::platform::x11::WindowAttributesExtX11;
|
use winit::platform::x11::WindowAttributesExtX11;
|
||||||
use winit::window::{Window, WindowId};
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
#[path = "util/fill.rs"]
|
#[path = "util/fill.rs"]
|
||||||
mod fill;
|
mod fill;
|
||||||
|
|
||||||
pub struct XEmbedDemo {
|
pub struct XEmbedDemo {
|
||||||
parent_window_id: u32,
|
parent_window_id: u32,
|
||||||
window: Option<Window>,
|
window: Option<Box<dyn Window>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ApplicationHandler for XEmbedDemo {
|
impl ApplicationHandler for XEmbedDemo {
|
||||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
let window_attributes = Window::default_attributes()
|
let window_attributes = WindowAttributes::default()
|
||||||
.with_title("An embedded window!")
|
.with_title("An embedded window!")
|
||||||
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
.with_surface_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
||||||
.with_embed_parent_window(self.parent_window_id);
|
.with_embed_parent_window(self.parent_window_id);
|
||||||
|
|
||||||
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||||
@@ -29,7 +29,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
|
|
||||||
fn window_event(
|
fn window_event(
|
||||||
&mut self,
|
&mut self,
|
||||||
event_loop: &ActiveEventLoop,
|
event_loop: &dyn ActiveEventLoop,
|
||||||
_window_id: WindowId,
|
_window_id: WindowId,
|
||||||
event: WindowEvent,
|
event: WindowEvent,
|
||||||
) {
|
) {
|
||||||
@@ -38,13 +38,13 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
WindowEvent::CloseRequested => event_loop.exit(),
|
WindowEvent::CloseRequested => event_loop.exit(),
|
||||||
WindowEvent::RedrawRequested => {
|
WindowEvent::RedrawRequested => {
|
||||||
window.pre_present_notify();
|
window.pre_present_notify();
|
||||||
fill::fill_window(window);
|
fill::fill_window(window.as_ref());
|
||||||
}
|
},
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
|
fn about_to_wait(&mut self, _event_loop: &dyn ActiveEventLoop) {
|
||||||
self.window.as_ref().unwrap().request_redraw();
|
self.window.as_ref().unwrap().request_redraw();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -58,11 +58,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
tracing_subscriber::fmt::init();
|
tracing_subscriber::fmt::init();
|
||||||
let event_loop = EventLoop::new()?;
|
let event_loop = EventLoop::new()?;
|
||||||
|
|
||||||
let mut app = XEmbedDemo {
|
Ok(event_loop.run_app(XEmbedDemo { parent_window_id, window: None })?)
|
||||||
parent_window_id,
|
|
||||||
window: None,
|
|
||||||
};
|
|
||||||
event_loop.run_app(&mut app).map_err(Into::into)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(x11_platform))]
|
#[cfg(not(x11_platform))]
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "common-tests"
|
|
||||||
version = "0.1.0"
|
|
||||||
rust-version.workspace = true
|
|
||||||
repository.workspace = true
|
|
||||||
license.workspace = true
|
|
||||||
edition.workspace = true
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
gui-test.workspace = true
|
|
||||||
macro_rules_attribute = "0.2.0"
|
|
||||||
winit.workspace = true
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
//! Run the test.
|
|
||||||
|
|
||||||
use gui_test::{test, Harness};
|
|
||||||
use macro_rules_attribute::apply;
|
|
||||||
|
|
||||||
use winit::event_loop::EventLoop;
|
|
||||||
|
|
||||||
#[allow(deprecated)]
|
|
||||||
#[apply(test)]
|
|
||||||
fn initialize(harness: &mut Harness) {
|
|
||||||
let mut group = harness.group("sanity");
|
|
||||||
group.harness().with_test("startup/shutdown", || {
|
|
||||||
let evl = EventLoop::new().expect("initialization");
|
|
||||||
evl.run(|_event, elwt| {
|
|
||||||
elwt.exit();
|
|
||||||
})
|
|
||||||
.expect("running");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
gui_test::main! {
|
|
||||||
gui_test::remote::handler()
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "gui-test-runner"
|
|
||||||
version = "0.1.0"
|
|
||||||
rust-version.workspace = true
|
|
||||||
repository.workspace = true
|
|
||||||
license.workspace = true
|
|
||||||
edition.workspace = true
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
camino = "1.1.6"
|
|
||||||
fastrand = "2.0.1"
|
|
||||||
gui-test.workspace = true
|
|
||||||
serde_json.workspace = true
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
// Copyright 2024 The Winit Contributors
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
//! A wrapper around the `Command` type that dumps the command to stderr.
|
|
||||||
//!
|
|
||||||
//! Essentially it's like `set -x` in Bash.
|
|
||||||
|
|
||||||
use std::ffi::{OsStr, OsString};
|
|
||||||
use std::io::{self, prelude::*};
|
|
||||||
use std::process::Child;
|
|
||||||
|
|
||||||
/// Simple `Command` wrapper.
|
|
||||||
pub(super) struct Command {
|
|
||||||
/// Actual inner command.
|
|
||||||
inner: std::process::Command,
|
|
||||||
|
|
||||||
/// Command to run.
|
|
||||||
text: Vec<OsString>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Command {
|
|
||||||
/// Create a new `Command`.
|
|
||||||
pub(super) fn new(cmd: impl AsRef<OsStr>) -> Self {
|
|
||||||
let cmd = cmd.as_ref();
|
|
||||||
Self {
|
|
||||||
inner: std::process::Command::new(cmd),
|
|
||||||
text: vec![cmd.to_os_string()],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Add an argument to the `Command`.
|
|
||||||
pub(super) fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
|
|
||||||
let arg = arg.as_ref();
|
|
||||||
self.inner.arg(arg);
|
|
||||||
self.text.push(arg.to_os_string());
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Add multiple arguments to the `Command`.
|
|
||||||
pub(super) fn args<T: AsRef<OsStr>>(&mut self, args: impl IntoIterator<Item = T>) -> &mut Self {
|
|
||||||
for arg in args {
|
|
||||||
let arg = arg.as_ref();
|
|
||||||
self.inner.arg(arg);
|
|
||||||
self.text.push(arg.to_os_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Spawn the process.
|
|
||||||
pub(super) fn spawn(&mut self) -> io::Result<Child> {
|
|
||||||
dump_text(&self.text);
|
|
||||||
self.inner.spawn()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Dump `OsString` list to stderr.
|
|
||||||
fn dump_text(text: &[OsString]) {
|
|
||||||
let mut cerr = io::stderr().lock();
|
|
||||||
write!(&mut cerr, "+").unwrap();
|
|
||||||
|
|
||||||
for arg in text {
|
|
||||||
match arg.to_str() {
|
|
||||||
Some(arg) => write!(&mut cerr, " {}", arg).unwrap(),
|
|
||||||
None => write!(&mut cerr, " {:?}", arg).unwrap(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
writeln!(&mut cerr).unwrap();
|
|
||||||
}
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
// Copyright 2024 The Winit Contributors
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
//! Run the actual Docker command.
|
|
||||||
|
|
||||||
use crate::command::Command;
|
|
||||||
|
|
||||||
use camino::Utf8Path;
|
|
||||||
|
|
||||||
use std::ffi::OsStr;
|
|
||||||
use std::io;
|
|
||||||
use std::process::Child;
|
|
||||||
|
|
||||||
/// The Docker command line.
|
|
||||||
pub(super) struct DockerRun {
|
|
||||||
command: Command,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DockerRun {
|
|
||||||
/// Start the command.
|
|
||||||
pub(super) fn new() -> Self {
|
|
||||||
let mut command = Command::new("docker");
|
|
||||||
command.arg("run");
|
|
||||||
|
|
||||||
Self { command }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Run with an environment variable.
|
|
||||||
pub(super) fn env(&mut self, name: impl AsRef<str>, value: impl AsRef<str>) -> &mut Self {
|
|
||||||
let env_arg = format!("{}={}", name.as_ref(), value.as_ref());
|
|
||||||
self.command.args(["--env", &env_arg]);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Run with a simple `init` process.
|
|
||||||
pub(super) fn init(&mut self) -> &mut Self {
|
|
||||||
self.command.arg("--init");
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the working directory.
|
|
||||||
pub(super) fn workdir(&mut self, dir: impl AsRef<OsStr>) -> &mut Self {
|
|
||||||
self.command.arg("--workdir");
|
|
||||||
self.command.arg(dir);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Remove the container once it is complete.
|
|
||||||
pub(super) fn rm(&mut self) -> &mut Self {
|
|
||||||
self.command.arg("--rm");
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Pass a volume into the container.
|
|
||||||
pub(super) fn volume(
|
|
||||||
&mut self,
|
|
||||||
host: impl AsRef<Utf8Path>,
|
|
||||||
container: impl AsRef<Utf8Path>,
|
|
||||||
) -> &mut Self {
|
|
||||||
let list = format!("{}:{}", host.as_ref(), container.as_ref());
|
|
||||||
self.command.args(["--volume", &list]);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Run the container with a command.
|
|
||||||
pub(super) fn run_with_command<T: AsRef<OsStr>>(
|
|
||||||
&mut self,
|
|
||||||
container_name: impl AsRef<str>,
|
|
||||||
container_version: impl AsRef<str>,
|
|
||||||
command: impl IntoIterator<Item = T>,
|
|
||||||
) -> io::Result<Child> {
|
|
||||||
self.command.arg(format!(
|
|
||||||
"{}:{}",
|
|
||||||
container_name.as_ref(),
|
|
||||||
container_version.as_ref()
|
|
||||||
));
|
|
||||||
self.command.args(command);
|
|
||||||
self.command.spawn()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,114 +0,0 @@
|
|||||||
// Copyright 2024 The Winit Contributors
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
//! Run tests inside of a Linux docker container.
|
|
||||||
|
|
||||||
use super::command::DockerRun;
|
|
||||||
use crate::stream::StreamReader;
|
|
||||||
|
|
||||||
use gui_test::remote::handler;
|
|
||||||
use gui_test::TestHandler;
|
|
||||||
|
|
||||||
use std::io;
|
|
||||||
use std::os::unix::net::UnixListener;
|
|
||||||
use std::path::Path;
|
|
||||||
use std::thread;
|
|
||||||
|
|
||||||
const UBUNTU_DOCKERFILE: &str = "ghcr.io/rust-windowing/testubuntu";
|
|
||||||
const LATEST: &str = "latest";
|
|
||||||
|
|
||||||
/// Run the provided test in a Linux docker container.
|
|
||||||
pub(crate) fn linux_test(test_name: &str) -> io::Result<()> {
|
|
||||||
// Create a Unix socket to listen for events on.
|
|
||||||
let unix_path = format!("/tmp/gui_test_{}.sock", fastrand::u16(..));
|
|
||||||
let listener = UnixListener::bind(&unix_path)?;
|
|
||||||
|
|
||||||
// Spawn the Docker container.
|
|
||||||
let mut container = {
|
|
||||||
let mut docker = DockerRun::new();
|
|
||||||
|
|
||||||
// Usual options.
|
|
||||||
docker.rm().init();
|
|
||||||
|
|
||||||
// Pass through the socket as a volume.
|
|
||||||
docker.volume(&unix_path, &unix_path);
|
|
||||||
|
|
||||||
// Pass through the winit directory.
|
|
||||||
let winit_directory = Path::new(env!("CARGO_MANIFEST_DIR"))
|
|
||||||
.ancestors()
|
|
||||||
.find_map(|path| {
|
|
||||||
let cargo_toml = path.join("Cargo.toml");
|
|
||||||
let contents = std::fs::read(cargo_toml).ok()?;
|
|
||||||
|
|
||||||
if std::str::from_utf8(&contents)
|
|
||||||
.ok()?
|
|
||||||
.contains("name = \"winit\"")
|
|
||||||
{
|
|
||||||
Some(path)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
docker.volume(
|
|
||||||
camino::Utf8Path::from_path(winit_directory).unwrap(),
|
|
||||||
"/app/winit/",
|
|
||||||
);
|
|
||||||
|
|
||||||
// Set the working dir to this directory.
|
|
||||||
docker.workdir("/app/winit/");
|
|
||||||
|
|
||||||
// Set GUI_TEST_UNIX_STREAM to the socket.
|
|
||||||
docker.env("GUI_TEST_UNIX_STREAM", &unix_path);
|
|
||||||
|
|
||||||
// Set CARGO_TARGET_DIR to a random other directory.
|
|
||||||
docker.env("CARGO_TARGET_DIR", "/tmp/");
|
|
||||||
|
|
||||||
// The command to run the test.
|
|
||||||
let command = ["xvfb-run", "cargo", "run", "-p", test_name];
|
|
||||||
|
|
||||||
// Spawn the test container.
|
|
||||||
docker.run_with_command(UBUNTU_DOCKERFILE, LATEST, command)?
|
|
||||||
};
|
|
||||||
|
|
||||||
// Run the console listener in another thread.
|
|
||||||
let handle = thread::spawn(move || {
|
|
||||||
// Attach to the listener.
|
|
||||||
let (event_reader, _) = listener.accept().unwrap();
|
|
||||||
|
|
||||||
// Read events and output them as we get them.
|
|
||||||
let input = StreamReader::new(event_reader);
|
|
||||||
let mut output = handler();
|
|
||||||
|
|
||||||
for event in input {
|
|
||||||
let event = event?;
|
|
||||||
output.handle_test(event);
|
|
||||||
}
|
|
||||||
|
|
||||||
io::Result::Ok(())
|
|
||||||
});
|
|
||||||
|
|
||||||
// Wait for the container to finish.
|
|
||||||
if !container.wait()?.success() {
|
|
||||||
return Err(io::Error::new(
|
|
||||||
io::ErrorKind::Other,
|
|
||||||
"docker exited with a failure exit code",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Stop the thread.
|
|
||||||
handle.join().unwrap().unwrap();
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
// Copyright 2024 The Winit Contributors
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
//! Dealing with Docker.
|
|
||||||
|
|
||||||
mod command;
|
|
||||||
|
|
||||||
#[cfg(unix)]
|
|
||||||
pub(super) mod linux;
|
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
//! Runner for the `gui-test` system.
|
|
||||||
|
|
||||||
mod command;
|
|
||||||
mod docker;
|
|
||||||
mod stream;
|
|
||||||
|
|
||||||
use std::env;
|
|
||||||
use std::process::{Command, Stdio};
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut args = env::args();
|
|
||||||
|
|
||||||
// Get the test crate name.
|
|
||||||
let test_crate = args.nth(1).unwrap();
|
|
||||||
|
|
||||||
// Get the target.
|
|
||||||
let target_tag = args.next().unwrap();
|
|
||||||
|
|
||||||
// Split the target into the target and the tag.
|
|
||||||
let (target, tag) = {
|
|
||||||
let mut split = target_tag.splitn(1, ':');
|
|
||||||
let target = split.next().unwrap();
|
|
||||||
let tag = split.next();
|
|
||||||
(target, tag)
|
|
||||||
};
|
|
||||||
|
|
||||||
// Get the current target.
|
|
||||||
let current_target = current_target();
|
|
||||||
|
|
||||||
// If we are building for Linux, run the Linux Docker container.
|
|
||||||
// TODO: Architecture differences.
|
|
||||||
if target.contains("linux") {
|
|
||||||
docker::linux::linux_test(&test_crate).unwrap();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// For now, we only support building for the current target.
|
|
||||||
assert_eq!(target, current_target);
|
|
||||||
assert!(tag.is_none());
|
|
||||||
|
|
||||||
// Just run the crate.
|
|
||||||
if !Command::new("cargo")
|
|
||||||
.args(["run", "-p", &test_crate])
|
|
||||||
.status()
|
|
||||||
.unwrap()
|
|
||||||
.success()
|
|
||||||
{
|
|
||||||
panic!("test failed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the current target.
|
|
||||||
fn current_target() -> String {
|
|
||||||
let output = Command::new("rustc")
|
|
||||||
.arg("-vV")
|
|
||||||
.stdout(Stdio::piped())
|
|
||||||
.output()
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
// Look for the line that starts with "host".
|
|
||||||
let stdout = String::from_utf8(output.stdout).unwrap();
|
|
||||||
for line in stdout.lines() {
|
|
||||||
if let Some(host) = line.strip_prefix("host: ") {
|
|
||||||
return host.to_string();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
panic!("failed to find host: line in rustc output")
|
|
||||||
}
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
// Copyright 2024 The Winit Contributors
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
//! Read test events from a stream.
|
|
||||||
|
|
||||||
use gui_test::{TestEvent, TestEventType};
|
|
||||||
use std::io::{self, Read};
|
|
||||||
|
|
||||||
/// Read events from a stream.
|
|
||||||
pub(super) struct StreamReader<R> {
|
|
||||||
/// The inner reader.
|
|
||||||
reader: Option<R>,
|
|
||||||
|
|
||||||
/// Reused buffer.
|
|
||||||
buffer: Vec<u8>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<R: Read> StreamReader<R> {
|
|
||||||
/// Create a new stream reader.
|
|
||||||
pub(super) fn new(reader: R) -> Self {
|
|
||||||
Self {
|
|
||||||
reader: Some(reader),
|
|
||||||
buffer: vec![0u8; 1024],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! leap {
|
|
||||||
($self:expr, $e:expr) => {{
|
|
||||||
match ($e) {
|
|
||||||
Ok(x) => x,
|
|
||||||
Err(err) => {
|
|
||||||
($self).reader = None;
|
|
||||||
return Some(Err(err));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}};
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<R: Read> Iterator for StreamReader<R> {
|
|
||||||
type Item = io::Result<TestEvent>;
|
|
||||||
|
|
||||||
fn next(&mut self) -> Option<Self::Item> {
|
|
||||||
let reader = self.reader.as_mut()?;
|
|
||||||
|
|
||||||
// Read eight bytes from the reader to get payload length.
|
|
||||||
let mut len_buffer = [0u8; 8];
|
|
||||||
leap!(self, reader.read_exact(&mut len_buffer));
|
|
||||||
|
|
||||||
// Parse that, then read the length's worth of bytes.
|
|
||||||
let length = u64::from_be_bytes(len_buffer);
|
|
||||||
self.buffer.resize(length as usize, 0);
|
|
||||||
leap!(self, reader.read_exact(&mut self.buffer));
|
|
||||||
|
|
||||||
// Parse as a test event.
|
|
||||||
let event: TestEvent = leap!(
|
|
||||||
self,
|
|
||||||
serde_json::from_slice(&self.buffer)
|
|
||||||
.map_err(|err| io::Error::new(io::ErrorKind::Other, err))
|
|
||||||
);
|
|
||||||
|
|
||||||
// If this is complete, stop running.
|
|
||||||
if matches!(event.ty, TestEventType::Complete { .. }) {
|
|
||||||
self.reader = None;
|
|
||||||
}
|
|
||||||
|
|
||||||
// We are okay.
|
|
||||||
Some(Ok(event))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "gui-test"
|
|
||||||
version = "0.1.0"
|
|
||||||
rust-version.workspace = true
|
|
||||||
repository.workspace = true
|
|
||||||
license.workspace = true
|
|
||||||
edition.workspace = true
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
async-executor = "1.8.0"
|
|
||||||
async-io.workspace = true
|
|
||||||
async-lock = "3.3.0"
|
|
||||||
async-process = "2.1.0"
|
|
||||||
inventory = "0.3.15"
|
|
||||||
owo-colors = "4.0.0"
|
|
||||||
serde = { workspace = true, features = ["derive"] }
|
|
||||||
serde_json.workspace = true
|
|
||||||
@@ -1,443 +0,0 @@
|
|||||||
//! A testing framework that can be run remotely.
|
|
||||||
|
|
||||||
pub mod remote;
|
|
||||||
pub mod stream;
|
|
||||||
pub mod user;
|
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use std::env;
|
|
||||||
use std::ffi::{OsStr, OsString};
|
|
||||||
use std::mem;
|
|
||||||
use std::num::NonZeroUsize;
|
|
||||||
use std::panic;
|
|
||||||
|
|
||||||
const GUI_TEST_CURRENT_TEST_NAME: &str = "GUI_TEST_CURRENT_TEST_NAME";
|
|
||||||
const GUI_TEST_SUBPROCESS_LIMIT: &str = "GUI_TEST_SUBPROCESS_LIMIT";
|
|
||||||
const DEFAULT_LIMIT: usize = 1;
|
|
||||||
|
|
||||||
#[doc(hidden)]
|
|
||||||
pub use inventory as __inventory;
|
|
||||||
|
|
||||||
/// Replacement for the `main` function.
|
|
||||||
#[macro_export]
|
|
||||||
macro_rules! main {
|
|
||||||
($handler:expr) => {
|
|
||||||
fn main() {
|
|
||||||
$crate::__entry(|| $handler)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set up a test for the test framework.
|
|
||||||
#[macro_export]
|
|
||||||
macro_rules! test {
|
|
||||||
(
|
|
||||||
$(#[$attr:meta])*
|
|
||||||
fn $name:ident ($hname:ident : $htype:ty) $bl:block
|
|
||||||
) => {
|
|
||||||
const _: () = {
|
|
||||||
$(#[$attr])*
|
|
||||||
fn $name ($hname: $htype) $bl
|
|
||||||
|
|
||||||
$crate::__inventory::submit! {
|
|
||||||
$crate::__TestStart::__new(
|
|
||||||
stringify!($name),
|
|
||||||
$name
|
|
||||||
)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Test start.
|
|
||||||
#[doc(hidden)]
|
|
||||||
pub struct __TestStart {
|
|
||||||
/// The name of the test.
|
|
||||||
name: &'static str,
|
|
||||||
|
|
||||||
/// The function to call.
|
|
||||||
func: fn(&mut Harness),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl __TestStart {
|
|
||||||
/// Create a new test start.
|
|
||||||
#[doc(hidden)]
|
|
||||||
pub const fn __new(name: &'static str, func: fn(&mut Harness)) -> Self {
|
|
||||||
Self { name, func }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
inventory::collect! {
|
|
||||||
__TestStart
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A harness for running the tests.
|
|
||||||
pub struct Harness {
|
|
||||||
/// Name of the test start.
|
|
||||||
name: String,
|
|
||||||
|
|
||||||
/// The inner test handler.
|
|
||||||
handler: Box<dyn TestHandler + Send + 'static>,
|
|
||||||
|
|
||||||
/// Number of tests that have been run so far.
|
|
||||||
test_count: usize,
|
|
||||||
|
|
||||||
/// Number of tests that have failed so far.
|
|
||||||
test_fails: usize,
|
|
||||||
|
|
||||||
/// Number of tests that have succeeded.
|
|
||||||
test_passed: usize,
|
|
||||||
|
|
||||||
/// Current state of the test harness.
|
|
||||||
state: State,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Harness {
|
|
||||||
/// Create a new test harness.
|
|
||||||
fn new<H: TestHandler + Send + 'static>(name: &str, handler: H) -> Self {
|
|
||||||
Self {
|
|
||||||
name: name.to_string(),
|
|
||||||
handler: Box::new(handler),
|
|
||||||
test_count: 0,
|
|
||||||
test_fails: 0,
|
|
||||||
test_passed: 0,
|
|
||||||
state: State::Default,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Begin a test.
|
|
||||||
pub fn test(&mut self, name: impl Into<String>) -> Testing<'_> {
|
|
||||||
// Make sure we aren't mid test.
|
|
||||||
match mem::replace(&mut self.state, State::Default) {
|
|
||||||
State::InTest { past_groups } => {
|
|
||||||
self.state = State::InTest { past_groups };
|
|
||||||
panic!("tried to start a test while another was underway");
|
|
||||||
}
|
|
||||||
|
|
||||||
State::InGroups(groups) => {
|
|
||||||
self.state = State::InTest {
|
|
||||||
past_groups: Some(groups),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
State::Default => {
|
|
||||||
self.state = State::InTest { past_groups: None };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send the "test started" event to the handler.
|
|
||||||
self.send_event(TestEventType::TestStarted { name: name.into() });
|
|
||||||
|
|
||||||
// Return the handle.
|
|
||||||
Testing {
|
|
||||||
harness: Some(self),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Run a closure as a test.
|
|
||||||
pub fn with_test<T>(&mut self, name: impl Into<String>, f: impl FnOnce() -> T) -> T {
|
|
||||||
let test = self.test(name.into());
|
|
||||||
match panic::catch_unwind(panic::AssertUnwindSafe(f)) {
|
|
||||||
Ok(x) => x,
|
|
||||||
|
|
||||||
Err(err) => {
|
|
||||||
if let Some(panic) = err.downcast_ref::<&'static str>() {
|
|
||||||
test.fail(panic.to_string());
|
|
||||||
} else if let Some(panic) = err.downcast_ref::<String>() {
|
|
||||||
test.fail(panic.clone());
|
|
||||||
} else {
|
|
||||||
test.fail("unintelligible error".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
panic::resume_unwind(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Begin a test group.
|
|
||||||
pub fn group(&mut self, name: impl Into<String>) -> Grouping<'_> {
|
|
||||||
// Make sure we can begin a group.
|
|
||||||
match mem::replace(&mut self.state, State::Default) {
|
|
||||||
State::Default => {
|
|
||||||
self.state = State::InGroups(NonZeroUsize::new(1).unwrap());
|
|
||||||
}
|
|
||||||
State::InGroups(groups) => {
|
|
||||||
self.state = State::InGroups(groups.checked_add(1).unwrap());
|
|
||||||
}
|
|
||||||
State::InTest { past_groups } => {
|
|
||||||
self.state = State::InTest { past_groups };
|
|
||||||
panic!("cannot start group mid-test")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send the "group started" event to the handler.
|
|
||||||
self.send_event(TestEventType::GroupStarted { name: name.into() });
|
|
||||||
|
|
||||||
// Return the handle.
|
|
||||||
Grouping { harness: self }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Run a closure inside of a group.
|
|
||||||
pub fn with_group<T>(&mut self, name: impl Into<String>, f: impl FnOnce(&mut Self) -> T) -> T {
|
|
||||||
let mut group = self.group(name.into());
|
|
||||||
f(group.harness())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// End an ongoing test.
|
|
||||||
fn end_test(&mut self, reason: TestResult) {
|
|
||||||
self.test_count += 1;
|
|
||||||
match &reason {
|
|
||||||
TestResult::Passed => self.test_passed += 1,
|
|
||||||
TestResult::Failed(..) => self.test_fails += 1,
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
self.send_event(TestEventType::TestEnded { result: reason });
|
|
||||||
|
|
||||||
let count = match mem::replace(&mut self.state, State::Default) {
|
|
||||||
State::InTest { past_groups } => past_groups,
|
|
||||||
_ => unreachable!(),
|
|
||||||
};
|
|
||||||
|
|
||||||
self.state = match count {
|
|
||||||
None => State::Default,
|
|
||||||
Some(count) => State::InGroups(count),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// End the current group.
|
|
||||||
fn end_group(&mut self) {
|
|
||||||
self.send_event(TestEventType::GroupEnded);
|
|
||||||
|
|
||||||
let count = match mem::replace(&mut self.state, State::Default) {
|
|
||||||
State::InGroups(groups) => groups,
|
|
||||||
_ => unreachable!(),
|
|
||||||
};
|
|
||||||
|
|
||||||
self.state = match NonZeroUsize::new(count.get() - 1) {
|
|
||||||
None => State::Default,
|
|
||||||
Some(groups) => State::InGroups(groups),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Send a test event of the provided type.
|
|
||||||
fn send_event(&mut self, ty: TestEventType) {
|
|
||||||
let event = TestEvent {
|
|
||||||
runner: self.name.clone(),
|
|
||||||
ty,
|
|
||||||
};
|
|
||||||
|
|
||||||
self.handler.handle_test(event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for Harness {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
self.send_event(TestEventType::Complete {
|
|
||||||
total: self.test_count,
|
|
||||||
fail: self.test_fails,
|
|
||||||
pass: self.test_passed,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An in-progress test.
|
|
||||||
pub struct Testing<'a> {
|
|
||||||
harness: Option<&'a mut Harness>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Testing<'_> {
|
|
||||||
/// Skip this test.
|
|
||||||
pub fn skip(mut self) {
|
|
||||||
// Send the "skipped" event.
|
|
||||||
self.harness.take().unwrap().end_test(TestResult::Skipped);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Fail this test.
|
|
||||||
fn fail(mut self, panic: String) {
|
|
||||||
self.harness
|
|
||||||
.take()
|
|
||||||
.unwrap()
|
|
||||||
.end_test(TestResult::Failed(panic));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for Testing<'_> {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
if let Some(harness) = self.harness.take() {
|
|
||||||
let result = if std::thread::panicking() {
|
|
||||||
TestResult::Failed("thread panicked".into())
|
|
||||||
} else {
|
|
||||||
TestResult::Passed
|
|
||||||
};
|
|
||||||
|
|
||||||
harness.end_test(result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// We are running a test group.
|
|
||||||
pub struct Grouping<'a> {
|
|
||||||
harness: &'a mut Harness,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Grouping<'_> {
|
|
||||||
/// Get the underlying test harness.
|
|
||||||
pub fn harness(&mut self) -> &mut Harness {
|
|
||||||
&mut self.harness
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for Grouping<'_> {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
self.harness.end_group();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Current testing state.
|
|
||||||
enum State {
|
|
||||||
/// We are in the middle of this many groups.
|
|
||||||
InGroups(NonZeroUsize),
|
|
||||||
|
|
||||||
/// We are in the middle of a test.
|
|
||||||
InTest { past_groups: Option<NonZeroUsize> },
|
|
||||||
|
|
||||||
/// We are in the default state.
|
|
||||||
Default,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A handler for incoming test events.
|
|
||||||
pub trait TestHandler {
|
|
||||||
/// Handle a test.
|
|
||||||
fn handle_test(&mut self, event: TestEvent);
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: TestHandler + ?Sized> TestHandler for Box<T> {
|
|
||||||
fn handle_test(&mut self, event: TestEvent) {
|
|
||||||
(**self).handle_test(event)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An event produced by the test harness.
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
|
||||||
pub struct TestEvent {
|
|
||||||
/// The name of the runner associated with the event.
|
|
||||||
pub runner: String,
|
|
||||||
|
|
||||||
/// The type of the event.
|
|
||||||
pub ty: TestEventType,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The type of the event.
|
|
||||||
#[non_exhaustive]
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
|
||||||
pub enum TestEventType {
|
|
||||||
/// The tests are complete and the harness can be disconnected.
|
|
||||||
Complete {
|
|
||||||
/// Total number of tests.
|
|
||||||
total: usize,
|
|
||||||
|
|
||||||
/// Total number of passing tests.
|
|
||||||
pass: usize,
|
|
||||||
|
|
||||||
/// Total number of failed tests.
|
|
||||||
fail: usize,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// A test has started.
|
|
||||||
TestStarted { name: String },
|
|
||||||
|
|
||||||
/// A test has completed.
|
|
||||||
TestEnded { result: TestResult },
|
|
||||||
|
|
||||||
/// A test group has started.
|
|
||||||
GroupStarted { name: String },
|
|
||||||
|
|
||||||
/// A test group has ended.
|
|
||||||
GroupEnded,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The result of a test.
|
|
||||||
#[non_exhaustive]
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
|
||||||
pub enum TestResult {
|
|
||||||
/// The test passed.
|
|
||||||
Passed,
|
|
||||||
|
|
||||||
/// The test failed with the provided error.
|
|
||||||
Failed(String),
|
|
||||||
|
|
||||||
/// The test was skipped.
|
|
||||||
Skipped,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Entry point of the test.
|
|
||||||
#[doc(hidden)]
|
|
||||||
pub fn __entry<H: TestHandler + Send + 'static>(handler: impl FnOnce() -> H) {
|
|
||||||
// Look for the test name environment variable.
|
|
||||||
if let Some(test_name) = env::var(GUI_TEST_CURRENT_TEST_NAME)
|
|
||||||
.ok()
|
|
||||||
.filter(|test_name| !test_name.is_empty())
|
|
||||||
{
|
|
||||||
// Find the provided test.
|
|
||||||
let test_to_run = inventory::iter::<__TestStart>
|
|
||||||
.into_iter()
|
|
||||||
.find(|test| test.name == test_name)
|
|
||||||
.unwrap_or_else(|| panic!("unable to find test '{test_name}'"));
|
|
||||||
|
|
||||||
// Create a harness.
|
|
||||||
let mut harness = Harness::new(test_to_run.name, handler());
|
|
||||||
|
|
||||||
// Run the test.
|
|
||||||
panic::catch_unwind(panic::AssertUnwindSafe(move || {
|
|
||||||
(test_to_run.func)(&mut harness)
|
|
||||||
}))
|
|
||||||
.ok();
|
|
||||||
} else {
|
|
||||||
// Run a subprocess for every test.
|
|
||||||
let limit = env::var(GUI_TEST_SUBPROCESS_LIMIT)
|
|
||||||
.ok()
|
|
||||||
.and_then(|limit| limit.parse::<usize>().ok())
|
|
||||||
.unwrap_or(DEFAULT_LIMIT);
|
|
||||||
let process_name = env::args_os().next().unwrap();
|
|
||||||
|
|
||||||
let sema = async_lock::Semaphore::new(limit);
|
|
||||||
let ex = async_executor::Executor::new();
|
|
||||||
|
|
||||||
async_io::block_on(ex.run(async {
|
|
||||||
let mut tasks = vec![];
|
|
||||||
|
|
||||||
// Set up an environment variable for this.
|
|
||||||
for test in inventory::iter::<__TestStart> {
|
|
||||||
// Acquire a guard.
|
|
||||||
let guard = sema.acquire().await;
|
|
||||||
|
|
||||||
// Spawn a subprocess.
|
|
||||||
let mut process = async_process::Command::new(&process_name)
|
|
||||||
.envs(env::vars_os().chain(Some({
|
|
||||||
(path(&GUI_TEST_CURRENT_TEST_NAME), path(&test.name))
|
|
||||||
})))
|
|
||||||
.spawn()
|
|
||||||
.expect("failed to spawn child process");
|
|
||||||
|
|
||||||
// Spawn a task to poll that subprocess.
|
|
||||||
let task = ex.spawn(async move {
|
|
||||||
let _guard = guard;
|
|
||||||
process.status().await.unwrap()
|
|
||||||
});
|
|
||||||
|
|
||||||
tasks.push(task);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Finish all of the tasks.
|
|
||||||
for task in tasks {
|
|
||||||
task.await;
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn path<A: AsRef<OsStr>>(s: &A) -> OsString {
|
|
||||||
s.as_ref().into()
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
//! Create a test handler that can be run remotely.
|
|
||||||
|
|
||||||
use crate::stream::WriteHandler;
|
|
||||||
use crate::user::UserHandler;
|
|
||||||
use crate::TestHandler;
|
|
||||||
|
|
||||||
use std::env;
|
|
||||||
use std::net::TcpStream;
|
|
||||||
|
|
||||||
/// Create a test handler adjusted for the current environment.
|
|
||||||
pub fn handler() -> Box<dyn TestHandler + Send + 'static> {
|
|
||||||
// If GUI_TEST_UNIX_STREAM is enabled, use that as a Unix stream.
|
|
||||||
#[cfg(unix)]
|
|
||||||
if let Some(stream_path) = env::var_os("GUI_TEST_UNIX_STREAM").filter(|s| !s.is_empty()) {
|
|
||||||
let stream = std::os::unix::net::UnixStream::connect(stream_path)
|
|
||||||
.expect("unable to connect to gui-test handler");
|
|
||||||
return Box::new(WriteHandler::new(stream));
|
|
||||||
}
|
|
||||||
|
|
||||||
// If GUI_TEST_TCP_STREAM is enabled, use that as a TCP stream.
|
|
||||||
if let Some(tcp_ip) = env::var("GUI_TEST_TCP_STREAM")
|
|
||||||
.ok()
|
|
||||||
.filter(|s| !s.is_empty())
|
|
||||||
{
|
|
||||||
let stream = TcpStream::connect(tcp_ip).unwrap();
|
|
||||||
return Box::new(WriteHandler::new(stream));
|
|
||||||
}
|
|
||||||
|
|
||||||
// By default, use the user handler.
|
|
||||||
Box::new(UserHandler::new())
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
//! Write events to an output stream.
|
|
||||||
//!
|
|
||||||
//! The format is as follows:
|
|
||||||
//! - First 8 bytes: big-endian length of payload.
|
|
||||||
//! - Next {len} bytes: JSON payload to deserialize from.
|
|
||||||
|
|
||||||
use crate::{TestEvent, TestHandler};
|
|
||||||
use std::io::Write;
|
|
||||||
|
|
||||||
/// A wrapper around a writer that sends data down a stream.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct WriteHandler<W: Write> {
|
|
||||||
/// The inner writer.
|
|
||||||
writer: W,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<W: Write> WriteHandler<W> {
|
|
||||||
/// Create a new write handler.
|
|
||||||
pub fn new(writer: W) -> Self {
|
|
||||||
Self { writer }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<W: Write> TestHandler for WriteHandler<W> {
|
|
||||||
fn handle_test(&mut self, event: TestEvent) {
|
|
||||||
let payload = serde_json::to_vec(&event).unwrap();
|
|
||||||
let length = u64::to_be_bytes(payload.len() as u64);
|
|
||||||
|
|
||||||
// Write the payload to the stream.
|
|
||||||
self.writer.write_all(&length).unwrap();
|
|
||||||
self.writer.write_all(&payload).unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<W: Write> Drop for WriteHandler<W> {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
self.writer.flush().ok();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,180 +0,0 @@
|
|||||||
//! User-facing reporter.
|
|
||||||
|
|
||||||
use crate::{TestEvent, TestEventType, TestHandler, TestResult};
|
|
||||||
use owo_colors::OwoColorize;
|
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
use std::io::{self, prelude::*};
|
|
||||||
|
|
||||||
const TABSIZE: usize = 2;
|
|
||||||
|
|
||||||
/// User-facing reporter.
|
|
||||||
///
|
|
||||||
/// This reporter dumps events to the console in a user-readable format.
|
|
||||||
pub struct UserHandler {
|
|
||||||
/// Current indent.
|
|
||||||
indent: usize,
|
|
||||||
|
|
||||||
/// The test set we're currently displaying.
|
|
||||||
current_start: Option<String>,
|
|
||||||
|
|
||||||
/// Test name we are running, if any.
|
|
||||||
test_name: Option<String>,
|
|
||||||
|
|
||||||
/// Cached events.
|
|
||||||
cache: BTreeMap<String, Vec<TestEventType>>,
|
|
||||||
|
|
||||||
/// Failures we had.
|
|
||||||
failures: Vec<(String, String)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl UserHandler {
|
|
||||||
/// Create a new handler.
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
indent: 0,
|
|
||||||
current_start: None,
|
|
||||||
test_name: None,
|
|
||||||
cache: BTreeMap::new(),
|
|
||||||
failures: vec![],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Process the provided events.
|
|
||||||
fn process_events(&mut self, events: impl IntoIterator<Item = TestEvent>) {
|
|
||||||
for event in events {
|
|
||||||
// Tell if this is an end event.
|
|
||||||
let mut ender = matches!(event.ty, TestEventType::Complete { .. });
|
|
||||||
|
|
||||||
// If there is no test name set, run the current one.
|
|
||||||
match self.current_start.as_ref() {
|
|
||||||
None => {
|
|
||||||
let TestEvent { runner, ty } = event;
|
|
||||||
self.current_start = Some(runner);
|
|
||||||
self.dump_events(Some(ty));
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(test_name) => {
|
|
||||||
// If there is a test name set and it's ours, post it immediately.
|
|
||||||
if test_name == &event.runner {
|
|
||||||
self.dump_events(Some(event.ty));
|
|
||||||
} else {
|
|
||||||
// Add it to the back of another one of the events.
|
|
||||||
self.cache
|
|
||||||
.entry(test_name.clone())
|
|
||||||
.or_default()
|
|
||||||
.push(event.ty);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If this is the end, dump other events.
|
|
||||||
while ender {
|
|
||||||
ender = false;
|
|
||||||
assert!(self.current_start.take().is_some());
|
|
||||||
|
|
||||||
// Pick one set.
|
|
||||||
if let Some(entry) = self.cache.first_entry() {
|
|
||||||
let (test_name, entries) = entry.remove_entry();
|
|
||||||
self.current_start = Some(test_name);
|
|
||||||
|
|
||||||
// Dump events and look for a conclusion.
|
|
||||||
self.dump_events(entries.into_iter().inspect(|ty| {
|
|
||||||
ender |= matches!(ty, TestEventType::Complete { .. });
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
println!();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Dump the provided events to the console.
|
|
||||||
fn dump_events(&mut self, events: impl IntoIterator<Item = TestEventType>) {
|
|
||||||
let mut stdout = io::stdout().lock();
|
|
||||||
|
|
||||||
for event in events {
|
|
||||||
// Write the indent.
|
|
||||||
for _ in 0..(self.indent * TABSIZE) {
|
|
||||||
stdout.write_all(b" ").unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
match event {
|
|
||||||
TestEventType::GroupStarted { name } => {
|
|
||||||
assert!(self.test_name.is_none());
|
|
||||||
|
|
||||||
// Write the group name and bump the indent.
|
|
||||||
writeln!(stdout, "{}", name.yellow().italic()).unwrap();
|
|
||||||
|
|
||||||
// Add to the indent.
|
|
||||||
self.indent += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
TestEventType::GroupEnded => {
|
|
||||||
assert!(self.test_name.is_none());
|
|
||||||
|
|
||||||
// Drop the indent.
|
|
||||||
self.indent = self.indent.checked_sub(1).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
TestEventType::TestStarted { name } => {
|
|
||||||
assert!(self.test_name.is_none());
|
|
||||||
|
|
||||||
// Write the line.
|
|
||||||
write!(stdout, "{} ", name.white().italic()).unwrap();
|
|
||||||
self.test_name = Some(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
TestEventType::TestEnded { result } => {
|
|
||||||
let test_name = self.test_name.take().unwrap();
|
|
||||||
|
|
||||||
// Write the result.
|
|
||||||
match result {
|
|
||||||
TestResult::Passed => {
|
|
||||||
writeln!(stdout, "{}", "ok".green().bold()).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
TestResult::Failed(failure) => {
|
|
||||||
self.failures.push((test_name, failure));
|
|
||||||
writeln!(stdout, "{}", "FAIL".red().bold()).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
TestResult::Skipped => {
|
|
||||||
writeln!(stdout, "{}", "skipped".yellow().bold()).unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_ => {
|
|
||||||
// Completion.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TestHandler for UserHandler {
|
|
||||||
fn handle_test(&mut self, event: TestEvent) {
|
|
||||||
self.process_events(Some(event));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for UserHandler {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
assert!(self.cache.is_empty());
|
|
||||||
|
|
||||||
// Write the final bit to the stdout.
|
|
||||||
let mut stdout = io::stdout().lock();
|
|
||||||
|
|
||||||
if !self.failures.is_empty() {
|
|
||||||
writeln!(stdout, "Test Failures:").ok();
|
|
||||||
|
|
||||||
for (test_name, panic) in &self.failures {
|
|
||||||
writeln!(stdout, " {}", test_name).ok();
|
|
||||||
writeln!(stdout, "-------------").ok();
|
|
||||||
writeln!(stdout, "{}", panic).ok();
|
|
||||||
writeln!(stdout, "-------------").ok();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "run-wasm"
|
|
||||||
version = "0.1.0"
|
|
||||||
rust-version.workspace = true
|
|
||||||
repository.workspace = true
|
|
||||||
license.workspace = true
|
|
||||||
edition.workspace = true
|
|
||||||
publish = false
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
cargo-run-wasm = "0.2.0"
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
cargo_run_wasm::run_wasm_with_css("body { margin: 0px; }");
|
|
||||||
}
|
|
||||||
23
rustfmt.toml
23
rustfmt.toml
@@ -1,3 +1,20 @@
|
|||||||
force_explicit_abi=true
|
comment_width = 100
|
||||||
use_field_init_shorthand=true
|
condense_wildcard_suffixes = true
|
||||||
# merge_imports=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
|
||||||
|
# Some macros break with this.
|
||||||
|
reorder_impl_items = false
|
||||||
|
use_field_init_shorthand = true
|
||||||
|
use_small_heuristics = "Max"
|
||||||
|
wrap_comments = true
|
||||||
|
|||||||
@@ -2,96 +2,202 @@
|
|||||||
|
|
||||||
use crate::event::{DeviceEvent, DeviceId, StartCause, WindowEvent};
|
use crate::event::{DeviceEvent, DeviceId, StartCause, WindowEvent};
|
||||||
use crate::event_loop::ActiveEventLoop;
|
use crate::event_loop::ActiveEventLoop;
|
||||||
|
#[cfg(any(docsrs, macos_platform))]
|
||||||
|
use crate::platform::macos::ApplicationHandlerExtMacOS;
|
||||||
use crate::window::WindowId;
|
use crate::window::WindowId;
|
||||||
|
|
||||||
/// The handler of the application events.
|
/// The handler of the application events.
|
||||||
pub trait ApplicationHandler<T: 'static = ()> {
|
pub trait ApplicationHandler {
|
||||||
/// Emitted when new events arrive from the OS to be processed.
|
/// Emitted when new events arrive from the OS to be processed.
|
||||||
///
|
///
|
||||||
/// This is a useful place to put code that should be done before you start processing
|
/// 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
|
/// events, such as updating frame timing information for benchmarking or checking the
|
||||||
/// [`StartCause`] to see if a timer set by
|
/// [`StartCause`] to see if a timer set by
|
||||||
/// [`ControlFlow::WaitUntil`][crate::event_loop::ControlFlow::WaitUntil] has elapsed.
|
/// [`ControlFlow::WaitUntil`][crate::event_loop::ControlFlow::WaitUntil] has elapsed.
|
||||||
fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
|
fn new_events(&mut self, event_loop: &dyn ActiveEventLoop, cause: StartCause) {
|
||||||
let _ = (event_loop, cause);
|
let _ = (event_loop, cause);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Emitted when the application has been resumed.
|
/// Emitted when the application has been resumed.
|
||||||
///
|
///
|
||||||
/// For consistency, all platforms emit a `Resumed` event even if they don't themselves have a
|
/// See [`suspended()`][Self::suspended].
|
||||||
/// 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
|
/// ## Platform-specific
|
||||||
///
|
///
|
||||||
/// It's recommended that applications should only initialize their graphics context and create
|
/// ### iOS
|
||||||
/// 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
|
/// On iOS, the [`resumed()`] method is called in response to an [`applicationDidBecomeActive`]
|
||||||
/// driven by multiple platform-specific events, and that there may be subtle differences across
|
/// callback which means the application is about to transition from the inactive to active
|
||||||
/// platforms with how these internal events are delivered, it's recommended that applications
|
/// state (according to the [iOS application lifecycle]).
|
||||||
/// 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
|
/// [`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
|
/// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle
|
||||||
///
|
///
|
||||||
/// ## Web
|
/// ### Web
|
||||||
///
|
///
|
||||||
/// On Web, the `Resumed` event is emitted in response to a [`pageshow`] event
|
/// On Web, the [`resumed()`] method is called in response to a [`pageshow`] event if the
|
||||||
/// with the property [`persisted`] being true, which means that the page is being
|
/// page is being restored from the [`bfcache`] (back/forward cache) - an in-memory cache
|
||||||
/// restored from the [`bfcache`] (back/forward cache) - an in-memory cache that
|
/// that stores a complete snapshot of a page (including the JavaScript heap) as the user is
|
||||||
/// stores a complete snapshot of a page (including the JavaScript heap) as the
|
/// navigating away.
|
||||||
/// user is navigating away.
|
|
||||||
///
|
///
|
||||||
/// [`pageshow`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event
|
/// [`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/
|
/// [`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
|
/// ### Android
|
||||||
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: T) {
|
///
|
||||||
let _ = (event_loop, event);
|
/// On Android, the [`resumed()`] method is called when the `Activity` is (again, if after a
|
||||||
|
/// prior [`suspended()`]) being displayed to the user. This is a good place to begin drawing
|
||||||
|
/// visual elements, running animations, etc. It is driven by Android's [`onStart()`] method.
|
||||||
|
///
|
||||||
|
/// [`onStart()`]: https://developer.android.com/reference/android/app/Activity#onStart()
|
||||||
|
///
|
||||||
|
/// ### Others
|
||||||
|
///
|
||||||
|
/// **macOS / Orbital / Wayland / Windows / X11:** Unsupported.
|
||||||
|
///
|
||||||
|
/// [`resumed()`]: Self::resumed()
|
||||||
|
/// [`suspended()`]: Self::suspended()
|
||||||
|
/// [`exiting()`]: Self::exiting()
|
||||||
|
fn resumed(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
let _ = event_loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emitted from the point onwards the application should create render surfaces.
|
||||||
|
///
|
||||||
|
/// See [`destroy_surfaces()`].
|
||||||
|
///
|
||||||
|
/// ## Portability
|
||||||
|
///
|
||||||
|
/// It's recommended that applications should only initialize their render surfaces after the
|
||||||
|
/// [`can_create_surfaces()`] method is called. Some systems (specifically Android) won't allow
|
||||||
|
/// applications to create a render surface until that point.
|
||||||
|
///
|
||||||
|
/// For consistency, all platforms call this method even if they don't themselves have a formal
|
||||||
|
/// surface destroy/create lifecycle. For systems without a surface destroy/create lifecycle the
|
||||||
|
/// [`can_create_surfaces()`] event is always emitted after the [`StartCause::Init`] event.
|
||||||
|
///
|
||||||
|
/// Applications should be able to gracefully handle back-to-back [`can_create_surfaces()`] and
|
||||||
|
/// [`destroy_surfaces()`] calls.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// ### Android
|
||||||
|
///
|
||||||
|
/// On Android, the [`can_create_surfaces()`] method is called when a new [`NativeWindow`]
|
||||||
|
/// (native [`Surface`]) is created which backs the application window. This is expected to
|
||||||
|
/// closely correlate with the [`onStart`] lifecycle event which typically results in a surface
|
||||||
|
/// to be created after the app becomes visible.
|
||||||
|
///
|
||||||
|
/// Applications that need to run on Android must wait until they have received a surface before
|
||||||
|
/// they will be able to create a render surface (such as an `EGLSurface`, [`VkSurfaceKHR`]
|
||||||
|
/// or [`wgpu::Surface`]) which depend on having a [`NativeWindow`]. Applications must handle
|
||||||
|
/// [`destroy_surfaces()`], where their render surfaces are invalid and should be dropped.
|
||||||
|
///
|
||||||
|
/// [`NativeWindow`]: https://developer.android.com/ndk/reference/group/a-native-window
|
||||||
|
/// [`Surface`]: https://developer.android.com/reference/android/view/Surface
|
||||||
|
/// [`onStart`]: https://developer.android.com/reference/android/app/Activity#onStart()
|
||||||
|
/// [`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
|
||||||
|
///
|
||||||
|
/// [`can_create_surfaces()`]: Self::can_create_surfaces()
|
||||||
|
/// [`destroy_surfaces()`]: Self::destroy_surfaces()
|
||||||
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop);
|
||||||
|
|
||||||
|
/// Called after a wake up is requested using [`EventLoopProxy::wake_up()`].
|
||||||
|
///
|
||||||
|
/// Multiple calls to the aforementioned method will be merged, and will only wake the event
|
||||||
|
/// loop once; however, due to the nature of multi-threading some wake ups may appear
|
||||||
|
/// spuriously. For these reasons, you should not rely on the number of times that this was
|
||||||
|
/// called.
|
||||||
|
///
|
||||||
|
/// The order in which this is emitted in relation to other events is not guaranteed. The time
|
||||||
|
/// at which this will be emitted is not guaranteed, only that it will happen "soon". That is,
|
||||||
|
/// there may be several executions of the event loop, including multiple redraws to windows,
|
||||||
|
/// between [`EventLoopProxy::wake_up()`] being called and the event being delivered.
|
||||||
|
///
|
||||||
|
/// [`EventLoopProxy::wake_up()`]: crate::event_loop::EventLoopProxy::wake_up
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// Use a [`std::sync::mpsc`] channel to handle events from a different thread.
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// use std::sync::mpsc;
|
||||||
|
/// use std::thread;
|
||||||
|
/// use std::time::Duration;
|
||||||
|
///
|
||||||
|
/// use winit::application::ApplicationHandler;
|
||||||
|
/// use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
|
///
|
||||||
|
/// struct MyApp {
|
||||||
|
/// receiver: mpsc::Receiver<u64>,
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// impl ApplicationHandler for MyApp {
|
||||||
|
/// # fn window_event(
|
||||||
|
/// # &mut self,
|
||||||
|
/// # _event_loop: &dyn ActiveEventLoop,
|
||||||
|
/// # _window_id: winit::window::WindowId,
|
||||||
|
/// # _event: winit::event::WindowEvent,
|
||||||
|
/// # ) {
|
||||||
|
/// # }
|
||||||
|
/// #
|
||||||
|
/// # fn can_create_surfaces(&mut self, _event_loop: &dyn ActiveEventLoop) {}
|
||||||
|
/// #
|
||||||
|
/// fn proxy_wake_up(&mut self, _event_loop: &dyn ActiveEventLoop) {
|
||||||
|
/// // Iterate current events, since wake-ups may have been merged.
|
||||||
|
/// //
|
||||||
|
/// // Note: We take care not to use `recv` or `iter` here, as those are blocking,
|
||||||
|
/// // and that would be bad for performance and might lead to a deadlock.
|
||||||
|
/// for i in self.receiver.try_iter() {
|
||||||
|
/// println!("received: {i}");
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// // Rest of `ApplicationHandler`
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
/// let event_loop = EventLoop::new()?;
|
||||||
|
///
|
||||||
|
/// let (sender, receiver) = mpsc::channel();
|
||||||
|
///
|
||||||
|
/// let mut app = MyApp { receiver };
|
||||||
|
///
|
||||||
|
/// // Send an event in a loop
|
||||||
|
/// let proxy = event_loop.create_proxy();
|
||||||
|
/// let background_thread = thread::spawn(move || {
|
||||||
|
/// let mut i = 0;
|
||||||
|
/// loop {
|
||||||
|
/// println!("sending: {i}");
|
||||||
|
/// if sender.send(i).is_err() {
|
||||||
|
/// // Stop sending once `MyApp` is dropped
|
||||||
|
/// break;
|
||||||
|
/// }
|
||||||
|
/// // Trigger the wake-up _after_ we placed the event in the channel.
|
||||||
|
/// // Otherwise, `proxy_wake_up` might be triggered prematurely.
|
||||||
|
/// proxy.wake_up();
|
||||||
|
/// i += 1;
|
||||||
|
/// thread::sleep(Duration::from_secs(1));
|
||||||
|
/// }
|
||||||
|
/// });
|
||||||
|
///
|
||||||
|
/// event_loop.run_app(&mut app)?;
|
||||||
|
///
|
||||||
|
/// drop(app);
|
||||||
|
/// background_thread.join().unwrap();
|
||||||
|
///
|
||||||
|
/// Ok(())
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
fn proxy_wake_up(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
let _ = event_loop;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Emitted when the OS sends an event to a winit window.
|
/// Emitted when the OS sends an event to a winit window.
|
||||||
fn window_event(
|
fn window_event(
|
||||||
&mut self,
|
&mut self,
|
||||||
event_loop: &ActiveEventLoop,
|
event_loop: &dyn ActiveEventLoop,
|
||||||
window_id: WindowId,
|
window_id: WindowId,
|
||||||
event: WindowEvent,
|
event: WindowEvent,
|
||||||
);
|
);
|
||||||
@@ -99,8 +205,8 @@ pub trait ApplicationHandler<T: 'static = ()> {
|
|||||||
/// Emitted when the OS sends an event to a device.
|
/// Emitted when the OS sends an event to a device.
|
||||||
fn device_event(
|
fn device_event(
|
||||||
&mut self,
|
&mut self,
|
||||||
event_loop: &ActiveEventLoop,
|
event_loop: &dyn ActiveEventLoop,
|
||||||
device_id: DeviceId,
|
device_id: Option<DeviceId>,
|
||||||
event: DeviceEvent,
|
event: DeviceEvent,
|
||||||
) {
|
) {
|
||||||
let _ = (event_loop, device_id, event);
|
let _ = (event_loop, device_id, event);
|
||||||
@@ -109,85 +215,106 @@ pub trait ApplicationHandler<T: 'static = ()> {
|
|||||||
/// Emitted when the event loop is about to block and wait for new events.
|
/// 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
|
/// 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.
|
/// 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
|
/// High frequency event sources, such as input devices could potentially lead to lots of wake
|
||||||
/// ups and also lots of corresponding `AboutToWait` events.
|
/// ups and also lots of corresponding `AboutToWait` events.
|
||||||
///
|
///
|
||||||
/// This is not an ideal event to drive application rendering from and instead applications
|
/// This is not an ideal event to drive application rendering from and instead applications
|
||||||
/// should render in response to [`WindowEvent::RedrawRequested`] events.
|
/// should render in response to [`WindowEvent::RedrawRequested`] events.
|
||||||
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
fn about_to_wait(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
let _ = event_loop;
|
let _ = event_loop;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Emitted when the application has been suspended.
|
/// Emitted when the application has been suspended.
|
||||||
///
|
///
|
||||||
/// # Portability
|
/// See [`resumed()`][Self::resumed].
|
||||||
///
|
///
|
||||||
/// Not all platforms support the notion of suspending applications, and there may be no
|
/// ## Platform-specific
|
||||||
/// 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
|
/// ### iOS
|
||||||
/// 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.
|
/// On iOS, the [`suspended()`] method is called in response to an
|
||||||
///
|
/// [`applicationWillResignActive`] callback which means that the application is about to
|
||||||
/// ## Android
|
/// transition from the active to inactive state (according to the [iOS application lifecycle]).
|
||||||
///
|
|
||||||
/// 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
|
/// [`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
|
/// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle
|
||||||
///
|
///
|
||||||
/// ## Web
|
/// ### Web
|
||||||
///
|
///
|
||||||
/// On Web, the `Suspended` event is emitted in response to a [`pagehide`] event
|
/// On Web, the [`suspended()`] method is called in response to a [`pagehide`] event if the
|
||||||
/// with the property [`persisted`] being true, which means that the page is being
|
/// page is being stored in the [`bfcache`] (back/forward cache) - an in-memory cache that
|
||||||
/// put in the [`bfcache`] (back/forward cache) - an in-memory cache that stores a
|
/// stores a complete snapshot of a page (including the JavaScript heap) as the user is
|
||||||
/// complete snapshot of a page (including the JavaScript heap) as the user is
|
|
||||||
/// navigating away.
|
/// navigating away.
|
||||||
///
|
///
|
||||||
/// [`pagehide`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event
|
/// [`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/
|
/// [`bfcache`]: https://web.dev/bfcache/
|
||||||
/// [`Resumed`]: Self::resumed
|
///
|
||||||
fn suspended(&mut self, event_loop: &ActiveEventLoop) {
|
/// ### Android
|
||||||
|
///
|
||||||
|
/// On Android, the [`suspended()`] method is called when the `Activity` is no longer visible
|
||||||
|
/// to the user. This is a good place to stop refreshing UI, running animations and other visual
|
||||||
|
/// things. It is driven by Android's [`onStop()`] method.
|
||||||
|
///
|
||||||
|
/// After this event the application either receives [`resumed()`] again, or [`exiting()`].
|
||||||
|
///
|
||||||
|
/// [`onStop()`]: https://developer.android.com/reference/android/app/Activity#onStop()
|
||||||
|
///
|
||||||
|
/// ### Others
|
||||||
|
///
|
||||||
|
/// **macOS / Orbital / Wayland / Windows / X11:** Unsupported.
|
||||||
|
///
|
||||||
|
/// [`resumed()`]: Self::resumed()
|
||||||
|
/// [`suspended()`]: Self::suspended()
|
||||||
|
/// [`exiting()`]: Self::exiting()
|
||||||
|
fn suspended(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
let _ = event_loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emitted when the application must destroy its render surfaces.
|
||||||
|
///
|
||||||
|
/// See [`can_create_surfaces()`] for more details.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// ### Android
|
||||||
|
///
|
||||||
|
/// On Android, the [`destroy_surfaces()`] method is called when the application's
|
||||||
|
/// [`NativeWindow`] (native [`Surface`]) is destroyed. This is expected to closely correlate
|
||||||
|
/// with the [`onStop`] lifecycle event which typically results in the surface to be destroyed
|
||||||
|
/// after the app becomes invisible.
|
||||||
|
///
|
||||||
|
/// Applications that need to run on Android should assume their [`NativeWindow`] 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`]).
|
||||||
|
///
|
||||||
|
/// When receiving [`destroy_surfaces()`] Android applications should drop all render surfaces
|
||||||
|
/// before the event callback completes, which may be re-created when the application next
|
||||||
|
/// receives [`can_create_surfaces()`].
|
||||||
|
///
|
||||||
|
/// [`NativeWindow`]: https://developer.android.com/ndk/reference/group/a-native-window
|
||||||
|
/// [`Surface`]: https://developer.android.com/reference/android/view/Surface
|
||||||
|
/// [`onStop`]: https://developer.android.com/reference/android/app/Activity#onStop()
|
||||||
|
/// [`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
|
||||||
|
///
|
||||||
|
/// ### Others
|
||||||
|
///
|
||||||
|
/// - **iOS / macOS / Orbital / Wayland / Web / Windows / X11:** Unsupported.
|
||||||
|
///
|
||||||
|
/// [`can_create_surfaces()`]: Self::can_create_surfaces()
|
||||||
|
/// [`destroy_surfaces()`]: Self::destroy_surfaces()
|
||||||
|
fn destroy_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
let _ = event_loop;
|
let _ = event_loop;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Emitted when the event loop is being shut down.
|
/// Emitted when the event loop is being shut down.
|
||||||
///
|
///
|
||||||
/// This is irreversible - if this method is called, it is guaranteed that the event loop
|
/// This is irreversible - if this method is called, it is guaranteed that the event loop
|
||||||
/// will exist right after.
|
/// will exit right after.
|
||||||
fn exiting(&mut self, event_loop: &ActiveEventLoop) {
|
fn exiting(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
let _ = event_loop;
|
let _ = event_loop;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -197,17 +324,17 @@ pub trait ApplicationHandler<T: 'static = ()> {
|
|||||||
///
|
///
|
||||||
/// ### Android
|
/// ### Android
|
||||||
///
|
///
|
||||||
/// On Android, the `MemoryWarning` event is sent when [`onLowMemory`] was called. The application
|
/// On Android, the `MemoryWarning` event is sent when [`onLowMemory`] was called. The
|
||||||
/// must [release memory] or risk being killed.
|
/// application must [release memory] or risk being killed.
|
||||||
///
|
///
|
||||||
/// [`onLowMemory`]: https://developer.android.com/reference/android/app/Application.html#onLowMemory()
|
/// [`onLowMemory`]: https://developer.android.com/reference/android/app/Application.html#onLowMemory()
|
||||||
/// [release memory]: https://developer.android.com/topic/performance/memory#release
|
/// [release memory]: https://developer.android.com/topic/performance/memory#release
|
||||||
///
|
///
|
||||||
/// ### iOS
|
/// ### iOS
|
||||||
///
|
///
|
||||||
/// On iOS, the `MemoryWarning` event is emitted in response to an [`applicationDidReceiveMemoryWarning`]
|
/// On iOS, the `MemoryWarning` event is emitted in response to an
|
||||||
/// callback. The application must free as much memory as possible or risk being terminated, see
|
/// [`applicationDidReceiveMemoryWarning`] callback. The application must free as much
|
||||||
/// [how to respond to memory warnings].
|
/// memory as possible or risk being terminated, see [how to respond to memory warnings].
|
||||||
///
|
///
|
||||||
/// [`applicationDidReceiveMemoryWarning`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623063-applicationdidreceivememorywarni
|
/// [`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
|
/// [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
|
||||||
@@ -215,7 +342,164 @@ pub trait ApplicationHandler<T: 'static = ()> {
|
|||||||
/// ### Others
|
/// ### Others
|
||||||
///
|
///
|
||||||
/// - **macOS / Orbital / Wayland / Web / Windows:** Unsupported.
|
/// - **macOS / Orbital / Wayland / Web / Windows:** Unsupported.
|
||||||
fn memory_warning(&mut self, event_loop: &ActiveEventLoop) {
|
fn memory_warning(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
let _ = event_loop;
|
let _ = event_loop;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The macOS-specific handler.
|
||||||
|
///
|
||||||
|
/// The return value from this should not change at runtime.
|
||||||
|
#[cfg(any(docsrs, macos_platform))]
|
||||||
|
#[inline(always)]
|
||||||
|
fn macos_handler(&mut self) -> Option<&mut dyn ApplicationHandlerExtMacOS> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[deny(clippy::missing_trait_methods)]
|
||||||
|
impl<A: ?Sized + ApplicationHandler> ApplicationHandler for &mut A {
|
||||||
|
#[inline]
|
||||||
|
fn new_events(&mut self, event_loop: &dyn ActiveEventLoop, cause: StartCause) {
|
||||||
|
(**self).new_events(event_loop, cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn resumed(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).resumed(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).can_create_surfaces(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn proxy_wake_up(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).proxy_wake_up(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
window_id: WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
(**self).window_event(event_loop, window_id, event);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn device_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
device_id: Option<DeviceId>,
|
||||||
|
event: DeviceEvent,
|
||||||
|
) {
|
||||||
|
(**self).device_event(event_loop, device_id, event);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn about_to_wait(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).about_to_wait(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn suspended(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).suspended(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn destroy_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).destroy_surfaces(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn exiting(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).exiting(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn memory_warning(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).memory_warning(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(docsrs, macos_platform))]
|
||||||
|
#[inline]
|
||||||
|
fn macos_handler(&mut self) -> Option<&mut dyn ApplicationHandlerExtMacOS> {
|
||||||
|
(**self).macos_handler()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[deny(clippy::missing_trait_methods)]
|
||||||
|
impl<A: ?Sized + ApplicationHandler> ApplicationHandler for Box<A> {
|
||||||
|
#[inline]
|
||||||
|
fn new_events(&mut self, event_loop: &dyn ActiveEventLoop, cause: StartCause) {
|
||||||
|
(**self).new_events(event_loop, cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn resumed(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).resumed(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).can_create_surfaces(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn proxy_wake_up(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).proxy_wake_up(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
window_id: WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
(**self).window_event(event_loop, window_id, event);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn device_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
device_id: Option<DeviceId>,
|
||||||
|
event: DeviceEvent,
|
||||||
|
) {
|
||||||
|
(**self).device_event(event_loop, device_id, event);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn about_to_wait(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).about_to_wait(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn suspended(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).suspended(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn destroy_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).destroy_surfaces(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn exiting(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).exiting(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn memory_warning(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
(**self).memory_warning(event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(docsrs, macos_platform))]
|
||||||
|
#[inline]
|
||||||
|
fn macos_handler(&mut self) -> Option<&mut dyn ApplicationHandlerExtMacOS> {
|
||||||
|
(**self).macos_handler()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,11 +2,13 @@
|
|||||||
//!
|
//!
|
||||||
//! All notable changes to this project will be documented in this module,
|
//! All notable changes to this project will be documented in this module,
|
||||||
//! along with migration instructions for larger changes.
|
//! along with migration instructions for larger changes.
|
||||||
//!
|
|
||||||
// Put the current entry at the top of this page, for discoverability.
|
// Put the current entry at the top of this page, for discoverability.
|
||||||
// See `.cargo/config.toml` for details about `unreleased_changelogs`.
|
// See `.cargo/config.toml` for details about `unreleased_changelogs`.
|
||||||
#![cfg_attr(unreleased_changelogs, doc = include_str!("unreleased.md"))]
|
#![cfg_attr(unreleased_changelogs, doc = include_str!("unreleased.md"))]
|
||||||
#![cfg_attr(not(unreleased_changelogs), doc = include_str!("v0.29.md"))]
|
#![cfg_attr(not(unreleased_changelogs), doc = include_str!("v0.30.md"))]
|
||||||
|
|
||||||
|
#[doc = include_str!("v0.30.md")]
|
||||||
|
pub mod v0_30 {}
|
||||||
|
|
||||||
#[doc = include_str!("v0.29.md")]
|
#[doc = include_str!("v0.29.md")]
|
||||||
pub mod v0_29 {}
|
pub mod v0_29 {}
|
||||||
|
|||||||
@@ -1,42 +1,218 @@
|
|||||||
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
|
||||||
|
|
||||||
|
The sections should follow the order `Added`, `Changed`, `Deprecated`,
|
||||||
|
`Removed`, and `Fixed`.
|
||||||
|
|
||||||
|
Platform specific changed should be added to the end of the section and grouped
|
||||||
|
by platform name. Common API additions should have `, implemented` at the end
|
||||||
|
for platforms where the API was initially implemented. See the following example
|
||||||
|
on how to add them:
|
||||||
|
|
||||||
|
```md
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Add `Window::turbo()`, implemented on X11, Wayland, and Web.
|
||||||
|
- On X11, add `Window::some_rare_api`.
|
||||||
|
- On X11, add `Window::even_more_rare_api`.
|
||||||
|
- On Wayland, add `Window::common_api`.
|
||||||
|
- On Windows, add `Window::some_rare_api`.
|
||||||
|
```
|
||||||
|
|
||||||
|
When the change requires non-trivial amount of work for users to comply
|
||||||
|
with it, the migration guide should be added below the entry, like:
|
||||||
|
|
||||||
|
```md
|
||||||
|
- Deprecate `Window` creation outside of `EventLoop::run`
|
||||||
|
|
||||||
|
This was done to simply migration in the future. Consider the
|
||||||
|
following code:
|
||||||
|
|
||||||
|
// Code snippet.
|
||||||
|
|
||||||
|
To migrate it we should do X, Y, and then Z, for example:
|
||||||
|
|
||||||
|
// Code snippet.
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
The migration guide could reference other migration examples in the current
|
||||||
|
changelog entry.
|
||||||
|
|
||||||
## Unreleased
|
## Unreleased
|
||||||
|
|
||||||
- Deprecate `EventLoop::run` in favor of `EventLoop::run_app`.
|
### Added
|
||||||
- Deprecate `EventLoopExtRunOnDemand::run_on_demand` in favor of `EventLoop::run_app_on_demand`.
|
|
||||||
- Deprecate `EventLoopExtPumpEvents::pump_events` in favor of `EventLoopExtPumpEvents::pump_app_events`.
|
- Add `ActiveEventLoop::create_proxy()`.
|
||||||
- Add `ApplicationHandler<T>` trait which mimics `Event<T>`.
|
- On Web, add `ActiveEventLoopExtWeb::is_cursor_lock_raw()` to determine if
|
||||||
- Move `dpi` types to its own crate, and re-export it from the root crate.
|
`DeviceEvent::MouseMotion` is returning raw data, not OS accelerated, when using
|
||||||
- Implement `Sync` for `EventLoopProxy<T: Send>`.
|
`CursorGrabMode::Locked`.
|
||||||
- **Breaking:** Move `Window::new` to `ActiveEventLoop::create_window` and `EventLoop::create_window` (with the latter being deprecated).
|
- On Web, implement `MonitorHandle` and `VideoModeHandle`.
|
||||||
- **Breaking:** Rename `EventLoopWindowTarget` to `ActiveEventLoop`.
|
|
||||||
- **Breaking:** Remove `Deref` implementation for `EventLoop` that gave `EventLoopWindowTarget`.
|
Without prompting the user for permission, only the current monitor is returned. But when
|
||||||
- **Breaking**: Remove `WindowBuilder` in favor of `WindowAttributes`.
|
prompting and being granted permission through
|
||||||
- **Breaking:** Removed unnecessary generic parameter `T` from `EventLoopWindowTarget`.
|
`ActiveEventLoop::request_detailed_monitor_permission()`, access to all monitors and their
|
||||||
- On Windows, macOS, X11, Wayland and Web, implement setting images as cursors. See the `custom_cursors.rs` example.
|
details is available. Handles created with "detailed monitor permissions" can be used in
|
||||||
- **Breaking:** Remove `Window::set_cursor_icon`
|
`Window::set_fullscreen()` as well.
|
||||||
- Add `WindowBuilder::with_cursor` and `Window::set_cursor` which takes a `CursorIcon` or `CustomCursor`
|
|
||||||
- Add `CustomCursor::from_rgba` to allow creating cursor images from RGBA data.
|
Keep in mind that handles do not auto-upgrade after permissions are granted and have to be
|
||||||
- Add `CustomCursorExtWebSys::from_url` to allow loading cursor images from URLs.
|
re-created to make full use of this feature.
|
||||||
- Add `CustomCursorExtWebSys::from_animation` to allow creating animated cursors from other `CustomCursor`s.
|
- Implement `Clone`, `Copy`, `Debug`, `Deserialize`, `Eq`, `Hash`, `Ord`, `PartialEq`, `PartialOrd`
|
||||||
- Add `{Active,}EventLoop::create_custom_cursor` to load custom cursor image sources.
|
and `Serialize` on many types.
|
||||||
- On macOS, add services menu.
|
- Add `MonitorHandle::current_video_mode()`.
|
||||||
- **Breaking:** On Web, remove queuing fullscreen request in absence of transient activation.
|
- On Android, the soft keyboard can now be shown using `Window::set_ime_allowed`.
|
||||||
- On Web, fix setting cursor icon overriding cursor visibility.
|
- Add basic iOS IME support. The soft keyboard can now be shown using `Window::set_ime_allowed`.
|
||||||
- **Breaking:** On Web, return `RawWindowHandle::WebCanvas` instead of `RawWindowHandle::Web`.
|
- Add `ApplicationHandlerExtMacOS` trait, and a `macos_handler` method to `ApplicationHandler` which returns a `dyn ApplicationHandlerExtMacOS` which allows for macOS specific extensions to winit.
|
||||||
- **Breaking:** On Web, macOS and iOS, return `HandleError::Unavailable` when a window handle is not available.
|
- Add a `standard_key_binding` method to the `ApplicationHandlerExtMacOS` trait. This allows handling of standard keybindings such as "go to end of line" on macOS.
|
||||||
- **Breaking:** Bump MSRV from `1.65` to `1.70`.
|
- On macOS, add `WindowExtMacOS::set_borderless_game` and `WindowAttributesExtMacOS::with_borderless_game`
|
||||||
- On Web, add the ability to toggle calling `Event.preventDefault()` on `Window`.
|
to fully disable the menu bar and dock in Borderless Fullscreen as commonly done in games.
|
||||||
- **Breaking:** Remove `WindowAttributes::fullscreen()` and expose as field directly.
|
- On macOS, add `WindowExtMacOS::set_unified_titlebar` and `WindowAttributesExtMacOS::with_unified_titlebar`
|
||||||
- **Breaking:** Rename `VideoMode` to `VideoModeHandle` to represent that it doesn't hold static data.
|
to use a larger style of titlebar.
|
||||||
- **Breaking:** No longer export `platform::x11::XNotSupported`.
|
- Add `WindowId::into_raw()` and `from_raw()`.
|
||||||
- **Breaking:** Renamed `platform::x11::XWindowType` to `platform::x11::WindowType`.
|
- Add `PointerKind`, `PointerSource`, `ButtonSource`, `FingerId`, `primary` and `position` to all
|
||||||
- Add the `OwnedDisplayHandle` type for allowing safe display handle usage outside of trivial cases.
|
pointer events as part of the pointer event overhaul.
|
||||||
- **Breaking:** Rename `TouchpadMagnify` to `PinchGesture`, `SmartMagnify` to `DoubleTapGesture` and `TouchpadRotate` to `RotationGesture` to represent the action rather than the intent.
|
- Add `DeviceId::into_raw()` and `from_raw()`.
|
||||||
- on iOS, add detection support for `PinchGesture`, `DoubleTapGesture` and `RotationGesture`.
|
- On X11, the `window` example now understands the `X11_VISUAL_ID` and `X11_SCREEN_ID` env
|
||||||
- on Windows: add `with_system_backdrop`, `with_border_color`, `with_title_background_color`, `with_title_text_color` and `with_corner_preference`
|
variables to test the respective modifiers of window creation.
|
||||||
- On Windows, Remove `WS_CAPTION`, `WS_BORDER` and `WS_EX_WINDOWEDGE` styles for child windows without decorations.
|
- Added `Window::surface_position`, which is the position of the surface inside the window.
|
||||||
- **Breaking:** Removed `EventLoopError::AlreadyRunning`, which can't happen as it is already prevented by the type system.
|
- Added `Window::safe_area`, which describes the area of the surface that is unobstructed.
|
||||||
- Added `EventLoop::builder`, which is intended to replace the (now deprecated) `EventLoopBuilder::new`.
|
- On X11, Wayland, Windows and macOS, improved scancode conversions for more obscure key codes.
|
||||||
- **Breaking:** Changed the signature of `EventLoop::with_user_event` to return a builder.
|
|
||||||
- **Breaking:** Removed `EventLoopBuilder::with_user_event`, the functionality is now available in `EventLoop::with_user_event`.
|
### Changed
|
||||||
- Add `Window::default_attributes` to get default `WindowAttributes`.
|
|
||||||
- `log` has been replaced with `tracing`. The old behavior can be emulated by setting the `log` feature on the `tracing` crate.
|
- Change `ActiveEventLoop` to be a trait.
|
||||||
|
- Change `Window` to be a trait.
|
||||||
|
- `ActiveEventLoop::create_window` now returns `Box<dyn Window>`.
|
||||||
|
- `ApplicationHandler` now uses `dyn ActiveEventLoop`.
|
||||||
|
- On Web, let events wake up event loop immediately when using `ControlFlow::Poll`.
|
||||||
|
- Bump MSRV from `1.70` to `1.73`.
|
||||||
|
- Changed `ApplicationHandler::user_event` to `user_wake_up`, removing the
|
||||||
|
generic user event.
|
||||||
|
|
||||||
|
Winit will now only indicate that wake up happened, you will have to pair
|
||||||
|
this with an external mechanism like `std::sync::mpsc::channel` if you want
|
||||||
|
to send specific data to be processed on the main thread.
|
||||||
|
- Changed `EventLoopProxy::send_event` to `EventLoopProxy::wake_up`, it now
|
||||||
|
only wakes up the loop.
|
||||||
|
- On X11, implement smooth resizing through the sync extension API.
|
||||||
|
- `ApplicationHandler::can_create|destroy_surfaces()` was split off from
|
||||||
|
`ApplicationHandler::resumed/suspended()`.
|
||||||
|
|
||||||
|
`ApplicationHandler::can_create_surfaces()` should, for portability reasons
|
||||||
|
to Android, be the only place to create render surfaces.
|
||||||
|
|
||||||
|
`ApplicationHandler::resumed/suspended()` are now only emitted by iOS, Web
|
||||||
|
and Android, and now signify actually resuming/suspending the application.
|
||||||
|
- Rename `platform::web::*ExtWebSys` to `*ExtWeb`.
|
||||||
|
- Change signature of `EventLoop::run_app`, `EventLoopExtPumpEvents::pump_app_events` and
|
||||||
|
`EventLoopExtRunOnDemand::run_app_on_demand` to accept a `impl ApplicationHandler` directly,
|
||||||
|
instead of requiring a `&mut` reference to it.
|
||||||
|
- On Web, `Window::canvas()` now returns a reference.
|
||||||
|
- On Web, `CursorGrabMode::Locked` now lets `DeviceEvent::MouseMotion` return raw data, not OS
|
||||||
|
accelerated, if the browser supports it.
|
||||||
|
- `(Active)EventLoop::create_custom_cursor()` now returns a `Result<CustomCursor, ExternalError>`.
|
||||||
|
- Changed how `ModifiersState` is serialized by Serde.
|
||||||
|
- `VideoModeHandle::refresh_rate_millihertz()` and `bit_depth()` now return a `Option<NonZero*>`.
|
||||||
|
- `MonitorHandle::position()` now returns an `Option`.
|
||||||
|
- On iOS and macOS, remove custom application delegates. You are now allowed to override the
|
||||||
|
application delegate yourself.
|
||||||
|
- On iOS, no longer act as-if the application successfully open all URLs. Override
|
||||||
|
`application:didFinishLaunchingWithOptions:` and provide the desired behaviour yourself.
|
||||||
|
- On X11, remove our dependency on libXcursor. (#3749)
|
||||||
|
- Renamed the following APIs to make it clearer that the sizes apply to the underlying surface:
|
||||||
|
- `WindowEvent::Resized` to `SurfaceResized`.
|
||||||
|
- `InnerSizeWriter` to `SurfaceSizeWriter`.
|
||||||
|
- `WindowAttributes.inner_size` to `surface_size`.
|
||||||
|
- `WindowAttributes.min_inner_size` to `min_surface_size`.
|
||||||
|
- `WindowAttributes.max_inner_size` to `max_surface_size`.
|
||||||
|
- `WindowAttributes.resize_increments` to `surface_resize_increments`.
|
||||||
|
- `WindowAttributes::with_inner_size` to `with_surface_size`.
|
||||||
|
- `WindowAttributes::with_min_inner_size` to `with_min_surface_size`.
|
||||||
|
- `WindowAttributes::with_max_inner_size` to `with_max_surface_size`.
|
||||||
|
- `WindowAttributes::with_resize_increments` to `with_surface_resize_increments`.
|
||||||
|
- `Window::inner_size` to `surface_size`.
|
||||||
|
- `Window::request_inner_size` to `request_surface_size`.
|
||||||
|
- `Window::set_min_inner_size` to `set_min_surface_size`.
|
||||||
|
- `Window::set_max_inner_size` to `set_max_surface_size`.
|
||||||
|
|
||||||
|
To migrate, you can probably just replace all instances of `inner_size` with `surface_size` in your codebase.
|
||||||
|
- Every event carrying a `DeviceId` now uses `Option<DeviceId>` instead. A `None` value signifies that the
|
||||||
|
device can't be uniquely identified.
|
||||||
|
- Pointer `WindowEvent`s were overhauled. The new events can handle any type of pointer, serving as
|
||||||
|
a single pointer input source. Now your application can handle any pointer type without having to
|
||||||
|
explicitly handle e.g. `Touch`:
|
||||||
|
- Rename `CursorMoved` to `PointerMoved`.
|
||||||
|
- Rename `CursorEntered` to `PointerEntered`.
|
||||||
|
- Rename `CursorLeft` to `PointerLeft`.
|
||||||
|
- Rename `MouseInput` to `PointerButton`.
|
||||||
|
- Add `primary` to every `PointerEvent` as a way to identify discard non-primary pointers in a
|
||||||
|
multi-touch interaction.
|
||||||
|
- Add `position` to every `PointerEvent`.
|
||||||
|
- `PointerMoved` is **not sent** after `PointerEntered` anymore.
|
||||||
|
- Remove `Touch`, which is folded into the `Pointer*` events.
|
||||||
|
- New `PointerKind` added to `PointerEntered` and `PointerLeft`, signifying which pointer type is
|
||||||
|
the source of this event.
|
||||||
|
- New `PointerSource` added to `PointerMoved`, similar to `PointerKind` but holding additional
|
||||||
|
data.
|
||||||
|
- New `ButtonSource` added to `PointerButton`, similar to `PointerKind` but holding pointer type
|
||||||
|
specific buttons. Use `ButtonSource::mouse_button()` to easily normalize any pointer button
|
||||||
|
type to a generic mouse button.
|
||||||
|
- New `FingerId` added to `PointerKind::Touch` and `PointerSource::Touch` able to uniquely
|
||||||
|
identify a finger in a multi-touch interaction. Replaces the old `Touch::id`.
|
||||||
|
- In the same spirit rename `DeviceEvent::MouseMotion` to `PointerMotion`.
|
||||||
|
- Remove `Force::Calibrated::altitude_angle`.
|
||||||
|
- On X11, use bottom-right corner for IME hotspot in `Window::set_ime_cursor_area`.
|
||||||
|
- On macOS and iOS, no longer emit `ScaleFactorChanged` upon window creation.
|
||||||
|
- On macOS, no longer emit `Focused` upon window creation.
|
||||||
|
- On iOS, emit more events immediately, instead of queuing them.
|
||||||
|
- Update `smol_str` to version `0.3`
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
|
||||||
|
- Remove `Event`.
|
||||||
|
- Remove already deprecated APIs:
|
||||||
|
- `EventLoop::create_window()`
|
||||||
|
- `EventLoop::run`.
|
||||||
|
- `EventLoopBuilder::new()`
|
||||||
|
- `EventLoopExtPumpEvents::pump_events`.
|
||||||
|
- `EventLoopExtRunOnDemand::run_on_demand`.
|
||||||
|
- `VideoMode`
|
||||||
|
- `WindowAttributes::new()`
|
||||||
|
- `Window::set_cursor_icon()`
|
||||||
|
- On iOS, remove `platform::ios::EventLoopExtIOS` and related `platform::ios::Idiom` type.
|
||||||
|
|
||||||
|
This feature was incomplete, and the equivalent functionality can be trivially achieved outside
|
||||||
|
of `winit` using `objc2-ui-kit` and calling `UIDevice::currentDevice().userInterfaceIdiom()`.
|
||||||
|
- On Web, remove unused `platform::web::CustomCursorError::Animation`.
|
||||||
|
- Remove the `rwh_04` and `rwh_05` cargo feature and the corresponding `raw-window-handle` v0.4 and
|
||||||
|
v0.5 support. v0.6 remains in place and is enabled by default.
|
||||||
|
- Remove `DeviceEvent::Added` and `DeviceEvent::Removed`.
|
||||||
|
- Remove `DeviceEvent::Motion` and `WindowEvent::AxisMotion`.
|
||||||
|
- Remove `MonitorHandle::size()` and `refresh_rate_millihertz()` in favor of
|
||||||
|
`MonitorHandle::current_video_mode()`.
|
||||||
|
- On Android, remove all `MonitorHandle` support instead of emitting false data.
|
||||||
|
- Remove `impl From<u64> for WindowId` and `impl From<WindowId> for u64`. Replaced with
|
||||||
|
`WindowId::into_raw()` and `from_raw()`.
|
||||||
|
- Remove `dummy()` from `WindowId` and `DeviceId`.
|
||||||
|
- Remove `WindowEvent::Touch` and `Touch` in favor of the new `PointerKind`, `PointerSource` and
|
||||||
|
`ButtonSource` as part of the new pointer event overhaul.
|
||||||
|
- Remove `Force::altitude_angle`.
|
||||||
|
- Removed `Window::inner_position`, use the new `Window::surface_position` instead.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- On Orbital, `MonitorHandle::name()` now returns `None` instead of a dummy name.
|
||||||
|
- On macOS, fix `WindowEvent::Moved` sometimes being triggered unnecessarily on resize.
|
||||||
|
- On macOS, package manifest definitions of `LSUIElement` will no longer be overridden with the
|
||||||
|
default activation policy, unless explicitly provided during initialization.
|
||||||
|
- On macOS, fix crash when calling `drag_window()` without a left click present.
|
||||||
|
- On X11, key events forward to IME anyway, even when it's disabled.
|
||||||
|
- On Windows, make `ControlFlow::WaitUntil` work more precisely using `CREATE_WAITABLE_TIMER_HIGH_RESOLUTION`.
|
||||||
|
- On X11, creating windows on screen that is not the first one (e.g. `DISPLAY=:0.1`) works again.
|
||||||
|
- On X11, creating windows while passing `with_x11_screen(non_default_screen)` works again.
|
||||||
|
- On X11, fix XInput handling that prevented a new window from getting the focus in some cases.
|
||||||
|
- On iOS, fixed `SurfaceResized` and `Window::surface_size` not reporting the size of the actual surface.
|
||||||
|
- On macOS, fixed the scancode conversion for audio volume keys.
|
||||||
|
- On macOS, fixed the scancode conversion for `IntlBackslash`.
|
||||||
|
- On macOS, fixed redundant `SurfaceResized` event at window creation.
|
||||||
|
- On macOS, fix crash when pressing Caps Lock in certain configurations.
|
||||||
|
- On iOS, fixed `MonitorHandle`'s `PartialEq` and `Hash` implementations.
|
||||||
|
|||||||
@@ -137,7 +137,7 @@
|
|||||||
|
|
||||||
- On X11, non-resizable windows now have maximize explicitly disabled.
|
- On X11, non-resizable windows now have maximize explicitly disabled.
|
||||||
- On Windows, support paths longer than MAX_PATH (260 characters) in `WindowEvent::DroppedFile`
|
- On Windows, support paths longer than MAX_PATH (260 characters) in `WindowEvent::DroppedFile`
|
||||||
and `WindowEvent::HoveredFile`.
|
and `WindowEvent::HoveredFile`.
|
||||||
- On Mac, implement `DeviceEvent::Button`.
|
- On Mac, implement `DeviceEvent::Button`.
|
||||||
- Change `Event::Suspended(true / false)` to `Event::Suspended` and `Event::Resumed`.
|
- Change `Event::Suspended(true / false)` to `Event::Suspended` and `Event::Resumed`.
|
||||||
- On X11, fix sanity check which checks that a monitor's reported width and height (in millimeters) are non-zero when calculating the DPI factor.
|
- On X11, fix sanity check which checks that a monitor's reported width and height (in millimeters) are non-zero when calculating the DPI factor.
|
||||||
|
|||||||
300
src/changelog/v0.30.md
Normal file
300
src/changelog/v0.30.md
Normal file
@@ -0,0 +1,300 @@
|
|||||||
|
## 0.30.5
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Add `ActiveEventLoop::system_theme()`, returning the current system theme.
|
||||||
|
- On Web, implement `Error` for `platform::web::CustomCursorError`.
|
||||||
|
- On Android, add `{Active,}EventLoopExtAndroid::android_app()` to access the app used to create the loop.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- On MacOS, fix building with `feature = "rwh_04"`.
|
||||||
|
- On Web, pen events are now routed through to `WindowEvent::Cursor*`.
|
||||||
|
- On macOS, fix panic when releasing not available monitor.
|
||||||
|
- On MacOS, return the system theme in `Window::theme()` if no theme override is set.
|
||||||
|
|
||||||
|
## 0.30.4
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- `DeviceId::dummy()` and `WindowId::dummy()` are no longer marked `unsafe`.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- On Wayland, avoid crashing when compositor is misbehaving.
|
||||||
|
- On Web, fix `WindowEvent::Resized` not using `requestAnimationFrame` when sending
|
||||||
|
`WindowEvent::RedrawRequested` and also potentially causing `WindowEvent::RedrawRequested`
|
||||||
|
to not be de-duplicated.
|
||||||
|
- Account for different browser engine implementations of pointer movement coordinate space.
|
||||||
|
|
||||||
|
## 0.30.3
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- On Web, add `EventLoopExtWebSys::(set_)poll_strategy()` to allow setting
|
||||||
|
control flow strategies before starting the event loop.
|
||||||
|
- On Web, add `WaitUntilStrategy`, which allows to set different strategies for
|
||||||
|
`ControlFlow::WaitUntil`. By default the Prioritized Task Scheduling API is
|
||||||
|
used, with a fallback to `setTimeout()` with a trick to circumvent throttling
|
||||||
|
to 4ms. But an option to use a Web worker to schedule the timer is available
|
||||||
|
as well, which commonly prevents any throttling when the window is not focused.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- On macOS, set the window theme on the `NSWindow` instead of application-wide.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- On X11, build on arm platforms.
|
||||||
|
- On macOS, fixed `WindowBuilder::with_theme` not having any effect on the window.
|
||||||
|
|
||||||
|
## 0.30.2
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- On Web, fix `EventLoopProxy::send_event()` triggering event loop immediately
|
||||||
|
when not called from inside the event loop. Now queues a microtask instead.
|
||||||
|
- On Web, stop overwriting default cursor with `CursorIcon::Default`.
|
||||||
|
- On Web, prevent crash when using `InnerSizeWriter::request_inner_size()`.
|
||||||
|
- On macOS, fix not working opacity for entire window.
|
||||||
|
|
||||||
|
## 0.30.1
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Reexport `raw-window-handle` versions 0.4 and 0.5 as `raw_window_handle_04` and `raw_window_handle_05`.
|
||||||
|
- Implement `ApplicationHandler` for `&mut` references and heap allocations to something that implements `ApplicationHandler`.
|
||||||
|
- Add traits `EventLoopExtWayland` and `EventLoopExtX11`, providing methods `is_wayland` and `is_x11` on `EventLoop`.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- On macOS, fix panic on exit when dropping windows outside the event loop.
|
||||||
|
- On macOS, fix window dragging glitches when dragging across a monitor boundary with different scale factor.
|
||||||
|
- On macOS, fix the range in `Ime::Preedit`.
|
||||||
|
- On macOS, use the system's internal mechanisms for queuing events.
|
||||||
|
- On macOS, handle events directly instead of queuing when possible.
|
||||||
|
|
||||||
|
## 0.30.0
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Add `OwnedDisplayHandle` type for allowing safe display handle usage outside of
|
||||||
|
trivial cases.
|
||||||
|
- Add `ApplicationHandler<T>` trait which mimics `Event<T>`.
|
||||||
|
- Add `WindowBuilder::with_cursor` and `Window::set_cursor` which takes a
|
||||||
|
`CursorIcon` or `CustomCursor`.
|
||||||
|
- Add `Sync` implementation for `EventLoopProxy<T: Send>`.
|
||||||
|
- Add `Window::default_attributes` to get default `WindowAttributes`.
|
||||||
|
- Add `EventLoop::builder` to get `EventLoopBuilder` without export.
|
||||||
|
- Add `CustomCursor::from_rgba` to allow creating cursor images from RGBA data.
|
||||||
|
- Add `CustomCursorExtWebSys::from_url` to allow loading cursor images from URLs.
|
||||||
|
- Add `CustomCursorExtWebSys::from_animation` to allow creating animated
|
||||||
|
cursors from other `CustomCursor`s.
|
||||||
|
- Add `{Active,}EventLoop::create_custom_cursor` to load custom cursor image sources.
|
||||||
|
- Add `ActiveEventLoop::create_window` and `EventLoop::create_window`.
|
||||||
|
- Add `CustomCursor` which could be set via `Window::set_cursor`, implemented on
|
||||||
|
Windows, macOS, X11, Wayland, and Web.
|
||||||
|
- On Web, add to toggle calling `Event.preventDefault()` on `Window`.
|
||||||
|
- On iOS, add `PinchGesture`, `DoubleTapGesture`, `PanGesture` and `RotationGesture`.
|
||||||
|
- on iOS, use `UIGestureRecognizerDelegate` for fine grained control of gesture recognizers.
|
||||||
|
- On macOS, add services menu.
|
||||||
|
- On Windows, add `with_title_text_color`, and `with_corner_preference` on
|
||||||
|
`WindowAttributesExtWindows`.
|
||||||
|
- On Windows, implement resize increments.
|
||||||
|
- On Windows, add `AnyThread` API to access window handle off the main thread.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Bump MSRV from `1.65` to `1.70`.
|
||||||
|
- On Wayland, bump `sctk-adwaita` to `0.9.0`, which changed system library
|
||||||
|
crates. This change is a **cascading breaking change**, you must do breaking
|
||||||
|
change as well, even if you don't expose winit.
|
||||||
|
- Rename `TouchpadMagnify` to `PinchGesture`.
|
||||||
|
- Rename `SmartMagnify` to `DoubleTapGesture`.
|
||||||
|
- Rename `TouchpadRotate` to `RotationGesture`.
|
||||||
|
- Rename `EventLoopWindowTarget` to `ActiveEventLoop`.
|
||||||
|
- Rename `platform::x11::XWindowType` to `platform::x11::WindowType`.
|
||||||
|
- Rename `VideoMode` to `VideoModeHandle` to represent that it doesn't hold
|
||||||
|
static data.
|
||||||
|
- Make `Debug` formatting of `WindowId` more concise.
|
||||||
|
- Move `dpi` types to its own crate, and re-export it from the root crate.
|
||||||
|
- Replace `log` with `tracing`, use `log` feature on `tracing` to restore old
|
||||||
|
behavior.
|
||||||
|
- `EventLoop::with_user_event` now returns `EventLoopBuilder`.
|
||||||
|
- On Web, return `HandleError::Unavailable` when a window handle is not available.
|
||||||
|
- On Web, return `RawWindowHandle::WebCanvas` instead of `RawWindowHandle::Web`.
|
||||||
|
- On Web, remove queuing fullscreen request in absence of transient activation.
|
||||||
|
- On iOS, return `HandleError::Unavailable` when a window handle is not available.
|
||||||
|
- On macOS, return `HandleError::Unavailable` when a window handle is not available.
|
||||||
|
- On Windows, remove `WS_CAPTION`, `WS_BORDER`, and `WS_EX_WINDOWEDGE` styles
|
||||||
|
for child windows without decorations.
|
||||||
|
- On Android, bump `ndk` to `0.9.0` and `android-activity` to `0.6.0`,
|
||||||
|
and remove unused direct dependency on `ndk-sys`.
|
||||||
|
|
||||||
|
### Deprecated
|
||||||
|
|
||||||
|
- Deprecate `EventLoop::run`, use `EventLoop::run_app`.
|
||||||
|
- Deprecate `EventLoopExtRunOnDemand::run_on_demand`, use `EventLoop::run_app_on_demand`.
|
||||||
|
- Deprecate `EventLoopExtPumpEvents::pump_events`, use `EventLoopExtPumpEvents::pump_app_events`.
|
||||||
|
|
||||||
|
The new `app` APIs accept a newly added `ApplicationHandler<T>` instead of
|
||||||
|
`Fn`. The semantics are mostly the same, given that the capture list of the
|
||||||
|
closure is your new `State`. Consider the following code:
|
||||||
|
|
||||||
|
```rust,no_run,ignore
|
||||||
|
use winit::event::Event;
|
||||||
|
use winit::event_loop::EventLoop;
|
||||||
|
use winit::window::Window;
|
||||||
|
|
||||||
|
struct MyUserEvent;
|
||||||
|
|
||||||
|
let event_loop = EventLoop::<MyUserEvent>::with_user_event().build().unwrap();
|
||||||
|
let window = event_loop.create_window(Window::default_attributes()).unwrap();
|
||||||
|
let mut counter = 0;
|
||||||
|
|
||||||
|
let _ = event_loop.run(move |event, event_loop| {
|
||||||
|
match event {
|
||||||
|
Event::AboutToWait => {
|
||||||
|
window.request_redraw();
|
||||||
|
counter += 1;
|
||||||
|
}
|
||||||
|
Event::WindowEvent { window_id, event } => {
|
||||||
|
// Handle window event.
|
||||||
|
}
|
||||||
|
Event::UserEvent(event) => {
|
||||||
|
// Handle user event.
|
||||||
|
}
|
||||||
|
Event::DeviceEvent { device_id, event } => {
|
||||||
|
// Handle device event.
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
To migrate this code, you should move all the captured values into some
|
||||||
|
newtype `State` and implement `ApplicationHandler` for this type. Finally,
|
||||||
|
we move particular `match event` arms into methods on `ApplicationHandler`,
|
||||||
|
for example:
|
||||||
|
|
||||||
|
```rust,no_run,ignore
|
||||||
|
use winit::application::ApplicationHandler;
|
||||||
|
use winit::event::{Event, WindowEvent, DeviceEvent, DeviceId};
|
||||||
|
use winit::event_loop::{EventLoop, ActiveEventLoop};
|
||||||
|
use winit::window::{Window, WindowId};
|
||||||
|
|
||||||
|
struct MyUserEvent;
|
||||||
|
|
||||||
|
struct State {
|
||||||
|
window: Window,
|
||||||
|
counter: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler<MyUserEvent> for State {
|
||||||
|
fn user_event(&mut self, event_loop: &ActiveEventLoop, user_event: MyUserEvent) {
|
||||||
|
// Handle user event.
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
// Your application got resumed.
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, event: WindowEvent) {
|
||||||
|
// Handle window event.
|
||||||
|
}
|
||||||
|
|
||||||
|
fn device_event(&mut self, event_loop: &ActiveEventLoop, device_id: DeviceId, event: DeviceEvent) {
|
||||||
|
// Handle device event.
|
||||||
|
}
|
||||||
|
|
||||||
|
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
self.window.request_redraw();
|
||||||
|
self.counter += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let event_loop = EventLoop::<MyUserEvent>::with_user_event().build().unwrap();
|
||||||
|
#[allow(deprecated)]
|
||||||
|
let window = event_loop.create_window(Window::default_attributes()).unwrap();
|
||||||
|
let mut state = State { window, counter: 0 };
|
||||||
|
|
||||||
|
let _ = event_loop.run_app(&mut state);
|
||||||
|
```
|
||||||
|
|
||||||
|
Please submit your feedback after migrating in [this issue](https://github.com/rust-windowing/winit/issues/3626).
|
||||||
|
|
||||||
|
- Deprecate `Window::set_cursor_icon`, use `Window::set_cursor`.
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
|
||||||
|
- Remove `Window::new`, use `ActiveEventLoop::create_window` instead.
|
||||||
|
|
||||||
|
You now have to create your windows inside the actively running event loop
|
||||||
|
(usually the `new_events(cause: StartCause::Init)` or `resumed()` events),
|
||||||
|
and can no longer do it before the application has properly launched.
|
||||||
|
This change is done to fix many long-standing issues on iOS and macOS, and
|
||||||
|
will improve things on Wayland once fully implemented.
|
||||||
|
|
||||||
|
To ease migration, we provide the deprecated `EventLoop::create_window` that
|
||||||
|
will allow you to bypass this restriction in this release.
|
||||||
|
|
||||||
|
Using the migration example from above, you can change your code as follows:
|
||||||
|
|
||||||
|
```rust,no_run,ignore
|
||||||
|
use winit::application::ApplicationHandler;
|
||||||
|
use winit::event::{Event, WindowEvent, DeviceEvent, DeviceId};
|
||||||
|
use winit::event_loop::{EventLoop, ActiveEventLoop};
|
||||||
|
use winit::window::{Window, WindowId};
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct State {
|
||||||
|
// Use an `Option` to allow the window to not be available until the
|
||||||
|
// application is properly running.
|
||||||
|
window: Option<Window>,
|
||||||
|
counter: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for State {
|
||||||
|
// This is a common indicator that you can create a window.
|
||||||
|
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, window_id: WindowId, event: WindowEvent) {
|
||||||
|
// `unwrap` is fine, the window will always be available when
|
||||||
|
// receiving a window event.
|
||||||
|
let window = self.window.as_ref().unwrap();
|
||||||
|
// Handle window event.
|
||||||
|
}
|
||||||
|
fn device_event(&mut self, event_loop: &ActiveEventLoop, device_id: DeviceId, event: DeviceEvent) {
|
||||||
|
// Handle window event.
|
||||||
|
}
|
||||||
|
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
if let Some(window) = self.window.as_ref() {
|
||||||
|
window.request_redraw();
|
||||||
|
self.counter += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
let mut state = State::default();
|
||||||
|
let _ = event_loop.run_app(&mut state);
|
||||||
|
```
|
||||||
|
|
||||||
|
- Remove `Deref` implementation for `EventLoop` that gave `EventLoopWindowTarget`.
|
||||||
|
- Remove `WindowBuilder` in favor of `WindowAttributes`.
|
||||||
|
- Remove Generic parameter `T` from `ActiveEventLoop`.
|
||||||
|
- Remove `EventLoopBuilder::with_user_event`, use `EventLoop::with_user_event`.
|
||||||
|
- Remove Redundant `EventLoopError::AlreadyRunning`.
|
||||||
|
- Remove `WindowAttributes::fullscreen` and expose as field directly.
|
||||||
|
- On X11, remove `platform::x11::XNotSupported` export.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- On Web, fix setting cursor icon overriding cursor visibility.
|
||||||
|
- On Windows, fix cursor not confined to center of window when grabbed and hidden.
|
||||||
|
- On macOS, fix sequence of mouse events being out of order when dragging on the trackpad.
|
||||||
|
- On Wayland, fix decoration glitch on close with some compositors.
|
||||||
|
- On Android, fix a regression introduced in #2748 to allow volume key events to be received again.
|
||||||
|
- On Windows, don't return a valid window handle outside of the GUI thread.
|
||||||
|
- On macOS, don't set the background color when initializing a window with transparency.
|
||||||
@@ -3,20 +3,20 @@
|
|||||||
- Added event `WindowEvent::HiDPIFactorChanged`.
|
- Added event `WindowEvent::HiDPIFactorChanged`.
|
||||||
- Added method `MonitorId::get_hidpi_factor`.
|
- Added method `MonitorId::get_hidpi_factor`.
|
||||||
- Deprecated `get_inner_size_pixels` and `get_inner_size_points` methods of `Window` in favor of
|
- Deprecated `get_inner_size_pixels` and `get_inner_size_points` methods of `Window` in favor of
|
||||||
`get_inner_size`.
|
`get_inner_size`.
|
||||||
- **Breaking:** `EventsLoop` is `!Send` and `!Sync` because of platform-dependant constraints,
|
- **Breaking:** `EventsLoop` is `!Send` and `!Sync` because of platform-dependant constraints,
|
||||||
but `Window`, `WindowId`, `DeviceId` and `MonitorId` guaranteed to be `Send`.
|
but `Window`, `WindowId`, `DeviceId` and `MonitorId` guaranteed to be `Send`.
|
||||||
- `MonitorId::get_position` now returns `(i32, i32)` instead of `(u32, u32)`.
|
- `MonitorId::get_position` now returns `(i32, i32)` instead of `(u32, u32)`.
|
||||||
- Rewrite of the wayland backend to use wayland-client-0.11
|
- Rewrite of the wayland backend to use wayland-client-0.11
|
||||||
- Support for dead keys on wayland for keyboard utf8 input
|
- Support for dead keys on wayland for keyboard utf8 input
|
||||||
- Monitor enumeration on Windows is now implemented using `EnumDisplayMonitors` instead of
|
- Monitor enumeration on Windows is now implemented using `EnumDisplayMonitors` instead of
|
||||||
`EnumDisplayDevices`. This changes the value returned by `MonitorId::get_name()`.
|
`EnumDisplayDevices`. This changes the value returned by `MonitorId::get_name()`.
|
||||||
- On Windows added `MonitorIdExt::hmonitor` method
|
- On Windows added `MonitorIdExt::hmonitor` method
|
||||||
- Impl `Clone` for `EventsLoopProxy`
|
- Impl `Clone` for `EventsLoopProxy`
|
||||||
- `EventsLoop::get_primary_monitor()` on X11 will fallback to any available monitor if no primary is found
|
- `EventsLoop::get_primary_monitor()` on X11 will fallback to any available monitor if no primary is found
|
||||||
- Support for touch event on wayland
|
- Support for touch event on wayland
|
||||||
- `WindowEvent`s `MouseMoved`, `MouseEntered`, and `MouseLeft` have been renamed to
|
- `WindowEvent`s `MouseMoved`, `MouseEntered`, and `MouseLeft` have been renamed to
|
||||||
`CursorMoved`, `CursorEntered`, and `CursorLeft`.
|
`CursorMoved`, `CursorEntered`, and `CursorLeft`.
|
||||||
- New `DeviceEvent`s added, `MouseMotion` and `MouseWheel`.
|
- New `DeviceEvent`s added, `MouseMotion` and `MouseWheel`.
|
||||||
- Send `CursorMoved` event after `CursorEntered` and `Focused` events.
|
- Send `CursorMoved` event after `CursorEntered` and `Focused` events.
|
||||||
- Add support for `ModifiersState`, `MouseMove`, `MouseInput`, `MouseMotion` for emscripten backend.
|
- Add support for `ModifiersState`, `MouseMove`, `MouseInput`, `MouseMotion` for emscripten backend.
|
||||||
|
|||||||
108
src/cursor.rs
108
src/cursor.rs
@@ -1,7 +1,7 @@
|
|||||||
use core::fmt;
|
use core::fmt;
|
||||||
use std::hash::Hasher;
|
use std::error::Error;
|
||||||
|
use std::hash::{Hash, Hasher};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::{error::Error, hash::Hash};
|
|
||||||
|
|
||||||
use cursor_icon::CursorIcon;
|
use cursor_icon::CursorIcon;
|
||||||
|
|
||||||
@@ -50,7 +50,7 @@ impl From<CustomCursor> for Cursor {
|
|||||||
/// ```no_run
|
/// ```no_run
|
||||||
/// # use winit::event_loop::ActiveEventLoop;
|
/// # use winit::event_loop::ActiveEventLoop;
|
||||||
/// # use winit::window::Window;
|
/// # use winit::window::Window;
|
||||||
/// # fn scope(event_loop: &ActiveEventLoop, window: &Window) {
|
/// # fn scope(event_loop: &dyn ActiveEventLoop, window: &dyn Window) {
|
||||||
/// use winit::window::CustomCursor;
|
/// use winit::window::CustomCursor;
|
||||||
///
|
///
|
||||||
/// let w = 10;
|
/// let w = 10;
|
||||||
@@ -62,13 +62,13 @@ impl From<CustomCursor> for Cursor {
|
|||||||
///
|
///
|
||||||
/// #[cfg(target_family = "wasm")]
|
/// #[cfg(target_family = "wasm")]
|
||||||
/// let source = {
|
/// let source = {
|
||||||
/// use winit::platform::web::CustomCursorExtWebSys;
|
/// use winit::platform::web::CustomCursorExtWeb;
|
||||||
/// CustomCursor::from_url(String::from("http://localhost:3000/cursor.png"), 0, 0)
|
/// CustomCursor::from_url(String::from("http://localhost:3000/cursor.png"), 0, 0)
|
||||||
/// };
|
/// };
|
||||||
///
|
///
|
||||||
/// let custom_cursor = event_loop.create_custom_cursor(source);
|
/// if let Ok(custom_cursor) = event_loop.create_custom_cursor(source) {
|
||||||
///
|
/// window.set_cursor(custom_cursor.clone().into());
|
||||||
/// window.set_cursor(custom_cursor.clone());
|
/// }
|
||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||||
@@ -88,14 +88,9 @@ impl CustomCursor {
|
|||||||
hotspot_x: u16,
|
hotspot_x: u16,
|
||||||
hotspot_y: u16,
|
hotspot_y: u16,
|
||||||
) -> Result<CustomCursorSource, BadImage> {
|
) -> Result<CustomCursorSource, BadImage> {
|
||||||
let _span = tracing::debug_span!(
|
let _span =
|
||||||
"winit::Cursor::from_rgba",
|
tracing::debug_span!("winit::Cursor::from_rgba", width, height, hotspot_x, hotspot_y)
|
||||||
width,
|
.entered();
|
||||||
height,
|
|
||||||
hotspot_x,
|
|
||||||
hotspot_y
|
|
||||||
)
|
|
||||||
.entered();
|
|
||||||
|
|
||||||
Ok(CustomCursorSource {
|
Ok(CustomCursorSource {
|
||||||
inner: PlatformCustomCursorSource::from_rgba(
|
inner: PlatformCustomCursorSource::from_rgba(
|
||||||
@@ -112,13 +107,16 @@ impl CustomCursor {
|
|||||||
/// Source for [`CustomCursor`].
|
/// Source for [`CustomCursor`].
|
||||||
///
|
///
|
||||||
/// See [`CustomCursor`] for more details.
|
/// See [`CustomCursor`] for more details.
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
||||||
pub struct CustomCursorSource {
|
pub struct CustomCursorSource {
|
||||||
|
// Some platforms don't support custom cursors.
|
||||||
|
#[allow(dead_code)]
|
||||||
pub(crate) inner: PlatformCustomCursorSource,
|
pub(crate) inner: PlatformCustomCursorSource,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An error produced when using [`CustomCursor::from_rgba`] with invalid arguments.
|
/// An error produced when using [`CustomCursor::from_rgba`] with invalid arguments.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
pub enum BadImage {
|
pub enum BadImage {
|
||||||
/// Produced when the image dimensions are larger than [`MAX_CURSOR_SIZE`]. This doesn't
|
/// Produced when the image dimensions are larger than [`MAX_CURSOR_SIZE`]. This doesn't
|
||||||
/// guarantee that the cursor will work, but should avoid many platform and device specific
|
/// guarantee that the cursor will work, but should avoid many platform and device specific
|
||||||
@@ -129,45 +127,36 @@ pub enum BadImage {
|
|||||||
ByteCountNotDivisibleBy4 { byte_count: usize },
|
ByteCountNotDivisibleBy4 { byte_count: usize },
|
||||||
/// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`.
|
/// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`.
|
||||||
/// At least one of your arguments is incorrect.
|
/// At least one of your arguments is incorrect.
|
||||||
DimensionsVsPixelCount {
|
DimensionsVsPixelCount { width: u16, height: u16, width_x_height: u64, pixel_count: u64 },
|
||||||
width: u16,
|
|
||||||
height: u16,
|
|
||||||
width_x_height: u64,
|
|
||||||
pixel_count: u64,
|
|
||||||
},
|
|
||||||
/// Produced when the hotspot is outside the image bounds
|
/// Produced when the hotspot is outside the image bounds
|
||||||
HotspotOutOfBounds {
|
HotspotOutOfBounds { width: u16, height: u16, hotspot_x: u16, hotspot_y: u16 },
|
||||||
width: u16,
|
|
||||||
height: u16,
|
|
||||||
hotspot_x: u16,
|
|
||||||
hotspot_y: u16,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for BadImage {
|
impl fmt::Display for BadImage {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
BadImage::TooLarge { width, height } => write!(f,
|
BadImage::TooLarge { width, height } => write!(
|
||||||
"The specified dimensions ({width:?}x{height:?}) are too large. The maximum is {MAX_CURSOR_SIZE:?}x{MAX_CURSOR_SIZE:?}.",
|
f,
|
||||||
|
"The specified dimensions ({width:?}x{height:?}) are too large. The maximum is \
|
||||||
|
{MAX_CURSOR_SIZE:?}x{MAX_CURSOR_SIZE:?}.",
|
||||||
),
|
),
|
||||||
BadImage::ByteCountNotDivisibleBy4 { byte_count } => write!(f,
|
BadImage::ByteCountNotDivisibleBy4 { byte_count } => write!(
|
||||||
"The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making it impossible to interpret as 32bpp RGBA pixels.",
|
f,
|
||||||
|
"The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making \
|
||||||
|
it impossible to interpret as 32bpp RGBA pixels.",
|
||||||
),
|
),
|
||||||
BadImage::DimensionsVsPixelCount {
|
BadImage::DimensionsVsPixelCount { width, height, width_x_height, pixel_count } => {
|
||||||
width,
|
write!(
|
||||||
height,
|
f,
|
||||||
width_x_height,
|
"The specified dimensions ({width:?}x{height:?}) don't match the number of \
|
||||||
pixel_count,
|
pixels supplied by the `rgba` argument ({pixel_count:?}). For those \
|
||||||
} => write!(f,
|
dimensions, the expected pixel count is {width_x_height:?}.",
|
||||||
"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:?}.",
|
)
|
||||||
),
|
},
|
||||||
BadImage::HotspotOutOfBounds {
|
BadImage::HotspotOutOfBounds { width, height, hotspot_x, hotspot_y } => write!(
|
||||||
width,
|
f,
|
||||||
height,
|
"The specified hotspot ({hotspot_x:?}, {hotspot_y:?}) is outside the image bounds \
|
||||||
hotspot_x,
|
({width:?}x{height:?}).",
|
||||||
hotspot_y,
|
|
||||||
} => write!(f,
|
|
||||||
"The specified hotspot ({hotspot_x:?}, {hotspot_y:?}) is outside the image bounds ({width:?}x{height:?}).",
|
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -178,7 +167,7 @@ impl Error for BadImage {}
|
|||||||
/// Platforms export this directly as `PlatformCustomCursorSource` if they need to only work with
|
/// Platforms export this directly as `PlatformCustomCursorSource` if they need to only work with
|
||||||
/// images.
|
/// images.
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
||||||
pub(crate) struct OnlyCursorImageSource(pub(crate) CursorImage);
|
pub(crate) struct OnlyCursorImageSource(pub(crate) CursorImage);
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
@@ -213,7 +202,7 @@ impl PartialEq for OnlyCursorImage {
|
|||||||
|
|
||||||
impl Eq for OnlyCursorImage {}
|
impl Eq for OnlyCursorImage {}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub(crate) struct CursorImage {
|
pub(crate) struct CursorImage {
|
||||||
pub(crate) rgba: Vec<u8>,
|
pub(crate) rgba: Vec<u8>,
|
||||||
@@ -236,9 +225,7 @@ impl CursorImage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if rgba.len() % PIXEL_SIZE != 0 {
|
if rgba.len() % PIXEL_SIZE != 0 {
|
||||||
return Err(BadImage::ByteCountNotDivisibleBy4 {
|
return Err(BadImage::ByteCountNotDivisibleBy4 { byte_count: rgba.len() });
|
||||||
byte_count: rgba.len(),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let pixel_count = (rgba.len() / PIXEL_SIZE) as u64;
|
let pixel_count = (rgba.len() / PIXEL_SIZE) as u64;
|
||||||
@@ -253,21 +240,10 @@ impl CursorImage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if hotspot_x >= width || hotspot_y >= height {
|
if hotspot_x >= width || hotspot_y >= height {
|
||||||
return Err(BadImage::HotspotOutOfBounds {
|
return Err(BadImage::HotspotOutOfBounds { width, height, hotspot_x, hotspot_y });
|
||||||
width,
|
|
||||||
height,
|
|
||||||
hotspot_x,
|
|
||||||
hotspot_y,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(CursorImage {
|
Ok(CursorImage { rgba, width, height, hotspot_x, hotspot_y })
|
||||||
rgba,
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
hotspot_x,
|
|
||||||
hotspot_y,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
231
src/error.rs
231
src/error.rs
@@ -1,44 +1,40 @@
|
|||||||
use std::{error, fmt};
|
use std::error::Error;
|
||||||
|
use std::fmt::{self, Display};
|
||||||
|
|
||||||
use crate::platform_impl;
|
/// A general error that may occur while running or creating
|
||||||
|
/// the event loop.
|
||||||
// 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)]
|
#[derive(Debug)]
|
||||||
|
#[non_exhaustive]
|
||||||
pub enum EventLoopError {
|
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.
|
/// The event loop can't be re-created.
|
||||||
RecreationAttempt,
|
RecreationAttempt,
|
||||||
/// Application has exit with an error status.
|
/// Application has exit with an error status.
|
||||||
ExitFailure(i32),
|
ExitFailure(i32),
|
||||||
|
/// Got unspecified OS-specific error during the request.
|
||||||
|
Os(OsError),
|
||||||
|
/// Creating the event loop with the requested configuration is not supported.
|
||||||
|
NotSupported(NotSupportedError),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for EventLoopError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::RecreationAttempt => write!(f, "EventLoop can't be recreated"),
|
||||||
|
Self::Os(err) => err.fmt(f),
|
||||||
|
Self::ExitFailure(status) => write!(f, "Exit Failure: {status}"),
|
||||||
|
Self::NotSupported(err) => err.fmt(f),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for EventLoopError {
|
||||||
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||||
|
if let Self::Os(err) = self {
|
||||||
|
err.source()
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<OsError> for EventLoopError {
|
impl From<OsError> for EventLoopError {
|
||||||
@@ -47,18 +43,102 @@ impl From<OsError> for EventLoopError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NotSupportedError {
|
impl From<NotSupportedError> for EventLoopError {
|
||||||
#[inline]
|
fn from(value: NotSupportedError) -> Self {
|
||||||
#[allow(dead_code)]
|
Self::NotSupported(value)
|
||||||
pub(crate) fn new() -> NotSupportedError {
|
|
||||||
NotSupportedError { _marker: () }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A general error that may occur during a request to the windowing system.
|
||||||
|
#[derive(Debug)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub enum RequestError {
|
||||||
|
/// The request is not supported.
|
||||||
|
NotSupported(NotSupportedError),
|
||||||
|
/// The request was ignored by the operating system.
|
||||||
|
Ignored,
|
||||||
|
/// Got unspecified OS specific error during the request.
|
||||||
|
Os(OsError),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for RequestError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::NotSupported(err) => err.fmt(f),
|
||||||
|
Self::Ignored => write!(f, "The request was ignored"),
|
||||||
|
Self::Os(err) => err.fmt(f),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Error for RequestError {
|
||||||
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||||
|
if let Self::Os(err) = self {
|
||||||
|
err.source()
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<NotSupportedError> for RequestError {
|
||||||
|
fn from(value: NotSupportedError) -> Self {
|
||||||
|
Self::NotSupported(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<OsError> for RequestError {
|
||||||
|
fn from(value: OsError) -> Self {
|
||||||
|
Self::Os(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The requested operation is not supported.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct NotSupportedError {
|
||||||
|
/// The reason why a certain operation is not supported.
|
||||||
|
reason: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NotSupportedError {
|
||||||
|
pub(crate) fn new(reason: &'static str) -> Self {
|
||||||
|
Self { reason }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for NotSupportedError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "Operation is not supported: {}", self.reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Error for NotSupportedError {}
|
||||||
|
|
||||||
|
/// Unclassified error from the OS.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct OsError {
|
||||||
|
line: u32,
|
||||||
|
file: &'static str,
|
||||||
|
error: Box<dyn Error + Send + Sync + 'static>,
|
||||||
|
}
|
||||||
|
|
||||||
impl OsError {
|
impl OsError {
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub(crate) fn new(line: u32, file: &'static str, error: platform_impl::OsError) -> OsError {
|
pub(crate) fn new(
|
||||||
OsError { line, file, error }
|
line: u32,
|
||||||
|
file: &'static str,
|
||||||
|
error: impl Into<Box<dyn Error + Send + Sync + 'static>>,
|
||||||
|
) -> Self {
|
||||||
|
Self { line, file, error: error.into() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for OsError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.pad(&format!("os error at {}:{}: {}", self.file, self.line, self.error))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Error for OsError {
|
||||||
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||||
|
Some(self.error.as_ref())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,72 +148,3 @@ macro_rules! os_error {
|
|||||||
crate::error::OsError::new(line!(), file!(), $error)
|
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)]
|
|
||||||
mod tests {
|
|
||||||
#![allow(clippy::redundant_clone)]
|
|
||||||
|
|
||||||
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())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
972
src/event.rs
972
src/event.rs
File diff suppressed because it is too large
Load Diff
@@ -3,25 +3,30 @@
|
|||||||
//!
|
//!
|
||||||
//! If you want to send custom events to the event loop, use
|
//! If you want to send custom events to the event loop, use
|
||||||
//! [`EventLoop::create_proxy`] to acquire an [`EventLoopProxy`] and call its
|
//! [`EventLoop::create_proxy`] to acquire an [`EventLoopProxy`] and call its
|
||||||
//! [`send_event`][EventLoopProxy::send_event] method.
|
//! [`wake_up`][EventLoopProxy::wake_up] method. Then during handling the wake up
|
||||||
|
//! you can poll your event sources.
|
||||||
//!
|
//!
|
||||||
//! See the root-level documentation for information on how to create and use an event loop to
|
//! See the root-level documentation for information on how to create and use an event loop to
|
||||||
//! handle events.
|
//! handle events.
|
||||||
|
use std::fmt;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
#[cfg(any(x11_platform, wayland_platform))]
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
|
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
|
||||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
use std::{error, fmt};
|
use std::sync::Arc;
|
||||||
|
|
||||||
#[cfg(not(web_platform))]
|
#[cfg(not(web_platform))]
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use rwh_06::{DisplayHandle, HandleError, HasDisplayHandle};
|
||||||
#[cfg(web_platform)]
|
#[cfg(web_platform)]
|
||||||
use web_time::{Duration, Instant};
|
use web_time::{Duration, Instant};
|
||||||
|
|
||||||
use crate::application::ApplicationHandler;
|
use crate::application::ApplicationHandler;
|
||||||
use crate::error::{EventLoopError, OsError};
|
use crate::error::{EventLoopError, RequestError};
|
||||||
use crate::window::{CustomCursor, CustomCursorSource, Window, WindowAttributes};
|
use crate::monitor::MonitorHandle;
|
||||||
use crate::{event::Event, monitor::MonitorHandle, platform_impl};
|
use crate::platform_impl;
|
||||||
|
use crate::utils::AsAny;
|
||||||
|
use crate::window::{CustomCursor, CustomCursorSource, Theme, Window, WindowAttributes};
|
||||||
|
|
||||||
/// Provides a way to retrieve events from the system and from the windows that were registered to
|
/// Provides a way to retrieve events from the system and from the windows that were registered to
|
||||||
/// the events loop.
|
/// the events loop.
|
||||||
@@ -33,22 +38,13 @@ use crate::{event::Event, monitor::MonitorHandle, platform_impl};
|
|||||||
/// To wake up an `EventLoop` from a another thread, see the [`EventLoopProxy`] docs.
|
/// 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
|
/// 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
|
/// forbidding it), as such it is neither [`Send`] nor [`Sync`]. If you need cross-thread access,
|
||||||
/// [`Window`] created from this _can_ be sent to an other thread, and the
|
/// 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.
|
/// [`EventLoopProxy`] allows you to wake up an `EventLoop` from another thread.
|
||||||
///
|
///
|
||||||
/// [`Window`]: crate::window::Window
|
/// [`Window`]: crate::window::Window
|
||||||
pub struct EventLoop<T: 'static> {
|
pub struct EventLoop {
|
||||||
pub(crate) event_loop: platform_impl::EventLoop<T>,
|
pub(crate) event_loop: platform_impl::EventLoop,
|
||||||
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
|
pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,25 +53,15 @@ pub struct ActiveEventLoop {
|
|||||||
/// This is used to make specifying options that affect the whole application
|
/// This is used to make specifying options that affect the whole application
|
||||||
/// easier. But note that constructing multiple event loops is not supported.
|
/// easier. But note that constructing multiple event loops is not supported.
|
||||||
///
|
///
|
||||||
/// This can be created using [`EventLoop::new`] or [`EventLoop::with_user_event`].
|
/// This can be created using [`EventLoop::builder`].
|
||||||
#[derive(Default)]
|
#[derive(Default, PartialEq, Eq, Hash)]
|
||||||
pub struct EventLoopBuilder<T: 'static> {
|
pub struct EventLoopBuilder {
|
||||||
pub(crate) platform_specific: platform_impl::PlatformSpecificEventLoopAttributes,
|
pub(crate) platform_specific: platform_impl::PlatformSpecificEventLoopAttributes,
|
||||||
_p: PhantomData<T>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static EVENT_LOOP_CREATED: AtomicBool = AtomicBool::new(false);
|
static EVENT_LOOP_CREATED: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
impl EventLoopBuilder<()> {
|
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.
|
/// Builds a new event loop.
|
||||||
///
|
///
|
||||||
/// ***For cross-platform compatibility, the [`EventLoop`] must be created on the main thread,
|
/// ***For cross-platform compatibility, the [`EventLoop`] must be created on the main thread,
|
||||||
@@ -88,28 +74,29 @@ impl<T> EventLoopBuilder<T> {
|
|||||||
/// Attempting to create the event loop off the main thread will panic. This
|
/// 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
|
/// restriction isn't strictly necessary on all platforms, but is imposed to
|
||||||
/// eliminate any nasty surprises when porting to platforms that require it.
|
/// eliminate any nasty surprises when porting to platforms that require it.
|
||||||
/// `EventLoopBuilderExt::any_thread` functions are exposed in the relevant
|
/// `EventLoopBuilderExt::with_any_thread` functions are exposed in the relevant
|
||||||
/// [`platform`] module if the target platform supports creating an event
|
/// [`platform`] module if the target platform supports creating an event
|
||||||
/// loop on any thread.
|
/// loop on any thread.
|
||||||
///
|
///
|
||||||
/// ## Platform-specific
|
/// ## Platform-specific
|
||||||
///
|
///
|
||||||
/// - **Wayland/X11:** to prevent running under `Wayland` or `X11` unset `WAYLAND_DISPLAY`
|
/// - **Wayland/X11:** to prevent running under `Wayland` or `X11` unset `WAYLAND_DISPLAY` or
|
||||||
/// or `DISPLAY` respectively when building the event loop.
|
/// `DISPLAY` respectively when building the event loop.
|
||||||
/// - **Android:** must be configured with an `AndroidApp` from `android_main()` by calling
|
/// - **Android:** must be configured with an `AndroidApp` from `android_main()` by calling
|
||||||
/// [`.with_android_app(app)`] before calling `.build()`, otherwise it'll panic.
|
/// [`.with_android_app(app)`] before calling `.build()`, otherwise it'll panic.
|
||||||
///
|
///
|
||||||
/// [`platform`]: crate::platform
|
/// [`platform`]: crate::platform
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
android,
|
android_platform,
|
||||||
doc = "[`.with_android_app(app)`]: crate::platform::android::EventLoopBuilderExtAndroid::with_android_app"
|
doc = "[`.with_android_app(app)`]: \
|
||||||
|
crate::platform::android::EventLoopBuilderExtAndroid::with_android_app"
|
||||||
)]
|
)]
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
not(android),
|
not(android_platform),
|
||||||
doc = "[`.with_android_app(app)`]: #only-available-on-android"
|
doc = "[`.with_android_app(app)`]: #only-available-on-android"
|
||||||
)]
|
)]
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn build(&mut self) -> Result<EventLoop<T>, EventLoopError> {
|
pub fn build(&mut self) -> Result<EventLoop, EventLoopError> {
|
||||||
let _span = tracing::debug_span!("winit::EventLoopBuilder::build").entered();
|
let _span = tracing::debug_span!("winit::EventLoopBuilder::build").entered();
|
||||||
|
|
||||||
if EVENT_LOOP_CREATED.swap(true, Ordering::Relaxed) {
|
if EVENT_LOOP_CREATED.swap(true, Ordering::Relaxed) {
|
||||||
@@ -130,26 +117,27 @@ impl<T> EventLoopBuilder<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> fmt::Debug for EventLoop<T> {
|
impl fmt::Debug for EventLoopBuilder {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.pad("EventLoop { .. }")
|
f.debug_struct("EventLoopBuilder").finish_non_exhaustive()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Debug for ActiveEventLoop {
|
impl fmt::Debug for EventLoop {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.pad("ActiveEventLoop { .. }")
|
f.debug_struct("EventLoop").finish_non_exhaustive()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set through [`ActiveEventLoop::set_control_flow()`].
|
/// Set through [`ActiveEventLoop::set_control_flow()`].
|
||||||
///
|
///
|
||||||
/// Indicates the desired behavior of the event loop after [`Event::AboutToWait`] is emitted.
|
/// Indicates the desired behavior of the event loop after [`about_to_wait`] is called.
|
||||||
///
|
///
|
||||||
/// Defaults to [`Wait`].
|
/// Defaults to [`Wait`].
|
||||||
///
|
///
|
||||||
/// [`Wait`]: Self::Wait
|
/// [`Wait`]: Self::Wait
|
||||||
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
/// [`about_to_wait`]: crate::application::ApplicationHandler::about_to_wait
|
||||||
|
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
|
||||||
pub enum ControlFlow {
|
pub enum ControlFlow {
|
||||||
/// When the current loop iteration finishes, immediately begin a new iteration regardless of
|
/// When the current loop iteration finishes, immediately begin a new iteration regardless of
|
||||||
/// whether or not new events are available to process.
|
/// whether or not new events are available to process.
|
||||||
@@ -162,9 +150,9 @@ pub enum ControlFlow {
|
|||||||
/// When the current loop iteration finishes, suspend the thread until either another event
|
/// When the current loop iteration finishes, suspend the thread until either another event
|
||||||
/// arrives or the given time is reached.
|
/// arrives or the given time is reached.
|
||||||
///
|
///
|
||||||
/// Useful for implementing efficient timers. Applications which want to render at the display's
|
/// Useful for implementing efficient timers. Applications which want to render at the
|
||||||
/// native refresh rate should instead use [`Poll`] and the VSync functionality of a graphics API
|
/// display's native refresh rate should instead use [`Poll`] and the VSync functionality
|
||||||
/// to reduce odds of missed frames.
|
/// of a graphics API to reduce odds of missed frames.
|
||||||
///
|
///
|
||||||
/// [`Poll`]: Self::Poll
|
/// [`Poll`]: Self::Poll
|
||||||
WaitUntil(Instant),
|
WaitUntil(Instant),
|
||||||
@@ -186,12 +174,12 @@ impl ControlFlow {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventLoop<()> {
|
impl EventLoop {
|
||||||
/// Create the event loop.
|
/// Create the event loop.
|
||||||
///
|
///
|
||||||
/// This is an alias of `EventLoop::builder().build()`.
|
/// This is an alias of `EventLoop::builder().build()`.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn new() -> Result<EventLoop<()>, EventLoopError> {
|
pub fn new() -> Result<EventLoop, EventLoopError> {
|
||||||
Self::builder().build()
|
Self::builder().build()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,36 +189,12 @@ impl EventLoop<()> {
|
|||||||
///
|
///
|
||||||
/// To get the actual event loop, call [`build`][EventLoopBuilder::build] on that.
|
/// To get the actual event loop, call [`build`][EventLoopBuilder::build] on that.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn builder() -> EventLoopBuilder<()> {
|
pub fn builder() -> EventLoopBuilder {
|
||||||
Self::with_user_event()
|
EventLoopBuilder { platform_specific: Default::default() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoop<T> {
|
impl EventLoop {
|
||||||
/// 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.
|
/// 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.
|
/// See the [`set_control_flow()`] docs on how to change the event loop's behavior.
|
||||||
@@ -239,48 +203,44 @@ impl<T> EventLoop<T> {
|
|||||||
///
|
///
|
||||||
/// - **iOS:** Will never return to the caller and so values not passed to this function will
|
/// - **iOS:** Will never return to the caller and so values not passed to this function will
|
||||||
/// *not* be dropped before the process exits.
|
/// *not* be dropped before the process exits.
|
||||||
/// - **Web:** Will _act_ as if it never returns to the caller by throwing a Javascript exception
|
/// - **Web:** Will _act_ as if it never returns to the caller by throwing a Javascript
|
||||||
/// (that Rust doesn't see) that will also mean that the rest of the function is never executed
|
/// exception (that Rust doesn't see) that will also mean that the rest of the function is
|
||||||
/// and any values not passed to this function will *not* be dropped.
|
/// never executed and any values not passed to this function will *not* be dropped.
|
||||||
///
|
///
|
||||||
/// Web applications are recommended to use
|
/// Web applications are recommended to use
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
web_platform,
|
any(web_platform, docsrs),
|
||||||
doc = "[`EventLoopExtWebSys::spawn_app()`][crate::platform::web::EventLoopExtWebSys::spawn_app()]"
|
doc = " [`EventLoopExtWeb::spawn_app()`][crate::platform::web::EventLoopExtWeb::spawn_app()]"
|
||||||
)]
|
)]
|
||||||
#[cfg_attr(not(web_platform), doc = "`EventLoopExtWebSys::spawn()`")]
|
#[cfg_attr(not(any(web_platform, docsrs)), doc = " `EventLoopExtWeb::spawn_app()`")]
|
||||||
/// [^1] instead of [`run_app()`] to avoid the need
|
/// [^1] instead of [`run_app()`] to avoid the need for the Javascript exception trick, and to
|
||||||
/// for the Javascript exception trick, and to make it clearer that the event loop runs
|
/// make it clearer that the event loop runs asynchronously (via the browser's own,
|
||||||
/// asynchronously (via the browser's own, internal, event loop) and doesn't block the
|
/// internal, event loop) and doesn't block the current thread of execution like it does
|
||||||
/// current thread of execution like it does on other platforms.
|
/// on other platforms.
|
||||||
///
|
///
|
||||||
/// This function won't be available with `target_feature = "exception-handling"`.
|
/// This function won't be available with `target_feature = "exception-handling"`.
|
||||||
///
|
///
|
||||||
|
/// [^1]: `spawn_app()` is only available on the Web platform.
|
||||||
|
///
|
||||||
/// [`set_control_flow()`]: ActiveEventLoop::set_control_flow()
|
/// [`set_control_flow()`]: ActiveEventLoop::set_control_flow()
|
||||||
/// [`run_app()`]: Self::run_app()
|
/// [`run_app()`]: Self::run_app()
|
||||||
/// [^1]: `EventLoopExtWebSys::spawn_app()` is only available on Web.
|
|
||||||
#[inline]
|
#[inline]
|
||||||
#[cfg(not(all(web_platform, target_feature = "exception-handling")))]
|
#[cfg(not(all(web_platform, target_feature = "exception-handling")))]
|
||||||
pub fn run_app<A: ApplicationHandler<T>>(self, app: &mut A) -> Result<(), EventLoopError> {
|
pub fn run_app<A: ApplicationHandler>(self, app: A) -> Result<(), EventLoopError> {
|
||||||
self.event_loop
|
self.event_loop.run_app(app)
|
||||||
.run(|event, event_loop| dispatch_event_for_app(app, event_loop, event))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates an [`EventLoopProxy`] that can be used to dispatch user events
|
/// Creates an [`EventLoopProxy`] that can be used to dispatch user events
|
||||||
/// to the main event loop, possibly from another thread.
|
/// to the main event loop, possibly from another thread.
|
||||||
pub fn create_proxy(&self) -> EventLoopProxy<T> {
|
pub fn create_proxy(&self) -> EventLoopProxy {
|
||||||
EventLoopProxy {
|
self.event_loop.window_target().create_proxy()
|
||||||
event_loop_proxy: self.event_loop.create_proxy(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Gets a persistent reference to the underlying platform display.
|
/// Gets a persistent reference to the underlying platform display.
|
||||||
///
|
///
|
||||||
/// See the [`OwnedDisplayHandle`] type for more information.
|
/// See the [`OwnedDisplayHandle`] type for more information.
|
||||||
pub fn owned_display_handle(&self) -> OwnedDisplayHandle {
|
pub fn owned_display_handle(&self) -> OwnedDisplayHandle {
|
||||||
OwnedDisplayHandle {
|
self.event_loop.window_target().owned_display_handle()
|
||||||
platform: self.event_loop.window_target().p.owned_display_handle(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Change if or when [`DeviceEvent`]s are captured.
|
/// Change if or when [`DeviceEvent`]s are captured.
|
||||||
@@ -294,65 +254,35 @@ impl<T> EventLoop<T> {
|
|||||||
allowed = ?allowed
|
allowed = ?allowed
|
||||||
)
|
)
|
||||||
.entered();
|
.entered();
|
||||||
|
self.event_loop.window_target().listen_device_events(allowed)
|
||||||
self.event_loop
|
|
||||||
.window_target()
|
|
||||||
.p
|
|
||||||
.listen_device_events(allowed);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets the [`ControlFlow`].
|
/// Sets the [`ControlFlow`].
|
||||||
pub fn set_control_flow(&self, control_flow: ControlFlow) {
|
pub fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||||
self.event_loop
|
self.event_loop.window_target().set_control_flow(control_flow);
|
||||||
.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.
|
/// Create custom cursor.
|
||||||
pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor {
|
///
|
||||||
self.event_loop
|
/// ## Platform-specific
|
||||||
.window_target()
|
///
|
||||||
.p
|
/// **iOS / Android / Orbital:** Unsupported.
|
||||||
.create_custom_cursor(custom_cursor)
|
pub fn create_custom_cursor(
|
||||||
|
&self,
|
||||||
|
custom_cursor: CustomCursorSource,
|
||||||
|
) -> Result<CustomCursor, RequestError> {
|
||||||
|
self.event_loop.window_target().create_custom_cursor(custom_cursor)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "rwh_06")]
|
impl HasDisplayHandle for EventLoop {
|
||||||
impl<T> rwh_06::HasDisplayHandle for EventLoop<T> {
|
fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
|
||||||
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
HasDisplayHandle::display_handle(self.event_loop.window_target().rwh_06_handle())
|
||||||
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))]
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
impl<T> AsFd for EventLoop<T> {
|
impl AsFd for EventLoop {
|
||||||
/// Get the underlying [EventLoop]'s `fd` which you can register
|
/// Get the underlying [EventLoop]'s `fd` which you can register
|
||||||
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
||||||
/// loop must be polled with the [`pump_app_events`] API.
|
/// loop must be polled with the [`pump_app_events`] API.
|
||||||
@@ -366,7 +296,7 @@ impl<T> AsFd for EventLoop<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(x11_platform, wayland_platform))]
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
impl<T> AsRawFd for EventLoop<T> {
|
impl AsRawFd for EventLoop {
|
||||||
/// Get the underlying [EventLoop]'s raw `fd` which you can register
|
/// Get the underlying [EventLoop]'s raw `fd` which you can register
|
||||||
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
||||||
/// loop must be polled with the [`pump_app_events`] API.
|
/// loop must be polled with the [`pump_app_events`] API.
|
||||||
@@ -379,45 +309,45 @@ impl<T> AsRawFd for EventLoop<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ActiveEventLoop {
|
pub trait ActiveEventLoop: AsAny {
|
||||||
|
/// Creates an [`EventLoopProxy`] that can be used to dispatch user events
|
||||||
|
/// to the main event loop, possibly from another thread.
|
||||||
|
fn create_proxy(&self) -> EventLoopProxy;
|
||||||
|
|
||||||
/// Create the window.
|
/// Create the window.
|
||||||
///
|
///
|
||||||
/// Possible causes of error include denied permission, incompatible system, and lack of memory.
|
/// Possible causes of error include denied permission, incompatible system, and lack of memory.
|
||||||
///
|
///
|
||||||
/// ## Platform-specific
|
/// ## Platform-specific
|
||||||
///
|
///
|
||||||
/// - **Web:** The window is created but not inserted into the web page automatically. Please
|
/// - **Web:** The window is created but not inserted into the Web page automatically. Please
|
||||||
/// see the web platform module for more information.
|
/// see the Web platform module for more information.
|
||||||
#[inline]
|
fn create_window(
|
||||||
pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> {
|
&self,
|
||||||
let _span = tracing::debug_span!(
|
window_attributes: WindowAttributes,
|
||||||
"winit::ActiveEventLoop::create_window",
|
) -> Result<Box<dyn Window>, RequestError>;
|
||||||
window_attributes = ?window_attributes
|
|
||||||
)
|
|
||||||
.entered();
|
|
||||||
|
|
||||||
let window = platform_impl::Window::new(&self.p, window_attributes)?;
|
|
||||||
Ok(Window { window })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create custom cursor.
|
/// Create custom cursor.
|
||||||
pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor {
|
///
|
||||||
let _span = tracing::debug_span!("winit::ActiveEventLoop::create_custom_cursor",).entered();
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
self.p.create_custom_cursor(custom_cursor)
|
/// **iOS / Android / Orbital:** Unsupported.
|
||||||
}
|
fn create_custom_cursor(
|
||||||
|
&self,
|
||||||
|
custom_cursor: CustomCursorSource,
|
||||||
|
) -> Result<CustomCursor, RequestError>;
|
||||||
|
|
||||||
/// Returns the list of all the monitors available on the system.
|
/// Returns the list of all the monitors available on the system.
|
||||||
#[inline]
|
///
|
||||||
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
|
/// ## Platform-specific
|
||||||
let _span = tracing::debug_span!("winit::ActiveEventLoop::available_monitors",).entered();
|
///
|
||||||
|
/// **Web:** Only returns the current monitor without
|
||||||
#[allow(clippy::useless_conversion)] // false positive on some platforms
|
#[cfg_attr(
|
||||||
self.p
|
any(web_platform, docsrs),
|
||||||
.available_monitors()
|
doc = "[detailed monitor permissions][crate::platform::web::ActiveEventLoopExtWeb::request_detailed_monitor_permission]."
|
||||||
.into_iter()
|
)]
|
||||||
.map(|inner| MonitorHandle { inner })
|
#[cfg_attr(not(any(web_platform, docsrs)), doc = "detailed monitor permissions.")]
|
||||||
}
|
fn available_monitors(&self) -> Box<dyn Iterator<Item = MonitorHandle>>;
|
||||||
|
|
||||||
/// Returns the primary monitor of the system.
|
/// Returns the primary monitor of the system.
|
||||||
///
|
///
|
||||||
@@ -425,15 +355,14 @@ impl ActiveEventLoop {
|
|||||||
///
|
///
|
||||||
/// ## Platform-specific
|
/// ## Platform-specific
|
||||||
///
|
///
|
||||||
/// **Wayland / Web:** Always returns `None`.
|
/// - **Wayland:** Always returns `None`.
|
||||||
#[inline]
|
/// - **Web:** Always returns `None` without
|
||||||
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
#[cfg_attr(
|
||||||
let _span = tracing::debug_span!("winit::ActiveEventLoop::primary_monitor",).entered();
|
any(web_platform, docsrs),
|
||||||
|
doc = " [detailed monitor permissions][crate::platform::web::ActiveEventLoopExtWeb::request_detailed_monitor_permission]."
|
||||||
self.p
|
)]
|
||||||
.primary_monitor()
|
#[cfg_attr(not(any(web_platform, docsrs)), doc = " detailed monitor permissions.")]
|
||||||
.map(|inner| MonitorHandle { inner })
|
fn primary_monitor(&self) -> Option<MonitorHandle>;
|
||||||
}
|
|
||||||
|
|
||||||
/// Change if or when [`DeviceEvent`]s are captured.
|
/// Change if or when [`DeviceEvent`]s are captured.
|
||||||
///
|
///
|
||||||
@@ -446,72 +375,51 @@ impl ActiveEventLoop {
|
|||||||
/// - **Wayland / macOS / iOS / Android / Orbital:** Unsupported.
|
/// - **Wayland / macOS / iOS / Android / Orbital:** Unsupported.
|
||||||
///
|
///
|
||||||
/// [`DeviceEvent`]: crate::event::DeviceEvent
|
/// [`DeviceEvent`]: crate::event::DeviceEvent
|
||||||
pub fn listen_device_events(&self, allowed: DeviceEvents) {
|
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.
|
||||||
|
fn system_theme(&self) -> Option<Theme>;
|
||||||
|
|
||||||
/// Sets the [`ControlFlow`].
|
/// Sets the [`ControlFlow`].
|
||||||
pub fn set_control_flow(&self, control_flow: ControlFlow) {
|
fn set_control_flow(&self, control_flow: ControlFlow);
|
||||||
self.p.set_control_flow(control_flow)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets the current [`ControlFlow`].
|
/// Gets the current [`ControlFlow`].
|
||||||
pub fn control_flow(&self) -> ControlFlow {
|
fn control_flow(&self) -> ControlFlow;
|
||||||
self.p.control_flow()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// This exits the event loop.
|
/// This exits the event loop.
|
||||||
///
|
///
|
||||||
/// See [`LoopExiting`][Event::LoopExiting].
|
/// See [`exiting`][crate::application::ApplicationHandler::exiting].
|
||||||
pub fn exit(&self) {
|
fn exit(&self);
|
||||||
let _span = tracing::debug_span!("winit::ActiveEventLoop::exit",).entered();
|
|
||||||
|
|
||||||
self.p.exit()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns if the [`EventLoop`] is about to stop.
|
/// Returns if the [`EventLoop`] is about to stop.
|
||||||
///
|
///
|
||||||
/// See [`exit()`][Self::exit].
|
/// See [`exit()`][Self::exit].
|
||||||
pub fn exiting(&self) -> bool {
|
fn exiting(&self) -> bool;
|
||||||
self.p.exiting()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets a persistent reference to the underlying platform display.
|
/// Gets a persistent reference to the underlying platform display.
|
||||||
///
|
///
|
||||||
/// See the [`OwnedDisplayHandle`] type for more information.
|
/// See the [`OwnedDisplayHandle`] type for more information.
|
||||||
pub fn owned_display_handle(&self) -> OwnedDisplayHandle {
|
fn owned_display_handle(&self) -> OwnedDisplayHandle;
|
||||||
OwnedDisplayHandle {
|
|
||||||
platform: self.p.owned_display_handle(),
|
/// Get the raw-window-handle handle.
|
||||||
}
|
fn rwh_06_handle(&self) -> &dyn HasDisplayHandle;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "rwh_06")]
|
impl HasDisplayHandle for dyn ActiveEventLoop + '_ {
|
||||||
impl rwh_06::HasDisplayHandle for ActiveEventLoop {
|
fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
|
||||||
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
self.rwh_06_handle().display_handle()
|
||||||
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.
|
/// A proxy for the underlying display handle.
|
||||||
///
|
///
|
||||||
/// The purpose of this type is to provide a cheaply clonable handle to the underlying
|
/// 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.
|
/// 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`]
|
/// 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
|
/// type. In contrast, this type involves no lifetimes and can be persisted for as long as
|
||||||
@@ -523,89 +431,83 @@ unsafe impl rwh_05::HasRawDisplayHandle for ActiveEventLoop {
|
|||||||
/// - A reference-counted pointer to the underlying type.
|
/// - A reference-counted pointer to the underlying type.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct OwnedDisplayHandle {
|
pub struct OwnedDisplayHandle {
|
||||||
#[cfg_attr(not(any(feature = "rwh_05", feature = "rwh_06")), allow(dead_code))]
|
pub(crate) handle: Arc<dyn HasDisplayHandle>,
|
||||||
platform: platform_impl::OwnedDisplayHandle,
|
}
|
||||||
|
|
||||||
|
impl OwnedDisplayHandle {
|
||||||
|
pub(crate) fn new(handle: Arc<dyn HasDisplayHandle>) -> Self {
|
||||||
|
Self { handle }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HasDisplayHandle for OwnedDisplayHandle {
|
||||||
|
fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
|
||||||
|
self.handle.display_handle()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Debug for OwnedDisplayHandle {
|
impl fmt::Debug for OwnedDisplayHandle {
|
||||||
#[inline]
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.debug_struct("OwnedDisplayHandle").finish_non_exhaustive()
|
f.debug_struct("OwnedDisplayHandle").finish_non_exhaustive()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "rwh_06")]
|
impl PartialEq for OwnedDisplayHandle {
|
||||||
impl rwh_06::HasDisplayHandle for OwnedDisplayHandle {
|
fn eq(&self, other: &Self) -> bool {
|
||||||
#[inline]
|
match (self.display_handle(), other.display_handle()) {
|
||||||
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
(Ok(lhs), Ok(rhs)) => lhs == rhs,
|
||||||
let raw = self.platform.raw_display_handle_rwh_06()?;
|
_ => false,
|
||||||
|
|
||||||
// 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> {
|
impl Eq for OwnedDisplayHandle {}
|
||||||
/// 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)
|
pub(crate) trait EventLoopProxyProvider: Send + Sync {
|
||||||
}
|
/// See [`EventLoopProxy::wake_up`] for details.
|
||||||
|
fn wake_up(&self);
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: 'static> fmt::Debug for EventLoopProxy<T> {
|
/// Control the [`EventLoop`], possibly from a different thread, without referencing it directly.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct EventLoopProxy {
|
||||||
|
pub(crate) proxy: Arc<dyn EventLoopProxyProvider>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for EventLoopProxy {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.pad("EventLoopProxy { .. }")
|
f.debug_struct("EventLoopProxy").finish_non_exhaustive()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The error that is returned when an [`EventLoopProxy`] attempts to wake up an [`EventLoop`] that
|
impl EventLoopProxy {
|
||||||
/// no longer exists.
|
/// Wake up the [`EventLoop`], resulting in [`ApplicationHandler::proxy_wake_up()`] being
|
||||||
///
|
/// called.
|
||||||
/// Contains the original event given to [`EventLoopProxy::send_event`].
|
///
|
||||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
/// Calls to this method are coalesced into a single call to [`proxy_wake_up`], see the
|
||||||
pub struct EventLoopClosed<T>(pub T);
|
/// documentation on that for details.
|
||||||
|
///
|
||||||
|
/// If the event loop is no longer running, this is a no-op.
|
||||||
|
///
|
||||||
|
/// [`proxy_wake_up`]: ApplicationHandler::proxy_wake_up
|
||||||
|
///
|
||||||
|
/// # Platform-specific
|
||||||
|
///
|
||||||
|
/// - **Windows**: The wake-up may be ignored under high contention, see [#3687].
|
||||||
|
///
|
||||||
|
/// [#3687]: https://github.com/rust-windowing/winit/pull/3687
|
||||||
|
pub fn wake_up(&self) {
|
||||||
|
self.proxy.wake_up();
|
||||||
|
}
|
||||||
|
|
||||||
impl<T> fmt::Display for EventLoopClosed<T> {
|
pub(crate) fn new(proxy: Arc<dyn EventLoopProxyProvider>) -> Self {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
Self { proxy }
|
||||||
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.
|
/// Control when device events are captured.
|
||||||
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
|
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
pub enum DeviceEvents {
|
pub enum DeviceEvents {
|
||||||
/// Report device events regardless of window focus.
|
/// Report device events regardless of window focus.
|
||||||
Always,
|
Always,
|
||||||
@@ -625,7 +527,7 @@ pub enum DeviceEvents {
|
|||||||
/// containing [`AsyncRequestSerial`] and some closure associated with it.
|
/// containing [`AsyncRequestSerial`] and some closure associated with it.
|
||||||
/// Then once event is arriving the working list is being traversed and a job
|
/// Then once event is arriving the working list is being traversed and a job
|
||||||
/// executed and removed from the list.
|
/// executed and removed from the list.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
pub struct AsyncRequestSerial {
|
pub struct AsyncRequestSerial {
|
||||||
serial: usize,
|
serial: usize,
|
||||||
}
|
}
|
||||||
@@ -641,23 +543,3 @@ impl AsyncRequestSerial {
|
|||||||
Self { serial }
|
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),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
55
src/icon.rs
55
src/icon.rs
@@ -1,5 +1,7 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use std::{fmt, io, mem};
|
||||||
|
|
||||||
use crate::platform_impl::PlatformIcon;
|
use crate::platform_impl::PlatformIcon;
|
||||||
use std::{error::Error, fmt, io, mem};
|
|
||||||
|
|
||||||
#[repr(C)]
|
#[repr(C)]
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -20,12 +22,7 @@ pub enum BadIcon {
|
|||||||
ByteCountNotDivisibleBy4 { byte_count: usize },
|
ByteCountNotDivisibleBy4 { byte_count: usize },
|
||||||
/// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`.
|
/// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`.
|
||||||
/// At least one of your arguments is incorrect.
|
/// At least one of your arguments is incorrect.
|
||||||
DimensionsVsPixelCount {
|
DimensionsVsPixelCount { width: u32, height: u32, width_x_height: usize, pixel_count: usize },
|
||||||
width: u32,
|
|
||||||
height: u32,
|
|
||||||
width_x_height: usize,
|
|
||||||
pixel_count: usize,
|
|
||||||
},
|
|
||||||
/// Produced when underlying OS functionality failed to create the icon
|
/// Produced when underlying OS functionality failed to create the icon
|
||||||
OsError(io::Error),
|
OsError(io::Error),
|
||||||
}
|
}
|
||||||
@@ -33,17 +30,19 @@ pub enum BadIcon {
|
|||||||
impl fmt::Display for BadIcon {
|
impl fmt::Display for BadIcon {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
BadIcon::ByteCountNotDivisibleBy4 { byte_count } => write!(f,
|
BadIcon::ByteCountNotDivisibleBy4 { byte_count } => write!(
|
||||||
"The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making it impossible to interpret as 32bpp RGBA pixels.",
|
f,
|
||||||
),
|
"The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making \
|
||||||
BadIcon::DimensionsVsPixelCount {
|
it impossible to interpret as 32bpp RGBA pixels.",
|
||||||
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::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:?}"),
|
BadIcon::OsError(e) => write!(f, "OS error when instantiating the icon: {e:?}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -51,15 +50,15 @@ impl fmt::Display for BadIcon {
|
|||||||
|
|
||||||
impl Error for BadIcon {}
|
impl Error for BadIcon {}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
pub(crate) struct RgbaIcon {
|
pub(crate) struct RgbaIcon {
|
||||||
pub(crate) rgba: Vec<u8>,
|
pub(crate) rgba: Vec<u8>,
|
||||||
pub(crate) width: u32,
|
pub(crate) width: u32,
|
||||||
pub(crate) height: u32,
|
pub(crate) height: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// For platforms which don't have window icons (e.g. web)
|
/// For platforms which don't have window icons (e.g. Web)
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
pub(crate) struct NoIcon;
|
pub(crate) struct NoIcon;
|
||||||
|
|
||||||
#[allow(dead_code)] // These are not used on every platform
|
#[allow(dead_code)] // These are not used on every platform
|
||||||
@@ -69,9 +68,7 @@ mod constructors {
|
|||||||
impl RgbaIcon {
|
impl RgbaIcon {
|
||||||
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
||||||
if rgba.len() % PIXEL_SIZE != 0 {
|
if rgba.len() % PIXEL_SIZE != 0 {
|
||||||
return Err(BadIcon::ByteCountNotDivisibleBy4 {
|
return Err(BadIcon::ByteCountNotDivisibleBy4 { byte_count: rgba.len() });
|
||||||
byte_count: rgba.len(),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
let pixel_count = rgba.len() / PIXEL_SIZE;
|
let pixel_count = rgba.len() / PIXEL_SIZE;
|
||||||
if pixel_count != (width * height) as usize {
|
if pixel_count != (width * height) as usize {
|
||||||
@@ -82,11 +79,7 @@ mod constructors {
|
|||||||
pixel_count,
|
pixel_count,
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
Ok(RgbaIcon {
|
Ok(RgbaIcon { rgba, width, height })
|
||||||
rgba,
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -101,7 +94,7 @@ mod constructors {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// An icon used for the window titlebar, taskbar, etc.
|
/// An icon used for the window titlebar, taskbar, etc.
|
||||||
#[derive(Clone)]
|
#[derive(Clone, Eq, Hash, PartialEq)]
|
||||||
pub struct Icon {
|
pub struct Icon {
|
||||||
pub(crate) inner: PlatformIcon,
|
pub(crate) inner: PlatformIcon,
|
||||||
}
|
}
|
||||||
@@ -120,8 +113,6 @@ impl Icon {
|
|||||||
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
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();
|
let _span = tracing::debug_span!("winit::Icon::from_rgba", width, height).entered();
|
||||||
|
|
||||||
Ok(Icon {
|
Ok(Icon { inner: PlatformIcon::from_rgba(rgba, width, height)? })
|
||||||
inner: PlatformIcon::from_rgba(rgba, width, height)?,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
133
src/keyboard.rs
133
src/keyboard.rs
@@ -84,7 +84,7 @@ pub use smol_str::SmolStr;
|
|||||||
/// haven't mapped for you yet, this lets you use use [`KeyCode`] to:
|
/// haven't mapped for you yet, this lets you use use [`KeyCode`] to:
|
||||||
///
|
///
|
||||||
/// - Correctly match key press and release events.
|
/// - Correctly match key press and release events.
|
||||||
/// - On non-web platforms, support assigning keybinds to virtually any key through a UI.
|
/// - On non-Web platforms, support assigning keybinds to virtually any key through a UI.
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum NativeKeyCode {
|
pub enum NativeKeyCode {
|
||||||
@@ -106,23 +106,23 @@ impl std::fmt::Debug for NativeKeyCode {
|
|||||||
match self {
|
match self {
|
||||||
Unidentified => {
|
Unidentified => {
|
||||||
debug_tuple = f.debug_tuple("Unidentified");
|
debug_tuple = f.debug_tuple("Unidentified");
|
||||||
}
|
},
|
||||||
Android(code) => {
|
Android(code) => {
|
||||||
debug_tuple = f.debug_tuple("Android");
|
debug_tuple = f.debug_tuple("Android");
|
||||||
debug_tuple.field(&format_args!("0x{code:04X}"));
|
debug_tuple.field(&format_args!("0x{code:04X}"));
|
||||||
}
|
},
|
||||||
MacOS(code) => {
|
MacOS(code) => {
|
||||||
debug_tuple = f.debug_tuple("MacOS");
|
debug_tuple = f.debug_tuple("MacOS");
|
||||||
debug_tuple.field(&format_args!("0x{code:04X}"));
|
debug_tuple.field(&format_args!("0x{code:04X}"));
|
||||||
}
|
},
|
||||||
Windows(code) => {
|
Windows(code) => {
|
||||||
debug_tuple = f.debug_tuple("Windows");
|
debug_tuple = f.debug_tuple("Windows");
|
||||||
debug_tuple.field(&format_args!("0x{code:04X}"));
|
debug_tuple.field(&format_args!("0x{code:04X}"));
|
||||||
}
|
},
|
||||||
Xkb(code) => {
|
Xkb(code) => {
|
||||||
debug_tuple = f.debug_tuple("Xkb");
|
debug_tuple = f.debug_tuple("Xkb");
|
||||||
debug_tuple.field(&format_args!("0x{code:04X}"));
|
debug_tuple.field(&format_args!("0x{code:04X}"));
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
debug_tuple.finish()
|
debug_tuple.finish()
|
||||||
}
|
}
|
||||||
@@ -162,27 +162,27 @@ impl std::fmt::Debug for NativeKey {
|
|||||||
match self {
|
match self {
|
||||||
Unidentified => {
|
Unidentified => {
|
||||||
debug_tuple = f.debug_tuple("Unidentified");
|
debug_tuple = f.debug_tuple("Unidentified");
|
||||||
}
|
},
|
||||||
Android(code) => {
|
Android(code) => {
|
||||||
debug_tuple = f.debug_tuple("Android");
|
debug_tuple = f.debug_tuple("Android");
|
||||||
debug_tuple.field(&format_args!("0x{code:04X}"));
|
debug_tuple.field(&format_args!("0x{code:04X}"));
|
||||||
}
|
},
|
||||||
MacOS(code) => {
|
MacOS(code) => {
|
||||||
debug_tuple = f.debug_tuple("MacOS");
|
debug_tuple = f.debug_tuple("MacOS");
|
||||||
debug_tuple.field(&format_args!("0x{code:04X}"));
|
debug_tuple.field(&format_args!("0x{code:04X}"));
|
||||||
}
|
},
|
||||||
Windows(code) => {
|
Windows(code) => {
|
||||||
debug_tuple = f.debug_tuple("Windows");
|
debug_tuple = f.debug_tuple("Windows");
|
||||||
debug_tuple.field(&format_args!("0x{code:04X}"));
|
debug_tuple.field(&format_args!("0x{code:04X}"));
|
||||||
}
|
},
|
||||||
Xkb(code) => {
|
Xkb(code) => {
|
||||||
debug_tuple = f.debug_tuple("Xkb");
|
debug_tuple = f.debug_tuple("Xkb");
|
||||||
debug_tuple.field(&format_args!("0x{code:04X}"));
|
debug_tuple.field(&format_args!("0x{code:04X}"));
|
||||||
}
|
},
|
||||||
Web(code) => {
|
Web(code) => {
|
||||||
debug_tuple = f.debug_tuple("Web");
|
debug_tuple = f.debug_tuple("Web");
|
||||||
debug_tuple.field(code);
|
debug_tuple.field(code);
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
debug_tuple.finish()
|
debug_tuple.finish()
|
||||||
}
|
}
|
||||||
@@ -442,7 +442,8 @@ pub enum KeyCode {
|
|||||||
Tab,
|
Tab,
|
||||||
/// Japanese: <kbd>変</kbd> (henkan)
|
/// Japanese: <kbd>変</kbd> (henkan)
|
||||||
Convert,
|
Convert,
|
||||||
/// Japanese: <kbd>カタカナ</kbd>/<kbd>ひらがな</kbd>/<kbd>ローマ字</kbd> (katakana/hiragana/romaji)
|
/// Japanese: <kbd>カタカナ</kbd>/<kbd>ひらがな</kbd>/<kbd>ローマ字</kbd>
|
||||||
|
/// (katakana/hiragana/romaji)
|
||||||
KanaMode,
|
KanaMode,
|
||||||
/// Korean: HangulMode <kbd>한/영</kbd> (han/yeong)
|
/// Korean: HangulMode <kbd>한/영</kbd> (han/yeong)
|
||||||
///
|
///
|
||||||
@@ -490,7 +491,8 @@ pub enum KeyCode {
|
|||||||
NumLock,
|
NumLock,
|
||||||
/// <kbd>0 Ins</kbd> on a keyboard. <kbd>0</kbd> on a phone or remote control
|
/// <kbd>0 Ins</kbd> on a keyboard. <kbd>0</kbd> on a phone or remote control
|
||||||
Numpad0,
|
Numpad0,
|
||||||
/// <kbd>1 End</kbd> on a keyboard. <kbd>1</kbd> or <kbd>1 QZ</kbd> on a phone or remote control
|
/// <kbd>1 End</kbd> on a keyboard. <kbd>1</kbd> or <kbd>1 QZ</kbd> on a phone or remote
|
||||||
|
/// control
|
||||||
Numpad1,
|
Numpad1,
|
||||||
/// <kbd>2 ↓</kbd> on a keyboard. <kbd>2 ABC</kbd> on a phone or remote control
|
/// <kbd>2 ↓</kbd> on a keyboard. <kbd>2 ABC</kbd> on a phone or remote control
|
||||||
Numpad2,
|
Numpad2,
|
||||||
@@ -794,13 +796,14 @@ pub enum NamedKey {
|
|||||||
// Legacy modifier key.
|
// Legacy modifier key.
|
||||||
Hyper,
|
Hyper,
|
||||||
/// Used to enable "super" modifier function for interpreting concurrent or subsequent keyboard
|
/// Used to enable "super" modifier function for interpreting concurrent or subsequent keyboard
|
||||||
/// input. This key value is used for the "Windows Logo" key and the Apple `Command` or `⌘` key.
|
/// input. This key value is used for the "Windows Logo" key and the Apple `Command` or `⌘`
|
||||||
|
/// key.
|
||||||
///
|
///
|
||||||
/// Note: In some contexts (e.g. the Web) this is referred to as the "Meta" key.
|
/// Note: In some contexts (e.g. the Web) this is referred to as the "Meta" key.
|
||||||
Super,
|
Super,
|
||||||
/// The `Enter` or `↵` key. Used to activate current selection or accept current input. This key
|
/// The `Enter` or `↵` key. Used to activate current selection or accept current input. This
|
||||||
/// value is also used for the `Return` (Macintosh numpad) key. This key value is also used for
|
/// key value is also used for the `Return` (Macintosh numpad) key. This key value is also
|
||||||
/// the Android `KEYCODE_DPAD_CENTER`.
|
/// used for the Android `KEYCODE_DPAD_CENTER`.
|
||||||
Enter,
|
Enter,
|
||||||
/// The Horizontal Tabulation `Tab` key.
|
/// The Horizontal Tabulation `Tab` key.
|
||||||
Tab,
|
Tab,
|
||||||
@@ -836,8 +839,8 @@ pub enum NamedKey {
|
|||||||
CrSel,
|
CrSel,
|
||||||
/// Cut the current selection. (`APPCOMMAND_CUT`)
|
/// Cut the current selection. (`APPCOMMAND_CUT`)
|
||||||
Cut,
|
Cut,
|
||||||
/// Used to delete the character to the right of the cursor. This key value is also used for the
|
/// Used to delete the character to the right of the cursor. This key value is also used for
|
||||||
/// key labeled `Delete` on MacOS keyboards when `Fn` is active.
|
/// the key labeled `Delete` on MacOS keyboards when `Fn` is active.
|
||||||
Delete,
|
Delete,
|
||||||
/// The Erase to End of Field key. This key deletes all characters from the current cursor
|
/// The Erase to End of Field key. This key deletes all characters from the current cursor
|
||||||
/// position to the end of the current field.
|
/// position to the end of the current field.
|
||||||
@@ -921,8 +924,8 @@ pub enum NamedKey {
|
|||||||
/// their code points.
|
/// their code points.
|
||||||
CodeInput,
|
CodeInput,
|
||||||
/// The Compose key, also known as "Multi_key" on the X Window System. This key acts in a
|
/// The Compose key, also known as "Multi_key" on the X Window System. This key acts in a
|
||||||
/// manner similar to a dead key, triggering a mode where subsequent key presses are combined to
|
/// manner similar to a dead key, triggering a mode where subsequent key presses are combined
|
||||||
/// produce a different character.
|
/// to produce a different character.
|
||||||
Compose,
|
Compose,
|
||||||
/// Convert the current input method sequence.
|
/// Convert the current input method sequence.
|
||||||
Convert,
|
Convert,
|
||||||
@@ -961,9 +964,9 @@ pub enum NamedKey {
|
|||||||
/// The Kana Mode (Kana Lock) key. This key is used to enter hiragana mode (typically from
|
/// The Kana Mode (Kana Lock) key. This key is used to enter hiragana mode (typically from
|
||||||
/// romaji mode).
|
/// romaji mode).
|
||||||
KanaMode,
|
KanaMode,
|
||||||
/// The Kanji (Japanese name for ideographic characters of Chinese origin) Mode key. This key is
|
/// The Kanji (Japanese name for ideographic characters of Chinese origin) Mode key. This key
|
||||||
/// typically used to switch to a hiragana keyboard for the purpose of converting input into
|
/// is typically used to switch to a hiragana keyboard for the purpose of converting input
|
||||||
/// kanji. (`KEYCODE_KANA`)
|
/// into kanji. (`KEYCODE_KANA`)
|
||||||
KanjiMode,
|
KanjiMode,
|
||||||
/// The Katakana (Japanese Kana characters) key.
|
/// The Katakana (Japanese Kana characters) key.
|
||||||
Katakana,
|
Katakana,
|
||||||
@@ -1565,10 +1568,15 @@ impl NamedKey {
|
|||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
|
/// # #[cfg(web_platform)]
|
||||||
|
/// # wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
|
||||||
|
/// # #[cfg_attr(web_platform, wasm_bindgen_test::wasm_bindgen_test)]
|
||||||
|
/// # fn main() {
|
||||||
/// use winit::keyboard::NamedKey;
|
/// use winit::keyboard::NamedKey;
|
||||||
///
|
///
|
||||||
/// assert_eq!(NamedKey::Enter.to_text(), Some("\r"));
|
/// assert_eq!(NamedKey::Enter.to_text(), Some("\r"));
|
||||||
/// assert_eq!(NamedKey::F20.to_text(), None);
|
/// assert_eq!(NamedKey::F20.to_text(), None);
|
||||||
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn to_text(&self) -> Option<&str> {
|
pub fn to_text(&self) -> Option<&str> {
|
||||||
match self {
|
match self {
|
||||||
@@ -1588,11 +1596,16 @@ impl Key {
|
|||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use winit::keyboard::{NamedKey, Key};
|
/// # #[cfg(web_platform)]
|
||||||
|
/// # wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
|
||||||
|
/// # #[cfg_attr(web_platform, wasm_bindgen_test::wasm_bindgen_test)]
|
||||||
|
/// # fn main() {
|
||||||
|
/// use winit::keyboard::{Key, NamedKey};
|
||||||
///
|
///
|
||||||
/// assert_eq!(Key::Character("a".into()).to_text(), Some("a"));
|
/// assert_eq!(Key::Character("a".into()).to_text(), Some("a"));
|
||||||
/// assert_eq!(Key::Named(NamedKey::Enter).to_text(), Some("\r"));
|
/// assert_eq!(Key::Named(NamedKey::Enter).to_text(), Some("\r"));
|
||||||
/// assert_eq!(Key::Named(NamedKey::F20).to_text(), None);
|
/// assert_eq!(Key::Named(NamedKey::F20).to_text(), None);
|
||||||
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn to_text(&self) -> Option<&str> {
|
pub fn to_text(&self) -> Option<&str> {
|
||||||
match self {
|
match self {
|
||||||
@@ -1610,17 +1623,18 @@ impl Key {
|
|||||||
/// keys can be above the letters or on the numpad. This enum allows the user to differentiate
|
/// keys can be above the letters or on the numpad. This enum allows the user to differentiate
|
||||||
/// them.
|
/// them.
|
||||||
///
|
///
|
||||||
/// See the documentation for the [`location`] field on the [`KeyEvent`] struct for more information.
|
/// See the documentation for the [`location`] field on the [`KeyEvent`] struct for more
|
||||||
|
/// information.
|
||||||
///
|
///
|
||||||
/// [`location`]: ../event/struct.KeyEvent.html#structfield.location
|
/// [`location`]: ../event/struct.KeyEvent.html#structfield.location
|
||||||
/// [`KeyEvent`]: crate::event::KeyEvent
|
/// [`KeyEvent`]: crate::event::KeyEvent
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum KeyLocation {
|
pub enum KeyLocation {
|
||||||
/// The key is in its "normal" location on the keyboard.
|
/// The key is in its "normal" location on the keyboard.
|
||||||
///
|
///
|
||||||
/// For instance, the "1" key above the "Q" key on a QWERTY keyboard will use this location. This
|
/// For instance, the "1" key above the "Q" key on a QWERTY keyboard will use this location.
|
||||||
/// invariant is also returned when the location of the key cannot be identified.
|
/// This invariant is also returned when the location of the key cannot be identified.
|
||||||
///
|
///
|
||||||
/// 
|
/// 
|
||||||
///
|
///
|
||||||
@@ -1686,6 +1700,7 @@ bitflags! {
|
|||||||
///
|
///
|
||||||
/// Each flag represents a modifier and is set if this modifier is active.
|
/// Each flag represents a modifier and is set if this modifier is active.
|
||||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub struct ModifiersState: u32 {
|
pub struct ModifiersState: u32 {
|
||||||
/// The "shift" key.
|
/// The "shift" key.
|
||||||
const SHIFT = 0b100;
|
const SHIFT = 0b100;
|
||||||
@@ -1703,14 +1718,17 @@ impl ModifiersState {
|
|||||||
pub fn shift_key(&self) -> bool {
|
pub fn shift_key(&self) -> bool {
|
||||||
self.intersects(Self::SHIFT)
|
self.intersects(Self::SHIFT)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns `true` if the control key is pressed.
|
/// Returns `true` if the control key is pressed.
|
||||||
pub fn control_key(&self) -> bool {
|
pub fn control_key(&self) -> bool {
|
||||||
self.intersects(Self::CONTROL)
|
self.intersects(Self::CONTROL)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns `true` if the alt key is pressed.
|
/// Returns `true` if the alt key is pressed.
|
||||||
pub fn alt_key(&self) -> bool {
|
pub fn alt_key(&self) -> bool {
|
||||||
self.intersects(Self::ALT)
|
self.intersects(Self::ALT)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns `true` if the super key is pressed.
|
/// Returns `true` if the super key is pressed.
|
||||||
pub fn super_key(&self) -> bool {
|
pub fn super_key(&self) -> bool {
|
||||||
self.intersects(Self::SUPER)
|
self.intersects(Self::SUPER)
|
||||||
@@ -1718,7 +1736,8 @@ impl ModifiersState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The state of the particular modifiers key.
|
/// The state of the particular modifiers key.
|
||||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum ModifiersKeyState {
|
pub enum ModifiersKeyState {
|
||||||
/// The particular key is pressed.
|
/// The particular key is pressed.
|
||||||
Pressed,
|
Pressed,
|
||||||
@@ -1737,6 +1756,7 @@ pub enum ModifiersKeyState {
|
|||||||
// on macOS due to their AltGr/Option situation.
|
// on macOS due to their AltGr/Option situation.
|
||||||
bitflags! {
|
bitflags! {
|
||||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub(crate) struct ModifiersKeys: u8 {
|
pub(crate) struct ModifiersKeys: u8 {
|
||||||
const LSHIFT = 0b0000_0001;
|
const LSHIFT = 0b0000_0001;
|
||||||
const RSHIFT = 0b0000_0010;
|
const RSHIFT = 0b0000_0010;
|
||||||
@@ -1748,54 +1768,3 @@ bitflags! {
|
|||||||
const RSUPER = 0b1000_0000;
|
const RSUPER = 0b1000_0000;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
mod modifiers_serde {
|
|
||||||
use super::ModifiersState;
|
|
||||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
|
||||||
|
|
||||||
#[derive(Default, Serialize, Deserialize)]
|
|
||||||
#[serde(default)]
|
|
||||||
#[serde(rename = "ModifiersState")]
|
|
||||||
pub struct ModifiersStateSerialize {
|
|
||||||
pub shift_key: bool,
|
|
||||||
pub control_key: bool,
|
|
||||||
pub alt_key: bool,
|
|
||||||
pub super_key: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Serialize for ModifiersState {
|
|
||||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
|
||||||
where
|
|
||||||
S: Serializer,
|
|
||||||
{
|
|
||||||
let s = ModifiersStateSerialize {
|
|
||||||
shift_key: self.shift_key(),
|
|
||||||
control_key: self.control_key(),
|
|
||||||
alt_key: self.alt_key(),
|
|
||||||
super_key: self.super_key(),
|
|
||||||
};
|
|
||||||
s.serialize(serializer)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'de> Deserialize<'de> for ModifiersState {
|
|
||||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
|
||||||
where
|
|
||||||
D: Deserializer<'de>,
|
|
||||||
{
|
|
||||||
let ModifiersStateSerialize {
|
|
||||||
shift_key,
|
|
||||||
control_key,
|
|
||||||
alt_key,
|
|
||||||
super_key,
|
|
||||||
} = ModifiersStateSerialize::deserialize(deserializer)?;
|
|
||||||
let mut m = ModifiersState::empty();
|
|
||||||
m.set(ModifiersState::SHIFT, shift_key);
|
|
||||||
m.set(ModifiersState::CONTROL, control_key);
|
|
||||||
m.set(ModifiersState::ALT, alt_key);
|
|
||||||
m.set(ModifiersState::SUPER, super_key);
|
|
||||||
Ok(m)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
245
src/lib.rs
245
src/lib.rs
@@ -1,5 +1,59 @@
|
|||||||
//! Winit is a cross-platform window creation and event loop management library.
|
//! Winit is a cross-platform window creation and event loop management library.
|
||||||
//!
|
//!
|
||||||
|
//! # Usage
|
||||||
|
//!
|
||||||
|
//! `winit` can be added to `Cargo.toml` as a dependency. It can be added via `cargo add`.
|
||||||
|
//!
|
||||||
|
//! ```bash
|
||||||
|
//! $ cargo add winit
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! To only enable the X11 backend on Free Unix[^unix] systems, disable default features
|
||||||
|
//! and enable the `x11` feature.
|
||||||
|
//!
|
||||||
|
//! ```bash
|
||||||
|
//! $ cargo add winit --no-default-features --features x11
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! To only enable the Wayland backend on Free Unix systems, disable default features
|
||||||
|
//! and enable the `wayland` feature.
|
||||||
|
//!
|
||||||
|
//! ```bash
|
||||||
|
//! $ cargo add winit --no-default-features --features wayland
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! These features have no effect on systems that are not Free Unix.
|
||||||
|
//!
|
||||||
|
//! ## Dependencies
|
||||||
|
//!
|
||||||
|
//! Dependencies on non-system libraries is managed through Cargo. For the X11
|
||||||
|
//! backend, the following Ubuntu packages or their equivalents must[^must] be installed.
|
||||||
|
//!
|
||||||
|
//! - `libx11-dev`
|
||||||
|
//! - `libxcb1-dev`
|
||||||
|
//! - `libxi-dev`
|
||||||
|
//! - `libxcbcommon-dev`
|
||||||
|
//! - `libxcbcommon-x11-dev`
|
||||||
|
//!
|
||||||
|
//! For the Wayland backend, the following Ubuntu packages or their equivalents
|
||||||
|
//! must be installed.
|
||||||
|
//!
|
||||||
|
//! - `libwayland-dev`
|
||||||
|
//! - `libxcbcommon-dev`
|
||||||
|
//! - `libfontconfig` (only with `sctk-adwaita` feature)
|
||||||
|
//! - `freetype` (only with `sctk-adwaita` feature)
|
||||||
|
//!
|
||||||
|
//! The "dev" packages are only needed for building binaries that use `winit`. On
|
||||||
|
//! deployed system the non-`dev` equivalents need to be installed.
|
||||||
|
//!
|
||||||
|
//! The other backends (Windows, macOS, etc) do not have any dependencies on system libraries
|
||||||
|
//! that don't already come with the operating system. However, note that the Windows backend
|
||||||
|
//! only supports Windows 10 and above, and the macOS backend only supports macOS
|
||||||
|
//! 10.14 and above.
|
||||||
|
//!
|
||||||
|
//! [^unix]: Unix systems outside of Android and Apple, like Linux or FreeBSD.
|
||||||
|
//! [^must]: This is not a "must" when the "dlopen" features are enabled
|
||||||
|
//!
|
||||||
//! # Building windows
|
//! # Building windows
|
||||||
//!
|
//!
|
||||||
//! Before you can create a [`Window`], you first need to build an [`EventLoop`]. This is done with
|
//! Before you can create a [`Window`], you first need to build an [`EventLoop`]. This is done with
|
||||||
@@ -7,7 +61,12 @@
|
|||||||
//!
|
//!
|
||||||
//! ```no_run
|
//! ```no_run
|
||||||
//! use winit::event_loop::EventLoop;
|
//! use winit::event_loop::EventLoop;
|
||||||
//! let event_loop = EventLoop::new().unwrap();
|
//!
|
||||||
|
//! # // Intentionally use `fn main` for clarity
|
||||||
|
//! fn main() {
|
||||||
|
//! let event_loop = EventLoop::new().unwrap();
|
||||||
|
//! // ...
|
||||||
|
//! }
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! Then you create a [`Window`] with [`create_window`].
|
//! Then you create a [`Window`] with [`create_window`].
|
||||||
@@ -19,33 +78,21 @@
|
|||||||
//! window or a key getting pressed while the window is focused. Devices can generate
|
//! 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.
|
//! [`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
|
//! 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.
|
//! [`DeviceEvent`].
|
||||||
//!
|
//!
|
||||||
//! You can retrieve events by calling [`EventLoop::run_app()`]. This function will
|
//! 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
|
//! dispatch events for every [`Window`] that was created with that particular [`EventLoop`], and
|
||||||
//! will run until [`exit()`] is used, at which point [`Event::LoopExiting`].
|
//! will run until [`exit()`] is used, at which point [`exiting()`] is called.
|
||||||
//!
|
//!
|
||||||
//! Winit no longer uses a `EventLoop::poll_events() -> impl Iterator<Event>`-based event loop
|
//! 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
|
//! model, since that can't be implemented properly on some platforms (e.g Web, iOS) and works
|
||||||
//! most other platforms. However, this model can be re-implemented to an extent with
|
//! poorly on most other platforms. However, this model can be re-implemented to an extent with
|
||||||
#![cfg_attr(
|
#![cfg_attr(
|
||||||
any(
|
any(windows_platform, macos_platform, android_platform, x11_platform, wayland_platform),
|
||||||
windows_platform,
|
|
||||||
macos_platform,
|
|
||||||
android_platform,
|
|
||||||
x11_platform,
|
|
||||||
wayland_platform
|
|
||||||
),
|
|
||||||
doc = "[`EventLoopExtPumpEvents::pump_app_events()`][platform::pump_events::EventLoopExtPumpEvents::pump_app_events()]"
|
doc = "[`EventLoopExtPumpEvents::pump_app_events()`][platform::pump_events::EventLoopExtPumpEvents::pump_app_events()]"
|
||||||
)]
|
)]
|
||||||
#![cfg_attr(
|
#![cfg_attr(
|
||||||
not(any(
|
not(any(windows_platform, macos_platform, android_platform, x11_platform, wayland_platform)),
|
||||||
windows_platform,
|
|
||||||
macos_platform,
|
|
||||||
android_platform,
|
|
||||||
x11_platform,
|
|
||||||
wayland_platform
|
|
||||||
)),
|
|
||||||
doc = "`EventLoopExtPumpEvents::pump_app_events()`"
|
doc = "`EventLoopExtPumpEvents::pump_app_events()`"
|
||||||
)]
|
)]
|
||||||
//! [^1]. See that method's documentation for more reasons about why
|
//! [^1]. See that method's documentation for more reasons about why
|
||||||
@@ -56,19 +103,19 @@
|
|||||||
//! use winit::application::ApplicationHandler;
|
//! use winit::application::ApplicationHandler;
|
||||||
//! use winit::event::WindowEvent;
|
//! use winit::event::WindowEvent;
|
||||||
//! use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
//! use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||||
//! use winit::window::{Window, WindowId};
|
//! use winit::window::{Window, WindowId, WindowAttributes};
|
||||||
//!
|
//!
|
||||||
//! #[derive(Default)]
|
//! #[derive(Default)]
|
||||||
//! struct App {
|
//! struct App {
|
||||||
//! window: Option<Window>,
|
//! window: Option<Box<dyn Window>>,
|
||||||
//! }
|
//! }
|
||||||
//!
|
//!
|
||||||
//! impl ApplicationHandler for App {
|
//! impl ApplicationHandler for App {
|
||||||
//! fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
//! fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
//! self.window = Some(event_loop.create_window(Window::default_attributes()).unwrap());
|
//! self.window = Some(event_loop.create_window(WindowAttributes::default()).unwrap());
|
||||||
//! }
|
//! }
|
||||||
//!
|
//!
|
||||||
//! fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
|
//! fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, id: WindowId, event: WindowEvent) {
|
||||||
//! match event {
|
//! match event {
|
||||||
//! WindowEvent::CloseRequested => {
|
//! WindowEvent::CloseRequested => {
|
||||||
//! println!("The close button was pressed; stopping");
|
//! println!("The close button was pressed; stopping");
|
||||||
@@ -95,19 +142,22 @@
|
|||||||
//! }
|
//! }
|
||||||
//! }
|
//! }
|
||||||
//!
|
//!
|
||||||
//! let event_loop = EventLoop::new().unwrap();
|
//! # // 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
|
//! // ControlFlow::Poll continuously runs the event loop, even if the OS hasn't
|
||||||
//! // dispatched any events. This is ideal for games and similar applications.
|
//! // dispatched any events. This is ideal for games and similar applications.
|
||||||
//! event_loop.set_control_flow(ControlFlow::Poll);
|
//! event_loop.set_control_flow(ControlFlow::Poll);
|
||||||
//!
|
//!
|
||||||
//! // ControlFlow::Wait pauses the event loop if no events are available to process.
|
//! // 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
|
//! // 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.
|
//! // input, and uses significantly less power/CPU time than ControlFlow::Poll.
|
||||||
//! event_loop.set_control_flow(ControlFlow::Wait);
|
//! event_loop.set_control_flow(ControlFlow::Wait);
|
||||||
//!
|
//!
|
||||||
//! let mut app = App::default();
|
//! let mut app = App::default();
|
||||||
//! event_loop.run_app(&mut app);
|
//! event_loop.run_app(&mut app);
|
||||||
|
//! }
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! [`WindowEvent`] has a [`WindowId`] member. In multi-window environments, it should be
|
//! [`WindowEvent`] has a [`WindowId`] member. In multi-window environments, it should be
|
||||||
@@ -116,16 +166,55 @@
|
|||||||
//!
|
//!
|
||||||
//! # Drawing on the window
|
//! # Drawing on the window
|
||||||
//!
|
//!
|
||||||
//! Winit doesn't directly provide any methods for drawing on a [`Window`]. However, it allows you to
|
//! Winit doesn't directly provide any methods for drawing on a [`Window`]. However, it allows you
|
||||||
//! retrieve the raw handle of the window and display (see the [`platform`] module and/or the
|
//! 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
|
//! [`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.
|
//! 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
|
//! 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
|
//! 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
|
//! 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
|
//! [`visible` set to `false`][crate::window::WindowAttributes::with_visible] and explicitly make
|
||||||
//! window visible only once you're ready to render into it.
|
//! the window visible only once you're ready to render into it.
|
||||||
|
//!
|
||||||
|
//! There is another important concept you need to know about when drawing: the "safe area". This
|
||||||
|
//! can be accessed with [`Window::safe_area`], and describes a rectangle in the surface that is not
|
||||||
|
//! obscured by notches, the status bar, and so on. You should be drawing your background and
|
||||||
|
//! non-important content on the entire surface, but restrict important content (such as
|
||||||
|
//! interactable UIs, text, etc.) to only being drawn inside the safe area.
|
||||||
|
//!
|
||||||
|
//! [`Window::safe_area`]: crate::window::Window::safe_area
|
||||||
|
//!
|
||||||
|
//! # Coordinate systems
|
||||||
|
//!
|
||||||
|
//! Windowing systems use many different coordinate systems, and this is reflected in Winit as well;
|
||||||
|
//! there are "desktop coordinates", which is the coordinates of a window or monitor relative to the
|
||||||
|
//! desktop at large, "window coordinates" which is the coordinates of the surface, relative to the
|
||||||
|
//! window, and finally "surface coordinates", which is the coordinates relative to the drawn
|
||||||
|
//! surface. All of these coordinates are relative to the top-left corner of their respective
|
||||||
|
//! origin.
|
||||||
|
//!
|
||||||
|
//! Most of the functionality in Winit works with surface coordinates, so usually you only need to
|
||||||
|
//! concern yourself with those. In case you need to convert to some other coordinate system, Winit
|
||||||
|
//! provides [`Window::surface_position`] and [`Window::surface_size`] to describe the surface's
|
||||||
|
//! location in window coordinates, and Winit provides [`Window::outer_position`] and
|
||||||
|
//! [`Window::outer_size`] to describe the window's location in desktop coordinates. Using these
|
||||||
|
//! methods, you should be able to convert a position in one coordinate system to another.
|
||||||
|
//!
|
||||||
|
//! An overview of how these four methods fit together can be seen in the image below:
|
||||||
|
#![doc = concat!("\n\n", include_str!("../docs/res/coordinate-systems-desktop.svg"), "\n\n")] // Rustfmt removes \n, adding them like this works around that.
|
||||||
|
//! On mobile, the situation is usually a bit different; because of the smaller screen space,
|
||||||
|
//! windows usually fill the whole screen at a time, and as such there is _rarely_ a difference
|
||||||
|
//! between these three coordinate systems, although you should still strive to handle this, as
|
||||||
|
//! they're still relevant in more niche area such as Mac Catalyst, or multi-tasking on tablets.
|
||||||
|
//!
|
||||||
|
//! This is illustrated in the image below, along with the safe area since it's often relevant on
|
||||||
|
//! mobile.
|
||||||
|
#![doc = concat!("\n\n", include_str!("../docs/res/coordinate-systems-mobile.svg"), "\n\n")] // Rustfmt removes \n, adding them like this works around that.
|
||||||
|
//! [`Window::surface_position`]: crate::window::Window::surface_position
|
||||||
|
//! [`Window::surface_size`]: crate::window::Window::surface_size
|
||||||
|
//! [`Window::outer_position`]: crate::window::Window::outer_position
|
||||||
|
//! [`Window::outer_size`]: crate::window::Window::outer_size
|
||||||
//!
|
//!
|
||||||
//! # UI scaling
|
//! # UI scaling
|
||||||
//!
|
//!
|
||||||
@@ -151,18 +240,70 @@
|
|||||||
//! Winit provides the following Cargo features:
|
//! Winit provides the following Cargo features:
|
||||||
//!
|
//!
|
||||||
//! * `x11` (enabled by default): On Unix platforms, enables the X11 backend.
|
//! * `x11` (enabled by default): On Unix platforms, enables the X11 backend.
|
||||||
//! * `wayland` (enabled by default): On Unix platforms, enables the Wayland
|
//! * `wayland` (enabled by default): On Unix platforms, enables the Wayland backend.
|
||||||
//! 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.
|
//! * `rwh_06`: Implement `raw-window-handle v0.6` traits.
|
||||||
//! * `serde`: Enables serialization/deserialization of certain types with
|
//! * `serde`: Enables serialization/deserialization of certain types with [Serde](https://crates.io/crates/serde).
|
||||||
//! [Serde](https://crates.io/crates/serde).
|
|
||||||
//! * `mint`: Enables mint (math interoperability standard types) conversions.
|
//! * `mint`: Enables mint (math interoperability standard types) conversions.
|
||||||
//!
|
//!
|
||||||
//! See the [`platform`] module for documentation on platform-specific cargo
|
//! See the [`platform`] module for documentation on platform-specific cargo
|
||||||
//! features.
|
//! features.
|
||||||
//!
|
//!
|
||||||
|
//! # Platform/Architecture Support
|
||||||
|
//!
|
||||||
|
//! Platform support on `winit` has two tiers: Tier 1 and Tier 2.
|
||||||
|
//!
|
||||||
|
//! - Tier 1 is **guaranteed to work**. Targets in this tier are actively tested both in CI and by
|
||||||
|
//! maintainers.
|
||||||
|
//! - Tier 2 is **guaranteed to build**. Code compilation is tested in CI, but deeper testing is not
|
||||||
|
//! done.
|
||||||
|
//!
|
||||||
|
//! Please open an issue if you would like to add a Tier 2 target, or if you would
|
||||||
|
//! like a Tier 2 target moved to Tier 1.
|
||||||
|
//!
|
||||||
|
//! ## Tier 1 Targets
|
||||||
|
//!
|
||||||
|
//! |Target Name |Target Triple |APIs |
|
||||||
|
//! |-------------------------------|------------------------------------|---------------|
|
||||||
|
//! |32-Bit x86 Windows with MSVC |`i686-pc-windows-msvc` |Win32 |
|
||||||
|
//! |64-Bit x86 Windows with MSVC |`x86_64-pc-windows-msvc` |Win32 |
|
||||||
|
//! |32-Bit x86 Windows with glibc |`i686-pc-windows-gnu` |Win32 |
|
||||||
|
//! |64-Bit x86 Windows with glibc |`x86_64-pc-windows-gnu` |Win32 |
|
||||||
|
//! |32-Bit x86 Linux with glibc |`i686-unknown-linux-gnu` |X11, Wayland |
|
||||||
|
//! |64-Bit x86 Linux with glibc |`x86_64-unknown-linux-gnu` |X11, Wayland |
|
||||||
|
//! |64-Bit ARM Android |`aarch64-linux-android` |Android |
|
||||||
|
//! |64-Bit x86 Redox OS |`x86_64-unknown-redox` |Orbital |
|
||||||
|
//! |32-Bit x86 Redox OS |`i686-unknown-redox` |Orbital |
|
||||||
|
//! |64-Bit ARM Redox OS |`aarch64-unknown-redox` |Orbital |
|
||||||
|
//! |64-bit x64 macOS |`x86_64-apple-darwin` |AppKit |
|
||||||
|
//! |64-bit ARM macOS |`aarch64-apple-darwin` |AppKit |
|
||||||
|
//! |32-bit Wasm Web browser |`wasm32-unknown-unknown` |`wasm-bindgen` |
|
||||||
|
//!
|
||||||
|
//! ## Tier 2 Targets
|
||||||
|
//!
|
||||||
|
//! |Target Name |Target Triple |APIs |
|
||||||
|
//! |------------------------------------|------------------------------------|---------------|
|
||||||
|
//! |64-Bit ARM Windows with MSVC |`aarch64-pc-windows-msvc` |Win32 |
|
||||||
|
//! |32-Bit x86 Windows 7 with MSVC |`i686-win7-windows-msvc` |Win32 |
|
||||||
|
//! |64-Bit x86 Windows 7 with MSVC |`x86_64-win7-windows-msvc` |Win32 |
|
||||||
|
//! |64-bit x86 Linux with Musl |`x86_64-unknown-linux-musl` |X11, Wayland |
|
||||||
|
//! |64-bit x86 Linux with 32-bit glibc |`x86_64-unknown-linux-gnux32` |X11, Wayland |
|
||||||
|
//! |64-bit x86 Android |`x86_64-linux-android` |Android |
|
||||||
|
//! |64-bit x64 iOS |`x86_64-apple-ios` |UIKit |
|
||||||
|
//! |64-bit ARM iOS |`aarch64-apple-ios` |UIKit |
|
||||||
|
//! |64-bit ARM Mac Catalyst |`aarch64-apple-ios-macabi` |UIKit |
|
||||||
|
//! |32-bit x86 Android |`i686-linux-android` |Android |
|
||||||
|
//! |64-bit x86 FreeBSD |`x86_64-unknown-freebsd` |X11, Wayland |
|
||||||
|
//! |64-bit x86 NetBSD |`x86_64-unknown-netbsd` |X11 |
|
||||||
|
//! |32-bit x86 Linux with Musl |`i686-unknown-linux-musl` |X11, Wayland |
|
||||||
|
//! |64-bit RISC-V Linux with glibc |`riscv64gc-unknown-linux-gnu` |X11, Wayland |
|
||||||
|
//! |64-bit ARM Linux with glibc |`aarch64-unknown-linux-gnu` |X11, Wayland |
|
||||||
|
//! |64-bit ARM Linux with Musl |`aarch64-unknown-linux-musl` |X11, Wayland |
|
||||||
|
//! |64-bit PowerPC Linux with glibc |`powerpc64le-unknown-linux-gnu` |X11, Wayland |
|
||||||
|
//! |32-Bit ARM Linux with glibc |`armv5te-unknown-linux-gnueabi` |X11, Wayland |
|
||||||
|
//! |64-Bit Linux on IBM Supercomputers |`s390x-unknown-linux-gnu` |X11, Wayland |
|
||||||
|
//! |32-bit ARM Android |`arm-linux-androideabi` |Android |
|
||||||
|
//! |64-bit SPARC Linux with glibc |`sparc64-unknown-linux-gnu` |X11, Wayland |
|
||||||
|
//!
|
||||||
//! [`EventLoop`]: event_loop::EventLoop
|
//! [`EventLoop`]: event_loop::EventLoop
|
||||||
//! [`EventLoop::new()`]: event_loop::EventLoop::new
|
//! [`EventLoop::new()`]: event_loop::EventLoop::new
|
||||||
//! [`EventLoop::run_app()`]: event_loop::EventLoop::run_app
|
//! [`EventLoop::run_app()`]: event_loop::EventLoop::run_app
|
||||||
@@ -176,7 +317,7 @@
|
|||||||
//! [`WindowEvent`]: event::WindowEvent
|
//! [`WindowEvent`]: event::WindowEvent
|
||||||
//! [`DeviceEvent`]: event::DeviceEvent
|
//! [`DeviceEvent`]: event::DeviceEvent
|
||||||
//! [`Event::UserEvent`]: event::Event::UserEvent
|
//! [`Event::UserEvent`]: event::Event::UserEvent
|
||||||
//! [`Event::LoopExiting`]: event::Event::LoopExiting
|
//! [`exiting()`]: crate::application::ApplicationHandler::exiting
|
||||||
//! [`raw_window_handle`]: ./window/struct.Window.html#method.raw_window_handle
|
//! [`raw_window_handle`]: ./window/struct.Window.html#method.raw_window_handle
|
||||||
//! [`raw_display_handle`]: ./window/struct.Window.html#method.raw_display_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.
|
//! [^1]: `EventLoopExtPumpEvents::pump_app_events()` is only available on Windows, macOS, Android, X11 and Wayland.
|
||||||
@@ -186,20 +327,16 @@
|
|||||||
#![deny(clippy::all)]
|
#![deny(clippy::all)]
|
||||||
#![deny(unsafe_op_in_unsafe_fn)]
|
#![deny(unsafe_op_in_unsafe_fn)]
|
||||||
#![cfg_attr(clippy, deny(warnings))]
|
#![cfg_attr(clippy, deny(warnings))]
|
||||||
// Doc feature labels can be tested locally by running RUSTDOCFLAGS="--cfg=docsrs" cargo +nightly doc
|
// Doc feature labels can be tested locally by running RUSTDOCFLAGS="--cfg=docsrs" cargo +nightly
|
||||||
#![cfg_attr(
|
// doc
|
||||||
docsrs,
|
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide), doc(cfg_hide(doc, docsrs)))]
|
||||||
feature(doc_auto_cfg, doc_cfg_hide),
|
|
||||||
doc(cfg_hide(doc, docsrs))
|
|
||||||
)]
|
|
||||||
#![allow(clippy::missing_safety_doc)]
|
#![allow(clippy::missing_safety_doc)]
|
||||||
|
#![warn(clippy::uninlined_format_args)]
|
||||||
#[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.
|
// Re-export DPI types so that users don't have to put it in Cargo.toml.
|
||||||
#[doc(inline)]
|
#[doc(inline)]
|
||||||
pub use dpi;
|
pub use dpi;
|
||||||
|
pub use rwh_06 as raw_window_handle;
|
||||||
|
|
||||||
pub mod application;
|
pub mod application;
|
||||||
#[cfg(any(doc, doctest, test))]
|
#[cfg(any(doc, doctest, test))]
|
||||||
|
|||||||
145
src/monitor.rs
145
src/monitor.rs
@@ -1,22 +1,12 @@
|
|||||||
//! Types useful for interacting with a user's monitors.
|
//! Types useful for interacting with a user's monitors.
|
||||||
//!
|
use std::num::{NonZeroU16, NonZeroU32};
|
||||||
//! 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},
|
|
||||||
platform_impl,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Deprecated! Use `VideoModeHandle` instead.
|
use crate::dpi::{PhysicalPosition, PhysicalSize};
|
||||||
#[deprecated = "Renamed to `VideoModeHandle`"]
|
use crate::platform_impl;
|
||||||
pub type VideoMode = VideoModeHandle;
|
|
||||||
|
|
||||||
/// Describes a fullscreen video mode of a monitor.
|
/// A handle to a fullscreen video mode of a specific monitor.
|
||||||
///
|
///
|
||||||
/// Can be acquired with [`MonitorHandle::video_modes`].
|
/// This can be acquired with [`MonitorHandle::video_modes`].
|
||||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||||
pub struct VideoModeHandle {
|
pub struct VideoModeHandle {
|
||||||
pub(crate) video_mode: platform_impl::VideoModeHandle,
|
pub(crate) video_mode: platform_impl::VideoModeHandle,
|
||||||
@@ -50,7 +40,10 @@ impl Ord for VideoModeHandle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl VideoModeHandle {
|
impl VideoModeHandle {
|
||||||
/// Returns the resolution of this video mode.
|
/// Returns the resolution of this video mode. This **must not** be used to create your
|
||||||
|
/// rendering surface. Use [`Window::surface_size()`] instead.
|
||||||
|
///
|
||||||
|
/// [`Window::surface_size()`]: crate::window::Window::surface_size
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn size(&self) -> PhysicalSize<u32> {
|
pub fn size(&self) -> PhysicalSize<u32> {
|
||||||
self.video_mode.size()
|
self.video_mode.size()
|
||||||
@@ -59,19 +52,14 @@ impl VideoModeHandle {
|
|||||||
/// Returns the bit depth of this video mode, as in how many bits you have
|
/// 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
|
/// available per color. This is generally 24 bits or 32 bits on modern
|
||||||
/// systems, depending on whether the alpha channel is counted or not.
|
/// systems, depending on whether the alpha channel is counted or not.
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// - **Wayland / Orbital:** Always returns 32.
|
|
||||||
/// - **iOS:** Always returns 32.
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn bit_depth(&self) -> u16 {
|
pub fn bit_depth(&self) -> Option<NonZeroU16> {
|
||||||
self.video_mode.bit_depth()
|
self.video_mode.bit_depth()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the refresh rate of this video mode in mHz.
|
/// Returns the refresh rate of this video mode in mHz.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn refresh_rate_millihertz(&self) -> u32 {
|
pub fn refresh_rate_millihertz(&self) -> Option<NonZeroU32> {
|
||||||
self.video_mode.refresh_rate_millihertz()
|
self.video_mode.refresh_rate_millihertz()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,9 +67,7 @@ impl VideoModeHandle {
|
|||||||
/// a separate set of valid video modes.
|
/// a separate set of valid video modes.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn monitor(&self) -> MonitorHandle {
|
pub fn monitor(&self) -> MonitorHandle {
|
||||||
MonitorHandle {
|
MonitorHandle { inner: self.video_mode.monitor() }
|
||||||
inner: self.video_mode.monitor(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,59 +75,93 @@ impl std::fmt::Display for VideoModeHandle {
|
|||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
write!(
|
write!(
|
||||||
f,
|
f,
|
||||||
"{}x{} @ {} mHz ({} bpp)",
|
"{}x{} {}{}",
|
||||||
self.size().width,
|
self.size().width,
|
||||||
self.size().height,
|
self.size().height,
|
||||||
self.refresh_rate_millihertz(),
|
self.refresh_rate_millihertz().map(|rate| format!("@ {rate} mHz ")).unwrap_or_default(),
|
||||||
self.bit_depth()
|
self.bit_depth().map(|bit_depth| format!("({bit_depth} bpp)")).unwrap_or_default(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle to a monitor.
|
/// Handle to a monitor.
|
||||||
///
|
///
|
||||||
/// Allows you to retrieve information about a given monitor and can be used in [`Window`] creation.
|
/// Allows you to retrieve basic information and metadata about a monitor.
|
||||||
|
///
|
||||||
|
/// Can be used in [`Window`] creation to place the window on a specific
|
||||||
|
/// monitor.
|
||||||
|
///
|
||||||
|
/// This can be retrieved from one of the following methods, which return an
|
||||||
|
/// iterator of [`MonitorHandle`]s:
|
||||||
|
/// - [`ActiveEventLoop::available_monitors`](crate::event_loop::ActiveEventLoop::available_monitors).
|
||||||
|
/// - [`Window::available_monitors`](crate::window::Window::available_monitors).
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// **Web:** A [`MonitorHandle`] created without
|
||||||
|
#[cfg_attr(
|
||||||
|
any(web_platform, docsrs),
|
||||||
|
doc = "[detailed monitor permissions][crate::platform::web::ActiveEventLoopExtWeb::request_detailed_monitor_permission]."
|
||||||
|
)]
|
||||||
|
#[cfg_attr(not(any(web_platform, docsrs)), doc = "detailed monitor permissions.")]
|
||||||
|
/// will always represent the current monitor the browser window is in instead of a specific
|
||||||
|
/// monitor. See
|
||||||
|
#[cfg_attr(
|
||||||
|
any(web_platform, docsrs),
|
||||||
|
doc = "[`MonitorHandleExtWeb::is_detailed()`][crate::platform::web::MonitorHandleExtWeb::is_detailed]"
|
||||||
|
)]
|
||||||
|
#[cfg_attr(not(any(web_platform, docsrs)), doc = "`MonitorHandleExtWeb::is_detailed()`")]
|
||||||
|
/// to check.
|
||||||
///
|
///
|
||||||
/// [`Window`]: crate::window::Window
|
/// [`Window`]: crate::window::Window
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||||
pub struct MonitorHandle {
|
pub struct MonitorHandle {
|
||||||
pub(crate) inner: platform_impl::MonitorHandle,
|
pub(crate) inner: platform_impl::MonitorHandle,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for MonitorHandle {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
self.inner.fmt(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl MonitorHandle {
|
impl MonitorHandle {
|
||||||
/// Returns a human-readable name of the monitor.
|
/// Returns a human-readable name of the monitor.
|
||||||
///
|
///
|
||||||
/// Returns `None` if the monitor doesn't exist anymore.
|
/// Returns `None` if the monitor doesn't exist anymore.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// **Web:** Always returns [`None`] without
|
||||||
|
#[cfg_attr(
|
||||||
|
any(web_platform, docsrs),
|
||||||
|
doc = "[detailed monitor permissions][crate::platform::web::ActiveEventLoopExtWeb::request_detailed_monitor_permission]."
|
||||||
|
)]
|
||||||
|
#[cfg_attr(not(any(web_platform, docsrs)), doc = "detailed monitor permissions.")]
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn name(&self) -> Option<String> {
|
pub fn name(&self) -> Option<String> {
|
||||||
self.inner.name()
|
self.inner.name()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the monitor's resolution.
|
/// Returns the top-left corner position of the monitor in desktop coordinates.
|
||||||
|
///
|
||||||
|
/// This position is in the same coordinate system as [`Window::outer_position`].
|
||||||
|
///
|
||||||
|
/// [`Window::outer_position`]: crate::window::Window::outer_position
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// **Web:** Always returns [`None`] without
|
||||||
|
#[cfg_attr(
|
||||||
|
any(web_platform, docsrs),
|
||||||
|
doc = "[detailed monitor permissions][crate::platform::web::ActiveEventLoopExtWeb::request_detailed_monitor_permission]."
|
||||||
|
)]
|
||||||
|
#[cfg_attr(not(any(web_platform, docsrs)), doc = "detailed monitor permissions.")]
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn size(&self) -> PhysicalSize<u32> {
|
pub fn position(&self) -> Option<PhysicalPosition<i32>> {
|
||||||
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()
|
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
|
/// Returns the scale factor of the underlying monitor. To map logical pixels to physical
|
||||||
/// pixels and vice versa, use [`Window::scale_factor`].
|
/// pixels and vice versa, use [`Window::scale_factor`].
|
||||||
///
|
///
|
||||||
@@ -152,22 +172,29 @@ impl MonitorHandle {
|
|||||||
/// - **X11:** Can be overridden using the `WINIT_X11_SCALE_FACTOR` environment variable.
|
/// - **X11:** Can be overridden using the `WINIT_X11_SCALE_FACTOR` environment variable.
|
||||||
/// - **Wayland:** May differ from [`Window::scale_factor`].
|
/// - **Wayland:** May differ from [`Window::scale_factor`].
|
||||||
/// - **Android:** Always returns 1.0.
|
/// - **Android:** Always returns 1.0.
|
||||||
|
/// - **Web:** Always returns `0.0` without
|
||||||
|
#[cfg_attr(
|
||||||
|
any(web_platform, docsrs),
|
||||||
|
doc = " [detailed monitor permissions][crate::platform::web::ActiveEventLoopExtWeb::request_detailed_monitor_permission]."
|
||||||
|
)]
|
||||||
|
#[cfg_attr(not(any(web_platform, docsrs)), doc = " detailed monitor permissions.")]
|
||||||
///
|
///
|
||||||
|
#[rustfmt::skip]
|
||||||
/// [`Window::scale_factor`]: crate::window::Window::scale_factor
|
/// [`Window::scale_factor`]: crate::window::Window::scale_factor
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn scale_factor(&self) -> f64 {
|
pub fn scale_factor(&self) -> f64 {
|
||||||
self.inner.scale_factor()
|
self.inner.scale_factor()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the currently active video mode of this monitor.
|
||||||
|
#[inline]
|
||||||
|
pub fn current_video_mode(&self) -> Option<VideoModeHandle> {
|
||||||
|
self.inner.current_video_mode().map(|video_mode| VideoModeHandle { video_mode })
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns all fullscreen video modes supported by this monitor.
|
/// Returns all fullscreen video modes supported by this monitor.
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// - **Web:** Always returns an empty iterator
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> {
|
pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> {
|
||||||
self.inner
|
self.inner.video_modes().map(|video_mode| VideoModeHandle { video_mode })
|
||||||
.video_modes()
|
|
||||||
.map(|video_mode| VideoModeHandle { video_mode })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,7 @@
|
|||||||
//!
|
//!
|
||||||
//! | winit | ndk-glue |
|
//! | winit | ndk-glue |
|
||||||
//! | :---: | :--------------------------: |
|
//! | :---: | :--------------------------: |
|
||||||
|
//! | 0.30 | `android-activity = "0.6"` |
|
||||||
//! | 0.29 | `android-activity = "0.5"` |
|
//! | 0.29 | `android-activity = "0.5"` |
|
||||||
//! | 0.28 | `android-activity = "0.4"` |
|
//! | 0.28 | `android-activity = "0.4"` |
|
||||||
//! | 0.27 | `ndk-glue = "0.7"` |
|
//! | 0.27 | `ndk-glue = "0.7"` |
|
||||||
@@ -58,26 +59,38 @@
|
|||||||
//!
|
//!
|
||||||
//! ## Converting from `ndk-glue` to `android-activity`
|
//! ## Converting from `ndk-glue` to `android-activity`
|
||||||
//!
|
//!
|
||||||
//! If your application is currently based on `NativeActivity` via the `ndk-glue` crate and building with `cargo apk`, then the minimal changes would be:
|
//! 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`
|
//! 1. Remove `ndk-glue` from your `Cargo.toml`
|
||||||
//! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.29.15", features = [ "android-native-activity" ] }`
|
//! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.30.5",
|
||||||
//! 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).
|
//! features = [ "android-native-activity" ] }`
|
||||||
//! 4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your event loop (as shown above).
|
//! 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
|
||||||
use crate::{
|
//! logging as above).
|
||||||
event_loop::{ActiveEventLoop, EventLoop, EventLoopBuilder},
|
//! 4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your
|
||||||
window::{Window, WindowAttributes},
|
//! event loop (as shown above).
|
||||||
};
|
|
||||||
|
|
||||||
use self::activity::{AndroidApp, ConfigurationRef, Rect};
|
use self::activity::{AndroidApp, ConfigurationRef, Rect};
|
||||||
|
use crate::event_loop::{ActiveEventLoop, EventLoop, EventLoopBuilder};
|
||||||
|
use crate::window::{Window, WindowAttributes};
|
||||||
|
|
||||||
/// Additional methods on [`EventLoop`] that are specific to Android.
|
/// Additional methods on [`EventLoop`] that are specific to Android.
|
||||||
pub trait EventLoopExtAndroid {}
|
pub trait EventLoopExtAndroid {
|
||||||
|
/// Get the [`AndroidApp`] which was used to create this event loop.
|
||||||
|
fn android_app(&self) -> &AndroidApp;
|
||||||
|
}
|
||||||
|
|
||||||
impl<T> EventLoopExtAndroid for EventLoop<T> {}
|
impl EventLoopExtAndroid for EventLoop {
|
||||||
|
fn android_app(&self) -> &AndroidApp {
|
||||||
|
&self.event_loop.android_app
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Additional methods on [`ActiveEventLoop`] that are specific to Android.
|
/// Additional methods on [`ActiveEventLoop`] that are specific to Android.
|
||||||
pub trait ActiveEventLoopExtAndroid {}
|
pub trait ActiveEventLoopExtAndroid {
|
||||||
|
/// Get the [`AndroidApp`] which was used to create this event loop.
|
||||||
|
fn android_app(&self) -> &AndroidApp;
|
||||||
|
}
|
||||||
|
|
||||||
/// Additional methods on [`Window`] that are specific to Android.
|
/// Additional methods on [`Window`] that are specific to Android.
|
||||||
pub trait WindowExtAndroid {
|
pub trait WindowExtAndroid {
|
||||||
@@ -86,17 +99,25 @@ pub trait WindowExtAndroid {
|
|||||||
fn config(&self) -> ConfigurationRef;
|
fn config(&self) -> ConfigurationRef;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowExtAndroid for Window {
|
impl WindowExtAndroid for dyn Window + '_ {
|
||||||
fn content_rect(&self) -> Rect {
|
fn content_rect(&self) -> Rect {
|
||||||
self.window.content_rect()
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.content_rect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn config(&self) -> ConfigurationRef {
|
fn config(&self) -> ConfigurationRef {
|
||||||
self.window.config()
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.config()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ActiveEventLoopExtAndroid for ActiveEventLoop {}
|
impl ActiveEventLoopExtAndroid for dyn ActiveEventLoop + '_ {
|
||||||
|
fn android_app(&self) -> &AndroidApp {
|
||||||
|
let event_loop =
|
||||||
|
self.as_any().downcast_ref::<crate::platform_impl::ActiveEventLoop>().unwrap();
|
||||||
|
&event_loop.app
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Additional methods on [`WindowAttributes`] that are specific to Android.
|
/// Additional methods on [`WindowAttributes`] that are specific to Android.
|
||||||
pub trait WindowAttributesExtAndroid {}
|
pub trait WindowAttributesExtAndroid {}
|
||||||
@@ -104,9 +125,9 @@ pub trait WindowAttributesExtAndroid {}
|
|||||||
impl WindowAttributesExtAndroid for WindowAttributes {}
|
impl WindowAttributesExtAndroid for WindowAttributes {}
|
||||||
|
|
||||||
pub trait EventLoopBuilderExtAndroid {
|
pub trait EventLoopBuilderExtAndroid {
|
||||||
/// Associates the `AndroidApp` that was passed to `android_main()` with the event loop
|
/// Associates the [`AndroidApp`] that was passed to `android_main()` with the event loop
|
||||||
///
|
///
|
||||||
/// This must be called on Android since the `AndroidApp` is not global state.
|
/// This must be called on Android since the [`AndroidApp`] is not global state.
|
||||||
fn with_android_app(&mut self, app: AndroidApp) -> &mut Self;
|
fn with_android_app(&mut self, app: AndroidApp) -> &mut Self;
|
||||||
|
|
||||||
/// Calling this will mark the volume keys to be manually handled by the application
|
/// Calling this will mark the volume keys to be manually handled by the application
|
||||||
@@ -115,7 +136,7 @@ pub trait EventLoopBuilderExtAndroid {
|
|||||||
fn handle_volume_keys(&mut self) -> &mut Self;
|
fn handle_volume_keys(&mut self) -> &mut Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoopBuilderExtAndroid for EventLoopBuilder<T> {
|
impl EventLoopBuilderExtAndroid for EventLoopBuilder {
|
||||||
fn with_android_app(&mut self, app: AndroidApp) -> &mut Self {
|
fn with_android_app(&mut self, app: AndroidApp) -> &mut Self {
|
||||||
self.platform_specific.android_app = Some(app);
|
self.platform_specific.android_app = Some(app);
|
||||||
self
|
self
|
||||||
@@ -143,10 +164,10 @@ impl<T> EventLoopBuilderExtAndroid for EventLoopBuilder<T> {
|
|||||||
/// depending on the `android_activity` crate, and instead consume the API that
|
/// depending on the `android_activity` crate, and instead consume the API that
|
||||||
/// is re-exported by Winit.
|
/// is re-exported by Winit.
|
||||||
///
|
///
|
||||||
/// For compatibility applications should then import the `AndroidApp` type for
|
/// For compatibility applications should then import the [`AndroidApp`] type for
|
||||||
/// their `android_main(app: AndroidApp)` function like:
|
/// their `android_main(app: AndroidApp)` function like:
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// #[cfg(target_os="android")]
|
/// #[cfg(target_os = "android")]
|
||||||
/// use winit::platform::android::activity::AndroidApp;
|
/// use winit::platform::android::activity::AndroidApp;
|
||||||
/// ```
|
/// ```
|
||||||
pub mod activity {
|
pub mod activity {
|
||||||
|
|||||||
@@ -1,51 +1,79 @@
|
|||||||
//! # iOS / UIKit
|
//! # iOS / UIKit
|
||||||
//!
|
//!
|
||||||
//! Winit has an OS requirement of iOS 8 or higher, and is regularly tested on
|
//! Winit has [the same iOS version requirements as `rustc`][rustc-ios-version], although it's
|
||||||
//! iOS 9.3.
|
//! frequently only tested on newer iOS versions.
|
||||||
//!
|
//!
|
||||||
//! iOS's main `UIApplicationMain` does some init work that's required by all
|
//! [rustc-ios-version]: https://doc.rust-lang.org/rustc/platform-support/apple-ios.html#os-version
|
||||||
//! UI-related code (see issue [#1705]). It is best to create your windows
|
|
||||||
//! inside `Event::Resumed`.
|
|
||||||
//!
|
//!
|
||||||
//! [#1705]: https://github.com/rust-windowing/winit/issues/1705
|
//! ## Running on Mac Catalyst
|
||||||
//!
|
//!
|
||||||
//! ## Building app
|
//! Mac Catalyst allows running applications using UIKit on macOS, which can be very useful for
|
||||||
|
//! testing. See [`rustc`'s documentation on Mac Catalyst][rustc-mac-catalyst] for details on how to
|
||||||
|
//! use these targets. To use these with Winit, you'll need to bundle your application before
|
||||||
|
//! running it, otherwise UIKit will exit with an error.
|
||||||
//!
|
//!
|
||||||
//! To build ios app you will need rustc built for this targets:
|
//! To run e.g. the `window` example in the Winit repository, you can use [`cargo-bundle`] as
|
||||||
|
//! follows:
|
||||||
//!
|
//!
|
||||||
//! - armv7-apple-ios
|
//! ```console
|
||||||
//! - armv7s-apple-ios
|
//! $ cargo +nightly bundle --format=ios --target=aarch64-apple-ios-macabi --example=window
|
||||||
//! - i386-apple-ios
|
//! $ ./target/aarch64-apple-ios-macabi/debug/examples/bundle/ios/winit.app/window
|
||||||
//! - aarch64-apple-ios
|
|
||||||
//! - x86_64-apple-ios
|
|
||||||
//!
|
|
||||||
//! Then
|
|
||||||
//!
|
|
||||||
//! ```
|
|
||||||
//! cargo build --target=...
|
|
||||||
//! ```
|
|
||||||
//! The simplest way to integrate your app into xcode environment is to build it
|
|
||||||
//! as a static library. Wrap your main function and export it.
|
|
||||||
//!
|
|
||||||
//! ```rust, ignore
|
|
||||||
//! #[no_mangle]
|
|
||||||
//! pub extern fn start_winit_app() {
|
|
||||||
//! start_inner()
|
|
||||||
//! }
|
|
||||||
//!
|
|
||||||
//! fn start_inner() {
|
|
||||||
//! ...
|
|
||||||
//! }
|
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! Compile project and then drag resulting .a into Xcode project. Add winit.h to xcode.
|
//! [rustc-mac-catalyst]: https://doc.rust-lang.org/rustc/platform-support/apple-ios-macabi.html
|
||||||
|
//! [`cargo-bundle`]: https://github.com/burtonageo/cargo-bundle
|
||||||
//!
|
//!
|
||||||
//! ```ignore
|
//! ## Introduction to building an app
|
||||||
//! void start_winit_app();
|
//!
|
||||||
|
//! Building and running your application in the iOS simulator, or on a real device, is a bit more
|
||||||
|
//! complicated than Mac Catalyst - fundamentally, you must use Xcode, since the binary needs to be
|
||||||
|
//! bundled, signed, notarized and uploaded to the device (there is [an open source work-in-progress
|
||||||
|
//! on re-implementing parts of this][apple-platform-rs], but the user-story around it is not yet
|
||||||
|
//! clear).
|
||||||
|
//!
|
||||||
|
//! This means that you're left with effectively two options: Use a tool that manages the Xcode
|
||||||
|
//! configuration for you, or use Xcode directly. [`cargo-dinghy`] and [`cargo-mobile2`] are notable
|
||||||
|
//! projects in the ecosystem that attempt the former, and [`cargo-xcode`] is an excellent project
|
||||||
|
//! that attempts the latter. We will also attempt to describe here how you would go about using
|
||||||
|
//! Xcode directly:
|
||||||
|
//!
|
||||||
|
//! First off, you'll need the correct Rust targets, see [`rustc`'s documentation on iOS][rustc-ios]
|
||||||
|
//! for details. Nowadays, the correct targets are usually `aarch64-apple-ios-sim` for the
|
||||||
|
//! simulator, and `aarch64-apple-ios` for the actual device.
|
||||||
|
//!
|
||||||
|
//! Next, create a new Xcode project using the "App" template. The exact configuration does not
|
||||||
|
//! really matter, as we're going to delete most of it, since it's tailored for Objective-C and/or
|
||||||
|
//! Swift, and Rust/Winit is neither. Specifically, we need to delete:
|
||||||
|
//! - Everything relating to storyboards (unless you want to use e.g. a launch screen). This
|
||||||
|
//! includes the relevant keys in `Info.plist`.
|
||||||
|
//! - All the generated C header, Objective-C and/or Swift files.
|
||||||
|
//!
|
||||||
|
//! Now that we have a fairly clean slate that we can build upon, you can add a "run script" build
|
||||||
|
//! phase to your Xcode target, which will get invoked instead of the "compile sources" and "link
|
||||||
|
//! binary" steps. The basic script should look something like:
|
||||||
|
//!
|
||||||
|
//! ```sh
|
||||||
|
//! # Build desired targets based on `ARCHS` environment variable
|
||||||
|
//! cargo build --target=aarch64-apple-ios --target=armv7s-apple-ios
|
||||||
|
//! # Merge these with `lipo`, and place the result in "$TARGET_BUILD_DIR/$EXECUTABLE_PATH", which
|
||||||
|
//! # is understood by Xcode
|
||||||
|
//! lipo "$TARGET_BUILD_DIR/$EXECUTABLE_PATH" target/aarch64-apple-ios/debug/my_app target/armv7s-apple-ios/debug/my_app
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! Use start_winit_app inside your xcode's main function.
|
//! Note that this is very much the overall idea; the script needs to be much more involved to
|
||||||
|
//! properly deal with different target architectures, invoking `lipo` when needed, incremental
|
||||||
|
//! rebuild change detection, and so on. `cargo-xcode` has a script [here][cargo-xcode-script] that
|
||||||
|
//! handles most of this complexity, you might be able to build upon that.
|
||||||
//!
|
//!
|
||||||
|
//! Apologies that we're not able to provide you with more than this; work is in-progress on
|
||||||
|
//! improving the situation, but it's slow-going.
|
||||||
|
//!
|
||||||
|
//! [apple-platform-rs]: https://github.com/indygreg/apple-platform-rs
|
||||||
|
//! [`cargo-dinghy`]: https://github.com/sonos/dinghy
|
||||||
|
//! [`cargo-mobile2`]: https://github.com/tauri-apps/cargo-mobile2
|
||||||
|
//! [`cargo-xcode`]: https://crates.io/crates/cargo-xcode
|
||||||
|
//! [rustc-ios]: https://doc.rust-lang.org/rustc/platform-support/apple-ios.html
|
||||||
|
//! [cargo-xcode-script]: https://gitlab.com/kornelski/cargo-xcode/-/blob/main/src/xcodebuild.sh
|
||||||
//!
|
//!
|
||||||
//! ## App lifecycle and events
|
//! ## App lifecycle and events
|
||||||
//!
|
//!
|
||||||
@@ -63,26 +91,24 @@
|
|||||||
//! opengl will result in segfault.
|
//! opengl will result in segfault.
|
||||||
//!
|
//!
|
||||||
//! Also note that app may not receive the LoopExiting event if suspended; it might be SIGKILL'ed.
|
//! Also note that app may not receive the LoopExiting event if suspended; it might be SIGKILL'ed.
|
||||||
|
//!
|
||||||
|
//! ## Custom `UIApplicationDelegate`
|
||||||
|
//!
|
||||||
|
//! Winit usually handles everything related to the lifecycle events of the application. Sometimes,
|
||||||
|
//! though, you might want to access some of the more niche stuff that [the application
|
||||||
|
//! delegate][app-delegate] provides. This functionality is not exposed directly in Winit, since it
|
||||||
|
//! would increase the API surface by quite a lot. Instead, Winit guarantees that it will not
|
||||||
|
//! register an application delegate, so you can set up a custom one in a nib file instead.
|
||||||
|
//!
|
||||||
|
//! [app-delegate]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate?language=objc
|
||||||
|
|
||||||
use std::os::raw::c_void;
|
use std::os::raw::c_void;
|
||||||
|
|
||||||
use crate::{
|
#[cfg(feature = "serde")]
|
||||||
event_loop::EventLoop,
|
use serde::{Deserialize, Serialize};
|
||||||
monitor::{MonitorHandle, VideoModeHandle},
|
|
||||||
window::{Window, WindowAttributes},
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Additional methods on [`EventLoop`] that are specific to iOS.
|
use crate::monitor::{MonitorHandle, VideoModeHandle};
|
||||||
pub trait EventLoopExtIOS {
|
use crate::window::{Window, WindowAttributes};
|
||||||
/// Returns the [`Idiom`] (phone/tablet/tv/etc) for the current device.
|
|
||||||
fn idiom(&self) -> Idiom;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: 'static> EventLoopExtIOS for EventLoop<T> {
|
|
||||||
fn idiom(&self) -> Idiom {
|
|
||||||
self.event_loop.idiom()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on [`Window`] that are specific to iOS.
|
/// Additional methods on [`Window`] that are specific to iOS.
|
||||||
pub trait WindowExtIOS {
|
pub trait WindowExtIOS {
|
||||||
@@ -157,6 +183,21 @@ pub trait WindowExtIOS {
|
|||||||
/// The default is to not recognize gestures.
|
/// The default is to not recognize gestures.
|
||||||
fn recognize_pinch_gesture(&self, should_recognize: bool);
|
fn recognize_pinch_gesture(&self, should_recognize: bool);
|
||||||
|
|
||||||
|
/// Sets whether the [`Window`] should recognize pan gestures.
|
||||||
|
///
|
||||||
|
/// The default is to not recognize gestures.
|
||||||
|
/// Installs [`UIPanGestureRecognizer`](https://developer.apple.com/documentation/uikit/uipangesturerecognizer) onto view
|
||||||
|
///
|
||||||
|
/// Set the minimum number of touches required: [`minimumNumberOfTouches`](https://developer.apple.com/documentation/uikit/uipangesturerecognizer/1621208-minimumnumberoftouches)
|
||||||
|
///
|
||||||
|
/// Set the maximum number of touches recognized: [`maximumNumberOfTouches`](https://developer.apple.com/documentation/uikit/uipangesturerecognizer/1621208-maximumnumberoftouches)
|
||||||
|
fn recognize_pan_gesture(
|
||||||
|
&self,
|
||||||
|
should_recognize: bool,
|
||||||
|
minimum_number_of_touches: u8,
|
||||||
|
maximum_number_of_touches: u8,
|
||||||
|
);
|
||||||
|
|
||||||
/// Sets whether the [`Window`] should recognize double tap gestures.
|
/// Sets whether the [`Window`] should recognize double tap gestures.
|
||||||
///
|
///
|
||||||
/// The default is to not recognize gestures.
|
/// The default is to not recognize gestures.
|
||||||
@@ -168,60 +209,78 @@ pub trait WindowExtIOS {
|
|||||||
fn recognize_rotation_gesture(&self, should_recognize: bool);
|
fn recognize_rotation_gesture(&self, should_recognize: bool);
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowExtIOS for Window {
|
impl WindowExtIOS for dyn Window + '_ {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_scale_factor(&self, scale_factor: f64) {
|
fn set_scale_factor(&self, scale_factor: f64) {
|
||||||
self.window
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
.maybe_queue_on_main(move |w| w.set_scale_factor(scale_factor))
|
window.maybe_wait_on_main(move |w| w.set_scale_factor(scale_factor));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_valid_orientations(&self, valid_orientations: ValidOrientations) {
|
fn set_valid_orientations(&self, valid_orientations: ValidOrientations) {
|
||||||
self.window
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
.maybe_queue_on_main(move |w| w.set_valid_orientations(valid_orientations))
|
window.maybe_wait_on_main(move |w| w.set_valid_orientations(valid_orientations));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_prefers_home_indicator_hidden(&self, hidden: bool) {
|
fn set_prefers_home_indicator_hidden(&self, hidden: bool) {
|
||||||
self.window
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
.maybe_queue_on_main(move |w| w.set_prefers_home_indicator_hidden(hidden))
|
window.maybe_wait_on_main(move |w| w.set_prefers_home_indicator_hidden(hidden));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge) {
|
fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge) {
|
||||||
self.window.maybe_queue_on_main(move |w| {
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.maybe_wait_on_main(move |w| {
|
||||||
w.set_preferred_screen_edges_deferring_system_gestures(edges)
|
w.set_preferred_screen_edges_deferring_system_gestures(edges)
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_prefers_status_bar_hidden(&self, hidden: bool) {
|
fn set_prefers_status_bar_hidden(&self, hidden: bool) {
|
||||||
self.window
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
.maybe_queue_on_main(move |w| w.set_prefers_status_bar_hidden(hidden))
|
window.maybe_wait_on_main(move |w| w.set_prefers_status_bar_hidden(hidden));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle) {
|
fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle) {
|
||||||
self.window
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
.maybe_queue_on_main(move |w| w.set_preferred_status_bar_style(status_bar_style))
|
window.maybe_wait_on_main(move |w| w.set_preferred_status_bar_style(status_bar_style))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn recognize_pinch_gesture(&self, should_recognize: bool) {
|
fn recognize_pinch_gesture(&self, should_recognize: bool) {
|
||||||
self.window
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
.maybe_queue_on_main(move |w| w.recognize_pinch_gesture(should_recognize));
|
window.maybe_wait_on_main(move |w| w.recognize_pinch_gesture(should_recognize));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn recognize_pan_gesture(
|
||||||
|
&self,
|
||||||
|
should_recognize: bool,
|
||||||
|
minimum_number_of_touches: u8,
|
||||||
|
maximum_number_of_touches: u8,
|
||||||
|
) {
|
||||||
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.maybe_wait_on_main(move |w| {
|
||||||
|
w.recognize_pan_gesture(
|
||||||
|
should_recognize,
|
||||||
|
minimum_number_of_touches,
|
||||||
|
maximum_number_of_touches,
|
||||||
|
)
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn recognize_doubletap_gesture(&self, should_recognize: bool) {
|
fn recognize_doubletap_gesture(&self, should_recognize: bool) {
|
||||||
self.window
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
.maybe_queue_on_main(move |w| w.recognize_doubletap_gesture(should_recognize));
|
window.maybe_wait_on_main(move |w| w.recognize_doubletap_gesture(should_recognize));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn recognize_rotation_gesture(&self, should_recognize: bool) {
|
fn recognize_rotation_gesture(&self, should_recognize: bool) {
|
||||||
self.window
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
.maybe_queue_on_main(move |w| w.recognize_rotation_gesture(should_recognize));
|
window.maybe_wait_on_main(move |w| w.recognize_rotation_gesture(should_recognize));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -301,8 +360,7 @@ impl WindowAttributesExtIOS for WindowAttributes {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_preferred_screen_edges_deferring_system_gestures(mut self, edges: ScreenEdge) -> Self {
|
fn with_preferred_screen_edges_deferring_system_gestures(mut self, edges: ScreenEdge) -> Self {
|
||||||
self.platform_specific
|
self.platform_specific.preferred_screen_edges_deferring_system_gestures = edges;
|
||||||
.preferred_screen_edges_deferring_system_gestures = edges;
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -336,20 +394,19 @@ impl MonitorHandleExtIOS for MonitorHandle {
|
|||||||
#[inline]
|
#[inline]
|
||||||
fn ui_screen(&self) -> *mut c_void {
|
fn ui_screen(&self) -> *mut c_void {
|
||||||
// SAFETY: The marker is only used to get the pointer of the screen
|
// SAFETY: The marker is only used to get the pointer of the screen
|
||||||
let mtm = unsafe { icrate::Foundation::MainThreadMarker::new_unchecked() };
|
let mtm = unsafe { objc2_foundation::MainThreadMarker::new_unchecked() };
|
||||||
objc2::rc::Id::as_ptr(self.inner.ui_screen(mtm)) as *mut c_void
|
objc2::rc::Retained::as_ptr(self.inner.ui_screen(mtm)) as *mut c_void
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn preferred_video_mode(&self) -> VideoModeHandle {
|
fn preferred_video_mode(&self) -> VideoModeHandle {
|
||||||
VideoModeHandle {
|
VideoModeHandle { video_mode: self.inner.preferred_video_mode() }
|
||||||
video_mode: self.inner.preferred_video_mode(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Valid orientations for a particular [`Window`].
|
/// Valid orientations for a particular [`Window`].
|
||||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum ValidOrientations {
|
pub enum ValidOrientations {
|
||||||
/// Excludes `PortraitUpsideDown` on iphone
|
/// Excludes `PortraitUpsideDown` on iphone
|
||||||
#[default]
|
#[default]
|
||||||
@@ -361,29 +418,12 @@ pub enum ValidOrientations {
|
|||||||
Portrait,
|
Portrait,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The device [idiom].
|
|
||||||
///
|
|
||||||
/// [idiom]: https://developer.apple.com/documentation/uikit/uidevice/1620037-userinterfaceidiom?language=objc
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
||||||
pub enum Idiom {
|
|
||||||
Unspecified,
|
|
||||||
|
|
||||||
/// iPhone and iPod touch.
|
|
||||||
Phone,
|
|
||||||
|
|
||||||
/// iPad.
|
|
||||||
Pad,
|
|
||||||
|
|
||||||
/// tvOS and Apple TV.
|
|
||||||
TV,
|
|
||||||
CarPlay,
|
|
||||||
}
|
|
||||||
|
|
||||||
bitflags::bitflags! {
|
bitflags::bitflags! {
|
||||||
/// The [edges] of a screen.
|
/// The [edges] of a screen.
|
||||||
///
|
///
|
||||||
/// [edges]: https://developer.apple.com/documentation/uikit/uirectedge?language=objc
|
/// [edges]: https://developer.apple.com/documentation/uikit/uirectedge?language=objc
|
||||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub struct ScreenEdge: u8 {
|
pub struct ScreenEdge: u8 {
|
||||||
const NONE = 0;
|
const NONE = 0;
|
||||||
const TOP = 1 << 0;
|
const TOP = 1 << 0;
|
||||||
@@ -395,7 +435,8 @@ bitflags::bitflags! {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum StatusBarStyle {
|
pub enum StatusBarStyle {
|
||||||
#[default]
|
#[default]
|
||||||
Default,
|
Default,
|
||||||
|
|||||||
@@ -1,29 +1,84 @@
|
|||||||
//! # macOS / AppKit
|
//! # macOS / AppKit
|
||||||
//!
|
//!
|
||||||
//! Winit has an OS requirement of macOS 10.11 or higher (same as Rust
|
//! Winit has [the same macOS version requirements as `rustc`][rustc-macos-version], and is tested
|
||||||
//! itself), and is regularly tested on macOS 10.14.
|
//! once in a while on as low as macOS 10.14.
|
||||||
//!
|
//!
|
||||||
//! A lot of functionality expects the application to be ready before you
|
//! [rustc-macos-version]: https://doc.rust-lang.org/rustc/platform-support/apple-darwin.html#os-version
|
||||||
//! 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
|
//! ## Custom `NSApplicationDelegate`
|
||||||
//! `Event::Resumed`.
|
|
||||||
//!
|
//!
|
||||||
//! [#2238]: https://github.com/rust-windowing/winit/issues/2238
|
//! Winit usually handles everything related to the lifecycle events of the application. Sometimes,
|
||||||
//! [#2051]: https://github.com/rust-windowing/winit/issues/2051
|
//! though, you might want to do more niche stuff, such as [handle when the user re-activates the
|
||||||
//! [#2087]: https://github.com/rust-windowing/winit/issues/2087
|
//! application][reopen]. Such functionality is not exposed directly in Winit, since it would
|
||||||
|
//! increase the API surface by quite a lot.
|
||||||
|
//!
|
||||||
|
//! [reopen]: https://developer.apple.com/documentation/appkit/nsapplicationdelegate/1428638-applicationshouldhandlereopen?language=objc
|
||||||
|
//!
|
||||||
|
//! Instead, Winit guarantees that it will not register an application delegate, so the solution is
|
||||||
|
//! to register your own application delegate, as outlined in the following example (see
|
||||||
|
//! `objc2-app-kit` for more detailed information).
|
||||||
|
#![cfg_attr(target_os = "macos", doc = "```")]
|
||||||
|
#![cfg_attr(not(target_os = "macos"), doc = "```ignore")]
|
||||||
|
//! use objc2::rc::Retained;
|
||||||
|
//! use objc2::runtime::ProtocolObject;
|
||||||
|
//! use objc2::{declare_class, msg_send_id, mutability, ClassType, DeclaredClass};
|
||||||
|
//! use objc2_app_kit::{NSApplication, NSApplicationDelegate};
|
||||||
|
//! use objc2_foundation::{NSArray, NSURL, MainThreadMarker, NSObject, NSObjectProtocol};
|
||||||
|
//! use winit::event_loop::EventLoop;
|
||||||
|
//!
|
||||||
|
//! declare_class!(
|
||||||
|
//! struct AppDelegate;
|
||||||
|
//!
|
||||||
|
//! unsafe impl ClassType for AppDelegate {
|
||||||
|
//! type Super = NSObject;
|
||||||
|
//! type Mutability = mutability::MainThreadOnly;
|
||||||
|
//! const NAME: &'static str = "MyAppDelegate";
|
||||||
|
//! }
|
||||||
|
//!
|
||||||
|
//! impl DeclaredClass for AppDelegate {}
|
||||||
|
//!
|
||||||
|
//! unsafe impl NSObjectProtocol for AppDelegate {}
|
||||||
|
//!
|
||||||
|
//! unsafe impl NSApplicationDelegate for AppDelegate {
|
||||||
|
//! #[method(application:openURLs:)]
|
||||||
|
//! fn application_openURLs(&self, application: &NSApplication, urls: &NSArray<NSURL>) {
|
||||||
|
//! // Note: To specifically get `application:openURLs:` to work, you _might_
|
||||||
|
//! // have to bundle your application. This is not done in this example.
|
||||||
|
//! println!("open urls: {application:?}, {urls:?}");
|
||||||
|
//! }
|
||||||
|
//! }
|
||||||
|
//! );
|
||||||
|
//!
|
||||||
|
//! impl AppDelegate {
|
||||||
|
//! fn new(mtm: MainThreadMarker) -> Retained<Self> {
|
||||||
|
//! unsafe { msg_send_id![super(mtm.alloc().set_ivars(())), init] }
|
||||||
|
//! }
|
||||||
|
//! }
|
||||||
|
//!
|
||||||
|
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
//! let event_loop = EventLoop::new()?;
|
||||||
|
//!
|
||||||
|
//! let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
//! let delegate = AppDelegate::new(mtm);
|
||||||
|
//! // Important: Call `sharedApplication` after `EventLoop::new`,
|
||||||
|
//! // doing it before is not yet supported.
|
||||||
|
//! let app = NSApplication::sharedApplication(mtm);
|
||||||
|
//! app.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
|
||||||
|
//!
|
||||||
|
//! // event_loop.run_app(&mut my_app);
|
||||||
|
//! Ok(())
|
||||||
|
//! }
|
||||||
|
//! ```
|
||||||
|
|
||||||
use std::os::raw::c_void;
|
use std::os::raw::c_void;
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::{
|
use crate::application::ApplicationHandler;
|
||||||
event_loop::{ActiveEventLoop, EventLoopBuilder},
|
use crate::event_loop::{ActiveEventLoop, EventLoopBuilder};
|
||||||
monitor::MonitorHandle,
|
use crate::monitor::MonitorHandle;
|
||||||
window::{Window, WindowAttributes},
|
use crate::window::{Window, WindowAttributes, WindowId};
|
||||||
};
|
|
||||||
|
|
||||||
/// Additional methods on [`Window`] that are specific to MacOS.
|
/// Additional methods on [`Window`] that are specific to MacOS.
|
||||||
pub trait WindowExtMacOS {
|
pub trait WindowExtMacOS {
|
||||||
@@ -37,6 +92,9 @@ pub trait WindowExtMacOS {
|
|||||||
/// This is how fullscreen used to work on macOS in versions before Lion.
|
/// 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
|
/// And allows the user to have a fullscreen window without using another
|
||||||
/// space or taking control over the entire monitor.
|
/// space or taking control over the entire monitor.
|
||||||
|
///
|
||||||
|
/// Make sure you only draw your important content inside the safe area so that it does not
|
||||||
|
/// overlap with the notch on newer devices, see [`Window::safe_area`] for details.
|
||||||
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool;
|
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool;
|
||||||
|
|
||||||
/// Returns whether or not the window has shadow.
|
/// Returns whether or not the window has shadow.
|
||||||
@@ -96,88 +154,134 @@ pub trait WindowExtMacOS {
|
|||||||
|
|
||||||
/// Getter for the [`WindowExtMacOS::set_option_as_alt`].
|
/// Getter for the [`WindowExtMacOS::set_option_as_alt`].
|
||||||
fn option_as_alt(&self) -> OptionAsAlt;
|
fn option_as_alt(&self) -> OptionAsAlt;
|
||||||
|
|
||||||
|
/// Disable the Menu Bar and Dock in Borderless Fullscreen mode. Useful for games.
|
||||||
|
fn set_borderless_game(&self, borderless_game: bool);
|
||||||
|
|
||||||
|
/// Getter for the [`WindowExtMacOS::set_borderless_game`].
|
||||||
|
fn is_borderless_game(&self) -> bool;
|
||||||
|
|
||||||
|
/// Makes the titlebar bigger, effectively adding more space around the
|
||||||
|
/// window controls if the titlebar is invisible.
|
||||||
|
fn set_unified_titlebar(&self, unified_titlebar: bool);
|
||||||
|
|
||||||
|
/// Getter for the [`WindowExtMacOS::set_unified_titlebar`].
|
||||||
|
fn unified_titlebar(&self) -> bool;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowExtMacOS for Window {
|
impl WindowExtMacOS for dyn Window + '_ {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn simple_fullscreen(&self) -> bool {
|
fn simple_fullscreen(&self) -> bool {
|
||||||
self.window.maybe_wait_on_main(|w| w.simple_fullscreen())
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.simple_fullscreen())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool {
|
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool {
|
||||||
self.window
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
.maybe_wait_on_main(move |w| w.set_simple_fullscreen(fullscreen))
|
window.maybe_wait_on_main(move |w| w.set_simple_fullscreen(fullscreen))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn has_shadow(&self) -> bool {
|
fn has_shadow(&self) -> bool {
|
||||||
self.window.maybe_wait_on_main(|w| w.has_shadow())
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.has_shadow())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_has_shadow(&self, has_shadow: bool) {
|
fn set_has_shadow(&self, has_shadow: bool) {
|
||||||
self.window
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
.maybe_queue_on_main(move |w| w.set_has_shadow(has_shadow))
|
window.maybe_wait_on_main(move |w| w.set_has_shadow(has_shadow));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_tabbing_identifier(&self, identifier: &str) {
|
fn set_tabbing_identifier(&self, identifier: &str) {
|
||||||
self.window
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
.maybe_wait_on_main(|w| w.set_tabbing_identifier(identifier))
|
window.maybe_wait_on_main(|w| w.set_tabbing_identifier(identifier))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn tabbing_identifier(&self) -> String {
|
fn tabbing_identifier(&self) -> String {
|
||||||
self.window.maybe_wait_on_main(|w| w.tabbing_identifier())
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.tabbing_identifier())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn select_next_tab(&self) {
|
fn select_next_tab(&self) {
|
||||||
self.window.maybe_queue_on_main(|w| w.select_next_tab())
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.select_next_tab());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn select_previous_tab(&self) {
|
fn select_previous_tab(&self) {
|
||||||
self.window.maybe_queue_on_main(|w| w.select_previous_tab())
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.select_previous_tab());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn select_tab_at_index(&self, index: usize) {
|
fn select_tab_at_index(&self, index: usize) {
|
||||||
self.window
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
.maybe_queue_on_main(move |w| w.select_tab_at_index(index))
|
window.maybe_wait_on_main(move |w| w.select_tab_at_index(index));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn num_tabs(&self) -> usize {
|
fn num_tabs(&self) -> usize {
|
||||||
self.window.maybe_wait_on_main(|w| w.num_tabs())
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.num_tabs())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn is_document_edited(&self) -> bool {
|
fn is_document_edited(&self) -> bool {
|
||||||
self.window.maybe_wait_on_main(|w| w.is_document_edited())
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.is_document_edited())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_document_edited(&self, edited: bool) {
|
fn set_document_edited(&self, edited: bool) {
|
||||||
self.window
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
.maybe_queue_on_main(move |w| w.set_document_edited(edited))
|
window.maybe_wait_on_main(move |w| w.set_document_edited(edited));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) {
|
fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) {
|
||||||
self.window
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
.maybe_queue_on_main(move |w| w.set_option_as_alt(option_as_alt))
|
window.maybe_wait_on_main(move |w| w.set_option_as_alt(option_as_alt));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn option_as_alt(&self) -> OptionAsAlt {
|
fn option_as_alt(&self) -> OptionAsAlt {
|
||||||
self.window.maybe_wait_on_main(|w| w.option_as_alt())
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.option_as_alt())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_borderless_game(&self, borderless_game: bool) {
|
||||||
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.set_borderless_game(borderless_game))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn is_borderless_game(&self) -> bool {
|
||||||
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.is_borderless_game())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_unified_titlebar(&self, unified_titlebar: bool) {
|
||||||
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.set_unified_titlebar(unified_titlebar))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn unified_titlebar(&self) -> bool {
|
||||||
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.unified_titlebar())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Corresponds to `NSApplicationActivationPolicy`.
|
/// Corresponds to `NSApplicationActivationPolicy`.
|
||||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum ActivationPolicy {
|
pub enum ActivationPolicy {
|
||||||
/// Corresponds to `NSApplicationActivationPolicyRegular`.
|
/// Corresponds to `NSApplicationActivationPolicyRegular`.
|
||||||
#[default]
|
#[default]
|
||||||
@@ -192,7 +296,8 @@ pub enum ActivationPolicy {
|
|||||||
|
|
||||||
/// Additional methods on [`WindowAttributes`] that are specific to MacOS.
|
/// Additional methods on [`WindowAttributes`] that are specific to MacOS.
|
||||||
///
|
///
|
||||||
/// **Note:** Properties dealing with the titlebar will be overwritten by the [`WindowAttributes::with_decorations`] method:
|
/// **Note:** Properties dealing with the titlebar will be overwritten by the
|
||||||
|
/// [`WindowAttributes::with_decorations`] method:
|
||||||
/// - `with_titlebar_transparent`
|
/// - `with_titlebar_transparent`
|
||||||
/// - `with_title_hidden`
|
/// - `with_title_hidden`
|
||||||
/// - `with_titlebar_hidden`
|
/// - `with_titlebar_hidden`
|
||||||
@@ -223,6 +328,10 @@ pub trait WindowAttributesExtMacOS {
|
|||||||
///
|
///
|
||||||
/// See [`WindowExtMacOS::set_option_as_alt`] for details on what this means if set.
|
/// See [`WindowExtMacOS::set_option_as_alt`] for details on what this means if set.
|
||||||
fn with_option_as_alt(self, option_as_alt: OptionAsAlt) -> Self;
|
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;
|
||||||
|
/// See [`WindowExtMacOS::set_unified_titlebar`] for details on what this means if set.
|
||||||
|
fn with_unified_titlebar(self, unified_titlebar: bool) -> Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowAttributesExtMacOS for WindowAttributes {
|
impl WindowAttributesExtMacOS for WindowAttributes {
|
||||||
@@ -282,9 +391,7 @@ impl WindowAttributesExtMacOS for WindowAttributes {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_tabbing_identifier(mut self, tabbing_identifier: &str) -> Self {
|
fn with_tabbing_identifier(mut self, tabbing_identifier: &str) -> Self {
|
||||||
self.platform_specific
|
self.platform_specific.tabbing_identifier.replace(tabbing_identifier.to_string());
|
||||||
.tabbing_identifier
|
|
||||||
.replace(tabbing_identifier.to_string());
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,23 +400,38 @@ impl WindowAttributesExtMacOS for WindowAttributes {
|
|||||||
self.platform_specific.option_as_alt = option_as_alt;
|
self.platform_specific.option_as_alt = option_as_alt;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_borderless_game(mut self, borderless_game: bool) -> Self {
|
||||||
|
self.platform_specific.borderless_game = borderless_game;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_unified_titlebar(mut self, unified_titlebar: bool) -> Self {
|
||||||
|
self.platform_specific.unified_titlebar = unified_titlebar;
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait EventLoopBuilderExtMacOS {
|
pub trait EventLoopBuilderExtMacOS {
|
||||||
/// Sets the activation policy for the application.
|
/// 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.
|
||||||
///
|
///
|
||||||
/// It is set to [`ActivationPolicy::Regular`] by default.
|
/// If unused, the Winit will honor the package manifest.
|
||||||
///
|
///
|
||||||
/// # Example
|
/// # Example
|
||||||
///
|
///
|
||||||
/// Set the activation policy to "accessory".
|
/// Set the activation policy to "accessory".
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use winit::event_loop::EventLoopBuilder;
|
/// use winit::event_loop::EventLoop;
|
||||||
/// #[cfg(target_os = "macos")]
|
/// #[cfg(target_os = "macos")]
|
||||||
/// use winit::platform::macos::{EventLoopBuilderExtMacOS, ActivationPolicy};
|
/// use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS};
|
||||||
///
|
///
|
||||||
/// let mut builder = EventLoopBuilder::new();
|
/// let mut builder = EventLoop::builder();
|
||||||
/// #[cfg(target_os = "macos")]
|
/// #[cfg(target_os = "macos")]
|
||||||
/// builder.with_activation_policy(ActivationPolicy::Accessory);
|
/// builder.with_activation_policy(ActivationPolicy::Accessory);
|
||||||
/// # if false { // We can't test this part
|
/// # if false { // We can't test this part
|
||||||
@@ -327,11 +449,11 @@ pub trait EventLoopBuilderExtMacOS {
|
|||||||
/// Disable creating a default menubar.
|
/// Disable creating a default menubar.
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use winit::event_loop::EventLoopBuilder;
|
/// use winit::event_loop::EventLoop;
|
||||||
/// #[cfg(target_os = "macos")]
|
/// #[cfg(target_os = "macos")]
|
||||||
/// use winit::platform::macos::EventLoopBuilderExtMacOS;
|
/// use winit::platform::macos::EventLoopBuilderExtMacOS;
|
||||||
///
|
///
|
||||||
/// let mut builder = EventLoopBuilder::new();
|
/// let mut builder = EventLoop::builder();
|
||||||
/// #[cfg(target_os = "macos")]
|
/// #[cfg(target_os = "macos")]
|
||||||
/// builder.with_default_menu(false);
|
/// builder.with_default_menu(false);
|
||||||
/// # if false { // We can't test this part
|
/// # if false { // We can't test this part
|
||||||
@@ -347,10 +469,10 @@ pub trait EventLoopBuilderExtMacOS {
|
|||||||
fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self;
|
fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoopBuilderExtMacOS for EventLoopBuilder<T> {
|
impl EventLoopBuilderExtMacOS for EventLoopBuilder {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_activation_policy(&mut self, activation_policy: ActivationPolicy) -> &mut Self {
|
fn with_activation_policy(&mut self, activation_policy: ActivationPolicy) -> &mut Self {
|
||||||
self.platform_specific.activation_policy = activation_policy;
|
self.platform_specific.activation_policy = Some(activation_policy);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -383,18 +505,18 @@ impl MonitorHandleExtMacOS for MonitorHandle {
|
|||||||
|
|
||||||
fn ns_screen(&self) -> Option<*mut c_void> {
|
fn ns_screen(&self) -> Option<*mut c_void> {
|
||||||
// SAFETY: We only use the marker to get a pointer
|
// SAFETY: We only use the marker to get a pointer
|
||||||
let mtm = unsafe { icrate::Foundation::MainThreadMarker::new_unchecked() };
|
let mtm = unsafe { objc2_foundation::MainThreadMarker::new_unchecked() };
|
||||||
self.inner
|
self.inner.ns_screen(mtm).map(|s| objc2::rc::Retained::as_ptr(&s) as _)
|
||||||
.ns_screen(mtm)
|
|
||||||
.map(|s| objc2::rc::Id::as_ptr(&s) as _)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Additional methods on [`ActiveEventLoop`] that are specific to macOS.
|
/// Additional methods on [`ActiveEventLoop`] that are specific to macOS.
|
||||||
pub trait ActiveEventLoopExtMacOS {
|
pub trait ActiveEventLoopExtMacOS {
|
||||||
/// Hide the entire application. In most applications this is typically triggered with Command-H.
|
/// Hide the entire application. In most applications this is typically triggered with
|
||||||
|
/// Command-H.
|
||||||
fn hide_application(&self);
|
fn hide_application(&self);
|
||||||
/// Hide the other applications. In most applications this is typically triggered with Command+Option-H.
|
/// Hide the other applications. In most applications this is typically triggered with
|
||||||
|
/// Command+Option-H.
|
||||||
fn hide_other_applications(&self);
|
fn hide_other_applications(&self);
|
||||||
/// Set whether the system can automatically organize windows into tabs.
|
/// Set whether the system can automatically organize windows into tabs.
|
||||||
///
|
///
|
||||||
@@ -404,28 +526,44 @@ pub trait ActiveEventLoopExtMacOS {
|
|||||||
fn allows_automatic_window_tabbing(&self) -> bool;
|
fn allows_automatic_window_tabbing(&self) -> bool;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ActiveEventLoopExtMacOS for ActiveEventLoop {
|
impl ActiveEventLoopExtMacOS for dyn ActiveEventLoop + '_ {
|
||||||
fn hide_application(&self) {
|
fn hide_application(&self) {
|
||||||
self.p.hide_application()
|
let event_loop = self
|
||||||
|
.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
||||||
|
.expect("non macOS event loop on macOS");
|
||||||
|
event_loop.hide_application()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn hide_other_applications(&self) {
|
fn hide_other_applications(&self) {
|
||||||
self.p.hide_other_applications()
|
let event_loop = self
|
||||||
|
.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
||||||
|
.expect("non macOS event loop on macOS");
|
||||||
|
event_loop.hide_other_applications()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_allows_automatic_window_tabbing(&self, enabled: bool) {
|
fn set_allows_automatic_window_tabbing(&self, enabled: bool) {
|
||||||
self.p.set_allows_automatic_window_tabbing(enabled);
|
let event_loop = self
|
||||||
|
.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
||||||
|
.expect("non macOS event loop on macOS");
|
||||||
|
event_loop.set_allows_automatic_window_tabbing(enabled);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn allows_automatic_window_tabbing(&self) -> bool {
|
fn allows_automatic_window_tabbing(&self) -> bool {
|
||||||
self.p.allows_automatic_window_tabbing()
|
let event_loop = self
|
||||||
|
.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
||||||
|
.expect("non macOS event loop on macOS");
|
||||||
|
event_loop.allows_automatic_window_tabbing()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Option as alt behavior.
|
/// Option as alt behavior.
|
||||||
///
|
///
|
||||||
/// The default is `None`.
|
/// The default is `None`.
|
||||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum OptionAsAlt {
|
pub enum OptionAsAlt {
|
||||||
/// The left `Option` key is treated as `Alt`.
|
/// The left `Option` key is treated as `Alt`.
|
||||||
@@ -441,3 +579,52 @@ pub enum OptionAsAlt {
|
|||||||
#[default]
|
#[default]
|
||||||
None,
|
None,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Additional events on [`ApplicationHandler`] that are specific to macOS.
|
||||||
|
///
|
||||||
|
/// This can be registered with [`ApplicationHandler::macos_handler`].
|
||||||
|
pub trait ApplicationHandlerExtMacOS: ApplicationHandler {
|
||||||
|
/// The system interpreted a keypress as a standard key binding command.
|
||||||
|
///
|
||||||
|
/// Examples include inserting tabs and newlines, or moving the insertion point, see
|
||||||
|
/// [`NSStandardKeyBindingResponding`] for the full list of key bindings. They are often text
|
||||||
|
/// editing related.
|
||||||
|
///
|
||||||
|
/// This corresponds to the [`doCommandBySelector:`] method on `NSTextInputClient`.
|
||||||
|
///
|
||||||
|
/// The `action` parameter contains the string representation of the selector. Examples include
|
||||||
|
/// `"insertBacktab:"`, `"indent:"` and `"noop:"`.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```ignore
|
||||||
|
/// impl ApplicationHandlerExtMacOS for App {
|
||||||
|
/// fn standard_key_binding(
|
||||||
|
/// &mut self,
|
||||||
|
/// event_loop: &dyn ActiveEventLoop,
|
||||||
|
/// window_id: WindowId,
|
||||||
|
/// action: &str,
|
||||||
|
/// ) {
|
||||||
|
/// match action {
|
||||||
|
/// "moveBackward:" => self.cursor.position -= 1,
|
||||||
|
/// "moveForward:" => self.cursor.position += 1,
|
||||||
|
/// _ => {} // Ignore other actions
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// [`NSStandardKeyBindingResponding`]: https://developer.apple.com/documentation/appkit/nsstandardkeybindingresponding?language=objc
|
||||||
|
/// [`doCommandBySelector:`]: https://developer.apple.com/documentation/appkit/nstextinputclient/1438256-docommandbyselector?language=objc
|
||||||
|
#[doc(alias = "doCommandBySelector:")]
|
||||||
|
fn standard_key_binding(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
window_id: WindowId,
|
||||||
|
action: &str,
|
||||||
|
) {
|
||||||
|
let _ = event_loop;
|
||||||
|
let _ = window_id;
|
||||||
|
let _ = action;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ pub mod windows;
|
|||||||
#[cfg(any(x11_platform, docsrs))]
|
#[cfg(any(x11_platform, docsrs))]
|
||||||
pub mod x11;
|
pub mod x11;
|
||||||
|
|
||||||
|
#[allow(unused_imports)]
|
||||||
#[cfg(any(
|
#[cfg(any(
|
||||||
windows_platform,
|
windows_platform,
|
||||||
macos_platform,
|
macos_platform,
|
||||||
@@ -51,11 +52,5 @@ pub mod pump_events;
|
|||||||
))]
|
))]
|
||||||
pub mod modifier_supplement;
|
pub mod modifier_supplement;
|
||||||
|
|
||||||
#[cfg(any(
|
#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform, docsrs))]
|
||||||
windows_platform,
|
|
||||||
macos_platform,
|
|
||||||
x11_platform,
|
|
||||||
wayland_platform,
|
|
||||||
docsrs
|
|
||||||
))]
|
|
||||||
pub mod scancode;
|
pub mod scancode;
|
||||||
|
|||||||
@@ -25,10 +25,7 @@ pub trait KeyEventExtModifierSupplement {
|
|||||||
impl KeyEventExtModifierSupplement for KeyEvent {
|
impl KeyEventExtModifierSupplement for KeyEvent {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn text_with_all_modifiers(&self) -> Option<&str> {
|
fn text_with_all_modifiers(&self) -> Option<&str> {
|
||||||
self.platform_specific
|
self.platform_specific.text_with_all_modifiers.as_ref().map(|s| s.as_str())
|
||||||
.text_with_all_modifiers
|
|
||||||
.as_ref()
|
|
||||||
.map(|s| s.as_str())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
|
|||||||
@@ -1,14 +1,10 @@
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use crate::application::ApplicationHandler;
|
use crate::application::ApplicationHandler;
|
||||||
use crate::event::Event;
|
use crate::event_loop::EventLoop;
|
||||||
use crate::event_loop::{self, ActiveEventLoop, EventLoop};
|
|
||||||
|
|
||||||
/// Additional methods on [`EventLoop`] for pumping events within an external event loop
|
/// Additional methods on [`EventLoop`] for pumping events within an external event loop
|
||||||
pub trait EventLoopExtPumpEvents {
|
pub trait EventLoopExtPumpEvents {
|
||||||
/// A type provided by the user that can be passed through [`Event::UserEvent`].
|
|
||||||
type UserEvent: 'static;
|
|
||||||
|
|
||||||
/// Pump the `EventLoop` to check for and dispatch pending events.
|
/// Pump the `EventLoop` to check for and dispatch pending events.
|
||||||
///
|
///
|
||||||
/// This API is designed to enable applications to integrate Winit into an
|
/// This API is designed to enable applications to integrate Winit into an
|
||||||
@@ -52,18 +48,18 @@ pub trait EventLoopExtPumpEvents {
|
|||||||
/// - `RedrawRequested` events, used to schedule rendering.
|
/// - `RedrawRequested` events, used to schedule rendering.
|
||||||
///
|
///
|
||||||
/// macOS for example uses a `drawRect` callback to drive rendering
|
/// macOS for example uses a `drawRect` callback to drive rendering
|
||||||
/// within applications and expects rendering to be finished before
|
/// within applications and expects rendering to be finished before
|
||||||
/// the `drawRect` callback returns.
|
/// the `drawRect` callback returns.
|
||||||
///
|
///
|
||||||
/// For portability it's strongly recommended that applications should
|
/// For portability it's strongly recommended that applications should
|
||||||
/// keep their rendering inside the closure provided to Winit.
|
/// keep their rendering inside the closure provided to Winit.
|
||||||
/// - Any lifecycle events, such as `Suspended` / `Resumed`.
|
/// - Any lifecycle events, such as `Suspended` / `Resumed`.
|
||||||
///
|
///
|
||||||
/// The handling of these events needs to be synchronized with the
|
/// The handling of these events needs to be synchronized with the
|
||||||
/// operating system and it would never be appropriate to buffer a
|
/// operating system and it would never be appropriate to buffer a
|
||||||
/// notification that your application has been suspended or resumed and
|
/// notification that your application has been suspended or resumed and
|
||||||
/// then handled that later since there would always be a chance that
|
/// then handled that later since there would always be a chance that
|
||||||
/// other lifecycle events occur while the event is buffered.
|
/// other lifecycle events occur while the event is buffered.
|
||||||
///
|
///
|
||||||
/// ## Supported Platforms
|
/// ## Supported Platforms
|
||||||
///
|
///
|
||||||
@@ -74,22 +70,21 @@ pub trait EventLoopExtPumpEvents {
|
|||||||
///
|
///
|
||||||
/// ## Unsupported Platforms
|
/// ## Unsupported Platforms
|
||||||
///
|
///
|
||||||
/// - **Web:** This API is fundamentally incompatible with the event-based way in which
|
/// - **Web:** This API is fundamentally incompatible with the event-based way in which Web
|
||||||
/// Web browsers work because it's not possible to have a long-running external
|
/// browsers work because it's not possible to have a long-running external loop that would
|
||||||
/// loop that would block the browser and there is nothing that can be
|
/// block the browser and there is nothing that can be polled to ask for new new events.
|
||||||
/// polled to ask for new new events. Events are delivered via callbacks based
|
/// Events are delivered via callbacks based on an event loop that is internal to the browser
|
||||||
/// on an event loop that is internal to the browser itself.
|
/// itself.
|
||||||
/// - **iOS:** It's not possible to stop and start an `NSApplication` repeatedly on iOS so
|
/// - **iOS:** It's not possible to stop and start an `NSApplication` repeatedly on iOS so
|
||||||
/// there's no way to support the same approach to polling as on MacOS.
|
/// there's no way to support the same approach to polling as on MacOS.
|
||||||
///
|
///
|
||||||
/// ## Platform-specific
|
/// ## Platform-specific
|
||||||
///
|
///
|
||||||
/// - **Windows**: The implementation will use `PeekMessage` when checking for
|
/// - **Windows**: The implementation will use `PeekMessage` when checking for window messages
|
||||||
/// window messages to avoid blocking your external event loop.
|
/// to avoid blocking your external event loop.
|
||||||
///
|
///
|
||||||
/// - **MacOS**: The implementation works in terms of stopping the global application
|
/// - **MacOS**: The implementation works in terms of stopping the global application whenever
|
||||||
/// whenever the application `RunLoop` indicates that it is preparing to block
|
/// the application `RunLoop` indicates that it is preparing to block and wait for new events.
|
||||||
/// and wait for new events.
|
|
||||||
///
|
///
|
||||||
/// This is very different to the polling APIs that are available on other
|
/// This is very different to the polling APIs that are available on other
|
||||||
/// platforms (the lower level polling primitives on MacOS are private
|
/// platforms (the lower level polling primitives on MacOS are private
|
||||||
@@ -104,38 +99,25 @@ pub trait EventLoopExtPumpEvents {
|
|||||||
/// If you render outside of Winit you are likely to see window resizing artifacts
|
/// If you render outside of Winit you are likely to see window resizing artifacts
|
||||||
/// since MacOS expects applications to render synchronously during any `drawRect`
|
/// since MacOS expects applications to render synchronously during any `drawRect`
|
||||||
/// callback.
|
/// callback.
|
||||||
fn pump_app_events<A: ApplicationHandler<Self::UserEvent>>(
|
fn pump_app_events<A: ApplicationHandler>(
|
||||||
&mut self,
|
&mut self,
|
||||||
timeout: Option<Duration>,
|
timeout: Option<Duration>,
|
||||||
app: &mut A,
|
app: A,
|
||||||
) -> PumpStatus {
|
) -> PumpStatus;
|
||||||
#[allow(deprecated)]
|
|
||||||
self.pump_events(timeout, |event, event_loop| {
|
|
||||||
event_loop::dispatch_event_for_app(app, event_loop, event)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// See [`pump_app_events`].
|
|
||||||
///
|
|
||||||
/// [`pump_app_events`]: Self::pump_app_events
|
|
||||||
#[deprecated = "use EventLoopExtPumpEvents::pump_app_events"]
|
|
||||||
fn pump_events<F>(&mut self, timeout: Option<Duration>, event_handler: F) -> PumpStatus
|
|
||||||
where
|
|
||||||
F: FnMut(Event<Self::UserEvent>, &ActiveEventLoop);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoopExtPumpEvents for EventLoop<T> {
|
impl EventLoopExtPumpEvents for EventLoop {
|
||||||
type UserEvent = T;
|
fn pump_app_events<A: ApplicationHandler>(
|
||||||
|
&mut self,
|
||||||
fn pump_events<F>(&mut self, timeout: Option<Duration>, event_handler: F) -> PumpStatus
|
timeout: Option<Duration>,
|
||||||
where
|
app: A,
|
||||||
F: FnMut(Event<Self::UserEvent>, &ActiveEventLoop),
|
) -> PumpStatus {
|
||||||
{
|
self.event_loop.pump_app_events(timeout, app)
|
||||||
self.event_loop.pump_events(timeout, event_handler)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The return status for `pump_events`
|
/// The return status for `pump_events`
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||||
pub enum PumpStatus {
|
pub enum PumpStatus {
|
||||||
/// Continue running external loop.
|
/// Continue running external loop.
|
||||||
Continue,
|
Continue,
|
||||||
|
|||||||
@@ -1,28 +1,17 @@
|
|||||||
use crate::application::ApplicationHandler;
|
use crate::application::ApplicationHandler;
|
||||||
use crate::error::EventLoopError;
|
use crate::error::EventLoopError;
|
||||||
use crate::event::Event;
|
use crate::event_loop::EventLoop;
|
||||||
use crate::event_loop::{self, ActiveEventLoop, EventLoop};
|
|
||||||
|
|
||||||
#[cfg(doc)]
|
#[cfg(doc)]
|
||||||
use crate::{platform::pump_events::EventLoopExtPumpEvents, window::Window};
|
use crate::{
|
||||||
|
event_loop::ActiveEventLoop, platform::pump_events::EventLoopExtPumpEvents, window::Window,
|
||||||
|
};
|
||||||
|
|
||||||
/// Additional methods on [`EventLoop`] to return control flow to the caller.
|
/// Additional methods on [`EventLoop`] to return control flow to the caller.
|
||||||
pub trait EventLoopExtRunOnDemand {
|
pub trait EventLoopExtRunOnDemand {
|
||||||
/// A type provided by the user that can be passed through [`Event::UserEvent`].
|
|
||||||
type UserEvent: 'static;
|
|
||||||
|
|
||||||
/// See [`run_app_on_demand`].
|
|
||||||
///
|
|
||||||
/// [`run_app_on_demand`]: Self::run_app_on_demand
|
|
||||||
#[deprecated = "use EventLoopExtRunOnDemand::run_app_on_demand"]
|
|
||||||
fn run_on_demand<F>(&mut self, event_handler: F) -> Result<(), EventLoopError>
|
|
||||||
where
|
|
||||||
F: FnMut(Event<Self::UserEvent>, &ActiveEventLoop);
|
|
||||||
|
|
||||||
/// Run the application with the event loop on the calling thread.
|
/// Run the application with the event loop on the calling thread.
|
||||||
///
|
///
|
||||||
/// Unlike [`EventLoop::run_app`], this function accepts non-`'static` (i.e. non-`move`) closures
|
/// Unlike [`EventLoop::run_app`], this function accepts non-`'static` (i.e. non-`move`)
|
||||||
/// and it is possible to return control back to the caller without
|
/// closures and it is possible to return control back to the caller without
|
||||||
/// consuming the `EventLoop` (by using [`exit()`]) and
|
/// consuming the `EventLoop` (by using [`exit()`]) and
|
||||||
/// so the event loop can be re-run after it has exit.
|
/// so the event loop can be re-run after it has exit.
|
||||||
///
|
///
|
||||||
@@ -42,7 +31,13 @@ pub trait EventLoopExtRunOnDemand {
|
|||||||
/// # Caveats
|
/// # Caveats
|
||||||
/// - This extension isn't available on all platforms, since it's not always possible to return
|
/// - This extension isn't available on all platforms, since it's not always possible to return
|
||||||
/// to the caller (specifically this is impossible on iOS and Web - though with the Web
|
/// to the caller (specifically this is impossible on iOS and Web - though with the Web
|
||||||
/// backend it is possible to use `EventLoopExtWebSys::spawn()`[^1] more than once instead).
|
/// backend it is possible to use
|
||||||
|
#[cfg_attr(
|
||||||
|
any(web_platform, docsrs),
|
||||||
|
doc = " [`EventLoopExtWeb::spawn_app()`][crate::platform::web::EventLoopExtWeb::spawn_app()]"
|
||||||
|
)]
|
||||||
|
#[cfg_attr(not(any(web_platform, docsrs)), doc = " `EventLoopExtWeb::spawn_app()`")]
|
||||||
|
/// [^1] more than once instead).
|
||||||
/// - No [`Window`] state can be carried between separate runs of the event loop.
|
/// - No [`Window`] state can be carried between separate runs of the event loop.
|
||||||
///
|
///
|
||||||
/// You are strongly encouraged to use [`EventLoop::run_app()`] for portability, unless you
|
/// You are strongly encouraged to use [`EventLoop::run_app()`] for portability, unless you
|
||||||
@@ -55,47 +50,22 @@ pub trait EventLoopExtRunOnDemand {
|
|||||||
/// - Android
|
/// - Android
|
||||||
///
|
///
|
||||||
/// # Unsupported Platforms
|
/// # Unsupported Platforms
|
||||||
/// - **Web:** This API is fundamentally incompatible with the event-based way in which
|
/// - **Web:** This API is fundamentally incompatible with the event-based way in which Web
|
||||||
/// Web browsers work because it's not possible to have a long-running external
|
/// browsers work because it's not possible to have a long-running external loop that would
|
||||||
/// loop that would block the browser and there is nothing that can be
|
/// block the browser and there is nothing that can be polled to ask for new events. Events
|
||||||
/// polled to ask for new events. Events are delivered via callbacks based
|
/// are delivered via callbacks based on an event loop that is internal to the browser itself.
|
||||||
/// on an event loop that is internal to the browser itself.
|
|
||||||
/// - **iOS:** It's not possible to stop and start an `UIApplication` repeatedly on iOS.
|
/// - **iOS:** It's not possible to stop and start an `UIApplication` repeatedly on iOS.
|
||||||
///
|
///
|
||||||
#[cfg_attr(
|
/// [^1]: `spawn_app()` is only available on the Web platforms.
|
||||||
not(web_platform),
|
|
||||||
doc = "[^1]: `spawn()` is only available on `wasm` platforms."
|
|
||||||
)]
|
|
||||||
///
|
///
|
||||||
/// [`exit()`]: ActiveEventLoop::exit()
|
/// [`exit()`]: ActiveEventLoop::exit()
|
||||||
/// [`set_control_flow()`]: ActiveEventLoop::set_control_flow()
|
/// [`set_control_flow()`]: ActiveEventLoop::set_control_flow()
|
||||||
fn run_app_on_demand<A: ApplicationHandler<Self::UserEvent>>(
|
fn run_app_on_demand<A: ApplicationHandler>(&mut self, app: A) -> Result<(), EventLoopError>;
|
||||||
&mut self,
|
|
||||||
app: &mut A,
|
|
||||||
) -> Result<(), EventLoopError> {
|
|
||||||
#[allow(deprecated)]
|
|
||||||
self.run_on_demand(|event, event_loop| {
|
|
||||||
event_loop::dispatch_event_for_app(app, event_loop, event)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoopExtRunOnDemand for EventLoop<T> {
|
impl EventLoopExtRunOnDemand for EventLoop {
|
||||||
type UserEvent = T;
|
fn run_app_on_demand<A: ApplicationHandler>(&mut self, app: A) -> Result<(), EventLoopError> {
|
||||||
|
self.event_loop.run_app_on_demand(app)
|
||||||
fn run_on_demand<F>(&mut self, event_handler: F) -> Result<(), EventLoopError>
|
|
||||||
where
|
|
||||||
F: FnMut(Event<Self::UserEvent>, &ActiveEventLoop),
|
|
||||||
{
|
|
||||||
self.event_loop.window_target().clear_exit();
|
|
||||||
self.event_loop.run_on_demand(event_handler)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ActiveEventLoop {
|
|
||||||
/// Clear exit status.
|
|
||||||
pub(crate) fn clear_exit(&self) {
|
|
||||||
self.p.clear_exit()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ use crate::keyboard::{KeyCode, PhysicalKey};
|
|||||||
|
|
||||||
// TODO: Describe what this value contains for each platform
|
// TODO: Describe what this value contains for each platform
|
||||||
|
|
||||||
/// Additional methods for the [`PhysicalKey`] type that allow the user to access the platform-specific
|
/// Additional methods for the [`PhysicalKey`] type that allow the user to access the
|
||||||
/// scancode.
|
/// platform-specific scancode.
|
||||||
///
|
///
|
||||||
/// [`PhysicalKey`]: crate::keyboard::PhysicalKey
|
/// [`PhysicalKey`]: crate::keyboard::PhysicalKey
|
||||||
pub trait PhysicalKeyExtScancode {
|
pub trait PhysicalKeyExtScancode {
|
||||||
@@ -23,7 +23,7 @@ pub trait PhysicalKeyExtScancode {
|
|||||||
///
|
///
|
||||||
/// ## Platform-specific
|
/// ## Platform-specific
|
||||||
/// - **Wayland/X11**: A 32-bit linux scancode. When building from X11/Wayland keycode subtract
|
/// - **Wayland/X11**: A 32-bit linux scancode. When building from X11/Wayland keycode subtract
|
||||||
/// `8` to get the value you wanted.
|
/// `8` to get the value you wanted.
|
||||||
fn from_scancode(scancode: u32) -> PhysicalKey;
|
fn from_scancode(scancode: u32) -> PhysicalKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,8 +23,10 @@
|
|||||||
|
|
||||||
use std::env;
|
use std::env;
|
||||||
|
|
||||||
use crate::error::NotSupportedError;
|
use crate::error::{NotSupportedError, RequestError};
|
||||||
use crate::event_loop::{ActiveEventLoop, AsyncRequestSerial};
|
use crate::event_loop::{ActiveEventLoop, AsyncRequestSerial};
|
||||||
|
#[cfg(wayland_platform)]
|
||||||
|
use crate::platform::wayland::ActiveEventLoopExtWayland;
|
||||||
use crate::window::{ActivationToken, Window, WindowAttributes};
|
use crate::window::{ActivationToken, Window, WindowAttributes};
|
||||||
|
|
||||||
/// The variable which is used mostly on X11.
|
/// The variable which is used mostly on X11.
|
||||||
@@ -44,7 +46,7 @@ pub trait WindowExtStartupNotify {
|
|||||||
/// Request a new activation token.
|
/// Request a new activation token.
|
||||||
///
|
///
|
||||||
/// The token will be delivered inside
|
/// The token will be delivered inside
|
||||||
fn request_activation_token(&self) -> Result<AsyncRequestSerial, NotSupportedError>;
|
fn request_activation_token(&self) -> Result<AsyncRequestSerial, RequestError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait WindowAttributesExtStartupNotify {
|
pub trait WindowAttributesExtStartupNotify {
|
||||||
@@ -55,22 +57,37 @@ pub trait WindowAttributesExtStartupNotify {
|
|||||||
fn with_activation_token(self, token: ActivationToken) -> Self;
|
fn with_activation_token(self, token: ActivationToken) -> Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventLoopExtStartupNotify for ActiveEventLoop {
|
impl EventLoopExtStartupNotify for dyn ActiveEventLoop + '_ {
|
||||||
fn read_token_from_env(&self) -> Option<ActivationToken> {
|
fn read_token_from_env(&self) -> Option<ActivationToken> {
|
||||||
match self.p {
|
#[cfg(x11_platform)]
|
||||||
#[cfg(wayland_platform)]
|
let _is_wayland = false;
|
||||||
crate::platform_impl::ActiveEventLoop::Wayland(_) => env::var(WAYLAND_VAR),
|
#[cfg(wayland_platform)]
|
||||||
#[cfg(x11_platform)]
|
let _is_wayland = self.is_wayland();
|
||||||
crate::platform_impl::ActiveEventLoop::X(_) => env::var(X11_VAR),
|
|
||||||
|
if _is_wayland {
|
||||||
|
env::var(WAYLAND_VAR).ok().map(ActivationToken::_new)
|
||||||
|
} else {
|
||||||
|
env::var(X11_VAR).ok().map(ActivationToken::_new)
|
||||||
}
|
}
|
||||||
.ok()
|
|
||||||
.map(ActivationToken::_new)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowExtStartupNotify for Window {
|
impl WindowExtStartupNotify for dyn Window + '_ {
|
||||||
fn request_activation_token(&self) -> Result<AsyncRequestSerial, NotSupportedError> {
|
fn request_activation_token(&self) -> Result<AsyncRequestSerial, RequestError> {
|
||||||
self.window.request_activation_token()
|
#[cfg(wayland_platform)]
|
||||||
|
if let Some(window) = self.as_any().downcast_ref::<crate::platform_impl::wayland::Window>()
|
||||||
|
{
|
||||||
|
return window.request_activation_token();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(x11_platform)]
|
||||||
|
if let Some(window) =
|
||||||
|
self.as_any().downcast_ref::<crate::platform_impl::x11::window::Window>()
|
||||||
|
{
|
||||||
|
return window.request_activation_token();
|
||||||
|
}
|
||||||
|
|
||||||
|
Err(NotSupportedError::new("startup notify is not supported").into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,13 +13,10 @@
|
|||||||
//! * `wayland-csd-adwaita` (default).
|
//! * `wayland-csd-adwaita` (default).
|
||||||
//! * `wayland-csd-adwaita-crossfont`.
|
//! * `wayland-csd-adwaita-crossfont`.
|
||||||
//! * `wayland-csd-adwaita-notitle`.
|
//! * `wayland-csd-adwaita-notitle`.
|
||||||
use crate::{
|
use crate::event_loop::{ActiveEventLoop, EventLoop, EventLoopBuilder};
|
||||||
event_loop::{ActiveEventLoop, EventLoopBuilder},
|
use crate::monitor::MonitorHandle;
|
||||||
monitor::MonitorHandle,
|
|
||||||
window::{Window, WindowAttributes},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub use crate::window::Theme;
|
pub use crate::window::Theme;
|
||||||
|
use crate::window::{Window as CoreWindow, WindowAttributes};
|
||||||
|
|
||||||
/// Additional methods on [`ActiveEventLoop`] that are specific to Wayland.
|
/// Additional methods on [`ActiveEventLoop`] that are specific to Wayland.
|
||||||
pub trait ActiveEventLoopExtWayland {
|
pub trait ActiveEventLoopExtWayland {
|
||||||
@@ -27,10 +24,23 @@ pub trait ActiveEventLoopExtWayland {
|
|||||||
fn is_wayland(&self) -> bool;
|
fn is_wayland(&self) -> bool;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ActiveEventLoopExtWayland for ActiveEventLoop {
|
impl ActiveEventLoopExtWayland for dyn ActiveEventLoop + '_ {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn is_wayland(&self) -> bool {
|
fn is_wayland(&self) -> bool {
|
||||||
self.p.is_wayland()
|
self.as_any().downcast_ref::<crate::platform_impl::wayland::ActiveEventLoop>().is_some()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoop`] that are specific to Wayland.
|
||||||
|
pub trait EventLoopExtWayland {
|
||||||
|
/// True if the [`EventLoop`] uses Wayland.
|
||||||
|
fn is_wayland(&self) -> bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopExtWayland for EventLoop {
|
||||||
|
#[inline]
|
||||||
|
fn is_wayland(&self) -> bool {
|
||||||
|
self.event_loop.is_wayland()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,7 +56,7 @@ pub trait EventLoopBuilderExtWayland {
|
|||||||
fn with_any_thread(&mut self, any_thread: bool) -> &mut Self;
|
fn with_any_thread(&mut self, any_thread: bool) -> &mut Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoopBuilderExtWayland for EventLoopBuilder<T> {
|
impl EventLoopBuilderExtWayland for EventLoopBuilder {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_wayland(&mut self) -> &mut Self {
|
fn with_wayland(&mut self) -> &mut Self {
|
||||||
self.platform_specific.forced_backend = Some(crate::platform_impl::Backend::Wayland);
|
self.platform_specific.forced_backend = Some(crate::platform_impl::Backend::Wayland);
|
||||||
@@ -61,9 +71,11 @@ impl<T> EventLoopBuilderExtWayland for EventLoopBuilder<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Additional methods on [`Window`] that are specific to Wayland.
|
/// Additional methods on [`Window`] that are specific to Wayland.
|
||||||
|
///
|
||||||
|
/// [`Window`]: crate::window::Window
|
||||||
pub trait WindowExtWayland {}
|
pub trait WindowExtWayland {}
|
||||||
|
|
||||||
impl WindowExtWayland for Window {}
|
impl WindowExtWayland for dyn CoreWindow + '_ {}
|
||||||
|
|
||||||
/// Additional methods on [`WindowAttributes`] that are specific to Wayland.
|
/// Additional methods on [`WindowAttributes`] that are specific to Wayland.
|
||||||
pub trait WindowAttributesExtWayland {
|
pub trait WindowAttributesExtWayland {
|
||||||
@@ -80,10 +92,8 @@ pub trait WindowAttributesExtWayland {
|
|||||||
impl WindowAttributesExtWayland for WindowAttributes {
|
impl WindowAttributesExtWayland for WindowAttributes {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self {
|
fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self {
|
||||||
self.platform_specific.name = Some(crate::platform_impl::ApplicationName::new(
|
self.platform_specific.name =
|
||||||
general.into(),
|
Some(crate::platform_impl::ApplicationName::new(general.into(), instance.into()));
|
||||||
instance.into(),
|
|
||||||
));
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +1,23 @@
|
|||||||
//! # Web
|
//! # Web
|
||||||
//!
|
//!
|
||||||
//! The officially supported browsers are Chrome, Firefox and Safari 13.1+,
|
//! Winit supports running in Browsers by compiling to WebAssembly with
|
||||||
//! though forks of these should work fine.
|
//! [`wasm-bindgen`][wasm_bindgen]. For information on using Rust on WebAssembly, check out the
|
||||||
|
//! [Rust and WebAssembly book].
|
||||||
//!
|
//!
|
||||||
//! Winit supports compiling to the `wasm32-unknown-unknown` target with
|
//! The officially supported browsers are Chrome, Firefox and Safari 13.1+, though forks of these
|
||||||
//! `web-sys`.
|
//! should work fine.
|
||||||
//!
|
//!
|
||||||
//! On the web platform, a Winit window is backed by a `<canvas>` element. You
|
//! On the Web platform, a Winit [`Window`] is backed by a [`HTMLCanvasElement`][canvas]. Winit will
|
||||||
//! can either [provide Winit with a `<canvas>` element][with_canvas], or
|
//! create that canvas for you or you can [provide your own][with_canvas]. Then you can either let
|
||||||
//! [let Winit create a `<canvas>` element which you can then retrieve][get]
|
//! Winit [insert it into the DOM for you][insert], or [retrieve the canvas][get] and insert it
|
||||||
//! and insert it into the DOM yourself.
|
//! yourself.
|
||||||
//!
|
//!
|
||||||
//! Currently, there is no example code using Winit on Web, see [#3473]. For
|
//! [canvas]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement
|
||||||
//! information on using Rust on WebAssembly, check out the [Rust and
|
//! [with_canvas]: WindowAttributesExtWeb::with_canvas
|
||||||
//! WebAssembly book].
|
//! [get]: WindowExtWeb::canvas
|
||||||
//!
|
//! [insert]: WindowAttributesExtWeb::with_append
|
||||||
//! [with_canvas]: WindowAttributesExtWebSys::with_canvas
|
#![cfg_attr(not(web_platform), doc = "[wasm_bindgen]: https://docs.rs/wasm-bindgen")]
|
||||||
//! [get]: WindowExtWebSys::canvas
|
//! [Rust and WebAssembly book]: https://rustwasm.github.io/book
|
||||||
//! [#3473]: https://github.com/rust-windowing/winit/issues/3473
|
|
||||||
//! [Rust and WebAssembly book]: https://rustwasm.github.io/book/
|
|
||||||
//!
|
//!
|
||||||
//! ## CSS properties
|
//! ## CSS properties
|
||||||
//!
|
//!
|
||||||
@@ -28,21 +27,21 @@
|
|||||||
//! - [`padding`](https://developer.mozilla.org/en-US/docs/Web/CSS/padding)
|
//! - [`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:
|
//! The following APIs can't take them into account and will therefore provide inaccurate results:
|
||||||
//! - [`WindowEvent::Resized`] and [`Window::(set_)inner_size()`]
|
//! - [`WindowEvent::SurfaceResized`] and [`Window::(set_)surface_size()`]
|
||||||
//! - [`WindowEvent::Occluded`]
|
//! - [`WindowEvent::Occluded`]
|
||||||
//! - [`WindowEvent::CursorMoved`], [`WindowEvent::CursorEntered`], [`WindowEvent::CursorLeft`],
|
//! - [`WindowEvent::PointerMoved`], [`WindowEvent::PointerEntered`] and
|
||||||
//! and [`WindowEvent::Touch`].
|
//! [`WindowEvent::PointerLeft`].
|
||||||
//! - [`Window::set_outer_position()`]
|
//! - [`Window::set_outer_position()`]
|
||||||
//!
|
//!
|
||||||
//! [`WindowEvent::Resized`]: crate::event::WindowEvent::Resized
|
//! [`WindowEvent::SurfaceResized`]: crate::event::WindowEvent::SurfaceResized
|
||||||
//! [`Window::(set_)inner_size()`]: crate::window::Window::inner_size
|
//! [`Window::(set_)surface_size()`]: crate::window::Window::surface_size
|
||||||
//! [`WindowEvent::Occluded`]: crate::event::WindowEvent::Occluded
|
//! [`WindowEvent::Occluded`]: crate::event::WindowEvent::Occluded
|
||||||
//! [`WindowEvent::CursorMoved`]: crate::event::WindowEvent::CursorMoved
|
//! [`WindowEvent::PointerMoved`]: crate::event::WindowEvent::PointerMoved
|
||||||
//! [`WindowEvent::CursorEntered`]: crate::event::WindowEvent::CursorEntered
|
//! [`WindowEvent::PointerEntered`]: crate::event::WindowEvent::PointerEntered
|
||||||
//! [`WindowEvent::CursorLeft`]: crate::event::WindowEvent::CursorLeft
|
//! [`WindowEvent::PointerLeft`]: crate::event::WindowEvent::PointerLeft
|
||||||
//! [`WindowEvent::Touch`]: crate::event::WindowEvent::Touch
|
|
||||||
//! [`Window::set_outer_position()`]: crate::window::Window::set_outer_position
|
//! [`Window::set_outer_position()`]: crate::window::Window::set_outer_position
|
||||||
|
|
||||||
|
use std::cell::Ref;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt::{self, Display, Formatter};
|
use std::fmt::{self, Display, Formatter};
|
||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
@@ -50,30 +49,38 @@ use std::pin::Pin;
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
#[cfg(web_platform)]
|
#[cfg(web_platform)]
|
||||||
use web_sys::HtmlCanvasElement;
|
use web_sys::HtmlCanvasElement;
|
||||||
|
|
||||||
use crate::application::ApplicationHandler;
|
use crate::application::ApplicationHandler;
|
||||||
use crate::cursor::CustomCursorSource;
|
use crate::cursor::CustomCursorSource;
|
||||||
use crate::event::Event;
|
use crate::error::NotSupportedError;
|
||||||
use crate::event_loop::{self, ActiveEventLoop, EventLoop};
|
use crate::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
#[cfg(web_platform)]
|
use crate::monitor::MonitorHandle;
|
||||||
use crate::platform_impl::CustomCursorFuture as PlatformCustomCursorFuture;
|
|
||||||
use crate::platform_impl::PlatformCustomCursorSource;
|
use crate::platform_impl::PlatformCustomCursorSource;
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
use crate::platform_impl::{
|
||||||
|
CustomCursorFuture as PlatformCustomCursorFuture,
|
||||||
|
HasMonitorPermissionFuture as PlatformHasMonitorPermissionFuture,
|
||||||
|
MonitorPermissionFuture as PlatformMonitorPermissionFuture,
|
||||||
|
OrientationLockFuture as PlatformOrientationLockFuture,
|
||||||
|
};
|
||||||
use crate::window::{CustomCursor, Window, WindowAttributes};
|
use crate::window::{CustomCursor, Window, WindowAttributes};
|
||||||
|
|
||||||
#[cfg(not(web_platform))]
|
#[cfg(not(web_platform))]
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub struct HtmlCanvasElement;
|
pub struct HtmlCanvasElement;
|
||||||
|
|
||||||
pub trait WindowExtWebSys {
|
pub trait WindowExtWeb {
|
||||||
/// Only returns the canvas if called from inside the window context (the
|
/// Only returns the canvas if called from inside the window context (the
|
||||||
/// main thread).
|
/// main thread).
|
||||||
fn canvas(&self) -> Option<HtmlCanvasElement>;
|
fn canvas(&self) -> Option<Ref<'_, HtmlCanvasElement>>;
|
||||||
|
|
||||||
/// Returns [`true`] if calling `event.preventDefault()` is enabled.
|
/// Returns [`true`] if calling `event.preventDefault()` is enabled.
|
||||||
///
|
///
|
||||||
/// See [`Window::set_prevent_default()`] for more details.
|
/// See [`WindowExtWeb::set_prevent_default()`] for more details.
|
||||||
fn prevent_default(&self) -> bool;
|
fn prevent_default(&self) -> bool;
|
||||||
|
|
||||||
/// Sets whether `event.preventDefault()` should be called on events on the
|
/// Sets whether `event.preventDefault()` should be called on events on the
|
||||||
@@ -85,41 +92,61 @@ pub trait WindowExtWebSys {
|
|||||||
/// Some events are impossible to prevent. E.g. Firefox allows to access the native browser
|
/// Some events are impossible to prevent. E.g. Firefox allows to access the native browser
|
||||||
/// context menu with Shift+Rightclick.
|
/// context menu with Shift+Rightclick.
|
||||||
fn set_prevent_default(&self, prevent_default: bool);
|
fn set_prevent_default(&self, prevent_default: bool);
|
||||||
|
|
||||||
|
/// Returns whether using [`CursorGrabMode::Locked`] returns raw, un-accelerated mouse input.
|
||||||
|
///
|
||||||
|
/// This is the same as [`ActiveEventLoopExtWeb::is_cursor_lock_raw()`], and is provided for
|
||||||
|
/// convenience.
|
||||||
|
///
|
||||||
|
/// [`CursorGrabMode::Locked`]: crate::window::CursorGrabMode::Locked
|
||||||
|
fn is_cursor_lock_raw(&self) -> bool;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowExtWebSys for Window {
|
impl WindowExtWeb for dyn Window + '_ {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn canvas(&self) -> Option<HtmlCanvasElement> {
|
fn canvas(&self) -> Option<Ref<'_, HtmlCanvasElement>> {
|
||||||
self.window.canvas()
|
self.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::Window>()
|
||||||
|
.expect("non Web window on Web")
|
||||||
|
.canvas()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn prevent_default(&self) -> bool {
|
fn prevent_default(&self) -> bool {
|
||||||
self.window.prevent_default()
|
self.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::Window>()
|
||||||
|
.expect("non Web window on Web")
|
||||||
|
.prevent_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_prevent_default(&self, prevent_default: bool) {
|
fn set_prevent_default(&self, prevent_default: bool) {
|
||||||
self.window.set_prevent_default(prevent_default)
|
self.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::Window>()
|
||||||
|
.expect("non Web window on Web")
|
||||||
|
.set_prevent_default(prevent_default)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_cursor_lock_raw(&self) -> bool {
|
||||||
|
self.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::Window>()
|
||||||
|
.expect("non Web window on Web")
|
||||||
|
.is_cursor_lock_raw()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait WindowAttributesExtWebSys {
|
pub trait WindowAttributesExtWeb {
|
||||||
/// Pass an [`HtmlCanvasElement`] to be used for this [`Window`]. If [`None`],
|
/// Pass an [`HtmlCanvasElement`] to be used for this [`Window`]. If [`None`],
|
||||||
/// [`WindowAttributes::default()`] will create one.
|
/// [`WindowAttributes::default()`] will create one.
|
||||||
///
|
///
|
||||||
/// In any case, the canvas won't be automatically inserted into the web page.
|
/// In any case, the canvas won't be automatically inserted into the Web page.
|
||||||
///
|
///
|
||||||
/// [`None`] by default.
|
/// [`None`] by default.
|
||||||
#[cfg_attr(
|
#[cfg_attr(not(web_platform), doc = "", doc = "[`HtmlCanvasElement`]: #only-available-on-wasm")]
|
||||||
not(web_platform),
|
|
||||||
doc = "",
|
|
||||||
doc = "[`HtmlCanvasElement`]: #only-available-on-wasm"
|
|
||||||
)]
|
|
||||||
fn with_canvas(self, canvas: Option<HtmlCanvasElement>) -> Self;
|
fn with_canvas(self, canvas: Option<HtmlCanvasElement>) -> Self;
|
||||||
|
|
||||||
/// Sets whether `event.preventDefault()` should be called on events on the
|
/// Sets whether `event.preventDefault()` should be called on events on the
|
||||||
/// canvas that have side effects.
|
/// canvas that have side effects.
|
||||||
///
|
///
|
||||||
/// See [`Window::set_prevent_default()`] for more details.
|
/// See [`WindowExtWeb::set_prevent_default()`] for more details.
|
||||||
///
|
///
|
||||||
/// Enabled by default.
|
/// Enabled by default.
|
||||||
fn with_prevent_default(self, prevent_default: bool) -> Self;
|
fn with_prevent_default(self, prevent_default: bool) -> Self;
|
||||||
@@ -130,13 +157,13 @@ pub trait WindowAttributesExtWebSys {
|
|||||||
/// Enabled by default.
|
/// Enabled by default.
|
||||||
fn with_focusable(self, focusable: bool) -> Self;
|
fn with_focusable(self, focusable: bool) -> Self;
|
||||||
|
|
||||||
/// On window creation, append the canvas element to the web page if it isn't already.
|
/// On window creation, append the canvas element to the Web page if it isn't already.
|
||||||
///
|
///
|
||||||
/// Disabled by default.
|
/// Disabled by default.
|
||||||
fn with_append(self, append: bool) -> Self;
|
fn with_append(self, append: bool) -> Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowAttributesExtWebSys for WindowAttributes {
|
impl WindowAttributesExtWeb for WindowAttributes {
|
||||||
fn with_canvas(mut self, canvas: Option<HtmlCanvasElement>) -> Self {
|
fn with_canvas(mut self, canvas: Option<HtmlCanvasElement>) -> Self {
|
||||||
self.platform_specific.set_canvas(canvas);
|
self.platform_specific.set_canvas(canvas);
|
||||||
self
|
self
|
||||||
@@ -158,18 +185,12 @@ impl WindowAttributesExtWebSys for WindowAttributes {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Additional methods on `EventLoop` that are specific to the web.
|
/// Additional methods on `EventLoop` that are specific to the Web.
|
||||||
pub trait EventLoopExtWebSys {
|
pub trait EventLoopExtWeb {
|
||||||
/// A type provided by the user that can be passed through `Event::UserEvent`.
|
|
||||||
type UserEvent: 'static;
|
|
||||||
|
|
||||||
/// Initializes the winit event loop.
|
/// Initializes the winit event loop.
|
||||||
///
|
///
|
||||||
/// Unlike
|
/// Unlike
|
||||||
#[cfg_attr(
|
#[cfg_attr(all(web_platform, target_feature = "exception-handling"), doc = "`run_app()`")]
|
||||||
all(web_platform, target_feature = "exception-handling"),
|
|
||||||
doc = "`run_app()`"
|
|
||||||
)]
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
not(all(web_platform, target_feature = "exception-handling")),
|
not(all(web_platform, target_feature = "exception-handling")),
|
||||||
doc = "[`run_app()`]"
|
doc = "[`run_app()`]"
|
||||||
@@ -181,41 +202,15 @@ pub trait EventLoopExtWebSys {
|
|||||||
/// by calling this function again. This can be useful if you want to recreate the 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
|
/// 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.
|
/// event loop when switching between tabs on a single page application.
|
||||||
|
#[rustfmt::skip]
|
||||||
///
|
///
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
not(all(web_platform, target_feature = "exception-handling")),
|
not(all(web_platform, target_feature = "exception-handling")),
|
||||||
doc = "[`run_app()`]: EventLoop::run_app()"
|
doc = "[`run_app()`]: EventLoop::run_app()"
|
||||||
)]
|
)]
|
||||||
/// [^1]: `run_app()` is _not_ available on WASM when the target supports `exception-handling`.
|
/// [^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);
|
fn spawn_app<A: ApplicationHandler + '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);
|
|
||||||
}
|
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait ActiveEventLoopExtWebSys {
|
|
||||||
/// Sets the strategy for [`ControlFlow::Poll`].
|
/// Sets the strategy for [`ControlFlow::Poll`].
|
||||||
///
|
///
|
||||||
/// See [`PollStrategy`].
|
/// See [`PollStrategy`].
|
||||||
@@ -230,30 +225,224 @@ pub trait ActiveEventLoopExtWebSys {
|
|||||||
/// [`ControlFlow::Poll`]: crate::event_loop::ControlFlow::Poll
|
/// [`ControlFlow::Poll`]: crate::event_loop::ControlFlow::Poll
|
||||||
fn poll_strategy(&self) -> PollStrategy;
|
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;
|
||||||
|
|
||||||
|
/// Returns if the users device has multiple screens. Useful to check before prompting the user
|
||||||
|
/// with [`EventLoopExtWeb::request_detailed_monitor_permission()`].
|
||||||
|
///
|
||||||
|
/// Browsers might always return [`false`] to reduce fingerprinting.
|
||||||
|
fn has_multiple_screens(&self) -> Result<bool, NotSupportedError>;
|
||||||
|
|
||||||
|
/// Prompts the user for permission to query detailed information about available monitors. The
|
||||||
|
/// returned [`MonitorPermissionFuture`] can be dropped without aborting the request.
|
||||||
|
///
|
||||||
|
/// Check [`EventLoopExtWeb::has_multiple_screens()`] before unnecessarily prompting the user
|
||||||
|
/// for such permissions.
|
||||||
|
///
|
||||||
|
/// [`MonitorHandle`]s don't automatically make use of this after permission is granted. New
|
||||||
|
/// [`MonitorHandle`]s have to be created instead.
|
||||||
|
fn request_detailed_monitor_permission(&self) -> MonitorPermissionFuture;
|
||||||
|
|
||||||
|
/// Returns whether the user has given permission to access detailed monitor information.
|
||||||
|
///
|
||||||
|
/// [`MonitorHandle`]s don't automatically make use of detailed monitor information after
|
||||||
|
/// permission is granted. New [`MonitorHandle`]s have to be created instead.
|
||||||
|
fn has_detailed_monitor_permission(&self) -> HasMonitorPermissionFuture;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopExtWeb for EventLoop {
|
||||||
|
fn spawn_app<A: ApplicationHandler + 'static>(self, app: A) {
|
||||||
|
self.event_loop.spawn_app(app);
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_multiple_screens(&self) -> Result<bool, NotSupportedError> {
|
||||||
|
self.event_loop.has_multiple_screens()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_detailed_monitor_permission(&self) -> MonitorPermissionFuture {
|
||||||
|
MonitorPermissionFuture(self.event_loop.request_detailed_monitor_permission())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_detailed_monitor_permission(&self) -> HasMonitorPermissionFuture {
|
||||||
|
HasMonitorPermissionFuture(self.event_loop.has_detailed_monitor_permission())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait ActiveEventLoopExtWeb {
|
||||||
|
/// 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
|
/// Async version of [`ActiveEventLoop::create_custom_cursor()`] which waits until the
|
||||||
/// cursor has completely finished loading.
|
/// cursor has completely finished loading.
|
||||||
fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture;
|
fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture;
|
||||||
|
|
||||||
|
/// Returns whether using [`CursorGrabMode::Locked`] returns raw, un-accelerated mouse input.
|
||||||
|
///
|
||||||
|
/// [`CursorGrabMode::Locked`]: crate::window::CursorGrabMode::Locked
|
||||||
|
fn is_cursor_lock_raw(&self) -> bool;
|
||||||
|
|
||||||
|
/// Returns if the users device has multiple screens. Useful to check before prompting the user
|
||||||
|
/// with [`EventLoopExtWeb::request_detailed_monitor_permission()`].
|
||||||
|
///
|
||||||
|
/// Browsers might always return [`false`] to reduce fingerprinting.
|
||||||
|
fn has_multiple_screens(&self) -> Result<bool, NotSupportedError>;
|
||||||
|
|
||||||
|
/// Prompts the user for permission to query detailed information about available monitors. The
|
||||||
|
/// returned [`MonitorPermissionFuture`] can be dropped without aborting the request.
|
||||||
|
///
|
||||||
|
/// Check [`EventLoopExtWeb::has_multiple_screens()`] before unnecessarily prompting the user
|
||||||
|
/// for such permissions.
|
||||||
|
///
|
||||||
|
/// [`MonitorHandle`]s don't automatically make use of this after permission is granted. New
|
||||||
|
/// [`MonitorHandle`]s have to be created instead.
|
||||||
|
fn request_detailed_monitor_permission(&self) -> MonitorPermissionFuture;
|
||||||
|
|
||||||
|
/// Returns whether the user has given permission to access detailed monitor information.
|
||||||
|
///
|
||||||
|
/// [`MonitorHandle`]s don't automatically make use of detailed monitor information after
|
||||||
|
/// permission is granted. New [`MonitorHandle`]s have to be created instead.
|
||||||
|
fn has_detailed_monitor_permission(&self) -> bool;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ActiveEventLoopExtWebSys for ActiveEventLoop {
|
impl ActiveEventLoopExtWeb for dyn ActiveEventLoop + '_ {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture {
|
fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture {
|
||||||
self.p.create_custom_cursor_async(source)
|
let event_loop = self
|
||||||
|
.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
||||||
|
.expect("non Web event loop on Web");
|
||||||
|
event_loop.create_custom_cursor_async(source)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_poll_strategy(&self, strategy: PollStrategy) {
|
fn set_poll_strategy(&self, strategy: PollStrategy) {
|
||||||
self.p.set_poll_strategy(strategy);
|
let event_loop = self
|
||||||
|
.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
||||||
|
.expect("non Web event loop on Web");
|
||||||
|
event_loop.set_poll_strategy(strategy);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn poll_strategy(&self) -> PollStrategy {
|
fn poll_strategy(&self) -> PollStrategy {
|
||||||
self.p.poll_strategy()
|
let event_loop = self
|
||||||
|
.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
||||||
|
.expect("non Web event loop on Web");
|
||||||
|
event_loop.poll_strategy()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy) {
|
||||||
|
let event_loop = self
|
||||||
|
.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
||||||
|
.expect("non Web event loop on Web");
|
||||||
|
event_loop.set_wait_until_strategy(strategy);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn wait_until_strategy(&self) -> WaitUntilStrategy {
|
||||||
|
let event_loop = self
|
||||||
|
.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
||||||
|
.expect("non Web event loop on Web");
|
||||||
|
event_loop.wait_until_strategy()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn is_cursor_lock_raw(&self) -> bool {
|
||||||
|
let event_loop = self
|
||||||
|
.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
||||||
|
.expect("non Web event loop on Web");
|
||||||
|
event_loop.is_cursor_lock_raw()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn has_multiple_screens(&self) -> Result<bool, NotSupportedError> {
|
||||||
|
let event_loop = self
|
||||||
|
.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
||||||
|
.expect("non Web event loop on Web");
|
||||||
|
event_loop.has_multiple_screens()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn request_detailed_monitor_permission(&self) -> MonitorPermissionFuture {
|
||||||
|
let event_loop = self
|
||||||
|
.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
||||||
|
.expect("non Web event loop on Web");
|
||||||
|
MonitorPermissionFuture(event_loop.request_detailed_monitor_permission())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn has_detailed_monitor_permission(&self) -> bool {
|
||||||
|
let event_loop = self
|
||||||
|
.as_any()
|
||||||
|
.downcast_ref::<crate::platform_impl::ActiveEventLoop>()
|
||||||
|
.expect("non Web event loop on Web");
|
||||||
|
event_loop.has_detailed_monitor_permission()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Strategy used for [`ControlFlow::Poll`][crate::event_loop::ControlFlow::Poll].
|
/// Strategy used for [`ControlFlow::Poll`][crate::event_loop::ControlFlow::Poll].
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum PollStrategy {
|
pub enum PollStrategy {
|
||||||
/// Uses [`Window.requestIdleCallback()`] to queue the next event loop. If not available
|
/// Uses [`Window.requestIdleCallback()`] to queue the next event loop. If not available
|
||||||
/// this will fallback to [`setTimeout()`].
|
/// this will fallback to [`setTimeout()`].
|
||||||
@@ -278,7 +467,31 @@ pub enum PollStrategy {
|
|||||||
Scheduler,
|
Scheduler,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait CustomCursorExtWebSys {
|
/// Strategy used for [`ControlFlow::WaitUntil`][crate::event_loop::ControlFlow::WaitUntil].
|
||||||
|
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
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 CustomCursorExtWeb {
|
||||||
/// Returns if this cursor is an animation.
|
/// Returns if this cursor is an animation.
|
||||||
fn is_animation(&self) -> bool;
|
fn is_animation(&self) -> bool;
|
||||||
|
|
||||||
@@ -297,19 +510,13 @@ pub trait CustomCursorExtWebSys {
|
|||||||
) -> Result<CustomCursorSource, BadAnimation>;
|
) -> Result<CustomCursorSource, BadAnimation>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CustomCursorExtWebSys for CustomCursor {
|
impl CustomCursorExtWeb for CustomCursor {
|
||||||
fn is_animation(&self) -> bool {
|
fn is_animation(&self) -> bool {
|
||||||
self.inner.animation
|
self.inner.animation
|
||||||
}
|
}
|
||||||
|
|
||||||
fn from_url(url: String, hotspot_x: u16, hotspot_y: u16) -> CustomCursorSource {
|
fn from_url(url: String, hotspot_x: u16, hotspot_y: u16) -> CustomCursorSource {
|
||||||
CustomCursorSource {
|
CustomCursorSource { inner: PlatformCustomCursorSource::Url { url, hotspot_x, hotspot_y } }
|
||||||
inner: PlatformCustomCursorSource::Url {
|
|
||||||
url,
|
|
||||||
hotspot_x,
|
|
||||||
hotspot_y,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn from_animation(
|
fn from_animation(
|
||||||
@@ -331,7 +538,8 @@ impl CustomCursorExtWebSys for CustomCursor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// An error produced when using [`CustomCursor::from_animation`] with invalid arguments.
|
/// An error produced when using [`CustomCursor::from_animation`] with invalid arguments.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum BadAnimation {
|
pub enum BadAnimation {
|
||||||
/// Produced when no cursors were supplied.
|
/// Produced when no cursors were supplied.
|
||||||
Empty,
|
Empty,
|
||||||
@@ -343,7 +551,7 @@ impl fmt::Display for BadAnimation {
|
|||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
Self::Empty => write!(f, "No cursors supplied"),
|
Self::Empty => write!(f, "No cursors supplied"),
|
||||||
Self::Animation => write!(f, "A supplied cursor is an animtion"),
|
Self::Animation => write!(f, "A supplied cursor is an animation"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -360,17 +568,15 @@ impl Future for CustomCursorFuture {
|
|||||||
type Output = Result<CustomCursor, CustomCursorError>;
|
type Output = Result<CustomCursor, CustomCursorError>;
|
||||||
|
|
||||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
Pin::new(&mut self.0)
|
Pin::new(&mut self.0).poll(cx).map_ok(|cursor| CustomCursor { inner: cursor })
|
||||||
.poll(cx)
|
|
||||||
.map_ok(|cursor| CustomCursor { inner: cursor })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum CustomCursorError {
|
pub enum CustomCursorError {
|
||||||
Blob,
|
Blob,
|
||||||
Decode(String),
|
Decode(String),
|
||||||
Animation,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for CustomCursorError {
|
impl Display for CustomCursorError {
|
||||||
@@ -378,10 +584,198 @@ impl Display for CustomCursorError {
|
|||||||
match self {
|
match self {
|
||||||
Self::Blob => write!(f, "failed to create `Blob`"),
|
Self::Blob => write!(f, "failed to create `Blob`"),
|
||||||
Self::Decode(error) => write!(f, "failed to decode image: {error}"),
|
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 {}
|
||||||
|
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
struct PlatformMonitorPermissionFuture;
|
||||||
|
|
||||||
|
/// Can be dropped without aborting the request for detailed monitor permissions.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct MonitorPermissionFuture(pub(crate) PlatformMonitorPermissionFuture);
|
||||||
|
|
||||||
|
impl Future for MonitorPermissionFuture {
|
||||||
|
type Output = Result<(), MonitorPermissionError>;
|
||||||
|
|
||||||
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
Pin::new(&mut self.0).poll(cx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||||
|
pub enum MonitorPermissionError {
|
||||||
|
/// User has explicitly denied permission to query detailed monitor information.
|
||||||
|
Denied,
|
||||||
|
/// User has not decided to give permission to query detailed monitor information.
|
||||||
|
Prompt,
|
||||||
|
/// Browser does not support detailed monitor information.
|
||||||
|
Unsupported,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for MonitorPermissionError {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
MonitorPermissionError::Denied => write!(
|
||||||
|
f,
|
||||||
|
"User has explicitly denied permission to query detailed monitor information"
|
||||||
|
),
|
||||||
|
MonitorPermissionError::Prompt => write!(
|
||||||
|
f,
|
||||||
|
"User has not decided to give permission to query detailed monitor information"
|
||||||
|
),
|
||||||
|
MonitorPermissionError::Unsupported => {
|
||||||
|
write!(f, "Browser does not support detailed monitor information")
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for MonitorPermissionError {}
|
||||||
|
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
struct PlatformHasMonitorPermissionFuture;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct HasMonitorPermissionFuture(PlatformHasMonitorPermissionFuture);
|
||||||
|
|
||||||
|
impl Future for HasMonitorPermissionFuture {
|
||||||
|
type Output = bool;
|
||||||
|
|
||||||
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
Pin::new(&mut self.0).poll(cx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`MonitorHandle`] that are specific to the Web.
|
||||||
|
pub trait MonitorHandleExtWeb {
|
||||||
|
/// Returns whether the screen is internal to the device or external.
|
||||||
|
///
|
||||||
|
/// External devices are generally manufactured separately from the device they are attached to
|
||||||
|
/// and can be connected and disconnected as needed, whereas internal screens are part of
|
||||||
|
/// the device and not intended to be disconnected.
|
||||||
|
fn is_internal(&self) -> Option<bool>;
|
||||||
|
|
||||||
|
/// Returns screen orientation data for this monitor.
|
||||||
|
fn orientation(&self) -> OrientationData;
|
||||||
|
|
||||||
|
/// Lock the screen orientation. The returned [`OrientationLockFuture`] can be dropped without
|
||||||
|
/// aborting the request.
|
||||||
|
///
|
||||||
|
/// Will fail if another locking call is in progress.
|
||||||
|
fn request_lock(&self, orientation: OrientationLock) -> OrientationLockFuture;
|
||||||
|
|
||||||
|
/// Unlock the screen orientation.
|
||||||
|
///
|
||||||
|
/// Will fail if a locking call is in progress.
|
||||||
|
fn unlock(&self) -> Result<(), OrientationLockError>;
|
||||||
|
|
||||||
|
/// Returns whether this [`MonitorHandle`] was created using detailed monitor permissions. If
|
||||||
|
/// [`false`] will always represent the current monitor the browser window is in instead of a
|
||||||
|
/// specific monitor.
|
||||||
|
///
|
||||||
|
/// See [`ActiveEventLoopExtWeb::request_detailed_monitor_permission()`].
|
||||||
|
fn is_detailed(&self) -> bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonitorHandleExtWeb for MonitorHandle {
|
||||||
|
fn is_internal(&self) -> Option<bool> {
|
||||||
|
self.inner.is_internal()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn orientation(&self) -> OrientationData {
|
||||||
|
self.inner.orientation()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_lock(&self, orientation_lock: OrientationLock) -> OrientationLockFuture {
|
||||||
|
OrientationLockFuture(self.inner.request_lock(orientation_lock))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unlock(&self) -> Result<(), OrientationLockError> {
|
||||||
|
self.inner.unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_detailed(&self) -> bool {
|
||||||
|
self.inner.is_detailed()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Screen orientation data.
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||||
|
pub struct OrientationData {
|
||||||
|
/// The orientation.
|
||||||
|
pub orientation: Orientation,
|
||||||
|
/// [`true`] if the [`orientation`](Self::orientation) is flipped upside down.
|
||||||
|
pub flipped: bool,
|
||||||
|
/// The most natural orientation for the screen. Computer monitors are commonly naturally
|
||||||
|
/// landscape mode, while mobile phones are commonly naturally portrait mode.
|
||||||
|
pub natural: Orientation,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Screen orientation.
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||||
|
pub enum Orientation {
|
||||||
|
/// The screen's aspect ratio has a width greater than the height.
|
||||||
|
Landscape,
|
||||||
|
/// The screen's aspect ratio has a height greater than the width.
|
||||||
|
Portrait,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Screen orientation lock options. Reoresents which orientations a user can use.
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||||
|
pub enum OrientationLock {
|
||||||
|
/// User is free to use any orientation.
|
||||||
|
Any,
|
||||||
|
/// User is locked to the most upright natural orientation for the screen. Computer monitors
|
||||||
|
/// are commonly naturally landscape mode, while mobile phones are commonly
|
||||||
|
/// naturally portrait mode.
|
||||||
|
Natural,
|
||||||
|
/// User is locked to landscape mode.
|
||||||
|
Landscape {
|
||||||
|
/// - [`None`]: User is locked to both upright or upside down landscape mode.
|
||||||
|
/// - [`true`]: User is locked to upright landscape mode.
|
||||||
|
/// - [`false`]: User is locked to upside down landscape mode.
|
||||||
|
flipped: Option<bool>,
|
||||||
|
},
|
||||||
|
/// User is locked to portrait mode.
|
||||||
|
Portrait {
|
||||||
|
/// - [`None`]: User is locked to both upright or upside down portrait mode.
|
||||||
|
/// - [`true`]: User is locked to upright portrait mode.
|
||||||
|
/// - [`false`]: User is locked to upside down portrait mode.
|
||||||
|
flipped: Option<bool>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
struct PlatformOrientationLockFuture;
|
||||||
|
|
||||||
|
/// Can be dropped without aborting the request to lock the screen.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct OrientationLockFuture(PlatformOrientationLockFuture);
|
||||||
|
|
||||||
|
impl Future for OrientationLockFuture {
|
||||||
|
type Output = Result<(), OrientationLockError>;
|
||||||
|
|
||||||
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
Pin::new(&mut self.0).poll(cx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||||
|
pub enum OrientationLockError {
|
||||||
|
Unsupported,
|
||||||
|
Busy,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for OrientationLockError {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Unsupported => write!(f, "Locking the screen orientation is not supported"),
|
||||||
|
Self::Busy => write!(f, "Another locking call is in progress"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for OrientationLockError {}
|
||||||
|
|||||||
@@ -2,15 +2,21 @@
|
|||||||
//!
|
//!
|
||||||
//! The supported OS version is Windows 7 or higher, though Windows 10 is
|
//! The supported OS version is Windows 7 or higher, though Windows 10 is
|
||||||
//! tested regularly.
|
//! tested regularly.
|
||||||
use std::{ffi::c_void, path::Path};
|
use std::borrow::Borrow;
|
||||||
|
use std::ffi::c_void;
|
||||||
|
use std::ops::Deref;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
use crate::{
|
#[cfg(feature = "serde")]
|
||||||
dpi::PhysicalSize,
|
use serde::{Deserialize, Serialize};
|
||||||
event::DeviceId,
|
#[cfg(windows_platform)]
|
||||||
event_loop::EventLoopBuilder,
|
use windows_sys::Win32::Foundation::HANDLE;
|
||||||
monitor::MonitorHandle,
|
|
||||||
window::{BadIcon, Icon, Window, WindowAttributes},
|
use crate::dpi::PhysicalSize;
|
||||||
};
|
use crate::event::DeviceId;
|
||||||
|
use crate::event_loop::EventLoopBuilder;
|
||||||
|
use crate::monitor::MonitorHandle;
|
||||||
|
use crate::window::{BadIcon, Icon, Window, WindowAttributes};
|
||||||
|
|
||||||
/// Window Handle type used by Win32 API
|
/// Window Handle type used by Win32 API
|
||||||
pub type HWND = isize;
|
pub type HWND = isize;
|
||||||
@@ -25,6 +31,7 @@ pub type HMONITOR = isize;
|
|||||||
///
|
///
|
||||||
/// [`DWM_SYSTEMBACKDROP_TYPE docs`]: https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_systembackdrop_type
|
/// [`DWM_SYSTEMBACKDROP_TYPE docs`]: https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_systembackdrop_type
|
||||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum BackdropType {
|
pub enum BackdropType {
|
||||||
/// Corresponds to `DWMSBT_AUTO`.
|
/// Corresponds to `DWMSBT_AUTO`.
|
||||||
///
|
///
|
||||||
@@ -54,14 +61,15 @@ pub enum BackdropType {
|
|||||||
/// Describes a color used by Windows
|
/// Describes a color used by Windows
|
||||||
#[repr(transparent)]
|
#[repr(transparent)]
|
||||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
|
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub struct Color(u32);
|
pub struct Color(u32);
|
||||||
|
|
||||||
impl Color {
|
impl Color {
|
||||||
|
// Special constant only valid for the window border and therefore modeled using Option<Color>
|
||||||
|
// for user facing code
|
||||||
|
const NONE: Color = Color(0xfffffffe);
|
||||||
/// Use the system's default color
|
/// Use the system's default color
|
||||||
pub const SYSTEM_DEFAULT: Color = Color(0xFFFFFFFF);
|
pub const SYSTEM_DEFAULT: Color = Color(0xffffffff);
|
||||||
|
|
||||||
//Special constant only valid for the window border and therefore modeled using Option<Color> for user facing code
|
|
||||||
const NONE: Color = Color(0xFFFFFFFE);
|
|
||||||
|
|
||||||
/// Create a new color from the given RGB values
|
/// Create a new color from the given RGB values
|
||||||
pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
|
pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
|
||||||
@@ -82,6 +90,7 @@ impl Default for Color {
|
|||||||
/// [`DWM_WINDOW_CORNER_PREFERENCE docs`]: https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_window_corner_preference
|
/// [`DWM_WINDOW_CORNER_PREFERENCE docs`]: https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_window_corner_preference
|
||||||
#[repr(i32)]
|
#[repr(i32)]
|
||||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum CornerPreference {
|
pub enum CornerPreference {
|
||||||
/// Corresponds to `DWMWCP_DEFAULT`.
|
/// Corresponds to `DWMWCP_DEFAULT`.
|
||||||
///
|
///
|
||||||
@@ -105,6 +114,34 @@ pub enum CornerPreference {
|
|||||||
RoundSmall = 3,
|
RoundSmall = 3,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A wrapper around a [`Window`] that ignores thread-specific window handle limitations.
|
||||||
|
///
|
||||||
|
/// See [`WindowBorrowExtWindows::any_thread`] for more information.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct AnyThread<W: Window>(W);
|
||||||
|
|
||||||
|
impl<W: Window> AnyThread<W> {
|
||||||
|
/// Get a reference to the inner window.
|
||||||
|
#[inline]
|
||||||
|
pub fn get_ref(&self) -> &dyn Window {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: Window> Deref for AnyThread<W> {
|
||||||
|
type Target = W;
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: Window> rwh_06::HasWindowHandle for AnyThread<W> {
|
||||||
|
fn window_handle(&self) -> Result<rwh_06::WindowHandle<'_>, rwh_06::HandleError> {
|
||||||
|
// SAFETY: The top level user has asserted this is only used safely.
|
||||||
|
unsafe { self.get_ref().window_handle_any_thread() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Additional methods on `EventLoop` that are specific to Windows.
|
/// Additional methods on `EventLoop` that are specific to Windows.
|
||||||
pub trait EventLoopBuilderExtWindows {
|
pub trait EventLoopBuilderExtWindows {
|
||||||
/// Whether to allow the event loop to be created off of the main thread.
|
/// Whether to allow the event loop to be created off of the main thread.
|
||||||
@@ -129,11 +166,11 @@ pub trait EventLoopBuilderExtWindows {
|
|||||||
/// Disable process-wide DPI awareness.
|
/// Disable process-wide DPI awareness.
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use winit::event_loop::EventLoopBuilder;
|
/// use winit::event_loop::EventLoop;
|
||||||
/// #[cfg(target_os = "windows")]
|
/// #[cfg(target_os = "windows")]
|
||||||
/// use winit::platform::windows::EventLoopBuilderExtWindows;
|
/// use winit::platform::windows::EventLoopBuilderExtWindows;
|
||||||
///
|
///
|
||||||
/// let mut builder = EventLoopBuilder::new();
|
/// let mut builder = EventLoop::builder();
|
||||||
/// #[cfg(target_os = "windows")]
|
/// #[cfg(target_os = "windows")]
|
||||||
/// builder.with_dpi_aware(false);
|
/// builder.with_dpi_aware(false);
|
||||||
/// # if false { // We can't test this part
|
/// # if false { // We can't test this part
|
||||||
@@ -149,11 +186,11 @@ pub trait EventLoopBuilderExtWindows {
|
|||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// # use windows_sys::Win32::UI::WindowsAndMessaging::{ACCEL, CreateAcceleratorTableW, TranslateAcceleratorW, DispatchMessageW, TranslateMessage, MSG};
|
/// # use windows_sys::Win32::UI::WindowsAndMessaging::{ACCEL, CreateAcceleratorTableW, TranslateAcceleratorW, DispatchMessageW, TranslateMessage, MSG};
|
||||||
/// use winit::event_loop::EventLoopBuilder;
|
/// use winit::event_loop::EventLoop;
|
||||||
/// #[cfg(target_os = "windows")]
|
/// #[cfg(target_os = "windows")]
|
||||||
/// use winit::platform::windows::EventLoopBuilderExtWindows;
|
/// use winit::platform::windows::EventLoopBuilderExtWindows;
|
||||||
///
|
///
|
||||||
/// let mut builder = EventLoopBuilder::new();
|
/// let mut builder = EventLoop::builder();
|
||||||
/// #[cfg(target_os = "windows")]
|
/// #[cfg(target_os = "windows")]
|
||||||
/// builder.with_msg_hook(|msg|{
|
/// builder.with_msg_hook(|msg|{
|
||||||
/// let msg = msg as *const MSG;
|
/// let msg = msg as *const MSG;
|
||||||
@@ -173,7 +210,7 @@ pub trait EventLoopBuilderExtWindows {
|
|||||||
F: FnMut(*const c_void) -> bool + 'static;
|
F: FnMut(*const c_void) -> bool + 'static;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoopBuilderExtWindows for EventLoopBuilder<T> {
|
impl EventLoopBuilderExtWindows for EventLoopBuilder {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_any_thread(&mut self, any_thread: bool) -> &mut Self {
|
fn with_any_thread(&mut self, any_thread: bool) -> &mut Self {
|
||||||
self.platform_specific.any_thread = any_thread;
|
self.platform_specific.any_thread = any_thread;
|
||||||
@@ -202,8 +239,8 @@ pub trait WindowExtWindows {
|
|||||||
///
|
///
|
||||||
/// A window must be enabled before it can be activated.
|
/// A window must be enabled before it can be activated.
|
||||||
/// If an application has create a modal dialog box by disabling its owner window
|
/// If an application has create a modal dialog box by disabling its owner window
|
||||||
/// (as described in [`WindowAttributesExtWindows::with_owner_window`]), the application must enable
|
/// (as described in [`WindowAttributesExtWindows::with_owner_window`]), the application must
|
||||||
/// the owner window before destroying the dialog box.
|
/// enable the owner window before destroying the dialog box.
|
||||||
/// Otherwise, another window will receive the keyboard focus and be activated.
|
/// Otherwise, another window will receive the keyboard focus and be activated.
|
||||||
///
|
///
|
||||||
/// If a child window is disabled, it is ignored when the system tries to determine which
|
/// If a child window is disabled, it is ignored when the system tries to determine which
|
||||||
@@ -248,65 +285,173 @@ pub trait WindowExtWindows {
|
|||||||
///
|
///
|
||||||
/// Supported starting with Windows 11 Build 22000.
|
/// Supported starting with Windows 11 Build 22000.
|
||||||
fn set_corner_preference(&self, preference: CornerPreference);
|
fn set_corner_preference(&self, preference: CornerPreference);
|
||||||
|
|
||||||
|
/// Get the raw window handle for this [`Window`] without checking for thread affinity.
|
||||||
|
///
|
||||||
|
/// Window handles in Win32 have a property called "thread affinity" that ties them to their
|
||||||
|
/// origin thread. Some operations can only happen on the window's origin thread, while others
|
||||||
|
/// can be called from any thread. For example, [`SetWindowSubclass`] is not thread safe while
|
||||||
|
/// [`GetDC`] is thread safe.
|
||||||
|
///
|
||||||
|
/// In Rust terms, the window handle is `Send` sometimes but `!Send` other times.
|
||||||
|
///
|
||||||
|
/// Therefore, in order to avoid confusing threading errors, [`Window`] only returns the
|
||||||
|
/// window handle when the [`window_handle`] function is called from the thread that created
|
||||||
|
/// the window. In other cases, it returns an [`Unavailable`] error.
|
||||||
|
///
|
||||||
|
/// However in some cases you may already know that you are using the window handle for
|
||||||
|
/// operations that are guaranteed to be thread-safe. In which case this function aims
|
||||||
|
/// to provide an escape hatch so these functions are still accessible from other threads.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
///
|
||||||
|
/// It is the responsibility of the user to only pass the window handle into thread-safe
|
||||||
|
/// Win32 APIs.
|
||||||
|
///
|
||||||
|
/// [`SetWindowSubclass`]: https://learn.microsoft.com/en-us/windows/win32/api/commctrl/nf-commctrl-setwindowsubclass
|
||||||
|
/// [`GetDC`]: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc
|
||||||
|
/// [`Window`]: crate::window::Window
|
||||||
|
/// [`window_handle`]: https://docs.rs/raw-window-handle/latest/raw_window_handle/trait.HasWindowHandle.html#tymethod.window_handle
|
||||||
|
/// [`Unavailable`]: https://docs.rs/raw-window-handle/latest/raw_window_handle/enum.HandleError.html#variant.Unavailable
|
||||||
|
///
|
||||||
|
/// ## Example
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// # use winit::window::Window;
|
||||||
|
/// # fn scope(window: Box<dyn Window>) {
|
||||||
|
/// use std::thread;
|
||||||
|
///
|
||||||
|
/// use winit::platform::windows::WindowExtWindows;
|
||||||
|
/// use winit::raw_window_handle::HasWindowHandle;
|
||||||
|
///
|
||||||
|
/// // We can get the window handle on the current thread.
|
||||||
|
/// let handle = window.window_handle().unwrap();
|
||||||
|
///
|
||||||
|
/// // However, on another thread, we can't!
|
||||||
|
/// thread::spawn(move || {
|
||||||
|
/// assert!(window.window_handle().is_err());
|
||||||
|
///
|
||||||
|
/// // We can use this function as an escape hatch.
|
||||||
|
/// let handle = unsafe { window.window_handle_any_thread().unwrap() };
|
||||||
|
/// });
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
unsafe fn window_handle_any_thread(
|
||||||
|
&self,
|
||||||
|
) -> Result<rwh_06::WindowHandle<'_>, rwh_06::HandleError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowExtWindows for Window {
|
impl WindowExtWindows for dyn Window + '_ {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_enable(&self, enabled: bool) {
|
fn set_enable(&self, enabled: bool) {
|
||||||
self.window.set_enable(enabled)
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.set_enable(enabled)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>) {
|
fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>) {
|
||||||
self.window.set_taskbar_icon(taskbar_icon)
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.set_taskbar_icon(taskbar_icon)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_skip_taskbar(&self, skip: bool) {
|
fn set_skip_taskbar(&self, skip: bool) {
|
||||||
self.window.set_skip_taskbar(skip)
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.set_skip_taskbar(skip)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_undecorated_shadow(&self, shadow: bool) {
|
fn set_undecorated_shadow(&self, shadow: bool) {
|
||||||
self.window.set_undecorated_shadow(shadow)
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.set_undecorated_shadow(shadow)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_system_backdrop(&self, backdrop_type: BackdropType) {
|
fn set_system_backdrop(&self, backdrop_type: BackdropType) {
|
||||||
self.window.set_system_backdrop(backdrop_type)
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.set_system_backdrop(backdrop_type)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_border_color(&self, color: Option<Color>) {
|
fn set_border_color(&self, color: Option<Color>) {
|
||||||
self.window.set_border_color(color.unwrap_or(Color::NONE))
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.set_border_color(color.unwrap_or(Color::NONE))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_title_background_color(&self, color: Option<Color>) {
|
fn set_title_background_color(&self, color: Option<Color>) {
|
||||||
// The windows docs don't mention NONE as a valid options but it works in practice and is useful
|
// The windows docs don't mention NONE as a valid options but it works in practice and is
|
||||||
// to circumvent the Windows option "Show accent color on title bars and window borders"
|
// useful to circumvent the Windows option "Show accent color on title bars and
|
||||||
self.window
|
// window borders"
|
||||||
.set_title_background_color(color.unwrap_or(Color::NONE))
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.set_title_background_color(color.unwrap_or(Color::NONE))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_title_text_color(&self, color: Color) {
|
fn set_title_text_color(&self, color: Color) {
|
||||||
self.window.set_title_text_color(color)
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.set_title_text_color(color)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_corner_preference(&self, preference: CornerPreference) {
|
fn set_corner_preference(&self, preference: CornerPreference) {
|
||||||
self.window.set_corner_preference(preference)
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
window.set_corner_preference(preference)
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn window_handle_any_thread(
|
||||||
|
&self,
|
||||||
|
) -> Result<rwh_06::WindowHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let window = self.as_any().downcast_ref::<crate::platform_impl::Window>().unwrap();
|
||||||
|
unsafe {
|
||||||
|
let handle = window.rwh_06_no_thread_check()?;
|
||||||
|
|
||||||
|
// SAFETY: The handle is valid in this context.
|
||||||
|
Ok(rwh_06::WindowHandle::borrow_raw(handle))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Additional methods for anything that dereference to [`Window`].
|
||||||
|
///
|
||||||
|
/// [`Window`]: crate::window::Window
|
||||||
|
pub trait WindowBorrowExtWindows: Borrow<dyn Window> + Sized {
|
||||||
|
/// Create an object that allows accessing the inner window handle in a thread-unsafe way.
|
||||||
|
///
|
||||||
|
/// It is possible to call [`window_handle_any_thread`] to get around Windows's thread
|
||||||
|
/// affinity limitations. However, it may be desired to pass the [`Window`] into something
|
||||||
|
/// that requires the [`HasWindowHandle`] trait, while ignoring thread affinity limitations.
|
||||||
|
///
|
||||||
|
/// This function wraps anything that implements `Borrow<Window>` into a structure that
|
||||||
|
/// uses the inner window handle as a mean of implementing [`HasWindowHandle`]. It wraps
|
||||||
|
/// `Window`, `&Window`, `Arc<Window>`, and other reference types.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
///
|
||||||
|
/// It is the responsibility of the user to only pass the window handle into thread-safe
|
||||||
|
/// Win32 APIs.
|
||||||
|
///
|
||||||
|
/// [`Window`]: crate::window::Window
|
||||||
|
/// [`HasWindowHandle`]: rwh_06::HasWindowHandle
|
||||||
|
/// [`window_handle_any_thread`]: WindowExtWindows::window_handle_any_thread
|
||||||
|
unsafe fn any_thread(self) -> AnyThread<Self>
|
||||||
|
where
|
||||||
|
Self: Window,
|
||||||
|
{
|
||||||
|
AnyThread(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: Borrow<dyn Window> + Sized> WindowBorrowExtWindows for W {}
|
||||||
|
|
||||||
/// Additional methods on `WindowAttributes` that are specific to Windows.
|
/// Additional methods on `WindowAttributes` that are specific to Windows.
|
||||||
#[allow(rustdoc::broken_intra_doc_links)]
|
#[allow(rustdoc::broken_intra_doc_links)]
|
||||||
pub trait WindowAttributesExtWindows {
|
pub trait WindowAttributesExtWindows {
|
||||||
/// Set an owner to the window to be created. Can be used to create a dialog box, for example.
|
/// Set an owner to the window to be created. Can be used to create a dialog box, for example.
|
||||||
/// This only works when [`WindowAttributes::with_parent_window`] isn't called or set to `None`.
|
/// This only works when [`WindowAttributes::with_parent_window`] isn't called or set to `None`.
|
||||||
/// Can be used in combination with [`WindowExtWindows::set_enable(false)`][WindowExtWindows::set_enable]
|
/// Can be used in combination with
|
||||||
/// on the owner window to create a modal dialog box.
|
/// [`WindowExtWindows::set_enable(false)`][WindowExtWindows::set_enable] on the owner
|
||||||
|
/// window to create a modal dialog box.
|
||||||
///
|
///
|
||||||
/// From MSDN:
|
/// From MSDN:
|
||||||
/// - An owned window is always above its owner in the z-order.
|
/// - An owned window is always above its owner in the z-order.
|
||||||
@@ -322,17 +467,14 @@ pub trait WindowAttributesExtWindows {
|
|||||||
///
|
///
|
||||||
/// The menu must have been manually created beforehand with [`CreateMenu`] or similar.
|
/// The menu must have been manually created beforehand with [`CreateMenu`] or similar.
|
||||||
///
|
///
|
||||||
/// Note: Dark mode cannot be supported for win32 menus, it's simply not possible to change how the menus look.
|
/// Note: Dark mode cannot be supported for win32 menus, it's simply not possible to change how
|
||||||
/// If you use this, it is recommended that you combine it with `with_theme(Some(Theme::Light))` to avoid a jarring effect.
|
/// the menus look. If you use this, it is recommended that you combine it with
|
||||||
///
|
/// `with_theme(Some(Theme::Light))` to avoid a jarring effect.
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
platform_windows,
|
windows_platform,
|
||||||
doc = "[`CreateMenu`]: windows_sys::Win32::UI::WindowsAndMessaging::CreateMenu"
|
doc = "[`CreateMenu`]: windows_sys::Win32::UI::WindowsAndMessaging::CreateMenu"
|
||||||
)]
|
)]
|
||||||
#[cfg_attr(
|
#[cfg_attr(not(windows_platform), doc = "[`CreateMenu`]: #only-available-on-windows")]
|
||||||
not(platform_windows),
|
|
||||||
doc = "[`CreateMenu`]: #only-available-on-windows"
|
|
||||||
)]
|
|
||||||
fn with_menu(self, menu: HMENU) -> Self;
|
fn with_menu(self, menu: HMENU) -> Self;
|
||||||
|
|
||||||
/// This sets `ICON_BIG`. A good ceiling here is 256x256.
|
/// This sets `ICON_BIG`. A good ceiling here is 256x256.
|
||||||
@@ -341,12 +483,12 @@ pub trait WindowAttributesExtWindows {
|
|||||||
/// This sets `WS_EX_NOREDIRECTIONBITMAP`.
|
/// This sets `WS_EX_NOREDIRECTIONBITMAP`.
|
||||||
fn with_no_redirection_bitmap(self, flag: bool) -> Self;
|
fn with_no_redirection_bitmap(self, flag: bool) -> Self;
|
||||||
|
|
||||||
/// Enables or disables drag and drop support (enabled by default). Will interfere with other crates
|
/// Enables or disables drag and drop support (enabled by default). Will interfere with other
|
||||||
/// that use multi-threaded COM API (`CoInitializeEx` with `COINIT_MULTITHREADED` instead of
|
/// crates that use multi-threaded COM API (`CoInitializeEx` with `COINIT_MULTITHREADED`
|
||||||
/// `COINIT_APARTMENTTHREADED`) on the same thread. Note that winit may still attempt to initialize
|
/// instead of `COINIT_APARTMENTTHREADED`) on the same thread. Note that winit may still
|
||||||
/// COM API regardless of this option. Currently only fullscreen mode does that, but there may be more in the future.
|
/// attempt to initialize COM API regardless of this option. Currently only fullscreen mode
|
||||||
/// If you need COM API with `COINIT_MULTITHREADED` you must initialize it before calling any winit functions.
|
/// does that, but there may be more in the future. If you need COM API with
|
||||||
/// See <https://docs.microsoft.com/en-us/windows/win32/api/objbase/nf-objbase-coinitialize#remarks> for more information.
|
/// `COINIT_MULTITHREADED` you must initialize it before calling any winit functions. See <https://docs.microsoft.com/en-us/windows/win32/api/objbase/nf-objbase-coinitialize#remarks> for more information.
|
||||||
fn with_drag_and_drop(self, flag: bool) -> Self;
|
fn with_drag_and_drop(self, flag: bool) -> Self;
|
||||||
|
|
||||||
/// Whether show or hide the window icon in the taskbar.
|
/// Whether show or hide the window icon in the taskbar.
|
||||||
@@ -505,10 +647,15 @@ pub trait DeviceIdExtWindows {
|
|||||||
fn persistent_identifier(&self) -> Option<String>;
|
fn persistent_identifier(&self) -> Option<String>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(windows_platform)]
|
||||||
impl DeviceIdExtWindows for DeviceId {
|
impl DeviceIdExtWindows for DeviceId {
|
||||||
#[inline]
|
|
||||||
fn persistent_identifier(&self) -> Option<String> {
|
fn persistent_identifier(&self) -> Option<String> {
|
||||||
self.0.persistent_identifier()
|
let raw_id = self.into_raw();
|
||||||
|
if raw_id != 0 {
|
||||||
|
crate::platform_impl::raw_input::get_raw_input_device_name(raw_id as HANDLE)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,24 +2,22 @@
|
|||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::{
|
|
||||||
event_loop::{ActiveEventLoop, EventLoopBuilder},
|
|
||||||
monitor::MonitorHandle,
|
|
||||||
window::{Window, WindowAttributes},
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::dpi::Size;
|
use crate::dpi::Size;
|
||||||
|
use crate::event_loop::{ActiveEventLoop, EventLoop, EventLoopBuilder};
|
||||||
|
use crate::monitor::MonitorHandle;
|
||||||
|
use crate::window::{Window as CoreWindow, WindowAttributes};
|
||||||
|
|
||||||
/// X window type. Maps directly to
|
/// X window type. Maps directly to
|
||||||
/// [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html).
|
/// [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html).
|
||||||
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
|
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum WindowType {
|
pub enum WindowType {
|
||||||
/// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the
|
/// A desktop feature. This can include a single window containing desktop icons with the same
|
||||||
/// screen, allowing the desktop environment to have full control of the desktop, without the need for proxying
|
/// dimensions as the screen, allowing the desktop environment to have full control of the
|
||||||
/// root window clicks.
|
/// desktop, without the need for proxying root window clicks.
|
||||||
Desktop,
|
Desktop,
|
||||||
/// A dock or panel feature. Typically a Window Manager would keep such windows on top of all other windows.
|
/// A dock or panel feature. Typically a Window Manager would keep such windows on top of all
|
||||||
|
/// other windows.
|
||||||
Dock,
|
Dock,
|
||||||
/// Toolbar windows. "Torn off" from the main application.
|
/// Toolbar windows. "Torn off" from the main application.
|
||||||
Toolbar,
|
Toolbar,
|
||||||
@@ -37,8 +35,8 @@ pub enum WindowType {
|
|||||||
/// A popup menu that usually appears when the user right clicks on an object.
|
/// A popup menu that usually appears when the user right clicks on an object.
|
||||||
/// This property is typically used on override-redirect windows.
|
/// This property is typically used on override-redirect windows.
|
||||||
PopupMenu,
|
PopupMenu,
|
||||||
/// A tooltip window. Usually used to show additional information when hovering over an object with the cursor.
|
/// A tooltip window. Usually used to show additional information when hovering over an object
|
||||||
/// This property is typically used on override-redirect windows.
|
/// with the cursor. This property is typically used on override-redirect windows.
|
||||||
Tooltip,
|
Tooltip,
|
||||||
/// The window is a notification.
|
/// The window is a notification.
|
||||||
/// This property is typically used on override-redirect windows.
|
/// This property is typically used on override-redirect windows.
|
||||||
@@ -46,7 +44,7 @@ pub enum WindowType {
|
|||||||
/// This should be used on the windows that are popped up by combo boxes.
|
/// This should be used on the windows that are popped up by combo boxes.
|
||||||
/// This property is typically used on override-redirect windows.
|
/// This property is typically used on override-redirect windows.
|
||||||
Combo,
|
Combo,
|
||||||
/// This indicates the the window is being dragged.
|
/// This indicates the window is being dragged.
|
||||||
/// This property is typically used on override-redirect windows.
|
/// This property is typically used on override-redirect windows.
|
||||||
Dnd,
|
Dnd,
|
||||||
/// This is a normal, top-level window.
|
/// This is a normal, top-level window.
|
||||||
@@ -82,12 +80,7 @@ pub type XWindow = u32;
|
|||||||
#[inline]
|
#[inline]
|
||||||
pub fn register_xlib_error_hook(hook: XlibErrorHook) {
|
pub fn register_xlib_error_hook(hook: XlibErrorHook) {
|
||||||
// Append new hook.
|
// Append new hook.
|
||||||
unsafe {
|
crate::platform_impl::XLIB_ERROR_HOOKS.lock().unwrap().push(hook);
|
||||||
crate::platform_impl::XLIB_ERROR_HOOKS
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.push(hook);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Additional methods on [`ActiveEventLoop`] that are specific to X11.
|
/// Additional methods on [`ActiveEventLoop`] that are specific to X11.
|
||||||
@@ -96,10 +89,23 @@ pub trait ActiveEventLoopExtX11 {
|
|||||||
fn is_x11(&self) -> bool;
|
fn is_x11(&self) -> bool;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ActiveEventLoopExtX11 for ActiveEventLoop {
|
impl ActiveEventLoopExtX11 for dyn ActiveEventLoop + '_ {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn is_x11(&self) -> bool {
|
fn is_x11(&self) -> bool {
|
||||||
!self.p.is_wayland()
|
self.as_any().downcast_ref::<crate::platform_impl::x11::ActiveEventLoop>().is_some()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoop`] that are specific to X11.
|
||||||
|
pub trait EventLoopExtX11 {
|
||||||
|
/// True if the [`EventLoop`] uses X11.
|
||||||
|
fn is_x11(&self) -> bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopExtX11 for EventLoop {
|
||||||
|
#[inline]
|
||||||
|
fn is_x11(&self) -> bool {
|
||||||
|
!self.event_loop.is_wayland()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,7 +121,7 @@ pub trait EventLoopBuilderExtX11 {
|
|||||||
fn with_any_thread(&mut self, any_thread: bool) -> &mut Self;
|
fn with_any_thread(&mut self, any_thread: bool) -> &mut Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoopBuilderExtX11 for EventLoopBuilder<T> {
|
impl EventLoopBuilderExtX11 for EventLoopBuilder {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_x11(&mut self) -> &mut Self {
|
fn with_x11(&mut self) -> &mut Self {
|
||||||
self.platform_specific.forced_backend = Some(crate::platform_impl::Backend::X);
|
self.platform_specific.forced_backend = Some(crate::platform_impl::Backend::X);
|
||||||
@@ -130,9 +136,11 @@ impl<T> EventLoopBuilderExtX11 for EventLoopBuilder<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Additional methods on [`Window`] that are specific to X11.
|
/// Additional methods on [`Window`] that are specific to X11.
|
||||||
|
///
|
||||||
|
/// [`Window`]: crate::window::Window
|
||||||
pub trait WindowExtX11 {}
|
pub trait WindowExtX11 {}
|
||||||
|
|
||||||
impl WindowExtX11 for Window {}
|
impl WindowExtX11 for dyn CoreWindow {}
|
||||||
|
|
||||||
/// Additional methods on [`WindowAttributes`] that are specific to X11.
|
/// Additional methods on [`WindowAttributes`] that are specific to X11.
|
||||||
pub trait WindowAttributesExtX11 {
|
pub trait WindowAttributesExtX11 {
|
||||||
@@ -144,7 +152,8 @@ pub trait WindowAttributesExtX11 {
|
|||||||
/// Build window with the given `general` and `instance` names.
|
/// Build window with the given `general` and `instance` names.
|
||||||
///
|
///
|
||||||
/// The `general` sets general class of `WM_CLASS(STRING)`, while `instance` set the
|
/// The `general` sets general class of `WM_CLASS(STRING)`, while `instance` set the
|
||||||
/// instance part of it. The resulted property looks like `WM_CLASS(STRING) = "instance", "general"`.
|
/// instance part of it. The resulted property looks like `WM_CLASS(STRING) = "instance",
|
||||||
|
/// "general"`.
|
||||||
///
|
///
|
||||||
/// For details about application ID conventions, see the
|
/// 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)
|
/// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id)
|
||||||
@@ -160,13 +169,13 @@ pub trait WindowAttributesExtX11 {
|
|||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// # use winit::dpi::{LogicalSize, PhysicalSize};
|
/// # use winit::dpi::{LogicalSize, PhysicalSize};
|
||||||
/// # use winit::window::Window;
|
/// # use winit::window::{Window, WindowAttributes};
|
||||||
/// # use winit::platform::x11::WindowAttributesExtX11;
|
/// # use winit::platform::x11::WindowAttributesExtX11;
|
||||||
/// // Specify the size in logical dimensions like this:
|
/// // Specify the size in logical dimensions like this:
|
||||||
/// Window::default_attributes().with_base_size(LogicalSize::new(400.0, 200.0));
|
/// WindowAttributes::default().with_base_size(LogicalSize::new(400.0, 200.0));
|
||||||
///
|
///
|
||||||
/// // Or specify the size in physical dimensions like this:
|
/// // Or specify the size in physical dimensions like this:
|
||||||
/// Window::default_attributes().with_base_size(PhysicalSize::new(400, 200));
|
/// WindowAttributes::default().with_base_size(PhysicalSize::new(400, 200));
|
||||||
/// ```
|
/// ```
|
||||||
fn with_base_size<S: Into<Size>>(self, base_size: S) -> Self;
|
fn with_base_size<S: Into<Size>>(self, base_size: S) -> Self;
|
||||||
|
|
||||||
@@ -175,12 +184,12 @@ pub trait WindowAttributesExtX11 {
|
|||||||
/// # Example
|
/// # Example
|
||||||
///
|
///
|
||||||
/// ```no_run
|
/// ```no_run
|
||||||
/// use winit::window::Window;
|
/// use winit::window::{Window, WindowAttributes};
|
||||||
/// use winit::event_loop::ActiveEventLoop;
|
/// use winit::event_loop::ActiveEventLoop;
|
||||||
/// use winit::platform::x11::{XWindow, WindowAttributesExtX11};
|
/// use winit::platform::x11::{XWindow, WindowAttributesExtX11};
|
||||||
/// # fn create_window(event_loop: &ActiveEventLoop) -> Result<(), Box<dyn std::error::Error>> {
|
/// # fn create_window(event_loop: &dyn ActiveEventLoop) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
/// let parent_window_id = std::env::args().nth(1).unwrap().parse::<XWindow>()?;
|
/// let parent_window_id = std::env::args().nth(1).unwrap().parse::<XWindow>()?;
|
||||||
/// let window_attributes = Window::default_attributes().with_embed_parent_window(parent_window_id);
|
/// let window_attributes = WindowAttributes::default().with_embed_parent_window(parent_window_id);
|
||||||
/// let window = event_loop.create_window(window_attributes)?;
|
/// let window = event_loop.create_window(window_attributes)?;
|
||||||
/// # Ok(()) }
|
/// # Ok(()) }
|
||||||
/// ```
|
/// ```
|
||||||
@@ -202,10 +211,8 @@ impl WindowAttributesExtX11 for WindowAttributes {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self {
|
fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self {
|
||||||
self.platform_specific.name = Some(crate::platform_impl::ApplicationName::new(
|
self.platform_specific.name =
|
||||||
general.into(),
|
Some(crate::platform_impl::ApplicationName::new(general.into(), instance.into()));
|
||||||
instance.into(),
|
|
||||||
));
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
use android_activity::{
|
use android_activity::input::{KeyAction, KeyEvent, KeyMapChar, Keycode};
|
||||||
input::{KeyAction, KeyEvent, KeyMapChar, Keycode},
|
use android_activity::AndroidApp;
|
||||||
AndroidApp,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey};
|
use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey};
|
||||||
|
|
||||||
@@ -105,7 +103,7 @@ pub fn to_physical_key(keycode: Keycode) -> PhysicalKey {
|
|||||||
Keycode::VolumeUp => KeyCode::AudioVolumeUp,
|
Keycode::VolumeUp => KeyCode::AudioVolumeUp,
|
||||||
Keycode::VolumeDown => KeyCode::AudioVolumeDown,
|
Keycode::VolumeDown => KeyCode::AudioVolumeDown,
|
||||||
Keycode::VolumeMute => KeyCode::AudioVolumeMute,
|
Keycode::VolumeMute => KeyCode::AudioVolumeMute,
|
||||||
//Keycode::Mute => None, // Microphone mute
|
// Keycode::Mute => None, // Microphone mute
|
||||||
Keycode::MediaPlayPause => KeyCode::MediaPlayPause,
|
Keycode::MediaPlayPause => KeyCode::MediaPlayPause,
|
||||||
Keycode::MediaStop => KeyCode::MediaStop,
|
Keycode::MediaStop => KeyCode::MediaStop,
|
||||||
Keycode::MediaNext => KeyCode::MediaTrackNext,
|
Keycode::MediaNext => KeyCode::MediaTrackNext,
|
||||||
@@ -176,7 +174,7 @@ pub fn character_map_and_combine_key(
|
|||||||
Err(err) => {
|
Err(err) => {
|
||||||
tracing::warn!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}");
|
tracing::warn!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}");
|
||||||
return None;
|
return None;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
match key_map.get(key_event.key_code(), key_event.meta_state()) {
|
match key_map.get(key_event.key_code(), key_event.meta_state()) {
|
||||||
@@ -188,9 +186,12 @@ pub fn character_map_and_combine_key(
|
|||||||
Ok(Some(key)) => Some(key),
|
Ok(Some(key)) => Some(key),
|
||||||
Ok(None) => None,
|
Ok(None) => None,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
tracing::warn!("KeyEvent: Failed to combine 'dead key' accent '{accent}' with '{unicode}': {err:?}");
|
tracing::warn!(
|
||||||
|
"KeyEvent: Failed to combine 'dead key' accent '{accent}' with \
|
||||||
|
'{unicode}': {err:?}"
|
||||||
|
);
|
||||||
None
|
None
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Some(unicode)
|
Some(unicode)
|
||||||
@@ -200,23 +201,23 @@ pub fn character_map_and_combine_key(
|
|||||||
} else {
|
} else {
|
||||||
Some(KeyMapChar::Unicode(unicode))
|
Some(KeyMapChar::Unicode(unicode))
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
Ok(KeyMapChar::CombiningAccent(accent)) => {
|
Ok(KeyMapChar::CombiningAccent(accent)) => {
|
||||||
if key_event.action() == KeyAction::Down {
|
if key_event.action() == KeyAction::Down {
|
||||||
*combining_accent = Some(accent);
|
*combining_accent = Some(accent);
|
||||||
}
|
}
|
||||||
Some(KeyMapChar::CombiningAccent(accent))
|
Some(KeyMapChar::CombiningAccent(accent))
|
||||||
}
|
},
|
||||||
Ok(KeyMapChar::None) => {
|
Ok(KeyMapChar::None) => {
|
||||||
// Leave any combining_accent state in tact (seems to match how other
|
// Leave any combining_accent state in tact (seems to match how other
|
||||||
// Android apps work)
|
// Android apps work)
|
||||||
None
|
None
|
||||||
}
|
},
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
tracing::warn!("KeyEvent: Failed to get key map character: {err:?}");
|
tracing::warn!("KeyEvent: Failed to get key map character: {err:?}");
|
||||||
*combining_accent = None;
|
*combining_accent = None;
|
||||||
None
|
None
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
89
src/platform_impl/apple/appkit/app.rs
Normal file
89
src/platform_impl/apple/appkit/app.rs
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
#![allow(clippy::unnecessary_cast)]
|
||||||
|
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
|
use objc2::{declare_class, msg_send, mutability, ClassType, DeclaredClass};
|
||||||
|
use objc2_app_kit::{NSApplication, NSEvent, NSEventModifierFlags, NSEventType, NSResponder};
|
||||||
|
use objc2_foundation::{MainThreadMarker, NSObject};
|
||||||
|
|
||||||
|
use super::app_state::AppState;
|
||||||
|
use crate::event::{DeviceEvent, ElementState};
|
||||||
|
|
||||||
|
declare_class!(
|
||||||
|
pub(super) struct WinitApplication;
|
||||||
|
|
||||||
|
unsafe impl ClassType for WinitApplication {
|
||||||
|
#[inherits(NSResponder, NSObject)]
|
||||||
|
type Super = NSApplication;
|
||||||
|
type Mutability = mutability::MainThreadOnly;
|
||||||
|
const NAME: &'static str = "WinitApplication";
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DeclaredClass for WinitApplication {}
|
||||||
|
|
||||||
|
unsafe impl WinitApplication {
|
||||||
|
// Normally, holding Cmd + any key never sends us a `keyUp` event for that key.
|
||||||
|
// Overriding `sendEvent:` like this fixes that. (https://stackoverflow.com/a/15294196)
|
||||||
|
// Fun fact: Firefox still has this bug! (https://bugzilla.mozilla.org/show_bug.cgi?id=1299553)
|
||||||
|
#[method(sendEvent:)]
|
||||||
|
fn send_event(&self, event: &NSEvent) {
|
||||||
|
// For posterity, there are some undocumented event types
|
||||||
|
// (https://github.com/servo/cocoa-rs/issues/155)
|
||||||
|
// but that doesn't really matter here.
|
||||||
|
let event_type = unsafe { event.r#type() };
|
||||||
|
let modifier_flags = unsafe { event.modifierFlags() };
|
||||||
|
if event_type == NSEventType::KeyUp
|
||||||
|
&& modifier_flags.contains(NSEventModifierFlags::NSEventModifierFlagCommand)
|
||||||
|
{
|
||||||
|
if let Some(key_window) = self.keyWindow() {
|
||||||
|
key_window.sendEvent(event);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let app_state = AppState::get(MainThreadMarker::from(self));
|
||||||
|
maybe_dispatch_device_event(&app_state, event);
|
||||||
|
unsafe { msg_send![super(self), sendEvent: event] }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
fn maybe_dispatch_device_event(app_state: &Rc<AppState>, event: &NSEvent) {
|
||||||
|
let event_type = unsafe { event.r#type() };
|
||||||
|
#[allow(non_upper_case_globals)]
|
||||||
|
match event_type {
|
||||||
|
NSEventType::MouseMoved
|
||||||
|
| NSEventType::LeftMouseDragged
|
||||||
|
| NSEventType::OtherMouseDragged
|
||||||
|
| NSEventType::RightMouseDragged => {
|
||||||
|
let delta_x = unsafe { event.deltaX() } as f64;
|
||||||
|
let delta_y = unsafe { event.deltaY() } as f64;
|
||||||
|
|
||||||
|
if delta_x != 0.0 || delta_y != 0.0 {
|
||||||
|
app_state.maybe_queue_with_handler(move |app, event_loop| {
|
||||||
|
app.device_event(event_loop, None, DeviceEvent::PointerMotion {
|
||||||
|
delta: (delta_x, delta_y),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
NSEventType::LeftMouseDown | NSEventType::RightMouseDown | NSEventType::OtherMouseDown => {
|
||||||
|
let button = unsafe { event.buttonNumber() } as u32;
|
||||||
|
app_state.maybe_queue_with_handler(move |app, event_loop| {
|
||||||
|
app.device_event(event_loop, None, DeviceEvent::Button {
|
||||||
|
button,
|
||||||
|
state: ElementState::Pressed,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
NSEventType::LeftMouseUp | NSEventType::RightMouseUp | NSEventType::OtherMouseUp => {
|
||||||
|
let button = unsafe { event.buttonNumber() } as u32;
|
||||||
|
app_state.maybe_queue_with_handler(move |app, event_loop| {
|
||||||
|
app.device_event(event_loop, None, DeviceEvent::Button {
|
||||||
|
button,
|
||||||
|
state: ElementState::Released,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
403
src/platform_impl/apple/appkit/app_state.rs
Normal file
403
src/platform_impl/apple/appkit/app_state.rs
Normal file
@@ -0,0 +1,403 @@
|
|||||||
|
use std::cell::{Cell, OnceCell, RefCell};
|
||||||
|
use std::mem;
|
||||||
|
use std::rc::{Rc, Weak};
|
||||||
|
use std::sync::atomic::Ordering as AtomicOrdering;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy, NSRunningApplication};
|
||||||
|
use objc2_foundation::{MainThreadMarker, NSNotification};
|
||||||
|
|
||||||
|
use super::super::event_handler::EventHandler;
|
||||||
|
use super::event_loop::{stop_app_immediately, ActiveEventLoop, EventLoopProxy, PanicInfo};
|
||||||
|
use super::menu;
|
||||||
|
use super::observer::{EventLoopWaker, RunLoop};
|
||||||
|
use crate::application::ApplicationHandler;
|
||||||
|
use crate::event::{StartCause, WindowEvent};
|
||||||
|
use crate::event_loop::ControlFlow;
|
||||||
|
use crate::window::WindowId;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
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.
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO(madsmtm): Use `MainThreadBound` once that is possible in `static`s.
|
||||||
|
struct StaticMainThreadBound<T>(T);
|
||||||
|
|
||||||
|
impl<T> StaticMainThreadBound<T> {
|
||||||
|
const fn get(&self, _mtm: MainThreadMarker) -> &T {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl<T> Send for StaticMainThreadBound<T> {}
|
||||||
|
unsafe impl<T> Sync for StaticMainThreadBound<T> {}
|
||||||
|
|
||||||
|
// SAFETY: Creating `StaticMainThreadBound` in a `const` context, where there is no concept of the
|
||||||
|
// main thread.
|
||||||
|
static GLOBAL: StaticMainThreadBound<OnceCell<Rc<AppState>>> =
|
||||||
|
StaticMainThreadBound(OnceCell::new());
|
||||||
|
|
||||||
|
impl AppState {
|
||||||
|
pub(super) fn setup_global(
|
||||||
|
mtm: MainThreadMarker,
|
||||||
|
activation_policy: Option<NSApplicationActivationPolicy>,
|
||||||
|
default_menu: bool,
|
||||||
|
activate_ignoring_other_apps: bool,
|
||||||
|
) -> Rc<Self> {
|
||||||
|
let this = Rc::new(AppState {
|
||||||
|
mtm,
|
||||||
|
activation_policy,
|
||||||
|
event_loop_proxy: Arc::new(EventLoopProxy::new()),
|
||||||
|
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![]),
|
||||||
|
});
|
||||||
|
|
||||||
|
GLOBAL.get(mtm).set(this.clone()).expect("application state can only be set once");
|
||||||
|
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 =
|
||||||
|
unsafe { 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");
|
||||||
|
// TODO: Notify every window that it will be destroyed, like done in iOS?
|
||||||
|
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: &mut dyn ApplicationHandler,
|
||||||
|
closure: impl FnOnce() -> R,
|
||||||
|
) -> R {
|
||||||
|
self.event_handler.set(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.with_handler(|app, event_loop| {
|
||||||
|
app.exiting(event_loop);
|
||||||
|
});
|
||||||
|
|
||||||
|
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>, panic_info: Weak<PanicInfo>) {
|
||||||
|
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.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>, panic_info: Weak<PanicInfo>) {
|
||||||
|
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.event_handler.ready() || !self.is_running() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.event_loop_proxy.wake_up.swap(false, AtomicOrdering::Relaxed) {
|
||||||
|
self.with_handler(|app, event_loop| app.proxy_wake_up(event_loop));
|
||||||
|
}
|
||||||
|
|
||||||
|
let redraw = mem::take(&mut *self.pending_redraw.borrow_mut());
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
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))))
|
||||||
|
}
|
||||||
@@ -2,34 +2,34 @@ use std::ffi::c_uchar;
|
|||||||
use std::slice;
|
use std::slice;
|
||||||
use std::sync::OnceLock;
|
use std::sync::OnceLock;
|
||||||
|
|
||||||
use icrate::AppKit::{NSBitmapImageRep, NSCursor, NSDeviceRGBColorSpace, NSImage};
|
use objc2::rc::Retained;
|
||||||
use icrate::Foundation::{
|
use objc2::runtime::Sel;
|
||||||
|
use objc2::{msg_send_id, sel, ClassType};
|
||||||
|
use objc2_app_kit::{NSBitmapImageRep, NSCursor, NSDeviceRGBColorSpace, NSImage};
|
||||||
|
use objc2_foundation::{
|
||||||
ns_string, NSData, NSDictionary, NSNumber, NSObject, NSObjectProtocol, NSPoint, NSSize,
|
ns_string, NSData, NSDictionary, NSNumber, NSObject, NSObjectProtocol, NSPoint, NSSize,
|
||||||
NSString,
|
NSString,
|
||||||
};
|
};
|
||||||
use objc2::rc::Id;
|
|
||||||
use objc2::runtime::Sel;
|
|
||||||
use objc2::{msg_send_id, sel, ClassType};
|
|
||||||
|
|
||||||
use crate::cursor::CursorImage;
|
use crate::cursor::{CursorImage, OnlyCursorImageSource};
|
||||||
use crate::cursor::OnlyCursorImageSource;
|
use crate::error::RequestError;
|
||||||
use crate::window::CursorIcon;
|
use crate::window::CursorIcon;
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||||
pub struct CustomCursor(pub(crate) Id<NSCursor>);
|
pub struct CustomCursor(pub(crate) Retained<NSCursor>);
|
||||||
|
|
||||||
// SAFETY: NSCursor is immutable and thread-safe
|
// SAFETY: NSCursor is immutable and thread-safe
|
||||||
// TODO(madsmtm): Put this logic in icrate itself
|
// TODO(madsmtm): Put this logic in objc2-app-kit itself
|
||||||
unsafe impl Send for CustomCursor {}
|
unsafe impl Send for CustomCursor {}
|
||||||
unsafe impl Sync for CustomCursor {}
|
unsafe impl Sync for CustomCursor {}
|
||||||
|
|
||||||
impl CustomCursor {
|
impl CustomCursor {
|
||||||
pub(crate) fn new(cursor: OnlyCursorImageSource) -> CustomCursor {
|
pub(crate) fn new(cursor: OnlyCursorImageSource) -> Result<CustomCursor, RequestError> {
|
||||||
Self(cursor_from_image(&cursor.0))
|
cursor_from_image(&cursor.0).map(Self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn cursor_from_image(cursor: &CursorImage) -> Id<NSCursor> {
|
pub(crate) fn cursor_from_image(cursor: &CursorImage) -> Result<Retained<NSCursor>, RequestError> {
|
||||||
let width = cursor.width;
|
let width = cursor.width;
|
||||||
let height = cursor.height;
|
let height = cursor.height;
|
||||||
|
|
||||||
@@ -46,8 +46,8 @@ pub(crate) fn cursor_from_image(cursor: &CursorImage) -> Id<NSCursor> {
|
|||||||
NSDeviceRGBColorSpace,
|
NSDeviceRGBColorSpace,
|
||||||
width as isize * 4,
|
width as isize * 4,
|
||||||
32,
|
32,
|
||||||
).unwrap()
|
)
|
||||||
};
|
}.ok_or_else(|| os_error!("parent view should be installed in a window"))?;
|
||||||
let bitmap_data = unsafe { slice::from_raw_parts_mut(bitmap.bitmapData(), cursor.rgba.len()) };
|
let bitmap_data = unsafe { slice::from_raw_parts_mut(bitmap.bitmapData(), cursor.rgba.len()) };
|
||||||
bitmap_data.copy_from_slice(&cursor.rgba);
|
bitmap_data.copy_from_slice(&cursor.rgba);
|
||||||
|
|
||||||
@@ -58,17 +58,17 @@ pub(crate) fn cursor_from_image(cursor: &CursorImage) -> Id<NSCursor> {
|
|||||||
|
|
||||||
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() -> Id<NSCursor> {
|
pub(crate) fn default_cursor() -> Retained<NSCursor> {
|
||||||
NSCursor::arrowCursor()
|
NSCursor::arrowCursor()
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe fn try_cursor_from_selector(sel: Sel) -> Option<Id<NSCursor>> {
|
unsafe fn try_cursor_from_selector(sel: Sel) -> Option<Retained<NSCursor>> {
|
||||||
let cls = NSCursor::class();
|
let cls = NSCursor::class();
|
||||||
if cls.responds_to(sel) {
|
if cls.responds_to(sel) {
|
||||||
let cursor: Id<NSCursor> = unsafe { msg_send_id![cls, performSelector: sel] };
|
let cursor: Retained<NSCursor> = unsafe { msg_send_id![cls, performSelector: sel] };
|
||||||
Some(cursor)
|
Some(cursor)
|
||||||
} else {
|
} else {
|
||||||
tracing::warn!("cursor `{sel}` appears to be invalid");
|
tracing::warn!("cursor `{sel}` appears to be invalid");
|
||||||
@@ -83,7 +83,7 @@ macro_rules! def_undocumented_cursor {
|
|||||||
)*} => {$(
|
)*} => {$(
|
||||||
$(#[$($m)*])*
|
$(#[$($m)*])*
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
fn $name() -> Id<NSCursor> {
|
fn $name() -> Retained<NSCursor> {
|
||||||
unsafe { try_cursor_from_selector(sel!($name)).unwrap_or_else(|| default_cursor()) }
|
unsafe { try_cursor_from_selector(sel!($name)).unwrap_or_else(|| default_cursor()) }
|
||||||
}
|
}
|
||||||
)*};
|
)*};
|
||||||
@@ -113,12 +113,15 @@ def_undocumented_cursor!(
|
|||||||
|
|
||||||
// Note that loading `busybutclickable` with this code won't animate
|
// Note that loading `busybutclickable` with this code won't animate
|
||||||
// the frames; instead you'll just get them all in a column.
|
// the frames; instead you'll just get them all in a column.
|
||||||
unsafe fn load_webkit_cursor(name: &NSString) -> Id<NSCursor> {
|
unsafe fn load_webkit_cursor(name: &NSString) -> Retained<NSCursor> {
|
||||||
// Snatch a cursor from WebKit; They fit the style of the native
|
// Snatch a cursor from WebKit; They fit the style of the native
|
||||||
// cursors, and will seem completely standard to macOS users.
|
// cursors, and will seem completely standard to macOS users.
|
||||||
//
|
//
|
||||||
// https://stackoverflow.com/a/21786835/5435443
|
// https://stackoverflow.com/a/21786835/5435443
|
||||||
let root = ns_string!("/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/Resources/cursors");
|
let root = ns_string!(
|
||||||
|
"/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/\
|
||||||
|
HIServices.framework/Versions/A/Resources/cursors"
|
||||||
|
);
|
||||||
let cursor_path = root.stringByAppendingPathComponent(name);
|
let cursor_path = root.stringByAppendingPathComponent(name);
|
||||||
|
|
||||||
let pdf_path = cursor_path.stringByAppendingPathComponent(ns_string!("cursor.pdf"));
|
let pdf_path = cursor_path.stringByAppendingPathComponent(ns_string!("cursor.pdf"));
|
||||||
@@ -126,7 +129,7 @@ unsafe fn load_webkit_cursor(name: &NSString) -> Id<NSCursor> {
|
|||||||
|
|
||||||
// TODO: Handle PLists better
|
// TODO: Handle PLists better
|
||||||
let info_path = cursor_path.stringByAppendingPathComponent(ns_string!("info.plist"));
|
let info_path = cursor_path.stringByAppendingPathComponent(ns_string!("info.plist"));
|
||||||
let info: Id<NSDictionary<NSObject, NSObject>> = unsafe {
|
let info: Retained<NSDictionary<NSObject, NSObject>> = unsafe {
|
||||||
msg_send_id![
|
msg_send_id![
|
||||||
<NSDictionary<NSObject, NSObject>>::class(),
|
<NSDictionary<NSObject, NSObject>>::class(),
|
||||||
dictionaryWithContentsOfFile: &*info_path,
|
dictionaryWithContentsOfFile: &*info_path,
|
||||||
@@ -153,26 +156,26 @@ unsafe fn load_webkit_cursor(name: &NSString) -> Id<NSCursor> {
|
|||||||
NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot)
|
NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn webkit_move() -> Id<NSCursor> {
|
fn webkit_move() -> Retained<NSCursor> {
|
||||||
unsafe { load_webkit_cursor(ns_string!("move")) }
|
unsafe { load_webkit_cursor(ns_string!("move")) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn webkit_cell() -> Id<NSCursor> {
|
fn webkit_cell() -> Retained<NSCursor> {
|
||||||
unsafe { load_webkit_cursor(ns_string!("cell")) }
|
unsafe { load_webkit_cursor(ns_string!("cell")) }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn invisible_cursor() -> Id<NSCursor> {
|
pub(crate) fn invisible_cursor() -> Retained<NSCursor> {
|
||||||
// 16x16 GIF data for invisible cursor
|
// 16x16 GIF data for invisible cursor
|
||||||
// You can reproduce this via ImageMagick.
|
// You can reproduce this via ImageMagick.
|
||||||
// $ convert -size 16x16 xc:none cursor.gif
|
// $ convert -size 16x16 xc:none cursor.gif
|
||||||
static CURSOR_BYTES: &[u8] = &[
|
static CURSOR_BYTES: &[u8] = &[
|
||||||
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x10, 0x00, 0x10, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00,
|
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x10, 0x00, 0x10, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x00,
|
||||||
0x00, 0x00, 0x00, 0x00, 0x21, 0xF9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00,
|
0x00, 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00,
|
||||||
0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x0E, 0x84, 0x8F, 0xA9, 0xCB, 0xED, 0x0F,
|
0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x0e, 0x84, 0x8f, 0xa9, 0xcb, 0xed, 0x0f,
|
||||||
0xA3, 0x9C, 0xB4, 0xDA, 0x8B, 0xB3, 0x3E, 0x05, 0x00, 0x3B,
|
0xa3, 0x9c, 0xb4, 0xda, 0x8b, 0xb3, 0x3e, 0x05, 0x00, 0x3b,
|
||||||
];
|
];
|
||||||
|
|
||||||
fn new_invisible() -> Id<NSCursor> {
|
fn new_invisible() -> Retained<NSCursor> {
|
||||||
// TODO: Consider using `dataWithBytesNoCopy:`
|
// TODO: Consider using `dataWithBytesNoCopy:`
|
||||||
let data = NSData::with_bytes(CURSOR_BYTES);
|
let data = NSData::with_bytes(CURSOR_BYTES);
|
||||||
let image = NSImage::initWithData(NSImage::alloc(), &data).unwrap();
|
let image = NSImage::initWithData(NSImage::alloc(), &data).unwrap();
|
||||||
@@ -182,13 +185,10 @@ pub(crate) fn invisible_cursor() -> Id<NSCursor> {
|
|||||||
|
|
||||||
// Cache this for efficiency
|
// Cache this for efficiency
|
||||||
static CURSOR: OnceLock<CustomCursor> = OnceLock::new();
|
static CURSOR: OnceLock<CustomCursor> = OnceLock::new();
|
||||||
CURSOR
|
CURSOR.get_or_init(|| CustomCursor(new_invisible())).0.clone()
|
||||||
.get_or_init(|| CustomCursor(new_invisible()))
|
|
||||||
.0
|
|
||||||
.clone()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn cursor_from_icon(icon: CursorIcon) -> Id<NSCursor> {
|
pub(crate) fn cursor_from_icon(icon: CursorIcon) -> Retained<NSCursor> {
|
||||||
match icon {
|
match icon {
|
||||||
CursorIcon::Default => default_cursor(),
|
CursorIcon::Default => default_cursor(),
|
||||||
CursorIcon::Pointer => NSCursor::pointingHandCursor(),
|
CursorIcon::Pointer => NSCursor::pointingHandCursor(),
|
||||||
@@ -1,25 +1,17 @@
|
|||||||
use std::ffi::c_void;
|
use std::ffi::c_void;
|
||||||
|
|
||||||
use core_foundation::{
|
use core_foundation::base::CFRelease;
|
||||||
base::CFRelease,
|
use core_foundation::data::{CFDataGetBytePtr, CFDataRef};
|
||||||
data::{CFDataGetBytePtr, CFDataRef},
|
use objc2::rc::Retained;
|
||||||
};
|
use objc2_app_kit::{NSEvent, NSEventModifierFlags, NSEventSubtype, NSEventType};
|
||||||
use icrate::AppKit::{
|
use objc2_foundation::{run_on_main, NSPoint};
|
||||||
NSEvent, NSEventModifierFlagCommand, NSEventModifierFlagControl, NSEventModifierFlagOption,
|
|
||||||
NSEventModifierFlagShift, NSEventModifierFlags, NSEventSubtypeWindowExposed,
|
|
||||||
NSEventTypeApplicationDefined,
|
|
||||||
};
|
|
||||||
use icrate::Foundation::{MainThreadMarker, NSPoint};
|
|
||||||
use objc2::rc::Id;
|
|
||||||
use smol_str::SmolStr;
|
use smol_str::SmolStr;
|
||||||
|
|
||||||
use crate::{
|
use super::ffi;
|
||||||
event::{ElementState, KeyEvent, Modifiers},
|
use crate::event::{ElementState, KeyEvent, Modifiers};
|
||||||
keyboard::{
|
use crate::keyboard::{
|
||||||
Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey,
|
Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey, NativeKeyCode,
|
||||||
NativeKeyCode, PhysicalKey,
|
PhysicalKey,
|
||||||
},
|
|
||||||
platform_impl::platform::ffi,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
@@ -48,7 +40,7 @@ pub fn get_modifierless_char(scancode: u16) -> Key {
|
|||||||
}
|
}
|
||||||
layout = CFDataGetBytePtr(layout_data as CFDataRef) as *const ffi::UCKeyboardLayout;
|
layout = CFDataGetBytePtr(layout_data as CFDataRef) as *const ffi::UCKeyboardLayout;
|
||||||
}
|
}
|
||||||
let keyboard_type = MainThreadMarker::run_on_main(|_mtm| unsafe { ffi::LMGetKbdType() });
|
let keyboard_type = run_on_main(|_mtm| unsafe { ffi::LMGetKbdType() });
|
||||||
|
|
||||||
let mut result_len = 0;
|
let mut result_len = 0;
|
||||||
let mut dead_keys = 0;
|
let mut dead_keys = 0;
|
||||||
@@ -71,10 +63,7 @@ pub fn get_modifierless_char(scancode: u16) -> Key {
|
|||||||
CFRelease(input_source as *mut c_void);
|
CFRelease(input_source as *mut c_void);
|
||||||
}
|
}
|
||||||
if translate_result != 0 {
|
if translate_result != 0 {
|
||||||
tracing::error!(
|
tracing::error!("`UCKeyTranslate` returned with the non-zero value: {}", translate_result);
|
||||||
"`UCKeyTranslate` returned with the non-zero value: {}",
|
|
||||||
translate_result
|
|
||||||
);
|
|
||||||
return Key::Unidentified(NativeKey::MacOS(scancode));
|
return Key::Unidentified(NativeKey::MacOS(scancode));
|
||||||
}
|
}
|
||||||
if result_len == 0 {
|
if result_len == 0 {
|
||||||
@@ -103,17 +92,12 @@ fn get_logical_key_char(ns_event: &NSEvent, modifierless_chars: &str) -> Key {
|
|||||||
/// Create `KeyEvent` for the given `NSEvent`.
|
/// Create `KeyEvent` for the given `NSEvent`.
|
||||||
///
|
///
|
||||||
/// This function shouldn't be called when the IME input is in process.
|
/// This function shouldn't be called when the IME input is in process.
|
||||||
pub(crate) fn create_key_event(
|
pub(crate) fn create_key_event(ns_event: &NSEvent, is_press: bool, is_repeat: bool) -> KeyEvent {
|
||||||
ns_event: &NSEvent,
|
|
||||||
is_press: bool,
|
|
||||||
is_repeat: bool,
|
|
||||||
key_override: Option<PhysicalKey>,
|
|
||||||
) -> KeyEvent {
|
|
||||||
use ElementState::{Pressed, Released};
|
use ElementState::{Pressed, Released};
|
||||||
let state = if is_press { Pressed } else { Released };
|
let state = if is_press { Pressed } else { Released };
|
||||||
|
|
||||||
let scancode = unsafe { ns_event.keyCode() };
|
let scancode = unsafe { ns_event.keyCode() };
|
||||||
let mut physical_key = key_override.unwrap_or_else(|| scancode_to_physicalkey(scancode as u32));
|
let mut physical_key = scancode_to_physicalkey(scancode as u32);
|
||||||
|
|
||||||
// NOTE: The logical key should heed both SHIFT and ALT if possible.
|
// NOTE: The logical key should heed both SHIFT and ALT if possible.
|
||||||
// For instance:
|
// For instance:
|
||||||
@@ -122,21 +106,15 @@ pub(crate) fn create_key_event(
|
|||||||
// * Pressing CTRL SHIFT A: logical key should also be "A"
|
// * Pressing CTRL SHIFT A: logical key should also be "A"
|
||||||
// This is not easy to tease out of `NSEvent`, but we do our best.
|
// This is not easy to tease out of `NSEvent`, but we do our best.
|
||||||
|
|
||||||
let text_with_all_modifiers: Option<SmolStr> = if key_override.is_some() {
|
let characters = unsafe { ns_event.characters() }.map(|s| s.to_string()).unwrap_or_default();
|
||||||
|
let text_with_all_modifiers = if characters.is_empty() {
|
||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
let characters = unsafe { ns_event.characters() }
|
if matches!(physical_key, PhysicalKey::Unidentified(_)) {
|
||||||
.map(|s| s.to_string())
|
// The key may be one of the funky function keys
|
||||||
.unwrap_or_default();
|
physical_key = extra_function_key_to_code(scancode, &characters);
|
||||||
if characters.is_empty() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
if matches!(physical_key, PhysicalKey::Unidentified(_)) {
|
|
||||||
// The key may be one of the funky function keys
|
|
||||||
physical_key = extra_function_key_to_code(scancode, &characters);
|
|
||||||
}
|
|
||||||
Some(SmolStr::new(characters))
|
|
||||||
}
|
}
|
||||||
|
Some(SmolStr::new(characters))
|
||||||
};
|
};
|
||||||
|
|
||||||
let key_from_code = code_to_key(physical_key, scancode);
|
let key_from_code = code_to_key(physical_key, scancode);
|
||||||
@@ -145,8 +123,8 @@ pub(crate) fn create_key_event(
|
|||||||
let key_without_modifiers = get_modifierless_char(scancode);
|
let key_without_modifiers = get_modifierless_char(scancode);
|
||||||
|
|
||||||
let modifiers = unsafe { ns_event.modifierFlags() };
|
let modifiers = unsafe { ns_event.modifierFlags() };
|
||||||
let has_ctrl = flags_contains(modifiers, NSEventModifierFlagControl);
|
let has_ctrl = modifiers.contains(NSEventModifierFlags::NSEventModifierFlagControl);
|
||||||
let has_cmd = flags_contains(modifiers, NSEventModifierFlagCommand);
|
let has_cmd = modifiers.contains(NSEventModifierFlags::NSEventModifierFlagCommand);
|
||||||
|
|
||||||
let logical_key = match text_with_all_modifiers.as_ref() {
|
let logical_key = match text_with_all_modifiers.as_ref() {
|
||||||
// Only checking for ctrl and cmd here, not checking for alt because we DO want to
|
// Only checking for ctrl and cmd here, not checking for alt because we DO want to
|
||||||
@@ -157,7 +135,7 @@ pub(crate) fn create_key_event(
|
|||||||
Some(text) if !has_ctrl && !has_cmd => {
|
Some(text) if !has_ctrl && !has_cmd => {
|
||||||
// Character heeding both SHIFT and ALT.
|
// Character heeding both SHIFT and ALT.
|
||||||
Key::Character(text.clone())
|
Key::Character(text.clone())
|
||||||
}
|
},
|
||||||
|
|
||||||
_ => match key_without_modifiers.as_ref() {
|
_ => match key_without_modifiers.as_ref() {
|
||||||
// Character heeding just SHIFT, ignoring ALT.
|
// Character heeding just SHIFT, ignoring ALT.
|
||||||
@@ -173,11 +151,7 @@ pub(crate) fn create_key_event(
|
|||||||
(key_from_code.clone(), key_from_code)
|
(key_from_code.clone(), key_from_code)
|
||||||
};
|
};
|
||||||
|
|
||||||
let text = if is_press {
|
let text = if is_press { logical_key.to_text().map(SmolStr::new) } else { None };
|
||||||
logical_key.to_text().map(SmolStr::new)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let location = code_to_location(physical_key);
|
let location = code_to_location(physical_key);
|
||||||
|
|
||||||
@@ -188,10 +162,7 @@ pub(crate) fn create_key_event(
|
|||||||
repeat: is_repeat,
|
repeat: is_repeat,
|
||||||
state,
|
state,
|
||||||
text,
|
text,
|
||||||
platform_specific: KeyEventExtra {
|
platform_specific: KeyEventExtra { text_with_all_modifiers, key_without_modifiers },
|
||||||
text_with_all_modifiers,
|
|
||||||
key_without_modifiers,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,25 +286,21 @@ pub fn extra_function_key_to_code(scancode: u16, string: &str) -> PhysicalKey {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The values are from the https://github.com/apple-oss-distributions/IOHIDFamily/blob/19666c840a6d896468416ff0007040a10b7b46b8/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h#L258-L259
|
// The values are from the https://github.com/apple-oss-distributions/IOHIDFamily/blob/19666c840a6d896468416ff0007040a10b7b46b8/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h#L258-L259
|
||||||
const NX_DEVICELCTLKEYMASK: NSEventModifierFlags = 0x00000001;
|
const NX_DEVICELCTLKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000001);
|
||||||
const NX_DEVICELSHIFTKEYMASK: NSEventModifierFlags = 0x00000002;
|
const NX_DEVICELSHIFTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000002);
|
||||||
const NX_DEVICERSHIFTKEYMASK: NSEventModifierFlags = 0x00000004;
|
const NX_DEVICERSHIFTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000004);
|
||||||
const NX_DEVICELCMDKEYMASK: NSEventModifierFlags = 0x00000008;
|
const NX_DEVICELCMDKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000008);
|
||||||
const NX_DEVICERCMDKEYMASK: NSEventModifierFlags = 0x00000010;
|
const NX_DEVICERCMDKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000010);
|
||||||
const NX_DEVICELALTKEYMASK: NSEventModifierFlags = 0x00000020;
|
const NX_DEVICELALTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000020);
|
||||||
const NX_DEVICERALTKEYMASK: NSEventModifierFlags = 0x00000040;
|
const NX_DEVICERALTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000040);
|
||||||
const NX_DEVICERCTLKEYMASK: NSEventModifierFlags = 0x00002000;
|
const NX_DEVICERCTLKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00002000);
|
||||||
|
|
||||||
pub(super) fn flags_contains(flags: NSEventModifierFlags, value: NSEventModifierFlags) -> bool {
|
|
||||||
flags & value == value
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn lalt_pressed(event: &NSEvent) -> bool {
|
pub(super) fn lalt_pressed(event: &NSEvent) -> bool {
|
||||||
flags_contains(unsafe { event.modifierFlags() }, NX_DEVICELALTKEYMASK)
|
unsafe { event.modifierFlags() }.contains(NX_DEVICELALTKEYMASK)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn ralt_pressed(event: &NSEvent) -> bool {
|
pub(super) fn ralt_pressed(event: &NSEvent) -> bool {
|
||||||
flags_contains(unsafe { event.modifierFlags() }, NX_DEVICERALTKEYMASK)
|
unsafe { event.modifierFlags() }.contains(NX_DEVICERALTKEYMASK)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn event_mods(event: &NSEvent) -> Modifiers {
|
pub(super) fn event_mods(event: &NSEvent) -> Modifiers {
|
||||||
@@ -341,74 +308,42 @@ pub(super) fn event_mods(event: &NSEvent) -> Modifiers {
|
|||||||
let mut state = ModifiersState::empty();
|
let mut state = ModifiersState::empty();
|
||||||
let mut pressed_mods = ModifiersKeys::empty();
|
let mut pressed_mods = ModifiersKeys::empty();
|
||||||
|
|
||||||
state.set(
|
state
|
||||||
ModifiersState::SHIFT,
|
.set(ModifiersState::SHIFT, flags.contains(NSEventModifierFlags::NSEventModifierFlagShift));
|
||||||
flags_contains(flags, NSEventModifierFlagShift),
|
pressed_mods.set(ModifiersKeys::LSHIFT, flags.contains(NX_DEVICELSHIFTKEYMASK));
|
||||||
);
|
pressed_mods.set(ModifiersKeys::RSHIFT, flags.contains(NX_DEVICERSHIFTKEYMASK));
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::LSHIFT,
|
|
||||||
flags_contains(flags, NX_DEVICELSHIFTKEYMASK),
|
|
||||||
);
|
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::RSHIFT,
|
|
||||||
flags_contains(flags, NX_DEVICERSHIFTKEYMASK),
|
|
||||||
);
|
|
||||||
|
|
||||||
state.set(
|
state.set(
|
||||||
ModifiersState::CONTROL,
|
ModifiersState::CONTROL,
|
||||||
flags_contains(flags, NSEventModifierFlagControl),
|
flags.contains(NSEventModifierFlags::NSEventModifierFlagControl),
|
||||||
);
|
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::LCONTROL,
|
|
||||||
flags_contains(flags, NX_DEVICELCTLKEYMASK),
|
|
||||||
);
|
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::RCONTROL,
|
|
||||||
flags_contains(flags, NX_DEVICERCTLKEYMASK),
|
|
||||||
);
|
);
|
||||||
|
pressed_mods.set(ModifiersKeys::LCONTROL, flags.contains(NX_DEVICELCTLKEYMASK));
|
||||||
|
pressed_mods.set(ModifiersKeys::RCONTROL, flags.contains(NX_DEVICERCTLKEYMASK));
|
||||||
|
|
||||||
state.set(
|
state.set(ModifiersState::ALT, flags.contains(NSEventModifierFlags::NSEventModifierFlagOption));
|
||||||
ModifiersState::ALT,
|
pressed_mods.set(ModifiersKeys::LALT, flags.contains(NX_DEVICELALTKEYMASK));
|
||||||
flags_contains(flags, NSEventModifierFlagOption),
|
pressed_mods.set(ModifiersKeys::RALT, flags.contains(NX_DEVICERALTKEYMASK));
|
||||||
);
|
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::LALT,
|
|
||||||
flags_contains(flags, NX_DEVICELALTKEYMASK),
|
|
||||||
);
|
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::RALT,
|
|
||||||
flags_contains(flags, NX_DEVICERALTKEYMASK),
|
|
||||||
);
|
|
||||||
|
|
||||||
state.set(
|
state.set(
|
||||||
ModifiersState::SUPER,
|
ModifiersState::SUPER,
|
||||||
flags_contains(flags, NSEventModifierFlagCommand),
|
flags.contains(NSEventModifierFlags::NSEventModifierFlagCommand),
|
||||||
);
|
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::LSUPER,
|
|
||||||
flags_contains(flags, NX_DEVICELCMDKEYMASK),
|
|
||||||
);
|
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::RSUPER,
|
|
||||||
flags_contains(flags, NX_DEVICERCMDKEYMASK),
|
|
||||||
);
|
);
|
||||||
|
pressed_mods.set(ModifiersKeys::LSUPER, flags.contains(NX_DEVICELCMDKEYMASK));
|
||||||
|
pressed_mods.set(ModifiersKeys::RSUPER, flags.contains(NX_DEVICERCMDKEYMASK));
|
||||||
|
|
||||||
Modifiers {
|
Modifiers { state, pressed_mods }
|
||||||
state,
|
|
||||||
pressed_mods,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn dummy_event() -> Option<Id<NSEvent>> {
|
pub(super) fn dummy_event() -> Option<Retained<NSEvent>> {
|
||||||
unsafe {
|
unsafe {
|
||||||
NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
|
NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
|
||||||
NSEventTypeApplicationDefined,
|
NSEventType::ApplicationDefined,
|
||||||
NSPoint::new(0.0, 0.0),
|
NSPoint::new(0.0, 0.0),
|
||||||
0, // Empty NSEventModifierFlags
|
NSEventModifierFlags(0),
|
||||||
0.0,
|
0.0,
|
||||||
0,
|
0,
|
||||||
None,
|
None,
|
||||||
NSEventSubtypeWindowExposed,
|
NSEventSubtype::WindowExposed.0,
|
||||||
0,
|
0,
|
||||||
0,
|
0,
|
||||||
)
|
)
|
||||||
@@ -432,6 +367,7 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
|
|||||||
KeyCode::KeyX => Some(0x07),
|
KeyCode::KeyX => Some(0x07),
|
||||||
KeyCode::KeyC => Some(0x08),
|
KeyCode::KeyC => Some(0x08),
|
||||||
KeyCode::KeyV => Some(0x09),
|
KeyCode::KeyV => Some(0x09),
|
||||||
|
KeyCode::IntlBackslash => Some(0x0a),
|
||||||
KeyCode::KeyB => Some(0x0b),
|
KeyCode::KeyB => Some(0x0b),
|
||||||
KeyCode::KeyQ => Some(0x0c),
|
KeyCode::KeyQ => Some(0x0c),
|
||||||
KeyCode::KeyW => Some(0x0d),
|
KeyCode::KeyW => Some(0x0d),
|
||||||
@@ -477,18 +413,21 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
|
|||||||
KeyCode::SuperRight => Some(0x36),
|
KeyCode::SuperRight => Some(0x36),
|
||||||
KeyCode::SuperLeft => Some(0x37),
|
KeyCode::SuperLeft => Some(0x37),
|
||||||
KeyCode::ShiftLeft => Some(0x38),
|
KeyCode::ShiftLeft => Some(0x38),
|
||||||
|
KeyCode::CapsLock => Some(0x39),
|
||||||
KeyCode::AltLeft => Some(0x3a),
|
KeyCode::AltLeft => Some(0x3a),
|
||||||
KeyCode::ControlLeft => Some(0x3b),
|
KeyCode::ControlLeft => Some(0x3b),
|
||||||
KeyCode::ShiftRight => Some(0x3c),
|
KeyCode::ShiftRight => Some(0x3c),
|
||||||
KeyCode::AltRight => Some(0x3d),
|
KeyCode::AltRight => Some(0x3d),
|
||||||
KeyCode::ControlRight => Some(0x3e),
|
KeyCode::ControlRight => Some(0x3e),
|
||||||
|
KeyCode::Fn => Some(0x3f),
|
||||||
KeyCode::F17 => Some(0x40),
|
KeyCode::F17 => Some(0x40),
|
||||||
KeyCode::NumpadDecimal => Some(0x41),
|
KeyCode::NumpadDecimal => Some(0x41),
|
||||||
KeyCode::NumpadMultiply => Some(0x43),
|
KeyCode::NumpadMultiply => Some(0x43),
|
||||||
KeyCode::NumpadAdd => Some(0x45),
|
KeyCode::NumpadAdd => Some(0x45),
|
||||||
KeyCode::NumLock => Some(0x47),
|
KeyCode::NumLock => Some(0x47),
|
||||||
KeyCode::AudioVolumeUp => Some(0x49),
|
KeyCode::AudioVolumeUp => Some(0x48),
|
||||||
KeyCode::AudioVolumeDown => Some(0x4a),
|
KeyCode::AudioVolumeDown => Some(0x49),
|
||||||
|
KeyCode::AudioVolumeMute => Some(0x4a),
|
||||||
KeyCode::NumpadDivide => Some(0x4b),
|
KeyCode::NumpadDivide => Some(0x4b),
|
||||||
KeyCode::NumpadEnter => Some(0x4c),
|
KeyCode::NumpadEnter => Some(0x4c),
|
||||||
KeyCode::NumpadSubtract => Some(0x4e),
|
KeyCode::NumpadSubtract => Some(0x4e),
|
||||||
@@ -507,17 +446,22 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
|
|||||||
KeyCode::Numpad8 => Some(0x5b),
|
KeyCode::Numpad8 => Some(0x5b),
|
||||||
KeyCode::Numpad9 => Some(0x5c),
|
KeyCode::Numpad9 => Some(0x5c),
|
||||||
KeyCode::IntlYen => Some(0x5d),
|
KeyCode::IntlYen => Some(0x5d),
|
||||||
|
KeyCode::IntlRo => Some(0x5e),
|
||||||
|
KeyCode::NumpadComma => Some(0x5f),
|
||||||
KeyCode::F5 => Some(0x60),
|
KeyCode::F5 => Some(0x60),
|
||||||
KeyCode::F6 => Some(0x61),
|
KeyCode::F6 => Some(0x61),
|
||||||
KeyCode::F7 => Some(0x62),
|
KeyCode::F7 => Some(0x62),
|
||||||
KeyCode::F3 => Some(0x63),
|
KeyCode::F3 => Some(0x63),
|
||||||
KeyCode::F8 => Some(0x64),
|
KeyCode::F8 => Some(0x64),
|
||||||
KeyCode::F9 => Some(0x65),
|
KeyCode::F9 => Some(0x65),
|
||||||
|
KeyCode::Lang2 => Some(0x66),
|
||||||
KeyCode::F11 => Some(0x67),
|
KeyCode::F11 => Some(0x67),
|
||||||
|
KeyCode::Lang1 => Some(0x68),
|
||||||
KeyCode::F13 => Some(0x69),
|
KeyCode::F13 => Some(0x69),
|
||||||
KeyCode::F16 => Some(0x6a),
|
KeyCode::F16 => Some(0x6a),
|
||||||
KeyCode::F14 => Some(0x6b),
|
KeyCode::F14 => Some(0x6b),
|
||||||
KeyCode::F10 => Some(0x6d),
|
KeyCode::F10 => Some(0x6d),
|
||||||
|
KeyCode::ContextMenu => Some(0x6e),
|
||||||
KeyCode::F12 => Some(0x6f),
|
KeyCode::F12 => Some(0x6f),
|
||||||
KeyCode::F15 => Some(0x71),
|
KeyCode::F15 => Some(0x71),
|
||||||
KeyCode::Insert => Some(0x72),
|
KeyCode::Insert => Some(0x72),
|
||||||
@@ -533,11 +477,26 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
|
|||||||
KeyCode::ArrowRight => Some(0x7c),
|
KeyCode::ArrowRight => Some(0x7c),
|
||||||
KeyCode::ArrowDown => Some(0x7d),
|
KeyCode::ArrowDown => Some(0x7d),
|
||||||
KeyCode::ArrowUp => Some(0x7e),
|
KeyCode::ArrowUp => Some(0x7e),
|
||||||
|
KeyCode::Power => Some(0x7f),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
pub(crate) 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 {
|
PhysicalKey::Code(match scancode {
|
||||||
0x00 => KeyCode::KeyA,
|
0x00 => KeyCode::KeyA,
|
||||||
0x01 => KeyCode::KeyS,
|
0x01 => KeyCode::KeyS,
|
||||||
@@ -549,7 +508,11 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
0x07 => KeyCode::KeyX,
|
0x07 => KeyCode::KeyX,
|
||||||
0x08 => KeyCode::KeyC,
|
0x08 => KeyCode::KeyC,
|
||||||
0x09 => KeyCode::KeyV,
|
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,
|
0x0b => KeyCode::KeyB,
|
||||||
0x0c => KeyCode::KeyQ,
|
0x0c => KeyCode::KeyQ,
|
||||||
0x0d => KeyCode::KeyW,
|
0x0d => KeyCode::KeyW,
|
||||||
@@ -591,7 +554,7 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
0x31 => KeyCode::Space,
|
0x31 => KeyCode::Space,
|
||||||
0x32 => KeyCode::Backquote,
|
0x32 => KeyCode::Backquote,
|
||||||
0x33 => KeyCode::Backspace,
|
0x33 => KeyCode::Backspace,
|
||||||
//0x34 => unknown,
|
// 0x34 => unknown, // kVK_Powerbook_KeypadEnter
|
||||||
0x35 => KeyCode::Escape,
|
0x35 => KeyCode::Escape,
|
||||||
0x36 => KeyCode::SuperRight,
|
0x36 => KeyCode::SuperRight,
|
||||||
0x37 => KeyCode::SuperLeft,
|
0x37 => KeyCode::SuperLeft,
|
||||||
@@ -605,22 +568,18 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
0x3f => KeyCode::Fn,
|
0x3f => KeyCode::Fn,
|
||||||
0x40 => KeyCode::F17,
|
0x40 => KeyCode::F17,
|
||||||
0x41 => KeyCode::NumpadDecimal,
|
0x41 => KeyCode::NumpadDecimal,
|
||||||
//0x42 -> unknown,
|
// 0x42 -> unknown,
|
||||||
0x43 => KeyCode::NumpadMultiply,
|
0x43 => KeyCode::NumpadMultiply,
|
||||||
//0x44 => unknown,
|
// 0x44 => unknown,
|
||||||
0x45 => KeyCode::NumpadAdd,
|
0x45 => KeyCode::NumpadAdd,
|
||||||
//0x46 => unknown,
|
// 0x46 => unknown,
|
||||||
0x47 => KeyCode::NumLock,
|
0x47 => KeyCode::NumLock, // kVK_ANSI_KeypadClear
|
||||||
//0x48 => KeyCode::NumpadClear,
|
0x48 => KeyCode::AudioVolumeUp,
|
||||||
|
0x49 => KeyCode::AudioVolumeDown,
|
||||||
// TODO: (Artur) for me, kVK_VolumeUp is 0x48
|
0x4a => KeyCode::AudioVolumeMute,
|
||||||
// macOS 10.11
|
|
||||||
// /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h
|
|
||||||
0x49 => KeyCode::AudioVolumeUp,
|
|
||||||
0x4a => KeyCode::AudioVolumeDown,
|
|
||||||
0x4b => KeyCode::NumpadDivide,
|
0x4b => KeyCode::NumpadDivide,
|
||||||
0x4c => KeyCode::NumpadEnter,
|
0x4c => KeyCode::NumpadEnter,
|
||||||
//0x4d => unknown,
|
// 0x4d => unknown,
|
||||||
0x4e => KeyCode::NumpadSubtract,
|
0x4e => KeyCode::NumpadSubtract,
|
||||||
0x4f => KeyCode::F18,
|
0x4f => KeyCode::F18,
|
||||||
0x50 => KeyCode::F19,
|
0x50 => KeyCode::F19,
|
||||||
@@ -637,25 +596,25 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
0x5b => KeyCode::Numpad8,
|
0x5b => KeyCode::Numpad8,
|
||||||
0x5c => KeyCode::Numpad9,
|
0x5c => KeyCode::Numpad9,
|
||||||
0x5d => KeyCode::IntlYen,
|
0x5d => KeyCode::IntlYen,
|
||||||
//0x5e => JIS Ro,
|
0x5e => KeyCode::IntlRo,
|
||||||
//0x5f => unknown,
|
0x5f => KeyCode::NumpadComma,
|
||||||
0x60 => KeyCode::F5,
|
0x60 => KeyCode::F5,
|
||||||
0x61 => KeyCode::F6,
|
0x61 => KeyCode::F6,
|
||||||
0x62 => KeyCode::F7,
|
0x62 => KeyCode::F7,
|
||||||
0x63 => KeyCode::F3,
|
0x63 => KeyCode::F3,
|
||||||
0x64 => KeyCode::F8,
|
0x64 => KeyCode::F8,
|
||||||
0x65 => KeyCode::F9,
|
0x65 => KeyCode::F9,
|
||||||
//0x66 => JIS Eisuu (macOS),
|
0x66 => KeyCode::Lang2,
|
||||||
0x67 => KeyCode::F11,
|
0x67 => KeyCode::F11,
|
||||||
//0x68 => JIS Kanna (macOS),
|
0x68 => KeyCode::Lang1,
|
||||||
0x69 => KeyCode::F13,
|
0x69 => KeyCode::F13,
|
||||||
0x6a => KeyCode::F16,
|
0x6a => KeyCode::F16,
|
||||||
0x6b => KeyCode::F14,
|
0x6b => KeyCode::F14,
|
||||||
//0x6c => unknown,
|
// 0x6c => unknown,
|
||||||
0x6d => KeyCode::F10,
|
0x6d => KeyCode::F10,
|
||||||
//0x6e => unknown,
|
0x6e => KeyCode::ContextMenu,
|
||||||
0x6f => KeyCode::F12,
|
0x6f => KeyCode::F12,
|
||||||
//0x70 => unknown,
|
// 0x70 => unknown,
|
||||||
0x71 => KeyCode::F15,
|
0x71 => KeyCode::F15,
|
||||||
0x72 => KeyCode::Insert,
|
0x72 => KeyCode::Insert,
|
||||||
0x73 => KeyCode::Home,
|
0x73 => KeyCode::Home,
|
||||||
@@ -670,11 +629,7 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
0x7c => KeyCode::ArrowRight,
|
0x7c => KeyCode::ArrowRight,
|
||||||
0x7d => KeyCode::ArrowDown,
|
0x7d => KeyCode::ArrowDown,
|
||||||
0x7e => KeyCode::ArrowUp,
|
0x7e => KeyCode::ArrowUp,
|
||||||
//0x7f => unknown,
|
0x7f => KeyCode::Power, // On 10.7 and 10.8 only
|
||||||
|
|
||||||
// 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,
|
|
||||||
_ => return PhysicalKey::Unidentified(NativeKeyCode::MacOS(scancode as u16)),
|
_ => return PhysicalKey::Unidentified(NativeKeyCode::MacOS(scancode as u16)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
494
src/platform_impl/apple/appkit/event_loop.rs
Normal file
494
src/platform_impl/apple/appkit/event_loop.rs
Normal file
@@ -0,0 +1,494 @@
|
|||||||
|
use std::any::Any;
|
||||||
|
use std::cell::Cell;
|
||||||
|
use std::os::raw::c_void;
|
||||||
|
use std::panic::{catch_unwind, resume_unwind, RefUnwindSafe, UnwindSafe};
|
||||||
|
use std::ptr;
|
||||||
|
use std::rc::{Rc, Weak};
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::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::{msg_send_id, sel, ClassType};
|
||||||
|
use objc2_app_kit::{
|
||||||
|
NSApplication, NSApplicationActivationPolicy, NSApplicationDidFinishLaunchingNotification,
|
||||||
|
NSApplicationWillTerminateNotification, NSWindow,
|
||||||
|
};
|
||||||
|
use objc2_foundation::{MainThreadMarker, NSNotificationCenter, NSObject, NSObjectProtocol};
|
||||||
|
use rwh_06::HasDisplayHandle;
|
||||||
|
|
||||||
|
use super::super::notification_center::create_observer;
|
||||||
|
use super::app::WinitApplication;
|
||||||
|
use super::app_state::AppState;
|
||||||
|
use super::cursor::CustomCursor;
|
||||||
|
use super::event::dummy_event;
|
||||||
|
use super::monitor;
|
||||||
|
use super::observer::setup_control_flow_observers;
|
||||||
|
use crate::application::ApplicationHandler;
|
||||||
|
use crate::error::{EventLoopError, RequestError};
|
||||||
|
use crate::event_loop::{
|
||||||
|
ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents,
|
||||||
|
EventLoopProxy as CoreEventLoopProxy, EventLoopProxyProvider,
|
||||||
|
OwnedDisplayHandle as CoreOwnedDisplayHandle,
|
||||||
|
};
|
||||||
|
use crate::monitor::MonitorHandle as RootMonitorHandle;
|
||||||
|
use crate::platform::macos::ActivationPolicy;
|
||||||
|
use crate::platform::pump_events::PumpStatus;
|
||||||
|
use crate::platform_impl::Window;
|
||||||
|
use crate::window::{CustomCursor as RootCustomCursor, CustomCursorSource, Theme};
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct PanicInfo {
|
||||||
|
inner: Cell<Option<Box<dyn Any + Send + 'static>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// WARNING:
|
||||||
|
// As long as this struct is used through its `impl`, it is UnwindSafe.
|
||||||
|
// (If `get_mut` is called on `inner`, unwind safety may get broken.)
|
||||||
|
impl UnwindSafe for PanicInfo {}
|
||||||
|
impl RefUnwindSafe for PanicInfo {}
|
||||||
|
impl PanicInfo {
|
||||||
|
pub fn is_panicking(&self) -> bool {
|
||||||
|
let inner = self.inner.take();
|
||||||
|
let result = inner.is_some();
|
||||||
|
self.inner.set(inner);
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Overwrites the current state if the current state is not panicking
|
||||||
|
pub fn set_panic(&self, p: Box<dyn Any + Send + 'static>) {
|
||||||
|
if !self.is_panicking() {
|
||||||
|
self.inner.set(Some(p));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn take(&self) -> Option<Box<dyn Any + Send + 'static>> {
|
||||||
|
self.inner.take()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ActiveEventLoop {
|
||||||
|
pub(super) app_state: Rc<AppState>,
|
||||||
|
pub(super) mtm: MainThreadMarker,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActiveEventLoop {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RootActiveEventLoop for ActiveEventLoop {
|
||||||
|
fn create_proxy(&self) -> CoreEventLoopProxy {
|
||||||
|
CoreEventLoopProxy::new(self.app_state.event_loop_proxy().clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_window(
|
||||||
|
&self,
|
||||||
|
window_attributes: crate::window::WindowAttributes,
|
||||||
|
) -> Result<Box<dyn crate::window::Window>, RequestError> {
|
||||||
|
Ok(Box::new(Window::new(self, window_attributes)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_custom_cursor(
|
||||||
|
&self,
|
||||||
|
source: CustomCursorSource,
|
||||||
|
) -> Result<RootCustomCursor, RequestError> {
|
||||||
|
Ok(RootCustomCursor { inner: CustomCursor::new(source.inner)? })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn available_monitors(&self) -> Box<dyn Iterator<Item = RootMonitorHandle>> {
|
||||||
|
Box::new(monitor::available_monitors().into_iter().map(|inner| RootMonitorHandle { inner }))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn primary_monitor(&self) -> Option<crate::monitor::MonitorHandle> {
|
||||||
|
let monitor = monitor::primary_monitor();
|
||||||
|
Some(RootMonitorHandle { inner: monitor })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn listen_device_events(&self, _allowed: DeviceEvents) {}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||||
|
self.app_state.set_control_flow(control_flow)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn control_flow(&self) -> ControlFlow {
|
||||||
|
self.app_state.control_flow()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exit(&self) {
|
||||||
|
self.app_state.exit()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exiting(&self) -> bool {
|
||||||
|
self.app_state.exiting()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn owned_display_handle(&self) -> CoreOwnedDisplayHandle {
|
||||||
|
CoreOwnedDisplayHandle::new(Arc::new(OwnedDisplayHandle))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rwh_06_handle(&self) -> &dyn rwh_06::HasDisplayHandle {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl rwh_06::HasDisplayHandle for ActiveEventLoop {
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let raw = rwh_06::RawDisplayHandle::AppKit(rwh_06::AppKitDisplayHandle::new());
|
||||||
|
unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct EventLoop {
|
||||||
|
/// 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>,
|
||||||
|
app_state: Rc<AppState>,
|
||||||
|
|
||||||
|
window_target: ActiveEventLoop,
|
||||||
|
panic_info: Rc<PanicInfo>,
|
||||||
|
|
||||||
|
// Since macOS 10.11, we no longer need to remove the observers before they are deallocated;
|
||||||
|
// the system instead cleans it up next time it would have posted a notification to it.
|
||||||
|
//
|
||||||
|
// Though we do still need to keep the observers around to prevent them from being deallocated.
|
||||||
|
_did_finish_launching_observer: Retained<NSObject>,
|
||||||
|
_will_terminate_observer: Retained<NSObject>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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 EventLoop {
|
||||||
|
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 app_state = AppState::setup_global(
|
||||||
|
mtm,
|
||||||
|
activation_policy,
|
||||||
|
attributes.default_menu,
|
||||||
|
attributes.activate_ignoring_other_apps,
|
||||||
|
);
|
||||||
|
|
||||||
|
let center = unsafe { NSNotificationCenter::defaultCenter() };
|
||||||
|
|
||||||
|
let weak_app_state = Rc::downgrade(&app_state);
|
||||||
|
let _did_finish_launching_observer = create_observer(
|
||||||
|
¢er,
|
||||||
|
// `applicationDidFinishLaunching:`
|
||||||
|
unsafe { NSApplicationDidFinishLaunchingNotification },
|
||||||
|
move |notification| {
|
||||||
|
if let Some(app_state) = weak_app_state.upgrade() {
|
||||||
|
app_state.did_finish_launching(notification);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
let weak_app_state = Rc::downgrade(&app_state);
|
||||||
|
let _will_terminate_observer = create_observer(
|
||||||
|
¢er,
|
||||||
|
// `applicationWillTerminate:`
|
||||||
|
unsafe { NSApplicationWillTerminateNotification },
|
||||||
|
move |notification| {
|
||||||
|
if let Some(app_state) = weak_app_state.upgrade() {
|
||||||
|
app_state.will_terminate(notification);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
let panic_info: Rc<PanicInfo> = Default::default();
|
||||||
|
setup_control_flow_observers(mtm, Rc::downgrade(&panic_info));
|
||||||
|
|
||||||
|
Ok(EventLoop {
|
||||||
|
app,
|
||||||
|
app_state: app_state.clone(),
|
||||||
|
window_target: ActiveEventLoop { app_state, mtm },
|
||||||
|
panic_info,
|
||||||
|
_did_finish_launching_observer,
|
||||||
|
_will_terminate_observer,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn window_target(&self) -> &dyn RootActiveEventLoop {
|
||||||
|
&self.window_target
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run_app<A: ApplicationHandler>(mut self, app: A) -> Result<(), EventLoopError> {
|
||||||
|
self.run_app_on_demand(app)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NB: we don't base this on `pump_events` because for `MacOs` we can't support
|
||||||
|
// `pump_events` elegantly (we just ask to run the loop for a "short" amount of
|
||||||
|
// time and so a layered implementation would end up using a lot of CPU due to
|
||||||
|
// redundant wake ups.
|
||||||
|
pub fn run_app_on_demand<A: ApplicationHandler>(
|
||||||
|
&mut self,
|
||||||
|
mut app: A,
|
||||||
|
) -> Result<(), EventLoopError> {
|
||||||
|
self.app_state.clear_exit();
|
||||||
|
self.app_state.set_event_handler(&mut app, || {
|
||||||
|
autoreleasepool(|_| {
|
||||||
|
// clear / normalize pump_events state
|
||||||
|
self.app_state.set_wait_timeout(None);
|
||||||
|
self.app_state.set_stop_before_wait(false);
|
||||||
|
self.app_state.set_stop_after_wait(false);
|
||||||
|
self.app_state.set_stop_on_redraw(false);
|
||||||
|
|
||||||
|
if self.app_state.is_launched() {
|
||||||
|
debug_assert!(!self.app_state.is_running());
|
||||||
|
self.app_state.set_is_running(true);
|
||||||
|
self.app_state.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.app_state.internal_exit()
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pump_app_events<A: ApplicationHandler>(
|
||||||
|
&mut self,
|
||||||
|
timeout: Option<Duration>,
|
||||||
|
mut app: A,
|
||||||
|
) -> PumpStatus {
|
||||||
|
self.app_state.set_event_handler(&mut app, || {
|
||||||
|
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.app_state.is_launched() {
|
||||||
|
debug_assert!(!self.app_state.is_running());
|
||||||
|
|
||||||
|
self.app_state.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.app_state.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.app_state.set_is_running(true);
|
||||||
|
self.app_state.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.app_state.set_wait_timeout(None);
|
||||||
|
self.app_state.set_stop_before_wait(true);
|
||||||
|
},
|
||||||
|
Some(duration) => {
|
||||||
|
self.app_state.set_stop_before_wait(false);
|
||||||
|
let timeout = Instant::now() + duration;
|
||||||
|
self.app_state.set_wait_timeout(Some(timeout));
|
||||||
|
self.app_state.set_stop_after_wait(true);
|
||||||
|
},
|
||||||
|
None => {
|
||||||
|
self.app_state.set_wait_timeout(None);
|
||||||
|
self.app_state.set_stop_before_wait(false);
|
||||||
|
self.app_state.set_stop_after_wait(true);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
self.app_state.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.app_state.exiting() {
|
||||||
|
self.app_state.internal_exit();
|
||||||
|
PumpStatus::Exit(0)
|
||||||
|
} else {
|
||||||
|
PumpStatus::Continue
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct OwnedDisplayHandle;
|
||||||
|
|
||||||
|
impl HasDisplayHandle for OwnedDisplayHandle {
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let raw = rwh_06::RawDisplayHandle::AppKit(rwh_06::AppKitDisplayHandle::new());
|
||||||
|
unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct EventLoopProxy {
|
||||||
|
pub(crate) wake_up: AtomicBool,
|
||||||
|
source: CFRunLoopSourceRef,
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl Send for EventLoopProxy {}
|
||||||
|
unsafe impl Sync for EventLoopProxy {}
|
||||||
|
|
||||||
|
impl Drop for EventLoopProxy {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
CFRelease(self.source as _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopProxy {
|
||||||
|
pub(crate) fn new() -> Self {
|
||||||
|
unsafe {
|
||||||
|
// just wake up the eventloop
|
||||||
|
extern "C" fn event_loop_proxy_handler(_: *const c_void) {}
|
||||||
|
|
||||||
|
// adding a Source to the main CFRunLoop lets us wake it up and
|
||||||
|
// process user events through the normal OS EventLoop mechanisms.
|
||||||
|
let rl = CFRunLoopGetMain();
|
||||||
|
let mut context = CFRunLoopSourceContext {
|
||||||
|
version: 0,
|
||||||
|
info: ptr::null_mut(),
|
||||||
|
retain: None,
|
||||||
|
release: None,
|
||||||
|
copyDescription: None,
|
||||||
|
equal: None,
|
||||||
|
hash: None,
|
||||||
|
schedule: None,
|
||||||
|
cancel: None,
|
||||||
|
perform: event_loop_proxy_handler,
|
||||||
|
};
|
||||||
|
let source = CFRunLoopSourceCreate(ptr::null_mut(), CFIndex::MAX - 1, &mut context);
|
||||||
|
CFRunLoopAddSource(rl, source, kCFRunLoopCommonModes);
|
||||||
|
CFRunLoopWakeUp(rl);
|
||||||
|
|
||||||
|
EventLoopProxy { wake_up: AtomicBool::new(false), source }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopProxyProvider for EventLoopProxy {
|
||||||
|
fn wake_up(&self) {
|
||||||
|
self.wake_up.store(true, AtomicOrdering::Relaxed);
|
||||||
|
unsafe {
|
||||||
|
// Let the main thread know there's a new event.
|
||||||
|
CFRunLoopSourceSignal(self.source);
|
||||||
|
let rl = CFRunLoopGetMain();
|
||||||
|
CFRunLoopWakeUp(rl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,14 +4,14 @@
|
|||||||
|
|
||||||
use std::ffi::c_void;
|
use std::ffi::c_void;
|
||||||
|
|
||||||
use core_foundation::{
|
use core_foundation::array::CFArrayRef;
|
||||||
array::CFArrayRef, dictionary::CFDictionaryRef, string::CFStringRef, uuid::CFUUIDRef,
|
use core_foundation::dictionary::CFDictionaryRef;
|
||||||
};
|
use core_foundation::string::CFStringRef;
|
||||||
use core_graphics::{
|
use core_foundation::uuid::CFUUIDRef;
|
||||||
base::CGError,
|
use core_graphics::base::CGError;
|
||||||
display::{CGDirectDisplayID, CGDisplayConfigRef},
|
use core_graphics::display::{CGDirectDisplayID, CGDisplayConfigRef};
|
||||||
};
|
use objc2::ffi::NSInteger;
|
||||||
use objc2::{ffi::NSInteger, runtime::AnyObject};
|
use objc2::runtime::AnyObject;
|
||||||
|
|
||||||
pub type CGDisplayFadeInterval = f32;
|
pub type CGDisplayFadeInterval = f32;
|
||||||
pub type CGDisplayReservationInterval = f32;
|
pub type CGDisplayReservationInterval = f32;
|
||||||
@@ -1,11 +1,8 @@
|
|||||||
use icrate::AppKit::{
|
use objc2::rc::Retained;
|
||||||
NSApplication, NSEventModifierFlagCommand, NSEventModifierFlagOption, NSEventModifierFlags,
|
|
||||||
NSMenu, NSMenuItem,
|
|
||||||
};
|
|
||||||
use icrate::Foundation::{ns_string, MainThreadMarker, NSProcessInfo, NSString};
|
|
||||||
use objc2::rc::Id;
|
|
||||||
use objc2::runtime::Sel;
|
use objc2::runtime::Sel;
|
||||||
use objc2::sel;
|
use objc2::sel;
|
||||||
|
use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSMenu, NSMenuItem};
|
||||||
|
use objc2_foundation::{ns_string, MainThreadMarker, NSProcessInfo, NSString};
|
||||||
|
|
||||||
struct KeyEquivalent<'a> {
|
struct KeyEquivalent<'a> {
|
||||||
key: &'a NSString,
|
key: &'a NSString,
|
||||||
@@ -23,12 +20,8 @@ pub fn initialize(app: &NSApplication) {
|
|||||||
|
|
||||||
// About menu item
|
// About menu item
|
||||||
let about_item_title = ns_string!("About ").stringByAppendingString(&process_name);
|
let about_item_title = ns_string!("About ").stringByAppendingString(&process_name);
|
||||||
let about_item = menu_item(
|
let about_item =
|
||||||
mtm,
|
menu_item(mtm, &about_item_title, Some(sel!(orderFrontStandardAboutPanel:)), None);
|
||||||
&about_item_title,
|
|
||||||
Some(sel!(orderFrontStandardAboutPanel:)),
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Services menu item
|
// Services menu item
|
||||||
let services_menu = NSMenu::new(mtm);
|
let services_menu = NSMenu::new(mtm);
|
||||||
@@ -44,10 +37,7 @@ pub fn initialize(app: &NSApplication) {
|
|||||||
mtm,
|
mtm,
|
||||||
&hide_item_title,
|
&hide_item_title,
|
||||||
Some(sel!(hide:)),
|
Some(sel!(hide:)),
|
||||||
Some(KeyEquivalent {
|
Some(KeyEquivalent { key: ns_string!("h"), masks: None }),
|
||||||
key: ns_string!("h"),
|
|
||||||
masks: None,
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
// Hide other applications menu item
|
// Hide other applications menu item
|
||||||
@@ -58,18 +48,17 @@ pub fn initialize(app: &NSApplication) {
|
|||||||
Some(sel!(hideOtherApplications:)),
|
Some(sel!(hideOtherApplications:)),
|
||||||
Some(KeyEquivalent {
|
Some(KeyEquivalent {
|
||||||
key: ns_string!("h"),
|
key: ns_string!("h"),
|
||||||
masks: Some(NSEventModifierFlagOption | NSEventModifierFlagCommand),
|
masks: Some(
|
||||||
|
NSEventModifierFlags::NSEventModifierFlagOption
|
||||||
|
| NSEventModifierFlags::NSEventModifierFlagCommand,
|
||||||
|
),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Show applications menu item
|
// Show applications menu item
|
||||||
let show_all_item_title = ns_string!("Show All");
|
let show_all_item_title = ns_string!("Show All");
|
||||||
let show_all_item = menu_item(
|
let show_all_item =
|
||||||
mtm,
|
menu_item(mtm, show_all_item_title, Some(sel!(unhideAllApplications:)), None);
|
||||||
show_all_item_title,
|
|
||||||
Some(sel!(unhideAllApplications:)),
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Separator menu item
|
// Separator menu item
|
||||||
let sep = NSMenuItem::separatorItem(mtm);
|
let sep = NSMenuItem::separatorItem(mtm);
|
||||||
@@ -80,10 +69,7 @@ pub fn initialize(app: &NSApplication) {
|
|||||||
mtm,
|
mtm,
|
||||||
&quit_item_title,
|
&quit_item_title,
|
||||||
Some(sel!(terminate:)),
|
Some(sel!(terminate:)),
|
||||||
Some(KeyEquivalent {
|
Some(KeyEquivalent { key: ns_string!("q"), masks: None }),
|
||||||
key: ns_string!("q"),
|
|
||||||
masks: None,
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
app_menu.addItem(&about_item);
|
app_menu.addItem(&about_item);
|
||||||
@@ -105,7 +91,7 @@ fn menu_item(
|
|||||||
title: &NSString,
|
title: &NSString,
|
||||||
selector: Option<Sel>,
|
selector: Option<Sel>,
|
||||||
key_equivalent: Option<KeyEquivalent<'_>>,
|
key_equivalent: Option<KeyEquivalent<'_>>,
|
||||||
) -> Id<NSMenuItem> {
|
) -> Retained<NSMenuItem> {
|
||||||
let (key, masks) = match key_equivalent {
|
let (key, masks) = match key_equivalent {
|
||||||
Some(ke) => (ke.key, ke.masks),
|
Some(ke) => (ke.key, ke.masks),
|
||||||
None => (ns_string!(""), None),
|
None => (ns_string!(""), None),
|
||||||
27
src/platform_impl/apple/appkit/mod.rs
Normal file
27
src/platform_impl/apple/appkit/mod.rs
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
#[macro_use]
|
||||||
|
mod util;
|
||||||
|
|
||||||
|
mod app;
|
||||||
|
mod app_state;
|
||||||
|
mod cursor;
|
||||||
|
mod event;
|
||||||
|
mod event_loop;
|
||||||
|
mod ffi;
|
||||||
|
mod menu;
|
||||||
|
mod monitor;
|
||||||
|
mod observer;
|
||||||
|
mod view;
|
||||||
|
mod window;
|
||||||
|
mod window_delegate;
|
||||||
|
|
||||||
|
pub(crate) use self::cursor::CustomCursor as PlatformCustomCursor;
|
||||||
|
pub(crate) use self::event::{physicalkey_to_scancode, scancode_to_physicalkey, KeyEventExtra};
|
||||||
|
pub(crate) use self::event_loop::{
|
||||||
|
ActiveEventLoop, EventLoop, PlatformSpecificEventLoopAttributes,
|
||||||
|
};
|
||||||
|
pub(crate) use self::monitor::{MonitorHandle, VideoModeHandle};
|
||||||
|
pub(crate) use self::window::Window;
|
||||||
|
pub(crate) use self::window_delegate::PlatformSpecificWindowAttributes;
|
||||||
|
pub(crate) use crate::cursor::OnlyCursorImageSource as PlatformCustomCursorSource;
|
||||||
|
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
||||||
|
pub(crate) use crate::platform_impl::Fullscreen;
|
||||||
@@ -1,18 +1,19 @@
|
|||||||
#![allow(clippy::unnecessary_cast)]
|
#![allow(clippy::unnecessary_cast)]
|
||||||
|
|
||||||
use std::{collections::VecDeque, fmt};
|
use std::collections::VecDeque;
|
||||||
|
use std::fmt;
|
||||||
|
use std::num::{NonZeroU16, NonZeroU32};
|
||||||
|
|
||||||
use core_foundation::{
|
use core_foundation::array::{CFArrayGetCount, CFArrayGetValueAtIndex};
|
||||||
array::{CFArrayGetCount, CFArrayGetValueAtIndex},
|
use core_foundation::base::{CFRelease, TCFType};
|
||||||
base::{CFRelease, TCFType},
|
use core_foundation::string::CFString;
|
||||||
string::CFString,
|
|
||||||
};
|
|
||||||
use core_graphics::display::{
|
use core_graphics::display::{
|
||||||
CGDirectDisplayID, CGDisplay, CGDisplayBounds, CGDisplayCopyDisplayMode,
|
CGDirectDisplayID, CGDisplay, CGDisplayBounds, CGDisplayCopyDisplayMode,
|
||||||
};
|
};
|
||||||
use icrate::AppKit::NSScreen;
|
use objc2::rc::Retained;
|
||||||
use icrate::Foundation::{ns_string, MainThreadMarker, NSNumber, NSPoint, NSRect};
|
use objc2::runtime::AnyObject;
|
||||||
use objc2::{rc::Id, runtime::AnyObject};
|
use objc2_app_kit::NSScreen;
|
||||||
|
use objc2_foundation::{ns_string, run_on_main, MainThreadMarker, NSNumber, NSPoint, NSRect};
|
||||||
|
|
||||||
use super::ffi;
|
use super::ffi;
|
||||||
use crate::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize};
|
use crate::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize};
|
||||||
@@ -20,8 +21,8 @@ use crate::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize};
|
|||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct VideoModeHandle {
|
pub struct VideoModeHandle {
|
||||||
size: PhysicalSize<u32>,
|
size: PhysicalSize<u32>,
|
||||||
bit_depth: u16,
|
bit_depth: Option<NonZeroU16>,
|
||||||
refresh_rate_millihertz: u32,
|
refresh_rate_millihertz: Option<NonZeroU32>,
|
||||||
pub(crate) monitor: MonitorHandle,
|
pub(crate) monitor: MonitorHandle,
|
||||||
pub(crate) native_mode: NativeDisplayMode,
|
pub(crate) native_mode: NativeDisplayMode,
|
||||||
}
|
}
|
||||||
@@ -80,15 +81,47 @@ impl Clone for NativeDisplayMode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl VideoModeHandle {
|
impl VideoModeHandle {
|
||||||
|
fn new(
|
||||||
|
monitor: MonitorHandle,
|
||||||
|
mode: NativeDisplayMode,
|
||||||
|
refresh_rate_millihertz: Option<NonZeroU32>,
|
||||||
|
) -> Self {
|
||||||
|
unsafe {
|
||||||
|
let pixel_encoding =
|
||||||
|
CFString::wrap_under_create_rule(ffi::CGDisplayModeCopyPixelEncoding(mode.0))
|
||||||
|
.to_string();
|
||||||
|
let bit_depth = if pixel_encoding.eq_ignore_ascii_case(ffi::IO32BitDirectPixels) {
|
||||||
|
32
|
||||||
|
} else if pixel_encoding.eq_ignore_ascii_case(ffi::IO16BitDirectPixels) {
|
||||||
|
16
|
||||||
|
} else if pixel_encoding.eq_ignore_ascii_case(ffi::kIO30BitDirectPixels) {
|
||||||
|
30
|
||||||
|
} else {
|
||||||
|
unimplemented!()
|
||||||
|
};
|
||||||
|
|
||||||
|
VideoModeHandle {
|
||||||
|
size: PhysicalSize::new(
|
||||||
|
ffi::CGDisplayModeGetPixelWidth(mode.0) as u32,
|
||||||
|
ffi::CGDisplayModeGetPixelHeight(mode.0) as u32,
|
||||||
|
),
|
||||||
|
refresh_rate_millihertz,
|
||||||
|
bit_depth: NonZeroU16::new(bit_depth),
|
||||||
|
monitor: monitor.clone(),
|
||||||
|
native_mode: mode,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn size(&self) -> PhysicalSize<u32> {
|
pub fn size(&self) -> PhysicalSize<u32> {
|
||||||
self.size
|
self.size
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn bit_depth(&self) -> u16 {
|
pub fn bit_depth(&self) -> Option<NonZeroU16> {
|
||||||
self.bit_depth
|
self.bit_depth
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn refresh_rate_millihertz(&self) -> u32 {
|
pub fn refresh_rate_millihertz(&self) -> Option<NonZeroU32> {
|
||||||
self.refresh_rate_millihertz
|
self.refresh_rate_millihertz
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,10 +191,8 @@ impl fmt::Debug for MonitorHandle {
|
|||||||
f.debug_struct("MonitorHandle")
|
f.debug_struct("MonitorHandle")
|
||||||
.field("name", &self.name())
|
.field("name", &self.name())
|
||||||
.field("native_identifier", &self.native_identifier())
|
.field("native_identifier", &self.native_identifier())
|
||||||
.field("size", &self.size())
|
|
||||||
.field("position", &self.position())
|
.field("position", &self.position())
|
||||||
.field("scale_factor", &self.scale_factor())
|
.field("scale_factor", &self.scale_factor())
|
||||||
.field("refresh_rate_millihertz", &self.refresh_rate_millihertz())
|
|
||||||
.finish_non_exhaustive()
|
.finish_non_exhaustive()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -184,26 +215,18 @@ impl MonitorHandle {
|
|||||||
self.0
|
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]
|
#[inline]
|
||||||
pub fn position(&self) -> PhysicalPosition<i32> {
|
pub fn position(&self) -> Option<PhysicalPosition<i32>> {
|
||||||
// This is already in screen coordinates. If we were using `NSScreen`,
|
// This is already in screen coordinates. If we were using `NSScreen`,
|
||||||
// then a conversion would've been needed:
|
// then a conversion would've been needed:
|
||||||
// flip_window_screen_coordinates(self.ns_screen(mtm)?.frame())
|
// flip_window_screen_coordinates(self.ns_screen(mtm)?.frame())
|
||||||
let bounds = unsafe { CGDisplayBounds(self.native_identifier()) };
|
let bounds = unsafe { CGDisplayBounds(self.native_identifier()) };
|
||||||
let position = LogicalPosition::new(bounds.origin.x, bounds.origin.y);
|
let position = LogicalPosition::new(bounds.origin.x, bounds.origin.y);
|
||||||
position.to_physical(self.scale_factor())
|
Some(position.to_physical(self.scale_factor()))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn scale_factor(&self) -> f64 {
|
pub fn scale_factor(&self) -> f64 {
|
||||||
MainThreadMarker::run_on_main(|mtm| {
|
run_on_main(|mtm| {
|
||||||
match self.ns_screen(mtm) {
|
match self.ns_screen(mtm) {
|
||||||
Some(screen) => screen.backingScaleFactor() as f64,
|
Some(screen) => screen.backingScaleFactor() as f64,
|
||||||
None => 1.0, // default to 1.0 when we can't find the screen
|
None => 1.0, // default to 1.0 when we can't find the screen
|
||||||
@@ -211,36 +234,20 @@ impl MonitorHandle {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn refresh_rate_millihertz(&self) -> Option<u32> {
|
fn refresh_rate_millihertz(&self) -> Option<NonZeroU32> {
|
||||||
unsafe {
|
let current_display_mode =
|
||||||
let current_display_mode = NativeDisplayMode(CGDisplayCopyDisplayMode(self.0) as _);
|
NativeDisplayMode(unsafe { CGDisplayCopyDisplayMode(self.0) } as _);
|
||||||
let refresh_rate = ffi::CGDisplayModeGetRefreshRate(current_display_mode.0);
|
refresh_rate_millihertz(self.0, ¤t_display_mode)
|
||||||
if refresh_rate > 0.0 {
|
}
|
||||||
return Some((refresh_rate * 1000.0).round() as u32);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut display_link = std::ptr::null_mut();
|
pub fn current_video_mode(&self) -> Option<VideoModeHandle> {
|
||||||
if ffi::CVDisplayLinkCreateWithCGDisplay(self.0, &mut display_link)
|
let mode = NativeDisplayMode(unsafe { CGDisplayCopyDisplayMode(self.0) } as _);
|
||||||
!= ffi::kCVReturnSuccess
|
let refresh_rate_millihertz = refresh_rate_millihertz(self.0, &mode);
|
||||||
{
|
Some(VideoModeHandle::new(self.clone(), mode, refresh_rate_millihertz))
|
||||||
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> {
|
pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> {
|
||||||
let refresh_rate_millihertz = self.refresh_rate_millihertz().unwrap_or(0);
|
let refresh_rate_millihertz = self.refresh_rate_millihertz();
|
||||||
let monitor = self.clone();
|
let monitor = self.clone();
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
@@ -265,39 +272,21 @@ impl MonitorHandle {
|
|||||||
// CGDisplayModeGetRefreshRate returns 0.0 for any display that
|
// CGDisplayModeGetRefreshRate returns 0.0 for any display that
|
||||||
// isn't a CRT
|
// isn't a CRT
|
||||||
let refresh_rate_millihertz = if cg_refresh_rate_hertz > 0 {
|
let refresh_rate_millihertz = if cg_refresh_rate_hertz > 0 {
|
||||||
(cg_refresh_rate_hertz * 1000) as u32
|
NonZeroU32::new((cg_refresh_rate_hertz * 1000) as u32)
|
||||||
} else {
|
} else {
|
||||||
refresh_rate_millihertz
|
refresh_rate_millihertz
|
||||||
};
|
};
|
||||||
|
|
||||||
let pixel_encoding =
|
VideoModeHandle::new(
|
||||||
CFString::wrap_under_create_rule(ffi::CGDisplayModeCopyPixelEncoding(mode))
|
monitor.clone(),
|
||||||
.to_string();
|
NativeDisplayMode(mode),
|
||||||
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,
|
refresh_rate_millihertz,
|
||||||
bit_depth,
|
)
|
||||||
monitor: monitor.clone(),
|
|
||||||
native_mode: NativeDisplayMode(mode),
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn ns_screen(&self, mtm: MainThreadMarker) -> Option<Id<NSScreen>> {
|
pub(crate) fn ns_screen(&self, mtm: MainThreadMarker) -> Option<Retained<NSScreen>> {
|
||||||
let uuid = unsafe { ffi::CGDisplayCreateUUIDFromDisplayID(self.0) };
|
let uuid = unsafe { ffi::CGDisplayCreateUUIDFromDisplayID(self.0) };
|
||||||
NSScreen::screens(mtm).into_iter().find(|screen| {
|
NSScreen::screens(mtm).into_iter().find(|screen| {
|
||||||
let other_native_id = get_display_id(screen);
|
let other_native_id = get_display_id(screen);
|
||||||
@@ -351,3 +340,29 @@ pub(crate) fn flip_window_screen_coordinates(frame: NSRect) -> NSPoint {
|
|||||||
let y = main_screen_height - frame.size.height - frame.origin.y;
|
let y = main_screen_height - frame.size.height - frame.origin.y;
|
||||||
NSPoint::new(frame.origin.x, y)
|
NSPoint::new(frame.origin.x, y)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn refresh_rate_millihertz(id: CGDirectDisplayID, mode: &NativeDisplayMode) -> Option<NonZeroU32> {
|
||||||
|
unsafe {
|
||||||
|
let refresh_rate = ffi::CGDisplayModeGetRefreshRate(mode.0);
|
||||||
|
if refresh_rate > 0.0 {
|
||||||
|
return NonZeroU32::new((refresh_rate * 1000.0).round() as u32);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut display_link = std::ptr::null_mut();
|
||||||
|
if ffi::CVDisplayLinkCreateWithCGDisplay(id, &mut display_link) != ffi::kCVReturnSuccess {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let time = ffi::CVDisplayLinkGetNominalOutputVideoRefreshPeriod(display_link);
|
||||||
|
ffi::CVDisplayLinkRelease(display_link);
|
||||||
|
|
||||||
|
// This value is indefinite if an invalid display link was specified
|
||||||
|
if time.flags & ffi::kCVTimeIsIndefinite != 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
(time.time_scale as i64)
|
||||||
|
.checked_div(time.time_value)
|
||||||
|
.map(|v| (v * 1000) as u32)
|
||||||
|
.and_then(NonZeroU32::new)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,27 +1,30 @@
|
|||||||
use std::{
|
//! Utilities for working with `CFRunLoop`.
|
||||||
ffi::c_void,
|
//!
|
||||||
panic::{AssertUnwindSafe, UnwindSafe},
|
//! See Apple's documentation on Run Loops for details:
|
||||||
ptr,
|
//! <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html>
|
||||||
rc::Weak,
|
use std::cell::Cell;
|
||||||
time::Instant,
|
use std::ffi::c_void;
|
||||||
};
|
use std::panic::{AssertUnwindSafe, UnwindSafe};
|
||||||
|
use std::ptr;
|
||||||
|
use std::rc::Weak;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
use core_foundation::base::{CFIndex, CFOptionFlags, CFRelease};
|
use block2::Block;
|
||||||
|
use core_foundation::base::{CFIndex, CFOptionFlags, CFRelease, CFTypeRef};
|
||||||
use core_foundation::date::CFAbsoluteTimeGetCurrent;
|
use core_foundation::date::CFAbsoluteTimeGetCurrent;
|
||||||
use core_foundation::runloop::{
|
use core_foundation::runloop::{
|
||||||
kCFRunLoopAfterWaiting, kCFRunLoopBeforeWaiting, kCFRunLoopCommonModes, kCFRunLoopExit,
|
kCFRunLoopAfterWaiting, kCFRunLoopBeforeWaiting, kCFRunLoopCommonModes, kCFRunLoopDefaultMode,
|
||||||
CFRunLoopActivity, CFRunLoopAddObserver, CFRunLoopAddTimer, CFRunLoopGetMain,
|
kCFRunLoopExit, CFRunLoopActivity, CFRunLoopAddObserver, CFRunLoopAddTimer, CFRunLoopGetMain,
|
||||||
CFRunLoopObserverCallBack, CFRunLoopObserverContext, CFRunLoopObserverCreate,
|
CFRunLoopObserverCallBack, CFRunLoopObserverContext, CFRunLoopObserverCreate,
|
||||||
CFRunLoopObserverRef, CFRunLoopRef, CFRunLoopTimerCreate, CFRunLoopTimerInvalidate,
|
CFRunLoopObserverRef, CFRunLoopRef, CFRunLoopTimerCreate, CFRunLoopTimerInvalidate,
|
||||||
CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate, CFRunLoopWakeUp,
|
CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate, CFRunLoopWakeUp,
|
||||||
};
|
};
|
||||||
use icrate::Foundation::MainThreadMarker;
|
use objc2_foundation::MainThreadMarker;
|
||||||
|
use tracing::error;
|
||||||
|
|
||||||
|
use super::app_state::AppState;
|
||||||
|
use super::event_loop::{stop_app_on_panic, PanicInfo};
|
||||||
use super::ffi;
|
use super::ffi;
|
||||||
use super::{
|
|
||||||
app_delegate::ApplicationDelegate,
|
|
||||||
event_loop::{stop_app_on_panic, PanicInfo},
|
|
||||||
};
|
|
||||||
|
|
||||||
unsafe fn control_flow_handler<F>(panic_info: *mut c_void, f: F)
|
unsafe fn control_flow_handler<F>(panic_info: *mut c_void, f: F)
|
||||||
where
|
where
|
||||||
@@ -55,10 +58,10 @@ extern "C" fn control_flow_begin_handler(
|
|||||||
#[allow(non_upper_case_globals)]
|
#[allow(non_upper_case_globals)]
|
||||||
match activity {
|
match activity {
|
||||||
kCFRunLoopAfterWaiting => {
|
kCFRunLoopAfterWaiting => {
|
||||||
//trace!("Triggered `CFRunLoopAfterWaiting`");
|
// trace!("Triggered `CFRunLoopAfterWaiting`");
|
||||||
ApplicationDelegate::get(MainThreadMarker::new().unwrap()).wakeup(panic_info);
|
AppState::get(MainThreadMarker::new().unwrap()).wakeup(panic_info);
|
||||||
//trace!("Completed `CFRunLoopAfterWaiting`");
|
// trace!("Completed `CFRunLoopAfterWaiting`");
|
||||||
}
|
},
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -77,21 +80,31 @@ extern "C" fn control_flow_end_handler(
|
|||||||
#[allow(non_upper_case_globals)]
|
#[allow(non_upper_case_globals)]
|
||||||
match activity {
|
match activity {
|
||||||
kCFRunLoopBeforeWaiting => {
|
kCFRunLoopBeforeWaiting => {
|
||||||
//trace!("Triggered `CFRunLoopBeforeWaiting`");
|
// trace!("Triggered `CFRunLoopBeforeWaiting`");
|
||||||
ApplicationDelegate::get(MainThreadMarker::new().unwrap()).cleared(panic_info);
|
AppState::get(MainThreadMarker::new().unwrap()).cleared(panic_info);
|
||||||
//trace!("Completed `CFRunLoopBeforeWaiting`");
|
// trace!("Completed `CFRunLoopBeforeWaiting`");
|
||||||
}
|
},
|
||||||
kCFRunLoopExit => (), //unimplemented!(), // not expected to ever happen
|
kCFRunLoopExit => (), // unimplemented!(), // not expected to ever happen
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
pub struct RunLoop(CFRunLoopRef);
|
pub struct RunLoop(CFRunLoopRef);
|
||||||
|
|
||||||
|
impl Default for RunLoop {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self(ptr::null_mut())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl RunLoop {
|
impl RunLoop {
|
||||||
pub unsafe fn get() -> Self {
|
pub fn main(mtm: MainThreadMarker) -> Self {
|
||||||
|
// SAFETY: We have a MainThreadMarker here, which means we know we're on the main thread, so
|
||||||
|
// scheduling (and scheduling a non-`Send` block) to that thread is allowed.
|
||||||
|
let _ = mtm;
|
||||||
RunLoop(unsafe { CFRunLoopGetMain() })
|
RunLoop(unsafe { CFRunLoopGetMain() })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,9 +131,79 @@ impl RunLoop {
|
|||||||
};
|
};
|
||||||
unsafe { CFRunLoopAddObserver(self.0, observer, kCFRunLoopCommonModes) };
|
unsafe { CFRunLoopAddObserver(self.0, observer, kCFRunLoopCommonModes) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Submit a closure to run on the main thread as the next step in the run loop, before other
|
||||||
|
/// event sources are processed.
|
||||||
|
///
|
||||||
|
/// This is used for running event handlers, as those are not allowed to run re-entrantly.
|
||||||
|
///
|
||||||
|
/// # Implementation
|
||||||
|
///
|
||||||
|
/// This queuing could be implemented in the following several ways with subtle differences in
|
||||||
|
/// timing. This list is sorted in rough order in which they are run:
|
||||||
|
///
|
||||||
|
/// 1. Using `CFRunLoopPerformBlock` or `-[NSRunLoop performBlock:]`.
|
||||||
|
///
|
||||||
|
/// 2. Using `-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]` or wrapping the
|
||||||
|
/// event in `NSEvent` and posting that to `-[NSApplication postEvent:atStart:]` (both
|
||||||
|
/// creates a custom `CFRunLoopSource`, and signals that to wake up the main event loop).
|
||||||
|
///
|
||||||
|
/// a. `atStart = true`.
|
||||||
|
///
|
||||||
|
/// b. `atStart = false`.
|
||||||
|
///
|
||||||
|
/// 3. `dispatch_async` or `dispatch_async_f`. Note that this may appear before 2b, it does not
|
||||||
|
/// respect the ordering that runloop events have.
|
||||||
|
///
|
||||||
|
/// We choose the first one, both for ease-of-implementation, but mostly for consistency, as we
|
||||||
|
/// want the event to be queued in a way that preserves the order the events originally arrived
|
||||||
|
/// in.
|
||||||
|
///
|
||||||
|
/// As an example, let's assume that we receive two events from the user, a mouse click which we
|
||||||
|
/// handled by queuing it, and a window resize which we handled immediately. If we allowed
|
||||||
|
/// AppKit to choose the ordering when queuing the mouse event, it might get put in the back of
|
||||||
|
/// the queue, and the events would appear out of order to the user of Winit. So we must instead
|
||||||
|
/// put the event at the very front of the queue, to be handled as soon as possible after
|
||||||
|
/// handling whatever event it's currently handling.
|
||||||
|
pub fn queue_closure(&self, closure: impl FnOnce() + 'static) {
|
||||||
|
extern "C" {
|
||||||
|
fn CFRunLoopPerformBlock(rl: CFRunLoopRef, mode: CFTypeRef, block: &Block<dyn Fn()>);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert `FnOnce()` to `Block<dyn Fn()>`.
|
||||||
|
let closure = Cell::new(Some(closure));
|
||||||
|
let block = block2::RcBlock::new(move || {
|
||||||
|
if let Some(closure) = closure.take() {
|
||||||
|
closure()
|
||||||
|
} else {
|
||||||
|
error!("tried to execute queued closure on main thread twice");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// There are a few common modes (`kCFRunLoopCommonModes`) defined by Cocoa:
|
||||||
|
// - `NSDefaultRunLoopMode`, alias of `kCFRunLoopDefaultMode`.
|
||||||
|
// - `NSEventTrackingRunLoopMode`, used when mouse-dragging and live-resizing a window.
|
||||||
|
// - `NSModalPanelRunLoopMode`, used when running a modal inside the Winit event loop.
|
||||||
|
// - `NSConnectionReplyMode`: TODO.
|
||||||
|
//
|
||||||
|
// We only want to run event handlers in the default mode, as we support running a blocking
|
||||||
|
// modal inside a Winit event handler (see [#1779]) which outrules the modal panel mode, and
|
||||||
|
// resizing such panel window enters the event tracking run loop mode, so we can't directly
|
||||||
|
// trigger events inside that mode either.
|
||||||
|
//
|
||||||
|
// Any events that are queued while running a modal or when live-resizing will instead wait,
|
||||||
|
// and be delivered to the application afterwards.
|
||||||
|
//
|
||||||
|
// [#1779]: https://github.com/rust-windowing/winit/issues/1779
|
||||||
|
let mode = unsafe { kCFRunLoopDefaultMode as CFTypeRef };
|
||||||
|
|
||||||
|
// SAFETY: The runloop is valid, the mode is a `CFStringRef`, and the block is `'static`.
|
||||||
|
unsafe { CFRunLoopPerformBlock(self.0, mode, &block) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn setup_control_flow_observers(panic_info: Weak<PanicInfo>) {
|
pub fn setup_control_flow_observers(mtm: MainThreadMarker, panic_info: Weak<PanicInfo>) {
|
||||||
|
let run_loop = RunLoop::main(mtm);
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut context = CFRunLoopObserverContext {
|
let mut context = CFRunLoopObserverContext {
|
||||||
info: Weak::into_raw(panic_info) as *mut _,
|
info: Weak::into_raw(panic_info) as *mut _,
|
||||||
@@ -129,16 +212,15 @@ pub fn setup_control_flow_observers(panic_info: Weak<PanicInfo>) {
|
|||||||
release: None,
|
release: None,
|
||||||
copyDescription: None,
|
copyDescription: None,
|
||||||
};
|
};
|
||||||
let run_loop = RunLoop::get();
|
|
||||||
run_loop.add_observer(
|
run_loop.add_observer(
|
||||||
kCFRunLoopAfterWaiting,
|
kCFRunLoopAfterWaiting,
|
||||||
CFIndex::min_value(),
|
CFIndex::MIN,
|
||||||
control_flow_begin_handler,
|
control_flow_begin_handler,
|
||||||
&mut context as *mut _,
|
&mut context as *mut _,
|
||||||
);
|
);
|
||||||
run_loop.add_observer(
|
run_loop.add_observer(
|
||||||
kCFRunLoopExit | kCFRunLoopBeforeWaiting,
|
kCFRunLoopExit | kCFRunLoopBeforeWaiting,
|
||||||
CFIndex::max_value(),
|
CFIndex::MAX,
|
||||||
control_flow_end_handler,
|
control_flow_end_handler,
|
||||||
&mut context as *mut _,
|
&mut context as *mut _,
|
||||||
);
|
);
|
||||||
@@ -169,8 +251,8 @@ impl Drop for EventLoopWaker {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for EventLoopWaker {
|
impl EventLoopWaker {
|
||||||
fn default() -> EventLoopWaker {
|
pub(crate) fn new() -> Self {
|
||||||
extern "C" fn wakeup_main_loop(_timer: CFRunLoopTimerRef, _info: *mut c_void) {}
|
extern "C" fn wakeup_main_loop(_timer: CFRunLoopTimerRef, _info: *mut c_void) {}
|
||||||
unsafe {
|
unsafe {
|
||||||
// Create a timer with a 0.1µs interval (1ns does not work) to mimic polling.
|
// Create a timer with a 0.1µs interval (1ns does not work) to mimic polling.
|
||||||
@@ -178,7 +260,7 @@ impl Default for EventLoopWaker {
|
|||||||
// future, but that gets changed to fire immediately in did_finish_launching
|
// future, but that gets changed to fire immediately in did_finish_launching
|
||||||
let timer = CFRunLoopTimerCreate(
|
let timer = CFRunLoopTimerCreate(
|
||||||
ptr::null_mut(),
|
ptr::null_mut(),
|
||||||
std::f64::MAX,
|
f64::MAX,
|
||||||
0.000_000_1,
|
0.000_000_1,
|
||||||
0,
|
0,
|
||||||
0,
|
0,
|
||||||
@@ -186,27 +268,21 @@ impl Default for EventLoopWaker {
|
|||||||
ptr::null_mut(),
|
ptr::null_mut(),
|
||||||
);
|
);
|
||||||
CFRunLoopAddTimer(CFRunLoopGetMain(), timer, kCFRunLoopCommonModes);
|
CFRunLoopAddTimer(CFRunLoopGetMain(), timer, kCFRunLoopCommonModes);
|
||||||
EventLoopWaker {
|
Self { timer, start_instant: Instant::now(), next_fire_date: None }
|
||||||
timer,
|
|
||||||
start_instant: Instant::now(),
|
|
||||||
next_fire_date: None,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl EventLoopWaker {
|
|
||||||
pub fn stop(&mut self) {
|
pub fn stop(&mut self) {
|
||||||
if self.next_fire_date.is_some() {
|
if self.next_fire_date.is_some() {
|
||||||
self.next_fire_date = None;
|
self.next_fire_date = None;
|
||||||
unsafe { CFRunLoopTimerSetNextFireDate(self.timer, std::f64::MAX) }
|
unsafe { CFRunLoopTimerSetNextFireDate(self.timer, f64::MAX) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn start(&mut self) {
|
pub fn start(&mut self) {
|
||||||
if self.next_fire_date != Some(self.start_instant) {
|
if self.next_fire_date != Some(self.start_instant) {
|
||||||
self.next_fire_date = Some(self.start_instant);
|
self.next_fire_date = Some(self.start_instant);
|
||||||
unsafe { CFRunLoopTimerSetNextFireDate(self.timer, std::f64::MIN) }
|
unsafe { CFRunLoopTimerSetNextFireDate(self.timer, f64::MIN) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -215,7 +291,7 @@ impl EventLoopWaker {
|
|||||||
match instant {
|
match instant {
|
||||||
Some(instant) if now >= instant => {
|
Some(instant) if now >= instant => {
|
||||||
self.start();
|
self.start();
|
||||||
}
|
},
|
||||||
Some(instant) => {
|
Some(instant) => {
|
||||||
if self.next_fire_date != Some(instant) {
|
if self.next_fire_date != Some(instant) {
|
||||||
self.next_fire_date = Some(instant);
|
self.next_fire_date = Some(instant);
|
||||||
@@ -227,10 +303,10 @@ impl EventLoopWaker {
|
|||||||
CFRunLoopTimerSetNextFireDate(self.timer, current + fsecs)
|
CFRunLoopTimerSetNextFireDate(self.timer, current + fsecs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
None => {
|
None => {
|
||||||
self.stop();
|
self.stop();
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
28
src/platform_impl/apple/appkit/util.rs
Normal file
28
src/platform_impl/apple/appkit/util.rs
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
use tracing::trace;
|
||||||
|
|
||||||
|
macro_rules! trace_scope {
|
||||||
|
($s:literal) => {
|
||||||
|
let _crate =
|
||||||
|
$crate::platform_impl::platform::appkit::util::TraceGuard::new(module_path!(), $s);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct TraceGuard {
|
||||||
|
module_path: &'static str,
|
||||||
|
called_from_fn: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TraceGuard {
|
||||||
|
#[inline]
|
||||||
|
pub(crate) fn new(module_path: &'static str, called_from_fn: &'static str) -> Self {
|
||||||
|
trace!(target = module_path, "Triggered `{}`", called_from_fn);
|
||||||
|
Self { module_path, called_from_fn }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TraceGuard {
|
||||||
|
#[inline]
|
||||||
|
fn drop(&mut self) {
|
||||||
|
trace!(target = self.module_path, "Completed `{}`", self.called_from_fn);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,53 +2,45 @@
|
|||||||
use std::cell::{Cell, RefCell};
|
use std::cell::{Cell, RefCell};
|
||||||
use std::collections::{HashMap, VecDeque};
|
use std::collections::{HashMap, VecDeque};
|
||||||
use std::ptr;
|
use std::ptr;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
use icrate::AppKit::{
|
use objc2::rc::Retained;
|
||||||
NSApplication, NSCursor, NSEvent, NSEventPhaseBegan, NSEventPhaseCancelled,
|
use objc2::runtime::{AnyObject, Sel};
|
||||||
NSEventPhaseChanged, NSEventPhaseEnded, NSEventPhaseMayBegin, NSResponder, NSTextInputClient,
|
use objc2::{declare_class, msg_send_id, mutability, ClassType, DeclaredClass};
|
||||||
|
use objc2_app_kit::{
|
||||||
|
NSApplication, NSCursor, NSEvent, NSEventPhase, NSResponder, NSTextInputClient,
|
||||||
NSTrackingRectTag, NSView,
|
NSTrackingRectTag, NSView,
|
||||||
};
|
};
|
||||||
use icrate::Foundation::{
|
use objc2_foundation::{
|
||||||
MainThreadMarker, NSArray, NSAttributedString, NSAttributedStringKey, NSCopying,
|
MainThreadMarker, NSArray, NSAttributedString, NSAttributedStringKey, NSCopying,
|
||||||
NSMutableAttributedString, NSObject, NSObjectProtocol, NSPoint, NSRange, NSRect, NSSize,
|
NSMutableAttributedString, NSNotFound, NSObject, NSObjectProtocol, NSPoint, NSRange, NSRect,
|
||||||
NSString, NSUInteger,
|
NSSize, NSString, NSUInteger,
|
||||||
};
|
|
||||||
use objc2::rc::{Id, WeakId};
|
|
||||||
use objc2::runtime::{AnyObject, Sel};
|
|
||||||
use objc2::{
|
|
||||||
class, declare_class, msg_send, msg_send_id, mutability, sel, ClassType, DeclaredClass,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::app_delegate::ApplicationDelegate;
|
use super::app_state::AppState;
|
||||||
use super::cursor::{default_cursor, invisible_cursor};
|
use super::cursor::{default_cursor, invisible_cursor};
|
||||||
use super::event::{
|
use super::event::{
|
||||||
code_to_key, code_to_location, create_key_event, event_mods, lalt_pressed, ralt_pressed,
|
code_to_key, code_to_location, create_key_event, event_mods, lalt_pressed, ralt_pressed,
|
||||||
scancode_to_physicalkey,
|
scancode_to_physicalkey, KeyEventExtra,
|
||||||
};
|
};
|
||||||
use super::window::WinitWindow;
|
use super::window::WinitWindow;
|
||||||
use super::{util, DEVICE_ID};
|
use crate::dpi::{LogicalPosition, LogicalSize};
|
||||||
use crate::{
|
use crate::event::{
|
||||||
dpi::{LogicalPosition, LogicalSize},
|
DeviceEvent, ElementState, Ime, KeyEvent, Modifiers, MouseButton, MouseScrollDelta,
|
||||||
event::{
|
PointerKind, PointerSource, TouchPhase, WindowEvent,
|
||||||
DeviceEvent, ElementState, Ime, Modifiers, MouseButton, MouseScrollDelta, TouchPhase,
|
|
||||||
WindowEvent,
|
|
||||||
},
|
|
||||||
keyboard::{Key, KeyCode, KeyLocation, ModifiersState, NamedKey},
|
|
||||||
platform::macos::OptionAsAlt,
|
|
||||||
};
|
};
|
||||||
|
use crate::keyboard::{Key, KeyCode, KeyLocation, ModifiersState, NamedKey};
|
||||||
|
use crate::platform::macos::OptionAsAlt;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct CursorState {
|
struct CursorState {
|
||||||
visible: bool,
|
visible: bool,
|
||||||
cursor: Id<NSCursor>,
|
cursor: Retained<NSCursor>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for CursorState {
|
impl Default for CursorState {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self { visible: true, cursor: default_cursor() }
|
||||||
visible: true,
|
|
||||||
cursor: default_cursor(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,8 +108,11 @@ fn get_left_modifier_code(key: &Key) -> KeyCode {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug)]
|
||||||
pub struct ViewState {
|
pub struct ViewState {
|
||||||
|
/// Strong reference to the global application state.
|
||||||
|
app_state: Rc<AppState>,
|
||||||
|
|
||||||
cursor_state: RefCell<CursorState>,
|
cursor_state: RefCell<CursorState>,
|
||||||
ime_position: Cell<NSPoint>,
|
ime_position: Cell<NSPoint>,
|
||||||
ime_size: Cell<NSSize>,
|
ime_size: Cell<NSSize>,
|
||||||
@@ -136,12 +131,9 @@ pub struct ViewState {
|
|||||||
/// to the application, even during IME
|
/// to the application, even during IME
|
||||||
forward_key_to_app: Cell<bool>,
|
forward_key_to_app: Cell<bool>,
|
||||||
|
|
||||||
marked_text: RefCell<Id<NSMutableAttributedString>>,
|
marked_text: RefCell<Retained<NSMutableAttributedString>>,
|
||||||
accepts_first_mouse: bool,
|
accepts_first_mouse: bool,
|
||||||
|
|
||||||
// Weak reference because the window keeps a strong reference to the view
|
|
||||||
_ns_window: WeakId<WinitWindow>,
|
|
||||||
|
|
||||||
/// The state of the `Option` as `Alt`.
|
/// The state of the `Option` as `Alt`.
|
||||||
option_as_alt: Cell<OptionAsAlt>,
|
option_as_alt: Cell<OptionAsAlt>,
|
||||||
}
|
}
|
||||||
@@ -175,20 +167,25 @@ declare_class!(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let rect = self.frame();
|
let rect = self.frame();
|
||||||
let tracking_rect = unsafe { self.addTrackingRect_owner_userData_assumeInside(rect, self, ptr::null_mut(), false) };
|
let tracking_rect = unsafe {
|
||||||
|
self.addTrackingRect_owner_userData_assumeInside(rect, self, ptr::null_mut(), false)
|
||||||
|
};
|
||||||
assert_ne!(tracking_rect, 0, "failed adding tracking rect");
|
assert_ne!(tracking_rect, 0, "failed adding tracking rect");
|
||||||
self.ivars().tracking_rect.set(Some(tracking_rect));
|
self.ivars().tracking_rect.set(Some(tracking_rect));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(frameDidChange:)]
|
// Not a normal method on `NSView`, it's triggered by `NSViewFrameDidChangeNotification`.
|
||||||
fn frame_did_change(&self, _event: &NSEvent) {
|
#[method(viewFrameDidChangeNotification:)]
|
||||||
trace_scope!("frameDidChange:");
|
fn frame_did_change(&self, _notification: Option<&AnyObject>) {
|
||||||
|
trace_scope!("NSViewFrameDidChangeNotification");
|
||||||
if let Some(tracking_rect) = self.ivars().tracking_rect.take() {
|
if let Some(tracking_rect) = self.ivars().tracking_rect.take() {
|
||||||
self.removeTrackingRect(tracking_rect);
|
self.removeTrackingRect(tracking_rect);
|
||||||
}
|
}
|
||||||
|
|
||||||
let rect = self.frame();
|
let rect = self.frame();
|
||||||
let tracking_rect = unsafe { self.addTrackingRect_owner_userData_assumeInside(rect, self, ptr::null_mut(), false) };
|
let tracking_rect = unsafe {
|
||||||
|
self.addTrackingRect_owner_userData_assumeInside(rect, self, ptr::null_mut(), false)
|
||||||
|
};
|
||||||
assert_ne!(tracking_rect, 0, "failed adding tracking rect");
|
assert_ne!(tracking_rect, 0, "failed adding tracking rect");
|
||||||
self.ivars().tracking_rect.set(Some(tracking_rect));
|
self.ivars().tracking_rect.set(Some(tracking_rect));
|
||||||
|
|
||||||
@@ -197,23 +194,16 @@ declare_class!(
|
|||||||
// 2. Even when a window resize does occur on a new tabbed window, it contains the wrong size (includes tab height).
|
// 2. Even when a window resize does occur on a new tabbed window, it contains the wrong size (includes tab height).
|
||||||
let logical_size = LogicalSize::new(rect.size.width as f64, rect.size.height as f64);
|
let logical_size = LogicalSize::new(rect.size.width as f64, rect.size.height as f64);
|
||||||
let size = logical_size.to_physical::<u32>(self.scale_factor());
|
let size = logical_size.to_physical::<u32>(self.scale_factor());
|
||||||
self.queue_event(WindowEvent::Resized(size));
|
self.queue_event(WindowEvent::SurfaceResized(size));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(drawRect:)]
|
#[method(drawRect:)]
|
||||||
fn draw_rect(&self, rect: NSRect) {
|
fn draw_rect(&self, _rect: NSRect) {
|
||||||
trace_scope!("drawRect:");
|
trace_scope!("drawRect:");
|
||||||
|
|
||||||
// It's a workaround for https://github.com/rust-windowing/winit/issues/2640, don't replace with `self.window_id()`.
|
self.ivars().app_state.handle_redraw(self.window().id());
|
||||||
if let Some(window) = self.ivars()._ns_window.load() {
|
|
||||||
let app_delegate = ApplicationDelegate::get(MainThreadMarker::from(self));
|
|
||||||
app_delegate.handle_redraw(window.id());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(clippy::let_unit_value)]
|
// This is a direct subclass of NSView, no need to call superclass' drawRect:
|
||||||
unsafe {
|
|
||||||
let _: () = msg_send![super(self), drawRect: rect];
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(acceptsFirstResponder)]
|
#[method(acceptsFirstResponder)]
|
||||||
@@ -226,7 +216,7 @@ declare_class!(
|
|||||||
// IMKInputSession [0x7fc573576ff0 presentFunctionRowItemTextInputViewWithEndpoint:completionHandler:] : [self textInputContext]=0x7fc573558e10 *NO* NSRemoteViewController to client, NSError=Error Domain=NSCocoaErrorDomain Code=4099 "The connection from pid 0 was invalidated from this process." UserInfo={NSDebugDescription=The connection from pid 0 was invalidated from this process.}, com.apple.inputmethod.EmojiFunctionRowItem
|
// IMKInputSession [0x7fc573576ff0 presentFunctionRowItemTextInputViewWithEndpoint:completionHandler:] : [self textInputContext]=0x7fc573558e10 *NO* NSRemoteViewController to client, NSError=Error Domain=NSCocoaErrorDomain Code=4099 "The connection from pid 0 was invalidated from this process." UserInfo={NSDebugDescription=The connection from pid 0 was invalidated from this process.}, com.apple.inputmethod.EmojiFunctionRowItem
|
||||||
// TODO: Add an API extension for using `NSTouchBar`
|
// TODO: Add an API extension for using `NSTouchBar`
|
||||||
#[method_id(touchBar)]
|
#[method_id(touchBar)]
|
||||||
fn touch_bar(&self) -> Option<Id<NSObject>> {
|
fn touch_bar(&self) -> Option<Retained<NSObject>> {
|
||||||
trace_scope!("touchBar");
|
trace_scope!("touchBar");
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@@ -259,33 +249,36 @@ declare_class!(
|
|||||||
if length > 0 {
|
if length > 0 {
|
||||||
NSRange::new(0, length)
|
NSRange::new(0, length)
|
||||||
} else {
|
} else {
|
||||||
util::EMPTY_RANGE
|
// Documented to return `{NSNotFound, 0}` if there is no marked range.
|
||||||
|
NSRange::new(NSNotFound as NSUInteger, 0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(selectedRange)]
|
#[method(selectedRange)]
|
||||||
fn selected_range(&self) -> NSRange {
|
fn selected_range(&self) -> NSRange {
|
||||||
trace_scope!("selectedRange");
|
trace_scope!("selectedRange");
|
||||||
util::EMPTY_RANGE
|
// Documented to return `{NSNotFound, 0}` if there is no selection.
|
||||||
|
NSRange::new(NSNotFound as NSUInteger, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(setMarkedText:selectedRange:replacementRange:)]
|
#[method(setMarkedText:selectedRange:replacementRange:)]
|
||||||
fn set_marked_text(
|
fn set_marked_text(
|
||||||
&self,
|
&self,
|
||||||
string: &NSObject,
|
string: &NSObject,
|
||||||
_selected_range: NSRange,
|
selected_range: NSRange,
|
||||||
_replacement_range: NSRange,
|
_replacement_range: NSRange,
|
||||||
) {
|
) {
|
||||||
|
// TODO: Use _replacement_range, requires changing the event to report surrounding text.
|
||||||
trace_scope!("setMarkedText:selectedRange:replacementRange:");
|
trace_scope!("setMarkedText:selectedRange:replacementRange:");
|
||||||
|
|
||||||
// SAFETY: This method is guaranteed to get either a `NSString` or a `NSAttributedString`.
|
// SAFETY: This method is guaranteed to get either a `NSString` or a `NSAttributedString`.
|
||||||
let (marked_text, preedit_string) = if string.is_kind_of::<NSAttributedString>() {
|
let (marked_text, string) = if string.is_kind_of::<NSAttributedString>() {
|
||||||
let string: *const NSObject = string;
|
let string: *const NSObject = string;
|
||||||
let string: *const NSAttributedString = string.cast();
|
let string: *const NSAttributedString = string.cast();
|
||||||
let string = unsafe { &*string };
|
let string = unsafe { &*string };
|
||||||
(
|
(
|
||||||
NSMutableAttributedString::from_attributed_nsstring(string),
|
NSMutableAttributedString::from_attributed_nsstring(string),
|
||||||
string.string().to_string(),
|
string.string(),
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
let string: *const NSObject = string;
|
let string: *const NSObject = string;
|
||||||
@@ -293,7 +286,7 @@ declare_class!(
|
|||||||
let string = unsafe { &*string };
|
let string = unsafe { &*string };
|
||||||
(
|
(
|
||||||
NSMutableAttributedString::from_nsstring(string),
|
NSMutableAttributedString::from_nsstring(string),
|
||||||
string.to_string(),
|
string.copy(),
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -313,16 +306,21 @@ declare_class!(
|
|||||||
self.ivars().ime_state.set(ImeState::Ground);
|
self.ivars().ime_state.set(ImeState::Ground);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Empty string basically means that there's no preedit, so indicate that by sending
|
let cursor_range = if string.is_empty() {
|
||||||
// `None` cursor range.
|
// An empty string basically means that there's no preedit, so indicate that by
|
||||||
let cursor_range = if preedit_string.is_empty() {
|
// sending a `None` cursor range.
|
||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
Some((preedit_string.len(), preedit_string.len()))
|
// Convert the selected range from UTF-16 indices to UTF-8 indices.
|
||||||
|
let sub_string_a = unsafe { string.substringToIndex(selected_range.location) };
|
||||||
|
let sub_string_b = unsafe { string.substringToIndex(selected_range.end()) };
|
||||||
|
let lowerbound_utf8 = sub_string_a.len();
|
||||||
|
let upperbound_utf8 = sub_string_b.len();
|
||||||
|
Some((lowerbound_utf8, upperbound_utf8))
|
||||||
};
|
};
|
||||||
|
|
||||||
// Send WindowEvent for updating marked text
|
// Send WindowEvent for updating marked text
|
||||||
self.queue_event(WindowEvent::Ime(Ime::Preedit(preedit_string, cursor_range)));
|
self.queue_event(WindowEvent::Ime(Ime::Preedit(string.to_string(), cursor_range)));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(unmarkText)]
|
#[method(unmarkText)]
|
||||||
@@ -343,7 +341,7 @@ declare_class!(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[method_id(validAttributesForMarkedText)]
|
#[method_id(validAttributesForMarkedText)]
|
||||||
fn valid_attributes_for_marked_text(&self) -> Id<NSArray<NSAttributedStringKey>> {
|
fn valid_attributes_for_marked_text(&self) -> Retained<NSArray<NSAttributedStringKey>> {
|
||||||
trace_scope!("validAttributesForMarkedText");
|
trace_scope!("validAttributesForMarkedText");
|
||||||
NSArray::new()
|
NSArray::new()
|
||||||
}
|
}
|
||||||
@@ -353,7 +351,7 @@ declare_class!(
|
|||||||
&self,
|
&self,
|
||||||
_range: NSRange,
|
_range: NSRange,
|
||||||
_actual_range: *mut NSRange,
|
_actual_range: *mut NSRange,
|
||||||
) -> Option<Id<NSAttributedString>> {
|
) -> Option<Retained<NSAttributedString>> {
|
||||||
trace_scope!("attributedSubstringForProposedRange:actualRange:");
|
trace_scope!("attributedSubstringForProposedRange:actualRange:");
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@@ -371,13 +369,18 @@ declare_class!(
|
|||||||
_actual_range: *mut NSRange,
|
_actual_range: *mut NSRange,
|
||||||
) -> NSRect {
|
) -> NSRect {
|
||||||
trace_scope!("firstRectForCharacterRange:actualRange:");
|
trace_scope!("firstRectForCharacterRange:actualRange:");
|
||||||
let rect = dbg!(NSRect::new(self.ivars().ime_position.get(), self.ivars().ime_size.get()));
|
let rect = NSRect::new(
|
||||||
|
self.ivars().ime_position.get(),
|
||||||
|
self.ivars().ime_size.get()
|
||||||
|
);
|
||||||
// Return value is expected to be in screen coordinates, so we need a conversion here
|
// Return value is expected to be in screen coordinates, so we need a conversion here
|
||||||
unsafe { self.window().convertRectToScreen(self.convertRect_toView(rect, None)) }
|
self.window()
|
||||||
|
.convertRectToScreen(self.convertRect_toView(rect, None))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(insertText:replacementRange:)]
|
#[method(insertText:replacementRange:)]
|
||||||
fn insert_text(&self, string: &NSObject, _replacement_range: NSRange) {
|
fn insert_text(&self, string: &NSObject, _replacement_range: NSRange) {
|
||||||
|
// TODO: Use _replacement_range, requires changing the event to report surrounding text.
|
||||||
trace_scope!("insertText:replacementRange:");
|
trace_scope!("insertText:replacementRange:");
|
||||||
|
|
||||||
// SAFETY: This method is guaranteed to get either a `NSString` or a `NSAttributedString`.
|
// SAFETY: This method is guaranteed to get either a `NSString` or a `NSAttributedString`.
|
||||||
@@ -391,7 +394,7 @@ declare_class!(
|
|||||||
unsafe { &*string }.to_string()
|
unsafe { &*string }.to_string()
|
||||||
};
|
};
|
||||||
|
|
||||||
let is_control = string.chars().next().map_or(false, |c| c.is_control());
|
let is_control = string.chars().next().is_some_and(|c| c.is_control());
|
||||||
|
|
||||||
// Commit only if we have marked text.
|
// Commit only if we have marked text.
|
||||||
if unsafe { self.hasMarkedText() } && self.is_ime_enabled() && !is_control {
|
if unsafe { self.hasMarkedText() } && self.is_ime_enabled() && !is_control {
|
||||||
@@ -404,8 +407,9 @@ declare_class!(
|
|||||||
// Basically, we're sent this message whenever a keyboard event that doesn't generate a "human
|
// Basically, we're sent this message whenever a keyboard event that doesn't generate a "human
|
||||||
// readable" character happens, i.e. newlines, tabs, and Ctrl+C.
|
// readable" character happens, i.e. newlines, tabs, and Ctrl+C.
|
||||||
#[method(doCommandBySelector:)]
|
#[method(doCommandBySelector:)]
|
||||||
fn do_command_by_selector(&self, _command: Sel) {
|
fn do_command_by_selector(&self, command: Sel) {
|
||||||
trace_scope!("doCommandBySelector:");
|
trace_scope!("doCommandBySelector:");
|
||||||
|
|
||||||
// We shouldn't forward any character from just committed text, since we'll end up sending
|
// We shouldn't forward any character from just committed text, since we'll end up sending
|
||||||
// it twice with some IMEs like Korean one. We'll also always send `Enter` in that case,
|
// it twice with some IMEs like Korean one. We'll also always send `Enter` in that case,
|
||||||
// which is not desired given it was used to confirm IME input.
|
// which is not desired given it was used to confirm IME input.
|
||||||
@@ -415,10 +419,23 @@ declare_class!(
|
|||||||
|
|
||||||
self.ivars().forward_key_to_app.set(true);
|
self.ivars().forward_key_to_app.set(true);
|
||||||
|
|
||||||
if unsafe { self.hasMarkedText() } && self.ivars().ime_state.get() == ImeState::Preedit {
|
if unsafe { self.hasMarkedText() } && self.ivars().ime_state.get() == ImeState::Preedit
|
||||||
|
{
|
||||||
// Leave preedit so that we also report the key-up for this key.
|
// Leave preedit so that we also report the key-up for this key.
|
||||||
self.ivars().ime_state.set(ImeState::Ground);
|
self.ivars().ime_state.set(ImeState::Ground);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Send command action to user if they requested it.
|
||||||
|
let window_id = self.window().id();
|
||||||
|
self.ivars().app_state.maybe_queue_with_handler(move |app, event_loop| {
|
||||||
|
if let Some(handler) = app.macos_handler() {
|
||||||
|
handler.standard_key_binding(event_loop, window_id, command.name());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// The documentation for `-[NSTextInputClient doCommandBySelector:]` clearly states that
|
||||||
|
// we should not be forwarding this event up the responder chain, so no calling `super`
|
||||||
|
// here either.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -473,9 +490,9 @@ declare_class!(
|
|||||||
};
|
};
|
||||||
|
|
||||||
if !had_ime_input || self.ivars().forward_key_to_app.get() {
|
if !had_ime_input || self.ivars().forward_key_to_app.get() {
|
||||||
let key_event = create_key_event(&event, true, unsafe { event.isARepeat() }, None);
|
let key_event = create_key_event(&event, true, unsafe { event.isARepeat() });
|
||||||
self.queue_event(WindowEvent::KeyboardInput {
|
self.queue_event(WindowEvent::KeyboardInput {
|
||||||
device_id: DEVICE_ID,
|
device_id: None,
|
||||||
event: key_event,
|
event: key_event,
|
||||||
is_synthetic: false,
|
is_synthetic: false,
|
||||||
});
|
});
|
||||||
@@ -495,8 +512,8 @@ declare_class!(
|
|||||||
ImeState::Ground | ImeState::Disabled
|
ImeState::Ground | ImeState::Disabled
|
||||||
) {
|
) {
|
||||||
self.queue_event(WindowEvent::KeyboardInput {
|
self.queue_event(WindowEvent::KeyboardInput {
|
||||||
device_id: DEVICE_ID,
|
device_id: None,
|
||||||
event: create_key_event(&event, false, false, None),
|
event: create_key_event(&event, false, false),
|
||||||
is_synthetic: false,
|
is_synthetic: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -543,15 +560,26 @@ declare_class!(
|
|||||||
.expect("could not find current event");
|
.expect("could not find current event");
|
||||||
|
|
||||||
self.update_modifiers(&event, false);
|
self.update_modifiers(&event, false);
|
||||||
let event = create_key_event(&event, true, unsafe { event.isARepeat() }, None);
|
let event = create_key_event(&event, true, unsafe { event.isARepeat() });
|
||||||
|
|
||||||
self.queue_event(WindowEvent::KeyboardInput {
|
self.queue_event(WindowEvent::KeyboardInput {
|
||||||
device_id: DEVICE_ID,
|
device_id: None,
|
||||||
event,
|
event,
|
||||||
is_synthetic: false,
|
is_synthetic: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// In the past (?), `mouseMoved:` events were not generated when the
|
||||||
|
// user hovered over a window from a separate window, and as such the
|
||||||
|
// application might not know the location of the mouse in the event.
|
||||||
|
//
|
||||||
|
// To fix this, we emit `mouse_motion` inside of mouse click, mouse
|
||||||
|
// scroll, magnify and other gesture event handlers, to ensure that
|
||||||
|
// the application's state of where the mouse click was located is up
|
||||||
|
// to date.
|
||||||
|
//
|
||||||
|
// See https://github.com/rust-windowing/winit/pull/1490 for history.
|
||||||
|
|
||||||
#[method(mouseDown:)]
|
#[method(mouseDown:)]
|
||||||
fn mouse_down(&self, event: &NSEvent) {
|
fn mouse_down(&self, event: &NSEvent) {
|
||||||
trace_scope!("mouseDown:");
|
trace_scope!("mouseDown:");
|
||||||
@@ -617,19 +645,30 @@ declare_class!(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[method(mouseEntered:)]
|
#[method(mouseEntered:)]
|
||||||
fn mouse_entered(&self, _event: &NSEvent) {
|
fn mouse_entered(&self, event: &NSEvent) {
|
||||||
trace_scope!("mouseEntered:");
|
trace_scope!("mouseEntered:");
|
||||||
self.queue_event(WindowEvent::CursorEntered {
|
|
||||||
device_id: DEVICE_ID,
|
let position = self.mouse_view_point(event).to_physical(self.scale_factor());
|
||||||
|
|
||||||
|
self.queue_event(WindowEvent::PointerEntered {
|
||||||
|
device_id: None,
|
||||||
|
primary: true,
|
||||||
|
position,
|
||||||
|
kind: PointerKind::Mouse,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(mouseExited:)]
|
#[method(mouseExited:)]
|
||||||
fn mouse_exited(&self, _event: &NSEvent) {
|
fn mouse_exited(&self, event: &NSEvent) {
|
||||||
trace_scope!("mouseExited:");
|
trace_scope!("mouseExited:");
|
||||||
|
|
||||||
self.queue_event(WindowEvent::CursorLeft {
|
let position = self.mouse_view_point(event).to_physical(self.scale_factor());
|
||||||
device_id: DEVICE_ID,
|
|
||||||
|
self.queue_event(WindowEvent::PointerLeft {
|
||||||
|
device_id: None,
|
||||||
|
primary: true,
|
||||||
|
position: Some(position),
|
||||||
|
kind: PointerKind::Mouse,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -655,28 +694,22 @@ declare_class!(
|
|||||||
// report the touch phase.
|
// report the touch phase.
|
||||||
#[allow(non_upper_case_globals)]
|
#[allow(non_upper_case_globals)]
|
||||||
let phase = match unsafe { event.momentumPhase() } {
|
let phase = match unsafe { event.momentumPhase() } {
|
||||||
NSEventPhaseMayBegin | NSEventPhaseBegan => {
|
NSEventPhase::MayBegin | NSEventPhase::Began => TouchPhase::Started,
|
||||||
TouchPhase::Started
|
NSEventPhase::Ended | NSEventPhase::Cancelled => TouchPhase::Ended,
|
||||||
}
|
|
||||||
NSEventPhaseEnded | NSEventPhaseCancelled => {
|
|
||||||
TouchPhase::Ended
|
|
||||||
}
|
|
||||||
_ => match unsafe { event.phase() } {
|
_ => match unsafe { event.phase() } {
|
||||||
NSEventPhaseMayBegin | NSEventPhaseBegan => {
|
NSEventPhase::MayBegin | NSEventPhase::Began => TouchPhase::Started,
|
||||||
TouchPhase::Started
|
NSEventPhase::Ended | NSEventPhase::Cancelled => TouchPhase::Ended,
|
||||||
}
|
|
||||||
NSEventPhaseEnded | NSEventPhaseCancelled => {
|
|
||||||
TouchPhase::Ended
|
|
||||||
}
|
|
||||||
_ => TouchPhase::Moved,
|
_ => TouchPhase::Moved,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
self.update_modifiers(event, false);
|
self.update_modifiers(event, false);
|
||||||
|
|
||||||
self.queue_device_event(DeviceEvent::MouseWheel { delta });
|
self.ivars().app_state.maybe_queue_with_handler(move |app, event_loop|
|
||||||
|
app.device_event(event_loop, None, DeviceEvent::MouseWheel { delta })
|
||||||
|
);
|
||||||
self.queue_event(WindowEvent::MouseWheel {
|
self.queue_event(WindowEvent::MouseWheel {
|
||||||
device_id: DEVICE_ID,
|
device_id: None,
|
||||||
delta,
|
delta,
|
||||||
phase,
|
phase,
|
||||||
});
|
});
|
||||||
@@ -686,28 +719,32 @@ declare_class!(
|
|||||||
fn magnify_with_event(&self, event: &NSEvent) {
|
fn magnify_with_event(&self, event: &NSEvent) {
|
||||||
trace_scope!("magnifyWithEvent:");
|
trace_scope!("magnifyWithEvent:");
|
||||||
|
|
||||||
|
self.mouse_motion(event);
|
||||||
|
|
||||||
#[allow(non_upper_case_globals)]
|
#[allow(non_upper_case_globals)]
|
||||||
let phase = match unsafe { event.phase() } {
|
let phase = match unsafe { event.phase() } {
|
||||||
NSEventPhaseBegan => TouchPhase::Started,
|
NSEventPhase::Began => TouchPhase::Started,
|
||||||
NSEventPhaseChanged => TouchPhase::Moved,
|
NSEventPhase::Changed => TouchPhase::Moved,
|
||||||
NSEventPhaseCancelled => TouchPhase::Cancelled,
|
NSEventPhase::Cancelled => TouchPhase::Cancelled,
|
||||||
NSEventPhaseEnded => TouchPhase::Ended,
|
NSEventPhase::Ended => TouchPhase::Ended,
|
||||||
_ => return,
|
_ => return,
|
||||||
};
|
};
|
||||||
|
|
||||||
self.queue_event(WindowEvent::PinchGesture {
|
self.queue_event(WindowEvent::PinchGesture {
|
||||||
device_id: DEVICE_ID,
|
device_id: None,
|
||||||
delta: unsafe { event.magnification() },
|
delta: unsafe { event.magnification() },
|
||||||
phase,
|
phase,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[method(smartMagnifyWithEvent:)]
|
#[method(smartMagnifyWithEvent:)]
|
||||||
fn smart_magnify_with_event(&self, _event: &NSEvent) {
|
fn smart_magnify_with_event(&self, event: &NSEvent) {
|
||||||
trace_scope!("smartMagnifyWithEvent:");
|
trace_scope!("smartMagnifyWithEvent:");
|
||||||
|
|
||||||
|
self.mouse_motion(event);
|
||||||
|
|
||||||
self.queue_event(WindowEvent::DoubleTapGesture {
|
self.queue_event(WindowEvent::DoubleTapGesture {
|
||||||
device_id: DEVICE_ID,
|
device_id: None,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -715,17 +752,19 @@ declare_class!(
|
|||||||
fn rotate_with_event(&self, event: &NSEvent) {
|
fn rotate_with_event(&self, event: &NSEvent) {
|
||||||
trace_scope!("rotateWithEvent:");
|
trace_scope!("rotateWithEvent:");
|
||||||
|
|
||||||
|
self.mouse_motion(event);
|
||||||
|
|
||||||
#[allow(non_upper_case_globals)]
|
#[allow(non_upper_case_globals)]
|
||||||
let phase = match unsafe { event.phase() } {
|
let phase = match unsafe { event.phase() } {
|
||||||
NSEventPhaseBegan => TouchPhase::Started,
|
NSEventPhase::Began => TouchPhase::Started,
|
||||||
NSEventPhaseChanged => TouchPhase::Moved,
|
NSEventPhase::Changed => TouchPhase::Moved,
|
||||||
NSEventPhaseCancelled => TouchPhase::Cancelled,
|
NSEventPhase::Cancelled => TouchPhase::Cancelled,
|
||||||
NSEventPhaseEnded => TouchPhase::Ended,
|
NSEventPhase::Ended => TouchPhase::Ended,
|
||||||
_ => return,
|
_ => return,
|
||||||
};
|
};
|
||||||
|
|
||||||
self.queue_event(WindowEvent::RotationGesture {
|
self.queue_event(WindowEvent::RotationGesture {
|
||||||
device_id: DEVICE_ID,
|
device_id: None,
|
||||||
delta: unsafe { event.rotation() },
|
delta: unsafe { event.rotation() },
|
||||||
phase,
|
phase,
|
||||||
});
|
});
|
||||||
@@ -735,10 +774,8 @@ declare_class!(
|
|||||||
fn pressure_change_with_event(&self, event: &NSEvent) {
|
fn pressure_change_with_event(&self, event: &NSEvent) {
|
||||||
trace_scope!("pressureChangeWithEvent:");
|
trace_scope!("pressureChangeWithEvent:");
|
||||||
|
|
||||||
self.mouse_motion(event);
|
|
||||||
|
|
||||||
self.queue_event(WindowEvent::TouchpadPressure {
|
self.queue_event(WindowEvent::TouchpadPressure {
|
||||||
device_id: DEVICE_ID,
|
device_id: None,
|
||||||
pressure: unsafe { event.pressure() },
|
pressure: unsafe { event.pressure() },
|
||||||
stage: unsafe { event.stage() } as i64,
|
stage: unsafe { event.stage() } as i64,
|
||||||
});
|
});
|
||||||
@@ -763,61 +800,50 @@ declare_class!(
|
|||||||
|
|
||||||
impl WinitView {
|
impl WinitView {
|
||||||
pub(super) fn new(
|
pub(super) fn new(
|
||||||
window: &WinitWindow,
|
app_state: &Rc<AppState>,
|
||||||
accepts_first_mouse: bool,
|
accepts_first_mouse: bool,
|
||||||
option_as_alt: OptionAsAlt,
|
option_as_alt: OptionAsAlt,
|
||||||
) -> Id<Self> {
|
mtm: MainThreadMarker,
|
||||||
let mtm = MainThreadMarker::from(window);
|
) -> Retained<Self> {
|
||||||
let this = mtm.alloc().set_ivars(ViewState {
|
let this = mtm.alloc().set_ivars(ViewState {
|
||||||
|
app_state: Rc::clone(app_state),
|
||||||
|
cursor_state: Default::default(),
|
||||||
|
ime_position: Default::default(),
|
||||||
|
ime_size: Default::default(),
|
||||||
|
modifiers: Default::default(),
|
||||||
|
phys_modifiers: Default::default(),
|
||||||
|
tracking_rect: Default::default(),
|
||||||
|
ime_state: Default::default(),
|
||||||
|
input_source: Default::default(),
|
||||||
|
ime_allowed: Default::default(),
|
||||||
|
forward_key_to_app: Default::default(),
|
||||||
|
marked_text: Default::default(),
|
||||||
accepts_first_mouse,
|
accepts_first_mouse,
|
||||||
_ns_window: WeakId::new(&window.retain()),
|
|
||||||
option_as_alt: Cell::new(option_as_alt),
|
option_as_alt: Cell::new(option_as_alt),
|
||||||
..Default::default()
|
|
||||||
});
|
});
|
||||||
let this: Id<Self> = unsafe { msg_send_id![super(this), init] };
|
let this: Retained<Self> = unsafe { msg_send_id![super(this), init] };
|
||||||
|
|
||||||
this.setPostsFrameChangedNotifications(true);
|
|
||||||
let notification_center: &AnyObject =
|
|
||||||
unsafe { msg_send![class!(NSNotificationCenter), defaultCenter] };
|
|
||||||
// About frame change
|
|
||||||
let frame_did_change_notification_name =
|
|
||||||
NSString::from_str("NSViewFrameDidChangeNotification");
|
|
||||||
#[allow(clippy::let_unit_value)]
|
|
||||||
unsafe {
|
|
||||||
let _: () = msg_send![
|
|
||||||
notification_center,
|
|
||||||
addObserver: &*this,
|
|
||||||
selector: sel!(frameDidChange:),
|
|
||||||
name: &*frame_did_change_notification_name,
|
|
||||||
object: &*this,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
*this.ivars().input_source.borrow_mut() = this.current_input_source();
|
*this.ivars().input_source.borrow_mut() = this.current_input_source();
|
||||||
|
|
||||||
this
|
this
|
||||||
}
|
}
|
||||||
|
|
||||||
fn window(&self) -> Id<WinitWindow> {
|
fn window(&self) -> Retained<WinitWindow> {
|
||||||
// TODO: Simply use `window` property on `NSView`.
|
let window = (**self).window().expect("view must be installed in a window");
|
||||||
// That only returns a window _after_ the view has been attached though!
|
|
||||||
// (which is incompatible with `frameDidChange:`)
|
if !window.isKindOfClass(WinitWindow::class()) {
|
||||||
//
|
unreachable!("view installed in non-WinitWindow");
|
||||||
// unsafe { msg_send_id![self, window] }
|
}
|
||||||
self.ivars()
|
|
||||||
._ns_window
|
// SAFETY: Just checked that the window is `WinitWindow`
|
||||||
.load()
|
unsafe { Retained::cast(window) }
|
||||||
.expect("view to have a window")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn queue_event(&self, event: WindowEvent) {
|
fn queue_event(&self, event: WindowEvent) {
|
||||||
let app_delegate = ApplicationDelegate::get(MainThreadMarker::from(self));
|
let window_id = self.window().id();
|
||||||
app_delegate.queue_window_event(self.window().id(), event);
|
self.ivars().app_state.maybe_queue_with_handler(move |app, event_loop| {
|
||||||
}
|
app.window_event(event_loop, window_id, event);
|
||||||
|
});
|
||||||
fn queue_device_event(&self, event: DeviceEvent) {
|
|
||||||
let app_delegate = ApplicationDelegate::get(MainThreadMarker::from(self));
|
|
||||||
app_delegate.queue_device_event(event);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn scale_factor(&self) -> f64 {
|
fn scale_factor(&self) -> f64 {
|
||||||
@@ -836,11 +862,11 @@ impl WinitView {
|
|||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn cursor_icon(&self) -> Id<NSCursor> {
|
pub(super) fn cursor_icon(&self) -> Retained<NSCursor> {
|
||||||
self.ivars().cursor_state.borrow().cursor.clone()
|
self.ivars().cursor_state.borrow().cursor.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn set_cursor_icon(&self, icon: Id<NSCursor>) {
|
pub(super) fn set_cursor_icon(&self, icon: Retained<NSCursor>) {
|
||||||
let mut cursor_state = self.ivars().cursor_state.borrow_mut();
|
let mut cursor_state = self.ivars().cursor_state.borrow_mut();
|
||||||
cursor_state.cursor = icon;
|
cursor_state.cursor = icon;
|
||||||
}
|
}
|
||||||
@@ -920,24 +946,36 @@ impl WinitView {
|
|||||||
let scancode = unsafe { ns_event.keyCode() };
|
let scancode = unsafe { ns_event.keyCode() };
|
||||||
let physical_key = scancode_to_physicalkey(scancode as u32);
|
let physical_key = scancode_to_physicalkey(scancode as u32);
|
||||||
|
|
||||||
// We'll correct the `is_press` later.
|
let logical_key = code_to_key(physical_key, scancode);
|
||||||
let mut event = create_key_event(ns_event, false, false, Some(physical_key));
|
|
||||||
|
|
||||||
let key = code_to_key(physical_key, scancode);
|
|
||||||
// Ignore processing of unknown modifiers because we can't determine whether
|
// Ignore processing of unknown modifiers because we can't determine whether
|
||||||
// it was pressed or release reliably.
|
// it was pressed or release reliably.
|
||||||
let Some(event_modifier) = key_to_modifier(&key) else {
|
//
|
||||||
|
// Furthermore, sometimes normal keys are reported inside flagsChanged:, such as
|
||||||
|
// when holding Caps Lock while pressing another key, see:
|
||||||
|
// https://github.com/alacritty/alacritty/issues/8268
|
||||||
|
let Some(event_modifier) = key_to_modifier(&logical_key) else {
|
||||||
break 'send_event;
|
break 'send_event;
|
||||||
};
|
};
|
||||||
event.physical_key = physical_key;
|
|
||||||
event.logical_key = key.clone();
|
let mut event = KeyEvent {
|
||||||
event.location = code_to_location(physical_key);
|
location: code_to_location(physical_key),
|
||||||
|
logical_key: logical_key.clone(),
|
||||||
|
physical_key,
|
||||||
|
repeat: false,
|
||||||
|
// We'll correct this later.
|
||||||
|
state: Pressed,
|
||||||
|
text: None,
|
||||||
|
platform_specific: KeyEventExtra {
|
||||||
|
text_with_all_modifiers: None,
|
||||||
|
key_without_modifiers: logical_key.clone(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
let location_mask = ModLocationMask::from_location(event.location);
|
let location_mask = ModLocationMask::from_location(event.location);
|
||||||
|
|
||||||
let mut phys_mod_state = self.ivars().phys_modifiers.borrow_mut();
|
let mut phys_mod_state = self.ivars().phys_modifiers.borrow_mut();
|
||||||
let phys_mod = phys_mod_state
|
let phys_mod =
|
||||||
.entry(key)
|
phys_mod_state.entry(logical_key).or_insert(ModLocationMask::empty());
|
||||||
.or_insert(ModLocationMask::empty());
|
|
||||||
|
|
||||||
let is_active = current_modifiers.state().contains(event_modifier);
|
let is_active = current_modifiers.state().contains(event_modifier);
|
||||||
let mut events = VecDeque::with_capacity(2);
|
let mut events = VecDeque::with_capacity(2);
|
||||||
@@ -954,7 +992,7 @@ impl WinitView {
|
|||||||
event.location = KeyLocation::Left;
|
event.location = KeyLocation::Left;
|
||||||
event.physical_key = get_left_modifier_code(&event.logical_key).into();
|
event.physical_key = get_left_modifier_code(&event.logical_key).into();
|
||||||
events.push_back(WindowEvent::KeyboardInput {
|
events.push_back(WindowEvent::KeyboardInput {
|
||||||
device_id: DEVICE_ID,
|
device_id: None,
|
||||||
event,
|
event,
|
||||||
is_synthetic: false,
|
is_synthetic: false,
|
||||||
});
|
});
|
||||||
@@ -963,7 +1001,7 @@ impl WinitView {
|
|||||||
event.location = KeyLocation::Right;
|
event.location = KeyLocation::Right;
|
||||||
event.physical_key = get_right_modifier_code(&event.logical_key).into();
|
event.physical_key = get_right_modifier_code(&event.logical_key).into();
|
||||||
events.push_back(WindowEvent::KeyboardInput {
|
events.push_back(WindowEvent::KeyboardInput {
|
||||||
device_id: DEVICE_ID,
|
device_id: None,
|
||||||
event,
|
event,
|
||||||
is_synthetic: false,
|
is_synthetic: false,
|
||||||
});
|
});
|
||||||
@@ -994,7 +1032,7 @@ impl WinitView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
events.push_back(WindowEvent::KeyboardInput {
|
events.push_back(WindowEvent::KeyboardInput {
|
||||||
device_id: DEVICE_ID,
|
device_id: None,
|
||||||
event,
|
event,
|
||||||
is_synthetic: false,
|
is_synthetic: false,
|
||||||
});
|
});
|
||||||
@@ -1016,20 +1054,22 @@ impl WinitView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn mouse_click(&self, event: &NSEvent, button_state: ElementState) {
|
fn mouse_click(&self, event: &NSEvent, button_state: ElementState) {
|
||||||
|
let position = self.mouse_view_point(event).to_physical(self.scale_factor());
|
||||||
let button = mouse_button(event);
|
let button = mouse_button(event);
|
||||||
|
|
||||||
self.update_modifiers(event, false);
|
self.update_modifiers(event, false);
|
||||||
|
|
||||||
self.queue_event(WindowEvent::MouseInput {
|
self.queue_event(WindowEvent::PointerButton {
|
||||||
device_id: DEVICE_ID,
|
device_id: None,
|
||||||
|
primary: true,
|
||||||
state: button_state,
|
state: button_state,
|
||||||
button,
|
position,
|
||||||
|
button: button.into(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn mouse_motion(&self, event: &NSEvent) {
|
fn mouse_motion(&self, event: &NSEvent) {
|
||||||
let window_point = unsafe { event.locationInWindow() };
|
let view_point = self.mouse_view_point(event);
|
||||||
let view_point = self.convertPoint_fromView(window_point, None);
|
|
||||||
let frame = self.frame();
|
let frame = self.frame();
|
||||||
|
|
||||||
if view_point.x.is_sign_negative()
|
if view_point.x.is_sign_negative()
|
||||||
@@ -1044,15 +1084,22 @@ impl WinitView {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let view_point = LogicalPosition::new(view_point.x, view_point.y);
|
|
||||||
|
|
||||||
self.update_modifiers(event, false);
|
self.update_modifiers(event, false);
|
||||||
|
|
||||||
self.queue_event(WindowEvent::CursorMoved {
|
self.queue_event(WindowEvent::PointerMoved {
|
||||||
device_id: DEVICE_ID,
|
device_id: None,
|
||||||
|
primary: true,
|
||||||
position: view_point.to_physical(self.scale_factor()),
|
position: view_point.to_physical(self.scale_factor()),
|
||||||
|
source: PointerSource::Mouse,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn mouse_view_point(&self, event: &NSEvent) -> LogicalPosition<f64> {
|
||||||
|
let window_point = unsafe { event.locationInWindow() };
|
||||||
|
let view_point = self.convertPoint_fromView(window_point, None);
|
||||||
|
|
||||||
|
LogicalPosition::new(view_point.x, view_point.y)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the mouse button from the NSEvent.
|
/// Get the mouse button from the NSEvent.
|
||||||
@@ -1075,7 +1122,7 @@ fn mouse_button(event: &NSEvent) -> MouseButton {
|
|||||||
// NOTE: to get option as alt working we need to rewrite events
|
// NOTE: to get option as alt working we need to rewrite events
|
||||||
// we're getting from the operating system, which makes it
|
// we're getting from the operating system, which makes it
|
||||||
// impossible to provide such events as extra in `KeyEvent`.
|
// impossible to provide such events as extra in `KeyEvent`.
|
||||||
fn replace_event(event: &NSEvent, option_as_alt: OptionAsAlt) -> Id<NSEvent> {
|
fn replace_event(event: &NSEvent, option_as_alt: OptionAsAlt) -> Retained<NSEvent> {
|
||||||
let ev_mods = event_mods(event).state;
|
let ev_mods = event_mods(event).state;
|
||||||
let ignore_alt_characters = match option_as_alt {
|
let ignore_alt_characters = match option_as_alt {
|
||||||
OptionAsAlt::OnlyLeft if lalt_pressed(event) => true,
|
OptionAsAlt::OnlyLeft if lalt_pressed(event) => true,
|
||||||
@@ -1087,9 +1134,7 @@ fn replace_event(event: &NSEvent, option_as_alt: OptionAsAlt) -> Id<NSEvent> {
|
|||||||
|
|
||||||
if ignore_alt_characters {
|
if ignore_alt_characters {
|
||||||
let ns_chars = unsafe {
|
let ns_chars = unsafe {
|
||||||
event
|
event.charactersIgnoringModifiers().expect("expected characters to be non-null")
|
||||||
.charactersIgnoringModifiers()
|
|
||||||
.expect("expected characters to be non-null")
|
|
||||||
};
|
};
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
367
src/platform_impl/apple/appkit/window.rs
Normal file
367
src/platform_impl/apple/appkit/window.rs
Normal file
@@ -0,0 +1,367 @@
|
|||||||
|
#![allow(clippy::unnecessary_cast)]
|
||||||
|
|
||||||
|
use dpi::{Position, Size};
|
||||||
|
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::RequestError;
|
||||||
|
use crate::monitor::MonitorHandle as CoreMonitorHandle;
|
||||||
|
use crate::window::{
|
||||||
|
Cursor, Fullscreen, Icon, ImePurpose, Theme, UserAttentionType, Window as CoreWindow,
|
||||||
|
WindowAttributes, WindowButtons, WindowId, WindowLevel,
|
||||||
|
};
|
||||||
|
|
||||||
|
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 Window {
|
||||||
|
pub(crate) fn new(
|
||||||
|
window_target: &ActiveEventLoop,
|
||||||
|
attributes: WindowAttributes,
|
||||||
|
) -> Result<Self, RequestError> {
|
||||||
|
let mtm = window_target.mtm;
|
||||||
|
let delegate =
|
||||||
|
autoreleasepool(|_| WindowDelegate::new(&window_target.app_state, attributes, mtm))?;
|
||||||
|
Ok(Window {
|
||||||
|
window: MainThreadBound::new(delegate.window().retain(), mtm),
|
||||||
|
delegate: MainThreadBound::new(delegate, mtm),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Window {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// Restore the video mode.
|
||||||
|
if matches!(self.fullscreen(), Some(Fullscreen::Exclusive(_))) {
|
||||||
|
self.set_fullscreen(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.window.get_on_main(|window| autoreleasepool(|_| window.close()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl rwh_06::HasDisplayHandle for Window {
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let raw = self.raw_display_handle_rwh_06()?;
|
||||||
|
unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl rwh_06::HasWindowHandle for Window {
|
||||||
|
fn window_handle(&self) -> Result<rwh_06::WindowHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let raw = self.raw_window_handle_rwh_06()?;
|
||||||
|
unsafe { Ok(rwh_06::WindowHandle::borrow_raw(raw)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CoreWindow for Window {
|
||||||
|
fn id(&self) -> crate::window::WindowId {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.id())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scale_factor(&self) -> f64 {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.scale_factor())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_redraw(&self) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.request_redraw());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pre_present_notify(&self) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.pre_present_notify());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reset_dead_keys(&self) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.reset_dead_keys());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn surface_position(&self) -> dpi::PhysicalPosition<i32> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.surface_position())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn outer_position(&self) -> Result<dpi::PhysicalPosition<i32>, RequestError> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.outer_position())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_outer_position(&self, position: Position) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_outer_position(position));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn surface_size(&self) -> dpi::PhysicalSize<u32> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.surface_size())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_surface_size(&self, size: Size) -> Option<dpi::PhysicalSize<u32>> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.request_surface_size(size))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn outer_size(&self) -> dpi::PhysicalSize<u32> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.outer_size())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn safe_area(&self) -> dpi::PhysicalInsets<u32> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.safe_area())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_min_surface_size(&self, min_size: Option<Size>) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_min_surface_size(min_size))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_max_surface_size(&self, max_size: Option<Size>) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_max_surface_size(max_size));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn surface_resize_increments(&self) -> Option<dpi::PhysicalSize<u32>> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.surface_resize_increments())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_surface_resize_increments(&self, increments: Option<Size>) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_surface_resize_increments(increments));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_title(&self, title: &str) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_title(title));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_transparent(&self, transparent: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_transparent(transparent));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_blur(&self, blur: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_blur(blur));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_visible(&self, visible: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_visible(visible));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_visible(&self) -> Option<bool> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.is_visible())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_resizable(&self, resizable: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_resizable(resizable))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_resizable(&self) -> bool {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.is_resizable())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_enabled_buttons(&self, buttons: WindowButtons) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_enabled_buttons(buttons))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn enabled_buttons(&self) -> WindowButtons {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.enabled_buttons())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_minimized(&self, minimized: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_minimized(minimized));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_minimized(&self) -> Option<bool> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.is_minimized())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_maximized(&self, maximized: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_maximized(maximized));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_maximized(&self) -> bool {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.is_maximized())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_fullscreen(fullscreen.map(Into::into)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fullscreen(&self) -> Option<Fullscreen> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.fullscreen().map(Into::into))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_decorations(&self, decorations: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_decorations(decorations));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_decorated(&self) -> bool {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.is_decorated())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_window_level(&self, level: WindowLevel) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_window_level(level));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_window_icon(&self, window_icon: Option<Icon>) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_window_icon(window_icon));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_ime_cursor_area(&self, position: Position, size: Size) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_ime_cursor_area(position, size));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_ime_allowed(&self, allowed: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_ime_allowed(allowed));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_ime_purpose(&self, purpose: ImePurpose) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_ime_purpose(purpose));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn focus_window(&self) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.focus_window());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_focus(&self) -> bool {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.has_focus())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_user_attention(&self, request_type: Option<UserAttentionType>) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.request_user_attention(request_type));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_theme(&self, theme: Option<Theme>) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_theme(theme));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn theme(&self) -> Option<Theme> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.theme())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_content_protected(&self, protected: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_content_protected(protected));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn title(&self) -> String {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.title())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_cursor(&self, cursor: Cursor) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_cursor(cursor));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_cursor_position(position))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_cursor_grab(&self, mode: crate::window::CursorGrabMode) -> Result<(), RequestError> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_cursor_grab(mode))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_cursor_visible(&self, visible: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_cursor_visible(visible))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drag_window(&self) -> Result<(), RequestError> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.drag_window())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drag_resize_window(
|
||||||
|
&self,
|
||||||
|
direction: crate::window::ResizeDirection,
|
||||||
|
) -> Result<(), RequestError> {
|
||||||
|
Ok(self.maybe_wait_on_main(|delegate| delegate.drag_resize_window(direction))?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show_window_menu(&self, position: Position) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.show_window_menu(position))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_cursor_hittest(hittest));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current_monitor(&self) -> Option<CoreMonitorHandle> {
|
||||||
|
self.maybe_wait_on_main(|delegate| {
|
||||||
|
delegate.current_monitor().map(|inner| CoreMonitorHandle { inner })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn available_monitors(&self) -> Box<dyn Iterator<Item = CoreMonitorHandle>> {
|
||||||
|
self.maybe_wait_on_main(|delegate| {
|
||||||
|
Box::new(
|
||||||
|
delegate.available_monitors().into_iter().map(|inner| CoreMonitorHandle { inner }),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn primary_monitor(&self) -> Option<CoreMonitorHandle> {
|
||||||
|
self.maybe_wait_on_main(|delegate| {
|
||||||
|
delegate.primary_monitor().map(|inner| CoreMonitorHandle { inner })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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::from_raw(self as *const Self as usize)
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,32 +1,35 @@
|
|||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
use std::fmt;
|
use std::{fmt, mem};
|
||||||
use std::mem;
|
|
||||||
|
|
||||||
use super::app_delegate::HandlePendingUserEvents;
|
use crate::application::ApplicationHandler;
|
||||||
use crate::event::Event;
|
|
||||||
use crate::event_loop::ActiveEventLoop as RootActiveEventLoop;
|
|
||||||
|
|
||||||
struct EventHandlerData {
|
/// A helper type for storing a reference to `ApplicationHandler`, allowing interior mutable access
|
||||||
#[allow(clippy::type_complexity)]
|
/// to it within the execution of a closure.
|
||||||
handler: Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop) + 'static>,
|
#[derive(Default)]
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Debug for EventHandlerData {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.debug_struct("EventHandlerData").finish_non_exhaustive()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
pub(crate) struct EventHandler {
|
pub(crate) struct EventHandler {
|
||||||
/// This can be in the following states:
|
/// This can be in the following states:
|
||||||
/// - Not registered by the event loop (None).
|
/// - Not registered by the event loop (None).
|
||||||
/// - Present (Some(handler)).
|
/// - Present (Some(handler)).
|
||||||
/// - Currently executing the handler / in use (RefCell borrowed).
|
/// - Currently executing the handler / in use (RefCell borrowed).
|
||||||
inner: RefCell<Option<EventHandlerData>>,
|
inner: RefCell<Option<&'static mut dyn ApplicationHandler>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for EventHandler {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
let state = match self.inner.try_borrow().as_deref() {
|
||||||
|
Ok(Some(_)) => "<available>",
|
||||||
|
Ok(None) => "<not set>",
|
||||||
|
Err(_) => "<in use>",
|
||||||
|
};
|
||||||
|
f.debug_struct("EventHandler").field("state", &state).finish_non_exhaustive()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventHandler {
|
impl EventHandler {
|
||||||
|
pub(crate) fn new() -> Self {
|
||||||
|
Self { inner: RefCell::new(None) }
|
||||||
|
}
|
||||||
|
|
||||||
/// Set the event loop handler for the duration of the given closure.
|
/// Set the event loop handler for the duration of the given closure.
|
||||||
///
|
///
|
||||||
/// This is similar to using the `scoped-tls` or `scoped-tls-hkt` crates
|
/// This is similar to using the `scoped-tls` or `scoped-tls-hkt` crates
|
||||||
@@ -34,7 +37,7 @@ impl EventHandler {
|
|||||||
/// from within the closure.
|
/// from within the closure.
|
||||||
pub(crate) fn set<'handler, R>(
|
pub(crate) fn set<'handler, R>(
|
||||||
&self,
|
&self,
|
||||||
handler: impl FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop) + 'handler,
|
app: &'handler mut dyn ApplicationHandler,
|
||||||
closure: impl FnOnce() -> R,
|
closure: impl FnOnce() -> R,
|
||||||
) -> R {
|
) -> R {
|
||||||
// SAFETY: We extend the lifetime of the handler here so that we can
|
// SAFETY: We extend the lifetime of the handler here so that we can
|
||||||
@@ -45,21 +48,21 @@ impl EventHandler {
|
|||||||
// extended beyond `'handler`.
|
// extended beyond `'handler`.
|
||||||
let handler = unsafe {
|
let handler = unsafe {
|
||||||
mem::transmute::<
|
mem::transmute::<
|
||||||
Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop) + 'handler>,
|
&'handler mut dyn ApplicationHandler,
|
||||||
Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop) + 'static>,
|
&'static mut dyn ApplicationHandler,
|
||||||
>(Box::new(handler))
|
>(app)
|
||||||
};
|
};
|
||||||
|
|
||||||
match self.inner.try_borrow_mut().as_deref_mut() {
|
match self.inner.try_borrow_mut().as_deref_mut() {
|
||||||
Ok(Some(_)) => {
|
Ok(Some(_)) => {
|
||||||
unreachable!("tried to set handler while another was already set");
|
unreachable!("tried to set handler while another was already set");
|
||||||
}
|
},
|
||||||
Ok(data @ None) => {
|
Ok(data @ None) => {
|
||||||
*data = Some(EventHandlerData { handler });
|
*data = Some(handler);
|
||||||
}
|
},
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
unreachable!("tried to set handler that is currently in use");
|
unreachable!("tried to set handler that is currently in use");
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ClearOnDrop<'a>(&'a EventHandler);
|
struct ClearOnDrop<'a>(&'a EventHandler);
|
||||||
@@ -69,10 +72,10 @@ impl EventHandler {
|
|||||||
match self.0.inner.try_borrow_mut().as_deref_mut() {
|
match self.0.inner.try_borrow_mut().as_deref_mut() {
|
||||||
Ok(data @ Some(_)) => {
|
Ok(data @ Some(_)) => {
|
||||||
*data = None;
|
*data = None;
|
||||||
}
|
},
|
||||||
Ok(None) => {
|
Ok(None) => {
|
||||||
tracing::error!("tried to clear handler, but no handler was set");
|
tracing::error!("tried to clear handler, but no handler was set");
|
||||||
}
|
},
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
// Note: This is not expected to ever happen, this
|
// Note: This is not expected to ever happen, this
|
||||||
// module generally controls the `RefCell`, and
|
// module generally controls the `RefCell`, and
|
||||||
@@ -83,7 +86,7 @@ impl EventHandler {
|
|||||||
// weren't able to unset the handler.
|
// weren't able to unset the handler.
|
||||||
eprintln!("tried to clear handler that is currently in use");
|
eprintln!("tried to clear handler that is currently in use");
|
||||||
std::process::abort();
|
std::process::abort();
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -98,6 +101,7 @@ impl EventHandler {
|
|||||||
// soundness.
|
// soundness.
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
pub(crate) fn in_use(&self) -> bool {
|
pub(crate) fn in_use(&self) -> bool {
|
||||||
self.inner.try_borrow().is_err()
|
self.inner.try_borrow().is_err()
|
||||||
}
|
}
|
||||||
@@ -106,31 +110,27 @@ impl EventHandler {
|
|||||||
matches!(self.inner.try_borrow().as_deref(), Ok(Some(_)))
|
matches!(self.inner.try_borrow().as_deref(), Ok(Some(_)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn handle_event(
|
pub(crate) fn handle(&self, callback: impl FnOnce(&mut dyn ApplicationHandler)) {
|
||||||
&self,
|
|
||||||
event: Event<HandlePendingUserEvents>,
|
|
||||||
event_loop: &RootActiveEventLoop,
|
|
||||||
) {
|
|
||||||
match self.inner.try_borrow_mut().as_deref_mut() {
|
match self.inner.try_borrow_mut().as_deref_mut() {
|
||||||
Ok(Some(EventHandlerData { handler })) => {
|
Ok(Some(user_app)) => {
|
||||||
// It is important that we keep the reference borrowed here,
|
// It is important that we keep the reference borrowed here,
|
||||||
// so that `in_use` can properly detect that the handler is
|
// so that `in_use` can properly detect that the handler is
|
||||||
// still in use.
|
// still in use.
|
||||||
//
|
//
|
||||||
// If the handler unwinds, the `RefMut` will ensure that the
|
// If the handler unwinds, the `RefMut` will ensure that the
|
||||||
// handler is no longer borrowed.
|
// handler is no longer borrowed.
|
||||||
(handler)(event, event_loop);
|
callback(*user_app);
|
||||||
}
|
},
|
||||||
Ok(None) => {
|
Ok(None) => {
|
||||||
// `NSApplication`, our app delegate and this handler are all
|
// `NSApplication`, our app state and this handler are all
|
||||||
// global state and so it's not impossible that we could get
|
// global state and so it's not impossible that we could get
|
||||||
// an event after the application has exited the `EventLoop`.
|
// an event after the application has exited the `EventLoop`.
|
||||||
tracing::error!("tried to run event handler, but no handler was set");
|
tracing::error!("tried to run event handler, but no handler was set");
|
||||||
}
|
},
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
// Prevent re-entrancy.
|
// Prevent re-entrancy.
|
||||||
panic!("tried to handle event while another event is currently being handled");
|
panic!("tried to handle event while another event is currently being handled");
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
15
src/platform_impl/apple/mod.rs
Normal file
15
src/platform_impl/apple/mod.rs
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
//! Apple/Darwin-specific implementations
|
||||||
|
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
mod appkit;
|
||||||
|
mod event_handler;
|
||||||
|
mod notification_center;
|
||||||
|
#[cfg(not(target_os = "macos"))]
|
||||||
|
mod uikit;
|
||||||
|
|
||||||
|
#[allow(unused_imports)]
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
pub use self::appkit::*;
|
||||||
|
#[allow(unused_imports)]
|
||||||
|
#[cfg(not(target_os = "macos"))]
|
||||||
|
pub use self::uikit::*;
|
||||||
27
src/platform_impl/apple/notification_center.rs
Normal file
27
src/platform_impl/apple/notification_center.rs
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
use std::ptr::NonNull;
|
||||||
|
|
||||||
|
use block2::RcBlock;
|
||||||
|
use objc2::rc::Retained;
|
||||||
|
use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName, NSObject};
|
||||||
|
|
||||||
|
/// Observe the given notification.
|
||||||
|
///
|
||||||
|
/// This is used in Winit as an alternative to declaring an application delegate, as we want to
|
||||||
|
/// give the user full control over those.
|
||||||
|
pub fn create_observer(
|
||||||
|
center: &NSNotificationCenter,
|
||||||
|
name: &NSNotificationName,
|
||||||
|
handler: impl Fn(&NSNotification) + 'static,
|
||||||
|
) -> Retained<NSObject> {
|
||||||
|
let block = RcBlock::new(move |notification: NonNull<NSNotification>| {
|
||||||
|
handler(unsafe { notification.as_ref() });
|
||||||
|
});
|
||||||
|
unsafe {
|
||||||
|
center.addObserverForName_object_queue_usingBlock(
|
||||||
|
Some(name),
|
||||||
|
None, // No sender filter
|
||||||
|
None, // No queue, run on posting thread (i.e. main thread)
|
||||||
|
&block,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
714
src/platform_impl/apple/uikit/app_state.rs
Normal file
714
src/platform_impl/apple/uikit/app_state.rs
Normal file
@@ -0,0 +1,714 @@
|
|||||||
|
#![deny(unused_results)]
|
||||||
|
|
||||||
|
use std::cell::{OnceCell, RefCell, RefMut};
|
||||||
|
use std::collections::HashSet;
|
||||||
|
use std::os::raw::c_void;
|
||||||
|
use std::sync::atomic::Ordering;
|
||||||
|
use std::sync::{Arc, Mutex, OnceLock};
|
||||||
|
use std::time::Instant;
|
||||||
|
use std::{mem, ptr};
|
||||||
|
|
||||||
|
use core_foundation::base::CFRelease;
|
||||||
|
use core_foundation::date::CFAbsoluteTimeGetCurrent;
|
||||||
|
use core_foundation::runloop::{
|
||||||
|
kCFRunLoopCommonModes, CFRunLoopAddTimer, CFRunLoopGetMain, CFRunLoopRef, CFRunLoopTimerCreate,
|
||||||
|
CFRunLoopTimerInvalidate, CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate,
|
||||||
|
};
|
||||||
|
use objc2::rc::Retained;
|
||||||
|
use objc2::sel;
|
||||||
|
use objc2_foundation::{
|
||||||
|
CGRect, CGSize, MainThreadMarker, NSInteger, NSObjectProtocol, NSOperatingSystemVersion,
|
||||||
|
NSProcessInfo,
|
||||||
|
};
|
||||||
|
use objc2_ui_kit::{UIApplication, UICoordinateSpace, UIView, UIWindow};
|
||||||
|
|
||||||
|
use super::super::event_handler::EventHandler;
|
||||||
|
use super::window::WinitUIWindow;
|
||||||
|
use super::{ActiveEventLoop, EventLoopProxy};
|
||||||
|
use crate::application::ApplicationHandler;
|
||||||
|
use crate::dpi::PhysicalSize;
|
||||||
|
use crate::event::{StartCause, SurfaceSizeWriter, WindowEvent};
|
||||||
|
use crate::event_loop::ControlFlow;
|
||||||
|
use crate::window::WindowId;
|
||||||
|
|
||||||
|
macro_rules! bug {
|
||||||
|
($($msg:tt)*) => {
|
||||||
|
panic!("winit iOS bug, file an issue: {}", format!($($msg)*))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! bug_assert {
|
||||||
|
($test:expr, $($msg:tt)*) => {
|
||||||
|
assert!($test, "winit iOS bug, file an issue: {}", format!($($msg)*))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the global event handler for the application.
|
||||||
|
///
|
||||||
|
/// This is stored separately from AppState, since AppState needs to be accessible while the handler
|
||||||
|
/// is executing.
|
||||||
|
fn get_handler(mtm: MainThreadMarker) -> &'static EventHandler {
|
||||||
|
// TODO(madsmtm): Use `MainThreadBound` once that is possible in `static`s.
|
||||||
|
struct StaticMainThreadBound<T>(T);
|
||||||
|
|
||||||
|
impl<T> StaticMainThreadBound<T> {
|
||||||
|
const fn get(&self, _mtm: MainThreadMarker) -> &T {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl<T> Send for StaticMainThreadBound<T> {}
|
||||||
|
unsafe impl<T> Sync for StaticMainThreadBound<T> {}
|
||||||
|
|
||||||
|
// SAFETY: Creating `StaticMainThreadBound` in a `const` context, where there is no concept
|
||||||
|
// of the main thread.
|
||||||
|
static GLOBAL: StaticMainThreadBound<OnceCell<EventHandler>> =
|
||||||
|
StaticMainThreadBound(OnceCell::new());
|
||||||
|
|
||||||
|
GLOBAL.get(mtm).get_or_init(EventHandler::new)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(crate) enum EventWrapper {
|
||||||
|
Window { window_id: WindowId, event: WindowEvent },
|
||||||
|
ScaleFactorChanged(ScaleFactorChanged),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ScaleFactorChanged {
|
||||||
|
pub(super) window: Retained<WinitUIWindow>,
|
||||||
|
pub(super) suggested_size: PhysicalSize<u32>,
|
||||||
|
pub(super) scale_factor: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventWrapper {
|
||||||
|
fn is_redraw(&self) -> bool {
|
||||||
|
matches!(self, Self::Window { event: WindowEvent::RedrawRequested, .. })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// this is the state machine for the app lifecycle
|
||||||
|
#[derive(Debug)]
|
||||||
|
#[must_use = "dropping `AppStateImpl` without inspecting it is probably a bug"]
|
||||||
|
enum AppStateImpl {
|
||||||
|
Initial {
|
||||||
|
queued_gpu_redraws: HashSet<Retained<WinitUIWindow>>,
|
||||||
|
},
|
||||||
|
ProcessingEvents {
|
||||||
|
queued_gpu_redraws: HashSet<Retained<WinitUIWindow>>,
|
||||||
|
active_control_flow: ControlFlow,
|
||||||
|
},
|
||||||
|
ProcessingRedraws {
|
||||||
|
active_control_flow: ControlFlow,
|
||||||
|
},
|
||||||
|
Waiting {
|
||||||
|
start: Instant,
|
||||||
|
},
|
||||||
|
PollFinished,
|
||||||
|
Terminated,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct AppState {
|
||||||
|
// This should never be `None`, except for briefly during a state transition.
|
||||||
|
app_state: Option<AppStateImpl>,
|
||||||
|
control_flow: ControlFlow,
|
||||||
|
waker: EventLoopWaker,
|
||||||
|
event_loop_proxy: Arc<EventLoopProxy>,
|
||||||
|
queued_events: Vec<EventWrapper>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppState {
|
||||||
|
pub(crate) fn get_mut(_mtm: MainThreadMarker) -> RefMut<'static, AppState> {
|
||||||
|
// basically everything in UIKit requires the main thread, so it's pointless to use the
|
||||||
|
// std::sync APIs.
|
||||||
|
// must be mut because plain `static` requires `Sync`
|
||||||
|
static mut APP_STATE: RefCell<Option<AppState>> = RefCell::new(None);
|
||||||
|
|
||||||
|
#[allow(unknown_lints)] // New lint below
|
||||||
|
#[allow(static_mut_refs)] // TODO: Use `MainThreadBound` instead.
|
||||||
|
let mut guard = unsafe { APP_STATE.borrow_mut() };
|
||||||
|
if guard.is_none() {
|
||||||
|
#[inline(never)]
|
||||||
|
#[cold]
|
||||||
|
fn init_guard(guard: &mut RefMut<'static, Option<AppState>>) {
|
||||||
|
let waker = EventLoopWaker::new(unsafe { CFRunLoopGetMain() });
|
||||||
|
**guard = Some(AppState {
|
||||||
|
app_state: Some(AppStateImpl::Initial { queued_gpu_redraws: HashSet::new() }),
|
||||||
|
control_flow: ControlFlow::default(),
|
||||||
|
waker,
|
||||||
|
event_loop_proxy: Arc::new(EventLoopProxy::new()),
|
||||||
|
queued_events: Vec::new(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
init_guard(&mut guard);
|
||||||
|
}
|
||||||
|
RefMut::map(guard, |state| state.as_mut().unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state(&self) -> &AppStateImpl {
|
||||||
|
match &self.app_state {
|
||||||
|
Some(ref state) => state,
|
||||||
|
None => bug!("`AppState` previously failed a state transition"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state_mut(&mut self) -> &mut AppStateImpl {
|
||||||
|
match &mut self.app_state {
|
||||||
|
Some(ref mut state) => state,
|
||||||
|
None => bug!("`AppState` previously failed a state transition"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn take_state(&mut self) -> AppStateImpl {
|
||||||
|
match self.app_state.take() {
|
||||||
|
Some(state) => state,
|
||||||
|
None => bug!("`AppState` previously failed a state transition"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_state(&mut self, new_state: AppStateImpl) {
|
||||||
|
bug_assert!(
|
||||||
|
self.app_state.is_none(),
|
||||||
|
"attempted to set an `AppState` without calling `take_state` first {:?}",
|
||||||
|
self.app_state
|
||||||
|
);
|
||||||
|
self.app_state = Some(new_state)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn replace_state(&mut self, new_state: AppStateImpl) -> AppStateImpl {
|
||||||
|
match &mut self.app_state {
|
||||||
|
Some(ref mut state) => mem::replace(state, new_state),
|
||||||
|
None => bug!("`AppState` previously failed a state transition"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_launched(&self) -> bool {
|
||||||
|
!matches!(self.state(), AppStateImpl::Initial { .. })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_terminated(&self) -> bool {
|
||||||
|
matches!(self.state(), AppStateImpl::Terminated)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn did_finish_launching_transition(&mut self) {
|
||||||
|
let queued_gpu_redraws = match self.take_state() {
|
||||||
|
AppStateImpl::Initial { queued_gpu_redraws } => queued_gpu_redraws,
|
||||||
|
s => bug!("unexpected state {:?}", s),
|
||||||
|
};
|
||||||
|
self.set_state(AppStateImpl::ProcessingEvents {
|
||||||
|
active_control_flow: self.control_flow,
|
||||||
|
queued_gpu_redraws,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wakeup_transition(&mut self) -> Option<StartCause> {
|
||||||
|
// before `AppState::did_finish_launching` is called, pretend there is no running
|
||||||
|
// event loop.
|
||||||
|
if !self.has_launched() || self.has_terminated() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let start_cause = match (self.control_flow, self.take_state()) {
|
||||||
|
(ControlFlow::Poll, AppStateImpl::PollFinished) => StartCause::Poll,
|
||||||
|
(ControlFlow::Wait, AppStateImpl::Waiting { start }) => {
|
||||||
|
StartCause::WaitCancelled { start, requested_resume: None }
|
||||||
|
},
|
||||||
|
(ControlFlow::WaitUntil(requested_resume), AppStateImpl::Waiting { start }) => {
|
||||||
|
if Instant::now() >= requested_resume {
|
||||||
|
StartCause::ResumeTimeReached { start, requested_resume }
|
||||||
|
} else {
|
||||||
|
StartCause::WaitCancelled { start, requested_resume: Some(requested_resume) }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
s => bug!("`EventHandler` unexpectedly woke up {:?}", s),
|
||||||
|
};
|
||||||
|
|
||||||
|
self.set_state(AppStateImpl::ProcessingEvents {
|
||||||
|
queued_gpu_redraws: Default::default(),
|
||||||
|
active_control_flow: self.control_flow,
|
||||||
|
});
|
||||||
|
Some(start_cause)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main_events_cleared_transition(&mut self) -> HashSet<Retained<WinitUIWindow>> {
|
||||||
|
let (queued_gpu_redraws, active_control_flow) = match self.take_state() {
|
||||||
|
AppStateImpl::ProcessingEvents { queued_gpu_redraws, active_control_flow } => {
|
||||||
|
(queued_gpu_redraws, active_control_flow)
|
||||||
|
},
|
||||||
|
s => bug!("unexpected state {:?}", s),
|
||||||
|
};
|
||||||
|
self.set_state(AppStateImpl::ProcessingRedraws { active_control_flow });
|
||||||
|
queued_gpu_redraws
|
||||||
|
}
|
||||||
|
|
||||||
|
fn events_cleared_transition(&mut self) {
|
||||||
|
if !self.has_launched() || self.has_terminated() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let old = match self.take_state() {
|
||||||
|
AppStateImpl::ProcessingRedraws { active_control_flow } => active_control_flow,
|
||||||
|
s => bug!("unexpected state {:?}", s),
|
||||||
|
};
|
||||||
|
|
||||||
|
let new = self.control_flow;
|
||||||
|
match (old, new) {
|
||||||
|
(ControlFlow::Wait, ControlFlow::Wait) => {
|
||||||
|
let start = Instant::now();
|
||||||
|
self.set_state(AppStateImpl::Waiting { start });
|
||||||
|
},
|
||||||
|
(ControlFlow::WaitUntil(old_instant), ControlFlow::WaitUntil(new_instant))
|
||||||
|
if old_instant == new_instant =>
|
||||||
|
{
|
||||||
|
let start = Instant::now();
|
||||||
|
self.set_state(AppStateImpl::Waiting { start });
|
||||||
|
},
|
||||||
|
(_, ControlFlow::Wait) => {
|
||||||
|
let start = Instant::now();
|
||||||
|
self.set_state(AppStateImpl::Waiting { start });
|
||||||
|
self.waker.stop()
|
||||||
|
},
|
||||||
|
(_, ControlFlow::WaitUntil(new_instant)) => {
|
||||||
|
let start = Instant::now();
|
||||||
|
self.set_state(AppStateImpl::Waiting { start });
|
||||||
|
self.waker.start_at(new_instant)
|
||||||
|
},
|
||||||
|
// Unlike on macOS, handle Poll to Poll transition here to call the waker
|
||||||
|
(_, ControlFlow::Poll) => {
|
||||||
|
self.set_state(AppStateImpl::PollFinished);
|
||||||
|
self.waker.start()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn terminated_transition(&mut self) {
|
||||||
|
match self.replace_state(AppStateImpl::Terminated) {
|
||||||
|
AppStateImpl::ProcessingEvents { .. } => {},
|
||||||
|
s => bug!("terminated while not processing events {:?}", s),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn event_loop_proxy(&self) -> &Arc<EventLoopProxy> {
|
||||||
|
&self.event_loop_proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn set_control_flow(&mut self, control_flow: ControlFlow) {
|
||||||
|
self.control_flow = control_flow;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn control_flow(&self) -> ControlFlow {
|
||||||
|
self.control_flow
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn queue_gl_or_metal_redraw(mtm: MainThreadMarker, window: Retained<WinitUIWindow>) {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
match this.state_mut() {
|
||||||
|
&mut AppStateImpl::Initial { ref mut queued_gpu_redraws, .. }
|
||||||
|
| &mut AppStateImpl::ProcessingEvents { ref mut queued_gpu_redraws, .. } => {
|
||||||
|
let _ = queued_gpu_redraws.insert(window);
|
||||||
|
},
|
||||||
|
s @ &mut AppStateImpl::ProcessingRedraws { .. }
|
||||||
|
| s @ &mut AppStateImpl::Waiting { .. }
|
||||||
|
| s @ &mut AppStateImpl::PollFinished { .. } => bug!("unexpected state {:?}", s),
|
||||||
|
&mut AppStateImpl::Terminated => {
|
||||||
|
panic!("Attempt to create a `Window` after the app has terminated")
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn launch(mtm: MainThreadMarker, app: &mut dyn ApplicationHandler, run: impl FnOnce()) {
|
||||||
|
get_handler(mtm).set(app, run)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn did_finish_launching(mtm: MainThreadMarker) {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
|
||||||
|
this.waker.start();
|
||||||
|
|
||||||
|
// have to drop RefMut because the window setup code below can trigger new events
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
AppState::get_mut(mtm).did_finish_launching_transition();
|
||||||
|
|
||||||
|
get_handler(mtm).handle(|app| app.new_events(&ActiveEventLoop { mtm }, StartCause::Init));
|
||||||
|
get_handler(mtm).handle(|app| app.can_create_surfaces(&ActiveEventLoop { mtm }));
|
||||||
|
handle_nonuser_events(mtm, []);
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppState::did_finish_launching handles the special transition `Init`
|
||||||
|
pub fn handle_wakeup_transition(mtm: MainThreadMarker) {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
let cause = match this.wakeup_transition() {
|
||||||
|
None => return,
|
||||||
|
Some(cause) => cause,
|
||||||
|
};
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
get_handler(mtm).handle(|app| app.new_events(&ActiveEventLoop { mtm }, cause));
|
||||||
|
handle_nonuser_events(mtm, []);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn handle_nonuser_event(mtm: MainThreadMarker, event: EventWrapper) {
|
||||||
|
handle_nonuser_events(mtm, std::iter::once(event))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>(
|
||||||
|
mtm: MainThreadMarker,
|
||||||
|
events: I,
|
||||||
|
) {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
if this.has_terminated() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !get_handler(mtm).ready() {
|
||||||
|
// Prevent re-entrancy; queue the events up for once we're done handling the event instead.
|
||||||
|
this.queued_events.extend(events);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let processing_redraws = matches!(this.state(), AppStateImpl::ProcessingRedraws { .. });
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
for event in events {
|
||||||
|
if !processing_redraws && event.is_redraw() {
|
||||||
|
tracing::info!("processing `RedrawRequested` during the main event loop");
|
||||||
|
} else if processing_redraws && !event.is_redraw() {
|
||||||
|
tracing::warn!(
|
||||||
|
"processing non `RedrawRequested` event after the main event loop: {:#?}",
|
||||||
|
event
|
||||||
|
);
|
||||||
|
}
|
||||||
|
handle_wrapped_event(mtm, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
let queued_events = mem::take(&mut this.queued_events);
|
||||||
|
if queued_events.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
for event in queued_events {
|
||||||
|
if !processing_redraws && event.is_redraw() {
|
||||||
|
tracing::info!("processing `RedrawRequested` during the main event loop");
|
||||||
|
} else if processing_redraws && !event.is_redraw() {
|
||||||
|
tracing::warn!(
|
||||||
|
"processing non-`RedrawRequested` event after the main event loop: {:#?}",
|
||||||
|
event
|
||||||
|
);
|
||||||
|
}
|
||||||
|
handle_wrapped_event(mtm, event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_user_events(mtm: MainThreadMarker) {
|
||||||
|
let this = AppState::get_mut(mtm);
|
||||||
|
if matches!(this.state(), AppStateImpl::ProcessingRedraws { .. }) {
|
||||||
|
bug!("user events attempted to be sent out while `ProcessingRedraws`");
|
||||||
|
}
|
||||||
|
let event_loop_proxy = this.event_loop_proxy().clone();
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
if event_loop_proxy.wake_up.swap(false, Ordering::Relaxed) {
|
||||||
|
get_handler(mtm).handle(|app| app.proxy_wake_up(&ActiveEventLoop { mtm }));
|
||||||
|
}
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
let queued_events = mem::take(&mut this.queued_events);
|
||||||
|
if queued_events.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
for event in queued_events {
|
||||||
|
handle_wrapped_event(mtm, event);
|
||||||
|
}
|
||||||
|
|
||||||
|
if event_loop_proxy.wake_up.swap(false, Ordering::Relaxed) {
|
||||||
|
get_handler(mtm).handle(|app| app.proxy_wake_up(&ActiveEventLoop { mtm }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn send_occluded_event_for_all_windows(application: &UIApplication, occluded: bool) {
|
||||||
|
let mtm = MainThreadMarker::from(application);
|
||||||
|
|
||||||
|
let mut events = Vec::new();
|
||||||
|
#[allow(deprecated)]
|
||||||
|
for window in application.windows().iter() {
|
||||||
|
if window.is_kind_of::<WinitUIWindow>() {
|
||||||
|
// SAFETY: We just checked that the window is a `winit` window
|
||||||
|
let window = unsafe {
|
||||||
|
let ptr: *const UIWindow = window;
|
||||||
|
let ptr: *const WinitUIWindow = ptr.cast();
|
||||||
|
&*ptr
|
||||||
|
};
|
||||||
|
events.push(EventWrapper::Window {
|
||||||
|
window_id: window.id(),
|
||||||
|
event: WindowEvent::Occluded(occluded),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
handle_nonuser_events(mtm, events);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn handle_main_events_cleared(mtm: MainThreadMarker) {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
if !this.has_launched() || this.has_terminated() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match this.state_mut() {
|
||||||
|
AppStateImpl::ProcessingEvents { .. } => {},
|
||||||
|
_ => bug!("`ProcessingRedraws` happened unexpectedly"),
|
||||||
|
};
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
handle_user_events(mtm);
|
||||||
|
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
let redraw_events: Vec<EventWrapper> = this
|
||||||
|
.main_events_cleared_transition()
|
||||||
|
.into_iter()
|
||||||
|
.map(|window| EventWrapper::Window {
|
||||||
|
window_id: window.id(),
|
||||||
|
event: WindowEvent::RedrawRequested,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
handle_nonuser_events(mtm, redraw_events);
|
||||||
|
get_handler(mtm).handle(|app| app.about_to_wait(&ActiveEventLoop { mtm }));
|
||||||
|
handle_nonuser_events(mtm, []);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn handle_events_cleared(mtm: MainThreadMarker) {
|
||||||
|
AppState::get_mut(mtm).events_cleared_transition();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn handle_resumed(mtm: MainThreadMarker) {
|
||||||
|
get_handler(mtm).handle(|app| app.resumed(&ActiveEventLoop { mtm }));
|
||||||
|
handle_nonuser_events(mtm, []);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn handle_suspended(mtm: MainThreadMarker) {
|
||||||
|
get_handler(mtm).handle(|app| app.suspended(&ActiveEventLoop { mtm }));
|
||||||
|
handle_nonuser_events(mtm, []);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn handle_memory_warning(mtm: MainThreadMarker) {
|
||||||
|
get_handler(mtm).handle(|app| app.memory_warning(&ActiveEventLoop { mtm }));
|
||||||
|
handle_nonuser_events(mtm, []);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn terminated(application: &UIApplication) {
|
||||||
|
let mtm = MainThreadMarker::from(application);
|
||||||
|
|
||||||
|
let mut events = Vec::new();
|
||||||
|
#[allow(deprecated)]
|
||||||
|
for window in application.windows().iter() {
|
||||||
|
if window.is_kind_of::<WinitUIWindow>() {
|
||||||
|
// SAFETY: We just checked that the window is a `winit` window
|
||||||
|
let window = unsafe {
|
||||||
|
let ptr: *const UIWindow = window;
|
||||||
|
let ptr: *const WinitUIWindow = ptr.cast();
|
||||||
|
&*ptr
|
||||||
|
};
|
||||||
|
events.push(EventWrapper::Window {
|
||||||
|
window_id: window.id(),
|
||||||
|
event: WindowEvent::Destroyed,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
handle_nonuser_events(mtm, events);
|
||||||
|
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
this.terminated_transition();
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
get_handler(mtm).handle(|app| app.exiting(&ActiveEventLoop { mtm }));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_wrapped_event(mtm: MainThreadMarker, event: EventWrapper) {
|
||||||
|
match event {
|
||||||
|
EventWrapper::Window { window_id, event } => get_handler(mtm)
|
||||||
|
.handle(|app| app.window_event(&ActiveEventLoop { mtm }, window_id, event)),
|
||||||
|
EventWrapper::ScaleFactorChanged(event) => handle_hidpi_proxy(mtm, event),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_hidpi_proxy(mtm: MainThreadMarker, event: ScaleFactorChanged) {
|
||||||
|
let ScaleFactorChanged { suggested_size, scale_factor, window } = event;
|
||||||
|
let new_surface_size = Arc::new(Mutex::new(suggested_size));
|
||||||
|
get_handler(mtm).handle(|app| {
|
||||||
|
app.window_event(&ActiveEventLoop { mtm }, window.id(), WindowEvent::ScaleFactorChanged {
|
||||||
|
scale_factor,
|
||||||
|
surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_surface_size)),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
let (view, screen_frame) = get_view_and_screen_frame(&window);
|
||||||
|
let physical_size = *new_surface_size.lock().unwrap();
|
||||||
|
drop(new_surface_size);
|
||||||
|
let logical_size = physical_size.to_logical(scale_factor);
|
||||||
|
let size = CGSize::new(logical_size.width, logical_size.height);
|
||||||
|
let new_frame: CGRect = CGRect::new(screen_frame.origin, size);
|
||||||
|
view.setFrame(new_frame);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_view_and_screen_frame(window: &WinitUIWindow) -> (Retained<UIView>, CGRect) {
|
||||||
|
let view_controller = window.rootViewController().unwrap();
|
||||||
|
let view = view_controller.view().unwrap();
|
||||||
|
let bounds = window.bounds();
|
||||||
|
let screen = window.screen();
|
||||||
|
let screen_space = screen.coordinateSpace();
|
||||||
|
let screen_frame = window.convertRect_toCoordinateSpace(bounds, &screen_space);
|
||||||
|
(view, screen_frame)
|
||||||
|
}
|
||||||
|
|
||||||
|
struct EventLoopWaker {
|
||||||
|
timer: CFRunLoopTimerRef,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for EventLoopWaker {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
CFRunLoopTimerInvalidate(self.timer);
|
||||||
|
CFRelease(self.timer as _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopWaker {
|
||||||
|
fn new(rl: CFRunLoopRef) -> EventLoopWaker {
|
||||||
|
extern "C" fn wakeup_main_loop(_timer: CFRunLoopTimerRef, _info: *mut c_void) {}
|
||||||
|
unsafe {
|
||||||
|
// Create a timer with a 0.1µs interval (1ns does not work) to mimic polling.
|
||||||
|
// It is initially setup with a first fire time really far into the
|
||||||
|
// future, but that gets changed to fire immediately in did_finish_launching
|
||||||
|
let timer = CFRunLoopTimerCreate(
|
||||||
|
ptr::null_mut(),
|
||||||
|
f64::MAX,
|
||||||
|
0.000_000_1,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
wakeup_main_loop,
|
||||||
|
ptr::null_mut(),
|
||||||
|
);
|
||||||
|
CFRunLoopAddTimer(rl, timer, kCFRunLoopCommonModes);
|
||||||
|
|
||||||
|
EventLoopWaker { timer }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stop(&mut self) {
|
||||||
|
unsafe { CFRunLoopTimerSetNextFireDate(self.timer, f64::MAX) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start(&mut self) {
|
||||||
|
unsafe { CFRunLoopTimerSetNextFireDate(self.timer, f64::MIN) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_at(&mut self, instant: Instant) {
|
||||||
|
let now = Instant::now();
|
||||||
|
if now >= instant {
|
||||||
|
self.start();
|
||||||
|
} else {
|
||||||
|
unsafe {
|
||||||
|
let current = CFAbsoluteTimeGetCurrent();
|
||||||
|
let duration = instant - now;
|
||||||
|
let fsecs =
|
||||||
|
duration.subsec_nanos() as f64 / 1_000_000_000.0 + duration.as_secs() as f64;
|
||||||
|
CFRunLoopTimerSetNextFireDate(self.timer, current + fsecs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! os_capabilities {
|
||||||
|
(
|
||||||
|
$(
|
||||||
|
$(#[$attr:meta])*
|
||||||
|
$error_name:ident: $objc_call:literal,
|
||||||
|
$name:ident: $major:literal-$minor:literal
|
||||||
|
),*
|
||||||
|
$(,)*
|
||||||
|
) => {
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct OSCapabilities {
|
||||||
|
$(
|
||||||
|
pub $name: bool,
|
||||||
|
)*
|
||||||
|
|
||||||
|
os_version: NSOperatingSystemVersion,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OSCapabilities {
|
||||||
|
fn from_os_version(os_version: NSOperatingSystemVersion) -> Self {
|
||||||
|
$(let $name = meets_requirements(os_version, $major, $minor);)*
|
||||||
|
Self { $($name,)* os_version, }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OSCapabilities {$(
|
||||||
|
$(#[$attr])*
|
||||||
|
pub fn $error_name(&self, extra_msg: &str) {
|
||||||
|
tracing::warn!(
|
||||||
|
concat!("`", $objc_call, "` requires iOS {}.{}+. This device is running iOS {}.{}.{}. {}"),
|
||||||
|
$major, $minor, self.os_version.majorVersion, self.os_version.minorVersion, self.os_version.patchVersion,
|
||||||
|
extra_msg
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)*}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
os_capabilities! {
|
||||||
|
/// <https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets?language=objc>
|
||||||
|
#[allow(unused)] // error message unused
|
||||||
|
safe_area_err_msg: "-[UIView safeAreaInsets]",
|
||||||
|
safe_area: 11-0,
|
||||||
|
/// <https://developer.apple.com/documentation/uikit/uiviewcontroller/2887509-setneedsupdateofhomeindicatoraut?language=objc>
|
||||||
|
home_indicator_hidden_err_msg: "-[UIViewController setNeedsUpdateOfHomeIndicatorAutoHidden]",
|
||||||
|
home_indicator_hidden: 11-0,
|
||||||
|
/// <https://developer.apple.com/documentation/uikit/uiviewcontroller/2887507-setneedsupdateofscreenedgesdefer?language=objc>
|
||||||
|
defer_system_gestures_err_msg: "-[UIViewController setNeedsUpdateOfScreenEdgesDeferringSystem]",
|
||||||
|
defer_system_gestures: 11-0,
|
||||||
|
/// <https://developer.apple.com/documentation/uikit/uiscreen/2806814-maximumframespersecond?language=objc>
|
||||||
|
maximum_frames_per_second_err_msg: "-[UIScreen maximumFramesPerSecond]",
|
||||||
|
maximum_frames_per_second: 10-3,
|
||||||
|
/// <https://developer.apple.com/documentation/uikit/uitouch/1618110-force?language=objc>
|
||||||
|
#[allow(unused)] // error message unused
|
||||||
|
force_touch_err_msg: "-[UITouch force]",
|
||||||
|
force_touch: 9-0,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn meets_requirements(
|
||||||
|
version: NSOperatingSystemVersion,
|
||||||
|
required_major: NSInteger,
|
||||||
|
required_minor: NSInteger,
|
||||||
|
) -> bool {
|
||||||
|
(version.majorVersion, version.minorVersion) >= (required_major, required_minor)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_version() -> NSOperatingSystemVersion {
|
||||||
|
let process_info = NSProcessInfo::processInfo();
|
||||||
|
let atleast_ios_8 = process_info.respondsToSelector(sel!(operatingSystemVersion));
|
||||||
|
// Winit requires atleast iOS 8 because no one has put the time into supporting earlier os
|
||||||
|
// versions. Older iOS versions are increasingly difficult to test. For example, Xcode 11 does
|
||||||
|
// not support debugging on devices with an iOS version of less than 8. Another example, in
|
||||||
|
// order to use an iOS simulator older than iOS 8, you must download an older version of Xcode
|
||||||
|
// (<9), and at least Xcode 7 has been tested to not even run on macOS 10.15 - Xcode 8 might?
|
||||||
|
//
|
||||||
|
// The minimum required iOS version is likely to grow in the future.
|
||||||
|
assert!(atleast_ios_8, "`winit` requires iOS version 8 or greater");
|
||||||
|
process_info.operatingSystemVersion()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn os_capabilities() -> OSCapabilities {
|
||||||
|
// Cache the version lookup for efficiency
|
||||||
|
static OS_CAPABILITIES: OnceLock<OSCapabilities> = OnceLock::new();
|
||||||
|
OS_CAPABILITIES.get_or_init(|| OSCapabilities::from_os_version(get_version())).clone()
|
||||||
|
}
|
||||||
428
src/platform_impl/apple/uikit/event_loop.rs
Normal file
428
src/platform_impl/apple/uikit/event_loop.rs
Normal file
@@ -0,0 +1,428 @@
|
|||||||
|
use std::ffi::{c_char, c_int, c_void};
|
||||||
|
use std::ptr::{self, NonNull};
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
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, NSNotificationCenter, NSObject};
|
||||||
|
use objc2_ui_kit::{
|
||||||
|
UIApplication, UIApplicationDidBecomeActiveNotification,
|
||||||
|
UIApplicationDidEnterBackgroundNotification, UIApplicationDidFinishLaunchingNotification,
|
||||||
|
UIApplicationDidReceiveMemoryWarningNotification, UIApplicationMain,
|
||||||
|
UIApplicationWillEnterForegroundNotification, UIApplicationWillResignActiveNotification,
|
||||||
|
UIApplicationWillTerminateNotification, UIScreen,
|
||||||
|
};
|
||||||
|
use rwh_06::HasDisplayHandle;
|
||||||
|
|
||||||
|
use super::super::notification_center::create_observer;
|
||||||
|
use super::app_state::{send_occluded_event_for_all_windows, AppState};
|
||||||
|
use super::{app_state, monitor, MonitorHandle};
|
||||||
|
use crate::application::ApplicationHandler;
|
||||||
|
use crate::error::{EventLoopError, NotSupportedError, RequestError};
|
||||||
|
use crate::event_loop::{
|
||||||
|
ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents,
|
||||||
|
EventLoopProxy as CoreEventLoopProxy, EventLoopProxyProvider,
|
||||||
|
OwnedDisplayHandle as CoreOwnedDisplayHandle,
|
||||||
|
};
|
||||||
|
use crate::monitor::MonitorHandle as RootMonitorHandle;
|
||||||
|
use crate::platform_impl::Window;
|
||||||
|
use crate::window::{CustomCursor, CustomCursorSource, Theme, Window as CoreWindow};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(crate) struct ActiveEventLoop {
|
||||||
|
pub(super) mtm: MainThreadMarker,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RootActiveEventLoop for ActiveEventLoop {
|
||||||
|
fn create_proxy(&self) -> CoreEventLoopProxy {
|
||||||
|
CoreEventLoopProxy::new(AppState::get_mut(self.mtm).event_loop_proxy().clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_window(
|
||||||
|
&self,
|
||||||
|
window_attributes: crate::window::WindowAttributes,
|
||||||
|
) -> Result<Box<dyn CoreWindow>, RequestError> {
|
||||||
|
Ok(Box::new(Window::new(self, window_attributes)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_custom_cursor(
|
||||||
|
&self,
|
||||||
|
_source: CustomCursorSource,
|
||||||
|
) -> Result<CustomCursor, RequestError> {
|
||||||
|
Err(NotSupportedError::new("create_custom_cursor is not supported").into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn available_monitors(&self) -> Box<dyn Iterator<Item = RootMonitorHandle>> {
|
||||||
|
Box::new(monitor::uiscreens(self.mtm).into_iter().map(|inner| RootMonitorHandle { inner }))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn primary_monitor(&self) -> Option<crate::monitor::MonitorHandle> {
|
||||||
|
#[allow(deprecated)]
|
||||||
|
let monitor = MonitorHandle::new(UIScreen::mainScreen(self.mtm));
|
||||||
|
Some(RootMonitorHandle { inner: monitor })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn listen_device_events(&self, _allowed: DeviceEvents) {}
|
||||||
|
|
||||||
|
fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||||
|
AppState::get_mut(self.mtm).set_control_flow(control_flow)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn system_theme(&self) -> Option<Theme> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn control_flow(&self) -> ControlFlow {
|
||||||
|
AppState::get_mut(self.mtm).control_flow()
|
||||||
|
}
|
||||||
|
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exiting(&self) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
fn owned_display_handle(&self) -> CoreOwnedDisplayHandle {
|
||||||
|
CoreOwnedDisplayHandle::new(Arc::new(OwnedDisplayHandle))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rwh_06_handle(&self) -> &dyn rwh_06::HasDisplayHandle {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl rwh_06::HasDisplayHandle for ActiveEventLoop {
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let raw = rwh_06::RawDisplayHandle::UiKit(rwh_06::UiKitDisplayHandle::new());
|
||||||
|
unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Eq)]
|
||||||
|
pub(crate) struct OwnedDisplayHandle;
|
||||||
|
|
||||||
|
impl HasDisplayHandle for OwnedDisplayHandle {
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let raw = rwh_06::RawDisplayHandle::UiKit(rwh_06::UiKitDisplayHandle::new());
|
||||||
|
unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct EventLoop {
|
||||||
|
mtm: MainThreadMarker,
|
||||||
|
window_target: ActiveEventLoop,
|
||||||
|
|
||||||
|
// Since iOS 9.0, we no longer need to remove the observers before they are deallocated; the
|
||||||
|
// system instead cleans it up next time it would have posted a notification to it.
|
||||||
|
//
|
||||||
|
// Though we do still need to keep the observers around to prevent them from being deallocated.
|
||||||
|
_did_finish_launching_observer: Retained<NSObject>,
|
||||||
|
_did_become_active_observer: Retained<NSObject>,
|
||||||
|
_will_resign_active_observer: Retained<NSObject>,
|
||||||
|
_will_enter_foreground_observer: Retained<NSObject>,
|
||||||
|
_did_enter_background_observer: Retained<NSObject>,
|
||||||
|
_will_terminate_observer: Retained<NSObject>,
|
||||||
|
_did_receive_memory_warning_observer: Retained<NSObject>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub(crate) struct PlatformSpecificEventLoopAttributes {}
|
||||||
|
|
||||||
|
impl EventLoop {
|
||||||
|
pub(crate) fn new(
|
||||||
|
_: &PlatformSpecificEventLoopAttributes,
|
||||||
|
) -> Result<EventLoop, 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// this line sets up the main run loop before `UIApplicationMain`
|
||||||
|
setup_control_flow_observers();
|
||||||
|
|
||||||
|
let center = unsafe { NSNotificationCenter::defaultCenter() };
|
||||||
|
|
||||||
|
let _did_finish_launching_observer = create_observer(
|
||||||
|
¢er,
|
||||||
|
// `application:didFinishLaunchingWithOptions:`
|
||||||
|
unsafe { UIApplicationDidFinishLaunchingNotification },
|
||||||
|
move |_| {
|
||||||
|
app_state::did_finish_launching(mtm);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let _did_become_active_observer = create_observer(
|
||||||
|
¢er,
|
||||||
|
// `applicationDidBecomeActive:`
|
||||||
|
unsafe { UIApplicationDidBecomeActiveNotification },
|
||||||
|
move |_| app_state::handle_resumed(mtm),
|
||||||
|
);
|
||||||
|
let _will_resign_active_observer = create_observer(
|
||||||
|
¢er,
|
||||||
|
// `applicationWillResignActive:`
|
||||||
|
unsafe { UIApplicationWillResignActiveNotification },
|
||||||
|
move |_| app_state::handle_suspended(mtm),
|
||||||
|
);
|
||||||
|
let _will_enter_foreground_observer = create_observer(
|
||||||
|
¢er,
|
||||||
|
// `applicationWillEnterForeground:`
|
||||||
|
unsafe { UIApplicationWillEnterForegroundNotification },
|
||||||
|
move |notification| {
|
||||||
|
let app = unsafe { notification.object() }.expect(
|
||||||
|
"UIApplicationWillEnterForegroundNotification to have application object",
|
||||||
|
);
|
||||||
|
// SAFETY: The `object` in `UIApplicationWillEnterForegroundNotification` is
|
||||||
|
// documented to be `UIApplication`.
|
||||||
|
let app: Retained<UIApplication> = unsafe { Retained::cast(app) };
|
||||||
|
send_occluded_event_for_all_windows(&app, false);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let _did_enter_background_observer = create_observer(
|
||||||
|
¢er,
|
||||||
|
// `applicationDidEnterBackground:`
|
||||||
|
unsafe { UIApplicationDidEnterBackgroundNotification },
|
||||||
|
move |notification| {
|
||||||
|
let app = unsafe { notification.object() }.expect(
|
||||||
|
"UIApplicationDidEnterBackgroundNotification to have application object",
|
||||||
|
);
|
||||||
|
// SAFETY: The `object` in `UIApplicationDidEnterBackgroundNotification` is
|
||||||
|
// documented to be `UIApplication`.
|
||||||
|
let app: Retained<UIApplication> = unsafe { Retained::cast(app) };
|
||||||
|
send_occluded_event_for_all_windows(&app, true);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let _will_terminate_observer = create_observer(
|
||||||
|
¢er,
|
||||||
|
// `applicationWillTerminate:`
|
||||||
|
unsafe { UIApplicationWillTerminateNotification },
|
||||||
|
move |notification| {
|
||||||
|
let app = unsafe { notification.object() }
|
||||||
|
.expect("UIApplicationWillTerminateNotification to have application object");
|
||||||
|
// SAFETY: The `object` in `UIApplicationWillTerminateNotification` is
|
||||||
|
// (somewhat) documented to be `UIApplication`.
|
||||||
|
let app: Retained<UIApplication> = unsafe { Retained::cast(app) };
|
||||||
|
app_state::terminated(&app);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let _did_receive_memory_warning_observer = create_observer(
|
||||||
|
¢er,
|
||||||
|
// `applicationDidReceiveMemoryWarning:`
|
||||||
|
unsafe { UIApplicationDidReceiveMemoryWarningNotification },
|
||||||
|
move |_| app_state::handle_memory_warning(mtm),
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(EventLoop {
|
||||||
|
mtm,
|
||||||
|
window_target: ActiveEventLoop { mtm },
|
||||||
|
_did_finish_launching_observer,
|
||||||
|
_did_become_active_observer,
|
||||||
|
_will_resign_active_observer,
|
||||||
|
_will_enter_foreground_observer,
|
||||||
|
_did_enter_background_observer,
|
||||||
|
_will_terminate_observer,
|
||||||
|
_did_receive_memory_warning_observer,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run_app<A: ApplicationHandler>(self, mut app: A) -> ! {
|
||||||
|
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",
|
||||||
|
);
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
// These functions are in crt_externs.h.
|
||||||
|
fn _NSGetArgc() -> *mut c_int;
|
||||||
|
fn _NSGetArgv() -> *mut *mut *mut c_char;
|
||||||
|
}
|
||||||
|
|
||||||
|
app_state::launch(self.mtm, &mut app, || unsafe {
|
||||||
|
UIApplicationMain(
|
||||||
|
*_NSGetArgc(),
|
||||||
|
NonNull::new(*_NSGetArgv()).unwrap(),
|
||||||
|
// We intentionally override neither the application nor the delegate, to allow
|
||||||
|
// the user to do so themselves!
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
unreachable!()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn window_target(&self) -> &dyn RootActiveEventLoop {
|
||||||
|
&self.window_target
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct EventLoopProxy {
|
||||||
|
pub(crate) wake_up: AtomicBool,
|
||||||
|
source: CFRunLoopSourceRef,
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl Send for EventLoopProxy {}
|
||||||
|
unsafe impl Sync for EventLoopProxy {}
|
||||||
|
|
||||||
|
impl Drop for EventLoopProxy {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
CFRunLoopSourceInvalidate(self.source);
|
||||||
|
CFRelease(self.source as _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopProxy {
|
||||||
|
pub(crate) fn new() -> EventLoopProxy {
|
||||||
|
unsafe {
|
||||||
|
// just wake up the eventloop
|
||||||
|
extern "C" fn event_loop_proxy_handler(_: *const c_void) {}
|
||||||
|
|
||||||
|
// adding a Source to the main CFRunLoop lets us wake it up and
|
||||||
|
// process user events through the normal OS EventLoop mechanisms.
|
||||||
|
let rl = CFRunLoopGetMain();
|
||||||
|
let mut context = CFRunLoopSourceContext {
|
||||||
|
version: 0,
|
||||||
|
info: ptr::null_mut(),
|
||||||
|
retain: None,
|
||||||
|
release: None,
|
||||||
|
copyDescription: None,
|
||||||
|
equal: None,
|
||||||
|
hash: None,
|
||||||
|
schedule: None,
|
||||||
|
cancel: None,
|
||||||
|
perform: event_loop_proxy_handler,
|
||||||
|
};
|
||||||
|
let source = CFRunLoopSourceCreate(ptr::null_mut(), CFIndex::MAX - 1, &mut context);
|
||||||
|
CFRunLoopAddSource(rl, source, kCFRunLoopCommonModes);
|
||||||
|
CFRunLoopWakeUp(rl);
|
||||||
|
|
||||||
|
EventLoopProxy { wake_up: AtomicBool::new(false), source }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopProxyProvider for EventLoopProxy {
|
||||||
|
fn wake_up(&self) {
|
||||||
|
self.wake_up.store(true, AtomicOrdering::Relaxed);
|
||||||
|
unsafe {
|
||||||
|
// let the main thread know there's a new event
|
||||||
|
CFRunLoopSourceSignal(self.source);
|
||||||
|
let rl = CFRunLoopGetMain();
|
||||||
|
CFRunLoopWakeUp(rl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
33
src/platform_impl/apple/uikit/mod.rs
Normal file
33
src/platform_impl/apple/uikit/mod.rs
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
#![allow(clippy::let_unit_value)]
|
||||||
|
|
||||||
|
mod app_state;
|
||||||
|
mod event_loop;
|
||||||
|
mod monitor;
|
||||||
|
mod view;
|
||||||
|
mod view_controller;
|
||||||
|
mod window;
|
||||||
|
|
||||||
|
use std::fmt;
|
||||||
|
|
||||||
|
pub(crate) use self::event_loop::{
|
||||||
|
ActiveEventLoop, EventLoop, EventLoopProxy, PlatformSpecificEventLoopAttributes,
|
||||||
|
};
|
||||||
|
pub(crate) use self::monitor::{MonitorHandle, VideoModeHandle};
|
||||||
|
pub(crate) use self::window::{PlatformSpecificWindowAttributes, Window};
|
||||||
|
pub(crate) use crate::cursor::{
|
||||||
|
NoCustomCursor as PlatformCustomCursor, NoCustomCursor as PlatformCustomCursorSource,
|
||||||
|
};
|
||||||
|
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
||||||
|
pub(crate) use crate::platform_impl::Fullscreen;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub struct KeyEventExtra {}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum OsError {}
|
||||||
|
|
||||||
|
impl fmt::Display for OsError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "os error")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,31 +1,26 @@
|
|||||||
#![allow(clippy::unnecessary_cast)]
|
#![allow(clippy::unnecessary_cast)]
|
||||||
|
|
||||||
use std::{
|
use std::collections::{BTreeSet, VecDeque};
|
||||||
collections::{BTreeSet, VecDeque},
|
use std::num::{NonZeroU16, NonZeroU32};
|
||||||
fmt, hash, ptr,
|
use std::{fmt, hash, ptr};
|
||||||
};
|
|
||||||
|
|
||||||
use icrate::Foundation::{MainThreadBound, MainThreadMarker, NSInteger};
|
|
||||||
use objc2::mutability::IsRetainable;
|
use objc2::mutability::IsRetainable;
|
||||||
use objc2::rc::Id;
|
use objc2::rc::Retained;
|
||||||
use objc2::Message;
|
use objc2::Message;
|
||||||
|
use objc2_foundation::{run_on_main, MainThreadBound, MainThreadMarker, NSInteger};
|
||||||
|
use objc2_ui_kit::{UIScreen, UIScreenMode};
|
||||||
|
|
||||||
use super::uikit::{UIScreen, UIScreenMode};
|
use super::app_state;
|
||||||
use crate::{
|
use crate::dpi::{PhysicalPosition, PhysicalSize};
|
||||||
dpi::{PhysicalPosition, PhysicalSize},
|
use crate::monitor::VideoModeHandle as RootVideoModeHandle;
|
||||||
monitor::VideoModeHandle as RootVideoModeHandle,
|
|
||||||
platform_impl::platform::app_state,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Workaround for `MainThreadBound` implementing almost no traits
|
// Workaround for `MainThreadBound` implementing almost no traits
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct MainThreadBoundDelegateImpls<T>(MainThreadBound<Id<T>>);
|
struct MainThreadBoundDelegateImpls<T>(MainThreadBound<Retained<T>>);
|
||||||
|
|
||||||
impl<T: IsRetainable + Message> Clone for MainThreadBoundDelegateImpls<T> {
|
impl<T: IsRetainable + Message> Clone for MainThreadBoundDelegateImpls<T> {
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Self(MainThreadMarker::run_on_main(|mtm| {
|
Self(run_on_main(|mtm| MainThreadBound::new(Retained::clone(self.0.get(mtm)), mtm)))
|
||||||
MainThreadBound::new(Id::clone(self.0.get(mtm)), mtm)
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,7 +28,7 @@ impl<T: IsRetainable + Message> hash::Hash for MainThreadBoundDelegateImpls<T> {
|
|||||||
fn hash<H: hash::Hasher>(&self, state: &mut H) {
|
fn hash<H: hash::Hasher>(&self, state: &mut H) {
|
||||||
// SAFETY: Marker only used to get the pointer
|
// SAFETY: Marker only used to get the pointer
|
||||||
let mtm = unsafe { MainThreadMarker::new_unchecked() };
|
let mtm = unsafe { MainThreadMarker::new_unchecked() };
|
||||||
Id::as_ptr(self.0.get(mtm)).hash(state);
|
Retained::as_ptr(self.0.get(mtm)).hash(state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,7 +36,7 @@ impl<T: IsRetainable + Message> PartialEq for MainThreadBoundDelegateImpls<T> {
|
|||||||
fn eq(&self, other: &Self) -> bool {
|
fn eq(&self, other: &Self) -> bool {
|
||||||
// SAFETY: Marker only used to get the pointer
|
// SAFETY: Marker only used to get the pointer
|
||||||
let mtm = unsafe { MainThreadMarker::new_unchecked() };
|
let mtm = unsafe { MainThreadMarker::new_unchecked() };
|
||||||
Id::as_ptr(self.0.get(mtm)) == Id::as_ptr(other.0.get(mtm))
|
Retained::as_ptr(self.0.get(mtm)) == Retained::as_ptr(other.0.get(mtm))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,23 +45,21 @@ impl<T: IsRetainable + Message> Eq for MainThreadBoundDelegateImpls<T> {}
|
|||||||
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
|
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
|
||||||
pub struct VideoModeHandle {
|
pub struct VideoModeHandle {
|
||||||
pub(crate) size: (u32, u32),
|
pub(crate) size: (u32, u32),
|
||||||
pub(crate) bit_depth: u16,
|
pub(crate) refresh_rate_millihertz: Option<NonZeroU32>,
|
||||||
pub(crate) refresh_rate_millihertz: u32,
|
|
||||||
screen_mode: MainThreadBoundDelegateImpls<UIScreenMode>,
|
screen_mode: MainThreadBoundDelegateImpls<UIScreenMode>,
|
||||||
pub(crate) monitor: MonitorHandle,
|
pub(crate) monitor: MonitorHandle,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl VideoModeHandle {
|
impl VideoModeHandle {
|
||||||
fn new(
|
fn new(
|
||||||
uiscreen: Id<UIScreen>,
|
uiscreen: Retained<UIScreen>,
|
||||||
screen_mode: Id<UIScreenMode>,
|
screen_mode: Retained<UIScreenMode>,
|
||||||
mtm: MainThreadMarker,
|
mtm: MainThreadMarker,
|
||||||
) -> VideoModeHandle {
|
) -> VideoModeHandle {
|
||||||
let refresh_rate_millihertz = refresh_rate_millihertz(&uiscreen);
|
let refresh_rate_millihertz = refresh_rate_millihertz(&uiscreen);
|
||||||
let size = screen_mode.size();
|
let size = screen_mode.size();
|
||||||
VideoModeHandle {
|
VideoModeHandle {
|
||||||
size: (size.width as u32, size.height as u32),
|
size: (size.width as u32, size.height as u32),
|
||||||
bit_depth: 32,
|
|
||||||
refresh_rate_millihertz,
|
refresh_rate_millihertz,
|
||||||
screen_mode: MainThreadBoundDelegateImpls(MainThreadBound::new(screen_mode, mtm)),
|
screen_mode: MainThreadBoundDelegateImpls(MainThreadBound::new(screen_mode, mtm)),
|
||||||
monitor: MonitorHandle::new(uiscreen),
|
monitor: MonitorHandle::new(uiscreen),
|
||||||
@@ -77,11 +70,11 @@ impl VideoModeHandle {
|
|||||||
self.size.into()
|
self.size.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn bit_depth(&self) -> u16 {
|
pub fn bit_depth(&self) -> Option<NonZeroU16> {
|
||||||
self.bit_depth
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn refresh_rate_millihertz(&self) -> u32 {
|
pub fn refresh_rate_millihertz(&self) -> Option<NonZeroU32> {
|
||||||
self.refresh_rate_millihertz
|
self.refresh_rate_millihertz
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,18 +82,18 @@ impl VideoModeHandle {
|
|||||||
self.monitor.clone()
|
self.monitor.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn screen_mode(&self, mtm: MainThreadMarker) -> &Id<UIScreenMode> {
|
pub(super) fn screen_mode(&self, mtm: MainThreadMarker) -> &Retained<UIScreenMode> {
|
||||||
self.screen_mode.0.get(mtm)
|
self.screen_mode.0.get(mtm)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct MonitorHandle {
|
pub struct MonitorHandle {
|
||||||
ui_screen: MainThreadBound<Id<UIScreen>>,
|
ui_screen: MainThreadBound<Retained<UIScreen>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Clone for MonitorHandle {
|
impl Clone for MonitorHandle {
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
MainThreadMarker::run_on_main(|mtm| Self {
|
run_on_main(|mtm| Self {
|
||||||
ui_screen: MainThreadBound::new(self.ui_screen.get(mtm).clone(), mtm),
|
ui_screen: MainThreadBound::new(self.ui_screen.get(mtm).clone(), mtm),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -108,13 +101,20 @@ impl Clone for MonitorHandle {
|
|||||||
|
|
||||||
impl hash::Hash for MonitorHandle {
|
impl hash::Hash for MonitorHandle {
|
||||||
fn hash<H: hash::Hasher>(&self, state: &mut H) {
|
fn hash<H: hash::Hasher>(&self, state: &mut H) {
|
||||||
(self as *const Self).hash(state);
|
// SAFETY: Only getting the pointer.
|
||||||
|
let mtm = unsafe { MainThreadMarker::new_unchecked() };
|
||||||
|
Retained::as_ptr(self.ui_screen.get(mtm)).hash(state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PartialEq for MonitorHandle {
|
impl PartialEq for MonitorHandle {
|
||||||
fn eq(&self, other: &Self) -> bool {
|
fn eq(&self, other: &Self) -> bool {
|
||||||
ptr::eq(self, other)
|
// SAFETY: Only getting the pointer.
|
||||||
|
let mtm = unsafe { MainThreadMarker::new_unchecked() };
|
||||||
|
ptr::eq(
|
||||||
|
Retained::as_ptr(self.ui_screen.get(mtm)),
|
||||||
|
Retained::as_ptr(other.ui_screen.get(mtm)),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,8 +128,10 @@ impl PartialOrd for MonitorHandle {
|
|||||||
|
|
||||||
impl Ord for MonitorHandle {
|
impl Ord for MonitorHandle {
|
||||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||||
|
// SAFETY: Only getting the pointer.
|
||||||
// TODO: Make a better ordering
|
// TODO: Make a better ordering
|
||||||
(self as *const Self).cmp(&(other as *const Self))
|
let mtm = unsafe { MainThreadMarker::new_unchecked() };
|
||||||
|
Retained::as_ptr(self.ui_screen.get(mtm)).cmp(&Retained::as_ptr(other.ui_screen.get(mtm)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,31 +139,29 @@ impl fmt::Debug for MonitorHandle {
|
|||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.debug_struct("MonitorHandle")
|
f.debug_struct("MonitorHandle")
|
||||||
.field("name", &self.name())
|
.field("name", &self.name())
|
||||||
.field("size", &self.size())
|
|
||||||
.field("position", &self.position())
|
.field("position", &self.position())
|
||||||
.field("scale_factor", &self.scale_factor())
|
.field("scale_factor", &self.scale_factor())
|
||||||
.field("refresh_rate_millihertz", &self.refresh_rate_millihertz())
|
|
||||||
.finish_non_exhaustive()
|
.finish_non_exhaustive()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MonitorHandle {
|
impl MonitorHandle {
|
||||||
pub(crate) fn new(ui_screen: Id<UIScreen>) -> Self {
|
pub(crate) fn new(ui_screen: Retained<UIScreen>) -> Self {
|
||||||
// Holding `Id<UIScreen>` implies we're on the main thread.
|
// Holding `Retained<UIScreen>` implies we're on the main thread.
|
||||||
let mtm = MainThreadMarker::new().unwrap();
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
Self {
|
Self { ui_screen: MainThreadBound::new(ui_screen, mtm) }
|
||||||
ui_screen: MainThreadBound::new(ui_screen, mtm),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn name(&self) -> Option<String> {
|
pub fn name(&self) -> Option<String> {
|
||||||
MainThreadMarker::run_on_main(|mtm| {
|
run_on_main(|mtm| {
|
||||||
let main = UIScreen::main(mtm);
|
#[allow(deprecated)]
|
||||||
|
let main = UIScreen::mainScreen(mtm);
|
||||||
if *self.ui_screen(mtm) == main {
|
if *self.ui_screen(mtm) == main {
|
||||||
Some("Primary".to_string())
|
Some("Primary".to_string())
|
||||||
} else if *self.ui_screen(mtm) == main.mirroredScreen() {
|
} else if Some(self.ui_screen(mtm)) == main.mirroredScreen().as_ref() {
|
||||||
Some("Mirrored".to_string())
|
Some("Mirrored".to_string())
|
||||||
} else {
|
} else {
|
||||||
|
#[allow(deprecated)]
|
||||||
UIScreen::screens(mtm)
|
UIScreen::screens(mtm)
|
||||||
.iter()
|
.iter()
|
||||||
.position(|rhs| rhs == &**self.ui_screen(mtm))
|
.position(|rhs| rhs == &**self.ui_screen(mtm))
|
||||||
@@ -170,34 +170,27 @@ impl MonitorHandle {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn size(&self) -> PhysicalSize<u32> {
|
pub fn position(&self) -> Option<PhysicalPosition<i32>> {
|
||||||
let bounds = self
|
let bounds = self.ui_screen.get_on_main(|ui_screen| ui_screen.nativeBounds());
|
||||||
.ui_screen
|
Some((bounds.origin.x as f64, bounds.origin.y as f64).into())
|
||||||
.get_on_main(|ui_screen| ui_screen.nativeBounds());
|
|
||||||
PhysicalSize::new(bounds.size.width as u32, bounds.size.height as u32)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn position(&self) -> PhysicalPosition<i32> {
|
|
||||||
let bounds = self
|
|
||||||
.ui_screen
|
|
||||||
.get_on_main(|ui_screen| ui_screen.nativeBounds());
|
|
||||||
(bounds.origin.x as f64, bounds.origin.y as f64).into()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn scale_factor(&self) -> f64 {
|
pub fn scale_factor(&self) -> f64 {
|
||||||
self.ui_screen
|
self.ui_screen.get_on_main(|ui_screen| ui_screen.nativeScale()) as f64
|
||||||
.get_on_main(|ui_screen| ui_screen.nativeScale()) as f64
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn refresh_rate_millihertz(&self) -> Option<u32> {
|
pub fn current_video_mode(&self) -> Option<VideoModeHandle> {
|
||||||
Some(
|
Some(run_on_main(|mtm| {
|
||||||
self.ui_screen
|
VideoModeHandle::new(
|
||||||
.get_on_main(|ui_screen| refresh_rate_millihertz(ui_screen)),
|
self.ui_screen(mtm).clone(),
|
||||||
)
|
self.ui_screen(mtm).currentMode().unwrap(),
|
||||||
|
mtm,
|
||||||
|
)
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> {
|
pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> {
|
||||||
MainThreadMarker::run_on_main(|mtm| {
|
run_on_main(|mtm| {
|
||||||
let ui_screen = self.ui_screen(mtm);
|
let ui_screen = self.ui_screen(mtm);
|
||||||
// Use Ord impl of RootVideoModeHandle
|
// Use Ord impl of RootVideoModeHandle
|
||||||
|
|
||||||
@@ -213,12 +206,12 @@ impl MonitorHandle {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn ui_screen(&self, mtm: MainThreadMarker) -> &Id<UIScreen> {
|
pub(crate) fn ui_screen(&self, mtm: MainThreadMarker) -> &Retained<UIScreen> {
|
||||||
self.ui_screen.get(mtm)
|
self.ui_screen.get(mtm)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn preferred_video_mode(&self) -> VideoModeHandle {
|
pub fn preferred_video_mode(&self) -> VideoModeHandle {
|
||||||
MainThreadMarker::run_on_main(|mtm| {
|
run_on_main(|mtm| {
|
||||||
VideoModeHandle::new(
|
VideoModeHandle::new(
|
||||||
self.ui_screen(mtm).clone(),
|
self.ui_screen(mtm).clone(),
|
||||||
self.ui_screen(mtm).preferredMode().unwrap(),
|
self.ui_screen(mtm).preferredMode().unwrap(),
|
||||||
@@ -228,7 +221,7 @@ impl MonitorHandle {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn refresh_rate_millihertz(uiscreen: &UIScreen) -> u32 {
|
fn refresh_rate_millihertz(uiscreen: &UIScreen) -> Option<NonZeroU32> {
|
||||||
let refresh_rate_millihertz: NSInteger = {
|
let refresh_rate_millihertz: NSInteger = {
|
||||||
let os_capabilities = app_state::os_capabilities();
|
let os_capabilities = app_state::os_capabilities();
|
||||||
if os_capabilities.maximum_frames_per_second {
|
if os_capabilities.maximum_frames_per_second {
|
||||||
@@ -249,12 +242,34 @@ fn refresh_rate_millihertz(uiscreen: &UIScreen) -> u32 {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
refresh_rate_millihertz as u32 * 1000
|
NonZeroU32::new(refresh_rate_millihertz as u32 * 1000)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn uiscreens(mtm: MainThreadMarker) -> VecDeque<MonitorHandle> {
|
pub fn uiscreens(mtm: MainThreadMarker) -> VecDeque<MonitorHandle> {
|
||||||
UIScreen::screens(mtm)
|
#[allow(deprecated)]
|
||||||
.into_iter()
|
UIScreen::screens(mtm).into_iter().map(MonitorHandle::new).collect()
|
||||||
.map(MonitorHandle::new)
|
}
|
||||||
.collect()
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use objc2_foundation::NSSet;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
// Test that UIScreen pointer comparisons are correct.
|
||||||
|
#[test]
|
||||||
|
#[allow(deprecated)]
|
||||||
|
fn screen_comparisons() {
|
||||||
|
// Test code, doesn't matter that it's not thread safe
|
||||||
|
let mtm = unsafe { MainThreadMarker::new_unchecked() };
|
||||||
|
|
||||||
|
assert!(ptr::eq(&*UIScreen::mainScreen(mtm), &*UIScreen::mainScreen(mtm)));
|
||||||
|
|
||||||
|
let main = UIScreen::mainScreen(mtm);
|
||||||
|
assert!(UIScreen::screens(mtm).iter().any(|screen| ptr::eq(screen, &*main)));
|
||||||
|
|
||||||
|
assert!(unsafe {
|
||||||
|
NSSet::setWithArray(&UIScreen::screens(mtm)).containsObject(&UIScreen::mainScreen(mtm))
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
697
src/platform_impl/apple/uikit/view.rs
Normal file
697
src/platform_impl/apple/uikit/view.rs
Normal file
@@ -0,0 +1,697 @@
|
|||||||
|
#![allow(clippy::unnecessary_cast)]
|
||||||
|
use std::cell::{Cell, RefCell};
|
||||||
|
|
||||||
|
use objc2::rc::Retained;
|
||||||
|
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
|
||||||
|
use objc2::{declare_class, msg_send, msg_send_id, mutability, sel, ClassType, DeclaredClass};
|
||||||
|
use objc2_foundation::{CGFloat, CGPoint, CGRect, MainThreadMarker, NSObject, NSSet, NSString};
|
||||||
|
use objc2_ui_kit::{
|
||||||
|
UIEvent, UIForceTouchCapability, UIGestureRecognizer, UIGestureRecognizerDelegate,
|
||||||
|
UIGestureRecognizerState, UIKeyInput, UIPanGestureRecognizer, UIPinchGestureRecognizer,
|
||||||
|
UIResponder, UIRotationGestureRecognizer, UITapGestureRecognizer, UITextInputTraits, UITouch,
|
||||||
|
UITouchPhase, UITouchType, UITraitEnvironment, UIView,
|
||||||
|
};
|
||||||
|
use tracing::debug;
|
||||||
|
|
||||||
|
use super::app_state::{self, EventWrapper};
|
||||||
|
use super::window::WinitUIWindow;
|
||||||
|
use crate::dpi::PhysicalPosition;
|
||||||
|
use crate::event::{
|
||||||
|
ButtonSource, ElementState, FingerId, Force, KeyEvent, PointerKind, PointerSource, TouchPhase,
|
||||||
|
WindowEvent,
|
||||||
|
};
|
||||||
|
use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKeyCode, PhysicalKey};
|
||||||
|
use crate::platform_impl::KeyEventExtra;
|
||||||
|
use crate::window::WindowAttributes;
|
||||||
|
|
||||||
|
pub struct WinitViewState {
|
||||||
|
pinch_gesture_recognizer: RefCell<Option<Retained<UIPinchGestureRecognizer>>>,
|
||||||
|
doubletap_gesture_recognizer: RefCell<Option<Retained<UITapGestureRecognizer>>>,
|
||||||
|
rotation_gesture_recognizer: RefCell<Option<Retained<UIRotationGestureRecognizer>>>,
|
||||||
|
pan_gesture_recognizer: RefCell<Option<Retained<UIPanGestureRecognizer>>>,
|
||||||
|
|
||||||
|
// for iOS delta references the start of the Gesture
|
||||||
|
rotation_last_delta: Cell<CGFloat>,
|
||||||
|
pinch_last_delta: Cell<CGFloat>,
|
||||||
|
pan_last_delta: Cell<CGPoint>,
|
||||||
|
|
||||||
|
primary_finger: Cell<Option<FingerId>>,
|
||||||
|
fingers: Cell<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
declare_class!(
|
||||||
|
pub(crate) struct WinitView;
|
||||||
|
|
||||||
|
unsafe impl ClassType for WinitView {
|
||||||
|
#[inherits(UIResponder, NSObject)]
|
||||||
|
type Super = UIView;
|
||||||
|
type Mutability = mutability::MainThreadOnly;
|
||||||
|
const NAME: &'static str = "WinitUIView";
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DeclaredClass for WinitView {
|
||||||
|
type Ivars = WinitViewState;
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl WinitView {
|
||||||
|
#[method(drawRect:)]
|
||||||
|
fn draw_rect(&self, rect: CGRect) {
|
||||||
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
let window = self.window().unwrap();
|
||||||
|
app_state::handle_nonuser_event(
|
||||||
|
mtm,
|
||||||
|
EventWrapper::Window {
|
||||||
|
window_id: window.id(),
|
||||||
|
event: WindowEvent::RedrawRequested,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let _: () = unsafe { msg_send![super(self), drawRect: rect] };
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(layoutSubviews)]
|
||||||
|
fn layout_subviews(&self) {
|
||||||
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
let _: () = unsafe { msg_send![super(self), layoutSubviews] };
|
||||||
|
|
||||||
|
let frame = self.frame();
|
||||||
|
let scale_factor = self.contentScaleFactor() as f64;
|
||||||
|
let size = crate::dpi::LogicalSize {
|
||||||
|
width: frame.size.width as f64,
|
||||||
|
height: frame.size.height as f64,
|
||||||
|
}
|
||||||
|
.to_physical(scale_factor);
|
||||||
|
|
||||||
|
let window = self.window().unwrap();
|
||||||
|
app_state::handle_nonuser_event(
|
||||||
|
mtm,
|
||||||
|
EventWrapper::Window {
|
||||||
|
window_id: window.id(),
|
||||||
|
event: WindowEvent::SurfaceResized(size),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(setContentScaleFactor:)]
|
||||||
|
fn set_content_scale_factor(&self, untrusted_scale_factor: CGFloat) {
|
||||||
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
let _: () =
|
||||||
|
unsafe { msg_send![super(self), setContentScaleFactor: untrusted_scale_factor] };
|
||||||
|
|
||||||
|
// `window` is null when `setContentScaleFactor` is invoked prior to `[UIWindow
|
||||||
|
// makeKeyAndVisible]` at window creation time (either manually or internally by
|
||||||
|
// UIKit when the `UIView` is first created), in which case we send no events here
|
||||||
|
let window = match self.window() {
|
||||||
|
Some(window) => window,
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
// `setContentScaleFactor` may be called with a value of 0, which means "reset the
|
||||||
|
// content scale factor to a device-specific default value", so we can't use the
|
||||||
|
// parameter here. We can query the actual factor using the getter
|
||||||
|
let scale_factor = self.contentScaleFactor();
|
||||||
|
assert!(
|
||||||
|
!scale_factor.is_nan()
|
||||||
|
&& scale_factor.is_finite()
|
||||||
|
&& scale_factor.is_sign_positive()
|
||||||
|
&& scale_factor > 0.0,
|
||||||
|
"invalid scale_factor set on UIView",
|
||||||
|
);
|
||||||
|
let scale_factor = scale_factor as f64;
|
||||||
|
let frame = self.frame();
|
||||||
|
let size = crate::dpi::LogicalSize {
|
||||||
|
width: frame.size.width as f64,
|
||||||
|
height: frame.size.height as f64,
|
||||||
|
};
|
||||||
|
let window_id = window.id();
|
||||||
|
app_state::handle_nonuser_events(
|
||||||
|
mtm,
|
||||||
|
std::iter::once(EventWrapper::ScaleFactorChanged(
|
||||||
|
app_state::ScaleFactorChanged {
|
||||||
|
window,
|
||||||
|
scale_factor,
|
||||||
|
suggested_size: size.to_physical(scale_factor),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
.chain(std::iter::once(EventWrapper::Window {
|
||||||
|
window_id,
|
||||||
|
event: WindowEvent::SurfaceResized(size.to_physical(scale_factor)),
|
||||||
|
},
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(safeAreaInsetsDidChange)]
|
||||||
|
fn safe_area_changed(&self) {
|
||||||
|
debug!("safeAreaInsetsDidChange was called, requesting redraw");
|
||||||
|
// When the safe area changes we want to make sure to emit a redraw event
|
||||||
|
self.setNeedsDisplay();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(touchesBegan:withEvent:)]
|
||||||
|
fn touches_began(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) {
|
||||||
|
self.handle_touches(touches)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(touchesMoved:withEvent:)]
|
||||||
|
fn touches_moved(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) {
|
||||||
|
self.handle_touches(touches)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(touchesEnded:withEvent:)]
|
||||||
|
fn touches_ended(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) {
|
||||||
|
self.handle_touches(touches)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(touchesCancelled:withEvent:)]
|
||||||
|
fn touches_cancelled(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) {
|
||||||
|
self.handle_touches(touches)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(pinchGesture:)]
|
||||||
|
fn pinch_gesture(&self, recognizer: &UIPinchGestureRecognizer) {
|
||||||
|
let window = self.window().unwrap();
|
||||||
|
|
||||||
|
let (phase, delta) = match recognizer.state() {
|
||||||
|
UIGestureRecognizerState::Began => {
|
||||||
|
self.ivars().pinch_last_delta.set(recognizer.scale());
|
||||||
|
(TouchPhase::Started, 0.0)
|
||||||
|
}
|
||||||
|
UIGestureRecognizerState::Changed => {
|
||||||
|
let last_scale: f64 = self.ivars().pinch_last_delta.replace(recognizer.scale());
|
||||||
|
(TouchPhase::Moved, recognizer.scale() - last_scale)
|
||||||
|
}
|
||||||
|
UIGestureRecognizerState::Ended => {
|
||||||
|
let last_scale: f64 = self.ivars().pinch_last_delta.replace(0.0);
|
||||||
|
(TouchPhase::Moved, recognizer.scale() - last_scale)
|
||||||
|
}
|
||||||
|
UIGestureRecognizerState::Cancelled | UIGestureRecognizerState::Failed => {
|
||||||
|
self.ivars().rotation_last_delta.set(0.0);
|
||||||
|
// Pass -delta so that action is reversed
|
||||||
|
(TouchPhase::Cancelled, -recognizer.scale())
|
||||||
|
}
|
||||||
|
state => panic!("unexpected recognizer state: {state:?}"),
|
||||||
|
};
|
||||||
|
|
||||||
|
let gesture_event = EventWrapper::Window {
|
||||||
|
window_id: window.id(),
|
||||||
|
event: WindowEvent::PinchGesture {
|
||||||
|
device_id: None,
|
||||||
|
delta: delta as f64,
|
||||||
|
phase,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
app_state::handle_nonuser_event(mtm, gesture_event);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(doubleTapGesture:)]
|
||||||
|
fn double_tap_gesture(&self, recognizer: &UITapGestureRecognizer) {
|
||||||
|
let window = self.window().unwrap();
|
||||||
|
|
||||||
|
if recognizer.state() == UIGestureRecognizerState::Ended {
|
||||||
|
let gesture_event = EventWrapper::Window {
|
||||||
|
window_id: window.id(),
|
||||||
|
event: WindowEvent::DoubleTapGesture {
|
||||||
|
device_id: None,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
app_state::handle_nonuser_event(mtm, gesture_event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(rotationGesture:)]
|
||||||
|
fn rotation_gesture(&self, recognizer: &UIRotationGestureRecognizer) {
|
||||||
|
let window = self.window().unwrap();
|
||||||
|
|
||||||
|
let (phase, delta) = match recognizer.state() {
|
||||||
|
UIGestureRecognizerState::Began => {
|
||||||
|
self.ivars().rotation_last_delta.set(0.0);
|
||||||
|
|
||||||
|
(TouchPhase::Started, 0.0)
|
||||||
|
}
|
||||||
|
UIGestureRecognizerState::Changed => {
|
||||||
|
let last_rotation = self.ivars().rotation_last_delta.replace(recognizer.rotation());
|
||||||
|
|
||||||
|
(TouchPhase::Moved, recognizer.rotation() - last_rotation)
|
||||||
|
}
|
||||||
|
UIGestureRecognizerState::Ended => {
|
||||||
|
let last_rotation = self.ivars().rotation_last_delta.replace(0.0);
|
||||||
|
|
||||||
|
(TouchPhase::Ended, recognizer.rotation() - last_rotation)
|
||||||
|
}
|
||||||
|
UIGestureRecognizerState::Cancelled | UIGestureRecognizerState::Failed => {
|
||||||
|
self.ivars().rotation_last_delta.set(0.0);
|
||||||
|
|
||||||
|
// Pass -delta so that action is reversed
|
||||||
|
(TouchPhase::Cancelled, -recognizer.rotation())
|
||||||
|
}
|
||||||
|
state => panic!("unexpected recognizer state: {state:?}"),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Make delta negative to match macos, convert to degrees
|
||||||
|
let gesture_event = EventWrapper::Window {
|
||||||
|
window_id: window.id(),
|
||||||
|
event: WindowEvent::RotationGesture {
|
||||||
|
device_id: None,
|
||||||
|
delta: -delta.to_degrees() as _,
|
||||||
|
phase,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
app_state::handle_nonuser_event(mtm, gesture_event);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(panGesture:)]
|
||||||
|
fn pan_gesture(&self, recognizer: &UIPanGestureRecognizer) {
|
||||||
|
let window = self.window().unwrap();
|
||||||
|
|
||||||
|
let translation = recognizer.translationInView(Some(self));
|
||||||
|
|
||||||
|
let (phase, dx, dy) = match recognizer.state() {
|
||||||
|
UIGestureRecognizerState::Began => {
|
||||||
|
self.ivars().pan_last_delta.set(translation);
|
||||||
|
|
||||||
|
(TouchPhase::Started, 0.0, 0.0)
|
||||||
|
}
|
||||||
|
UIGestureRecognizerState::Changed => {
|
||||||
|
let last_pan: CGPoint = self.ivars().pan_last_delta.replace(translation);
|
||||||
|
|
||||||
|
let dx = translation.x - last_pan.x;
|
||||||
|
let dy = translation.y - last_pan.y;
|
||||||
|
|
||||||
|
(TouchPhase::Moved, dx, dy)
|
||||||
|
}
|
||||||
|
UIGestureRecognizerState::Ended => {
|
||||||
|
let last_pan: CGPoint = self.ivars().pan_last_delta.replace(CGPoint{x:0.0, y:0.0});
|
||||||
|
|
||||||
|
let dx = translation.x - last_pan.x;
|
||||||
|
let dy = translation.y - last_pan.y;
|
||||||
|
|
||||||
|
(TouchPhase::Ended, dx, dy)
|
||||||
|
}
|
||||||
|
UIGestureRecognizerState::Cancelled | UIGestureRecognizerState::Failed => {
|
||||||
|
let last_pan: CGPoint = self.ivars().pan_last_delta.replace(CGPoint{x:0.0, y:0.0});
|
||||||
|
|
||||||
|
// Pass -delta so that action is reversed
|
||||||
|
(TouchPhase::Cancelled, -last_pan.x, -last_pan.y)
|
||||||
|
}
|
||||||
|
state => panic!("unexpected recognizer state: {state:?}"),
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
let gesture_event = EventWrapper::Window {
|
||||||
|
window_id: window.id(),
|
||||||
|
event: WindowEvent::PanGesture {
|
||||||
|
device_id: None,
|
||||||
|
delta: PhysicalPosition::new(dx as _, dy as _),
|
||||||
|
phase,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
app_state::handle_nonuser_event(mtm, gesture_event);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(canBecomeFirstResponder)]
|
||||||
|
fn can_become_first_responder(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl NSObjectProtocol for WinitView {}
|
||||||
|
|
||||||
|
unsafe impl UIGestureRecognizerDelegate for WinitView {
|
||||||
|
#[method(gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:)]
|
||||||
|
fn should_recognize_simultaneously(&self, _gesture_recognizer: &UIGestureRecognizer, _other_gesture_recognizer: &UIGestureRecognizer) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl UITextInputTraits for WinitView {
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl UIKeyInput for WinitView {
|
||||||
|
#[method(hasText)]
|
||||||
|
fn has_text(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(insertText:)]
|
||||||
|
fn insert_text(&self, text: &NSString) {
|
||||||
|
self.handle_insert_text(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(deleteBackward)]
|
||||||
|
fn delete_backward(&self) {
|
||||||
|
self.handle_delete_backward()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
impl WinitView {
|
||||||
|
pub(crate) fn new(
|
||||||
|
mtm: MainThreadMarker,
|
||||||
|
window_attributes: &WindowAttributes,
|
||||||
|
frame: CGRect,
|
||||||
|
) -> Retained<Self> {
|
||||||
|
let this = mtm.alloc().set_ivars(WinitViewState {
|
||||||
|
pinch_gesture_recognizer: RefCell::new(None),
|
||||||
|
doubletap_gesture_recognizer: RefCell::new(None),
|
||||||
|
rotation_gesture_recognizer: RefCell::new(None),
|
||||||
|
pan_gesture_recognizer: RefCell::new(None),
|
||||||
|
|
||||||
|
rotation_last_delta: Cell::new(0.0),
|
||||||
|
pinch_last_delta: Cell::new(0.0),
|
||||||
|
pan_last_delta: Cell::new(CGPoint { x: 0.0, y: 0.0 }),
|
||||||
|
|
||||||
|
primary_finger: Cell::new(None),
|
||||||
|
fingers: Cell::new(0),
|
||||||
|
});
|
||||||
|
let this: Retained<Self> = unsafe { msg_send_id![super(this), initWithFrame: frame] };
|
||||||
|
|
||||||
|
this.setMultipleTouchEnabled(true);
|
||||||
|
|
||||||
|
if let Some(scale_factor) = window_attributes.platform_specific.scale_factor {
|
||||||
|
this.setContentScaleFactor(scale_factor as _);
|
||||||
|
}
|
||||||
|
|
||||||
|
this
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window(&self) -> Option<Retained<WinitUIWindow>> {
|
||||||
|
// SAFETY: `WinitView`s are always installed in a `WinitUIWindow`
|
||||||
|
(**self).window().map(|window| unsafe { Retained::cast(window) })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn recognize_pinch_gesture(&self, should_recognize: bool) {
|
||||||
|
let mtm = MainThreadMarker::from(self);
|
||||||
|
if should_recognize {
|
||||||
|
if self.ivars().pinch_gesture_recognizer.borrow().is_none() {
|
||||||
|
let pinch = unsafe {
|
||||||
|
UIPinchGestureRecognizer::initWithTarget_action(
|
||||||
|
mtm.alloc(),
|
||||||
|
Some(self),
|
||||||
|
Some(sel!(pinchGesture:)),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
pinch.setDelegate(Some(ProtocolObject::from_ref(self)));
|
||||||
|
self.addGestureRecognizer(&pinch);
|
||||||
|
self.ivars().pinch_gesture_recognizer.replace(Some(pinch));
|
||||||
|
}
|
||||||
|
} else if let Some(recognizer) = self.ivars().pinch_gesture_recognizer.take() {
|
||||||
|
self.removeGestureRecognizer(&recognizer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn recognize_pan_gesture(
|
||||||
|
&self,
|
||||||
|
should_recognize: bool,
|
||||||
|
minimum_number_of_touches: u8,
|
||||||
|
maximum_number_of_touches: u8,
|
||||||
|
) {
|
||||||
|
let mtm = MainThreadMarker::from(self);
|
||||||
|
if should_recognize {
|
||||||
|
if self.ivars().pan_gesture_recognizer.borrow().is_none() {
|
||||||
|
let pan = unsafe {
|
||||||
|
UIPanGestureRecognizer::initWithTarget_action(
|
||||||
|
mtm.alloc(),
|
||||||
|
Some(self),
|
||||||
|
Some(sel!(panGesture:)),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
pan.setDelegate(Some(ProtocolObject::from_ref(self)));
|
||||||
|
pan.setMinimumNumberOfTouches(minimum_number_of_touches as _);
|
||||||
|
pan.setMaximumNumberOfTouches(maximum_number_of_touches as _);
|
||||||
|
self.addGestureRecognizer(&pan);
|
||||||
|
self.ivars().pan_gesture_recognizer.replace(Some(pan));
|
||||||
|
}
|
||||||
|
} else if let Some(recognizer) = self.ivars().pan_gesture_recognizer.take() {
|
||||||
|
self.removeGestureRecognizer(&recognizer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn recognize_doubletap_gesture(&self, should_recognize: bool) {
|
||||||
|
let mtm = MainThreadMarker::from(self);
|
||||||
|
if should_recognize {
|
||||||
|
if self.ivars().doubletap_gesture_recognizer.borrow().is_none() {
|
||||||
|
let tap = unsafe {
|
||||||
|
UITapGestureRecognizer::initWithTarget_action(
|
||||||
|
mtm.alloc(),
|
||||||
|
Some(self),
|
||||||
|
Some(sel!(doubleTapGesture:)),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
tap.setDelegate(Some(ProtocolObject::from_ref(self)));
|
||||||
|
tap.setNumberOfTapsRequired(2);
|
||||||
|
tap.setNumberOfTouchesRequired(1);
|
||||||
|
self.addGestureRecognizer(&tap);
|
||||||
|
self.ivars().doubletap_gesture_recognizer.replace(Some(tap));
|
||||||
|
}
|
||||||
|
} else if let Some(recognizer) = self.ivars().doubletap_gesture_recognizer.take() {
|
||||||
|
self.removeGestureRecognizer(&recognizer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn recognize_rotation_gesture(&self, should_recognize: bool) {
|
||||||
|
let mtm = MainThreadMarker::from(self);
|
||||||
|
if should_recognize {
|
||||||
|
if self.ivars().rotation_gesture_recognizer.borrow().is_none() {
|
||||||
|
let rotation = unsafe {
|
||||||
|
UIRotationGestureRecognizer::initWithTarget_action(
|
||||||
|
mtm.alloc(),
|
||||||
|
Some(self),
|
||||||
|
Some(sel!(rotationGesture:)),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
rotation.setDelegate(Some(ProtocolObject::from_ref(self)));
|
||||||
|
self.addGestureRecognizer(&rotation);
|
||||||
|
self.ivars().rotation_gesture_recognizer.replace(Some(rotation));
|
||||||
|
}
|
||||||
|
} else if let Some(recognizer) = self.ivars().rotation_gesture_recognizer.take() {
|
||||||
|
self.removeGestureRecognizer(&recognizer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_touches(&self, touches: &NSSet<UITouch>) {
|
||||||
|
let window = self.window().unwrap();
|
||||||
|
let mut touch_events = Vec::new();
|
||||||
|
let os_supports_force = app_state::os_capabilities().force_touch;
|
||||||
|
for touch in touches {
|
||||||
|
let logical_location = touch.locationInView(None);
|
||||||
|
let touch_type = touch.r#type();
|
||||||
|
let force = if let UITouchType::Pencil = touch_type {
|
||||||
|
None
|
||||||
|
} else if os_supports_force {
|
||||||
|
let trait_collection = self.traitCollection();
|
||||||
|
let touch_capability = trait_collection.forceTouchCapability();
|
||||||
|
// Both the OS _and_ the device need to be checked for force touch support.
|
||||||
|
if touch_capability == UIForceTouchCapability::Available {
|
||||||
|
let force = touch.force();
|
||||||
|
let max_possible_force = touch.maximumPossibleForce();
|
||||||
|
Some(Force::Calibrated {
|
||||||
|
force: force as _,
|
||||||
|
max_possible_force: max_possible_force as _,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let touch_id = touch as *const UITouch as usize;
|
||||||
|
let phase = touch.phase();
|
||||||
|
let position = {
|
||||||
|
let scale_factor = self.contentScaleFactor();
|
||||||
|
PhysicalPosition::from_logical::<(f64, f64), f64>(
|
||||||
|
(logical_location.x as _, logical_location.y as _),
|
||||||
|
scale_factor as f64,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let window_id = window.id();
|
||||||
|
let finger_id = FingerId::from_raw(touch_id);
|
||||||
|
|
||||||
|
let ivars = self.ivars();
|
||||||
|
|
||||||
|
match phase {
|
||||||
|
UITouchPhase::Began => {
|
||||||
|
let primary = if let UITouchType::Pencil = touch_type {
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
ivars.fingers.set(ivars.fingers.get() + 1);
|
||||||
|
// Keep the primary finger around until we clear all the fingers to
|
||||||
|
// recognize it when user briefly removes it.
|
||||||
|
match ivars.primary_finger.get() {
|
||||||
|
Some(primary_id) => primary_id == finger_id,
|
||||||
|
None => {
|
||||||
|
debug_assert_eq!(
|
||||||
|
ivars.fingers.get(),
|
||||||
|
1,
|
||||||
|
"number of fingers were not counted correctly"
|
||||||
|
);
|
||||||
|
ivars.primary_finger.set(Some(finger_id));
|
||||||
|
true
|
||||||
|
},
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
touch_events.push(EventWrapper::Window {
|
||||||
|
window_id,
|
||||||
|
event: WindowEvent::PointerEntered {
|
||||||
|
device_id: None,
|
||||||
|
primary,
|
||||||
|
position,
|
||||||
|
kind: if let UITouchType::Pencil = touch_type {
|
||||||
|
PointerKind::Unknown
|
||||||
|
} else {
|
||||||
|
PointerKind::Touch(finger_id)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
touch_events.push(EventWrapper::Window {
|
||||||
|
window_id,
|
||||||
|
event: WindowEvent::PointerButton {
|
||||||
|
device_id: None,
|
||||||
|
primary,
|
||||||
|
state: ElementState::Pressed,
|
||||||
|
position,
|
||||||
|
button: if let UITouchType::Pencil = touch_type {
|
||||||
|
ButtonSource::Unknown(0)
|
||||||
|
} else {
|
||||||
|
ButtonSource::Touch { finger_id, force }
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
UITouchPhase::Moved => {
|
||||||
|
let (primary, source) = if let UITouchType::Pencil = touch_type {
|
||||||
|
(true, PointerSource::Unknown)
|
||||||
|
} else {
|
||||||
|
(ivars.primary_finger.get().unwrap() == finger_id, PointerSource::Touch {
|
||||||
|
finger_id,
|
||||||
|
force,
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
|
touch_events.push(EventWrapper::Window {
|
||||||
|
window_id,
|
||||||
|
event: WindowEvent::PointerMoved {
|
||||||
|
device_id: None,
|
||||||
|
primary,
|
||||||
|
position,
|
||||||
|
source,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
// 2 is UITouchPhase::Stationary and is not expected here
|
||||||
|
UITouchPhase::Ended | UITouchPhase::Cancelled => {
|
||||||
|
let primary = if let UITouchType::Pencil = touch_type {
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
ivars.fingers.set(ivars.fingers.get() - 1);
|
||||||
|
let primary = ivars.primary_finger.get().unwrap() == finger_id;
|
||||||
|
if ivars.fingers.get() == 0 {
|
||||||
|
ivars.primary_finger.set(None);
|
||||||
|
}
|
||||||
|
primary
|
||||||
|
};
|
||||||
|
|
||||||
|
if let UITouchPhase::Ended = phase {
|
||||||
|
touch_events.push(EventWrapper::Window {
|
||||||
|
window_id,
|
||||||
|
event: WindowEvent::PointerButton {
|
||||||
|
device_id: None,
|
||||||
|
primary,
|
||||||
|
state: ElementState::Released,
|
||||||
|
position,
|
||||||
|
button: if let UITouchType::Pencil = touch_type {
|
||||||
|
ButtonSource::Unknown(0)
|
||||||
|
} else {
|
||||||
|
ButtonSource::Touch { finger_id, force }
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
touch_events.push(EventWrapper::Window {
|
||||||
|
window_id,
|
||||||
|
event: WindowEvent::PointerLeft {
|
||||||
|
device_id: None,
|
||||||
|
primary,
|
||||||
|
position: Some(position),
|
||||||
|
kind: if let UITouchType::Pencil = touch_type {
|
||||||
|
PointerKind::Unknown
|
||||||
|
} else {
|
||||||
|
PointerKind::Touch(finger_id)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
_ => panic!("unexpected touch phase: {phase:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
app_state::handle_nonuser_events(mtm, touch_events);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_insert_text(&self, text: &NSString) {
|
||||||
|
let window = self.window().unwrap();
|
||||||
|
let window_id = window.id();
|
||||||
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
// send individual events for each character
|
||||||
|
app_state::handle_nonuser_events(
|
||||||
|
mtm,
|
||||||
|
text.to_string().chars().flat_map(|c| {
|
||||||
|
let text = smol_str::SmolStr::from_iter([c]);
|
||||||
|
// Emit both press and release events
|
||||||
|
[ElementState::Pressed, ElementState::Released].map(|state| EventWrapper::Window {
|
||||||
|
window_id,
|
||||||
|
event: WindowEvent::KeyboardInput {
|
||||||
|
device_id: None,
|
||||||
|
event: KeyEvent {
|
||||||
|
text: if state == ElementState::Pressed {
|
||||||
|
Some(text.clone())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
},
|
||||||
|
state,
|
||||||
|
location: KeyLocation::Standard,
|
||||||
|
repeat: false,
|
||||||
|
logical_key: Key::Character(text.clone()),
|
||||||
|
physical_key: PhysicalKey::Unidentified(NativeKeyCode::Unidentified),
|
||||||
|
platform_specific: KeyEventExtra {},
|
||||||
|
},
|
||||||
|
is_synthetic: false,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_delete_backward(&self) {
|
||||||
|
let window = self.window().unwrap();
|
||||||
|
let window_id = window.id();
|
||||||
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
app_state::handle_nonuser_events(
|
||||||
|
mtm,
|
||||||
|
[ElementState::Pressed, ElementState::Released].map(|state| EventWrapper::Window {
|
||||||
|
window_id,
|
||||||
|
event: WindowEvent::KeyboardInput {
|
||||||
|
device_id: None,
|
||||||
|
event: KeyEvent {
|
||||||
|
state,
|
||||||
|
logical_key: Key::Named(NamedKey::Backspace),
|
||||||
|
physical_key: PhysicalKey::Code(KeyCode::Backspace),
|
||||||
|
platform_specific: KeyEventExtra {},
|
||||||
|
repeat: false,
|
||||||
|
location: KeyLocation::Standard,
|
||||||
|
text: None,
|
||||||
|
},
|
||||||
|
is_synthetic: false,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user