Compare commits
427 Commits
v0.28.4
...
android-no
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1850131b97 | ||
|
|
2bc1943188 | ||
|
|
385c4b3c88 | ||
|
|
ea70f773d3 | ||
|
|
83012f4c1c | ||
|
|
6825fed073 | ||
|
|
273984a385 | ||
|
|
dbe0f852da | ||
|
|
d1902aa15a | ||
|
|
4112fccc12 | ||
|
|
bd6ce32860 | ||
|
|
8936fe1acd | ||
|
|
fedb86ea5a | ||
|
|
20687fef1c | ||
|
|
56035e1f13 | ||
|
|
08fc4099e8 | ||
|
|
4d4d6e5052 | ||
|
|
cf5f4de19e | ||
|
|
21df84b7f4 | ||
|
|
dd13ccda4c | ||
|
|
df8805c0d2 | ||
|
|
db1ca45a17 | ||
|
|
ff731197dc | ||
|
|
f526a47152 | ||
|
|
f204467838 | ||
|
|
6641dfa412 | ||
|
|
c1168b4f58 | ||
|
|
f8b7c4b78f | ||
|
|
3830b492c4 | ||
|
|
8862ce0163 | ||
|
|
569c44a632 | ||
|
|
ef2ec904ce | ||
|
|
98d3391f2d | ||
|
|
d0a1917603 | ||
|
|
b36d8d1e52 | ||
|
|
a5b08fc48c | ||
|
|
0482d9cfce | ||
|
|
10a785019c | ||
|
|
0cc19716f3 | ||
|
|
572d7ee77c | ||
|
|
b0c59c8416 | ||
|
|
d7c7ba1d6c | ||
|
|
aec608f93c | ||
|
|
d1717b6a01 | ||
|
|
6b29253797 | ||
|
|
30775f4982 | ||
|
|
41070d7c67 | ||
|
|
6df972d108 | ||
|
|
73910d20cc | ||
|
|
16d860736b | ||
|
|
2ee44246ae | ||
|
|
14b418a3a7 | ||
|
|
c86b0daf7f | ||
|
|
40b61d2d92 | ||
|
|
22311802b5 | ||
|
|
169cd39f93 | ||
|
|
bdeb2574dc | ||
|
|
4fe38d8067 | ||
|
|
816798bfd1 | ||
|
|
f99c810bec | ||
|
|
d39528aa69 | ||
|
|
787b2d7362 | ||
|
|
37b6243289 | ||
|
|
8ea1da7879 | ||
|
|
b1209bc253 | ||
|
|
021fd23c34 | ||
|
|
dd127463c5 | ||
|
|
ac247cd081 | ||
|
|
ea1bfd254d | ||
|
|
178f5fda05 | ||
|
|
42dbc4748e | ||
|
|
8b3de7cedf | ||
|
|
8b0ffb7e7d | ||
|
|
c55a2c779b | ||
|
|
c5a422eed6 | ||
|
|
1893b0ec42 | ||
|
|
5e106b4dbb | ||
|
|
5a1d3e4656 | ||
|
|
8f6de4ef4b | ||
|
|
ad1843aea6 | ||
|
|
ca1674519a | ||
|
|
f78edc7ef1 | ||
|
|
4f295e0c94 | ||
|
|
658f49b014 | ||
|
|
34e42ff94d | ||
|
|
ba654bb61e | ||
|
|
f5c691467b | ||
|
|
a87cfb62c3 | ||
|
|
25d6a1d46d | ||
|
|
e0fea25b06 | ||
|
|
843d7904d6 | ||
|
|
28a811bbba | ||
|
|
61a873d79a | ||
|
|
be4a660011 | ||
|
|
34dd2cdba9 | ||
|
|
775c8ece70 | ||
|
|
c12c7b82e8 | ||
|
|
8cc5cb9d9b | ||
|
|
9a28bb4b49 | ||
|
|
4f6fd44c6c | ||
|
|
5a43ea8cd6 | ||
|
|
e9a25a4c91 | ||
|
|
674657efb6 | ||
|
|
7d5bee767c | ||
|
|
745cfaab2c | ||
|
|
a8f49dc8ef | ||
|
|
e5310ade08 | ||
|
|
37946e0a3a | ||
|
|
86b737f5e7 | ||
|
|
e37585e5bc | ||
|
|
4aeeb24745 | ||
|
|
8cd3aaa8a2 | ||
|
|
2c15de7cf9 | ||
|
|
0a7ea61834 | ||
|
|
4ee11018c2 | ||
|
|
4f669ebbd2 | ||
|
|
7761b2b16c | ||
|
|
ae41e3265f | ||
|
|
8702a09333 | ||
|
|
8b5c84f404 | ||
|
|
a676d0018b | ||
|
|
04ca85a909 | ||
|
|
cc33212479 | ||
|
|
f2c5127f27 | ||
|
|
af93167237 | ||
|
|
7f6b16a6af | ||
|
|
bf5806a9b2 | ||
|
|
2a9c593e01 | ||
|
|
becdd0dbd2 | ||
|
|
3eea505440 | ||
|
|
b863283c38 | ||
|
|
73718c9f2f | ||
|
|
f735f028a1 | ||
|
|
da947992ac | ||
|
|
e9784127df | ||
|
|
0be2bb0a8c | ||
|
|
075996b1fa | ||
|
|
a7241b3db3 | ||
|
|
17296e9878 | ||
|
|
b3c87caa7c | ||
|
|
81a1d9c396 | ||
|
|
5612626944 | ||
|
|
d3ca685b77 | ||
|
|
7bed5eecfd | ||
|
|
14140607d1 | ||
|
|
eab982c402 | ||
|
|
21701a33de | ||
|
|
c89e6df758 | ||
|
|
e9210555c1 | ||
|
|
0994b5ceb8 | ||
|
|
bcce5134e1 | ||
|
|
d333dd8664 | ||
|
|
52af1b4a77 | ||
|
|
3c9f9da19e | ||
|
|
075dfcea19 | ||
|
|
92b7dcccc1 | ||
|
|
5a3be586f4 | ||
|
|
12dbbf8012 | ||
|
|
53ca5af48f | ||
|
|
c235bd154a | ||
|
|
f4e71a1d9c | ||
|
|
62ed51a138 | ||
|
|
b2a2ec91ae | ||
|
|
d37d1a03b2 | ||
|
|
772b21ce09 | ||
|
|
2edcd09704 | ||
|
|
d35c3bea42 | ||
|
|
89a184ed84 | ||
|
|
36d4907da8 | ||
|
|
98b3508aca | ||
|
|
c0db53a516 | ||
|
|
52b7205b75 | ||
|
|
41dbbc27a0 | ||
|
|
c346fb7e61 | ||
|
|
6a041f84ba | ||
|
|
acfeff5327 | ||
|
|
b9e1e96eaa | ||
|
|
880238a24f | ||
|
|
f5b4d6938f | ||
|
|
c65e2247a1 | ||
|
|
801fddbfcf | ||
|
|
3ad64fb811 | ||
|
|
9bf4493a21 | ||
|
|
48f6582eb4 | ||
|
|
ef34692148 | ||
|
|
c48116a8fd | ||
|
|
b938fe9df5 | ||
|
|
b7e3649e8b | ||
|
|
844269d017 | ||
|
|
e41fac825c | ||
|
|
bbeacc46d5 | ||
|
|
61581ebb4f | ||
|
|
93f1000a05 | ||
|
|
1ea41a2ee2 | ||
|
|
42c9b7e40e | ||
|
|
0960635895 | ||
|
|
789a497980 | ||
|
|
fac6110cb6 | ||
|
|
0363be4776 | ||
|
|
f5dd1c008c | ||
|
|
48a1e84906 | ||
|
|
ee0db52ac4 | ||
|
|
c7cf0cfd83 | ||
|
|
8393d98940 | ||
|
|
af247eac0f | ||
|
|
b2b4564a5f | ||
|
|
cb58c49a90 | ||
|
|
ffb46dd61f | ||
|
|
8c8fb39fcd | ||
|
|
2422ea39d0 | ||
|
|
878d832d24 | ||
|
|
e2e01e1fc6 | ||
|
|
c8b685ddbc | ||
|
|
f10ae52385 | ||
|
|
e731041c15 | ||
|
|
9df7fc47a1 | ||
|
|
992aeb0ca0 | ||
|
|
0caba93b51 | ||
|
|
c00c1e9eb7 | ||
|
|
83950acd5a | ||
|
|
b99403b1b9 | ||
|
|
4f0ce7201d | ||
|
|
e648169861 | ||
|
|
8fdd81ecef | ||
|
|
7a2a2341c2 | ||
|
|
d68d9eab38 | ||
|
|
a06ea45c0f | ||
|
|
67b041e231 | ||
|
|
6dfc78fb50 | ||
|
|
477619c0a7 | ||
|
|
5f1a4b65ad | ||
|
|
bb9b629bc3 | ||
|
|
0c8cf94a70 | ||
|
|
1dfca5a395 | ||
|
|
7541220a41 | ||
|
|
7e11912d22 | ||
|
|
86baa1c99a | ||
|
|
d9f04780cc | ||
|
|
67d3fd28f7 | ||
|
|
a3cba838ea | ||
|
|
48abf52aac | ||
|
|
68ef9f707e | ||
|
|
9979441c82 | ||
|
|
309e6aa85a | ||
|
|
8b8556798e | ||
|
|
2d96480a89 | ||
|
|
6caff77abb | ||
|
|
af6c343d0e | ||
|
|
119462795a | ||
|
|
f801c4a00b | ||
|
|
f9758528f6 | ||
|
|
778d70c001 | ||
|
|
dc973883c9 | ||
|
|
2233edb9a0 | ||
|
|
bd2f1e8312 | ||
|
|
e9ebf1e5f4 | ||
|
|
5f7955cb2b | ||
|
|
793c535b01 | ||
|
|
ed26dd58fd | ||
|
|
584aab4cd0 | ||
|
|
8100a6a584 | ||
|
|
cad3277550 | ||
|
|
3c3a863cc9 | ||
|
|
8a7e18aaf0 | ||
|
|
57fad2ce15 | ||
|
|
7a58fe58ce | ||
|
|
38f28d5836 | ||
|
|
189a0080a6 | ||
|
|
b5aa96bea4 | ||
|
|
19e3906369 | ||
|
|
9ac3259a79 | ||
|
|
2b2dd6b65d | ||
|
|
75173118b0 | ||
|
|
e33d2bee6c | ||
|
|
ae7497e18f | ||
|
|
935146d299 | ||
|
|
755c533b08 | ||
|
|
ae9b02e097 | ||
|
|
e6c7cc297d | ||
|
|
b74cee8df1 | ||
|
|
e5eb253698 | ||
|
|
ec11b4877f | ||
|
|
9e46dffcc5 | ||
|
|
7501039d57 | ||
|
|
289ce32d77 | ||
|
|
0d366ffbda | ||
|
|
a6f414d732 | ||
|
|
c47d0846fa | ||
|
|
461efaf99f | ||
|
|
420840278b | ||
|
|
f5e73b0af4 | ||
|
|
f40b5f0dad | ||
|
|
c91402efb9 | ||
|
|
43acf7f42f | ||
|
|
c62e64060b | ||
|
|
f7a84a5b50 | ||
|
|
89aa7cc06e | ||
|
|
b166e1ff13 | ||
|
|
97434d8d80 | ||
|
|
06fb089633 | ||
|
|
4d6dbea74c | ||
|
|
c5941d105f | ||
|
|
b63164645b | ||
|
|
5b5ebc25d8 | ||
|
|
d7ec899d69 | ||
|
|
5379d60e4d | ||
|
|
44e2f95331 | ||
|
|
3b2d1a7643 | ||
|
|
50b17a3907 | ||
|
|
af26f01b95 | ||
|
|
c4d70d75c1 | ||
|
|
db8de03142 | ||
|
|
ff0ce9d065 | ||
|
|
42e492cde8 | ||
|
|
5e0e1e96bc | ||
|
|
bd890e69aa | ||
|
|
bca57ed0b4 | ||
|
|
4652d48105 | ||
|
|
96c0b267e2 | ||
|
|
81fd39485f | ||
|
|
6178acede8 | ||
|
|
a320702a71 | ||
|
|
b0106898f7 | ||
|
|
924f3323b5 | ||
|
|
b97df599c5 | ||
|
|
0defd747c8 | ||
|
|
e23186db8e | ||
|
|
059abb06fc | ||
|
|
bc216b8f67 | ||
|
|
864a1d5924 | ||
|
|
05444628e6 | ||
|
|
66ff52b012 | ||
|
|
7929999c1c | ||
|
|
7094a223af | ||
|
|
b2a46d0439 | ||
|
|
4748890935 | ||
|
|
6300cf915e | ||
|
|
9a9c9b15ba | ||
|
|
7ce86c3d2a | ||
|
|
a444637b18 | ||
|
|
f0d88c52a3 | ||
|
|
e17977d7c7 | ||
|
|
a7a8ff0bbb | ||
|
|
fc046add78 | ||
|
|
ab4a4a89e6 | ||
|
|
f7a400ddf6 | ||
|
|
07d39abddd | ||
|
|
0c8bf25ae4 | ||
|
|
b5785ba785 | ||
|
|
9797ed86f0 | ||
|
|
e220a75556 | ||
|
|
29d3729ac8 | ||
|
|
4a36741f9c | ||
|
|
ab46aa5b79 | ||
|
|
12fb37d827 | ||
|
|
c88a4ab221 | ||
|
|
8f7f3efc0d | ||
|
|
eb2d3894ef | ||
|
|
3f4f580181 | ||
|
|
d3aeff8838 | ||
|
|
0786d534f4 | ||
|
|
b4b2389d0a | ||
|
|
964e342f69 | ||
|
|
a134a59917 | ||
|
|
fbba203c4a | ||
|
|
61bd8b8254 | ||
|
|
587fa67571 | ||
|
|
7500a88230 | ||
|
|
82d0380ea6 | ||
|
|
642ce2bfa7 | ||
|
|
5bbe87960e | ||
|
|
cf77f82ae3 | ||
|
|
72cf4e577f | ||
|
|
4f3eacf01e | ||
|
|
31ebc5caf4 | ||
|
|
d273518ce9 | ||
|
|
2ade772ab0 | ||
|
|
4ac2006cbc | ||
|
|
ba5ad3be13 | ||
|
|
8092fa2440 | ||
|
|
8bb004a1d9 | ||
|
|
de5327477a | ||
|
|
8f959714cc | ||
|
|
035eebb19a | ||
|
|
b5af6bb266 | ||
|
|
1805124c54 | ||
|
|
0f64589dba | ||
|
|
5438a2a524 | ||
|
|
918430979f | ||
|
|
f3f46cb3f6 | ||
|
|
3c3be71a77 | ||
|
|
a7986b077f | ||
|
|
8a0edde5c8 | ||
|
|
a9e168e10d | ||
|
|
bd9cc2a9da | ||
|
|
596c0edf0f | ||
|
|
92592ec605 | ||
|
|
25c4e2e451 | ||
|
|
ad52c72e41 | ||
|
|
d15feb5cfa | ||
|
|
9938327066 | ||
|
|
f980ed7b83 | ||
|
|
2496098890 | ||
|
|
60e91b187a | ||
|
|
2486f0f1a1 | ||
|
|
fbea75d31f | ||
|
|
d4c9535af9 | ||
|
|
f0fcb346b0 | ||
|
|
77f8e511e9 | ||
|
|
3217eaa416 | ||
|
|
b18295a1ce | ||
|
|
fb9695d56d | ||
|
|
08bdca19b1 | ||
|
|
79ac236721 | ||
|
|
b870a11a99 | ||
|
|
2af1550bbb | ||
|
|
ed796dcd15 | ||
|
|
a006cd7dc8 | ||
|
|
a31f71ee07 | ||
|
|
0f89aac9f6 | ||
|
|
82df9531f4 | ||
|
|
265152355e | ||
|
|
37c0f615cf | ||
|
|
5ba6bdef49 | ||
|
|
69d6076310 | ||
|
|
7029ce6ecd | ||
|
|
1eb1a13a77 |
20
.github/CODEOWNERS
vendored
@@ -1,12 +1,6 @@
|
|||||||
# Core maintainers:
|
|
||||||
# - @msiglreith
|
|
||||||
# - @kchibisov
|
|
||||||
# - @madsmtm
|
|
||||||
# - @maroider
|
|
||||||
|
|
||||||
# Android
|
# Android
|
||||||
/src/platform/android.rs @msiglreith
|
/src/platform/android.rs @msiglreith @MarijnS95
|
||||||
/src/platform_impl/android @msiglreith
|
/src/platform_impl/android @msiglreith @MarijnS95
|
||||||
|
|
||||||
# iOS
|
# iOS
|
||||||
/src/platform/ios.rs @madsmtm
|
/src/platform/ios.rs @madsmtm
|
||||||
@@ -20,16 +14,16 @@
|
|||||||
/src/platform_impl/linux/wayland @kchibisov
|
/src/platform_impl/linux/wayland @kchibisov
|
||||||
|
|
||||||
# X11
|
# X11
|
||||||
/src/platform/x11.rs @kchibisov
|
/src/platform/x11.rs @kchibisov @notgull
|
||||||
/src/platform_impl/linux/x11 @kchibisov
|
/src/platform_impl/linux/x11 @kchibisov @notgull
|
||||||
|
|
||||||
# macOS
|
# macOS
|
||||||
/src/platform/macos.rs @madsmtm
|
/src/platform/macos.rs @madsmtm
|
||||||
/src/platform_impl/macos @madsmtm
|
/src/platform_impl/macos @madsmtm
|
||||||
|
|
||||||
# Web (no maintainer)
|
# Web
|
||||||
/src/platform/web.rs
|
/src/platform/web.rs @daxpedda
|
||||||
/src/platform_impl/web
|
/src/platform_impl/web @daxpedda
|
||||||
|
|
||||||
# Windows
|
# Windows
|
||||||
/src/platform/windows.rs @msiglreith
|
/src/platform/windows.rs @msiglreith
|
||||||
|
|||||||
204
.github/workflows/ci.yml
vendored
@@ -6,116 +6,198 @@ on:
|
|||||||
branches: [master]
|
branches: [master]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
Check_Formatting:
|
fmt:
|
||||||
|
name: Check formatting
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v3
|
||||||
- uses: hecrj/setup-rust-action@v1
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
with:
|
with:
|
||||||
rust-version: stable
|
|
||||||
components: rustfmt
|
components: rustfmt
|
||||||
- name: Check Formatting
|
- name: Check Formatting
|
||||||
run: cargo +stable fmt --all -- --check
|
run: cargo fmt -- --check
|
||||||
|
|
||||||
tests:
|
tests:
|
||||||
name: Tests
|
name: Test ${{ matrix.toolchain }} ${{ matrix.platform.name }}
|
||||||
|
runs-on: ${{ matrix.platform.os }}
|
||||||
|
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
rust_version: ['1.60.0', stable, nightly]
|
toolchain: [stable, nightly, '1.70.0']
|
||||||
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!
|
||||||
- { target: x86_64-pc-windows-msvc, os: windows-latest, }
|
- { name: 'Windows 64bit MSVC', target: x86_64-pc-windows-msvc, os: windows-latest, }
|
||||||
- { target: i686-pc-windows-msvc, os: windows-latest, }
|
- { name: 'Windows 32bit MSVC', target: i686-pc-windows-msvc, os: windows-latest, }
|
||||||
- { target: x86_64-pc-windows-gnu, os: windows-latest, host: -x86_64-pc-windows-gnu }
|
- { name: 'Windows 64bit GNU', target: x86_64-pc-windows-gnu, os: windows-latest, host: -x86_64-pc-windows-gnu }
|
||||||
- { target: i686-pc-windows-gnu, os: windows-latest, host: -i686-pc-windows-gnu }
|
- { name: 'Windows 32bit GNU', target: i686-pc-windows-gnu, os: windows-latest, host: -i686-pc-windows-gnu }
|
||||||
- { target: i686-unknown-linux-gnu, os: ubuntu-latest, }
|
- { name: 'Linux 32bit', target: i686-unknown-linux-gnu, os: ubuntu-latest, }
|
||||||
- { target: x86_64-unknown-linux-gnu, os: ubuntu-latest, }
|
- { name: 'Linux 64bit', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, }
|
||||||
- { target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: --no-default-features, features: x11 }
|
- { name: 'X11', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: '--no-default-features --features=x11' }
|
||||||
- { 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' }
|
||||||
- { target: aarch64-linux-android, os: ubuntu-latest, options: -p winit, cmd: 'apk --', features: "android-native-activity" }
|
- { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
||||||
- { target: x86_64-unknown-redox, os: ubuntu-latest, }
|
- { name: 'Redox OS', target: x86_64-unknown-redox, os: ubuntu-latest, }
|
||||||
- { target: x86_64-apple-darwin, os: macos-latest, }
|
- { name: 'macOS', target: x86_64-apple-darwin, os: macos-latest, }
|
||||||
- { target: x86_64-apple-ios, os: macos-latest, }
|
- { name: 'iOS x86_64', target: x86_64-apple-ios, os: macos-latest, }
|
||||||
- { target: aarch64-apple-ios, os: macos-latest, }
|
- { name: 'iOS Aarch64', target: aarch64-apple-ios, os: macos-latest, }
|
||||||
# We're using Windows rather than Ubuntu to run the wasm tests because caching cargo-web
|
- { name: 'web', target: wasm32-unknown-unknown, os: ubuntu-latest, }
|
||||||
# doesn't currently work on Linux.
|
exclude:
|
||||||
- { target: wasm32-unknown-unknown, os: windows-latest, }
|
# Android is tested on stable-3
|
||||||
|
- toolchain: '1.70.0'
|
||||||
|
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
||||||
|
include:
|
||||||
|
- toolchain: '1.70.0'
|
||||||
|
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
||||||
|
- toolchain: 'nightly'
|
||||||
|
platform: {
|
||||||
|
name: 'web Atomic',
|
||||||
|
target: wasm32-unknown-unknown,
|
||||||
|
os: ubuntu-latest,
|
||||||
|
options: '-Zbuild-std=panic_abort,std',
|
||||||
|
rustflags: '-Ctarget-feature=+atomics,+bulk-memory',
|
||||||
|
components: rust-src,
|
||||||
|
}
|
||||||
|
|
||||||
env:
|
env:
|
||||||
|
# Set more verbose terminal output
|
||||||
|
CARGO_TERM_VERBOSE: true
|
||||||
RUST_BACKTRACE: 1
|
RUST_BACKTRACE: 1
|
||||||
CARGO_INCREMENTAL: 0
|
|
||||||
RUSTFLAGS: "-C debuginfo=0 --deny warnings"
|
# Faster compilation and error on warnings
|
||||||
OPTIONS: ${{ matrix.platform.options }}
|
RUSTFLAGS: '--codegen=debuginfo=0 --deny=warnings ${{ matrix.platform.rustflags }}'
|
||||||
FEATURES: ${{ format(',{0}', matrix.platform.features ) }}
|
|
||||||
|
OPTIONS: --target=${{ matrix.platform.target }} ${{ matrix.platform.options }}
|
||||||
CMD: ${{ matrix.platform.cmd }}
|
CMD: ${{ matrix.platform.cmd }}
|
||||||
RUSTDOCFLAGS: -Dwarnings
|
|
||||||
|
|
||||||
runs-on: ${{ matrix.platform.os }}
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v3
|
||||||
# Used to cache cargo-web
|
|
||||||
- name: Cache cargo folder
|
|
||||||
uses: actions/cache@v1
|
|
||||||
with:
|
|
||||||
path: ~/.cargo
|
|
||||||
key: ${{ matrix.platform.target }}-cargo-${{ matrix.rust_version }}
|
|
||||||
|
|
||||||
- uses: hecrj/setup-rust-action@v1
|
- name: Restore cache of cargo folder
|
||||||
|
# We use `restore` and later `save`, so that we can create the key after
|
||||||
|
# the cache has been downloaded.
|
||||||
|
#
|
||||||
|
# This could be avoided if we added Cargo.lock to the repository.
|
||||||
|
uses: actions/cache/restore@v3
|
||||||
with:
|
with:
|
||||||
rust-version: ${{ matrix.rust_version }}${{ matrix.platform.host }}
|
# https://doc.rust-lang.org/cargo/guide/cargo-home.html#caching-the-cargo-home-in-ci
|
||||||
targets: ${{ matrix.platform.target }}
|
path: |
|
||||||
components: clippy
|
~/.cargo/registry/index/
|
||||||
|
~/.cargo/registry/cache/
|
||||||
|
~/.cargo/git/db/
|
||||||
|
key: cargo-${{ matrix.toolchain }}-${{ matrix.platform.name }}-never-intended-to-be-found
|
||||||
|
restore-keys: cargo-${{ matrix.toolchain }}-${{ matrix.platform.name }}
|
||||||
|
|
||||||
|
- name: Generate lockfile
|
||||||
|
# Also updates the crates.io index
|
||||||
|
run: cargo generate-lockfile && cargo update -p ahash --precise 0.8.7
|
||||||
|
|
||||||
- name: Install GCC Multilib
|
- name: Install GCC Multilib
|
||||||
if: (matrix.platform.os == 'ubuntu-latest') && contains(matrix.platform.target, 'i686')
|
if: (matrix.platform.os == 'ubuntu-latest') && contains(matrix.platform.target, 'i686')
|
||||||
run: sudo apt-get update && sudo apt-get install gcc-multilib
|
run: sudo apt-get update && sudo apt-get install gcc-multilib
|
||||||
- name: Install cargo-apk
|
|
||||||
|
- name: Cache cargo-apk
|
||||||
if: contains(matrix.platform.target, 'android')
|
if: contains(matrix.platform.target, 'android')
|
||||||
run: cargo install cargo-apk
|
id: cargo-apk-cache
|
||||||
|
uses: actions/cache@v3
|
||||||
|
with:
|
||||||
|
path: ~/.cargo/bin/cargo-apk
|
||||||
|
# Change this key if we update the required cargo-apk version
|
||||||
|
key: cargo-apk-v0-9-7
|
||||||
|
|
||||||
|
- uses: dtolnay/rust-toolchain@master
|
||||||
|
if: contains(matrix.platform.target, 'android') && (steps.cargo-apk-cache.outputs.cache-hit != 'true')
|
||||||
|
with:
|
||||||
|
toolchain: stable
|
||||||
|
|
||||||
|
- name: Install cargo-apk
|
||||||
|
if: contains(matrix.platform.target, 'android') && (steps.cargo-apk-cache.outputs.cache-hit != 'true')
|
||||||
|
run: cargo install cargo-apk --version=^0.9.7 --locked
|
||||||
|
|
||||||
|
- uses: dtolnay/rust-toolchain@master
|
||||||
|
with:
|
||||||
|
toolchain: ${{ matrix.toolchain }}${{ matrix.platform.host }}
|
||||||
|
targets: ${{ matrix.platform.target }}
|
||||||
|
components: clippy, ${{ matrix.platform.components }}
|
||||||
|
|
||||||
- name: Check documentation
|
- name: Check documentation
|
||||||
shell: bash
|
run: cargo doc --no-deps $OPTIONS --document-private-items
|
||||||
run: cargo doc --no-deps --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES --document-private-items
|
env:
|
||||||
|
RUSTDOCFLAGS: '--deny=warnings ${{ matrix.platform.rustflags }}'
|
||||||
|
|
||||||
- name: Build crate
|
- name: Build crate
|
||||||
shell: bash
|
run: cargo $CMD build $OPTIONS
|
||||||
run: cargo $CMD build --verbose --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES
|
|
||||||
|
|
||||||
- name: Build tests
|
- name: Build tests
|
||||||
shell: bash
|
|
||||||
if: >
|
if: >
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.rust_version != '1.60.0'
|
matrix.toolchain != '1.70.0'
|
||||||
run: cargo $CMD test --no-run --verbose --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES
|
run: cargo $CMD test --no-run $OPTIONS
|
||||||
|
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
shell: bash
|
|
||||||
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') &&
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.rust_version != '1.60.0'
|
matrix.toolchain != '1.70.0'
|
||||||
run: cargo $CMD test --verbose --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES
|
run: cargo $CMD test $OPTIONS
|
||||||
|
|
||||||
- name: Lint with clippy
|
- name: Lint with clippy
|
||||||
shell: bash
|
if: (matrix.toolchain == 'stable') && !contains(matrix.platform.options, '--no-default-features')
|
||||||
if: (matrix.rust_version == 'stable') && !contains(matrix.platform.options, '--no-default-features')
|
run: cargo clippy --all-targets $OPTIONS -- -Dwarnings
|
||||||
run: cargo clippy --all-targets --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES -- -Dwarnings
|
|
||||||
|
|
||||||
- name: Build tests with serde enabled
|
- name: Build tests with serde enabled
|
||||||
shell: bash
|
|
||||||
if: >
|
if: >
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.rust_version != '1.60.0'
|
matrix.toolchain != '1.70.0'
|
||||||
run: cargo $CMD test --no-run --verbose --target ${{ matrix.platform.target }} $OPTIONS --features serde,$FEATURES
|
run: cargo $CMD test --no-run $OPTIONS --features serde
|
||||||
|
|
||||||
- name: Run tests with serde enabled
|
- name: Run tests with serde enabled
|
||||||
shell: bash
|
|
||||||
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') &&
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.rust_version != '1.60.0'
|
matrix.toolchain != '1.70.0'
|
||||||
run: cargo $CMD test --verbose --target ${{ matrix.platform.target }} $OPTIONS --features serde,$FEATURES
|
run: cargo $CMD test $OPTIONS --features serde
|
||||||
|
|
||||||
|
- name: Check docs.rs documentation
|
||||||
|
if: matrix.toolchain == 'nightly'
|
||||||
|
run: cargo doc --no-deps $OPTIONS --features=rwh_04,rwh_05,rwh_06,serde,mint,android-native-activity
|
||||||
|
env:
|
||||||
|
RUSTDOCFLAGS: '--deny=warnings ${{ matrix.platform.rustflags }} --cfg=docsrs'
|
||||||
|
|
||||||
|
# See restore step above
|
||||||
|
- name: Save cache of cargo folder
|
||||||
|
uses: actions/cache/save@v3
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cargo/registry/index/
|
||||||
|
~/.cargo/registry/cache/
|
||||||
|
~/.cargo/git/db/
|
||||||
|
key: cargo-${{ matrix.toolchain }}-${{ matrix.platform.name }}-${{ hashFiles('Cargo.lock') }}
|
||||||
|
|
||||||
|
cargo-deny:
|
||||||
|
name: Run cargo-deny on ${{ matrix.platform.name }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
# TODO: remove this matrix when https://github.com/EmbarkStudios/cargo-deny/issues/324 is resolved
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
platform:
|
||||||
|
- { name: 'Android', target: aarch64-linux-android }
|
||||||
|
- { name: 'iOS', target: aarch64-apple-ios }
|
||||||
|
- { name: 'Linux', target: x86_64-unknown-linux-gnu }
|
||||||
|
- { name: 'macOS', target: x86_64-apple-darwin }
|
||||||
|
- { name: 'Redox OS', target: x86_64-unknown-redox }
|
||||||
|
- { name: 'web', target: wasm32-unknown-unknown }
|
||||||
|
- { name: 'Windows', target: x86_64-pc-windows-gnu }
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- uses: EmbarkStudios/cargo-deny-action@v1
|
||||||
|
with:
|
||||||
|
command: check
|
||||||
|
log-level: error
|
||||||
|
arguments: --all-features --target ${{ matrix.platform.target }}
|
||||||
|
|||||||
50
.github/workflows/docs.yml
vendored
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
name: Docs
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [master]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
docs:
|
||||||
|
name: Documentation
|
||||||
|
environment:
|
||||||
|
name: github-pages
|
||||||
|
url: ${{ steps.deployment.outputs.page_url }}winit
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
pages: write
|
||||||
|
id-token: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- uses: dtolnay/rust-toolchain@master
|
||||||
|
with:
|
||||||
|
toolchain: nightly
|
||||||
|
|
||||||
|
- name: Run Rustdoc
|
||||||
|
env:
|
||||||
|
RUSTDOCFLAGS: --crate-version master --cfg=docsrs
|
||||||
|
run: |
|
||||||
|
cargo doc --no-deps -Z rustdoc-map -Z rustdoc-scrape-examples --features=rwh_04,rwh_05,rwh_06,serde,mint,android-native-activity
|
||||||
|
|
||||||
|
- name: Setup Pages
|
||||||
|
uses: actions/configure-pages@v4
|
||||||
|
|
||||||
|
- name: Fix permissions
|
||||||
|
run: |
|
||||||
|
chmod -c -R +rX "target/doc" | while read line; do
|
||||||
|
echo "::warning title=Invalid file permissions automatically fixed::$line"
|
||||||
|
done
|
||||||
|
|
||||||
|
- name: Upload artifact
|
||||||
|
uses: actions/upload-pages-artifact@v3
|
||||||
|
with:
|
||||||
|
path: target/doc
|
||||||
|
|
||||||
|
- name: Deploy to GitHub Pages
|
||||||
|
id: deployment
|
||||||
|
uses: actions/deploy-pages@v4
|
||||||
3
.gitmodules
vendored
@@ -1,3 +0,0 @@
|
|||||||
[submodule "deps/apk-builder"]
|
|
||||||
path = deps/apk-builder
|
|
||||||
url = https://github.com/rust-windowing/android-rs-glue
|
|
||||||
344
CHANGELOG.md
@@ -2,12 +2,350 @@
|
|||||||
|
|
||||||
All notable changes to this project will be documented in this file.
|
All notable changes to this project will be documented in this file.
|
||||||
|
|
||||||
Please keep one empty line before and after all headers. (This is required for `git` to produce a conflict when a release is made while a PR is open and the PR's changelog entry would go into the wrong section).
|
Please keep one empty line before and after all headers. (This is required for
|
||||||
|
`git` to produce a conflict when a release is made while a PR is open and the
|
||||||
|
PR's changelog entry would go into the wrong section).
|
||||||
|
|
||||||
And please only add new entries to the top of this list, right below the `# Unreleased` header.
|
And please only add new entries to the top of this list, right below the `#
|
||||||
|
Unreleased` header.
|
||||||
|
|
||||||
# Unreleased
|
# Unreleased
|
||||||
|
|
||||||
|
- On X11, don't require XIM to run.
|
||||||
|
- Fix compatibility with 32-bit platforms without 64-bit atomics.
|
||||||
|
- On X11, fix swapped instance and general class names.
|
||||||
|
- **Breaking:** Removed unnecessary generic parameter `T` from `EventLoopWindowTarget`.
|
||||||
|
- On Windows, macOS, X11, Wayland and Web, implement setting images as cursors. See the `custom_cursors.rs` example.
|
||||||
|
- **Breaking:** Remove `Window::set_cursor_icon`
|
||||||
|
- Add `WindowBuilder::with_cursor` and `Window::set_cursor` which takes a `CursorIcon` or `CustomCursor`
|
||||||
|
- Add `CustomCursor`
|
||||||
|
- 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.
|
||||||
|
- On macOS, add services menu.
|
||||||
|
- **Breaking:** On Web, remove queuing fullscreen request in absence of transient activation.
|
||||||
|
- On Web, fix setting cursor icon overriding cursor visibility.
|
||||||
|
- **Breaking:** On Web, return `RawWindowHandle::WebCanvas` instead of `RawWindowHandle::Web`.
|
||||||
|
- **Breaking:** On Web, macOS and iOS, return `HandleError::Unavailable` when a window handle is not available.
|
||||||
|
- **Breaking:** Bump MSRV from `1.65` to `1.70`.
|
||||||
|
- On Web, add the ability to toggle calling `Event.preventDefault()` on `Window`.
|
||||||
|
- **Breaking:** Remove `WindowAttributes::fullscreen()` and expose as field directly.
|
||||||
|
- **Breaking:** Rename `VideoMode` to `VideoModeHandle` to represent that it doesn't hold static data.
|
||||||
|
- **Breaking:** No longer export `platform::x11::XNotSupported`.
|
||||||
|
- **Breaking:** Renamed `platform::x11::XWindowType` to `platform::x11::WindowType`.
|
||||||
|
- Add the `OwnedDisplayHandle` type for allowing safe display handle usage outside of trivial cases.
|
||||||
|
- **Breaking:** Rename `TouchpadMagnify` to `PinchGesture`, `SmartMagnify` to `DoubleTapGesture` and `TouchpadRotate` to `RotationGesture` to represent the action rather than the intent.
|
||||||
|
- on iOS, add detection support for `PinchGesture`, `DoubleTapGesture` and `RotationGesture`.
|
||||||
|
- on Windows: add `with_system_backdrop`, `with_border_color`, `with_title_background_color`, `with_title_text_color` and `with_corner_preference`
|
||||||
|
- On Windows, Remove `WS_CAPTION`, `WS_BORDER` and `WS_EX_WINDOWEDGE` styles for child windows without decorations.
|
||||||
|
- On Windows, fixed a race condition when sending an event through the loop proxy.
|
||||||
|
- **Breaking:** Removed `EventLoopError::AlreadyRunning`, which can't happen as it is already prevented by the type system.
|
||||||
|
- On Wayland, disable `Occluded` event handling.
|
||||||
|
- Added `EventLoop::builder`, which is intended to replace the (now deprecated) `EventLoopBuilder::new`.
|
||||||
|
- **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`.
|
||||||
|
- Add `Window::builder`, which is intended to replace the (now deprecated) `WindowBuilder::new`.
|
||||||
|
- On X11, reload dpi on `_XSETTINGS_SETTINGS` update.
|
||||||
|
- On X11, fix deadlock when adjusting DPI and resizing at the same time.
|
||||||
|
- On Wayland, fix `Focused(false)` being send when other seats still have window focused.
|
||||||
|
- On Wayland, fix `Window::set_{min,max}_inner_size` not always applied.
|
||||||
|
- On Windows, fix inconsistent resizing behavior with multi-monitor setups when repositioning outside the event loop.
|
||||||
|
- On Wayland, fix `WAYLAND_SOCKET` not used when detecting platform.
|
||||||
|
- On Orbital, fix `logical_key` and `text` not reported in `KeyEvent`.
|
||||||
|
- On Orbital, implement `KeyEventExtModifierSupplement`.
|
||||||
|
- On Orbital, map keys to `NamedKey` when possible.
|
||||||
|
- On Orbital, implement `set_cursor_grab`.
|
||||||
|
- On Orbital, implement `set_cursor_visible`.
|
||||||
|
- On Orbital, implement `drag_window`.
|
||||||
|
- On Orbital, implement `drag_resize_window`.
|
||||||
|
- On Orbital, implement `set_transparent`.
|
||||||
|
- On Orbital, implement `set_visible`.
|
||||||
|
- On Orbital, implement `is_visible`.
|
||||||
|
- On Orbital, implement `set_resizable`.
|
||||||
|
- On Orbital, implement `is_resizable`.
|
||||||
|
- On Orbital, implement `set_maximized`.
|
||||||
|
- On Orbital, implement `is_maximized`.
|
||||||
|
- On Orbital, implement `set_decorations`.
|
||||||
|
- On Orbital, implement `is_decorated`.
|
||||||
|
- On Orbital, implement `set_window_level`.
|
||||||
|
- On Orbital, emit `DeviceEvent::MouseMotion`.
|
||||||
|
- On Wayland, fix title in CSD not updated from `AboutToWait`.
|
||||||
|
|
||||||
|
# 0.29.10
|
||||||
|
|
||||||
|
- On Web, account for canvas being focused already before event loop starts.
|
||||||
|
- On Web, increase cursor position accuracy.
|
||||||
|
|
||||||
|
# 0.29.9
|
||||||
|
|
||||||
|
- On X11, fix `NotSupported` error not propagated when creating event loop.
|
||||||
|
- On Wayland, fix resize not issued when scale changes
|
||||||
|
- On X11 and Wayland, fix arrow up on keypad reported as `ArrowLeft`.
|
||||||
|
- On macOS, report correct logical key when Ctrl or Cmd is pressed.
|
||||||
|
|
||||||
|
# 0.29.8
|
||||||
|
|
||||||
|
- On X11, fix IME input lagging behind.
|
||||||
|
- On X11, fix `ModifiersChanged` not sent from xdotool-like input
|
||||||
|
- On X11, fix keymap not updated from xmodmap.
|
||||||
|
- On X11, reduce the amount of time spent fetching screen resources.
|
||||||
|
- On Wayland, fix `Window::request_inner_size` being overwritten by resize.
|
||||||
|
- On Wayland, fix `Window::inner_size` not using the correct rounding.
|
||||||
|
|
||||||
|
# 0.29.7
|
||||||
|
|
||||||
|
- On X11, fix `Xft.dpi` reload during runtime.
|
||||||
|
- On X11, fix window minimize.
|
||||||
|
|
||||||
|
# 0.29.6
|
||||||
|
|
||||||
|
- On Web, fix context menu not being disabled by `with_prevent_default(true)`.
|
||||||
|
- On Wayland, fix `WindowEvent::Destroyed` not being delivered after destroying window.
|
||||||
|
- Fix `EventLoopExtRunOnDemand::run_on_demand` not working for consequent invocation
|
||||||
|
|
||||||
|
# 0.29.5
|
||||||
|
|
||||||
|
- On macOS, remove spurious error logging when handling `Fn`.
|
||||||
|
- On X11, fix an issue where floating point data from the server is
|
||||||
|
misinterpreted during a drag and drop operation.
|
||||||
|
- On X11, fix a bug where focusing the window would panic.
|
||||||
|
- On macOS, fix `refresh_rate_millihertz`.
|
||||||
|
- On Wayland, disable Client Side Decorations when `wl_subcompositor` is not supported.
|
||||||
|
- On X11, fix `Xft.dpi` detection from Xresources.
|
||||||
|
- On Windows, fix consecutive calls to `window.set_fullscreen(Some(Fullscreen::Borderless(None)))` resulting in losing previous window state when eventually exiting fullscreen using `window.set_fullscreen(None)`.
|
||||||
|
- On Wayland, fix resize being sent on focus change.
|
||||||
|
- On Windows, fix `set_ime_cursor_area`.
|
||||||
|
|
||||||
|
# 0.29.4
|
||||||
|
|
||||||
|
- Fix crash when running iOS app on macOS.
|
||||||
|
- On X11, check common alternative cursor names when loading cursor.
|
||||||
|
- On X11, reload the DPI after a property change event.
|
||||||
|
- On Windows, fix so `drag_window` and `drag_resize_window` can be called from another thread.
|
||||||
|
- On Windows, fix `set_control_flow` in `AboutToWait` not being taken in account.
|
||||||
|
- On macOS, send a `Resized` event after each `ScaleFactorChanged` event.
|
||||||
|
- On Wayland, fix `wl_surface` being destroyed before associated objects.
|
||||||
|
- On macOS, fix assertion when pressing `Fn` key.
|
||||||
|
- On Windows, add `WindowBuilderExtWindows::with_clip_children` to control `WS_CLIPCHILDREN` style.
|
||||||
|
|
||||||
|
# 0.29.3
|
||||||
|
|
||||||
|
- On Wayland, apply correct scale to `PhysicalSize` passed in `WindowBuilder::with_inner_size` when possible.
|
||||||
|
- On Wayland, fix `RedrawRequsted` being always sent without decorations and `sctk-adwaita` feature.
|
||||||
|
- On Wayland, ignore resize requests when the window is fully tiled.
|
||||||
|
- On Wayland, use `configure_bounds` to constrain `with_inner_size` when compositor wants users to pick size.
|
||||||
|
- On Windows, fix deadlock when accessing the state during `Cursor{Enter,Leave}`.
|
||||||
|
- On Windows, add support for `Window::set_transparent`.
|
||||||
|
- On macOS, fix deadlock when entering a nested event loop from an event handler.
|
||||||
|
- On macOS, add support for `Window::set_blur`.
|
||||||
|
|
||||||
|
# 0.29.2
|
||||||
|
|
||||||
|
- **Breaking:** Bump MSRV from `1.60` to `1.65`.
|
||||||
|
- **Breaking:** Add `Event::MemoryWarning`; implemented on iOS/Android.
|
||||||
|
- **Breaking:** Bump `ndk` version to `0.8.0`, ndk-sys to `0.5.0`, `android-activity` to `0.5.0`.
|
||||||
|
- **Breaking:** Change default `ControlFlow` from `Poll` to `Wait`.
|
||||||
|
- **Breaking:** Move `Event::RedrawRequested` to `WindowEvent::RedrawRequested`.
|
||||||
|
- **Breaking:** Moved `ControlFlow::Exit` to `EventLoopWindowTarget::exit()` and `EventLoopWindowTarget::exiting()` and removed `ControlFlow::ExitWithCode(_)` entirely.
|
||||||
|
- **Breaking:** Moved `ControlFlow` to `EventLoopWindowTarget::set_control_flow()` and `EventLoopWindowTarget::control_flow()`.
|
||||||
|
- **Breaking:** `EventLoop::new` and `EventLoopBuilder::build` now return `Result<Self, EventLoopError>`
|
||||||
|
- **Breaking:** `WINIT_UNIX_BACKEND` was removed in favor of standard `WAYLAND_DISPLAY` and `DISPLAY` variables.
|
||||||
|
- **Breaking:** on Wayland, dispatching user created Wayland queue won't wake up the loop unless winit has event to send back.
|
||||||
|
- **Breaking:** remove `DeviceEvent::Text`.
|
||||||
|
- **Breaking:** Remove lifetime parameter from `Event` and `WindowEvent`.
|
||||||
|
- **Breaking:** Rename `Window::set_inner_size` to `Window::request_inner_size` and indicate if the size was applied immediately.
|
||||||
|
- **Breaking:** `ActivationTokenDone` event which could be requested with the new `startup_notify` module, see its docs for more.
|
||||||
|
- **Breaking:** `ScaleFactorChanged` now contains a writer instead of a reference to update inner size.
|
||||||
|
- **Breaking** `run() -> !` has been replaced by `run() -> Result<(), EventLoopError>` for returning errors without calling `std::process::exit()` ([#2767](https://github.com/rust-windowing/winit/pull/2767))
|
||||||
|
- **Breaking** Removed `EventLoopExtRunReturn` / `run_return` in favor of `EventLoopExtPumpEvents` / `pump_events` and `EventLoopExtRunOnDemand` / `run_on_demand` ([#2767](https://github.com/rust-windowing/winit/pull/2767))
|
||||||
|
- `RedrawRequested` is no longer guaranteed to be emitted after `MainEventsCleared`, it is now platform-specific when the event is emitted after being requested via `redraw_request()`.
|
||||||
|
- On Windows, `RedrawRequested` is now driven by `WM_PAINT` messages which are requested via `redraw_request()`
|
||||||
|
- **Breaking** `LoopDestroyed` renamed to `LoopExiting` ([#2900](https://github.com/rust-windowing/winit/issues/2900))
|
||||||
|
- **Breaking** `RedrawEventsCleared` removed ([#2900](https://github.com/rust-windowing/winit/issues/2900))
|
||||||
|
- **Breaking** `MainEventsCleared` removed ([#2900](https://github.com/rust-windowing/winit/issues/2900))
|
||||||
|
- **Breaking:** Remove all deprecated `modifiers` fields.
|
||||||
|
- **Breaking:** Rename `DeviceEventFilter` to `DeviceEvents` reversing the behavior of variants.
|
||||||
|
- **Breaking** Add `AboutToWait` event which is emitted when the event loop is about to block and wait for new events ([#2900](https://github.com/rust-windowing/winit/issues/2900))
|
||||||
|
- **Breaking:** Rename `EventLoopWindowTarget::set_device_event_filter` to `listen_device_events`.
|
||||||
|
- **Breaking:** Rename `Window::set_ime_position` to `Window::set_ime_cursor_area` adding a way to set exclusive zone.
|
||||||
|
- **Breaking:** `with_x11_visual` now takes the visual ID instead of the bare pointer.
|
||||||
|
- **Breaking** `MouseButton` now supports `Back` and `Forward` variants, emitted from mouse events on Wayland, X11, Windows, macOS and Web.
|
||||||
|
- **Breaking:** On Web, `instant` is now replaced by `web_time`.
|
||||||
|
- **Breaking:** On Web, dropped support for Safari versions below 13.1.
|
||||||
|
- **Breaking:** On Web, the canvas output bitmap size is no longer adjusted.
|
||||||
|
- **Breaking:** On Web, the canvas size is not controlled by Winit anymore and external changes to the canvas size will be reported through `WindowEvent::Resized`.
|
||||||
|
- **Breaking:** Updated `bitflags` crate version to `2`, which changes the API on exposed types.
|
||||||
|
- **Breaking:** `CursorIcon::Arrow` was removed.
|
||||||
|
- **Breaking:** `CursorIcon::Hand` is now named `CursorIcon::Pointer`.
|
||||||
|
- **Breaking:** `CursorIcon` is now used from the `cursor-icon` crate.
|
||||||
|
- **Breaking:** `WindowExtWebSys::canvas()` now returns an `Option`.
|
||||||
|
- **Breaking:** Overhaul keyboard input handling.
|
||||||
|
- Replace `KeyboardInput` with `KeyEvent` and `RawKeyEvent`.
|
||||||
|
- Change `WindowEvent::KeyboardInput` to contain a `KeyEvent`.
|
||||||
|
- Change `Event::Key` to contain a `RawKeyEvent`.
|
||||||
|
- Remove `Event::ReceivedCharacter`. In its place, you should use
|
||||||
|
`KeyEvent.text` in combination with `WindowEvent::Ime`.
|
||||||
|
- Replace `VirtualKeyCode` with the `Key` enum.
|
||||||
|
- Replace `ScanCode` with the `KeyCode` enum.
|
||||||
|
- Rename `ModifiersState::LOGO` to `SUPER` and `ModifiersState::CTRL` to `CONTROL`.
|
||||||
|
- Add `PhysicalKey` wrapping `KeyCode` and `NativeKeyCode`.
|
||||||
|
- Add `KeyCode` to refer to keys (roughly) by their physical location.
|
||||||
|
- Add `NativeKeyCode` to represent raw `KeyCode`s which Winit doesn't
|
||||||
|
understand.
|
||||||
|
- Add `Key` to represent the keys after they've been interpreted by the
|
||||||
|
active (software) keyboard layout.
|
||||||
|
- Add `NamedKey` to represent the categorized keys.
|
||||||
|
- Add `NativeKey` to represent raw `Key`s which Winit doesn't understand.
|
||||||
|
- Add `KeyLocation` to tell apart `Key`s which usually "mean" the same thing,
|
||||||
|
but can appear simultaneously in different spots on the same keyboard
|
||||||
|
layout.
|
||||||
|
- Add `Window::reset_dead_keys` to enable application-controlled cancellation
|
||||||
|
of dead key sequences.
|
||||||
|
- Add `KeyEventExtModifierSupplement` to expose additional (and less
|
||||||
|
portable) interpretations of a given key-press.
|
||||||
|
- Add `PhysicalKeyExtScancode`, which lets you convert between scancodes and
|
||||||
|
`PhysicalKey`.
|
||||||
|
- `ModifiersChanged` now uses dedicated `Modifiers` struct.
|
||||||
|
- Removed platform-specific extensions that should be retrieved through `raw-window-handle` trait implementations instead:
|
||||||
|
- `platform::windows::HINSTANCE`.
|
||||||
|
- `WindowExtWindows::hinstance`.
|
||||||
|
- `WindowExtWindows::hwnd`.
|
||||||
|
- `WindowExtIOS::ui_window`.
|
||||||
|
- `WindowExtIOS::ui_view_controller`.
|
||||||
|
- `WindowExtIOS::ui_view`.
|
||||||
|
- `WindowExtMacOS::ns_window`.
|
||||||
|
- `WindowExtMacOS::ns_view`.
|
||||||
|
- `EventLoopWindowTargetExtWayland::wayland_display`.
|
||||||
|
- `WindowExtWayland::wayland_surface`.
|
||||||
|
- `WindowExtWayland::wayland_display`.
|
||||||
|
- `WindowExtX11::xlib_window`.
|
||||||
|
- `WindowExtX11::xlib_display`.
|
||||||
|
- `WindowExtX11::xlib_screen_id`.
|
||||||
|
- `WindowExtX11::xcb_connection`.
|
||||||
|
- Reexport `raw-window-handle` in `window` module.
|
||||||
|
- Add `ElementState::is_pressed`.
|
||||||
|
- Add `Window::pre_present_notify` to notify winit before presenting to the windowing system.
|
||||||
|
- Add `Window::set_blur` to request a blur behind the window; implemented on Wayland for now.
|
||||||
|
- Add `Window::show_window_menu` to request a titlebar/system menu; implemented on Wayland/Windows for now.
|
||||||
|
- Implement `AsFd`/`AsRawFd` for `EventLoop<T>` on X11 and Wayland.
|
||||||
|
- Implement `PartialOrd` and `Ord` for `MouseButton`.
|
||||||
|
- Implement `PartialOrd` and `Ord` on types in the `dpi` module.
|
||||||
|
- Make `WindowBuilder` `Send + Sync`.
|
||||||
|
- Make iOS `MonitorHandle` and `VideoMode` usable from other threads.
|
||||||
|
- Make iOS windows usable from other threads.
|
||||||
|
- On Android, add force data to touch events.
|
||||||
|
- On Android, added `EventLoopBuilderExtAndroid::handle_volume_keys` to indicate that the application will handle the volume keys manually.
|
||||||
|
- On Android, fix `DeviceId` to contain device id's.
|
||||||
|
- On Orbital, fix `ModifiersChanged` not being sent.
|
||||||
|
- On Wayland, `Window::outer_size` now accounts for **client side** decorations.
|
||||||
|
- On Wayland, add `Window::drag_resize_window` method.
|
||||||
|
- On Wayland, remove `WINIT_WAYLAND_CSD_THEME` variable.
|
||||||
|
- On Wayland, fix `TouchPhase::Canceled` being sent for moved events.
|
||||||
|
- On Wayland, fix forward compatibility issues.
|
||||||
|
- On Wayland, fix initial window size not restored for maximized/fullscreened on startup window.
|
||||||
|
- On Wayland, fix maximized startup not taking full size on GNOME.
|
||||||
|
- On Wayland, fix maximized window creation and window geometry handling.
|
||||||
|
- On Wayland, fix window not checking that it actually got initial configure event.
|
||||||
|
- On Wayland, make double clicking and moving the CSD frame more reliable.
|
||||||
|
- On Wayland, support `Occluded` event with xdg-shell v6
|
||||||
|
- On Wayland, use frame callbacks to throttle `RedrawRequested` events so redraws will align with compositor.
|
||||||
|
- On Web, `ControlFlow::WaitUntil` now uses the Prioritized Task Scheduling API. `setTimeout()`, with a trick to circumvent throttling to 4ms, is used as a fallback.
|
||||||
|
- On Web, `EventLoopProxy` now implements `Send`.
|
||||||
|
- On Web, `Window` now implements `Send` and `Sync`.
|
||||||
|
- On Web, account for CSS `padding`, `border`, and `margin` when getting or setting the canvas position.
|
||||||
|
- On Web, add Fullscreen API compatibility for Safari.
|
||||||
|
- On Web, add `DeviceEvent::Motion`, `DeviceEvent::MouseWheel`, `DeviceEvent::Button` and `DeviceEvent::Key` support.
|
||||||
|
- On Web, add `EventLoopWindowTargetExtWebSys` and `PollStrategy`, which allows to set different strategies for `ControlFlow::Poll`. By default the Prioritized Task Scheduling API is used, but an option to use `Window.requestIdleCallback` is available as well. Both use `setTimeout()`, with a trick to circumvent throttling to 4ms, as a fallback.
|
||||||
|
- On Web, add `WindowBuilderExtWebSys::with_append()` to append the canvas element to the web page on creation.
|
||||||
|
- On Web, allow event loops to be recreated with `spawn`.
|
||||||
|
- On Web, enable event propagation.
|
||||||
|
- On Web, fix `ControlFlow::WaitUntil` to never wake up **before** the given time.
|
||||||
|
- On Web, fix `DeviceEvent::MouseMotion` only being emitted for each canvas instead of the whole window.
|
||||||
|
- On Web, fix `Window:::set_fullscreen` doing nothing when called outside the event loop but during transient activation.
|
||||||
|
- On Web, fix pen treated as mouse input.
|
||||||
|
- On Web, fix pointer button events not being processed when a buttons is already pressed.
|
||||||
|
- On Web, fix scale factor resize suggestion always overwriting the canvas size.
|
||||||
|
- On Web, fix some `WindowBuilder` methods doing nothing.
|
||||||
|
- On Web, fix some `Window` methods using incorrect HTML attributes instead of CSS properties.
|
||||||
|
- On Web, fix the bfcache by not using the `beforeunload` event and map bfcache loading/unloading to `Suspended`/`Resumed` events.
|
||||||
|
- On Web, fix touch input not gaining or loosing focus.
|
||||||
|
- On Web, fix touch location to be as accurate as mouse position.
|
||||||
|
- On Web, handle coalesced pointer events, which increases the resolution of pointer inputs.
|
||||||
|
- On Web, implement `Window::focus_window()`.
|
||||||
|
- On Web, implement `Window::set_(min|max)_inner_size()`.
|
||||||
|
- On Web, implement `WindowEvent::Occluded`.
|
||||||
|
- On Web, never return a `MonitorHandle`.
|
||||||
|
- On Web, prevent clicks on the canvas to select text.
|
||||||
|
- On Web, remove any fullscreen requests from the queue when an external fullscreen activation was detected.
|
||||||
|
- On Web, remove unnecessary `Window::is_dark_mode()`, which was replaced with `Window::theme()`.
|
||||||
|
- On Web, respect `EventLoopWindowTarget::listen_device_events()` settings.
|
||||||
|
- On Web, scale factor and dark mode detection are now more robust.
|
||||||
|
- On Web, send mouse position on button release as well.
|
||||||
|
- On Web, take all transient activations on the canvas and window into account to queue a fullscreen request.
|
||||||
|
- On Web, use `Window.requestAnimationFrame()` to throttle `RedrawRequested` events.
|
||||||
|
- On Web, use the correct canvas size when calculating the new size during scale factor change, instead of using the output bitmap size.
|
||||||
|
- On Web: fix `Window::request_redraw` not waking the event loop when called from outside the loop.
|
||||||
|
- On Web: fix position of touch events to be relative to the canvas.
|
||||||
|
- On Windows, add `drag_resize_window` method support.
|
||||||
|
- On Windows, add horizontal MouseWheel `DeviceEvent`.
|
||||||
|
- On Windows, added `WindowBuilderExtWindows::with_class_name` to customize the internal class name.
|
||||||
|
- On Windows, fix IME APIs not working when from non event loop thread.
|
||||||
|
- On Windows, fix `CursorEnter/Left` not being sent when grabbing the mouse.
|
||||||
|
- On Windows, fix `RedrawRequested` not being delivered when calling `Window::request_redraw` from `RedrawRequested`.
|
||||||
|
- On Windows, port to `windows-sys` version 0.48.0.
|
||||||
|
- On X11, add a `with_embedded_parent_window` function to the window builder to allow embedding a window into another window.
|
||||||
|
- On X11, fix event loop not waking up on `ControlFlow::Poll` and `ControlFlow::WaitUntil`.
|
||||||
|
- On X11, fix false positive flagging of key repeats when pressing different keys with no release between presses.
|
||||||
|
- On X11, set `visual_id` in returned `raw-window-handle`.
|
||||||
|
- On iOS, add ability to change the status bar style.
|
||||||
|
- On iOS, add force data to touch events when using the Apple Pencil.
|
||||||
|
- On iOS, always wake the event loop when transitioning from `ControlFlow::Poll` to `ControlFlow::Poll`.
|
||||||
|
- On iOS, send events `WindowEvent::Occluded(false)`, `WindowEvent::Occluded(true)` when application enters/leaves foreground.
|
||||||
|
- On macOS, add tabbing APIs on `WindowExtMacOS` and `EventLoopWindowTargetExtMacOS`.
|
||||||
|
- On macOS, fix assertion when pressing `Globe` key.
|
||||||
|
- On macOS, fix crash in `window.set_minimized(false)`.
|
||||||
|
- On macOS, fix crash when dropping `Window`.
|
||||||
|
|
||||||
|
# 0.28.7
|
||||||
|
|
||||||
|
- Fix window size sometimes being invalid when resizing on macOS 14 Sonoma.
|
||||||
|
|
||||||
|
# 0.28.6
|
||||||
|
|
||||||
|
- On macOS, fixed memory leak when getting monitor handle.
|
||||||
|
- On macOS, fix `Backspace` being emitted when clearing preedit with it.
|
||||||
|
|
||||||
|
# 0.28.5
|
||||||
|
|
||||||
|
- On macOS, fix `key_up` being ignored when `Ime` is disabled.
|
||||||
|
|
||||||
|
# 0.28.4
|
||||||
|
|
||||||
|
- On macOS, fix empty marked text blocking regular input.
|
||||||
|
- On macOS, fix potential panic when getting refresh rate.
|
||||||
|
- On macOS, fix crash when calling `Window::set_ime_position` from another thread.
|
||||||
|
|
||||||
|
# 0.28.3
|
||||||
|
|
||||||
|
- Fix macOS memory leaks.
|
||||||
|
|
||||||
|
# 0.28.2
|
||||||
|
|
||||||
|
- Implement `HasRawDisplayHandle` for `EventLoop`.
|
||||||
|
- On macOS, set resize increments only for live resizes.
|
||||||
|
- On Wayland, fix rare crash on DPI change
|
||||||
|
- Web: Added support for `Window::theme`.
|
||||||
|
- On Wayland, fix rounding issues when doing resize.
|
||||||
|
- On macOS, fix wrong focused state on startup.
|
||||||
|
- On Windows, fix crash on setting taskbar when using Visual Studio debugger.
|
||||||
|
- On macOS, resize simple fullscreen windows on windowDidChangeScreen events.
|
||||||
|
|
||||||
|
# 0.28.1
|
||||||
|
|
||||||
|
- On Wayland, fix crash when dropping a window in multi-window setup.
|
||||||
|
|
||||||
|
# 0.28.0
|
||||||
|
|
||||||
- On macOS, fixed `Ime::Commit` persisting for all input after interacting with `Ime`.
|
- On macOS, fixed `Ime::Commit` persisting for all input after interacting with `Ime`.
|
||||||
- On macOS, added `WindowExtMacOS::option_as_alt` and `WindowExtMacOS::set_option_as_alt`.
|
- On macOS, added `WindowExtMacOS::option_as_alt` and `WindowExtMacOS::set_option_as_alt`.
|
||||||
- On Windows, fix window size for maximized, undecorated windows.
|
- On Windows, fix window size for maximized, undecorated windows.
|
||||||
@@ -277,7 +615,7 @@ And please only add new entries to the top of this list, right below the `# Unre
|
|||||||
|
|
||||||
# 0.23.0 (2020-10-02)
|
# 0.23.0 (2020-10-02)
|
||||||
|
|
||||||
- On iOS, fixed support for the "Debug View Heirarchy" feature in Xcode.
|
- On iOS, fixed support for the "Debug View Hierarchy" feature in Xcode.
|
||||||
- On all platforms, `available_monitors` and `primary_monitor` are now on `EventLoopWindowTarget` rather than `EventLoop` to list monitors event in the event loop.
|
- On all platforms, `available_monitors` and `primary_monitor` are now on `EventLoopWindowTarget` rather than `EventLoop` to list monitors event in the event loop.
|
||||||
- On Unix, X11 and Wayland are now optional features (enabled by default)
|
- On Unix, X11 and Wayland are now optional features (enabled by default)
|
||||||
- On X11, fix deadlock when calling `set_fullscreen_inner`.
|
- On X11, fix deadlock when calling `set_fullscreen_inner`.
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ may be worth creating a separate crate that extends Winit's API to add that func
|
|||||||
When reporting an issue, in order to help the maintainers understand what the problem is, please make
|
When reporting an issue, in order to help the maintainers understand what the problem is, please make
|
||||||
your description of the issue as detailed as possible:
|
your description of the issue as detailed as possible:
|
||||||
|
|
||||||
- if it is a bug, please provide clear explanation of what happens, what should happen, and how to
|
- if it is a bug, please provide a clear explanation of what happens, what should happen, and how to
|
||||||
reproduce the issue, ideally by providing a minimal program exhibiting the problem
|
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
|
- if it is a feature request, please provide a clear argumentation about why you believe this feature
|
||||||
should be supported by winit
|
should be supported by winit
|
||||||
@@ -20,8 +20,8 @@ your description of the issue as detailed as possible:
|
|||||||
|
|
||||||
When making a code contribution to winit, before opening your pull request, please make sure that:
|
When making a code contribution to winit, before opening your pull request, please make sure that:
|
||||||
|
|
||||||
- your patch builds with Winit's minimal supported rust version - Rust 1.60.
|
- your patch builds with Winit's minimal supported rust version - Rust 1.70.
|
||||||
- you tested your modifications on all the platforms impacted, or if not possible detail which platforms
|
- you tested your modifications on all the platforms impacted, or if not possible, detail which platforms
|
||||||
were not tested, and what should be tested, so that a maintainer or another contributor can test them
|
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 updated any relevant documentation in winit
|
||||||
- you left comments in your code explaining any part that is not straightforward, so that the
|
- you left comments in your code explaining any part that is not straightforward, so that the
|
||||||
@@ -34,7 +34,7 @@ When making a code contribution to winit, before opening your pull request, plea
|
|||||||
relevant sections in [`FEATURES.md`](https://github.com/rust-windowing/winit/blob/master/FEATURES.md#features)
|
relevant sections in [`FEATURES.md`](https://github.com/rust-windowing/winit/blob/master/FEATURES.md#features)
|
||||||
should be updated.
|
should be updated.
|
||||||
|
|
||||||
Once your PR is open, you can ask for review by a maintainer of your platform. Winit's merging policy
|
Once your PR is open, you can ask for a review by a maintainer of your platform. Winit's merging policy
|
||||||
is that a PR must be approved by at least two maintainers of winit before being merged, including
|
is that a PR must be approved by at least two maintainers of winit before being merged, including
|
||||||
at least a maintainer of the platform (a maintainer making a PR themselves counts as approving it).
|
at least a maintainer of the platform (a maintainer making a PR themselves counts as approving it).
|
||||||
|
|
||||||
@@ -46,27 +46,26 @@ Once your PR is deemed ready, the merging maintainer will take care of resolving
|
|||||||
|
|
||||||
The current maintainers are listed in the [CODEOWNERS](.github/CODEOWNERS) file.
|
The current maintainers are listed in the [CODEOWNERS](.github/CODEOWNERS) file.
|
||||||
|
|
||||||
If you are interested in being pinged when testing is needed for a certain platform, please add yourself to the [Testers and Contributors](https://github.com/rust-windowing/winit/wiki/Testers-and-Contributors) table!
|
If you are interested in being pinged when testing is needed for a specific platform, please add yourself to the [Testers and Contributors](https://github.com/rust-windowing/winit/wiki/Testers-and-Contributors) table!
|
||||||
|
|
||||||
## Release process
|
## 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.
|
||||||
|
|
||||||
To achieve these goals, a new branch is created for every new release. Releases
|
To achieve these goals, a new branch is created for every new release. Releases and later patch releases are committed and tagged in this branch.
|
||||||
and later patch releases are committed and tagged in this branch.
|
|
||||||
|
|
||||||
The exact steps for an exemplary `0.2.0` release might look like this:
|
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. In the branch, the version is bumped to `v0.2.0`
|
3. In the branch, the version is bumped to `v0.2.0`
|
||||||
4. The new commit in the branch is tagged `v0.2.0`
|
4. The new commit in the branch is tagged `v0.2.0`
|
||||||
5. The version is pushed to crates.io
|
5. The version is pushed to crates.io
|
||||||
6. A GitHub release is created for the `v0.2.0` tag
|
6. A GitHub release is created for the `v0.2.0` tag
|
||||||
7. On master, the version is bumped to `0.2.0` and the CHANGELOG is updated
|
7. On master, the version is bumped to `0.2.0`, and the CHANGELOG is updated
|
||||||
|
|
||||||
When doing a patch release the process is similar:
|
When doing a patch release, the process is similar:
|
||||||
1. Initially the version of the latest release is `0.2.0`
|
1. Initially, the version of the latest release is `0.2.0`
|
||||||
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 3-7 of the regular release example
|
4. Follow steps 3-7 of the regular release example
|
||||||
|
|||||||
196
Cargo.toml
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "winit"
|
name = "winit"
|
||||||
version = "0.27.5"
|
version = "0.29.10"
|
||||||
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."
|
description = "Cross-platform window creation library."
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
@@ -10,10 +10,18 @@ readme = "README.md"
|
|||||||
repository = "https://github.com/rust-windowing/winit"
|
repository = "https://github.com/rust-windowing/winit"
|
||||||
documentation = "https://docs.rs/winit"
|
documentation = "https://docs.rs/winit"
|
||||||
categories = ["gui"]
|
categories = ["gui"]
|
||||||
rust-version = "1.60.0"
|
rust-version = "1.70.0"
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
features = ["serde"]
|
features = [
|
||||||
|
"rwh_04",
|
||||||
|
"rwh_05",
|
||||||
|
"rwh_06",
|
||||||
|
"serde",
|
||||||
|
"mint",
|
||||||
|
# Enabled to get docs to compile
|
||||||
|
"android-native-activity",
|
||||||
|
]
|
||||||
default-target = "x86_64-unknown-linux-gnu"
|
default-target = "x86_64-unknown-linux-gnu"
|
||||||
# These are all tested in CI
|
# These are all tested in CI
|
||||||
targets = [
|
targets = [
|
||||||
@@ -29,53 +37,115 @@ targets = [
|
|||||||
"x86_64-apple-ios",
|
"x86_64-apple-ios",
|
||||||
# Android
|
# Android
|
||||||
"aarch64-linux-android",
|
"aarch64-linux-android",
|
||||||
# WebAssembly
|
# Web
|
||||||
"wasm32-unknown-unknown",
|
"wasm32-unknown-unknown",
|
||||||
]
|
]
|
||||||
rustdoc-args = ["--cfg", "docsrs"]
|
rustdoc-args = ["--cfg", "docsrs"]
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["x11", "wayland", "wayland-dlopen", "wayland-csd-adwaita"]
|
default = ["rwh_06", "x11", "wayland", "wayland-dlopen", "wayland-csd-adwaita"]
|
||||||
x11 = ["x11-dl", "mio", "percent-encoding"]
|
x11 = ["x11-dl", "bytemuck", "percent-encoding", "xkbcommon-dl/x11", "x11rb"]
|
||||||
wayland = ["wayland-client", "wayland-protocols", "sctk", "wayland-commons"]
|
wayland = ["wayland-client", "wayland-backend", "wayland-protocols", "wayland-protocols-plasma", "sctk", "ahash", "memmap2"]
|
||||||
wayland-dlopen = ["sctk/dlopen", "wayland-client/dlopen"]
|
wayland-dlopen = ["wayland-backend/dlopen"]
|
||||||
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" ]
|
android-native-activity = ["android-activity/native-activity"]
|
||||||
android-game-activity = [ "android-activity/game-activity" ]
|
android-game-activity = ["android-activity/game-activity"]
|
||||||
|
serde = ["dep:serde", "cursor-icon/serde", "smol_str/serde"]
|
||||||
|
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.1.1"
|
cfg_aliases = "0.2.0"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
bitflags = "1"
|
bitflags = "2"
|
||||||
instant = { version = "0.1", features = ["wasm-bindgen"] }
|
cursor-icon = "1.1.0"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
mint = { version = "0.5.6", optional = true }
|
mint = { version = "0.5.6", optional = true }
|
||||||
once_cell = "1.12"
|
once_cell = "1.12"
|
||||||
raw_window_handle = { package = "raw-window-handle", version = "0.5" }
|
rwh_04 = { package = "raw-window-handle", version = "0.4", optional = true }
|
||||||
|
rwh_05 = { package = "raw-window-handle", version = "0.5.2", features = ["std"], optional = true }
|
||||||
|
rwh_06 = { package = "raw-window-handle", version = "0.6", features = ["std"], optional = true }
|
||||||
serde = { version = "1", optional = true, features = ["serde_derive"] }
|
serde = { version = "1", optional = true, features = ["serde_derive"] }
|
||||||
|
smol_str = "0.2.0"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
image = { version = "0.24.0", default-features = false, features = ["png"] }
|
image = { version = "0.24.0", default-features = false, features = ["png"] }
|
||||||
simple_logger = { version = "2.1.0", default_features = false }
|
simple_logger = { version = "4.2.0", default_features = false }
|
||||||
|
winit = { path = ".", features = ["rwh_05"] }
|
||||||
|
|
||||||
|
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dev-dependencies]
|
||||||
|
softbuffer = { version = "0.3.0", default-features = false, features = ["x11", "x11-dlopen", "wayland", "wayland-dlopen"] }
|
||||||
|
|
||||||
[target.'cfg(target_os = "android")'.dependencies]
|
[target.'cfg(target_os = "android")'.dependencies]
|
||||||
# Coordinate the next winit release with android-ndk-rs: https://github.com/rust-windowing/winit/issues/1995
|
android-activity = "0.5.0"
|
||||||
android-activity = "0.4.0"
|
ndk = { version = "0.8.0", default-features = false }
|
||||||
ndk = "0.7.0"
|
ndk-sys = "0.5.0"
|
||||||
|
|
||||||
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
|
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
|
||||||
core-foundation = "0.9.3"
|
core-foundation = "0.9.3"
|
||||||
objc2 = "=0.3.0-beta.3"
|
objc2 = "0.5.0"
|
||||||
|
|
||||||
[target.'cfg(target_os = "macos")'.dependencies]
|
[target.'cfg(target_os = "macos")'.dependencies]
|
||||||
core-graphics = "0.22.3"
|
core-graphics = "0.23.1"
|
||||||
dispatch = "0.2.0"
|
|
||||||
|
[target.'cfg(target_os = "macos")'.dependencies.icrate]
|
||||||
|
version = "0.1.0"
|
||||||
|
features = [
|
||||||
|
"dispatch",
|
||||||
|
"Foundation",
|
||||||
|
"Foundation_NSArray",
|
||||||
|
"Foundation_NSAttributedString",
|
||||||
|
"Foundation_NSMutableAttributedString",
|
||||||
|
"Foundation_NSData",
|
||||||
|
"Foundation_NSDictionary",
|
||||||
|
"Foundation_NSString",
|
||||||
|
"Foundation_NSProcessInfo",
|
||||||
|
"Foundation_NSThread",
|
||||||
|
"Foundation_NSNumber",
|
||||||
|
"AppKit",
|
||||||
|
"AppKit_NSAppearance",
|
||||||
|
"AppKit_NSApplication",
|
||||||
|
"AppKit_NSBitmapImageRep",
|
||||||
|
"AppKit_NSButton",
|
||||||
|
"AppKit_NSColor",
|
||||||
|
"AppKit_NSControl",
|
||||||
|
"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]
|
||||||
|
version = "0.1.0"
|
||||||
|
features = [
|
||||||
|
"dispatch",
|
||||||
|
"Foundation",
|
||||||
|
"Foundation_NSArray",
|
||||||
|
"Foundation_NSString",
|
||||||
|
"Foundation_NSProcessInfo",
|
||||||
|
"Foundation_NSThread",
|
||||||
|
"Foundation_NSSet",
|
||||||
|
]
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "windows")'.dependencies]
|
||||||
|
unicode-segmentation = "1.7.1"
|
||||||
|
|
||||||
[target.'cfg(target_os = "windows")'.dependencies.windows-sys]
|
[target.'cfg(target_os = "windows")'.dependencies.windows-sys]
|
||||||
version = "0.45"
|
version = "0.48"
|
||||||
features = [
|
features = [
|
||||||
"Win32_Devices_HumanInterfaceDevice",
|
"Win32_Devices_HumanInterfaceDevice",
|
||||||
"Win32_Foundation",
|
"Win32_Foundation",
|
||||||
@@ -103,59 +173,93 @@ features = [
|
|||||||
"Win32_UI_WindowsAndMessaging",
|
"Win32_UI_WindowsAndMessaging",
|
||||||
]
|
]
|
||||||
|
|
||||||
[target.'cfg(all(unix, not(any(target_os = "redox", target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies]
|
[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies]
|
||||||
|
ahash = { version = "0.8.7", features = ["no-rng"], optional = true }
|
||||||
|
bytemuck = { version = "1.13.1", default-features = false, optional = true }
|
||||||
|
calloop = "0.12.3"
|
||||||
libc = "0.2.64"
|
libc = "0.2.64"
|
||||||
mio = { version = "0.8", features = ["os-ext"], optional = true }
|
memmap2 = { version = "0.9.0", optional = true }
|
||||||
percent-encoding = { version = "2.0", optional = true }
|
percent-encoding = { version = "2.0", optional = true }
|
||||||
sctk = { package = "smithay-client-toolkit", version = "0.16.0", default_features = false, features = ["calloop"], optional = true }
|
rustix = { version = "0.38.4", default-features = false, features = ["std", "system", "thread", "process"] }
|
||||||
sctk-adwaita = { version = "0.5.1", default_features = false, optional = true }
|
sctk = { package = "smithay-client-toolkit", version = "0.18.0", default-features = false, features = ["calloop"], optional = true }
|
||||||
wayland-client = { version = "0.29.5", default_features = false, features = ["use_system_lib"], optional = true }
|
sctk-adwaita = { version = "0.8.0", default_features = false, optional = true }
|
||||||
wayland-protocols = { version = "0.29.5", features = [ "staging_protocols"], optional = true }
|
wayland-backend = { version = "0.3.0", default_features = false, features = ["client_system"], optional = true }
|
||||||
wayland-commons = { version = "0.29.5", optional = true }
|
wayland-client = { version = "0.31.1", optional = true }
|
||||||
|
wayland-protocols = { version = "0.31.0", features = [ "staging"], optional = true }
|
||||||
|
wayland-protocols-plasma = { version = "0.2.0", features = [ "client" ], optional = true }
|
||||||
x11-dl = { version = "2.18.5", optional = true }
|
x11-dl = { version = "2.18.5", optional = true }
|
||||||
|
x11rb = { version = "0.13.0", default-features = false, features = ["allow-unsafe-code", "dl-libxcb", "randr", "resource_manager", "xinput", "xkb"], optional = true }
|
||||||
|
xkbcommon-dl = "0.4.0"
|
||||||
|
|
||||||
[target.'cfg(target_os = "redox")'.dependencies]
|
[target.'cfg(target_os = "redox")'.dependencies]
|
||||||
orbclient = { version = "0.3.42", default-features = false }
|
orbclient = { version = "0.3.47", default-features = false }
|
||||||
redox_syscall = "0.3"
|
redox_syscall = "0.4.1"
|
||||||
|
|
||||||
[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.build-dependencies]
|
[target.'cfg(target_family = "wasm")'.dependencies.web_sys]
|
||||||
wayland-scanner = "0.29.5"
|
|
||||||
|
|
||||||
[target.'cfg(target_arch = "wasm32")'.dependencies.web_sys]
|
|
||||||
package = "web-sys"
|
package = "web-sys"
|
||||||
version = "0.3.22"
|
version = "0.3.64"
|
||||||
features = [
|
features = [
|
||||||
|
'AbortController',
|
||||||
|
'AbortSignal',
|
||||||
|
'Blob',
|
||||||
'console',
|
'console',
|
||||||
"AddEventListenerOptions",
|
|
||||||
'CssStyleDeclaration',
|
'CssStyleDeclaration',
|
||||||
'BeforeUnloadEvent',
|
|
||||||
'Document',
|
'Document',
|
||||||
|
'DomException',
|
||||||
'DomRect',
|
'DomRect',
|
||||||
|
'DomRectReadOnly',
|
||||||
'Element',
|
'Element',
|
||||||
'Event',
|
'Event',
|
||||||
"EventListenerOptions",
|
|
||||||
'EventTarget',
|
'EventTarget',
|
||||||
'FocusEvent',
|
'FocusEvent',
|
||||||
'HtmlCanvasElement',
|
'HtmlCanvasElement',
|
||||||
'HtmlElement',
|
'HtmlElement',
|
||||||
|
'HtmlImageElement',
|
||||||
|
'ImageBitmap',
|
||||||
|
'ImageBitmapOptions',
|
||||||
|
'ImageBitmapRenderingContext',
|
||||||
|
'ImageData',
|
||||||
|
'IntersectionObserver',
|
||||||
|
'IntersectionObserverEntry',
|
||||||
'KeyboardEvent',
|
'KeyboardEvent',
|
||||||
'MediaQueryList',
|
'MediaQueryList',
|
||||||
'MediaQueryListEvent',
|
'MessageChannel',
|
||||||
'MouseEvent',
|
'MessagePort',
|
||||||
'Node',
|
'Node',
|
||||||
|
'PageTransitionEvent',
|
||||||
'PointerEvent',
|
'PointerEvent',
|
||||||
|
'PremultiplyAlpha',
|
||||||
|
'ResizeObserver',
|
||||||
|
'ResizeObserverBoxOptions',
|
||||||
|
'ResizeObserverEntry',
|
||||||
|
'ResizeObserverOptions',
|
||||||
|
'ResizeObserverSize',
|
||||||
|
'VisibilityState',
|
||||||
'Window',
|
'Window',
|
||||||
'WheelEvent'
|
'WheelEvent',
|
||||||
|
'Url',
|
||||||
]
|
]
|
||||||
|
|
||||||
[target.'cfg(target_arch = "wasm32")'.dependencies.wasm-bindgen]
|
[target.'cfg(target_family = "wasm")'.dependencies]
|
||||||
version = "0.2.45"
|
js-sys = "0.3.64"
|
||||||
|
pin-project = "1"
|
||||||
|
wasm-bindgen = "0.2"
|
||||||
|
wasm-bindgen-futures = "0.4"
|
||||||
|
web-time = "1"
|
||||||
|
|
||||||
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
|
[target.'cfg(all(target_family = "wasm", target_feature = "atomics"))'.dependencies]
|
||||||
console_log = "0.2"
|
atomic-waker = "1"
|
||||||
|
concurrent-queue = { version = "2", default-features = false }
|
||||||
|
|
||||||
|
[target.'cfg(target_family = "wasm")'.dev-dependencies]
|
||||||
|
console_log = "1"
|
||||||
web-sys = { version = "0.3.22", features = ['CanvasRenderingContext2d'] }
|
web-sys = { version = "0.3.22", features = ['CanvasRenderingContext2d'] }
|
||||||
|
|
||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
"run-wasm",
|
"run-wasm",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
doc-scrape-examples = true
|
||||||
|
name = "window"
|
||||||
|
|||||||
60
FEATURES.md
@@ -1,6 +1,6 @@
|
|||||||
# Winit Scope
|
# Winit Scope
|
||||||
|
|
||||||
Winit aims to expose an interface that abstracts over window creation and input handling, and can
|
Winit aims to expose an interface that abstracts over window creation and input handling and can
|
||||||
be used to create both games and applications. It supports the following main graphical platforms:
|
be used to create both games and applications. It supports the following main graphical platforms:
|
||||||
- Desktop
|
- Desktop
|
||||||
- Windows 7+ (10+ is tested regularly)
|
- Windows 7+ (10+ is tested regularly)
|
||||||
@@ -13,7 +13,9 @@ be used to create both games and applications. It supports the following main gr
|
|||||||
- iOS
|
- iOS
|
||||||
- Android
|
- Android
|
||||||
- Web
|
- Web
|
||||||
- via WASM
|
- Chrome
|
||||||
|
- Firefox
|
||||||
|
- Safari 13.1+
|
||||||
|
|
||||||
Most platforms expose capabilities that cannot be meaningfully transposed onto others. Winit does not
|
Most platforms expose capabilities that cannot be meaningfully transposed onto others. Winit does not
|
||||||
aim to support every single feature of every platform, but rather to abstract over the common features
|
aim to support every single feature of every platform, but rather to abstract over the common features
|
||||||
@@ -43,10 +45,10 @@ be released and the library will enter maintenance mode. For the most part, new
|
|||||||
be added past this point. New platform features may be accepted and exposed through point releases.
|
be added past this point. New platform features may be accepted and exposed through point releases.
|
||||||
|
|
||||||
### Tier upgrades
|
### Tier upgrades
|
||||||
Some platform features could in theory be exposed across multiple platforms, but have not gone
|
Some platform features could, in theory, be exposed across multiple platforms, but have not gone
|
||||||
through the implementation work necessary to function on all platforms. When one of these features
|
through the implementation work necessary to function on all platforms. When one of these features
|
||||||
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 gets 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
|
# Features
|
||||||
@@ -86,7 +88,7 @@ If your PR makes notable changes to Winit's features, please update this section
|
|||||||
- **Fullscreen toggle**: The windows created by winit can be switched to and from fullscreen after
|
- **Fullscreen toggle**: The windows created by winit can be switched to and from fullscreen after
|
||||||
creation.
|
creation.
|
||||||
- **Exclusive fullscreen**: Winit allows changing the video mode of the monitor
|
- **Exclusive fullscreen**: Winit allows changing the video mode of the monitor
|
||||||
for fullscreen windows, and if applicable, captures the monitor for exclusive
|
for fullscreen windows and, if applicable, captures the monitor for exclusive
|
||||||
use by this application.
|
use by this application.
|
||||||
- **HiDPI support**: Winit assists developers in appropriately scaling HiDPI content.
|
- **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
|
- **Popup / modal windows**: Windows can be created relative to the client area of other windows, and parent
|
||||||
@@ -103,7 +105,8 @@ If your PR makes notable changes to Winit's features, please update this section
|
|||||||
- **Mouse set location**: Forcibly changing the location of the pointer.
|
- **Mouse set location**: Forcibly changing the location of the pointer.
|
||||||
- **Cursor locking**: Locking the cursor inside the window so it cannot move.
|
- **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 confining**: Confining the cursor to the window bounds so it cannot leave them.
|
||||||
- **Cursor icon**: Changing the cursor icon, or hiding the cursor.
|
- **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.
|
- **Cursor hittest**: Handle or ignore mouse events for a window.
|
||||||
- **Touch events**: Single-touch events.
|
- **Touch events**: Single-touch events.
|
||||||
- **Touch pressure**: Touch events contain information about the amount of force being applied.
|
- **Touch pressure**: Touch events contain information about the amount of force being applied.
|
||||||
@@ -117,11 +120,17 @@ If your PR makes notable changes to Winit's features, please update this section
|
|||||||
|
|
||||||
## Platform
|
## Platform
|
||||||
### Windows
|
### Windows
|
||||||
|
* Setting the name of the internal window class
|
||||||
* Setting the taskbar icon
|
* Setting the taskbar icon
|
||||||
* Setting the parent window
|
* Setting the parent window
|
||||||
* Setting a menu bar
|
* Setting a menu bar
|
||||||
* `WS_EX_NOREDIRECTIONBITMAP` support
|
* `WS_EX_NOREDIRECTIONBITMAP` support
|
||||||
* Theme the title bar according to Windows 10 Dark Mode setting or set a preferred theme
|
* 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
|
### macOS
|
||||||
* Window activation policy
|
* Window activation policy
|
||||||
@@ -143,20 +152,17 @@ If your PR makes notable changes to Winit's features, please update this section
|
|||||||
|
|
||||||
### iOS
|
### iOS
|
||||||
* `winit` has a minimum OS requirement of iOS 8
|
* `winit` has a minimum OS requirement of iOS 8
|
||||||
* Get the `UIWindow` object pointer
|
|
||||||
* Get the `UIViewController` object pointer
|
|
||||||
* Get the `UIView` object pointer
|
|
||||||
* Get the `UIScreen` object pointer
|
* Get the `UIScreen` object pointer
|
||||||
* Setting the `UIView` hidpi factor
|
* Setting the `UIView` hidpi factor
|
||||||
* Valid orientations
|
* Valid orientations
|
||||||
* Home indicator visibility
|
* Home indicator visibility
|
||||||
* Status bar visibility
|
* Status bar visibility and style
|
||||||
* Deferrring system gestures
|
* Deferring system gestures
|
||||||
* Getting the device idiom
|
* Getting the device idiom
|
||||||
* Getting the preferred video mode
|
* Getting the preferred video mode
|
||||||
|
|
||||||
### Web
|
### Web
|
||||||
* Get if systems preferred color scheme is "dark"
|
* Get if the systems preferred color scheme is "dark"
|
||||||
|
|
||||||
## Usability
|
## Usability
|
||||||
* `serde`: Enables serialization/deserialization of certain types with Serde. (Maintainer: @Osspial)
|
* `serde`: Enables serialization/deserialization of certain types with Serde. (Maintainer: @Osspial)
|
||||||
@@ -166,22 +172,23 @@ If your PR makes notable changes to Winit's features, please update this section
|
|||||||
Legend:
|
Legend:
|
||||||
|
|
||||||
- ✔️: Works as intended
|
- ✔️: Works as intended
|
||||||
- ▢: Mostly works but some bugs are known
|
- ▢: Mostly works, but some bugs are known
|
||||||
- ❌: Missing feature or large bugs making it unusable
|
- ❌: Missing feature or large bugs making it unusable
|
||||||
- **N/A**: Not applicable for this platform
|
- **N/A**: Not applicable for this platform
|
||||||
- ❓: Unknown status
|
- ❓: Unknown status
|
||||||
|
|
||||||
### Windowing
|
### Windowing
|
||||||
|Feature |Windows|MacOS |Linux x11 |Linux Wayland |Android|iOS |WASM |Redox OS|
|
|Feature |Windows|MacOS |Linux x11 |Linux Wayland |Android|iOS |Web |Redox OS|
|
||||||
|-------------------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
|-------------------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
||||||
|Window initialization |✔️ |✔️ |▢[#5] |✔️ |▢[#33]|▢[#33] |✔️ |✔️ |
|
|Window initialization |✔️ |✔️ |▢[#5] |✔️ |▢[#33]|▢[#33] |✔️ |✔️ |
|
||||||
|Providing pointer to init OpenGL |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |
|
|Providing pointer to init OpenGL |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |
|
||||||
|Providing pointer to init Vulkan |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |**N/A**|**N/A** |
|
|Providing pointer to init Vulkan |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |**N/A**|**N/A** |
|
||||||
|Window decorations |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|✔️ |
|
|Window decorations |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|✔️ |
|
||||||
|Window decorations toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
|Window decorations toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||||
|Window resizing |✔️ |▢[#219]|✔️ |▢[#306] |**N/A**|**N/A**|✔️ |✔️ |
|
|Window resizing |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |✔️ |
|
||||||
|Window resize increments |❌ |✔️ |✔️ |❌ |**N/A**|**N/A**|**N/A**|**N/A** |
|
|Window resize increments |❌ |✔️ |✔️ |❌ |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||||
|Window transparency |✔️ |✔️ |✔️ |✔️ |**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 |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||||
|Window maximization toggle |✔️ |✔️ |✔️ |✔️ |**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** |
|
|Window minimization |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||||
@@ -192,42 +199,43 @@ Legend:
|
|||||||
|Popup windows |❌ |❌ |❌ |❌ |❌ |❌ |**N/A**|**N/A** |
|
|Popup windows |❌ |❌ |❌ |❌ |❌ |❌ |**N/A**|**N/A** |
|
||||||
|
|
||||||
### System information
|
### System information
|
||||||
|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |WASM |Redox OS|
|
|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
||||||
|---------------- | ----- | ---- | ------- | ----------- | ----- | ------- | -------- | ------ |
|
|---------------- | ----- | ---- | ------- | ----------- | ----- | ------- | -------- | ------ |
|
||||||
|Monitor list |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|❌ |
|
|Monitor list |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|❌ |
|
||||||
|Video mode query |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|❌ |
|
|Video mode query |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|❌ |
|
||||||
|
|
||||||
### Input handling
|
### Input handling
|
||||||
|Feature |Windows |MacOS |Linux x11|Linux Wayland|Android|iOS |WASM |Redox OS|
|
|Feature |Windows |MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
||||||
|----------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
|----------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
||||||
|Mouse events |✔️ |▢[#63] |✔️ |✔️ |**N/A**|**N/A**|✔️ |✔️ |
|
|Mouse events |✔️ |▢[#63] |✔️ |✔️ |**N/A**|**N/A**|✔️ |✔️ |
|
||||||
|Mouse set location |✔️ |✔️ |✔️ |✔️(when locked) |**N/A**|**N/A**|**N/A**|**N/A** |
|
|Mouse set location |✔️ |✔️ |✔️ |✔️(when locked) |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||||
|Cursor locking |❌ |✔️ |❌ |✔️ |**N/A**|**N/A**|✔️ |❌ |
|
|Cursor locking |❌ |✔️ |❌ |✔️ |**N/A**|**N/A**|✔️ |❌ |
|
||||||
|Cursor confining |✔️ |❌ |✔️ |✔️ |**N/A**|**N/A**|❌ |❌ |
|
|Cursor confining |✔️ |❌ |✔️ |✔️ |**N/A**|**N/A**|❌ |❌ |
|
||||||
|Cursor icon |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |**N/A** |
|
|Cursor icon |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |**N/A** |
|
||||||
|Cursor hittest |✔️ |✔️ |❌ |✔️ |**N/A**|**N/A**|❌ |❌ |
|
|Cursor image |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |**N/A** |
|
||||||
|
|Cursor hittest |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|❌ |❌ |
|
||||||
|Touch events |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A** |
|
|Touch events |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A** |
|
||||||
|Touch pressure |✔️ |❌ |❌ |❌ |❌ |✔️ |✔️ |**N/A** |
|
|Touch pressure |✔️ |❌ |❌ |❌ |❌ |✔️ |✔️ |**N/A** |
|
||||||
|Multitouch |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |❌ |**N/A** |
|
|Multitouch |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |❌ |**N/A** |
|
||||||
|Keyboard events |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |✔️ |✔️ |
|
|Keyboard events |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |✔️ |✔️ |
|
||||||
|Drag & Drop |▢[#720] |▢[#720] |▢[#720] |❌[#306] |**N/A**|**N/A**|❓ |**N/A** |
|
|Drag & Drop |▢[#720] |▢[#720] |▢[#720] |▢[#720] |**N/A**|**N/A**|❓ |**N/A** |
|
||||||
|Raw Device Events |▢[#750] |▢[#750] |▢[#750] |❌ |❌ |❌ |❓ |**N/A** |
|
|Raw Device Events |▢[#750] |▢[#750] |▢[#750] |❌ |❌ |❌ |❓ |**N/A** |
|
||||||
|Gamepad/Joystick events |❌[#804] |❌ |❌ |❌ |❌ |❌ |❓ |**N/A** |
|
|Gamepad/Joystick events |❌[#804] |❌ |❌ |❌ |❌ |❌ |❓ |**N/A** |
|
||||||
|Device movement events |❓ |❓ |❓ |❓ |❌ |❌ |❓ |**N/A** |
|
|Device movement events |❓ |❓ |❓ |❓ |❌ |❌ |❓ |**N/A** |
|
||||||
|Drag window with cursor |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A** |**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** |
|
|Resize with cursor |✔️ |❌ |✔️ |✔️ |**N/A**|**N/A**|**N/A** |**N/A** |
|
||||||
|
|
||||||
### Pending API Reworks
|
### Pending API Reworks
|
||||||
Changes in the API that have been agreed upon but aren't implemented across all platforms.
|
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 |WASM |Redox OS|
|
|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
||||||
|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
||||||
|New API for HiDPI ([#315] [#319]) |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |❓ |
|
|New API for HiDPI ([#315] [#319]) |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |❓ |
|
||||||
|Event Loop 2.0 ([#459]) |✔️ |✔️ |❌ |✔️ |✔️ |✔️ |❓ |❓ |
|
|Event Loop 2.0 ([#459]) |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |✔️ |
|
||||||
|Keyboard Input ([#812]) |❌ |❌ |❌ |❌ |❌ |❌ |❓ |❓ |
|
|Keyboard Input 2.0 ([#753]) |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |✔️ |✔️ |
|
||||||
|
|
||||||
### Completed API Reworks
|
### Completed API Reworks
|
||||||
|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |WASM |Redox OS|
|
|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
||||||
|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
||||||
|
|
||||||
[#165]: https://github.com/rust-windowing/winit/issues/165
|
[#165]: https://github.com/rust-windowing/winit/issues/165
|
||||||
@@ -243,5 +251,5 @@ Changes in the API that have been agreed upon but aren't implemented across all
|
|||||||
[#720]: https://github.com/rust-windowing/winit/issues/720
|
[#720]: https://github.com/rust-windowing/winit/issues/720
|
||||||
[#721]: https://github.com/rust-windowing/winit/issues/721
|
[#721]: https://github.com/rust-windowing/winit/issues/721
|
||||||
[#750]: https://github.com/rust-windowing/winit/issues/750
|
[#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
|
[#804]: https://github.com/rust-windowing/winit/issues/804
|
||||||
[#812]: https://github.com/rust-windowing/winit/issues/812
|
|
||||||
|
|||||||
@@ -2,21 +2,20 @@
|
|||||||
|
|
||||||
The winit maintainers would like to recognize the following former winit
|
The winit maintainers would like to recognize the following former winit
|
||||||
contributors, without whom winit would not exist in its current form. We thank
|
contributors, without whom winit would not exist in its current form. We thank
|
||||||
them deeply for their time and efforts, and wish them best of luck in their
|
them deeply for their time and efforts and wish them the best of luck in their
|
||||||
future endeavors:
|
future endeavors:
|
||||||
|
|
||||||
* [@tomaka]: For creating the winit project and guiding it through its early
|
* [@tomaka]: For creating the winit project and guiding it through its early
|
||||||
years of existence.
|
years of existence.
|
||||||
* [@vberger]: For diligently creating the Wayland backend, and being its
|
* [@vberger]: For diligently creating the Wayland backend and being its
|
||||||
extremely helpful and benevolent maintainer for years.
|
extremely helpful and benevolent maintainer for years.
|
||||||
* [@francesca64]: For taking over the responsibility of maintaining almost every
|
* [@francesca64]: For taking over the responsibility of maintaining almost every
|
||||||
winit backend, and standardizing HiDPI support across all of them.
|
winit backend and standardizing HiDPI support across all of them.
|
||||||
* [@Osspial]: For heroically landing EventLoop 2.0, and valiantly ushering in a
|
* [@Osspial]: For heroically landing EventLoop 2.0 and valiantly ushering in a
|
||||||
vastly more sustainable era of winit.
|
vastly more sustainable era of winit.
|
||||||
* [@goddessfreya]: For selflessly taking over maintainership of glutin, and her
|
* [@goddessfreya]: For selflessly taking over maintainership of glutin and her
|
||||||
stellar dedication to improving both winit and glutin.
|
stellar dedication to improving both winit and glutin.
|
||||||
* [@ArturKovacs]: For consistently maintaining the macOS backend, and his
|
* [@ArturKovacs]: For consistently maintaining the macOS backend and for his immense involvement in designing and implementing the new keyboard API.
|
||||||
immense involvement in designing and implementing the new keyboard API.
|
|
||||||
|
|
||||||
[@tomaka]: https://github.com/tomaka
|
[@tomaka]: https://github.com/tomaka
|
||||||
[@vberger]: https://github.com/vberger
|
[@vberger]: https://github.com/vberger
|
||||||
|
|||||||
128
README.md
@@ -2,63 +2,37 @@
|
|||||||
|
|
||||||
[](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://github.com/rust-windowing/winit/actions)
|
[](https://github.com/rust-windowing/winit/actions)
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[dependencies]
|
[dependencies]
|
||||||
winit = "0.27.5"
|
winit = "0.29.10"
|
||||||
```
|
```
|
||||||
|
|
||||||
## [Documentation](https://docs.rs/winit)
|
## [Documentation](https://docs.rs/winit)
|
||||||
|
|
||||||
For features _within_ the scope of winit, see [FEATURES.md](FEATURES.md).
|
For features _within_ the scope of winit, see [FEATURES.md](FEATURES.md).
|
||||||
|
|
||||||
For features _outside_ the scope of winit, see [Missing features provided by other crates](https://github.com/rust-windowing/winit/wiki/Missing-features-provided-by-other-crates) in the wiki.
|
For features _outside_ the scope of winit, see [Are we GUI Yet?](https://areweguiyet.com/) and [Are we game yet?](https://arewegameyet.rs/), depending on what kind of project you're looking to do.
|
||||||
|
|
||||||
## Contact Us
|
## Contact Us
|
||||||
|
|
||||||
Join us in any of these:
|
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).
|
||||||
|
|
||||||
[](https://matrix.to/#/#rust-windowing:matrix.org)
|
The maintainers have a meeting every friday at UTC 15. The meeting notes can be found [here](https://hackmd.io/@winit-meetings).
|
||||||
[](https://web.libera.chat/#winit)
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
Winit is a window creation and management library. It can create windows and lets you handle
|
Winit is a window creation and management library. It can create windows and lets you handle
|
||||||
events (for example: the window being resized, a key being pressed, a mouse movement, etc.)
|
events (for example: the window being resized, a key being pressed, a mouse movement, etc.)
|
||||||
produced by window.
|
produced by the window.
|
||||||
|
|
||||||
Winit is designed to be a low-level brick in a hierarchy of libraries. Consequently, in order to
|
Winit is designed to be a low-level brick in a hierarchy of libraries. Consequently, in order to
|
||||||
show something on the window you need to use the platform-specific getters provided by winit, or
|
show something on the window you need to use the platform-specific getters provided by winit, or
|
||||||
another library.
|
another library.
|
||||||
|
|
||||||
```rust
|
|
||||||
use winit::{
|
|
||||||
event::{Event, WindowEvent},
|
|
||||||
event_loop::{ControlFlow, EventLoop},
|
|
||||||
window::WindowBuilder,
|
|
||||||
};
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
let window = WindowBuilder::new().build(&event_loop).unwrap();
|
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
|
||||||
*control_flow = ControlFlow::Wait;
|
|
||||||
|
|
||||||
match event {
|
|
||||||
Event::WindowEvent {
|
|
||||||
event: WindowEvent::CloseRequested,
|
|
||||||
window_id,
|
|
||||||
} if window_id == window.id() => *control_flow = ControlFlow::Exit,
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Winit is only officially supported on the latest stable version of the Rust compiler.
|
|
||||||
|
|
||||||
### Cargo Features
|
### Cargo Features
|
||||||
|
|
||||||
Winit provides the following features, which can be enabled in your `Cargo.toml` file:
|
Winit provides the following features, which can be enabled in your `Cargo.toml` file:
|
||||||
@@ -67,17 +41,41 @@ Winit provides the following features, which can be enabled in your `Cargo.toml`
|
|||||||
* `wayland` (enabled by default): On Unix platform, compiles with the Wayland backend
|
* `wayland` (enabled by default): On Unix platform, compiles with the Wayland backend
|
||||||
* `mint`: Enables mint (math interoperability standard types) conversions.
|
* `mint`: Enables mint (math interoperability standard types) conversions.
|
||||||
|
|
||||||
|
## MSRV Policy
|
||||||
|
|
||||||
|
This crate's Minimum Supported Rust Version (MSRV) is **1.70**. Changes to
|
||||||
|
the MSRV will be accompanied by a minor version bump.
|
||||||
|
|
||||||
|
As a **tentative** policy, the upper bound of the MSRV is given by the following
|
||||||
|
formula:
|
||||||
|
|
||||||
|
```
|
||||||
|
min(sid, stable - 3)
|
||||||
|
```
|
||||||
|
|
||||||
|
Where `sid` is the current version of `rustc` provided by [Debian Sid], and
|
||||||
|
`stable` is the latest stable version of Rust. This bound may be broken in case of a major ecosystem shift or a security vulnerability.
|
||||||
|
|
||||||
|
[Debian Sid]: https://packages.debian.org/sid/rustc
|
||||||
|
|
||||||
|
The exception is for the Android platform, where a higher Rust version
|
||||||
|
must be used for certain Android features. In this case, the MSRV will be
|
||||||
|
capped at the latest stable version of Rust minus three. This inconsistency is
|
||||||
|
not reflected in Cargo metadata, as it is not powerful enough to expose this
|
||||||
|
restriction.
|
||||||
|
|
||||||
|
All crates in the [`rust-windowing`] organizations have the
|
||||||
|
same MSRV policy.
|
||||||
|
|
||||||
|
[`rust-windowing`]: https://github.com/rust-windowing
|
||||||
|
|
||||||
### Platform-specific usage
|
### Platform-specific usage
|
||||||
|
|
||||||
#### Wayland
|
#### Wayland
|
||||||
|
|
||||||
Note that windows don't appear on Wayland until you draw/present to them.
|
Note that windows don't appear on Wayland until you draw/present to them.
|
||||||
|
|
||||||
`winit` doesn't do drawing, try the examples in [`glutin`] instead.
|
#### Web
|
||||||
|
|
||||||
[`glutin`]: https://github.com/rust-windowing/glutin
|
|
||||||
|
|
||||||
#### WebAssembly
|
|
||||||
|
|
||||||
To run the web example: `cargo run-wasm --example web`
|
To run the web example: `cargo run-wasm --example web`
|
||||||
|
|
||||||
@@ -88,7 +86,7 @@ either [provide Winit with a `<canvas>` element][web with_canvas], or [let Winit
|
|||||||
create a `<canvas>` element which you can then retrieve][web canvas getter] and
|
create a `<canvas>` element which you can then retrieve][web canvas getter] and
|
||||||
insert it into the DOM yourself.
|
insert it into the DOM yourself.
|
||||||
|
|
||||||
For example code using Winit with WebAssembly, check out the [web example]. For
|
For the example code using Winit on Web, check out the [web example]. For
|
||||||
information on using Rust on WebAssembly, check out the [Rust and WebAssembly
|
information on using Rust on WebAssembly, check out the [Rust and WebAssembly
|
||||||
book].
|
book].
|
||||||
|
|
||||||
@@ -99,7 +97,7 @@ book].
|
|||||||
|
|
||||||
#### Android
|
#### Android
|
||||||
|
|
||||||
The Android backend builds on (and exposes types from) the [`ndk`](https://docs.rs/ndk/0.7.0/ndk/) crate.
|
The Android backend builds on (and exposes types from) the [`ndk`](https://docs.rs/ndk/latest/ndk/) crate.
|
||||||
|
|
||||||
Native Android applications need some form of "glue" crate that is responsible
|
Native Android applications need some form of "glue" crate that is responsible
|
||||||
for defining the main entry point for your Rust application as well as tracking
|
for defining the main entry point for your Rust application as well as tracking
|
||||||
@@ -111,13 +109,14 @@ glue crate (prior to `0.28` it used
|
|||||||
|
|
||||||
The version of the glue crate that your application depends on _must_ match the
|
The version of the glue crate that your application depends on _must_ match the
|
||||||
version that Winit depends on because the glue crate is responsible for your
|
version that Winit depends on because the glue crate is responsible for your
|
||||||
application's main entrypoint. If Cargo resolves multiple versions they will
|
application's main entry point. If Cargo resolves multiple versions, they will
|
||||||
clash.
|
clash.
|
||||||
|
|
||||||
`winit` glue compatibility table:
|
`winit` glue compatibility table:
|
||||||
|
|
||||||
| winit | ndk-glue |
|
| winit | ndk-glue |
|
||||||
| :---: | :--------------------------: |
|
| :---: | :--------------------------: |
|
||||||
|
| 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"` |
|
||||||
| 0.26 | `ndk-glue = "0.5"` |
|
| 0.26 | `ndk-glue = "0.5"` |
|
||||||
@@ -128,7 +127,7 @@ The recommended way to avoid a conflict with the glue version is to avoid explic
|
|||||||
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 under `winit::platform::android::activity::*`
|
is re-exported by Winit under `winit::platform::android::activity::*`
|
||||||
|
|
||||||
Running on an Android device needs a dynamic system library, add this to Cargo.toml:
|
Running on an Android device needs a dynamic system library. Add this to Cargo.toml:
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[lib]
|
[lib]
|
||||||
@@ -136,14 +135,14 @@ name = "main"
|
|||||||
crate-type = ["cdylib"]
|
crate-type = ["cdylib"]
|
||||||
```
|
```
|
||||||
|
|
||||||
All Android applications are based on an `Activity` subclass and the
|
All Android applications are based on an `Activity` subclass, and the
|
||||||
`android-activity` crate is designed to support different choices for this base
|
`android-activity` crate is designed to support different choices for this base
|
||||||
class. Your application _must_ specify the base class it needs via a feature flag:
|
class. Your application _must_ specify the base class it needs via a feature flag:
|
||||||
|
|
||||||
| Base Class | Feature Flag | Notes |
|
| Base Class | Feature Flag | Notes |
|
||||||
| :--------------: | :---------------: | :-----: |
|
| :--------------: | :---------------: | :-----: |
|
||||||
| `NativeActivity` | `android-native-activity` | Built-in to Android - it is possible to use without compiling any Java or Kotlin code. Java or Kotlin code may be needed to subclass `NativeActivity` to access some platform features. It does not derive from the [`AndroidAppCompat`] base class.|
|
| `NativeActivity` | `android-native-activity` | Built-in to Android - it is possible to use without compiling any Java or Kotlin code. Java or Kotlin code may be needed to subclass `NativeActivity` to access some platform features. It does not derive from the [`AndroidAppCompat`] base class.|
|
||||||
| [`GameActivity`] | `android-game-activity` | Derives from [`AndroidAppCompat`] which is a defacto standard `Activity` base class that helps support a wider range of Android versions. Requires a build system that can compile Java or Kotlin and fetch Android dependencies from a [Maven repository][agdk_jetpack] (or link with an embedded [release][agdk_releases] of [`GameActivity`]) |
|
| [`GameActivity`] | `android-game-activity` | Derives from [`AndroidAppCompat`], a defacto standard `Activity` base class that helps support a wider range of Android versions. Requires a build system that can compile Java or Kotlin and fetch Android dependencies from a [Maven repository][agdk_jetpack] (or link with an embedded [release][agdk_releases] of [`GameActivity`]) |
|
||||||
|
|
||||||
[`GameActivity`]: https://developer.android.com/games/agdk/game-activity
|
[`GameActivity`]: https://developer.android.com/games/agdk/game-activity
|
||||||
[`GameTextInput`]: https://developer.android.com/games/agdk/add-support-for-text-input
|
[`GameTextInput`]: https://developer.android.com/games/agdk/add-support-for-text-input
|
||||||
@@ -152,40 +151,13 @@ class. Your application _must_ specify the base class it needs via a feature fla
|
|||||||
[agdk_releases]: https://developer.android.com/games/agdk/download#agdk-libraries
|
[agdk_releases]: https://developer.android.com/games/agdk/download#agdk-libraries
|
||||||
[Gradle]: https://developer.android.com/studio/build
|
[Gradle]: https://developer.android.com/studio/build
|
||||||
|
|
||||||
For example, add this to Cargo.toml:
|
For more details, refer to these `android-activity` [example applications](https://github.com/rust-mobile/android-activity/tree/main/examples).
|
||||||
```toml
|
|
||||||
winit = { version = "0.28", features = [ "android-native-activity" ] }
|
|
||||||
|
|
||||||
[target.'cfg(target_os = "android")'.dependencies]
|
|
||||||
android_logger = "0.11.0"
|
|
||||||
```
|
|
||||||
|
|
||||||
And, for example, define an entry point for your library like this:
|
|
||||||
```rust
|
|
||||||
#[cfg(target_os = "android")]
|
|
||||||
use winit::platform::android::activity::AndroidApp;
|
|
||||||
|
|
||||||
#[cfg(target_os = "android")]
|
|
||||||
#[no_mangle]
|
|
||||||
fn android_main(app: AndroidApp) {
|
|
||||||
use winit::platform::android::EventLoopBuilderExtAndroid;
|
|
||||||
|
|
||||||
android_logger::init_once(android_logger::Config::default().with_min_level(log::Level::Trace));
|
|
||||||
|
|
||||||
let event_loop = EventLoopBuilder::with_user_event()
|
|
||||||
.with_android_app(app)
|
|
||||||
.build();
|
|
||||||
_main(event_loop);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
For more details, refer to these `android-activity` [example applications](https://github.com/rib/android-activity/tree/main/examples).
|
|
||||||
|
|
||||||
##### 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.28", features = [ "android-native-activity" ] }`
|
2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.29.10", features = [ "android-native-activity" ] }`
|
||||||
3. Add an `android_main` entrypoint (as above), instead of using the '`[ndk_glue::main]` proc macro from `ndk-macros` (optionally add a dependency on `android_logger` and initialize logging as above).
|
3. Add an `android_main` entrypoint (as above), instead of using the '`[ndk_glue::main]` proc macro from `ndk-macros` (optionally add a dependency on `android_logger` and initialize logging as above).
|
||||||
4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your event loop (as shown above).
|
4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your event loop (as shown above).
|
||||||
|
|
||||||
@@ -196,13 +168,13 @@ doing anything; this includes creating windows, fetching monitors, drawing,
|
|||||||
and so on, see issues [#2238], [#2051] and [#2087].
|
and so on, see issues [#2238], [#2051] and [#2087].
|
||||||
|
|
||||||
If you encounter problems, you should try doing your initialization inside
|
If you encounter problems, you should try doing your initialization inside
|
||||||
`Event::NewEvents(StartCause::Init)`.
|
`Event::Resumed`.
|
||||||
|
|
||||||
#### iOS
|
#### iOS
|
||||||
|
|
||||||
Similar to macOS, iOS's main `UIApplicationMain` does some init work that's required
|
Similar to macOS, iOS's main `UIApplicationMain` does some init work that's required
|
||||||
by all UI related code, see issue [#1705]. You should consider creating your windows
|
by all UI-related code (see issue [#1705]). It would be best to consider creating your windows
|
||||||
inside `Event::NewEvents(StartCause::Init)`.
|
inside `Event::Resumed`.
|
||||||
|
|
||||||
|
|
||||||
[#2238]: https://github.com/rust-windowing/winit/issues/2238
|
[#2238]: https://github.com/rust-windowing/winit/issues/2238
|
||||||
@@ -212,5 +184,5 @@ inside `Event::NewEvents(StartCause::Init)`.
|
|||||||
|
|
||||||
#### Redox OS
|
#### Redox OS
|
||||||
|
|
||||||
Redox OS has some functionality not present yet, that will be implemented when
|
Redox OS has some functionality not yet present that will be implemented when
|
||||||
its orbital display server provides it.
|
its orbital display server provides it.
|
||||||
|
|||||||
48
build.rs
@@ -1,64 +1,24 @@
|
|||||||
use cfg_aliases::cfg_aliases;
|
use cfg_aliases::cfg_aliases;
|
||||||
|
|
||||||
#[cfg(all(
|
|
||||||
any(
|
|
||||||
target_os = "linux",
|
|
||||||
target_os = "dragonfly",
|
|
||||||
target_os = "freebsd",
|
|
||||||
target_os = "openbsd",
|
|
||||||
target_os = "netbsd",
|
|
||||||
),
|
|
||||||
feature = "wayland",
|
|
||||||
))]
|
|
||||||
mod wayland {
|
|
||||||
use std::env;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
use wayland_scanner::Side;
|
|
||||||
|
|
||||||
pub fn main() {
|
|
||||||
let mut path = PathBuf::from(env::var("OUT_DIR").unwrap());
|
|
||||||
path.push("fractional_scale_v1.rs");
|
|
||||||
wayland_scanner::generate_code(
|
|
||||||
"wayland_protocols/fractional-scale-v1.xml",
|
|
||||||
&path,
|
|
||||||
Side::Client,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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");
|
||||||
println!("cargo:rerun-if-changed=wayland_protocols");
|
|
||||||
|
|
||||||
// Setup cfg aliases
|
// Setup cfg aliases
|
||||||
cfg_aliases! {
|
cfg_aliases! {
|
||||||
// Systems.
|
// Systems.
|
||||||
android_platform: { target_os = "android" },
|
android_platform: { target_os = "android" },
|
||||||
wasm_platform: { target_arch = "wasm32" },
|
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: { target_os = "ios" },
|
||||||
windows_platform: { target_os = "windows" },
|
windows_platform: { target_os = "windows" },
|
||||||
apple: { any(target_os = "ios", target_os = "macos") },
|
apple: { any(target_os = "ios", target_os = "macos") },
|
||||||
free_unix: { all(unix, not(apple), not(android_platform)) },
|
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.
|
||||||
x11_platform: { all(feature = "x11", free_unix, not(wasm), not(redox)) },
|
x11_platform: { all(feature = "x11", free_unix, not(redox)) },
|
||||||
wayland_platform: { all(feature = "wayland", free_unix, not(wasm), not(redox)) },
|
wayland_platform: { all(feature = "wayland", free_unix, not(redox)) },
|
||||||
orbital_platform: { redox },
|
orbital_platform: { redox },
|
||||||
}
|
}
|
||||||
|
|
||||||
// XXX aliases are not available for the build script itself.
|
|
||||||
#[cfg(all(
|
|
||||||
any(
|
|
||||||
target_os = "linux",
|
|
||||||
target_os = "dragonfly",
|
|
||||||
target_os = "freebsd",
|
|
||||||
target_os = "openbsd",
|
|
||||||
target_os = "netbsd",
|
|
||||||
),
|
|
||||||
feature = "wayland",
|
|
||||||
))]
|
|
||||||
wayland::main();
|
|
||||||
}
|
}
|
||||||
|
|||||||
15
clippy.toml
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
disallowed-methods = [
|
||||||
|
{ path = "web_sys::window", reason = "is not available in every context" },
|
||||||
|
{ path = "web_sys::HtmlCanvasElement::width", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
|
{ path = "web_sys::HtmlCanvasElement::height", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
|
{ path = "web_sys::HtmlCanvasElement::set_width", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
|
{ path = "web_sys::HtmlCanvasElement::set_height", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
|
{ path = "web_sys::Window::document", reason = "cache this to reduce calls to JS" },
|
||||||
|
{ path = "web_sys::Window::get_computed_style", reason = "cache this to reduce calls to JS" },
|
||||||
|
{ path = "web_sys::HtmlElement::style", reason = "cache this to reduce calls to JS" },
|
||||||
|
{ path = "web_sys::Element::request_fullscreen", reason = "Doesn't account for compatibility with Safari" },
|
||||||
|
{ path = "web_sys::Document::exit_fullscreen", reason = "Doesn't account for compatibility with Safari" },
|
||||||
|
{ path = "web_sys::Document::fullscreen_element", reason = "Doesn't account for compatibility with Safari" },
|
||||||
|
{ path = "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 = "icrate::AppKit::NSWindow::setFrameTopLeftPoint", reason = "Not sufficient when working with Winit's coordinate system, use `flip_window_screen_coordinates` instead" },
|
||||||
|
]
|
||||||
63
deny.toml
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
# https://embarkstudios.github.io/cargo-deny/
|
||||||
|
# cargo install cargo-deny
|
||||||
|
# cargo update && cargo deny --all-features --log-level error --target aarch64-apple-ios check
|
||||||
|
# Note: running just `cargo deny check` without a `--target` will result in
|
||||||
|
# false positives due to https://github.com/EmbarkStudios/cargo-deny/issues/324
|
||||||
|
targets = [
|
||||||
|
{ triple = "aarch64-apple-ios" },
|
||||||
|
{ triple = "aarch64-linux-android" },
|
||||||
|
{ triple = "i686-pc-windows-gnu" },
|
||||||
|
{ triple = "i686-pc-windows-msvc" },
|
||||||
|
{ triple = "i686-unknown-linux-gnu" },
|
||||||
|
{ triple = "wasm32-unknown-unknown" },
|
||||||
|
{ triple = "x86_64-apple-darwin" },
|
||||||
|
{ triple = "x86_64-apple-ios" },
|
||||||
|
{ triple = "x86_64-pc-windows-gnu" },
|
||||||
|
{ triple = "x86_64-pc-windows-msvc" },
|
||||||
|
{ triple = "x86_64-unknown-linux-gnu" },
|
||||||
|
{ triple = "x86_64-unknown-redox" },
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
[advisories]
|
||||||
|
vulnerability = "deny"
|
||||||
|
unmaintained = "warn"
|
||||||
|
yanked = "deny"
|
||||||
|
ignore = []
|
||||||
|
|
||||||
|
|
||||||
|
[bans]
|
||||||
|
multiple-versions = "deny"
|
||||||
|
wildcards = "allow" # at least until https://github.com/EmbarkStudios/cargo-deny/issues/241 is fixed
|
||||||
|
deny = []
|
||||||
|
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 = []
|
||||||
|
|
||||||
|
|
||||||
|
[licenses]
|
||||||
|
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 = [
|
||||||
|
"Apache-2.0 WITH LLVM-exception", # https://spdx.org/licenses/LLVM-exception.html
|
||||||
|
"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)
|
||||||
|
]
|
||||||
11
docs/res/ATTRIBUTION.md
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
# Image Attribution
|
||||||
|
|
||||||
|
These images are used in the documentation of `winit`.
|
||||||
|
|
||||||
|
## keyboard_*.svg
|
||||||
|
|
||||||
|
These files are a modified version of "[ANSI US QWERTY (Windows)](https://commons.wikimedia.org/wiki/File:ANSI_US_QWERTY_(Windows).svg)"
|
||||||
|
by [Tomiĉo] (https://commons.wikimedia.org/wiki/User:Tomi%C4%89o). It was
|
||||||
|
originally released under the [CC-BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/deed.en)
|
||||||
|
License. Minor modifications have been made by [John Nunley](https://github.com/notgull),
|
||||||
|
which have been released under the same license as a derivative work.
|
||||||
1
docs/res/keyboard_left_shift_key.svg
Normal file
|
After Width: | Height: | Size: 73 KiB |
1
docs/res/keyboard_numpad_1_key.svg
Normal file
|
After Width: | Height: | Size: 73 KiB |
1
docs/res/keyboard_right_shift_key.svg
Normal file
|
After Width: | Height: | Size: 73 KiB |
1
docs/res/keyboard_standard_1_key.svg
Normal file
|
After Width: | Height: | Size: 73 KiB |
@@ -1,22 +1,33 @@
|
|||||||
#[cfg(any(x11_platform, macos_platform, windows_platform))]
|
#[cfg(all(
|
||||||
fn main() {
|
feature = "rwh_06",
|
||||||
|
any(x11_platform, macos_platform, windows_platform)
|
||||||
|
))]
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
#[cfg(all(
|
||||||
|
feature = "rwh_06",
|
||||||
|
any(x11_platform, macos_platform, windows_platform)
|
||||||
|
))]
|
||||||
|
#[allow(deprecated)]
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use raw_window_handle::HasRawWindowHandle;
|
|
||||||
use winit::{
|
use winit::{
|
||||||
dpi::{LogicalPosition, LogicalSize, Position},
|
dpi::{LogicalPosition, LogicalSize, Position},
|
||||||
event::{ElementState, Event, KeyboardInput, WindowEvent},
|
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||||
event_loop::{ControlFlow, EventLoop, EventLoopWindowTarget},
|
event_loop::{EventLoop, EventLoopWindowTarget},
|
||||||
window::{Window, WindowBuilder, WindowId},
|
raw_window_handle::HasRawWindowHandle,
|
||||||
|
window::{Window, WindowId},
|
||||||
};
|
};
|
||||||
|
|
||||||
fn spawn_child_window(
|
fn spawn_child_window(
|
||||||
parent: &Window,
|
parent: &Window,
|
||||||
event_loop: &EventLoopWindowTarget<()>,
|
event_loop: &EventLoopWindowTarget,
|
||||||
windows: &mut HashMap<WindowId, Window>,
|
windows: &mut HashMap<WindowId, Window>,
|
||||||
) {
|
) {
|
||||||
let parent = parent.raw_window_handle();
|
let parent = parent.raw_window_handle().unwrap();
|
||||||
let mut builder = WindowBuilder::new()
|
let mut builder = Window::builder()
|
||||||
.with_title("child window")
|
.with_title("child window")
|
||||||
.with_inner_size(LogicalSize::new(200.0f32, 200.0f32))
|
.with_inner_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)))
|
||||||
@@ -32,8 +43,8 @@ fn main() {
|
|||||||
|
|
||||||
let mut windows = HashMap::new();
|
let mut windows = HashMap::new();
|
||||||
|
|
||||||
let event_loop: EventLoop<()> = EventLoop::new();
|
let event_loop: EventLoop<()> = EventLoop::new().unwrap();
|
||||||
let parent_window = WindowBuilder::new()
|
let parent_window = Window::builder()
|
||||||
.with_title("parent window")
|
.with_title("parent window")
|
||||||
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
||||||
.with_inner_size(LogicalSize::new(640.0f32, 480.0f32))
|
.with_inner_size(LogicalSize::new(640.0f32, 480.0f32))
|
||||||
@@ -42,14 +53,12 @@ fn main() {
|
|||||||
|
|
||||||
println!("parent window: {parent_window:?})");
|
println!("parent window: {parent_window:?})");
|
||||||
|
|
||||||
event_loop.run(move |event: Event<'_, ()>, event_loop, control_flow| {
|
event_loop.run(move |event: Event<()>, elwt| {
|
||||||
*control_flow = ControlFlow::Wait;
|
|
||||||
|
|
||||||
if let Event::WindowEvent { event, window_id } = event {
|
if let Event::WindowEvent { event, window_id } = event {
|
||||||
match event {
|
match event {
|
||||||
WindowEvent::CloseRequested => {
|
WindowEvent::CloseRequested => {
|
||||||
windows.clear();
|
windows.clear();
|
||||||
*control_flow = ControlFlow::Exit;
|
elwt.exit();
|
||||||
}
|
}
|
||||||
WindowEvent::CursorEntered { device_id: _ } => {
|
WindowEvent::CursorEntered { device_id: _ } => {
|
||||||
// On x11, println when the cursor entered in a window even if the child window is created
|
// On x11, println when the cursor entered in a window even if the child window is created
|
||||||
@@ -59,14 +68,19 @@ fn main() {
|
|||||||
println!("cursor entered in the window {window_id:?}");
|
println!("cursor entered in the window {window_id:?}");
|
||||||
}
|
}
|
||||||
WindowEvent::KeyboardInput {
|
WindowEvent::KeyboardInput {
|
||||||
input:
|
event:
|
||||||
KeyboardInput {
|
KeyEvent {
|
||||||
state: ElementState::Pressed,
|
state: ElementState::Pressed,
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
spawn_child_window(&parent_window, event_loop, &mut windows);
|
spawn_child_window(&parent_window, elwt, &mut windows);
|
||||||
|
}
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
if let Some(window) = windows.get(&window_id) {
|
||||||
|
fill::fill_window(window);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
@@ -74,7 +88,10 @@ fn main() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(any(x11_platform, macos_platform, windows_platform)))]
|
#[cfg(not(all(
|
||||||
|
feature = "rwh_06",
|
||||||
|
any(x11_platform, macos_platform, windows_platform)
|
||||||
|
)))]
|
||||||
fn main() {
|
fn main() {
|
||||||
panic!("This example is supported only on x11, macOS, and Windows.");
|
panic!("This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature enabled.");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,22 @@
|
|||||||
#![allow(clippy::single_match)]
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
use std::{thread, time};
|
use std::thread;
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
use std::time;
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
use web_time as time;
|
||||||
|
|
||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
event::{Event, KeyboardInput, WindowEvent},
|
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::{ControlFlow, EventLoop},
|
||||||
window::WindowBuilder,
|
keyboard::{Key, NamedKey},
|
||||||
|
window::Window,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
enum Mode {
|
enum Mode {
|
||||||
Wait,
|
Wait,
|
||||||
@@ -19,7 +27,7 @@ enum Mode {
|
|||||||
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);
|
||||||
|
|
||||||
fn main() {
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
SimpleLogger::new().init().unwrap();
|
SimpleLogger::new().init().unwrap();
|
||||||
|
|
||||||
println!("Press '1' to switch to Wait mode.");
|
println!("Press '1' to switch to Wait mode.");
|
||||||
@@ -28,8 +36,8 @@ fn main() {
|
|||||||
println!("Press 'R' to toggle request_redraw() calls.");
|
println!("Press 'R' to toggle request_redraw() calls.");
|
||||||
println!("Press 'Esc' to close the window.");
|
println!("Press 'Esc' to close the window.");
|
||||||
|
|
||||||
let event_loop = EventLoop::new();
|
let event_loop = EventLoop::new().unwrap();
|
||||||
let window = WindowBuilder::new()
|
let window = Window::builder()
|
||||||
.with_title("Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.")
|
.with_title("Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.")
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -39,8 +47,8 @@ fn main() {
|
|||||||
let mut wait_cancelled = false;
|
let mut wait_cancelled = false;
|
||||||
let mut close_requested = false;
|
let mut close_requested = false;
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
use winit::event::{ElementState, StartCause, VirtualKeyCode};
|
use winit::event::StartCause;
|
||||||
println!("{event:?}");
|
println!("{event:?}");
|
||||||
match event {
|
match event {
|
||||||
Event::NewEvents(start_cause) => {
|
Event::NewEvents(start_cause) => {
|
||||||
@@ -54,61 +62,67 @@ fn main() {
|
|||||||
close_requested = true;
|
close_requested = true;
|
||||||
}
|
}
|
||||||
WindowEvent::KeyboardInput {
|
WindowEvent::KeyboardInput {
|
||||||
input:
|
event:
|
||||||
KeyboardInput {
|
KeyEvent {
|
||||||
virtual_keycode: Some(virtual_code),
|
logical_key: key,
|
||||||
state: ElementState::Pressed,
|
state: ElementState::Pressed,
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
..
|
..
|
||||||
} => match virtual_code {
|
} => match key.as_ref() {
|
||||||
VirtualKeyCode::Key1 => {
|
// WARNING: Consider using `key_without_modifers()` if available on your platform.
|
||||||
|
// See the `key_binding` example
|
||||||
|
Key::Character("1") => {
|
||||||
mode = Mode::Wait;
|
mode = Mode::Wait;
|
||||||
println!("\nmode: {mode:?}\n");
|
println!("\nmode: {mode:?}\n");
|
||||||
}
|
}
|
||||||
VirtualKeyCode::Key2 => {
|
Key::Character("2") => {
|
||||||
mode = Mode::WaitUntil;
|
mode = Mode::WaitUntil;
|
||||||
println!("\nmode: {mode:?}\n");
|
println!("\nmode: {mode:?}\n");
|
||||||
}
|
}
|
||||||
VirtualKeyCode::Key3 => {
|
Key::Character("3") => {
|
||||||
mode = Mode::Poll;
|
mode = Mode::Poll;
|
||||||
println!("\nmode: {mode:?}\n");
|
println!("\nmode: {mode:?}\n");
|
||||||
}
|
}
|
||||||
VirtualKeyCode::R => {
|
Key::Character("r") => {
|
||||||
request_redraw = !request_redraw;
|
request_redraw = !request_redraw;
|
||||||
println!("\nrequest_redraw: {request_redraw}\n");
|
println!("\nrequest_redraw: {request_redraw}\n");
|
||||||
}
|
}
|
||||||
VirtualKeyCode::Escape => {
|
Key::Named(NamedKey::Escape) => {
|
||||||
close_requested = true;
|
close_requested = true;
|
||||||
}
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
},
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
},
|
},
|
||||||
Event::MainEventsCleared => {
|
Event::AboutToWait => {
|
||||||
if request_redraw && !wait_cancelled && !close_requested {
|
if request_redraw && !wait_cancelled && !close_requested {
|
||||||
window.request_redraw();
|
window.request_redraw();
|
||||||
}
|
}
|
||||||
if close_requested {
|
|
||||||
control_flow.set_exit();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Event::RedrawRequested(_window_id) => {}
|
|
||||||
Event::RedrawEventsCleared => {
|
|
||||||
match mode {
|
match mode {
|
||||||
Mode::Wait => control_flow.set_wait(),
|
Mode::Wait => elwt.set_control_flow(ControlFlow::Wait),
|
||||||
Mode::WaitUntil => {
|
Mode::WaitUntil => {
|
||||||
if !wait_cancelled {
|
if !wait_cancelled {
|
||||||
control_flow.set_wait_until(instant::Instant::now() + WAIT_TIME);
|
elwt.set_control_flow(ControlFlow::WaitUntil(
|
||||||
|
time::Instant::now() + WAIT_TIME,
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Mode::Poll => {
|
Mode::Poll => {
|
||||||
thread::sleep(POLL_SLEEP_TIME);
|
thread::sleep(POLL_SLEEP_TIME);
|
||||||
control_flow.set_poll();
|
elwt.set_control_flow(ControlFlow::Poll);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if close_requested {
|
||||||
|
elwt.exit();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,60 +2,58 @@
|
|||||||
|
|
||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
event::{ElementState, Event, KeyboardInput, WindowEvent},
|
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
window::{CursorIcon, WindowBuilder},
|
window::{CursorIcon, Window},
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
SimpleLogger::new().init().unwrap();
|
mod fill;
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
let window = WindowBuilder::new().build(&event_loop).unwrap();
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder().build(&event_loop).unwrap();
|
||||||
window.set_title("A fantastic window!");
|
window.set_title("A fantastic window!");
|
||||||
|
|
||||||
let mut cursor_idx = 0;
|
let mut cursor_idx = 0;
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
control_flow.set_wait();
|
if let Event::WindowEvent { event, .. } = event {
|
||||||
|
match event {
|
||||||
match event {
|
WindowEvent::KeyboardInput {
|
||||||
Event::WindowEvent {
|
event:
|
||||||
event:
|
KeyEvent {
|
||||||
WindowEvent::KeyboardInput {
|
state: ElementState::Pressed,
|
||||||
input:
|
..
|
||||||
KeyboardInput {
|
},
|
||||||
state: ElementState::Pressed,
|
..
|
||||||
..
|
} => {
|
||||||
},
|
println!("Setting cursor to \"{:?}\"", CURSORS[cursor_idx]);
|
||||||
..
|
window.set_cursor(CURSORS[cursor_idx]);
|
||||||
},
|
if cursor_idx < CURSORS.len() - 1 {
|
||||||
..
|
cursor_idx += 1;
|
||||||
} => {
|
} else {
|
||||||
println!("Setting cursor to \"{:?}\"", CURSORS[cursor_idx]);
|
cursor_idx = 0;
|
||||||
window.set_cursor_icon(CURSORS[cursor_idx]);
|
}
|
||||||
if cursor_idx < CURSORS.len() - 1 {
|
|
||||||
cursor_idx += 1;
|
|
||||||
} else {
|
|
||||||
cursor_idx = 0;
|
|
||||||
}
|
}
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
elwt.exit();
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
}
|
}
|
||||||
Event::WindowEvent {
|
|
||||||
event: WindowEvent::CloseRequested,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
control_flow.set_exit();
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const CURSORS: &[CursorIcon] = &[
|
const CURSORS: &[CursorIcon] = &[
|
||||||
CursorIcon::Default,
|
CursorIcon::Default,
|
||||||
CursorIcon::Crosshair,
|
CursorIcon::Crosshair,
|
||||||
CursorIcon::Hand,
|
CursorIcon::Pointer,
|
||||||
CursorIcon::Arrow,
|
|
||||||
CursorIcon::Move,
|
CursorIcon::Move,
|
||||||
CursorIcon::Text,
|
CursorIcon::Text,
|
||||||
CursorIcon::Wait,
|
CursorIcon::Wait,
|
||||||
|
|||||||
@@ -2,69 +2,72 @@
|
|||||||
|
|
||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
event::{DeviceEvent, ElementState, Event, KeyboardInput, ModifiersState, WindowEvent},
|
event::{DeviceEvent, ElementState, Event, KeyEvent, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
window::{CursorGrabMode, WindowBuilder},
|
keyboard::{Key, ModifiersState, NamedKey},
|
||||||
|
window::{CursorGrabMode, Window},
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
SimpleLogger::new().init().unwrap();
|
mod fill;
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
.with_title("Super Cursor Grab'n'Hide Simulator 9000")
|
.with_title("Super Cursor Grab'n'Hide Simulator 9000")
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let mut modifiers = ModifiersState::default();
|
let mut modifiers = ModifiersState::default();
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| match event {
|
||||||
control_flow.set_wait();
|
Event::WindowEvent { event, .. } => match event {
|
||||||
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
match event {
|
WindowEvent::KeyboardInput {
|
||||||
Event::WindowEvent { event, .. } => match event {
|
event:
|
||||||
WindowEvent::CloseRequested => control_flow.set_exit(),
|
KeyEvent {
|
||||||
WindowEvent::KeyboardInput {
|
logical_key: key,
|
||||||
input:
|
state: ElementState::Released,
|
||||||
KeyboardInput {
|
..
|
||||||
state: ElementState::Released,
|
},
|
||||||
virtual_keycode: Some(key),
|
..
|
||||||
..
|
} => {
|
||||||
},
|
let result = match key {
|
||||||
..
|
Key::Named(NamedKey::Escape) => {
|
||||||
} => {
|
elwt.exit();
|
||||||
use winit::event::VirtualKeyCode::*;
|
Ok(())
|
||||||
let result = match key {
|
}
|
||||||
Escape => {
|
Key::Character(ch) => match ch.to_lowercase().as_str() {
|
||||||
control_flow.set_exit();
|
"g" => window.set_cursor_grab(CursorGrabMode::Confined),
|
||||||
Ok(())
|
"l" => window.set_cursor_grab(CursorGrabMode::Locked),
|
||||||
}
|
"a" => window.set_cursor_grab(CursorGrabMode::None),
|
||||||
G => window.set_cursor_grab(CursorGrabMode::Confined),
|
"h" => {
|
||||||
L => window.set_cursor_grab(CursorGrabMode::Locked),
|
window.set_cursor_visible(modifiers.shift_key());
|
||||||
A => window.set_cursor_grab(CursorGrabMode::None),
|
|
||||||
H => {
|
|
||||||
window.set_cursor_visible(modifiers.shift());
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
_ => Ok(()),
|
_ => Ok(()),
|
||||||
};
|
},
|
||||||
|
_ => Ok(()),
|
||||||
|
};
|
||||||
|
|
||||||
if let Err(err) = result {
|
if let Err(err) = result {
|
||||||
println!("error: {err}");
|
println!("error: {err}");
|
||||||
}
|
|
||||||
}
|
}
|
||||||
WindowEvent::ModifiersChanged(m) => modifiers = m,
|
}
|
||||||
_ => (),
|
WindowEvent::ModifiersChanged(new) => modifiers = new.state(),
|
||||||
},
|
WindowEvent::RedrawRequested => fill::fill_window(&window),
|
||||||
Event::DeviceEvent { event, .. } => match event {
|
_ => (),
|
||||||
DeviceEvent::MouseMotion { delta } => println!("mouse moved: {delta:?}"),
|
},
|
||||||
DeviceEvent::Button { button, state } => match state {
|
Event::DeviceEvent { event, .. } => match event {
|
||||||
ElementState::Pressed => println!("mouse button {button} pressed"),
|
DeviceEvent::MouseMotion { delta } => println!("mouse moved: {delta:?}"),
|
||||||
ElementState::Released => println!("mouse button {button} released"),
|
DeviceEvent::Button { button, state } => match state {
|
||||||
},
|
ElementState::Pressed => println!("mouse button {button} pressed"),
|
||||||
_ => (),
|
ElementState::Released => println!("mouse button {button} released"),
|
||||||
},
|
},
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
},
|
||||||
});
|
_ => (),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
143
examples/custom_cursors.rs
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
#![allow(clippy::single_match, clippy::disallowed_methods)]
|
||||||
|
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
use simple_logger::SimpleLogger;
|
||||||
|
use winit::{
|
||||||
|
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||||
|
event_loop::{EventLoop, EventLoopWindowTarget},
|
||||||
|
keyboard::Key,
|
||||||
|
window::{CursorIcon, CustomCursor, Window},
|
||||||
|
};
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
use {
|
||||||
|
std::sync::atomic::{AtomicU64, Ordering},
|
||||||
|
std::time::Duration,
|
||||||
|
winit::platform::web::CustomCursorExtWebSys,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||||
|
|
||||||
|
fn decode_cursor(bytes: &[u8], window_target: &EventLoopWindowTarget) -> CustomCursor {
|
||||||
|
let img = image::load_from_memory(bytes).unwrap().to_rgba8();
|
||||||
|
let samples = img.into_flat_samples();
|
||||||
|
let (_, w, h) = samples.extents();
|
||||||
|
let (w, h) = (w as u16, h as u16);
|
||||||
|
let builder = CustomCursor::from_rgba(samples.samples, w, h, w / 2, h / 2).unwrap();
|
||||||
|
|
||||||
|
builder.build(window_target)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
SimpleLogger::new()
|
||||||
|
.with_level(log::LevelFilter::Info)
|
||||||
|
.init()
|
||||||
|
.unwrap();
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
console_log::init_with_level(log::Level::Debug).unwrap();
|
||||||
|
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
let builder = Window::builder().with_title("A fantastic window!");
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
let builder = {
|
||||||
|
use winit::platform::web::WindowBuilderExtWebSys;
|
||||||
|
builder.with_append(true)
|
||||||
|
};
|
||||||
|
let window = builder.build(&event_loop).unwrap();
|
||||||
|
|
||||||
|
let mut cursor_idx = 0;
|
||||||
|
let mut cursor_visible = true;
|
||||||
|
|
||||||
|
let custom_cursors = [
|
||||||
|
decode_cursor(include_bytes!("data/cross.png"), &event_loop),
|
||||||
|
decode_cursor(include_bytes!("data/cross2.png"), &event_loop),
|
||||||
|
decode_cursor(include_bytes!("data/gradient.png"), &event_loop),
|
||||||
|
];
|
||||||
|
|
||||||
|
event_loop.run(move |event, _elwt| match event {
|
||||||
|
Event::WindowEvent { event, .. } => match event {
|
||||||
|
WindowEvent::KeyboardInput {
|
||||||
|
event:
|
||||||
|
KeyEvent {
|
||||||
|
state: ElementState::Pressed,
|
||||||
|
logical_key: key,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
..
|
||||||
|
} => match key.as_ref() {
|
||||||
|
Key::Character("1") => {
|
||||||
|
log::debug!("Setting cursor to {:?}", cursor_idx);
|
||||||
|
window.set_cursor(custom_cursors[cursor_idx].clone());
|
||||||
|
cursor_idx = (cursor_idx + 1) % 3;
|
||||||
|
}
|
||||||
|
Key::Character("2") => {
|
||||||
|
log::debug!("Setting cursor icon to default");
|
||||||
|
window.set_cursor(CursorIcon::default());
|
||||||
|
}
|
||||||
|
Key::Character("3") => {
|
||||||
|
cursor_visible = !cursor_visible;
|
||||||
|
log::debug!("Setting cursor visibility to {:?}", cursor_visible);
|
||||||
|
window.set_cursor_visible(cursor_visible);
|
||||||
|
}
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
Key::Character("4") => {
|
||||||
|
log::debug!("Setting cursor to a random image from an URL");
|
||||||
|
window.set_cursor(
|
||||||
|
CustomCursor::from_url(
|
||||||
|
format!(
|
||||||
|
"https://picsum.photos/128?random={}",
|
||||||
|
COUNTER.fetch_add(1, Ordering::Relaxed)
|
||||||
|
),
|
||||||
|
64,
|
||||||
|
64,
|
||||||
|
)
|
||||||
|
.build(_elwt),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
Key::Character("5") => {
|
||||||
|
log::debug!("Setting cursor to an animation");
|
||||||
|
window.set_cursor(
|
||||||
|
CustomCursor::from_animation(
|
||||||
|
Duration::from_secs(3),
|
||||||
|
vec![
|
||||||
|
custom_cursors[0].clone(),
|
||||||
|
custom_cursors[1].clone(),
|
||||||
|
CustomCursor::from_url(
|
||||||
|
format!(
|
||||||
|
"https://picsum.photos/128?random={}",
|
||||||
|
COUNTER.fetch_add(1, Ordering::Relaxed)
|
||||||
|
),
|
||||||
|
64,
|
||||||
|
64,
|
||||||
|
)
|
||||||
|
.build(_elwt),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
.build(_elwt),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
_elwt.exit();
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
},
|
||||||
|
Event::AboutToWait => {
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,23 +1,26 @@
|
|||||||
#![allow(clippy::single_match)]
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
#[cfg(not(wasm_platform))]
|
#[cfg(not(web_platform))]
|
||||||
fn main() {
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
event::{Event, WindowEvent},
|
event::{Event, WindowEvent},
|
||||||
event_loop::EventLoopBuilder,
|
event_loop::EventLoop,
|
||||||
window::WindowBuilder,
|
window::Window,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
enum CustomEvent {
|
enum CustomEvent {
|
||||||
Timer,
|
Timer,
|
||||||
}
|
}
|
||||||
|
|
||||||
SimpleLogger::new().init().unwrap();
|
SimpleLogger::new().init().unwrap();
|
||||||
let event_loop = EventLoopBuilder::<CustomEvent>::with_user_event().build();
|
let event_loop = EventLoop::<CustomEvent>::with_user_event().build().unwrap();
|
||||||
|
|
||||||
let _window = WindowBuilder::new()
|
let window = Window::builder()
|
||||||
.with_title("A fantastic window!")
|
.with_title("A fantastic window!")
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -35,21 +38,23 @@ fn main() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| match event {
|
||||||
control_flow.set_wait();
|
Event::UserEvent(event) => println!("user event: {event:?}"),
|
||||||
|
Event::WindowEvent {
|
||||||
match event {
|
event: WindowEvent::CloseRequested,
|
||||||
Event::UserEvent(event) => println!("user event: {event:?}"),
|
..
|
||||||
Event::WindowEvent {
|
} => elwt.exit(),
|
||||||
event: WindowEvent::CloseRequested,
|
Event::WindowEvent {
|
||||||
..
|
event: WindowEvent::RedrawRequested,
|
||||||
} => control_flow.set_exit(),
|
..
|
||||||
_ => (),
|
} => {
|
||||||
|
fill::fill_window(&window);
|
||||||
}
|
}
|
||||||
});
|
_ => (),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(wasm_platform)]
|
#[cfg(web_platform)]
|
||||||
fn main() {
|
fn main() {
|
||||||
panic!("This example is not supported on web.");
|
panic!("This example is not supported on web.");
|
||||||
}
|
}
|
||||||
|
|||||||
BIN
examples/data/cross.png
Normal file
|
After Width: | Height: | Size: 159 B |
BIN
examples/data/cross2.png
Normal file
|
After Width: | Height: | Size: 129 B |
BIN
examples/data/gradient.png
Normal file
|
After Width: | Height: | Size: 229 B |
@@ -2,34 +2,34 @@
|
|||||||
|
|
||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
event::{
|
event::{ElementState, Event, KeyEvent, MouseButton, StartCause, WindowEvent},
|
||||||
ElementState, Event, KeyboardInput, MouseButton, StartCause, VirtualKeyCode, WindowEvent,
|
|
||||||
},
|
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
window::{Window, WindowBuilder, WindowId},
|
keyboard::Key,
|
||||||
|
window::{Window, WindowId},
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
SimpleLogger::new().init().unwrap();
|
mod fill;
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
let window_1 = WindowBuilder::new().build(&event_loop).unwrap();
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
let window_2 = WindowBuilder::new().build(&event_loop).unwrap();
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window_1 = Window::builder().build(&event_loop).unwrap();
|
||||||
|
let window_2 = Window::builder().build(&event_loop).unwrap();
|
||||||
|
|
||||||
let mut switched = false;
|
let mut switched = false;
|
||||||
let mut entered_id = window_2.id();
|
let mut entered_id = window_2.id();
|
||||||
|
let mut cursor_location = None;
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| match event {
|
event_loop.run(move |event, elwt| match event {
|
||||||
Event::NewEvents(StartCause::Init) => {
|
Event::NewEvents(StartCause::Init) => {
|
||||||
eprintln!("Switch which window is to be dragged by pressing \"x\".")
|
eprintln!("Switch which window is to be dragged by pressing \"x\".")
|
||||||
}
|
}
|
||||||
Event::WindowEvent { event, window_id } => match event {
|
Event::WindowEvent { event, window_id } => match event {
|
||||||
WindowEvent::CloseRequested => control_flow.set_exit(),
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
WindowEvent::MouseInput {
|
WindowEvent::CursorMoved { position, .. } => cursor_location = Some(position),
|
||||||
state: ElementState::Pressed,
|
WindowEvent::MouseInput { state, button, .. } => {
|
||||||
button: MouseButton::Left,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
let window = if (window_id == window_1.id() && switched)
|
let window = if (window_id == window_1.id() && switched)
|
||||||
|| (window_id == window_2.id() && !switched)
|
|| (window_id == window_2.id() && !switched)
|
||||||
{
|
{
|
||||||
@@ -38,29 +38,59 @@ fn main() {
|
|||||||
&window_1
|
&window_1
|
||||||
};
|
};
|
||||||
|
|
||||||
window.drag_window().unwrap()
|
match (button, state) {
|
||||||
|
(MouseButton::Left, ElementState::Pressed) => window.drag_window().unwrap(),
|
||||||
|
(MouseButton::Right, ElementState::Released) => {
|
||||||
|
if let Some(position) = cursor_location {
|
||||||
|
window.show_window_menu(position);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
WindowEvent::CursorEntered { .. } => {
|
WindowEvent::CursorEntered { .. } => {
|
||||||
entered_id = window_id;
|
entered_id = window_id;
|
||||||
name_windows(entered_id, switched, &window_1, &window_2)
|
name_windows(entered_id, switched, &window_1, &window_2)
|
||||||
}
|
}
|
||||||
WindowEvent::KeyboardInput {
|
WindowEvent::KeyboardInput {
|
||||||
input:
|
event:
|
||||||
KeyboardInput {
|
KeyEvent {
|
||||||
state: ElementState::Released,
|
state: ElementState::Released,
|
||||||
virtual_keycode: Some(VirtualKeyCode::X),
|
logical_key: Key::Character(c),
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
..
|
..
|
||||||
} => {
|
} => match c.as_str() {
|
||||||
switched = !switched;
|
"x" => {
|
||||||
name_windows(entered_id, switched, &window_1, &window_2);
|
switched = !switched;
|
||||||
println!("Switched!")
|
name_windows(entered_id, switched, &window_1, &window_2);
|
||||||
|
println!("Switched!")
|
||||||
|
}
|
||||||
|
"d" => {
|
||||||
|
let window = if (window_id == window_1.id() && switched)
|
||||||
|
|| (window_id == window_2.id() && !switched)
|
||||||
|
{
|
||||||
|
&window_2
|
||||||
|
} else {
|
||||||
|
&window_1
|
||||||
|
};
|
||||||
|
|
||||||
|
window.set_decorations(!window.is_decorated());
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
if window_id == window_1.id() {
|
||||||
|
fill::fill_window(&window_1);
|
||||||
|
} else if window_id == window_2.id() {
|
||||||
|
fill::fill_window(&window_2);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
},
|
},
|
||||||
|
|
||||||
_ => (),
|
_ => (),
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn name_windows(window_id: WindowId, switched: bool, window_1: &Window, window_2: &Window) {
|
fn name_windows(window_id: WindowId, switched: bool, window_1: &Window, window_2: &Window) {
|
||||||
|
|||||||
56
examples/focus.rs
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
|
//! Example for focusing a window.
|
||||||
|
|
||||||
|
use simple_logger::SimpleLogger;
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
use std::time;
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
use web_time as time;
|
||||||
|
use winit::{
|
||||||
|
event::{Event, StartCause, WindowEvent},
|
||||||
|
event_loop::EventLoop,
|
||||||
|
window::Window,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
|
.with_title("A fantastic window!")
|
||||||
|
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
||||||
|
.build(&event_loop)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let mut deadline = time::Instant::now() + time::Duration::from_secs(3);
|
||||||
|
event_loop.run(move |event, elwt| {
|
||||||
|
match event {
|
||||||
|
Event::NewEvents(StartCause::ResumeTimeReached { .. }) => {
|
||||||
|
// Timeout reached; focus the window.
|
||||||
|
println!("Re-focusing the window.");
|
||||||
|
deadline += time::Duration::from_secs(3);
|
||||||
|
window.focus_window();
|
||||||
|
}
|
||||||
|
Event::WindowEvent { event, window_id } if window_id == window.id() => match event {
|
||||||
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
// Notify the windowing system that we'll be presenting to the window.
|
||||||
|
window.pre_present_notify();
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
},
|
||||||
|
Event::AboutToWait => {
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
|
||||||
|
elwt.set_control_flow(winit::event_loop::ControlFlow::WaitUntil(deadline));
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,18 +1,28 @@
|
|||||||
#![allow(clippy::single_match)]
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent};
|
use winit::dpi::LogicalSize;
|
||||||
|
use winit::event::{ElementState, Event, KeyEvent, WindowEvent};
|
||||||
use winit::event_loop::EventLoop;
|
use winit::event_loop::EventLoop;
|
||||||
use winit::window::{Fullscreen, WindowBuilder};
|
use winit::keyboard::{Key, NamedKey};
|
||||||
|
use winit::window::{Fullscreen, Window};
|
||||||
|
|
||||||
fn main() {
|
#[cfg(target_os = "macos")]
|
||||||
|
use winit::platform::macos::WindowExtMacOS;
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
SimpleLogger::new().init().unwrap();
|
SimpleLogger::new().init().unwrap();
|
||||||
let event_loop = EventLoop::new();
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
let mut decorations = true;
|
let mut decorations = true;
|
||||||
let mut minimized = false;
|
let mut minimized = false;
|
||||||
|
let mut with_min_size = false;
|
||||||
|
let mut with_max_size = false;
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
let window = Window::builder()
|
||||||
.with_title("Hello world!")
|
.with_title("Hello world!")
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -32,82 +42,122 @@ fn main() {
|
|||||||
println!("- Esc\tExit");
|
println!("- Esc\tExit");
|
||||||
println!("- F\tToggle exclusive fullscreen mode");
|
println!("- F\tToggle exclusive fullscreen mode");
|
||||||
println!("- B\tToggle borderless mode");
|
println!("- B\tToggle borderless mode");
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
println!("- C\tToggle simple fullscreen mode");
|
||||||
println!("- S\tNext screen");
|
println!("- S\tNext screen");
|
||||||
println!("- M\tNext mode for this screen");
|
println!("- M\tNext mode for this screen");
|
||||||
println!("- D\tToggle window decorations");
|
println!("- D\tToggle window decorations");
|
||||||
println!("- X\tMaximize window");
|
println!("- X\tMaximize window");
|
||||||
println!("- Z\tMinimize window");
|
println!("- Z\tMinimize window");
|
||||||
|
println!("- I\tToggle mIn size limit");
|
||||||
|
println!("- A\tToggle mAx size limit");
|
||||||
|
|
||||||
event_loop.run(move |event, elwt, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
control_flow.set_wait();
|
if let Event::WindowEvent { event, .. } = event {
|
||||||
|
match event {
|
||||||
match event {
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
Event::WindowEvent { event, .. } => match event {
|
|
||||||
WindowEvent::CloseRequested => control_flow.set_exit(),
|
|
||||||
WindowEvent::KeyboardInput {
|
WindowEvent::KeyboardInput {
|
||||||
input:
|
event:
|
||||||
KeyboardInput {
|
KeyEvent {
|
||||||
virtual_keycode: Some(virtual_code),
|
logical_key: key,
|
||||||
state: ElementState::Pressed,
|
state: ElementState::Pressed,
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
..
|
..
|
||||||
} => match virtual_code {
|
} => match key {
|
||||||
VirtualKeyCode::Escape => control_flow.set_exit(),
|
Key::Named(NamedKey::Escape) => elwt.exit(),
|
||||||
VirtualKeyCode::F | VirtualKeyCode::B if window.fullscreen().is_some() => {
|
// WARNING: Consider using `key_without_modifers()` if available on your platform.
|
||||||
window.set_fullscreen(None);
|
// See the `key_binding` example
|
||||||
}
|
Key::Character(ch) => match ch.to_lowercase().as_str() {
|
||||||
VirtualKeyCode::F => {
|
"f" | "b" if window.fullscreen().is_some() => {
|
||||||
let fullscreen = Some(Fullscreen::Exclusive(mode.clone()));
|
window.set_fullscreen(None);
|
||||||
println!("Setting mode: {fullscreen:?}");
|
|
||||||
window.set_fullscreen(fullscreen);
|
|
||||||
}
|
|
||||||
VirtualKeyCode::B => {
|
|
||||||
let fullscreen = Some(Fullscreen::Borderless(Some(monitor.clone())));
|
|
||||||
println!("Setting mode: {fullscreen:?}");
|
|
||||||
window.set_fullscreen(fullscreen);
|
|
||||||
}
|
|
||||||
VirtualKeyCode::S => {
|
|
||||||
monitor_index += 1;
|
|
||||||
if let Some(mon) = elwt.available_monitors().nth(monitor_index) {
|
|
||||||
monitor = mon;
|
|
||||||
} else {
|
|
||||||
monitor_index = 0;
|
|
||||||
monitor = elwt.available_monitors().next().expect("no monitor found!");
|
|
||||||
}
|
}
|
||||||
println!("Monitor: {:?}", monitor.name());
|
"f" => {
|
||||||
|
let fullscreen = Some(Fullscreen::Exclusive(mode.clone()));
|
||||||
|
println!("Setting mode: {fullscreen:?}");
|
||||||
|
window.set_fullscreen(fullscreen);
|
||||||
|
}
|
||||||
|
"b" => {
|
||||||
|
let fullscreen = Some(Fullscreen::Borderless(Some(monitor.clone())));
|
||||||
|
println!("Setting mode: {fullscreen:?}");
|
||||||
|
window.set_fullscreen(fullscreen);
|
||||||
|
}
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
"c" => {
|
||||||
|
window.set_simple_fullscreen(!window.simple_fullscreen());
|
||||||
|
}
|
||||||
|
"s" => {
|
||||||
|
monitor_index += 1;
|
||||||
|
if let Some(mon) = elwt.available_monitors().nth(monitor_index) {
|
||||||
|
monitor = mon;
|
||||||
|
} else {
|
||||||
|
monitor_index = 0;
|
||||||
|
monitor =
|
||||||
|
elwt.available_monitors().next().expect("no monitor found!");
|
||||||
|
}
|
||||||
|
println!("Monitor: {:?}", monitor.name());
|
||||||
|
|
||||||
mode_index = 0;
|
|
||||||
mode = monitor.video_modes().next().expect("no mode found");
|
|
||||||
println!("Mode: {mode}");
|
|
||||||
}
|
|
||||||
VirtualKeyCode::M => {
|
|
||||||
mode_index += 1;
|
|
||||||
if let Some(m) = monitor.video_modes().nth(mode_index) {
|
|
||||||
mode = m;
|
|
||||||
} else {
|
|
||||||
mode_index = 0;
|
mode_index = 0;
|
||||||
mode = monitor.video_modes().next().expect("no mode found");
|
mode = monitor.video_modes().next().expect("no mode found");
|
||||||
|
println!("Mode: {mode}");
|
||||||
}
|
}
|
||||||
println!("Mode: {mode}");
|
"m" => {
|
||||||
}
|
mode_index += 1;
|
||||||
VirtualKeyCode::D => {
|
if let Some(m) = monitor.video_modes().nth(mode_index) {
|
||||||
decorations = !decorations;
|
mode = m;
|
||||||
window.set_decorations(decorations);
|
} else {
|
||||||
}
|
mode_index = 0;
|
||||||
VirtualKeyCode::X => {
|
mode = monitor.video_modes().next().expect("no mode found");
|
||||||
let is_maximized = window.is_maximized();
|
}
|
||||||
window.set_maximized(!is_maximized);
|
println!("Mode: {mode}");
|
||||||
}
|
}
|
||||||
VirtualKeyCode::Z => {
|
"d" => {
|
||||||
minimized = !minimized;
|
decorations = !decorations;
|
||||||
window.set_minimized(minimized);
|
window.set_decorations(decorations);
|
||||||
}
|
}
|
||||||
|
"x" => {
|
||||||
|
let is_maximized = window.is_maximized();
|
||||||
|
window.set_maximized(!is_maximized);
|
||||||
|
}
|
||||||
|
"z" => {
|
||||||
|
minimized = !minimized;
|
||||||
|
window.set_minimized(minimized);
|
||||||
|
}
|
||||||
|
"i" => {
|
||||||
|
with_min_size = !with_min_size;
|
||||||
|
let min_size = if with_min_size {
|
||||||
|
Some(LogicalSize::new(100, 100))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
window.set_min_inner_size(min_size);
|
||||||
|
eprintln!(
|
||||||
|
"Min: {with_min_size}: {min_size:?} => {:?}",
|
||||||
|
window.inner_size()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
"a" => {
|
||||||
|
with_max_size = !with_max_size;
|
||||||
|
let max_size = if with_max_size {
|
||||||
|
Some(LogicalSize::new(200, 200))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
window.set_max_inner_size(max_size);
|
||||||
|
eprintln!(
|
||||||
|
"Max: {with_max_size}: {max_size:?} => {:?}",
|
||||||
|
window.inner_size()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
},
|
||||||
_ => (),
|
_ => (),
|
||||||
},
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
},
|
}
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,85 +2,85 @@
|
|||||||
|
|
||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
event::{Event, KeyboardInput, WindowEvent},
|
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
window::WindowBuilder,
|
keyboard::Key,
|
||||||
|
window::Window,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
SimpleLogger::new().init().unwrap();
|
mod fill;
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
let _window = WindowBuilder::new()
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
.with_title("Your faithful window")
|
.with_title("Your faithful window")
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let mut close_requested = false;
|
let mut close_requested = false;
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
use winit::event::{
|
if let Event::WindowEvent { event, .. } = event {
|
||||||
ElementState::Released,
|
match event {
|
||||||
VirtualKeyCode::{N, Y},
|
WindowEvent::CloseRequested => {
|
||||||
};
|
// `CloseRequested` is sent when the close button on the window is pressed (or
|
||||||
control_flow.set_wait();
|
// through whatever other mechanisms the window manager provides for closing a
|
||||||
|
// window). If you don't handle this event, the close button won't actually do
|
||||||
|
// anything.
|
||||||
|
|
||||||
match event {
|
// A common thing to do here is prompt the user if they have unsaved work.
|
||||||
Event::WindowEvent { event, .. } => {
|
// Creating a proper dialog box for that is far beyond the scope of this
|
||||||
match event {
|
// example, so here we'll just respond to the Y and N keys.
|
||||||
WindowEvent::CloseRequested => {
|
println!("Are you ready to bid your window farewell? [Y/N]");
|
||||||
// `CloseRequested` is sent when the close button on the window is pressed (or
|
close_requested = true;
|
||||||
// through whatever other mechanisms the window manager provides for closing a
|
|
||||||
// window). If you don't handle this event, the close button won't actually do
|
|
||||||
// anything.
|
|
||||||
|
|
||||||
// A common thing to do here is prompt the user if they have unsaved work.
|
// In applications where you can safely close the window without further
|
||||||
// Creating a proper dialog box for that is far beyond the scope of this
|
// action from the user, this is generally where you'd handle cleanup before
|
||||||
// example, so here we'll just respond to the Y and N keys.
|
// closing the window. How to close the window is detailed in the handler for
|
||||||
println!("Are you ready to bid your window farewell? [Y/N]");
|
// the Y key.
|
||||||
close_requested = true;
|
|
||||||
|
|
||||||
// In applications where you can safely close the window without further
|
|
||||||
// action from the user, this is generally where you'd handle cleanup before
|
|
||||||
// closing the window. How to close the window is detailed in the handler for
|
|
||||||
// the Y key.
|
|
||||||
}
|
|
||||||
WindowEvent::KeyboardInput {
|
|
||||||
input:
|
|
||||||
KeyboardInput {
|
|
||||||
virtual_keycode: Some(virtual_code),
|
|
||||||
state: Released,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
match virtual_code {
|
|
||||||
Y => {
|
|
||||||
if close_requested {
|
|
||||||
// This is where you'll want to do any cleanup you need.
|
|
||||||
println!("Buh-bye!");
|
|
||||||
|
|
||||||
// For a single-window application like this, you'd normally just
|
|
||||||
// break out of the event loop here. If you wanted to keep running the
|
|
||||||
// event loop (i.e. if it's a multi-window application), you need to
|
|
||||||
// drop the window. That closes it, and results in `Destroyed` being
|
|
||||||
// sent.
|
|
||||||
control_flow.set_exit();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
N => {
|
|
||||||
if close_requested {
|
|
||||||
println!("Your window will continue to stay by your side.");
|
|
||||||
close_requested = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
}
|
}
|
||||||
|
WindowEvent::KeyboardInput {
|
||||||
|
event:
|
||||||
|
KeyEvent {
|
||||||
|
logical_key: key,
|
||||||
|
state: ElementState::Released,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
// WARNING: Consider using `key_without_modifers()` if available on your platform.
|
||||||
|
// See the `key_binding` example
|
||||||
|
match key.as_ref() {
|
||||||
|
Key::Character("y") => {
|
||||||
|
if close_requested {
|
||||||
|
// This is where you'll want to do any cleanup you need.
|
||||||
|
println!("Buh-bye!");
|
||||||
|
|
||||||
|
// For a single-window application like this, you'd normally just
|
||||||
|
// break out of the event loop here. If you wanted to keep running the
|
||||||
|
// event loop (i.e. if it's a multi-window application), you need to
|
||||||
|
// drop the window. That closes it, and results in `Destroyed` being
|
||||||
|
// sent.
|
||||||
|
elwt.exit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Key::Character("n") => {
|
||||||
|
if close_requested {
|
||||||
|
println!("Your window will continue to stay by your side.");
|
||||||
|
close_requested = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
}
|
}
|
||||||
_ => (),
|
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
130
examples/ime.rs
@@ -3,13 +3,17 @@
|
|||||||
use log::LevelFilter;
|
use log::LevelFilter;
|
||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
dpi::PhysicalPosition,
|
dpi::{PhysicalPosition, PhysicalSize},
|
||||||
event::{ElementState, Event, Ime, VirtualKeyCode, WindowEvent},
|
event::{ElementState, Event, Ime, WindowEvent},
|
||||||
event_loop::{ControlFlow, EventLoop},
|
event_loop::EventLoop,
|
||||||
window::{ImePurpose, WindowBuilder},
|
keyboard::NamedKey,
|
||||||
|
window::{ImePurpose, Window},
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
SimpleLogger::new()
|
SimpleLogger::new()
|
||||||
.with_level(LevelFilter::Trace)
|
.with_level(LevelFilter::Trace)
|
||||||
.init()
|
.init()
|
||||||
@@ -20,9 +24,9 @@ fn main() {
|
|||||||
println!("Press F2 to toggle IME. See the documentation of `set_ime_allowed` for more info");
|
println!("Press F2 to toggle IME. See the documentation of `set_ime_allowed` for more info");
|
||||||
println!("Press F3 to cycle through IME purposes.");
|
println!("Press F3 to cycle through IME purposes.");
|
||||||
|
|
||||||
let event_loop = EventLoop::new();
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
let window = Window::builder()
|
||||||
.with_inner_size(winit::dpi::LogicalSize::new(256f64, 128f64))
|
.with_inner_size(winit::dpi::LogicalSize::new(256f64, 128f64))
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -35,78 +39,56 @@ fn main() {
|
|||||||
let mut cursor_position = PhysicalPosition::new(0.0, 0.0);
|
let mut cursor_position = PhysicalPosition::new(0.0, 0.0);
|
||||||
let mut ime_pos = PhysicalPosition::new(0.0, 0.0);
|
let mut ime_pos = PhysicalPosition::new(0.0, 0.0);
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
*control_flow = ControlFlow::Wait;
|
if let Event::WindowEvent { event, .. } = event {
|
||||||
match event {
|
match event {
|
||||||
Event::WindowEvent {
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
event: WindowEvent::CloseRequested,
|
WindowEvent::CursorMoved { position, .. } => {
|
||||||
..
|
cursor_position = position;
|
||||||
} => *control_flow = ControlFlow::Exit,
|
|
||||||
Event::WindowEvent {
|
|
||||||
event: WindowEvent::CursorMoved { position, .. },
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
cursor_position = position;
|
|
||||||
}
|
|
||||||
Event::WindowEvent {
|
|
||||||
event:
|
|
||||||
WindowEvent::MouseInput {
|
|
||||||
state: ElementState::Released,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
println!(
|
|
||||||
"Setting ime position to {}, {}",
|
|
||||||
cursor_position.x, cursor_position.y
|
|
||||||
);
|
|
||||||
ime_pos = cursor_position;
|
|
||||||
if may_show_ime {
|
|
||||||
window.set_ime_position(ime_pos);
|
|
||||||
}
|
}
|
||||||
}
|
WindowEvent::MouseInput {
|
||||||
Event::WindowEvent {
|
state: ElementState::Released,
|
||||||
event: WindowEvent::Ime(event),
|
..
|
||||||
..
|
} => {
|
||||||
} => {
|
println!(
|
||||||
println!("{event:?}");
|
"Setting ime position to {}, {}",
|
||||||
may_show_ime = event != Ime::Disabled;
|
cursor_position.x, cursor_position.y
|
||||||
if may_show_ime {
|
);
|
||||||
window.set_ime_position(ime_pos);
|
ime_pos = cursor_position;
|
||||||
|
if may_show_ime {
|
||||||
|
window.set_ime_cursor_area(ime_pos, PhysicalSize::new(10, 10));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
WindowEvent::Ime(event) => {
|
||||||
Event::WindowEvent {
|
println!("{event:?}");
|
||||||
event: WindowEvent::ReceivedCharacter(ch),
|
may_show_ime = event != Ime::Disabled;
|
||||||
..
|
if may_show_ime {
|
||||||
} => {
|
window.set_ime_cursor_area(ime_pos, PhysicalSize::new(10, 10));
|
||||||
println!("ch: {ch:?}");
|
}
|
||||||
}
|
}
|
||||||
Event::WindowEvent {
|
WindowEvent::KeyboardInput { event, .. } => {
|
||||||
event: WindowEvent::KeyboardInput { input, .. },
|
println!("key: {event:?}");
|
||||||
..
|
|
||||||
} => {
|
|
||||||
println!("key: {input:?}");
|
|
||||||
|
|
||||||
if input.state == ElementState::Pressed
|
if event.state == ElementState::Pressed && event.logical_key == NamedKey::F2 {
|
||||||
&& input.virtual_keycode == Some(VirtualKeyCode::F2)
|
ime_allowed = !ime_allowed;
|
||||||
{
|
window.set_ime_allowed(ime_allowed);
|
||||||
ime_allowed = !ime_allowed;
|
println!("\nIME allowed: {ime_allowed}\n");
|
||||||
window.set_ime_allowed(ime_allowed);
|
}
|
||||||
println!("\nIME allowed: {ime_allowed}\n");
|
if event.state == ElementState::Pressed && event.logical_key == NamedKey::F3 {
|
||||||
|
ime_purpose = match ime_purpose {
|
||||||
|
ImePurpose::Normal => ImePurpose::Password,
|
||||||
|
ImePurpose::Password => ImePurpose::Terminal,
|
||||||
|
_ => ImePurpose::Normal,
|
||||||
|
};
|
||||||
|
window.set_ime_purpose(ime_purpose);
|
||||||
|
println!("\nIME purpose: {ime_purpose:?}\n");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if input.state == ElementState::Pressed
|
WindowEvent::RedrawRequested => {
|
||||||
&& input.virtual_keycode == Some(VirtualKeyCode::F3)
|
fill::fill_window(&window);
|
||||||
{
|
|
||||||
ime_purpose = match ime_purpose {
|
|
||||||
ImePurpose::Normal => ImePurpose::Password,
|
|
||||||
ImePurpose::Password => ImePurpose::Terminal,
|
|
||||||
_ => ImePurpose::Normal,
|
|
||||||
};
|
|
||||||
window.set_ime_purpose(ime_purpose);
|
|
||||||
println!("\nIME purpose: {ime_purpose:?}\n");
|
|
||||||
}
|
}
|
||||||
|
_ => (),
|
||||||
}
|
}
|
||||||
_ => (),
|
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
62
examples/key_binding.rs
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
|
#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
|
||||||
|
use winit::{
|
||||||
|
dpi::LogicalSize,
|
||||||
|
event::{ElementState, Event, WindowEvent},
|
||||||
|
event_loop::EventLoop,
|
||||||
|
keyboard::{Key, ModifiersState},
|
||||||
|
// WARNING: This is not available on all platforms (for example on the web).
|
||||||
|
platform::modifier_supplement::KeyEventExtModifierSupplement,
|
||||||
|
window::Window,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
|
||||||
|
fn main() {
|
||||||
|
println!("This example is not supported on this platform");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
simple_logger::SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
|
.with_inner_size(LogicalSize::new(400.0, 200.0))
|
||||||
|
.build(&event_loop)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let mut modifiers = ModifiersState::default();
|
||||||
|
|
||||||
|
event_loop.run(move |event, elwt| {
|
||||||
|
if let Event::WindowEvent { event, .. } = event {
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
|
WindowEvent::ModifiersChanged(new) => {
|
||||||
|
modifiers = new.state();
|
||||||
|
}
|
||||||
|
WindowEvent::KeyboardInput { event, .. } => {
|
||||||
|
if event.state == ElementState::Pressed && !event.repeat {
|
||||||
|
match event.key_without_modifiers().as_ref() {
|
||||||
|
Key::Character("1") => {
|
||||||
|
if modifiers.shift_key() {
|
||||||
|
println!("Shift + 1 | logical_key: {:?}", event.logical_key);
|
||||||
|
} else {
|
||||||
|
println!("1");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -3,12 +3,12 @@
|
|||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::dpi::{PhysicalPosition, PhysicalSize};
|
use winit::dpi::{PhysicalPosition, PhysicalSize};
|
||||||
use winit::monitor::MonitorHandle;
|
use winit::monitor::MonitorHandle;
|
||||||
use winit::{event_loop::EventLoop, window::WindowBuilder};
|
use winit::{event_loop::EventLoop, window::Window};
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
SimpleLogger::new().init().unwrap();
|
SimpleLogger::new().init().unwrap();
|
||||||
let event_loop = EventLoop::new();
|
let event_loop = EventLoop::new().unwrap();
|
||||||
let window = WindowBuilder::new().build(&event_loop).unwrap();
|
let window = Window::builder().build(&event_loop).unwrap();
|
||||||
|
|
||||||
if let Some(mon) = window.primary_monitor() {
|
if let Some(mon) = window.primary_monitor() {
|
||||||
print_info("Primary output", mon);
|
print_info("Primary output", mon);
|
||||||
|
|||||||
@@ -4,14 +4,17 @@ use simple_logger::SimpleLogger;
|
|||||||
use winit::{
|
use winit::{
|
||||||
event::{Event, WindowEvent},
|
event::{Event, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
window::WindowBuilder,
|
window::Window,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
SimpleLogger::new().init().unwrap();
|
mod fill;
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
.with_title("Mouse Wheel events")
|
.with_title("Mouse Wheel events")
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -31,12 +34,10 @@ In both cases the example window should move like the content of a scroll area i
|
|||||||
In other words, the deltas indicate the direction in which to move the content (in this case the window)."
|
In other words, the deltas indicate the direction in which to move the content (in this case the window)."
|
||||||
);
|
);
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
control_flow.set_wait();
|
if let Event::WindowEvent { event, .. } = event {
|
||||||
|
match event {
|
||||||
match event {
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
Event::WindowEvent { event, .. } => match event {
|
|
||||||
WindowEvent::CloseRequested => control_flow.set_exit(),
|
|
||||||
WindowEvent::MouseWheel { delta, .. } => match delta {
|
WindowEvent::MouseWheel { delta, .. } => match delta {
|
||||||
winit::event::MouseScrollDelta::LineDelta(x, y) => {
|
winit::event::MouseScrollDelta::LineDelta(x, y) => {
|
||||||
println!("mouse wheel Line Delta: ({x},{y})");
|
println!("mouse wheel Line Delta: ({x},{y})");
|
||||||
@@ -54,9 +55,11 @@ In other words, the deltas indicate the direction in which to move the content (
|
|||||||
window.set_outer_position(pos)
|
window.set_outer_position(pos)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
},
|
}
|
||||||
_ => (),
|
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,26 @@
|
|||||||
#![allow(clippy::single_match)]
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
#[cfg(not(wasm_platform))]
|
#[cfg(not(web_platform))]
|
||||||
fn main() {
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
use std::{collections::HashMap, sync::mpsc, thread, time::Duration};
|
use std::{collections::HashMap, sync::mpsc, thread, time::Duration};
|
||||||
|
|
||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
dpi::{PhysicalPosition, PhysicalSize, Position, Size},
|
dpi::{PhysicalPosition, PhysicalSize, Position, Size},
|
||||||
event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent},
|
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
window::{CursorGrabMode, CursorIcon, Fullscreen, WindowBuilder, WindowLevel},
|
keyboard::{Key, ModifiersState, NamedKey},
|
||||||
|
window::{CursorGrabMode, CursorIcon, Fullscreen, Window, WindowLevel},
|
||||||
};
|
};
|
||||||
|
|
||||||
const WINDOW_COUNT: usize = 3;
|
const WINDOW_COUNT: usize = 3;
|
||||||
const WINDOW_SIZE: PhysicalSize<u32> = PhysicalSize::new(600, 400);
|
const WINDOW_SIZE: PhysicalSize<u32> = PhysicalSize::new(600, 400);
|
||||||
|
|
||||||
SimpleLogger::new().init().unwrap();
|
SimpleLogger::new().init().unwrap();
|
||||||
let event_loop = EventLoop::new();
|
let event_loop = EventLoop::new().unwrap();
|
||||||
let mut window_senders = HashMap::with_capacity(WINDOW_COUNT);
|
let mut window_senders = HashMap::with_capacity(WINDOW_COUNT);
|
||||||
for _ in 0..WINDOW_COUNT {
|
for _ in 0..WINDOW_COUNT {
|
||||||
let window = WindowBuilder::new()
|
let window = Window::builder()
|
||||||
.with_inner_size(WINDOW_SIZE)
|
.with_inner_size(WINDOW_SIZE)
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -29,6 +30,7 @@ fn main() {
|
|||||||
|
|
||||||
let (tx, rx) = mpsc::channel();
|
let (tx, rx) = mpsc::channel();
|
||||||
window_senders.insert(window.id(), tx);
|
window_senders.insert(window.id(), tx);
|
||||||
|
let mut modifiers = ModifiersState::default();
|
||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
while let Ok(event) = rx.recv() {
|
while let Ok(event) = rx.recv() {
|
||||||
match event {
|
match event {
|
||||||
@@ -51,107 +53,120 @@ fn main() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#[allow(deprecated)]
|
WindowEvent::ModifiersChanged(new) => {
|
||||||
|
modifiers = new.state();
|
||||||
|
}
|
||||||
WindowEvent::KeyboardInput {
|
WindowEvent::KeyboardInput {
|
||||||
input:
|
event:
|
||||||
KeyboardInput {
|
KeyEvent {
|
||||||
state: ElementState::Released,
|
state: ElementState::Released,
|
||||||
virtual_keycode: Some(key),
|
logical_key: key,
|
||||||
modifiers,
|
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
|
use NamedKey::{ArrowLeft, ArrowRight};
|
||||||
window.set_title(&format!("{key:?}"));
|
window.set_title(&format!("{key:?}"));
|
||||||
let state = !modifiers.shift();
|
let state = !modifiers.shift_key();
|
||||||
use VirtualKeyCode::*;
|
|
||||||
match key {
|
match key {
|
||||||
Key1 => window.set_window_level(WindowLevel::AlwaysOnTop),
|
|
||||||
Key2 => window.set_window_level(WindowLevel::AlwaysOnBottom),
|
|
||||||
Key3 => window.set_window_level(WindowLevel::Normal),
|
|
||||||
C => window.set_cursor_icon(match state {
|
|
||||||
true => CursorIcon::Progress,
|
|
||||||
false => CursorIcon::Default,
|
|
||||||
}),
|
|
||||||
D => window.set_decorations(!state),
|
|
||||||
// Cycle through video modes
|
// Cycle through video modes
|
||||||
Right | Left => {
|
Key::Named(ArrowRight) | Key::Named(ArrowLeft) => {
|
||||||
video_mode_id = match key {
|
if key == ArrowLeft {
|
||||||
Left => video_mode_id.saturating_sub(1),
|
video_mode_id = video_mode_id.saturating_sub(1);
|
||||||
Right => (video_modes.len() - 1).min(video_mode_id + 1),
|
} else if key == ArrowRight {
|
||||||
_ => unreachable!(),
|
video_mode_id = (video_modes.len() - 1).min(video_mode_id + 1);
|
||||||
};
|
}
|
||||||
println!("Picking video mode: {}", video_modes[video_mode_id]);
|
println!("Picking video mode: {}", video_modes[video_mode_id]);
|
||||||
}
|
}
|
||||||
F => window.set_fullscreen(match (state, modifiers.alt()) {
|
// WARNING: Consider using `key_without_modifers()` if available on your platform.
|
||||||
(true, false) => Some(Fullscreen::Borderless(None)),
|
// See the `key_binding` example
|
||||||
(true, true) => {
|
Key::Character(ch) => match ch.to_lowercase().as_str() {
|
||||||
Some(Fullscreen::Exclusive(video_modes[video_mode_id].clone()))
|
"1" => window.set_window_level(WindowLevel::AlwaysOnTop),
|
||||||
|
"2" => window.set_window_level(WindowLevel::AlwaysOnBottom),
|
||||||
|
"3" => window.set_window_level(WindowLevel::Normal),
|
||||||
|
"c" => window.set_cursor(match state {
|
||||||
|
true => CursorIcon::Progress,
|
||||||
|
false => CursorIcon::Default,
|
||||||
|
}),
|
||||||
|
"d" => window.set_decorations(!state),
|
||||||
|
"f" => window.set_fullscreen(match (state, modifiers.alt_key()) {
|
||||||
|
(true, false) => Some(Fullscreen::Borderless(None)),
|
||||||
|
(true, true) => Some(Fullscreen::Exclusive(
|
||||||
|
video_modes[video_mode_id].clone(),
|
||||||
|
)),
|
||||||
|
(false, _) => None,
|
||||||
|
}),
|
||||||
|
ch @ ("g" | "l") => {
|
||||||
|
let mode = match (ch, state) {
|
||||||
|
("l", true) => CursorGrabMode::Locked,
|
||||||
|
("g", true) => CursorGrabMode::Confined,
|
||||||
|
(_, _) => CursorGrabMode::None,
|
||||||
|
};
|
||||||
|
if let Err(err) = window.set_cursor_grab(mode) {
|
||||||
|
println!("error: {err}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
(false, _) => None,
|
"h" => window.set_cursor_visible(!state),
|
||||||
}),
|
"i" => {
|
||||||
L if state => {
|
println!("Info:");
|
||||||
if let Err(err) = window.set_cursor_grab(CursorGrabMode::Locked) {
|
println!("-> outer_position : {:?}", window.outer_position());
|
||||||
println!("error: {err}");
|
println!("-> inner_position : {:?}", window.inner_position());
|
||||||
|
println!("-> outer_size : {:?}", window.outer_size());
|
||||||
|
println!("-> inner_size : {:?}", window.inner_size());
|
||||||
|
println!("-> fullscreen : {:?}", window.fullscreen());
|
||||||
}
|
}
|
||||||
}
|
"m" => window.set_maximized(state),
|
||||||
G if state => {
|
"p" => window.set_outer_position({
|
||||||
if let Err(err) = window.set_cursor_grab(CursorGrabMode::Confined) {
|
let mut position = window.outer_position().unwrap();
|
||||||
println!("error: {err}");
|
let sign = if state { 1 } else { -1 };
|
||||||
|
position.x += 10 * sign;
|
||||||
|
position.y += 10 * sign;
|
||||||
|
position
|
||||||
|
}),
|
||||||
|
"q" => window.request_redraw(),
|
||||||
|
"r" => window.set_resizable(state),
|
||||||
|
"s" => {
|
||||||
|
let _ = window.request_inner_size(match state {
|
||||||
|
true => PhysicalSize::new(
|
||||||
|
WINDOW_SIZE.width + 50,
|
||||||
|
WINDOW_SIZE.height + 50,
|
||||||
|
),
|
||||||
|
false => WINDOW_SIZE,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
"k" => window.set_min_inner_size(match state {
|
||||||
G | L if !state => {
|
true => Some(PhysicalSize::new(
|
||||||
if let Err(err) = window.set_cursor_grab(CursorGrabMode::None) {
|
WINDOW_SIZE.width - 100,
|
||||||
println!("error: {err}");
|
WINDOW_SIZE.height - 100,
|
||||||
|
)),
|
||||||
|
false => None,
|
||||||
|
}),
|
||||||
|
"o" => window.set_max_inner_size(match state {
|
||||||
|
true => Some(PhysicalSize::new(
|
||||||
|
WINDOW_SIZE.width + 100,
|
||||||
|
WINDOW_SIZE.height + 100,
|
||||||
|
)),
|
||||||
|
false => None,
|
||||||
|
}),
|
||||||
|
"w" => {
|
||||||
|
if let Size::Physical(size) = WINDOW_SIZE.into() {
|
||||||
|
window
|
||||||
|
.set_cursor_position(Position::Physical(
|
||||||
|
PhysicalPosition::new(
|
||||||
|
size.width as i32 / 2,
|
||||||
|
size.height as i32 / 2,
|
||||||
|
),
|
||||||
|
))
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
"z" => {
|
||||||
H => window.set_cursor_visible(!state),
|
window.set_visible(false);
|
||||||
I => {
|
thread::sleep(Duration::from_secs(1));
|
||||||
println!("Info:");
|
window.set_visible(true);
|
||||||
println!("-> outer_position : {:?}", window.outer_position());
|
|
||||||
println!("-> inner_position : {:?}", window.inner_position());
|
|
||||||
println!("-> outer_size : {:?}", window.outer_size());
|
|
||||||
println!("-> inner_size : {:?}", window.inner_size());
|
|
||||||
println!("-> fullscreen : {:?}", window.fullscreen());
|
|
||||||
}
|
|
||||||
L => window.set_min_inner_size(match state {
|
|
||||||
true => Some(WINDOW_SIZE),
|
|
||||||
false => None,
|
|
||||||
}),
|
|
||||||
M => window.set_maximized(state),
|
|
||||||
P => window.set_outer_position({
|
|
||||||
let mut position = window.outer_position().unwrap();
|
|
||||||
let sign = if state { 1 } else { -1 };
|
|
||||||
position.x += 10 * sign;
|
|
||||||
position.y += 10 * sign;
|
|
||||||
position
|
|
||||||
}),
|
|
||||||
Q => window.request_redraw(),
|
|
||||||
R => window.set_resizable(state),
|
|
||||||
S => window.set_inner_size(match state {
|
|
||||||
true => PhysicalSize::new(
|
|
||||||
WINDOW_SIZE.width + 100,
|
|
||||||
WINDOW_SIZE.height + 100,
|
|
||||||
),
|
|
||||||
false => WINDOW_SIZE,
|
|
||||||
}),
|
|
||||||
W => {
|
|
||||||
if let Size::Physical(size) = WINDOW_SIZE.into() {
|
|
||||||
window
|
|
||||||
.set_cursor_position(Position::Physical(
|
|
||||||
PhysicalPosition::new(
|
|
||||||
size.width as i32 / 2,
|
|
||||||
size.height as i32 / 2,
|
|
||||||
),
|
|
||||||
))
|
|
||||||
.unwrap()
|
|
||||||
}
|
}
|
||||||
}
|
_ => (),
|
||||||
Z => {
|
},
|
||||||
window.set_visible(false);
|
|
||||||
thread::sleep(Duration::from_secs(1));
|
|
||||||
window.set_visible(true);
|
|
||||||
}
|
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -160,20 +175,19 @@ fn main() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
event_loop.run(move |event, _event_loop, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
match !window_senders.is_empty() {
|
if window_senders.is_empty() {
|
||||||
true => control_flow.set_wait(),
|
elwt.exit()
|
||||||
false => control_flow.set_exit(),
|
}
|
||||||
};
|
|
||||||
match event {
|
match event {
|
||||||
Event::WindowEvent { event, window_id } => match event {
|
Event::WindowEvent { event, window_id } => match event {
|
||||||
WindowEvent::CloseRequested
|
WindowEvent::CloseRequested
|
||||||
| WindowEvent::Destroyed
|
| WindowEvent::Destroyed
|
||||||
| WindowEvent::KeyboardInput {
|
| WindowEvent::KeyboardInput {
|
||||||
input:
|
event:
|
||||||
KeyboardInput {
|
KeyEvent {
|
||||||
state: ElementState::Released,
|
state: ElementState::Released,
|
||||||
virtual_keycode: Some(VirtualKeyCode::Escape),
|
logical_key: Key::Named(NamedKey::Escape),
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
..
|
..
|
||||||
@@ -182,9 +196,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
if let Some(tx) = window_senders.get(&window_id) {
|
if let Some(tx) = window_senders.get(&window_id) {
|
||||||
if let Some(event) = event.to_static() {
|
tx.send(event).unwrap();
|
||||||
tx.send(event).unwrap();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -193,7 +205,7 @@ fn main() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(wasm_platform)]
|
#[cfg(web_platform)]
|
||||||
fn main() {
|
fn main() {
|
||||||
panic!("Example not supported on Wasm");
|
panic!("Example not supported on Web");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,14 +4,18 @@ use std::collections::HashMap;
|
|||||||
|
|
||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent},
|
event::{ElementState, Event, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
|
keyboard::{Key, NamedKey},
|
||||||
window::Window,
|
window::Window,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
SimpleLogger::new().init().unwrap();
|
SimpleLogger::new().init().unwrap();
|
||||||
let event_loop = EventLoop::new();
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
let mut windows = HashMap::new();
|
let mut windows = HashMap::new();
|
||||||
for _ in 0..3 {
|
for _ in 0..3 {
|
||||||
@@ -22,40 +26,39 @@ fn main() {
|
|||||||
|
|
||||||
println!("Press N to open a new window.");
|
println!("Press N to open a new window.");
|
||||||
|
|
||||||
event_loop.run(move |event, event_loop, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
control_flow.set_wait();
|
if let Event::WindowEvent { event, window_id } = event {
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
println!("Window {window_id:?} has received the signal to close");
|
||||||
|
|
||||||
match event {
|
// This drops the window, causing it to close.
|
||||||
Event::WindowEvent { event, window_id } => {
|
windows.remove(&window_id);
|
||||||
match event {
|
|
||||||
WindowEvent::CloseRequested => {
|
|
||||||
println!("Window {window_id:?} has received the signal to close");
|
|
||||||
|
|
||||||
// This drops the window, causing it to close.
|
if windows.is_empty() {
|
||||||
windows.remove(&window_id);
|
elwt.exit();
|
||||||
|
|
||||||
if windows.is_empty() {
|
|
||||||
control_flow.set_exit();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
WindowEvent::KeyboardInput {
|
}
|
||||||
input:
|
WindowEvent::KeyboardInput {
|
||||||
KeyboardInput {
|
event,
|
||||||
state: ElementState::Pressed,
|
is_synthetic: false,
|
||||||
virtual_keycode: Some(VirtualKeyCode::N),
|
..
|
||||||
..
|
} if event.state == ElementState::Pressed => match event.logical_key {
|
||||||
},
|
Key::Named(NamedKey::Escape) => elwt.exit(),
|
||||||
is_synthetic: false,
|
Key::Character(c) if c == "n" || c == "N" => {
|
||||||
..
|
let window = Window::new(elwt).unwrap();
|
||||||
} => {
|
|
||||||
let window = Window::new(event_loop).unwrap();
|
|
||||||
println!("Opened a new window: {:?}", window.id());
|
println!("Opened a new window: {:?}", window.id());
|
||||||
windows.insert(window.id(), window);
|
windows.insert(window.id(), window);
|
||||||
}
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
if let Some(window) = windows.get(&window_id) {
|
||||||
|
fill::fill_window(window);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
_ => (),
|
||||||
}
|
}
|
||||||
_ => (),
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,38 +4,39 @@ use simple_logger::SimpleLogger;
|
|||||||
use winit::{
|
use winit::{
|
||||||
event::{ElementState, Event, WindowEvent},
|
event::{ElementState, Event, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
window::WindowBuilder,
|
window::Window,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
SimpleLogger::new().init().unwrap();
|
mod fill;
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
.with_title("A fantastic window!")
|
.with_title("A fantastic window!")
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
println!("{event:?}");
|
println!("{event:?}");
|
||||||
|
|
||||||
control_flow.set_wait();
|
if let Event::WindowEvent { event, .. } = event {
|
||||||
|
match event {
|
||||||
match event {
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
Event::WindowEvent { event, .. } => match event {
|
|
||||||
WindowEvent::CloseRequested => control_flow.set_exit(),
|
|
||||||
WindowEvent::MouseInput {
|
WindowEvent::MouseInput {
|
||||||
state: ElementState::Released,
|
state: ElementState::Released,
|
||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
window.request_redraw();
|
window.request_redraw();
|
||||||
}
|
}
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
println!("\nredrawing!\n");
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
},
|
|
||||||
Event::RedrawRequested(_) => {
|
|
||||||
println!("\nredrawing!\n");
|
|
||||||
}
|
}
|
||||||
_ => (),
|
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,48 +1,59 @@
|
|||||||
#![allow(clippy::single_match)]
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
#[cfg(not(wasm_platform))]
|
#[cfg(not(web_platform))]
|
||||||
fn main() {
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
use std::{thread, time};
|
use std::{sync::Arc, thread, time};
|
||||||
|
|
||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
event::{Event, WindowEvent},
|
event::{Event, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
window::WindowBuilder,
|
window::Window,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
SimpleLogger::new().init().unwrap();
|
SimpleLogger::new().init().unwrap();
|
||||||
let event_loop = EventLoop::new();
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
let window = {
|
||||||
.with_title("A fantastic window!")
|
let window = Window::builder()
|
||||||
.build(&event_loop)
|
.with_title("A fantastic window!")
|
||||||
.unwrap();
|
.build(&event_loop)
|
||||||
|
.unwrap();
|
||||||
|
Arc::new(window)
|
||||||
|
};
|
||||||
|
|
||||||
thread::spawn(move || loop {
|
thread::spawn({
|
||||||
thread::sleep(time::Duration::from_secs(1));
|
let window = window.clone();
|
||||||
window.request_redraw();
|
move || loop {
|
||||||
|
thread::sleep(time::Duration::from_secs(1));
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
println!("{event:?}");
|
println!("{event:?}");
|
||||||
|
|
||||||
control_flow.set_wait();
|
|
||||||
|
|
||||||
match event {
|
match event {
|
||||||
Event::WindowEvent {
|
Event::WindowEvent {
|
||||||
event: WindowEvent::CloseRequested,
|
event: WindowEvent::CloseRequested,
|
||||||
..
|
..
|
||||||
} => control_flow.set_exit(),
|
} => elwt.exit(),
|
||||||
Event::RedrawRequested(_) => {
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::RedrawRequested,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
println!("\nredrawing!\n");
|
println!("\nredrawing!\n");
|
||||||
|
fill::fill_window(&window);
|
||||||
}
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(wasm_platform)]
|
#[cfg(web_platform)]
|
||||||
fn main() {
|
fn main() {
|
||||||
unimplemented!() // `Window` can't be sent between threads
|
unimplemented!() // `Window` can't be sent between threads
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,18 +3,22 @@
|
|||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
dpi::LogicalSize,
|
dpi::LogicalSize,
|
||||||
event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent},
|
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
window::WindowBuilder,
|
keyboard::{KeyCode, PhysicalKey},
|
||||||
|
window::Window,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
SimpleLogger::new().init().unwrap();
|
SimpleLogger::new().init().unwrap();
|
||||||
let event_loop = EventLoop::new();
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
let mut resizable = false;
|
let mut resizable = false;
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
let window = Window::builder()
|
||||||
.with_title("Hit space to toggle resizability.")
|
.with_title("Hit space to toggle resizability.")
|
||||||
.with_inner_size(LogicalSize::new(600.0, 300.0))
|
.with_inner_size(LogicalSize::new(600.0, 300.0))
|
||||||
.with_min_inner_size(LogicalSize::new(400.0, 200.0))
|
.with_min_inner_size(LogicalSize::new(400.0, 200.0))
|
||||||
@@ -23,16 +27,14 @@ fn main() {
|
|||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
control_flow.set_wait();
|
if let Event::WindowEvent { event, .. } = event {
|
||||||
|
match event {
|
||||||
match event {
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
Event::WindowEvent { event, .. } => match event {
|
|
||||||
WindowEvent::CloseRequested => control_flow.set_exit(),
|
|
||||||
WindowEvent::KeyboardInput {
|
WindowEvent::KeyboardInput {
|
||||||
input:
|
event:
|
||||||
KeyboardInput {
|
KeyEvent {
|
||||||
virtual_keycode: Some(VirtualKeyCode::Space),
|
physical_key: PhysicalKey::Code(KeyCode::Space),
|
||||||
state: ElementState::Released,
|
state: ElementState::Released,
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
@@ -42,9 +44,11 @@ fn main() {
|
|||||||
println!("Resizable: {resizable}");
|
println!("Resizable: {resizable}");
|
||||||
window.set_resizable(resizable);
|
window.set_resizable(resizable);
|
||||||
}
|
}
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
},
|
}
|
||||||
_ => (),
|
|
||||||
};
|
};
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
115
examples/startup_notification.rs
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
//! Demonstrates the use of startup notifications on Linux.
|
||||||
|
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
#[path = "./util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
mod example {
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
|
use winit::event::{ElementState, Event, KeyEvent, WindowEvent};
|
||||||
|
use winit::event_loop::EventLoop;
|
||||||
|
use winit::platform::startup_notify::{
|
||||||
|
EventLoopExtStartupNotify, WindowBuilderExtStartupNotify, WindowExtStartupNotify,
|
||||||
|
};
|
||||||
|
use winit::window::{Window, WindowId};
|
||||||
|
|
||||||
|
pub(super) fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
// Create the event loop and get the activation token.
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
let mut current_token = match event_loop.read_token_from_env() {
|
||||||
|
Some(token) => Some(token),
|
||||||
|
None => {
|
||||||
|
println!("No startup notification token found in environment.");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut windows: HashMap<WindowId, Rc<Window>> = HashMap::new();
|
||||||
|
let mut counter = 0;
|
||||||
|
let mut create_first_window = false;
|
||||||
|
|
||||||
|
event_loop.run(move |event, elwt| {
|
||||||
|
match event {
|
||||||
|
Event::Resumed => create_first_window = true,
|
||||||
|
|
||||||
|
Event::WindowEvent { window_id, event } => match event {
|
||||||
|
WindowEvent::KeyboardInput {
|
||||||
|
event:
|
||||||
|
KeyEvent {
|
||||||
|
logical_key,
|
||||||
|
state: ElementState::Pressed,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
if logical_key == "n" {
|
||||||
|
if let Some(window) = windows.get(&window_id) {
|
||||||
|
// Request a new activation token on this window.
|
||||||
|
// Once we get it we will use it to create a window.
|
||||||
|
window
|
||||||
|
.request_activation_token()
|
||||||
|
.expect("Failed to request activation token.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
// Remove the window from the map.
|
||||||
|
windows.remove(&window_id);
|
||||||
|
if windows.is_empty() {
|
||||||
|
elwt.exit();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
WindowEvent::ActivationTokenDone { token, .. } => {
|
||||||
|
current_token = Some(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
if let Some(window) = windows.get(&window_id) {
|
||||||
|
super::fill::fill_window(window);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_ => {}
|
||||||
|
},
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
|
||||||
|
// See if we've passed the deadline.
|
||||||
|
if current_token.is_some() || create_first_window {
|
||||||
|
// Create the initial window.
|
||||||
|
let window = {
|
||||||
|
let mut builder = Window::builder().with_title(format!("Window {}", counter));
|
||||||
|
|
||||||
|
if let Some(token) = current_token.take() {
|
||||||
|
println!("Creating a window with token {token:?}");
|
||||||
|
builder = builder.with_activation_token(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
Rc::new(builder.build(elwt).unwrap())
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add the window to the map.
|
||||||
|
windows.insert(window.id(), window.clone());
|
||||||
|
|
||||||
|
counter += 1;
|
||||||
|
create_first_window = false;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
example::main()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(any(x11_platform, wayland_platform)))]
|
||||||
|
fn main() {
|
||||||
|
println!("This example is only supported on X11 and Wayland platforms.");
|
||||||
|
}
|
||||||
@@ -2,16 +2,20 @@
|
|||||||
|
|
||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent},
|
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||||
event_loop::{ControlFlow, EventLoop},
|
event_loop::EventLoop,
|
||||||
window::{Theme, WindowBuilder},
|
keyboard::Key,
|
||||||
|
window::{Theme, Window},
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
SimpleLogger::new().init().unwrap();
|
mod fill;
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
.with_title("A fantastic window!")
|
.with_title("A fantastic window!")
|
||||||
.with_theme(Some(Theme::Dark))
|
.with_theme(Some(Theme::Dark))
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
@@ -23,49 +27,42 @@ fn main() {
|
|||||||
println!(" (L) Light theme");
|
println!(" (L) Light theme");
|
||||||
println!(" (D) Dark theme");
|
println!(" (D) Dark theme");
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
*control_flow = ControlFlow::Wait;
|
if let Event::WindowEvent { window_id, event } = event {
|
||||||
|
match event {
|
||||||
match event {
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
Event::WindowEvent {
|
WindowEvent::ThemeChanged(theme) if window_id == window.id() => {
|
||||||
event: WindowEvent::CloseRequested,
|
println!("Theme is changed: {theme:?}")
|
||||||
..
|
|
||||||
} => *control_flow = ControlFlow::Exit,
|
|
||||||
Event::WindowEvent {
|
|
||||||
event: WindowEvent::ThemeChanged(theme),
|
|
||||||
window_id,
|
|
||||||
..
|
|
||||||
} if window_id == window.id() => {
|
|
||||||
println!("Theme is changed: {theme:?}")
|
|
||||||
}
|
|
||||||
Event::WindowEvent {
|
|
||||||
event:
|
|
||||||
WindowEvent::KeyboardInput {
|
|
||||||
input:
|
|
||||||
KeyboardInput {
|
|
||||||
virtual_keycode: Some(key),
|
|
||||||
state: ElementState::Pressed,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
} => match key {
|
|
||||||
VirtualKeyCode::A => {
|
|
||||||
println!("Theme was: {:?}", window.theme());
|
|
||||||
window.set_theme(None);
|
|
||||||
}
|
}
|
||||||
VirtualKeyCode::L => {
|
WindowEvent::KeyboardInput {
|
||||||
println!("Theme was: {:?}", window.theme());
|
event:
|
||||||
window.set_theme(Some(Theme::Light));
|
KeyEvent {
|
||||||
}
|
logical_key: key,
|
||||||
VirtualKeyCode::D => {
|
state: ElementState::Pressed,
|
||||||
println!("Theme was: {:?}", window.theme());
|
..
|
||||||
window.set_theme(Some(Theme::Dark));
|
},
|
||||||
|
..
|
||||||
|
} => match key.as_ref() {
|
||||||
|
Key::Character("A" | "a") => {
|
||||||
|
println!("Theme was: {:?}", window.theme());
|
||||||
|
window.set_theme(None);
|
||||||
|
}
|
||||||
|
Key::Character("L" | "l") => {
|
||||||
|
println!("Theme was: {:?}", window.theme());
|
||||||
|
window.set_theme(Some(Theme::Light));
|
||||||
|
}
|
||||||
|
Key::Character("D" | "d") => {
|
||||||
|
println!("Theme was: {:?}", window.theme());
|
||||||
|
window.set_theme(Some(Theme::Dark));
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
println!("\nredrawing!\n");
|
||||||
|
fill::fill_window(&window);
|
||||||
}
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
},
|
}
|
||||||
_ => (),
|
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,42 +1,54 @@
|
|||||||
#![allow(clippy::single_match)]
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
use instant::Instant;
|
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
use std::time::Instant;
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
use web_time::Instant;
|
||||||
|
|
||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
event::{Event, StartCause, WindowEvent},
|
event::{Event, StartCause, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::{ControlFlow, EventLoop},
|
||||||
window::WindowBuilder,
|
window::Window,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
SimpleLogger::new().init().unwrap();
|
mod fill;
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
let _window = WindowBuilder::new()
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
.with_title("A fantastic window!")
|
.with_title("A fantastic window!")
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let timer_length = Duration::new(1, 0);
|
let timer_length = Duration::new(1, 0);
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
println!("{event:?}");
|
println!("{event:?}");
|
||||||
|
|
||||||
match event {
|
match event {
|
||||||
Event::NewEvents(StartCause::Init) => {
|
Event::NewEvents(StartCause::Init) => {
|
||||||
control_flow.set_wait_until(Instant::now() + timer_length);
|
elwt.set_control_flow(ControlFlow::WaitUntil(Instant::now() + timer_length));
|
||||||
}
|
}
|
||||||
Event::NewEvents(StartCause::ResumeTimeReached { .. }) => {
|
Event::NewEvents(StartCause::ResumeTimeReached { .. }) => {
|
||||||
control_flow.set_wait_until(Instant::now() + timer_length);
|
elwt.set_control_flow(ControlFlow::WaitUntil(Instant::now() + timer_length));
|
||||||
println!("\nTimer\n");
|
println!("\nTimer\n");
|
||||||
}
|
}
|
||||||
Event::WindowEvent {
|
Event::WindowEvent {
|
||||||
event: WindowEvent::CloseRequested,
|
event: WindowEvent::CloseRequested,
|
||||||
..
|
..
|
||||||
} => control_flow.set_exit(),
|
} => elwt.exit(),
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::RedrawRequested,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
62
examples/touch_gestures.rs
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
use simple_logger::SimpleLogger;
|
||||||
|
use winit::{
|
||||||
|
event::{Event, WindowEvent},
|
||||||
|
event_loop::EventLoop,
|
||||||
|
window::Window,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
|
.with_title("Touchpad gestures")
|
||||||
|
.build(&event_loop)
|
||||||
|
.unwrap();
|
||||||
|
#[cfg(target_os = "ios")]
|
||||||
|
{
|
||||||
|
use winit::platform::ios::WindowExtIOS;
|
||||||
|
window.recognize_doubletap_gesture(true);
|
||||||
|
window.recognize_pinch_gesture(true);
|
||||||
|
window.recognize_rotation_gesture(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("Only supported on macOS/iOS at the moment.");
|
||||||
|
|
||||||
|
let mut zoom = 0.0;
|
||||||
|
let mut rotated = 0.0;
|
||||||
|
|
||||||
|
event_loop.run(move |event, elwt| {
|
||||||
|
if let Event::WindowEvent { event, .. } = event {
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
|
WindowEvent::PinchGesture { delta, .. } => {
|
||||||
|
zoom += delta;
|
||||||
|
if delta > 0.0 {
|
||||||
|
println!("Zoomed in {delta:.5} (now: {zoom:.5})");
|
||||||
|
} else {
|
||||||
|
println!("Zoomed out {delta:.5} (now: {zoom:.5})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::DoubleTapGesture { .. } => {
|
||||||
|
println!("Smart zoom");
|
||||||
|
}
|
||||||
|
WindowEvent::RotationGesture { delta, .. } => {
|
||||||
|
rotated += delta;
|
||||||
|
if delta > 0.0 {
|
||||||
|
println!("Rotated counterclockwise {delta:.5} (now: {rotated:.5})");
|
||||||
|
} else {
|
||||||
|
println!("Rotated clockwise {delta:.5} (now: {rotated:.5})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
use simple_logger::SimpleLogger;
|
|
||||||
use winit::{
|
|
||||||
event::{Event, WindowEvent},
|
|
||||||
event_loop::{ControlFlow, EventLoop},
|
|
||||||
window::WindowBuilder,
|
|
||||||
};
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
SimpleLogger::new().init().unwrap();
|
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
let _window = WindowBuilder::new()
|
|
||||||
.with_title("Touchpad gestures")
|
|
||||||
.build(&event_loop)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
println!("Only supported on macOS at the moment.");
|
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
|
||||||
*control_flow = ControlFlow::Wait;
|
|
||||||
|
|
||||||
if let Event::WindowEvent { event, .. } = event {
|
|
||||||
match event {
|
|
||||||
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
|
|
||||||
WindowEvent::TouchpadMagnify { delta, .. } => {
|
|
||||||
if delta > 0.0 {
|
|
||||||
println!("Zoomed in {delta}");
|
|
||||||
} else {
|
|
||||||
println!("Zoomed out {delta}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
WindowEvent::SmartMagnify { .. } => {
|
|
||||||
println!("Smart zoom");
|
|
||||||
}
|
|
||||||
WindowEvent::TouchpadRotate { delta, .. } => {
|
|
||||||
if delta > 0.0 {
|
|
||||||
println!("Rotated counterclockwise {delta}");
|
|
||||||
} else {
|
|
||||||
println!("Rotated clockwise {delta}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -4,14 +4,17 @@ use simple_logger::SimpleLogger;
|
|||||||
use winit::{
|
use winit::{
|
||||||
event::{Event, WindowEvent},
|
event::{Event, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
window::WindowBuilder,
|
window::Window,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
SimpleLogger::new().init().unwrap();
|
mod fill;
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
.with_decorations(false)
|
.with_decorations(false)
|
||||||
.with_transparent(true)
|
.with_transparent(true)
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
@@ -19,16 +22,17 @@ fn main() {
|
|||||||
|
|
||||||
window.set_title("A fantastic window!");
|
window.set_title("A fantastic window!");
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
control_flow.set_wait();
|
|
||||||
println!("{event:?}");
|
println!("{event:?}");
|
||||||
|
|
||||||
match event {
|
if let Event::WindowEvent { event, .. } = event {
|
||||||
Event::WindowEvent {
|
match event {
|
||||||
event: WindowEvent::CloseRequested,
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
..
|
WindowEvent::RedrawRequested => {
|
||||||
} => control_flow.set_exit(),
|
fill::fill_window(&window);
|
||||||
_ => (),
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
116
examples/util/fill.rs
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
//! Fill the window buffer with a solid color.
|
||||||
|
//!
|
||||||
|
//! Launching a window without drawing to it has unpredictable results varying from platform to
|
||||||
|
//! platform. In order to have well-defined examples, this module provides an easy way to
|
||||||
|
//! fill the window buffer with a solid color.
|
||||||
|
//!
|
||||||
|
//! The `softbuffer` crate is used, largely because of its ease of use. `glutin` or `wgpu` could
|
||||||
|
//! also be used to fill the window buffer, but they are more complicated to use.
|
||||||
|
|
||||||
|
#[allow(unused_imports)]
|
||||||
|
pub use platform::cleanup_window;
|
||||||
|
pub use platform::fill_window;
|
||||||
|
|
||||||
|
#[cfg(all(feature = "rwh_05", not(any(target_os = "android", target_os = "ios"))))]
|
||||||
|
mod platform {
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::mem::ManuallyDrop;
|
||||||
|
use std::num::NonZeroU32;
|
||||||
|
|
||||||
|
use softbuffer::{Context, Surface};
|
||||||
|
use winit::window::Window;
|
||||||
|
use winit::window::WindowId;
|
||||||
|
|
||||||
|
thread_local! {
|
||||||
|
// NOTE: You should never do things like that, create context and drop it before
|
||||||
|
// you drop the event loop. We do this for brevity to not blow up examples. We use
|
||||||
|
// ManuallyDrop to prevent destructors from running.
|
||||||
|
//
|
||||||
|
// A static, thread-local map of graphics contexts to open windows.
|
||||||
|
static GC: ManuallyDrop<RefCell<Option<GraphicsContext>>> = ManuallyDrop::new(RefCell::new(None));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The graphics context used to draw to a window.
|
||||||
|
struct GraphicsContext {
|
||||||
|
/// The global softbuffer context.
|
||||||
|
context: Context,
|
||||||
|
|
||||||
|
/// The hash map of window IDs to surfaces.
|
||||||
|
surfaces: HashMap<WindowId, Surface>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GraphicsContext {
|
||||||
|
fn new(w: &Window) -> Self {
|
||||||
|
Self {
|
||||||
|
context: unsafe { Context::new(w) }.expect("Failed to create a softbuffer context"),
|
||||||
|
surfaces: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_surface(&mut self, window: &Window) -> &mut Surface {
|
||||||
|
self.surfaces.entry(window.id()).or_insert_with(|| {
|
||||||
|
unsafe { Surface::new(&self.context, window) }
|
||||||
|
.expect("Failed to create a softbuffer surface")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn destroy_surface(&mut self, window: &Window) {
|
||||||
|
self.surfaces.remove(&window.id());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fill_window(window: &Window) {
|
||||||
|
GC.with(|gc| {
|
||||||
|
let size = window.inner_size();
|
||||||
|
let (Some(width), Some(height)) =
|
||||||
|
(NonZeroU32::new(size.width), NonZeroU32::new(size.height))
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Either get the last context used or create a new one.
|
||||||
|
let mut gc = gc.borrow_mut();
|
||||||
|
let surface = gc
|
||||||
|
.get_or_insert_with(|| GraphicsContext::new(window))
|
||||||
|
.create_surface(window);
|
||||||
|
|
||||||
|
// Fill a buffer with a solid color.
|
||||||
|
const DARK_GRAY: u32 = 0xFF181818;
|
||||||
|
|
||||||
|
surface
|
||||||
|
.resize(width, height)
|
||||||
|
.expect("Failed to resize the softbuffer surface");
|
||||||
|
|
||||||
|
let mut buffer = surface
|
||||||
|
.buffer_mut()
|
||||||
|
.expect("Failed to get the softbuffer buffer");
|
||||||
|
buffer.fill(DARK_GRAY);
|
||||||
|
buffer
|
||||||
|
.present()
|
||||||
|
.expect("Failed to present the softbuffer buffer");
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn cleanup_window(window: &Window) {
|
||||||
|
GC.with(|gc| {
|
||||||
|
let mut gc = gc.borrow_mut();
|
||||||
|
if let Some(context) = gc.as_mut() {
|
||||||
|
context.destroy_surface(window);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(all(feature = "rwh_05", not(any(target_os = "android", target_os = "ios")))))]
|
||||||
|
mod platform {
|
||||||
|
pub fn fill_window(_window: &winit::window::Window) {
|
||||||
|
// No-op on mobile platforms.
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn cleanup_window(_window: &winit::window::Window) {
|
||||||
|
// No-op on mobile platforms.
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@ use winit::event_loop::EventLoop;
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
SimpleLogger::new().init().unwrap();
|
SimpleLogger::new().init().unwrap();
|
||||||
let event_loop = EventLoop::new();
|
let event_loop = EventLoop::new().unwrap();
|
||||||
let monitor = match event_loop.primary_monitor() {
|
let monitor = match event_loop.primary_monitor() {
|
||||||
Some(monitor) => monitor,
|
Some(monitor) => monitor,
|
||||||
None => {
|
None => {
|
||||||
|
|||||||
109
examples/web.rs
@@ -1,66 +1,105 @@
|
|||||||
#![allow(clippy::single_match)]
|
#![allow(clippy::disallowed_methods, clippy::single_match)]
|
||||||
|
|
||||||
use winit::{
|
use winit::{
|
||||||
event::{Event, WindowEvent},
|
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
window::WindowBuilder,
|
keyboard::Key,
|
||||||
|
window::{Fullscreen, Window},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn main() {
|
pub fn main() -> Result<(), impl std::error::Error> {
|
||||||
let event_loop = EventLoop::new();
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
|
||||||
.with_title("A fantastic window!")
|
|
||||||
.build(&event_loop)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
|
let builder = Window::builder().with_title("A fantastic window!");
|
||||||
#[cfg(wasm_platform)]
|
#[cfg(wasm_platform)]
|
||||||
|
let builder = {
|
||||||
|
use winit::platform::web::WindowBuilderExtWebSys;
|
||||||
|
builder.with_append(true)
|
||||||
|
};
|
||||||
|
let window = builder.build(&event_loop).unwrap();
|
||||||
|
|
||||||
|
#[cfg(web_platform)]
|
||||||
let log_list = wasm::insert_canvas_and_create_log_list(&window);
|
let log_list = wasm::insert_canvas_and_create_log_list(&window);
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
control_flow.set_wait();
|
#[cfg(web_platform)]
|
||||||
|
|
||||||
#[cfg(wasm_platform)]
|
|
||||||
wasm::log_event(&log_list, &event);
|
wasm::log_event(&log_list, &event);
|
||||||
|
|
||||||
match event {
|
match event {
|
||||||
Event::WindowEvent {
|
Event::WindowEvent {
|
||||||
event: WindowEvent::CloseRequested,
|
event: WindowEvent::CloseRequested,
|
||||||
window_id,
|
window_id,
|
||||||
} if window_id == window.id() => control_flow.set_exit(),
|
} if window_id == window.id() => elwt.exit(),
|
||||||
Event::MainEventsCleared => {
|
Event::AboutToWait => {
|
||||||
window.request_redraw();
|
window.request_redraw();
|
||||||
}
|
}
|
||||||
|
Event::WindowEvent {
|
||||||
|
window_id,
|
||||||
|
event:
|
||||||
|
WindowEvent::KeyboardInput {
|
||||||
|
event:
|
||||||
|
KeyEvent {
|
||||||
|
logical_key: Key::Character(c),
|
||||||
|
state: ElementState::Released,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
..
|
||||||
|
},
|
||||||
|
} if window_id == window.id() && c == "f" => {
|
||||||
|
if window.fullscreen().is_some() {
|
||||||
|
window.set_fullscreen(None);
|
||||||
|
} else {
|
||||||
|
window.set_fullscreen(Some(Fullscreen::Borderless(None)));
|
||||||
|
}
|
||||||
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(wasm_platform)]
|
#[cfg(web_platform)]
|
||||||
mod wasm {
|
mod wasm {
|
||||||
|
use std::num::NonZeroU32;
|
||||||
|
|
||||||
|
use softbuffer::{Surface, SurfaceExtWeb};
|
||||||
use wasm_bindgen::prelude::*;
|
use wasm_bindgen::prelude::*;
|
||||||
use winit::{event::Event, window::Window};
|
use winit::{
|
||||||
|
event::{Event, WindowEvent},
|
||||||
|
window::Window,
|
||||||
|
};
|
||||||
|
|
||||||
#[wasm_bindgen(start)]
|
#[wasm_bindgen(start)]
|
||||||
pub fn run() {
|
pub fn run() {
|
||||||
console_log::init_with_level(log::Level::Debug).expect("error initializing logger");
|
console_log::init_with_level(log::Level::Debug).expect("error initializing logger");
|
||||||
|
|
||||||
#[allow(clippy::main_recursion)]
|
#[allow(clippy::main_recursion)]
|
||||||
super::main();
|
let _ = super::main();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn insert_canvas_and_create_log_list(window: &Window) -> web_sys::Element {
|
pub fn insert_canvas_and_create_log_list(window: &Window) -> web_sys::Element {
|
||||||
use winit::platform::web::WindowExtWebSys;
|
use winit::platform::web::WindowExtWebSys;
|
||||||
|
|
||||||
let canvas = window.canvas();
|
let canvas = window.canvas().unwrap();
|
||||||
|
let mut surface = Surface::from_canvas(canvas.clone()).unwrap();
|
||||||
|
surface
|
||||||
|
.resize(
|
||||||
|
NonZeroU32::new(canvas.width()).unwrap(),
|
||||||
|
NonZeroU32::new(canvas.height()).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let mut buffer = surface.buffer_mut().unwrap();
|
||||||
|
buffer.fill(0xFFF0000);
|
||||||
|
buffer.present().unwrap();
|
||||||
|
|
||||||
let window = web_sys::window().unwrap();
|
let window = web_sys::window().unwrap();
|
||||||
let document = window.document().unwrap();
|
let document = window.document().unwrap();
|
||||||
let body = document.body().unwrap();
|
let body = document.body().unwrap();
|
||||||
|
|
||||||
// Set a background color for the canvas to make it easier to tell where the canvas is for debugging purposes.
|
let style = &canvas.style();
|
||||||
canvas.style().set_css_text("background-color: crimson;");
|
style.set_property("margin", "50px").unwrap();
|
||||||
body.append_child(&canvas).unwrap();
|
// Use to test interactions with border and padding.
|
||||||
|
//style.set_property("border", "50px solid black").unwrap();
|
||||||
|
//style.set_property("padding", "50px").unwrap();
|
||||||
|
|
||||||
let log_header = document.create_element("h2").unwrap();
|
let log_header = document.create_element("h2").unwrap();
|
||||||
log_header.set_text_content(Some("Event Log"));
|
log_header.set_text_content(Some("Event Log"));
|
||||||
@@ -77,11 +116,29 @@ mod wasm {
|
|||||||
// Getting access to browser logs requires a lot of setup on mobile devices.
|
// Getting access to browser logs requires a lot of setup on mobile devices.
|
||||||
// So we implement this basic logging system into the page to give developers an easy alternative.
|
// So we implement this basic logging system into the page to give developers an easy alternative.
|
||||||
// As a bonus its also kind of handy on desktop.
|
// As a bonus its also kind of handy on desktop.
|
||||||
if let Event::WindowEvent { event, .. } = &event {
|
let event = match event {
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::RedrawRequested,
|
||||||
|
..
|
||||||
|
} => None,
|
||||||
|
Event::WindowEvent { event, .. } => Some(format!("{event:?}")),
|
||||||
|
Event::Resumed | Event::Suspended => Some(format!("{event:?}")),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
if let Some(event) = event {
|
||||||
let window = web_sys::window().unwrap();
|
let window = web_sys::window().unwrap();
|
||||||
let document = window.document().unwrap();
|
let document = window.document().unwrap();
|
||||||
let log = document.create_element("li").unwrap();
|
let log = document.create_element("li").unwrap();
|
||||||
log.set_text_content(Some(&format!("{event:?}")));
|
|
||||||
|
let date = js_sys::Date::new_0();
|
||||||
|
log.set_text_content(Some(&format!(
|
||||||
|
"{:02}:{:02}:{:02}.{:03}: {event}",
|
||||||
|
date.get_hours(),
|
||||||
|
date.get_minutes(),
|
||||||
|
date.get_seconds(),
|
||||||
|
date.get_milliseconds(),
|
||||||
|
)));
|
||||||
|
|
||||||
log_list
|
log_list
|
||||||
.insert_before(&log, log_list.first_child().as_ref())
|
.insert_before(&log, log_list.first_child().as_ref())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
|
#![allow(clippy::disallowed_methods)]
|
||||||
|
|
||||||
pub fn main() {
|
pub fn main() {
|
||||||
println!("This example must be run with cargo run-wasm --example web_aspect_ratio")
|
println!("This example must be run with cargo run-wasm --example web_aspect_ratio")
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(wasm_platform)]
|
#[cfg(web_platform)]
|
||||||
mod wasm {
|
mod wasm {
|
||||||
use wasm_bindgen::prelude::*;
|
use wasm_bindgen::prelude::*;
|
||||||
use wasm_bindgen::JsCast;
|
use wasm_bindgen::JsCast;
|
||||||
@@ -10,8 +12,9 @@ mod wasm {
|
|||||||
use winit::{
|
use winit::{
|
||||||
dpi::PhysicalSize,
|
dpi::PhysicalSize,
|
||||||
event::{Event, WindowEvent},
|
event::{Event, WindowEvent},
|
||||||
event_loop::{ControlFlow, EventLoop},
|
event_loop::EventLoop,
|
||||||
window::{Window, WindowBuilder},
|
platform::web::WindowBuilderExtWebSys,
|
||||||
|
window::Window,
|
||||||
};
|
};
|
||||||
|
|
||||||
const EXPLANATION: &str = "
|
const EXPLANATION: &str = "
|
||||||
@@ -28,13 +31,14 @@ This example demonstrates the desired future functionality which will possibly b
|
|||||||
#[wasm_bindgen(start)]
|
#[wasm_bindgen(start)]
|
||||||
pub fn run() {
|
pub fn run() {
|
||||||
console_log::init_with_level(log::Level::Debug).expect("error initializing logger");
|
console_log::init_with_level(log::Level::Debug).expect("error initializing logger");
|
||||||
let event_loop = EventLoop::new();
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
let window = Window::builder()
|
||||||
.with_title("A fantastic window!")
|
.with_title("A fantastic window!")
|
||||||
// When running in a non-wasm environment this would set the window size to 100x100.
|
// When running in a non-wasm environment this would set the window size to 100x100.
|
||||||
// However in this example it just sets a default initial size of 100x100 that is immediately overwritten due to the layout + styling of the page.
|
// However in this example it just sets a default initial size of 100x100 that is immediately overwritten due to the layout + styling of the page.
|
||||||
.with_inner_size(PhysicalSize::new(100, 100))
|
.with_inner_size(PhysicalSize::new(100, 100))
|
||||||
|
.with_append(true)
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
@@ -43,18 +47,14 @@ This example demonstrates the desired future functionality which will possibly b
|
|||||||
// Render once with the size info we currently have
|
// Render once with the size info we currently have
|
||||||
render_circle(&canvas, window.inner_size());
|
render_circle(&canvas, window.inner_size());
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
let _ = event_loop.run(move |event, _| match event {
|
||||||
*control_flow = ControlFlow::Wait;
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::Resized(resize),
|
||||||
match event {
|
window_id,
|
||||||
Event::WindowEvent {
|
} if window_id == window.id() => {
|
||||||
event: WindowEvent::Resized(resize),
|
render_circle(&canvas, resize);
|
||||||
window_id,
|
|
||||||
} if window_id == window.id() => {
|
|
||||||
render_circle(&canvas, resize);
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
}
|
}
|
||||||
|
_ => (),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,11 +66,10 @@ This example demonstrates the desired future functionality which will possibly b
|
|||||||
let body = document.body().unwrap();
|
let body = document.body().unwrap();
|
||||||
|
|
||||||
// Set a background color for the canvas to make it easier to tell the where the canvas is for debugging purposes.
|
// Set a background color for the canvas to make it easier to tell the where the canvas is for debugging purposes.
|
||||||
let canvas = window.canvas();
|
let canvas = window.canvas().unwrap();
|
||||||
canvas
|
canvas
|
||||||
.style()
|
.style()
|
||||||
.set_css_text("display: block; background-color: crimson; margin: auto; width: 50%; aspect-ratio: 4 / 1;");
|
.set_css_text("display: block; background-color: crimson; margin: auto; width: 50%; aspect-ratio: 4 / 1;");
|
||||||
body.append_child(&canvas).unwrap();
|
|
||||||
|
|
||||||
let explanation = document.create_element("pre").unwrap();
|
let explanation = document.create_element("pre").unwrap();
|
||||||
explanation.set_text_content(Some(EXPLANATION));
|
explanation.set_text_content(Some(EXPLANATION));
|
||||||
|
|||||||
@@ -4,32 +4,40 @@ use simple_logger::SimpleLogger;
|
|||||||
use winit::{
|
use winit::{
|
||||||
event::{Event, WindowEvent},
|
event::{Event, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
window::WindowBuilder,
|
window::Window,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
SimpleLogger::new().init().unwrap();
|
mod fill;
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
.with_title("A fantastic window!")
|
.with_title("A fantastic window!")
|
||||||
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
control_flow.set_wait();
|
|
||||||
println!("{event:?}");
|
println!("{event:?}");
|
||||||
|
|
||||||
match event {
|
match event {
|
||||||
Event::WindowEvent {
|
Event::WindowEvent { event, window_id } if window_id == window.id() => match event {
|
||||||
event: WindowEvent::CloseRequested,
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
window_id,
|
WindowEvent::RedrawRequested => {
|
||||||
} if window_id == window.id() => control_flow.set_exit(),
|
// Notify the windowing system that we'll be presenting to the window.
|
||||||
Event::MainEventsCleared => {
|
window.pre_present_notify();
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
},
|
||||||
|
Event::AboutToWait => {
|
||||||
window.request_redraw();
|
window.request_redraw();
|
||||||
}
|
}
|
||||||
|
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,16 +5,20 @@
|
|||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
dpi::LogicalSize,
|
dpi::LogicalSize,
|
||||||
event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent},
|
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||||
event_loop::{DeviceEventFilter, EventLoop},
|
event_loop::{DeviceEvents, EventLoop},
|
||||||
window::{WindowBuilder, WindowButtons},
|
keyboard::Key,
|
||||||
|
window::{Window, WindowButtons},
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
SimpleLogger::new().init().unwrap();
|
mod fill;
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
.with_title("A fantastic window!")
|
.with_title("A fantastic window!")
|
||||||
.with_inner_size(LogicalSize::new(300.0, 300.0))
|
.with_inner_size(LogicalSize::new(300.0, 300.0))
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
@@ -25,44 +29,40 @@ fn main() {
|
|||||||
eprintln!(" (G) Toggle maximize button");
|
eprintln!(" (G) Toggle maximize button");
|
||||||
eprintln!(" (H) Toggle minimize button");
|
eprintln!(" (H) Toggle minimize button");
|
||||||
|
|
||||||
event_loop.set_device_event_filter(DeviceEventFilter::Never);
|
event_loop.listen_device_events(DeviceEvents::Always);
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
control_flow.set_wait();
|
if let Event::WindowEvent { window_id, event } = event {
|
||||||
|
match event {
|
||||||
match event {
|
WindowEvent::KeyboardInput {
|
||||||
Event::WindowEvent {
|
event:
|
||||||
event:
|
KeyEvent {
|
||||||
WindowEvent::KeyboardInput {
|
logical_key: key,
|
||||||
input:
|
state: ElementState::Pressed,
|
||||||
KeyboardInput {
|
..
|
||||||
virtual_keycode: Some(key),
|
},
|
||||||
state: ElementState::Pressed,
|
..
|
||||||
..
|
} => match key.as_ref() {
|
||||||
},
|
Key::Character("F" | "f") => {
|
||||||
..
|
let buttons = window.enabled_buttons();
|
||||||
},
|
window.set_enabled_buttons(buttons ^ WindowButtons::CLOSE);
|
||||||
..
|
}
|
||||||
} => match key {
|
Key::Character("G" | "g") => {
|
||||||
VirtualKeyCode::F => {
|
let buttons = window.enabled_buttons();
|
||||||
let buttons = window.enabled_buttons();
|
window.set_enabled_buttons(buttons ^ WindowButtons::MAXIMIZE);
|
||||||
window.set_enabled_buttons(buttons ^ WindowButtons::CLOSE);
|
}
|
||||||
}
|
Key::Character("H" | "h") => {
|
||||||
VirtualKeyCode::G => {
|
let buttons = window.enabled_buttons();
|
||||||
let buttons = window.enabled_buttons();
|
window.set_enabled_buttons(buttons ^ WindowButtons::MINIMIZE);
|
||||||
window.set_enabled_buttons(buttons ^ WindowButtons::MAXIMIZE);
|
}
|
||||||
}
|
_ => (),
|
||||||
VirtualKeyCode::H => {
|
},
|
||||||
let buttons = window.enabled_buttons();
|
WindowEvent::CloseRequested if window_id == window.id() => elwt.exit(),
|
||||||
window.set_enabled_buttons(buttons ^ WindowButtons::MINIMIZE);
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(&window);
|
||||||
}
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
},
|
}
|
||||||
Event::WindowEvent {
|
|
||||||
event: WindowEvent::CloseRequested,
|
|
||||||
window_id,
|
|
||||||
} if window_id == window.id() => control_flow.set_exit(),
|
|
||||||
_ => (),
|
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,16 +5,20 @@
|
|||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
dpi::{LogicalSize, PhysicalSize},
|
dpi::{LogicalSize, PhysicalSize},
|
||||||
event::{DeviceEvent, ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent},
|
event::{DeviceEvent, ElementState, Event, KeyEvent, RawKeyEvent, WindowEvent},
|
||||||
event_loop::{DeviceEventFilter, EventLoop},
|
event_loop::{DeviceEvents, EventLoop},
|
||||||
window::{Fullscreen, WindowBuilder},
|
keyboard::{Key, KeyCode, PhysicalKey},
|
||||||
|
window::{Fullscreen, Window},
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
SimpleLogger::new().init().unwrap();
|
mod fill;
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
.with_title("A fantastic window!")
|
.with_title("A fantastic window!")
|
||||||
.with_inner_size(LogicalSize::new(100.0, 100.0))
|
.with_inner_size(LogicalSize::new(100.0, 100.0))
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
@@ -32,29 +36,29 @@ fn main() {
|
|||||||
let mut minimized = false;
|
let mut minimized = false;
|
||||||
let mut visible = true;
|
let mut visible = true;
|
||||||
|
|
||||||
event_loop.set_device_event_filter(DeviceEventFilter::Never);
|
event_loop.listen_device_events(DeviceEvents::Always);
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
|
||||||
control_flow.set_wait();
|
|
||||||
|
|
||||||
|
event_loop.run(move |event, elwt| {
|
||||||
match event {
|
match event {
|
||||||
|
// This used to use the virtual key, but the new API
|
||||||
|
// only provides the `physical_key` (`Code`).
|
||||||
Event::DeviceEvent {
|
Event::DeviceEvent {
|
||||||
event:
|
event:
|
||||||
DeviceEvent::Key(KeyboardInput {
|
DeviceEvent::Key(RawKeyEvent {
|
||||||
virtual_keycode: Some(key),
|
physical_key,
|
||||||
state: ElementState::Pressed,
|
state: ElementState::Released,
|
||||||
..
|
..
|
||||||
}),
|
}),
|
||||||
..
|
..
|
||||||
} => match key {
|
} => match physical_key {
|
||||||
VirtualKeyCode::M => {
|
PhysicalKey::Code(KeyCode::KeyM) => {
|
||||||
if minimized {
|
if minimized {
|
||||||
minimized = !minimized;
|
minimized = !minimized;
|
||||||
window.set_minimized(minimized);
|
window.set_minimized(minimized);
|
||||||
window.focus_window();
|
window.focus_window();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
VirtualKeyCode::V => {
|
PhysicalKey::Code(KeyCode::KeyV) => {
|
||||||
if !visible {
|
if !visible {
|
||||||
visible = !visible;
|
visible = !visible;
|
||||||
window.set_visible(visible);
|
window.set_visible(visible);
|
||||||
@@ -62,71 +66,72 @@ fn main() {
|
|||||||
}
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
},
|
},
|
||||||
Event::WindowEvent {
|
Event::WindowEvent { window_id, event } => match event {
|
||||||
event:
|
WindowEvent::KeyboardInput {
|
||||||
WindowEvent::KeyboardInput {
|
event:
|
||||||
input:
|
KeyEvent {
|
||||||
KeyboardInput {
|
logical_key: Key::Character(key_str),
|
||||||
virtual_keycode: Some(key),
|
state: ElementState::Pressed,
|
||||||
state: ElementState::Pressed,
|
..
|
||||||
..
|
},
|
||||||
},
|
..
|
||||||
..
|
} => match key_str.as_ref() {
|
||||||
},
|
// WARNING: Consider using `key_without_modifers()` if available on your platform.
|
||||||
..
|
// See the `key_binding` example
|
||||||
} => match key {
|
"e" => {
|
||||||
VirtualKeyCode::E => {
|
fn area(size: PhysicalSize<u32>) -> u32 {
|
||||||
fn area(size: PhysicalSize<u32>) -> u32 {
|
size.width * size.height
|
||||||
size.width * size.height
|
}
|
||||||
}
|
|
||||||
|
|
||||||
let monitor = window.current_monitor().unwrap();
|
let monitor = window.current_monitor().unwrap();
|
||||||
if let Some(mode) = monitor
|
if let Some(mode) = monitor
|
||||||
.video_modes()
|
.video_modes()
|
||||||
.max_by(|a, b| area(a.size()).cmp(&area(b.size())))
|
.max_by(|a, b| area(a.size()).cmp(&area(b.size())))
|
||||||
{
|
{
|
||||||
window.set_fullscreen(Some(Fullscreen::Exclusive(mode)));
|
window.set_fullscreen(Some(Fullscreen::Exclusive(mode)));
|
||||||
} else {
|
} else {
|
||||||
eprintln!("no video modes available");
|
eprintln!("no video modes available");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
"f" => {
|
||||||
VirtualKeyCode::F => {
|
if window.fullscreen().is_some() {
|
||||||
if window.fullscreen().is_some() {
|
window.set_fullscreen(None);
|
||||||
window.set_fullscreen(None);
|
} else {
|
||||||
} else {
|
let monitor = window.current_monitor();
|
||||||
let monitor = window.current_monitor();
|
window.set_fullscreen(Some(Fullscreen::Borderless(monitor)));
|
||||||
window.set_fullscreen(Some(Fullscreen::Borderless(monitor)));
|
}
|
||||||
}
|
}
|
||||||
}
|
"p" => {
|
||||||
VirtualKeyCode::P => {
|
if window.fullscreen().is_some() {
|
||||||
if window.fullscreen().is_some() {
|
window.set_fullscreen(None);
|
||||||
window.set_fullscreen(None);
|
} else {
|
||||||
} else {
|
window.set_fullscreen(Some(Fullscreen::Borderless(None)));
|
||||||
window.set_fullscreen(Some(Fullscreen::Borderless(None)));
|
}
|
||||||
}
|
}
|
||||||
}
|
"m" => {
|
||||||
VirtualKeyCode::M => {
|
minimized = !minimized;
|
||||||
minimized = !minimized;
|
window.set_minimized(minimized);
|
||||||
window.set_minimized(minimized);
|
}
|
||||||
}
|
"q" => {
|
||||||
VirtualKeyCode::Q => {
|
elwt.exit();
|
||||||
control_flow.set_exit();
|
}
|
||||||
}
|
"v" => {
|
||||||
VirtualKeyCode::V => {
|
visible = !visible;
|
||||||
visible = !visible;
|
window.set_visible(visible);
|
||||||
window.set_visible(visible);
|
}
|
||||||
}
|
"x" => {
|
||||||
VirtualKeyCode::X => {
|
let is_maximized = window.is_maximized();
|
||||||
let is_maximized = window.is_maximized();
|
window.set_maximized(!is_maximized);
|
||||||
window.set_maximized(!is_maximized);
|
}
|
||||||
|
_ => (),
|
||||||
|
},
|
||||||
|
WindowEvent::CloseRequested if window_id == window.id() => elwt.exit(),
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(&window);
|
||||||
}
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
},
|
},
|
||||||
Event::WindowEvent {
|
|
||||||
event: WindowEvent::CloseRequested,
|
|
||||||
window_id,
|
|
||||||
} if window_id == window.id() => control_flow.set_exit(),
|
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,20 +2,22 @@
|
|||||||
|
|
||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
event::{
|
event::{ElementState, Event, KeyEvent, MouseButton, StartCause, WindowEvent},
|
||||||
ElementState, Event, KeyboardInput, MouseButton, StartCause, VirtualKeyCode, WindowEvent,
|
event_loop::EventLoop,
|
||||||
},
|
keyboard::Key,
|
||||||
event_loop::{ControlFlow, EventLoop},
|
window::{CursorIcon, ResizeDirection, Window},
|
||||||
window::{CursorIcon, ResizeDirection, WindowBuilder},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const BORDER: f64 = 8.0;
|
const BORDER: f64 = 8.0;
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
SimpleLogger::new().init().unwrap();
|
mod fill;
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
.with_inner_size(winit::dpi::LogicalSize::new(600.0, 400.0))
|
.with_inner_size(winit::dpi::LogicalSize::new(600.0, 400.0))
|
||||||
.with_min_inner_size(winit::dpi::LogicalSize::new(400.0, 200.0))
|
.with_min_inner_size(winit::dpi::LogicalSize::new(400.0, 200.0))
|
||||||
.with_decorations(false)
|
.with_decorations(false)
|
||||||
@@ -25,12 +27,12 @@ fn main() {
|
|||||||
let mut border = false;
|
let mut border = false;
|
||||||
let mut cursor_location = None;
|
let mut cursor_location = None;
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| match event {
|
event_loop.run(move |event, elwt| match event {
|
||||||
Event::NewEvents(StartCause::Init) => {
|
Event::NewEvents(StartCause::Init) => {
|
||||||
eprintln!("Press 'B' to toggle borderless")
|
eprintln!("Press 'B' to toggle borderless")
|
||||||
}
|
}
|
||||||
Event::WindowEvent { event, .. } => match event {
|
Event::WindowEvent { event, .. } => match event {
|
||||||
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
WindowEvent::CursorMoved { position, .. } => {
|
WindowEvent::CursorMoved { position, .. } => {
|
||||||
if !window.is_decorated() {
|
if !window.is_decorated() {
|
||||||
let new_location =
|
let new_location =
|
||||||
@@ -38,7 +40,7 @@ fn main() {
|
|||||||
|
|
||||||
if new_location != cursor_location {
|
if new_location != cursor_location {
|
||||||
cursor_location = new_location;
|
cursor_location = new_location;
|
||||||
window.set_cursor_icon(cursor_direction_icon(cursor_location))
|
window.set_cursor(cursor_direction_icon(cursor_location))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -50,24 +52,30 @@ fn main() {
|
|||||||
} => {
|
} => {
|
||||||
if let Some(dir) = cursor_location {
|
if let Some(dir) = cursor_location {
|
||||||
let _res = window.drag_resize_window(dir);
|
let _res = window.drag_resize_window(dir);
|
||||||
|
} else if !window.is_decorated() {
|
||||||
|
let _res = window.drag_window();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
WindowEvent::KeyboardInput {
|
WindowEvent::KeyboardInput {
|
||||||
input:
|
event:
|
||||||
KeyboardInput {
|
KeyEvent {
|
||||||
state: ElementState::Released,
|
state: ElementState::Released,
|
||||||
virtual_keycode: Some(VirtualKeyCode::B),
|
logical_key: Key::Character(c),
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
..
|
..
|
||||||
} => {
|
} if matches!(c.as_ref(), "B" | "b") => {
|
||||||
border = !border;
|
border = !border;
|
||||||
window.set_decorations(border);
|
window.set_decorations(border);
|
||||||
}
|
}
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
},
|
},
|
||||||
|
|
||||||
_ => (),
|
_ => (),
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn cursor_direction_icon(resize_direction: Option<ResizeDirection>) -> CursorIcon {
|
fn cursor_direction_icon(resize_direction: Option<ResizeDirection>) -> CursorIcon {
|
||||||
|
|||||||
@@ -4,12 +4,15 @@ use std::path::Path;
|
|||||||
|
|
||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
event::Event,
|
event::{Event, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
window::{Icon, WindowBuilder},
|
window::{Icon, Window},
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
SimpleLogger::new().init().unwrap();
|
SimpleLogger::new().init().unwrap();
|
||||||
|
|
||||||
// You'll have to choose an icon size at your own discretion. On X11, the desired size varies
|
// You'll have to choose an icon size at your own discretion. On X11, the desired size varies
|
||||||
@@ -20,9 +23,9 @@ fn main() {
|
|||||||
|
|
||||||
let icon = load_icon(Path::new(path));
|
let icon = load_icon(Path::new(path));
|
||||||
|
|
||||||
let event_loop = EventLoop::new();
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
let window = Window::builder()
|
||||||
.with_title("An iconic window!")
|
.with_title("An iconic window!")
|
||||||
// At present, this only does anything on Windows and X11, so if you want to save load
|
// At present, this only does anything on Windows and X11, so if you want to save load
|
||||||
// time, you can put icon loading behind a function that returns `None` on other platforms.
|
// time, you can put icon loading behind a function that returns `None` on other platforms.
|
||||||
@@ -30,20 +33,18 @@ fn main() {
|
|||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| {
|
||||||
control_flow.set_wait();
|
|
||||||
|
|
||||||
if let Event::WindowEvent { event, .. } = event {
|
if let Event::WindowEvent { event, .. } = event {
|
||||||
use winit::event::WindowEvent::*;
|
|
||||||
match event {
|
match event {
|
||||||
CloseRequested => control_flow.set_exit(),
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
DroppedFile(path) => {
|
WindowEvent::DroppedFile(path) => {
|
||||||
window.set_window_icon(Some(load_icon(&path)));
|
window.set_window_icon(Some(load_icon(&path)));
|
||||||
}
|
}
|
||||||
|
WindowEvent::RedrawRequested => fill::fill_window(&window),
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn load_icon(path: &Path) -> Icon {
|
fn load_icon(path: &Path) -> Icon {
|
||||||
|
|||||||
93
examples/window_on_demand.rs
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
|
// Limit this example to only compatible platforms.
|
||||||
|
#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform,))]
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use simple_logger::SimpleLogger;
|
||||||
|
|
||||||
|
use winit::{
|
||||||
|
error::EventLoopError,
|
||||||
|
event::{Event, WindowEvent},
|
||||||
|
event_loop::EventLoop,
|
||||||
|
platform::run_on_demand::EventLoopExtRunOnDemand,
|
||||||
|
window::{Window, WindowId},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct App {
|
||||||
|
window_id: Option<WindowId>,
|
||||||
|
window: Option<Window>,
|
||||||
|
}
|
||||||
|
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let mut event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
fn run_app(event_loop: &mut EventLoop<()>, idx: usize) -> Result<(), EventLoopError> {
|
||||||
|
let mut app = App::default();
|
||||||
|
|
||||||
|
event_loop.run_on_demand(move |event, elwt| {
|
||||||
|
println!("Run {idx}: {:?}", event);
|
||||||
|
|
||||||
|
if let Some(window) = &app.window {
|
||||||
|
match event {
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::CloseRequested,
|
||||||
|
window_id,
|
||||||
|
} if window.id() == window_id => {
|
||||||
|
println!("--------------------------------------------------------- Window {idx} CloseRequested");
|
||||||
|
fill::cleanup_window(window);
|
||||||
|
app.window = None;
|
||||||
|
}
|
||||||
|
Event::AboutToWait => window.request_redraw(),
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::RedrawRequested,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
fill::fill_window(window);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
} else if let Some(id) = app.window_id {
|
||||||
|
match event {
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::Destroyed,
|
||||||
|
window_id,
|
||||||
|
} if id == window_id => {
|
||||||
|
println!("--------------------------------------------------------- Window {idx} Destroyed");
|
||||||
|
app.window_id = None;
|
||||||
|
elwt.exit();
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
} else if let Event::Resumed = event {
|
||||||
|
let window = Window::builder()
|
||||||
|
.with_title("Fantastic window number one!")
|
||||||
|
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
||||||
|
.build(elwt)
|
||||||
|
.unwrap();
|
||||||
|
app.window_id = Some(window.id());
|
||||||
|
app.window = Some(window);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
run_app(&mut event_loop, 1)?;
|
||||||
|
|
||||||
|
println!("--------------------------------------------------------- Finished first loop");
|
||||||
|
println!("--------------------------------------------------------- Waiting 5 seconds");
|
||||||
|
std::thread::sleep(Duration::from_secs(5));
|
||||||
|
|
||||||
|
let ret = run_app(&mut event_loop, 2);
|
||||||
|
println!("--------------------------------------------------------- Finished second loop");
|
||||||
|
ret
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(any(windows_platform, macos_platform, x11_platform, wayland_platform,)))]
|
||||||
|
fn main() {
|
||||||
|
println!("This example is not supported on this platform");
|
||||||
|
}
|
||||||
@@ -8,57 +8,62 @@ use winit::{
|
|||||||
event::ElementState,
|
event::ElementState,
|
||||||
event::{Event, MouseButton, WindowEvent},
|
event::{Event, MouseButton, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
window::WindowBuilder,
|
window::Window,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
/// Prints the keyboard events characters received when option_is_alt is true versus false.
|
/// Prints the keyboard events characters received when option_is_alt is true versus false.
|
||||||
/// A left mouse click will toggle option_is_alt.
|
/// A left mouse click will toggle option_is_alt.
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
fn main() {
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
let event_loop = EventLoop::new();
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
let window = Window::builder()
|
||||||
.with_title("A fantastic window!")
|
.with_title("A fantastic window!")
|
||||||
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
||||||
.build(&event_loop)
|
.build(&event_loop)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
window.set_ime_allowed(true);
|
||||||
|
|
||||||
let mut option_as_alt = window.option_as_alt();
|
let mut option_as_alt = window.option_as_alt();
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| match event {
|
||||||
control_flow.set_wait();
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::CloseRequested,
|
||||||
|
window_id,
|
||||||
|
} if window_id == window.id() => elwt.exit(),
|
||||||
|
Event::WindowEvent { event, .. } => match event {
|
||||||
|
WindowEvent::MouseInput {
|
||||||
|
state: ElementState::Pressed,
|
||||||
|
button: MouseButton::Left,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
option_as_alt = match option_as_alt {
|
||||||
|
OptionAsAlt::None => OptionAsAlt::OnlyLeft,
|
||||||
|
OptionAsAlt::OnlyLeft => OptionAsAlt::OnlyRight,
|
||||||
|
OptionAsAlt::OnlyRight => OptionAsAlt::Both,
|
||||||
|
OptionAsAlt::Both => OptionAsAlt::None,
|
||||||
|
};
|
||||||
|
|
||||||
match event {
|
println!("Received Mouse click, toggling option_as_alt to: {option_as_alt:?}");
|
||||||
Event::WindowEvent {
|
window.set_option_as_alt(option_as_alt);
|
||||||
event: WindowEvent::CloseRequested,
|
}
|
||||||
window_id,
|
WindowEvent::KeyboardInput { .. } => println!("KeyboardInput: {event:?}"),
|
||||||
} if window_id == window.id() => control_flow.set_exit(),
|
WindowEvent::RedrawRequested => {
|
||||||
Event::WindowEvent { event, .. } => match event {
|
fill::fill_window(&window);
|
||||||
WindowEvent::MouseInput {
|
|
||||||
state: ElementState::Pressed,
|
|
||||||
button: MouseButton::Left,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
option_as_alt = match option_as_alt {
|
|
||||||
OptionAsAlt::None => OptionAsAlt::OnlyLeft,
|
|
||||||
OptionAsAlt::OnlyLeft => OptionAsAlt::OnlyRight,
|
|
||||||
OptionAsAlt::OnlyRight => OptionAsAlt::Both,
|
|
||||||
OptionAsAlt::Both => OptionAsAlt::None,
|
|
||||||
};
|
|
||||||
|
|
||||||
println!("Received Mouse click, toggling option_as_alt to: {option_as_alt:?}");
|
|
||||||
window.set_option_as_alt(option_as_alt);
|
|
||||||
}
|
|
||||||
WindowEvent::ReceivedCharacter(c) => println!("ReceivedCharacter: {c:?}"),
|
|
||||||
WindowEvent::KeyboardInput { .. } => println!("KeyboardInput: {event:?}"),
|
|
||||||
_ => (),
|
|
||||||
},
|
|
||||||
Event::MainEventsCleared => {
|
|
||||||
window.request_redraw();
|
|
||||||
}
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
|
},
|
||||||
|
Event::AboutToWait => {
|
||||||
|
window.request_redraw();
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
_ => (),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(target_os = "macos"))]
|
#[cfg(not(target_os = "macos"))]
|
||||||
|
|||||||
74
examples/window_pump_events.rs
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
|
// Limit this example to only compatible platforms.
|
||||||
|
#[cfg(any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform,
|
||||||
|
android_platform,
|
||||||
|
))]
|
||||||
|
fn main() -> std::process::ExitCode {
|
||||||
|
use std::{process::ExitCode, thread::sleep, time::Duration};
|
||||||
|
|
||||||
|
use simple_logger::SimpleLogger;
|
||||||
|
use winit::{
|
||||||
|
event::{Event, WindowEvent},
|
||||||
|
event_loop::EventLoop,
|
||||||
|
platform::pump_events::{EventLoopExtPumpEvents, PumpStatus},
|
||||||
|
window::Window,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
let mut event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let window = Window::builder()
|
||||||
|
.with_title("A fantastic window!")
|
||||||
|
.build(&event_loop)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
'main: loop {
|
||||||
|
let timeout = Some(Duration::ZERO);
|
||||||
|
let status = event_loop.pump_events(timeout, |event, elwt| {
|
||||||
|
if let Event::WindowEvent { event, .. } = &event {
|
||||||
|
// Print only Window events to reduce noise
|
||||||
|
println!("{event:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
match event {
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::CloseRequested,
|
||||||
|
window_id,
|
||||||
|
} if window_id == window.id() => elwt.exit(),
|
||||||
|
Event::AboutToWait => {
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::RedrawRequested,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if let PumpStatus::Exit(exit_code) = status {
|
||||||
|
break 'main ExitCode::from(exit_code as u8);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sleep for 1/60 second to simulate application work
|
||||||
|
//
|
||||||
|
// Since `pump_events` doesn't block it will be important to
|
||||||
|
// throttle the loop in the app somehow.
|
||||||
|
println!("Update()");
|
||||||
|
sleep(Duration::from_millis(16));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(ios_platform, web_platform, orbital_platform))]
|
||||||
|
fn main() {
|
||||||
|
println!("This platform doesn't support pump_events.");
|
||||||
|
}
|
||||||
@@ -2,16 +2,20 @@ use log::debug;
|
|||||||
use simple_logger::SimpleLogger;
|
use simple_logger::SimpleLogger;
|
||||||
use winit::{
|
use winit::{
|
||||||
dpi::LogicalSize,
|
dpi::LogicalSize,
|
||||||
event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent},
|
event::{ElementState, Event, WindowEvent},
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
window::WindowBuilder,
|
keyboard::NamedKey,
|
||||||
|
window::Window,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn main() {
|
#[path = "util/fill.rs"]
|
||||||
SimpleLogger::new().init().unwrap();
|
mod fill;
|
||||||
let event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
let window = WindowBuilder::new()
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
.with_title("A fantastic window!")
|
.with_title("A fantastic window!")
|
||||||
.with_inner_size(LogicalSize::new(128.0, 128.0))
|
.with_inner_size(LogicalSize::new(128.0, 128.0))
|
||||||
.with_resize_increments(LogicalSize::new(25.0, 25.0))
|
.with_resize_increments(LogicalSize::new(25.0, 25.0))
|
||||||
@@ -20,27 +24,13 @@ fn main() {
|
|||||||
|
|
||||||
let mut has_increments = true;
|
let mut has_increments = true;
|
||||||
|
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, elwt| match event {
|
||||||
control_flow.set_wait();
|
Event::WindowEvent { event, window_id } if window_id == window.id() => match event {
|
||||||
|
WindowEvent::CloseRequested => elwt.exit(),
|
||||||
match event {
|
WindowEvent::KeyboardInput { event, .. }
|
||||||
Event::WindowEvent {
|
if event.logical_key == NamedKey::Space
|
||||||
event: WindowEvent::CloseRequested,
|
&& event.state == ElementState::Released =>
|
||||||
window_id,
|
{
|
||||||
} if window_id == window.id() => control_flow.set_exit(),
|
|
||||||
Event::WindowEvent {
|
|
||||||
event:
|
|
||||||
WindowEvent::KeyboardInput {
|
|
||||||
input:
|
|
||||||
KeyboardInput {
|
|
||||||
virtual_keycode: Some(VirtualKeyCode::Space),
|
|
||||||
state: ElementState::Released,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
},
|
|
||||||
window_id,
|
|
||||||
} if window_id == window.id() => {
|
|
||||||
has_increments = !has_increments;
|
has_increments = !has_increments;
|
||||||
|
|
||||||
let new_increments = match window.resize_increments() {
|
let new_increments = match window.resize_increments() {
|
||||||
@@ -50,8 +40,13 @@ fn main() {
|
|||||||
debug!("Had increments: {}", new_increments.is_none());
|
debug!("Had increments: {}", new_increments.is_none());
|
||||||
window.set_resize_increments(new_increments);
|
window.set_resize_increments(new_increments);
|
||||||
}
|
}
|
||||||
Event::MainEventsCleared => window.request_redraw(),
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
},
|
||||||
});
|
Event::AboutToWait => window.request_redraw(),
|
||||||
|
|
||||||
|
_ => (),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
#![allow(clippy::single_match)]
|
|
||||||
|
|
||||||
// Limit this example to only compatible platforms.
|
|
||||||
#[cfg(any(
|
|
||||||
windows_platform,
|
|
||||||
macos_platform,
|
|
||||||
x11_platform,
|
|
||||||
wayland_platform,
|
|
||||||
android_platform,
|
|
||||||
orbital_platform,
|
|
||||||
))]
|
|
||||||
fn main() {
|
|
||||||
use std::{thread::sleep, time::Duration};
|
|
||||||
|
|
||||||
use simple_logger::SimpleLogger;
|
|
||||||
use winit::{
|
|
||||||
event::{Event, WindowEvent},
|
|
||||||
event_loop::EventLoop,
|
|
||||||
platform::run_return::EventLoopExtRunReturn,
|
|
||||||
window::WindowBuilder,
|
|
||||||
};
|
|
||||||
let mut event_loop = EventLoop::new();
|
|
||||||
|
|
||||||
SimpleLogger::new().init().unwrap();
|
|
||||||
let _window = WindowBuilder::new()
|
|
||||||
.with_title("A fantastic window!")
|
|
||||||
.build(&event_loop)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let mut quit = false;
|
|
||||||
|
|
||||||
while !quit {
|
|
||||||
event_loop.run_return(|event, _, control_flow| {
|
|
||||||
control_flow.set_wait();
|
|
||||||
|
|
||||||
if let Event::WindowEvent { event, .. } = &event {
|
|
||||||
// Print only Window events to reduce noise
|
|
||||||
println!("{event:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
match event {
|
|
||||||
Event::WindowEvent {
|
|
||||||
event: WindowEvent::CloseRequested,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
quit = true;
|
|
||||||
}
|
|
||||||
Event::MainEventsCleared => {
|
|
||||||
control_flow.set_exit();
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Sleep for 1/60 second to simulate rendering
|
|
||||||
println!("rendering");
|
|
||||||
sleep(Duration::from_millis(16));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(ios_platform, wasm_platform))]
|
|
||||||
fn main() {
|
|
||||||
println!("This platform doesn't support run_return.");
|
|
||||||
}
|
|
||||||
107
examples/window_tabbing.rs
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
use std::{collections::HashMap, num::NonZeroUsize};
|
||||||
|
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
use simple_logger::SimpleLogger;
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
use winit::{
|
||||||
|
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||||
|
event_loop::EventLoop,
|
||||||
|
keyboard::{Key, NamedKey},
|
||||||
|
platform::macos::{WindowBuilderExtMacOS, WindowExtMacOS},
|
||||||
|
window::Window,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let mut windows = HashMap::new();
|
||||||
|
let window = Window::new(&event_loop).unwrap();
|
||||||
|
println!("Opened a new window: {:?}", window.id());
|
||||||
|
windows.insert(window.id(), window);
|
||||||
|
|
||||||
|
println!("Press N to open a new window.");
|
||||||
|
|
||||||
|
event_loop.run(move |event, elwt| {
|
||||||
|
if let Event::WindowEvent { event, window_id } = event {
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
println!("Window {window_id:?} has received the signal to close");
|
||||||
|
|
||||||
|
// This drops the window, causing it to close.
|
||||||
|
windows.remove(&window_id);
|
||||||
|
|
||||||
|
if windows.is_empty() {
|
||||||
|
elwt.exit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::Resized(_) => {
|
||||||
|
if let Some(window) = windows.get(&window_id) {
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::KeyboardInput {
|
||||||
|
event:
|
||||||
|
KeyEvent {
|
||||||
|
state: ElementState::Pressed,
|
||||||
|
logical_key,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
is_synthetic: false,
|
||||||
|
..
|
||||||
|
} => match logical_key.as_ref() {
|
||||||
|
Key::Character("t") => {
|
||||||
|
let tabbing_id = windows.get(&window_id).unwrap().tabbing_identifier();
|
||||||
|
let window = Window::builder()
|
||||||
|
.with_tabbing_identifier(&tabbing_id)
|
||||||
|
.build(elwt)
|
||||||
|
.unwrap();
|
||||||
|
println!("Added a new tab: {:?}", window.id());
|
||||||
|
windows.insert(window.id(), window);
|
||||||
|
}
|
||||||
|
Key::Character("w") => {
|
||||||
|
let _ = windows.remove(&window_id);
|
||||||
|
}
|
||||||
|
Key::Named(NamedKey::ArrowRight) => {
|
||||||
|
windows.get(&window_id).unwrap().select_next_tab();
|
||||||
|
}
|
||||||
|
Key::Named(NamedKey::ArrowLeft) => {
|
||||||
|
windows.get(&window_id).unwrap().select_previous_tab();
|
||||||
|
}
|
||||||
|
Key::Character(ch) => {
|
||||||
|
if let Ok(index) = ch.parse::<NonZeroUsize>() {
|
||||||
|
let index = index.get();
|
||||||
|
// Select the last tab when pressing `9`.
|
||||||
|
let window = windows.get(&window_id).unwrap();
|
||||||
|
if index == 9 {
|
||||||
|
window.select_tab_at_index(window.num_tabs() - 1)
|
||||||
|
} else {
|
||||||
|
window.select_tab_at_index(index - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
if let Some(window) = windows.get(&window_id) {
|
||||||
|
fill::fill_window(window);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_os = "macos"))]
|
||||||
|
fn main() {
|
||||||
|
println!("This example is only supported on MacOS");
|
||||||
|
}
|
||||||
70
examples/x11_embed.rs
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
//! A demonstration of embedding a winit window in an existing X11 application.
|
||||||
|
|
||||||
|
#[cfg(x11_platform)]
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
#[cfg(x11_platform)]
|
||||||
|
mod imple {
|
||||||
|
use super::fill;
|
||||||
|
use simple_logger::SimpleLogger;
|
||||||
|
use winit::{
|
||||||
|
event::{Event, WindowEvent},
|
||||||
|
event_loop::EventLoop,
|
||||||
|
platform::x11::WindowBuilderExtX11,
|
||||||
|
window::Window,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(super) fn entry() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
// First argument should be a 32-bit X11 window ID.
|
||||||
|
let parent_window_id = std::env::args()
|
||||||
|
.nth(1)
|
||||||
|
.ok_or("Expected a 32-bit X11 window ID as the first argument.")?
|
||||||
|
.parse::<u32>()?;
|
||||||
|
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new()?;
|
||||||
|
|
||||||
|
let window = Window::builder()
|
||||||
|
.with_title("An embedded window!")
|
||||||
|
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
||||||
|
.with_embed_parent_window(parent_window_id)
|
||||||
|
.build(&event_loop)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
event_loop.run(move |event, elwt| {
|
||||||
|
match event {
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::CloseRequested,
|
||||||
|
window_id,
|
||||||
|
} if window_id == window.id() => elwt.exit(),
|
||||||
|
Event::AboutToWait => {
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::RedrawRequested,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
// Notify the windowing system that we'll be presenting to the window.
|
||||||
|
window.pre_present_notify();
|
||||||
|
fill::fill_window(&window);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(x11_platform))]
|
||||||
|
mod imple {
|
||||||
|
pub(super) fn entry() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
println!("This example is only supported on X11 platforms.");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
imple::entry()
|
||||||
|
}
|
||||||
304
src/cursor.rs
Normal file
@@ -0,0 +1,304 @@
|
|||||||
|
use core::fmt;
|
||||||
|
use std::hash::Hasher;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::{error::Error, hash::Hash};
|
||||||
|
|
||||||
|
use cursor_icon::CursorIcon;
|
||||||
|
|
||||||
|
use crate::event_loop::EventLoopWindowTarget;
|
||||||
|
use crate::platform_impl::{self, PlatformCustomCursor, PlatformCustomCursorBuilder};
|
||||||
|
|
||||||
|
/// The maximum width and height for a cursor when using [`CustomCursor::from_rgba`].
|
||||||
|
pub const MAX_CURSOR_SIZE: u16 = 2048;
|
||||||
|
|
||||||
|
const PIXEL_SIZE: usize = 4;
|
||||||
|
|
||||||
|
/// See [`Window::set_cursor()`](crate::window::Window::set_cursor) for more details.
|
||||||
|
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||||
|
pub enum Cursor {
|
||||||
|
Icon(CursorIcon),
|
||||||
|
Custom(CustomCursor),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Cursor {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::Icon(CursorIcon::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<CursorIcon> for Cursor {
|
||||||
|
fn from(icon: CursorIcon) -> Self {
|
||||||
|
Self::Icon(icon)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<CustomCursor> for Cursor {
|
||||||
|
fn from(custom: CustomCursor) -> Self {
|
||||||
|
Self::Custom(custom)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Use a custom image as a cursor (mouse pointer).
|
||||||
|
///
|
||||||
|
/// Is guaranteed to be cheap to clone.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// **Web**: Some browsers have limits on cursor sizes usually at 128x128.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// use winit::{
|
||||||
|
/// event::{Event, WindowEvent},
|
||||||
|
/// event_loop::{ControlFlow, EventLoop},
|
||||||
|
/// window::{CustomCursor, Window},
|
||||||
|
/// };
|
||||||
|
///
|
||||||
|
/// let mut event_loop = EventLoop::new().unwrap();
|
||||||
|
///
|
||||||
|
/// let w = 10;
|
||||||
|
/// let h = 10;
|
||||||
|
/// let rgba = vec![255; (w * h * 4) as usize];
|
||||||
|
///
|
||||||
|
/// #[cfg(not(target_family = "wasm"))]
|
||||||
|
/// let builder = CustomCursor::from_rgba(rgba, w, h, w / 2, h / 2).unwrap();
|
||||||
|
///
|
||||||
|
/// #[cfg(target_family = "wasm")]
|
||||||
|
/// let builder = {
|
||||||
|
/// use winit::platform::web::CustomCursorExtWebSys;
|
||||||
|
/// CustomCursor::from_url(String::from("http://localhost:3000/cursor.png"), 0, 0)
|
||||||
|
/// };
|
||||||
|
///
|
||||||
|
/// let custom_cursor = builder.build(&event_loop);
|
||||||
|
///
|
||||||
|
/// let window = Window::new(&event_loop).unwrap();
|
||||||
|
/// window.set_cursor(custom_cursor.clone());
|
||||||
|
/// ```
|
||||||
|
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||||
|
pub struct CustomCursor {
|
||||||
|
/// Platforms should make sure this is cheap to clone.
|
||||||
|
pub(crate) inner: PlatformCustomCursor,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CustomCursor {
|
||||||
|
/// Creates a new cursor from an rgba buffer.
|
||||||
|
///
|
||||||
|
/// The alpha channel is assumed to be **not** premultiplied.
|
||||||
|
pub fn from_rgba(
|
||||||
|
rgba: impl Into<Vec<u8>>,
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
hotspot_x: u16,
|
||||||
|
hotspot_y: u16,
|
||||||
|
) -> Result<CustomCursorBuilder, BadImage> {
|
||||||
|
Ok(CustomCursorBuilder {
|
||||||
|
inner: PlatformCustomCursorBuilder::from_rgba(
|
||||||
|
rgba.into(),
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
hotspot_x,
|
||||||
|
hotspot_y,
|
||||||
|
)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds a [`CustomCursor`].
|
||||||
|
///
|
||||||
|
/// See [`CustomCursor`] for more details.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct CustomCursorBuilder {
|
||||||
|
pub(crate) inner: PlatformCustomCursorBuilder,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CustomCursorBuilder {
|
||||||
|
pub fn build(self, window_target: &EventLoopWindowTarget) -> CustomCursor {
|
||||||
|
CustomCursor {
|
||||||
|
inner: PlatformCustomCursor::build(self.inner, &window_target.p),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An error produced when using [`CustomCursor::from_rgba`] with invalid arguments.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum BadImage {
|
||||||
|
/// 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
|
||||||
|
/// limits.
|
||||||
|
TooLarge { width: u16, height: u16 },
|
||||||
|
/// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be
|
||||||
|
/// safely interpreted as 32bpp RGBA pixels.
|
||||||
|
ByteCountNotDivisibleBy4 { byte_count: usize },
|
||||||
|
/// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`.
|
||||||
|
/// At least one of your arguments is incorrect.
|
||||||
|
DimensionsVsPixelCount {
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
width_x_height: u64,
|
||||||
|
pixel_count: u64,
|
||||||
|
},
|
||||||
|
/// Produced when the hotspot is outside the image bounds
|
||||||
|
HotspotOutOfBounds {
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
hotspot_x: u16,
|
||||||
|
hotspot_y: u16,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for BadImage {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
BadImage::TooLarge { width, height } => write!(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,
|
||||||
|
"The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making it impossible to interpret as 32bpp RGBA pixels.",
|
||||||
|
),
|
||||||
|
BadImage::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:?}.",
|
||||||
|
),
|
||||||
|
BadImage::HotspotOutOfBounds {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
hotspot_x,
|
||||||
|
hotspot_y,
|
||||||
|
} => write!(f,
|
||||||
|
"The specified hotspot ({hotspot_x:?}, {hotspot_y:?}) is outside the image bounds ({width:?}x{height:?}).",
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for BadImage {}
|
||||||
|
|
||||||
|
/// Platforms export this directly as `PlatformCustomCursorBuilder` if they need to only work with images.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(crate) struct OnlyCursorImageBuilder(pub(crate) CursorImage);
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl OnlyCursorImageBuilder {
|
||||||
|
pub(crate) fn from_rgba(
|
||||||
|
rgba: Vec<u8>,
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
hotspot_x: u16,
|
||||||
|
hotspot_y: u16,
|
||||||
|
) -> Result<Self, BadImage> {
|
||||||
|
CursorImage::from_rgba(rgba, width, height, hotspot_x, hotspot_y).map(Self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Platforms export this directly as `PlatformCustomCursor` if they don't implement caching.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub(crate) struct OnlyCursorImage(pub(crate) Arc<CursorImage>);
|
||||||
|
|
||||||
|
impl Hash for OnlyCursorImage {
|
||||||
|
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||||
|
Arc::as_ptr(&self.0).hash(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for OnlyCursorImage {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
Arc::ptr_eq(&self.0, &other.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Eq for OnlyCursorImage {}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl OnlyCursorImage {
|
||||||
|
pub(crate) fn build(
|
||||||
|
builder: OnlyCursorImageBuilder,
|
||||||
|
_: &platform_impl::EventLoopWindowTarget,
|
||||||
|
) -> Self {
|
||||||
|
Self(Arc::new(builder.0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) struct CursorImage {
|
||||||
|
pub(crate) rgba: Vec<u8>,
|
||||||
|
pub(crate) width: u16,
|
||||||
|
pub(crate) height: u16,
|
||||||
|
pub(crate) hotspot_x: u16,
|
||||||
|
pub(crate) hotspot_y: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CursorImage {
|
||||||
|
pub(crate) fn from_rgba(
|
||||||
|
rgba: Vec<u8>,
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
hotspot_x: u16,
|
||||||
|
hotspot_y: u16,
|
||||||
|
) -> Result<Self, BadImage> {
|
||||||
|
if width > MAX_CURSOR_SIZE || height > MAX_CURSOR_SIZE {
|
||||||
|
return Err(BadImage::TooLarge { width, height });
|
||||||
|
}
|
||||||
|
|
||||||
|
if rgba.len() % PIXEL_SIZE != 0 {
|
||||||
|
return Err(BadImage::ByteCountNotDivisibleBy4 {
|
||||||
|
byte_count: rgba.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let pixel_count = (rgba.len() / PIXEL_SIZE) as u64;
|
||||||
|
let width_x_height = width as u64 * height as u64;
|
||||||
|
if pixel_count != width_x_height {
|
||||||
|
return Err(BadImage::DimensionsVsPixelCount {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
width_x_height,
|
||||||
|
pixel_count,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if hotspot_x >= width || hotspot_y >= height {
|
||||||
|
return Err(BadImage::HotspotOutOfBounds {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
hotspot_x,
|
||||||
|
hotspot_y,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(CursorImage {
|
||||||
|
rgba,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
hotspot_x,
|
||||||
|
hotspot_y,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Platforms that don't support cursors will export this as `PlatformCustomCursor`.
|
||||||
|
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
|
||||||
|
pub(crate) struct NoCustomCursor;
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl NoCustomCursor {
|
||||||
|
pub(crate) fn from_rgba(
|
||||||
|
rgba: Vec<u8>,
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
hotspot_x: u16,
|
||||||
|
hotspot_y: u16,
|
||||||
|
) -> Result<Self, BadImage> {
|
||||||
|
CursorImage::from_rgba(rgba, width, height, hotspot_x, hotspot_y)?;
|
||||||
|
Ok(Self)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build(self, _: &platform_impl::EventLoopWindowTarget) -> NoCustomCursor {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
469
src/dpi.rs
@@ -4,13 +4,13 @@
|
|||||||
//!
|
//!
|
||||||
//! Modern computer screens don't have a consistent relationship between resolution and size.
|
//! Modern computer screens don't have a consistent relationship between resolution and size.
|
||||||
//! 1920x1080 is a common resolution for both desktop and mobile screens, despite mobile screens
|
//! 1920x1080 is a common resolution for both desktop and mobile screens, despite mobile screens
|
||||||
//! normally being less than a quarter the size of their desktop counterparts. What's more, neither
|
//! typically being less than a quarter the size of their desktop counterparts. Moreover, neither
|
||||||
//! desktop nor mobile screens are consistent resolutions within their own size classes - common
|
//! desktop nor mobile screens have consistent resolutions within their own size classes - common
|
||||||
//! mobile screens range from below 720p to above 1440p, and desktop screens range from 720p to 5K
|
//! mobile screens range from below 720p to above 1440p, and desktop screens range from 720p to 5K
|
||||||
//! and beyond.
|
//! and beyond.
|
||||||
//!
|
//!
|
||||||
//! Given that, it's a mistake to assume that 2D content will only be displayed on screens with
|
//! Given that, it's a mistake to assume that 2D content will only be displayed on screens with
|
||||||
//! a consistent pixel density. If you were to render a 96-pixel-square image on a 1080p screen,
|
//! a consistent pixel density. If you were to render a 96-pixel-square image on a 1080p screen and
|
||||||
//! then render the same image on a similarly-sized 4K screen, the 4K rendition would only take up
|
//! then render the same image on a similarly-sized 4K screen, the 4K rendition would only take up
|
||||||
//! about a quarter of the physical space as it did on the 1080p screen. That issue is especially
|
//! about a quarter of the physical space as it did on the 1080p screen. That issue is especially
|
||||||
//! problematic with text rendering, where quarter-sized text becomes a significant legibility
|
//! problematic with text rendering, where quarter-sized text becomes a significant legibility
|
||||||
@@ -25,12 +25,12 @@
|
|||||||
//!
|
//!
|
||||||
//! The solution to this problem is to account for the device's *scale factor*. The scale factor is
|
//! The solution to this problem is to account for the device's *scale factor*. The scale factor is
|
||||||
//! the factor UI elements should be scaled by to be consistent with the rest of the user's system -
|
//! the factor UI elements should be scaled by to be consistent with the rest of the user's system -
|
||||||
//! for example, a button that's normally 50 pixels across would be 100 pixels across on a device
|
//! for example, a button that's usually 50 pixels across would be 100 pixels across on a device
|
||||||
//! with a scale factor of `2.0`, or 75 pixels across with a scale factor of `1.5`.
|
//! with a scale factor of `2.0`, or 75 pixels across with a scale factor of `1.5`.
|
||||||
//!
|
//!
|
||||||
//! Many UI systems, such as CSS, expose DPI-dependent units like [points] or [picas]. That's
|
//! Many UI systems, such as CSS, expose DPI-dependent units like [points] or [picas]. That's
|
||||||
//! usually a mistake, since there's no consistent mapping between the scale factor and the screen's
|
//! usually a mistake since there's no consistent mapping between the scale factor and the screen's
|
||||||
//! actual DPI. Unless you're printing to a physical medium, you should work in scaled pixels rather
|
//! actual DPI. Unless printing to a physical medium, you should work in scaled pixels rather
|
||||||
//! than any DPI-dependent units.
|
//! than any DPI-dependent units.
|
||||||
//!
|
//!
|
||||||
//! ### Position and Size types
|
//! ### Position and Size types
|
||||||
@@ -42,11 +42,11 @@
|
|||||||
//! coordinates as input, allowing you to use the most convenient coordinate system for your
|
//! coordinates as input, allowing you to use the most convenient coordinate system for your
|
||||||
//! particular application.
|
//! particular application.
|
||||||
//!
|
//!
|
||||||
//! Winit's position and size types types are generic over their exact pixel type, `P`, to allow the
|
//! Winit's 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
|
||||||
//! floating precision when necessary (e.g. logical sizes for fractional scale factors and touch
|
//! floating precision when necessary (e.g. logical sizes for fractional scale factors and touch
|
||||||
//! input). If `P` is a floating-point type, please do not cast the values with `as {int}`. Doing so
|
//! input). If `P` is a floating-point type, please do not cast the values with `as {int}`. Doing so
|
||||||
//! will truncate the fractional part of the float, rather than properly round to the nearest
|
//! will truncate the fractional part of the float rather than properly round to the nearest
|
||||||
//! integer. Use the provided `cast` function or [`From`]/[`Into`] conversions, which handle the
|
//! integer. Use the provided `cast` function or [`From`]/[`Into`] conversions, which handle the
|
||||||
//! rounding properly. Note that precision loss will still occur when rounding from a float to an
|
//! rounding properly. Note that precision loss will still occur when rounding from a float to an
|
||||||
//! int, although rounding lessens the problem.
|
//! int, although rounding lessens the problem.
|
||||||
@@ -55,35 +55,35 @@
|
|||||||
//!
|
//!
|
||||||
//! Winit will dispatch a [`ScaleFactorChanged`] event whenever a window's scale factor has changed.
|
//! Winit will dispatch a [`ScaleFactorChanged`] event whenever a window's scale factor has changed.
|
||||||
//! This can happen if the user drags their window from a standard-resolution monitor to a high-DPI
|
//! This can happen if the user drags their window from a standard-resolution monitor to a high-DPI
|
||||||
//! monitor, or if the user changes their DPI settings. This gives you a chance to rescale your
|
//! monitor or if the user changes their DPI settings. This allows you to rescale your application's
|
||||||
//! application's UI elements and adjust how the platform changes the window's size to reflect the new
|
//! UI elements and adjust how the platform changes the window's size to reflect the new scale
|
||||||
//! scale factor. If a window hasn't received a [`ScaleFactorChanged`] event, then its scale factor
|
//! factor. If a window hasn't received a [`ScaleFactorChanged`] event, its scale factor
|
||||||
//! can be found by calling [`window.scale_factor()`].
|
//! can be found by calling [`window.scale_factor()`].
|
||||||
//!
|
//!
|
||||||
//! ## How is the scale factor calculated?
|
//! ## How is the scale factor calculated?
|
||||||
//!
|
//!
|
||||||
//! Scale factor is calculated differently on different platforms:
|
//! The scale factor is calculated differently on different platforms:
|
||||||
//!
|
//!
|
||||||
//! - **Windows:** On Windows 8 and 10, per-monitor scaling is readily configured by users from the
|
//! - **Windows:** On Windows 8 and 10, per-monitor scaling is readily configured by users from the
|
||||||
//! display settings. While users are free to select any option they want, they're only given a
|
//! display settings. While users are free to select any option they want, they're only given a
|
||||||
//! selection of "nice" scale factors, i.e. 1.0, 1.25, 1.5... on Windows 7, the scale factor is
|
//! selection of "nice" scale factors, i.e. 1.0, 1.25, 1.5... on Windows 7. The scale factor is
|
||||||
//! global and changing it requires logging out. See [this article][windows_1] for technical
|
//! global and changing it requires logging out. See [this article][windows_1] for technical
|
||||||
//! details.
|
//! details.
|
||||||
//! - **macOS:** Recent versions of macOS allow the user to change the scaling factor for certain
|
//! - **macOS:** Recent macOS versions allow the user to change the scaling factor for specific
|
||||||
//! displays. When this is available, the user may pick a per-monitor scaling factor from a set
|
//! displays. When available, the user may pick a per-monitor scaling factor from a set of
|
||||||
//! of pre-defined settings. All "retina displays" have a scaling factor above 1.0 by default but
|
//! pre-defined settings. All "retina displays" have a scaling factor above 1.0 by default,
|
||||||
//! the specific value varies across devices.
|
//! but the specific value varies across devices.
|
||||||
//! - **X11:** Many man-hours have been spent trying to figure out how to handle DPI in X11. Winit
|
//! - **X11:** Many man-hours have been spent trying to figure out how to handle DPI in X11. Winit
|
||||||
//! currently uses a three-pronged approach:
|
//! currently uses a three-pronged approach:
|
||||||
//! + Use the value in the `WINIT_X11_SCALE_FACTOR` environment variable, if present.
|
//! + Use the value in the `WINIT_X11_SCALE_FACTOR` environment variable if present.
|
||||||
//! + If not present, use the value set in `Xft.dpi` in Xresources.
|
//! + If not present, use the value set in `Xft.dpi` in Xresources.
|
||||||
//! + Otherwise, calculate the scale factor based on the millimeter monitor dimensions provided by XRandR.
|
//! + Otherwise, calculate the scale factor based on the millimeter monitor dimensions provided by XRandR.
|
||||||
//!
|
//!
|
||||||
//! If `WINIT_X11_SCALE_FACTOR` is set to `randr`, it'll ignore the `Xft.dpi` field and use the
|
//! If `WINIT_X11_SCALE_FACTOR` is set to `randr`, it'll ignore the `Xft.dpi` field and use the
|
||||||
//! XRandR scaling method. Generally speaking, you should try to configure the standard system
|
//! XRandR scaling method. Generally speaking, you should try to configure the standard system
|
||||||
//! variables to do what you want before resorting to `WINIT_X11_SCALE_FACTOR`.
|
//! variables to do what you want before resorting to `WINIT_X11_SCALE_FACTOR`.
|
||||||
//! - **Wayland:** On Wayland, scale factors are set per-screen by the server, and are always
|
//! - **Wayland:** The scale factor is suggested by the compositor for each window individually. The
|
||||||
//! integers (most often 1 or 2).
|
//! monitor scale factor may differ from the window scale factor.
|
||||||
//! - **iOS:** Scale factors are set by Apple to the value that best suits the device, and range
|
//! - **iOS:** Scale factors are set by Apple to the value that best suits the device, and range
|
||||||
//! from `1.0` to `3.0`. See [this article][apple_1] and [this article][apple_2] for more
|
//! from `1.0` to `3.0`. See [this article][apple_1] and [this article][apple_2] for more
|
||||||
//! information.
|
//! information.
|
||||||
@@ -104,6 +104,9 @@
|
|||||||
//! [android_1]: https://developer.android.com/training/multiscreen/screendensities
|
//! [android_1]: https://developer.android.com/training/multiscreen/screendensities
|
||||||
//! [web_1]: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
|
//! [web_1]: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
|
||||||
|
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
pub trait Pixel: Copy + Into<f64> {
|
pub trait Pixel: Copy + Into<f64> {
|
||||||
fn from_f64(f: f64) -> Self;
|
fn from_f64(f: f64) -> Self;
|
||||||
fn cast<P: Pixel>(self) -> P {
|
fn cast<P: Pixel>(self) -> P {
|
||||||
@@ -167,7 +170,7 @@ pub fn validate_scale_factor(scale_factor: f64) -> bool {
|
|||||||
/// The position is stored as floats, so please be careful. Casting floats to integers truncates the
|
/// The position is stored as floats, so please be careful. Casting floats to integers truncates the
|
||||||
/// fractional part, which can cause noticable issues. To help with that, an `Into<(i32, i32)>`
|
/// fractional part, which can cause noticable issues. To help with that, an `Into<(i32, i32)>`
|
||||||
/// implementation is provided which does the rounding for you.
|
/// implementation is provided which does the rounding for you.
|
||||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default, Hash)]
|
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub struct LogicalPosition<P> {
|
pub struct LogicalPosition<P> {
|
||||||
pub x: P,
|
pub x: P,
|
||||||
@@ -246,7 +249,7 @@ impl<P: Pixel> From<LogicalPosition<P>> for mint::Point2<P> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A position represented in physical pixels.
|
/// A position represented in physical pixels.
|
||||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default, Hash)]
|
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub struct PhysicalPosition<P> {
|
pub struct PhysicalPosition<P> {
|
||||||
pub x: P,
|
pub x: P,
|
||||||
@@ -325,7 +328,7 @@ impl<P: Pixel> From<PhysicalPosition<P>> for mint::Point2<P> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A size represented in logical pixels.
|
/// A size represented in logical pixels.
|
||||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default, Hash)]
|
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub struct LogicalSize<P> {
|
pub struct LogicalSize<P> {
|
||||||
pub width: P,
|
pub width: P,
|
||||||
@@ -407,7 +410,7 @@ impl<P: Pixel> From<LogicalSize<P>> for mint::Vector2<P> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A size represented in physical pixels.
|
/// A size represented in physical pixels.
|
||||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default, Hash)]
|
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub struct PhysicalSize<P> {
|
pub struct PhysicalSize<P> {
|
||||||
pub width: P,
|
pub width: P,
|
||||||
@@ -581,3 +584,421 @@ impl<P: Pixel> From<LogicalPosition<P>> for Position {
|
|||||||
Position::Logical(position.cast())
|
Position::Logical(position.cast())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use crate::dpi;
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
macro_rules! test_pixel_int_impl {
|
||||||
|
($($name:ident => $ty:ty),*) => {$(
|
||||||
|
#[test]
|
||||||
|
fn $name() {
|
||||||
|
use dpi::Pixel;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.0),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.4),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.5),
|
||||||
|
38,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.9),
|
||||||
|
38,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u8>(37),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u16>(37),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u32>(37),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i8>(37),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i16>(37),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i32>(37),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
)*};
|
||||||
|
}
|
||||||
|
|
||||||
|
test_pixel_int_impl! {
|
||||||
|
test_pixel_int_u8 => u8,
|
||||||
|
test_pixel_int_u16 => u16,
|
||||||
|
test_pixel_int_u32 => u32,
|
||||||
|
test_pixel_int_i8 => i8,
|
||||||
|
test_pixel_int_i16 => i16
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! assert_approx_eq {
|
||||||
|
($a:expr, $b:expr $(,)?) => {
|
||||||
|
assert!(
|
||||||
|
($a - $b).abs() < 0.001,
|
||||||
|
"{} is not approximately equal to {}",
|
||||||
|
$a,
|
||||||
|
$b
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! test_pixel_float_impl {
|
||||||
|
($($name:ident => $ty:ty),*) => {$(
|
||||||
|
#[test]
|
||||||
|
fn $name() {
|
||||||
|
use dpi::Pixel;
|
||||||
|
|
||||||
|
assert_approx_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.0),
|
||||||
|
37.0,
|
||||||
|
);
|
||||||
|
assert_approx_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.4),
|
||||||
|
37.4,
|
||||||
|
);
|
||||||
|
assert_approx_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.5),
|
||||||
|
37.5,
|
||||||
|
);
|
||||||
|
assert_approx_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.9),
|
||||||
|
37.9,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u8>(37.0),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u8>(37.4),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u8>(37.5),
|
||||||
|
38,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u16>(37.0),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u16>(37.4),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u16>(37.5),
|
||||||
|
38,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u32>(37.0),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u32>(37.4),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u32>(37.5),
|
||||||
|
38,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i8>(37.0),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i8>(37.4),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i8>(37.5),
|
||||||
|
38,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i16>(37.0),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i16>(37.4),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i16>(37.5),
|
||||||
|
38,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
)*};
|
||||||
|
}
|
||||||
|
|
||||||
|
test_pixel_float_impl! {
|
||||||
|
test_pixel_float_f32 => f32,
|
||||||
|
test_pixel_float_f64 => f64
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_validate_scale_factor() {
|
||||||
|
assert!(dpi::validate_scale_factor(1.0));
|
||||||
|
assert!(dpi::validate_scale_factor(2.0));
|
||||||
|
assert!(dpi::validate_scale_factor(3.0));
|
||||||
|
assert!(dpi::validate_scale_factor(1.5));
|
||||||
|
assert!(dpi::validate_scale_factor(0.5));
|
||||||
|
|
||||||
|
assert!(!dpi::validate_scale_factor(0.0));
|
||||||
|
assert!(!dpi::validate_scale_factor(-1.0));
|
||||||
|
assert!(!dpi::validate_scale_factor(f64::INFINITY));
|
||||||
|
assert!(!dpi::validate_scale_factor(f64::NAN));
|
||||||
|
assert!(!dpi::validate_scale_factor(f64::NEG_INFINITY));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_logical_position() {
|
||||||
|
let log_pos = dpi::LogicalPosition::new(1.0, 2.0);
|
||||||
|
assert_eq!(
|
||||||
|
log_pos.to_physical::<u32>(1.0),
|
||||||
|
dpi::PhysicalPosition::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
log_pos.to_physical::<u32>(2.0),
|
||||||
|
dpi::PhysicalPosition::new(2, 4)
|
||||||
|
);
|
||||||
|
assert_eq!(log_pos.cast::<u32>(), dpi::LogicalPosition::new(1, 2));
|
||||||
|
assert_eq!(
|
||||||
|
log_pos,
|
||||||
|
dpi::LogicalPosition::from_physical(dpi::PhysicalPosition::new(1.0, 2.0), 1.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
log_pos,
|
||||||
|
dpi::LogicalPosition::from_physical(dpi::PhysicalPosition::new(2.0, 4.0), 2.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::LogicalPosition::from((2.0, 2.0)),
|
||||||
|
dpi::LogicalPosition::new(2.0, 2.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::LogicalPosition::from([2.0, 3.0]),
|
||||||
|
dpi::LogicalPosition::new(2.0, 3.0)
|
||||||
|
);
|
||||||
|
|
||||||
|
let x: (f64, f64) = log_pos.into();
|
||||||
|
assert_eq!(x, (1.0, 2.0));
|
||||||
|
let x: [f64; 2] = log_pos.into();
|
||||||
|
assert_eq!(x, [1.0, 2.0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_physical_position() {
|
||||||
|
assert_eq!(
|
||||||
|
dpi::PhysicalPosition::from_logical(dpi::LogicalPosition::new(1.0, 2.0), 1.0),
|
||||||
|
dpi::PhysicalPosition::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::PhysicalPosition::from_logical(dpi::LogicalPosition::new(2.0, 4.0), 0.5),
|
||||||
|
dpi::PhysicalPosition::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::PhysicalPosition::from((2.0, 2.0)),
|
||||||
|
dpi::PhysicalPosition::new(2.0, 2.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::PhysicalPosition::from([2.0, 3.0]),
|
||||||
|
dpi::PhysicalPosition::new(2.0, 3.0)
|
||||||
|
);
|
||||||
|
|
||||||
|
let x: (f64, f64) = dpi::PhysicalPosition::new(1, 2).into();
|
||||||
|
assert_eq!(x, (1.0, 2.0));
|
||||||
|
let x: [f64; 2] = dpi::PhysicalPosition::new(1, 2).into();
|
||||||
|
assert_eq!(x, [1.0, 2.0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_logical_size() {
|
||||||
|
let log_size = dpi::LogicalSize::new(1.0, 2.0);
|
||||||
|
assert_eq!(
|
||||||
|
log_size.to_physical::<u32>(1.0),
|
||||||
|
dpi::PhysicalSize::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
log_size.to_physical::<u32>(2.0),
|
||||||
|
dpi::PhysicalSize::new(2, 4)
|
||||||
|
);
|
||||||
|
assert_eq!(log_size.cast::<u32>(), dpi::LogicalSize::new(1, 2));
|
||||||
|
assert_eq!(
|
||||||
|
log_size,
|
||||||
|
dpi::LogicalSize::from_physical(dpi::PhysicalSize::new(1.0, 2.0), 1.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
log_size,
|
||||||
|
dpi::LogicalSize::from_physical(dpi::PhysicalSize::new(2.0, 4.0), 2.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::LogicalSize::from((2.0, 2.0)),
|
||||||
|
dpi::LogicalSize::new(2.0, 2.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::LogicalSize::from([2.0, 3.0]),
|
||||||
|
dpi::LogicalSize::new(2.0, 3.0)
|
||||||
|
);
|
||||||
|
|
||||||
|
let x: (f64, f64) = log_size.into();
|
||||||
|
assert_eq!(x, (1.0, 2.0));
|
||||||
|
let x: [f64; 2] = log_size.into();
|
||||||
|
assert_eq!(x, [1.0, 2.0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_physical_size() {
|
||||||
|
assert_eq!(
|
||||||
|
dpi::PhysicalSize::from_logical(dpi::LogicalSize::new(1.0, 2.0), 1.0),
|
||||||
|
dpi::PhysicalSize::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::PhysicalSize::from_logical(dpi::LogicalSize::new(2.0, 4.0), 0.5),
|
||||||
|
dpi::PhysicalSize::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::PhysicalSize::from((2.0, 2.0)),
|
||||||
|
dpi::PhysicalSize::new(2.0, 2.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::PhysicalSize::from([2.0, 3.0]),
|
||||||
|
dpi::PhysicalSize::new(2.0, 3.0)
|
||||||
|
);
|
||||||
|
|
||||||
|
let x: (f64, f64) = dpi::PhysicalSize::new(1, 2).into();
|
||||||
|
assert_eq!(x, (1.0, 2.0));
|
||||||
|
let x: [f64; 2] = dpi::PhysicalSize::new(1, 2).into();
|
||||||
|
assert_eq!(x, [1.0, 2.0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_size() {
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Size::new(dpi::PhysicalSize::new(1, 2)),
|
||||||
|
dpi::Size::Physical(dpi::PhysicalSize::new(1, 2))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Size::new(dpi::LogicalSize::new(1.0, 2.0)),
|
||||||
|
dpi::Size::Logical(dpi::LogicalSize::new(1.0, 2.0))
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Size::new(dpi::PhysicalSize::new(1, 2)).to_logical::<f64>(1.0),
|
||||||
|
dpi::LogicalSize::new(1.0, 2.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Size::new(dpi::PhysicalSize::new(1, 2)).to_logical::<f64>(2.0),
|
||||||
|
dpi::LogicalSize::new(0.5, 1.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Size::new(dpi::LogicalSize::new(1.0, 2.0)).to_logical::<f64>(1.0),
|
||||||
|
dpi::LogicalSize::new(1.0, 2.0)
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Size::new(dpi::PhysicalSize::new(1, 2)).to_physical::<u32>(1.0),
|
||||||
|
dpi::PhysicalSize::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Size::new(dpi::PhysicalSize::new(1, 2)).to_physical::<u32>(2.0),
|
||||||
|
dpi::PhysicalSize::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Size::new(dpi::LogicalSize::new(1.0, 2.0)).to_physical::<u32>(1.0),
|
||||||
|
dpi::PhysicalSize::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Size::new(dpi::LogicalSize::new(1.0, 2.0)).to_physical::<u32>(2.0),
|
||||||
|
dpi::PhysicalSize::new(2, 4)
|
||||||
|
);
|
||||||
|
|
||||||
|
let small = dpi::Size::Physical((1, 2).into());
|
||||||
|
let medium = dpi::Size::Logical((3, 4).into());
|
||||||
|
let medium_physical = dpi::Size::new(medium.to_physical::<u32>(1.0));
|
||||||
|
let large = dpi::Size::Physical((5, 6).into());
|
||||||
|
assert_eq!(dpi::Size::clamp(medium, small, large, 1.0), medium_physical);
|
||||||
|
assert_eq!(dpi::Size::clamp(small, medium, large, 1.0), medium_physical);
|
||||||
|
assert_eq!(dpi::Size::clamp(large, small, medium, 1.0), medium_physical);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_position() {
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Position::new(dpi::PhysicalPosition::new(1, 2)),
|
||||||
|
dpi::Position::Physical(dpi::PhysicalPosition::new(1, 2))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Position::new(dpi::LogicalPosition::new(1.0, 2.0)),
|
||||||
|
dpi::Position::Logical(dpi::LogicalPosition::new(1.0, 2.0))
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Position::new(dpi::PhysicalPosition::new(1, 2)).to_logical::<f64>(1.0),
|
||||||
|
dpi::LogicalPosition::new(1.0, 2.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Position::new(dpi::PhysicalPosition::new(1, 2)).to_logical::<f64>(2.0),
|
||||||
|
dpi::LogicalPosition::new(0.5, 1.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Position::new(dpi::LogicalPosition::new(1.0, 2.0)).to_logical::<f64>(1.0),
|
||||||
|
dpi::LogicalPosition::new(1.0, 2.0)
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Position::new(dpi::PhysicalPosition::new(1, 2)).to_physical::<u32>(1.0),
|
||||||
|
dpi::PhysicalPosition::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Position::new(dpi::PhysicalPosition::new(1, 2)).to_physical::<u32>(2.0),
|
||||||
|
dpi::PhysicalPosition::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Position::new(dpi::LogicalPosition::new(1.0, 2.0)).to_physical::<u32>(1.0),
|
||||||
|
dpi::PhysicalPosition::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
dpi::Position::new(dpi::LogicalPosition::new(1.0, 2.0)).to_physical::<u32>(2.0),
|
||||||
|
dpi::PhysicalPosition::new(2, 4)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Eat coverage for the Debug impls et al
|
||||||
|
#[test]
|
||||||
|
fn ensure_attrs_do_not_panic() {
|
||||||
|
let _ = format!("{:?}", dpi::LogicalPosition::<u32>::default().clone());
|
||||||
|
HashSet::new().insert(dpi::LogicalPosition::<u32>::default());
|
||||||
|
|
||||||
|
let _ = format!("{:?}", dpi::PhysicalPosition::<u32>::default().clone());
|
||||||
|
HashSet::new().insert(dpi::PhysicalPosition::<u32>::default());
|
||||||
|
|
||||||
|
let _ = format!("{:?}", dpi::LogicalSize::<u32>::default().clone());
|
||||||
|
HashSet::new().insert(dpi::LogicalSize::<u32>::default());
|
||||||
|
|
||||||
|
let _ = format!("{:?}", dpi::PhysicalSize::<u32>::default().clone());
|
||||||
|
HashSet::new().insert(dpi::PhysicalSize::<u32>::default());
|
||||||
|
|
||||||
|
let _ = format!("{:?}", dpi::Size::Physical((1, 2).into()).clone());
|
||||||
|
let _ = format!("{:?}", dpi::Position::Physical((1, 2).into()).clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
59
src/error.rs
@@ -2,11 +2,14 @@ use std::{error, fmt};
|
|||||||
|
|
||||||
use crate::platform_impl;
|
use crate::platform_impl;
|
||||||
|
|
||||||
/// An error whose cause it outside Winit's control.
|
// TODO: Rename
|
||||||
|
/// An error that may be generated when requesting Winit state
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum ExternalError {
|
pub enum ExternalError {
|
||||||
/// The operation is not supported by the backend.
|
/// The operation is not supported by the backend.
|
||||||
NotSupported(NotSupportedError),
|
NotSupported(NotSupportedError),
|
||||||
|
/// The operation was ignored.
|
||||||
|
Ignored,
|
||||||
/// The OS cannot perform the operation.
|
/// The OS cannot perform the operation.
|
||||||
Os(OsError),
|
Os(OsError),
|
||||||
}
|
}
|
||||||
@@ -25,6 +28,25 @@ pub struct OsError {
|
|||||||
error: platform_impl::OsError,
|
error: platform_impl::OsError,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A general error that may occur while running the Winit event loop
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum EventLoopError {
|
||||||
|
/// The operation is not supported by the backend.
|
||||||
|
NotSupported(NotSupportedError),
|
||||||
|
/// The OS cannot perform the operation.
|
||||||
|
Os(OsError),
|
||||||
|
/// The event loop can't be re-created.
|
||||||
|
RecreationAttempt,
|
||||||
|
/// Application has exit with an error status.
|
||||||
|
ExitFailure(i32),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<OsError> for EventLoopError {
|
||||||
|
fn from(value: OsError) -> Self {
|
||||||
|
Self::Os(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl NotSupportedError {
|
impl NotSupportedError {
|
||||||
#[inline]
|
#[inline]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
@@ -60,6 +82,7 @@ impl fmt::Display for ExternalError {
|
|||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||||
match self {
|
match self {
|
||||||
ExternalError::NotSupported(e) => e.fmt(f),
|
ExternalError::NotSupported(e) => e.fmt(f),
|
||||||
|
ExternalError::Ignored => write!(f, "Operation was ignored"),
|
||||||
ExternalError::Os(e) => e.fmt(f),
|
ExternalError::Os(e) => e.fmt(f),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -77,6 +100,40 @@ impl fmt::Display for NotSupportedError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 OsError {}
|
||||||
impl error::Error for ExternalError {}
|
impl error::Error for ExternalError {}
|
||||||
impl error::Error for NotSupportedError {}
|
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())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
1341
src/event.rs
@@ -9,12 +9,17 @@
|
|||||||
//! handle events.
|
//! handle events.
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
use std::{error, fmt};
|
use std::{error, fmt};
|
||||||
|
|
||||||
use instant::{Duration, Instant};
|
#[cfg(not(web_platform))]
|
||||||
use once_cell::sync::OnceCell;
|
use std::time::{Duration, Instant};
|
||||||
use raw_window_handle::{HasRawDisplayHandle, RawDisplayHandle};
|
#[cfg(web_platform)]
|
||||||
|
use web_time::{Duration, Instant};
|
||||||
|
|
||||||
|
use crate::error::EventLoopError;
|
||||||
use crate::{event::Event, monitor::MonitorHandle, platform_impl};
|
use crate::{event::Event, monitor::MonitorHandle, platform_impl};
|
||||||
|
|
||||||
/// 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
|
||||||
@@ -43,8 +48,8 @@ pub struct EventLoop<T: 'static> {
|
|||||||
/// your callback. [`EventLoop`] will coerce into this type (`impl<T> Deref for
|
/// your callback. [`EventLoop`] will coerce into this type (`impl<T> Deref for
|
||||||
/// EventLoop<T>`), so functions that take this as a parameter can also take
|
/// EventLoop<T>`), so functions that take this as a parameter can also take
|
||||||
/// `&EventLoop`.
|
/// `&EventLoop`.
|
||||||
pub struct EventLoopWindowTarget<T: 'static> {
|
pub struct EventLoopWindowTarget {
|
||||||
pub(crate) p: platform_impl::EventLoopWindowTarget<T>,
|
pub(crate) p: platform_impl::EventLoopWindowTarget,
|
||||||
pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync
|
pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,53 +57,48 @@ pub struct EventLoopWindowTarget<T: 'static> {
|
|||||||
///
|
///
|
||||||
/// 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`].
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct EventLoopBuilder<T: 'static> {
|
pub struct EventLoopBuilder<T: 'static> {
|
||||||
pub(crate) platform_specific: platform_impl::PlatformSpecificEventLoopAttributes,
|
pub(crate) platform_specific: platform_impl::PlatformSpecificEventLoopAttributes,
|
||||||
_p: PhantomData<T>,
|
_p: PhantomData<T>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static EVENT_LOOP_CREATED: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
impl EventLoopBuilder<()> {
|
impl EventLoopBuilder<()> {
|
||||||
/// Start building a new event loop.
|
/// Start building a new event loop.
|
||||||
#[inline]
|
#[inline]
|
||||||
|
#[deprecated = "use `EventLoop::builder` instead"]
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self::with_user_event()
|
EventLoop::builder()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoopBuilder<T> {
|
impl<T> EventLoopBuilder<T> {
|
||||||
/// Start building a new event loop, with the given type as the user event
|
|
||||||
/// type.
|
|
||||||
#[inline]
|
|
||||||
pub fn with_user_event() -> Self {
|
|
||||||
Self {
|
|
||||||
platform_specific: Default::default(),
|
|
||||||
_p: PhantomData,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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,
|
||||||
/// and only once per application.***
|
/// and only once per application.***
|
||||||
///
|
///
|
||||||
/// Attempting to create the event loop on a different thread, or multiple event loops in
|
|
||||||
/// the same application, will panic. This restriction isn't
|
|
||||||
/// strictly necessary on all platforms, but is imposed to eliminate any nasty surprises when
|
|
||||||
/// porting to platforms that require it. `EventLoopBuilderExt::any_thread` functions are exposed
|
|
||||||
/// in the relevant [`platform`] module if the target platform supports creating an event loop on
|
|
||||||
/// any thread.
|
|
||||||
///
|
|
||||||
/// Calling this function will result in display backend initialisation.
|
/// Calling this function will result in display backend initialisation.
|
||||||
///
|
///
|
||||||
|
/// ## Panics
|
||||||
|
///
|
||||||
|
/// Attempting to create the event loop off the main thread will panic. This
|
||||||
|
/// restriction isn't strictly necessary on all platforms, but is imposed to
|
||||||
|
/// eliminate any nasty surprises when porting to platforms that require it.
|
||||||
|
/// `EventLoopBuilderExt::any_thread` functions are exposed in the relevant
|
||||||
|
/// [`platform`] module if the target platform supports creating an event
|
||||||
|
/// loop on any thread.
|
||||||
|
///
|
||||||
/// ## Platform-specific
|
/// ## Platform-specific
|
||||||
///
|
///
|
||||||
/// - **Linux:** Backend type can be controlled using an environment variable
|
/// - **Wayland/X11:** to prevent running under `Wayland` or `X11` unset `WAYLAND_DISPLAY`
|
||||||
/// `WINIT_UNIX_BACKEND`. Legal values are `x11` and `wayland`.
|
/// or `DISPLAY` respectively when building the event loop.
|
||||||
/// If it is not set, winit will try to connect to a Wayland connection, and if that fails,
|
/// - **Android:** must be configured with an `AndroidApp` from `android_main()` by calling
|
||||||
/// will fall back on X11. If this variable is set with any other value, winit will panic.
|
/// [`.with_android_app(app)`] before calling `.build()`, otherwise it'll panic.
|
||||||
/// - **Android:** Must be configured with an `AndroidApp` from `android_main()` by calling
|
|
||||||
/// [`.with_android_app(app)`] before calling `.build()`.
|
|
||||||
///
|
///
|
||||||
/// [`platform`]: crate::platform
|
/// [`platform`]: crate::platform
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -110,17 +110,22 @@ impl<T> EventLoopBuilder<T> {
|
|||||||
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) -> EventLoop<T> {
|
pub fn build(&mut self) -> Result<EventLoop<T>, EventLoopError> {
|
||||||
static EVENT_LOOP_CREATED: OnceCell<()> = OnceCell::new();
|
if EVENT_LOOP_CREATED.swap(true, Ordering::Relaxed) {
|
||||||
if EVENT_LOOP_CREATED.set(()).is_err() {
|
return Err(EventLoopError::RecreationAttempt);
|
||||||
panic!("Creating EventLoop multiple times is not supported.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Certain platforms accept a mutable reference in their API.
|
// Certain platforms accept a mutable reference in their API.
|
||||||
#[allow(clippy::unnecessary_mut_passed)]
|
#[allow(clippy::unnecessary_mut_passed)]
|
||||||
EventLoop {
|
Ok(EventLoop {
|
||||||
event_loop: platform_impl::EventLoop::new(&mut self.platform_specific),
|
event_loop: platform_impl::EventLoop::new(&mut self.platform_specific)?,
|
||||||
_marker: PhantomData,
|
_marker: PhantomData,
|
||||||
}
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
pub(crate) fn allow_event_loop_recreation() {
|
||||||
|
EVENT_LOOP_CREATED.store(false, Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,41 +135,27 @@ impl<T> fmt::Debug for EventLoop<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> fmt::Debug for EventLoopWindowTarget<T> {
|
impl fmt::Debug for EventLoopWindowTarget {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.pad("EventLoopWindowTarget { .. }")
|
f.pad("EventLoopWindowTarget { .. }")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set by the user callback given to the [`EventLoop::run`] method.
|
/// Set through [`EventLoopWindowTarget::set_control_flow()`].
|
||||||
///
|
///
|
||||||
/// Indicates the desired behavior of the event loop after [`Event::RedrawEventsCleared`] is emitted.
|
/// Indicates the desired behavior of the event loop after [`Event::AboutToWait`] is emitted.
|
||||||
///
|
///
|
||||||
/// Defaults to [`Poll`].
|
/// Defaults to [`Wait`].
|
||||||
///
|
///
|
||||||
/// ## Persistency
|
/// [`Wait`]: Self::Wait
|
||||||
///
|
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
||||||
/// Almost every change is persistent between multiple calls to the event loop closure within a
|
|
||||||
/// given run loop. The only exception to this is [`ExitWithCode`] which, once set, cannot be unset.
|
|
||||||
/// Changes are **not** persistent between multiple calls to `run_return` - issuing a new call will
|
|
||||||
/// reset the control flow to [`Poll`].
|
|
||||||
///
|
|
||||||
/// [`ExitWithCode`]: Self::ExitWithCode
|
|
||||||
/// [`Poll`]: Self::Poll
|
|
||||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
|
||||||
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.
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// - **Web:** Events are queued and usually sent when `requestAnimationFrame` fires but sometimes
|
|
||||||
/// the events in the queue may be sent before the next `requestAnimationFrame` callback, for
|
|
||||||
/// example when the scaling of the page has changed. This should be treated as an implementation
|
|
||||||
/// detail which should not be relied on.
|
|
||||||
Poll,
|
Poll,
|
||||||
|
|
||||||
/// When the current loop iteration finishes, suspend the thread until another event arrives.
|
/// When the current loop iteration finishes, suspend the thread until another event arrives.
|
||||||
|
#[default]
|
||||||
Wait,
|
Wait,
|
||||||
|
|
||||||
/// 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
|
||||||
@@ -176,131 +167,88 @@ pub enum ControlFlow {
|
|||||||
///
|
///
|
||||||
/// [`Poll`]: Self::Poll
|
/// [`Poll`]: Self::Poll
|
||||||
WaitUntil(Instant),
|
WaitUntil(Instant),
|
||||||
|
|
||||||
/// Send a [`LoopDestroyed`] event and stop the event loop. This variant is *sticky* - once set,
|
|
||||||
/// `control_flow` cannot be changed from `ExitWithCode`, and any future attempts to do so will
|
|
||||||
/// result in the `control_flow` parameter being reset to `ExitWithCode`.
|
|
||||||
///
|
|
||||||
/// The contained number will be used as exit code. The [`Exit`] constant is a shortcut for this
|
|
||||||
/// with exit code 0.
|
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// - **Android / iOS / WASM:** The supplied exit code is unused.
|
|
||||||
/// - **Unix:** On most Unix-like platforms, only the 8 least significant bits will be used,
|
|
||||||
/// which can cause surprises with negative exit values (`-42` would end up as `214`). See
|
|
||||||
/// [`std::process::exit`].
|
|
||||||
///
|
|
||||||
/// [`LoopDestroyed`]: Event::LoopDestroyed
|
|
||||||
/// [`Exit`]: ControlFlow::Exit
|
|
||||||
ExitWithCode(i32),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ControlFlow {
|
impl ControlFlow {
|
||||||
/// Alias for [`ExitWithCode`]`(0)`.
|
/// Creates a [`ControlFlow`] that waits until a timeout has expired.
|
||||||
///
|
|
||||||
/// [`ExitWithCode`]: Self::ExitWithCode
|
|
||||||
#[allow(non_upper_case_globals)]
|
|
||||||
pub const Exit: Self = Self::ExitWithCode(0);
|
|
||||||
|
|
||||||
/// Sets this to [`Poll`].
|
|
||||||
///
|
|
||||||
/// [`Poll`]: Self::Poll
|
|
||||||
pub fn set_poll(&mut self) {
|
|
||||||
*self = Self::Poll;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets this to [`Wait`].
|
|
||||||
///
|
|
||||||
/// [`Wait`]: Self::Wait
|
|
||||||
pub fn set_wait(&mut self) {
|
|
||||||
*self = Self::Wait;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets this to [`WaitUntil`]`(instant)`.
|
|
||||||
///
|
|
||||||
/// [`WaitUntil`]: Self::WaitUntil
|
|
||||||
pub fn set_wait_until(&mut self, instant: Instant) {
|
|
||||||
*self = Self::WaitUntil(instant);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets this to wait until a timeout has expired.
|
|
||||||
///
|
///
|
||||||
/// In most cases, this is set to [`WaitUntil`]. However, if the timeout overflows, it is
|
/// In most cases, this is set to [`WaitUntil`]. However, if the timeout overflows, it is
|
||||||
/// instead set to [`Wait`].
|
/// instead set to [`Wait`].
|
||||||
///
|
///
|
||||||
/// [`WaitUntil`]: Self::WaitUntil
|
/// [`WaitUntil`]: Self::WaitUntil
|
||||||
/// [`Wait`]: Self::Wait
|
/// [`Wait`]: Self::Wait
|
||||||
pub fn set_wait_timeout(&mut self, timeout: Duration) {
|
pub fn wait_duration(timeout: Duration) -> Self {
|
||||||
match Instant::now().checked_add(timeout) {
|
match Instant::now().checked_add(timeout) {
|
||||||
Some(instant) => self.set_wait_until(instant),
|
Some(instant) => Self::WaitUntil(instant),
|
||||||
None => self.set_wait(),
|
None => Self::Wait,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets this to [`ExitWithCode`]`(code)`.
|
|
||||||
///
|
|
||||||
/// [`ExitWithCode`]: Self::ExitWithCode
|
|
||||||
pub fn set_exit_with_code(&mut self, code: i32) {
|
|
||||||
*self = Self::ExitWithCode(code);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets this to [`Exit`].
|
|
||||||
///
|
|
||||||
/// [`Exit`]: Self::Exit
|
|
||||||
pub fn set_exit(&mut self) {
|
|
||||||
*self = Self::Exit;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for ControlFlow {
|
|
||||||
#[inline(always)]
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::Poll
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventLoop<()> {
|
impl EventLoop<()> {
|
||||||
/// Alias for [`EventLoopBuilder::new().build()`].
|
/// Create the event loop.
|
||||||
///
|
///
|
||||||
/// [`EventLoopBuilder::new().build()`]: EventLoopBuilder::build
|
/// This is an alias of `EventLoop::builder().build()`.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn new() -> EventLoop<()> {
|
pub fn new() -> Result<EventLoop<()>, EventLoopError> {
|
||||||
EventLoopBuilder::new().build()
|
Self::builder().build()
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for EventLoop<()> {
|
/// Start building a new event loop.
|
||||||
fn default() -> Self {
|
///
|
||||||
Self::new()
|
/// This returns an [`EventLoopBuilder`], to allow configuring the event loop before creation.
|
||||||
|
///
|
||||||
|
/// To get the actual event loop, call [`build`][EventLoopBuilder::build] on that.
|
||||||
|
#[inline]
|
||||||
|
pub fn builder() -> EventLoopBuilder<()> {
|
||||||
|
Self::with_user_event()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoop<T> {
|
impl<T> EventLoop<T> {
|
||||||
#[deprecated = "Use `EventLoopBuilder::<T>::with_user_event().build()` instead."]
|
/// Start building a new event loop, with the given type as the user event
|
||||||
pub fn with_user_event() -> EventLoop<T> {
|
/// type.
|
||||||
EventLoopBuilder::<T>::with_user_event().build()
|
pub fn with_user_event() -> EventLoopBuilder<T> {
|
||||||
|
EventLoopBuilder {
|
||||||
|
platform_specific: Default::default(),
|
||||||
|
_p: PhantomData,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Hijacks the calling thread and initializes the winit event loop with the provided
|
/// Runs the event loop in the calling thread and calls the given `event_handler` closure
|
||||||
/// closure. Since the closure is `'static`, it must be a `move` closure if it needs to
|
/// to dispatch any pending events.
|
||||||
/// access any data from the calling context.
|
|
||||||
///
|
///
|
||||||
/// See the [`ControlFlow`] docs for information on how changes to `&mut ControlFlow` impact the
|
/// See the [`set_control_flow()`] docs on how to change the event loop's behavior.
|
||||||
/// event loop's behavior.
|
|
||||||
///
|
|
||||||
/// Any values not passed to this function will *not* be dropped.
|
|
||||||
///
|
///
|
||||||
/// ## Platform-specific
|
/// ## Platform-specific
|
||||||
///
|
///
|
||||||
/// - **X11 / Wayland:** The program terminates with exit code 1 if the display server
|
/// - **iOS:** Will never return to the caller and so values not passed to this function will
|
||||||
/// disconnects.
|
/// *not* be dropped before the process exits.
|
||||||
|
/// - **Web:** Will _act_ as if it never returns to the caller by throwing a Javascript exception
|
||||||
|
/// (that Rust doesn't see) that will also mean that the rest of the function is never executed
|
||||||
|
/// and any values not passed to this function will *not* be dropped.
|
||||||
///
|
///
|
||||||
/// [`ControlFlow`]: crate::event_loop::ControlFlow
|
/// Web applications are recommended to use
|
||||||
|
#[cfg_attr(
|
||||||
|
web_platform,
|
||||||
|
doc = "[`EventLoopExtWebSys::spawn()`][crate::platform::web::EventLoopExtWebSys::spawn()]"
|
||||||
|
)]
|
||||||
|
#[cfg_attr(not(web_platform), doc = "`EventLoopExtWebSys::spawn()`")]
|
||||||
|
/// [^1] instead of [`run()`] to avoid the need
|
||||||
|
/// for the Javascript exception trick, and to make it clearer that the event loop runs
|
||||||
|
/// asynchronously (via the browser's own, internal, event loop) and doesn't block the
|
||||||
|
/// current thread of execution like it does on other platforms.
|
||||||
|
///
|
||||||
|
/// This function won't be available with `target_feature = "exception-handling"`.
|
||||||
|
///
|
||||||
|
/// [`set_control_flow()`]: EventLoopWindowTarget::set_control_flow()
|
||||||
|
/// [`run()`]: Self::run()
|
||||||
|
/// [^1]: `EventLoopExtWebSys::spawn()` is only available on Web.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn run<F>(self, event_handler: F) -> !
|
#[cfg(not(all(web_platform, target_feature = "exception-handling")))]
|
||||||
|
pub fn run<F>(self, event_handler: F) -> Result<(), EventLoopError>
|
||||||
where
|
where
|
||||||
F: 'static + FnMut(Event<'_, T>, &EventLoopWindowTarget<T>, &mut ControlFlow),
|
F: FnMut(Event<T>, &EventLoopWindowTarget),
|
||||||
{
|
{
|
||||||
self.event_loop.run(event_handler)
|
self.event_loop.run(event_handler)
|
||||||
}
|
}
|
||||||
@@ -313,17 +261,61 @@ impl<T> EventLoop<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_06")]
|
||||||
|
impl<T> rwh_06::HasDisplayHandle for EventLoop<T> {
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
rwh_06::HasDisplayHandle::display_handle(&**self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
impl<T> AsFd for EventLoop<T> {
|
||||||
|
/// Get the underlying [EventLoop]'s `fd` which you can register
|
||||||
|
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
||||||
|
/// loop must be polled with the [`pump_events`] API.
|
||||||
|
///
|
||||||
|
/// [`calloop`]: https://crates.io/crates/calloop
|
||||||
|
/// [`mio`]: https://crates.io/crates/mio
|
||||||
|
/// [`pump_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_events
|
||||||
|
fn as_fd(&self) -> BorrowedFd<'_> {
|
||||||
|
self.event_loop.as_fd()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
impl<T> AsRawFd for EventLoop<T> {
|
||||||
|
/// Get the underlying [EventLoop]'s raw `fd` which you can register
|
||||||
|
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
||||||
|
/// loop must be polled with the [`pump_events`] API.
|
||||||
|
///
|
||||||
|
/// [`calloop`]: https://crates.io/crates/calloop
|
||||||
|
/// [`mio`]: https://crates.io/crates/mio
|
||||||
|
/// [`pump_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_events
|
||||||
|
fn as_raw_fd(&self) -> RawFd {
|
||||||
|
self.event_loop.as_raw_fd()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl<T> Deref for EventLoop<T> {
|
impl<T> Deref for EventLoop<T> {
|
||||||
type Target = EventLoopWindowTarget<T>;
|
type Target = EventLoopWindowTarget;
|
||||||
fn deref(&self) -> &EventLoopWindowTarget<T> {
|
fn deref(&self) -> &EventLoopWindowTarget {
|
||||||
self.event_loop.window_target()
|
self.event_loop.window_target()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoopWindowTarget<T> {
|
impl EventLoopWindowTarget {
|
||||||
/// Returns the list of all the monitors available on the system.
|
/// Returns the list of all the monitors available on the system.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
|
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
|
||||||
|
#[allow(clippy::useless_conversion)] // false positive on some platforms
|
||||||
self.p
|
self.p
|
||||||
.available_monitors()
|
.available_monitors()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -336,7 +328,7 @@ impl<T> EventLoopWindowTarget<T> {
|
|||||||
///
|
///
|
||||||
/// ## Platform-specific
|
/// ## Platform-specific
|
||||||
///
|
///
|
||||||
/// **Wayland:** Always returns `None`.
|
/// **Wayland / Web:** Always returns `None`.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||||
self.p
|
self.p
|
||||||
@@ -344,27 +336,115 @@ impl<T> EventLoopWindowTarget<T> {
|
|||||||
.map(|inner| MonitorHandle { inner })
|
.map(|inner| MonitorHandle { inner })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Change [`DeviceEvent`] filter mode.
|
/// Change if or when [`DeviceEvent`]s are captured.
|
||||||
///
|
///
|
||||||
/// Since the [`DeviceEvent`] capture can lead to high CPU usage for unfocused windows, winit
|
/// Since the [`DeviceEvent`] capture can lead to high CPU usage for unfocused windows, winit
|
||||||
/// will ignore them by default for unfocused windows on Linux/BSD. This method allows changing
|
/// will ignore them by default for unfocused windows on Linux/BSD. This method allows changing
|
||||||
/// this filter at runtime to explicitly capture them again.
|
/// this at runtime to explicitly capture them again.
|
||||||
///
|
///
|
||||||
/// ## Platform-specific
|
/// ## Platform-specific
|
||||||
///
|
///
|
||||||
/// - **Wayland / macOS / iOS / Android / Web / Orbital:** Unsupported.
|
/// - **Wayland / macOS / iOS / Android / Orbital:** Unsupported.
|
||||||
///
|
///
|
||||||
/// [`DeviceEvent`]: crate::event::DeviceEvent
|
/// [`DeviceEvent`]: crate::event::DeviceEvent
|
||||||
pub fn set_device_event_filter(&self, _filter: DeviceEventFilter) {
|
pub fn listen_device_events(&self, allowed: DeviceEvents) {
|
||||||
#[cfg(any(x11_platform, wayland_platform, windows))]
|
self.p.listen_device_events(allowed);
|
||||||
self.p.set_device_event_filter(_filter);
|
}
|
||||||
|
|
||||||
|
/// Sets the [`ControlFlow`].
|
||||||
|
pub fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||||
|
self.p.set_control_flow(control_flow)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets the current [`ControlFlow`].
|
||||||
|
pub fn control_flow(&self) -> ControlFlow {
|
||||||
|
self.p.control_flow()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This exits the event loop.
|
||||||
|
///
|
||||||
|
/// See [`LoopExiting`](Event::LoopExiting).
|
||||||
|
pub fn exit(&self) {
|
||||||
|
self.p.exit()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns if the [`EventLoop`] is about to stop.
|
||||||
|
///
|
||||||
|
/// See [`exit()`](Self::exit).
|
||||||
|
pub fn exiting(&self) -> bool {
|
||||||
|
self.p.exiting()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets a persistent reference to the underlying platform display.
|
||||||
|
///
|
||||||
|
/// See the [`OwnedDisplayHandle`] type for more information.
|
||||||
|
pub fn owned_display_handle(&self) -> OwnedDisplayHandle {
|
||||||
|
OwnedDisplayHandle {
|
||||||
|
platform: self.p.owned_display_handle(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe impl<T> HasRawDisplayHandle for EventLoopWindowTarget<T> {
|
#[cfg(feature = "rwh_06")]
|
||||||
/// Returns a [`raw_window_handle::RawDisplayHandle`] for the event loop.
|
impl rwh_06::HasDisplayHandle for EventLoopWindowTarget {
|
||||||
fn raw_display_handle(&self) -> RawDisplayHandle {
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
self.p.raw_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 EventLoopWindowTarget {
|
||||||
|
/// Returns a [`rwh_05::RawDisplayHandle`] for the event loop.
|
||||||
|
fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
|
||||||
|
self.p.raw_display_handle_rwh_05()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A proxy for the underlying display handle.
|
||||||
|
///
|
||||||
|
/// The purpose of this type is to provide a cheaply clonable handle to the underlying
|
||||||
|
/// display handle. This is often used by graphics APIs to connect to the underlying APIs.
|
||||||
|
/// It is difficult to keep a handle to the [`EventLoop`] type or the [`EventLoopWindowTarget`]
|
||||||
|
/// type. In contrast, this type involves no lifetimes and can be persisted for as long as
|
||||||
|
/// needed.
|
||||||
|
///
|
||||||
|
/// For all platforms, this is one of the following:
|
||||||
|
///
|
||||||
|
/// - A zero-sized type that is likely optimized out.
|
||||||
|
/// - A reference-counted pointer to the underlying type.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct OwnedDisplayHandle {
|
||||||
|
#[cfg_attr(not(any(feature = "rwh_05", feature = "rwh_06")), allow(dead_code))]
|
||||||
|
platform: platform_impl::OwnedDisplayHandle,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for OwnedDisplayHandle {
|
||||||
|
#[inline]
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("OwnedDisplayHandle").finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_06")]
|
||||||
|
impl rwh_06::HasDisplayHandle for OwnedDisplayHandle {
|
||||||
|
#[inline]
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let raw = self.platform.raw_display_handle_rwh_06()?;
|
||||||
|
|
||||||
|
// SAFETY: The underlying display handle should be safe.
|
||||||
|
let handle = unsafe { rwh_06::DisplayHandle::borrow_raw(raw) };
|
||||||
|
|
||||||
|
Ok(handle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_05")]
|
||||||
|
unsafe impl rwh_05::HasRawDisplayHandle for OwnedDisplayHandle {
|
||||||
|
#[inline]
|
||||||
|
fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
|
||||||
|
self.platform.raw_display_handle_rwh_05()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -415,19 +495,40 @@ impl<T> fmt::Display for EventLoopClosed<T> {
|
|||||||
|
|
||||||
impl<T: fmt::Debug> error::Error for EventLoopClosed<T> {}
|
impl<T: fmt::Debug> error::Error for EventLoopClosed<T> {}
|
||||||
|
|
||||||
/// Filter controlling the propagation of device events.
|
/// Control when device events are captured.
|
||||||
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
|
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
|
||||||
pub enum DeviceEventFilter {
|
pub enum DeviceEvents {
|
||||||
/// Always filter out device events.
|
/// Report device events regardless of window focus.
|
||||||
Always,
|
Always,
|
||||||
/// Filter out device events while the window is not focused.
|
/// Only capture device events while the window is focused.
|
||||||
Unfocused,
|
#[default]
|
||||||
/// Report all device events regardless of window focus.
|
WhenFocused,
|
||||||
|
/// Never capture device events.
|
||||||
Never,
|
Never,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for DeviceEventFilter {
|
/// A unique identifier of the winit's async request.
|
||||||
fn default() -> Self {
|
///
|
||||||
Self::Unfocused
|
/// This could be used to identify the async request once it's done
|
||||||
|
/// and a specific action must be taken.
|
||||||
|
///
|
||||||
|
/// One of the handling scenarious could be to maintain a working list
|
||||||
|
/// containing [`AsyncRequestSerial`] and some closure associated with it.
|
||||||
|
/// Then once event is arriving the working list is being traversed and a job
|
||||||
|
/// executed and removed from the list.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct AsyncRequestSerial {
|
||||||
|
serial: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsyncRequestSerial {
|
||||||
|
// TODO(kchibisov): Remove `cfg` when the clipboard will be added.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) fn get() -> Self {
|
||||||
|
static CURRENT_SERIAL: AtomicUsize = AtomicUsize::new(0);
|
||||||
|
// NOTE: We rely on wrap around here, while the user may just request
|
||||||
|
// in the loop usize::MAX times that's issue is considered on them.
|
||||||
|
let serial = CURRENT_SERIAL.fetch_add(1, Ordering::Relaxed);
|
||||||
|
Self { serial }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,11 +49,7 @@ impl fmt::Display for BadIcon {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Error for BadIcon {
|
impl Error for BadIcon {}
|
||||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
|
||||||
Some(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub(crate) struct RgbaIcon {
|
pub(crate) struct RgbaIcon {
|
||||||
|
|||||||
1801
src/keyboard.rs
Normal file
124
src/lib.rs
@@ -7,15 +7,15 @@
|
|||||||
//!
|
//!
|
||||||
//! ```no_run
|
//! ```no_run
|
||||||
//! use winit::event_loop::EventLoop;
|
//! use winit::event_loop::EventLoop;
|
||||||
//! let event_loop = EventLoop::new();
|
//! let event_loop = EventLoop::new().unwrap();
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! Once this is done there are two ways to create a [`Window`]:
|
//! Once this is done, there are two ways to create a [`Window`]:
|
||||||
//!
|
//!
|
||||||
//! - Calling [`Window::new(&event_loop)`][window_new].
|
//! - Calling [`Window::new(&event_loop)`][window_new].
|
||||||
//! - Calling [`let builder = WindowBuilder::new()`][window_builder_new] then [`builder.build(&event_loop)`][window_builder_build].
|
//! - Calling [`let builder = Window::builder()`][window_builder_new] then [`builder.build(&event_loop)`][window_builder_build].
|
||||||
//!
|
//!
|
||||||
//! The first method is the simplest, and will give you default values for everything. The second
|
//! The first method is the simplest and will give you default values for everything. The second
|
||||||
//! method allows you to customize the way your [`Window`] will look and behave by modifying the
|
//! method allows you to customize the way your [`Window`] will look and behave by modifying the
|
||||||
//! fields of the [`WindowBuilder`] object before you create the [`Window`].
|
//! fields of the [`WindowBuilder`] object before you create the [`Window`].
|
||||||
//!
|
//!
|
||||||
@@ -26,64 +26,85 @@
|
|||||||
//! 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 [`UserEvent`]s, if desired.
|
//! [`DeviceEvent`]. You can also create and handle your own custom [`Event::UserEvent`]s, if desired.
|
||||||
//!
|
//!
|
||||||
//! You can retrieve events by calling [`EventLoop::run`][event_loop_run]. This function will
|
//! You can retrieve events by calling [`EventLoop::run()`]. 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 the `control_flow` argument given to the closure is set to
|
//! will run until [`exit()`] is used, at which point [`Event::LoopExiting`].
|
||||||
//! [`ControlFlow`]`::`[`ExitWithCode`] (which [`ControlFlow`]`::`[`Exit`] aliases to), at which
|
|
||||||
//! point [`Event`]`::`[`LoopDestroyed`] is emitted and the entire program terminates.
|
|
||||||
//!
|
//!
|
||||||
//! 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 poorly on
|
||||||
//! most other platforms. However, this model can be re-implemented to an extent with
|
//! most other platforms. However, this model can be re-implemented to an extent with
|
||||||
//! [`EventLoopExtRunReturn::run_return`]. See that method's documentation for more reasons about why
|
#![cfg_attr(
|
||||||
//! it's discouraged, beyond compatibility reasons.
|
any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
android_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform
|
||||||
|
),
|
||||||
|
doc = "[`EventLoopExtPumpEvents::pump_events()`][platform::pump_events::EventLoopExtPumpEvents::pump_events()]"
|
||||||
|
)]
|
||||||
|
#![cfg_attr(
|
||||||
|
not(any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
android_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform
|
||||||
|
)),
|
||||||
|
doc = "`EventLoopExtPumpEvents::pump_events()`"
|
||||||
|
)]
|
||||||
|
//! [^1]. See that method's documentation for more reasons about why
|
||||||
|
//! it's discouraged beyond compatibility reasons.
|
||||||
//!
|
//!
|
||||||
//!
|
//!
|
||||||
//! ```no_run
|
//! ```no_run
|
||||||
//! use winit::{
|
//! use winit::{
|
||||||
//! event::{Event, WindowEvent},
|
//! event::{Event, WindowEvent},
|
||||||
//! event_loop::EventLoop,
|
//! event_loop::{ControlFlow, EventLoop},
|
||||||
//! window::WindowBuilder,
|
//! window::Window,
|
||||||
//! };
|
//! };
|
||||||
//!
|
//!
|
||||||
//! let event_loop = EventLoop::new();
|
//! let event_loop = EventLoop::new().unwrap();
|
||||||
//! let window = WindowBuilder::new().build(&event_loop).unwrap();
|
//! let window = Window::builder().build(&event_loop).unwrap();
|
||||||
//!
|
//!
|
||||||
//! event_loop.run(move |event, _, control_flow| {
|
//! // 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);
|
||||||
//! control_flow.set_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.
|
||||||
//! control_flow.set_wait();
|
//! event_loop.set_control_flow(ControlFlow::Wait);
|
||||||
//!
|
//!
|
||||||
|
//! event_loop.run(move |event, elwt| {
|
||||||
//! match event {
|
//! match event {
|
||||||
//! Event::WindowEvent {
|
//! Event::WindowEvent {
|
||||||
//! event: WindowEvent::CloseRequested,
|
//! event: WindowEvent::CloseRequested,
|
||||||
//! ..
|
//! ..
|
||||||
//! } => {
|
//! } => {
|
||||||
//! println!("The close button was pressed; stopping");
|
//! println!("The close button was pressed; stopping");
|
||||||
//! control_flow.set_exit();
|
//! elwt.exit();
|
||||||
//! },
|
//! },
|
||||||
//! Event::MainEventsCleared => {
|
//! Event::AboutToWait => {
|
||||||
//! // Application update code.
|
//! // Application update code.
|
||||||
//!
|
//!
|
||||||
//! // Queue a RedrawRequested event.
|
//! // Queue a RedrawRequested event.
|
||||||
//! //
|
//! //
|
||||||
//! // You only need to call this if you've determined that you need to redraw, in
|
//! // You only need to call this if you've determined that you need to redraw in
|
||||||
//! // applications which do not always need to. Applications that redraw continuously
|
//! // applications which do not always need to. Applications that redraw continuously
|
||||||
//! // can just render here instead.
|
//! // can render here instead.
|
||||||
//! window.request_redraw();
|
//! window.request_redraw();
|
||||||
//! },
|
//! },
|
||||||
//! Event::RedrawRequested(_) => {
|
//! Event::WindowEvent {
|
||||||
|
//! event: WindowEvent::RedrawRequested,
|
||||||
|
//! ..
|
||||||
|
//! } => {
|
||||||
//! // Redraw the application.
|
//! // Redraw the application.
|
||||||
//! //
|
//! //
|
||||||
//! // It's preferable for applications that do not render continuously to render in
|
//! // It's preferable for applications that do not render continuously to render in
|
||||||
//! // this event rather than in MainEventsCleared, since rendering in here allows
|
//! // this event rather than in AboutToWait, since rendering in here allows
|
||||||
//! // the program to gracefully handle redraws requested by the OS.
|
//! // the program to gracefully handle redraws requested by the OS.
|
||||||
//! },
|
//! },
|
||||||
//! _ => ()
|
//! _ => ()
|
||||||
@@ -91,16 +112,16 @@
|
|||||||
//! });
|
//! });
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! [`Event`]`::`[`WindowEvent`] has a [`WindowId`] member. In multi-window environments, it should be
|
//! [`WindowEvent`] has a [`WindowId`] member. In multi-window environments, it should be
|
||||||
//! compared to the value returned by [`Window::id()`][window_id_fn] to determine which [`Window`]
|
//! compared to the value returned by [`Window::id()`] to determine which [`Window`]
|
||||||
//! dispatched the event.
|
//! dispatched the event.
|
||||||
//!
|
//!
|
||||||
//! # 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 to
|
||||||
//! retrieve the raw handle of the window and display (see the [`platform`] module and/or the
|
//! 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
|
||||||
@@ -109,51 +130,48 @@
|
|||||||
//! window visible only once you're ready to render into it.
|
//! window visible only once you're ready to render into it.
|
||||||
//!
|
//!
|
||||||
//! [`EventLoop`]: event_loop::EventLoop
|
//! [`EventLoop`]: event_loop::EventLoop
|
||||||
//! [`EventLoopExtRunReturn::run_return`]: ./platform/run_return/trait.EventLoopExtRunReturn.html#tymethod.run_return
|
|
||||||
//! [`EventLoop::new()`]: event_loop::EventLoop::new
|
//! [`EventLoop::new()`]: event_loop::EventLoop::new
|
||||||
//! [event_loop_run]: event_loop::EventLoop::run
|
//! [`EventLoop::run()`]: event_loop::EventLoop::run
|
||||||
//! [`ControlFlow`]: event_loop::ControlFlow
|
//! [`exit()`]: event_loop::EventLoopWindowTarget::exit
|
||||||
//! [`Exit`]: event_loop::ControlFlow::Exit
|
|
||||||
//! [`ExitWithCode`]: event_loop::ControlFlow::ExitWithCode
|
|
||||||
//! [`Window`]: window::Window
|
//! [`Window`]: window::Window
|
||||||
//! [`WindowId`]: window::WindowId
|
//! [`WindowId`]: window::WindowId
|
||||||
//! [`WindowBuilder`]: window::WindowBuilder
|
//! [`WindowBuilder`]: window::WindowBuilder
|
||||||
//! [window_new]: window::Window::new
|
//! [window_new]: window::Window::new
|
||||||
//! [window_builder_new]: window::WindowBuilder::new
|
//! [window_builder_new]: window::Window::builder
|
||||||
//! [window_builder_build]: window::WindowBuilder::build
|
//! [window_builder_build]: window::WindowBuilder::build
|
||||||
//! [window_id_fn]: window::Window::id
|
//! [`Window::id()`]: window::Window::id
|
||||||
//! [`Event`]: event::Event
|
|
||||||
//! [`WindowEvent`]: event::WindowEvent
|
//! [`WindowEvent`]: event::WindowEvent
|
||||||
//! [`DeviceEvent`]: event::DeviceEvent
|
//! [`DeviceEvent`]: event::DeviceEvent
|
||||||
//! [`UserEvent`]: event::Event::UserEvent
|
//! [`Event::UserEvent`]: event::Event::UserEvent
|
||||||
//! [`LoopDestroyed`]: event::Event::LoopDestroyed
|
//! [`Event::LoopExiting`]: event::Event::LoopExiting
|
||||||
//! [`platform`]: platform
|
|
||||||
//! [`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_events()` is only available on Windows, macOS, Android, X11 and Wayland.
|
||||||
|
|
||||||
#![deny(rust_2018_idioms)]
|
#![deny(rust_2018_idioms)]
|
||||||
#![deny(rustdoc::broken_intra_doc_links)]
|
#![deny(rustdoc::broken_intra_doc_links)]
|
||||||
#![deny(clippy::all)]
|
#![deny(clippy::all)]
|
||||||
|
#![deny(unsafe_op_in_unsafe_fn)]
|
||||||
#![cfg_attr(feature = "cargo-clippy", deny(warnings))]
|
#![cfg_attr(feature = "cargo-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 doc
|
||||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
#![cfg_attr(
|
||||||
|
docsrs,
|
||||||
|
feature(doc_auto_cfg, doc_cfg_hide),
|
||||||
|
doc(cfg_hide(doc, docsrs))
|
||||||
|
)]
|
||||||
#![allow(clippy::missing_safety_doc)]
|
#![allow(clippy::missing_safety_doc)]
|
||||||
|
|
||||||
#[allow(unused_imports)]
|
#[cfg(feature = "rwh_06")]
|
||||||
#[macro_use]
|
pub use rwh_06 as raw_window_handle;
|
||||||
extern crate log;
|
|
||||||
#[cfg(feature = "serde")]
|
|
||||||
#[macro_use]
|
|
||||||
extern crate serde;
|
|
||||||
#[macro_use]
|
|
||||||
extern crate bitflags;
|
|
||||||
|
|
||||||
pub mod dpi;
|
pub mod dpi;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
pub mod error;
|
pub mod error;
|
||||||
|
mod cursor;
|
||||||
pub mod event;
|
pub mod event;
|
||||||
pub mod event_loop;
|
pub mod event_loop;
|
||||||
mod icon;
|
mod icon;
|
||||||
|
pub mod keyboard;
|
||||||
pub mod monitor;
|
pub mod monitor;
|
||||||
mod platform_impl;
|
mod platform_impl;
|
||||||
pub mod window;
|
pub mod window;
|
||||||
|
|||||||
@@ -10,34 +10,35 @@ use crate::{
|
|||||||
platform_impl,
|
platform_impl,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// Deprecated! Use `VideoModeHandle` instead.
|
||||||
|
#[deprecated = "Renamed to `VideoModeHandle`"]
|
||||||
|
pub type VideoMode = VideoModeHandle;
|
||||||
|
|
||||||
/// Describes a fullscreen video mode of a monitor.
|
/// Describes a fullscreen video mode of a monitor.
|
||||||
///
|
///
|
||||||
/// Can be acquired with [`MonitorHandle::video_modes`].
|
/// Can be acquired with [`MonitorHandle::video_modes`].
|
||||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||||
pub struct VideoMode {
|
pub struct VideoModeHandle {
|
||||||
pub(crate) video_mode: platform_impl::VideoMode,
|
pub(crate) video_mode: platform_impl::VideoModeHandle,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Debug for VideoMode {
|
impl std::fmt::Debug for VideoModeHandle {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
self.video_mode.fmt(f)
|
self.video_mode.fmt(f)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PartialOrd for VideoMode {
|
impl PartialOrd for VideoModeHandle {
|
||||||
fn partial_cmp(&self, other: &VideoMode) -> Option<std::cmp::Ordering> {
|
fn partial_cmp(&self, other: &VideoModeHandle) -> Option<std::cmp::Ordering> {
|
||||||
Some(self.cmp(other))
|
Some(self.cmp(other))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Ord for VideoMode {
|
impl Ord for VideoModeHandle {
|
||||||
fn cmp(&self, other: &VideoMode) -> std::cmp::Ordering {
|
fn cmp(&self, other: &VideoModeHandle) -> std::cmp::Ordering {
|
||||||
// TODO: we can impl `Ord` for `PhysicalSize` once we switch from `f32`
|
|
||||||
// to `u32` there
|
|
||||||
let size: (u32, u32) = self.size().into();
|
|
||||||
let other_size: (u32, u32) = other.size().into();
|
|
||||||
self.monitor().cmp(&other.monitor()).then(
|
self.monitor().cmp(&other.monitor()).then(
|
||||||
size.cmp(&other_size)
|
self.size()
|
||||||
|
.cmp(&other.size())
|
||||||
.then(
|
.then(
|
||||||
self.refresh_rate_millihertz()
|
self.refresh_rate_millihertz()
|
||||||
.cmp(&other.refresh_rate_millihertz())
|
.cmp(&other.refresh_rate_millihertz())
|
||||||
@@ -48,7 +49,7 @@ impl Ord for VideoMode {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl VideoMode {
|
impl VideoModeHandle {
|
||||||
/// Returns the resolution of this video mode.
|
/// Returns the resolution of this video mode.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn size(&self) -> PhysicalSize<u32> {
|
pub fn size(&self) -> PhysicalSize<u32> {
|
||||||
@@ -84,7 +85,7 @@ impl VideoMode {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Display for VideoMode {
|
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,
|
||||||
@@ -111,20 +112,12 @@ 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
|
|
||||||
#[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 monitor's resolution.
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// - **Web:** Always returns (0,0)
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn size(&self) -> PhysicalSize<u32> {
|
pub fn size(&self) -> PhysicalSize<u32> {
|
||||||
self.inner.size()
|
self.inner.size()
|
||||||
@@ -132,10 +125,6 @@ impl MonitorHandle {
|
|||||||
|
|
||||||
/// Returns the top-left corner position of the monitor relative to the larger full
|
/// Returns the top-left corner position of the monitor relative to the larger full
|
||||||
/// screen area.
|
/// screen area.
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// - **Web:** Always returns (0,0)
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn position(&self) -> PhysicalPosition<i32> {
|
pub fn position(&self) -> PhysicalPosition<i32> {
|
||||||
self.inner.position()
|
self.inner.position()
|
||||||
@@ -146,22 +135,25 @@ impl MonitorHandle {
|
|||||||
/// Return `Some` if succeed, or `None` if failed, which usually happens when the monitor
|
/// Return `Some` if succeed, or `None` if failed, which usually happens when the monitor
|
||||||
/// the window is on is removed.
|
/// the window is on is removed.
|
||||||
///
|
///
|
||||||
/// When using exclusive fullscreen, the refresh rate of the [`VideoMode`] that was used to
|
/// When using exclusive fullscreen, the refresh rate of the [`VideoModeHandle`] that was
|
||||||
/// enter fullscreen should be used instead.
|
/// used to enter fullscreen should be used instead.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn refresh_rate_millihertz(&self) -> Option<u32> {
|
pub fn refresh_rate_millihertz(&self) -> Option<u32> {
|
||||||
self.inner.refresh_rate_millihertz()
|
self.inner.refresh_rate_millihertz()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
|
/// Returns the scale factor of the underlying monitor. To map logical pixels to physical
|
||||||
|
/// pixels and vice versa, use [`Window::scale_factor`].
|
||||||
///
|
///
|
||||||
/// See the [`dpi`](crate::dpi) module for more information.
|
/// See the [`dpi`](crate::dpi) module for more information.
|
||||||
///
|
///
|
||||||
/// ## Platform-specific
|
/// ## Platform-specific
|
||||||
///
|
///
|
||||||
/// - **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`].
|
||||||
/// - **Android:** Always returns 1.0.
|
/// - **Android:** Always returns 1.0.
|
||||||
/// - **Web:** Always returns 1.0
|
///
|
||||||
|
/// [`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()
|
||||||
@@ -173,9 +165,9 @@ impl MonitorHandle {
|
|||||||
///
|
///
|
||||||
/// - **Web:** Always returns an empty iterator
|
/// - **Web:** Always returns an empty iterator
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn video_modes(&self) -> impl Iterator<Item = VideoMode> {
|
pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> {
|
||||||
self.inner
|
self.inner
|
||||||
.video_modes()
|
.video_modes()
|
||||||
.map(|video_mode| VideoMode { video_mode })
|
.map(|video_mode| VideoModeHandle { video_mode })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use crate::{
|
|||||||
window::{Window, WindowBuilder},
|
window::{Window, WindowBuilder},
|
||||||
};
|
};
|
||||||
|
|
||||||
use android_activity::{AndroidApp, ConfigurationRef, Rect};
|
use self::activity::{AndroidApp, ConfigurationRef, Rect};
|
||||||
|
|
||||||
/// Additional methods on [`EventLoop`] that are specific to Android.
|
/// Additional methods on [`EventLoop`] that are specific to Android.
|
||||||
pub trait EventLoopExtAndroid {}
|
pub trait EventLoopExtAndroid {}
|
||||||
@@ -30,7 +30,7 @@ impl WindowExtAndroid for Window {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoopWindowTargetExtAndroid for EventLoopWindowTarget<T> {}
|
impl EventLoopWindowTargetExtAndroid for EventLoopWindowTarget {}
|
||||||
|
|
||||||
/// Additional methods on [`WindowBuilder`] that are specific to Android.
|
/// Additional methods on [`WindowBuilder`] that are specific to Android.
|
||||||
pub trait WindowBuilderExtAndroid {}
|
pub trait WindowBuilderExtAndroid {}
|
||||||
@@ -42,6 +42,11 @@ pub trait EventLoopBuilderExtAndroid {
|
|||||||
///
|
///
|
||||||
/// 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
|
||||||
|
///
|
||||||
|
/// Default is to let the operating system handle the volume keys
|
||||||
|
fn handle_volume_keys(&mut self) -> &mut Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoopBuilderExtAndroid for EventLoopBuilder<T> {
|
impl<T> EventLoopBuilderExtAndroid for EventLoopBuilder<T> {
|
||||||
@@ -49,6 +54,11 @@ impl<T> EventLoopBuilderExtAndroid for EventLoopBuilder<T> {
|
|||||||
self.platform_specific.android_app = Some(app);
|
self.platform_specific.android_app = Some(app);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn handle_volume_keys(&mut self) -> &mut Self {
|
||||||
|
self.platform_specific.ignore_volume_keys = false;
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Re-export of the `android_activity` API
|
/// Re-export of the `android_activity` API
|
||||||
@@ -74,5 +84,21 @@ impl<T> EventLoopBuilderExtAndroid for EventLoopBuilder<T> {
|
|||||||
/// use winit::platform::android::activity::AndroidApp;
|
/// use winit::platform::android::activity::AndroidApp;
|
||||||
/// ```
|
/// ```
|
||||||
pub mod activity {
|
pub mod activity {
|
||||||
|
// We enable the `"native-activity"` feature just so that we can build the
|
||||||
|
// docs, but it'll be very confusing for users to see the docs with that
|
||||||
|
// feature enabled, so we avoid inlining it so that they're forced to view
|
||||||
|
// it on the crate's own docs.rs page.
|
||||||
|
#[doc(no_inline)]
|
||||||
|
#[cfg(android_platform)]
|
||||||
pub use android_activity::*;
|
pub use android_activity::*;
|
||||||
|
|
||||||
|
#[cfg(not(android_platform))]
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub struct Rect;
|
||||||
|
#[cfg(not(android_platform))]
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub struct ConfigurationRef;
|
||||||
|
#[cfg(not(android_platform))]
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub struct AndroidApp;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
use std::os::raw::c_void;
|
use std::os::raw::c_void;
|
||||||
|
|
||||||
use objc2::rc::Id;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
event_loop::EventLoop,
|
event_loop::EventLoop,
|
||||||
monitor::{MonitorHandle, VideoMode},
|
monitor::{MonitorHandle, VideoModeHandle},
|
||||||
window::{Window, WindowBuilder},
|
window::{Window, WindowBuilder},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -22,27 +20,6 @@ impl<T: 'static> EventLoopExtIOS for EventLoop<T> {
|
|||||||
|
|
||||||
/// Additional methods on [`Window`] that are specific to iOS.
|
/// Additional methods on [`Window`] that are specific to iOS.
|
||||||
pub trait WindowExtIOS {
|
pub trait WindowExtIOS {
|
||||||
/// Returns a pointer to the [`UIWindow`] that is used by this window.
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the [`Window`] is destroyed.
|
|
||||||
///
|
|
||||||
/// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc
|
|
||||||
fn ui_window(&self) -> *mut c_void;
|
|
||||||
|
|
||||||
/// Returns a pointer to the [`UIViewController`] that is used by this window.
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the [`Window`] is destroyed.
|
|
||||||
///
|
|
||||||
/// [`UIViewController`]: https://developer.apple.com/documentation/uikit/uiviewcontroller?language=objc
|
|
||||||
fn ui_view_controller(&self) -> *mut c_void;
|
|
||||||
|
|
||||||
/// Returns a pointer to the [`UIView`] that is used by this window.
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the [`Window`] is destroyed.
|
|
||||||
///
|
|
||||||
/// [`UIView`]: https://developer.apple.com/documentation/uikit/uiview?language=objc
|
|
||||||
fn ui_view(&self) -> *mut c_void;
|
|
||||||
|
|
||||||
/// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `scale_factor`.
|
/// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `scale_factor`.
|
||||||
///
|
///
|
||||||
/// The default value is device dependent, and it's recommended GLES or Metal applications set
|
/// The default value is device dependent, and it's recommended GLES or Metal applications set
|
||||||
@@ -89,53 +66,96 @@ pub trait WindowExtIOS {
|
|||||||
///
|
///
|
||||||
/// The default is to prefer showing the status bar.
|
/// The default is to prefer showing the status bar.
|
||||||
///
|
///
|
||||||
/// This changes the value returned by
|
/// This sets the value of the
|
||||||
/// [`-[UIViewController prefersStatusBarHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621440-prefersstatusbarhidden?language=objc),
|
/// [`prefersStatusBarHidden`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621440-prefersstatusbarhidden?language=objc)
|
||||||
/// and then calls
|
/// property.
|
||||||
/// [`-[UIViewController setNeedsStatusBarAppearanceUpdate]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621354-setneedsstatusbarappearanceupdat?language=objc).
|
///
|
||||||
|
/// [`setNeedsStatusBarAppearanceUpdate()`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621354-setneedsstatusbarappearanceupdat?language=objc)
|
||||||
|
/// is also called for you.
|
||||||
fn set_prefers_status_bar_hidden(&self, hidden: bool);
|
fn set_prefers_status_bar_hidden(&self, hidden: bool);
|
||||||
|
|
||||||
|
/// Sets the preferred status bar style for the [`Window`].
|
||||||
|
///
|
||||||
|
/// The default is system-defined.
|
||||||
|
///
|
||||||
|
/// This sets the value of the
|
||||||
|
/// [`preferredStatusBarStyle`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621416-preferredstatusbarstyle?language=objc)
|
||||||
|
/// property.
|
||||||
|
///
|
||||||
|
/// [`setNeedsStatusBarAppearanceUpdate()`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621354-setneedsstatusbarappearanceupdat?language=objc)
|
||||||
|
/// is also called for you.
|
||||||
|
fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle);
|
||||||
|
|
||||||
|
/// Sets whether the [`Window`] should recognize pinch gestures.
|
||||||
|
///
|
||||||
|
/// The default is to not recognize gestures.
|
||||||
|
fn recognize_pinch_gesture(&self, should_recognize: bool);
|
||||||
|
|
||||||
|
/// Sets whether the [`Window`] should recognize double tap gestures.
|
||||||
|
///
|
||||||
|
/// The default is to not recognize gestures.
|
||||||
|
fn recognize_doubletap_gesture(&self, should_recognize: bool);
|
||||||
|
|
||||||
|
/// Sets whether the [`Window`] should recognize rotation gestures.
|
||||||
|
///
|
||||||
|
/// The default is to not recognize gestures.
|
||||||
|
fn recognize_rotation_gesture(&self, should_recognize: bool);
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowExtIOS for Window {
|
impl WindowExtIOS for Window {
|
||||||
#[inline]
|
|
||||||
fn ui_window(&self) -> *mut c_void {
|
|
||||||
self.window.ui_window()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn ui_view_controller(&self) -> *mut c_void {
|
|
||||||
self.window.ui_view_controller()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn ui_view(&self) -> *mut c_void {
|
|
||||||
self.window.ui_view()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_scale_factor(&self, scale_factor: f64) {
|
fn set_scale_factor(&self, scale_factor: f64) {
|
||||||
self.window.set_scale_factor(scale_factor)
|
self.window
|
||||||
|
.maybe_queue_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.set_valid_orientations(valid_orientations)
|
self.window
|
||||||
|
.maybe_queue_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.set_prefers_home_indicator_hidden(hidden)
|
self.window
|
||||||
|
.maybe_queue_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
|
self.window.maybe_queue_on_main(move |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.set_prefers_status_bar_hidden(hidden)
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_prefers_status_bar_hidden(hidden))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_preferred_status_bar_style(status_bar_style))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn recognize_pinch_gesture(&self, should_recognize: bool) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.recognize_pinch_gesture(should_recognize));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn recognize_doubletap_gesture(&self, should_recognize: bool) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.recognize_doubletap_gesture(should_recognize));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn recognize_rotation_gesture(&self, should_recognize: bool) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.recognize_rotation_gesture(should_recognize));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,7 +168,7 @@ pub trait WindowBuilderExtIOS {
|
|||||||
///
|
///
|
||||||
/// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc
|
/// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc
|
||||||
/// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc
|
/// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc
|
||||||
fn with_scale_factor(self, scale_factor: f64) -> WindowBuilder;
|
fn with_scale_factor(self, scale_factor: f64) -> Self;
|
||||||
|
|
||||||
/// Sets the valid orientations for the [`Window`].
|
/// Sets the valid orientations for the [`Window`].
|
||||||
///
|
///
|
||||||
@@ -156,7 +176,7 @@ pub trait WindowBuilderExtIOS {
|
|||||||
///
|
///
|
||||||
/// This sets the initial value returned by
|
/// This sets the initial value returned by
|
||||||
/// [`-[UIViewController supportedInterfaceOrientations]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621435-supportedinterfaceorientations?language=objc).
|
/// [`-[UIViewController supportedInterfaceOrientations]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621435-supportedinterfaceorientations?language=objc).
|
||||||
fn with_valid_orientations(self, valid_orientations: ValidOrientations) -> WindowBuilder;
|
fn with_valid_orientations(self, valid_orientations: ValidOrientations) -> Self;
|
||||||
|
|
||||||
/// Sets whether the [`Window`] prefers the home indicator hidden.
|
/// Sets whether the [`Window`] prefers the home indicator hidden.
|
||||||
///
|
///
|
||||||
@@ -166,7 +186,7 @@ pub trait WindowBuilderExtIOS {
|
|||||||
/// [`-[UIViewController prefersHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887510-prefershomeindicatorautohidden?language=objc).
|
/// [`-[UIViewController prefersHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887510-prefershomeindicatorautohidden?language=objc).
|
||||||
///
|
///
|
||||||
/// This only has an effect on iOS 11.0+.
|
/// This only has an effect on iOS 11.0+.
|
||||||
fn with_prefers_home_indicator_hidden(self, hidden: bool) -> WindowBuilder;
|
fn with_prefers_home_indicator_hidden(self, hidden: bool) -> Self;
|
||||||
|
|
||||||
/// Sets the screen edges for which the system gestures will take a lower priority than the
|
/// Sets the screen edges for which the system gestures will take a lower priority than the
|
||||||
/// application's touch handling.
|
/// application's touch handling.
|
||||||
@@ -175,10 +195,7 @@ pub trait WindowBuilderExtIOS {
|
|||||||
/// [`-[UIViewController preferredScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887512-preferredscreenedgesdeferringsys?language=objc).
|
/// [`-[UIViewController preferredScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887512-preferredscreenedgesdeferringsys?language=objc).
|
||||||
///
|
///
|
||||||
/// This only has an effect on iOS 11.0+.
|
/// This only has an effect on iOS 11.0+.
|
||||||
fn with_preferred_screen_edges_deferring_system_gestures(
|
fn with_preferred_screen_edges_deferring_system_gestures(self, edges: ScreenEdge) -> Self;
|
||||||
self,
|
|
||||||
edges: ScreenEdge,
|
|
||||||
) -> WindowBuilder;
|
|
||||||
|
|
||||||
/// Sets whether the [`Window`] prefers the status bar hidden.
|
/// Sets whether the [`Window`] prefers the status bar hidden.
|
||||||
///
|
///
|
||||||
@@ -186,41 +203,53 @@ pub trait WindowBuilderExtIOS {
|
|||||||
///
|
///
|
||||||
/// This sets the initial value returned by
|
/// This sets the initial value returned by
|
||||||
/// [`-[UIViewController prefersStatusBarHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621440-prefersstatusbarhidden?language=objc).
|
/// [`-[UIViewController prefersStatusBarHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621440-prefersstatusbarhidden?language=objc).
|
||||||
fn with_prefers_status_bar_hidden(self, hidden: bool) -> WindowBuilder;
|
fn with_prefers_status_bar_hidden(self, hidden: bool) -> Self;
|
||||||
|
|
||||||
|
/// Sets the style of the [`Window`]'s status bar.
|
||||||
|
///
|
||||||
|
/// The default is system-defined.
|
||||||
|
///
|
||||||
|
/// This sets the initial value returned by
|
||||||
|
/// [`-[UIViewController preferredStatusBarStyle]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621416-preferredstatusbarstyle?language=objc),
|
||||||
|
fn with_preferred_status_bar_style(self, status_bar_style: StatusBarStyle) -> Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowBuilderExtIOS for WindowBuilder {
|
impl WindowBuilderExtIOS for WindowBuilder {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_scale_factor(mut self, scale_factor: f64) -> WindowBuilder {
|
fn with_scale_factor(mut self, scale_factor: f64) -> Self {
|
||||||
self.platform_specific.scale_factor = Some(scale_factor);
|
self.window.platform_specific.scale_factor = Some(scale_factor);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_valid_orientations(mut self, valid_orientations: ValidOrientations) -> WindowBuilder {
|
fn with_valid_orientations(mut self, valid_orientations: ValidOrientations) -> Self {
|
||||||
self.platform_specific.valid_orientations = valid_orientations;
|
self.window.platform_specific.valid_orientations = valid_orientations;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_prefers_home_indicator_hidden(mut self, hidden: bool) -> WindowBuilder {
|
fn with_prefers_home_indicator_hidden(mut self, hidden: bool) -> Self {
|
||||||
self.platform_specific.prefers_home_indicator_hidden = hidden;
|
self.window.platform_specific.prefers_home_indicator_hidden = hidden;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_preferred_screen_edges_deferring_system_gestures(
|
fn with_preferred_screen_edges_deferring_system_gestures(mut self, edges: ScreenEdge) -> Self {
|
||||||
mut self,
|
self.window
|
||||||
edges: ScreenEdge,
|
.platform_specific
|
||||||
) -> WindowBuilder {
|
|
||||||
self.platform_specific
|
|
||||||
.preferred_screen_edges_deferring_system_gestures = edges;
|
.preferred_screen_edges_deferring_system_gestures = edges;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_prefers_status_bar_hidden(mut self, hidden: bool) -> WindowBuilder {
|
fn with_prefers_status_bar_hidden(mut self, hidden: bool) -> Self {
|
||||||
self.platform_specific.prefers_status_bar_hidden = hidden;
|
self.window.platform_specific.prefers_status_bar_hidden = hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_preferred_status_bar_style(mut self, status_bar_style: StatusBarStyle) -> Self {
|
||||||
|
self.window.platform_specific.preferred_status_bar_style = status_bar_style;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -232,30 +261,33 @@ pub trait MonitorHandleExtIOS {
|
|||||||
/// [`UIScreen`]: https://developer.apple.com/documentation/uikit/uiscreen?language=objc
|
/// [`UIScreen`]: https://developer.apple.com/documentation/uikit/uiscreen?language=objc
|
||||||
fn ui_screen(&self) -> *mut c_void;
|
fn ui_screen(&self) -> *mut c_void;
|
||||||
|
|
||||||
/// Returns the preferred [`VideoMode`] for this monitor.
|
/// Returns the preferred [`VideoModeHandle`] for this monitor.
|
||||||
///
|
///
|
||||||
/// This translates to a call to [`-[UIScreen preferredMode]`](https://developer.apple.com/documentation/uikit/uiscreen/1617823-preferredmode?language=objc).
|
/// This translates to a call to [`-[UIScreen preferredMode]`](https://developer.apple.com/documentation/uikit/uiscreen/1617823-preferredmode?language=objc).
|
||||||
fn preferred_video_mode(&self) -> VideoMode;
|
fn preferred_video_mode(&self) -> VideoModeHandle;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MonitorHandleExtIOS for MonitorHandle {
|
impl MonitorHandleExtIOS for MonitorHandle {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn ui_screen(&self) -> *mut c_void {
|
fn ui_screen(&self) -> *mut c_void {
|
||||||
Id::as_ptr(self.inner.ui_screen()) as *mut c_void
|
// SAFETY: The marker is only used to get the pointer of the screen
|
||||||
|
let mtm = unsafe { icrate::Foundation::MainThreadMarker::new_unchecked() };
|
||||||
|
objc2::rc::Id::as_ptr(self.inner.ui_screen(mtm)) as *mut c_void
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn preferred_video_mode(&self) -> VideoMode {
|
fn preferred_video_mode(&self) -> VideoModeHandle {
|
||||||
VideoMode {
|
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(Clone, Copy, Debug)]
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
pub enum ValidOrientations {
|
pub enum ValidOrientations {
|
||||||
/// Excludes `PortraitUpsideDown` on iphone
|
/// Excludes `PortraitUpsideDown` on iphone
|
||||||
|
#[default]
|
||||||
LandscapeAndPortrait,
|
LandscapeAndPortrait,
|
||||||
|
|
||||||
Landscape,
|
Landscape,
|
||||||
@@ -264,17 +296,10 @@ pub enum ValidOrientations {
|
|||||||
Portrait,
|
Portrait,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ValidOrientations {
|
|
||||||
#[inline]
|
|
||||||
fn default() -> ValidOrientations {
|
|
||||||
ValidOrientations::LandscapeAndPortrait
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The device [idiom].
|
/// The device [idiom].
|
||||||
///
|
///
|
||||||
/// [idiom]: https://developer.apple.com/documentation/uikit/uidevice/1620037-userinterfaceidiom?language=objc
|
/// [idiom]: https://developer.apple.com/documentation/uikit/uidevice/1620037-userinterfaceidiom?language=objc
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
pub enum Idiom {
|
pub enum Idiom {
|
||||||
Unspecified,
|
Unspecified,
|
||||||
|
|
||||||
@@ -289,18 +314,26 @@ pub enum Idiom {
|
|||||||
CarPlay,
|
CarPlay,
|
||||||
}
|
}
|
||||||
|
|
||||||
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)]
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
pub struct ScreenEdge: u8 {
|
pub struct ScreenEdge: u8 {
|
||||||
const NONE = 0;
|
const NONE = 0;
|
||||||
const TOP = 1 << 0;
|
const TOP = 1 << 0;
|
||||||
const LEFT = 1 << 1;
|
const LEFT = 1 << 1;
|
||||||
const BOTTOM = 1 << 2;
|
const BOTTOM = 1 << 2;
|
||||||
const RIGHT = 1 << 3;
|
const RIGHT = 1 << 3;
|
||||||
const ALL = ScreenEdge::TOP.bits | ScreenEdge::LEFT.bits
|
const ALL = ScreenEdge::TOP.bits() | ScreenEdge::LEFT.bits()
|
||||||
| ScreenEdge::BOTTOM.bits | ScreenEdge::RIGHT.bits;
|
| ScreenEdge::BOTTOM.bits() | ScreenEdge::RIGHT.bits();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub enum StatusBarStyle {
|
||||||
|
#[default]
|
||||||
|
Default,
|
||||||
|
LightContent,
|
||||||
|
DarkContent,
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use std::os::raw::c_void;
|
use std::os::raw::c_void;
|
||||||
|
|
||||||
use objc2::rc::Id;
|
#[cfg(feature = "serde")]
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
event_loop::{EventLoopBuilder, EventLoopWindowTarget},
|
event_loop::{EventLoopBuilder, EventLoopWindowTarget},
|
||||||
@@ -10,16 +11,6 @@ use crate::{
|
|||||||
|
|
||||||
/// Additional methods on [`Window`] that are specific to MacOS.
|
/// Additional methods on [`Window`] that are specific to MacOS.
|
||||||
pub trait WindowExtMacOS {
|
pub trait WindowExtMacOS {
|
||||||
/// Returns a pointer to the cocoa `NSWindow` that is used by this window.
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the [`Window`] is destroyed.
|
|
||||||
fn ns_window(&self) -> *mut c_void;
|
|
||||||
|
|
||||||
/// Returns a pointer to the cocoa `NSView` that is used by this window.
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the [`Window`] is destroyed.
|
|
||||||
fn ns_view(&self) -> *mut c_void;
|
|
||||||
|
|
||||||
/// Returns whether or not the window is in simple fullscreen mode.
|
/// Returns whether or not the window is in simple fullscreen mode.
|
||||||
fn simple_fullscreen(&self) -> bool;
|
fn simple_fullscreen(&self) -> bool;
|
||||||
|
|
||||||
@@ -38,6 +29,28 @@ pub trait WindowExtMacOS {
|
|||||||
/// Sets whether or not the window has shadow.
|
/// Sets whether or not the window has shadow.
|
||||||
fn set_has_shadow(&self, has_shadow: bool);
|
fn set_has_shadow(&self, has_shadow: bool);
|
||||||
|
|
||||||
|
/// Group windows together by using the same tabbing identifier.
|
||||||
|
///
|
||||||
|
/// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
|
||||||
|
fn set_tabbing_identifier(&self, identifier: &str);
|
||||||
|
|
||||||
|
/// Returns the window's tabbing identifier.
|
||||||
|
fn tabbing_identifier(&self) -> String;
|
||||||
|
|
||||||
|
/// Select next tab.
|
||||||
|
fn select_next_tab(&self);
|
||||||
|
|
||||||
|
/// Select previous tab.
|
||||||
|
fn select_previous_tab(&self);
|
||||||
|
|
||||||
|
/// Select the tab with the given index.
|
||||||
|
///
|
||||||
|
/// Will no-op when the index is out of bounds.
|
||||||
|
fn select_tab_at_index(&self, index: usize);
|
||||||
|
|
||||||
|
/// Get the number of tabs in the window tab group.
|
||||||
|
fn num_tabs(&self) -> usize;
|
||||||
|
|
||||||
/// Get the window's edit state.
|
/// Get the window's edit state.
|
||||||
///
|
///
|
||||||
/// # Examples
|
/// # Examples
|
||||||
@@ -70,74 +83,97 @@ pub trait WindowExtMacOS {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl WindowExtMacOS for Window {
|
impl WindowExtMacOS for Window {
|
||||||
#[inline]
|
|
||||||
fn ns_window(&self) -> *mut c_void {
|
|
||||||
self.window.ns_window()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn ns_view(&self) -> *mut c_void {
|
|
||||||
self.window.ns_view()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn simple_fullscreen(&self) -> bool {
|
fn simple_fullscreen(&self) -> bool {
|
||||||
self.window.simple_fullscreen()
|
self.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.set_simple_fullscreen(fullscreen)
|
self.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.has_shadow()
|
self.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.set_has_shadow(has_shadow)
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_has_shadow(has_shadow))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_tabbing_identifier(&self, identifier: &str) {
|
||||||
|
self.window
|
||||||
|
.maybe_wait_on_main(|w| w.set_tabbing_identifier(identifier))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn tabbing_identifier(&self) -> String {
|
||||||
|
self.window.maybe_wait_on_main(|w| w.tabbing_identifier())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn select_next_tab(&self) {
|
||||||
|
self.window.maybe_queue_on_main(|w| w.select_next_tab())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn select_previous_tab(&self) {
|
||||||
|
self.window.maybe_queue_on_main(|w| w.select_previous_tab())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn select_tab_at_index(&self, index: usize) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.select_tab_at_index(index))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn num_tabs(&self) -> usize {
|
||||||
|
self.window.maybe_wait_on_main(|w| w.num_tabs())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn is_document_edited(&self) -> bool {
|
fn is_document_edited(&self) -> bool {
|
||||||
self.window.is_document_edited()
|
self.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.set_document_edited(edited)
|
self.window
|
||||||
|
.maybe_queue_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.set_option_as_alt(option_as_alt)
|
self.window
|
||||||
|
.maybe_queue_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.option_as_alt()
|
self.window.maybe_wait_on_main(|w| w.option_as_alt())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Corresponds to `NSApplicationActivationPolicy`.
|
/// Corresponds to `NSApplicationActivationPolicy`.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
pub enum ActivationPolicy {
|
pub enum ActivationPolicy {
|
||||||
/// Corresponds to `NSApplicationActivationPolicyRegular`.
|
/// Corresponds to `NSApplicationActivationPolicyRegular`.
|
||||||
|
#[default]
|
||||||
Regular,
|
Regular,
|
||||||
|
|
||||||
/// Corresponds to `NSApplicationActivationPolicyAccessory`.
|
/// Corresponds to `NSApplicationActivationPolicyAccessory`.
|
||||||
Accessory,
|
Accessory,
|
||||||
|
|
||||||
/// Corresponds to `NSApplicationActivationPolicyProhibited`.
|
/// Corresponds to `NSApplicationActivationPolicyProhibited`.
|
||||||
Prohibited,
|
Prohibited,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ActivationPolicy {
|
|
||||||
fn default() -> Self {
|
|
||||||
ActivationPolicy::Regular
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on [`WindowBuilder`] that are specific to MacOS.
|
/// Additional methods on [`WindowBuilder`] that are specific to MacOS.
|
||||||
///
|
///
|
||||||
/// **Note:** Properties dealing with the titlebar will be overwritten by the [`WindowBuilder::with_decorations`] method:
|
/// **Note:** Properties dealing with the titlebar will be overwritten by the [`WindowBuilder::with_decorations`] method:
|
||||||
@@ -148,90 +184,98 @@ impl Default for ActivationPolicy {
|
|||||||
/// - `with_fullsize_content_view`
|
/// - `with_fullsize_content_view`
|
||||||
pub trait WindowBuilderExtMacOS {
|
pub trait WindowBuilderExtMacOS {
|
||||||
/// Enables click-and-drag behavior for the entire window, not just the titlebar.
|
/// Enables click-and-drag behavior for the entire window, not just the titlebar.
|
||||||
fn with_movable_by_window_background(self, movable_by_window_background: bool)
|
fn with_movable_by_window_background(self, movable_by_window_background: bool) -> Self;
|
||||||
-> WindowBuilder;
|
|
||||||
/// Makes the titlebar transparent and allows the content to appear behind it.
|
/// Makes the titlebar transparent and allows the content to appear behind it.
|
||||||
fn with_titlebar_transparent(self, titlebar_transparent: bool) -> WindowBuilder;
|
fn with_titlebar_transparent(self, titlebar_transparent: bool) -> Self;
|
||||||
/// Hides the window title.
|
/// Hides the window title.
|
||||||
fn with_title_hidden(self, title_hidden: bool) -> WindowBuilder;
|
fn with_title_hidden(self, title_hidden: bool) -> Self;
|
||||||
/// Hides the window titlebar.
|
/// Hides the window titlebar.
|
||||||
fn with_titlebar_hidden(self, titlebar_hidden: bool) -> WindowBuilder;
|
fn with_titlebar_hidden(self, titlebar_hidden: bool) -> Self;
|
||||||
/// Hides the window titlebar buttons.
|
/// Hides the window titlebar buttons.
|
||||||
fn with_titlebar_buttons_hidden(self, titlebar_buttons_hidden: bool) -> WindowBuilder;
|
fn with_titlebar_buttons_hidden(self, titlebar_buttons_hidden: bool) -> Self;
|
||||||
/// Makes the window content appear behind the titlebar.
|
/// Makes the window content appear behind the titlebar.
|
||||||
fn with_fullsize_content_view(self, fullsize_content_view: bool) -> WindowBuilder;
|
fn with_fullsize_content_view(self, fullsize_content_view: bool) -> Self;
|
||||||
fn with_disallow_hidpi(self, disallow_hidpi: bool) -> WindowBuilder;
|
fn with_disallow_hidpi(self, disallow_hidpi: bool) -> Self;
|
||||||
fn with_has_shadow(self, has_shadow: bool) -> WindowBuilder;
|
fn with_has_shadow(self, has_shadow: bool) -> Self;
|
||||||
/// Window accepts click-through mouse events.
|
/// Window accepts click-through mouse events.
|
||||||
fn with_accepts_first_mouse(self, accepts_first_mouse: bool) -> WindowBuilder;
|
fn with_accepts_first_mouse(self, accepts_first_mouse: bool) -> Self;
|
||||||
|
/// Defines the window tabbing identifier.
|
||||||
/// Set whether the `OptionAsAlt` key is interpreted as the `Alt` modifier.
|
///
|
||||||
|
/// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
|
||||||
|
fn with_tabbing_identifier(self, identifier: &str) -> Self;
|
||||||
|
/// Set how the <kbd>Option</kbd> keys are interpreted.
|
||||||
///
|
///
|
||||||
/// See [`WindowExtMacOS::set_option_as_alt`] for details on what this means if set.
|
/// See [`WindowExtMacOS::set_option_as_alt`] for details on what this means if set.
|
||||||
fn with_option_as_alt(self, option_as_alt: OptionAsAlt) -> WindowBuilder;
|
fn with_option_as_alt(self, option_as_alt: OptionAsAlt) -> Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowBuilderExtMacOS for WindowBuilder {
|
impl WindowBuilderExtMacOS for WindowBuilder {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_movable_by_window_background(
|
fn with_movable_by_window_background(mut self, movable_by_window_background: bool) -> Self {
|
||||||
mut self,
|
self.window.platform_specific.movable_by_window_background = movable_by_window_background;
|
||||||
movable_by_window_background: bool,
|
|
||||||
) -> WindowBuilder {
|
|
||||||
self.platform_specific.movable_by_window_background = movable_by_window_background;
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> WindowBuilder {
|
fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> Self {
|
||||||
self.platform_specific.titlebar_transparent = titlebar_transparent;
|
self.window.platform_specific.titlebar_transparent = titlebar_transparent;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_titlebar_hidden(mut self, titlebar_hidden: bool) -> WindowBuilder {
|
fn with_titlebar_hidden(mut self, titlebar_hidden: bool) -> Self {
|
||||||
self.platform_specific.titlebar_hidden = titlebar_hidden;
|
self.window.platform_specific.titlebar_hidden = titlebar_hidden;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_titlebar_buttons_hidden(mut self, titlebar_buttons_hidden: bool) -> WindowBuilder {
|
fn with_titlebar_buttons_hidden(mut self, titlebar_buttons_hidden: bool) -> Self {
|
||||||
self.platform_specific.titlebar_buttons_hidden = titlebar_buttons_hidden;
|
self.window.platform_specific.titlebar_buttons_hidden = titlebar_buttons_hidden;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_title_hidden(mut self, title_hidden: bool) -> WindowBuilder {
|
fn with_title_hidden(mut self, title_hidden: bool) -> Self {
|
||||||
self.platform_specific.title_hidden = title_hidden;
|
self.window.platform_specific.title_hidden = title_hidden;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_fullsize_content_view(mut self, fullsize_content_view: bool) -> WindowBuilder {
|
fn with_fullsize_content_view(mut self, fullsize_content_view: bool) -> Self {
|
||||||
self.platform_specific.fullsize_content_view = fullsize_content_view;
|
self.window.platform_specific.fullsize_content_view = fullsize_content_view;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_disallow_hidpi(mut self, disallow_hidpi: bool) -> WindowBuilder {
|
fn with_disallow_hidpi(mut self, disallow_hidpi: bool) -> Self {
|
||||||
self.platform_specific.disallow_hidpi = disallow_hidpi;
|
self.window.platform_specific.disallow_hidpi = disallow_hidpi;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_has_shadow(mut self, has_shadow: bool) -> WindowBuilder {
|
fn with_has_shadow(mut self, has_shadow: bool) -> Self {
|
||||||
self.platform_specific.has_shadow = has_shadow;
|
self.window.platform_specific.has_shadow = has_shadow;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_accepts_first_mouse(mut self, accepts_first_mouse: bool) -> WindowBuilder {
|
fn with_accepts_first_mouse(mut self, accepts_first_mouse: bool) -> Self {
|
||||||
self.platform_specific.accepts_first_mouse = accepts_first_mouse;
|
self.window.platform_specific.accepts_first_mouse = accepts_first_mouse;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_option_as_alt(mut self, option_as_alt: OptionAsAlt) -> WindowBuilder {
|
fn with_tabbing_identifier(mut self, tabbing_identifier: &str) -> Self {
|
||||||
self.platform_specific.option_as_alt = option_as_alt;
|
self.window
|
||||||
|
.platform_specific
|
||||||
|
.tabbing_identifier
|
||||||
|
.replace(tabbing_identifier.to_string());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_option_as_alt(mut self, option_as_alt: OptionAsAlt) -> Self {
|
||||||
|
self.window.platform_specific.option_as_alt = option_as_alt;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -323,7 +367,11 @@ impl MonitorHandleExtMacOS for MonitorHandle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn ns_screen(&self) -> Option<*mut c_void> {
|
fn ns_screen(&self) -> Option<*mut c_void> {
|
||||||
self.inner.ns_screen().map(|s| Id::as_ptr(&s) as _)
|
// SAFETY: We only use the marker to get a pointer
|
||||||
|
let mtm = unsafe { icrate::Foundation::MainThreadMarker::new_unchecked() };
|
||||||
|
self.inner
|
||||||
|
.ns_screen(mtm)
|
||||||
|
.map(|s| objc2::rc::Id::as_ptr(&s) as _)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -333,9 +381,15 @@ pub trait EventLoopWindowTargetExtMacOS {
|
|||||||
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.
|
||||||
|
///
|
||||||
|
/// <https://developer.apple.com/documentation/appkit/nswindow/1646657-allowsautomaticwindowtabbing>
|
||||||
|
fn set_allows_automatic_window_tabbing(&self, enabled: bool);
|
||||||
|
/// Returns whether the system can automatically organize windows into tabs.
|
||||||
|
fn allows_automatic_window_tabbing(&self) -> bool;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoopWindowTargetExtMacOS for EventLoopWindowTarget<T> {
|
impl EventLoopWindowTargetExtMacOS for EventLoopWindowTarget {
|
||||||
fn hide_application(&self) {
|
fn hide_application(&self) {
|
||||||
self.p.hide_application()
|
self.p.hide_application()
|
||||||
}
|
}
|
||||||
@@ -343,12 +397,20 @@ impl<T> EventLoopWindowTargetExtMacOS for EventLoopWindowTarget<T> {
|
|||||||
fn hide_other_applications(&self) {
|
fn hide_other_applications(&self) {
|
||||||
self.p.hide_other_applications()
|
self.p.hide_other_applications()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn set_allows_automatic_window_tabbing(&self, enabled: bool) {
|
||||||
|
self.p.set_allows_automatic_window_tabbing(enabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn allows_automatic_window_tabbing(&self) -> bool {
|
||||||
|
self.p.allows_automatic_window_tabbing()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Option as alt behavior.
|
/// Option as alt behavior.
|
||||||
///
|
///
|
||||||
/// The default is `None`.
|
/// The default is `None`.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
#[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`.
|
||||||
@@ -361,11 +423,6 @@ pub enum OptionAsAlt {
|
|||||||
Both,
|
Both,
|
||||||
|
|
||||||
/// No special handling is applied for `Option` key.
|
/// No special handling is applied for `Option` key.
|
||||||
|
#[default]
|
||||||
None,
|
None,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for OptionAsAlt {
|
|
||||||
fn default() -> Self {
|
|
||||||
OptionAsAlt::None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,35 +1,24 @@
|
|||||||
//! Contains traits with platform-specific methods in them.
|
//! Contains traits with platform-specific methods in them.
|
||||||
//!
|
//!
|
||||||
//! Contains the follow OS-specific modules:
|
//! Only the modules corresponding to the platform you're compiling to will be available.
|
||||||
//!
|
|
||||||
//! - `android`
|
|
||||||
//! - `ios`
|
|
||||||
//! - `macos`
|
|
||||||
//! - `unix`
|
|
||||||
//! - `windows`
|
|
||||||
//! - `web`
|
|
||||||
//!
|
|
||||||
//! And the following platform-specific module:
|
|
||||||
//!
|
|
||||||
//! - `run_return` (available on `windows`, `unix`, `macos`, and `android`)
|
|
||||||
//!
|
|
||||||
//! However only the module corresponding to the platform you're compiling to will be available.
|
|
||||||
|
|
||||||
#[cfg(android_platform)]
|
#[cfg(any(android_platform, docsrs))]
|
||||||
pub mod android;
|
pub mod android;
|
||||||
#[cfg(ios_platform)]
|
#[cfg(any(ios_platform, docsrs))]
|
||||||
pub mod ios;
|
pub mod ios;
|
||||||
#[cfg(macos_platform)]
|
#[cfg(any(macos_platform, docsrs))]
|
||||||
pub mod macos;
|
pub mod macos;
|
||||||
#[cfg(orbital_platform)]
|
#[cfg(any(orbital_platform, docsrs))]
|
||||||
pub mod orbital;
|
pub mod orbital;
|
||||||
#[cfg(wayland_platform)]
|
#[cfg(any(x11_platform, wayland_platform, docsrs))]
|
||||||
|
pub mod startup_notify;
|
||||||
|
#[cfg(any(wayland_platform, docsrs))]
|
||||||
pub mod wayland;
|
pub mod wayland;
|
||||||
#[cfg(wasm_platform)]
|
#[cfg(any(web_platform, docsrs))]
|
||||||
pub mod web;
|
pub mod web;
|
||||||
#[cfg(windows_platform)]
|
#[cfg(any(windows_platform, docsrs))]
|
||||||
pub mod windows;
|
pub mod windows;
|
||||||
#[cfg(x11_platform)]
|
#[cfg(any(x11_platform, docsrs))]
|
||||||
pub mod x11;
|
pub mod x11;
|
||||||
|
|
||||||
#[cfg(any(
|
#[cfg(any(
|
||||||
@@ -38,6 +27,35 @@ pub mod x11;
|
|||||||
android_platform,
|
android_platform,
|
||||||
x11_platform,
|
x11_platform,
|
||||||
wayland_platform,
|
wayland_platform,
|
||||||
orbital_platform
|
docsrs,
|
||||||
))]
|
))]
|
||||||
pub mod run_return;
|
pub mod run_on_demand;
|
||||||
|
|
||||||
|
#[cfg(any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
android_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform,
|
||||||
|
docsrs,
|
||||||
|
))]
|
||||||
|
pub mod pump_events;
|
||||||
|
|
||||||
|
#[cfg(any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform,
|
||||||
|
orbital_platform,
|
||||||
|
docsrs
|
||||||
|
))]
|
||||||
|
pub mod modifier_supplement;
|
||||||
|
|
||||||
|
#[cfg(any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform,
|
||||||
|
docsrs
|
||||||
|
))]
|
||||||
|
pub mod scancode;
|
||||||
|
|||||||
38
src/platform/modifier_supplement.rs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
use crate::event::KeyEvent;
|
||||||
|
use crate::keyboard::Key;
|
||||||
|
|
||||||
|
/// Additional methods for the `KeyEvent` which cannot be implemented on all
|
||||||
|
/// platforms.
|
||||||
|
pub trait KeyEventExtModifierSupplement {
|
||||||
|
/// Identical to `KeyEvent::text` but this is affected by <kbd>Ctrl</kbd>.
|
||||||
|
///
|
||||||
|
/// For example, pressing <kbd>Ctrl</kbd>+<kbd>a</kbd> produces `Some("\x01")`.
|
||||||
|
fn text_with_all_modifiers(&self) -> Option<&str>;
|
||||||
|
|
||||||
|
/// This value ignores all modifiers including,
|
||||||
|
/// but not limited to <kbd>Shift</kbd>, <kbd>Caps Lock</kbd>,
|
||||||
|
/// and <kbd>Ctrl</kbd>. In most cases this means that the
|
||||||
|
/// unicode character in the resulting string is lowercase.
|
||||||
|
///
|
||||||
|
/// This is useful for key-bindings / shortcut key combinations.
|
||||||
|
///
|
||||||
|
/// In case `logical_key` reports `Dead`, this will still report the
|
||||||
|
/// key as `Character` according to the current keyboard layout. This value
|
||||||
|
/// cannot be `Dead`.
|
||||||
|
fn key_without_modifiers(&self) -> Key;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KeyEventExtModifierSupplement for KeyEvent {
|
||||||
|
#[inline]
|
||||||
|
fn text_with_all_modifiers(&self) -> Option<&str> {
|
||||||
|
self.platform_specific
|
||||||
|
.text_with_all_modifiers
|
||||||
|
.as_ref()
|
||||||
|
.map(|s| s.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn key_without_modifiers(&self) -> Key {
|
||||||
|
self.platform_specific.key_without_modifiers.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
189
src/platform/pump_events.rs
Normal file
@@ -0,0 +1,189 @@
|
|||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
event::Event,
|
||||||
|
event_loop::{EventLoop, EventLoopWindowTarget},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The return status for `pump_events`
|
||||||
|
pub enum PumpStatus {
|
||||||
|
/// Continue running external loop.
|
||||||
|
Continue,
|
||||||
|
/// Exit external loop.
|
||||||
|
Exit(i32),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoop`] for pumping events within an external event loop
|
||||||
|
pub trait EventLoopExtPumpEvents {
|
||||||
|
/// A type provided by the user that can be passed through [`Event::UserEvent`].
|
||||||
|
type UserEvent;
|
||||||
|
|
||||||
|
/// Pump the `EventLoop` to check for and dispatch pending events.
|
||||||
|
///
|
||||||
|
/// This API is designed to enable applications to integrate Winit into an
|
||||||
|
/// external event loop, for platforms that can support this.
|
||||||
|
///
|
||||||
|
/// The given `timeout` limits how long it may block waiting for new events.
|
||||||
|
///
|
||||||
|
/// Passing a `timeout` of `Some(Duration::ZERO)` would ensure your external
|
||||||
|
/// event loop is never blocked but you would likely need to consider how
|
||||||
|
/// to throttle your own external loop.
|
||||||
|
///
|
||||||
|
/// Passing a `timeout` of `None` means that it may wait indefinitely for new
|
||||||
|
/// events before returning control back to the external loop.
|
||||||
|
///
|
||||||
|
/// ## Example
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// # // Copied from examples/window_pump_events.rs
|
||||||
|
/// # #[cfg(any(
|
||||||
|
/// # windows_platform,
|
||||||
|
/// # macos_platform,
|
||||||
|
/// # x11_platform,
|
||||||
|
/// # wayland_platform,
|
||||||
|
/// # android_platform,
|
||||||
|
/// # ))]
|
||||||
|
/// fn main() -> std::process::ExitCode {
|
||||||
|
/// # use std::{process::ExitCode, thread::sleep, time::Duration};
|
||||||
|
/// #
|
||||||
|
/// # use simple_logger::SimpleLogger;
|
||||||
|
/// # use winit::{
|
||||||
|
/// # event::{Event, WindowEvent},
|
||||||
|
/// # event_loop::EventLoop,
|
||||||
|
/// # platform::pump_events::{EventLoopExtPumpEvents, PumpStatus},
|
||||||
|
/// # window::Window,
|
||||||
|
/// # };
|
||||||
|
/// let mut event_loop = EventLoop::new().unwrap();
|
||||||
|
/// #
|
||||||
|
/// # SimpleLogger::new().init().unwrap();
|
||||||
|
/// let window = Window::builder()
|
||||||
|
/// .with_title("A fantastic window!")
|
||||||
|
/// .build(&event_loop)
|
||||||
|
/// .unwrap();
|
||||||
|
///
|
||||||
|
/// 'main: loop {
|
||||||
|
/// let timeout = Some(Duration::ZERO);
|
||||||
|
/// let status = event_loop.pump_events(timeout, |event, elwt| {
|
||||||
|
/// # if let Event::WindowEvent { event, .. } = &event {
|
||||||
|
/// # // Print only Window events to reduce noise
|
||||||
|
/// # println!("{event:?}");
|
||||||
|
/// # }
|
||||||
|
/// #
|
||||||
|
/// match event {
|
||||||
|
/// Event::WindowEvent {
|
||||||
|
/// event: WindowEvent::CloseRequested,
|
||||||
|
/// window_id,
|
||||||
|
/// } if window_id == window.id() => elwt.exit(),
|
||||||
|
/// Event::AboutToWait => {
|
||||||
|
/// window.request_redraw();
|
||||||
|
/// }
|
||||||
|
/// _ => (),
|
||||||
|
/// }
|
||||||
|
/// });
|
||||||
|
/// if let PumpStatus::Exit(exit_code) = status {
|
||||||
|
/// break 'main ExitCode::from(exit_code as u8);
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// // Sleep for 1/60 second to simulate application work
|
||||||
|
/// //
|
||||||
|
/// // Since `pump_events` doesn't block it will be important to
|
||||||
|
/// // throttle the loop in the app somehow.
|
||||||
|
/// println!("Update()");
|
||||||
|
/// sleep(Duration::from_millis(16));
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// **Note:** This is not a portable API, and its usage involves a number of
|
||||||
|
/// caveats and trade offs that should be considered before using this API!
|
||||||
|
///
|
||||||
|
/// You almost certainly shouldn't use this API, unless you absolutely know it's
|
||||||
|
/// the only practical option you have.
|
||||||
|
///
|
||||||
|
/// ## Synchronous events
|
||||||
|
///
|
||||||
|
/// Some events _must_ only be handled synchronously via the closure that
|
||||||
|
/// is passed to Winit so that the handler will also be synchronized with
|
||||||
|
/// the window system and operating system.
|
||||||
|
///
|
||||||
|
/// This is because some events are driven by a window system callback
|
||||||
|
/// where the window systems expects the application to have handled the
|
||||||
|
/// event before returning.
|
||||||
|
///
|
||||||
|
/// **These events can not be buffered and handled outside of the closure
|
||||||
|
/// passed to Winit.**
|
||||||
|
///
|
||||||
|
/// As a general rule it is not recommended to ever buffer events to handle
|
||||||
|
/// them outside of the closure passed to Winit since it's difficult to
|
||||||
|
/// provide guarantees about which events are safe to buffer across all
|
||||||
|
/// operating systems.
|
||||||
|
///
|
||||||
|
/// Notable events that will certainly create portability problems if
|
||||||
|
/// buffered and handled outside of Winit include:
|
||||||
|
/// - `RedrawRequested` events, used to schedule rendering.
|
||||||
|
///
|
||||||
|
/// macOS for example uses a `drawRect` callback to drive rendering
|
||||||
|
/// within applications and expects rendering to be finished before
|
||||||
|
/// the `drawRect` callback returns.
|
||||||
|
///
|
||||||
|
/// For portability it's strongly recommended that applications should
|
||||||
|
/// keep their rendering inside the closure provided to Winit.
|
||||||
|
/// - Any lifecycle events, such as `Suspended` / `Resumed`.
|
||||||
|
///
|
||||||
|
/// The handling of these events needs to be synchronized with the
|
||||||
|
/// operating system and it would never be appropriate to buffer a
|
||||||
|
/// notification that your application has been suspended or resumed and
|
||||||
|
/// then handled that later since there would always be a chance that
|
||||||
|
/// other lifecycle events occur while the event is buffered.
|
||||||
|
///
|
||||||
|
/// ## Supported Platforms
|
||||||
|
/// - Windows
|
||||||
|
/// - Linux
|
||||||
|
/// - MacOS
|
||||||
|
/// - Android
|
||||||
|
///
|
||||||
|
/// ## Unsupported Platforms
|
||||||
|
/// - **Web:** This API is fundamentally incompatible with the event-based way in which
|
||||||
|
/// Web browsers work because it's not possible to have a long-running external
|
||||||
|
/// loop that would block the browser and there is nothing that can be
|
||||||
|
/// polled to ask for new new events. Events are delivered via callbacks based
|
||||||
|
/// on an event loop that is internal to the browser itself.
|
||||||
|
/// - **iOS:** It's not possible to stop and start an `NSApplication` repeatedly on iOS so
|
||||||
|
/// there's no way to support the same approach to polling as on MacOS.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
/// - **Windows**: The implementation will use `PeekMessage` when checking for
|
||||||
|
/// window messages to avoid blocking your external event loop.
|
||||||
|
///
|
||||||
|
/// - **MacOS**: The implementation works in terms of stopping the global application
|
||||||
|
/// whenever the application `RunLoop` indicates that it is preparing to block
|
||||||
|
/// and wait for new events.
|
||||||
|
///
|
||||||
|
/// This is very different to the polling APIs that are available on other
|
||||||
|
/// platforms (the lower level polling primitives on MacOS are private
|
||||||
|
/// implementation details for `NSApplication` which aren't accessible to
|
||||||
|
/// application developers)
|
||||||
|
///
|
||||||
|
/// It's likely this will be less efficient than polling on other OSs and
|
||||||
|
/// it also means the `NSApplication` is stopped while outside of the Winit
|
||||||
|
/// event loop - and that's observable (for example to crates like `rfd`)
|
||||||
|
/// because the `NSApplication` is global state.
|
||||||
|
///
|
||||||
|
/// If you render outside of Winit you are likely to see window resizing artifacts
|
||||||
|
/// since MacOS expects applications to render synchronously during any `drawRect`
|
||||||
|
/// callback.
|
||||||
|
fn pump_events<F>(&mut self, timeout: Option<Duration>, event_handler: F) -> PumpStatus
|
||||||
|
where
|
||||||
|
F: FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopExtPumpEvents for EventLoop<T> {
|
||||||
|
type UserEvent = T;
|
||||||
|
|
||||||
|
fn pump_events<F>(&mut self, timeout: Option<Duration>, event_handler: F) -> PumpStatus
|
||||||
|
where
|
||||||
|
F: FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget),
|
||||||
|
{
|
||||||
|
self.event_loop.pump_events(timeout, event_handler)
|
||||||
|
}
|
||||||
|
}
|
||||||
102
src/platform/run_on_demand.rs
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
use crate::{
|
||||||
|
error::EventLoopError,
|
||||||
|
event::Event,
|
||||||
|
event_loop::{EventLoop, EventLoopWindowTarget},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(doc)]
|
||||||
|
use crate::{platform::pump_events::EventLoopExtPumpEvents, window::Window};
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoop`] to return control flow to the caller.
|
||||||
|
pub trait EventLoopExtRunOnDemand {
|
||||||
|
/// A type provided by the user that can be passed through [`Event::UserEvent`].
|
||||||
|
type UserEvent;
|
||||||
|
|
||||||
|
/// Runs the event loop in the calling thread and calls the given `event_handler` closure
|
||||||
|
/// to dispatch any window system events.
|
||||||
|
///
|
||||||
|
/// Unlike [`EventLoop::run`], this function accepts non-`'static` (i.e. non-`move`) closures
|
||||||
|
/// and it is possible to return control back to the caller without
|
||||||
|
/// consuming the `EventLoop` (by using [`exit()`]) and
|
||||||
|
/// so the event loop can be re-run after it has exit.
|
||||||
|
///
|
||||||
|
/// It's expected that each run of the loop will be for orthogonal instantiations of your
|
||||||
|
/// Winit application, but internally each instantiation may re-use some common window
|
||||||
|
/// system resources, such as a display server connection.
|
||||||
|
///
|
||||||
|
/// This API is not designed to run an event loop in bursts that you can exit from and return
|
||||||
|
/// to while maintaining the full state of your application. (If you need something like this
|
||||||
|
/// you can look at the [`EventLoopExtPumpEvents::pump_events()`] API)
|
||||||
|
///
|
||||||
|
/// Each time `run_on_demand` is called the `event_handler` can expect to receive a
|
||||||
|
/// `NewEvents(Init)` and `Resumed` event (even on platforms that have no suspend/resume
|
||||||
|
/// lifecycle) - which can be used to consistently initialize application state.
|
||||||
|
///
|
||||||
|
/// See the [`set_control_flow()`] docs on how to change the event loop's behavior.
|
||||||
|
///
|
||||||
|
/// # Caveats
|
||||||
|
/// - This extension isn't available on all platforms, since it's not always possible to return
|
||||||
|
/// to the caller (specifically this is impossible on iOS and Web - though with the Web
|
||||||
|
/// backend it is possible to use `EventLoopExtWebSys::spawn()`[^1] more than once instead).
|
||||||
|
/// - No [`Window`] state can be carried between separate runs of the event loop.
|
||||||
|
///
|
||||||
|
/// You are strongly encouraged to use [`EventLoop::run()`] for portability, unless you specifically need
|
||||||
|
/// the ability to re-run a single event loop more than once
|
||||||
|
///
|
||||||
|
/// # Supported Platforms
|
||||||
|
/// - Windows
|
||||||
|
/// - Linux
|
||||||
|
/// - macOS
|
||||||
|
/// - Android
|
||||||
|
///
|
||||||
|
/// # Unsupported Platforms
|
||||||
|
/// - **Web:** This API is fundamentally incompatible with the event-based way in which
|
||||||
|
/// Web browsers work because it's not possible to have a long-running external
|
||||||
|
/// loop that would block the browser and there is nothing that can be
|
||||||
|
/// polled to ask for new events. Events are delivered via callbacks based
|
||||||
|
/// on an event loop that is internal to the browser itself.
|
||||||
|
/// - **iOS:** It's not possible to stop and start an `UIApplication` repeatedly on iOS.
|
||||||
|
///
|
||||||
|
#[cfg_attr(
|
||||||
|
not(web_platform),
|
||||||
|
doc = "[^1]: `spawn()` is only available on `wasm` platforms."
|
||||||
|
)]
|
||||||
|
///
|
||||||
|
/// [`exit()`]: EventLoopWindowTarget::exit()
|
||||||
|
/// [`set_control_flow()`]: EventLoopWindowTarget::set_control_flow()
|
||||||
|
fn run_on_demand<F>(&mut self, event_handler: F) -> Result<(), EventLoopError>
|
||||||
|
where
|
||||||
|
F: FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopExtRunOnDemand for EventLoop<T> {
|
||||||
|
type UserEvent = T;
|
||||||
|
|
||||||
|
fn run_on_demand<F>(&mut self, event_handler: F) -> Result<(), EventLoopError>
|
||||||
|
where
|
||||||
|
F: FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget),
|
||||||
|
{
|
||||||
|
self.event_loop.window_target().clear_exit();
|
||||||
|
self.event_loop.run_on_demand(event_handler)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopWindowTarget {
|
||||||
|
/// Clear exit status.
|
||||||
|
pub(crate) fn clear_exit(&self) {
|
||||||
|
self.p.clear_exit()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// ```compile_fail
|
||||||
|
/// use winit::event_loop::EventLoop;
|
||||||
|
/// use winit::platform::run_on_demand::EventLoopExtRunOnDemand;
|
||||||
|
///
|
||||||
|
/// let mut event_loop = EventLoop::new().unwrap();
|
||||||
|
/// event_loop.run_on_demand(|_, _| {
|
||||||
|
/// // Attempt to run the event loop re-entrantly; this must fail.
|
||||||
|
/// event_loop.run_on_demand(|_, _| {});
|
||||||
|
/// });
|
||||||
|
/// ```
|
||||||
|
#[allow(dead_code)]
|
||||||
|
fn test_run_on_demand_cannot_access_event_loop() {}
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
use crate::{
|
|
||||||
event::Event,
|
|
||||||
event_loop::{ControlFlow, EventLoop, EventLoopWindowTarget},
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Additional methods on [`EventLoop`] to return control flow to the caller.
|
|
||||||
pub trait EventLoopExtRunReturn {
|
|
||||||
/// A type provided by the user that can be passed through [`Event::UserEvent`].
|
|
||||||
type UserEvent;
|
|
||||||
|
|
||||||
/// Initializes the `winit` event loop.
|
|
||||||
///
|
|
||||||
/// Unlike [`EventLoop::run`], this function accepts non-`'static` (i.e. non-`move`) closures
|
|
||||||
/// and returns control flow to the caller when `control_flow` is set to [`ControlFlow::Exit`].
|
|
||||||
///
|
|
||||||
/// # Caveats
|
|
||||||
///
|
|
||||||
/// Despite its appearance at first glance, this is *not* a perfect replacement for
|
|
||||||
/// `poll_events`. For example, this function will not return on Windows or macOS while a
|
|
||||||
/// window is getting resized, resulting in all application logic outside of the
|
|
||||||
/// `event_handler` closure not running until the resize operation ends. Other OS operations
|
|
||||||
/// may also result in such freezes. This behavior is caused by fundamental limitations in the
|
|
||||||
/// underlying OS APIs, which cannot be hidden by `winit` without severe stability repercussions.
|
|
||||||
///
|
|
||||||
/// You are strongly encouraged to use `run`, unless the use of this is absolutely necessary.
|
|
||||||
///
|
|
||||||
/// ## Platform-specific
|
|
||||||
///
|
|
||||||
/// - **X11 / Wayland:** This function returns `1` upon disconnection from
|
|
||||||
/// the display server.
|
|
||||||
fn run_return<F>(&mut self, event_handler: F) -> i32
|
|
||||||
where
|
|
||||||
F: FnMut(
|
|
||||||
Event<'_, Self::UserEvent>,
|
|
||||||
&EventLoopWindowTarget<Self::UserEvent>,
|
|
||||||
&mut ControlFlow,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> EventLoopExtRunReturn for EventLoop<T> {
|
|
||||||
type UserEvent = T;
|
|
||||||
|
|
||||||
fn run_return<F>(&mut self, event_handler: F) -> i32
|
|
||||||
where
|
|
||||||
F: FnMut(
|
|
||||||
Event<'_, Self::UserEvent>,
|
|
||||||
&EventLoopWindowTarget<Self::UserEvent>,
|
|
||||||
&mut ControlFlow,
|
|
||||||
),
|
|
||||||
{
|
|
||||||
self.event_loop.run_return(event_handler)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
50
src/platform/scancode.rs
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
use crate::keyboard::{KeyCode, PhysicalKey};
|
||||||
|
|
||||||
|
// TODO: Describe what this value contains for each platform
|
||||||
|
|
||||||
|
/// Additional methods for the [`PhysicalKey`] type that allow the user to access the platform-specific
|
||||||
|
/// scancode.
|
||||||
|
///
|
||||||
|
/// [`PhysicalKey`]: crate::keyboard::PhysicalKey
|
||||||
|
pub trait PhysicalKeyExtScancode {
|
||||||
|
/// The raw value of the platform-specific physical key identifier.
|
||||||
|
///
|
||||||
|
/// Returns `Some(key_id)` if the conversion was succesful; returns `None` otherwise.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
/// - **Windows:** A 16bit extended scancode
|
||||||
|
/// - **Wayland/X11**: A 32-bit linux scancode, which is X11/Wayland keycode subtracted by 8.
|
||||||
|
fn to_scancode(self) -> Option<u32>;
|
||||||
|
|
||||||
|
/// Constructs a `PhysicalKey` from a platform-specific physical key identifier.
|
||||||
|
///
|
||||||
|
/// Note that this conversion may be lossy, i.e. converting the returned `PhysicalKey` back
|
||||||
|
/// using `to_scancode` might not yield the original value.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
/// - **Wayland/X11**: A 32-bit linux scancode. When building from X11/Wayland keycode subtract
|
||||||
|
/// `8` to get the value you wanted.
|
||||||
|
fn from_scancode(scancode: u32) -> PhysicalKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PhysicalKeyExtScancode for PhysicalKey {
|
||||||
|
fn to_scancode(self) -> Option<u32> {
|
||||||
|
crate::platform_impl::physicalkey_to_scancode(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_scancode(scancode: u32) -> PhysicalKey {
|
||||||
|
crate::platform_impl::scancode_to_physicalkey(scancode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PhysicalKeyExtScancode for KeyCode {
|
||||||
|
#[inline]
|
||||||
|
fn to_scancode(self) -> Option<u32> {
|
||||||
|
<PhysicalKey as PhysicalKeyExtScancode>::to_scancode(PhysicalKey::Code(self))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn from_scancode(scancode: u32) -> PhysicalKey {
|
||||||
|
<PhysicalKey as PhysicalKeyExtScancode>::from_scancode(scancode)
|
||||||
|
}
|
||||||
|
}
|
||||||
99
src/platform/startup_notify.rs
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
//! Window startup notification to handle window raising.
|
||||||
|
//!
|
||||||
|
//! The [`ActivationToken`] is essential to ensure that your newly
|
||||||
|
//! created window will obtain the focus, otherwise the user could
|
||||||
|
//! be requered to click on the window.
|
||||||
|
//!
|
||||||
|
//! Such token is usually delivered via the environment variable and
|
||||||
|
//! could be read from it with the [`EventLoopExtStartupNotify::read_token_from_env`].
|
||||||
|
//!
|
||||||
|
//! Such token must also be reset after reading it from your environment with
|
||||||
|
//! [`reset_activation_token_env`] otherwise child processes could inherit it.
|
||||||
|
//!
|
||||||
|
//! When starting a new child process with a newly obtained [`ActivationToken`] from
|
||||||
|
//! [`WindowExtStartupNotify::request_activation_token`] the [`set_activation_token_env`]
|
||||||
|
//! must be used to propagate it to the child
|
||||||
|
//!
|
||||||
|
//! To ensure the delivery of such token by other processes to you, the user should
|
||||||
|
//! set `StartupNotify=true` inside the `.desktop` file of their application.
|
||||||
|
//!
|
||||||
|
//! The specification could be found [`here`].
|
||||||
|
//!
|
||||||
|
//! [`here`]: https://specifications.freedesktop.org/startup-notification-spec/startup-notification-latest.txt
|
||||||
|
|
||||||
|
use std::env;
|
||||||
|
|
||||||
|
use crate::error::NotSupportedError;
|
||||||
|
use crate::event_loop::{AsyncRequestSerial, EventLoopWindowTarget};
|
||||||
|
use crate::window::{ActivationToken, Window, WindowBuilder};
|
||||||
|
|
||||||
|
/// The variable which is used mostly on X11.
|
||||||
|
const X11_VAR: &str = "DESKTOP_STARTUP_ID";
|
||||||
|
|
||||||
|
/// The variable which is used mostly on Wayland.
|
||||||
|
const WAYLAND_VAR: &str = "XDG_ACTIVATION_TOKEN";
|
||||||
|
|
||||||
|
pub trait EventLoopExtStartupNotify {
|
||||||
|
/// Read the token from the environment.
|
||||||
|
///
|
||||||
|
/// It's recommended **to unset** this environment variable for child processes.
|
||||||
|
fn read_token_from_env(&self) -> Option<ActivationToken>;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait WindowExtStartupNotify {
|
||||||
|
/// Request a new activation token.
|
||||||
|
///
|
||||||
|
/// The token will be delivered inside
|
||||||
|
fn request_activation_token(&self) -> Result<AsyncRequestSerial, NotSupportedError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait WindowBuilderExtStartupNotify {
|
||||||
|
/// Use this [`ActivationToken`] during window creation.
|
||||||
|
///
|
||||||
|
/// Not using such a token upon a window could make your window not gaining
|
||||||
|
/// focus until the user clicks on the window.
|
||||||
|
fn with_activation_token(self, token: ActivationToken) -> Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopExtStartupNotify for EventLoopWindowTarget {
|
||||||
|
fn read_token_from_env(&self) -> Option<ActivationToken> {
|
||||||
|
match self.p {
|
||||||
|
#[cfg(wayland_platform)]
|
||||||
|
crate::platform_impl::EventLoopWindowTarget::Wayland(_) => env::var(WAYLAND_VAR),
|
||||||
|
#[cfg(x11_platform)]
|
||||||
|
crate::platform_impl::EventLoopWindowTarget::X(_) => env::var(X11_VAR),
|
||||||
|
}
|
||||||
|
.ok()
|
||||||
|
.map(ActivationToken::_new)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowExtStartupNotify for Window {
|
||||||
|
fn request_activation_token(&self) -> Result<AsyncRequestSerial, NotSupportedError> {
|
||||||
|
self.window.request_activation_token()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowBuilderExtStartupNotify for WindowBuilder {
|
||||||
|
fn with_activation_token(mut self, token: ActivationToken) -> Self {
|
||||||
|
self.window.platform_specific.activation_token = Some(token);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove the activation environment variables from the current process.
|
||||||
|
///
|
||||||
|
/// This is wise to do before running child processes,
|
||||||
|
/// which may not to support the activation token.
|
||||||
|
pub fn reset_activation_token_env() {
|
||||||
|
env::remove_var(X11_VAR);
|
||||||
|
env::remove_var(WAYLAND_VAR);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set environment variables responsible for activation token.
|
||||||
|
///
|
||||||
|
/// This could be used before running daemon processes.
|
||||||
|
pub fn set_activation_token_env(token: ActivationToken) {
|
||||||
|
env::set_var(X11_VAR, &token._token);
|
||||||
|
env::set_var(WAYLAND_VAR, token._token);
|
||||||
|
}
|
||||||
@@ -1,50 +1,22 @@
|
|||||||
use std::os::raw;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
event_loop::{EventLoopBuilder, EventLoopWindowTarget},
|
event_loop::{EventLoopBuilder, EventLoopWindowTarget},
|
||||||
monitor::MonitorHandle,
|
monitor::MonitorHandle,
|
||||||
window::{Window, WindowBuilder},
|
window::{Window, WindowBuilder},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::platform_impl::{
|
|
||||||
ApplicationName, Backend, EventLoopWindowTarget as LinuxEventLoopWindowTarget,
|
|
||||||
Window as LinuxWindow,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub use crate::window::Theme;
|
pub use crate::window::Theme;
|
||||||
|
|
||||||
/// Additional methods on [`EventLoopWindowTarget`] that are specific to Wayland.
|
/// Additional methods on [`EventLoopWindowTarget`] that are specific to Wayland.
|
||||||
pub trait EventLoopWindowTargetExtWayland {
|
pub trait EventLoopWindowTargetExtWayland {
|
||||||
/// True if the [`EventLoopWindowTarget`] uses Wayland.
|
/// True if the [`EventLoopWindowTarget`] uses Wayland.
|
||||||
fn is_wayland(&self) -> bool;
|
fn is_wayland(&self) -> bool;
|
||||||
|
|
||||||
/// Returns a pointer to the `wl_display` object of wayland that is used by this
|
|
||||||
/// [`EventLoopWindowTarget`].
|
|
||||||
///
|
|
||||||
/// Returns `None` if the [`EventLoop`] doesn't use wayland (if it uses xlib for example).
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the winit [`EventLoop`] is destroyed.
|
|
||||||
///
|
|
||||||
/// [`EventLoop`]: crate::event_loop::EventLoop
|
|
||||||
fn wayland_display(&self) -> Option<*mut raw::c_void>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoopWindowTargetExtWayland for EventLoopWindowTarget<T> {
|
impl EventLoopWindowTargetExtWayland for EventLoopWindowTarget {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn is_wayland(&self) -> bool {
|
fn is_wayland(&self) -> bool {
|
||||||
self.p.is_wayland()
|
self.p.is_wayland()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn wayland_display(&self) -> Option<*mut raw::c_void> {
|
|
||||||
match self.p {
|
|
||||||
LinuxEventLoopWindowTarget::Wayland(ref p) => {
|
|
||||||
Some(p.display().get_display_ptr() as *mut _)
|
|
||||||
}
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Additional methods on [`EventLoopBuilder`] that are specific to Wayland.
|
/// Additional methods on [`EventLoopBuilder`] that are specific to Wayland.
|
||||||
@@ -62,7 +34,7 @@ pub trait EventLoopBuilderExtWayland {
|
|||||||
impl<T> EventLoopBuilderExtWayland for EventLoopBuilder<T> {
|
impl<T> EventLoopBuilderExtWayland for EventLoopBuilder<T> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_wayland(&mut self) -> &mut Self {
|
fn with_wayland(&mut self) -> &mut Self {
|
||||||
self.platform_specific.forced_backend = Some(Backend::Wayland);
|
self.platform_specific.forced_backend = Some(crate::platform_impl::Backend::Wayland);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,41 +46,9 @@ impl<T> EventLoopBuilderExtWayland for EventLoopBuilder<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Additional methods on [`Window`] that are specific to Wayland.
|
/// Additional methods on [`Window`] that are specific to Wayland.
|
||||||
pub trait WindowExtWayland {
|
pub trait WindowExtWayland {}
|
||||||
/// Returns a pointer to the `wl_surface` object of wayland that is used by this window.
|
|
||||||
///
|
|
||||||
/// Returns `None` if the window doesn't use wayland (if it uses xlib for example).
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the [`Window`] is destroyed.
|
|
||||||
fn wayland_surface(&self) -> Option<*mut raw::c_void>;
|
|
||||||
|
|
||||||
/// Returns a pointer to the `wl_display` object of wayland that is used by this window.
|
impl WindowExtWayland for Window {}
|
||||||
///
|
|
||||||
/// Returns `None` if the window doesn't use wayland (if it uses xlib for example).
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the [`Window`] is destroyed.
|
|
||||||
fn wayland_display(&self) -> Option<*mut raw::c_void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowExtWayland for Window {
|
|
||||||
#[inline]
|
|
||||||
fn wayland_surface(&self) -> Option<*mut raw::c_void> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::Wayland(ref w) => Some(w.surface().as_ref().c_ptr() as *mut _),
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn wayland_display(&self) -> Option<*mut raw::c_void> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::Wayland(ref w) => Some(w.display().get_display_ptr() as *mut _),
|
|
||||||
#[cfg(x11_platform)]
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on [`WindowBuilder`] that are specific to Wayland.
|
/// Additional methods on [`WindowBuilder`] that are specific to Wayland.
|
||||||
pub trait WindowBuilderExtWayland {
|
pub trait WindowBuilderExtWayland {
|
||||||
@@ -125,7 +65,10 @@ pub trait WindowBuilderExtWayland {
|
|||||||
impl WindowBuilderExtWayland for WindowBuilder {
|
impl WindowBuilderExtWayland for WindowBuilder {
|
||||||
#[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(ApplicationName::new(general.into(), instance.into()));
|
self.window.platform_specific.name = Some(crate::platform_impl::ApplicationName::new(
|
||||||
|
general.into(),
|
||||||
|
instance.into(),
|
||||||
|
));
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,53 +2,141 @@
|
|||||||
//! allow end users to determine how the page should be laid out. Use the [`WindowExtWebSys`] trait
|
//! allow end users to determine how the page should be laid out. Use the [`WindowExtWebSys`] trait
|
||||||
//! to retrieve the canvas from the Window. Alternatively, use the [`WindowBuilderExtWebSys`] trait
|
//! to retrieve the canvas from the Window. Alternatively, use the [`WindowBuilderExtWebSys`] trait
|
||||||
//! to provide your own canvas.
|
//! to provide your own canvas.
|
||||||
|
//!
|
||||||
|
//! It is recommended **not** to apply certain CSS properties to the canvas:
|
||||||
|
//! - [`transform`]
|
||||||
|
//! - [`border`]
|
||||||
|
//! - [`padding`]
|
||||||
|
//!
|
||||||
|
//! The following APIs can't take them into account and will therefore provide inaccurate results:
|
||||||
|
//! - [`WindowEvent::Resized`] and [`Window::(set_)inner_size()`]
|
||||||
|
//! - [`WindowEvent::Occluded`]
|
||||||
|
//! - [`WindowEvent::CursorMoved`], [`WindowEvent::CursorEntered`], [`WindowEvent::CursorLeft`],
|
||||||
|
//! and [`WindowEvent::Touch`].
|
||||||
|
//! - [`Window::set_outer_position()`]
|
||||||
|
//!
|
||||||
|
//! [`WindowEvent::Resized`]: crate::event::WindowEvent::Resized
|
||||||
|
//! [`Window::(set_)inner_size()`]: crate::window::Window::inner_size()
|
||||||
|
//! [`WindowEvent::Occluded`]: crate::event::WindowEvent::Occluded
|
||||||
|
//! [`WindowEvent::CursorMoved`]: crate::event::WindowEvent::CursorMoved
|
||||||
|
//! [`WindowEvent::CursorEntered`]: crate::event::WindowEvent::CursorEntered
|
||||||
|
//! [`WindowEvent::CursorLeft`]: crate::event::WindowEvent::CursorLeft
|
||||||
|
//! [`WindowEvent::Touch`]: crate::event::WindowEvent::Touch
|
||||||
|
//! [`Window::set_outer_position()`]: crate::window::Window::set_outer_position()
|
||||||
|
//! [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform
|
||||||
|
//! [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border
|
||||||
|
//! [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding
|
||||||
|
|
||||||
use crate::event::Event;
|
use std::error::Error;
|
||||||
use crate::event_loop::ControlFlow;
|
use std::fmt::{self, Display, Formatter};
|
||||||
use crate::event_loop::EventLoop;
|
use std::future::Future;
|
||||||
use crate::event_loop::EventLoopWindowTarget;
|
use std::pin::Pin;
|
||||||
use crate::window::WindowBuilder;
|
use std::task::{Context, Poll};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
#[cfg(web_platform)]
|
||||||
use web_sys::HtmlCanvasElement;
|
use web_sys::HtmlCanvasElement;
|
||||||
|
|
||||||
pub trait WindowExtWebSys {
|
use crate::cursor::CustomCursorBuilder;
|
||||||
fn canvas(&self) -> HtmlCanvasElement;
|
use crate::event::Event;
|
||||||
|
use crate::event_loop::{EventLoop, EventLoopWindowTarget};
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
use crate::platform_impl::CustomCursorFuture as PlatformCustomCursorFuture;
|
||||||
|
use crate::platform_impl::{PlatformCustomCursor, PlatformCustomCursorBuilder};
|
||||||
|
use crate::window::{CustomCursor, Window, WindowBuilder};
|
||||||
|
|
||||||
/// Whether the browser reports the preferred color scheme to be "dark".
|
#[cfg(not(web_platform))]
|
||||||
fn is_dark_mode(&self) -> bool;
|
#[doc(hidden)]
|
||||||
|
pub struct HtmlCanvasElement;
|
||||||
|
|
||||||
|
pub trait WindowExtWebSys {
|
||||||
|
/// Only returns the canvas if called from inside the window context (the
|
||||||
|
/// main thread).
|
||||||
|
fn canvas(&self) -> Option<HtmlCanvasElement>;
|
||||||
|
|
||||||
|
/// Returns [`true`] if calling `event.preventDefault()` is enabled.
|
||||||
|
///
|
||||||
|
/// See [`Window::set_prevent_default()`] for more details.
|
||||||
|
fn prevent_default(&self) -> bool;
|
||||||
|
|
||||||
|
/// Sets whether `event.preventDefault()` should be called on events on the
|
||||||
|
/// canvas that have side effects.
|
||||||
|
///
|
||||||
|
/// For example, by default using the mouse wheel would cause the page to scroll, enabling this
|
||||||
|
/// would prevent that.
|
||||||
|
///
|
||||||
|
/// Some events are impossible to prevent. E.g. Firefox allows to access the native browser
|
||||||
|
/// context menu with Shift+Rightclick.
|
||||||
|
fn set_prevent_default(&self, prevent_default: bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowExtWebSys for Window {
|
||||||
|
#[inline]
|
||||||
|
fn canvas(&self) -> Option<HtmlCanvasElement> {
|
||||||
|
self.window.canvas()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prevent_default(&self) -> bool {
|
||||||
|
self.window.prevent_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_prevent_default(&self, prevent_default: bool) {
|
||||||
|
self.window.set_prevent_default(prevent_default)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait WindowBuilderExtWebSys {
|
pub trait WindowBuilderExtWebSys {
|
||||||
|
/// Pass an [`HtmlCanvasElement`] to be used for this [`Window`]. If [`None`],
|
||||||
|
/// [`WindowBuilder::build()`] will create one.
|
||||||
|
///
|
||||||
|
/// In any case, the canvas won't be automatically inserted into the web page.
|
||||||
|
///
|
||||||
|
/// [`None`] by default.
|
||||||
|
#[cfg_attr(
|
||||||
|
not(web_platform),
|
||||||
|
doc = "",
|
||||||
|
doc = "[`HtmlCanvasElement`]: #only-available-on-wasm"
|
||||||
|
)]
|
||||||
fn with_canvas(self, canvas: Option<HtmlCanvasElement>) -> Self;
|
fn with_canvas(self, canvas: Option<HtmlCanvasElement>) -> Self;
|
||||||
|
|
||||||
/// Whether `event.preventDefault` should be automatically called to prevent event propagation
|
/// Sets whether `event.preventDefault()` should be called on events on the
|
||||||
/// when appropriate.
|
/// canvas that have side effects.
|
||||||
///
|
///
|
||||||
/// For example, mouse wheel events are only handled by the canvas by default. This avoids
|
/// See [`Window::set_prevent_default()`] for more details.
|
||||||
/// the default behavior of scrolling the page.
|
///
|
||||||
|
/// Enabled by default.
|
||||||
fn with_prevent_default(self, prevent_default: bool) -> Self;
|
fn with_prevent_default(self, prevent_default: bool) -> Self;
|
||||||
|
|
||||||
/// Whether the canvas should be focusable using the tab key. This is necessary to capture
|
/// Whether the canvas should be focusable using the tab key. This is necessary to capture
|
||||||
/// canvas keyboard events.
|
/// canvas keyboard events.
|
||||||
|
///
|
||||||
|
/// 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.
|
||||||
|
///
|
||||||
|
/// Disabled by default.
|
||||||
|
fn with_append(self, append: bool) -> Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowBuilderExtWebSys for WindowBuilder {
|
impl WindowBuilderExtWebSys for WindowBuilder {
|
||||||
fn with_canvas(mut self, canvas: Option<HtmlCanvasElement>) -> Self {
|
fn with_canvas(mut self, canvas: Option<HtmlCanvasElement>) -> Self {
|
||||||
self.platform_specific.canvas = canvas;
|
self.window.platform_specific.set_canvas(canvas);
|
||||||
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
fn with_prevent_default(mut self, prevent_default: bool) -> Self {
|
fn with_prevent_default(mut self, prevent_default: bool) -> Self {
|
||||||
self.platform_specific.prevent_default = prevent_default;
|
self.window.platform_specific.prevent_default = prevent_default;
|
||||||
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
fn with_focusable(mut self, focusable: bool) -> Self {
|
fn with_focusable(mut self, focusable: bool) -> Self {
|
||||||
self.platform_specific.focusable = focusable;
|
self.window.platform_specific.focusable = focusable;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn with_append(mut self, append: bool) -> Self {
|
||||||
|
self.window.platform_specific.append = append;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -60,16 +148,31 @@ pub trait EventLoopExtWebSys {
|
|||||||
|
|
||||||
/// Initializes the winit event loop.
|
/// Initializes the winit event loop.
|
||||||
///
|
///
|
||||||
/// Unlike `run`, this returns immediately, and doesn't throw an exception in order to
|
/// Unlike
|
||||||
/// satisfy its `!` return type.
|
#[cfg_attr(
|
||||||
|
all(web_platform, target_feature = "exception-handling"),
|
||||||
|
doc = "`run()`"
|
||||||
|
)]
|
||||||
|
#[cfg_attr(
|
||||||
|
not(all(web_platform, target_feature = "exception-handling")),
|
||||||
|
doc = "[`run()`]"
|
||||||
|
)]
|
||||||
|
/// [^1], this returns immediately, and doesn't throw an exception in order to
|
||||||
|
/// satisfy its [`!`] return type.
|
||||||
|
///
|
||||||
|
/// Once the event loop has been destroyed, it's possible to reinitialize another event loop
|
||||||
|
/// by calling this function again. This can be useful if you want to recreate the event loop
|
||||||
|
/// while the WebAssembly module is still loaded. For example, this can be used to recreate the
|
||||||
|
/// event loop when switching between tabs on a single page application.
|
||||||
|
///
|
||||||
|
#[cfg_attr(
|
||||||
|
not(all(web_platform, target_feature = "exception-handling")),
|
||||||
|
doc = "[`run()`]: EventLoop::run()"
|
||||||
|
)]
|
||||||
|
/// [^1]: `run()` is _not_ available on WASM when the target supports `exception-handling`.
|
||||||
fn spawn<F>(self, event_handler: F)
|
fn spawn<F>(self, event_handler: F)
|
||||||
where
|
where
|
||||||
F: 'static
|
F: 'static + FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget);
|
||||||
+ FnMut(
|
|
||||||
Event<'_, Self::UserEvent>,
|
|
||||||
&EventLoopWindowTarget<Self::UserEvent>,
|
|
||||||
&mut ControlFlow,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoopExtWebSys for EventLoop<T> {
|
impl<T> EventLoopExtWebSys for EventLoop<T> {
|
||||||
@@ -77,13 +180,185 @@ impl<T> EventLoopExtWebSys for EventLoop<T> {
|
|||||||
|
|
||||||
fn spawn<F>(self, event_handler: F)
|
fn spawn<F>(self, event_handler: F)
|
||||||
where
|
where
|
||||||
F: 'static
|
F: 'static + FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget),
|
||||||
+ FnMut(
|
|
||||||
Event<'_, Self::UserEvent>,
|
|
||||||
&EventLoopWindowTarget<Self::UserEvent>,
|
|
||||||
&mut ControlFlow,
|
|
||||||
),
|
|
||||||
{
|
{
|
||||||
self.event_loop.spawn(event_handler)
|
self.event_loop.spawn(event_handler)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub trait EventLoopWindowTargetExtWebSys {
|
||||||
|
/// 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopWindowTargetExtWebSys for EventLoopWindowTarget {
|
||||||
|
#[inline]
|
||||||
|
fn set_poll_strategy(&self, strategy: PollStrategy) {
|
||||||
|
self.p.set_poll_strategy(strategy);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn poll_strategy(&self) -> PollStrategy {
|
||||||
|
self.p.poll_strategy()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strategy used for [`ControlFlow::Poll`](crate::event_loop::ControlFlow::Poll).
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub enum PollStrategy {
|
||||||
|
/// Uses [`Window.requestIdleCallback()`] to queue the next event loop. If not available
|
||||||
|
/// this will fallback to [`setTimeout()`].
|
||||||
|
///
|
||||||
|
/// This strategy will wait for the browser to enter an idle period before running and might
|
||||||
|
/// be affected by browser throttling.
|
||||||
|
///
|
||||||
|
/// [`Window.requestIdleCallback()`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback
|
||||||
|
/// [`setTimeout()`]: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
|
||||||
|
IdleCallback,
|
||||||
|
/// Uses the [Prioritized Task Scheduling API] to queue the next event loop. If not available
|
||||||
|
/// this will fallback to [`setTimeout()`].
|
||||||
|
///
|
||||||
|
/// This strategy will run as fast as possible without disturbing users from interacting with
|
||||||
|
/// the page and is not affected by browser throttling.
|
||||||
|
///
|
||||||
|
/// This is the default strategy.
|
||||||
|
///
|
||||||
|
/// [Prioritized Task Scheduling API]: https://developer.mozilla.org/en-US/docs/Web/API/Prioritized_Task_Scheduling_API
|
||||||
|
/// [`setTimeout()`]: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
|
||||||
|
#[default]
|
||||||
|
Scheduler,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait CustomCursorExtWebSys {
|
||||||
|
/// Returns if this cursor is an animation.
|
||||||
|
fn is_animation(&self) -> bool;
|
||||||
|
|
||||||
|
/// Creates a new cursor from a URL pointing to an image.
|
||||||
|
/// It uses the [url css function](https://developer.mozilla.org/en-US/docs/Web/CSS/url),
|
||||||
|
/// but browser support for image formats is inconsistent. Using [PNG] is recommended.
|
||||||
|
///
|
||||||
|
/// [PNG]: https://en.wikipedia.org/wiki/PNG
|
||||||
|
fn from_url(url: String, hotspot_x: u16, hotspot_y: u16) -> CustomCursorBuilder;
|
||||||
|
|
||||||
|
/// Crates a new animated cursor from multiple [`CustomCursor`]s.
|
||||||
|
/// Supplied `cursors` can't be empty or other animations.
|
||||||
|
fn from_animation(
|
||||||
|
duration: Duration,
|
||||||
|
cursors: Vec<CustomCursor>,
|
||||||
|
) -> Result<CustomCursorBuilder, BadAnimation>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CustomCursorExtWebSys for CustomCursor {
|
||||||
|
fn is_animation(&self) -> bool {
|
||||||
|
self.inner.animation
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_url(url: String, hotspot_x: u16, hotspot_y: u16) -> CustomCursorBuilder {
|
||||||
|
CustomCursorBuilder {
|
||||||
|
inner: PlatformCustomCursorBuilder::Url {
|
||||||
|
url,
|
||||||
|
hotspot_x,
|
||||||
|
hotspot_y,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_animation(
|
||||||
|
duration: Duration,
|
||||||
|
cursors: Vec<CustomCursor>,
|
||||||
|
) -> Result<CustomCursorBuilder, BadAnimation> {
|
||||||
|
if cursors.is_empty() {
|
||||||
|
return Err(BadAnimation::Empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
if cursors.iter().any(CustomCursor::is_animation) {
|
||||||
|
return Err(BadAnimation::Animation);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(CustomCursorBuilder {
|
||||||
|
inner: PlatformCustomCursorBuilder::Animation { duration, cursors },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An error produced when using [`CustomCursor::from_animation`] with invalid arguments.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum BadAnimation {
|
||||||
|
/// Produced when no cursors were supplied.
|
||||||
|
Empty,
|
||||||
|
/// Produced when a supplied cursor is an animation.
|
||||||
|
Animation,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for BadAnimation {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Empty => write!(f, "No cursors supplied"),
|
||||||
|
Self::Animation => write!(f, "A supplied cursor is an animtion"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for BadAnimation {}
|
||||||
|
|
||||||
|
pub trait CustomCursorBuilderExtWebSys {
|
||||||
|
/// Async version of [`CustomCursorBuilder::build()`] which waits until the
|
||||||
|
/// cursor has completely finished loading.
|
||||||
|
fn build_async(self, window_target: &EventLoopWindowTarget) -> CustomCursorFuture;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CustomCursorBuilderExtWebSys for CustomCursorBuilder {
|
||||||
|
fn build_async(self, window_target: &EventLoopWindowTarget) -> CustomCursorFuture {
|
||||||
|
CustomCursorFuture(PlatformCustomCursor::build_async(
|
||||||
|
self.inner,
|
||||||
|
&window_target.p,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
struct PlatformCustomCursorFuture;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct CustomCursorFuture(PlatformCustomCursorFuture);
|
||||||
|
|
||||||
|
impl Future for CustomCursorFuture {
|
||||||
|
type Output = Result<CustomCursor, CustomCursorError>;
|
||||||
|
|
||||||
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
Pin::new(&mut self.0)
|
||||||
|
.poll(cx)
|
||||||
|
.map_ok(|cursor| CustomCursor { inner: cursor })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub enum CustomCursorError {
|
||||||
|
Blob,
|
||||||
|
Decode(String),
|
||||||
|
Animation,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for CustomCursorError {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Blob => write!(f, "failed to create `Blob`"),
|
||||||
|
Self::Decode(error) => write!(f, "failed to decode image: {error}"),
|
||||||
|
Self::Animation => write!(
|
||||||
|
f,
|
||||||
|
"found `CustomCursor` that is an animation when building an animation"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ use crate::{
|
|||||||
event::DeviceId,
|
event::DeviceId,
|
||||||
event_loop::EventLoopBuilder,
|
event_loop::EventLoopBuilder,
|
||||||
monitor::MonitorHandle,
|
monitor::MonitorHandle,
|
||||||
platform_impl::WinIcon,
|
|
||||||
window::{BadIcon, Icon, Window, WindowBuilder},
|
window::{BadIcon, Icon, Window, WindowBuilder},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -15,8 +14,92 @@ pub type HWND = isize;
|
|||||||
pub type HMENU = isize;
|
pub type HMENU = isize;
|
||||||
/// Monitor Handle type used by Win32 API
|
/// Monitor Handle type used by Win32 API
|
||||||
pub type HMONITOR = isize;
|
pub type HMONITOR = isize;
|
||||||
/// Instance Handle type used by Win32 API
|
|
||||||
pub type HINSTANCE = isize;
|
/// Describes a system-drawn backdrop material of a window.
|
||||||
|
///
|
||||||
|
/// For a detailed explanation, see [`DWM_SYSTEMBACKDROP_TYPE docs`].
|
||||||
|
///
|
||||||
|
/// [`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)]
|
||||||
|
pub enum BackdropType {
|
||||||
|
/// Corresponds to `DWMSBT_AUTO`.
|
||||||
|
///
|
||||||
|
/// Usually draws a default backdrop effect on the title bar.
|
||||||
|
#[default]
|
||||||
|
Auto = 0,
|
||||||
|
|
||||||
|
/// Corresponds to `DWMSBT_NONE`.
|
||||||
|
None = 1,
|
||||||
|
|
||||||
|
/// Corresponds to `DWMSBT_MAINWINDOW`.
|
||||||
|
///
|
||||||
|
/// Draws the Mica backdrop material.
|
||||||
|
MainWindow = 2,
|
||||||
|
|
||||||
|
/// Corresponds to `DWMSBT_TRANSIENTWINDOW`.
|
||||||
|
///
|
||||||
|
/// Draws the Background Acrylic backdrop material.
|
||||||
|
TransientWindow = 3,
|
||||||
|
|
||||||
|
/// Corresponds to `DWMSBT_TABBEDWINDOW`.
|
||||||
|
///
|
||||||
|
/// Draws the Alt Mica backdrop material.
|
||||||
|
TabbedWindow = 4,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Describes a color used by Windows
|
||||||
|
#[repr(transparent)]
|
||||||
|
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
|
||||||
|
pub struct Color(u32);
|
||||||
|
|
||||||
|
impl Color {
|
||||||
|
/// Use the system's default color
|
||||||
|
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
|
||||||
|
pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
|
||||||
|
Self((r as u32) | ((g as u32) << 8) | ((b as u32) << 16))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Color {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::SYSTEM_DEFAULT
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Describes how the corners of a window should look like.
|
||||||
|
///
|
||||||
|
/// For a detailed explanation, see [`DWM_WINDOW_CORNER_PREFERENCE docs`].
|
||||||
|
///
|
||||||
|
/// [`DWM_WINDOW_CORNER_PREFERENCE docs`]: https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_window_corner_preference
|
||||||
|
#[repr(i32)]
|
||||||
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub enum CornerPreference {
|
||||||
|
/// Corresponds to `DWMWCP_DEFAULT`.
|
||||||
|
///
|
||||||
|
/// Let the system decide when to round window corners.
|
||||||
|
#[default]
|
||||||
|
Default = 0,
|
||||||
|
|
||||||
|
/// Corresponds to `DWMWCP_DONOTROUND`.
|
||||||
|
///
|
||||||
|
/// Never round window corners.
|
||||||
|
DoNotRound = 1,
|
||||||
|
|
||||||
|
/// Corresponds to `DWMWCP_ROUND`.
|
||||||
|
///
|
||||||
|
/// Round the corners, if appropriate.
|
||||||
|
Round = 2,
|
||||||
|
|
||||||
|
/// Corresponds to `DWMWCP_ROUNDSMALL`.
|
||||||
|
///
|
||||||
|
/// Round the corners if appropriate, with a small radius.
|
||||||
|
RoundSmall = 3,
|
||||||
|
}
|
||||||
|
|
||||||
/// Additional methods on `EventLoop` that are specific to Windows.
|
/// Additional methods on `EventLoop` that are specific to Windows.
|
||||||
pub trait EventLoopBuilderExtWindows {
|
pub trait EventLoopBuilderExtWindows {
|
||||||
@@ -111,13 +194,6 @@ impl<T> EventLoopBuilderExtWindows for EventLoopBuilder<T> {
|
|||||||
|
|
||||||
/// Additional methods on `Window` that are specific to Windows.
|
/// Additional methods on `Window` that are specific to Windows.
|
||||||
pub trait WindowExtWindows {
|
pub trait WindowExtWindows {
|
||||||
/// Returns the HINSTANCE of the window
|
|
||||||
fn hinstance(&self) -> HINSTANCE;
|
|
||||||
/// Returns the native handle that is used by this window.
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the native window was destroyed.
|
|
||||||
fn hwnd(&self) -> HWND;
|
|
||||||
|
|
||||||
/// Enables or disables mouse and keyboard input to the specified window.
|
/// Enables or disables mouse and keyboard input to the specified window.
|
||||||
///
|
///
|
||||||
/// A window must be enabled before it can be activated.
|
/// A window must be enabled before it can be activated.
|
||||||
@@ -143,19 +219,34 @@ pub trait WindowExtWindows {
|
|||||||
///
|
///
|
||||||
/// Enabling the shadow causes a thin 1px line to appear on the top of the window.
|
/// Enabling the shadow causes a thin 1px line to appear on the top of the window.
|
||||||
fn set_undecorated_shadow(&self, shadow: bool);
|
fn set_undecorated_shadow(&self, shadow: bool);
|
||||||
|
|
||||||
|
/// Sets system-drawn backdrop type.
|
||||||
|
///
|
||||||
|
/// Requires Windows 11 build 22523+.
|
||||||
|
fn set_system_backdrop(&self, backdrop_type: BackdropType);
|
||||||
|
|
||||||
|
/// Sets the color of the window border.
|
||||||
|
///
|
||||||
|
/// Supported starting with Windows 11 Build 22000.
|
||||||
|
fn set_border_color(&self, color: Option<Color>);
|
||||||
|
|
||||||
|
/// Sets the background color of the title bar.
|
||||||
|
///
|
||||||
|
/// Supported starting with Windows 11 Build 22000.
|
||||||
|
fn set_title_background_color(&self, color: Option<Color>);
|
||||||
|
|
||||||
|
/// Sets the color of the window title.
|
||||||
|
///
|
||||||
|
/// Supported starting with Windows 11 Build 22000.
|
||||||
|
fn set_title_text_color(&self, color: Color);
|
||||||
|
|
||||||
|
/// Sets the preferred style of the window corners.
|
||||||
|
///
|
||||||
|
/// Supported starting with Windows 11 Build 22000.
|
||||||
|
fn set_corner_preference(&self, preference: CornerPreference);
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowExtWindows for Window {
|
impl WindowExtWindows for Window {
|
||||||
#[inline]
|
|
||||||
fn hinstance(&self) -> HINSTANCE {
|
|
||||||
self.window.hinstance()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn hwnd(&self) -> HWND {
|
|
||||||
self.window.hwnd()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn set_enable(&self, enabled: bool) {
|
fn set_enable(&self, enabled: bool) {
|
||||||
self.window.set_enable(enabled)
|
self.window.set_enable(enabled)
|
||||||
@@ -175,9 +266,38 @@ impl WindowExtWindows for Window {
|
|||||||
fn set_undecorated_shadow(&self, shadow: bool) {
|
fn set_undecorated_shadow(&self, shadow: bool) {
|
||||||
self.window.set_undecorated_shadow(shadow)
|
self.window.set_undecorated_shadow(shadow)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_system_backdrop(&self, backdrop_type: BackdropType) {
|
||||||
|
self.window.set_system_backdrop(backdrop_type)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_border_color(&self, color: Option<Color>) {
|
||||||
|
self.window.set_border_color(color.unwrap_or(Color::NONE))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
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
|
||||||
|
// to circumvent the Windows option "Show accent color on title bars and window borders"
|
||||||
|
self.window
|
||||||
|
.set_title_background_color(color.unwrap_or(Color::NONE))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_title_text_color(&self, color: Color) {
|
||||||
|
self.window.set_title_text_color(color)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_corner_preference(&self, preference: CornerPreference) {
|
||||||
|
self.window.set_corner_preference(preference)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Additional methods on `WindowBuilder` that are specific to Windows.
|
/// Additional methods on `WindowBuilder` that are specific to Windows.
|
||||||
|
#[allow(rustdoc::broken_intra_doc_links)]
|
||||||
pub trait WindowBuilderExtWindows {
|
pub trait WindowBuilderExtWindows {
|
||||||
/// 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 [`WindowBuilder::with_parent_window`] isn't called or set to `None`.
|
/// This only works when [`WindowBuilder::with_parent_window`] isn't called or set to `None`.
|
||||||
@@ -190,7 +310,7 @@ pub trait WindowBuilderExtWindows {
|
|||||||
/// - An owned window is hidden when its owner is minimized.
|
/// - An owned window is hidden when its owner is minimized.
|
||||||
///
|
///
|
||||||
/// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
|
/// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
|
||||||
fn with_owner_window(self, parent: HWND) -> WindowBuilder;
|
fn with_owner_window(self, parent: HWND) -> Self;
|
||||||
|
|
||||||
/// Sets a menu on the window to be created.
|
/// Sets a menu on the window to be created.
|
||||||
///
|
///
|
||||||
@@ -201,14 +321,21 @@ pub trait WindowBuilderExtWindows {
|
|||||||
/// 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 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.
|
/// If you use this, it is recommended that you combine it with `with_theme(Some(Theme::Light))` to avoid a jarring effect.
|
||||||
///
|
///
|
||||||
/// [`CreateMenu`]: windows_sys::Win32::UI::WindowsAndMessaging::CreateMenu
|
#[cfg_attr(
|
||||||
fn with_menu(self, menu: HMENU) -> WindowBuilder;
|
platform_windows,
|
||||||
|
doc = "[`CreateMenu`]: windows_sys::Win32::UI::WindowsAndMessaging::CreateMenu"
|
||||||
|
)]
|
||||||
|
#[cfg_attr(
|
||||||
|
not(platform_windows),
|
||||||
|
doc = "[`CreateMenu`]: #only-available-on-windows"
|
||||||
|
)]
|
||||||
|
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.
|
||||||
fn with_taskbar_icon(self, taskbar_icon: Option<Icon>) -> WindowBuilder;
|
fn with_taskbar_icon(self, taskbar_icon: Option<Icon>) -> Self;
|
||||||
|
|
||||||
/// This sets `WS_EX_NOREDIRECTIONBITMAP`.
|
/// This sets `WS_EX_NOREDIRECTIONBITMAP`.
|
||||||
fn with_no_redirection_bitmap(self, flag: bool) -> WindowBuilder;
|
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 crates
|
||||||
/// that use multi-threaded COM API (`CoInitializeEx` with `COINIT_MULTITHREADED` instead of
|
/// that use multi-threaded COM API (`CoInitializeEx` with `COINIT_MULTITHREADED` instead of
|
||||||
@@ -216,58 +343,131 @@ pub trait WindowBuilderExtWindows {
|
|||||||
/// COM API regardless of this option. Currently only fullscreen mode does that, but there may be more in the future.
|
/// COM API regardless of this option. Currently only fullscreen mode does that, but there may be more in the future.
|
||||||
/// If you need COM API with `COINIT_MULTITHREADED` you must initialize it before calling any winit functions.
|
/// If you need COM API with `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.
|
/// 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) -> WindowBuilder;
|
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.
|
||||||
fn with_skip_taskbar(self, skip: bool) -> WindowBuilder;
|
fn with_skip_taskbar(self, skip: bool) -> Self;
|
||||||
|
|
||||||
|
/// Customize the window class name.
|
||||||
|
fn with_class_name<S: Into<String>>(self, class_name: S) -> Self;
|
||||||
|
|
||||||
/// Shows or hides the background drop shadow for undecorated windows.
|
/// Shows or hides the background drop shadow for undecorated windows.
|
||||||
///
|
///
|
||||||
/// The shadow is hidden by default.
|
/// The shadow is hidden by default.
|
||||||
/// Enabling the shadow causes a thin 1px line to appear on the top of the window.
|
/// Enabling the shadow causes a thin 1px line to appear on the top of the window.
|
||||||
fn with_undecorated_shadow(self, shadow: bool) -> WindowBuilder;
|
fn with_undecorated_shadow(self, shadow: bool) -> Self;
|
||||||
|
|
||||||
|
/// Sets system-drawn backdrop type.
|
||||||
|
///
|
||||||
|
/// Requires Windows 11 build 22523+.
|
||||||
|
fn with_system_backdrop(self, backdrop_type: BackdropType) -> Self;
|
||||||
|
|
||||||
|
/// This sets or removes `WS_CLIPCHILDREN` style.
|
||||||
|
fn with_clip_children(self, flag: bool) -> Self;
|
||||||
|
|
||||||
|
/// Sets the color of the window border.
|
||||||
|
///
|
||||||
|
/// Supported starting with Windows 11 Build 22000.
|
||||||
|
fn with_border_color(self, color: Option<Color>) -> Self;
|
||||||
|
|
||||||
|
/// Sets the background color of the title bar.
|
||||||
|
///
|
||||||
|
/// Supported starting with Windows 11 Build 22000.
|
||||||
|
fn with_title_background_color(self, color: Option<Color>) -> Self;
|
||||||
|
|
||||||
|
/// Sets the color of the window title.
|
||||||
|
///
|
||||||
|
/// Supported starting with Windows 11 Build 22000.
|
||||||
|
fn with_title_text_color(self, color: Color) -> Self;
|
||||||
|
|
||||||
|
/// Sets the preferred style of the window corners.
|
||||||
|
///
|
||||||
|
/// Supported starting with Windows 11 Build 22000.
|
||||||
|
fn with_corner_preference(self, corners: CornerPreference) -> Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowBuilderExtWindows for WindowBuilder {
|
impl WindowBuilderExtWindows for WindowBuilder {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_owner_window(mut self, parent: HWND) -> WindowBuilder {
|
fn with_owner_window(mut self, parent: HWND) -> Self {
|
||||||
self.platform_specific.owner = Some(parent);
|
self.window.platform_specific.owner = Some(parent);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_menu(mut self, menu: HMENU) -> WindowBuilder {
|
fn with_menu(mut self, menu: HMENU) -> Self {
|
||||||
self.platform_specific.menu = Some(menu);
|
self.window.platform_specific.menu = Some(menu);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_taskbar_icon(mut self, taskbar_icon: Option<Icon>) -> WindowBuilder {
|
fn with_taskbar_icon(mut self, taskbar_icon: Option<Icon>) -> Self {
|
||||||
self.platform_specific.taskbar_icon = taskbar_icon;
|
self.window.platform_specific.taskbar_icon = taskbar_icon;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_no_redirection_bitmap(mut self, flag: bool) -> WindowBuilder {
|
fn with_no_redirection_bitmap(mut self, flag: bool) -> Self {
|
||||||
self.platform_specific.no_redirection_bitmap = flag;
|
self.window.platform_specific.no_redirection_bitmap = flag;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_drag_and_drop(mut self, flag: bool) -> WindowBuilder {
|
fn with_drag_and_drop(mut self, flag: bool) -> Self {
|
||||||
self.platform_specific.drag_and_drop = flag;
|
self.window.platform_specific.drag_and_drop = flag;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_skip_taskbar(mut self, skip: bool) -> WindowBuilder {
|
fn with_skip_taskbar(mut self, skip: bool) -> Self {
|
||||||
self.platform_specific.skip_taskbar = skip;
|
self.window.platform_specific.skip_taskbar = skip;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_undecorated_shadow(mut self, shadow: bool) -> WindowBuilder {
|
fn with_class_name<S: Into<String>>(mut self, class_name: S) -> Self {
|
||||||
self.platform_specific.decoration_shadow = shadow;
|
self.window.platform_specific.class_name = class_name.into();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_undecorated_shadow(mut self, shadow: bool) -> Self {
|
||||||
|
self.window.platform_specific.decoration_shadow = shadow;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_system_backdrop(mut self, backdrop_type: BackdropType) -> Self {
|
||||||
|
self.window.platform_specific.backdrop_type = backdrop_type;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_clip_children(mut self, flag: bool) -> Self {
|
||||||
|
self.window.platform_specific.clip_children = flag;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_border_color(mut self, color: Option<Color>) -> Self {
|
||||||
|
self.window.platform_specific.border_color = Some(color.unwrap_or(Color::NONE));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_title_background_color(mut self, color: Option<Color>) -> Self {
|
||||||
|
self.window.platform_specific.title_background_color = Some(color.unwrap_or(Color::NONE));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_title_text_color(mut self, color: Color) -> Self {
|
||||||
|
self.window.platform_specific.title_text_color = Some(color);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_corner_preference(mut self, corners: CornerPreference) -> Self {
|
||||||
|
self.window.platform_specific.corner_preference = Some(corners);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -335,12 +535,12 @@ impl IconExtWindows for Icon {
|
|||||||
path: P,
|
path: P,
|
||||||
size: Option<PhysicalSize<u32>>,
|
size: Option<PhysicalSize<u32>>,
|
||||||
) -> Result<Self, BadIcon> {
|
) -> Result<Self, BadIcon> {
|
||||||
let win_icon = WinIcon::from_path(path, size)?;
|
let win_icon = crate::platform_impl::WinIcon::from_path(path, size)?;
|
||||||
Ok(Icon { inner: win_icon })
|
Ok(Icon { inner: win_icon })
|
||||||
}
|
}
|
||||||
|
|
||||||
fn from_resource(ordinal: u16, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon> {
|
fn from_resource(ordinal: u16, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon> {
|
||||||
let win_icon = WinIcon::from_resource(ordinal, size)?;
|
let win_icon = crate::platform_impl::WinIcon::from_resource(ordinal, size)?;
|
||||||
Ok(Icon { inner: win_icon })
|
Ok(Icon { inner: win_icon })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use std::os::raw;
|
#[cfg(feature = "serde")]
|
||||||
use std::ptr;
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
event_loop::{EventLoopBuilder, EventLoopWindowTarget},
|
event_loop::{EventLoopBuilder, EventLoopWindowTarget},
|
||||||
@@ -8,11 +8,50 @@ use crate::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use crate::dpi::Size;
|
use crate::dpi::Size;
|
||||||
use crate::platform_impl::{
|
|
||||||
x11::ffi::XVisualInfo, ApplicationName, Backend, Window as LinuxWindow, XLIB_ERROR_HOOKS,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub use crate::platform_impl::{x11::util::WindowType as XWindowType, XNotSupported};
|
/// X window type. Maps directly to
|
||||||
|
/// [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html).
|
||||||
|
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
pub enum WindowType {
|
||||||
|
/// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the
|
||||||
|
/// screen, allowing the desktop environment to have full control of the desktop, without the need for proxying
|
||||||
|
/// root window clicks.
|
||||||
|
Desktop,
|
||||||
|
/// A dock or panel feature. Typically a Window Manager would keep such windows on top of all other windows.
|
||||||
|
Dock,
|
||||||
|
/// Toolbar windows. "Torn off" from the main application.
|
||||||
|
Toolbar,
|
||||||
|
/// Pinnable menu windows. "Torn off" from the main application.
|
||||||
|
Menu,
|
||||||
|
/// A small persistent utility window, such as a palette or toolbox.
|
||||||
|
Utility,
|
||||||
|
/// The window is a splash screen displayed as an application is starting up.
|
||||||
|
Splash,
|
||||||
|
/// This is a dialog window.
|
||||||
|
Dialog,
|
||||||
|
/// A dropdown menu that usually appears when the user clicks on an item in a menu bar.
|
||||||
|
/// This property is typically used on override-redirect windows.
|
||||||
|
DropdownMenu,
|
||||||
|
/// A popup menu that usually appears when the user right clicks on an object.
|
||||||
|
/// This property is typically used on override-redirect windows.
|
||||||
|
PopupMenu,
|
||||||
|
/// A tooltip window. Usually used to show additional information when hovering over an object with the cursor.
|
||||||
|
/// This property is typically used on override-redirect windows.
|
||||||
|
Tooltip,
|
||||||
|
/// The window is a notification.
|
||||||
|
/// This property is typically used on override-redirect windows.
|
||||||
|
Notification,
|
||||||
|
/// This should be used on the windows that are popped up by combo boxes.
|
||||||
|
/// This property is typically used on override-redirect windows.
|
||||||
|
Combo,
|
||||||
|
/// This indicates the the window is being dragged.
|
||||||
|
/// This property is typically used on override-redirect windows.
|
||||||
|
Dnd,
|
||||||
|
/// This is a normal, top-level window.
|
||||||
|
#[default]
|
||||||
|
Normal,
|
||||||
|
}
|
||||||
|
|
||||||
/// The first argument in the provided hook will be the pointer to `XDisplay`
|
/// The first argument in the provided hook will be the pointer to `XDisplay`
|
||||||
/// and the second one the pointer to [`XErrorEvent`]. The returned `bool` is an
|
/// and the second one the pointer to [`XErrorEvent`]. The returned `bool` is an
|
||||||
@@ -22,6 +61,12 @@ pub use crate::platform_impl::{x11::util::WindowType as XWindowType, XNotSupport
|
|||||||
pub type XlibErrorHook =
|
pub type XlibErrorHook =
|
||||||
Box<dyn Fn(*mut std::ffi::c_void, *mut std::ffi::c_void) -> bool + Send + Sync>;
|
Box<dyn Fn(*mut std::ffi::c_void, *mut std::ffi::c_void) -> bool + Send + Sync>;
|
||||||
|
|
||||||
|
/// A unique identifer for an X11 visual.
|
||||||
|
pub type XVisualID = u32;
|
||||||
|
|
||||||
|
/// A unique identifier for an X11 window.
|
||||||
|
pub type XWindow = u32;
|
||||||
|
|
||||||
/// Hook to winit's xlib error handling callback.
|
/// Hook to winit's xlib error handling callback.
|
||||||
///
|
///
|
||||||
/// This method is provided as a safe way to handle the errors comming from X11
|
/// This method is provided as a safe way to handle the errors comming from X11
|
||||||
@@ -37,7 +82,10 @@ pub type XlibErrorHook =
|
|||||||
pub fn register_xlib_error_hook(hook: XlibErrorHook) {
|
pub fn register_xlib_error_hook(hook: XlibErrorHook) {
|
||||||
// Append new hook.
|
// Append new hook.
|
||||||
unsafe {
|
unsafe {
|
||||||
XLIB_ERROR_HOOKS.lock().unwrap().push(hook);
|
crate::platform_impl::XLIB_ERROR_HOOKS
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.push(hook);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,7 +95,7 @@ pub trait EventLoopWindowTargetExtX11 {
|
|||||||
fn is_x11(&self) -> bool;
|
fn is_x11(&self) -> bool;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> EventLoopWindowTargetExtX11 for EventLoopWindowTarget<T> {
|
impl EventLoopWindowTargetExtX11 for EventLoopWindowTarget {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn is_x11(&self) -> bool {
|
fn is_x11(&self) -> bool {
|
||||||
!self.p.is_wayland()
|
!self.p.is_wayland()
|
||||||
@@ -69,7 +117,7 @@ pub trait EventLoopBuilderExtX11 {
|
|||||||
impl<T> EventLoopBuilderExtX11 for EventLoopBuilder<T> {
|
impl<T> EventLoopBuilderExtX11 for EventLoopBuilder<T> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_x11(&mut self) -> &mut Self {
|
fn with_x11(&mut self) -> &mut Self {
|
||||||
self.platform_specific.forced_backend = Some(Backend::X);
|
self.platform_specific.forced_backend = Some(crate::platform_impl::Backend::X);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,140 +129,107 @@ impl<T> EventLoopBuilderExtX11 for EventLoopBuilder<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Additional methods on [`Window`] that are specific to X11.
|
/// Additional methods on [`Window`] that are specific to X11.
|
||||||
pub trait WindowExtX11 {
|
pub trait WindowExtX11 {}
|
||||||
/// Returns the ID of the [`Window`] xlib object that is used by this window.
|
|
||||||
///
|
|
||||||
/// Returns `None` if the window doesn't use xlib (if it uses wayland for example).
|
|
||||||
fn xlib_window(&self) -> Option<raw::c_ulong>;
|
|
||||||
|
|
||||||
/// Returns a pointer to the `Display` object of xlib that is used by this window.
|
impl WindowExtX11 for Window {}
|
||||||
///
|
|
||||||
/// Returns `None` if the window doesn't use xlib (if it uses wayland for example).
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the [`Window`] is destroyed.
|
|
||||||
fn xlib_display(&self) -> Option<*mut raw::c_void>;
|
|
||||||
|
|
||||||
fn xlib_screen_id(&self) -> Option<raw::c_int>;
|
|
||||||
|
|
||||||
/// This function returns the underlying `xcb_connection_t` of an xlib `Display`.
|
|
||||||
///
|
|
||||||
/// Returns `None` if the window doesn't use xlib (if it uses wayland for example).
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the [`Window`] is destroyed.
|
|
||||||
fn xcb_connection(&self) -> Option<*mut raw::c_void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowExtX11 for Window {
|
|
||||||
#[inline]
|
|
||||||
fn xlib_window(&self) -> Option<raw::c_ulong> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::X(ref w) => Some(w.xlib_window()),
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn xlib_display(&self) -> Option<*mut raw::c_void> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::X(ref w) => Some(w.xlib_display()),
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn xlib_screen_id(&self) -> Option<raw::c_int> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::X(ref w) => Some(w.xlib_screen_id()),
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn xcb_connection(&self) -> Option<*mut raw::c_void> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::X(ref w) => Some(w.xcb_connection()),
|
|
||||||
#[cfg(wayland_platform)]
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on [`WindowBuilder`] that are specific to X11.
|
/// Additional methods on [`WindowBuilder`] that are specific to X11.
|
||||||
pub trait WindowBuilderExtX11 {
|
pub trait WindowBuilderExtX11 {
|
||||||
fn with_x11_visual<T>(self, visual_infos: *const T) -> Self;
|
/// Create this window with a specific X11 visual.
|
||||||
|
fn with_x11_visual(self, visual_id: XVisualID) -> Self;
|
||||||
|
|
||||||
fn with_x11_screen(self, screen_id: i32) -> Self;
|
fn with_x11_screen(self, screen_id: i32) -> Self;
|
||||||
|
|
||||||
/// 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) = "general", "instance"`.
|
/// 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)
|
||||||
fn with_name(self, general: impl Into<String>, instance: impl Into<String>) -> Self;
|
fn with_name(self, general: impl Into<String>, instance: impl Into<String>) -> Self;
|
||||||
|
|
||||||
/// Build window with override-redirect flag; defaults to false. Only relevant on X11.
|
/// Build window with override-redirect flag; defaults to false.
|
||||||
fn with_override_redirect(self, override_redirect: bool) -> Self;
|
fn with_override_redirect(self, override_redirect: bool) -> Self;
|
||||||
|
|
||||||
/// Build window with `_NET_WM_WINDOW_TYPE` hints; defaults to `Normal`. Only relevant on X11.
|
/// Build window with `_NET_WM_WINDOW_TYPE` hints; defaults to `Normal`.
|
||||||
fn with_x11_window_type(self, x11_window_type: Vec<XWindowType>) -> Self;
|
fn with_x11_window_type(self, x11_window_type: Vec<WindowType>) -> Self;
|
||||||
|
|
||||||
/// Build window with base size hint. Only implemented on X11.
|
/// Build window with base size hint.
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// # use winit::dpi::{LogicalSize, PhysicalSize};
|
/// # use winit::dpi::{LogicalSize, PhysicalSize};
|
||||||
/// # use winit::window::WindowBuilder;
|
/// # use winit::window::Window;
|
||||||
/// # use winit::platform::x11::WindowBuilderExtX11;
|
/// # use winit::platform::x11::WindowBuilderExtX11;
|
||||||
/// // Specify the size in logical dimensions like this:
|
/// // Specify the size in logical dimensions like this:
|
||||||
/// WindowBuilder::new().with_base_size(LogicalSize::new(400.0, 200.0));
|
/// Window::builder().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:
|
||||||
/// WindowBuilder::new().with_base_size(PhysicalSize::new(400, 200));
|
/// Window::builder().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;
|
||||||
|
|
||||||
|
/// Embed this window into another parent window.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// use winit::window::Window;
|
||||||
|
/// use winit::platform::x11::{XWindow, WindowBuilderExtX11};
|
||||||
|
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
/// let event_loop = winit::event_loop::EventLoop::new().unwrap();
|
||||||
|
/// let parent_window_id = std::env::args().nth(1).unwrap().parse::<XWindow>()?;
|
||||||
|
/// let window = Window::builder()
|
||||||
|
/// .with_embed_parent_window(parent_window_id)
|
||||||
|
/// .build(&event_loop)?;
|
||||||
|
/// # Ok(()) }
|
||||||
|
/// ```
|
||||||
|
fn with_embed_parent_window(self, parent_window_id: XWindow) -> Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowBuilderExtX11 for WindowBuilder {
|
impl WindowBuilderExtX11 for WindowBuilder {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_x11_visual<T>(mut self, visual_infos: *const T) -> Self {
|
fn with_x11_visual(mut self, visual_id: XVisualID) -> Self {
|
||||||
{
|
self.window.platform_specific.x11.visual_id = Some(visual_id);
|
||||||
self.platform_specific.visual_infos =
|
|
||||||
Some(unsafe { ptr::read(visual_infos as *const XVisualInfo) });
|
|
||||||
}
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_x11_screen(mut self, screen_id: i32) -> Self {
|
fn with_x11_screen(mut self, screen_id: i32) -> Self {
|
||||||
self.platform_specific.screen_id = Some(screen_id);
|
self.window.platform_specific.x11.screen_id = Some(screen_id);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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(ApplicationName::new(general.into(), instance.into()));
|
self.window.platform_specific.name = Some(crate::platform_impl::ApplicationName::new(
|
||||||
|
general.into(),
|
||||||
|
instance.into(),
|
||||||
|
));
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_override_redirect(mut self, override_redirect: bool) -> Self {
|
fn with_override_redirect(mut self, override_redirect: bool) -> Self {
|
||||||
self.platform_specific.override_redirect = override_redirect;
|
self.window.platform_specific.x11.override_redirect = override_redirect;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_x11_window_type(mut self, x11_window_types: Vec<XWindowType>) -> Self {
|
fn with_x11_window_type(mut self, x11_window_types: Vec<WindowType>) -> Self {
|
||||||
self.platform_specific.x11_window_types = x11_window_types;
|
self.window.platform_specific.x11.x11_window_types = x11_window_types;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn with_base_size<S: Into<Size>>(mut self, base_size: S) -> Self {
|
fn with_base_size<S: Into<Size>>(mut self, base_size: S) -> Self {
|
||||||
self.platform_specific.base_size = Some(base_size.into());
|
self.window.platform_specific.x11.base_size = Some(base_size.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_embed_parent_window(mut self, parent_window_id: XWindow) -> Self {
|
||||||
|
self.window.platform_specific.x11.embed_window = Some(parent_window_id);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
607
src/platform_impl/android/keycodes.rs
Normal file
@@ -0,0 +1,607 @@
|
|||||||
|
use android_activity::{
|
||||||
|
input::{KeyAction, KeyEvent, KeyMapChar, Keycode},
|
||||||
|
AndroidApp,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey};
|
||||||
|
|
||||||
|
pub fn to_physical_key(keycode: Keycode) -> PhysicalKey {
|
||||||
|
PhysicalKey::Code(match keycode {
|
||||||
|
Keycode::A => KeyCode::KeyA,
|
||||||
|
Keycode::B => KeyCode::KeyB,
|
||||||
|
Keycode::C => KeyCode::KeyC,
|
||||||
|
Keycode::D => KeyCode::KeyD,
|
||||||
|
Keycode::E => KeyCode::KeyE,
|
||||||
|
Keycode::F => KeyCode::KeyF,
|
||||||
|
Keycode::G => KeyCode::KeyG,
|
||||||
|
Keycode::H => KeyCode::KeyH,
|
||||||
|
Keycode::I => KeyCode::KeyI,
|
||||||
|
Keycode::J => KeyCode::KeyJ,
|
||||||
|
Keycode::K => KeyCode::KeyK,
|
||||||
|
Keycode::L => KeyCode::KeyL,
|
||||||
|
Keycode::M => KeyCode::KeyM,
|
||||||
|
Keycode::N => KeyCode::KeyN,
|
||||||
|
Keycode::O => KeyCode::KeyO,
|
||||||
|
Keycode::P => KeyCode::KeyP,
|
||||||
|
Keycode::Q => KeyCode::KeyQ,
|
||||||
|
Keycode::R => KeyCode::KeyR,
|
||||||
|
Keycode::S => KeyCode::KeyS,
|
||||||
|
Keycode::T => KeyCode::KeyT,
|
||||||
|
Keycode::U => KeyCode::KeyU,
|
||||||
|
Keycode::V => KeyCode::KeyV,
|
||||||
|
Keycode::W => KeyCode::KeyW,
|
||||||
|
Keycode::X => KeyCode::KeyX,
|
||||||
|
Keycode::Y => KeyCode::KeyY,
|
||||||
|
Keycode::Z => KeyCode::KeyZ,
|
||||||
|
|
||||||
|
Keycode::Keycode0 => KeyCode::Digit0,
|
||||||
|
Keycode::Keycode1 => KeyCode::Digit1,
|
||||||
|
Keycode::Keycode2 => KeyCode::Digit2,
|
||||||
|
Keycode::Keycode3 => KeyCode::Digit3,
|
||||||
|
Keycode::Keycode4 => KeyCode::Digit4,
|
||||||
|
Keycode::Keycode5 => KeyCode::Digit5,
|
||||||
|
Keycode::Keycode6 => KeyCode::Digit6,
|
||||||
|
Keycode::Keycode7 => KeyCode::Digit7,
|
||||||
|
Keycode::Keycode8 => KeyCode::Digit8,
|
||||||
|
Keycode::Keycode9 => KeyCode::Digit9,
|
||||||
|
|
||||||
|
Keycode::Numpad0 => KeyCode::Numpad0,
|
||||||
|
Keycode::Numpad1 => KeyCode::Numpad1,
|
||||||
|
Keycode::Numpad2 => KeyCode::Numpad2,
|
||||||
|
Keycode::Numpad3 => KeyCode::Numpad3,
|
||||||
|
Keycode::Numpad4 => KeyCode::Numpad4,
|
||||||
|
Keycode::Numpad5 => KeyCode::Numpad5,
|
||||||
|
Keycode::Numpad6 => KeyCode::Numpad6,
|
||||||
|
Keycode::Numpad7 => KeyCode::Numpad7,
|
||||||
|
Keycode::Numpad8 => KeyCode::Numpad8,
|
||||||
|
Keycode::Numpad9 => KeyCode::Numpad9,
|
||||||
|
|
||||||
|
Keycode::NumpadAdd => KeyCode::NumpadAdd,
|
||||||
|
Keycode::NumpadSubtract => KeyCode::NumpadSubtract,
|
||||||
|
Keycode::NumpadMultiply => KeyCode::NumpadMultiply,
|
||||||
|
Keycode::NumpadDivide => KeyCode::NumpadDivide,
|
||||||
|
Keycode::NumpadEnter => KeyCode::NumpadEnter,
|
||||||
|
Keycode::NumpadEquals => KeyCode::NumpadEqual,
|
||||||
|
Keycode::NumpadComma => KeyCode::NumpadComma,
|
||||||
|
Keycode::NumpadDot => KeyCode::NumpadDecimal,
|
||||||
|
Keycode::NumLock => KeyCode::NumLock,
|
||||||
|
|
||||||
|
Keycode::DpadLeft => KeyCode::ArrowLeft,
|
||||||
|
Keycode::DpadRight => KeyCode::ArrowRight,
|
||||||
|
Keycode::DpadUp => KeyCode::ArrowUp,
|
||||||
|
Keycode::DpadDown => KeyCode::ArrowDown,
|
||||||
|
|
||||||
|
Keycode::F1 => KeyCode::F1,
|
||||||
|
Keycode::F2 => KeyCode::F2,
|
||||||
|
Keycode::F3 => KeyCode::F3,
|
||||||
|
Keycode::F4 => KeyCode::F4,
|
||||||
|
Keycode::F5 => KeyCode::F5,
|
||||||
|
Keycode::F6 => KeyCode::F6,
|
||||||
|
Keycode::F7 => KeyCode::F7,
|
||||||
|
Keycode::F8 => KeyCode::F8,
|
||||||
|
Keycode::F9 => KeyCode::F9,
|
||||||
|
Keycode::F10 => KeyCode::F10,
|
||||||
|
Keycode::F11 => KeyCode::F11,
|
||||||
|
Keycode::F12 => KeyCode::F12,
|
||||||
|
|
||||||
|
Keycode::Space => KeyCode::Space,
|
||||||
|
Keycode::Escape => KeyCode::Escape,
|
||||||
|
Keycode::Enter => KeyCode::Enter, // not on the Numpad
|
||||||
|
Keycode::Tab => KeyCode::Tab,
|
||||||
|
|
||||||
|
Keycode::PageUp => KeyCode::PageUp,
|
||||||
|
Keycode::PageDown => KeyCode::PageDown,
|
||||||
|
Keycode::MoveHome => KeyCode::Home,
|
||||||
|
Keycode::MoveEnd => KeyCode::End,
|
||||||
|
Keycode::Insert => KeyCode::Insert,
|
||||||
|
|
||||||
|
Keycode::Del => KeyCode::Backspace, // Backspace (above Enter)
|
||||||
|
Keycode::ForwardDel => KeyCode::Delete, // Delete (below Insert)
|
||||||
|
|
||||||
|
Keycode::Copy => KeyCode::Copy,
|
||||||
|
Keycode::Paste => KeyCode::Paste,
|
||||||
|
Keycode::Cut => KeyCode::Cut,
|
||||||
|
|
||||||
|
Keycode::VolumeUp => KeyCode::AudioVolumeUp,
|
||||||
|
Keycode::VolumeDown => KeyCode::AudioVolumeDown,
|
||||||
|
Keycode::VolumeMute => KeyCode::AudioVolumeMute,
|
||||||
|
//Keycode::Mute => None, // Microphone mute
|
||||||
|
Keycode::MediaPlayPause => KeyCode::MediaPlayPause,
|
||||||
|
Keycode::MediaStop => KeyCode::MediaStop,
|
||||||
|
Keycode::MediaNext => KeyCode::MediaTrackNext,
|
||||||
|
Keycode::MediaPrevious => KeyCode::MediaTrackPrevious,
|
||||||
|
|
||||||
|
Keycode::Plus => KeyCode::Equal,
|
||||||
|
Keycode::Minus => KeyCode::Minus,
|
||||||
|
// Winit doesn't differentiate both '+' and '=', considering they are usually
|
||||||
|
// on the same physical key
|
||||||
|
Keycode::Equals => KeyCode::Equal,
|
||||||
|
Keycode::Semicolon => KeyCode::Semicolon,
|
||||||
|
Keycode::Slash => KeyCode::Slash,
|
||||||
|
Keycode::Backslash => KeyCode::Backslash,
|
||||||
|
Keycode::Comma => KeyCode::Comma,
|
||||||
|
Keycode::Period => KeyCode::Period,
|
||||||
|
Keycode::Apostrophe => KeyCode::Quote,
|
||||||
|
Keycode::Grave => KeyCode::Backquote,
|
||||||
|
|
||||||
|
// Winit doesn't expose a SysRq code, so map to PrintScreen since it's
|
||||||
|
// usually the same physical key
|
||||||
|
Keycode::Sysrq => KeyCode::PrintScreen,
|
||||||
|
// These are usually the same (Pause/Break)
|
||||||
|
Keycode::Break => KeyCode::Pause,
|
||||||
|
// These are exactly the same
|
||||||
|
Keycode::ScrollLock => KeyCode::ScrollLock,
|
||||||
|
|
||||||
|
Keycode::Yen => KeyCode::IntlYen,
|
||||||
|
Keycode::Kana => KeyCode::Lang1,
|
||||||
|
Keycode::KatakanaHiragana => KeyCode::KanaMode,
|
||||||
|
|
||||||
|
Keycode::CtrlLeft => KeyCode::ControlLeft,
|
||||||
|
Keycode::CtrlRight => KeyCode::ControlRight,
|
||||||
|
|
||||||
|
Keycode::ShiftLeft => KeyCode::ShiftLeft,
|
||||||
|
Keycode::ShiftRight => KeyCode::ShiftRight,
|
||||||
|
|
||||||
|
Keycode::AltLeft => KeyCode::AltLeft,
|
||||||
|
Keycode::AltRight => KeyCode::AltRight,
|
||||||
|
|
||||||
|
Keycode::MetaLeft => KeyCode::SuperLeft,
|
||||||
|
Keycode::MetaRight => KeyCode::SuperRight,
|
||||||
|
|
||||||
|
Keycode::LeftBracket => KeyCode::BracketLeft,
|
||||||
|
Keycode::RightBracket => KeyCode::BracketRight,
|
||||||
|
|
||||||
|
Keycode::Power => KeyCode::Power,
|
||||||
|
Keycode::Sleep => KeyCode::Sleep, // what about SoftSleep?
|
||||||
|
Keycode::Wakeup => KeyCode::WakeUp,
|
||||||
|
|
||||||
|
keycode => return PhysicalKey::Unidentified(NativeKeyCode::Android(keycode.into())),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tries to map the `key_event` to a `KeyMapChar` containing a unicode character or dead key accent
|
||||||
|
///
|
||||||
|
/// This takes a `KeyEvent` and looks up its corresponding `KeyCharacterMap` and
|
||||||
|
/// uses that to try and map the `key_code` + `meta_state` to a unicode
|
||||||
|
/// character or a dead key that can be combined with the next key press.
|
||||||
|
pub fn character_map_and_combine_key(
|
||||||
|
app: &AndroidApp,
|
||||||
|
key_event: &KeyEvent<'_>,
|
||||||
|
combining_accent: &mut Option<char>,
|
||||||
|
) -> Option<KeyMapChar> {
|
||||||
|
let device_id = key_event.device_id();
|
||||||
|
|
||||||
|
let key_map = match app.device_key_character_map(device_id) {
|
||||||
|
Ok(key_map) => key_map,
|
||||||
|
Err(err) => {
|
||||||
|
log::warn!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}");
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match key_map.get(key_event.key_code(), key_event.meta_state()) {
|
||||||
|
Ok(KeyMapChar::Unicode(unicode)) => {
|
||||||
|
// Only do dead key combining on key down
|
||||||
|
if key_event.action() == KeyAction::Down {
|
||||||
|
let combined_unicode = if let Some(accent) = combining_accent {
|
||||||
|
match key_map.get_dead_char(*accent, unicode) {
|
||||||
|
Ok(Some(key)) => Some(key),
|
||||||
|
Ok(None) => None,
|
||||||
|
Err(err) => {
|
||||||
|
log::warn!("KeyEvent: Failed to combine 'dead key' accent '{accent}' with '{unicode}': {err:?}");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Some(unicode)
|
||||||
|
};
|
||||||
|
*combining_accent = None;
|
||||||
|
combined_unicode.map(KeyMapChar::Unicode)
|
||||||
|
} else {
|
||||||
|
Some(KeyMapChar::Unicode(unicode))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(KeyMapChar::CombiningAccent(accent)) => {
|
||||||
|
if key_event.action() == KeyAction::Down {
|
||||||
|
*combining_accent = Some(accent);
|
||||||
|
}
|
||||||
|
Some(KeyMapChar::CombiningAccent(accent))
|
||||||
|
}
|
||||||
|
Ok(KeyMapChar::None) => {
|
||||||
|
// Leave any combining_accent state in tact (seems to match how other
|
||||||
|
// Android apps work)
|
||||||
|
None
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
log::warn!("KeyEvent: Failed to get key map character: {err:?}");
|
||||||
|
*combining_accent = None;
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_logical(key_char: Option<KeyMapChar>, keycode: Keycode) -> Key {
|
||||||
|
use android_activity::input::Keycode::*;
|
||||||
|
|
||||||
|
let native = NativeKey::Android(keycode.into());
|
||||||
|
|
||||||
|
match key_char {
|
||||||
|
Some(KeyMapChar::Unicode(c)) => Key::Character(smol_str::SmolStr::from_iter([c])),
|
||||||
|
Some(KeyMapChar::CombiningAccent(c)) => Key::Dead(Some(c)),
|
||||||
|
None | Some(KeyMapChar::None) => match keycode {
|
||||||
|
// Using `BrowserHome` instead of `GoHome` according to
|
||||||
|
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values
|
||||||
|
Home => Key::Named(NamedKey::BrowserHome),
|
||||||
|
Back => Key::Named(NamedKey::BrowserBack),
|
||||||
|
Call => Key::Named(NamedKey::Call),
|
||||||
|
Endcall => Key::Named(NamedKey::EndCall),
|
||||||
|
|
||||||
|
//-------------------------------------------------------------------------------
|
||||||
|
// These should be redundant because they should have already been matched
|
||||||
|
// as `KeyMapChar::Unicode`, but also matched here as a fallback
|
||||||
|
Keycode0 => Key::Character("0".into()),
|
||||||
|
Keycode1 => Key::Character("1".into()),
|
||||||
|
Keycode2 => Key::Character("2".into()),
|
||||||
|
Keycode3 => Key::Character("3".into()),
|
||||||
|
Keycode4 => Key::Character("4".into()),
|
||||||
|
Keycode5 => Key::Character("5".into()),
|
||||||
|
Keycode6 => Key::Character("6".into()),
|
||||||
|
Keycode7 => Key::Character("7".into()),
|
||||||
|
Keycode8 => Key::Character("8".into()),
|
||||||
|
Keycode9 => Key::Character("9".into()),
|
||||||
|
Star => Key::Character("*".into()),
|
||||||
|
Pound => Key::Character("#".into()),
|
||||||
|
A => Key::Character("a".into()),
|
||||||
|
B => Key::Character("b".into()),
|
||||||
|
C => Key::Character("c".into()),
|
||||||
|
D => Key::Character("d".into()),
|
||||||
|
E => Key::Character("e".into()),
|
||||||
|
F => Key::Character("f".into()),
|
||||||
|
G => Key::Character("g".into()),
|
||||||
|
H => Key::Character("h".into()),
|
||||||
|
I => Key::Character("i".into()),
|
||||||
|
J => Key::Character("j".into()),
|
||||||
|
K => Key::Character("k".into()),
|
||||||
|
L => Key::Character("l".into()),
|
||||||
|
M => Key::Character("m".into()),
|
||||||
|
N => Key::Character("n".into()),
|
||||||
|
O => Key::Character("o".into()),
|
||||||
|
P => Key::Character("p".into()),
|
||||||
|
Q => Key::Character("q".into()),
|
||||||
|
R => Key::Character("r".into()),
|
||||||
|
S => Key::Character("s".into()),
|
||||||
|
T => Key::Character("t".into()),
|
||||||
|
U => Key::Character("u".into()),
|
||||||
|
V => Key::Character("v".into()),
|
||||||
|
W => Key::Character("w".into()),
|
||||||
|
X => Key::Character("x".into()),
|
||||||
|
Y => Key::Character("y".into()),
|
||||||
|
Z => Key::Character("z".into()),
|
||||||
|
Comma => Key::Character(",".into()),
|
||||||
|
Period => Key::Character(".".into()),
|
||||||
|
Grave => Key::Character("`".into()),
|
||||||
|
Minus => Key::Character("-".into()),
|
||||||
|
Equals => Key::Character("=".into()),
|
||||||
|
LeftBracket => Key::Character("[".into()),
|
||||||
|
RightBracket => Key::Character("]".into()),
|
||||||
|
Backslash => Key::Character("\\".into()),
|
||||||
|
Semicolon => Key::Character(";".into()),
|
||||||
|
Apostrophe => Key::Character("'".into()),
|
||||||
|
Slash => Key::Character("/".into()),
|
||||||
|
At => Key::Character("@".into()),
|
||||||
|
Plus => Key::Character("+".into()),
|
||||||
|
//-------------------------------------------------------------------------------
|
||||||
|
DpadUp => Key::Named(NamedKey::ArrowUp),
|
||||||
|
DpadDown => Key::Named(NamedKey::ArrowDown),
|
||||||
|
DpadLeft => Key::Named(NamedKey::ArrowLeft),
|
||||||
|
DpadRight => Key::Named(NamedKey::ArrowRight),
|
||||||
|
DpadCenter => Key::Named(NamedKey::Enter),
|
||||||
|
|
||||||
|
VolumeUp => Key::Named(NamedKey::AudioVolumeUp),
|
||||||
|
VolumeDown => Key::Named(NamedKey::AudioVolumeDown),
|
||||||
|
Power => Key::Named(NamedKey::Power),
|
||||||
|
Camera => Key::Named(NamedKey::Camera),
|
||||||
|
Clear => Key::Named(NamedKey::Clear),
|
||||||
|
|
||||||
|
AltLeft => Key::Named(NamedKey::Alt),
|
||||||
|
AltRight => Key::Named(NamedKey::Alt),
|
||||||
|
ShiftLeft => Key::Named(NamedKey::Shift),
|
||||||
|
ShiftRight => Key::Named(NamedKey::Shift),
|
||||||
|
Tab => Key::Named(NamedKey::Tab),
|
||||||
|
Space => Key::Named(NamedKey::Space),
|
||||||
|
Sym => Key::Named(NamedKey::Symbol),
|
||||||
|
Explorer => Key::Named(NamedKey::LaunchWebBrowser),
|
||||||
|
Envelope => Key::Named(NamedKey::LaunchMail),
|
||||||
|
Enter => Key::Named(NamedKey::Enter),
|
||||||
|
Del => Key::Named(NamedKey::Backspace),
|
||||||
|
|
||||||
|
// According to https://developer.android.com/reference/android/view/KeyEvent#KEYCODE_NUM
|
||||||
|
Num => Key::Named(NamedKey::Alt),
|
||||||
|
|
||||||
|
Headsethook => Key::Named(NamedKey::HeadsetHook),
|
||||||
|
Focus => Key::Named(NamedKey::CameraFocus),
|
||||||
|
|
||||||
|
Notification => Key::Named(NamedKey::Notification),
|
||||||
|
Search => Key::Named(NamedKey::BrowserSearch),
|
||||||
|
MediaPlayPause => Key::Named(NamedKey::MediaPlayPause),
|
||||||
|
MediaStop => Key::Named(NamedKey::MediaStop),
|
||||||
|
MediaNext => Key::Named(NamedKey::MediaTrackNext),
|
||||||
|
MediaPrevious => Key::Named(NamedKey::MediaTrackPrevious),
|
||||||
|
MediaRewind => Key::Named(NamedKey::MediaRewind),
|
||||||
|
MediaFastForward => Key::Named(NamedKey::MediaFastForward),
|
||||||
|
Mute => Key::Named(NamedKey::MicrophoneVolumeMute),
|
||||||
|
PageUp => Key::Named(NamedKey::PageUp),
|
||||||
|
PageDown => Key::Named(NamedKey::PageDown),
|
||||||
|
|
||||||
|
Escape => Key::Named(NamedKey::Escape),
|
||||||
|
ForwardDel => Key::Named(NamedKey::Delete),
|
||||||
|
CtrlLeft => Key::Named(NamedKey::Control),
|
||||||
|
CtrlRight => Key::Named(NamedKey::Control),
|
||||||
|
CapsLock => Key::Named(NamedKey::CapsLock),
|
||||||
|
ScrollLock => Key::Named(NamedKey::ScrollLock),
|
||||||
|
MetaLeft => Key::Named(NamedKey::Super),
|
||||||
|
MetaRight => Key::Named(NamedKey::Super),
|
||||||
|
Function => Key::Named(NamedKey::Fn),
|
||||||
|
Sysrq => Key::Named(NamedKey::PrintScreen),
|
||||||
|
Break => Key::Named(NamedKey::Pause),
|
||||||
|
MoveHome => Key::Named(NamedKey::Home),
|
||||||
|
MoveEnd => Key::Named(NamedKey::End),
|
||||||
|
Insert => Key::Named(NamedKey::Insert),
|
||||||
|
Forward => Key::Named(NamedKey::BrowserForward),
|
||||||
|
MediaPlay => Key::Named(NamedKey::MediaPlay),
|
||||||
|
MediaPause => Key::Named(NamedKey::MediaPause),
|
||||||
|
MediaClose => Key::Named(NamedKey::MediaClose),
|
||||||
|
MediaEject => Key::Named(NamedKey::Eject),
|
||||||
|
MediaRecord => Key::Named(NamedKey::MediaRecord),
|
||||||
|
F1 => Key::Named(NamedKey::F1),
|
||||||
|
F2 => Key::Named(NamedKey::F2),
|
||||||
|
F3 => Key::Named(NamedKey::F3),
|
||||||
|
F4 => Key::Named(NamedKey::F4),
|
||||||
|
F5 => Key::Named(NamedKey::F5),
|
||||||
|
F6 => Key::Named(NamedKey::F6),
|
||||||
|
F7 => Key::Named(NamedKey::F7),
|
||||||
|
F8 => Key::Named(NamedKey::F8),
|
||||||
|
F9 => Key::Named(NamedKey::F9),
|
||||||
|
F10 => Key::Named(NamedKey::F10),
|
||||||
|
F11 => Key::Named(NamedKey::F11),
|
||||||
|
F12 => Key::Named(NamedKey::F12),
|
||||||
|
NumLock => Key::Named(NamedKey::NumLock),
|
||||||
|
Numpad0 => Key::Character("0".into()),
|
||||||
|
Numpad1 => Key::Character("1".into()),
|
||||||
|
Numpad2 => Key::Character("2".into()),
|
||||||
|
Numpad3 => Key::Character("3".into()),
|
||||||
|
Numpad4 => Key::Character("4".into()),
|
||||||
|
Numpad5 => Key::Character("5".into()),
|
||||||
|
Numpad6 => Key::Character("6".into()),
|
||||||
|
Numpad7 => Key::Character("7".into()),
|
||||||
|
Numpad8 => Key::Character("8".into()),
|
||||||
|
Numpad9 => Key::Character("9".into()),
|
||||||
|
NumpadDivide => Key::Character("/".into()),
|
||||||
|
NumpadMultiply => Key::Character("*".into()),
|
||||||
|
NumpadSubtract => Key::Character("-".into()),
|
||||||
|
NumpadAdd => Key::Character("+".into()),
|
||||||
|
NumpadDot => Key::Character(".".into()),
|
||||||
|
NumpadComma => Key::Character(",".into()),
|
||||||
|
NumpadEnter => Key::Named(NamedKey::Enter),
|
||||||
|
NumpadEquals => Key::Character("=".into()),
|
||||||
|
NumpadLeftParen => Key::Character("(".into()),
|
||||||
|
NumpadRightParen => Key::Character(")".into()),
|
||||||
|
|
||||||
|
VolumeMute => Key::Named(NamedKey::AudioVolumeMute),
|
||||||
|
Info => Key::Named(NamedKey::Info),
|
||||||
|
ChannelUp => Key::Named(NamedKey::ChannelUp),
|
||||||
|
ChannelDown => Key::Named(NamedKey::ChannelDown),
|
||||||
|
ZoomIn => Key::Named(NamedKey::ZoomIn),
|
||||||
|
ZoomOut => Key::Named(NamedKey::ZoomOut),
|
||||||
|
Tv => Key::Named(NamedKey::TV),
|
||||||
|
Guide => Key::Named(NamedKey::Guide),
|
||||||
|
Dvr => Key::Named(NamedKey::DVR),
|
||||||
|
Bookmark => Key::Named(NamedKey::BrowserFavorites),
|
||||||
|
Captions => Key::Named(NamedKey::ClosedCaptionToggle),
|
||||||
|
Settings => Key::Named(NamedKey::Settings),
|
||||||
|
TvPower => Key::Named(NamedKey::TVPower),
|
||||||
|
TvInput => Key::Named(NamedKey::TVInput),
|
||||||
|
StbPower => Key::Named(NamedKey::STBPower),
|
||||||
|
StbInput => Key::Named(NamedKey::STBInput),
|
||||||
|
AvrPower => Key::Named(NamedKey::AVRPower),
|
||||||
|
AvrInput => Key::Named(NamedKey::AVRInput),
|
||||||
|
ProgRed => Key::Named(NamedKey::ColorF0Red),
|
||||||
|
ProgGreen => Key::Named(NamedKey::ColorF1Green),
|
||||||
|
ProgYellow => Key::Named(NamedKey::ColorF2Yellow),
|
||||||
|
ProgBlue => Key::Named(NamedKey::ColorF3Blue),
|
||||||
|
AppSwitch => Key::Named(NamedKey::AppSwitch),
|
||||||
|
LanguageSwitch => Key::Named(NamedKey::GroupNext),
|
||||||
|
MannerMode => Key::Named(NamedKey::MannerMode),
|
||||||
|
Keycode3dMode => Key::Named(NamedKey::TV3DMode),
|
||||||
|
Contacts => Key::Named(NamedKey::LaunchContacts),
|
||||||
|
Calendar => Key::Named(NamedKey::LaunchCalendar),
|
||||||
|
Music => Key::Named(NamedKey::LaunchMusicPlayer),
|
||||||
|
Calculator => Key::Named(NamedKey::LaunchApplication2),
|
||||||
|
ZenkakuHankaku => Key::Named(NamedKey::ZenkakuHankaku),
|
||||||
|
Eisu => Key::Named(NamedKey::Eisu),
|
||||||
|
Muhenkan => Key::Named(NamedKey::NonConvert),
|
||||||
|
Henkan => Key::Named(NamedKey::Convert),
|
||||||
|
KatakanaHiragana => Key::Named(NamedKey::HiraganaKatakana),
|
||||||
|
Kana => Key::Named(NamedKey::KanjiMode),
|
||||||
|
BrightnessDown => Key::Named(NamedKey::BrightnessDown),
|
||||||
|
BrightnessUp => Key::Named(NamedKey::BrightnessUp),
|
||||||
|
MediaAudioTrack => Key::Named(NamedKey::MediaAudioTrack),
|
||||||
|
Sleep => Key::Named(NamedKey::Standby),
|
||||||
|
Wakeup => Key::Named(NamedKey::WakeUp),
|
||||||
|
Pairing => Key::Named(NamedKey::Pairing),
|
||||||
|
MediaTopMenu => Key::Named(NamedKey::MediaTopMenu),
|
||||||
|
LastChannel => Key::Named(NamedKey::MediaLast),
|
||||||
|
TvDataService => Key::Named(NamedKey::TVDataService),
|
||||||
|
VoiceAssist => Key::Named(NamedKey::VoiceDial),
|
||||||
|
TvRadioService => Key::Named(NamedKey::TVRadioService),
|
||||||
|
TvTeletext => Key::Named(NamedKey::Teletext),
|
||||||
|
TvNumberEntry => Key::Named(NamedKey::TVNumberEntry),
|
||||||
|
TvTerrestrialAnalog => Key::Named(NamedKey::TVTerrestrialAnalog),
|
||||||
|
TvTerrestrialDigital => Key::Named(NamedKey::TVTerrestrialDigital),
|
||||||
|
TvSatellite => Key::Named(NamedKey::TVSatellite),
|
||||||
|
TvSatelliteBs => Key::Named(NamedKey::TVSatelliteBS),
|
||||||
|
TvSatelliteCs => Key::Named(NamedKey::TVSatelliteCS),
|
||||||
|
TvSatelliteService => Key::Named(NamedKey::TVSatelliteToggle),
|
||||||
|
TvNetwork => Key::Named(NamedKey::TVNetwork),
|
||||||
|
TvAntennaCable => Key::Named(NamedKey::TVAntennaCable),
|
||||||
|
TvInputHdmi1 => Key::Named(NamedKey::TVInputHDMI1),
|
||||||
|
TvInputHdmi2 => Key::Named(NamedKey::TVInputHDMI2),
|
||||||
|
TvInputHdmi3 => Key::Named(NamedKey::TVInputHDMI3),
|
||||||
|
TvInputHdmi4 => Key::Named(NamedKey::TVInputHDMI4),
|
||||||
|
TvInputComposite1 => Key::Named(NamedKey::TVInputComposite1),
|
||||||
|
TvInputComposite2 => Key::Named(NamedKey::TVInputComposite2),
|
||||||
|
TvInputComponent1 => Key::Named(NamedKey::TVInputComponent1),
|
||||||
|
TvInputComponent2 => Key::Named(NamedKey::TVInputComponent2),
|
||||||
|
TvInputVga1 => Key::Named(NamedKey::TVInputVGA1),
|
||||||
|
TvAudioDescription => Key::Named(NamedKey::TVAudioDescription),
|
||||||
|
TvAudioDescriptionMixUp => Key::Named(NamedKey::TVAudioDescriptionMixUp),
|
||||||
|
TvAudioDescriptionMixDown => Key::Named(NamedKey::TVAudioDescriptionMixDown),
|
||||||
|
TvZoomMode => Key::Named(NamedKey::ZoomToggle),
|
||||||
|
TvContentsMenu => Key::Named(NamedKey::TVContentsMenu),
|
||||||
|
TvMediaContextMenu => Key::Named(NamedKey::TVMediaContext),
|
||||||
|
TvTimerProgramming => Key::Named(NamedKey::TVTimer),
|
||||||
|
Help => Key::Named(NamedKey::Help),
|
||||||
|
NavigatePrevious => Key::Named(NamedKey::NavigatePrevious),
|
||||||
|
NavigateNext => Key::Named(NamedKey::NavigateNext),
|
||||||
|
NavigateIn => Key::Named(NamedKey::NavigateIn),
|
||||||
|
NavigateOut => Key::Named(NamedKey::NavigateOut),
|
||||||
|
MediaSkipForward => Key::Named(NamedKey::MediaSkipForward),
|
||||||
|
MediaSkipBackward => Key::Named(NamedKey::MediaSkipBackward),
|
||||||
|
MediaStepForward => Key::Named(NamedKey::MediaStepForward),
|
||||||
|
MediaStepBackward => Key::Named(NamedKey::MediaStepBackward),
|
||||||
|
Cut => Key::Named(NamedKey::Cut),
|
||||||
|
Copy => Key::Named(NamedKey::Copy),
|
||||||
|
Paste => Key::Named(NamedKey::Paste),
|
||||||
|
Refresh => Key::Named(NamedKey::BrowserRefresh),
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
// Keycodes that don't have a logical Key mapping
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
Unknown => Key::Unidentified(native),
|
||||||
|
|
||||||
|
// Can be added on demand
|
||||||
|
SoftLeft => Key::Unidentified(native),
|
||||||
|
SoftRight => Key::Unidentified(native),
|
||||||
|
|
||||||
|
Menu => Key::Unidentified(native),
|
||||||
|
|
||||||
|
Pictsymbols => Key::Unidentified(native),
|
||||||
|
SwitchCharset => Key::Unidentified(native),
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
// Gamepad events should be exposed through a separate API, not
|
||||||
|
// keyboard events
|
||||||
|
ButtonA => Key::Unidentified(native),
|
||||||
|
ButtonB => Key::Unidentified(native),
|
||||||
|
ButtonC => Key::Unidentified(native),
|
||||||
|
ButtonX => Key::Unidentified(native),
|
||||||
|
ButtonY => Key::Unidentified(native),
|
||||||
|
ButtonZ => Key::Unidentified(native),
|
||||||
|
ButtonL1 => Key::Unidentified(native),
|
||||||
|
ButtonR1 => Key::Unidentified(native),
|
||||||
|
ButtonL2 => Key::Unidentified(native),
|
||||||
|
ButtonR2 => Key::Unidentified(native),
|
||||||
|
ButtonThumbl => Key::Unidentified(native),
|
||||||
|
ButtonThumbr => Key::Unidentified(native),
|
||||||
|
ButtonStart => Key::Unidentified(native),
|
||||||
|
ButtonSelect => Key::Unidentified(native),
|
||||||
|
ButtonMode => Key::Unidentified(native),
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
Window => Key::Unidentified(native),
|
||||||
|
|
||||||
|
Button1 => Key::Unidentified(native),
|
||||||
|
Button2 => Key::Unidentified(native),
|
||||||
|
Button3 => Key::Unidentified(native),
|
||||||
|
Button4 => Key::Unidentified(native),
|
||||||
|
Button5 => Key::Unidentified(native),
|
||||||
|
Button6 => Key::Unidentified(native),
|
||||||
|
Button7 => Key::Unidentified(native),
|
||||||
|
Button8 => Key::Unidentified(native),
|
||||||
|
Button9 => Key::Unidentified(native),
|
||||||
|
Button10 => Key::Unidentified(native),
|
||||||
|
Button11 => Key::Unidentified(native),
|
||||||
|
Button12 => Key::Unidentified(native),
|
||||||
|
Button13 => Key::Unidentified(native),
|
||||||
|
Button14 => Key::Unidentified(native),
|
||||||
|
Button15 => Key::Unidentified(native),
|
||||||
|
Button16 => Key::Unidentified(native),
|
||||||
|
|
||||||
|
Yen => Key::Unidentified(native),
|
||||||
|
Ro => Key::Unidentified(native),
|
||||||
|
|
||||||
|
Assist => Key::Unidentified(native),
|
||||||
|
|
||||||
|
Keycode11 => Key::Unidentified(native),
|
||||||
|
Keycode12 => Key::Unidentified(native),
|
||||||
|
|
||||||
|
StemPrimary => Key::Unidentified(native),
|
||||||
|
Stem1 => Key::Unidentified(native),
|
||||||
|
Stem2 => Key::Unidentified(native),
|
||||||
|
Stem3 => Key::Unidentified(native),
|
||||||
|
|
||||||
|
DpadUpLeft => Key::Unidentified(native),
|
||||||
|
DpadDownLeft => Key::Unidentified(native),
|
||||||
|
DpadUpRight => Key::Unidentified(native),
|
||||||
|
DpadDownRight => Key::Unidentified(native),
|
||||||
|
|
||||||
|
SoftSleep => Key::Unidentified(native),
|
||||||
|
|
||||||
|
SystemNavigationUp => Key::Unidentified(native),
|
||||||
|
SystemNavigationDown => Key::Unidentified(native),
|
||||||
|
SystemNavigationLeft => Key::Unidentified(native),
|
||||||
|
SystemNavigationRight => Key::Unidentified(native),
|
||||||
|
|
||||||
|
AllApps => Key::Unidentified(native),
|
||||||
|
ThumbsUp => Key::Unidentified(native),
|
||||||
|
ThumbsDown => Key::Unidentified(native),
|
||||||
|
ProfileSwitch => Key::Unidentified(native),
|
||||||
|
|
||||||
|
// It's always possible that new versions of Android could introduce
|
||||||
|
// key codes we can't know about at compile time.
|
||||||
|
_ => Key::Unidentified(native),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_location(keycode: Keycode) -> KeyLocation {
|
||||||
|
use android_activity::input::Keycode::*;
|
||||||
|
|
||||||
|
match keycode {
|
||||||
|
AltLeft => KeyLocation::Left,
|
||||||
|
AltRight => KeyLocation::Right,
|
||||||
|
ShiftLeft => KeyLocation::Left,
|
||||||
|
ShiftRight => KeyLocation::Right,
|
||||||
|
|
||||||
|
// According to https://developer.android.com/reference/android/view/KeyEvent#KEYCODE_NUM
|
||||||
|
Num => KeyLocation::Left,
|
||||||
|
|
||||||
|
CtrlLeft => KeyLocation::Left,
|
||||||
|
CtrlRight => KeyLocation::Right,
|
||||||
|
MetaLeft => KeyLocation::Left,
|
||||||
|
MetaRight => KeyLocation::Right,
|
||||||
|
|
||||||
|
NumLock => KeyLocation::Numpad,
|
||||||
|
Numpad0 => KeyLocation::Numpad,
|
||||||
|
Numpad1 => KeyLocation::Numpad,
|
||||||
|
Numpad2 => KeyLocation::Numpad,
|
||||||
|
Numpad3 => KeyLocation::Numpad,
|
||||||
|
Numpad4 => KeyLocation::Numpad,
|
||||||
|
Numpad5 => KeyLocation::Numpad,
|
||||||
|
Numpad6 => KeyLocation::Numpad,
|
||||||
|
Numpad7 => KeyLocation::Numpad,
|
||||||
|
Numpad8 => KeyLocation::Numpad,
|
||||||
|
Numpad9 => KeyLocation::Numpad,
|
||||||
|
NumpadDivide => KeyLocation::Numpad,
|
||||||
|
NumpadMultiply => KeyLocation::Numpad,
|
||||||
|
NumpadSubtract => KeyLocation::Numpad,
|
||||||
|
NumpadAdd => KeyLocation::Numpad,
|
||||||
|
NumpadDot => KeyLocation::Numpad,
|
||||||
|
NumpadComma => KeyLocation::Numpad,
|
||||||
|
NumpadEnter => KeyLocation::Numpad,
|
||||||
|
NumpadEquals => KeyLocation::Numpad,
|
||||||
|
NumpadLeftParen => KeyLocation::Numpad,
|
||||||
|
NumpadRightParen => KeyLocation::Numpad,
|
||||||
|
|
||||||
|
_ => KeyLocation::Standard,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,9 +3,10 @@
|
|||||||
use std::{
|
use std::{
|
||||||
cell::{RefCell, RefMut},
|
cell::{RefCell, RefMut},
|
||||||
collections::HashSet,
|
collections::HashSet,
|
||||||
mem,
|
fmt, mem,
|
||||||
os::raw::c_void,
|
os::raw::c_void,
|
||||||
ptr,
|
ptr,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
time::Instant,
|
time::Instant,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -15,22 +16,20 @@ use core_foundation::runloop::{
|
|||||||
kCFRunLoopCommonModes, CFRunLoopAddTimer, CFRunLoopGetMain, CFRunLoopRef, CFRunLoopTimerCreate,
|
kCFRunLoopCommonModes, CFRunLoopAddTimer, CFRunLoopGetMain, CFRunLoopRef, CFRunLoopTimerCreate,
|
||||||
CFRunLoopTimerInvalidate, CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate,
|
CFRunLoopTimerInvalidate, CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate,
|
||||||
};
|
};
|
||||||
use objc2::foundation::{CGRect, CGSize, NSInteger, NSProcessInfo};
|
use icrate::Foundation::{
|
||||||
use objc2::rc::{Id, Shared};
|
CGRect, CGSize, MainThreadMarker, NSInteger, NSOperatingSystemVersion, NSProcessInfo,
|
||||||
use objc2::runtime::Object;
|
};
|
||||||
|
use objc2::rc::Id;
|
||||||
|
use objc2::runtime::AnyObject;
|
||||||
use objc2::{msg_send, sel};
|
use objc2::{msg_send, sel};
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
|
|
||||||
use super::uikit::UIView;
|
use super::uikit::UIView;
|
||||||
use super::view::WinitUIWindow;
|
use super::view::WinitUIWindow;
|
||||||
use crate::{
|
use crate::{
|
||||||
dpi::LogicalSize,
|
dpi::PhysicalSize,
|
||||||
event::{Event, StartCause, WindowEvent},
|
event::{Event, InnerSizeWriter, StartCause, WindowEvent},
|
||||||
event_loop::ControlFlow,
|
event_loop::{ControlFlow, EventLoopWindowTarget as RootEventLoopWindowTarget},
|
||||||
platform_impl::platform::{
|
|
||||||
event_loop::{EventHandler, EventProxy, EventWrapper, Never},
|
|
||||||
ffi::NSOperatingSystemVersion,
|
|
||||||
},
|
|
||||||
window::WindowId as RootWindowId,
|
window::WindowId as RootWindowId,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -46,9 +45,46 @@ macro_rules! bug_assert {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(crate) struct HandlePendingUserEvents;
|
||||||
|
|
||||||
|
pub(crate) struct EventLoopHandler {
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
|
pub(crate) handler: Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootEventLoopWindowTarget)>,
|
||||||
|
pub(crate) event_loop: RootEventLoopWindowTarget,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for EventLoopHandler {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("EventLoopHandler")
|
||||||
|
.field("handler", &"...")
|
||||||
|
.field("event_loop", &self.event_loop)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopHandler {
|
||||||
|
fn handle_event(&mut self, event: Event<HandlePendingUserEvents>) {
|
||||||
|
(self.handler)(event, &self.event_loop)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(crate) enum EventWrapper {
|
||||||
|
StaticEvent(Event<HandlePendingUserEvents>),
|
||||||
|
ScaleFactorChanged(ScaleFactorChanged),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ScaleFactorChanged {
|
||||||
|
pub(super) window: Id<WinitUIWindow>,
|
||||||
|
pub(super) suggested_size: PhysicalSize<u32>,
|
||||||
|
pub(super) scale_factor: f64,
|
||||||
|
}
|
||||||
|
|
||||||
enum UserCallbackTransitionResult<'a> {
|
enum UserCallbackTransitionResult<'a> {
|
||||||
Success {
|
Success {
|
||||||
event_handler: Box<dyn EventHandler>,
|
handler: EventLoopHandler,
|
||||||
active_control_flow: ControlFlow,
|
active_control_flow: ControlFlow,
|
||||||
processing_redraws: bool,
|
processing_redraws: bool,
|
||||||
},
|
},
|
||||||
@@ -57,9 +93,15 @@ enum UserCallbackTransitionResult<'a> {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Event<'static, Never> {
|
impl Event<HandlePendingUserEvents> {
|
||||||
fn is_redraw(&self) -> bool {
|
fn is_redraw(&self) -> bool {
|
||||||
matches!(self, Event::RedrawRequested(_))
|
matches!(
|
||||||
|
self,
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::RedrawRequested,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,41 +110,41 @@ impl Event<'static, Never> {
|
|||||||
#[must_use = "dropping `AppStateImpl` without inspecting it is probably a bug"]
|
#[must_use = "dropping `AppStateImpl` without inspecting it is probably a bug"]
|
||||||
enum AppStateImpl {
|
enum AppStateImpl {
|
||||||
NotLaunched {
|
NotLaunched {
|
||||||
queued_windows: Vec<Id<WinitUIWindow, Shared>>,
|
queued_windows: Vec<Id<WinitUIWindow>>,
|
||||||
queued_events: Vec<EventWrapper>,
|
queued_events: Vec<EventWrapper>,
|
||||||
queued_gpu_redraws: HashSet<Id<WinitUIWindow, Shared>>,
|
queued_gpu_redraws: HashSet<Id<WinitUIWindow>>,
|
||||||
},
|
},
|
||||||
Launching {
|
Launching {
|
||||||
queued_windows: Vec<Id<WinitUIWindow, Shared>>,
|
queued_windows: Vec<Id<WinitUIWindow>>,
|
||||||
queued_events: Vec<EventWrapper>,
|
queued_events: Vec<EventWrapper>,
|
||||||
queued_event_handler: Box<dyn EventHandler>,
|
queued_handler: EventLoopHandler,
|
||||||
queued_gpu_redraws: HashSet<Id<WinitUIWindow, Shared>>,
|
queued_gpu_redraws: HashSet<Id<WinitUIWindow>>,
|
||||||
},
|
},
|
||||||
ProcessingEvents {
|
ProcessingEvents {
|
||||||
event_handler: Box<dyn EventHandler>,
|
handler: EventLoopHandler,
|
||||||
queued_gpu_redraws: HashSet<Id<WinitUIWindow, Shared>>,
|
queued_gpu_redraws: HashSet<Id<WinitUIWindow>>,
|
||||||
active_control_flow: ControlFlow,
|
active_control_flow: ControlFlow,
|
||||||
},
|
},
|
||||||
// special state to deal with reentrancy and prevent mutable aliasing.
|
// special state to deal with reentrancy and prevent mutable aliasing.
|
||||||
InUserCallback {
|
InUserCallback {
|
||||||
queued_events: Vec<EventWrapper>,
|
queued_events: Vec<EventWrapper>,
|
||||||
queued_gpu_redraws: HashSet<Id<WinitUIWindow, Shared>>,
|
queued_gpu_redraws: HashSet<Id<WinitUIWindow>>,
|
||||||
},
|
},
|
||||||
ProcessingRedraws {
|
ProcessingRedraws {
|
||||||
event_handler: Box<dyn EventHandler>,
|
handler: EventLoopHandler,
|
||||||
active_control_flow: ControlFlow,
|
active_control_flow: ControlFlow,
|
||||||
},
|
},
|
||||||
Waiting {
|
Waiting {
|
||||||
waiting_event_handler: Box<dyn EventHandler>,
|
waiting_handler: EventLoopHandler,
|
||||||
start: Instant,
|
start: Instant,
|
||||||
},
|
},
|
||||||
PollFinished {
|
PollFinished {
|
||||||
waiting_event_handler: Box<dyn EventHandler>,
|
waiting_handler: EventLoopHandler,
|
||||||
},
|
},
|
||||||
Terminated,
|
Terminated,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct AppState {
|
pub(crate) struct AppState {
|
||||||
// This should never be `None`, except for briefly during a state transition.
|
// This should never be `None`, except for briefly during a state transition.
|
||||||
app_state: Option<AppStateImpl>,
|
app_state: Option<AppStateImpl>,
|
||||||
control_flow: ControlFlow,
|
control_flow: ControlFlow,
|
||||||
@@ -110,24 +152,18 @@ struct AppState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AppState {
|
impl AppState {
|
||||||
// requires main thread
|
pub(crate) fn get_mut(_mtm: MainThreadMarker) -> RefMut<'static, AppState> {
|
||||||
unsafe fn get_mut() -> RefMut<'static, AppState> {
|
|
||||||
// basically everything in UIKit requires the main thread, so it's pointless to use the
|
// basically everything in UIKit requires the main thread, so it's pointless to use the
|
||||||
// std::sync APIs.
|
// std::sync APIs.
|
||||||
// must be mut because plain `static` requires `Sync`
|
// must be mut because plain `static` requires `Sync`
|
||||||
static mut APP_STATE: RefCell<Option<AppState>> = RefCell::new(None);
|
static mut APP_STATE: RefCell<Option<AppState>> = RefCell::new(None);
|
||||||
|
|
||||||
if cfg!(debug_assertions) {
|
let mut guard = unsafe { APP_STATE.borrow_mut() };
|
||||||
assert_main_thread!(
|
|
||||||
"bug in winit: `AppState::get_mut()` can only be called on the main thread"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let mut guard = APP_STATE.borrow_mut();
|
|
||||||
if guard.is_none() {
|
if guard.is_none() {
|
||||||
#[inline(never)]
|
#[inline(never)]
|
||||||
#[cold]
|
#[cold]
|
||||||
unsafe fn init_guard(guard: &mut RefMut<'static, Option<AppState>>) {
|
fn init_guard(guard: &mut RefMut<'static, Option<AppState>>) {
|
||||||
let waker = EventLoopWaker::new(CFRunLoopGetMain());
|
let waker = EventLoopWaker::new(unsafe { CFRunLoopGetMain() });
|
||||||
**guard = Some(AppState {
|
**guard = Some(AppState {
|
||||||
app_state: Some(AppStateImpl::NotLaunched {
|
app_state: Some(AppStateImpl::NotLaunched {
|
||||||
queued_windows: Vec::new(),
|
queued_windows: Vec::new(),
|
||||||
@@ -138,7 +174,7 @@ impl AppState {
|
|||||||
waker,
|
waker,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
init_guard(&mut guard)
|
init_guard(&mut guard);
|
||||||
}
|
}
|
||||||
RefMut::map(guard, |state| state.as_mut().unwrap())
|
RefMut::map(guard, |state| state.as_mut().unwrap())
|
||||||
}
|
}
|
||||||
@@ -187,7 +223,11 @@ impl AppState {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn will_launch_transition(&mut self, queued_event_handler: Box<dyn EventHandler>) {
|
fn has_terminated(&self) -> bool {
|
||||||
|
matches!(self.state(), AppStateImpl::Terminated)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn will_launch_transition(&mut self, queued_handler: EventLoopHandler) {
|
||||||
let (queued_windows, queued_events, queued_gpu_redraws) = match self.take_state() {
|
let (queued_windows, queued_events, queued_gpu_redraws) = match self.take_state() {
|
||||||
AppStateImpl::NotLaunched {
|
AppStateImpl::NotLaunched {
|
||||||
queued_windows,
|
queued_windows,
|
||||||
@@ -199,31 +239,29 @@ impl AppState {
|
|||||||
self.set_state(AppStateImpl::Launching {
|
self.set_state(AppStateImpl::Launching {
|
||||||
queued_windows,
|
queued_windows,
|
||||||
queued_events,
|
queued_events,
|
||||||
queued_event_handler,
|
queued_handler,
|
||||||
queued_gpu_redraws,
|
queued_gpu_redraws,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn did_finish_launching_transition(
|
fn did_finish_launching_transition(&mut self) -> (Vec<Id<WinitUIWindow>>, Vec<EventWrapper>) {
|
||||||
&mut self,
|
let (windows, events, handler, queued_gpu_redraws) = match self.take_state() {
|
||||||
) -> (Vec<Id<WinitUIWindow, Shared>>, Vec<EventWrapper>) {
|
|
||||||
let (windows, events, event_handler, queued_gpu_redraws) = match self.take_state() {
|
|
||||||
AppStateImpl::Launching {
|
AppStateImpl::Launching {
|
||||||
queued_windows,
|
queued_windows,
|
||||||
queued_events,
|
queued_events,
|
||||||
queued_event_handler,
|
queued_handler,
|
||||||
queued_gpu_redraws,
|
queued_gpu_redraws,
|
||||||
} => (
|
} => (
|
||||||
queued_windows,
|
queued_windows,
|
||||||
queued_events,
|
queued_events,
|
||||||
queued_event_handler,
|
queued_handler,
|
||||||
queued_gpu_redraws,
|
queued_gpu_redraws,
|
||||||
),
|
),
|
||||||
s => bug!("unexpected state {:?}", s),
|
s => bug!("unexpected state {:?}", s),
|
||||||
};
|
};
|
||||||
self.set_state(AppStateImpl::ProcessingEvents {
|
self.set_state(AppStateImpl::ProcessingEvents {
|
||||||
event_handler,
|
handler,
|
||||||
active_control_flow: ControlFlow::Poll,
|
active_control_flow: self.control_flow,
|
||||||
queued_gpu_redraws,
|
queued_gpu_redraws,
|
||||||
});
|
});
|
||||||
(windows, events)
|
(windows, events)
|
||||||
@@ -232,28 +270,23 @@ impl AppState {
|
|||||||
fn wakeup_transition(&mut self) -> Option<EventWrapper> {
|
fn wakeup_transition(&mut self) -> Option<EventWrapper> {
|
||||||
// before `AppState::did_finish_launching` is called, pretend there is no running
|
// before `AppState::did_finish_launching` is called, pretend there is no running
|
||||||
// event loop.
|
// event loop.
|
||||||
if !self.has_launched() {
|
if !self.has_launched() || self.has_terminated() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let (event_handler, event) = match (self.control_flow, self.take_state()) {
|
let (handler, event) = match (self.control_flow, self.take_state()) {
|
||||||
(
|
(ControlFlow::Poll, AppStateImpl::PollFinished { waiting_handler }) => (
|
||||||
ControlFlow::Poll,
|
waiting_handler,
|
||||||
AppStateImpl::PollFinished {
|
|
||||||
waiting_event_handler,
|
|
||||||
},
|
|
||||||
) => (
|
|
||||||
waiting_event_handler,
|
|
||||||
EventWrapper::StaticEvent(Event::NewEvents(StartCause::Poll)),
|
EventWrapper::StaticEvent(Event::NewEvents(StartCause::Poll)),
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
ControlFlow::Wait,
|
ControlFlow::Wait,
|
||||||
AppStateImpl::Waiting {
|
AppStateImpl::Waiting {
|
||||||
waiting_event_handler,
|
waiting_handler,
|
||||||
start,
|
start,
|
||||||
},
|
},
|
||||||
) => (
|
) => (
|
||||||
waiting_event_handler,
|
waiting_handler,
|
||||||
EventWrapper::StaticEvent(Event::NewEvents(StartCause::WaitCancelled {
|
EventWrapper::StaticEvent(Event::NewEvents(StartCause::WaitCancelled {
|
||||||
start,
|
start,
|
||||||
requested_resume: None,
|
requested_resume: None,
|
||||||
@@ -262,7 +295,7 @@ impl AppState {
|
|||||||
(
|
(
|
||||||
ControlFlow::WaitUntil(requested_resume),
|
ControlFlow::WaitUntil(requested_resume),
|
||||||
AppStateImpl::Waiting {
|
AppStateImpl::Waiting {
|
||||||
waiting_event_handler,
|
waiting_handler,
|
||||||
start,
|
start,
|
||||||
},
|
},
|
||||||
) => {
|
) => {
|
||||||
@@ -277,14 +310,13 @@ impl AppState {
|
|||||||
requested_resume: Some(requested_resume),
|
requested_resume: Some(requested_resume),
|
||||||
}))
|
}))
|
||||||
};
|
};
|
||||||
(waiting_event_handler, event)
|
(waiting_handler, event)
|
||||||
}
|
}
|
||||||
(ControlFlow::ExitWithCode(_), _) => bug!("unexpected `ControlFlow` `Exit`"),
|
|
||||||
s => bug!("`EventHandler` unexpectedly woke up {:?}", s),
|
s => bug!("`EventHandler` unexpectedly woke up {:?}", s),
|
||||||
};
|
};
|
||||||
|
|
||||||
self.set_state(AppStateImpl::ProcessingEvents {
|
self.set_state(AppStateImpl::ProcessingEvents {
|
||||||
event_handler,
|
handler,
|
||||||
queued_gpu_redraws: Default::default(),
|
queued_gpu_redraws: Default::default(),
|
||||||
active_control_flow: self.control_flow,
|
active_control_flow: self.control_flow,
|
||||||
});
|
});
|
||||||
@@ -329,25 +361,20 @@ impl AppState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let (event_handler, queued_gpu_redraws, active_control_flow, processing_redraws) =
|
let (handler, queued_gpu_redraws, active_control_flow, processing_redraws) =
|
||||||
match self.take_state() {
|
match self.take_state() {
|
||||||
AppStateImpl::Launching { .. }
|
AppStateImpl::Launching { .. }
|
||||||
| AppStateImpl::NotLaunched { .. }
|
| AppStateImpl::NotLaunched { .. }
|
||||||
| AppStateImpl::InUserCallback { .. } => unreachable!(),
|
| AppStateImpl::InUserCallback { .. } => unreachable!(),
|
||||||
AppStateImpl::ProcessingEvents {
|
AppStateImpl::ProcessingEvents {
|
||||||
event_handler,
|
handler,
|
||||||
queued_gpu_redraws,
|
queued_gpu_redraws,
|
||||||
active_control_flow,
|
active_control_flow,
|
||||||
} => (
|
} => (handler, queued_gpu_redraws, active_control_flow, false),
|
||||||
event_handler,
|
|
||||||
queued_gpu_redraws,
|
|
||||||
active_control_flow,
|
|
||||||
false,
|
|
||||||
),
|
|
||||||
AppStateImpl::ProcessingRedraws {
|
AppStateImpl::ProcessingRedraws {
|
||||||
event_handler,
|
handler,
|
||||||
active_control_flow,
|
active_control_flow,
|
||||||
} => (event_handler, Default::default(), active_control_flow, true),
|
} => (handler, Default::default(), active_control_flow, true),
|
||||||
AppStateImpl::PollFinished { .. }
|
AppStateImpl::PollFinished { .. }
|
||||||
| AppStateImpl::Waiting { .. }
|
| AppStateImpl::Waiting { .. }
|
||||||
| AppStateImpl::Terminated => unreachable!(),
|
| AppStateImpl::Terminated => unreachable!(),
|
||||||
@@ -357,49 +384,46 @@ impl AppState {
|
|||||||
queued_gpu_redraws,
|
queued_gpu_redraws,
|
||||||
});
|
});
|
||||||
UserCallbackTransitionResult::Success {
|
UserCallbackTransitionResult::Success {
|
||||||
event_handler,
|
handler,
|
||||||
active_control_flow,
|
active_control_flow,
|
||||||
processing_redraws,
|
processing_redraws,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main_events_cleared_transition(&mut self) -> HashSet<Id<WinitUIWindow, Shared>> {
|
fn main_events_cleared_transition(&mut self) -> HashSet<Id<WinitUIWindow>> {
|
||||||
let (event_handler, queued_gpu_redraws, active_control_flow) = match self.take_state() {
|
let (handler, queued_gpu_redraws, active_control_flow) = match self.take_state() {
|
||||||
AppStateImpl::ProcessingEvents {
|
AppStateImpl::ProcessingEvents {
|
||||||
event_handler,
|
handler,
|
||||||
queued_gpu_redraws,
|
queued_gpu_redraws,
|
||||||
active_control_flow,
|
active_control_flow,
|
||||||
} => (event_handler, queued_gpu_redraws, active_control_flow),
|
} => (handler, queued_gpu_redraws, active_control_flow),
|
||||||
s => bug!("unexpected state {:?}", s),
|
s => bug!("unexpected state {:?}", s),
|
||||||
};
|
};
|
||||||
self.set_state(AppStateImpl::ProcessingRedraws {
|
self.set_state(AppStateImpl::ProcessingRedraws {
|
||||||
event_handler,
|
handler,
|
||||||
active_control_flow,
|
active_control_flow,
|
||||||
});
|
});
|
||||||
queued_gpu_redraws
|
queued_gpu_redraws
|
||||||
}
|
}
|
||||||
|
|
||||||
fn events_cleared_transition(&mut self) {
|
fn events_cleared_transition(&mut self) {
|
||||||
if !self.has_launched() {
|
if !self.has_launched() || self.has_terminated() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let (waiting_event_handler, old) = match self.take_state() {
|
let (waiting_handler, old) = match self.take_state() {
|
||||||
AppStateImpl::ProcessingRedraws {
|
AppStateImpl::ProcessingRedraws {
|
||||||
event_handler,
|
handler,
|
||||||
active_control_flow,
|
active_control_flow,
|
||||||
} => (event_handler, active_control_flow),
|
} => (handler, active_control_flow),
|
||||||
s => bug!("unexpected state {:?}", s),
|
s => bug!("unexpected state {:?}", s),
|
||||||
};
|
};
|
||||||
|
|
||||||
let new = self.control_flow;
|
let new = self.control_flow;
|
||||||
match (old, new) {
|
match (old, new) {
|
||||||
(ControlFlow::Poll, ControlFlow::Poll) => self.set_state(AppStateImpl::PollFinished {
|
|
||||||
waiting_event_handler,
|
|
||||||
}),
|
|
||||||
(ControlFlow::Wait, ControlFlow::Wait) => {
|
(ControlFlow::Wait, ControlFlow::Wait) => {
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
self.set_state(AppStateImpl::Waiting {
|
self.set_state(AppStateImpl::Waiting {
|
||||||
waiting_event_handler,
|
waiting_handler,
|
||||||
start,
|
start,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -408,14 +432,14 @@ impl AppState {
|
|||||||
{
|
{
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
self.set_state(AppStateImpl::Waiting {
|
self.set_state(AppStateImpl::Waiting {
|
||||||
waiting_event_handler,
|
waiting_handler,
|
||||||
start,
|
start,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
(_, ControlFlow::Wait) => {
|
(_, ControlFlow::Wait) => {
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
self.set_state(AppStateImpl::Waiting {
|
self.set_state(AppStateImpl::Waiting {
|
||||||
waiting_event_handler,
|
waiting_handler,
|
||||||
start,
|
start,
|
||||||
});
|
});
|
||||||
self.waker.stop()
|
self.waker.stop()
|
||||||
@@ -423,41 +447,37 @@ impl AppState {
|
|||||||
(_, ControlFlow::WaitUntil(new_instant)) => {
|
(_, ControlFlow::WaitUntil(new_instant)) => {
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
self.set_state(AppStateImpl::Waiting {
|
self.set_state(AppStateImpl::Waiting {
|
||||||
waiting_event_handler,
|
waiting_handler,
|
||||||
start,
|
start,
|
||||||
});
|
});
|
||||||
self.waker.start_at(new_instant)
|
self.waker.start_at(new_instant)
|
||||||
}
|
}
|
||||||
|
// Unlike on macOS, handle Poll to Poll transition here to call the waker
|
||||||
(_, ControlFlow::Poll) => {
|
(_, ControlFlow::Poll) => {
|
||||||
self.set_state(AppStateImpl::PollFinished {
|
self.set_state(AppStateImpl::PollFinished { waiting_handler });
|
||||||
waiting_event_handler,
|
|
||||||
});
|
|
||||||
self.waker.start()
|
self.waker.start()
|
||||||
}
|
}
|
||||||
(_, ControlFlow::ExitWithCode(_)) => {
|
|
||||||
// https://developer.apple.com/library/archive/qa/qa1561/_index.html
|
|
||||||
// it is not possible to quit an iOS app gracefully and programatically
|
|
||||||
warn!("`ControlFlow::Exit` ignored on iOS");
|
|
||||||
self.control_flow = old
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn terminated_transition(&mut self) -> Box<dyn EventHandler> {
|
fn terminated_transition(&mut self) -> EventLoopHandler {
|
||||||
match self.replace_state(AppStateImpl::Terminated) {
|
match self.replace_state(AppStateImpl::Terminated) {
|
||||||
AppStateImpl::ProcessingEvents { event_handler, .. } => event_handler,
|
AppStateImpl::ProcessingEvents { handler, .. } => handler,
|
||||||
s => bug!(
|
s => bug!("`LoopExiting` happened while not processing events {:?}", s),
|
||||||
"`LoopDestroyed` happened while not processing events {:?}",
|
|
||||||
s
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn set_control_flow(&mut self, control_flow: ControlFlow) {
|
||||||
|
self.control_flow = control_flow;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn control_flow(&self) -> ControlFlow {
|
||||||
|
self.control_flow
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// requires main thread and window is a UIWindow
|
pub(crate) fn set_key_window(mtm: MainThreadMarker, window: &Id<WinitUIWindow>) {
|
||||||
// retains window
|
let mut this = AppState::get_mut(mtm);
|
||||||
pub(crate) unsafe fn set_key_window(window: &Id<WinitUIWindow, Shared>) {
|
|
||||||
let mut this = AppState::get_mut();
|
|
||||||
match this.state_mut() {
|
match this.state_mut() {
|
||||||
&mut AppStateImpl::NotLaunched {
|
&mut AppStateImpl::NotLaunched {
|
||||||
ref mut queued_windows,
|
ref mut queued_windows,
|
||||||
@@ -477,10 +497,8 @@ pub(crate) unsafe fn set_key_window(window: &Id<WinitUIWindow, Shared>) {
|
|||||||
window.makeKeyAndVisible();
|
window.makeKeyAndVisible();
|
||||||
}
|
}
|
||||||
|
|
||||||
// requires main thread and window is a UIWindow
|
pub(crate) fn queue_gl_or_metal_redraw(mtm: MainThreadMarker, window: Id<WinitUIWindow>) {
|
||||||
// retains window
|
let mut this = AppState::get_mut(mtm);
|
||||||
pub(crate) unsafe fn queue_gl_or_metal_redraw(window: Id<WinitUIWindow, Shared>) {
|
|
||||||
let mut this = AppState::get_mut();
|
|
||||||
match this.state_mut() {
|
match this.state_mut() {
|
||||||
&mut AppStateImpl::NotLaunched {
|
&mut AppStateImpl::NotLaunched {
|
||||||
ref mut queued_gpu_redraws,
|
ref mut queued_gpu_redraws,
|
||||||
@@ -509,24 +527,17 @@ pub(crate) unsafe fn queue_gl_or_metal_redraw(window: Id<WinitUIWindow, Shared>)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// requires main thread
|
pub(crate) fn will_launch(mtm: MainThreadMarker, queued_handler: EventLoopHandler) {
|
||||||
pub unsafe fn will_launch(queued_event_handler: Box<dyn EventHandler>) {
|
AppState::get_mut(mtm).will_launch_transition(queued_handler)
|
||||||
AppState::get_mut().will_launch_transition(queued_event_handler)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// requires main thread
|
pub fn did_finish_launching(mtm: MainThreadMarker) {
|
||||||
pub unsafe fn did_finish_launching() {
|
let mut this = AppState::get_mut(mtm);
|
||||||
let mut this = AppState::get_mut();
|
|
||||||
let windows = match this.state_mut() {
|
let windows = match this.state_mut() {
|
||||||
AppStateImpl::Launching { queued_windows, .. } => mem::take(queued_windows),
|
AppStateImpl::Launching { queued_windows, .. } => mem::take(queued_windows),
|
||||||
s => bug!("unexpected state {:?}", s),
|
s => bug!("unexpected state {:?}", s),
|
||||||
};
|
};
|
||||||
|
|
||||||
// start waking up the event loop now!
|
|
||||||
bug_assert!(
|
|
||||||
this.control_flow == ControlFlow::Poll,
|
|
||||||
"unexpectedly not setup to `Poll` on launch!"
|
|
||||||
);
|
|
||||||
this.waker.start();
|
this.waker.start();
|
||||||
|
|
||||||
// have to drop RefMut because the window setup code below can trigger new events
|
// have to drop RefMut because the window setup code below can trigger new events
|
||||||
@@ -544,7 +555,7 @@ pub unsafe fn did_finish_launching() {
|
|||||||
// completed. This may result in incorrect visual appearance.
|
// completed. This may result in incorrect visual appearance.
|
||||||
// ```
|
// ```
|
||||||
let screen = window.screen();
|
let screen = window.screen();
|
||||||
let _: () = msg_send![&window, setScreen: ptr::null::<Object>()];
|
let _: () = unsafe { msg_send![&window, setScreen: ptr::null::<AnyObject>()] };
|
||||||
window.setScreen(&screen);
|
window.setScreen(&screen);
|
||||||
|
|
||||||
let controller = window.rootViewController();
|
let controller = window.rootViewController();
|
||||||
@@ -554,13 +565,13 @@ pub unsafe fn did_finish_launching() {
|
|||||||
window.makeKeyAndVisible();
|
window.makeKeyAndVisible();
|
||||||
}
|
}
|
||||||
|
|
||||||
let (windows, events) = AppState::get_mut().did_finish_launching_transition();
|
let (windows, events) = AppState::get_mut(mtm).did_finish_launching_transition();
|
||||||
|
|
||||||
let events = std::iter::once(EventWrapper::StaticEvent(Event::NewEvents(
|
let events = std::iter::once(EventWrapper::StaticEvent(Event::NewEvents(
|
||||||
StartCause::Init,
|
StartCause::Init,
|
||||||
)))
|
)))
|
||||||
.chain(events);
|
.chain(events);
|
||||||
handle_nonuser_events(events);
|
handle_nonuser_events(mtm, events);
|
||||||
|
|
||||||
// the above window dance hack, could possibly trigger new windows to be created.
|
// the above window dance hack, could possibly trigger new windows to be created.
|
||||||
// we can just set those windows up normally, as they were created after didFinishLaunching
|
// we can just set those windows up normally, as they were created after didFinishLaunching
|
||||||
@@ -569,40 +580,43 @@ pub unsafe fn did_finish_launching() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// requires main thread
|
|
||||||
// AppState::did_finish_launching handles the special transition `Init`
|
// AppState::did_finish_launching handles the special transition `Init`
|
||||||
pub unsafe fn handle_wakeup_transition() {
|
pub fn handle_wakeup_transition(mtm: MainThreadMarker) {
|
||||||
let mut this = AppState::get_mut();
|
let mut this = AppState::get_mut(mtm);
|
||||||
let wakeup_event = match this.wakeup_transition() {
|
let wakeup_event = match this.wakeup_transition() {
|
||||||
None => return,
|
None => return,
|
||||||
Some(wakeup_event) => wakeup_event,
|
Some(wakeup_event) => wakeup_event,
|
||||||
};
|
};
|
||||||
drop(this);
|
drop(this);
|
||||||
|
|
||||||
handle_nonuser_event(wakeup_event)
|
handle_nonuser_event(mtm, wakeup_event)
|
||||||
}
|
}
|
||||||
|
|
||||||
// requires main thread
|
pub(crate) fn handle_nonuser_event(mtm: MainThreadMarker, event: EventWrapper) {
|
||||||
pub(crate) unsafe fn handle_nonuser_event(event: EventWrapper) {
|
handle_nonuser_events(mtm, std::iter::once(event))
|
||||||
handle_nonuser_events(std::iter::once(event))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// requires main thread
|
pub(crate) fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>(
|
||||||
pub(crate) unsafe fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>(events: I) {
|
mtm: MainThreadMarker,
|
||||||
let mut this = AppState::get_mut();
|
events: I,
|
||||||
let (mut event_handler, active_control_flow, processing_redraws) =
|
) {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
if this.has_terminated() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (mut handler, active_control_flow, processing_redraws) =
|
||||||
match this.try_user_callback_transition() {
|
match this.try_user_callback_transition() {
|
||||||
UserCallbackTransitionResult::ReentrancyPrevented { queued_events } => {
|
UserCallbackTransitionResult::ReentrancyPrevented { queued_events } => {
|
||||||
queued_events.extend(events);
|
queued_events.extend(events);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
UserCallbackTransitionResult::Success {
|
UserCallbackTransitionResult::Success {
|
||||||
event_handler,
|
handler,
|
||||||
active_control_flow,
|
active_control_flow,
|
||||||
processing_redraws,
|
processing_redraws,
|
||||||
} => (event_handler, active_control_flow, processing_redraws),
|
} => (handler, active_control_flow, processing_redraws),
|
||||||
};
|
};
|
||||||
let mut control_flow = this.control_flow;
|
|
||||||
drop(this);
|
drop(this);
|
||||||
|
|
||||||
for wrapper in events {
|
for wrapper in events {
|
||||||
@@ -616,16 +630,14 @@ pub(crate) unsafe fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>
|
|||||||
event
|
event
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
event_handler.handle_nonuser_event(event, &mut control_flow)
|
handler.handle_event(event)
|
||||||
}
|
|
||||||
EventWrapper::EventProxy(proxy) => {
|
|
||||||
handle_event_proxy(&mut event_handler, control_flow, proxy)
|
|
||||||
}
|
}
|
||||||
|
EventWrapper::ScaleFactorChanged(event) => handle_hidpi_proxy(&mut handler, event),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let mut this = AppState::get_mut();
|
let mut this = AppState::get_mut(mtm);
|
||||||
let queued_events = match this.state_mut() {
|
let queued_events = match this.state_mut() {
|
||||||
&mut AppStateImpl::InUserCallback {
|
&mut AppStateImpl::InUserCallback {
|
||||||
ref mut queued_events,
|
ref mut queued_events,
|
||||||
@@ -647,17 +659,16 @@ pub(crate) unsafe fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>
|
|||||||
"redraw queued while processing redraws"
|
"redraw queued while processing redraws"
|
||||||
);
|
);
|
||||||
AppStateImpl::ProcessingRedraws {
|
AppStateImpl::ProcessingRedraws {
|
||||||
event_handler,
|
handler,
|
||||||
active_control_flow,
|
active_control_flow,
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
AppStateImpl::ProcessingEvents {
|
AppStateImpl::ProcessingEvents {
|
||||||
event_handler,
|
handler,
|
||||||
queued_gpu_redraws,
|
queued_gpu_redraws,
|
||||||
active_control_flow,
|
active_control_flow,
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
this.control_flow = control_flow;
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
drop(this);
|
drop(this);
|
||||||
@@ -673,40 +684,36 @@ pub(crate) unsafe fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>
|
|||||||
event
|
event
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
event_handler.handle_nonuser_event(event, &mut control_flow)
|
handler.handle_event(event)
|
||||||
}
|
|
||||||
EventWrapper::EventProxy(proxy) => {
|
|
||||||
handle_event_proxy(&mut event_handler, control_flow, proxy)
|
|
||||||
}
|
}
|
||||||
|
EventWrapper::ScaleFactorChanged(event) => handle_hidpi_proxy(&mut handler, event),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// requires main thread
|
fn handle_user_events(mtm: MainThreadMarker) {
|
||||||
unsafe fn handle_user_events() {
|
let mut this = AppState::get_mut(mtm);
|
||||||
let mut this = AppState::get_mut();
|
let (mut handler, active_control_flow, processing_redraws) =
|
||||||
let mut control_flow = this.control_flow;
|
|
||||||
let (mut event_handler, active_control_flow, processing_redraws) =
|
|
||||||
match this.try_user_callback_transition() {
|
match this.try_user_callback_transition() {
|
||||||
UserCallbackTransitionResult::ReentrancyPrevented { .. } => {
|
UserCallbackTransitionResult::ReentrancyPrevented { .. } => {
|
||||||
bug!("unexpected attempted to process an event")
|
bug!("unexpected attempted to process an event")
|
||||||
}
|
}
|
||||||
UserCallbackTransitionResult::Success {
|
UserCallbackTransitionResult::Success {
|
||||||
event_handler,
|
handler,
|
||||||
active_control_flow,
|
active_control_flow,
|
||||||
processing_redraws,
|
processing_redraws,
|
||||||
} => (event_handler, active_control_flow, processing_redraws),
|
} => (handler, active_control_flow, processing_redraws),
|
||||||
};
|
};
|
||||||
if processing_redraws {
|
if processing_redraws {
|
||||||
bug!("user events attempted to be sent out while `ProcessingRedraws`");
|
bug!("user events attempted to be sent out while `ProcessingRedraws`");
|
||||||
}
|
}
|
||||||
drop(this);
|
drop(this);
|
||||||
|
|
||||||
event_handler.handle_user_events(&mut control_flow);
|
handler.handle_event(Event::UserEvent(HandlePendingUserEvents));
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let mut this = AppState::get_mut();
|
let mut this = AppState::get_mut(mtm);
|
||||||
let queued_events = match this.state_mut() {
|
let queued_events = match this.state_mut() {
|
||||||
&mut AppStateImpl::InUserCallback {
|
&mut AppStateImpl::InUserCallback {
|
||||||
ref mut queued_events,
|
ref mut queued_events,
|
||||||
@@ -723,33 +730,28 @@ unsafe fn handle_user_events() {
|
|||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
};
|
};
|
||||||
this.app_state = Some(AppStateImpl::ProcessingEvents {
|
this.app_state = Some(AppStateImpl::ProcessingEvents {
|
||||||
event_handler,
|
handler,
|
||||||
queued_gpu_redraws,
|
queued_gpu_redraws,
|
||||||
active_control_flow,
|
active_control_flow,
|
||||||
});
|
});
|
||||||
this.control_flow = control_flow;
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
drop(this);
|
drop(this);
|
||||||
|
|
||||||
for wrapper in queued_events {
|
for wrapper in queued_events {
|
||||||
match wrapper {
|
match wrapper {
|
||||||
EventWrapper::StaticEvent(event) => {
|
EventWrapper::StaticEvent(event) => handler.handle_event(event),
|
||||||
event_handler.handle_nonuser_event(event, &mut control_flow)
|
EventWrapper::ScaleFactorChanged(event) => handle_hidpi_proxy(&mut handler, event),
|
||||||
}
|
|
||||||
EventWrapper::EventProxy(proxy) => {
|
|
||||||
handle_event_proxy(&mut event_handler, control_flow, proxy)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
event_handler.handle_user_events(&mut control_flow);
|
|
||||||
|
handler.handle_event(Event::UserEvent(HandlePendingUserEvents));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// requires main thread
|
pub fn handle_main_events_cleared(mtm: MainThreadMarker) {
|
||||||
pub unsafe fn handle_main_events_cleared() {
|
let mut this = AppState::get_mut(mtm);
|
||||||
let mut this = AppState::get_mut();
|
if !this.has_launched() || this.has_terminated() {
|
||||||
if !this.has_launched() {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
match this.state_mut() {
|
match this.state_mut() {
|
||||||
@@ -758,84 +760,62 @@ pub unsafe fn handle_main_events_cleared() {
|
|||||||
};
|
};
|
||||||
drop(this);
|
drop(this);
|
||||||
|
|
||||||
// User events are always sent out at the end of the "MainEventLoop"
|
handle_user_events(mtm);
|
||||||
handle_user_events();
|
|
||||||
handle_nonuser_event(EventWrapper::StaticEvent(Event::MainEventsCleared));
|
|
||||||
|
|
||||||
let mut this = AppState::get_mut();
|
let mut this = AppState::get_mut(mtm);
|
||||||
let mut redraw_events: Vec<EventWrapper> = this
|
let redraw_events: Vec<EventWrapper> = this
|
||||||
.main_events_cleared_transition()
|
.main_events_cleared_transition()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|window| EventWrapper::StaticEvent(Event::RedrawRequested(RootWindowId(window.id()))))
|
.map(|window| {
|
||||||
|
EventWrapper::StaticEvent(Event::WindowEvent {
|
||||||
|
window_id: RootWindowId(window.id()),
|
||||||
|
event: WindowEvent::RedrawRequested,
|
||||||
|
})
|
||||||
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
redraw_events.push(EventWrapper::StaticEvent(Event::RedrawEventsCleared));
|
|
||||||
drop(this);
|
drop(this);
|
||||||
|
|
||||||
handle_nonuser_events(redraw_events);
|
handle_nonuser_events(mtm, redraw_events);
|
||||||
|
handle_nonuser_event(mtm, EventWrapper::StaticEvent(Event::AboutToWait));
|
||||||
}
|
}
|
||||||
|
|
||||||
// requires main thread
|
pub fn handle_events_cleared(mtm: MainThreadMarker) {
|
||||||
pub unsafe fn handle_events_cleared() {
|
AppState::get_mut(mtm).events_cleared_transition();
|
||||||
AppState::get_mut().events_cleared_transition();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// requires main thread
|
pub fn terminated(mtm: MainThreadMarker) {
|
||||||
pub unsafe fn terminated() {
|
let mut this = AppState::get_mut(mtm);
|
||||||
let mut this = AppState::get_mut();
|
let mut handler = this.terminated_transition();
|
||||||
let mut event_handler = this.terminated_transition();
|
|
||||||
let mut control_flow = this.control_flow;
|
|
||||||
drop(this);
|
drop(this);
|
||||||
|
|
||||||
event_handler.handle_nonuser_event(Event::LoopDestroyed, &mut control_flow)
|
handler.handle_event(Event::LoopExiting)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_event_proxy(
|
fn handle_hidpi_proxy(handler: &mut EventLoopHandler, event: ScaleFactorChanged) {
|
||||||
event_handler: &mut Box<dyn EventHandler>,
|
let ScaleFactorChanged {
|
||||||
control_flow: ControlFlow,
|
suggested_size,
|
||||||
proxy: EventProxy,
|
scale_factor,
|
||||||
) {
|
window,
|
||||||
match proxy {
|
} = event;
|
||||||
EventProxy::DpiChangedProxy {
|
let new_inner_size = Arc::new(Mutex::new(suggested_size));
|
||||||
suggested_size,
|
|
||||||
scale_factor,
|
|
||||||
window,
|
|
||||||
} => handle_hidpi_proxy(
|
|
||||||
event_handler,
|
|
||||||
control_flow,
|
|
||||||
suggested_size,
|
|
||||||
scale_factor,
|
|
||||||
window,
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn handle_hidpi_proxy(
|
|
||||||
event_handler: &mut Box<dyn EventHandler>,
|
|
||||||
mut control_flow: ControlFlow,
|
|
||||||
suggested_size: LogicalSize<f64>,
|
|
||||||
scale_factor: f64,
|
|
||||||
window: Id<WinitUIWindow, Shared>,
|
|
||||||
) {
|
|
||||||
let mut size = suggested_size.to_physical(scale_factor);
|
|
||||||
let new_inner_size = &mut size;
|
|
||||||
let event = Event::WindowEvent {
|
let event = Event::WindowEvent {
|
||||||
window_id: RootWindowId(window.id()),
|
window_id: RootWindowId(window.id()),
|
||||||
event: WindowEvent::ScaleFactorChanged {
|
event: WindowEvent::ScaleFactorChanged {
|
||||||
scale_factor,
|
scale_factor,
|
||||||
new_inner_size,
|
inner_size_writer: InnerSizeWriter::new(Arc::downgrade(&new_inner_size)),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
event_handler.handle_nonuser_event(event, &mut control_flow);
|
handler.handle_event(event);
|
||||||
let (view, screen_frame) = get_view_and_screen_frame(&window);
|
let (view, screen_frame) = get_view_and_screen_frame(&window);
|
||||||
let physical_size = *new_inner_size;
|
let physical_size = *new_inner_size.lock().unwrap();
|
||||||
|
drop(new_inner_size);
|
||||||
let logical_size = physical_size.to_logical(scale_factor);
|
let logical_size = physical_size.to_logical(scale_factor);
|
||||||
let size = CGSize::new(logical_size.width, logical_size.height);
|
let size = CGSize::new(logical_size.width, logical_size.height);
|
||||||
let new_frame: CGRect = CGRect::new(screen_frame.origin, size);
|
let new_frame: CGRect = CGRect::new(screen_frame.origin, size);
|
||||||
view.setFrame(new_frame);
|
view.setFrame(new_frame);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_view_and_screen_frame(window: &WinitUIWindow) -> (Id<UIView, Shared>, CGRect) {
|
fn get_view_and_screen_frame(window: &WinitUIWindow) -> (Id<UIView>, CGRect) {
|
||||||
let view_controller = window.rootViewController().unwrap();
|
let view_controller = window.rootViewController().unwrap();
|
||||||
let view = view_controller.view().unwrap();
|
let view = view_controller.view().unwrap();
|
||||||
let bounds = window.bounds();
|
let bounds = window.bounds();
|
||||||
@@ -924,7 +904,7 @@ macro_rules! os_capabilities {
|
|||||||
|
|
||||||
impl From<NSOperatingSystemVersion> for OSCapabilities {
|
impl From<NSOperatingSystemVersion> for OSCapabilities {
|
||||||
fn from(os_version: NSOperatingSystemVersion) -> OSCapabilities {
|
fn from(os_version: NSOperatingSystemVersion) -> OSCapabilities {
|
||||||
$(let $name = os_version.meets_requirements($major, $minor);)*
|
$(let $name = meets_requirements(os_version, $major, $minor);)*
|
||||||
OSCapabilities { $($name,)* os_version, }
|
OSCapabilities { $($name,)* os_version, }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -934,7 +914,7 @@ macro_rules! os_capabilities {
|
|||||||
pub fn $error_name(&self, extra_msg: &str) {
|
pub fn $error_name(&self, extra_msg: &str) {
|
||||||
log::warn!(
|
log::warn!(
|
||||||
concat!("`", $objc_call, "` requires iOS {}.{}+. This device is running iOS {}.{}.{}. {}"),
|
concat!("`", $objc_call, "` requires iOS {}.{}+. This device is running iOS {}.{}.{}. {}"),
|
||||||
$major, $minor, self.os_version.major, self.os_version.minor, self.os_version.patch,
|
$major, $minor, self.os_version.majorVersion, self.os_version.minorVersion, self.os_version.patchVersion,
|
||||||
extra_msg
|
extra_msg
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -962,16 +942,18 @@ os_capabilities! {
|
|||||||
force_touch: 9-0,
|
force_touch: 9-0,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NSOperatingSystemVersion {
|
fn meets_requirements(
|
||||||
fn meets_requirements(&self, required_major: NSInteger, required_minor: NSInteger) -> bool {
|
version: NSOperatingSystemVersion,
|
||||||
(self.major, self.minor) >= (required_major, required_minor)
|
required_major: NSInteger,
|
||||||
}
|
required_minor: NSInteger,
|
||||||
|
) -> bool {
|
||||||
|
(version.majorVersion, version.minorVersion) >= (required_major, required_minor)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn os_capabilities() -> OSCapabilities {
|
pub fn os_capabilities() -> OSCapabilities {
|
||||||
static OS_CAPABILITIES: Lazy<OSCapabilities> = Lazy::new(|| {
|
static OS_CAPABILITIES: Lazy<OSCapabilities> = Lazy::new(|| {
|
||||||
let version: NSOperatingSystemVersion = unsafe {
|
let version: NSOperatingSystemVersion = unsafe {
|
||||||
let process_info = NSProcessInfo::process_info();
|
let process_info = NSProcessInfo::processInfo();
|
||||||
let atleast_ios_8: bool = msg_send![
|
let atleast_ios_8: bool = msg_send![
|
||||||
&process_info,
|
&process_info,
|
||||||
respondsToSelector: sel!(operatingSystemVersion)
|
respondsToSelector: sel!(operatingSystemVersion)
|
||||||
@@ -984,7 +966,7 @@ pub fn os_capabilities() -> OSCapabilities {
|
|||||||
//
|
//
|
||||||
// The minimum required iOS version is likely to grow in the future.
|
// The minimum required iOS version is likely to grow in the future.
|
||||||
assert!(atleast_ios_8, "`winit` requires iOS version 8 or greater");
|
assert!(atleast_ios_8, "`winit` requires iOS version 8 or greater");
|
||||||
msg_send![&process_info, operatingSystemVersion]
|
process_info.operatingSystemVersion()
|
||||||
};
|
};
|
||||||
version.into()
|
version.into()
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
use std::{
|
use std::{
|
||||||
collections::VecDeque,
|
collections::VecDeque,
|
||||||
ffi::c_void,
|
ffi::c_void,
|
||||||
fmt::{self, Debug},
|
|
||||||
marker::PhantomData,
|
marker::PhantomData,
|
||||||
ptr,
|
ptr,
|
||||||
sync::mpsc::{self, Receiver, Sender},
|
sync::mpsc::{self, Receiver, Sender},
|
||||||
@@ -14,69 +13,131 @@ use core_foundation::runloop::{
|
|||||||
CFRunLoopObserverCreate, CFRunLoopObserverRef, CFRunLoopSourceContext, CFRunLoopSourceCreate,
|
CFRunLoopObserverCreate, CFRunLoopObserverRef, CFRunLoopSourceContext, CFRunLoopSourceCreate,
|
||||||
CFRunLoopSourceInvalidate, CFRunLoopSourceRef, CFRunLoopSourceSignal, CFRunLoopWakeUp,
|
CFRunLoopSourceInvalidate, CFRunLoopSourceRef, CFRunLoopSourceSignal, CFRunLoopWakeUp,
|
||||||
};
|
};
|
||||||
use objc2::foundation::{MainThreadMarker, NSString};
|
use icrate::Foundation::{MainThreadMarker, NSString};
|
||||||
use objc2::rc::{Id, Shared};
|
|
||||||
use objc2::ClassType;
|
use objc2::ClassType;
|
||||||
use raw_window_handle::{RawDisplayHandle, UiKitDisplayHandle};
|
|
||||||
|
|
||||||
use super::uikit::{UIApplication, UIApplicationMain, UIDevice, UIScreen};
|
|
||||||
use super::view::WinitUIWindow;
|
|
||||||
use super::{app_state, monitor, view, MonitorHandle};
|
|
||||||
use crate::{
|
use crate::{
|
||||||
dpi::LogicalSize,
|
error::EventLoopError,
|
||||||
event::Event,
|
event::Event,
|
||||||
event_loop::{
|
event_loop::{
|
||||||
ControlFlow, EventLoopClosed, EventLoopWindowTarget as RootEventLoopWindowTarget,
|
ControlFlow, DeviceEvents, EventLoopClosed,
|
||||||
|
EventLoopWindowTarget as RootEventLoopWindowTarget,
|
||||||
},
|
},
|
||||||
platform::ios::Idiom,
|
platform::ios::Idiom,
|
||||||
|
platform_impl::platform::app_state::{EventLoopHandler, HandlePendingUserEvents},
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::{app_state, monitor, view, MonitorHandle};
|
||||||
|
use super::{
|
||||||
|
app_state::AppState,
|
||||||
|
uikit::{UIApplication, UIApplicationMain, UIDevice, UIScreen},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub(crate) enum EventWrapper {
|
pub struct EventLoopWindowTarget {
|
||||||
StaticEvent(Event<'static, Never>),
|
pub(super) mtm: MainThreadMarker,
|
||||||
EventProxy(EventProxy),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
impl EventLoopWindowTarget {
|
||||||
pub(crate) enum EventProxy {
|
|
||||||
DpiChangedProxy {
|
|
||||||
window: Id<WinitUIWindow, Shared>,
|
|
||||||
suggested_size: LogicalSize<f64>,
|
|
||||||
scale_factor: f64,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct EventLoopWindowTarget<T: 'static> {
|
|
||||||
receiver: Receiver<T>,
|
|
||||||
sender_to_clone: Sender<T>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: 'static> EventLoopWindowTarget<T> {
|
|
||||||
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||||
monitor::uiscreens(MainThreadMarker::new().unwrap())
|
monitor::uiscreens(self.mtm)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||||
Some(MonitorHandle::new(UIScreen::main(
|
Some(MonitorHandle::new(UIScreen::main(self.mtm)))
|
||||||
MainThreadMarker::new().unwrap(),
|
|
||||||
)))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn raw_display_handle(&self) -> RawDisplayHandle {
|
#[inline]
|
||||||
RawDisplayHandle::UiKit(UiKitDisplayHandle::empty())
|
pub fn listen_device_events(&self, _allowed: DeviceEvents) {}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_05")]
|
||||||
|
#[inline]
|
||||||
|
pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
|
||||||
|
rwh_05::RawDisplayHandle::UiKit(rwh_05::UiKitDisplayHandle::empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_06")]
|
||||||
|
#[inline]
|
||||||
|
pub fn raw_display_handle_rwh_06(
|
||||||
|
&self,
|
||||||
|
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
|
||||||
|
Ok(rwh_06::RawDisplayHandle::UiKit(
|
||||||
|
rwh_06::UiKitDisplayHandle::new(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||||
|
AppState::get_mut(self.mtm).set_control_flow(control_flow)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn control_flow(&self) -> ControlFlow {
|
||||||
|
AppState::get_mut(self.mtm).control_flow()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn exit(&self) {
|
||||||
|
// https://developer.apple.com/library/archive/qa/qa1561/_index.html
|
||||||
|
// it is not possible to quit an iOS app gracefully and programatically
|
||||||
|
log::warn!("`ControlFlow::Exit` ignored on iOS");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn exiting(&self) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn owned_display_handle(&self) -> OwnedDisplayHandle {
|
||||||
|
OwnedDisplayHandle
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub(crate) struct OwnedDisplayHandle;
|
||||||
|
|
||||||
|
impl OwnedDisplayHandle {
|
||||||
|
#[cfg(feature = "rwh_05")]
|
||||||
|
#[inline]
|
||||||
|
pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
|
||||||
|
rwh_05::UiKitDisplayHandle::empty().into()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_06")]
|
||||||
|
#[inline]
|
||||||
|
pub fn raw_display_handle_rwh_06(
|
||||||
|
&self,
|
||||||
|
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
|
||||||
|
Ok(rwh_06::UiKitDisplayHandle::new().into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn map_user_event<T: 'static>(
|
||||||
|
mut handler: impl FnMut(Event<T>, &RootEventLoopWindowTarget),
|
||||||
|
receiver: mpsc::Receiver<T>,
|
||||||
|
) -> impl FnMut(Event<HandlePendingUserEvents>, &RootEventLoopWindowTarget) {
|
||||||
|
move |event, window_target| match event.map_nonuser_event() {
|
||||||
|
Ok(event) => (handler)(event, window_target),
|
||||||
|
Err(_) => {
|
||||||
|
for event in receiver.try_iter() {
|
||||||
|
(handler)(Event::UserEvent(event), window_target);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct EventLoop<T: 'static> {
|
pub struct EventLoop<T: 'static> {
|
||||||
window_target: RootEventLoopWindowTarget<T>,
|
mtm: MainThreadMarker,
|
||||||
|
sender: Sender<T>,
|
||||||
|
receiver: Receiver<T>,
|
||||||
|
window_target: RootEventLoopWindowTarget,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||||
pub(crate) struct PlatformSpecificEventLoopAttributes {}
|
pub(crate) struct PlatformSpecificEventLoopAttributes {}
|
||||||
|
|
||||||
impl<T: 'static> EventLoop<T> {
|
impl<T: 'static> EventLoop<T> {
|
||||||
pub(crate) fn new(_: &PlatformSpecificEventLoopAttributes) -> EventLoop<T> {
|
pub(crate) fn new(
|
||||||
assert_main_thread!("`EventLoop` can only be created on the main thread on iOS");
|
_: &PlatformSpecificEventLoopAttributes,
|
||||||
|
) -> Result<EventLoop<T>, EventLoopError> {
|
||||||
|
let mtm = MainThreadMarker::new()
|
||||||
|
.expect("On iOS, `EventLoop` must be created on the main thread");
|
||||||
|
|
||||||
static mut SINGLETON_INIT: bool = false;
|
static mut SINGLETON_INIT: bool = false;
|
||||||
unsafe {
|
unsafe {
|
||||||
@@ -88,57 +149,69 @@ impl<T: 'static> EventLoop<T> {
|
|||||||
SINGLETON_INIT = true;
|
SINGLETON_INIT = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
let (sender_to_clone, receiver) = mpsc::channel();
|
let (sender, receiver) = mpsc::channel();
|
||||||
|
|
||||||
// this line sets up the main run loop before `UIApplicationMain`
|
// this line sets up the main run loop before `UIApplicationMain`
|
||||||
setup_control_flow_observers();
|
setup_control_flow_observers();
|
||||||
|
|
||||||
EventLoop {
|
Ok(EventLoop {
|
||||||
|
mtm,
|
||||||
|
sender,
|
||||||
|
receiver,
|
||||||
window_target: RootEventLoopWindowTarget {
|
window_target: RootEventLoopWindowTarget {
|
||||||
p: EventLoopWindowTarget {
|
p: EventLoopWindowTarget { mtm },
|
||||||
receiver,
|
|
||||||
sender_to_clone,
|
|
||||||
},
|
|
||||||
_marker: PhantomData,
|
_marker: PhantomData,
|
||||||
},
|
},
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn run<F>(self, event_handler: F) -> !
|
pub fn run<F>(self, handler: F) -> !
|
||||||
where
|
where
|
||||||
F: 'static + FnMut(Event<'_, T>, &RootEventLoopWindowTarget<T>, &mut ControlFlow),
|
F: FnMut(Event<T>, &RootEventLoopWindowTarget),
|
||||||
{
|
{
|
||||||
unsafe {
|
let application = UIApplication::shared(self.mtm);
|
||||||
let application = UIApplication::shared(MainThreadMarker::new().unwrap());
|
assert!(
|
||||||
assert!(
|
application.is_none(),
|
||||||
application.is_none(),
|
"\
|
||||||
"\
|
|
||||||
`EventLoop` cannot be `run` after a call to `UIApplicationMain` on iOS\n\
|
`EventLoop` cannot be `run` after a call to `UIApplicationMain` on iOS\n\
|
||||||
Note: `EventLoop::run` calls `UIApplicationMain` on iOS",
|
Note: `EventLoop::run` calls `UIApplicationMain` on iOS",
|
||||||
);
|
);
|
||||||
app_state::will_launch(Box::new(EventLoopHandler {
|
|
||||||
f: event_handler,
|
|
||||||
event_loop: self.window_target,
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Ensure application delegate is initialized
|
let handler = map_user_event(handler, self.receiver);
|
||||||
view::WinitApplicationDelegate::class();
|
|
||||||
|
|
||||||
|
let handler = unsafe {
|
||||||
|
std::mem::transmute::<
|
||||||
|
Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootEventLoopWindowTarget)>,
|
||||||
|
Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootEventLoopWindowTarget)>,
|
||||||
|
>(Box::new(handler))
|
||||||
|
};
|
||||||
|
|
||||||
|
let handler = EventLoopHandler {
|
||||||
|
handler,
|
||||||
|
event_loop: self.window_target,
|
||||||
|
};
|
||||||
|
|
||||||
|
app_state::will_launch(self.mtm, handler);
|
||||||
|
|
||||||
|
// Ensure application delegate is initialized
|
||||||
|
view::WinitApplicationDelegate::class();
|
||||||
|
|
||||||
|
unsafe {
|
||||||
UIApplicationMain(
|
UIApplicationMain(
|
||||||
0,
|
0,
|
||||||
ptr::null(),
|
ptr::null(),
|
||||||
None,
|
None,
|
||||||
Some(&NSString::from_str("WinitApplicationDelegate")),
|
Some(&NSString::from_str("WinitApplicationDelegate")),
|
||||||
);
|
)
|
||||||
unreachable!()
|
};
|
||||||
}
|
unreachable!()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_proxy(&self) -> EventLoopProxy<T> {
|
pub fn create_proxy(&self) -> EventLoopProxy<T> {
|
||||||
EventLoopProxy::new(self.window_target.p.sender_to_clone.clone())
|
EventLoopProxy::new(self.sender.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn window_target(&self) -> &RootEventLoopWindowTarget<T> {
|
pub fn window_target(&self) -> &RootEventLoopWindowTarget {
|
||||||
&self.window_target
|
&self.window_target
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -146,9 +219,7 @@ impl<T: 'static> EventLoop<T> {
|
|||||||
// EventLoopExtIOS
|
// EventLoopExtIOS
|
||||||
impl<T: 'static> EventLoop<T> {
|
impl<T: 'static> EventLoop<T> {
|
||||||
pub fn idiom(&self) -> Idiom {
|
pub fn idiom(&self) -> Idiom {
|
||||||
UIDevice::current(MainThreadMarker::new().unwrap())
|
UIDevice::current(self.mtm).userInterfaceIdiom().into()
|
||||||
.userInterfaceIdiom()
|
|
||||||
.into()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -226,21 +297,20 @@ fn setup_control_flow_observers() {
|
|||||||
activity: CFRunLoopActivity,
|
activity: CFRunLoopActivity,
|
||||||
_: *mut c_void,
|
_: *mut c_void,
|
||||||
) {
|
) {
|
||||||
unsafe {
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
#[allow(non_upper_case_globals)]
|
#[allow(non_upper_case_globals)]
|
||||||
match activity {
|
match activity {
|
||||||
kCFRunLoopAfterWaiting => app_state::handle_wakeup_transition(),
|
kCFRunLoopAfterWaiting => app_state::handle_wakeup_transition(mtm),
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Core Animation registers its `CFRunLoopObserver` that performs drawing operations in
|
// Core Animation registers its `CFRunLoopObserver` that performs drawing operations in
|
||||||
// `CA::Transaction::ensure_implicit` with a priority of `0x1e8480`. We set the main_end
|
// `CA::Transaction::ensure_implicit` with a priority of `0x1e8480`. We set the main_end
|
||||||
// priority to be 0, in order to send MainEventsCleared before RedrawRequested. This value was
|
// 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
|
// 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
|
// 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 `MainEventsCleared`.
|
// 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
|
// 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.
|
// registers for every `CFRunLoopAddObserver` call on an iPad Air 2 running iOS 11.4.
|
||||||
@@ -251,13 +321,12 @@ fn setup_control_flow_observers() {
|
|||||||
activity: CFRunLoopActivity,
|
activity: CFRunLoopActivity,
|
||||||
_: *mut c_void,
|
_: *mut c_void,
|
||||||
) {
|
) {
|
||||||
unsafe {
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
#[allow(non_upper_case_globals)]
|
#[allow(non_upper_case_globals)]
|
||||||
match activity {
|
match activity {
|
||||||
kCFRunLoopBeforeWaiting => app_state::handle_main_events_cleared(),
|
kCFRunLoopBeforeWaiting => app_state::handle_main_events_cleared(mtm),
|
||||||
kCFRunLoopExit => unimplemented!(), // not expected to ever happen
|
kCFRunLoopExit => {} // may happen when running on macOS
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -267,13 +336,12 @@ fn setup_control_flow_observers() {
|
|||||||
activity: CFRunLoopActivity,
|
activity: CFRunLoopActivity,
|
||||||
_: *mut c_void,
|
_: *mut c_void,
|
||||||
) {
|
) {
|
||||||
unsafe {
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
#[allow(non_upper_case_globals)]
|
#[allow(non_upper_case_globals)]
|
||||||
match activity {
|
match activity {
|
||||||
kCFRunLoopBeforeWaiting => app_state::handle_events_cleared(),
|
kCFRunLoopBeforeWaiting => app_state::handle_events_cleared(mtm),
|
||||||
kCFRunLoopExit => unimplemented!(), // not expected to ever happen
|
kCFRunLoopExit => {} // may happen when running on macOS
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -310,44 +378,3 @@ fn setup_control_flow_observers() {
|
|||||||
CFRunLoopAddObserver(main_loop, end_observer, kCFRunLoopDefaultMode);
|
CFRunLoopAddObserver(main_loop, end_observer, kCFRunLoopDefaultMode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum Never {}
|
|
||||||
|
|
||||||
pub trait EventHandler: Debug {
|
|
||||||
fn handle_nonuser_event(&mut self, event: Event<'_, Never>, control_flow: &mut ControlFlow);
|
|
||||||
fn handle_user_events(&mut self, control_flow: &mut ControlFlow);
|
|
||||||
}
|
|
||||||
|
|
||||||
struct EventLoopHandler<F, T: 'static> {
|
|
||||||
f: F,
|
|
||||||
event_loop: RootEventLoopWindowTarget<T>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<F, T: 'static> Debug for EventLoopHandler<F, T> {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.debug_struct("EventLoopHandler")
|
|
||||||
.field("event_loop", &self.event_loop)
|
|
||||||
.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<F, T> EventHandler for EventLoopHandler<F, T>
|
|
||||||
where
|
|
||||||
F: 'static + FnMut(Event<'_, T>, &RootEventLoopWindowTarget<T>, &mut ControlFlow),
|
|
||||||
T: 'static,
|
|
||||||
{
|
|
||||||
fn handle_nonuser_event(&mut self, event: Event<'_, Never>, control_flow: &mut ControlFlow) {
|
|
||||||
(self.f)(
|
|
||||||
event.map_nonuser_event().unwrap(),
|
|
||||||
&self.event_loop,
|
|
||||||
control_flow,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn handle_user_events(&mut self, control_flow: &mut ControlFlow) {
|
|
||||||
for event in self.event_loop.p.receiver.try_iter() {
|
|
||||||
(self.f)(Event::UserEvent(event), &self.event_loop, control_flow);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,30 +2,11 @@
|
|||||||
|
|
||||||
use std::convert::TryInto;
|
use std::convert::TryInto;
|
||||||
|
|
||||||
|
use icrate::Foundation::{NSInteger, NSUInteger};
|
||||||
use objc2::encode::{Encode, Encoding};
|
use objc2::encode::{Encode, Encoding};
|
||||||
use objc2::foundation::{NSInteger, NSUInteger};
|
|
||||||
|
|
||||||
use crate::platform::ios::{Idiom, ScreenEdge};
|
use crate::platform::ios::{Idiom, ScreenEdge};
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct NSOperatingSystemVersion {
|
|
||||||
pub major: NSInteger,
|
|
||||||
pub minor: NSInteger,
|
|
||||||
pub patch: NSInteger,
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe impl Encode for NSOperatingSystemVersion {
|
|
||||||
const ENCODING: Encoding = Encoding::Struct(
|
|
||||||
"NSOperatingSystemVersion",
|
|
||||||
&[
|
|
||||||
NSInteger::ENCODING,
|
|
||||||
NSInteger::ENCODING,
|
|
||||||
NSInteger::ENCODING,
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[repr(transparent)]
|
#[repr(transparent)]
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
pub struct UIUserInterfaceIdiom(NSInteger);
|
pub struct UIUserInterfaceIdiom(NSInteger);
|
||||||
@@ -70,6 +51,10 @@ impl From<UIUserInterfaceIdiom> for Idiom {
|
|||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
pub struct UIRectEdge(NSUInteger);
|
pub struct UIRectEdge(NSUInteger);
|
||||||
|
|
||||||
|
impl UIRectEdge {
|
||||||
|
pub(crate) const NONE: Self = Self(0);
|
||||||
|
}
|
||||||
|
|
||||||
unsafe impl Encode for UIRectEdge {
|
unsafe impl Encode for UIRectEdge {
|
||||||
const ENCODING: Encoding = NSUInteger::ENCODING;
|
const ENCODING: Encoding = NSUInteger::ENCODING;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,27 +48,16 @@
|
|||||||
//!
|
//!
|
||||||
//! - applicationDidBecomeActive is Resumed
|
//! - applicationDidBecomeActive is Resumed
|
||||||
//! - applicationWillResignActive is Suspended
|
//! - applicationWillResignActive is Suspended
|
||||||
//! - applicationWillTerminate is LoopDestroyed
|
//! - applicationWillTerminate is LoopExiting
|
||||||
//!
|
//!
|
||||||
//! Keep in mind that after LoopDestroyed event is received every attempt to draw with
|
//! Keep in mind that after LoopExiting event is received every attempt to draw with
|
||||||
//! opengl will result in segfault.
|
//! opengl will result in segfault.
|
||||||
//!
|
//!
|
||||||
//! Also note that app may not receive the LoopDestroyed 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.
|
||||||
|
|
||||||
#![cfg(ios_platform)]
|
#![cfg(ios_platform)]
|
||||||
#![allow(clippy::let_unit_value)]
|
#![allow(clippy::let_unit_value)]
|
||||||
|
|
||||||
// TODO: (mtak-) UIKit requires main thread for virtually all function/method calls. This could be
|
|
||||||
// worked around in the future by using GCD (grand central dispatch) and/or caching of values like
|
|
||||||
// window size/position.
|
|
||||||
macro_rules! assert_main_thread {
|
|
||||||
($($t:tt)*) => {
|
|
||||||
if !::objc2::foundation::is_main_thread() {
|
|
||||||
panic!($($t)*);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
mod app_state;
|
mod app_state;
|
||||||
mod event_loop;
|
mod event_loop;
|
||||||
mod ffi;
|
mod ffi;
|
||||||
@@ -79,33 +68,38 @@ mod window;
|
|||||||
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
|
use crate::event::DeviceId as RootDeviceId;
|
||||||
|
|
||||||
pub(crate) use self::{
|
pub(crate) use self::{
|
||||||
event_loop::{
|
event_loop::{
|
||||||
EventLoop, EventLoopProxy, EventLoopWindowTarget, PlatformSpecificEventLoopAttributes,
|
EventLoop, EventLoopProxy, EventLoopWindowTarget, OwnedDisplayHandle,
|
||||||
|
PlatformSpecificEventLoopAttributes,
|
||||||
},
|
},
|
||||||
monitor::{MonitorHandle, VideoMode},
|
monitor::{MonitorHandle, VideoModeHandle},
|
||||||
window::{PlatformSpecificWindowBuilderAttributes, Window, WindowId},
|
window::{PlatformSpecificWindowBuilderAttributes, Window, WindowId},
|
||||||
};
|
};
|
||||||
|
pub(crate) use crate::cursor::NoCustomCursor as PlatformCustomCursor;
|
||||||
use self::uikit::UIScreen;
|
pub(crate) use crate::cursor::NoCustomCursor as PlatformCustomCursorBuilder;
|
||||||
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
||||||
pub(self) use crate::platform_impl::Fullscreen;
|
pub(crate) use crate::platform_impl::Fullscreen;
|
||||||
|
|
||||||
|
/// There is no way to detect which device that performed a certain event in
|
||||||
|
/// UIKit (i.e. you can't differentiate between different external keyboards,
|
||||||
|
/// or wether it was the main touchscreen, assistive technologies, or some
|
||||||
|
/// other pointer device that caused a touch event).
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
pub struct DeviceId {
|
pub struct DeviceId;
|
||||||
uiscreen: *const UIScreen,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DeviceId {
|
impl DeviceId {
|
||||||
pub const unsafe fn dummy() -> Self {
|
pub const unsafe fn dummy() -> Self {
|
||||||
DeviceId {
|
DeviceId
|
||||||
uiscreen: std::ptr::null(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe impl Send for DeviceId {}
|
pub(crate) const DEVICE_ID: RootDeviceId = RootDeviceId(DeviceId);
|
||||||
unsafe impl Sync for DeviceId {}
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub struct KeyEventExtra {}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum OsError {}
|
pub enum OsError {}
|
||||||
|
|||||||
@@ -2,46 +2,73 @@
|
|||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
collections::{BTreeSet, VecDeque},
|
collections::{BTreeSet, VecDeque},
|
||||||
fmt,
|
fmt, hash, ptr,
|
||||||
ops::{Deref, DerefMut},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use objc2::foundation::{MainThreadMarker, NSInteger};
|
use icrate::Foundation::{MainThreadBound, MainThreadMarker, NSInteger};
|
||||||
use objc2::rc::{Id, Shared};
|
use objc2::mutability::IsRetainable;
|
||||||
|
use objc2::rc::Id;
|
||||||
|
use objc2::Message;
|
||||||
|
|
||||||
use super::uikit::{UIScreen, UIScreenMode};
|
use super::uikit::{UIScreen, UIScreenMode};
|
||||||
use crate::{
|
use crate::{
|
||||||
dpi::{PhysicalPosition, PhysicalSize},
|
dpi::{PhysicalPosition, PhysicalSize},
|
||||||
monitor::VideoMode as RootVideoMode,
|
monitor::VideoModeHandle as RootVideoModeHandle,
|
||||||
platform_impl::platform::app_state,
|
platform_impl::platform::app_state,
|
||||||
};
|
};
|
||||||
|
|
||||||
// TODO(madsmtm): Remove or refactor this
|
// Workaround for `MainThreadBound` implementing almost no traits
|
||||||
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
|
#[derive(Debug)]
|
||||||
pub(crate) struct ScreenModeSendSync(pub(crate) Id<UIScreenMode, Shared>);
|
struct MainThreadBoundDelegateImpls<T>(MainThreadBound<Id<T>>);
|
||||||
|
|
||||||
unsafe impl Send for ScreenModeSendSync {}
|
impl<T: IsRetainable + Message> Clone for MainThreadBoundDelegateImpls<T> {
|
||||||
unsafe impl Sync for ScreenModeSendSync {}
|
fn clone(&self) -> Self {
|
||||||
|
Self(MainThreadMarker::run_on_main(|mtm| {
|
||||||
|
MainThreadBound::new(Id::clone(self.0.get(mtm)), mtm)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: IsRetainable + Message> hash::Hash for MainThreadBoundDelegateImpls<T> {
|
||||||
|
fn hash<H: hash::Hasher>(&self, state: &mut H) {
|
||||||
|
// SAFETY: Marker only used to get the pointer
|
||||||
|
let mtm = unsafe { MainThreadMarker::new_unchecked() };
|
||||||
|
Id::as_ptr(self.0.get(mtm)).hash(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: IsRetainable + Message> PartialEq for MainThreadBoundDelegateImpls<T> {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
// SAFETY: Marker only used to get the pointer
|
||||||
|
let mtm = unsafe { MainThreadMarker::new_unchecked() };
|
||||||
|
Id::as_ptr(self.0.get(mtm)) == Id::as_ptr(other.0.get(mtm))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: IsRetainable + Message> Eq for MainThreadBoundDelegateImpls<T> {}
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
|
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
|
||||||
pub struct VideoMode {
|
pub struct VideoModeHandle {
|
||||||
pub(crate) size: (u32, u32),
|
pub(crate) size: (u32, u32),
|
||||||
pub(crate) bit_depth: u16,
|
pub(crate) bit_depth: u16,
|
||||||
pub(crate) refresh_rate_millihertz: u32,
|
pub(crate) refresh_rate_millihertz: u32,
|
||||||
pub(crate) screen_mode: ScreenModeSendSync,
|
screen_mode: MainThreadBoundDelegateImpls<UIScreenMode>,
|
||||||
pub(crate) monitor: MonitorHandle,
|
pub(crate) monitor: MonitorHandle,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl VideoMode {
|
impl VideoModeHandle {
|
||||||
fn new(uiscreen: Id<UIScreen, Shared>, screen_mode: Id<UIScreenMode, Shared>) -> VideoMode {
|
fn new(
|
||||||
assert_main_thread!("`VideoMode` can only be created on the main thread on iOS");
|
uiscreen: Id<UIScreen>,
|
||||||
|
screen_mode: Id<UIScreenMode>,
|
||||||
|
mtm: MainThreadMarker,
|
||||||
|
) -> 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();
|
||||||
VideoMode {
|
VideoModeHandle {
|
||||||
size: (size.width as u32, size.height as u32),
|
size: (size.width as u32, size.height as u32),
|
||||||
bit_depth: 32,
|
bit_depth: 32,
|
||||||
refresh_rate_millihertz,
|
refresh_rate_millihertz,
|
||||||
screen_mode: ScreenModeSendSync(screen_mode),
|
screen_mode: MainThreadBoundDelegateImpls(MainThreadBound::new(screen_mode, mtm)),
|
||||||
monitor: MonitorHandle::new(uiscreen),
|
monitor: MonitorHandle::new(uiscreen),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -61,18 +88,38 @@ impl VideoMode {
|
|||||||
pub fn monitor(&self) -> MonitorHandle {
|
pub fn monitor(&self) -> MonitorHandle {
|
||||||
self.monitor.clone()
|
self.monitor.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) fn screen_mode(&self, mtm: MainThreadMarker) -> &Id<UIScreenMode> {
|
||||||
|
self.screen_mode.0.get(mtm)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
|
||||||
pub struct Inner {
|
|
||||||
uiscreen: Id<UIScreen, Shared>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
|
||||||
pub struct MonitorHandle {
|
pub struct MonitorHandle {
|
||||||
inner: Inner,
|
ui_screen: MainThreadBound<Id<UIScreen>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Clone for MonitorHandle {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
MainThreadMarker::run_on_main(|mtm| Self {
|
||||||
|
ui_screen: MainThreadBound::new(self.ui_screen.get(mtm).clone(), mtm),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl hash::Hash for MonitorHandle {
|
||||||
|
fn hash<H: hash::Hasher>(&self, state: &mut H) {
|
||||||
|
(self as *const Self).hash(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for MonitorHandle {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
ptr::eq(self, other)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Eq for MonitorHandle {}
|
||||||
|
|
||||||
impl PartialOrd for MonitorHandle {
|
impl PartialOrd for MonitorHandle {
|
||||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||||
Some(self.cmp(other))
|
Some(self.cmp(other))
|
||||||
@@ -86,113 +133,98 @@ impl Ord for MonitorHandle {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Deref for MonitorHandle {
|
|
||||||
type Target = Inner;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Inner {
|
|
||||||
assert_main_thread!("`MonitorHandle` methods can only be run on the main thread on iOS");
|
|
||||||
&self.inner
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DerefMut for MonitorHandle {
|
|
||||||
fn deref_mut(&mut self) -> &mut Inner {
|
|
||||||
assert_main_thread!("`MonitorHandle` methods can only be run on the main thread on iOS");
|
|
||||||
&mut self.inner
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe impl Send for MonitorHandle {}
|
|
||||||
unsafe impl Sync for MonitorHandle {}
|
|
||||||
|
|
||||||
impl Drop for MonitorHandle {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
assert_main_thread!("`MonitorHandle` can only be dropped on the main thread on iOS");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Debug for MonitorHandle {
|
impl fmt::Debug for MonitorHandle {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
// TODO: Do this using the proper fmt API
|
f.debug_struct("MonitorHandle")
|
||||||
#[derive(Debug)]
|
.field("name", &self.name())
|
||||||
#[allow(dead_code)]
|
.field("size", &self.size())
|
||||||
struct MonitorHandle {
|
.field("position", &self.position())
|
||||||
name: Option<String>,
|
.field("scale_factor", &self.scale_factor())
|
||||||
size: PhysicalSize<u32>,
|
.field("refresh_rate_millihertz", &self.refresh_rate_millihertz())
|
||||||
position: PhysicalPosition<i32>,
|
.finish_non_exhaustive()
|
||||||
scale_factor: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
let monitor_id_proxy = MonitorHandle {
|
|
||||||
name: self.name(),
|
|
||||||
size: self.size(),
|
|
||||||
position: self.position(),
|
|
||||||
scale_factor: self.scale_factor(),
|
|
||||||
};
|
|
||||||
|
|
||||||
monitor_id_proxy.fmt(f)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MonitorHandle {
|
impl MonitorHandle {
|
||||||
pub(crate) fn new(uiscreen: Id<UIScreen, Shared>) -> Self {
|
pub(crate) fn new(ui_screen: Id<UIScreen>) -> Self {
|
||||||
assert_main_thread!("`MonitorHandle` can only be created on the main thread on iOS");
|
// Holding `Id<UIScreen>` implies we're on the main thread.
|
||||||
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
Self {
|
Self {
|
||||||
inner: Inner { uiscreen },
|
ui_screen: MainThreadBound::new(ui_screen, mtm),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl Inner {
|
|
||||||
pub fn name(&self) -> Option<String> {
|
pub fn name(&self) -> Option<String> {
|
||||||
let main = UIScreen::main(MainThreadMarker::new().unwrap());
|
MainThreadMarker::run_on_main(|mtm| {
|
||||||
if self.uiscreen == main {
|
let main = UIScreen::main(mtm);
|
||||||
Some("Primary".to_string())
|
if *self.ui_screen(mtm) == main {
|
||||||
} else if self.uiscreen == main.mirroredScreen() {
|
Some("Primary".to_string())
|
||||||
Some("Mirrored".to_string())
|
} else if *self.ui_screen(mtm) == main.mirroredScreen() {
|
||||||
} else {
|
Some("Mirrored".to_string())
|
||||||
UIScreen::screens(MainThreadMarker::new().unwrap())
|
} else {
|
||||||
.iter()
|
UIScreen::screens(mtm)
|
||||||
.position(|rhs| rhs == &*self.uiscreen)
|
.iter()
|
||||||
.map(|idx| idx.to_string())
|
.position(|rhs| rhs == &**self.ui_screen(mtm))
|
||||||
}
|
.map(|idx| idx.to_string())
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn size(&self) -> PhysicalSize<u32> {
|
pub fn size(&self) -> PhysicalSize<u32> {
|
||||||
let bounds = self.uiscreen.nativeBounds();
|
let bounds = self
|
||||||
|
.ui_screen
|
||||||
|
.get_on_main(|ui_screen| ui_screen.nativeBounds());
|
||||||
PhysicalSize::new(bounds.size.width as u32, bounds.size.height as u32)
|
PhysicalSize::new(bounds.size.width as u32, bounds.size.height as u32)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn position(&self) -> PhysicalPosition<i32> {
|
pub fn position(&self) -> PhysicalPosition<i32> {
|
||||||
let bounds = self.uiscreen.nativeBounds();
|
let bounds = self
|
||||||
|
.ui_screen
|
||||||
|
.get_on_main(|ui_screen| ui_screen.nativeBounds());
|
||||||
(bounds.origin.x as f64, bounds.origin.y as f64).into()
|
(bounds.origin.x as f64, bounds.origin.y as f64).into()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn scale_factor(&self) -> f64 {
|
pub fn scale_factor(&self) -> f64 {
|
||||||
self.uiscreen.nativeScale() as f64
|
self.ui_screen
|
||||||
|
.get_on_main(|ui_screen| ui_screen.nativeScale()) as f64
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn refresh_rate_millihertz(&self) -> Option<u32> {
|
pub fn refresh_rate_millihertz(&self) -> Option<u32> {
|
||||||
Some(refresh_rate_millihertz(&self.uiscreen))
|
Some(
|
||||||
|
self.ui_screen
|
||||||
|
.get_on_main(|ui_screen| refresh_rate_millihertz(ui_screen)),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn video_modes(&self) -> impl Iterator<Item = VideoMode> {
|
pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> {
|
||||||
// Use Ord impl of RootVideoMode
|
MainThreadMarker::run_on_main(|mtm| {
|
||||||
let modes: BTreeSet<_> = self
|
let ui_screen = self.ui_screen(mtm);
|
||||||
.uiscreen
|
// Use Ord impl of RootVideoModeHandle
|
||||||
.availableModes()
|
|
||||||
.into_iter()
|
|
||||||
.map(|mode| {
|
|
||||||
let mode: *const UIScreenMode = mode;
|
|
||||||
let mode = unsafe { Id::retain(mode as *mut UIScreenMode).unwrap() };
|
|
||||||
|
|
||||||
RootVideoMode {
|
let modes: BTreeSet<_> = ui_screen
|
||||||
video_mode: VideoMode::new(self.uiscreen.clone(), mode),
|
.availableModes()
|
||||||
}
|
.into_iter()
|
||||||
})
|
.map(|mode| RootVideoModeHandle {
|
||||||
.collect();
|
video_mode: VideoModeHandle::new(ui_screen.clone(), mode, mtm),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
modes.into_iter().map(|mode| mode.video_mode)
|
modes.into_iter().map(|mode| mode.video_mode)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn ui_screen(&self, mtm: MainThreadMarker) -> &Id<UIScreen> {
|
||||||
|
self.ui_screen.get(mtm)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn preferred_video_mode(&self) -> VideoModeHandle {
|
||||||
|
MainThreadMarker::run_on_main(|mtm| {
|
||||||
|
VideoModeHandle::new(
|
||||||
|
self.ui_screen(mtm).clone(),
|
||||||
|
self.ui_screen(mtm).preferredMode().unwrap(),
|
||||||
|
mtm,
|
||||||
|
)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -220,27 +252,9 @@ fn refresh_rate_millihertz(uiscreen: &UIScreen) -> u32 {
|
|||||||
refresh_rate_millihertz as u32 * 1000
|
refresh_rate_millihertz as u32 * 1000
|
||||||
}
|
}
|
||||||
|
|
||||||
// MonitorHandleExtIOS
|
|
||||||
impl Inner {
|
|
||||||
pub(crate) fn ui_screen(&self) -> &Id<UIScreen, Shared> {
|
|
||||||
&self.uiscreen
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn preferred_video_mode(&self) -> VideoMode {
|
|
||||||
VideoMode::new(
|
|
||||||
self.uiscreen.clone(),
|
|
||||||
self.uiscreen.preferredMode().unwrap(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn uiscreens(mtm: MainThreadMarker) -> VecDeque<MonitorHandle> {
|
pub fn uiscreens(mtm: MainThreadMarker) -> VecDeque<MonitorHandle> {
|
||||||
UIScreen::screens(mtm)
|
UIScreen::screens(mtm)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|screen| {
|
.map(MonitorHandle::new)
|
||||||
let screen: *const UIScreen = screen;
|
|
||||||
let screen = unsafe { Id::retain(screen as *mut UIScreen).unwrap() };
|
|
||||||
MonitorHandle::new(screen)
|
|
||||||
})
|
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use objc2::foundation::{CGRect, MainThreadMarker, NSArray, NSObject};
|
use icrate::Foundation::{CGRect, MainThreadMarker, NSArray, NSObject};
|
||||||
use objc2::rc::{Id, Shared};
|
use objc2::rc::Id;
|
||||||
use objc2::{extern_class, extern_methods, msg_send_id, ClassType};
|
use objc2::{extern_class, extern_methods, msg_send_id, mutability, ClassType};
|
||||||
|
|
||||||
use super::{UIResponder, UIWindow};
|
use super::{UIResponder, UIWindow};
|
||||||
|
|
||||||
@@ -11,20 +11,21 @@ extern_class!(
|
|||||||
unsafe impl ClassType for UIApplication {
|
unsafe impl ClassType for UIApplication {
|
||||||
#[inherits(NSObject)]
|
#[inherits(NSObject)]
|
||||||
type Super = UIResponder;
|
type Super = UIResponder;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
extern_methods!(
|
extern_methods!(
|
||||||
unsafe impl UIApplication {
|
unsafe impl UIApplication {
|
||||||
pub fn shared(_mtm: MainThreadMarker) -> Option<Id<Self, Shared>> {
|
pub fn shared(_mtm: MainThreadMarker) -> Option<Id<Self>> {
|
||||||
unsafe { msg_send_id![Self::class(), sharedApplication] }
|
unsafe { msg_send_id![Self::class(), sharedApplication] }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn windows(&self) -> Id<NSArray<UIWindow, Shared>, Shared> {
|
pub fn windows(&self) -> Id<NSArray<UIWindow>> {
|
||||||
unsafe { msg_send_id![self, windows] }
|
unsafe { msg_send_id![self, windows] }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[sel(statusBarFrame)]
|
#[method(statusBarFrame)]
|
||||||
pub fn statusBarFrame(&self) -> CGRect;
|
pub fn statusBarFrame(&self) -> CGRect;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use objc2::foundation::NSObject;
|
use icrate::Foundation::NSObject;
|
||||||
use objc2::{extern_class, ClassType};
|
use objc2::{extern_class, mutability, ClassType};
|
||||||
|
|
||||||
extern_class!(
|
extern_class!(
|
||||||
#[derive(Debug, PartialEq, Eq, Hash)]
|
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||||
@@ -7,5 +7,6 @@ extern_class!(
|
|||||||
|
|
||||||
unsafe impl ClassType for UICoordinateSpace {
|
unsafe impl ClassType for UICoordinateSpace {
|
||||||
type Super = NSObject;
|
type Super = NSObject;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use objc2::foundation::{MainThreadMarker, NSObject};
|
use icrate::Foundation::{MainThreadMarker, NSObject};
|
||||||
use objc2::rc::{Id, Shared};
|
use objc2::rc::Id;
|
||||||
use objc2::{extern_class, extern_methods, msg_send_id, ClassType};
|
use objc2::{extern_class, extern_methods, msg_send_id, mutability, ClassType};
|
||||||
|
|
||||||
use super::super::ffi::UIUserInterfaceIdiom;
|
use super::super::ffi::UIUserInterfaceIdiom;
|
||||||
|
|
||||||
@@ -10,16 +10,17 @@ extern_class!(
|
|||||||
|
|
||||||
unsafe impl ClassType for UIDevice {
|
unsafe impl ClassType for UIDevice {
|
||||||
type Super = NSObject;
|
type Super = NSObject;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
extern_methods!(
|
extern_methods!(
|
||||||
unsafe impl UIDevice {
|
unsafe impl UIDevice {
|
||||||
pub fn current(_mtm: MainThreadMarker) -> Id<Self, Shared> {
|
pub fn current(_mtm: MainThreadMarker) -> Id<Self> {
|
||||||
unsafe { msg_send_id![Self::class(), currentDevice] }
|
unsafe { msg_send_id![Self::class(), currentDevice] }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[sel(userInterfaceIdiom)]
|
#[method(userInterfaceIdiom)]
|
||||||
pub fn userInterfaceIdiom(&self) -> UIUserInterfaceIdiom;
|
pub fn userInterfaceIdiom(&self) -> UIUserInterfaceIdiom;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use objc2::foundation::NSObject;
|
use icrate::Foundation::NSObject;
|
||||||
use objc2::{extern_class, ClassType};
|
use objc2::{extern_class, mutability, ClassType};
|
||||||
|
|
||||||
extern_class!(
|
extern_class!(
|
||||||
#[derive(Debug, PartialEq, Eq, Hash)]
|
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||||
@@ -7,5 +7,6 @@ extern_class!(
|
|||||||
|
|
||||||
unsafe impl ClassType for UIEvent {
|
unsafe impl ClassType for UIEvent {
|
||||||
type Super = NSObject;
|
type Super = NSObject;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|||||||
121
src/platform_impl/ios/uikit/gesture_recognizer.rs
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
use icrate::Foundation::{CGFloat, NSInteger, NSObject, NSUInteger};
|
||||||
|
use objc2::{
|
||||||
|
encode::{Encode, Encoding},
|
||||||
|
extern_class, extern_methods, mutability, ClassType,
|
||||||
|
};
|
||||||
|
|
||||||
|
// https://developer.apple.com/documentation/uikit/uigesturerecognizer
|
||||||
|
extern_class!(
|
||||||
|
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub(crate) struct UIGestureRecognizer;
|
||||||
|
|
||||||
|
unsafe impl ClassType for UIGestureRecognizer {
|
||||||
|
type Super = NSObject;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
extern_methods!(
|
||||||
|
unsafe impl UIGestureRecognizer {
|
||||||
|
#[method(state)]
|
||||||
|
pub fn state(&self) -> UIGestureRecognizerState;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
unsafe impl Encode for UIGestureRecognizer {
|
||||||
|
const ENCODING: Encoding = Encoding::Object;
|
||||||
|
}
|
||||||
|
|
||||||
|
// https://developer.apple.com/documentation/uikit/uigesturerecognizer/state
|
||||||
|
#[repr(transparent)]
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct UIGestureRecognizerState(NSInteger);
|
||||||
|
|
||||||
|
unsafe impl Encode for UIGestureRecognizerState {
|
||||||
|
const ENCODING: Encoding = NSInteger::ENCODING;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl UIGestureRecognizerState {
|
||||||
|
pub const Possible: Self = Self(0);
|
||||||
|
pub const Began: Self = Self(1);
|
||||||
|
pub const Changed: Self = Self(2);
|
||||||
|
pub const Ended: Self = Self(3);
|
||||||
|
pub const Cancelled: Self = Self(4);
|
||||||
|
pub const Failed: Self = Self(5);
|
||||||
|
}
|
||||||
|
|
||||||
|
// https://developer.apple.com/documentation/uikit/uipinchgesturerecognizer
|
||||||
|
extern_class!(
|
||||||
|
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub(crate) struct UIPinchGestureRecognizer;
|
||||||
|
|
||||||
|
unsafe impl ClassType for UIPinchGestureRecognizer {
|
||||||
|
type Super = UIGestureRecognizer;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
extern_methods!(
|
||||||
|
unsafe impl UIPinchGestureRecognizer {
|
||||||
|
#[method(scale)]
|
||||||
|
pub fn scale(&self) -> CGFloat;
|
||||||
|
|
||||||
|
#[method(velocity)]
|
||||||
|
pub fn velocity(&self) -> CGFloat;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
unsafe impl Encode for UIPinchGestureRecognizer {
|
||||||
|
const ENCODING: Encoding = Encoding::Object;
|
||||||
|
}
|
||||||
|
|
||||||
|
// https://developer.apple.com/documentation/uikit/uirotationgesturerecognizer
|
||||||
|
extern_class!(
|
||||||
|
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub(crate) struct UIRotationGestureRecognizer;
|
||||||
|
|
||||||
|
unsafe impl ClassType for UIRotationGestureRecognizer {
|
||||||
|
type Super = UIGestureRecognizer;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
extern_methods!(
|
||||||
|
unsafe impl UIRotationGestureRecognizer {
|
||||||
|
#[method(rotation)]
|
||||||
|
pub fn rotation(&self) -> CGFloat;
|
||||||
|
|
||||||
|
#[method(velocity)]
|
||||||
|
pub fn velocity(&self) -> CGFloat;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
unsafe impl Encode for UIRotationGestureRecognizer {
|
||||||
|
const ENCODING: Encoding = Encoding::Object;
|
||||||
|
}
|
||||||
|
|
||||||
|
// https://developer.apple.com/documentation/uikit/uitapgesturerecognizer
|
||||||
|
extern_class!(
|
||||||
|
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub(crate) struct UITapGestureRecognizer;
|
||||||
|
|
||||||
|
unsafe impl ClassType for UITapGestureRecognizer {
|
||||||
|
type Super = UIGestureRecognizer;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
extern_methods!(
|
||||||
|
unsafe impl UITapGestureRecognizer {
|
||||||
|
#[method(setNumberOfTapsRequired:)]
|
||||||
|
pub fn setNumberOfTapsRequired(&self, number_of_taps_required: NSUInteger);
|
||||||
|
|
||||||
|
#[method(setNumberOfTouchesRequired:)]
|
||||||
|
pub fn setNumberOfTouchesRequired(&self, number_of_touches_required: NSUInteger);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
unsafe impl Encode for UITapGestureRecognizer {
|
||||||
|
const ENCODING: Encoding = Encoding::Object;
|
||||||
|
}
|
||||||
@@ -1,18 +1,19 @@
|
|||||||
#![deny(unsafe_op_in_unsafe_fn)]
|
|
||||||
#![allow(non_snake_case)]
|
#![allow(non_snake_case)]
|
||||||
#![allow(non_upper_case_globals)]
|
#![allow(non_upper_case_globals)]
|
||||||
|
|
||||||
use std::os::raw::{c_char, c_int};
|
use std::os::raw::{c_char, c_int};
|
||||||
|
|
||||||
use objc2::foundation::NSString;
|
use icrate::Foundation::NSString;
|
||||||
|
|
||||||
mod application;
|
mod application;
|
||||||
mod coordinate_space;
|
mod coordinate_space;
|
||||||
mod device;
|
mod device;
|
||||||
mod event;
|
mod event;
|
||||||
|
mod gesture_recognizer;
|
||||||
mod responder;
|
mod responder;
|
||||||
mod screen;
|
mod screen;
|
||||||
mod screen_mode;
|
mod screen_mode;
|
||||||
|
mod status_bar_style;
|
||||||
mod touch;
|
mod touch;
|
||||||
mod trait_collection;
|
mod trait_collection;
|
||||||
mod view;
|
mod view;
|
||||||
@@ -23,9 +24,14 @@ pub(crate) use self::application::UIApplication;
|
|||||||
pub(crate) use self::coordinate_space::UICoordinateSpace;
|
pub(crate) use self::coordinate_space::UICoordinateSpace;
|
||||||
pub(crate) use self::device::UIDevice;
|
pub(crate) use self::device::UIDevice;
|
||||||
pub(crate) use self::event::UIEvent;
|
pub(crate) use self::event::UIEvent;
|
||||||
|
pub(crate) use self::gesture_recognizer::{
|
||||||
|
UIGestureRecognizer, UIGestureRecognizerState, UIPinchGestureRecognizer,
|
||||||
|
UIRotationGestureRecognizer, UITapGestureRecognizer,
|
||||||
|
};
|
||||||
pub(crate) use self::responder::UIResponder;
|
pub(crate) use self::responder::UIResponder;
|
||||||
pub(crate) use self::screen::{UIScreen, UIScreenOverscanCompensation};
|
pub(crate) use self::screen::{UIScreen, UIScreenOverscanCompensation};
|
||||||
pub(crate) use self::screen_mode::UIScreenMode;
|
pub(crate) use self::screen_mode::UIScreenMode;
|
||||||
|
pub(crate) use self::status_bar_style::UIStatusBarStyle;
|
||||||
pub(crate) use self::touch::{UITouch, UITouchPhase, UITouchType};
|
pub(crate) use self::touch::{UITouch, UITouchPhase, UITouchType};
|
||||||
pub(crate) use self::trait_collection::{UIForceTouchCapability, UITraitCollection};
|
pub(crate) use self::trait_collection::{UIForceTouchCapability, UITraitCollection};
|
||||||
#[allow(unused_imports)]
|
#[allow(unused_imports)]
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use objc2::foundation::NSObject;
|
use icrate::Foundation::NSObject;
|
||||||
use objc2::{extern_class, ClassType};
|
use objc2::{extern_class, mutability, ClassType};
|
||||||
|
|
||||||
extern_class!(
|
extern_class!(
|
||||||
#[derive(Debug, PartialEq, Eq, Hash)]
|
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||||
@@ -7,5 +7,6 @@ extern_class!(
|
|||||||
|
|
||||||
unsafe impl ClassType for UIResponder {
|
unsafe impl ClassType for UIResponder {
|
||||||
type Super = NSObject;
|
type Super = NSObject;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
|
use icrate::Foundation::{CGFloat, CGRect, MainThreadMarker, NSArray, NSInteger, NSObject};
|
||||||
use objc2::encode::{Encode, Encoding};
|
use objc2::encode::{Encode, Encoding};
|
||||||
use objc2::foundation::{CGFloat, CGRect, MainThreadMarker, NSArray, NSInteger, NSObject};
|
use objc2::rc::Id;
|
||||||
use objc2::rc::{Id, Shared};
|
use objc2::{extern_class, extern_methods, msg_send_id, mutability, ClassType};
|
||||||
use objc2::{extern_class, extern_methods, msg_send_id, ClassType};
|
|
||||||
|
|
||||||
use super::{UICoordinateSpace, UIScreenMode};
|
use super::{UICoordinateSpace, UIScreenMode};
|
||||||
|
|
||||||
@@ -11,53 +11,54 @@ extern_class!(
|
|||||||
|
|
||||||
unsafe impl ClassType for UIScreen {
|
unsafe impl ClassType for UIScreen {
|
||||||
type Super = NSObject;
|
type Super = NSObject;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
extern_methods!(
|
extern_methods!(
|
||||||
unsafe impl UIScreen {
|
unsafe impl UIScreen {
|
||||||
pub fn main(_mtm: MainThreadMarker) -> Id<Self, Shared> {
|
pub fn main(_mtm: MainThreadMarker) -> Id<Self> {
|
||||||
unsafe { msg_send_id![Self::class(), mainScreen] }
|
unsafe { msg_send_id![Self::class(), mainScreen] }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn screens(_mtm: MainThreadMarker) -> Id<NSArray<Self, Shared>, Shared> {
|
pub fn screens(_mtm: MainThreadMarker) -> Id<NSArray<Self>> {
|
||||||
unsafe { msg_send_id![Self::class(), screens] }
|
unsafe { msg_send_id![Self::class(), screens] }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[sel(bounds)]
|
#[method(bounds)]
|
||||||
pub fn bounds(&self) -> CGRect;
|
pub fn bounds(&self) -> CGRect;
|
||||||
|
|
||||||
#[sel(scale)]
|
#[method(scale)]
|
||||||
pub fn scale(&self) -> CGFloat;
|
pub fn scale(&self) -> CGFloat;
|
||||||
|
|
||||||
#[sel(nativeBounds)]
|
#[method(nativeBounds)]
|
||||||
pub fn nativeBounds(&self) -> CGRect;
|
pub fn nativeBounds(&self) -> CGRect;
|
||||||
|
|
||||||
#[sel(nativeScale)]
|
#[method(nativeScale)]
|
||||||
pub fn nativeScale(&self) -> CGFloat;
|
pub fn nativeScale(&self) -> CGFloat;
|
||||||
|
|
||||||
#[sel(maximumFramesPerSecond)]
|
#[method(maximumFramesPerSecond)]
|
||||||
pub fn maximumFramesPerSecond(&self) -> NSInteger;
|
pub fn maximumFramesPerSecond(&self) -> NSInteger;
|
||||||
|
|
||||||
pub fn mirroredScreen(&self) -> Id<Self, Shared> {
|
pub fn mirroredScreen(&self) -> Id<Self> {
|
||||||
unsafe { msg_send_id![Self::class(), mirroredScreen] }
|
unsafe { msg_send_id![Self::class(), mirroredScreen] }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn preferredMode(&self) -> Option<Id<UIScreenMode, Shared>> {
|
pub fn preferredMode(&self) -> Option<Id<UIScreenMode>> {
|
||||||
unsafe { msg_send_id![self, preferredMode] }
|
unsafe { msg_send_id![self, preferredMode] }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[sel(setCurrentMode:)]
|
#[method(setCurrentMode:)]
|
||||||
pub fn setCurrentMode(&self, mode: Option<&UIScreenMode>);
|
pub fn setCurrentMode(&self, mode: Option<&UIScreenMode>);
|
||||||
|
|
||||||
pub fn availableModes(&self) -> Id<NSArray<UIScreenMode, Shared>, Shared> {
|
pub fn availableModes(&self) -> Id<NSArray<UIScreenMode>> {
|
||||||
unsafe { msg_send_id![self, availableModes] }
|
unsafe { msg_send_id![self, availableModes] }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[sel(setOverscanCompensation:)]
|
#[method(setOverscanCompensation:)]
|
||||||
pub fn setOverscanCompensation(&self, overscanCompensation: UIScreenOverscanCompensation);
|
pub fn setOverscanCompensation(&self, overscanCompensation: UIScreenOverscanCompensation);
|
||||||
|
|
||||||
pub fn coordinateSpace(&self) -> Id<UICoordinateSpace, Shared> {
|
pub fn coordinateSpace(&self) -> Id<UICoordinateSpace> {
|
||||||
unsafe { msg_send_id![self, coordinateSpace] }
|
unsafe { msg_send_id![self, coordinateSpace] }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||