Compare commits
406 Commits
notgull/sp
...
waker
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a391b348a | ||
|
|
488c036a05 | ||
|
|
a4af50ec13 | ||
|
|
317d62fb93 | ||
|
|
b13b39aa0b | ||
|
|
abea6e64e4 | ||
|
|
d6f7a28499 | ||
|
|
bd98561b38 | ||
|
|
ca6f523924 | ||
|
|
d7fdfb1bca | ||
|
|
120f21a010 | ||
|
|
5904529ba1 | ||
|
|
e7a6034b55 | ||
|
|
eb66c25980 | ||
|
|
0ccb8a9f87 | ||
|
|
abed32eb80 | ||
|
|
08907148ec | ||
|
|
fa0795a50c | ||
|
|
fe1eab07ae | ||
|
|
552c7a6252 | ||
|
|
50c0180af3 | ||
|
|
4f33643509 | ||
|
|
0b21c55b72 | ||
|
|
e1bccb68d8 | ||
|
|
e540062ac0 | ||
|
|
f1e0f6c646 | ||
|
|
3218316420 | ||
|
|
2900ecab93 | ||
|
|
3a84da6951 | ||
|
|
478427b0bd | ||
|
|
b0f26c79ff | ||
|
|
969237f422 | ||
|
|
e542a78deb | ||
|
|
2d4b9938f0 | ||
|
|
8ad016362a | ||
|
|
5f2c7350e9 | ||
|
|
256bbe949e | ||
|
|
1126e9ea2f | ||
|
|
927af44aa4 | ||
|
|
0adc0898f0 | ||
|
|
3b986f5583 | ||
|
|
b1f8d778a1 | ||
|
|
04482d5a2e | ||
|
|
3e50911adb | ||
|
|
f51a470872 | ||
|
|
47b938dbe7 | ||
|
|
e2b883d215 | ||
|
|
38fd3c6a99 | ||
|
|
5190472bee | ||
|
|
eab03dca80 | ||
|
|
59e3dda89f | ||
|
|
c846f67bcb | ||
|
|
03c01e038b | ||
|
|
ed4ebd4242 | ||
|
|
b5921d89f2 | ||
|
|
b5a6a4e616 | ||
|
|
9598eb371c | ||
|
|
634b9baea2 | ||
|
|
cf5e422dc8 | ||
|
|
276597e009 | ||
|
|
c0b737de4a | ||
|
|
79fa4061cb | ||
|
|
056421546a | ||
|
|
b4c5b76155 | ||
|
|
c8b9a86885 | ||
|
|
fe2df61884 | ||
|
|
446482367b | ||
|
|
cbb29ab526 | ||
|
|
a491c2abed | ||
|
|
3142355417 | ||
|
|
3493a20173 | ||
|
|
bf0bde8067 | ||
|
|
519947463f | ||
|
|
8c36ed4900 | ||
|
|
7b2c9d42b4 | ||
|
|
587ade844d | ||
|
|
6756549ac9 | ||
|
|
17666e3171 | ||
|
|
f6ca06cd58 | ||
|
|
e634cc609f | ||
|
|
aa83726c72 | ||
|
|
1800fa1670 | ||
|
|
a5e6d0aaaf | ||
|
|
4fe4ce3d77 | ||
|
|
078c4c0c4f | ||
|
|
c8579a1882 | ||
|
|
ab96fa8395 | ||
|
|
6461cfa9b1 | ||
|
|
6c214e71ae | ||
|
|
ecc884ac91 | ||
|
|
24e2c6914a | ||
|
|
ed4d70fdd4 | ||
|
|
07c25b9703 | ||
|
|
cdbdd974fb | ||
|
|
7e13248be3 | ||
|
|
b15a40cd14 | ||
|
|
8db4a9cc61 | ||
|
|
a4ab7dc64c | ||
|
|
afb731bb52 | ||
|
|
ef37b1d5dd | ||
|
|
2b4e8ef916 | ||
|
|
ae28eea406 | ||
|
|
a0464ae83b | ||
|
|
16d5f46db1 | ||
|
|
5cada36ae8 | ||
|
|
b3dcfa1275 | ||
|
|
f1c5afd84e | ||
|
|
be1baf164c | ||
|
|
39c0862198 | ||
|
|
aa8ebdc795 | ||
|
|
ea68916055 | ||
|
|
e26b831f23 | ||
|
|
8c3e69c08b | ||
|
|
46879429ed | ||
|
|
0c89ea7386 | ||
|
|
6c0e3c3b15 | ||
|
|
675582bd46 | ||
|
|
4d6fe7e35c | ||
|
|
f9912baf09 | ||
|
|
f290619dce | ||
|
|
23011c6b0a | ||
|
|
3a39a6ddb0 | ||
|
|
90cf9a3398 | ||
|
|
05d8fa0b91 | ||
|
|
d7d20507ed | ||
|
|
f6e66a71f8 | ||
|
|
c09160d1a8 | ||
|
|
2230e71093 | ||
|
|
5e6350d142 | ||
|
|
a6998af997 | ||
|
|
5c48ec7977 | ||
|
|
953d9b4268 | ||
|
|
f5dcd2aabe | ||
|
|
77f1c73f06 | ||
|
|
24c226416e | ||
|
|
69382fda9a | ||
|
|
ee245c569d | ||
|
|
5462f27dda | ||
|
|
927deb030f | ||
|
|
5ea81efc74 | ||
|
|
6896de5b73 | ||
|
|
d736763216 | ||
|
|
e316a89847 | ||
|
|
f0d8689039 | ||
|
|
4d5e68c6e2 | ||
|
|
5835c9102e | ||
|
|
e47081e385 | ||
|
|
171d53c042 | ||
|
|
35379f305a | ||
|
|
4d2a0dd2b3 | ||
|
|
4a8b659228 | ||
|
|
f314cd2b9a | ||
|
|
3657506f6e | ||
|
|
edca3ebc41 | ||
|
|
ca46e29203 | ||
|
|
132fbe14d5 | ||
|
|
164bf85b5b | ||
|
|
cfa8f027cc | ||
|
|
2e5db75101 | ||
|
|
19e5bee3d1 | ||
|
|
fc6cf89ac0 | ||
|
|
dbcdb6f1b4 | ||
|
|
d0c6c34eaa | ||
|
|
f2688d94ea | ||
|
|
f6b20852bf | ||
|
|
59b1eb5410 | ||
|
|
f781e13166 | ||
|
|
9f8ac8feb5 | ||
|
|
74958ecc6f | ||
|
|
3a60cbaba5 | ||
|
|
ae4c449670 | ||
|
|
b2896d7408 | ||
|
|
edfb4b03f4 | ||
|
|
c8c1eca3c7 | ||
|
|
d3207a8d76 | ||
|
|
9d347b72d9 | ||
|
|
13bb51c7e0 | ||
|
|
bb4aa22cf9 | ||
|
|
3e9b80d47a | ||
|
|
c913cdab0b | ||
|
|
a5f5ce6a3d | ||
|
|
fb6b1d487b | ||
|
|
7d77ccfad3 | ||
|
|
c23bed20b8 | ||
|
|
8fe2b62adf | ||
|
|
4e3165f3d8 | ||
|
|
da2268ae22 | ||
|
|
eccd9e415d | ||
|
|
32cd1ad9a7 | ||
|
|
6e1b9fa24d | ||
|
|
380eea0072 | ||
|
|
a18658284c | ||
|
|
8ddd10a7f9 | ||
|
|
4f1c5b6129 | ||
|
|
7e819bb2ce | ||
|
|
dfea49f488 | ||
|
|
b674d20edf | ||
|
|
8db3e0e043 | ||
|
|
d37c591378 | ||
|
|
9419e4e1a7 | ||
|
|
241b7a80bb | ||
|
|
e716adcc0a | ||
|
|
aee95114db | ||
|
|
8f4a8efa99 | ||
|
|
1e1f0fd7e9 | ||
|
|
6e008b39e9 | ||
|
|
6c4da19197 | ||
|
|
a61e7bb4f4 | ||
|
|
7fbc2118b6 | ||
|
|
a96491f302 | ||
|
|
d96fd02f33 | ||
|
|
92e9bfe0fc | ||
|
|
3392e9c1de | ||
|
|
038ef5c3ad | ||
|
|
70c54ee0ff | ||
|
|
3bab4ef4fb | ||
|
|
58142680ce | ||
|
|
0ffcfd8a3a | ||
|
|
2e53533cc1 | ||
|
|
1168cd4113 | ||
|
|
9dff801f93 | ||
|
|
f07153b8e0 | ||
|
|
f5304815a1 | ||
|
|
29e1041987 | ||
|
|
15b79b18e1 | ||
|
|
54ff9c3bb5 | ||
|
|
546962c904 | ||
|
|
b7a7f59298 | ||
|
|
586255ac0a | ||
|
|
42ba0a74e0 | ||
|
|
34a37b8747 | ||
|
|
02a0a91a94 | ||
|
|
e3fbfb81d7 | ||
|
|
0909bf3d9d | ||
|
|
3398ebe467 | ||
|
|
21c121f9b3 | ||
|
|
ce0d1dfe1b | ||
|
|
7892e86731 | ||
|
|
7b0104b54c | ||
|
|
facb809f12 | ||
|
|
4e2e764e4a | ||
|
|
a0bc3e5dc8 | ||
|
|
2e97ab3d4f | ||
|
|
ef580b817d | ||
|
|
5ec934b1b0 | ||
|
|
c9c260ca08 | ||
|
|
b6109d4a17 | ||
|
|
eef2848c98 | ||
|
|
73c01fff96 | ||
|
|
88bbdb33da | ||
|
|
652ff7576c | ||
|
|
d741c58ac3 | ||
|
|
944ab60eda | ||
|
|
8e23d1608a | ||
|
|
dc99920612 | ||
|
|
ee3ab33a7c | ||
|
|
5b8f5cb54a | ||
|
|
bf97def398 | ||
|
|
d5fd8682eb | ||
|
|
39a7d5b738 | ||
|
|
2665c12098 | ||
|
|
936da131c2 | ||
|
|
850dd97177 | ||
|
|
1170554dbd | ||
|
|
75ce71f05a | ||
|
|
a0d69c782a | ||
|
|
2e93e48a3b | ||
|
|
82d9bbe559 | ||
|
|
8bdd4d620e | ||
|
|
9d5412ffe1 | ||
|
|
ecb887e5c3 | ||
|
|
7d1287958f | ||
|
|
c0c14aaf00 | ||
|
|
10dc0674bb | ||
|
|
4f59796e8a | ||
|
|
32097d75c7 | ||
|
|
c6c4395c3b | ||
|
|
38e6f9ad84 | ||
|
|
3e6092b8ed | ||
|
|
b4e83a5966 | ||
|
|
db2c97a995 | ||
|
|
1552eb21f7 | ||
|
|
d8ffd4bb26 | ||
|
|
34c15608e0 | ||
|
|
eef6977f45 | ||
|
|
078b46720b | ||
|
|
3b4e064a07 | ||
|
|
39bc139500 | ||
|
|
9522670081 | ||
|
|
9a1ef49dc3 | ||
|
|
3a624e0f52 | ||
|
|
279e3edc54 | ||
|
|
0e74d37ff5 | ||
|
|
2d1382f7d6 | ||
|
|
5d8091fc7f | ||
|
|
d7abe0316e | ||
|
|
5ea20fc905 | ||
|
|
e108fa2fbf | ||
|
|
fff6788c12 | ||
|
|
3e8fa41073 | ||
|
|
2b1c8cea1b | ||
|
|
ab33fb8eda | ||
|
|
b0b64a9a15 | ||
|
|
d5d202d60e | ||
|
|
cb39ab29f4 | ||
|
|
0a3cacd577 | ||
|
|
16fd2baba0 | ||
|
|
7f8771a362 | ||
|
|
337d50779c | ||
|
|
fd477986de | ||
|
|
94664ff687 | ||
|
|
0fc8c37721 | ||
|
|
ec29c81ad2 | ||
|
|
304a585493 | ||
|
|
1682703b5c | ||
|
|
bdd80c8af2 | ||
|
|
7b0c7b6cb2 | ||
|
|
7006c7ceca | ||
|
|
2491f2bbd6 | ||
|
|
babbb715c5 | ||
|
|
be79e8979a | ||
|
|
9ab4c03e89 | ||
|
|
4f47a4e793 | ||
|
|
c15fa6e433 | ||
|
|
24faacf497 | ||
|
|
080556f2c8 | ||
|
|
259e868c05 | ||
|
|
575d978202 | ||
|
|
7dd7dc1fc8 | ||
|
|
df7c496a5d | ||
|
|
0086d7153b | ||
|
|
b79acd8a5a | ||
|
|
c2951e0194 | ||
|
|
8998e36994 | ||
|
|
5a7169c7a6 | ||
|
|
4cd6877e8e | ||
|
|
44aabdddcc | ||
|
|
c4415009c0 | ||
|
|
63a7c02492 | ||
|
|
7b0ef160fc | ||
|
|
962241e2a0 | ||
|
|
3efa6d855d | ||
|
|
9067426dca | ||
|
|
ba10c35240 | ||
|
|
baf10de958 | ||
|
|
c10f9c32d3 | ||
|
|
975cf068c7 | ||
|
|
8e69a8fa40 | ||
|
|
fedb944d57 | ||
|
|
a63b04385a | ||
|
|
06f4e28de9 | ||
|
|
249d5d8bff | ||
|
|
66df2c22ba | ||
|
|
359a38844b | ||
|
|
563b0bf5e3 | ||
|
|
b2f9fad654 | ||
|
|
4ade1a7518 | ||
|
|
e06ecf4d72 | ||
|
|
4a8050289d | ||
|
|
99e238065e | ||
|
|
d123cd2f8e | ||
|
|
fc8a008b25 | ||
|
|
f6f1c45a72 | ||
|
|
388c40b1e0 | ||
|
|
7a40aa43dc | ||
|
|
944347696a | ||
|
|
96172693fe | ||
|
|
32004405ee | ||
|
|
22e932b5ab | ||
|
|
3d4c53459a | ||
|
|
f0b4889227 | ||
|
|
c81448e0b8 | ||
|
|
f498ff0369 | ||
|
|
c4e6e94b80 | ||
|
|
a5dbd3ee52 | ||
|
|
a4480a0652 | ||
|
|
e41f0eabb1 | ||
|
|
7e28d7615e | ||
|
|
010787a430 | ||
|
|
352e70b8ac | ||
|
|
990bbf178f | ||
|
|
97cfdd4b09 | ||
|
|
a127bd6f66 | ||
|
|
4a8648be57 | ||
|
|
a8c7109e89 | ||
|
|
7abd427216 | ||
|
|
3fb93b4f83 | ||
|
|
19190a95a0 | ||
|
|
c4310af83c | ||
|
|
542d1938ce | ||
|
|
31f8b816bd | ||
|
|
e61a7320a2 | ||
|
|
db41938deb | ||
|
|
2bc1943188 | ||
|
|
385c4b3c88 | ||
|
|
ea70f773d3 | ||
|
|
83012f4c1c | ||
|
|
6825fed073 | ||
|
|
273984a385 | ||
|
|
dbe0f852da | ||
|
|
d1902aa15a | ||
|
|
4112fccc12 | ||
|
|
bd6ce32860 | ||
|
|
8936fe1acd | ||
|
|
fedb86ea5a | ||
|
|
20687fef1c |
@@ -1,2 +1,9 @@
|
|||||||
[alias]
|
# Allow rust-analyzer and local `cargo doc` invocations to pick up unreleased changelog entries
|
||||||
run-wasm = ["run", "--release", "--package", "run-wasm", "--"]
|
#
|
||||||
|
# Note that these flags are (intentionally) not included when building from the downloaded crate.
|
||||||
|
[build]
|
||||||
|
rustdocflags = ["--cfg=unreleased_changelogs"]
|
||||||
|
rustflags = ["--cfg=unreleased_changelogs"]
|
||||||
|
|
||||||
|
[target.wasm32-unknown-unknown]
|
||||||
|
runner = "wasm-bindgen-test-runner"
|
||||||
|
|||||||
8
.git-blame-ignore-revs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
# $ git config blame.ignoreRevsFile .git-blame-ignore-revs
|
||||||
|
|
||||||
|
# chore(rustfmt): use nightly
|
||||||
|
7b0c7b6cb2c62767ca0c73c857b299883f55a883
|
||||||
|
# Rustfmt: use `group_imports`
|
||||||
|
2665c120981af548433645c6383b3580dd8f8fc4
|
||||||
|
# Use Taplo for TOML formatting
|
||||||
|
3398ebe467c43ccfd91916c5b81ff3c68f598556
|
||||||
36
.github/CODEOWNERS
vendored
@@ -1,34 +1,26 @@
|
|||||||
# Android
|
# Android
|
||||||
/src/platform/android.rs @msiglreith @MarijnS95
|
/winit-android @MarijnS95
|
||||||
/src/platform_impl/android @msiglreith @MarijnS95
|
|
||||||
|
|
||||||
# iOS
|
# Apple (AppKit + UIKit)
|
||||||
/src/platform/ios.rs @madsmtm
|
/winit-appkit @madsmtm
|
||||||
/src/platform_impl/ios @madsmtm
|
/winit-uikit @madsmtm
|
||||||
|
/winit-common/src/core_foundation @madsmtm
|
||||||
|
/winit-common/src/event_handler.rs @madsmtm
|
||||||
|
|
||||||
# Unix
|
# XKB
|
||||||
/src/platform_impl/linux/mod.rs @kchibisov
|
/winit-common/src/xkb @kchibisov
|
||||||
|
|
||||||
# Wayland
|
# Wayland
|
||||||
/src/platform/wayland.rs @kchibisov
|
/winit-wayland @kchibisov
|
||||||
/src/platform_impl/linux/wayland @kchibisov
|
|
||||||
|
|
||||||
# X11
|
# X11
|
||||||
/src/platform/x11.rs @kchibisov @notgull
|
/winit-x11 @kchibisov
|
||||||
/src/platform_impl/linux/x11 @kchibisov @notgull
|
|
||||||
|
|
||||||
# macOS
|
|
||||||
/src/platform/macos.rs @madsmtm
|
|
||||||
/src/platform_impl/macos @madsmtm
|
|
||||||
|
|
||||||
# Web
|
# Web
|
||||||
/src/platform/web.rs @daxpedda
|
/winit-web @daxpedda
|
||||||
/src/platform_impl/web @daxpedda
|
|
||||||
|
|
||||||
# Windows
|
# Windows (Win32) (UNOWNED)
|
||||||
/src/platform/windows.rs @msiglreith
|
#/winit-win32
|
||||||
/src/platform_impl/windows @msiglreith
|
|
||||||
|
|
||||||
# Orbital (Redox OS)
|
# Orbital (Redox OS)
|
||||||
/src/platform/orbital.rs @jackpot51
|
/winit-orbital @jackpot51
|
||||||
/src/platform_impl/orbital @jackpot51
|
|
||||||
|
|||||||
4
.github/ISSUE_TEMPLATE/blank_issue.md
vendored
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
---
|
||||||
|
name: Blank Issue
|
||||||
|
about: Create a blank issue.
|
||||||
|
---
|
||||||
36
.github/ISSUE_TEMPLATE/bug_android.yml
vendored
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
name: Android bug
|
||||||
|
description: Create an Android-specific bug report
|
||||||
|
labels:
|
||||||
|
- B - bug
|
||||||
|
- DS - android
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thanks for taking the time to fill out this bug report!
|
||||||
|
- type: textarea
|
||||||
|
id: description
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
description: Description of the problem you're having
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: device
|
||||||
|
attributes:
|
||||||
|
label: Device and Android version
|
||||||
|
description: Which devices and Android versions are you seeing the problem on?
|
||||||
|
placeholder: |
|
||||||
|
Samsung Galaxy Z running Android Pie (API level 28),
|
||||||
|
Samsung Galaxy Z running Android 14 (API level 34),
|
||||||
|
Pixel 8 running Android 14 (API level 34)
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: winit-version
|
||||||
|
attributes:
|
||||||
|
label: Winit version
|
||||||
|
description: What version of Winit are you using?
|
||||||
|
placeholder: 0.29.11
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
37
.github/ISSUE_TEMPLATE/bug_ios.yml
vendored
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
name: iOS bug
|
||||||
|
description: Create an iOS-specific bug report
|
||||||
|
labels:
|
||||||
|
- B - bug
|
||||||
|
- DS - ios
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thanks for taking the time to fill out this bug report!
|
||||||
|
- type: textarea
|
||||||
|
id: description
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
description: Description of the problem you're having
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: device
|
||||||
|
attributes:
|
||||||
|
label: Device and iOS version
|
||||||
|
description: Which devices and iOS versions are you seeing the problem on?
|
||||||
|
placeholder: |
|
||||||
|
iPhone 15 running iOS 14.0,
|
||||||
|
iPhone 15 running iOS 17.0,
|
||||||
|
MacBook Pro M2 Mac Catalyst running macOS 14.2,
|
||||||
|
iPhone simulator running iOS 17.0
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: winit-version
|
||||||
|
attributes:
|
||||||
|
label: Winit version
|
||||||
|
description: What version of Winit are you using?
|
||||||
|
placeholder: 0.29.11
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
37
.github/ISSUE_TEMPLATE/bug_macos.yml
vendored
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
name: MacOS bug
|
||||||
|
description: Create a macOS-specific bug report
|
||||||
|
labels:
|
||||||
|
- B - bug
|
||||||
|
- DS - macos
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thanks for taking the time to fill out this bug report!
|
||||||
|
- type: textarea
|
||||||
|
id: description
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
description: Description of the problem you're having
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: os-version
|
||||||
|
attributes:
|
||||||
|
label: macOS version
|
||||||
|
description: What version of macOS are you using? Please paste in the output of `sw_vers`.
|
||||||
|
placeholder: |
|
||||||
|
ProductName: macOS
|
||||||
|
ProductVersion: 14.2.1
|
||||||
|
BuildVersion: 23C71
|
||||||
|
render: shell
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: winit-version
|
||||||
|
attributes:
|
||||||
|
label: Winit version
|
||||||
|
description: What version of Winit are you using?
|
||||||
|
placeholder: 0.29.11
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
41
.github/ISSUE_TEMPLATE/bug_wayland.yml
vendored
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
name: Wayland bug
|
||||||
|
description: Create a Wayland-specific bug report
|
||||||
|
labels:
|
||||||
|
- B - bug
|
||||||
|
- DS - wayland
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thanks for taking the time to fill out this bug report!
|
||||||
|
- type: textarea
|
||||||
|
id: description
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
description: Description of the problem you're having
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: debug
|
||||||
|
attributes:
|
||||||
|
label: Debugging output
|
||||||
|
description: Output of a binary run with `WAYLAND_DEBUG=1`
|
||||||
|
placeholder: |
|
||||||
|
[1234.5678] -> wl_display@1.get_registry(new id wl_registry@2)
|
||||||
|
[1234.5678] -> wl_display@1.sync(new id wl_callback@3)
|
||||||
|
...
|
||||||
|
render: shell
|
||||||
|
- type: checkboxes
|
||||||
|
attributes:
|
||||||
|
label: Window isn't shown unless you draw
|
||||||
|
options:
|
||||||
|
- label: I understand that windows aren't shown on Wayland unless I draw and present to them.
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: winit-version
|
||||||
|
attributes:
|
||||||
|
label: Winit version
|
||||||
|
description: What version of Winit are you using?
|
||||||
|
placeholder: 0.29.11
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
51
.github/ISSUE_TEMPLATE/bug_web.yml
vendored
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
name: Web bug
|
||||||
|
description: Create a Web-specific bug report
|
||||||
|
labels:
|
||||||
|
- B - bug
|
||||||
|
- DS - web
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thanks for taking the time to fill out this bug report!
|
||||||
|
- type: textarea
|
||||||
|
id: description
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
description: Description of the problem you're having
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: browsers
|
||||||
|
attributes:
|
||||||
|
label: Tested browsers
|
||||||
|
description: What browsers are you seeing the problem on?
|
||||||
|
options:
|
||||||
|
- Firefox
|
||||||
|
- Chrome
|
||||||
|
- Microsoft Edge
|
||||||
|
- Safari 13
|
||||||
|
- Safari 14
|
||||||
|
- Safari 15
|
||||||
|
- Safari 16
|
||||||
|
- Safari 17
|
||||||
|
- Safari (newer than listed)
|
||||||
|
multiple: true
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: device
|
||||||
|
attributes:
|
||||||
|
label: Tested devices
|
||||||
|
description: Which device(s) are you using?
|
||||||
|
placeholder: 'iPhone 15, Lenovo ThinkPad X1, MacBook Pro M2, Samsung Galaxy Z, ...'
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: winit-version
|
||||||
|
attributes:
|
||||||
|
label: Winit version
|
||||||
|
description: What version of Winit are you using?
|
||||||
|
placeholder: 0.29.11
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
35
.github/ISSUE_TEMPLATE/bug_windows.yml
vendored
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
name: Windows bug
|
||||||
|
description: Create a Windows-specific bug report
|
||||||
|
labels:
|
||||||
|
- B - bug
|
||||||
|
- DS - windows
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thanks for taking the time to fill out this bug report!
|
||||||
|
- type: textarea
|
||||||
|
id: description
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
description: Description of the problem you're having
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: os-version
|
||||||
|
attributes:
|
||||||
|
label: Windows version
|
||||||
|
description: What version of Windows are you using? Please paste in the output of the `ver` command.
|
||||||
|
placeholder: |
|
||||||
|
Microsoft Windows [Version 10.0.19042.2251]
|
||||||
|
render: shell
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: winit-version
|
||||||
|
attributes:
|
||||||
|
label: Winit version
|
||||||
|
description: What version of Winit are you using?
|
||||||
|
placeholder: 0.29.11
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
32
.github/ISSUE_TEMPLATE/bug_x11.yml
vendored
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
name: X11 bug
|
||||||
|
description: Create a X11-specific bug report
|
||||||
|
labels:
|
||||||
|
- B - bug
|
||||||
|
- DS - x11
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thanks for taking the time to fill out this bug report!
|
||||||
|
- type: textarea
|
||||||
|
id: description
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
description: Description of the problem you're having
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: os-info
|
||||||
|
attributes:
|
||||||
|
label: OS and window mananger
|
||||||
|
description: Which operating system and window manager are you using?
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: winit-version
|
||||||
|
attributes:
|
||||||
|
label: Winit version
|
||||||
|
description: What version of Winit are you using?
|
||||||
|
placeholder: 0.29.11
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
blank_issues_enabled: true
|
||||||
|
contact_links:
|
||||||
|
- name: Question
|
||||||
|
url: https://matrix.to/#/#rust-windowing:matrix.org
|
||||||
|
about: Please ask questions on the Matrix channel.
|
||||||
26
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
name: Feature request
|
||||||
|
description: Propose a new feature
|
||||||
|
labels:
|
||||||
|
- S - enhancement
|
||||||
|
body:
|
||||||
|
- type: textarea
|
||||||
|
id: description
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
description: Description of the problem does this solve or what need does it fill? Please be mindful of the [scope](https://github.com/rust-windowing/winit/blob/master/FEATURES.md) of Winit.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: platforms
|
||||||
|
attributes:
|
||||||
|
label: Relevant platforms
|
||||||
|
description: On which platforms is this feature relevant?
|
||||||
|
options:
|
||||||
|
- Windows
|
||||||
|
- macOS
|
||||||
|
- Wayland
|
||||||
|
- X11
|
||||||
|
- Web
|
||||||
|
- iOS
|
||||||
|
- Android
|
||||||
|
multiple: true
|
||||||
3
.github/PULL_REQUEST_TEMPLATE.md
vendored
@@ -1,5 +1,4 @@
|
|||||||
- [ ] Tested on all platforms changed
|
- [ ] Tested on all platforms changed
|
||||||
- [ ] Added an entry to `CHANGELOG.md` if knowledge of this change could be valuable to users
|
- [ ] Added an entry to the `changelog` module if knowledge of this change could be valuable to users
|
||||||
- [ ] Updated documentation to reflect any user-facing changes, including notes of platform-specific behavior
|
- [ ] Updated documentation to reflect any user-facing changes, including notes of platform-specific behavior
|
||||||
- [ ] Created or updated an example program if it would help users understand this functionality
|
- [ ] Created or updated an example program if it would help users understand this functionality
|
||||||
- [ ] Updated [feature matrix](https://github.com/rust-windowing/winit/blob/master/FEATURES.md), if new features were added or implemented
|
|
||||||
|
|||||||
22
.github/dependabot.yaml
vendored
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
version: 2
|
||||||
|
|
||||||
|
updates:
|
||||||
|
- package-ecosystem: github-actions
|
||||||
|
directory: /
|
||||||
|
schedule:
|
||||||
|
interval: daily
|
||||||
|
groups:
|
||||||
|
github-actions:
|
||||||
|
patterns:
|
||||||
|
- "*"
|
||||||
|
|
||||||
|
- package-ecosystem: npm
|
||||||
|
directory: src/platform_impl/web/script
|
||||||
|
schedule:
|
||||||
|
interval: daily
|
||||||
|
groups:
|
||||||
|
github-actions:
|
||||||
|
patterns:
|
||||||
|
- '*'
|
||||||
|
labels:
|
||||||
|
- "DS - web"
|
||||||
226
.github/workflows/ci.yml
vendored
@@ -10,13 +10,44 @@ jobs:
|
|||||||
name: Check formatting
|
name: Check formatting
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: taiki-e/checkout-action@v1
|
||||||
- uses: dtolnay/rust-toolchain@stable
|
- uses: dtolnay/rust-toolchain@nightly
|
||||||
with:
|
with:
|
||||||
components: rustfmt
|
components: rustfmt
|
||||||
- name: Check Formatting
|
- name: Check Formatting
|
||||||
run: cargo fmt -- --check
|
run: cargo fmt -- --check
|
||||||
|
|
||||||
|
taplo:
|
||||||
|
name: Taplo
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: taiki-e/checkout-action@v1
|
||||||
|
- name: Install Taplo
|
||||||
|
uses: taiki-e/install-action@v2
|
||||||
|
with:
|
||||||
|
tool: taplo-cli
|
||||||
|
- name: Run Taplo
|
||||||
|
run: taplo fmt --check
|
||||||
|
|
||||||
|
typos:
|
||||||
|
name: Check for typos
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 30
|
||||||
|
steps:
|
||||||
|
- uses: taiki-e/checkout-action@v1
|
||||||
|
- uses: taiki-e/install-action@v2
|
||||||
|
with:
|
||||||
|
tool: typos-cli
|
||||||
|
- name: run typos
|
||||||
|
run: typos
|
||||||
|
- name: Typos info
|
||||||
|
if: failure()
|
||||||
|
run: |
|
||||||
|
echo 'To fix typos, please run `typos -w`'
|
||||||
|
echo 'To check for a diff, run `typos`'
|
||||||
|
echo 'You can find typos here: https://crates.io/crates/typos'
|
||||||
|
|
||||||
tests:
|
tests:
|
||||||
name: Test ${{ matrix.toolchain }} ${{ matrix.platform.name }}
|
name: Test ${{ matrix.toolchain }} ${{ matrix.platform.name }}
|
||||||
runs-on: ${{ matrix.platform.os }}
|
runs-on: ${{ matrix.platform.os }}
|
||||||
@@ -24,7 +55,7 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
toolchain: [stable, nightly, '1.70.0']
|
toolchain: [stable, nightly, '1.80']
|
||||||
platform:
|
platform:
|
||||||
# Note: Make sure that we test all the `docs.rs` targets defined in Cargo.toml!
|
# Note: Make sure that we test all the `docs.rs` targets defined in Cargo.toml!
|
||||||
- { name: 'Windows 64bit MSVC', target: x86_64-pc-windows-msvc, os: windows-latest, }
|
- { name: 'Windows 64bit MSVC', target: x86_64-pc-windows-msvc, os: windows-latest, }
|
||||||
@@ -35,27 +66,41 @@ jobs:
|
|||||||
- { name: 'Linux 64bit', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, }
|
- { name: 'Linux 64bit', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, }
|
||||||
- { name: 'X11', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: '--no-default-features --features=x11' }
|
- { name: 'X11', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: '--no-default-features --features=x11' }
|
||||||
- { name: 'Wayland', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: '--no-default-features --features=wayland,wayland-dlopen' }
|
- { name: 'Wayland', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: '--no-default-features --features=wayland,wayland-dlopen' }
|
||||||
- { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--features=android-native-activity', cmd: 'apk --' }
|
- { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package winit --features=android-native-activity', cmd: 'apk -- ' }
|
||||||
- { name: 'Redox OS', target: x86_64-unknown-redox, os: ubuntu-latest, }
|
- { name: 'Redox OS', target: x86_64-unknown-redox, os: ubuntu-latest, }
|
||||||
- { name: 'macOS', target: x86_64-apple-darwin, os: macos-latest, }
|
- { name: 'macOS x86_64', target: x86_64-apple-darwin, os: macos-latest, }
|
||||||
|
- { name: 'macOS Aarch64', target: aarch64-apple-darwin, os: macos-latest, }
|
||||||
- { name: 'iOS x86_64', target: x86_64-apple-ios, os: macos-latest, }
|
- { name: 'iOS x86_64', target: x86_64-apple-ios, os: macos-latest, }
|
||||||
- { name: 'iOS Aarch64', target: aarch64-apple-ios, os: macos-latest, }
|
- { name: 'iOS Aarch64', target: aarch64-apple-ios, os: macos-latest, }
|
||||||
- { name: 'web', target: wasm32-unknown-unknown, os: ubuntu-latest, }
|
- { name: 'Web', target: wasm32-unknown-unknown, os: ubuntu-latest, }
|
||||||
exclude:
|
exclude:
|
||||||
|
# Web on nightly needs extra arguments
|
||||||
|
|
||||||
|
- toolchain: nightly
|
||||||
|
platform: { name: 'Web' }
|
||||||
|
# Rustup is broken.
|
||||||
|
- toolchain: nightly
|
||||||
|
platform: { name: 'Windows 32bit GNU' }
|
||||||
# Android is tested on stable-3
|
# Android is tested on stable-3
|
||||||
- toolchain: '1.70.0'
|
- toolchain: '1.80'
|
||||||
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
platform: { name: 'Android' }
|
||||||
|
# Redox OS doesn't follow MSRV
|
||||||
|
- toolchain: '1.80'
|
||||||
|
platform: { name: 'Redox OS' }
|
||||||
include:
|
include:
|
||||||
- toolchain: '1.70.0'
|
- toolchain: '1.80'
|
||||||
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package winit --features=android-native-activity', cmd: 'apk -- ' }
|
||||||
|
- toolchain: 'nightly'
|
||||||
|
platform: { name: 'Web', target: wasm32-unknown-unknown, os: ubuntu-latest, test-options: -Zdoctest-xcompile }
|
||||||
- toolchain: 'nightly'
|
- toolchain: 'nightly'
|
||||||
platform: {
|
platform: {
|
||||||
name: 'web Atomic',
|
name: 'Web Atomic',
|
||||||
target: wasm32-unknown-unknown,
|
target: wasm32-unknown-unknown,
|
||||||
os: ubuntu-latest,
|
os: ubuntu-latest,
|
||||||
options: '-Zbuild-std=panic_abort,std',
|
options: '-Zbuild-std=panic_abort,std',
|
||||||
rustflags: '-Ctarget-feature=+atomics,+bulk-memory',
|
test-options: -Zdoctest-xcompile,
|
||||||
components: rust-src,
|
rustflags: '-Ctarget-feature=+atomics,+bulk-memory',
|
||||||
|
components: rust-src,
|
||||||
}
|
}
|
||||||
|
|
||||||
env:
|
env:
|
||||||
@@ -65,19 +110,21 @@ jobs:
|
|||||||
|
|
||||||
# Faster compilation and error on warnings
|
# Faster compilation and error on warnings
|
||||||
RUSTFLAGS: '--codegen=debuginfo=0 --deny=warnings ${{ matrix.platform.rustflags }}'
|
RUSTFLAGS: '--codegen=debuginfo=0 --deny=warnings ${{ matrix.platform.rustflags }}'
|
||||||
|
RUSTDOCFLAGS: ${{ matrix.platform.rustflags }}
|
||||||
|
|
||||||
OPTIONS: --target=${{ matrix.platform.target }} ${{ matrix.platform.options }}
|
OPTIONS: --target=${{ matrix.platform.target }} ${{ matrix.platform.options }}
|
||||||
|
TEST_OPTIONS: ${{ matrix.platform.test-options }}
|
||||||
CMD: ${{ matrix.platform.cmd }}
|
CMD: ${{ matrix.platform.cmd }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: taiki-e/checkout-action@v1
|
||||||
|
|
||||||
- name: Restore cache of cargo folder
|
- name: Restore cache of cargo folder
|
||||||
# We use `restore` and later `save`, so that we can create the key after
|
# We use `restore` and later `save`, so that we can create the key after
|
||||||
# the cache has been downloaded.
|
# the cache has been downloaded.
|
||||||
#
|
#
|
||||||
# This could be avoided if we added Cargo.lock to the repository.
|
# This could be avoided if we added Cargo.lock to the repository.
|
||||||
uses: actions/cache/restore@v3
|
uses: actions/cache/restore@v4
|
||||||
with:
|
with:
|
||||||
# https://doc.rust-lang.org/cargo/guide/cargo-home.html#caching-the-cargo-home-in-ci
|
# https://doc.rust-lang.org/cargo/guide/cargo-home.html#caching-the-cargo-home-in-ci
|
||||||
path: |
|
path: |
|
||||||
@@ -89,7 +136,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Generate lockfile
|
- name: Generate lockfile
|
||||||
# Also updates the crates.io index
|
# Also updates the crates.io index
|
||||||
run: cargo generate-lockfile
|
run: cargo generate-lockfile && cargo update -p ahash --precise 0.8.7 && cargo update -p bumpalo --precise 3.14.0
|
||||||
|
|
||||||
- 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')
|
||||||
@@ -98,7 +145,7 @@ jobs:
|
|||||||
- name: Cache cargo-apk
|
- name: Cache cargo-apk
|
||||||
if: contains(matrix.platform.target, 'android')
|
if: contains(matrix.platform.target, 'android')
|
||||||
id: cargo-apk-cache
|
id: cargo-apk-cache
|
||||||
uses: actions/cache@v3
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
path: ~/.cargo/bin/cargo-apk
|
path: ~/.cargo/bin/cargo-apk
|
||||||
# Change this key if we update the required cargo-apk version
|
# Change this key if we update the required cargo-apk version
|
||||||
@@ -113,6 +160,11 @@ jobs:
|
|||||||
if: contains(matrix.platform.target, 'android') && (steps.cargo-apk-cache.outputs.cache-hit != 'true')
|
if: contains(matrix.platform.target, 'android') && (steps.cargo-apk-cache.outputs.cache-hit != 'true')
|
||||||
run: cargo install cargo-apk --version=^0.9.7 --locked
|
run: cargo install cargo-apk --version=^0.9.7 --locked
|
||||||
|
|
||||||
|
- uses: taiki-e/cache-cargo-install-action@v2
|
||||||
|
if: contains(matrix.platform.target, 'wasm32') && matrix.toolchain == 'nightly'
|
||||||
|
with:
|
||||||
|
tool: wasm-bindgen-cli
|
||||||
|
|
||||||
- uses: dtolnay/rust-toolchain@master
|
- uses: dtolnay/rust-toolchain@master
|
||||||
with:
|
with:
|
||||||
toolchain: ${{ matrix.toolchain }}${{ matrix.platform.host }}
|
toolchain: ${{ matrix.toolchain }}${{ matrix.platform.host }}
|
||||||
@@ -125,51 +177,111 @@ jobs:
|
|||||||
RUSTDOCFLAGS: '--deny=warnings ${{ matrix.platform.rustflags }}'
|
RUSTDOCFLAGS: '--deny=warnings ${{ matrix.platform.rustflags }}'
|
||||||
|
|
||||||
- name: Build crate
|
- name: Build crate
|
||||||
run: cargo $CMD build -p winit $OPTIONS
|
run: cargo $CMD build $OPTIONS
|
||||||
|
|
||||||
|
- name: Test winit core
|
||||||
|
run: cargo test -p winit-core
|
||||||
|
|
||||||
|
- name: Test winit Android
|
||||||
|
if: contains(matrix.platform.target, 'android')
|
||||||
|
run: cargo $CMD test -p winit-android --features native-activity --no-run
|
||||||
|
|
||||||
|
- name: Test winit Common (EventHandler)
|
||||||
|
run: cargo $CMD test -p winit-common --features event-handler --no-run
|
||||||
|
|
||||||
|
- name: Test winit Common (CF)
|
||||||
|
if: contains(matrix.platform.target, 'apple')
|
||||||
|
run: cargo $CMD test -p winit-common --features core-foundation --no-run
|
||||||
|
|
||||||
|
- name: Test winit Common (XKB)
|
||||||
|
if: contains(matrix.platform.target, 'linux-gnu')
|
||||||
|
run: cargo $CMD test -p winit-common --features xkb,x11,wayland --no-run
|
||||||
|
|
||||||
|
- name: Test winit AppKit
|
||||||
|
if: contains(matrix.platform.target, 'macos')
|
||||||
|
run: cargo $CMD test -p winit-appkit $OPTIONS
|
||||||
|
|
||||||
|
- name: Test winit Orbital
|
||||||
|
if: contains(matrix.platform.target, 'redox')
|
||||||
|
run: cargo test -p winit-orbital
|
||||||
|
|
||||||
|
- name: Test winit UIKit
|
||||||
|
if: contains(matrix.platform.target, 'ios')
|
||||||
|
# TODO: Run on Simulator
|
||||||
|
run: cargo $CMD test -p winit-uikit $OPTIONS --no-run
|
||||||
|
|
||||||
|
- name: Test winit Web
|
||||||
|
if: contains(matrix.platform.target, 'wasm')
|
||||||
|
run: cargo $CMD test -p winit-web $OPTIONS --no-run
|
||||||
|
|
||||||
|
- name: Test winit Win32
|
||||||
|
if: contains(matrix.platform.target, 'windows')
|
||||||
|
run: cargo $CMD test -p winit-win32 $OPTIONS
|
||||||
|
|
||||||
|
- name: Test winit X11
|
||||||
|
if: contains(matrix.platform.target, 'linux-gnu')
|
||||||
|
run: cargo $CMD test -p winit-x11 --target=${{ matrix.platform.target }}
|
||||||
|
|
||||||
|
- name: Test winit Wayland
|
||||||
|
if: contains(matrix.platform.target, 'linux-gnu')
|
||||||
|
run: cargo $CMD test -p winit-wayland --target=${{ matrix.platform.target }}
|
||||||
|
|
||||||
|
# Test only on Linux x86_64, so we avoid spending unnecessary CI hours.
|
||||||
|
- name: Test dpi crate
|
||||||
|
if: >
|
||||||
|
contains(matrix.platform.name, 'Linux 64bit') &&
|
||||||
|
matrix.toolchain != '1.80'
|
||||||
|
run: cargo test -p dpi
|
||||||
|
|
||||||
|
- name: Check dpi crate (no_std)
|
||||||
|
if: >
|
||||||
|
contains(matrix.platform.name, 'Linux 64bit') &&
|
||||||
|
matrix.toolchain != '1.80'
|
||||||
|
run: cargo check -p dpi --no-default-features
|
||||||
|
|
||||||
- name: Build tests
|
- name: Build tests
|
||||||
if: >
|
if: >
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.toolchain != '1.70.0'
|
matrix.toolchain != '1.80'
|
||||||
run: cargo $CMD test -p winit --no-run $OPTIONS
|
run: cargo $CMD test --no-run $OPTIONS
|
||||||
|
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
if: >
|
if: >
|
||||||
!contains(matrix.platform.target, 'android') &&
|
!contains(matrix.platform.target, 'android') &&
|
||||||
!contains(matrix.platform.target, 'ios') &&
|
!contains(matrix.platform.target, 'ios') &&
|
||||||
!contains(matrix.platform.target, 'wasm32') &&
|
(!contains(matrix.platform.target, 'wasm32') || matrix.toolchain == 'nightly') &&
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.toolchain != '1.70.0'
|
matrix.toolchain != '1.80'
|
||||||
run: cargo $CMD test $OPTIONS
|
run: cargo $CMD test $OPTIONS
|
||||||
|
|
||||||
- name: Lint with clippy
|
- name: Lint with clippy
|
||||||
if: (matrix.toolchain == 'stable') && !contains(matrix.platform.options, '--no-default-features')
|
if: (matrix.toolchain == 'stable') && !contains(matrix.platform.options, '--no-default-features')
|
||||||
run: cargo clippy --all-targets $OPTIONS -- -Dwarnings
|
run: cargo clippy --all-targets $OPTIONS $TEST_OPTIONS -- -Dwarnings
|
||||||
|
|
||||||
- name: Build tests with serde enabled
|
- name: Build tests with serde enabled
|
||||||
if: >
|
if: >
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.toolchain != '1.70.0'
|
matrix.toolchain != '1.80'
|
||||||
run: cargo $CMD test --no-run $OPTIONS -p winit --features serde
|
run: cargo $CMD test --no-run $OPTIONS $TEST_OPTIONS --features serde
|
||||||
|
|
||||||
- name: Run tests with serde enabled
|
- name: Run tests with serde enabled
|
||||||
if: >
|
if: >
|
||||||
!contains(matrix.platform.target, 'android') &&
|
!contains(matrix.platform.target, 'android') &&
|
||||||
!contains(matrix.platform.target, 'ios') &&
|
!contains(matrix.platform.target, 'ios') &&
|
||||||
!contains(matrix.platform.target, 'wasm32') &&
|
(!contains(matrix.platform.target, 'wasm32') || matrix.toolchain == 'nightly') &&
|
||||||
!contains(matrix.platform.target, 'redox') &&
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
matrix.toolchain != '1.70.0'
|
matrix.toolchain != '1.80'
|
||||||
run: cargo $CMD test $OPTIONS --features serde
|
run: cargo $CMD test $OPTIONS $TEST_OPTIONS --features serde
|
||||||
|
|
||||||
- name: Check docs.rs documentation
|
- name: Check docs.rs documentation
|
||||||
if: matrix.toolchain == 'nightly'
|
if: matrix.toolchain == 'nightly'
|
||||||
run: cargo doc --no-deps $OPTIONS --features=rwh_04,rwh_05,rwh_06,serde,mint,android-native-activity
|
run: cargo doc --no-deps $OPTIONS --features=serde,mint,android-native-activity
|
||||||
env:
|
env:
|
||||||
RUSTDOCFLAGS: '--deny=warnings ${{ matrix.platform.rustflags }} --cfg=docsrs'
|
RUSTDOCFLAGS: '--deny=warnings ${{ matrix.platform.rustflags }} --cfg=docsrs --cfg=unreleased_changelogs'
|
||||||
|
|
||||||
# See restore step above
|
# See restore step above
|
||||||
- name: Save cache of cargo folder
|
- name: Save cache of cargo folder
|
||||||
uses: actions/cache/save@v3
|
uses: actions/cache/save@v4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
~/.cargo/registry/index/
|
~/.cargo/registry/index/
|
||||||
@@ -189,15 +301,51 @@ jobs:
|
|||||||
- { name: 'Android', target: aarch64-linux-android }
|
- { name: 'Android', target: aarch64-linux-android }
|
||||||
- { name: 'iOS', target: aarch64-apple-ios }
|
- { name: 'iOS', target: aarch64-apple-ios }
|
||||||
- { name: 'Linux', target: x86_64-unknown-linux-gnu }
|
- { name: 'Linux', target: x86_64-unknown-linux-gnu }
|
||||||
- { name: 'macOS', target: x86_64-apple-darwin }
|
- { name: 'macOS', target: aarch64-apple-darwin }
|
||||||
- { name: 'Redox OS', target: x86_64-unknown-redox }
|
- { name: 'Redox OS', target: x86_64-unknown-redox }
|
||||||
- { name: 'web', target: wasm32-unknown-unknown }
|
- { name: 'Web', target: wasm32-unknown-unknown }
|
||||||
- { name: 'Windows', target: x86_64-pc-windows-gnu }
|
- { name: 'Windows GNU', target: x86_64-pc-windows-gnu }
|
||||||
|
- { name: 'Windows MSVC', target: x86_64-pc-windows-msvc }
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: taiki-e/checkout-action@v1
|
||||||
- uses: EmbarkStudios/cargo-deny-action@v1
|
- uses: EmbarkStudios/cargo-deny-action@v2
|
||||||
with:
|
with:
|
||||||
command: check
|
command: check
|
||||||
log-level: error
|
log-level: error
|
||||||
|
manifest-path: winit/Cargo.toml
|
||||||
arguments: --all-features --target ${{ matrix.platform.target }}
|
arguments: --all-features --target ${{ matrix.platform.target }}
|
||||||
|
|
||||||
|
eslint:
|
||||||
|
name: ESLint
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: ./winit-web/src/script
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: taiki-e/checkout-action@v1
|
||||||
|
- name: Setup NPM
|
||||||
|
run: npm install
|
||||||
|
- name: Run ESLint
|
||||||
|
run: npx eslint
|
||||||
|
|
||||||
|
swc:
|
||||||
|
name: Minimize JavaScript
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: ./winit-web/src/script
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: taiki-e/checkout-action@v1
|
||||||
|
- name: Install SWC
|
||||||
|
run: sudo npm i -g @swc/cli
|
||||||
|
- name: Run SWC
|
||||||
|
run: |
|
||||||
|
swc . --ignore node_modules,**/*.d.ts --only **/*.ts -d . --out-file-extension min.js
|
||||||
|
- name: Check for diff
|
||||||
|
run: |
|
||||||
|
[[ -z $(git status -s) ]]
|
||||||
|
|||||||
12
.github/workflows/docs.yml
vendored
@@ -17,9 +17,9 @@ jobs:
|
|||||||
contents: read
|
contents: read
|
||||||
pages: write
|
pages: write
|
||||||
id-token: write
|
id-token: write
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v5
|
||||||
|
|
||||||
- uses: dtolnay/rust-toolchain@master
|
- uses: dtolnay/rust-toolchain@master
|
||||||
with:
|
with:
|
||||||
@@ -27,12 +27,12 @@ jobs:
|
|||||||
|
|
||||||
- name: Run Rustdoc
|
- name: Run Rustdoc
|
||||||
env:
|
env:
|
||||||
RUSTDOCFLAGS: --crate-version master --cfg=docsrs
|
RUSTDOCFLAGS: --crate-version master --cfg=docsrs --cfg=unreleased_changelogs
|
||||||
run: |
|
run: |
|
||||||
cargo doc --no-deps -Z rustdoc-map -Z rustdoc-scrape-examples --features=rwh_04,rwh_05,rwh_06,serde,mint,android-native-activity
|
cargo doc --no-deps -Z rustdoc-map -Z rustdoc-scrape-examples --features=serde,mint,android-native-activity
|
||||||
|
|
||||||
- name: Setup Pages
|
- name: Setup Pages
|
||||||
uses: actions/configure-pages@v4
|
uses: actions/configure-pages@v5
|
||||||
|
|
||||||
- name: Fix permissions
|
- name: Fix permissions
|
||||||
run: |
|
run: |
|
||||||
@@ -41,7 +41,7 @@ jobs:
|
|||||||
done
|
done
|
||||||
|
|
||||||
- name: Upload artifact
|
- name: Upload artifact
|
||||||
uses: actions/upload-pages-artifact@v3
|
uses: actions/upload-pages-artifact@v4
|
||||||
with:
|
with:
|
||||||
path: target/doc
|
path: target/doc
|
||||||
|
|
||||||
|
|||||||
6
.gitignore
vendored
@@ -3,8 +3,8 @@ target/
|
|||||||
rls/
|
rls/
|
||||||
.vscode/
|
.vscode/
|
||||||
*~
|
*~
|
||||||
*.wasm
|
|
||||||
*.ts
|
|
||||||
*.js
|
|
||||||
#*#
|
#*#
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
# NPM package used to run ESLint.
|
||||||
|
/src/platform_impl/web/script/node_modules
|
||||||
|
/src/platform_impl/web/script/package-lock.json
|
||||||
|
|||||||
1259
CHANGELOG.md
6
CODE_OF_CONDUCT.md
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
# Code of Conduct
|
||||||
|
|
||||||
|
The `rust-windowing` project adheres to the [Rust Code of Conduct]. This
|
||||||
|
describes the minimum behavior expected from all contributors.
|
||||||
|
|
||||||
|
[Rust Code of Conduct]: https://www.rust-lang.org/policies/code-of-conduct
|
||||||
179
CONTRIBUTING.md
@@ -1,71 +1,162 @@
|
|||||||
# Winit Contributing Guidelines
|
# Contribution Guidelines
|
||||||
|
|
||||||
## Scope
|
This document contains guidelines for contributing code to winit. It has to be
|
||||||
[See `FEATURES.md`](./FEATURES.md). When requesting or implementing a new Winit feature, you should
|
followed in order for your patch to be approved and applied.
|
||||||
consider whether or not it's directly related to window creation or input handling. If it isn't, it
|
|
||||||
may be worth creating a separate crate that extends Winit's API to add that functionality.
|
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
## Reporting an issue
|
Anyone can contribute to winit, however given that it's a cross platform
|
||||||
|
windowing toolkit getting certain changes incorporated could be challenging.
|
||||||
|
|
||||||
When reporting an issue, in order to help the maintainers understand what the problem is, please make
|
To save your time it's wise to check already opened [pull requests][prs] and
|
||||||
your description of the issue as detailed as possible:
|
[issues][issues]. In general, bug fixes and missing implementations are always
|
||||||
|
accepted, however larger new API proposals should go into the issue first. When
|
||||||
|
in doubt contact us on [Matrix][matrix] or via opening an issue.
|
||||||
|
|
||||||
- if it is a bug, please provide a clear explanation of what happens, what should happen, and how to
|
### Windows
|
||||||
reproduce the issue, ideally by providing a minimal program exhibiting the problem
|
|
||||||
- if it is a feature request, please provide a clear argumentation about why you believe this feature
|
|
||||||
should be supported by winit
|
|
||||||
|
|
||||||
## Making a pull request
|
To run the examples on Windows, you must have symlinks enabled, see
|
||||||
|
[this][git-windows-symlinks].
|
||||||
|
|
||||||
When making a code contribution to winit, before opening your pull request, please make sure that:
|
[git-windows-symlinks]: https://gitforwindows.org/symbolic-links.html
|
||||||
|
|
||||||
- your patch builds with Winit's minimal supported rust version - Rust 1.70.
|
### Submitting your work and handling review
|
||||||
- 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
|
|
||||||
- you updated any relevant documentation in winit
|
|
||||||
- you left comments in your code explaining any part that is not straightforward, so that the
|
|
||||||
maintainers and future contributors don't have to try to guess what your code is supposed to do
|
|
||||||
- your PR adds an entry to the changelog file if the introduced change is relevant to winit users.
|
|
||||||
|
|
||||||
You needn't worry about the added entry causing conflicts, the maintainer that merges the PR will
|
All patches have to be sent on Github as [pull requests][prs]. To simplify your
|
||||||
handle those for you when merging (see below).
|
life during review it's recommended to check the "give contributors write access
|
||||||
- if your PR affects the platform compatibility of one or more features or adds another feature, the
|
to the branch" checkbox.
|
||||||
relevant sections in [`FEATURES.md`](https://github.com/rust-windowing/winit/blob/master/FEATURES.md#features)
|
|
||||||
should be updated.
|
|
||||||
|
|
||||||
Once your PR is open, you can ask for a review by a maintainer of your platform. Winit's merging policy
|
We use unstable Rustfmt options across the project, so please run
|
||||||
is that a PR must be approved by at least two maintainers of winit before being merged, including
|
`cargo +nightly fmt` before submitting your work. If you are unable to do so,
|
||||||
at least a maintainer of the platform (a maintainer making a PR themselves counts as approving it).
|
the maintainers can do it for you before merging, just state so in your pull
|
||||||
|
request description. For details on how to use nightly, consult [the
|
||||||
|
documentation][toolchains].
|
||||||
|
|
||||||
Once your PR is deemed ready, the merging maintainer will take care of resolving conflicts in
|
When editing markdown files (`.md`) they must be wrapped at 80 characters.
|
||||||
`CHANGELOG.md` (but you must resolve other conflicts yourself). Doing this requires that you check the
|
|
||||||
"give contributors write access to the branch" checkbox when creating the PR.
|
|
||||||
|
|
||||||
## Maintainers & Testers
|
[toolchains]: https://rust-lang.github.io/rustup/concepts/toolchains.html
|
||||||
|
|
||||||
The current maintainers are listed in the [CODEOWNERS](.github/CODEOWNERS) file.
|
#### Handling review
|
||||||
|
|
||||||
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!
|
During the review process certain events could require an action from your side,
|
||||||
|
common patterns and reactions are described below.
|
||||||
|
|
||||||
## Release process
|
_Event:_ The CI fails to build, but it looks like it is not your fault. Not
|
||||||
|
communicating so could result in maintainers not looking into your patch,
|
||||||
|
since they may assume that you're still working on it.\
|
||||||
|
_Desired behaviour:_ Write a message saying roughly the following "The CI
|
||||||
|
failure is unrelated", so that the maintainers will fix it for you.
|
||||||
|
|
||||||
|
_Event:_ Maintainer requested changes to your PR.\
|
||||||
|
_Desired behavior:_ Once you address the request, you should re-request a review
|
||||||
|
with GitHub's UI. If you don't agree with what maintainer suggested, you
|
||||||
|
should state your objections and re-request the review. That will indicate that
|
||||||
|
the ball is on maintainer's side.
|
||||||
|
|
||||||
|
_Event:_ You've opened a PR, but maintainer shortly after commented that they
|
||||||
|
want to work on that themselves.\
|
||||||
|
_Desired behavior:_ Discuss with the maintainer regarding their plans if they
|
||||||
|
were not outlined in the initial response, because such response means that they
|
||||||
|
are not interested in reviewing your code. Such thing could happen when
|
||||||
|
underestimating complexity of the task you're solving or when your patch
|
||||||
|
mandate certain downstream designs. In general, the maintainer will likely
|
||||||
|
close your PR in order to prevent work being done on it.
|
||||||
|
|
||||||
|
[prs]: https://github.com/rust-windowing/winit/pulls
|
||||||
|
[issues]: https://github.com/rust-windowing/winit/issues
|
||||||
|
[matrix]: https://matrix.to/#/#rust-windowing:matrix.org
|
||||||
|
|
||||||
|
## Maintainers
|
||||||
|
|
||||||
|
Winit has plenty of maintainers with different backgrounds, different time
|
||||||
|
available to work on Winit, and reasons to be winit maintainer in the first
|
||||||
|
place. To ensure that Winit's code quality does not decrease over time and to
|
||||||
|
make it easier to teach new maintainers the "winit way of doing things" the
|
||||||
|
common policies and routines are defined in this section.
|
||||||
|
|
||||||
|
The current maintainers for each platform are listed in [this file][CODEOWNERS].
|
||||||
|
|
||||||
|
### Contributions handling
|
||||||
|
|
||||||
|
The maintainers must ensure that the external contributions meet Winit's
|
||||||
|
quality standards. If it's not, it **is the maintainer's responsibility** to
|
||||||
|
bring it on par, which includes:
|
||||||
|
|
||||||
|
- Ensure that formatting is consistent and `CHANGELOG` messages are clear
|
||||||
|
for the end users.
|
||||||
|
- Improve the commit message, so it'll be easier for other maintainers to
|
||||||
|
understand the motivation without going through all the discussions on the
|
||||||
|
particular patch/PR.
|
||||||
|
- Ensure that the proposed patch doesn't break platform parity. If the
|
||||||
|
breakage is desired by contributor, an issue should be opened to discuss
|
||||||
|
with other maintainers before merging.
|
||||||
|
- Always fix CI issues before merging if they don't originate from the
|
||||||
|
submitted work.
|
||||||
|
|
||||||
|
However, maintainers should give some leeway for external contributors, so they
|
||||||
|
don't feel discouraged contributing, for example:
|
||||||
|
|
||||||
|
- Suggest a patch to resolve style issues, if it's the only issue with the
|
||||||
|
submitted work. Keep in mind that pushing the resolution yourself is not
|
||||||
|
desired, because the contributor might not agree with what you did.
|
||||||
|
- Be more explicit on how things should be done if you don't like the
|
||||||
|
approach.
|
||||||
|
- Suggest to finish the PR for them if they're absent for a while and you need
|
||||||
|
the proposed changes to move forward with something. In such cases the
|
||||||
|
maintainer must preserve attribution with `Co-authored-by`, `Suggested-by`,
|
||||||
|
or keep the original committer.
|
||||||
|
- Rebase their work for them when massive changes to the Winit codebase were
|
||||||
|
introduced.
|
||||||
|
|
||||||
|
When reviewing code of other maintainers all of the above is on the maintainer
|
||||||
|
who submitted the patch. Interested maintainers could help push the work over
|
||||||
|
the finish line, but teaching other maintainers should be preferred.
|
||||||
|
|
||||||
|
For a _regular_ contributor to winit, the maintainer should slowly start
|
||||||
|
requiring contributor to match *maintainer* quality standards when writing
|
||||||
|
patches and commit messages.
|
||||||
|
|
||||||
|
### Contributing
|
||||||
|
|
||||||
|
When submitting a patch, the maintainer should follow the general contributing
|
||||||
|
guidelines, however greater attention to detail is expected in this case.
|
||||||
|
|
||||||
|
To make life simpler for other maintainers it's suggested to create your branch
|
||||||
|
under the project repository instead of your own fork. The naming scheme is
|
||||||
|
`github_user_name/branch_name`. Doing so will make your work easier to rebase
|
||||||
|
for other maintainers when you're absent.
|
||||||
|
|
||||||
|
### Administrative Actions
|
||||||
|
|
||||||
|
Some things (such as changing required CI steps, adding contributors, ...)
|
||||||
|
require administrative permissions. If you don't have those, ask about the
|
||||||
|
change in an issue. If you have the permissions, discuss it with at least one
|
||||||
|
other admin before making the change.
|
||||||
|
|
||||||
|
### Release process
|
||||||
|
|
||||||
Given that winit is a widely used library, we should be able to make a patch
|
Given that winit is a widely used library, we should be able to make a patch
|
||||||
releases at any time we want without blocking the development of new features.
|
releases at any time we want without blocking the development of new features.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
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. Update released `cfg_attr` in `src/changelog/mod.rs` to `v0.2.md`
|
||||||
4. The new commit in the branch is tagged `v0.2.0`
|
4. Move entries from `src/changelog/unreleased.md` into
|
||||||
5. The version is pushed to crates.io
|
`src/changelog/v0.2.md`
|
||||||
6. A GitHub release is created for the `v0.2.0` tag
|
5. In the branch, the version is bumped to `v0.2.0`
|
||||||
7. On master, the version is bumped to `0.2.0`, and the CHANGELOG is updated
|
6. The new commit in the branch is tagged `v0.2.0`
|
||||||
|
7. The version is pushed to crates.io
|
||||||
|
8. A GitHub release is created for the `v0.2.0` tag
|
||||||
|
9. 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 4-9 of the regular release example
|
||||||
|
|
||||||
|
[CODEOWNERS]: .github/CODEOWNERS
|
||||||
|
|||||||
104
Cargo.toml
@@ -1,16 +1,104 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
default-members = ["winit"]
|
||||||
"run-wasm",
|
members = ["dpi", "winit*"]
|
||||||
"winit",
|
|
||||||
"winit-core"
|
|
||||||
]
|
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
||||||
|
[workspace.package]
|
||||||
|
edition = "2021"
|
||||||
|
license = "Apache-2.0"
|
||||||
|
repository = "https://github.com/rust-windowing/winit"
|
||||||
|
rust-version = "1.80"
|
||||||
|
version = "0.30.12"
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
|
# Workspace dependencies.
|
||||||
|
# `winit` has no version here to allow using it in dev deps for docs.
|
||||||
|
winit = { path = "winit" }
|
||||||
|
winit-android = { version = "0.30.12", path = "winit-android" }
|
||||||
|
winit-appkit = { version = "0.30.12", path = "winit-appkit" }
|
||||||
|
winit-common = { version = "0.30.12", path = "winit-common" }
|
||||||
|
winit-core = { version = "0.30.12", path = "winit-core" }
|
||||||
|
winit-orbital = { version = "0.30.12", path = "winit-orbital" }
|
||||||
|
winit-uikit = { version = "0.30.12", path = "winit-uikit" }
|
||||||
|
winit-wayland = { version = "0.30.12", path = "winit-wayland", default-features = false }
|
||||||
|
winit-web = { version = "0.30.12", path = "winit-web" }
|
||||||
|
winit-win32 = { version = "0.30.12", path = "winit-win32" }
|
||||||
|
winit-x11 = { version = "0.30.12", path = "winit-x11" }
|
||||||
|
|
||||||
|
# Core dependencies.
|
||||||
bitflags = "2"
|
bitflags = "2"
|
||||||
cfg_aliases = "0.2.0"
|
cfg_aliases = "0.2.1"
|
||||||
cursor-icon = "1.1.0"
|
cursor-icon = "1.1.0"
|
||||||
|
dpi = { version = "0.1.2", path = "dpi" }
|
||||||
|
keyboard-types = "0.8.0"
|
||||||
|
mint = "0.5.6"
|
||||||
|
rwh_06 = { package = "raw-window-handle", version = "0.6", features = ["std"] }
|
||||||
serde = { version = "1", features = ["serde_derive"] }
|
serde = { version = "1", features = ["serde_derive"] }
|
||||||
smol_str = "0.2.0"
|
smol_str = "0.3"
|
||||||
|
tracing = { version = "0.1.40", default-features = false }
|
||||||
|
|
||||||
|
# Dev dependencies.
|
||||||
|
image = { version = "0.25.0", default-features = false }
|
||||||
|
softbuffer = { version = "0.4.6", default-features = false, features = [
|
||||||
|
"x11",
|
||||||
|
"x11-dlopen",
|
||||||
|
"wayland",
|
||||||
|
"wayland-dlopen",
|
||||||
|
] }
|
||||||
|
tracing-subscriber = "0.3.18"
|
||||||
|
|
||||||
|
# Android dependencies.
|
||||||
|
android-activity = "0.6.0"
|
||||||
|
ndk = { version = "0.9.0", features = ["rwh_06"], default-features = false }
|
||||||
|
|
||||||
|
# Apple dependencies.
|
||||||
|
block2 = "0.6.1"
|
||||||
|
dispatch2 = { version = "0.3.0", default-features = false, features = ["std", "objc2"] }
|
||||||
|
objc2 = { version = "0.6.1", features = ["relax-sign-encoding"] }
|
||||||
|
objc2-app-kit = { version = "0.3.1", default-features = false }
|
||||||
|
objc2-core-foundation = { version = "0.3.1", default-features = false }
|
||||||
|
objc2-core-graphics = { version = "0.3.1", default-features = false }
|
||||||
|
objc2-core-video = { version = "0.3.1", default-features = false }
|
||||||
|
objc2-foundation = { version = "0.3.1", default-features = false }
|
||||||
|
objc2-ui-kit = { version = "0.3.1", default-features = false }
|
||||||
|
|
||||||
|
# Windows dependencies.
|
||||||
|
unicode-segmentation = "1.7.1"
|
||||||
|
windows-sys = "0.59.0"
|
||||||
|
|
||||||
|
# Linux dependencies.
|
||||||
|
ahash = { version = "0.8.7", features = ["no-rng"] }
|
||||||
|
bytemuck = { version = "1.13.1", default-features = false }
|
||||||
|
calloop = "0.13.0"
|
||||||
|
libc = "0.2.64"
|
||||||
|
memmap2 = "0.9.0"
|
||||||
|
percent-encoding = "2.0"
|
||||||
|
rustix = { version = "1.0.7", default-features = false }
|
||||||
|
sctk = { package = "smithay-client-toolkit", version = "0.19.2", default-features = false, features = [
|
||||||
|
"calloop",
|
||||||
|
] }
|
||||||
|
sctk-adwaita = { version = "0.10.1", default-features = false }
|
||||||
|
wayland-backend = { version = "0.3.10", default-features = false, features = ["client_system"] }
|
||||||
|
wayland-client = "0.31.10"
|
||||||
|
wayland-protocols = { version = "0.32.8", features = ["staging"] }
|
||||||
|
wayland-protocols-plasma = { version = "0.3.8", features = ["client"] }
|
||||||
|
x11-dl = "2.19.1"
|
||||||
|
x11rb = { version = "0.13.0", default-features = false }
|
||||||
|
xkbcommon-dl = "0.4.2"
|
||||||
|
|
||||||
|
# Orbital dependencies.
|
||||||
|
orbclient = { version = "0.3.47", default-features = false }
|
||||||
|
redox_syscall = "0.5.7"
|
||||||
|
|
||||||
|
# Web dependencies.
|
||||||
|
atomic-waker = "1"
|
||||||
|
concurrent-queue = { version = "2", default-features = false }
|
||||||
|
console_error_panic_hook = "0.1"
|
||||||
|
js-sys = "0.3.70"
|
||||||
|
pin-project = "1"
|
||||||
|
tracing-web = "0.1"
|
||||||
|
wasm-bindgen = "0.2.93"
|
||||||
|
wasm-bindgen-futures = "0.4.43"
|
||||||
|
wasm-bindgen-test = "0.3"
|
||||||
web-time = "1"
|
web-time = "1"
|
||||||
winit-core = { path = "./winit-core", default-features = false, features = ["std"] }
|
web_sys = { package = "web-sys", version = "0.3.70" }
|
||||||
|
|||||||
210
FEATURES.md
@@ -3,8 +3,8 @@
|
|||||||
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
|
||||||
- macOS 10.7+ (10.14+ is tested regularly)
|
- macOS
|
||||||
- Unix
|
- Unix
|
||||||
- via X11
|
- via X11
|
||||||
- via Wayland
|
- via Wayland
|
||||||
@@ -13,9 +13,6 @@ be used to create both games and applications. It supports the following main gr
|
|||||||
- iOS
|
- iOS
|
||||||
- Android
|
- Android
|
||||||
- Web
|
- Web
|
||||||
- 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
|
||||||
@@ -50,206 +47,3 @@ through the implementation work necessary to function on all platforms. When one
|
|||||||
gets implemented across all platforms, a PR can be opened to upgrade the feature to a core feature.
|
gets implemented across all platforms, a PR can be opened to upgrade the feature to a core feature.
|
||||||
If that gets accepted, the platform-specific functions get deprecated and become permanently
|
If that gets accepted, the platform-specific functions get deprecated and become permanently
|
||||||
exposed through the core, cross-platform API.
|
exposed through the core, cross-platform API.
|
||||||
|
|
||||||
# Features
|
|
||||||
|
|
||||||
## Extending this section
|
|
||||||
|
|
||||||
If your PR makes notable changes to Winit's features, please update this section as follows:
|
|
||||||
|
|
||||||
- If your PR adds a new feature, add a brief description to the relevant section. If the feature is a core
|
|
||||||
feature, add a row to the feature matrix and describe what platforms the feature has been implemented on.
|
|
||||||
|
|
||||||
- If your PR begins a new API rework, add a row to the `Pending API Reworks` table. If the PR implements the
|
|
||||||
API rework on all relevant platforms, please move it to the `Completed API Reworks` table.
|
|
||||||
|
|
||||||
- If your PR implements an already-existing feature on a new platform, either mark the feature as *completed*,
|
|
||||||
or mark it as *mostly completed* and link to an issue describing the problems with the implementation.
|
|
||||||
|
|
||||||
## Core
|
|
||||||
|
|
||||||
### Windowing
|
|
||||||
- **Window initialization**: Winit allows the creation of a window
|
|
||||||
- **Providing pointer to init OpenGL**: Winit provides the necessary pointers to initialize a working opengl context
|
|
||||||
- **Providing pointer to init Vulkan**: Same as OpenGL but for Vulkan
|
|
||||||
- **Window decorations**: The windows created by winit are properly decorated, and the decorations can
|
|
||||||
be deactivated
|
|
||||||
- **Window decorations toggle**: Decorations can be turned on or off after window creation
|
|
||||||
- **Window resizing**: The windows created by winit can be resized and generate the appropriate events
|
|
||||||
when they are. The application can precisely control its window size if desired.
|
|
||||||
- **Window resize increments**: When the window gets resized, the application can choose to snap the window's
|
|
||||||
size to specific values.
|
|
||||||
- **Window transparency**: Winit allows the creation of windows with a transparent background.
|
|
||||||
- **Window maximization**: The windows created by winit can be maximized upon creation.
|
|
||||||
- **Window maximization toggle**: The windows created by winit can be maximized and unmaximized after
|
|
||||||
creation.
|
|
||||||
- **Window minimization**: The windows created by winit can be minimized after creation.
|
|
||||||
- **Fullscreen**: The windows created by winit can be put into fullscreen mode.
|
|
||||||
- **Fullscreen toggle**: The windows created by winit can be switched to and from fullscreen after
|
|
||||||
creation.
|
|
||||||
- **Exclusive fullscreen**: Winit allows changing the video mode of the monitor
|
|
||||||
for fullscreen windows and, if applicable, captures the monitor for exclusive
|
|
||||||
use by this application.
|
|
||||||
- **HiDPI support**: Winit assists developers in appropriately scaling HiDPI content.
|
|
||||||
- **Popup / modal windows**: Windows can be created relative to the client area of other windows, and parent
|
|
||||||
windows can be disabled in favor of popup windows. This feature also guarantees that popup windows
|
|
||||||
get drawn above their owner.
|
|
||||||
|
|
||||||
|
|
||||||
### System Information
|
|
||||||
- **Monitor list**: Retrieve the list of monitors and their metadata, including which one is primary.
|
|
||||||
- **Video mode query**: Monitors can be queried for their supported fullscreen video modes (consisting of resolution, refresh rate, and bit depth).
|
|
||||||
|
|
||||||
### Input Handling
|
|
||||||
- **Mouse events**: Generating mouse events associated with pointer motion, click, and scrolling events.
|
|
||||||
- **Mouse set location**: Forcibly changing the location of the pointer.
|
|
||||||
- **Cursor locking**: Locking the cursor inside the window so it cannot move.
|
|
||||||
- **Cursor confining**: Confining the cursor to the window bounds so it cannot leave them.
|
|
||||||
- **Cursor icon**: Changing the cursor icon or hiding the cursor.
|
|
||||||
- **Cursor image**: Changing the cursor to your own image.
|
|
||||||
- **Cursor hittest**: Handle or ignore mouse events for a window.
|
|
||||||
- **Touch events**: Single-touch events.
|
|
||||||
- **Touch pressure**: Touch events contain information about the amount of force being applied.
|
|
||||||
- **Multitouch**: Multi-touch events, including cancellation of a gesture.
|
|
||||||
- **Keyboard events**: Properly processing keyboard events using the user-specified keymap and
|
|
||||||
translating keypresses into UTF-8 characters, handling dead keys and IMEs.
|
|
||||||
- **Drag & Drop**: Dragging content into winit, detecting when content enters, drops, or if the drop is cancelled.
|
|
||||||
- **Raw Device Events**: Capturing input from input devices without any OS filtering.
|
|
||||||
- **Gamepad/Joystick events**: Capturing input from gamepads and joysticks.
|
|
||||||
- **Device movement events**: Capturing input from the device gyroscope and accelerometer.
|
|
||||||
|
|
||||||
## Platform
|
|
||||||
### Windows
|
|
||||||
* Setting the name of the internal window class
|
|
||||||
* Setting the taskbar icon
|
|
||||||
* Setting the parent window
|
|
||||||
* Setting a menu bar
|
|
||||||
* `WS_EX_NOREDIRECTIONBITMAP` support
|
|
||||||
* Theme the title bar according to Windows 10 Dark Mode setting or set a preferred theme
|
|
||||||
* Changing a system-drawn backdrop
|
|
||||||
* Setting the window border color
|
|
||||||
* Setting the title bar background color
|
|
||||||
* Setting the title color
|
|
||||||
* Setting the corner rounding preference
|
|
||||||
|
|
||||||
### macOS
|
|
||||||
* Window activation policy
|
|
||||||
* Window movable by background
|
|
||||||
* Transparent titlebar
|
|
||||||
* Hidden titlebar
|
|
||||||
* Hidden titlebar buttons
|
|
||||||
* Full-size content view
|
|
||||||
* Accepts first mouse
|
|
||||||
* Set a preferred theme and get current theme.
|
|
||||||
|
|
||||||
### Unix
|
|
||||||
* Window urgency
|
|
||||||
* X11 Window Class
|
|
||||||
* X11 Override Redirect Flag
|
|
||||||
* GTK Theme Variant
|
|
||||||
* Base window size
|
|
||||||
* Setting the X11 parent window
|
|
||||||
|
|
||||||
### iOS
|
|
||||||
* `winit` has a minimum OS requirement of iOS 8
|
|
||||||
* Get the `UIScreen` object pointer
|
|
||||||
* Setting the `UIView` hidpi factor
|
|
||||||
* Valid orientations
|
|
||||||
* Home indicator visibility
|
|
||||||
* Status bar visibility and style
|
|
||||||
* Deferring system gestures
|
|
||||||
* Getting the device idiom
|
|
||||||
* Getting the preferred video mode
|
|
||||||
|
|
||||||
### Web
|
|
||||||
* Get if the systems preferred color scheme is "dark"
|
|
||||||
|
|
||||||
## Usability
|
|
||||||
* `serde`: Enables serialization/deserialization of certain types with Serde. (Maintainer: @Osspial)
|
|
||||||
|
|
||||||
## Compatibility Matrix
|
|
||||||
|
|
||||||
Legend:
|
|
||||||
|
|
||||||
- ✔️: Works as intended
|
|
||||||
- ▢: Mostly works, but some bugs are known
|
|
||||||
- ❌: Missing feature or large bugs making it unusable
|
|
||||||
- **N/A**: Not applicable for this platform
|
|
||||||
- ❓: Unknown status
|
|
||||||
|
|
||||||
### Windowing
|
|
||||||
|Feature |Windows|MacOS |Linux x11 |Linux Wayland |Android|iOS |Web |Redox OS|
|
|
||||||
|-------------------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
|
||||||
|Window initialization |✔️ |✔️ |▢[#5] |✔️ |▢[#33]|▢[#33] |✔️ |✔️ |
|
|
||||||
|Providing pointer to init OpenGL |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |
|
|
||||||
|Providing pointer to init Vulkan |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |**N/A**|**N/A** |
|
|
||||||
|Window decorations |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|✔️ |
|
|
||||||
|Window decorations toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
|
||||||
|Window resizing |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |✔️ |
|
|
||||||
|Window resize increments |❌ |✔️ |✔️ |❌ |**N/A**|**N/A**|**N/A**|**N/A** |
|
|
||||||
|Window transparency |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|N/A |✔️ |
|
|
||||||
|Window blur |❌ |❌ |❌ |✔️ |**N/A**|**N/A**|N/A |❌ |
|
|
||||||
|Window maximization |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
|
||||||
|Window maximization toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
|
||||||
|Window minimization |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
|
||||||
|Fullscreen |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |✔️ |**N/A** |
|
|
||||||
|Fullscreen toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |✔️ |**N/A** |
|
|
||||||
|Exclusive fullscreen |✔️ |✔️ |✔️ |**N/A** |❌ |✔️ |**N/A**|**N/A** |
|
|
||||||
|HiDPI support |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |
|
|
||||||
|Popup windows |❌ |❌ |❌ |❌ |❌ |❌ |**N/A**|**N/A** |
|
|
||||||
|
|
||||||
### System information
|
|
||||||
|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
|
||||||
|---------------- | ----- | ---- | ------- | ----------- | ----- | ------- | -------- | ------ |
|
|
||||||
|Monitor list |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|❌ |
|
|
||||||
|Video mode query |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|❌ |
|
|
||||||
|
|
||||||
### Input handling
|
|
||||||
|Feature |Windows |MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
|
||||||
|----------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
|
||||||
|Mouse events |✔️ |▢[#63] |✔️ |✔️ |**N/A**|**N/A**|✔️ |✔️ |
|
|
||||||
|Mouse set location |✔️ |✔️ |✔️ |✔️(when locked) |**N/A**|**N/A**|**N/A**|**N/A** |
|
|
||||||
|Cursor locking |❌ |✔️ |❌ |✔️ |**N/A**|**N/A**|✔️ |❌ |
|
|
||||||
|Cursor confining |✔️ |❌ |✔️ |✔️ |**N/A**|**N/A**|❌ |❌ |
|
|
||||||
|Cursor icon |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |**N/A** |
|
|
||||||
|Cursor image |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |**N/A** |
|
|
||||||
|Cursor hittest |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|❌ |❌ |
|
|
||||||
|Touch events |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A** |
|
|
||||||
|Touch pressure |✔️ |❌ |❌ |❌ |❌ |✔️ |✔️ |**N/A** |
|
|
||||||
|Multitouch |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |❌ |**N/A** |
|
|
||||||
|Keyboard events |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |✔️ |✔️ |
|
|
||||||
|Drag & Drop |▢[#720] |▢[#720] |▢[#720] |▢[#720] |**N/A**|**N/A**|❓ |**N/A** |
|
|
||||||
|Raw Device Events |▢[#750] |▢[#750] |▢[#750] |❌ |❌ |❌ |❓ |**N/A** |
|
|
||||||
|Gamepad/Joystick events |❌[#804] |❌ |❌ |❌ |❌ |❌ |❓ |**N/A** |
|
|
||||||
|Device movement events |❓ |❓ |❓ |❓ |❌ |❌ |❓ |**N/A** |
|
|
||||||
|Drag window with cursor |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A** |**N/A** |
|
|
||||||
|Resize with cursor |✔️ |❌ |✔️ |✔️ |**N/A**|**N/A**|**N/A** |**N/A** |
|
|
||||||
|
|
||||||
### Pending API Reworks
|
|
||||||
Changes in the API that have been agreed upon but aren't implemented across all platforms.
|
|
||||||
|
|
||||||
|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
|
||||||
|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
|
||||||
|New API for HiDPI ([#315] [#319]) |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |❓ |
|
|
||||||
|Event Loop 2.0 ([#459]) |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |✔️ |
|
|
||||||
|Keyboard Input 2.0 ([#753]) |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |✔️ |✔️ |
|
|
||||||
|
|
||||||
### Completed API Reworks
|
|
||||||
|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
|
||||||
|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
|
||||||
|
|
||||||
[#165]: https://github.com/rust-windowing/winit/issues/165
|
|
||||||
[#219]: https://github.com/rust-windowing/winit/issues/219
|
|
||||||
[#242]: https://github.com/rust-windowing/winit/issues/242
|
|
||||||
[#306]: https://github.com/rust-windowing/winit/issues/306
|
|
||||||
[#315]: https://github.com/rust-windowing/winit/issues/315
|
|
||||||
[#319]: https://github.com/rust-windowing/winit/issues/319
|
|
||||||
[#33]: https://github.com/rust-windowing/winit/issues/33
|
|
||||||
[#459]: https://github.com/rust-windowing/winit/issues/459
|
|
||||||
[#5]: https://github.com/rust-windowing/winit/issues/5
|
|
||||||
[#63]: https://github.com/rust-windowing/winit/issues/63
|
|
||||||
[#720]: https://github.com/rust-windowing/winit/issues/720
|
|
||||||
[#721]: https://github.com/rust-windowing/winit/issues/721
|
|
||||||
[#750]: https://github.com/rust-windowing/winit/issues/750
|
|
||||||
[#753]: https://github.com/rust-windowing/winit/issues/753
|
|
||||||
[#804]: https://github.com/rust-windowing/winit/issues/804
|
|
||||||
|
|||||||
141
README.md
@@ -2,13 +2,13 @@
|
|||||||
|
|
||||||
[](https://crates.io/crates/winit)
|
[](https://crates.io/crates/winit)
|
||||||
[](https://docs.rs/winit)
|
[](https://docs.rs/winit)
|
||||||
[](https://rust-windowing.github.io/winit/winit/index.html)
|
)](https://rust-windowing.github.io/winit/winit/index.html)
|
||||||
[](https://github.com/rust-windowing/winit/actions)
|
[](https://github.com/rust-windowing/winit/actions)
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[dependencies]
|
[dependencies]
|
||||||
winit = "0.29.10"
|
winit = "0.30.12"
|
||||||
```
|
```
|
||||||
|
|
||||||
## [Documentation](https://docs.rs/winit)
|
## [Documentation](https://docs.rs/winit)
|
||||||
@@ -19,9 +19,9 @@ For features _outside_ the scope of winit, see [Are we GUI Yet?](https://arewegu
|
|||||||
|
|
||||||
## Contact Us
|
## Contact Us
|
||||||
|
|
||||||
Join us in our [](https://matrix.to/#/#rust-windowing:matrix.org) room. If you don't get an answer there, try [](https://web.libera.chat/#winit).
|
Join us in our [](https://matrix.to/#/#rust-windowing:matrix.org) room.
|
||||||
|
|
||||||
The maintainers have a meeting every friday at UTC 14. The meeting notes can be found [here](https://hackmd.io/@winit-meetings).
|
The maintainers have a meeting every friday at UTC 15. The meeting notes can be found [here](https://hackmd.io/@winit-meetings).
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
@@ -33,17 +33,13 @@ Winit is designed to be a low-level brick in a hierarchy of libraries. Consequen
|
|||||||
show something on the window you need to use the platform-specific getters provided by winit, or
|
show something on the window you need to use the platform-specific getters provided by winit, or
|
||||||
another library.
|
another library.
|
||||||
|
|
||||||
### Cargo Features
|
## CONTRIBUTING
|
||||||
|
|
||||||
Winit provides the following features, which can be enabled in your `Cargo.toml` file:
|
For contributing guidelines see [CONTRIBUTING.md](./CONTRIBUTING.md).
|
||||||
* `serde`: Enables serialization/deserialization of certain types with [Serde](https://crates.io/crates/serde).
|
|
||||||
* `x11` (enabled by default): On Unix platform, compiles with the X11 backend
|
|
||||||
* `wayland` (enabled by default): On Unix platform, compiles with the Wayland backend
|
|
||||||
* `mint`: Enables mint (math interoperability standard types) conversions.
|
|
||||||
|
|
||||||
## MSRV Policy
|
## MSRV Policy
|
||||||
|
|
||||||
This crate's Minimum Supported Rust Version (MSRV) is **1.70**. Changes to
|
This crate's Minimum Supported Rust Version (MSRV) is **1.80**. Changes to
|
||||||
the MSRV will be accompanied by a minor version bump.
|
the MSRV will be accompanied by a minor version bump.
|
||||||
|
|
||||||
As a **tentative** policy, the upper bound of the MSRV is given by the following
|
As a **tentative** policy, the upper bound of the MSRV is given by the following
|
||||||
@@ -58,12 +54,15 @@ Where `sid` is the current version of `rustc` provided by [Debian Sid], and
|
|||||||
|
|
||||||
[Debian Sid]: https://packages.debian.org/sid/rustc
|
[Debian Sid]: https://packages.debian.org/sid/rustc
|
||||||
|
|
||||||
The exception is for the Android platform, where a higher Rust version
|
An exception is made for the Android platform, where a higher Rust version
|
||||||
must be used for certain Android features. In this case, the MSRV will be
|
must be used for certain Android features. In this case, the MSRV will be
|
||||||
capped at the latest stable version of Rust minus three. This inconsistency is
|
capped at the latest stable version of Rust minus three. This inconsistency is
|
||||||
not reflected in Cargo metadata, as it is not powerful enough to expose this
|
not reflected in Cargo metadata, as it is not powerful enough to expose this
|
||||||
restriction.
|
restriction.
|
||||||
|
|
||||||
|
Redox OS is also not covered by this MSRV policy, as it requires a Rust nightly
|
||||||
|
toolchain to compile.
|
||||||
|
|
||||||
All crates in the [`rust-windowing`] organizations have the
|
All crates in the [`rust-windowing`] organizations have the
|
||||||
same MSRV policy.
|
same MSRV policy.
|
||||||
|
|
||||||
@@ -71,118 +70,10 @@ same MSRV policy.
|
|||||||
|
|
||||||
### Platform-specific usage
|
### Platform-specific usage
|
||||||
|
|
||||||
#### Wayland
|
Check out the [`winit::platform`](https://docs.rs/winit/latest/winit/platform/index.html) module for platform-specific usage.
|
||||||
|
|
||||||
Note that windows don't appear on Wayland until you draw/present to them.
|
### Repository License
|
||||||
|
|
||||||
#### Web
|
Note that the license in `LICENSE` doesn't apply in full to the DPI package [./dpi](./dpi).
|
||||||
|
Full details can be found in that folder's README.
|
||||||
To run the web example: `cargo run-wasm --example web`
|
<!-- This doesn't apply to users of the Winit crate, but this is also the repository level README -->
|
||||||
|
|
||||||
Winit supports compiling to the `wasm32-unknown-unknown` target with `web-sys`.
|
|
||||||
|
|
||||||
On the web platform, a Winit window is backed by a `<canvas>` element. You can
|
|
||||||
either [provide Winit with a `<canvas>` element][web with_canvas], or [let Winit
|
|
||||||
create a `<canvas>` element which you can then retrieve][web canvas getter] and
|
|
||||||
insert it into the DOM yourself.
|
|
||||||
|
|
||||||
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
|
|
||||||
book].
|
|
||||||
|
|
||||||
[web with_canvas]: https://docs.rs/winit/latest/wasm32-unknown-unknown/winit/platform/web/trait.WindowBuilderExtWebSys.html#tymethod.with_canvas
|
|
||||||
[web canvas getter]: https://docs.rs/winit/latest/wasm32-unknown-unknown/winit/platform/web/trait.WindowExtWebSys.html#tymethod.canvas
|
|
||||||
[web example]: ./examples/web.rs
|
|
||||||
[Rust and WebAssembly book]: https://rustwasm.github.io/book/
|
|
||||||
|
|
||||||
#### Android
|
|
||||||
|
|
||||||
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
|
|
||||||
for defining the main entry point for your Rust application as well as tracking
|
|
||||||
various life-cycle events and synchronizing with the main JVM thread.
|
|
||||||
|
|
||||||
Winit uses the [android-activity](https://github.com/rib/android-activity) as a
|
|
||||||
glue crate (prior to `0.28` it used
|
|
||||||
[ndk-glue](https://github.com/rust-windowing/android-ndk-rs/tree/master/ndk-glue)).
|
|
||||||
|
|
||||||
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
|
|
||||||
application's main entry point. If Cargo resolves multiple versions, they will
|
|
||||||
clash.
|
|
||||||
|
|
||||||
`winit` glue compatibility table:
|
|
||||||
|
|
||||||
| winit | ndk-glue |
|
|
||||||
| :---: | :--------------------------: |
|
|
||||||
| 0.29 | `android-activity = "0.5"` |
|
|
||||||
| 0.28 | `android-activity = "0.4"` |
|
|
||||||
| 0.27 | `ndk-glue = "0.7"` |
|
|
||||||
| 0.26 | `ndk-glue = "0.5"` |
|
|
||||||
| 0.25 | `ndk-glue = "0.3"` |
|
|
||||||
| 0.24 | `ndk-glue = "0.2"` |
|
|
||||||
|
|
||||||
The recommended way to avoid a conflict with the glue version is to avoid explicitly
|
|
||||||
depending on the `android-activity` crate, and instead consume the API that
|
|
||||||
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:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[lib]
|
|
||||||
name = "main"
|
|
||||||
crate-type = ["cdylib"]
|
|
||||||
```
|
|
||||||
|
|
||||||
All Android applications are based on an `Activity` subclass, and the
|
|
||||||
`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:
|
|
||||||
|
|
||||||
| 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.|
|
|
||||||
| [`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
|
|
||||||
[`GameTextInput`]: https://developer.android.com/games/agdk/add-support-for-text-input
|
|
||||||
[`AndroidAppCompat`]: https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity
|
|
||||||
[agdk_jetpack]: https://developer.android.com/jetpack/androidx/releases/games
|
|
||||||
[agdk_releases]: https://developer.android.com/games/agdk/download#agdk-libraries
|
|
||||||
[Gradle]: https://developer.android.com/studio/build
|
|
||||||
|
|
||||||
For more details, refer to these `android-activity` [example applications](https://github.com/rust-mobile/android-activity/tree/main/examples).
|
|
||||||
|
|
||||||
##### 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:
|
|
||||||
1. Remove `ndk-glue` from your `Cargo.toml`
|
|
||||||
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).
|
|
||||||
4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your event loop (as shown above).
|
|
||||||
|
|
||||||
#### MacOS
|
|
||||||
|
|
||||||
A lot of functionality expects the application to be ready before you start
|
|
||||||
doing anything; this includes creating windows, fetching monitors, drawing,
|
|
||||||
and so on, see issues [#2238], [#2051] and [#2087].
|
|
||||||
|
|
||||||
If you encounter problems, you should try doing your initialization inside
|
|
||||||
`Event::Resumed`.
|
|
||||||
|
|
||||||
#### iOS
|
|
||||||
|
|
||||||
Similar to macOS, iOS's main `UIApplicationMain` does some init work that's required
|
|
||||||
by all UI-related code (see issue [#1705]). It would be best to consider creating your windows
|
|
||||||
inside `Event::Resumed`.
|
|
||||||
|
|
||||||
|
|
||||||
[#2238]: https://github.com/rust-windowing/winit/issues/2238
|
|
||||||
[#2051]: https://github.com/rust-windowing/winit/issues/2051
|
|
||||||
[#2087]: https://github.com/rust-windowing/winit/issues/2087
|
|
||||||
[#1705]: https://github.com/rust-windowing/winit/issues/1705
|
|
||||||
|
|
||||||
#### Redox OS
|
|
||||||
|
|
||||||
Redox OS has some functionality not yet present that will be implemented when
|
|
||||||
its orbital display server provides it.
|
|
||||||
|
|||||||
28
clippy.toml
@@ -1,15 +1,17 @@
|
|||||||
|
# Using allow-invalid because this is platform-specific code
|
||||||
disallowed-methods = [
|
disallowed-methods = [
|
||||||
{ path = "web_sys::window", reason = "is not available in every context" },
|
{ allow-invalid = true, path = "objc2_app_kit::NSView::visibleRect", reason = "We expose a render target to the user, and visibility is not really relevant to that (and can break if you don't use the rectangle position as well). Use `frame` instead." },
|
||||||
{ path = "web_sys::HtmlCanvasElement::width", reason = "Winit shouldn't touch the internal canvas size" },
|
{ allow-invalid = true, path = "objc2_app_kit::NSWindow::setFrameTopLeftPoint", reason = "Not sufficient when working with Winit's coordinate system, use `flip_window_screen_coordinates` instead" },
|
||||||
{ path = "web_sys::HtmlCanvasElement::height", reason = "Winit shouldn't touch the internal canvas size" },
|
{ allow-invalid = true, path = "web_sys::Document::exit_fullscreen", reason = "Doesn't account for compatibility with Safari" },
|
||||||
{ path = "web_sys::HtmlCanvasElement::set_width", reason = "Winit shouldn't touch the internal canvas size" },
|
{ allow-invalid = true, path = "web_sys::Document::fullscreen_element", reason = "Doesn't account for compatibility with Safari" },
|
||||||
{ path = "web_sys::HtmlCanvasElement::set_height", reason = "Winit shouldn't touch the internal canvas size" },
|
{ allow-invalid = true, path = "web_sys::Element::request_fullscreen", reason = "Doesn't account for compatibility with Safari" },
|
||||||
{ path = "web_sys::Window::document", reason = "cache this to reduce calls to JS" },
|
{ allow-invalid = true, path = "web_sys::HtmlCanvasElement::height", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
{ path = "web_sys::Window::get_computed_style", reason = "cache this to reduce calls to JS" },
|
{ allow-invalid = true, path = "web_sys::HtmlCanvasElement::set_height", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
{ path = "web_sys::HtmlElement::style", reason = "cache this to reduce calls to JS" },
|
{ allow-invalid = true, path = "web_sys::HtmlCanvasElement::set_width", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
{ path = "web_sys::Element::request_fullscreen", reason = "Doesn't account for compatibility with Safari" },
|
{ allow-invalid = true, path = "web_sys::HtmlCanvasElement::width", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
{ path = "web_sys::Document::exit_fullscreen", reason = "Doesn't account for compatibility with Safari" },
|
{ allow-invalid = true, path = "web_sys::HtmlElement::style", reason = "cache this to reduce calls to JS" },
|
||||||
{ path = "web_sys::Document::fullscreen_element", reason = "Doesn't account for compatibility with Safari" },
|
{ allow-invalid = true, path = "web_sys::Window::document", reason = "cache this to reduce calls to JS" },
|
||||||
{ 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." },
|
{ allow-invalid = true, path = "web_sys::Window::get_computed_style", reason = "cache this to reduce calls to JS" },
|
||||||
{ path = "icrate::AppKit::NSWindow::setFrameTopLeftPoint", reason = "Not sufficient when working with Winit's coordinate system, use `flip_window_screen_coordinates` instead" },
|
{ allow-invalid = true, path = "web_sys::Window::navigator", reason = "cache this to reduce calls to JS" },
|
||||||
|
{ allow-invalid = true, path = "web_sys::window", reason = "is not available in every context" },
|
||||||
]
|
]
|
||||||
|
|||||||
93
deny.toml
@@ -1,15 +1,21 @@
|
|||||||
# https://embarkstudios.github.io/cargo-deny/
|
# https://embarkstudios.github.io/cargo-deny
|
||||||
# cargo install cargo-deny
|
# cargo install cargo-deny
|
||||||
# cargo update && cargo deny --all-features --log-level error --target aarch64-apple-ios check
|
# cargo update && cargo deny --target aarch64-apple-ios check
|
||||||
# Note: running just `cargo deny check` without a `--target` will result in
|
# Note: running just `cargo deny check` without a `--target` will result in
|
||||||
# false positives due to https://github.com/EmbarkStudios/cargo-deny/issues/324
|
# false positives due to https://github.com/EmbarkStudios/cargo-deny/issues/324
|
||||||
|
[graph]
|
||||||
|
all-features = true
|
||||||
|
exclude-dev = true
|
||||||
targets = [
|
targets = [
|
||||||
|
{ triple = "aarch64-apple-darwin" },
|
||||||
{ triple = "aarch64-apple-ios" },
|
{ triple = "aarch64-apple-ios" },
|
||||||
{ triple = "aarch64-linux-android" },
|
{ triple = "aarch64-linux-android" },
|
||||||
{ triple = "i686-pc-windows-gnu" },
|
{ triple = "i686-pc-windows-gnu" },
|
||||||
{ triple = "i686-pc-windows-msvc" },
|
{ triple = "i686-pc-windows-msvc" },
|
||||||
{ triple = "i686-unknown-linux-gnu" },
|
{ triple = "i686-unknown-linux-gnu" },
|
||||||
{ triple = "wasm32-unknown-unknown" },
|
{ triple = "wasm32-unknown-unknown", features = [
|
||||||
|
"atomics",
|
||||||
|
] },
|
||||||
{ triple = "x86_64-apple-darwin" },
|
{ triple = "x86_64-apple-darwin" },
|
||||||
{ triple = "x86_64-apple-ios" },
|
{ triple = "x86_64-apple-ios" },
|
||||||
{ triple = "x86_64-pc-windows-gnu" },
|
{ triple = "x86_64-pc-windows-gnu" },
|
||||||
@@ -18,48 +24,57 @@ targets = [
|
|||||||
{ triple = "x86_64-unknown-redox" },
|
{ triple = "x86_64-unknown-redox" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[licenses]
|
||||||
[advisories]
|
allow = [
|
||||||
vulnerability = "deny"
|
"Apache-2.0", # https://tldrlegal.com/license/apache-license-2.0-(apache-2.0)
|
||||||
unmaintained = "warn"
|
"BSD-2-Clause", # https://tldrlegal.com/license/bsd-2-clause-license-(freebsd)
|
||||||
yanked = "deny"
|
"BSD-3-Clause", # https://tldrlegal.com/license/bsd-3-clause-license-(revised)
|
||||||
ignore = []
|
"ISC", # https://tldrlegal.com/license/isc-license
|
||||||
|
"MIT", # https://tldrlegal.com/license/mit-license
|
||||||
|
"Unicode-3.0", # https://spdx.org/licenses/Unicode-3.0.html
|
||||||
|
]
|
||||||
|
confidence-threshold = 1.0
|
||||||
|
private = { ignore = true }
|
||||||
|
|
||||||
[bans]
|
[bans]
|
||||||
multiple-versions = "deny"
|
multiple-versions = "deny"
|
||||||
wildcards = "allow" # at least until https://github.com/EmbarkStudios/cargo-deny/issues/241 is fixed
|
|
||||||
deny = []
|
|
||||||
skip = [
|
skip = [
|
||||||
{ name = "raw-window-handle" }, # we intentionally have multiple versions of this
|
{ crate = "bitflags@1", reason = "the ecosystem is in the process of migrating" },
|
||||||
{ name = "bitflags" }, # the ecosystem is in the process of migrating.
|
{ crate = "rustix@0.38", reason = "the ecosystem is in the process of migrating" },
|
||||||
{ name = "libloading" }, # x11rb uses a different version until the next update
|
{ crate = "linux-raw-sys@0.4", reason = "the ecosystem is in the process of migrating" },
|
||||||
]
|
|
||||||
skip-tree = [
|
|
||||||
{ name = "run-wasm", version = "0.1.0" }
|
|
||||||
]
|
]
|
||||||
|
wildcards = "allow" # at least until https://github.com/EmbarkStudios/cargo-deny/issues/241 is fixed
|
||||||
|
|
||||||
|
[bans.build]
|
||||||
|
include-archives = true
|
||||||
|
interpreted = "deny"
|
||||||
|
|
||||||
[licenses]
|
[[bans.build.bypass]]
|
||||||
private = { ignore = true }
|
|
||||||
unlicensed = "deny"
|
|
||||||
allow-osi-fsf-free = "neither"
|
|
||||||
confidence-threshold = 0.92 # We want really high confidence when inferring licenses from text
|
|
||||||
copyleft = "deny"
|
|
||||||
allow = [
|
allow = [
|
||||||
"Apache-2.0 WITH LLVM-exception", # https://spdx.org/licenses/LLVM-exception.html
|
{ path = "generate-bindings.sh", checksum = "268ec23248218d779e33853cdc60e2985e70214ff004716cd734270de1f6b561" },
|
||||||
"Apache-2.0", # https://tldrlegal.com/license/apache-license-2.0-(apache-2.0)
|
|
||||||
"BSD-2-Clause", # https://tldrlegal.com/license/bsd-2-clause-license-(freebsd)
|
|
||||||
"BSD-3-Clause", # https://tldrlegal.com/license/bsd-3-clause-license-(revised)
|
|
||||||
"BSL-1.0", # https://tldrlegal.com/license/boost-software-license-1.0-explained
|
|
||||||
"CC0-1.0", # https://creativecommons.org/publicdomain/zero/1.0/
|
|
||||||
"ISC", # https://tldrlegal.com/license/-isc-license
|
|
||||||
"LicenseRef-UFL-1.0", # https://tldrlegal.com/license/ubuntu-font-license,-1.0 - no official SPDX, see https://github.com/emilk/egui/issues/2321
|
|
||||||
"MIT-0", # https://choosealicense.com/licenses/mit-0/
|
|
||||||
"MIT", # https://tldrlegal.com/license/mit-license
|
|
||||||
"MPL-2.0", # https://www.mozilla.org/en-US/MPL/2.0/FAQ/ - see Q11. Used by webpki-roots on Linux.
|
|
||||||
"OFL-1.1", # https://spdx.org/licenses/OFL-1.1.html
|
|
||||||
"OpenSSL", # https://www.openssl.org/source/license.html - used on Linux
|
|
||||||
"Unicode-DFS-2016", # https://spdx.org/licenses/Unicode-DFS-2016.html
|
|
||||||
"Zlib", # https://tldrlegal.com/license/zlib-libpng-license-(zlib)
|
|
||||||
]
|
]
|
||||||
|
crate = "android-activity"
|
||||||
|
|
||||||
|
[[bans.build.bypass]]
|
||||||
|
allow-globs = ["ci/*", "githooks/*"]
|
||||||
|
crate = "zerocopy"
|
||||||
|
|
||||||
|
[[bans.build.bypass]]
|
||||||
|
allow-globs = ["freetype2/*"]
|
||||||
|
crate = "freetype-sys"
|
||||||
|
|
||||||
|
[[bans.build.bypass]]
|
||||||
|
allow-globs = ["lib/*.a"]
|
||||||
|
crate = "windows_i686_gnu"
|
||||||
|
|
||||||
|
[[bans.build.bypass]]
|
||||||
|
allow-globs = ["lib/*.lib"]
|
||||||
|
crate = "windows_i686_msvc"
|
||||||
|
|
||||||
|
[[bans.build.bypass]]
|
||||||
|
allow-globs = ["lib/*.a"]
|
||||||
|
crate = "windows_x86_64_gnu"
|
||||||
|
|
||||||
|
[[bans.build.bypass]]
|
||||||
|
allow-globs = ["lib/*.lib"]
|
||||||
|
crate = "windows_x86_64_msvc"
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
# Image Attribution
|
|
||||||
|
|
||||||
These images are used in the documentation of `winit`.
|
|
||||||
|
|
||||||
## keyboard_*.svg
|
|
||||||
|
|
||||||
These files are a modified version of "[ANSI US QWERTY (Windows)](https://commons.wikimedia.org/wiki/File:ANSI_US_QWERTY_(Windows).svg)"
|
|
||||||
by [Tomiĉo] (https://commons.wikimedia.org/wiki/User:Tomi%C4%89o). It was
|
|
||||||
originally released under the [CC-BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/deed.en)
|
|
||||||
License. Minor modifications have been made by [John Nunley](https://github.com/notgull),
|
|
||||||
which have been released under the same license as a derivative work.
|
|
||||||
|
Before Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 73 KiB |
25
dpi/CHANGELOG.md
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
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).
|
||||||
|
|
||||||
|
And please only add new entries to the top of this list, right below the `#
|
||||||
|
Unreleased` header.
|
||||||
|
|
||||||
|
## Unreleased
|
||||||
|
|
||||||
|
## 0.1.2
|
||||||
|
|
||||||
|
- Added `Insets`, `LogicalInsets` and `PhysicalInsets` types.
|
||||||
|
- Make `no_std` compatible. If you use this functionality, DPI's license has changed.
|
||||||
|
|
||||||
|
## 0.1.1
|
||||||
|
|
||||||
|
- Derive `Debug`, `Copy`, `Clone`, `PartialEq`, `Serialize`, `Deserialize` traits for `PixelUnit`.
|
||||||
|
|
||||||
|
## 0.1.0
|
||||||
|
|
||||||
|
- Add `LogicalUnit`, `PhysicalUnit` and `PixelUnit` types and related functions.
|
||||||
46
dpi/Cargo.toml
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
[package]
|
||||||
|
categories = ["gui"]
|
||||||
|
description = "Types for handling UI scaling"
|
||||||
|
edition.workspace = true
|
||||||
|
keywords = ["DPI", "HiDPI", "scale-factor"]
|
||||||
|
# N.B. This is "AND", because of the imported libm code.
|
||||||
|
license = "Apache-2.0 AND MIT"
|
||||||
|
name = "dpi"
|
||||||
|
repository.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
version = "0.1.2"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["std"]
|
||||||
|
|
||||||
|
mint = ["dep:mint"]
|
||||||
|
serde = ["dep:serde"]
|
||||||
|
|
||||||
|
# Access mathematical functions using the standard library implementations
|
||||||
|
std = []
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
mint = { workspace = true, optional = true }
|
||||||
|
serde = { workspace = true, optional = true }
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
features = ["mint", "serde"]
|
||||||
|
# These are all tested in CI
|
||||||
|
rustdoc-args = ["--cfg", "docsrs"]
|
||||||
|
targets = [
|
||||||
|
# Windows
|
||||||
|
"i686-pc-windows-msvc",
|
||||||
|
"x86_64-pc-windows-msvc",
|
||||||
|
# macOS
|
||||||
|
"aarch64-apple-darwin",
|
||||||
|
"x86_64-apple-darwin",
|
||||||
|
# Unix (X11 & Wayland)
|
||||||
|
"i686-unknown-linux-gnu",
|
||||||
|
"x86_64-unknown-linux-gnu",
|
||||||
|
# iOS
|
||||||
|
"aarch64-apple-ios",
|
||||||
|
# Android
|
||||||
|
"aarch64-linux-android",
|
||||||
|
# Web
|
||||||
|
"wasm32-unknown-unknown",
|
||||||
|
]
|
||||||
1
dpi/LICENSE
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE
|
||||||
51
dpi/LICENSE-LIBM-MIT
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
rust-lang/libm as a whole is available for use under the MIT license:
|
||||||
|
|
||||||
|
------------------------------------------------------------------------------
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
This Rust library contains the following copyrights:
|
||||||
|
|
||||||
|
Copyright (c) 2018 Jorge Aparicio
|
||||||
|
|
||||||
|
Portions of this software are derived from third-party works licensed under
|
||||||
|
terms compatible with the above MIT license:
|
||||||
|
|
||||||
|
* musl libc https://www.musl-libc.org/. This library contains the following
|
||||||
|
copyright:
|
||||||
|
|
||||||
|
Copyright © 2005-2020 Rich Felker, et al.
|
||||||
|
|
||||||
|
* The CORE-MATH project https://core-math.gitlabpages.inria.fr/. CORE-MATH
|
||||||
|
routines are available under the MIT license on a per-file basis.
|
||||||
|
|
||||||
|
The musl libc COPYRIGHT file also includes the following notice relevant to
|
||||||
|
math portions of the library:
|
||||||
|
|
||||||
|
------------------------------------------------------------------------------
|
||||||
|
Much of the math library code (src/math/* and src/complex/*) is
|
||||||
|
Copyright © 1993,2004 Sun Microsystems or
|
||||||
|
Copyright © 2003-2011 David Schultz or
|
||||||
|
Copyright © 2003-2009 Steven G. Kargl or
|
||||||
|
Copyright © 2003-2009 Bruce D. Evans or
|
||||||
|
Copyright © 2008 Stephen L. Moshier or
|
||||||
|
Copyright © 2017-2018 Arm Limited
|
||||||
|
and labelled as such in comments in the individual source files. All
|
||||||
|
have been licensed under extremely permissive terms.
|
||||||
|
------------------------------------------------------------------------------
|
||||||
18
dpi/README.md
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
# DPI
|
||||||
|
|
||||||
|
Full docs can be found on docs.rs.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Most of DPI is licensed under the Apache License, Version 2.0 ([LICENSE](LICENSE)).
|
||||||
|
All files except for `src/libm.rs` (and `LICENSE-LIBM-MIT`) are available solely under that license.
|
||||||
|
|
||||||
|
For its `no_std` support, DPI uses code from the [libm](https://crates.io/crates/libm) crate.
|
||||||
|
This is in the `libm.rs` file, and is licensed solely under the MIT Licence ([LICENSE-LIBM-MIT](LICENSE-LIBM-MIT)).
|
||||||
|
That file contains details of all potentially applicable copyright notices.
|
||||||
|
This is feature gated to only be included if you disable the `std` feature, otherwise it will not be compiled into your final binary
|
||||||
|
(and so these license terms will not apply).
|
||||||
|
|
||||||
|
Overall, this means that the license for this crate depends on what features you have enabled.
|
||||||
|
If you enable the `std` feature, then DPI uses only code available under the Apache-2.0 license, and so can be used under the terms of that license.
|
||||||
|
However, if you disable the `std` feature, then both these licenses must be followed to use the crate as a whole.
|
||||||
1343
dpi/src/lib.rs
Normal file
56
dpi/src/libm.rs
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
// Copyright (c) 2018 Jorge Aparicio
|
||||||
|
// Copyright © 2005-2020 Rich Felker, et al.
|
||||||
|
// Copyright © 1993,2004 Sun Microsystems or
|
||||||
|
// Copyright © 2003-2011 David Schultz or
|
||||||
|
// Copyright © 2003-2009 Steven G. Kargl or
|
||||||
|
// Copyright © 2003-2009 Bruce D. Evans or
|
||||||
|
// Copyright © 2008 Stephen L. Moshier or
|
||||||
|
// Copyright © 2017-2018 Arm Limited
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
// This file is licensed solely under the terms discussed in LICENSE-LIBM-MIT at the crate root.
|
||||||
|
// See the package-level README for full details.
|
||||||
|
|
||||||
|
// Taken from https://github.com/rust-lang/libm/blob/master/src/math/mod.rs#L1
|
||||||
|
macro_rules! force_eval {
|
||||||
|
($e:expr) => {
|
||||||
|
unsafe { ::core::ptr::read_volatile(&$e) }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Taken from https://github.com/rust-lang/libm/blob/libm-v0.2.11/src/math/round.rs
|
||||||
|
pub(crate) fn round(x: f64) -> f64 {
|
||||||
|
trunc(x + copysign(0.5 - 0.25 * f64::EPSILON, x))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adapted from: https://github.com/rust-lang/libm/blob/libm-v0.2.11/src/math/trunc.rs#L8-L12
|
||||||
|
#[allow(clippy::needless_late_init /*, reason = "The original libm code uses this style" */)]
|
||||||
|
fn trunc(x: f64) -> f64 {
|
||||||
|
let x1p120 = f64::from_bits(0x4770000000000000); // 0x1p120f === 2 ^ 120
|
||||||
|
|
||||||
|
let mut i: u64 = x.to_bits();
|
||||||
|
let mut e: i64 = ((i >> 52) & 0x7ff) as i64 - 0x3ff + 12;
|
||||||
|
let m: u64;
|
||||||
|
|
||||||
|
if e >= 52 + 12 {
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
if e < 12 {
|
||||||
|
e = 1;
|
||||||
|
}
|
||||||
|
m = -1i64 as u64 >> e;
|
||||||
|
if (i & m) == 0 {
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
force_eval!(x + x1p120);
|
||||||
|
i &= !m;
|
||||||
|
f64::from_bits(i)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Taken from https://github.com/rust-lang/libm/blob/libm-v0.2.11/src/math/copysign.rs
|
||||||
|
fn copysign(x: f64, y: f64) -> f64 {
|
||||||
|
let mut ux = x.to_bits();
|
||||||
|
let uy = y.to_bits();
|
||||||
|
ux &= (!0) >> 1;
|
||||||
|
ux |= uy & (1 << 63);
|
||||||
|
f64::from_bits(ux)
|
||||||
|
}
|
||||||
1416
examples/application.rs
Normal file
129
examples/child_window.rs
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
#[cfg(any(x11_platform, macos_platform, windows_platform))]
|
||||||
|
#[allow(deprecated)]
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use winit::application::ApplicationHandler;
|
||||||
|
use winit::dpi::{LogicalPosition, LogicalSize, Position};
|
||||||
|
use winit::event::{ElementState, KeyEvent, WindowEvent};
|
||||||
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
|
use winit::raw_window_handle::HasRawWindowHandle;
|
||||||
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct WindowData {
|
||||||
|
window: Box<dyn Window>,
|
||||||
|
color: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowData {
|
||||||
|
fn new(window: Box<dyn Window>, color: u32) -> Self {
|
||||||
|
Self { window, color }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Debug)]
|
||||||
|
struct Application {
|
||||||
|
parent_window_id: Option<WindowId>,
|
||||||
|
windows: HashMap<WindowId, WindowData>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for Application {
|
||||||
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
let attributes = WindowAttributes::default()
|
||||||
|
.with_title("parent window")
|
||||||
|
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
||||||
|
.with_surface_size(LogicalSize::new(640.0f32, 480.0f32));
|
||||||
|
let window = event_loop.create_window(attributes).unwrap();
|
||||||
|
println!("Parent window id: {:?})", window.id());
|
||||||
|
self.parent_window_id = Some(window.id());
|
||||||
|
|
||||||
|
self.windows.insert(window.id(), WindowData::new(window, 0xffbbbbbb));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
window_id: winit::window::WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
self.windows.clear();
|
||||||
|
event_loop.exit();
|
||||||
|
},
|
||||||
|
WindowEvent::PointerEntered { device_id: _, .. } => {
|
||||||
|
// On x11, println when the cursor entered in a window even if the child window
|
||||||
|
// is created by some key inputs.
|
||||||
|
// the child windows are always placed at (0, 0) with size (200, 200) in the
|
||||||
|
// parent window, so we also can see this log when we move
|
||||||
|
// the cursor around (200, 200) in parent window.
|
||||||
|
println!("cursor entered in the window {window_id:?}");
|
||||||
|
},
|
||||||
|
WindowEvent::KeyboardInput {
|
||||||
|
event: KeyEvent { state: ElementState::Pressed, .. },
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
let child_index = self.windows.len() - 1;
|
||||||
|
let child_color =
|
||||||
|
0xff000000 + 3_u32.pow((child_index + 2).rem_euclid(16) as u32);
|
||||||
|
|
||||||
|
let parent_window = self.windows.get(&self.parent_window_id.unwrap()).unwrap();
|
||||||
|
let child_window =
|
||||||
|
spawn_child_window(parent_window.window.as_ref(), event_loop, child_index);
|
||||||
|
let child_id = child_window.id();
|
||||||
|
println!("Child window created with id: {child_id:?}");
|
||||||
|
self.windows.insert(child_id, WindowData::new(child_window, child_color));
|
||||||
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
if let Some(window) = self.windows.get(&window_id) {
|
||||||
|
if window_id == self.parent_window_id.unwrap() {
|
||||||
|
fill::fill_window(window.window.as_ref());
|
||||||
|
} else {
|
||||||
|
fill::fill_window_with_color(window.window.as_ref(), window.color);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_child_window(
|
||||||
|
parent: &dyn Window,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
child_count: usize,
|
||||||
|
) -> Box<dyn Window> {
|
||||||
|
let parent = parent.raw_window_handle().unwrap();
|
||||||
|
|
||||||
|
// As child count increases, x goes from 0*128 to 5*128 and then repeats
|
||||||
|
let x: f64 = child_count.rem_euclid(5) as f64 * 128.0;
|
||||||
|
|
||||||
|
// After 5 windows have been put side by side horizontally, a new row starts
|
||||||
|
let y: f64 = (child_count / 5) as f64 * 96.0;
|
||||||
|
|
||||||
|
let mut window_attributes = WindowAttributes::default()
|
||||||
|
.with_title("child window")
|
||||||
|
.with_surface_size(LogicalSize::new(128.0f32, 96.0))
|
||||||
|
.with_position(Position::Logical(LogicalPosition::new(x, y)))
|
||||||
|
.with_visible(true);
|
||||||
|
// `with_parent_window` is unsafe. Parent window must be a valid window.
|
||||||
|
window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) };
|
||||||
|
|
||||||
|
event_loop.create_window(window_attributes).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
event_loop.run_app(Application::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(any(x11_platform, macos_platform, windows_platform)))]
|
||||||
|
fn main() {
|
||||||
|
panic!(
|
||||||
|
"This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature \
|
||||||
|
enabled."
|
||||||
|
);
|
||||||
|
}
|
||||||
146
examples/control_flow.rs
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
|
use std::thread;
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
use std::time;
|
||||||
|
|
||||||
|
use ::tracing::{info, warn};
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
use web_time as time;
|
||||||
|
use winit::application::ApplicationHandler;
|
||||||
|
use winit::event::{ElementState, KeyEvent, StartCause, WindowEvent};
|
||||||
|
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||||
|
use winit::keyboard::{Key, NamedKey};
|
||||||
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
#[path = "util/tracing.rs"]
|
||||||
|
mod tracing;
|
||||||
|
|
||||||
|
const WAIT_TIME: time::Duration = time::Duration::from_millis(100);
|
||||||
|
const POLL_SLEEP_TIME: time::Duration = time::Duration::from_millis(100);
|
||||||
|
|
||||||
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum Mode {
|
||||||
|
#[default]
|
||||||
|
Wait,
|
||||||
|
WaitUntil,
|
||||||
|
Poll,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
console_error_panic_hook::set_once();
|
||||||
|
|
||||||
|
tracing::init();
|
||||||
|
|
||||||
|
info!("Press '1' to switch to Wait mode.");
|
||||||
|
info!("Press '2' to switch to WaitUntil mode.");
|
||||||
|
info!("Press '3' to switch to Poll mode.");
|
||||||
|
info!("Press 'R' to toggle request_redraw() calls.");
|
||||||
|
info!("Press 'Esc' to close the window.");
|
||||||
|
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
event_loop.run_app(ControlFlowDemo::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Debug)]
|
||||||
|
struct ControlFlowDemo {
|
||||||
|
mode: Mode,
|
||||||
|
request_redraw: bool,
|
||||||
|
wait_cancelled: bool,
|
||||||
|
close_requested: bool,
|
||||||
|
window: Option<Box<dyn Window>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for ControlFlowDemo {
|
||||||
|
fn new_events(&mut self, _event_loop: &dyn ActiveEventLoop, cause: StartCause) {
|
||||||
|
info!("new_events: {cause:?}");
|
||||||
|
|
||||||
|
self.wait_cancelled = match cause {
|
||||||
|
StartCause::WaitCancelled { .. } => self.mode == Mode::WaitUntil,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
let window_attributes = WindowAttributes::default().with_title(
|
||||||
|
"Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.",
|
||||||
|
);
|
||||||
|
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
_event_loop: &dyn ActiveEventLoop,
|
||||||
|
_window_id: WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
info!("{event:?}");
|
||||||
|
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
self.close_requested = true;
|
||||||
|
},
|
||||||
|
WindowEvent::KeyboardInput {
|
||||||
|
event: KeyEvent { logical_key: key, state: ElementState::Pressed, .. },
|
||||||
|
..
|
||||||
|
} => match key.as_ref() {
|
||||||
|
// WARNING: Consider using `key_without_modifiers()` if available on your platform.
|
||||||
|
// See the `key_binding` example
|
||||||
|
Key::Character("1") => {
|
||||||
|
self.mode = Mode::Wait;
|
||||||
|
warn!("mode: {:?}", self.mode);
|
||||||
|
},
|
||||||
|
Key::Character("2") => {
|
||||||
|
self.mode = Mode::WaitUntil;
|
||||||
|
warn!("mode: {:?}", self.mode);
|
||||||
|
},
|
||||||
|
Key::Character("3") => {
|
||||||
|
self.mode = Mode::Poll;
|
||||||
|
warn!("mode: {:?}", self.mode);
|
||||||
|
},
|
||||||
|
Key::Character("r") => {
|
||||||
|
self.request_redraw = !self.request_redraw;
|
||||||
|
warn!("request_redraw: {}", self.request_redraw);
|
||||||
|
},
|
||||||
|
Key::Named(NamedKey::Escape) => {
|
||||||
|
self.close_requested = true;
|
||||||
|
},
|
||||||
|
_ => (),
|
||||||
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
let window = self.window.as_ref().unwrap();
|
||||||
|
window.pre_present_notify();
|
||||||
|
fill::fill_window(window.as_ref());
|
||||||
|
},
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn about_to_wait(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
if self.request_redraw && !self.wait_cancelled && !self.close_requested {
|
||||||
|
self.window.as_ref().unwrap().request_redraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
match self.mode {
|
||||||
|
Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
|
||||||
|
Mode::WaitUntil => {
|
||||||
|
if !self.wait_cancelled {
|
||||||
|
event_loop
|
||||||
|
.set_control_flow(ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Mode::Poll => {
|
||||||
|
thread::sleep(POLL_SLEEP_TIME);
|
||||||
|
event_loop.set_control_flow(ControlFlow::Poll);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
if self.close_requested {
|
||||||
|
event_loop.exit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Before Width: | Height: | Size: 159 B After Width: | Height: | Size: 159 B |
|
Before Width: | Height: | Size: 129 B After Width: | Height: | Size: 129 B |
|
Before Width: | Height: | Size: 229 B After Width: | Height: | Size: 229 B |
|
Before Width: | Height: | Size: 2.9 KiB After Width: | Height: | Size: 2.9 KiB |
65
examples/dnd.rs
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
|
||||||
|
use winit::application::ApplicationHandler;
|
||||||
|
use winit::event::WindowEvent;
|
||||||
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
#[path = "util/tracing.rs"]
|
||||||
|
mod tracing;
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
tracing::init();
|
||||||
|
|
||||||
|
let event_loop = EventLoop::new()?;
|
||||||
|
|
||||||
|
let app = Application::new();
|
||||||
|
Ok(event_loop.run_app(app)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Application state and event handling.
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Application {
|
||||||
|
window: Option<Box<dyn Window>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Application {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self { window: None }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for Application {
|
||||||
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
let window_attributes =
|
||||||
|
WindowAttributes::default().with_title("Drag and drop files on me!");
|
||||||
|
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
_window_id: WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
match event {
|
||||||
|
WindowEvent::DragLeft { .. }
|
||||||
|
| WindowEvent::DragEntered { .. }
|
||||||
|
| WindowEvent::DragMoved { .. }
|
||||||
|
| WindowEvent::DragDropped { .. } => {
|
||||||
|
println!("{event:?}");
|
||||||
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
let window = self.window.as_ref().unwrap();
|
||||||
|
window.pre_present_notify();
|
||||||
|
fill::fill_window(window.as_ref());
|
||||||
|
},
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
event_loop.exit();
|
||||||
|
},
|
||||||
|
_ => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
80
examples/pump_events.rs
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
#![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;
|
||||||
|
use std::thread::sleep;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use winit::application::ApplicationHandler;
|
||||||
|
use winit::event::WindowEvent;
|
||||||
|
use winit::event_loop::pump_events::{EventLoopExtPumpEvents, PumpStatus};
|
||||||
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
#[derive(Default, Debug)]
|
||||||
|
struct PumpDemo {
|
||||||
|
window: Option<Box<dyn Window>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for PumpDemo {
|
||||||
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
let window_attributes = WindowAttributes::default().with_title("A fantastic window!");
|
||||||
|
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
_window_id: WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
println!("{event:?}");
|
||||||
|
|
||||||
|
let window = match self.window.as_ref() {
|
||||||
|
Some(window) => window,
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => event_loop.exit(),
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(window.as_ref());
|
||||||
|
window.request_redraw();
|
||||||
|
},
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
let mut app = PumpDemo::default();
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let timeout = Some(Duration::ZERO);
|
||||||
|
let status = event_loop.pump_app_events(timeout, &mut app);
|
||||||
|
|
||||||
|
if let PumpStatus::Exit(exit_code) = status {
|
||||||
|
break 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.");
|
||||||
|
}
|
||||||
99
examples/run_on_demand.rs
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
|
// Limit this example to only compatible platforms.
|
||||||
|
#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform,))]
|
||||||
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use winit::application::ApplicationHandler;
|
||||||
|
use winit::event::WindowEvent;
|
||||||
|
use winit::event_loop::run_on_demand::EventLoopExtRunOnDemand;
|
||||||
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
#[derive(Default, Debug)]
|
||||||
|
struct App {
|
||||||
|
idx: usize,
|
||||||
|
window_id: Option<WindowId>,
|
||||||
|
window: Option<Box<dyn Window>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for App {
|
||||||
|
fn about_to_wait(&mut self, _event_loop: &dyn ActiveEventLoop) {
|
||||||
|
if let Some(window) = self.window.as_ref() {
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
let window_attributes = WindowAttributes::default()
|
||||||
|
.with_title("Fantastic window number one!")
|
||||||
|
.with_surface_size(winit::dpi::LogicalSize::new(128.0, 128.0));
|
||||||
|
let window = event_loop.create_window(window_attributes).unwrap();
|
||||||
|
self.window_id = Some(window.id());
|
||||||
|
self.window = Some(window);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
window_id: WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
if event == WindowEvent::Destroyed && self.window_id == Some(window_id) {
|
||||||
|
println!(
|
||||||
|
"--------------------------------------------------------- Window {} Destroyed",
|
||||||
|
self.idx
|
||||||
|
);
|
||||||
|
self.window_id = None;
|
||||||
|
event_loop.exit();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let window = match self.window.as_mut() {
|
||||||
|
Some(window) => window,
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
println!(
|
||||||
|
"--------------------------------------------------------- Window {} \
|
||||||
|
CloseRequested",
|
||||||
|
self.idx
|
||||||
|
);
|
||||||
|
fill::cleanup_window(window.as_ref());
|
||||||
|
self.window = None;
|
||||||
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(window.as_ref());
|
||||||
|
},
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
let mut event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let mut app = App { idx: 1, ..Default::default() };
|
||||||
|
event_loop.run_app_on_demand(&mut app)?;
|
||||||
|
|
||||||
|
println!("--------------------------------------------------------- Finished first loop");
|
||||||
|
println!("--------------------------------------------------------- Waiting 5 seconds");
|
||||||
|
std::thread::sleep(Duration::from_secs(5));
|
||||||
|
|
||||||
|
app.idx += 1;
|
||||||
|
event_loop.run_app_on_demand(&mut app)?;
|
||||||
|
println!("--------------------------------------------------------- Finished second loop");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(any(windows_platform, macos_platform, x11_platform, wayland_platform,)))]
|
||||||
|
fn main() {
|
||||||
|
println!("This example is not supported on this platform");
|
||||||
|
}
|
||||||
156
examples/util/fill.rs
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
//! Fill the window buffer with a solid color.
|
||||||
|
//!
|
||||||
|
//! Launching a window without drawing to it has unpredictable results varying from platform to
|
||||||
|
//! platform. In order to have well-defined examples, this module provides an easy way to
|
||||||
|
//! fill the window buffer with a solid color.
|
||||||
|
//!
|
||||||
|
//! The `softbuffer` crate is used, largely because of its ease of use. `glutin` or `wgpu` could
|
||||||
|
//! also be used to fill the window buffer, but they are more complicated to use.
|
||||||
|
|
||||||
|
#[allow(unused_imports)]
|
||||||
|
pub use platform::cleanup_window;
|
||||||
|
#[allow(unused_imports)]
|
||||||
|
pub use platform::fill_window;
|
||||||
|
#[allow(unused_imports)]
|
||||||
|
pub use platform::fill_window_with_animated_color;
|
||||||
|
#[allow(unused_imports)]
|
||||||
|
pub use platform::fill_window_with_color;
|
||||||
|
|
||||||
|
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||||
|
mod platform {
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::mem;
|
||||||
|
use std::mem::ManuallyDrop;
|
||||||
|
use std::num::NonZeroU32;
|
||||||
|
#[cfg(all(not(android_platform), not(web_platform)))]
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use softbuffer::{Context, Surface};
|
||||||
|
#[cfg(all(web_platform, not(android_platform)))]
|
||||||
|
use web_time::Instant;
|
||||||
|
use winit::window::{Window, WindowId};
|
||||||
|
|
||||||
|
thread_local! {
|
||||||
|
// NOTE: You should never do things like that, create context and drop it before
|
||||||
|
// you drop the event loop. We do this for brevity to not blow up examples. We use
|
||||||
|
// ManuallyDrop to prevent destructors from running.
|
||||||
|
//
|
||||||
|
// A static, thread-local map of graphics contexts to open windows.
|
||||||
|
static GC: ManuallyDrop<RefCell<Option<GraphicsContext>>> = const { ManuallyDrop::new(RefCell::new(None)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The graphics context used to draw to a window.
|
||||||
|
struct GraphicsContext {
|
||||||
|
/// The global softbuffer context.
|
||||||
|
context: RefCell<Context<&'static dyn Window>>,
|
||||||
|
|
||||||
|
/// The hash map of window IDs to surfaces.
|
||||||
|
surfaces: HashMap<WindowId, Surface<&'static dyn Window, &'static dyn Window>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GraphicsContext {
|
||||||
|
fn new(w: &dyn Window) -> Self {
|
||||||
|
Self {
|
||||||
|
context: RefCell::new(
|
||||||
|
Context::new(unsafe {
|
||||||
|
mem::transmute::<&'_ dyn Window, &'static dyn Window>(w)
|
||||||
|
})
|
||||||
|
.expect("Failed to create a softbuffer context"),
|
||||||
|
),
|
||||||
|
surfaces: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_surface(
|
||||||
|
&mut self,
|
||||||
|
window: &dyn Window,
|
||||||
|
) -> &mut Surface<&'static dyn Window, &'static dyn Window> {
|
||||||
|
self.surfaces.entry(window.id()).or_insert_with(|| {
|
||||||
|
Surface::new(&self.context.borrow(), unsafe {
|
||||||
|
mem::transmute::<&'_ dyn Window, &'static dyn Window>(window)
|
||||||
|
})
|
||||||
|
.expect("Failed to create a softbuffer surface")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn destroy_surface(&mut self, window: &dyn Window) {
|
||||||
|
self.surfaces.remove(&window.id());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fill_window_with_color(window: &dyn Window, color: u32) {
|
||||||
|
GC.with(|gc| {
|
||||||
|
let size = window.surface_size();
|
||||||
|
let (Some(width), Some(height)) =
|
||||||
|
(NonZeroU32::new(size.width), NonZeroU32::new(size.height))
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Either get the last context used or create a new one.
|
||||||
|
let mut gc = gc.borrow_mut();
|
||||||
|
let surface =
|
||||||
|
gc.get_or_insert_with(|| GraphicsContext::new(window)).create_surface(window);
|
||||||
|
|
||||||
|
// Fill a buffer with a solid color
|
||||||
|
|
||||||
|
surface.resize(width, height).expect("Failed to resize the softbuffer surface");
|
||||||
|
|
||||||
|
let mut buffer = surface.buffer_mut().expect("Failed to get the softbuffer buffer");
|
||||||
|
buffer.fill(color);
|
||||||
|
buffer.present().expect("Failed to present the softbuffer buffer");
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn fill_window(window: &dyn Window) {
|
||||||
|
fill_window_with_color(window, 0xff181818);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn fill_window_with_animated_color(window: &dyn Window, start: Instant) {
|
||||||
|
let time = start.elapsed().as_secs_f32() * 1.5;
|
||||||
|
let blue = (time.sin() * 255.0) as u32;
|
||||||
|
let green = ((time.cos() * 255.0) as u32) << 8;
|
||||||
|
let red = ((1.0 - time.sin() * 255.0) as u32) << 16;
|
||||||
|
let color = red | green | blue;
|
||||||
|
fill_window_with_color(window, color);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn cleanup_window(window: &dyn Window) {
|
||||||
|
GC.with(|gc| {
|
||||||
|
let mut gc = gc.borrow_mut();
|
||||||
|
if let Some(context) = gc.as_mut() {
|
||||||
|
context.destroy_surface(window);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(target_os = "android", target_os = "ios"))]
|
||||||
|
mod platform {
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn fill_window(_window: &dyn winit::window::Window) {
|
||||||
|
// No-op on mobile platforms.
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn fill_window_with_color(_window: &dyn winit::window::Window, _color: u32) {
|
||||||
|
// No-op on mobile platforms.
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn fill_window_with_animated_color(
|
||||||
|
_window: &dyn winit::window::Window,
|
||||||
|
_start: std::time::Instant,
|
||||||
|
) {
|
||||||
|
// No-op on mobile platforms.
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn cleanup_window(_window: &dyn winit::window::Window) {
|
||||||
|
// No-op on mobile platforms.
|
||||||
|
}
|
||||||
|
}
|
||||||
25
examples/util/tracing.rs
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
#[cfg(not(web_platform))]
|
||||||
|
pub fn init() {
|
||||||
|
use tracing_subscriber::filter::{EnvFilter, LevelFilter};
|
||||||
|
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_env_filter(
|
||||||
|
EnvFilter::builder().with_default_directive(LevelFilter::INFO.into()).from_env_lossy(),
|
||||||
|
)
|
||||||
|
.init();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
pub fn init() {
|
||||||
|
use tracing_subscriber::layer::SubscriberExt;
|
||||||
|
use tracing_subscriber::util::SubscriberInitExt;
|
||||||
|
|
||||||
|
tracing_subscriber::registry()
|
||||||
|
.with(
|
||||||
|
tracing_subscriber::fmt::layer()
|
||||||
|
.with_ansi(false)
|
||||||
|
.without_time()
|
||||||
|
.with_writer(tracing_web::MakeWebConsoleWriter::new()),
|
||||||
|
)
|
||||||
|
.init();
|
||||||
|
}
|
||||||
84
examples/window.rs
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
//! Simple winit window example.
|
||||||
|
|
||||||
|
use std::error::Error;
|
||||||
|
|
||||||
|
use winit::application::ApplicationHandler;
|
||||||
|
use winit::event::WindowEvent;
|
||||||
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
use winit::platform::web::WindowAttributesWeb;
|
||||||
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
#[path = "util/tracing.rs"]
|
||||||
|
mod tracing;
|
||||||
|
|
||||||
|
#[derive(Default, Debug)]
|
||||||
|
struct App {
|
||||||
|
window: Option<Box<dyn Window>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for App {
|
||||||
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
let window_attributes = WindowAttributes::default();
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
let window_attributes = WindowAttributes::default()
|
||||||
|
.with_platform_attributes(Box::new(WindowAttributesWeb::default().with_append(true)));
|
||||||
|
self.window = match event_loop.create_window(window_attributes) {
|
||||||
|
Ok(window) => Some(window),
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("error creating window: {err}");
|
||||||
|
event_loop.exit();
|
||||||
|
return;
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, _: WindowId, event: WindowEvent) {
|
||||||
|
println!("{event:?}");
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
println!("Close was requested; stopping");
|
||||||
|
event_loop.exit();
|
||||||
|
},
|
||||||
|
WindowEvent::SurfaceResized(_) => {
|
||||||
|
self.window.as_ref().expect("resize event without a window").request_redraw();
|
||||||
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
// Redraw the application.
|
||||||
|
//
|
||||||
|
// It's preferable for applications that do not render continuously to render in
|
||||||
|
// this event rather than in AboutToWait, since rendering in here allows
|
||||||
|
// the program to gracefully handle redraws requested by the OS.
|
||||||
|
|
||||||
|
let window = self.window.as_ref().expect("redraw request without a window");
|
||||||
|
|
||||||
|
// Notify that you're about to draw.
|
||||||
|
window.pre_present_notify();
|
||||||
|
|
||||||
|
// Draw.
|
||||||
|
fill::fill_window(window.as_ref());
|
||||||
|
|
||||||
|
// For contiguous redraw loop you can request a redraw from here.
|
||||||
|
// window.request_redraw();
|
||||||
|
},
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
console_error_panic_hook::set_once();
|
||||||
|
|
||||||
|
tracing::init();
|
||||||
|
|
||||||
|
let event_loop = EventLoop::new()?;
|
||||||
|
|
||||||
|
// For alternative loop run options see `pump_events` and `run_on_demand` examples.
|
||||||
|
event_loop.run_app(App::default())?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
71
examples/x11_embed.rs
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
//! A demonstration of embedding a winit window in an existing X11 application.
|
||||||
|
use std::error::Error;
|
||||||
|
|
||||||
|
#[cfg(x11_platform)]
|
||||||
|
fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
use winit::application::ApplicationHandler;
|
||||||
|
use winit::event::WindowEvent;
|
||||||
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
|
use winit::platform::x11::WindowAttributesX11;
|
||||||
|
use winit::window::{Window, WindowAttributes, WindowId};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct XEmbedDemo {
|
||||||
|
parent_window_id: u32,
|
||||||
|
window: Option<Box<dyn Window>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for XEmbedDemo {
|
||||||
|
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||||
|
let mut window_attributes = WindowAttributes::default()
|
||||||
|
.with_title("An embedded window!")
|
||||||
|
.with_surface_size(winit::dpi::LogicalSize::new(128.0, 128.0));
|
||||||
|
let x11_attrs =
|
||||||
|
WindowAttributesX11::default().with_embed_parent_window(self.parent_window_id);
|
||||||
|
window_attributes = window_attributes.with_platform_attributes(Box::new(x11_attrs));
|
||||||
|
|
||||||
|
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
_window_id: WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
let window = self.window.as_ref().unwrap();
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => event_loop.exit(),
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
window.pre_present_notify();
|
||||||
|
fill::fill_window(window.as_ref());
|
||||||
|
},
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn about_to_wait(&mut self, _event_loop: &dyn ActiveEventLoop) {
|
||||||
|
self.window.as_ref().unwrap().request_redraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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>()?;
|
||||||
|
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
let event_loop = EventLoop::new()?;
|
||||||
|
|
||||||
|
Ok(event_loop.run_app(XEmbedDemo { parent_window_id, window: None })?)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(x11_platform))]
|
||||||
|
fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
println!("This example is only supported on X11 platforms.");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "run-wasm"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2021"
|
|
||||||
publish = false
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
cargo-run-wasm = "0.2.0"
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
cargo_run_wasm::run_wasm_with_css("body { margin: 0px; }");
|
|
||||||
}
|
|
||||||
23
rustfmt.toml
@@ -1,3 +1,20 @@
|
|||||||
force_explicit_abi=true
|
comment_width = 100
|
||||||
use_field_init_shorthand=true
|
condense_wildcard_suffixes = true
|
||||||
# merge_imports=true
|
error_on_unformatted = true
|
||||||
|
format_code_in_doc_comments = true
|
||||||
|
format_macro_bodies = true
|
||||||
|
format_macro_matchers = true
|
||||||
|
format_strings = true
|
||||||
|
group_imports = "StdExternalCrate"
|
||||||
|
hex_literal_case = "Lower"
|
||||||
|
imports_granularity = "Module"
|
||||||
|
match_block_trailing_comma = true
|
||||||
|
newline_style = "Unix"
|
||||||
|
normalize_comments = true
|
||||||
|
normalize_doc_attributes = true
|
||||||
|
overflow_delimited_expr = true
|
||||||
|
# Some macros break with this.
|
||||||
|
reorder_impl_items = false
|
||||||
|
use_field_init_shorthand = true
|
||||||
|
use_small_heuristics = "Max"
|
||||||
|
wrap_comments = true
|
||||||
|
|||||||
5
taplo.toml
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
[formatting]
|
||||||
|
allowed_blank_lines = 1
|
||||||
|
column_width = 100
|
||||||
|
indent_string = ' '
|
||||||
|
reorder_keys = true
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
#[allow(dead_code)]
|
|
||||||
fn needs_send<T: Send>() {}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn event_loop_proxy_send() {
|
|
||||||
#[allow(dead_code)]
|
|
||||||
fn is_send<T: 'static + Send>() {
|
|
||||||
// ensures that `winit::EventLoopProxy` implements `Send`
|
|
||||||
needs_send::<winit::event_loop::EventLoopProxy<T>>();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn window_send() {
|
|
||||||
// ensures that `winit::Window` implements `Send`
|
|
||||||
needs_send::<winit::window::Window>();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn window_builder_send() {
|
|
||||||
needs_send::<winit::window::WindowBuilder>();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ids_send() {
|
|
||||||
// ensures that the various `..Id` types implement `Send`
|
|
||||||
needs_send::<winit::window::WindowId>();
|
|
||||||
needs_send::<winit::event::DeviceId>();
|
|
||||||
needs_send::<winit::monitor::MonitorHandle>();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn custom_cursor_send() {
|
|
||||||
needs_send::<winit::window::CustomCursorBuilder>();
|
|
||||||
needs_send::<winit::window::CustomCursor>();
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
#[allow(dead_code)]
|
|
||||||
fn needs_sync<T: Sync>() {}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn window_sync() {
|
|
||||||
// ensures that `winit::Window` implements `Sync`
|
|
||||||
needs_sync::<winit::window::Window>();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn window_builder_sync() {
|
|
||||||
needs_sync::<winit::window::WindowBuilder>();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn custom_cursor_sync() {
|
|
||||||
needs_sync::<winit::window::CustomCursorBuilder>();
|
|
||||||
needs_sync::<winit::window::CustomCursor>();
|
|
||||||
}
|
|
||||||
10
typos.toml
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
# documentation: https://github.com/crate-ci/typos/blob/master/docs/reference.md
|
||||||
|
|
||||||
|
[default.extend-identifiers]
|
||||||
|
TME_LEAVE = "TME_LEAVE" # From windows_sys::Win32::UI::Input::KeyboardAndMouse::TME_LEAVE
|
||||||
|
XF86_Calculater = "XF86_Calculater" # From xkbcommon_dl::keysyms::XF86_Calculater
|
||||||
|
ptd = "ptd" # From windows_sys::Win32::System::Com::FORMATETC { ptd, ..}
|
||||||
|
requestor = "requestor" # From x11_dl::xlib::XSelectionEvent { requestor ..}
|
||||||
|
|
||||||
|
[files]
|
||||||
|
extend-exclude = ["*.drawio"]
|
||||||
35
winit-android/Cargo.toml
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
[package]
|
||||||
|
description = "Winit's Android backend"
|
||||||
|
documentation = "https://docs.rs/winit-android"
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
name = "winit-android"
|
||||||
|
repository.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
version.workspace = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
game-activity = ["android-activity/game-activity"]
|
||||||
|
native-activity = ["android-activity/native-activity"]
|
||||||
|
serde = ["dep:serde", "bitflags/serde", "smol_str/serde", "dpi/serde", "winit-core/serde"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
bitflags.workspace = true
|
||||||
|
dpi.workspace = true
|
||||||
|
rwh_06.workspace = true
|
||||||
|
serde = { workspace = true, optional = true }
|
||||||
|
smol_str.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
winit-core.workspace = true
|
||||||
|
|
||||||
|
# Platform-specific
|
||||||
|
[target.'cfg(target_os = "android")'.dependencies]
|
||||||
|
android-activity.workspace = true
|
||||||
|
ndk.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
winit.workspace = true
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
features = ["serde", "native-activity"]
|
||||||
|
targets = ["aarch64-linux-android"]
|
||||||
1
winit-android/LICENSE
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE
|
||||||
1
winit-android/README.md
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../README.md
|
||||||
1044
winit-android/src/event_loop.rs
Normal file
@@ -1,10 +1,9 @@
|
|||||||
use android_activity::{
|
use android_activity::input::{KeyAction, KeyEvent, KeyMapChar, Keycode};
|
||||||
input::{KeyAction, KeyEvent, KeyMapChar, Keycode},
|
use android_activity::AndroidApp;
|
||||||
AndroidApp,
|
use winit_core::keyboard::{
|
||||||
|
Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey};
|
|
||||||
|
|
||||||
pub fn to_physical_key(keycode: Keycode) -> PhysicalKey {
|
pub fn to_physical_key(keycode: Keycode) -> PhysicalKey {
|
||||||
PhysicalKey::Code(match keycode {
|
PhysicalKey::Code(match keycode {
|
||||||
Keycode::A => KeyCode::KeyA,
|
Keycode::A => KeyCode::KeyA,
|
||||||
@@ -105,7 +104,7 @@ pub fn to_physical_key(keycode: Keycode) -> PhysicalKey {
|
|||||||
Keycode::VolumeUp => KeyCode::AudioVolumeUp,
|
Keycode::VolumeUp => KeyCode::AudioVolumeUp,
|
||||||
Keycode::VolumeDown => KeyCode::AudioVolumeDown,
|
Keycode::VolumeDown => KeyCode::AudioVolumeDown,
|
||||||
Keycode::VolumeMute => KeyCode::AudioVolumeMute,
|
Keycode::VolumeMute => KeyCode::AudioVolumeMute,
|
||||||
//Keycode::Mute => None, // Microphone mute
|
// Keycode::Mute => None, // Microphone mute
|
||||||
Keycode::MediaPlayPause => KeyCode::MediaPlayPause,
|
Keycode::MediaPlayPause => KeyCode::MediaPlayPause,
|
||||||
Keycode::MediaStop => KeyCode::MediaStop,
|
Keycode::MediaStop => KeyCode::MediaStop,
|
||||||
Keycode::MediaNext => KeyCode::MediaTrackNext,
|
Keycode::MediaNext => KeyCode::MediaTrackNext,
|
||||||
@@ -145,8 +144,8 @@ pub fn to_physical_key(keycode: Keycode) -> PhysicalKey {
|
|||||||
Keycode::AltLeft => KeyCode::AltLeft,
|
Keycode::AltLeft => KeyCode::AltLeft,
|
||||||
Keycode::AltRight => KeyCode::AltRight,
|
Keycode::AltRight => KeyCode::AltRight,
|
||||||
|
|
||||||
Keycode::MetaLeft => KeyCode::SuperLeft,
|
Keycode::MetaLeft => KeyCode::MetaLeft,
|
||||||
Keycode::MetaRight => KeyCode::SuperRight,
|
Keycode::MetaRight => KeyCode::MetaRight,
|
||||||
|
|
||||||
Keycode::LeftBracket => KeyCode::BracketLeft,
|
Keycode::LeftBracket => KeyCode::BracketLeft,
|
||||||
Keycode::RightBracket => KeyCode::BracketRight,
|
Keycode::RightBracket => KeyCode::BracketRight,
|
||||||
@@ -174,9 +173,9 @@ pub fn character_map_and_combine_key(
|
|||||||
let key_map = match app.device_key_character_map(device_id) {
|
let key_map = match app.device_key_character_map(device_id) {
|
||||||
Ok(key_map) => key_map,
|
Ok(key_map) => key_map,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
log::warn!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}");
|
tracing::warn!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}");
|
||||||
return None;
|
return None;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
match key_map.get(key_event.key_code(), key_event.meta_state()) {
|
match key_map.get(key_event.key_code(), key_event.meta_state()) {
|
||||||
@@ -188,9 +187,12 @@ pub fn character_map_and_combine_key(
|
|||||||
Ok(Some(key)) => Some(key),
|
Ok(Some(key)) => Some(key),
|
||||||
Ok(None) => None,
|
Ok(None) => None,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
log::warn!("KeyEvent: Failed to combine 'dead key' accent '{accent}' with '{unicode}': {err:?}");
|
tracing::warn!(
|
||||||
|
"KeyEvent: Failed to combine 'dead key' accent '{accent}' with \
|
||||||
|
'{unicode}': {err:?}"
|
||||||
|
);
|
||||||
None
|
None
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Some(unicode)
|
Some(unicode)
|
||||||
@@ -200,23 +202,23 @@ pub fn character_map_and_combine_key(
|
|||||||
} else {
|
} else {
|
||||||
Some(KeyMapChar::Unicode(unicode))
|
Some(KeyMapChar::Unicode(unicode))
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
Ok(KeyMapChar::CombiningAccent(accent)) => {
|
Ok(KeyMapChar::CombiningAccent(accent)) => {
|
||||||
if key_event.action() == KeyAction::Down {
|
if key_event.action() == KeyAction::Down {
|
||||||
*combining_accent = Some(accent);
|
*combining_accent = Some(accent);
|
||||||
}
|
}
|
||||||
Some(KeyMapChar::CombiningAccent(accent))
|
Some(KeyMapChar::CombiningAccent(accent))
|
||||||
}
|
},
|
||||||
Ok(KeyMapChar::None) => {
|
Ok(KeyMapChar::None) => {
|
||||||
// Leave any combining_accent state in tact (seems to match how other
|
// Leave any combining_accent state in tact (seems to match how other
|
||||||
// Android apps work)
|
// Android apps work)
|
||||||
None
|
None
|
||||||
}
|
},
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
log::warn!("KeyEvent: Failed to get key map character: {err:?}");
|
tracing::warn!("KeyEvent: Failed to get key map character: {err:?}");
|
||||||
*combining_accent = None;
|
*combining_accent = None;
|
||||||
None
|
None
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -308,7 +310,7 @@ pub fn to_logical(key_char: Option<KeyMapChar>, keycode: Keycode) -> Key {
|
|||||||
ShiftLeft => Key::Named(NamedKey::Shift),
|
ShiftLeft => Key::Named(NamedKey::Shift),
|
||||||
ShiftRight => Key::Named(NamedKey::Shift),
|
ShiftRight => Key::Named(NamedKey::Shift),
|
||||||
Tab => Key::Named(NamedKey::Tab),
|
Tab => Key::Named(NamedKey::Tab),
|
||||||
Space => Key::Named(NamedKey::Space),
|
Space => Key::Character(" ".into()),
|
||||||
Sym => Key::Named(NamedKey::Symbol),
|
Sym => Key::Named(NamedKey::Symbol),
|
||||||
Explorer => Key::Named(NamedKey::LaunchWebBrowser),
|
Explorer => Key::Named(NamedKey::LaunchWebBrowser),
|
||||||
Envelope => Key::Named(NamedKey::LaunchMail),
|
Envelope => Key::Named(NamedKey::LaunchMail),
|
||||||
@@ -339,8 +341,8 @@ pub fn to_logical(key_char: Option<KeyMapChar>, keycode: Keycode) -> Key {
|
|||||||
CtrlRight => Key::Named(NamedKey::Control),
|
CtrlRight => Key::Named(NamedKey::Control),
|
||||||
CapsLock => Key::Named(NamedKey::CapsLock),
|
CapsLock => Key::Named(NamedKey::CapsLock),
|
||||||
ScrollLock => Key::Named(NamedKey::ScrollLock),
|
ScrollLock => Key::Named(NamedKey::ScrollLock),
|
||||||
MetaLeft => Key::Named(NamedKey::Super),
|
MetaLeft => Key::Named(NamedKey::Meta),
|
||||||
MetaRight => Key::Named(NamedKey::Super),
|
MetaRight => Key::Named(NamedKey::Meta),
|
||||||
Function => Key::Named(NamedKey::Fn),
|
Function => Key::Named(NamedKey::Fn),
|
||||||
Sysrq => Key::Named(NamedKey::PrintScreen),
|
Sysrq => Key::Named(NamedKey::PrintScreen),
|
||||||
Break => Key::Named(NamedKey::Pause),
|
Break => Key::Named(NamedKey::Pause),
|
||||||
165
winit-android/src/lib.rs
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
//! # Android
|
||||||
|
//!
|
||||||
|
//! The Android backend builds on (and exposes types from) the [`ndk`](https://docs.rs/ndk/) crate.
|
||||||
|
//!
|
||||||
|
//! 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
|
||||||
|
//! various life-cycle events and synchronizing with the main JVM thread.
|
||||||
|
//!
|
||||||
|
//! Winit uses the [android-activity](https://docs.rs/android-activity/) as a
|
||||||
|
//! glue crate (prior to `0.28` it used
|
||||||
|
//! [ndk-glue](https://github.com/rust-windowing/android-ndk-rs/tree/master/ndk-glue)).
|
||||||
|
//!
|
||||||
|
//! 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
|
||||||
|
//! application's main entry point. If Cargo resolves multiple versions, they will
|
||||||
|
//! clash.
|
||||||
|
//!
|
||||||
|
//! `winit` glue compatibility table:
|
||||||
|
//!
|
||||||
|
//! | winit | ndk-glue |
|
||||||
|
//! | :---: | :--------------------------: |
|
||||||
|
//! | 0.30 | `android-activity = "0.6"` |
|
||||||
|
//! | 0.29 | `android-activity = "0.5"` |
|
||||||
|
//! | 0.28 | `android-activity = "0.4"` |
|
||||||
|
//! | 0.27 | `ndk-glue = "0.7"` |
|
||||||
|
//! | 0.26 | `ndk-glue = "0.5"` |
|
||||||
|
//! | 0.25 | `ndk-glue = "0.3"` |
|
||||||
|
//! | 0.24 | `ndk-glue = "0.2"` |
|
||||||
|
//!
|
||||||
|
//! The recommended way to avoid a conflict with the glue version is to avoid explicitly
|
||||||
|
//! depending on the `android-activity` crate, and instead consume the API that
|
||||||
|
//! 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:
|
||||||
|
//!
|
||||||
|
//! ```toml
|
||||||
|
//! [lib]
|
||||||
|
//! name = "main"
|
||||||
|
//! crate-type = ["cdylib"]
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! All Android applications are based on an `Activity` subclass, and the
|
||||||
|
//! `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:
|
||||||
|
//!
|
||||||
|
//! | 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.|
|
||||||
|
//! | [`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
|
||||||
|
//! [`GameTextInput`]: https://developer.android.com/games/agdk/add-support-for-text-input
|
||||||
|
//! [`AndroidAppCompat`]: https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity
|
||||||
|
//! [agdk_jetpack]: https://developer.android.com/jetpack/androidx/releases/games
|
||||||
|
//! [agdk_releases]: https://developer.android.com/games/agdk/download#agdk-libraries
|
||||||
|
//! [Gradle]: https://developer.android.com/studio/build
|
||||||
|
//!
|
||||||
|
//! For more details, refer to these `android-activity` [example applications](https://github.com/rust-mobile/android-activity/tree/main/examples).
|
||||||
|
//!
|
||||||
|
//! ## 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:
|
||||||
|
//! 1. Remove `ndk-glue` from your `Cargo.toml`
|
||||||
|
//! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.30.12",
|
||||||
|
//! features = [ "android-native-activity" ] }`
|
||||||
|
//! 3. Add an `android_main` entrypoint (as above), instead of using the '`[ndk_glue::main]` proc
|
||||||
|
//! macro from `ndk-macros` (optionally add a dependency on `android_logger` and initialize
|
||||||
|
//! logging as above).
|
||||||
|
//! 4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your
|
||||||
|
//! event loop (as shown above).
|
||||||
|
#![cfg(target_os = "android")]
|
||||||
|
|
||||||
|
mod event_loop;
|
||||||
|
mod keycodes;
|
||||||
|
|
||||||
|
use winit_core::event_loop::ActiveEventLoop as CoreActiveEventLoop;
|
||||||
|
use winit_core::window::Window as CoreWindow;
|
||||||
|
|
||||||
|
use self::activity::{AndroidApp, ConfigurationRef, Rect};
|
||||||
|
pub use crate::event_loop::{
|
||||||
|
ActiveEventLoop, EventLoop, EventLoopProxy, PlatformSpecificEventLoopAttributes,
|
||||||
|
PlatformSpecificWindowAttributes, Window,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoop`] that are specific to Android.
|
||||||
|
pub trait EventLoopExtAndroid {
|
||||||
|
/// Get the [`AndroidApp`] which was used to create this event loop.
|
||||||
|
fn android_app(&self) -> &AndroidApp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`ActiveEventLoop`] that are specific to Android.
|
||||||
|
pub trait ActiveEventLoopExtAndroid {
|
||||||
|
/// Get the [`AndroidApp`] which was used to create this event loop.
|
||||||
|
fn android_app(&self) -> &AndroidApp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`Window`] that are specific to Android.
|
||||||
|
pub trait WindowExtAndroid {
|
||||||
|
fn content_rect(&self) -> Rect;
|
||||||
|
|
||||||
|
fn config(&self) -> ConfigurationRef;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowExtAndroid for dyn CoreWindow + '_ {
|
||||||
|
fn content_rect(&self) -> Rect {
|
||||||
|
let window = self.cast_ref::<Window>().unwrap();
|
||||||
|
window.content_rect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn config(&self) -> ConfigurationRef {
|
||||||
|
let window = self.cast_ref::<Window>().unwrap();
|
||||||
|
window.config()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActiveEventLoopExtAndroid for dyn CoreActiveEventLoop + '_ {
|
||||||
|
fn android_app(&self) -> &AndroidApp {
|
||||||
|
let event_loop = self.cast_ref::<ActiveEventLoop>().unwrap();
|
||||||
|
&event_loop.app
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait EventLoopBuilderExtAndroid {
|
||||||
|
/// Associates the [`AndroidApp`] that was passed to `android_main()` with the event loop
|
||||||
|
///
|
||||||
|
/// This must be called on Android since the [`AndroidApp`] is not global state.
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-export of the `android_activity` API
|
||||||
|
///
|
||||||
|
/// Winit re-exports the `android_activity` API for convenience so that most
|
||||||
|
/// applications can rely on the Winit crate to resolve the required version of
|
||||||
|
/// `android_activity` and avoid any chance of a conflict between Winit and the
|
||||||
|
/// application crate.
|
||||||
|
///
|
||||||
|
/// Unlike most libraries there can only be a single implementation
|
||||||
|
/// of the `android_activity` glue crate linked with an application because
|
||||||
|
/// it is responsible for the application's `android_main()` entry point.
|
||||||
|
///
|
||||||
|
/// Since Winit depends on a specific version of `android_activity` the simplest
|
||||||
|
/// way to avoid creating a conflict is for applications to avoid explicitly
|
||||||
|
/// depending on the `android_activity` crate, and instead consume the API that
|
||||||
|
/// is re-exported by Winit.
|
||||||
|
///
|
||||||
|
/// For compatibility applications should then import the [`AndroidApp`] type for
|
||||||
|
/// their `android_main(app: AndroidApp)` function like:
|
||||||
|
/// ```rust
|
||||||
|
/// #[cfg(target_os = "android")]
|
||||||
|
/// use winit::platform::android::activity::AndroidApp;
|
||||||
|
/// ```
|
||||||
|
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)]
|
||||||
|
pub use android_activity::*;
|
||||||
|
}
|
||||||
116
winit-appkit/Cargo.toml
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
[package]
|
||||||
|
description = "Winit's Appkit / macOS backend"
|
||||||
|
documentation = "https://docs.rs/winit-appkit"
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
name = "winit-appkit"
|
||||||
|
repository.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
version.workspace = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
serde = ["dep:serde", "bitflags/serde", "smol_str/serde", "dpi/serde"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
bitflags.workspace = true
|
||||||
|
dpi.workspace = true
|
||||||
|
rwh_06.workspace = true
|
||||||
|
serde = { workspace = true, optional = true }
|
||||||
|
smol_str.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
winit-common = { workspace = true, features = ["core-foundation", "event-handler"] }
|
||||||
|
winit-core.workspace = true
|
||||||
|
|
||||||
|
# Platform-specific
|
||||||
|
[target.'cfg(target_vendor = "apple")'.dependencies]
|
||||||
|
block2.workspace = true
|
||||||
|
dispatch2 = { workspace = true, features = ["std", "objc2"] }
|
||||||
|
objc2.workspace = true
|
||||||
|
objc2-app-kit = { workspace = true, features = [
|
||||||
|
"std",
|
||||||
|
"objc2-core-foundation",
|
||||||
|
"NSAppearance",
|
||||||
|
"NSApplication",
|
||||||
|
"NSBitmapImageRep",
|
||||||
|
"NSButton",
|
||||||
|
"NSColor",
|
||||||
|
"NSControl",
|
||||||
|
"NSCursor",
|
||||||
|
"NSDragging",
|
||||||
|
"NSEvent",
|
||||||
|
"NSGraphics",
|
||||||
|
"NSGraphicsContext",
|
||||||
|
"NSImage",
|
||||||
|
"NSImageRep",
|
||||||
|
"NSMenu",
|
||||||
|
"NSMenuItem",
|
||||||
|
"NSOpenGLView",
|
||||||
|
"NSPanel",
|
||||||
|
"NSPasteboard",
|
||||||
|
"NSResponder",
|
||||||
|
"NSRunningApplication",
|
||||||
|
"NSScreen",
|
||||||
|
"NSTextInputClient",
|
||||||
|
"NSTextInputContext",
|
||||||
|
"NSToolbar",
|
||||||
|
"NSView",
|
||||||
|
"NSWindow",
|
||||||
|
"NSWindowScripting",
|
||||||
|
"NSWindowTabGroup",
|
||||||
|
] }
|
||||||
|
objc2-core-foundation = { workspace = true, features = [
|
||||||
|
"std",
|
||||||
|
"block2",
|
||||||
|
"CFBase",
|
||||||
|
"CFCGTypes",
|
||||||
|
"CFData",
|
||||||
|
"CFRunLoop",
|
||||||
|
"CFString",
|
||||||
|
"CFUUID",
|
||||||
|
] }
|
||||||
|
objc2-core-graphics = { workspace = true, features = [
|
||||||
|
"std",
|
||||||
|
"libc",
|
||||||
|
"CGDirectDisplay",
|
||||||
|
"CGDisplayConfiguration",
|
||||||
|
"CGDisplayFade",
|
||||||
|
"CGError",
|
||||||
|
"CGRemoteOperation",
|
||||||
|
"CGWindowLevel",
|
||||||
|
] }
|
||||||
|
objc2-core-video = { workspace = true, features = [
|
||||||
|
"std",
|
||||||
|
"objc2-core-graphics",
|
||||||
|
"CVBase",
|
||||||
|
"CVReturn",
|
||||||
|
"CVDisplayLink",
|
||||||
|
] }
|
||||||
|
objc2-foundation = { workspace = true, features = [
|
||||||
|
"std",
|
||||||
|
"block2",
|
||||||
|
"objc2-core-foundation",
|
||||||
|
"NSArray",
|
||||||
|
"NSAttributedString",
|
||||||
|
"NSData",
|
||||||
|
"NSDictionary",
|
||||||
|
"NSDistributedNotificationCenter",
|
||||||
|
"NSEnumerator",
|
||||||
|
"NSGeometry",
|
||||||
|
"NSKeyValueObserving",
|
||||||
|
"NSNotification",
|
||||||
|
"NSObjCRuntime",
|
||||||
|
"NSOperation",
|
||||||
|
"NSPathUtilities",
|
||||||
|
"NSProcessInfo",
|
||||||
|
"NSRunLoop",
|
||||||
|
"NSString",
|
||||||
|
"NSThread",
|
||||||
|
"NSValue",
|
||||||
|
] }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
winit.workspace = true
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
all-features = true
|
||||||
|
targets = ["aarch64-apple-darwin", "x86_64-apple-darwin"]
|
||||||
1
winit-appkit/LICENSE
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE
|
||||||
1
winit-appkit/README.md
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../README.md
|
||||||
188
winit-appkit/src/app.rs
Normal file
@@ -0,0 +1,188 @@
|
|||||||
|
#![allow(clippy::unnecessary_cast)]
|
||||||
|
|
||||||
|
use std::cell::Cell;
|
||||||
|
use std::mem;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
|
use dispatch2::MainThreadBound;
|
||||||
|
use objc2::runtime::{Imp, Sel};
|
||||||
|
use objc2::sel;
|
||||||
|
use objc2_app_kit::{NSApplication, NSEvent, NSEventModifierFlags, NSEventType};
|
||||||
|
use objc2_foundation::MainThreadMarker;
|
||||||
|
use winit_core::event::{DeviceEvent, ElementState};
|
||||||
|
|
||||||
|
use super::app_state::AppState;
|
||||||
|
|
||||||
|
type SendEvent = extern "C-unwind" fn(&NSApplication, Sel, &NSEvent);
|
||||||
|
|
||||||
|
static ORIGINAL: MainThreadBound<Cell<Option<SendEvent>>> = {
|
||||||
|
// SAFETY: Creating in a `const` context, where there is no concept of the main thread.
|
||||||
|
MainThreadBound::new(Cell::new(None), unsafe { MainThreadMarker::new_unchecked() })
|
||||||
|
};
|
||||||
|
|
||||||
|
extern "C-unwind" fn send_event(app: &NSApplication, sel: Sel, event: &NSEvent) {
|
||||||
|
let mtm = MainThreadMarker::from(app);
|
||||||
|
|
||||||
|
// Normally, holding Cmd + any key never sends us a `keyUp` event for that key.
|
||||||
|
// Overriding `sendEvent:` fixes that. (https://stackoverflow.com/a/15294196)
|
||||||
|
// Fun fact: Firefox still has this bug! (https://bugzilla.mozilla.org/show_bug.cgi?id=1299553)
|
||||||
|
//
|
||||||
|
// For posterity, there are some undocumented event types
|
||||||
|
// (https://github.com/servo/cocoa-rs/issues/155)
|
||||||
|
// but that doesn't really matter here.
|
||||||
|
let event_type = unsafe { event.r#type() };
|
||||||
|
let modifier_flags = unsafe { event.modifierFlags() };
|
||||||
|
if event_type == NSEventType::KeyUp && modifier_flags.contains(NSEventModifierFlags::Command) {
|
||||||
|
if let Some(key_window) = app.keyWindow() {
|
||||||
|
key_window.sendEvent(event);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Events are generally scoped to the window level, so the best way
|
||||||
|
// to get device events is to listen for them on NSApplication.
|
||||||
|
let app_state = AppState::get(mtm);
|
||||||
|
maybe_dispatch_device_event(&app_state, event);
|
||||||
|
|
||||||
|
let original = ORIGINAL.get(mtm).get().expect("no existing sendEvent: handler set");
|
||||||
|
original(app, sel, event)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Override the [`sendEvent:`][NSApplication::sendEvent] method on the given application class.
|
||||||
|
///
|
||||||
|
/// The previous implementation created a subclass of [`NSApplication`], however we would like to
|
||||||
|
/// give the user full control over their `NSApplication`, so we override the method here using
|
||||||
|
/// method swizzling instead.
|
||||||
|
///
|
||||||
|
/// This _should_ also allow two versions of Winit to exist in the same application.
|
||||||
|
///
|
||||||
|
/// See the following links for more info on method swizzling:
|
||||||
|
/// - <https://nshipster.com/method-swizzling/>
|
||||||
|
/// - <https://spin.atomicobject.com/method-swizzling-objective-c/>
|
||||||
|
/// - <https://web.archive.org/web/20130308110627/http://cocoadev.com/wiki/MethodSwizzling>
|
||||||
|
///
|
||||||
|
/// NOTE: This function assumes that the passed in application object is the one returned from
|
||||||
|
/// [`NSApplication::sharedApplication`], i.e. the one and only global shared application object.
|
||||||
|
/// For testing though, we allow it to be a different object.
|
||||||
|
pub(crate) fn override_send_event(global_app: &NSApplication) {
|
||||||
|
let mtm = MainThreadMarker::from(global_app);
|
||||||
|
let class = global_app.class();
|
||||||
|
|
||||||
|
let method =
|
||||||
|
class.instance_method(sel!(sendEvent:)).expect("NSApplication must have sendEvent: method");
|
||||||
|
|
||||||
|
// SAFETY: Converting our `sendEvent:` implementation to an IMP.
|
||||||
|
let overridden = unsafe { mem::transmute::<SendEvent, Imp>(send_event) };
|
||||||
|
|
||||||
|
// If we've already overridden the method, don't do anything.
|
||||||
|
// FIXME(madsmtm): Use `std::ptr::fn_addr_eq` (Rust 1.85) once available in MSRV.
|
||||||
|
#[allow(unknown_lints, unpredictable_function_pointer_comparisons)]
|
||||||
|
if overridden == method.implementation() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// SAFETY: Our implementation has:
|
||||||
|
// 1. The same signature as `sendEvent:`.
|
||||||
|
// 2. Does not impose extra safety requirements on callers.
|
||||||
|
let original = unsafe { method.set_implementation(overridden) };
|
||||||
|
|
||||||
|
// SAFETY: This is the actual signature of `sendEvent:`.
|
||||||
|
let original = unsafe { mem::transmute::<Imp, SendEvent>(original) };
|
||||||
|
|
||||||
|
// NOTE: If NSApplication was safe to use from multiple threads, then this would potentially be
|
||||||
|
// a (checked) race-condition, since one could call `sendEvent:` before the original had been
|
||||||
|
// stored here.
|
||||||
|
//
|
||||||
|
// It is only usable from the main thread, however, so we're good!
|
||||||
|
ORIGINAL.get(mtm).set(Some(original));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn maybe_dispatch_device_event(app_state: &Rc<AppState>, event: &NSEvent) {
|
||||||
|
let event_type = unsafe { event.r#type() };
|
||||||
|
#[allow(non_upper_case_globals)]
|
||||||
|
match event_type {
|
||||||
|
NSEventType::MouseMoved
|
||||||
|
| NSEventType::LeftMouseDragged
|
||||||
|
| NSEventType::OtherMouseDragged
|
||||||
|
| NSEventType::RightMouseDragged => {
|
||||||
|
let delta_x = unsafe { event.deltaX() } as f64;
|
||||||
|
let delta_y = unsafe { event.deltaY() } as f64;
|
||||||
|
|
||||||
|
if delta_x != 0.0 || delta_y != 0.0 {
|
||||||
|
app_state.maybe_queue_with_handler(move |app, event_loop| {
|
||||||
|
app.device_event(event_loop, None, DeviceEvent::PointerMotion {
|
||||||
|
delta: (delta_x, delta_y),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
NSEventType::LeftMouseDown | NSEventType::RightMouseDown | NSEventType::OtherMouseDown => {
|
||||||
|
let button = unsafe { event.buttonNumber() } as u32;
|
||||||
|
app_state.maybe_queue_with_handler(move |app, event_loop| {
|
||||||
|
app.device_event(event_loop, None, DeviceEvent::Button {
|
||||||
|
button,
|
||||||
|
state: ElementState::Pressed,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
NSEventType::LeftMouseUp | NSEventType::RightMouseUp | NSEventType::OtherMouseUp => {
|
||||||
|
let button = unsafe { event.buttonNumber() } as u32;
|
||||||
|
app_state.maybe_queue_with_handler(move |app, event_loop| {
|
||||||
|
app.device_event(event_loop, None, DeviceEvent::Button {
|
||||||
|
button,
|
||||||
|
state: ElementState::Released,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use objc2::rc::Retained;
|
||||||
|
use objc2::{define_class, msg_send, ClassType};
|
||||||
|
use objc2_app_kit::NSResponder;
|
||||||
|
use objc2_foundation::NSObject;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_override() {
|
||||||
|
// FIXME(madsmtm): Ensure this always runs (maybe use cargo-nextest or `--test-threads=1`?)
|
||||||
|
let Some(mtm) = MainThreadMarker::new() else { return };
|
||||||
|
|
||||||
|
// Create a new application, without making it the shared application.
|
||||||
|
let app = unsafe { NSApplication::new(mtm) };
|
||||||
|
override_send_event(&app);
|
||||||
|
// Test calling twice works.
|
||||||
|
override_send_event(&app);
|
||||||
|
|
||||||
|
// FIXME(madsmtm): Can't test this yet, need some way to mock AppState.
|
||||||
|
// unsafe {
|
||||||
|
// let event = super::super::event::dummy_event().unwrap();
|
||||||
|
// app.sendEvent(&event)
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_custom_class() {
|
||||||
|
let Some(_mtm) = MainThreadMarker::new() else { return };
|
||||||
|
|
||||||
|
define_class!(
|
||||||
|
#[unsafe(super(NSApplication, NSResponder, NSObject))]
|
||||||
|
#[name = "TestApplication"]
|
||||||
|
pub(super) struct TestApplication;
|
||||||
|
|
||||||
|
impl TestApplication {
|
||||||
|
#[unsafe(method(sendEvent:))]
|
||||||
|
fn send_event(&self, _event: &NSEvent) {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
let app: Retained<TestApplication> = unsafe { msg_send![TestApplication::class(), new] };
|
||||||
|
override_send_event(&app);
|
||||||
|
}
|
||||||
|
}
|
||||||
383
winit-appkit/src/app_state.rs
Normal file
@@ -0,0 +1,383 @@
|
|||||||
|
use std::cell::{Cell, OnceCell, RefCell};
|
||||||
|
use std::mem;
|
||||||
|
use std::rc::Rc;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use dispatch2::MainThreadBound;
|
||||||
|
use objc2::MainThreadMarker;
|
||||||
|
use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy, NSRunningApplication};
|
||||||
|
use objc2_foundation::NSNotification;
|
||||||
|
use winit_common::core_foundation::EventLoopProxy;
|
||||||
|
use winit_common::event_handler::EventHandler;
|
||||||
|
use winit_core::application::ApplicationHandler;
|
||||||
|
use winit_core::event::{StartCause, WindowEvent};
|
||||||
|
use winit_core::event_loop::ControlFlow;
|
||||||
|
use winit_core::window::WindowId;
|
||||||
|
|
||||||
|
use super::event_loop::{notify_windows_of_exit, stop_app_immediately, ActiveEventLoop};
|
||||||
|
use super::menu;
|
||||||
|
use super::observer::{EventLoopWaker, RunLoop};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(super) struct AppState {
|
||||||
|
mtm: MainThreadMarker,
|
||||||
|
activation_policy: Option<NSApplicationActivationPolicy>,
|
||||||
|
default_menu: bool,
|
||||||
|
activate_ignoring_other_apps: bool,
|
||||||
|
run_loop: RunLoop,
|
||||||
|
event_loop_proxy: Arc<EventLoopProxy>,
|
||||||
|
event_handler: EventHandler,
|
||||||
|
stop_on_launch: Cell<bool>,
|
||||||
|
stop_before_wait: Cell<bool>,
|
||||||
|
stop_after_wait: Cell<bool>,
|
||||||
|
stop_on_redraw: Cell<bool>,
|
||||||
|
/// Whether `applicationDidFinishLaunching:` has been run or not.
|
||||||
|
is_launched: Cell<bool>,
|
||||||
|
/// Whether an `EventLoop` is currently running.
|
||||||
|
is_running: Cell<bool>,
|
||||||
|
/// Whether the user has requested the event loop to exit.
|
||||||
|
exit: Cell<bool>,
|
||||||
|
control_flow: Cell<ControlFlow>,
|
||||||
|
waker: RefCell<EventLoopWaker>,
|
||||||
|
start_time: Cell<Option<Instant>>,
|
||||||
|
wait_timeout: Cell<Option<Instant>>,
|
||||||
|
pending_redraw: RefCell<Vec<WindowId>>,
|
||||||
|
// NOTE: This is strongly referenced by our `NSWindowDelegate` and our `NSView` subclass, and
|
||||||
|
// as such should be careful to not add fields that, in turn, strongly reference those.
|
||||||
|
}
|
||||||
|
|
||||||
|
// SAFETY: Creating `MainThreadBound` in a `const` context, where there is no concept of the
|
||||||
|
// main thread.
|
||||||
|
static GLOBAL: MainThreadBound<OnceCell<Rc<AppState>>> =
|
||||||
|
MainThreadBound::new(OnceCell::new(), unsafe { MainThreadMarker::new_unchecked() });
|
||||||
|
|
||||||
|
impl AppState {
|
||||||
|
pub(super) fn setup_global(
|
||||||
|
mtm: MainThreadMarker,
|
||||||
|
activation_policy: Option<NSApplicationActivationPolicy>,
|
||||||
|
default_menu: bool,
|
||||||
|
activate_ignoring_other_apps: bool,
|
||||||
|
) -> Option<Rc<Self>> {
|
||||||
|
let event_loop_proxy = Arc::new(EventLoopProxy::new(mtm, move || {
|
||||||
|
Self::get(mtm).with_handler(|app, event_loop| app.proxy_wake_up(event_loop));
|
||||||
|
}));
|
||||||
|
|
||||||
|
let this = Rc::new(Self {
|
||||||
|
mtm,
|
||||||
|
activation_policy,
|
||||||
|
default_menu,
|
||||||
|
activate_ignoring_other_apps,
|
||||||
|
run_loop: RunLoop::main(mtm),
|
||||||
|
event_loop_proxy,
|
||||||
|
event_handler: EventHandler::new(),
|
||||||
|
stop_on_launch: Cell::new(false),
|
||||||
|
stop_before_wait: Cell::new(false),
|
||||||
|
stop_after_wait: Cell::new(false),
|
||||||
|
stop_on_redraw: Cell::new(false),
|
||||||
|
is_launched: Cell::new(false),
|
||||||
|
is_running: Cell::new(false),
|
||||||
|
exit: Cell::new(false),
|
||||||
|
control_flow: Cell::new(ControlFlow::default()),
|
||||||
|
waker: RefCell::new(EventLoopWaker::new()),
|
||||||
|
start_time: Cell::new(None),
|
||||||
|
wait_timeout: Cell::new(None),
|
||||||
|
pending_redraw: RefCell::new(vec![]),
|
||||||
|
});
|
||||||
|
|
||||||
|
GLOBAL.get(mtm).set(this.clone()).ok().and(Some(this))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(mtm: MainThreadMarker) -> Rc<Self> {
|
||||||
|
GLOBAL
|
||||||
|
.get(mtm)
|
||||||
|
.get()
|
||||||
|
.expect("tried to get application state before it was registered")
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
// NOTE: This notification will, globally, only be emitted once,
|
||||||
|
// no matter how many `EventLoop`s the user creates.
|
||||||
|
pub fn did_finish_launching(self: &Rc<Self>, _notification: &NSNotification) {
|
||||||
|
trace_scope!("NSApplicationDidFinishLaunchingNotification");
|
||||||
|
self.is_launched.set(true);
|
||||||
|
|
||||||
|
let app = NSApplication::sharedApplication(self.mtm);
|
||||||
|
// We need to delay setting the activation policy and activating the app
|
||||||
|
// until `applicationDidFinishLaunching` has been called. Otherwise the
|
||||||
|
// menu bar is initially unresponsive on macOS 10.15.
|
||||||
|
if let Some(activation_policy) = self.activation_policy {
|
||||||
|
app.setActivationPolicy(activation_policy);
|
||||||
|
} else {
|
||||||
|
// If no activation policy is explicitly provided, and the application
|
||||||
|
// is bundled, do not set the activation policy at all, to allow the
|
||||||
|
// package manifest to define the behavior via LSUIElement.
|
||||||
|
//
|
||||||
|
// See:
|
||||||
|
// - https://github.com/rust-windowing/winit/issues/261
|
||||||
|
// - https://github.com/rust-windowing/winit/issues/3958
|
||||||
|
let is_bundled =
|
||||||
|
unsafe { NSRunningApplication::currentApplication().bundleIdentifier().is_some() };
|
||||||
|
if !is_bundled {
|
||||||
|
app.setActivationPolicy(NSApplicationActivationPolicy::Regular);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(deprecated)]
|
||||||
|
app.activateIgnoringOtherApps(self.activate_ignoring_other_apps);
|
||||||
|
|
||||||
|
if self.default_menu {
|
||||||
|
// The menubar initialization should be before the `NewEvents` event, to allow
|
||||||
|
// overriding of the default menu even if it's created
|
||||||
|
menu::initialize(&app);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.waker.borrow_mut().start();
|
||||||
|
|
||||||
|
self.set_is_running(true);
|
||||||
|
self.dispatch_init_events();
|
||||||
|
|
||||||
|
// If the application is being launched via `EventLoop::pump_app_events()` then we'll
|
||||||
|
// want to stop the app once it is launched (and return to the external loop)
|
||||||
|
//
|
||||||
|
// In this case we still want to consider Winit's `EventLoop` to be "running",
|
||||||
|
// so we call `start_running()` above.
|
||||||
|
if self.stop_on_launch.get() {
|
||||||
|
// NOTE: the original idea had been to only stop the underlying `RunLoop`
|
||||||
|
// for the app but that didn't work as expected (`-[NSApplication run]`
|
||||||
|
// effectively ignored the attempt to stop the RunLoop and re-started it).
|
||||||
|
//
|
||||||
|
// So we return from `pump_events` by stopping the application.
|
||||||
|
let app = NSApplication::sharedApplication(self.mtm);
|
||||||
|
stop_app_immediately(&app);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn will_terminate(self: &Rc<Self>, _notification: &NSNotification) {
|
||||||
|
trace_scope!("NSApplicationWillTerminateNotification");
|
||||||
|
let app = NSApplication::sharedApplication(self.mtm);
|
||||||
|
notify_windows_of_exit(&app);
|
||||||
|
self.event_handler.terminate();
|
||||||
|
self.internal_exit();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Place the event handler in the application state for the duration
|
||||||
|
/// of the given closure.
|
||||||
|
pub fn set_event_handler<R>(
|
||||||
|
&self,
|
||||||
|
handler: impl ApplicationHandler,
|
||||||
|
closure: impl FnOnce() -> R,
|
||||||
|
) -> R {
|
||||||
|
self.event_handler.set(Box::new(handler), closure)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn event_loop_proxy(&self) -> &Arc<EventLoopProxy> {
|
||||||
|
&self.event_loop_proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
/// If `pump_events` is called to progress the event loop then we
|
||||||
|
/// bootstrap the event loop via `-[NSApplication run]` but will use
|
||||||
|
/// `CFRunLoopRunInMode` for subsequent calls to `pump_events`.
|
||||||
|
pub fn set_stop_on_launch(&self) {
|
||||||
|
self.stop_on_launch.set(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_stop_before_wait(&self, value: bool) {
|
||||||
|
self.stop_before_wait.set(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_stop_after_wait(&self, value: bool) {
|
||||||
|
self.stop_after_wait.set(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_stop_on_redraw(&self, value: bool) {
|
||||||
|
self.stop_on_redraw.set(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_wait_timeout(&self, value: Option<Instant>) {
|
||||||
|
self.wait_timeout.set(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clears the `running` state and resets the `control_flow` state when an `EventLoop` exits.
|
||||||
|
///
|
||||||
|
/// NOTE: that if the `NSApplication` has been launched then that state is preserved,
|
||||||
|
/// and we won't need to re-launch the app if subsequent EventLoops are run.
|
||||||
|
pub fn internal_exit(self: &Rc<Self>) {
|
||||||
|
self.set_is_running(false);
|
||||||
|
self.set_stop_on_redraw(false);
|
||||||
|
self.set_stop_before_wait(false);
|
||||||
|
self.set_stop_after_wait(false);
|
||||||
|
self.set_wait_timeout(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_launched(&self) -> bool {
|
||||||
|
self.is_launched.get()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_is_running(&self, value: bool) {
|
||||||
|
self.is_running.set(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_running(&self) -> bool {
|
||||||
|
self.is_running.get()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn exit(&self) {
|
||||||
|
self.exit.set(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_exit(&self) {
|
||||||
|
self.exit.set(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn exiting(&self) -> bool {
|
||||||
|
self.exit.get()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_control_flow(&self, value: ControlFlow) {
|
||||||
|
self.control_flow.set(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn control_flow(&self) -> ControlFlow {
|
||||||
|
self.control_flow.get()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn handle_redraw(self: &Rc<Self>, window_id: WindowId) {
|
||||||
|
// Redraw request might come out of order from the OS.
|
||||||
|
// -> Don't go back into the event handler when our callstack originates from there
|
||||||
|
if !self.event_handler.in_use() {
|
||||||
|
self.with_handler(|app, event_loop| {
|
||||||
|
app.window_event(event_loop, window_id, WindowEvent::RedrawRequested);
|
||||||
|
});
|
||||||
|
|
||||||
|
// `pump_events` will request to stop immediately _after_ dispatching RedrawRequested
|
||||||
|
// events as a way to ensure that `pump_events` can't block an external loop
|
||||||
|
// indefinitely
|
||||||
|
if self.stop_on_redraw.get() {
|
||||||
|
let app = NSApplication::sharedApplication(self.mtm);
|
||||||
|
stop_app_immediately(&app);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn queue_redraw(&self, window_id: WindowId) {
|
||||||
|
let mut pending_redraw = self.pending_redraw.borrow_mut();
|
||||||
|
if !pending_redraw.contains(&window_id) {
|
||||||
|
pending_redraw.push(window_id);
|
||||||
|
}
|
||||||
|
self.run_loop.wakeup();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[track_caller]
|
||||||
|
pub fn maybe_queue_with_handler(
|
||||||
|
self: &Rc<Self>,
|
||||||
|
callback: impl FnOnce(&mut dyn ApplicationHandler, &ActiveEventLoop) + 'static,
|
||||||
|
) {
|
||||||
|
// Most programmer actions in AppKit (e.g. change window fullscreen, set focused, etc.)
|
||||||
|
// result in an event being queued, and applied at a later point.
|
||||||
|
//
|
||||||
|
// However, it is not documented which actions do this, and which ones are done immediately,
|
||||||
|
// so to make sure that we don't encounter re-entrancy issues, we first check if we're
|
||||||
|
// currently handling another event, and if we are, we queue the event instead.
|
||||||
|
if !self.event_handler.in_use() {
|
||||||
|
self.with_handler(callback);
|
||||||
|
} else {
|
||||||
|
tracing::debug!("had to queue event since another is currently being handled");
|
||||||
|
let this = Rc::clone(self);
|
||||||
|
self.run_loop.queue_closure(move || {
|
||||||
|
this.with_handler(callback);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[track_caller]
|
||||||
|
fn with_handler(
|
||||||
|
self: &Rc<Self>,
|
||||||
|
callback: impl FnOnce(&mut dyn ApplicationHandler, &ActiveEventLoop),
|
||||||
|
) {
|
||||||
|
let event_loop = ActiveEventLoop { app_state: Rc::clone(self), mtm: self.mtm };
|
||||||
|
self.event_handler.handle(|app| callback(app, &event_loop));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// dispatch `NewEvents(Init)` + `Resumed`
|
||||||
|
pub fn dispatch_init_events(self: &Rc<Self>) {
|
||||||
|
self.with_handler(|app, event_loop| app.new_events(event_loop, StartCause::Init));
|
||||||
|
// NB: For consistency all platforms must call `can_create_surfaces` even though macOS
|
||||||
|
// applications don't themselves have a formal surface destroy/create lifecycle.
|
||||||
|
self.with_handler(|app, event_loop| app.can_create_surfaces(event_loop));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Called by RunLoopObserver after finishing waiting for new events
|
||||||
|
pub fn wakeup(self: &Rc<Self>) {
|
||||||
|
// Return when in event handler due to https://github.com/rust-windowing/winit/issues/1779
|
||||||
|
if !self.event_handler.ready() || !self.is_running() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.stop_after_wait.get() {
|
||||||
|
let app = NSApplication::sharedApplication(self.mtm);
|
||||||
|
stop_app_immediately(&app);
|
||||||
|
}
|
||||||
|
|
||||||
|
let start = self.start_time.get().unwrap();
|
||||||
|
let cause = match self.control_flow() {
|
||||||
|
ControlFlow::Poll => StartCause::Poll,
|
||||||
|
ControlFlow::Wait => StartCause::WaitCancelled { start, requested_resume: None },
|
||||||
|
ControlFlow::WaitUntil(requested_resume) => {
|
||||||
|
if Instant::now() >= requested_resume {
|
||||||
|
StartCause::ResumeTimeReached { start, requested_resume }
|
||||||
|
} else {
|
||||||
|
StartCause::WaitCancelled { start, requested_resume: Some(requested_resume) }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
self.with_handler(|app, event_loop| app.new_events(event_loop, cause));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Called by RunLoopObserver before waiting for new events
|
||||||
|
pub fn cleared(self: &Rc<Self>) {
|
||||||
|
// Return when in event handler due to https://github.com/rust-windowing/winit/issues/1779
|
||||||
|
// XXX: how does it make sense that `event_handler.ready()` can ever return `false` here if
|
||||||
|
// we're about to return to the `CFRunLoop` to poll for new events?
|
||||||
|
if !self.event_handler.ready() || !self.is_running() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let redraw = mem::take(&mut *self.pending_redraw.borrow_mut());
|
||||||
|
for window_id in redraw {
|
||||||
|
self.with_handler(|app, event_loop| {
|
||||||
|
app.window_event(event_loop, window_id, WindowEvent::RedrawRequested);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
self.with_handler(|app, event_loop| {
|
||||||
|
app.about_to_wait(event_loop);
|
||||||
|
});
|
||||||
|
|
||||||
|
if self.exiting() {
|
||||||
|
let app = NSApplication::sharedApplication(self.mtm);
|
||||||
|
stop_app_immediately(&app);
|
||||||
|
notify_windows_of_exit(&app);
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.stop_before_wait.get() {
|
||||||
|
let app = NSApplication::sharedApplication(self.mtm);
|
||||||
|
stop_app_immediately(&app);
|
||||||
|
}
|
||||||
|
self.start_time.set(Some(Instant::now()));
|
||||||
|
let wait_timeout = self.wait_timeout.get(); // configured by pump_events
|
||||||
|
let app_timeout = match self.control_flow() {
|
||||||
|
ControlFlow::Wait => None,
|
||||||
|
ControlFlow::Poll => Some(Instant::now()),
|
||||||
|
ControlFlow::WaitUntil(instant) => Some(instant),
|
||||||
|
};
|
||||||
|
self.waker.borrow_mut().start_at(min_timeout(wait_timeout, app_timeout));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the minimum `Option<Instant>`, taking into account that `None`
|
||||||
|
/// equates to an infinite timeout, not a zero timeout (so can't just use
|
||||||
|
/// `Option::min`)
|
||||||
|
fn min_timeout(a: Option<Instant>, b: Option<Instant>) -> Option<Instant> {
|
||||||
|
a.map_or(b, |a_timeout| b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout))))
|
||||||
|
}
|
||||||
@@ -1,37 +1,47 @@
|
|||||||
use icrate::AppKit::{NSBitmapImageRep, NSCursor, NSDeviceRGBColorSpace, NSImage};
|
|
||||||
use icrate::Foundation::{
|
|
||||||
ns_string, NSData, NSDictionary, NSNumber, NSObject, NSObjectProtocol, NSPoint, NSSize,
|
|
||||||
NSString,
|
|
||||||
};
|
|
||||||
use objc2::rc::Id;
|
|
||||||
use objc2::runtime::Sel;
|
|
||||||
use objc2::{msg_send_id, sel, ClassType};
|
|
||||||
use once_cell::sync::Lazy;
|
|
||||||
use std::ffi::c_uchar;
|
use std::ffi::c_uchar;
|
||||||
use std::slice;
|
use std::slice;
|
||||||
|
use std::sync::OnceLock;
|
||||||
|
|
||||||
use super::EventLoopWindowTarget;
|
use objc2::rc::Retained;
|
||||||
use crate::cursor::CursorImage;
|
use objc2::runtime::Sel;
|
||||||
use crate::cursor::OnlyCursorImageBuilder;
|
use objc2::{available, msg_send, sel, AllocAnyThread, ClassType};
|
||||||
use crate::window::CursorIcon;
|
use objc2_app_kit::{NSBitmapImageRep, NSCursor, NSDeviceRGBColorSpace, NSImage};
|
||||||
|
use objc2_foundation::{
|
||||||
|
ns_string, NSData, NSDictionary, NSNumber, NSObject, NSPoint, NSSize, NSString,
|
||||||
|
};
|
||||||
|
use winit_core::cursor::{CursorIcon, CursorImage, CustomCursorProvider, CustomCursorSource};
|
||||||
|
use winit_core::error::{NotSupportedError, RequestError};
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||||
pub struct CustomCursor(pub(crate) Id<NSCursor>);
|
pub struct CustomCursor(pub(crate) Retained<NSCursor>);
|
||||||
|
|
||||||
|
impl CustomCursorProvider for CustomCursor {
|
||||||
|
fn is_animated(&self) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// SAFETY: NSCursor is immutable and thread-safe
|
// SAFETY: NSCursor is immutable and thread-safe
|
||||||
// TODO(madsmtm): Put this logic in icrate itself
|
// TODO(madsmtm): Put this logic in objc2-app-kit itself
|
||||||
unsafe impl Send for CustomCursor {}
|
unsafe impl Send for CustomCursor {}
|
||||||
unsafe impl Sync for CustomCursor {}
|
unsafe impl Sync for CustomCursor {}
|
||||||
|
|
||||||
impl CustomCursor {
|
impl CustomCursor {
|
||||||
pub(crate) fn build(cursor: OnlyCursorImageBuilder, _: &EventLoopWindowTarget) -> CustomCursor {
|
pub(crate) fn new(cursor: CustomCursorSource) -> Result<CustomCursor, RequestError> {
|
||||||
Self(cursor_from_image(&cursor.0))
|
let cursor = match cursor {
|
||||||
|
CustomCursorSource::Image(cursor_image) => cursor_image,
|
||||||
|
CustomCursorSource::Animation { .. } | CustomCursorSource::Url { .. } => {
|
||||||
|
return Err(NotSupportedError::new("unsupported cursor kind").into())
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
cursor_from_image(&cursor).map(Self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn cursor_from_image(cursor: &CursorImage) -> Id<NSCursor> {
|
pub(crate) fn cursor_from_image(cursor: &CursorImage) -> Result<Retained<NSCursor>, RequestError> {
|
||||||
let width = cursor.width;
|
let width = cursor.width();
|
||||||
let height = cursor.height;
|
let height = cursor.height();
|
||||||
|
|
||||||
let bitmap = unsafe {
|
let bitmap = unsafe {
|
||||||
NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
|
NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
|
||||||
@@ -46,32 +56,33 @@ pub(crate) fn cursor_from_image(cursor: &CursorImage) -> Id<NSCursor> {
|
|||||||
NSDeviceRGBColorSpace,
|
NSDeviceRGBColorSpace,
|
||||||
width as isize * 4,
|
width as isize * 4,
|
||||||
32,
|
32,
|
||||||
).unwrap()
|
)
|
||||||
};
|
}.ok_or_else(|| os_error!("parent view should be installed in a window"))?;
|
||||||
let bitmap_data = unsafe { slice::from_raw_parts_mut(bitmap.bitmapData(), cursor.rgba.len()) };
|
let bitmap_data =
|
||||||
bitmap_data.copy_from_slice(&cursor.rgba);
|
unsafe { slice::from_raw_parts_mut(bitmap.bitmapData(), cursor.buffer().len()) };
|
||||||
|
bitmap_data.copy_from_slice(cursor.buffer());
|
||||||
|
|
||||||
let image = unsafe {
|
let image = unsafe {
|
||||||
NSImage::initWithSize(NSImage::alloc(), NSSize::new(width.into(), height.into()))
|
NSImage::initWithSize(NSImage::alloc(), NSSize::new(width.into(), height.into()))
|
||||||
};
|
};
|
||||||
unsafe { image.addRepresentation(&bitmap) };
|
unsafe { image.addRepresentation(&bitmap) };
|
||||||
|
|
||||||
let hotspot = NSPoint::new(cursor.hotspot_x as f64, cursor.hotspot_y as f64);
|
let hotspot = NSPoint::new(cursor.hotspot_x() as f64, cursor.hotspot_y() as f64);
|
||||||
|
|
||||||
NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot)
|
Ok(NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn default_cursor() -> Id<NSCursor> {
|
pub(crate) fn default_cursor() -> Retained<NSCursor> {
|
||||||
NSCursor::arrowCursor()
|
NSCursor::arrowCursor()
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe fn try_cursor_from_selector(sel: Sel) -> Option<Id<NSCursor>> {
|
unsafe fn try_cursor_from_selector(sel: Sel) -> Option<Retained<NSCursor>> {
|
||||||
let cls = NSCursor::class();
|
let cls = NSCursor::class();
|
||||||
if cls.responds_to(sel) {
|
if unsafe { msg_send![cls, respondsToSelector: sel] } {
|
||||||
let cursor: Id<NSCursor> = unsafe { msg_send_id![cls, performSelector: sel] };
|
let cursor: Retained<NSCursor> = unsafe { msg_send![cls, performSelector: sel] };
|
||||||
Some(cursor)
|
Some(cursor)
|
||||||
} else {
|
} else {
|
||||||
log::warn!("cursor `{sel}` appears to be invalid");
|
tracing::warn!("cursor `{sel}` appears to be invalid");
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -83,7 +94,7 @@ macro_rules! def_undocumented_cursor {
|
|||||||
)*} => {$(
|
)*} => {$(
|
||||||
$(#[$($m)*])*
|
$(#[$($m)*])*
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
fn $name() -> Id<NSCursor> {
|
fn $name() -> Retained<NSCursor> {
|
||||||
unsafe { try_cursor_from_selector(sel!($name)).unwrap_or_else(|| default_cursor()) }
|
unsafe { try_cursor_from_selector(sel!($name)).unwrap_or_else(|| default_cursor()) }
|
||||||
}
|
}
|
||||||
)*};
|
)*};
|
||||||
@@ -113,12 +124,15 @@ def_undocumented_cursor!(
|
|||||||
|
|
||||||
// Note that loading `busybutclickable` with this code won't animate
|
// Note that loading `busybutclickable` with this code won't animate
|
||||||
// the frames; instead you'll just get them all in a column.
|
// the frames; instead you'll just get them all in a column.
|
||||||
unsafe fn load_webkit_cursor(name: &NSString) -> Id<NSCursor> {
|
unsafe fn load_webkit_cursor(name: &NSString) -> Retained<NSCursor> {
|
||||||
// Snatch a cursor from WebKit; They fit the style of the native
|
// Snatch a cursor from WebKit; They fit the style of the native
|
||||||
// cursors, and will seem completely standard to macOS users.
|
// cursors, and will seem completely standard to macOS users.
|
||||||
//
|
//
|
||||||
// https://stackoverflow.com/a/21786835/5435443
|
// https://stackoverflow.com/a/21786835/5435443
|
||||||
let root = ns_string!("/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/Resources/cursors");
|
let root = ns_string!(
|
||||||
|
"/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/\
|
||||||
|
HIServices.framework/Versions/A/Resources/cursors"
|
||||||
|
);
|
||||||
let cursor_path = root.stringByAppendingPathComponent(name);
|
let cursor_path = root.stringByAppendingPathComponent(name);
|
||||||
|
|
||||||
let pdf_path = cursor_path.stringByAppendingPathComponent(ns_string!("cursor.pdf"));
|
let pdf_path = cursor_path.stringByAppendingPathComponent(ns_string!("cursor.pdf"));
|
||||||
@@ -126,26 +140,22 @@ unsafe fn load_webkit_cursor(name: &NSString) -> Id<NSCursor> {
|
|||||||
|
|
||||||
// TODO: Handle PLists better
|
// TODO: Handle PLists better
|
||||||
let info_path = cursor_path.stringByAppendingPathComponent(ns_string!("info.plist"));
|
let info_path = cursor_path.stringByAppendingPathComponent(ns_string!("info.plist"));
|
||||||
let info: Id<NSDictionary<NSObject, NSObject>> = unsafe {
|
let info: Retained<NSDictionary<NSObject, NSObject>> = unsafe {
|
||||||
msg_send_id![
|
msg_send![
|
||||||
<NSDictionary<NSObject, NSObject>>::class(),
|
<NSDictionary<NSObject, NSObject>>::class(),
|
||||||
dictionaryWithContentsOfFile: &*info_path,
|
dictionaryWithContentsOfFile: &*info_path,
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
let mut x = 0.0;
|
let mut x = 0.0;
|
||||||
if let Some(n) = info.get(&*ns_string!("hotx")) {
|
if let Some(n) = info.objectForKey(ns_string!("hotx")) {
|
||||||
if n.is_kind_of::<NSNumber>() {
|
if let Ok(n) = n.downcast::<NSNumber>() {
|
||||||
let ptr: *const NSObject = n;
|
x = n.as_cgfloat();
|
||||||
let ptr: *const NSNumber = ptr.cast();
|
|
||||||
x = unsafe { &*ptr }.as_cgfloat()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let mut y = 0.0;
|
let mut y = 0.0;
|
||||||
if let Some(n) = info.get(&*ns_string!("hotx")) {
|
if let Some(n) = info.objectForKey(ns_string!("hoty")) {
|
||||||
if n.is_kind_of::<NSNumber>() {
|
if let Ok(n) = n.downcast::<NSNumber>() {
|
||||||
let ptr: *const NSObject = n;
|
y = n.as_cgfloat();
|
||||||
let ptr: *const NSNumber = ptr.cast();
|
|
||||||
y = unsafe { &*ptr }.as_cgfloat()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,41 +163,40 @@ unsafe fn load_webkit_cursor(name: &NSString) -> Id<NSCursor> {
|
|||||||
NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot)
|
NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn webkit_move() -> Id<NSCursor> {
|
fn webkit_move() -> Retained<NSCursor> {
|
||||||
unsafe { load_webkit_cursor(ns_string!("move")) }
|
unsafe { load_webkit_cursor(ns_string!("move")) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn webkit_cell() -> Id<NSCursor> {
|
fn webkit_cell() -> Retained<NSCursor> {
|
||||||
unsafe { load_webkit_cursor(ns_string!("cell")) }
|
unsafe { load_webkit_cursor(ns_string!("cell")) }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn invisible_cursor() -> Id<NSCursor> {
|
pub(crate) fn invisible_cursor() -> Retained<NSCursor> {
|
||||||
// 16x16 GIF data for invisible cursor
|
// 16x16 GIF data for invisible cursor
|
||||||
// You can reproduce this via ImageMagick.
|
// You can reproduce this via ImageMagick.
|
||||||
// $ convert -size 16x16 xc:none cursor.gif
|
// $ convert -size 16x16 xc:none cursor.gif
|
||||||
static CURSOR_BYTES: &[u8] = &[
|
static CURSOR_BYTES: &[u8] = &[
|
||||||
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x10, 0x00, 0x10, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00,
|
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x10, 0x00, 0x10, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x00,
|
||||||
0x00, 0x00, 0x00, 0x00, 0x21, 0xF9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00,
|
0x00, 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00,
|
||||||
0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x0E, 0x84, 0x8F, 0xA9, 0xCB, 0xED, 0x0F,
|
0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x0e, 0x84, 0x8f, 0xa9, 0xcb, 0xed, 0x0f,
|
||||||
0xA3, 0x9C, 0xB4, 0xDA, 0x8B, 0xB3, 0x3E, 0x05, 0x00, 0x3B,
|
0xa3, 0x9c, 0xb4, 0xda, 0x8b, 0xb3, 0x3e, 0x05, 0x00, 0x3b,
|
||||||
];
|
];
|
||||||
|
|
||||||
static CURSOR: Lazy<CustomCursor> = Lazy::new(|| {
|
fn new_invisible() -> Retained<NSCursor> {
|
||||||
// TODO: Consider using `dataWithBytesNoCopy:`
|
// TODO: Consider using `dataWithBytesNoCopy:`
|
||||||
let data = NSData::with_bytes(CURSOR_BYTES);
|
let data = NSData::with_bytes(CURSOR_BYTES);
|
||||||
let image = NSImage::initWithData(NSImage::alloc(), &data).unwrap();
|
let image = NSImage::initWithData(NSImage::alloc(), &data).unwrap();
|
||||||
let hotspot = NSPoint::new(0.0, 0.0);
|
let hotspot = NSPoint::new(0.0, 0.0);
|
||||||
CustomCursor(NSCursor::initWithImage_hotSpot(
|
NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot)
|
||||||
NSCursor::alloc(),
|
}
|
||||||
&image,
|
|
||||||
hotspot,
|
|
||||||
))
|
|
||||||
});
|
|
||||||
|
|
||||||
CURSOR.0.clone()
|
// Cache this for efficiency
|
||||||
|
static CURSOR: OnceLock<CustomCursor> = OnceLock::new();
|
||||||
|
CURSOR.get_or_init(|| CustomCursor(new_invisible())).0.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn cursor_from_icon(icon: CursorIcon) -> Id<NSCursor> {
|
#[allow(deprecated)]
|
||||||
|
pub(crate) fn cursor_from_icon(icon: CursorIcon) -> Retained<NSCursor> {
|
||||||
match icon {
|
match icon {
|
||||||
CursorIcon::Default => default_cursor(),
|
CursorIcon::Default => default_cursor(),
|
||||||
CursorIcon::Pointer => NSCursor::pointingHandCursor(),
|
CursorIcon::Pointer => NSCursor::pointingHandCursor(),
|
||||||
@@ -207,7 +216,9 @@ pub(crate) fn cursor_from_icon(icon: CursorIcon) -> Id<NSCursor> {
|
|||||||
CursorIcon::EwResize | CursorIcon::ColResize => NSCursor::resizeLeftRightCursor(),
|
CursorIcon::EwResize | CursorIcon::ColResize => NSCursor::resizeLeftRightCursor(),
|
||||||
CursorIcon::NsResize | CursorIcon::RowResize => NSCursor::resizeUpDownCursor(),
|
CursorIcon::NsResize | CursorIcon::RowResize => NSCursor::resizeUpDownCursor(),
|
||||||
CursorIcon::Help => _helpCursor(),
|
CursorIcon::Help => _helpCursor(),
|
||||||
|
CursorIcon::ZoomIn if available!(macos = 15.0) => unsafe { NSCursor::zoomInCursor() },
|
||||||
CursorIcon::ZoomIn => _zoomInCursor(),
|
CursorIcon::ZoomIn => _zoomInCursor(),
|
||||||
|
CursorIcon::ZoomOut if available!(macos = 15.0) => unsafe { NSCursor::zoomOutCursor() },
|
||||||
CursorIcon::ZoomOut => _zoomOutCursor(),
|
CursorIcon::ZoomOut => _zoomOutCursor(),
|
||||||
CursorIcon::NeResize => _windowResizeNorthEastCursor(),
|
CursorIcon::NeResize => _windowResizeNorthEastCursor(),
|
||||||
CursorIcon::NwResize => _windowResizeNorthWestCursor(),
|
CursorIcon::NwResize => _windowResizeNorthWestCursor(),
|
||||||
@@ -1,58 +1,42 @@
|
|||||||
use std::ffi::c_void;
|
use std::ptr::NonNull;
|
||||||
|
|
||||||
use core_foundation::{
|
use dispatch2::run_on_main;
|
||||||
base::CFRelease,
|
use objc2::rc::Retained;
|
||||||
data::{CFDataGetBytePtr, CFDataRef},
|
use objc2_app_kit::{NSEvent, NSEventModifierFlags, NSEventSubtype, NSEventType};
|
||||||
};
|
use objc2_core_foundation::{CFData, CFRetained};
|
||||||
use icrate::AppKit::{
|
use objc2_foundation::NSPoint;
|
||||||
NSEvent, NSEventModifierFlagCommand, NSEventModifierFlagControl, NSEventModifierFlagOption,
|
|
||||||
NSEventModifierFlagShift, NSEventModifierFlags, NSEventSubtypeWindowExposed,
|
|
||||||
NSEventTypeApplicationDefined,
|
|
||||||
};
|
|
||||||
use icrate::Foundation::{MainThreadMarker, NSPoint};
|
|
||||||
use objc2::rc::Id;
|
|
||||||
use smol_str::SmolStr;
|
use smol_str::SmolStr;
|
||||||
|
use winit_core::event::{ElementState, KeyEvent, Modifiers};
|
||||||
use crate::{
|
use winit_core::keyboard::{
|
||||||
event::{ElementState, KeyEvent, Modifiers},
|
Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey, NativeKeyCode,
|
||||||
keyboard::{
|
PhysicalKey,
|
||||||
Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey,
|
|
||||||
NativeKeyCode, PhysicalKey,
|
|
||||||
},
|
|
||||||
platform_impl::platform::ffi,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
use super::ffi;
|
||||||
pub struct KeyEventExtra {
|
|
||||||
pub text_with_all_modifiers: Option<SmolStr>,
|
|
||||||
pub key_without_modifiers: Key,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Ignores ALL modifiers.
|
/// Ignores ALL modifiers.
|
||||||
pub fn get_modifierless_char(scancode: u16) -> Key {
|
pub fn get_modifierless_char(scancode: u16) -> Key {
|
||||||
let mut string = [0; 16];
|
let Some(ptr) = NonNull::new(unsafe { ffi::TISCopyCurrentKeyboardLayoutInputSource() }) else {
|
||||||
let input_source;
|
tracing::error!("`TISCopyCurrentKeyboardLayoutInputSource` returned null ptr");
|
||||||
let layout;
|
return Key::Unidentified(NativeKey::MacOS(scancode));
|
||||||
unsafe {
|
};
|
||||||
input_source = ffi::TISCopyCurrentKeyboardLayoutInputSource();
|
let input_source = unsafe { CFRetained::from_raw(ptr) };
|
||||||
if input_source.is_null() {
|
|
||||||
log::error!("`TISCopyCurrentKeyboardLayoutInputSource` returned null ptr");
|
let layout_data = unsafe {
|
||||||
return Key::Unidentified(NativeKey::MacOS(scancode));
|
ffi::TISGetInputSourceProperty(&input_source, ffi::kTISPropertyUnicodeKeyLayoutData)
|
||||||
}
|
};
|
||||||
let layout_data =
|
let Some(layout_data) = (unsafe { layout_data.cast::<CFData>().as_ref() }) else {
|
||||||
ffi::TISGetInputSourceProperty(input_source, ffi::kTISPropertyUnicodeKeyLayoutData);
|
tracing::error!("`TISGetInputSourceProperty` returned null ptr");
|
||||||
if layout_data.is_null() {
|
return Key::Unidentified(NativeKey::MacOS(scancode));
|
||||||
CFRelease(input_source as *mut c_void);
|
};
|
||||||
log::error!("`TISGetInputSourceProperty` returned null ptr");
|
|
||||||
return Key::Unidentified(NativeKey::MacOS(scancode));
|
let layout = layout_data.byte_ptr().cast();
|
||||||
}
|
let keyboard_type = run_on_main(|_mtm| unsafe { ffi::LMGetKbdType() });
|
||||||
layout = CFDataGetBytePtr(layout_data as CFDataRef) as *const ffi::UCKeyboardLayout;
|
|
||||||
}
|
|
||||||
let keyboard_type = MainThreadMarker::run_on_main(|_mtm| unsafe { ffi::LMGetKbdType() });
|
|
||||||
|
|
||||||
let mut result_len = 0;
|
let mut result_len = 0;
|
||||||
let mut dead_keys = 0;
|
let mut dead_keys = 0;
|
||||||
let modifiers = 0;
|
let modifiers = 0;
|
||||||
|
let mut string = [0; 16];
|
||||||
let translate_result = unsafe {
|
let translate_result = unsafe {
|
||||||
ffi::UCKeyTranslate(
|
ffi::UCKeyTranslate(
|
||||||
layout,
|
layout,
|
||||||
@@ -67,14 +51,8 @@ pub fn get_modifierless_char(scancode: u16) -> Key {
|
|||||||
string.as_mut_ptr(),
|
string.as_mut_ptr(),
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
unsafe {
|
|
||||||
CFRelease(input_source as *mut c_void);
|
|
||||||
}
|
|
||||||
if translate_result != 0 {
|
if translate_result != 0 {
|
||||||
log::error!(
|
tracing::error!("`UCKeyTranslate` returned with the non-zero value: {}", translate_result);
|
||||||
"`UCKeyTranslate` returned with the non-zero value: {}",
|
|
||||||
translate_result
|
|
||||||
);
|
|
||||||
return Key::Unidentified(NativeKey::MacOS(scancode));
|
return Key::Unidentified(NativeKey::MacOS(scancode));
|
||||||
}
|
}
|
||||||
if result_len == 0 {
|
if result_len == 0 {
|
||||||
@@ -103,17 +81,12 @@ fn get_logical_key_char(ns_event: &NSEvent, modifierless_chars: &str) -> Key {
|
|||||||
/// Create `KeyEvent` for the given `NSEvent`.
|
/// Create `KeyEvent` for the given `NSEvent`.
|
||||||
///
|
///
|
||||||
/// This function shouldn't be called when the IME input is in process.
|
/// This function shouldn't be called when the IME input is in process.
|
||||||
pub(crate) fn create_key_event(
|
pub(crate) fn create_key_event(ns_event: &NSEvent, is_press: bool, is_repeat: bool) -> KeyEvent {
|
||||||
ns_event: &NSEvent,
|
|
||||||
is_press: bool,
|
|
||||||
is_repeat: bool,
|
|
||||||
key_override: Option<PhysicalKey>,
|
|
||||||
) -> KeyEvent {
|
|
||||||
use ElementState::{Pressed, Released};
|
use ElementState::{Pressed, Released};
|
||||||
let state = if is_press { Pressed } else { Released };
|
let state = if is_press { Pressed } else { Released };
|
||||||
|
|
||||||
let scancode = unsafe { ns_event.keyCode() };
|
let scancode = unsafe { ns_event.keyCode() };
|
||||||
let mut physical_key = key_override.unwrap_or_else(|| scancode_to_physicalkey(scancode as u32));
|
let mut physical_key = scancode_to_physicalkey(scancode as u32);
|
||||||
|
|
||||||
// NOTE: The logical key should heed both SHIFT and ALT if possible.
|
// NOTE: The logical key should heed both SHIFT and ALT if possible.
|
||||||
// For instance:
|
// For instance:
|
||||||
@@ -122,21 +95,15 @@ pub(crate) fn create_key_event(
|
|||||||
// * Pressing CTRL SHIFT A: logical key should also be "A"
|
// * Pressing CTRL SHIFT A: logical key should also be "A"
|
||||||
// This is not easy to tease out of `NSEvent`, but we do our best.
|
// This is not easy to tease out of `NSEvent`, but we do our best.
|
||||||
|
|
||||||
let text_with_all_modifiers: Option<SmolStr> = if key_override.is_some() {
|
let characters = unsafe { ns_event.characters() }.map(|s| s.to_string()).unwrap_or_default();
|
||||||
|
let text_with_all_modifiers = if characters.is_empty() {
|
||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
let characters = unsafe { ns_event.characters() }
|
if matches!(physical_key, PhysicalKey::Unidentified(_)) {
|
||||||
.map(|s| s.to_string())
|
// The key may be one of the funky function keys
|
||||||
.unwrap_or_default();
|
physical_key = extra_function_key_to_code(scancode, &characters);
|
||||||
if characters.is_empty() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
if matches!(physical_key, PhysicalKey::Unidentified(_)) {
|
|
||||||
// The key may be one of the funky function keys
|
|
||||||
physical_key = extra_function_key_to_code(scancode, &characters);
|
|
||||||
}
|
|
||||||
Some(SmolStr::new(characters))
|
|
||||||
}
|
}
|
||||||
|
Some(SmolStr::new(characters))
|
||||||
};
|
};
|
||||||
|
|
||||||
let key_from_code = code_to_key(physical_key, scancode);
|
let key_from_code = code_to_key(physical_key, scancode);
|
||||||
@@ -145,8 +112,8 @@ pub(crate) fn create_key_event(
|
|||||||
let key_without_modifiers = get_modifierless_char(scancode);
|
let key_without_modifiers = get_modifierless_char(scancode);
|
||||||
|
|
||||||
let modifiers = unsafe { ns_event.modifierFlags() };
|
let modifiers = unsafe { ns_event.modifierFlags() };
|
||||||
let has_ctrl = flags_contains(modifiers, NSEventModifierFlagControl);
|
let has_ctrl = modifiers.contains(NSEventModifierFlags::Control);
|
||||||
let has_cmd = flags_contains(modifiers, NSEventModifierFlagCommand);
|
let has_cmd = modifiers.contains(NSEventModifierFlags::Command);
|
||||||
|
|
||||||
let logical_key = match text_with_all_modifiers.as_ref() {
|
let logical_key = match text_with_all_modifiers.as_ref() {
|
||||||
// Only checking for ctrl and cmd here, not checking for alt because we DO want to
|
// Only checking for ctrl and cmd here, not checking for alt because we DO want to
|
||||||
@@ -157,7 +124,7 @@ pub(crate) fn create_key_event(
|
|||||||
Some(text) if !has_ctrl && !has_cmd => {
|
Some(text) if !has_ctrl && !has_cmd => {
|
||||||
// Character heeding both SHIFT and ALT.
|
// Character heeding both SHIFT and ALT.
|
||||||
Key::Character(text.clone())
|
Key::Character(text.clone())
|
||||||
}
|
},
|
||||||
|
|
||||||
_ => match key_without_modifiers.as_ref() {
|
_ => match key_without_modifiers.as_ref() {
|
||||||
// Character heeding just SHIFT, ignoring ALT.
|
// Character heeding just SHIFT, ignoring ALT.
|
||||||
@@ -173,11 +140,7 @@ pub(crate) fn create_key_event(
|
|||||||
(key_from_code.clone(), key_from_code)
|
(key_from_code.clone(), key_from_code)
|
||||||
};
|
};
|
||||||
|
|
||||||
let text = if is_press {
|
let text = if is_press { logical_key.to_text().map(SmolStr::new) } else { None };
|
||||||
logical_key.to_text().map(SmolStr::new)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let location = code_to_location(physical_key);
|
let location = code_to_location(physical_key);
|
||||||
|
|
||||||
@@ -188,12 +151,8 @@ pub(crate) fn create_key_event(
|
|||||||
repeat: is_repeat,
|
repeat: is_repeat,
|
||||||
state,
|
state,
|
||||||
text,
|
text,
|
||||||
extra: crate::event::KeyExtra {
|
text_with_all_modifiers,
|
||||||
extra: KeyEventExtra {
|
key_without_modifiers,
|
||||||
text_with_all_modifiers,
|
|
||||||
key_without_modifiers,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -203,28 +162,34 @@ pub fn code_to_key(key: PhysicalKey, scancode: u16) -> Key {
|
|||||||
PhysicalKey::Unidentified(code) => return Key::Unidentified(code.into()),
|
PhysicalKey::Unidentified(code) => return Key::Unidentified(code.into()),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Roughly same handling as Firefox and Chromium:
|
||||||
|
// https://searchfox.org/mozilla-central/rev/c597e9c789ad36af84a0370d395be066b7dc94f4/widget/NativeKeyToDOMKeyName.h
|
||||||
|
// https://chromium.googlesource.com/chromium/src.git/+/010a75a426c4a2292955a52f480e9251cacf750e/ui/events/keycodes/keyboard_code_conversion_mac.mm#100
|
||||||
Key::Named(match code {
|
Key::Named(match code {
|
||||||
KeyCode::Enter => NamedKey::Enter,
|
KeyCode::Enter => NamedKey::Enter,
|
||||||
KeyCode::Tab => NamedKey::Tab,
|
KeyCode::Tab => NamedKey::Tab,
|
||||||
KeyCode::Space => NamedKey::Space,
|
KeyCode::Space => return Key::Character(" ".into()),
|
||||||
KeyCode::Backspace => NamedKey::Backspace,
|
KeyCode::Backspace => NamedKey::Backspace,
|
||||||
KeyCode::Escape => NamedKey::Escape,
|
KeyCode::Escape => NamedKey::Escape,
|
||||||
KeyCode::SuperRight => NamedKey::Super,
|
KeyCode::MetaRight => NamedKey::Meta,
|
||||||
KeyCode::SuperLeft => NamedKey::Super,
|
KeyCode::MetaLeft => NamedKey::Meta,
|
||||||
KeyCode::ShiftLeft => NamedKey::Shift,
|
KeyCode::ShiftLeft => NamedKey::Shift,
|
||||||
KeyCode::AltLeft => NamedKey::Alt,
|
KeyCode::AltLeft => NamedKey::Alt,
|
||||||
KeyCode::ControlLeft => NamedKey::Control,
|
KeyCode::ControlLeft => NamedKey::Control,
|
||||||
KeyCode::ShiftRight => NamedKey::Shift,
|
KeyCode::ShiftRight => NamedKey::Shift,
|
||||||
KeyCode::AltRight => NamedKey::Alt,
|
KeyCode::AltRight => NamedKey::Alt,
|
||||||
KeyCode::ControlRight => NamedKey::Control,
|
KeyCode::ControlRight => NamedKey::Control,
|
||||||
|
KeyCode::CapsLock => NamedKey::CapsLock,
|
||||||
|
|
||||||
KeyCode::NumLock => NamedKey::NumLock,
|
KeyCode::NumLock => NamedKey::NumLock,
|
||||||
KeyCode::AudioVolumeUp => NamedKey::AudioVolumeUp,
|
KeyCode::AudioVolumeUp => NamedKey::AudioVolumeUp,
|
||||||
KeyCode::AudioVolumeDown => NamedKey::AudioVolumeDown,
|
KeyCode::AudioVolumeDown => NamedKey::AudioVolumeDown,
|
||||||
|
KeyCode::AudioVolumeMute => NamedKey::AudioVolumeMute,
|
||||||
|
|
||||||
// Other numpad keys all generate text on macOS (if I understand correctly)
|
// Other numpad keys all generate text on macOS (if I understand correctly)
|
||||||
KeyCode::NumpadEnter => NamedKey::Enter,
|
KeyCode::NumpadEnter => NamedKey::Enter,
|
||||||
|
|
||||||
|
KeyCode::Fn => NamedKey::Fn,
|
||||||
KeyCode::F1 => NamedKey::F1,
|
KeyCode::F1 => NamedKey::F1,
|
||||||
KeyCode::F2 => NamedKey::F2,
|
KeyCode::F2 => NamedKey::F2,
|
||||||
KeyCode::F3 => NamedKey::F3,
|
KeyCode::F3 => NamedKey::F3,
|
||||||
@@ -245,17 +210,27 @@ pub fn code_to_key(key: PhysicalKey, scancode: u16) -> Key {
|
|||||||
KeyCode::F18 => NamedKey::F18,
|
KeyCode::F18 => NamedKey::F18,
|
||||||
KeyCode::F19 => NamedKey::F19,
|
KeyCode::F19 => NamedKey::F19,
|
||||||
KeyCode::F20 => NamedKey::F20,
|
KeyCode::F20 => NamedKey::F20,
|
||||||
|
KeyCode::F21 => NamedKey::F21,
|
||||||
|
KeyCode::F22 => NamedKey::F22,
|
||||||
|
KeyCode::F23 => NamedKey::F23,
|
||||||
|
KeyCode::F24 => NamedKey::F24,
|
||||||
|
|
||||||
KeyCode::Insert => NamedKey::Insert,
|
KeyCode::Insert => NamedKey::Insert,
|
||||||
KeyCode::Home => NamedKey::Home,
|
KeyCode::Home => NamedKey::Home,
|
||||||
KeyCode::PageUp => NamedKey::PageUp,
|
KeyCode::PageUp => NamedKey::PageUp,
|
||||||
KeyCode::Delete => NamedKey::Delete,
|
KeyCode::Delete => NamedKey::Delete,
|
||||||
KeyCode::End => NamedKey::End,
|
KeyCode::End => NamedKey::End,
|
||||||
|
KeyCode::Help => NamedKey::Help,
|
||||||
KeyCode::PageDown => NamedKey::PageDown,
|
KeyCode::PageDown => NamedKey::PageDown,
|
||||||
KeyCode::ArrowLeft => NamedKey::ArrowLeft,
|
KeyCode::ArrowLeft => NamedKey::ArrowLeft,
|
||||||
KeyCode::ArrowRight => NamedKey::ArrowRight,
|
KeyCode::ArrowRight => NamedKey::ArrowRight,
|
||||||
KeyCode::ArrowDown => NamedKey::ArrowDown,
|
KeyCode::ArrowDown => NamedKey::ArrowDown,
|
||||||
KeyCode::ArrowUp => NamedKey::ArrowUp,
|
KeyCode::ArrowUp => NamedKey::ArrowUp,
|
||||||
|
KeyCode::ContextMenu => NamedKey::ContextMenu,
|
||||||
|
|
||||||
|
KeyCode::Lang2 => NamedKey::Eisu,
|
||||||
|
KeyCode::Lang1 => NamedKey::KanjiMode,
|
||||||
|
|
||||||
_ => return Key::Unidentified(NativeKey::MacOS(scancode)),
|
_ => return Key::Unidentified(NativeKey::MacOS(scancode)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -267,8 +242,8 @@ pub fn code_to_location(key: PhysicalKey) -> KeyLocation {
|
|||||||
};
|
};
|
||||||
|
|
||||||
match code {
|
match code {
|
||||||
KeyCode::SuperRight => KeyLocation::Right,
|
KeyCode::MetaRight => KeyLocation::Right,
|
||||||
KeyCode::SuperLeft => KeyLocation::Left,
|
KeyCode::MetaLeft => KeyLocation::Left,
|
||||||
KeyCode::ShiftLeft => KeyLocation::Left,
|
KeyCode::ShiftLeft => KeyLocation::Left,
|
||||||
KeyCode::AltLeft => KeyLocation::Left,
|
KeyCode::AltLeft => KeyLocation::Left,
|
||||||
KeyCode::ControlLeft => KeyLocation::Left,
|
KeyCode::ControlLeft => KeyLocation::Left,
|
||||||
@@ -317,25 +292,21 @@ pub fn extra_function_key_to_code(scancode: u16, string: &str) -> PhysicalKey {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The values are from the https://github.com/apple-oss-distributions/IOHIDFamily/blob/19666c840a6d896468416ff0007040a10b7b46b8/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h#L258-L259
|
// The values are from the https://github.com/apple-oss-distributions/IOHIDFamily/blob/19666c840a6d896468416ff0007040a10b7b46b8/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h#L258-L259
|
||||||
const NX_DEVICELCTLKEYMASK: NSEventModifierFlags = 0x00000001;
|
const NX_DEVICELCTLKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000001);
|
||||||
const NX_DEVICELSHIFTKEYMASK: NSEventModifierFlags = 0x00000002;
|
const NX_DEVICELSHIFTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000002);
|
||||||
const NX_DEVICERSHIFTKEYMASK: NSEventModifierFlags = 0x00000004;
|
const NX_DEVICERSHIFTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000004);
|
||||||
const NX_DEVICELCMDKEYMASK: NSEventModifierFlags = 0x00000008;
|
const NX_DEVICELCMDKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000008);
|
||||||
const NX_DEVICERCMDKEYMASK: NSEventModifierFlags = 0x00000010;
|
const NX_DEVICERCMDKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000010);
|
||||||
const NX_DEVICELALTKEYMASK: NSEventModifierFlags = 0x00000020;
|
const NX_DEVICELALTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000020);
|
||||||
const NX_DEVICERALTKEYMASK: NSEventModifierFlags = 0x00000040;
|
const NX_DEVICERALTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000040);
|
||||||
const NX_DEVICERCTLKEYMASK: NSEventModifierFlags = 0x00002000;
|
const NX_DEVICERCTLKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00002000);
|
||||||
|
|
||||||
pub(super) fn flags_contains(flags: NSEventModifierFlags, value: NSEventModifierFlags) -> bool {
|
|
||||||
flags & value == value
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn lalt_pressed(event: &NSEvent) -> bool {
|
pub(super) fn lalt_pressed(event: &NSEvent) -> bool {
|
||||||
flags_contains(unsafe { event.modifierFlags() }, NX_DEVICELALTKEYMASK)
|
unsafe { event.modifierFlags() }.contains(NX_DEVICELALTKEYMASK)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn ralt_pressed(event: &NSEvent) -> bool {
|
pub(super) fn ralt_pressed(event: &NSEvent) -> bool {
|
||||||
flags_contains(unsafe { event.modifierFlags() }, NX_DEVICERALTKEYMASK)
|
unsafe { event.modifierFlags() }.contains(NX_DEVICERALTKEYMASK)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn event_mods(event: &NSEvent) -> Modifiers {
|
pub(super) fn event_mods(event: &NSEvent) -> Modifiers {
|
||||||
@@ -343,78 +314,42 @@ pub(super) fn event_mods(event: &NSEvent) -> Modifiers {
|
|||||||
let mut state = ModifiersState::empty();
|
let mut state = ModifiersState::empty();
|
||||||
let mut pressed_mods = ModifiersKeys::empty();
|
let mut pressed_mods = ModifiersKeys::empty();
|
||||||
|
|
||||||
state.set(
|
state.set(ModifiersState::SHIFT, flags.contains(NSEventModifierFlags::Shift));
|
||||||
ModifiersState::SHIFT,
|
pressed_mods.set(ModifiersKeys::LSHIFT, flags.contains(NX_DEVICELSHIFTKEYMASK));
|
||||||
flags_contains(flags, NSEventModifierFlagShift),
|
pressed_mods.set(ModifiersKeys::RSHIFT, flags.contains(NX_DEVICERSHIFTKEYMASK));
|
||||||
);
|
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::LSHIFT,
|
|
||||||
flags_contains(flags, NX_DEVICELSHIFTKEYMASK),
|
|
||||||
);
|
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::RSHIFT,
|
|
||||||
flags_contains(flags, NX_DEVICERSHIFTKEYMASK),
|
|
||||||
);
|
|
||||||
|
|
||||||
state.set(
|
state.set(ModifiersState::CONTROL, flags.contains(NSEventModifierFlags::Control));
|
||||||
ModifiersState::CONTROL,
|
pressed_mods.set(ModifiersKeys::LCONTROL, flags.contains(NX_DEVICELCTLKEYMASK));
|
||||||
flags_contains(flags, NSEventModifierFlagControl),
|
pressed_mods.set(ModifiersKeys::RCONTROL, flags.contains(NX_DEVICERCTLKEYMASK));
|
||||||
);
|
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::LCONTROL,
|
|
||||||
flags_contains(flags, NX_DEVICELCTLKEYMASK),
|
|
||||||
);
|
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::RCONTROL,
|
|
||||||
flags_contains(flags, NX_DEVICERCTLKEYMASK),
|
|
||||||
);
|
|
||||||
|
|
||||||
state.set(
|
state.set(ModifiersState::ALT, flags.contains(NSEventModifierFlags::Option));
|
||||||
ModifiersState::ALT,
|
pressed_mods.set(ModifiersKeys::LALT, flags.contains(NX_DEVICELALTKEYMASK));
|
||||||
flags_contains(flags, NSEventModifierFlagOption),
|
pressed_mods.set(ModifiersKeys::RALT, flags.contains(NX_DEVICERALTKEYMASK));
|
||||||
);
|
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::LALT,
|
|
||||||
flags_contains(flags, NX_DEVICELALTKEYMASK),
|
|
||||||
);
|
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::RALT,
|
|
||||||
flags_contains(flags, NX_DEVICERALTKEYMASK),
|
|
||||||
);
|
|
||||||
|
|
||||||
state.set(
|
state.set(ModifiersState::META, flags.contains(NSEventModifierFlags::Command));
|
||||||
ModifiersState::SUPER,
|
pressed_mods.set(ModifiersKeys::LMETA, flags.contains(NX_DEVICELCMDKEYMASK));
|
||||||
flags_contains(flags, NSEventModifierFlagCommand),
|
pressed_mods.set(ModifiersKeys::RMETA, flags.contains(NX_DEVICERCMDKEYMASK));
|
||||||
);
|
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::LSUPER,
|
|
||||||
flags_contains(flags, NX_DEVICELCMDKEYMASK),
|
|
||||||
);
|
|
||||||
pressed_mods.set(
|
|
||||||
ModifiersKeys::RSUPER,
|
|
||||||
flags_contains(flags, NX_DEVICERCMDKEYMASK),
|
|
||||||
);
|
|
||||||
|
|
||||||
Modifiers::new(state, pressed_mods)
|
Modifiers::new(state, pressed_mods)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn dummy_event() -> Option<Id<NSEvent>> {
|
pub(super) fn dummy_event() -> Option<Retained<NSEvent>> {
|
||||||
unsafe {
|
unsafe {
|
||||||
NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
|
NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
|
||||||
NSEventTypeApplicationDefined,
|
NSEventType::ApplicationDefined,
|
||||||
NSPoint::new(0.0, 0.0),
|
NSPoint::new(0.0, 0.0),
|
||||||
0, // Empty NSEventModifierFlags
|
NSEventModifierFlags(0),
|
||||||
0.0,
|
0.0,
|
||||||
0,
|
0,
|
||||||
None,
|
None,
|
||||||
NSEventSubtypeWindowExposed,
|
NSEventSubtype::WindowExposed.0,
|
||||||
0,
|
0,
|
||||||
0,
|
0,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32> {
|
pub fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32> {
|
||||||
let code = match physical_key {
|
let code = match physical_key {
|
||||||
PhysicalKey::Code(code) => code,
|
PhysicalKey::Code(code) => code,
|
||||||
PhysicalKey::Unidentified(_) => return None,
|
PhysicalKey::Unidentified(_) => return None,
|
||||||
@@ -431,6 +366,7 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
|
|||||||
KeyCode::KeyX => Some(0x07),
|
KeyCode::KeyX => Some(0x07),
|
||||||
KeyCode::KeyC => Some(0x08),
|
KeyCode::KeyC => Some(0x08),
|
||||||
KeyCode::KeyV => Some(0x09),
|
KeyCode::KeyV => Some(0x09),
|
||||||
|
KeyCode::IntlBackslash => Some(0x0a),
|
||||||
KeyCode::KeyB => Some(0x0b),
|
KeyCode::KeyB => Some(0x0b),
|
||||||
KeyCode::KeyQ => Some(0x0c),
|
KeyCode::KeyQ => Some(0x0c),
|
||||||
KeyCode::KeyW => Some(0x0d),
|
KeyCode::KeyW => Some(0x0d),
|
||||||
@@ -473,21 +409,24 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
|
|||||||
KeyCode::Backquote => Some(0x32),
|
KeyCode::Backquote => Some(0x32),
|
||||||
KeyCode::Backspace => Some(0x33),
|
KeyCode::Backspace => Some(0x33),
|
||||||
KeyCode::Escape => Some(0x35),
|
KeyCode::Escape => Some(0x35),
|
||||||
KeyCode::SuperRight => Some(0x36),
|
KeyCode::MetaRight => Some(0x36),
|
||||||
KeyCode::SuperLeft => Some(0x37),
|
KeyCode::MetaLeft => Some(0x37),
|
||||||
KeyCode::ShiftLeft => Some(0x38),
|
KeyCode::ShiftLeft => Some(0x38),
|
||||||
|
KeyCode::CapsLock => Some(0x39),
|
||||||
KeyCode::AltLeft => Some(0x3a),
|
KeyCode::AltLeft => Some(0x3a),
|
||||||
KeyCode::ControlLeft => Some(0x3b),
|
KeyCode::ControlLeft => Some(0x3b),
|
||||||
KeyCode::ShiftRight => Some(0x3c),
|
KeyCode::ShiftRight => Some(0x3c),
|
||||||
KeyCode::AltRight => Some(0x3d),
|
KeyCode::AltRight => Some(0x3d),
|
||||||
KeyCode::ControlRight => Some(0x3e),
|
KeyCode::ControlRight => Some(0x3e),
|
||||||
|
KeyCode::Fn => Some(0x3f),
|
||||||
KeyCode::F17 => Some(0x40),
|
KeyCode::F17 => Some(0x40),
|
||||||
KeyCode::NumpadDecimal => Some(0x41),
|
KeyCode::NumpadDecimal => Some(0x41),
|
||||||
KeyCode::NumpadMultiply => Some(0x43),
|
KeyCode::NumpadMultiply => Some(0x43),
|
||||||
KeyCode::NumpadAdd => Some(0x45),
|
KeyCode::NumpadAdd => Some(0x45),
|
||||||
KeyCode::NumLock => Some(0x47),
|
KeyCode::NumLock => Some(0x47),
|
||||||
KeyCode::AudioVolumeUp => Some(0x49),
|
KeyCode::AudioVolumeUp => Some(0x48),
|
||||||
KeyCode::AudioVolumeDown => Some(0x4a),
|
KeyCode::AudioVolumeDown => Some(0x49),
|
||||||
|
KeyCode::AudioVolumeMute => Some(0x4a),
|
||||||
KeyCode::NumpadDivide => Some(0x4b),
|
KeyCode::NumpadDivide => Some(0x4b),
|
||||||
KeyCode::NumpadEnter => Some(0x4c),
|
KeyCode::NumpadEnter => Some(0x4c),
|
||||||
KeyCode::NumpadSubtract => Some(0x4e),
|
KeyCode::NumpadSubtract => Some(0x4e),
|
||||||
@@ -506,17 +445,22 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
|
|||||||
KeyCode::Numpad8 => Some(0x5b),
|
KeyCode::Numpad8 => Some(0x5b),
|
||||||
KeyCode::Numpad9 => Some(0x5c),
|
KeyCode::Numpad9 => Some(0x5c),
|
||||||
KeyCode::IntlYen => Some(0x5d),
|
KeyCode::IntlYen => Some(0x5d),
|
||||||
|
KeyCode::IntlRo => Some(0x5e),
|
||||||
|
KeyCode::NumpadComma => Some(0x5f),
|
||||||
KeyCode::F5 => Some(0x60),
|
KeyCode::F5 => Some(0x60),
|
||||||
KeyCode::F6 => Some(0x61),
|
KeyCode::F6 => Some(0x61),
|
||||||
KeyCode::F7 => Some(0x62),
|
KeyCode::F7 => Some(0x62),
|
||||||
KeyCode::F3 => Some(0x63),
|
KeyCode::F3 => Some(0x63),
|
||||||
KeyCode::F8 => Some(0x64),
|
KeyCode::F8 => Some(0x64),
|
||||||
KeyCode::F9 => Some(0x65),
|
KeyCode::F9 => Some(0x65),
|
||||||
|
KeyCode::Lang2 => Some(0x66),
|
||||||
KeyCode::F11 => Some(0x67),
|
KeyCode::F11 => Some(0x67),
|
||||||
|
KeyCode::Lang1 => Some(0x68),
|
||||||
KeyCode::F13 => Some(0x69),
|
KeyCode::F13 => Some(0x69),
|
||||||
KeyCode::F16 => Some(0x6a),
|
KeyCode::F16 => Some(0x6a),
|
||||||
KeyCode::F14 => Some(0x6b),
|
KeyCode::F14 => Some(0x6b),
|
||||||
KeyCode::F10 => Some(0x6d),
|
KeyCode::F10 => Some(0x6d),
|
||||||
|
KeyCode::ContextMenu => Some(0x6e),
|
||||||
KeyCode::F12 => Some(0x6f),
|
KeyCode::F12 => Some(0x6f),
|
||||||
KeyCode::F15 => Some(0x71),
|
KeyCode::F15 => Some(0x71),
|
||||||
KeyCode::Insert => Some(0x72),
|
KeyCode::Insert => Some(0x72),
|
||||||
@@ -532,11 +476,26 @@ pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32>
|
|||||||
KeyCode::ArrowRight => Some(0x7c),
|
KeyCode::ArrowRight => Some(0x7c),
|
||||||
KeyCode::ArrowDown => Some(0x7d),
|
KeyCode::ArrowDown => Some(0x7d),
|
||||||
KeyCode::ArrowUp => Some(0x7e),
|
KeyCode::ArrowUp => Some(0x7e),
|
||||||
|
KeyCode::Power => Some(0x7f),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
||||||
|
// Follows what Chromium and Firefox do:
|
||||||
|
// https://chromium.googlesource.com/chromium/src.git/+/3e1a26c44c024d97dc9a4c09bbc6a2365398ca2c/ui/events/keycodes/dom/dom_code_data.inc
|
||||||
|
// https://searchfox.org/mozilla-central/rev/c597e9c789ad36af84a0370d395be066b7dc94f4/widget/NativeKeyToDOMCodeName.h
|
||||||
|
//
|
||||||
|
// See also:
|
||||||
|
// Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h
|
||||||
|
//
|
||||||
|
// Also see https://developer.apple.com/documentation/appkit/function-key-unicode-values:
|
||||||
|
//
|
||||||
|
// > the system handles some function keys at a lower level and your app never sees them.
|
||||||
|
// > Examples include the Volume Up key, Volume Down key, Volume Mute key, Eject key, and
|
||||||
|
// > Function key found on many Macs.
|
||||||
|
//
|
||||||
|
// So the handling of some of these is mostly for show.
|
||||||
PhysicalKey::Code(match scancode {
|
PhysicalKey::Code(match scancode {
|
||||||
0x00 => KeyCode::KeyA,
|
0x00 => KeyCode::KeyA,
|
||||||
0x01 => KeyCode::KeyS,
|
0x01 => KeyCode::KeyS,
|
||||||
@@ -548,7 +507,11 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
0x07 => KeyCode::KeyX,
|
0x07 => KeyCode::KeyX,
|
||||||
0x08 => KeyCode::KeyC,
|
0x08 => KeyCode::KeyC,
|
||||||
0x09 => KeyCode::KeyV,
|
0x09 => KeyCode::KeyV,
|
||||||
//0x0a => World 1,
|
// This key is typically located near LeftShift key, roughly the same location as backquote
|
||||||
|
// (`) on Windows' US layout.
|
||||||
|
//
|
||||||
|
// The keycap varies on international keyboards.
|
||||||
|
0x0a => KeyCode::IntlBackslash,
|
||||||
0x0b => KeyCode::KeyB,
|
0x0b => KeyCode::KeyB,
|
||||||
0x0c => KeyCode::KeyQ,
|
0x0c => KeyCode::KeyQ,
|
||||||
0x0d => KeyCode::KeyW,
|
0x0d => KeyCode::KeyW,
|
||||||
@@ -590,10 +553,10 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
0x31 => KeyCode::Space,
|
0x31 => KeyCode::Space,
|
||||||
0x32 => KeyCode::Backquote,
|
0x32 => KeyCode::Backquote,
|
||||||
0x33 => KeyCode::Backspace,
|
0x33 => KeyCode::Backspace,
|
||||||
//0x34 => unknown,
|
// 0x34 => unknown, // kVK_Powerbook_KeypadEnter
|
||||||
0x35 => KeyCode::Escape,
|
0x35 => KeyCode::Escape,
|
||||||
0x36 => KeyCode::SuperRight,
|
0x36 => KeyCode::MetaRight,
|
||||||
0x37 => KeyCode::SuperLeft,
|
0x37 => KeyCode::MetaLeft,
|
||||||
0x38 => KeyCode::ShiftLeft,
|
0x38 => KeyCode::ShiftLeft,
|
||||||
0x39 => KeyCode::CapsLock,
|
0x39 => KeyCode::CapsLock,
|
||||||
0x3a => KeyCode::AltLeft,
|
0x3a => KeyCode::AltLeft,
|
||||||
@@ -604,22 +567,18 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
0x3f => KeyCode::Fn,
|
0x3f => KeyCode::Fn,
|
||||||
0x40 => KeyCode::F17,
|
0x40 => KeyCode::F17,
|
||||||
0x41 => KeyCode::NumpadDecimal,
|
0x41 => KeyCode::NumpadDecimal,
|
||||||
//0x42 -> unknown,
|
// 0x42 -> unknown,
|
||||||
0x43 => KeyCode::NumpadMultiply,
|
0x43 => KeyCode::NumpadMultiply,
|
||||||
//0x44 => unknown,
|
// 0x44 => unknown,
|
||||||
0x45 => KeyCode::NumpadAdd,
|
0x45 => KeyCode::NumpadAdd,
|
||||||
//0x46 => unknown,
|
// 0x46 => unknown,
|
||||||
0x47 => KeyCode::NumLock,
|
0x47 => KeyCode::NumLock, // kVK_ANSI_KeypadClear
|
||||||
//0x48 => KeyCode::NumpadClear,
|
0x48 => KeyCode::AudioVolumeUp,
|
||||||
|
0x49 => KeyCode::AudioVolumeDown,
|
||||||
// TODO: (Artur) for me, kVK_VolumeUp is 0x48
|
0x4a => KeyCode::AudioVolumeMute,
|
||||||
// macOS 10.11
|
|
||||||
// /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h
|
|
||||||
0x49 => KeyCode::AudioVolumeUp,
|
|
||||||
0x4a => KeyCode::AudioVolumeDown,
|
|
||||||
0x4b => KeyCode::NumpadDivide,
|
0x4b => KeyCode::NumpadDivide,
|
||||||
0x4c => KeyCode::NumpadEnter,
|
0x4c => KeyCode::NumpadEnter,
|
||||||
//0x4d => unknown,
|
// 0x4d => unknown,
|
||||||
0x4e => KeyCode::NumpadSubtract,
|
0x4e => KeyCode::NumpadSubtract,
|
||||||
0x4f => KeyCode::F18,
|
0x4f => KeyCode::F18,
|
||||||
0x50 => KeyCode::F19,
|
0x50 => KeyCode::F19,
|
||||||
@@ -636,25 +595,25 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
0x5b => KeyCode::Numpad8,
|
0x5b => KeyCode::Numpad8,
|
||||||
0x5c => KeyCode::Numpad9,
|
0x5c => KeyCode::Numpad9,
|
||||||
0x5d => KeyCode::IntlYen,
|
0x5d => KeyCode::IntlYen,
|
||||||
//0x5e => JIS Ro,
|
0x5e => KeyCode::IntlRo,
|
||||||
//0x5f => unknown,
|
0x5f => KeyCode::NumpadComma,
|
||||||
0x60 => KeyCode::F5,
|
0x60 => KeyCode::F5,
|
||||||
0x61 => KeyCode::F6,
|
0x61 => KeyCode::F6,
|
||||||
0x62 => KeyCode::F7,
|
0x62 => KeyCode::F7,
|
||||||
0x63 => KeyCode::F3,
|
0x63 => KeyCode::F3,
|
||||||
0x64 => KeyCode::F8,
|
0x64 => KeyCode::F8,
|
||||||
0x65 => KeyCode::F9,
|
0x65 => KeyCode::F9,
|
||||||
//0x66 => JIS Eisuu (macOS),
|
0x66 => KeyCode::Lang2,
|
||||||
0x67 => KeyCode::F11,
|
0x67 => KeyCode::F11,
|
||||||
//0x68 => JIS Kanna (macOS),
|
0x68 => KeyCode::Lang1,
|
||||||
0x69 => KeyCode::F13,
|
0x69 => KeyCode::F13,
|
||||||
0x6a => KeyCode::F16,
|
0x6a => KeyCode::F16,
|
||||||
0x6b => KeyCode::F14,
|
0x6b => KeyCode::F14,
|
||||||
//0x6c => unknown,
|
// 0x6c => unknown,
|
||||||
0x6d => KeyCode::F10,
|
0x6d => KeyCode::F10,
|
||||||
//0x6e => unknown,
|
0x6e => KeyCode::ContextMenu,
|
||||||
0x6f => KeyCode::F12,
|
0x6f => KeyCode::F12,
|
||||||
//0x70 => unknown,
|
// 0x70 => unknown,
|
||||||
0x71 => KeyCode::F15,
|
0x71 => KeyCode::F15,
|
||||||
0x72 => KeyCode::Insert,
|
0x72 => KeyCode::Insert,
|
||||||
0x73 => KeyCode::Home,
|
0x73 => KeyCode::Home,
|
||||||
@@ -669,11 +628,7 @@ pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
0x7c => KeyCode::ArrowRight,
|
0x7c => KeyCode::ArrowRight,
|
||||||
0x7d => KeyCode::ArrowDown,
|
0x7d => KeyCode::ArrowDown,
|
||||||
0x7e => KeyCode::ArrowUp,
|
0x7e => KeyCode::ArrowUp,
|
||||||
//0x7f => unknown,
|
0x7f => KeyCode::Power, // On 10.7 and 10.8 only
|
||||||
|
|
||||||
// 0xA is the caret (^) an macOS's German QERTZ layout. This key is at the same location as
|
|
||||||
// backquote (`) on Windows' US layout.
|
|
||||||
0xa => KeyCode::Backquote,
|
|
||||||
_ => return PhysicalKey::Unidentified(NativeKeyCode::MacOS(scancode as u16)),
|
_ => return PhysicalKey::Unidentified(NativeKeyCode::MacOS(scancode as u16)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
363
winit-appkit/src/event_loop.rs
Normal file
@@ -0,0 +1,363 @@
|
|||||||
|
use std::rc::Rc;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use objc2::rc::{autoreleasepool, Retained};
|
||||||
|
use objc2::runtime::ProtocolObject;
|
||||||
|
use objc2::{available, MainThreadMarker};
|
||||||
|
use objc2_app_kit::{
|
||||||
|
NSApplication, NSApplicationActivationPolicy, NSApplicationDidFinishLaunchingNotification,
|
||||||
|
NSApplicationWillTerminateNotification, NSWindow,
|
||||||
|
};
|
||||||
|
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol};
|
||||||
|
use rwh_06::HasDisplayHandle;
|
||||||
|
use winit_core::application::ApplicationHandler;
|
||||||
|
use winit_core::cursor::{CustomCursor as CoreCustomCursor, CustomCursorSource};
|
||||||
|
use winit_core::error::{EventLoopError, RequestError};
|
||||||
|
use winit_core::event_loop::pump_events::PumpStatus;
|
||||||
|
use winit_core::event_loop::{
|
||||||
|
ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents,
|
||||||
|
EventLoopProxy as CoreEventLoopProxy, OwnedDisplayHandle as CoreOwnedDisplayHandle,
|
||||||
|
};
|
||||||
|
use winit_core::monitor::MonitorHandle as CoreMonitorHandle;
|
||||||
|
use winit_core::window::Theme;
|
||||||
|
|
||||||
|
use super::app::override_send_event;
|
||||||
|
use super::app_state::AppState;
|
||||||
|
use super::cursor::CustomCursor;
|
||||||
|
use super::event::dummy_event;
|
||||||
|
use super::monitor;
|
||||||
|
use super::notification_center::create_observer;
|
||||||
|
use super::observer::setup_control_flow_observers;
|
||||||
|
use crate::window::Window;
|
||||||
|
use crate::ActivationPolicy;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ActiveEventLoop {
|
||||||
|
pub(super) app_state: Rc<AppState>,
|
||||||
|
pub(super) mtm: MainThreadMarker,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActiveEventLoop {
|
||||||
|
pub(crate) fn hide_application(&self) {
|
||||||
|
NSApplication::sharedApplication(self.mtm).hide(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn hide_other_applications(&self) {
|
||||||
|
NSApplication::sharedApplication(self.mtm).hideOtherApplications(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn set_allows_automatic_window_tabbing(&self, enabled: bool) {
|
||||||
|
NSWindow::setAllowsAutomaticWindowTabbing(enabled, self.mtm)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn allows_automatic_window_tabbing(&self) -> bool {
|
||||||
|
NSWindow::allowsAutomaticWindowTabbing(self.mtm)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RootActiveEventLoop for ActiveEventLoop {
|
||||||
|
fn create_proxy(&self) -> CoreEventLoopProxy {
|
||||||
|
CoreEventLoopProxy::new(self.app_state.event_loop_proxy().clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_window(
|
||||||
|
&self,
|
||||||
|
window_attributes: winit_core::window::WindowAttributes,
|
||||||
|
) -> Result<Box<dyn winit_core::window::Window>, RequestError> {
|
||||||
|
Ok(Box::new(Window::new(self, window_attributes)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_custom_cursor(
|
||||||
|
&self,
|
||||||
|
source: CustomCursorSource,
|
||||||
|
) -> Result<CoreCustomCursor, RequestError> {
|
||||||
|
Ok(CoreCustomCursor(Arc::new(CustomCursor::new(source)?)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn available_monitors(&self) -> Box<dyn Iterator<Item = CoreMonitorHandle>> {
|
||||||
|
Box::new(
|
||||||
|
monitor::available_monitors()
|
||||||
|
.into_iter()
|
||||||
|
.map(|monitor| CoreMonitorHandle(Arc::new(monitor))),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn primary_monitor(&self) -> Option<winit_core::monitor::MonitorHandle> {
|
||||||
|
let monitor = monitor::primary_monitor();
|
||||||
|
Some(CoreMonitorHandle(Arc::new(monitor)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn listen_device_events(&self, _allowed: DeviceEvents) {}
|
||||||
|
|
||||||
|
fn system_theme(&self) -> Option<Theme> {
|
||||||
|
let app = NSApplication::sharedApplication(self.mtm);
|
||||||
|
|
||||||
|
// Dark appearance was introduced in macOS 10.14
|
||||||
|
if available!(macos = 10.14) {
|
||||||
|
Some(super::window_delegate::appearance_to_theme(&app.effectiveAppearance()))
|
||||||
|
} else {
|
||||||
|
Some(Theme::Light)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||||
|
self.app_state.set_control_flow(control_flow)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn control_flow(&self) -> ControlFlow {
|
||||||
|
self.app_state.control_flow()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exit(&self) {
|
||||||
|
self.app_state.exit()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exiting(&self) -> bool {
|
||||||
|
self.app_state.exiting()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn owned_display_handle(&self) -> CoreOwnedDisplayHandle {
|
||||||
|
CoreOwnedDisplayHandle::new(Arc::new(OwnedDisplayHandle))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rwh_06_handle(&self) -> &dyn rwh_06::HasDisplayHandle {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl rwh_06::HasDisplayHandle for ActiveEventLoop {
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let raw = rwh_06::RawDisplayHandle::AppKit(rwh_06::AppKitDisplayHandle::new());
|
||||||
|
unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct EventLoop {
|
||||||
|
/// Store a reference to the application for convenience.
|
||||||
|
///
|
||||||
|
/// We intentionally don't store `WinitApplication` since we want to have
|
||||||
|
/// the possibility of swapping that out at some point.
|
||||||
|
app: Retained<NSApplication>,
|
||||||
|
app_state: Rc<AppState>,
|
||||||
|
|
||||||
|
window_target: ActiveEventLoop,
|
||||||
|
|
||||||
|
// Since macOS 10.11, we no longer need to remove the observers before they are deallocated;
|
||||||
|
// the system instead cleans it up next time it would have posted a notification to it.
|
||||||
|
//
|
||||||
|
// Though we do still need to keep the observers around to prevent them from being deallocated.
|
||||||
|
_did_finish_launching_observer: Retained<ProtocolObject<dyn NSObjectProtocol>>,
|
||||||
|
_will_terminate_observer: Retained<ProtocolObject<dyn NSObjectProtocol>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub struct PlatformSpecificEventLoopAttributes {
|
||||||
|
pub activation_policy: Option<ActivationPolicy>,
|
||||||
|
pub default_menu: bool,
|
||||||
|
pub activate_ignoring_other_apps: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for PlatformSpecificEventLoopAttributes {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { activation_policy: None, default_menu: true, activate_ignoring_other_apps: true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoop {
|
||||||
|
pub fn new(attributes: &PlatformSpecificEventLoopAttributes) -> Result<Self, EventLoopError> {
|
||||||
|
let mtm = MainThreadMarker::new()
|
||||||
|
.expect("on macOS, `EventLoop` must be created on the main thread!");
|
||||||
|
|
||||||
|
let activation_policy = match attributes.activation_policy {
|
||||||
|
None => None,
|
||||||
|
Some(ActivationPolicy::Regular) => Some(NSApplicationActivationPolicy::Regular),
|
||||||
|
Some(ActivationPolicy::Accessory) => Some(NSApplicationActivationPolicy::Accessory),
|
||||||
|
Some(ActivationPolicy::Prohibited) => Some(NSApplicationActivationPolicy::Prohibited),
|
||||||
|
};
|
||||||
|
|
||||||
|
let app_state = AppState::setup_global(
|
||||||
|
mtm,
|
||||||
|
activation_policy,
|
||||||
|
attributes.default_menu,
|
||||||
|
attributes.activate_ignoring_other_apps,
|
||||||
|
)
|
||||||
|
.ok_or_else(|| EventLoopError::RecreationAttempt)?;
|
||||||
|
|
||||||
|
// Initialize the application (if it has not already been).
|
||||||
|
let app = NSApplication::sharedApplication(mtm);
|
||||||
|
|
||||||
|
// Override `sendEvent:` on the application to forward to our application state.
|
||||||
|
override_send_event(&app);
|
||||||
|
|
||||||
|
let center = unsafe { NSNotificationCenter::defaultCenter() };
|
||||||
|
|
||||||
|
let weak_app_state = Rc::downgrade(&app_state);
|
||||||
|
let _did_finish_launching_observer = create_observer(
|
||||||
|
¢er,
|
||||||
|
// `applicationDidFinishLaunching:`
|
||||||
|
unsafe { NSApplicationDidFinishLaunchingNotification },
|
||||||
|
move |notification| {
|
||||||
|
if let Some(app_state) = weak_app_state.upgrade() {
|
||||||
|
app_state.did_finish_launching(notification);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
let weak_app_state = Rc::downgrade(&app_state);
|
||||||
|
let _will_terminate_observer = create_observer(
|
||||||
|
¢er,
|
||||||
|
// `applicationWillTerminate:`
|
||||||
|
unsafe { NSApplicationWillTerminateNotification },
|
||||||
|
move |notification| {
|
||||||
|
if let Some(app_state) = weak_app_state.upgrade() {
|
||||||
|
app_state.will_terminate(notification);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
setup_control_flow_observers(mtm);
|
||||||
|
|
||||||
|
Ok(EventLoop {
|
||||||
|
app,
|
||||||
|
app_state: app_state.clone(),
|
||||||
|
window_target: ActiveEventLoop { app_state, mtm },
|
||||||
|
_did_finish_launching_observer,
|
||||||
|
_will_terminate_observer,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn window_target(&self) -> &dyn RootActiveEventLoop {
|
||||||
|
&self.window_target
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run_app<A: ApplicationHandler>(mut self, app: A) -> Result<(), EventLoopError> {
|
||||||
|
self.run_app_on_demand(app)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NB: we don't base this on `pump_events` because for `MacOs` we can't support
|
||||||
|
// `pump_events` elegantly (we just ask to run the loop for a "short" amount of
|
||||||
|
// time and so a layered implementation would end up using a lot of CPU due to
|
||||||
|
// redundant wake ups.
|
||||||
|
pub fn run_app_on_demand<A: ApplicationHandler>(
|
||||||
|
&mut self,
|
||||||
|
app: A,
|
||||||
|
) -> Result<(), EventLoopError> {
|
||||||
|
self.app_state.clear_exit();
|
||||||
|
self.app_state.set_event_handler(app, || {
|
||||||
|
autoreleasepool(|_| {
|
||||||
|
// clear / normalize pump_events state
|
||||||
|
self.app_state.set_wait_timeout(None);
|
||||||
|
self.app_state.set_stop_before_wait(false);
|
||||||
|
self.app_state.set_stop_after_wait(false);
|
||||||
|
self.app_state.set_stop_on_redraw(false);
|
||||||
|
|
||||||
|
if self.app_state.is_launched() {
|
||||||
|
debug_assert!(!self.app_state.is_running());
|
||||||
|
self.app_state.set_is_running(true);
|
||||||
|
self.app_state.dispatch_init_events();
|
||||||
|
}
|
||||||
|
|
||||||
|
// NOTE: Make sure to not run the application re-entrantly, as that'd be confusing.
|
||||||
|
self.app.run();
|
||||||
|
|
||||||
|
self.app_state.internal_exit()
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pump_app_events<A: ApplicationHandler>(
|
||||||
|
&mut self,
|
||||||
|
timeout: Option<Duration>,
|
||||||
|
app: A,
|
||||||
|
) -> PumpStatus {
|
||||||
|
self.app_state.set_event_handler(app, || {
|
||||||
|
autoreleasepool(|_| {
|
||||||
|
// As a special case, if the application hasn't been launched yet then we at least
|
||||||
|
// run the loop until it has fully launched.
|
||||||
|
if !self.app_state.is_launched() {
|
||||||
|
debug_assert!(!self.app_state.is_running());
|
||||||
|
|
||||||
|
self.app_state.set_stop_on_launch();
|
||||||
|
self.app.run();
|
||||||
|
|
||||||
|
// Note: we dispatch `NewEvents(Init)` + `Resumed` events after the application
|
||||||
|
// has launched
|
||||||
|
} else if !self.app_state.is_running() {
|
||||||
|
// Even though the application may have been launched, it's possible we aren't
|
||||||
|
// running if the `EventLoop` was run before and has since
|
||||||
|
// exited. This indicates that we just starting to re-run
|
||||||
|
// the same `EventLoop` again.
|
||||||
|
self.app_state.set_is_running(true);
|
||||||
|
self.app_state.dispatch_init_events();
|
||||||
|
} else {
|
||||||
|
// Only run for as long as the given `Duration` allows so we don't block the
|
||||||
|
// external loop.
|
||||||
|
match timeout {
|
||||||
|
Some(Duration::ZERO) => {
|
||||||
|
self.app_state.set_wait_timeout(None);
|
||||||
|
self.app_state.set_stop_before_wait(true);
|
||||||
|
},
|
||||||
|
Some(duration) => {
|
||||||
|
self.app_state.set_stop_before_wait(false);
|
||||||
|
let timeout = Instant::now() + duration;
|
||||||
|
self.app_state.set_wait_timeout(Some(timeout));
|
||||||
|
self.app_state.set_stop_after_wait(true);
|
||||||
|
},
|
||||||
|
None => {
|
||||||
|
self.app_state.set_wait_timeout(None);
|
||||||
|
self.app_state.set_stop_before_wait(false);
|
||||||
|
self.app_state.set_stop_after_wait(true);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
self.app_state.set_stop_on_redraw(true);
|
||||||
|
self.app.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.app_state.exiting() {
|
||||||
|
self.app_state.internal_exit();
|
||||||
|
PumpStatus::Exit(0)
|
||||||
|
} else {
|
||||||
|
PumpStatus::Continue
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct OwnedDisplayHandle;
|
||||||
|
|
||||||
|
impl HasDisplayHandle for OwnedDisplayHandle {
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let raw = rwh_06::RawDisplayHandle::AppKit(rwh_06::AppKitDisplayHandle::new());
|
||||||
|
unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn stop_app_immediately(app: &NSApplication) {
|
||||||
|
autoreleasepool(|_| {
|
||||||
|
app.stop(None);
|
||||||
|
// To stop event loop immediately, we need to post some event here.
|
||||||
|
// See: https://stackoverflow.com/questions/48041279/stopping-the-nsapplication-main-event-loop/48064752#48064752
|
||||||
|
app.postEvent_atStart(&dummy_event().unwrap(), true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tell all windows to close.
|
||||||
|
///
|
||||||
|
/// This will synchronously trigger `WindowEvent::Destroyed` within
|
||||||
|
/// `windowWillClose:`, giving the application one last chance to handle
|
||||||
|
/// those events. It doesn't matter if the user also ends up closing the
|
||||||
|
/// windows in `Window`'s `Drop` impl, once a window has been closed once, it
|
||||||
|
/// stays closed.
|
||||||
|
///
|
||||||
|
/// This ensures that no windows linger on after the event loop has exited,
|
||||||
|
/// see <https://github.com/rust-windowing/winit/issues/4135>.
|
||||||
|
pub(super) fn notify_windows_of_exit(app: &NSApplication) {
|
||||||
|
for window in app.windows() {
|
||||||
|
window.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
89
winit-appkit/src/ffi.rs
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
// TODO: Upstream these
|
||||||
|
|
||||||
|
#![allow(non_upper_case_globals)]
|
||||||
|
|
||||||
|
use std::ffi::c_void;
|
||||||
|
|
||||||
|
use objc2::ffi::NSInteger;
|
||||||
|
use objc2::runtime::AnyObject;
|
||||||
|
use objc2_core_foundation::{cf_type, CFString, CFUUID};
|
||||||
|
use objc2_core_graphics::CGDirectDisplayID;
|
||||||
|
|
||||||
|
pub const IO16BitDirectPixels: &str = "-RRRRRGGGGGBBBBB";
|
||||||
|
pub const IO32BitDirectPixels: &str = "--------RRRRRRRRGGGGGGGGBBBBBBBB";
|
||||||
|
pub const kIO30BitDirectPixels: &str = "--RRRRRRRRRRGGGGGGGGGGBBBBBBBBBB";
|
||||||
|
pub const kIO64BitDirectPixels: &str = "-16R16G16B16";
|
||||||
|
|
||||||
|
// `CGDisplayCreateUUIDFromDisplayID` comes from the `ColorSync` framework.
|
||||||
|
// However, that framework was only introduced "publicly" in macOS 10.13.
|
||||||
|
//
|
||||||
|
// Since we want to support older versions, we can't link to `ColorSync`
|
||||||
|
// directly. Fortunately, it has always been available as a subframework of
|
||||||
|
// `ApplicationServices`, see:
|
||||||
|
// https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/OSX_Technology_Overview/SystemFrameworks/SystemFrameworks.html#//apple_ref/doc/uid/TP40001067-CH210-BBCFFIEG
|
||||||
|
#[link(name = "ApplicationServices", kind = "framework")]
|
||||||
|
extern "C" {
|
||||||
|
pub fn CGDisplayCreateUUIDFromDisplayID(display: CGDirectDisplayID) -> *mut CFUUID;
|
||||||
|
|
||||||
|
pub fn CGDisplayGetDisplayIDFromUUID(uuid: &CFUUID) -> CGDirectDisplayID;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[link(name = "CoreGraphics", kind = "framework")]
|
||||||
|
extern "C" {
|
||||||
|
// Wildly used private APIs; Apple uses them for their Terminal.app.
|
||||||
|
pub fn CGSMainConnectionID() -> *mut AnyObject;
|
||||||
|
pub fn CGSSetWindowBackgroundBlurRadius(
|
||||||
|
connection_id: *mut AnyObject,
|
||||||
|
window_id: NSInteger,
|
||||||
|
radius: i64,
|
||||||
|
) -> i32;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(transparent)]
|
||||||
|
pub struct TISInputSource(std::ffi::c_void);
|
||||||
|
|
||||||
|
cf_type!(
|
||||||
|
unsafe impl TISInputSource {}
|
||||||
|
);
|
||||||
|
|
||||||
|
#[repr(transparent)]
|
||||||
|
pub struct UCKeyboardLayout(std::ffi::c_void);
|
||||||
|
|
||||||
|
pub type OptionBits = u32;
|
||||||
|
pub type UniCharCount = std::os::raw::c_ulong;
|
||||||
|
pub type UniChar = std::os::raw::c_ushort;
|
||||||
|
pub type OSStatus = i32;
|
||||||
|
|
||||||
|
#[allow(non_upper_case_globals)]
|
||||||
|
pub const kUCKeyActionDisplay: u16 = 3;
|
||||||
|
#[allow(non_upper_case_globals)]
|
||||||
|
pub const kUCKeyTranslateNoDeadKeysMask: OptionBits = 1;
|
||||||
|
|
||||||
|
#[link(name = "Carbon", kind = "framework")]
|
||||||
|
extern "C" {
|
||||||
|
pub static kTISPropertyUnicodeKeyLayoutData: &'static CFString;
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
pub fn TISGetInputSourceProperty(
|
||||||
|
inputSource: &TISInputSource,
|
||||||
|
propertyKey: &CFString,
|
||||||
|
) -> *mut c_void;
|
||||||
|
|
||||||
|
pub fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut TISInputSource;
|
||||||
|
|
||||||
|
pub fn LMGetKbdType() -> u8;
|
||||||
|
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
pub fn UCKeyTranslate(
|
||||||
|
keyLayoutPtr: *const UCKeyboardLayout,
|
||||||
|
virtualKeyCode: u16,
|
||||||
|
keyAction: u16,
|
||||||
|
modifierKeyState: u32,
|
||||||
|
keyboardType: u32,
|
||||||
|
keyTranslateOptions: OptionBits,
|
||||||
|
deadKeyState: *mut u32,
|
||||||
|
maxStringLength: UniCharCount,
|
||||||
|
actualStringLength: *mut UniCharCount,
|
||||||
|
unicodeString: *mut UniChar,
|
||||||
|
) -> OSStatus;
|
||||||
|
}
|
||||||
611
winit-appkit/src/lib.rs
Normal file
@@ -0,0 +1,611 @@
|
|||||||
|
//! # macOS / AppKit
|
||||||
|
//!
|
||||||
|
//! Winit has [the same macOS version requirements as `rustc`][rustc-macos-version], and is tested
|
||||||
|
//! once in a while on as low as macOS 10.14.
|
||||||
|
//!
|
||||||
|
//! [rustc-macos-version]: https://doc.rust-lang.org/rustc/platform-support/apple-darwin.html#os-version
|
||||||
|
//!
|
||||||
|
//! ## Custom `NSApplicationDelegate`
|
||||||
|
//!
|
||||||
|
//! Winit usually handles everything related to the lifecycle events of the application. Sometimes,
|
||||||
|
//! though, you might want to do more niche stuff, such as [handle when the user re-activates the
|
||||||
|
//! application][reopen]. Such functionality is not exposed directly in Winit, since it would
|
||||||
|
//! increase the API surface by quite a lot.
|
||||||
|
//!
|
||||||
|
//! [reopen]: https://developer.apple.com/documentation/appkit/nsapplicationdelegate/1428638-applicationshouldhandlereopen?language=objc
|
||||||
|
//!
|
||||||
|
//! Instead, Winit guarantees that it will not register an application delegate, so the solution is
|
||||||
|
//! to register your own application delegate, as outlined in the following example (see
|
||||||
|
//! `objc2-app-kit` for more detailed information).
|
||||||
|
//! ```
|
||||||
|
//! use objc2::rc::Retained;
|
||||||
|
//! use objc2::runtime::ProtocolObject;
|
||||||
|
//! use objc2::{define_class, msg_send, DefinedClass, MainThreadMarker, MainThreadOnly};
|
||||||
|
//! use objc2_app_kit::{NSApplication, NSApplicationDelegate};
|
||||||
|
//! use objc2_foundation::{NSArray, NSObject, NSObjectProtocol, NSURL};
|
||||||
|
//! use winit::event_loop::EventLoop;
|
||||||
|
//!
|
||||||
|
//! define_class!(
|
||||||
|
//! #[unsafe(super(NSObject))]
|
||||||
|
//! #[thread_kind = MainThreadOnly]
|
||||||
|
//! #[name = "AppDelegate"]
|
||||||
|
//! struct AppDelegate;
|
||||||
|
//!
|
||||||
|
//! unsafe impl NSObjectProtocol for AppDelegate {}
|
||||||
|
//!
|
||||||
|
//! unsafe impl NSApplicationDelegate for AppDelegate {
|
||||||
|
//! #[unsafe(method(application:openURLs:))]
|
||||||
|
//! fn application_openURLs(&self, application: &NSApplication, urls: &NSArray<NSURL>) {
|
||||||
|
//! // Note: To specifically get `application:openURLs:` to work, you _might_
|
||||||
|
//! // have to bundle your application. This is not done in this example.
|
||||||
|
//! println!("open urls: {application:?}, {urls:?}");
|
||||||
|
//! }
|
||||||
|
//! }
|
||||||
|
//! );
|
||||||
|
//!
|
||||||
|
//! impl AppDelegate {
|
||||||
|
//! fn new(mtm: MainThreadMarker) -> Retained<Self> {
|
||||||
|
//! unsafe { msg_send![super(Self::alloc(mtm).set_ivars(())), init] }
|
||||||
|
//! }
|
||||||
|
//! }
|
||||||
|
//!
|
||||||
|
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
//! let event_loop = EventLoop::new()?;
|
||||||
|
//!
|
||||||
|
//! let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
//! let delegate = AppDelegate::new(mtm);
|
||||||
|
//! // Important: Call `sharedApplication` after `EventLoop::new`,
|
||||||
|
//! // doing it before is not yet supported.
|
||||||
|
//! let app = NSApplication::sharedApplication(mtm);
|
||||||
|
//! app.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
|
||||||
|
//!
|
||||||
|
//! // event_loop.run_app(&mut my_app);
|
||||||
|
//! Ok(())
|
||||||
|
//! }
|
||||||
|
//! ```
|
||||||
|
#![cfg(target_vendor = "apple")] // TODO: Remove once `objc2` allows compiling on all platforms
|
||||||
|
|
||||||
|
#[macro_use]
|
||||||
|
mod util;
|
||||||
|
|
||||||
|
mod app;
|
||||||
|
mod app_state;
|
||||||
|
mod cursor;
|
||||||
|
mod event;
|
||||||
|
mod event_loop;
|
||||||
|
mod ffi;
|
||||||
|
mod menu;
|
||||||
|
mod monitor;
|
||||||
|
mod notification_center;
|
||||||
|
mod observer;
|
||||||
|
mod view;
|
||||||
|
mod window;
|
||||||
|
mod window_delegate;
|
||||||
|
|
||||||
|
use std::os::raw::c_void;
|
||||||
|
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
#[doc(inline)]
|
||||||
|
pub use winit_core::application::macos::ApplicationHandlerExtMacOS;
|
||||||
|
use winit_core::event_loop::ActiveEventLoop;
|
||||||
|
use winit_core::monitor::MonitorHandle;
|
||||||
|
use winit_core::window::{PlatformWindowAttributes, Window};
|
||||||
|
|
||||||
|
pub use self::event::{physicalkey_to_scancode, scancode_to_physicalkey};
|
||||||
|
use self::event_loop::ActiveEventLoop as AppKitActiveEventLoop;
|
||||||
|
pub use self::event_loop::{EventLoop, PlatformSpecificEventLoopAttributes};
|
||||||
|
use self::monitor::MonitorHandle as AppKitMonitorHandle;
|
||||||
|
use self::window::Window as AppKitWindow;
|
||||||
|
|
||||||
|
/// Additional methods on [`Window`] that are specific to MacOS.
|
||||||
|
pub trait WindowExtMacOS {
|
||||||
|
/// Returns whether or not the window is in simple fullscreen mode.
|
||||||
|
fn simple_fullscreen(&self) -> bool;
|
||||||
|
|
||||||
|
/// Toggles a fullscreen mode that doesn't require a new macOS space.
|
||||||
|
/// Returns a boolean indicating whether the transition was successful (this
|
||||||
|
/// won't work if the window was already in the native fullscreen).
|
||||||
|
///
|
||||||
|
/// This is how fullscreen used to work on macOS in versions before Lion.
|
||||||
|
/// And allows the user to have a fullscreen window without using another
|
||||||
|
/// space or taking control over the entire monitor.
|
||||||
|
///
|
||||||
|
/// Make sure you only draw your important content inside the safe area so that it does not
|
||||||
|
/// overlap with the notch on newer devices, see [`Window::safe_area`] for details.
|
||||||
|
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool;
|
||||||
|
|
||||||
|
/// Returns whether or not the window has shadow.
|
||||||
|
fn has_shadow(&self) -> bool;
|
||||||
|
|
||||||
|
/// Sets whether or not the window has shadow.
|
||||||
|
fn set_has_shadow(&self, has_shadow: bool);
|
||||||
|
|
||||||
|
/// Group windows together by using the same tabbing identifier.
|
||||||
|
///
|
||||||
|
/// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
|
||||||
|
fn set_tabbing_identifier(&self, identifier: &str);
|
||||||
|
|
||||||
|
/// Returns the window's tabbing identifier.
|
||||||
|
fn tabbing_identifier(&self) -> String;
|
||||||
|
|
||||||
|
/// Select next tab.
|
||||||
|
fn select_next_tab(&self);
|
||||||
|
|
||||||
|
/// Select previous tab.
|
||||||
|
fn select_previous_tab(&self);
|
||||||
|
|
||||||
|
/// Select the tab with the given index.
|
||||||
|
///
|
||||||
|
/// Will no-op when the index is out of bounds.
|
||||||
|
fn select_tab_at_index(&self, index: usize);
|
||||||
|
|
||||||
|
/// Get the number of tabs in the window tab group.
|
||||||
|
fn num_tabs(&self) -> usize;
|
||||||
|
|
||||||
|
/// Get the window's edit state.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```ignore
|
||||||
|
/// WindowEvent::CloseRequested => {
|
||||||
|
/// if window.is_document_edited() {
|
||||||
|
/// // Show the user a save pop-up or similar
|
||||||
|
/// } else {
|
||||||
|
/// // Close the window
|
||||||
|
/// drop(window);
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
fn is_document_edited(&self) -> bool;
|
||||||
|
|
||||||
|
/// Put the window in a state which indicates a file save is required.
|
||||||
|
fn set_document_edited(&self, edited: bool);
|
||||||
|
|
||||||
|
/// Set option as alt behavior as described in [`OptionAsAlt`].
|
||||||
|
///
|
||||||
|
/// This will ignore diacritical marks and accent characters from
|
||||||
|
/// being processed as received characters. Instead, the input
|
||||||
|
/// device's raw character will be placed in event queues with the
|
||||||
|
/// Alt modifier set.
|
||||||
|
fn set_option_as_alt(&self, option_as_alt: OptionAsAlt);
|
||||||
|
|
||||||
|
/// Getter for the [`WindowExtMacOS::set_option_as_alt`].
|
||||||
|
fn option_as_alt(&self) -> OptionAsAlt;
|
||||||
|
|
||||||
|
/// Disable the Menu Bar and Dock in Simple or Borderless Fullscreen mode. Useful for games.
|
||||||
|
/// The effect is applied when [`WindowExtMacOS::set_simple_fullscreen`] or
|
||||||
|
/// [`Window::set_fullscreen`] is called.
|
||||||
|
fn set_borderless_game(&self, borderless_game: bool);
|
||||||
|
|
||||||
|
/// Getter for the [`WindowExtMacOS::set_borderless_game`].
|
||||||
|
fn is_borderless_game(&self) -> bool;
|
||||||
|
|
||||||
|
/// Makes the titlebar bigger, effectively adding more space around the
|
||||||
|
/// window controls if the titlebar is invisible.
|
||||||
|
fn set_unified_titlebar(&self, unified_titlebar: bool);
|
||||||
|
|
||||||
|
/// Getter for the [`WindowExtMacOS::set_unified_titlebar`].
|
||||||
|
fn unified_titlebar(&self) -> bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowExtMacOS for dyn Window + '_ {
|
||||||
|
#[inline]
|
||||||
|
fn simple_fullscreen(&self) -> bool {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.simple_fullscreen())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(move |w| w.set_simple_fullscreen(fullscreen))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn has_shadow(&self) -> bool {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.has_shadow())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_has_shadow(&self, has_shadow: bool) {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(move |w| w.set_has_shadow(has_shadow));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_tabbing_identifier(&self, identifier: &str) {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.set_tabbing_identifier(identifier))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn tabbing_identifier(&self) -> String {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.tabbing_identifier())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn select_next_tab(&self) {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.select_next_tab());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn select_previous_tab(&self) {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.select_previous_tab());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn select_tab_at_index(&self, index: usize) {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(move |w| w.select_tab_at_index(index));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn num_tabs(&self) -> usize {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.num_tabs())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn is_document_edited(&self) -> bool {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.is_document_edited())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_document_edited(&self, edited: bool) {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(move |w| w.set_document_edited(edited));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(move |w| w.set_option_as_alt(option_as_alt));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn option_as_alt(&self) -> OptionAsAlt {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.option_as_alt())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_borderless_game(&self, borderless_game: bool) {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.set_borderless_game(borderless_game))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn is_borderless_game(&self) -> bool {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.is_borderless_game())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_unified_titlebar(&self, unified_titlebar: bool) {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.set_unified_titlebar(unified_titlebar))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn unified_titlebar(&self) -> bool {
|
||||||
|
let window = self.cast_ref::<AppKitWindow>().unwrap();
|
||||||
|
window.maybe_wait_on_main(|w| w.unified_titlebar())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Corresponds to `NSApplicationActivationPolicy`.
|
||||||
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
pub enum ActivationPolicy {
|
||||||
|
/// Corresponds to `NSApplicationActivationPolicyRegular`.
|
||||||
|
#[default]
|
||||||
|
Regular,
|
||||||
|
|
||||||
|
/// Corresponds to `NSApplicationActivationPolicyAccessory`.
|
||||||
|
Accessory,
|
||||||
|
|
||||||
|
/// Corresponds to `NSApplicationActivationPolicyProhibited`.
|
||||||
|
Prohibited,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Window attributes that are specific to MacOS.
|
||||||
|
///
|
||||||
|
/// **Note:** Properties dealing with the titlebar will be overwritten by the
|
||||||
|
/// [`WindowAttributes::with_decorations`] method:
|
||||||
|
/// - `with_titlebar_transparent`
|
||||||
|
/// - `with_title_hidden`
|
||||||
|
/// - `with_titlebar_hidden`
|
||||||
|
/// - `with_titlebar_buttons_hidden`
|
||||||
|
/// - `with_fullsize_content_view`
|
||||||
|
///
|
||||||
|
/// [`WindowAttributes::with_decorations`]: crate::window::WindowAttributes::with_decorations
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct WindowAttributesMacOS {
|
||||||
|
pub(crate) movable_by_window_background: bool,
|
||||||
|
pub(crate) titlebar_transparent: bool,
|
||||||
|
pub(crate) title_hidden: bool,
|
||||||
|
pub(crate) titlebar_hidden: bool,
|
||||||
|
pub(crate) titlebar_buttons_hidden: bool,
|
||||||
|
pub(crate) fullsize_content_view: bool,
|
||||||
|
pub(crate) disallow_hidpi: bool,
|
||||||
|
pub(crate) has_shadow: bool,
|
||||||
|
pub(crate) accepts_first_mouse: bool,
|
||||||
|
pub(crate) tabbing_identifier: Option<String>,
|
||||||
|
pub(crate) option_as_alt: OptionAsAlt,
|
||||||
|
pub(crate) borderless_game: bool,
|
||||||
|
pub(crate) unified_titlebar: bool,
|
||||||
|
pub(crate) panel: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowAttributesMacOS {
|
||||||
|
/// Enables click-and-drag behavior for the entire window, not just the titlebar.
|
||||||
|
#[inline]
|
||||||
|
pub fn with_movable_by_window_background(mut self, movable_by_window_background: bool) -> Self {
|
||||||
|
self.movable_by_window_background = movable_by_window_background;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Makes the titlebar transparent and allows the content to appear behind it.
|
||||||
|
#[inline]
|
||||||
|
pub fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> Self {
|
||||||
|
self.titlebar_transparent = titlebar_transparent;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hides the window titlebar.
|
||||||
|
#[inline]
|
||||||
|
pub fn with_titlebar_hidden(mut self, titlebar_hidden: bool) -> Self {
|
||||||
|
self.titlebar_hidden = titlebar_hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hides the window titlebar buttons.
|
||||||
|
#[inline]
|
||||||
|
pub fn with_titlebar_buttons_hidden(mut self, titlebar_buttons_hidden: bool) -> Self {
|
||||||
|
self.titlebar_buttons_hidden = titlebar_buttons_hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hides the window title.
|
||||||
|
#[inline]
|
||||||
|
pub fn with_title_hidden(mut self, title_hidden: bool) -> Self {
|
||||||
|
self.title_hidden = title_hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Makes the window content appear behind the titlebar.
|
||||||
|
#[inline]
|
||||||
|
pub fn with_fullsize_content_view(mut self, fullsize_content_view: bool) -> Self {
|
||||||
|
self.fullsize_content_view = fullsize_content_view;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn with_disallow_hidpi(mut self, disallow_hidpi: bool) -> Self {
|
||||||
|
self.disallow_hidpi = disallow_hidpi;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn with_has_shadow(mut self, has_shadow: bool) -> Self {
|
||||||
|
self.has_shadow = has_shadow;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Window accepts click-through mouse events.
|
||||||
|
#[inline]
|
||||||
|
pub fn with_accepts_first_mouse(mut self, accepts_first_mouse: bool) -> Self {
|
||||||
|
self.accepts_first_mouse = accepts_first_mouse;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Defines the window tabbing identifier.
|
||||||
|
///
|
||||||
|
/// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
|
||||||
|
#[inline]
|
||||||
|
pub fn with_tabbing_identifier(mut self, tabbing_identifier: &str) -> Self {
|
||||||
|
self.tabbing_identifier.replace(tabbing_identifier.to_string());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set how the <kbd>Option</kbd> keys are interpreted.
|
||||||
|
///
|
||||||
|
/// See [`WindowExtMacOS::set_option_as_alt`] for details on what this means if set.
|
||||||
|
#[inline]
|
||||||
|
pub fn with_option_as_alt(mut self, option_as_alt: OptionAsAlt) -> Self {
|
||||||
|
self.option_as_alt = option_as_alt;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// See [`WindowExtMacOS::set_borderless_game`] for details on what this means if set.
|
||||||
|
#[inline]
|
||||||
|
pub fn with_borderless_game(mut self, borderless_game: bool) -> Self {
|
||||||
|
self.borderless_game = borderless_game;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// See [`WindowExtMacOS::set_unified_titlebar`] for details on what this means if set.
|
||||||
|
#[inline]
|
||||||
|
pub fn with_unified_titlebar(mut self, unified_titlebar: bool) -> Self {
|
||||||
|
self.unified_titlebar = unified_titlebar;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Use [`NSPanel`] window with [`NonactivatingPanel`] window style mask instead of
|
||||||
|
/// [`NSWindow`].
|
||||||
|
///
|
||||||
|
/// [`NSWindow`]: https://developer.apple.com/documentation/appkit/NSWindow?language=objc
|
||||||
|
/// [`NSPanel`]: https://developer.apple.com/documentation/appkit/NSPanel?language=objc
|
||||||
|
/// [`NonactivatingPanel`]: https://developer.apple.com/documentation/appkit/nswindow/stylemask-swift.struct/nonactivatingpanel?language=objc
|
||||||
|
#[inline]
|
||||||
|
pub fn with_panel(mut self, panel: bool) -> Self {
|
||||||
|
self.panel = panel;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for WindowAttributesMacOS {
|
||||||
|
#[inline]
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
movable_by_window_background: false,
|
||||||
|
titlebar_transparent: false,
|
||||||
|
title_hidden: false,
|
||||||
|
titlebar_hidden: false,
|
||||||
|
titlebar_buttons_hidden: false,
|
||||||
|
fullsize_content_view: false,
|
||||||
|
disallow_hidpi: false,
|
||||||
|
has_shadow: true,
|
||||||
|
accepts_first_mouse: true,
|
||||||
|
tabbing_identifier: None,
|
||||||
|
option_as_alt: Default::default(),
|
||||||
|
borderless_game: false,
|
||||||
|
unified_titlebar: false,
|
||||||
|
panel: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PlatformWindowAttributes for WindowAttributesMacOS {
|
||||||
|
fn box_clone(&self) -> Box<dyn PlatformWindowAttributes> {
|
||||||
|
Box::from(self.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait EventLoopBuilderExtMacOS {
|
||||||
|
/// Sets the activation policy for the application. If used, this will override
|
||||||
|
/// any relevant settings provided in the package manifest.
|
||||||
|
/// For instance, `with_activation_policy(ActivationPolicy::Regular)` will prevent
|
||||||
|
/// the application from running as an "agent", even if LSUIElement is set to true.
|
||||||
|
///
|
||||||
|
/// If unused, the Winit will honor the package manifest.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// Set the activation policy to "accessory".
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use winit::event_loop::EventLoop;
|
||||||
|
/// #[cfg(target_os = "macos")]
|
||||||
|
/// use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS};
|
||||||
|
///
|
||||||
|
/// let mut builder = EventLoop::builder();
|
||||||
|
/// #[cfg(target_os = "macos")]
|
||||||
|
/// builder.with_activation_policy(ActivationPolicy::Accessory);
|
||||||
|
/// # if false { // We can't test this part
|
||||||
|
/// let event_loop = builder.build();
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
fn with_activation_policy(&mut self, activation_policy: ActivationPolicy) -> &mut Self;
|
||||||
|
|
||||||
|
/// Used to control whether a default menubar menu is created.
|
||||||
|
///
|
||||||
|
/// Menu creation is enabled by default.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// Disable creating a default menubar.
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use winit::event_loop::EventLoop;
|
||||||
|
/// #[cfg(target_os = "macos")]
|
||||||
|
/// use winit::platform::macos::EventLoopBuilderExtMacOS;
|
||||||
|
///
|
||||||
|
/// let mut builder = EventLoop::builder();
|
||||||
|
/// #[cfg(target_os = "macos")]
|
||||||
|
/// builder.with_default_menu(false);
|
||||||
|
/// # if false { // We can't test this part
|
||||||
|
/// let event_loop = builder.build();
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
fn with_default_menu(&mut self, enable: bool) -> &mut Self;
|
||||||
|
|
||||||
|
/// Used to prevent the application from automatically activating when launched if
|
||||||
|
/// another application is already active.
|
||||||
|
///
|
||||||
|
/// The default behavior is to ignore other applications and activate when launched.
|
||||||
|
fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`MonitorHandle`] that are specific to MacOS.
|
||||||
|
pub trait MonitorHandleExtMacOS {
|
||||||
|
/// Returns a pointer to the NSScreen representing this monitor.
|
||||||
|
fn ns_screen(&self) -> Option<*mut c_void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonitorHandleExtMacOS for MonitorHandle {
|
||||||
|
fn ns_screen(&self) -> Option<*mut c_void> {
|
||||||
|
let monitor = self.cast_ref::<AppKitMonitorHandle>().unwrap();
|
||||||
|
// SAFETY: We only use the marker to get a pointer
|
||||||
|
let mtm = unsafe { objc2::MainThreadMarker::new_unchecked() };
|
||||||
|
monitor.ns_screen(mtm).map(|s| objc2::rc::Retained::as_ptr(&s) as _)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`ActiveEventLoop`] that are specific to macOS.
|
||||||
|
pub trait ActiveEventLoopExtMacOS {
|
||||||
|
/// Hide the entire application. In most applications this is typically triggered with
|
||||||
|
/// Command-H.
|
||||||
|
fn hide_application(&self);
|
||||||
|
/// Hide the other applications. In most applications this is typically triggered with
|
||||||
|
/// Command+Option-H.
|
||||||
|
fn hide_other_applications(&self);
|
||||||
|
/// Set whether the system can automatically organize windows into tabs.
|
||||||
|
///
|
||||||
|
/// <https://developer.apple.com/documentation/appkit/nswindow/1646657-allowsautomaticwindowtabbing>
|
||||||
|
fn set_allows_automatic_window_tabbing(&self, enabled: bool);
|
||||||
|
/// Returns whether the system can automatically organize windows into tabs.
|
||||||
|
fn allows_automatic_window_tabbing(&self) -> bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActiveEventLoopExtMacOS for dyn ActiveEventLoop + '_ {
|
||||||
|
fn hide_application(&self) {
|
||||||
|
let event_loop =
|
||||||
|
self.cast_ref::<AppKitActiveEventLoop>().expect("non macOS event loop on macOS");
|
||||||
|
event_loop.hide_application()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hide_other_applications(&self) {
|
||||||
|
let event_loop =
|
||||||
|
self.cast_ref::<AppKitActiveEventLoop>().expect("non macOS event loop on macOS");
|
||||||
|
event_loop.hide_other_applications()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_allows_automatic_window_tabbing(&self, enabled: bool) {
|
||||||
|
let event_loop =
|
||||||
|
self.cast_ref::<AppKitActiveEventLoop>().expect("non macOS event loop on macOS");
|
||||||
|
event_loop.set_allows_automatic_window_tabbing(enabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn allows_automatic_window_tabbing(&self) -> bool {
|
||||||
|
let event_loop =
|
||||||
|
self.cast_ref::<AppKitActiveEventLoop>().expect("non macOS event loop on macOS");
|
||||||
|
event_loop.allows_automatic_window_tabbing()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Option as alt behavior.
|
||||||
|
///
|
||||||
|
/// The default is `None`.
|
||||||
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
pub enum OptionAsAlt {
|
||||||
|
/// The left `Option` key is treated as `Alt`.
|
||||||
|
OnlyLeft,
|
||||||
|
|
||||||
|
/// The right `Option` key is treated as `Alt`.
|
||||||
|
OnlyRight,
|
||||||
|
|
||||||
|
/// Both `Option` keys are treated as `Alt`.
|
||||||
|
Both,
|
||||||
|
|
||||||
|
/// No special handling is applied for `Option` key.
|
||||||
|
#[default]
|
||||||
|
None,
|
||||||
|
}
|
||||||
@@ -1,11 +1,8 @@
|
|||||||
use icrate::AppKit::{
|
use objc2::rc::Retained;
|
||||||
NSApplication, NSEventModifierFlagCommand, NSEventModifierFlagOption, NSEventModifierFlags,
|
|
||||||
NSMenu, NSMenuItem,
|
|
||||||
};
|
|
||||||
use icrate::Foundation::{ns_string, MainThreadMarker, NSProcessInfo, NSString};
|
|
||||||
use objc2::rc::Id;
|
|
||||||
use objc2::runtime::Sel;
|
use objc2::runtime::Sel;
|
||||||
use objc2::sel;
|
use objc2::{sel, MainThreadMarker};
|
||||||
|
use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSMenu, NSMenuItem};
|
||||||
|
use objc2_foundation::{ns_string, NSBundle, NSProcessInfo, NSString};
|
||||||
|
|
||||||
struct KeyEquivalent<'a> {
|
struct KeyEquivalent<'a> {
|
||||||
key: &'a NSString,
|
key: &'a NSString,
|
||||||
@@ -19,23 +16,22 @@ pub fn initialize(app: &NSApplication) {
|
|||||||
menubar.addItem(&app_menu_item);
|
menubar.addItem(&app_menu_item);
|
||||||
|
|
||||||
let app_menu = NSMenu::new(mtm);
|
let app_menu = NSMenu::new(mtm);
|
||||||
let process_name = NSProcessInfo::processInfo().processName();
|
let process_name = match NSBundle::mainBundle().name() {
|
||||||
|
Some(bundle_name) => bundle_name,
|
||||||
|
None => NSProcessInfo::processInfo().processName(),
|
||||||
|
};
|
||||||
|
|
||||||
// About menu item
|
// About menu item
|
||||||
let about_item_title = ns_string!("About ").stringByAppendingString(&process_name);
|
let about_item_title = ns_string!("About ").stringByAppendingString(&process_name);
|
||||||
let about_item = menu_item(
|
let about_item =
|
||||||
mtm,
|
menu_item(mtm, &about_item_title, Some(sel!(orderFrontStandardAboutPanel:)), None);
|
||||||
&about_item_title,
|
|
||||||
Some(sel!(orderFrontStandardAboutPanel:)),
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Services menu item
|
// Services menu item
|
||||||
let services_menu = NSMenu::new(mtm);
|
let services_menu = NSMenu::new(mtm);
|
||||||
let services_item = menu_item(mtm, ns_string!("Services"), None, None);
|
let services_item = menu_item(mtm, ns_string!("Services"), None, None);
|
||||||
services_item.setSubmenu(Some(&services_menu));
|
services_item.setSubmenu(Some(&services_menu));
|
||||||
|
|
||||||
// Seperator menu item
|
// Separator menu item
|
||||||
let sep_first = NSMenuItem::separatorItem(mtm);
|
let sep_first = NSMenuItem::separatorItem(mtm);
|
||||||
|
|
||||||
// Hide application menu item
|
// Hide application menu item
|
||||||
@@ -44,10 +40,7 @@ pub fn initialize(app: &NSApplication) {
|
|||||||
mtm,
|
mtm,
|
||||||
&hide_item_title,
|
&hide_item_title,
|
||||||
Some(sel!(hide:)),
|
Some(sel!(hide:)),
|
||||||
Some(KeyEquivalent {
|
Some(KeyEquivalent { key: ns_string!("h"), masks: None }),
|
||||||
key: ns_string!("h"),
|
|
||||||
masks: None,
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
// Hide other applications menu item
|
// Hide other applications menu item
|
||||||
@@ -58,20 +51,16 @@ pub fn initialize(app: &NSApplication) {
|
|||||||
Some(sel!(hideOtherApplications:)),
|
Some(sel!(hideOtherApplications:)),
|
||||||
Some(KeyEquivalent {
|
Some(KeyEquivalent {
|
||||||
key: ns_string!("h"),
|
key: ns_string!("h"),
|
||||||
masks: Some(NSEventModifierFlagOption | NSEventModifierFlagCommand),
|
masks: Some(NSEventModifierFlags::Option | NSEventModifierFlags::Command),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Show applications menu item
|
// Show applications menu item
|
||||||
let show_all_item_title = ns_string!("Show All");
|
let show_all_item_title = ns_string!("Show All");
|
||||||
let show_all_item = menu_item(
|
let show_all_item =
|
||||||
mtm,
|
menu_item(mtm, show_all_item_title, Some(sel!(unhideAllApplications:)), None);
|
||||||
show_all_item_title,
|
|
||||||
Some(sel!(unhideAllApplications:)),
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Seperator menu item
|
// Separator menu item
|
||||||
let sep = NSMenuItem::separatorItem(mtm);
|
let sep = NSMenuItem::separatorItem(mtm);
|
||||||
|
|
||||||
// Quit application menu item
|
// Quit application menu item
|
||||||
@@ -80,10 +69,7 @@ pub fn initialize(app: &NSApplication) {
|
|||||||
mtm,
|
mtm,
|
||||||
&quit_item_title,
|
&quit_item_title,
|
||||||
Some(sel!(terminate:)),
|
Some(sel!(terminate:)),
|
||||||
Some(KeyEquivalent {
|
Some(KeyEquivalent { key: ns_string!("q"), masks: None }),
|
||||||
key: ns_string!("q"),
|
|
||||||
masks: None,
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
app_menu.addItem(&about_item);
|
app_menu.addItem(&about_item);
|
||||||
@@ -105,7 +91,7 @@ fn menu_item(
|
|||||||
title: &NSString,
|
title: &NSString,
|
||||||
selector: Option<Sel>,
|
selector: Option<Sel>,
|
||||||
key_equivalent: Option<KeyEquivalent<'_>>,
|
key_equivalent: Option<KeyEquivalent<'_>>,
|
||||||
) -> Id<NSMenuItem> {
|
) -> Retained<NSMenuItem> {
|
||||||
let (key, masks) = match key_equivalent {
|
let (key, masks) = match key_equivalent {
|
||||||
Some(ke) => (ke.key, ke.masks),
|
Some(ke) => (ke.key, ke.masks),
|
||||||
None => (ns_string!(""), None),
|
None => (ns_string!(""), None),
|
||||||
403
winit-appkit/src/monitor.rs
Normal file
@@ -0,0 +1,403 @@
|
|||||||
|
#![allow(clippy::unnecessary_cast)]
|
||||||
|
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
use std::num::{NonZeroU16, NonZeroU32};
|
||||||
|
use std::ptr::NonNull;
|
||||||
|
use std::{fmt, ptr};
|
||||||
|
|
||||||
|
use dispatch2::run_on_main;
|
||||||
|
use dpi::{LogicalPosition, PhysicalPosition, PhysicalSize};
|
||||||
|
use objc2::rc::Retained;
|
||||||
|
use objc2::MainThreadMarker;
|
||||||
|
use objc2_app_kit::NSScreen;
|
||||||
|
use objc2_core_foundation::{CFArray, CFRetained, CFUUID};
|
||||||
|
use objc2_core_graphics::{
|
||||||
|
CGDirectDisplayID, CGDisplayBounds, CGDisplayCopyAllDisplayModes, CGDisplayCopyDisplayMode,
|
||||||
|
CGDisplayMode, CGDisplayModelNumber, CGGetActiveDisplayList, CGMainDisplayID,
|
||||||
|
};
|
||||||
|
use objc2_core_video::{kCVReturnSuccess, CVDisplayLink, CVTimeFlags};
|
||||||
|
use objc2_foundation::{ns_string, NSNumber, NSPoint, NSRect};
|
||||||
|
use tracing::warn;
|
||||||
|
use winit_core::monitor::{MonitorHandleProvider, VideoMode};
|
||||||
|
|
||||||
|
use super::ffi;
|
||||||
|
use super::util::cgerr;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct VideoModeHandle {
|
||||||
|
pub(crate) mode: VideoMode,
|
||||||
|
pub(crate) monitor: MonitorHandle,
|
||||||
|
pub(crate) native_mode: NativeDisplayMode,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for VideoModeHandle {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.monitor == other.monitor && self.mode == other.mode
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Eq for VideoModeHandle {}
|
||||||
|
|
||||||
|
impl std::hash::Hash for VideoModeHandle {
|
||||||
|
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||||
|
self.monitor.hash(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for VideoModeHandle {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("VideoModeHandle")
|
||||||
|
.field("mode", &self.mode)
|
||||||
|
.field("monitor", &self.monitor)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub struct NativeDisplayMode(pub CFRetained<CGDisplayMode>);
|
||||||
|
|
||||||
|
unsafe impl Send for NativeDisplayMode {}
|
||||||
|
unsafe impl Sync for NativeDisplayMode {}
|
||||||
|
|
||||||
|
impl VideoModeHandle {
|
||||||
|
fn new(
|
||||||
|
monitor: MonitorHandle,
|
||||||
|
native_mode: NativeDisplayMode,
|
||||||
|
refresh_rate_millihertz: Option<NonZeroU32>,
|
||||||
|
) -> Self {
|
||||||
|
unsafe {
|
||||||
|
// The bit-depth is basically always 32 since macOS 10.12.
|
||||||
|
#[allow(deprecated)]
|
||||||
|
let pixel_encoding =
|
||||||
|
CGDisplayMode::pixel_encoding(Some(&native_mode.0)).unwrap().to_string();
|
||||||
|
let bit_depth = if pixel_encoding.eq_ignore_ascii_case(ffi::IO32BitDirectPixels) {
|
||||||
|
NonZeroU16::new(32)
|
||||||
|
} else if pixel_encoding.eq_ignore_ascii_case(ffi::IO16BitDirectPixels) {
|
||||||
|
NonZeroU16::new(16)
|
||||||
|
} else if pixel_encoding.eq_ignore_ascii_case(ffi::kIO30BitDirectPixels) {
|
||||||
|
NonZeroU16::new(30)
|
||||||
|
} else if pixel_encoding.eq_ignore_ascii_case(ffi::kIO64BitDirectPixels) {
|
||||||
|
NonZeroU16::new(64)
|
||||||
|
} else {
|
||||||
|
warn!(?pixel_encoding, "unknown bit depth");
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let mode = VideoMode::new(
|
||||||
|
PhysicalSize::new(
|
||||||
|
CGDisplayMode::pixel_width(Some(&native_mode.0)) as u32,
|
||||||
|
CGDisplayMode::pixel_height(Some(&native_mode.0)) as u32,
|
||||||
|
),
|
||||||
|
bit_depth,
|
||||||
|
refresh_rate_millihertz,
|
||||||
|
);
|
||||||
|
|
||||||
|
VideoModeHandle { mode, monitor: monitor.clone(), native_mode }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `CGDirectDisplayID` is documented as:
|
||||||
|
/// > a framebuffer, a color correction (gamma) table, and possibly an attached monitor.
|
||||||
|
///
|
||||||
|
/// That is, it doesn't actually represent the monitor itself. Instead, we use the UUID of the
|
||||||
|
/// monitor, as retrieved from `CGDisplayCreateUUIDFromDisplayID` (this makes the monitor ID stable,
|
||||||
|
/// even across reboots and video mode changes).
|
||||||
|
///
|
||||||
|
/// NOTE: I'd be perfectly valid to store `[u8; 16]` in here instead, we only store `CFUUID` to
|
||||||
|
/// avoid having to re-create it when we want to fetch the display ID.
|
||||||
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub struct MonitorHandle(CFRetained<CFUUID>);
|
||||||
|
|
||||||
|
impl MonitorHandle {
|
||||||
|
/// Internal comparisons of [`MonitorHandle`]s are done first requesting a UUID for the handle.
|
||||||
|
fn uuid(&self) -> u128 {
|
||||||
|
u128::from_ne_bytes(self.0.uuid_bytes().into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn display_id(&self) -> CGDirectDisplayID {
|
||||||
|
unsafe { ffi::CGDisplayGetDisplayIDFromUUID(&self.0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[track_caller]
|
||||||
|
pub(crate) fn new(display_id: CGDirectDisplayID) -> Option<Self> {
|
||||||
|
// kCGNullDirectDisplay
|
||||||
|
if display_id == 0 {
|
||||||
|
// `CGDisplayCreateUUIDFromDisplayID` checks kCGNullDirectDisplay internally.
|
||||||
|
warn!("constructing monitor from invalid display ID 0; falling back to main monitor");
|
||||||
|
}
|
||||||
|
// SAFETY: Valid to call.
|
||||||
|
let ptr = unsafe { ffi::CGDisplayCreateUUIDFromDisplayID(display_id) };
|
||||||
|
let ptr = NonNull::new(ptr)?;
|
||||||
|
// SAFETY: `CGDisplayCreateUUIDFromDisplayID` is a "create" function, so the pointer has
|
||||||
|
// +1 retain count.
|
||||||
|
let uuid = unsafe { CFRetained::from_raw(ptr) };
|
||||||
|
Some(Self(uuid))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refresh_rate_millihertz(&self) -> Option<NonZeroU32> {
|
||||||
|
let current_display_mode =
|
||||||
|
NativeDisplayMode(unsafe { CGDisplayCopyDisplayMode(self.display_id()) }.unwrap());
|
||||||
|
refresh_rate_millihertz(self.display_id(), ¤t_display_mode)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn video_mode_handles(&self) -> impl Iterator<Item = VideoModeHandle> {
|
||||||
|
let refresh_rate_millihertz = self.refresh_rate_millihertz();
|
||||||
|
let monitor = self.clone();
|
||||||
|
|
||||||
|
let array = unsafe { CGDisplayCopyAllDisplayModes(self.display_id(), None) };
|
||||||
|
let modes = if let Some(array) = array {
|
||||||
|
// SAFETY: `CGDisplayCopyAllDisplayModes` is documented to return an array of
|
||||||
|
// display modes.
|
||||||
|
unsafe { CFRetained::cast_unchecked::<CFArray<CGDisplayMode>>(array) }
|
||||||
|
} else {
|
||||||
|
// Occasionally, certain CalDigit Thunderbolt Hubs report a spurious monitor during
|
||||||
|
// sleep/wake/cycling monitors. It tends to have null or 1 video mode only.
|
||||||
|
// See <https://github.com/bevyengine/bevy/issues/17827>.
|
||||||
|
warn!(monitor = ?self, "failed to get a list of display modes");
|
||||||
|
CFArray::empty()
|
||||||
|
};
|
||||||
|
|
||||||
|
modes.into_iter().map(move |mode| {
|
||||||
|
let cg_refresh_rate_hertz = unsafe { CGDisplayMode::refresh_rate(Some(&mode)) };
|
||||||
|
|
||||||
|
// CGDisplayModeGetRefreshRate returns 0.0 for any display that
|
||||||
|
// isn't a CRT
|
||||||
|
let refresh_rate_millihertz = if cg_refresh_rate_hertz > 0.0 {
|
||||||
|
NonZeroU32::new((cg_refresh_rate_hertz * 1000.0).round() as u32)
|
||||||
|
} else {
|
||||||
|
refresh_rate_millihertz
|
||||||
|
};
|
||||||
|
|
||||||
|
VideoModeHandle::new(monitor.clone(), NativeDisplayMode(mode), refresh_rate_millihertz)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn ns_screen(&self, mtm: MainThreadMarker) -> Option<Retained<NSScreen>> {
|
||||||
|
let uuid = self.uuid();
|
||||||
|
NSScreen::screens(mtm).into_iter().find(|screen| {
|
||||||
|
let other_native_id = get_display_id(screen);
|
||||||
|
if let Some(other) = MonitorHandle::new(other_native_id) {
|
||||||
|
uuid == other.uuid()
|
||||||
|
} else {
|
||||||
|
// Display ID was just fetched from live NSScreen, but can still result in `None`
|
||||||
|
// with certain Thunderbolt docked monitors.
|
||||||
|
warn!(other_native_id, "comparing against screen with invalid display ID");
|
||||||
|
false
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonitorHandleProvider for MonitorHandle {
|
||||||
|
fn id(&self) -> u128 {
|
||||||
|
self.uuid()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn native_id(&self) -> u64 {
|
||||||
|
self.display_id() as _
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Be smarter about this:
|
||||||
|
//
|
||||||
|
// <https://github.com/glfw/glfw/blob/57cbded0760a50b9039ee0cb3f3c14f60145567c/src/cocoa_monitor.m#L44-L126>
|
||||||
|
fn name(&self) -> Option<std::borrow::Cow<'_, str>> {
|
||||||
|
let screen_num = unsafe { CGDisplayModelNumber(self.display_id()) };
|
||||||
|
Some(format!("Monitor #{screen_num}").into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn position(&self) -> Option<PhysicalPosition<i32>> {
|
||||||
|
// This is already in screen coordinates. If we were using `NSScreen`,
|
||||||
|
// then a conversion would've been needed:
|
||||||
|
// flip_window_screen_coordinates(self.ns_screen(mtm)?.frame())
|
||||||
|
let bounds = unsafe { CGDisplayBounds(self.display_id()) };
|
||||||
|
let position = LogicalPosition::new(bounds.origin.x, bounds.origin.y);
|
||||||
|
Some(position.to_physical(self.scale_factor()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scale_factor(&self) -> f64 {
|
||||||
|
run_on_main(|mtm| {
|
||||||
|
match self.ns_screen(mtm) {
|
||||||
|
Some(screen) => screen.backingScaleFactor() as f64,
|
||||||
|
None => 1.0, // default to 1.0 when we can't find the screen
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current_video_mode(&self) -> Option<VideoMode> {
|
||||||
|
let mode =
|
||||||
|
NativeDisplayMode(unsafe { CGDisplayCopyDisplayMode(self.display_id()) }.unwrap());
|
||||||
|
let refresh_rate_millihertz = refresh_rate_millihertz(self.display_id(), &mode);
|
||||||
|
Some(VideoModeHandle::new(self.clone(), mode, refresh_rate_millihertz).mode)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn video_modes(&self) -> Box<dyn Iterator<Item = VideoMode>> {
|
||||||
|
Box::new(self.video_mode_handles().map(|mode| mode.mode))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn available_monitors() -> VecDeque<MonitorHandle> {
|
||||||
|
let mut expected_count = 0;
|
||||||
|
let res = cgerr(unsafe { CGGetActiveDisplayList(0, ptr::null_mut(), &mut expected_count) });
|
||||||
|
if res.is_err() {
|
||||||
|
return VecDeque::with_capacity(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut displays: Vec<CGDirectDisplayID> = vec![0; expected_count as usize];
|
||||||
|
let mut actual_count = 0;
|
||||||
|
let res = cgerr(unsafe {
|
||||||
|
CGGetActiveDisplayList(expected_count, displays.as_mut_ptr(), &mut actual_count)
|
||||||
|
});
|
||||||
|
displays.truncate(actual_count as usize);
|
||||||
|
|
||||||
|
if res.is_err() {
|
||||||
|
return VecDeque::with_capacity(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut monitors = VecDeque::with_capacity(displays.len());
|
||||||
|
for display in displays {
|
||||||
|
// Display ID just fetched from `CGGetActiveDisplayList`, should be fine to unwrap.
|
||||||
|
monitors.push_back(MonitorHandle::new(display).expect("invalid display ID"));
|
||||||
|
}
|
||||||
|
monitors
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn primary_monitor() -> MonitorHandle {
|
||||||
|
// Display ID just fetched from `CGMainDisplayID`, should be fine to unwrap.
|
||||||
|
MonitorHandle::new(unsafe { CGMainDisplayID() }).expect("invalid display ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for MonitorHandle {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("MonitorHandle")
|
||||||
|
.field("name", &self.name())
|
||||||
|
.field("uuid", &self.uuid())
|
||||||
|
.field("display_id", &self.display_id())
|
||||||
|
.field("position", &self.position())
|
||||||
|
.field("scale_factor", &self.scale_factor())
|
||||||
|
.finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn get_display_id(screen: &NSScreen) -> u32 {
|
||||||
|
let key = ns_string!("NSScreenNumber");
|
||||||
|
|
||||||
|
objc2::rc::autoreleasepool(|_| {
|
||||||
|
let device_description = screen.deviceDescription();
|
||||||
|
|
||||||
|
// Retrieve the CGDirectDisplayID associated with this screen
|
||||||
|
//
|
||||||
|
// The value from @"NSScreenNumber" in deviceDescription is guaranteed
|
||||||
|
// to be an NSNumber. See documentation for details:
|
||||||
|
// <https://developer.apple.com/documentation/appkit/nsscreen/1388360-devicedescription?language=objc>
|
||||||
|
let obj = device_description
|
||||||
|
.objectForKey(key)
|
||||||
|
.expect("failed getting screen display id from device description")
|
||||||
|
.downcast::<NSNumber>()
|
||||||
|
.expect("NSScreenNumber must be NSNumber");
|
||||||
|
|
||||||
|
obj.as_u32()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Core graphics screen coordinates are relative to the top-left corner of
|
||||||
|
/// the so-called "main" display, with y increasing downwards - which is
|
||||||
|
/// exactly what we want in Winit.
|
||||||
|
///
|
||||||
|
/// However, `NSWindow` and `NSScreen` changes these coordinates to:
|
||||||
|
/// 1. Be relative to the bottom-left corner of the "main" screen.
|
||||||
|
/// 2. Be relative to the bottom-left corner of the window/screen itself.
|
||||||
|
/// 3. Have y increasing upwards.
|
||||||
|
///
|
||||||
|
/// This conversion happens to be symmetric, so we only need this one function
|
||||||
|
/// to convert between the two coordinate systems.
|
||||||
|
pub(crate) fn flip_window_screen_coordinates(frame: NSRect) -> NSPoint {
|
||||||
|
// It is intentional that we use `CGMainDisplayID` (as opposed to
|
||||||
|
// `NSScreen::mainScreen`), because that's what the screen coordinates
|
||||||
|
// are relative to, no matter which display the window is currently on.
|
||||||
|
let main_screen_height = unsafe { CGDisplayBounds(CGMainDisplayID()) }.size.height;
|
||||||
|
|
||||||
|
let y = main_screen_height - frame.size.height - frame.origin.y;
|
||||||
|
NSPoint::new(frame.origin.x, y)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refresh_rate_millihertz(id: CGDirectDisplayID, mode: &NativeDisplayMode) -> Option<NonZeroU32> {
|
||||||
|
unsafe {
|
||||||
|
let refresh_rate = CGDisplayMode::refresh_rate(Some(&mode.0));
|
||||||
|
if refresh_rate > 0.0 {
|
||||||
|
return NonZeroU32::new((refresh_rate * 1000.0).round() as u32);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut display_link = std::ptr::null_mut();
|
||||||
|
#[allow(deprecated)]
|
||||||
|
if CVDisplayLink::create_with_cg_display(id, NonNull::from(&mut display_link))
|
||||||
|
!= kCVReturnSuccess
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let display_link = CFRetained::from_raw(NonNull::new(display_link).unwrap());
|
||||||
|
#[allow(deprecated)]
|
||||||
|
let time = display_link.nominal_output_video_refresh_period();
|
||||||
|
|
||||||
|
// This value is indefinite if an invalid display link was specified
|
||||||
|
if time.flags & CVTimeFlags::IsIndefinite.0 != 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
(time.timeScale as i64)
|
||||||
|
.checked_div(time.timeValue)
|
||||||
|
.map(|v| (v * 1000) as u32)
|
||||||
|
.and_then(NonZeroU32::new)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn uuid_stable() {
|
||||||
|
let handle_a = MonitorHandle::new(1).unwrap();
|
||||||
|
let handle_b = MonitorHandle::new(1).unwrap();
|
||||||
|
assert_eq!(handle_a, handle_b);
|
||||||
|
assert_eq!(handle_a.display_id(), handle_b.display_id());
|
||||||
|
assert_eq!(handle_a.uuid(), handle_b.uuid());
|
||||||
|
|
||||||
|
let handle_a = primary_monitor();
|
||||||
|
let handle_b = primary_monitor();
|
||||||
|
assert_eq!(handle_a, handle_b);
|
||||||
|
assert_eq!(handle_a.display_id(), handle_b.display_id());
|
||||||
|
assert_eq!(handle_a.uuid(), handle_b.uuid());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Test the MonitorHandle::new fallback.
|
||||||
|
#[test]
|
||||||
|
fn monitorhandle_from_zero() {
|
||||||
|
let handle0 = MonitorHandle::new(0).unwrap();
|
||||||
|
let handle1 = MonitorHandle::new(1).unwrap();
|
||||||
|
assert_eq!(handle0, handle1);
|
||||||
|
assert_eq!(handle0.display_id(), handle1.display_id());
|
||||||
|
assert_eq!(handle0.uuid(), handle1.uuid());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn from_invalid_id() {
|
||||||
|
// Assume there are never this many monitors connected.
|
||||||
|
assert!(MonitorHandle::new(10000).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Test that calling `CGDisplayGetDisplayIDFromUUID` on an invalid UUID returns an invalid
|
||||||
|
/// display ID.
|
||||||
|
#[test]
|
||||||
|
fn invalid_monitor_handle() {
|
||||||
|
// `CGMainDisplayID` must be called to avoid:
|
||||||
|
// ```
|
||||||
|
// Assertion failed: (did_initialize), function CGS_REQUIRE_INIT, file CGInitialization.c, line 44.
|
||||||
|
// ```
|
||||||
|
// See https://github.com/JXA-Cookbook/JXA-Cookbook/issues/27#issuecomment-277517668
|
||||||
|
let _ = unsafe { CGMainDisplayID() };
|
||||||
|
|
||||||
|
let handle = MonitorHandle(CFUUID::new(None).unwrap());
|
||||||
|
assert_eq!(handle.display_id(), 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
31
winit-appkit/src/notification_center.rs
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
// NOTE: This is symlinked to be contained in both the AppKit and UIKit implementations.
|
||||||
|
use std::ptr::NonNull;
|
||||||
|
|
||||||
|
use block2::RcBlock;
|
||||||
|
use objc2::rc::Retained;
|
||||||
|
use objc2::runtime::ProtocolObject;
|
||||||
|
use objc2_foundation::{
|
||||||
|
NSNotification, NSNotificationCenter, NSNotificationName, NSObjectProtocol,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Observe the given notification.
|
||||||
|
///
|
||||||
|
/// This is used in Winit as an alternative to declaring an application delegate, as we want to
|
||||||
|
/// give the user full control over those.
|
||||||
|
pub(crate) fn create_observer(
|
||||||
|
center: &NSNotificationCenter,
|
||||||
|
name: &NSNotificationName,
|
||||||
|
handler: impl Fn(&NSNotification) + 'static,
|
||||||
|
) -> Retained<ProtocolObject<dyn NSObjectProtocol>> {
|
||||||
|
let block = RcBlock::new(move |notification: NonNull<NSNotification>| {
|
||||||
|
handler(unsafe { notification.as_ref() });
|
||||||
|
});
|
||||||
|
unsafe {
|
||||||
|
center.addObserverForName_object_queue_usingBlock(
|
||||||
|
Some(name),
|
||||||
|
None, // No sender filter
|
||||||
|
None, // No queue, run on posting thread (i.e. main thread)
|
||||||
|
&block,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
248
winit-appkit/src/observer.rs
Normal file
@@ -0,0 +1,248 @@
|
|||||||
|
//! Utilities for working with `CFRunLoop`.
|
||||||
|
//!
|
||||||
|
//! See Apple's documentation on Run Loops for details:
|
||||||
|
//! <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html>
|
||||||
|
use std::cell::Cell;
|
||||||
|
use std::ffi::c_void;
|
||||||
|
use std::ptr;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use objc2::MainThreadMarker;
|
||||||
|
use objc2_core_foundation::{
|
||||||
|
kCFRunLoopCommonModes, kCFRunLoopDefaultMode, CFAbsoluteTimeGetCurrent, CFIndex, CFRetained,
|
||||||
|
CFRunLoop, CFRunLoopActivity, CFRunLoopObserver, CFRunLoopObserverCallBack,
|
||||||
|
CFRunLoopObserverContext, CFRunLoopTimer,
|
||||||
|
};
|
||||||
|
use tracing::error;
|
||||||
|
|
||||||
|
use super::app_state::AppState;
|
||||||
|
|
||||||
|
// begin is queued with the highest priority to ensure it is processed before other observers
|
||||||
|
extern "C-unwind" fn control_flow_begin_handler(
|
||||||
|
_: *mut CFRunLoopObserver,
|
||||||
|
activity: CFRunLoopActivity,
|
||||||
|
_info: *mut c_void,
|
||||||
|
) {
|
||||||
|
match activity {
|
||||||
|
CFRunLoopActivity::AfterWaiting => {
|
||||||
|
AppState::get(MainThreadMarker::new().unwrap()).wakeup();
|
||||||
|
},
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// end is queued with the lowest priority to ensure it is processed after other observers
|
||||||
|
// without that, LoopExiting would get sent after AboutToWait
|
||||||
|
extern "C-unwind" fn control_flow_end_handler(
|
||||||
|
_: *mut CFRunLoopObserver,
|
||||||
|
activity: CFRunLoopActivity,
|
||||||
|
_info: *mut c_void,
|
||||||
|
) {
|
||||||
|
match activity {
|
||||||
|
CFRunLoopActivity::BeforeWaiting => {
|
||||||
|
AppState::get(MainThreadMarker::new().unwrap()).cleared();
|
||||||
|
},
|
||||||
|
CFRunLoopActivity::Exit => (), // unimplemented!(), // not expected to ever happen
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct RunLoop(CFRetained<CFRunLoop>);
|
||||||
|
|
||||||
|
impl RunLoop {
|
||||||
|
pub fn main(mtm: MainThreadMarker) -> Self {
|
||||||
|
// SAFETY: We have a MainThreadMarker here, which means we know we're on the main thread, so
|
||||||
|
// scheduling (and scheduling a non-`Send` block) to that thread is allowed.
|
||||||
|
let _ = mtm;
|
||||||
|
RunLoop(CFRunLoop::main().unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn wakeup(&self) {
|
||||||
|
self.0.wake_up();
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn add_observer(
|
||||||
|
&self,
|
||||||
|
flags: CFRunLoopActivity,
|
||||||
|
// The lower the value, the sooner this will run
|
||||||
|
priority: CFIndex,
|
||||||
|
handler: CFRunLoopObserverCallBack,
|
||||||
|
context: *mut CFRunLoopObserverContext,
|
||||||
|
) {
|
||||||
|
let observer =
|
||||||
|
unsafe { CFRunLoopObserver::new(None, flags.0, true, priority, handler, context) }
|
||||||
|
.unwrap();
|
||||||
|
self.0.add_observer(Some(&observer), unsafe { kCFRunLoopCommonModes });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Submit a closure to run on the main thread as the next step in the run loop, before other
|
||||||
|
/// event sources are processed.
|
||||||
|
///
|
||||||
|
/// This is used for running event handlers, as those are not allowed to run re-entrantly.
|
||||||
|
///
|
||||||
|
/// # Implementation
|
||||||
|
///
|
||||||
|
/// This queuing could be implemented in the following several ways with subtle differences in
|
||||||
|
/// timing. This list is sorted in rough order in which they are run:
|
||||||
|
///
|
||||||
|
/// 1. Using `CFRunLoopPerformBlock` or `-[NSRunLoop performBlock:]`.
|
||||||
|
///
|
||||||
|
/// 2. Using `-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]` or wrapping the
|
||||||
|
/// event in `NSEvent` and posting that to `-[NSApplication postEvent:atStart:]` (both
|
||||||
|
/// creates a custom `CFRunLoopSource`, and signals that to wake up the main event loop).
|
||||||
|
///
|
||||||
|
/// a. `atStart = true`.
|
||||||
|
///
|
||||||
|
/// b. `atStart = false`.
|
||||||
|
///
|
||||||
|
/// 3. `dispatch_async` or `dispatch_async_f`. Note that this may appear before 2b, it does not
|
||||||
|
/// respect the ordering that runloop events have.
|
||||||
|
///
|
||||||
|
/// We choose the first one, both for ease-of-implementation, but mostly for consistency, as we
|
||||||
|
/// want the event to be queued in a way that preserves the order the events originally arrived
|
||||||
|
/// in.
|
||||||
|
///
|
||||||
|
/// As an example, let's assume that we receive two events from the user, a mouse click which we
|
||||||
|
/// handled by queuing it, and a window resize which we handled immediately. If we allowed
|
||||||
|
/// AppKit to choose the ordering when queuing the mouse event, it might get put in the back of
|
||||||
|
/// the queue, and the events would appear out of order to the user of Winit. So we must instead
|
||||||
|
/// put the event at the very front of the queue, to be handled as soon as possible after
|
||||||
|
/// handling whatever event it's currently handling.
|
||||||
|
pub fn queue_closure(&self, closure: impl FnOnce() + 'static) {
|
||||||
|
// Convert `FnOnce()` to `Block<dyn Fn()>`.
|
||||||
|
let closure = Cell::new(Some(closure));
|
||||||
|
let block = block2::RcBlock::new(move || {
|
||||||
|
if let Some(closure) = closure.take() {
|
||||||
|
closure()
|
||||||
|
} else {
|
||||||
|
error!("tried to execute queued closure on main thread twice");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// There are a few common modes (`kCFRunLoopCommonModes`) defined by Cocoa:
|
||||||
|
// - `NSDefaultRunLoopMode`, alias of `kCFRunLoopDefaultMode`.
|
||||||
|
// - `NSEventTrackingRunLoopMode`, used when mouse-dragging and live-resizing a window.
|
||||||
|
// - `NSModalPanelRunLoopMode`, used when running a modal inside the Winit event loop.
|
||||||
|
// - `NSConnectionReplyMode`: TODO.
|
||||||
|
//
|
||||||
|
// We only want to run event handlers in the default mode, as we support running a blocking
|
||||||
|
// modal inside a Winit event handler (see [#1779]) which outrules the modal panel mode, and
|
||||||
|
// resizing such panel window enters the event tracking run loop mode, so we can't directly
|
||||||
|
// trigger events inside that mode either.
|
||||||
|
//
|
||||||
|
// Any events that are queued while running a modal or when live-resizing will instead wait,
|
||||||
|
// and be delivered to the application afterwards.
|
||||||
|
//
|
||||||
|
// [#1779]: https://github.com/rust-windowing/winit/issues/1779
|
||||||
|
let mode = unsafe { kCFRunLoopDefaultMode.unwrap() };
|
||||||
|
|
||||||
|
// SAFETY: The runloop is valid, the mode is a `CFStringRef`, and the block is `'static`.
|
||||||
|
unsafe { self.0.perform_block(Some(mode), Some(&block)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn setup_control_flow_observers(mtm: MainThreadMarker) {
|
||||||
|
let run_loop = RunLoop::main(mtm);
|
||||||
|
unsafe {
|
||||||
|
let mut context = CFRunLoopObserverContext {
|
||||||
|
info: ptr::null_mut(),
|
||||||
|
version: 0,
|
||||||
|
retain: None,
|
||||||
|
release: None,
|
||||||
|
copyDescription: None,
|
||||||
|
};
|
||||||
|
run_loop.add_observer(
|
||||||
|
CFRunLoopActivity::AfterWaiting,
|
||||||
|
CFIndex::MIN,
|
||||||
|
Some(control_flow_begin_handler),
|
||||||
|
&mut context as *mut _,
|
||||||
|
);
|
||||||
|
run_loop.add_observer(
|
||||||
|
CFRunLoopActivity::Exit | CFRunLoopActivity::BeforeWaiting,
|
||||||
|
CFIndex::MAX,
|
||||||
|
Some(control_flow_end_handler),
|
||||||
|
&mut context as *mut _,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct EventLoopWaker {
|
||||||
|
timer: CFRetained<CFRunLoopTimer>,
|
||||||
|
|
||||||
|
/// An arbitrary instant in the past, that will trigger an immediate wake
|
||||||
|
/// We save this as the `next_fire_date` for consistency so we can
|
||||||
|
/// easily check if the next_fire_date needs updating.
|
||||||
|
start_instant: Instant,
|
||||||
|
|
||||||
|
/// This is what the `NextFireDate` has been set to.
|
||||||
|
/// `None` corresponds to `waker.stop()` and `start_instant` is used
|
||||||
|
/// for `waker.start()`
|
||||||
|
next_fire_date: Option<Instant>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for EventLoopWaker {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.timer.invalidate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopWaker {
|
||||||
|
pub(crate) fn new() -> Self {
|
||||||
|
extern "C-unwind" fn wakeup_main_loop(_timer: *mut CFRunLoopTimer, _info: *mut c_void) {}
|
||||||
|
unsafe {
|
||||||
|
// Create a timer with a 0.1µs interval (1ns does not work) to mimic polling.
|
||||||
|
// It is initially setup with a first fire time really far into the
|
||||||
|
// future, but that gets changed to fire immediately in did_finish_launching
|
||||||
|
let timer = CFRunLoopTimer::new(
|
||||||
|
None,
|
||||||
|
f64::MAX,
|
||||||
|
0.000_000_1,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
Some(wakeup_main_loop),
|
||||||
|
ptr::null_mut(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
CFRunLoop::main().unwrap().add_timer(Some(&timer), kCFRunLoopCommonModes);
|
||||||
|
Self { timer, start_instant: Instant::now(), next_fire_date: None }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop(&mut self) {
|
||||||
|
if self.next_fire_date.is_some() {
|
||||||
|
self.next_fire_date = None;
|
||||||
|
self.timer.set_next_fire_date(f64::MAX);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start(&mut self) {
|
||||||
|
if self.next_fire_date != Some(self.start_instant) {
|
||||||
|
self.next_fire_date = Some(self.start_instant);
|
||||||
|
self.timer.set_next_fire_date(f64::MIN);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start_at(&mut self, instant: Option<Instant>) {
|
||||||
|
let now = Instant::now();
|
||||||
|
match instant {
|
||||||
|
Some(instant) if now >= instant => {
|
||||||
|
self.start();
|
||||||
|
},
|
||||||
|
Some(instant) => {
|
||||||
|
if self.next_fire_date != Some(instant) {
|
||||||
|
self.next_fire_date = Some(instant);
|
||||||
|
let current = CFAbsoluteTimeGetCurrent();
|
||||||
|
let duration = instant - now;
|
||||||
|
let fsecs = duration.subsec_nanos() as f64 / 1_000_000_000.0
|
||||||
|
+ duration.as_secs() as f64;
|
||||||
|
self.timer.set_next_fire_date(current + fsecs);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None => {
|
||||||
|
self.stop();
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
44
winit-appkit/src/util.rs
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
use objc2_core_graphics::CGError;
|
||||||
|
use tracing::trace;
|
||||||
|
use winit_core::error::OsError;
|
||||||
|
|
||||||
|
macro_rules! os_error {
|
||||||
|
($error:expr) => {{
|
||||||
|
winit_core::error::OsError::new(line!(), file!(), $error)
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! trace_scope {
|
||||||
|
($s:literal) => {
|
||||||
|
let _crate = $crate::util::TraceGuard::new(module_path!(), $s);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct TraceGuard {
|
||||||
|
module_path: &'static str,
|
||||||
|
called_from_fn: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TraceGuard {
|
||||||
|
#[inline]
|
||||||
|
pub(crate) fn new(module_path: &'static str, called_from_fn: &'static str) -> Self {
|
||||||
|
trace!(target = module_path, "Triggered `{}`", called_from_fn);
|
||||||
|
Self { module_path, called_from_fn }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TraceGuard {
|
||||||
|
#[inline]
|
||||||
|
fn drop(&mut self) {
|
||||||
|
trace!(target = self.module_path, "Completed `{}`", self.called_from_fn);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[track_caller]
|
||||||
|
pub(crate) fn cgerr(err: CGError) -> Result<(), OsError> {
|
||||||
|
if err == CGError::Success {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(os_error!(format!("CGError {err:?}")))
|
||||||
|
}
|
||||||
|
}
|
||||||
385
winit-appkit/src/window.rs
Normal file
@@ -0,0 +1,385 @@
|
|||||||
|
#![allow(clippy::unnecessary_cast)]
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use dispatch2::MainThreadBound;
|
||||||
|
use dpi::{Position, Size};
|
||||||
|
use objc2::rc::{autoreleasepool, Retained};
|
||||||
|
use objc2::{define_class, MainThreadMarker, Message};
|
||||||
|
use objc2_app_kit::{NSPanel, NSResponder, NSWindow};
|
||||||
|
use objc2_foundation::NSObject;
|
||||||
|
use winit_core::cursor::Cursor;
|
||||||
|
use winit_core::error::RequestError;
|
||||||
|
use winit_core::icon::Icon;
|
||||||
|
use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle};
|
||||||
|
use winit_core::window::{
|
||||||
|
ImeCapabilities, ImeRequest, ImeRequestError, Theme, UserAttentionType, Window as CoreWindow,
|
||||||
|
WindowAttributes, WindowButtons, WindowId, WindowLevel,
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::event_loop::ActiveEventLoop;
|
||||||
|
use super::window_delegate::WindowDelegate;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(crate) struct Window {
|
||||||
|
window: MainThreadBound<Retained<NSWindow>>,
|
||||||
|
/// The window only keeps a weak reference to this, so we must keep it around here.
|
||||||
|
delegate: MainThreadBound<Retained<WindowDelegate>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Window {
|
||||||
|
pub(crate) fn new(
|
||||||
|
window_target: &ActiveEventLoop,
|
||||||
|
attributes: WindowAttributes,
|
||||||
|
) -> Result<Self, RequestError> {
|
||||||
|
let mtm = window_target.mtm;
|
||||||
|
let delegate =
|
||||||
|
autoreleasepool(|_| WindowDelegate::new(&window_target.app_state, attributes, mtm))?;
|
||||||
|
Ok(Window {
|
||||||
|
window: MainThreadBound::new(delegate.window().retain(), mtm),
|
||||||
|
delegate: MainThreadBound::new(delegate, mtm),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn maybe_wait_on_main<R: Send>(
|
||||||
|
&self,
|
||||||
|
f: impl FnOnce(&WindowDelegate) -> R + Send,
|
||||||
|
) -> R {
|
||||||
|
self.delegate.get_on_main(|delegate| f(delegate))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub(crate) fn raw_window_handle_rwh_06(
|
||||||
|
&self,
|
||||||
|
) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> {
|
||||||
|
if let Some(mtm) = MainThreadMarker::new() {
|
||||||
|
Ok(self.delegate.get(mtm).raw_window_handle_rwh_06())
|
||||||
|
} else {
|
||||||
|
Err(rwh_06::HandleError::Unavailable)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub(crate) fn raw_display_handle_rwh_06(
|
||||||
|
&self,
|
||||||
|
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
|
||||||
|
Ok(rwh_06::RawDisplayHandle::AppKit(rwh_06::AppKitDisplayHandle::new()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Window {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// Restore the video mode.
|
||||||
|
if matches!(self.fullscreen(), Some(Fullscreen::Exclusive(_, _))) {
|
||||||
|
self.set_fullscreen(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.window.get_on_main(|window| autoreleasepool(|_| window.close()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl rwh_06::HasDisplayHandle for Window {
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let raw = self.raw_display_handle_rwh_06()?;
|
||||||
|
unsafe { Ok(rwh_06::DisplayHandle::borrow_raw(raw)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl rwh_06::HasWindowHandle for Window {
|
||||||
|
fn window_handle(&self) -> Result<rwh_06::WindowHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let raw = self.raw_window_handle_rwh_06()?;
|
||||||
|
unsafe { Ok(rwh_06::WindowHandle::borrow_raw(raw)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CoreWindow for Window {
|
||||||
|
fn id(&self) -> winit_core::window::WindowId {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.id())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scale_factor(&self) -> f64 {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.scale_factor())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_redraw(&self) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.request_redraw());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pre_present_notify(&self) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.pre_present_notify());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reset_dead_keys(&self) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.reset_dead_keys());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn surface_position(&self) -> dpi::PhysicalPosition<i32> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.surface_position())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn outer_position(&self) -> Result<dpi::PhysicalPosition<i32>, RequestError> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.outer_position())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_outer_position(&self, position: Position) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_outer_position(position));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn surface_size(&self) -> dpi::PhysicalSize<u32> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.surface_size())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_surface_size(&self, size: Size) -> Option<dpi::PhysicalSize<u32>> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.request_surface_size(size))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn outer_size(&self) -> dpi::PhysicalSize<u32> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.outer_size())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn safe_area(&self) -> dpi::PhysicalInsets<u32> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.safe_area())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_min_surface_size(&self, min_size: Option<Size>) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_min_surface_size(min_size))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_max_surface_size(&self, max_size: Option<Size>) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_max_surface_size(max_size));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn surface_resize_increments(&self) -> Option<dpi::PhysicalSize<u32>> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.surface_resize_increments())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_surface_resize_increments(&self, increments: Option<Size>) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_surface_resize_increments(increments));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_title(&self, title: &str) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_title(title));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_transparent(&self, transparent: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_transparent(transparent));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_blur(&self, blur: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_blur(blur));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_visible(&self, visible: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_visible(visible));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_visible(&self) -> Option<bool> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.is_visible())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_resizable(&self, resizable: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_resizable(resizable))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_resizable(&self) -> bool {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.is_resizable())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_enabled_buttons(&self, buttons: WindowButtons) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_enabled_buttons(buttons))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn enabled_buttons(&self) -> WindowButtons {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.enabled_buttons())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_minimized(&self, minimized: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_minimized(minimized));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_minimized(&self) -> Option<bool> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.is_minimized())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_maximized(&self, maximized: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_maximized(maximized));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_maximized(&self) -> bool {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.is_maximized())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_fullscreen(fullscreen))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fullscreen(&self) -> Option<Fullscreen> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.fullscreen())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_decorations(&self, decorations: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_decorations(decorations));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_decorated(&self) -> bool {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.is_decorated())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_window_level(&self, level: WindowLevel) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_window_level(level));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_window_icon(&self, window_icon: Option<Icon>) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_window_icon(window_icon));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_ime_update(&self, request: ImeRequest) -> Result<(), ImeRequestError> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.request_ime_update(request))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ime_capabilities(&self) -> Option<ImeCapabilities> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.ime_capabilities())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn focus_window(&self) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.focus_window());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_focus(&self) -> bool {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.has_focus())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_user_attention(&self, request_type: Option<UserAttentionType>) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.request_user_attention(request_type));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_theme(&self, theme: Option<Theme>) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_theme(theme));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn theme(&self) -> Option<Theme> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.theme())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_content_protected(&self, protected: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_content_protected(protected));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn title(&self) -> String {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.title())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_cursor(&self, cursor: Cursor) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_cursor(cursor));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_cursor_position(&self, position: Position) -> Result<(), RequestError> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_cursor_position(position))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_cursor_grab(
|
||||||
|
&self,
|
||||||
|
mode: winit_core::window::CursorGrabMode,
|
||||||
|
) -> Result<(), RequestError> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_cursor_grab(mode))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_cursor_visible(&self, visible: bool) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_cursor_visible(visible))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drag_window(&self) -> Result<(), RequestError> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.drag_window())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drag_resize_window(
|
||||||
|
&self,
|
||||||
|
direction: winit_core::window::ResizeDirection,
|
||||||
|
) -> Result<(), RequestError> {
|
||||||
|
Ok(self.maybe_wait_on_main(|delegate| delegate.drag_resize_window(direction))?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show_window_menu(&self, position: Position) {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.show_window_menu(position))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_cursor_hittest(&self, hittest: bool) -> Result<(), RequestError> {
|
||||||
|
self.maybe_wait_on_main(|delegate| delegate.set_cursor_hittest(hittest));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current_monitor(&self) -> Option<CoreMonitorHandle> {
|
||||||
|
self.maybe_wait_on_main(|delegate| {
|
||||||
|
delegate.current_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor)))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn available_monitors(&self) -> Box<dyn Iterator<Item = CoreMonitorHandle>> {
|
||||||
|
self.maybe_wait_on_main(|delegate| {
|
||||||
|
Box::new(
|
||||||
|
delegate
|
||||||
|
.available_monitors()
|
||||||
|
.into_iter()
|
||||||
|
.map(|monitor| CoreMonitorHandle(Arc::new(monitor))),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn primary_monitor(&self) -> Option<CoreMonitorHandle> {
|
||||||
|
self.maybe_wait_on_main(|delegate| {
|
||||||
|
delegate.primary_monitor().map(|monitor| CoreMonitorHandle(Arc::new(monitor)))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rwh_06_display_handle(&self) -> &dyn rwh_06::HasDisplayHandle {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rwh_06_window_handle(&self) -> &dyn rwh_06::HasWindowHandle {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
define_class!(
|
||||||
|
#[unsafe(super(NSWindow, NSResponder, NSObject))]
|
||||||
|
#[name = "WinitWindow"]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct WinitWindow;
|
||||||
|
|
||||||
|
/// This documentation attribute makes rustfmt work for some reason?
|
||||||
|
impl WinitWindow {
|
||||||
|
#[unsafe(method(canBecomeMainWindow))]
|
||||||
|
fn can_become_main_window(&self) -> bool {
|
||||||
|
trace_scope!("canBecomeMainWindow");
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unsafe(method(canBecomeKeyWindow))]
|
||||||
|
fn can_become_key_window(&self) -> bool {
|
||||||
|
trace_scope!("canBecomeKeyWindow");
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
define_class!(
|
||||||
|
#[unsafe(super(NSPanel, NSWindow, NSResponder, NSObject))]
|
||||||
|
#[name = "WinitPanel"]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct WinitPanel;
|
||||||
|
|
||||||
|
/// This documentation attribute makes rustfmt work for some reason?
|
||||||
|
impl WinitPanel {
|
||||||
|
// although NSPanel can become key window
|
||||||
|
// it doesn't if window doesn't have NSWindowStyleMask::Titled
|
||||||
|
#[unsafe(method(canBecomeKeyWindow))]
|
||||||
|
fn can_become_key_window(&self) -> bool {
|
||||||
|
trace_scope!("canBecomeKeyWindow");
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
pub(super) fn window_id(window: &NSWindow) -> WindowId {
|
||||||
|
WindowId::from_raw(window as *const _ as usize)
|
||||||
|
}
|
||||||
42
winit-common/Cargo.toml
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
[package]
|
||||||
|
description = "Winit implementation helpers"
|
||||||
|
documentation = "https://docs.rs/winit-common"
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
name = "winit-common"
|
||||||
|
repository.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
version.workspace = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
# Event Handler
|
||||||
|
event-handler = []
|
||||||
|
|
||||||
|
# XKB
|
||||||
|
wayland = ["dep:memmap2"]
|
||||||
|
x11 = ["xkbcommon-dl?/x11", "dep:x11-dl"]
|
||||||
|
xkb = ["dep:xkbcommon-dl", "dep:smol_str"]
|
||||||
|
|
||||||
|
# CoreFoundation
|
||||||
|
core-foundation = ["dep:objc2", "dep:objc2-core-foundation"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
smol_str = { workspace = true, optional = true }
|
||||||
|
tracing.workspace = true
|
||||||
|
winit-core.workspace = true
|
||||||
|
|
||||||
|
# XKB
|
||||||
|
memmap2 = { workspace = true, optional = true }
|
||||||
|
x11-dl = { workspace = true, optional = true }
|
||||||
|
xkbcommon-dl = { workspace = true, optional = true }
|
||||||
|
|
||||||
|
# CoreFoundation
|
||||||
|
objc2 = { workspace = true, optional = true }
|
||||||
|
objc2-core-foundation = { workspace = true, optional = true, features = [
|
||||||
|
"std",
|
||||||
|
"CFRunLoop",
|
||||||
|
"CFString",
|
||||||
|
] }
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
all-features = true
|
||||||
1
winit-common/LICENSE
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE
|
||||||
1
winit-common/README.md
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../README.md
|
||||||
175
winit-common/src/core_foundation/event_loop_proxy.rs
Normal file
@@ -0,0 +1,175 @@
|
|||||||
|
use std::os::raw::c_void;
|
||||||
|
use std::ptr::NonNull;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::task::{RawWaker, RawWakerVTable, Waker};
|
||||||
|
|
||||||
|
use objc2::MainThreadMarker;
|
||||||
|
use objc2_core_foundation::{
|
||||||
|
kCFRunLoopCommonModes, CFIndex, CFRetained, CFRunLoop, CFRunLoopSource, CFRunLoopSourceContext,
|
||||||
|
Type,
|
||||||
|
};
|
||||||
|
use winit_core::event_loop::EventLoopProxyProvider;
|
||||||
|
|
||||||
|
/// A waker that signals a `CFRunLoopSource` on the main thread.
|
||||||
|
///
|
||||||
|
/// We use this to integrate with the system as cleanly as possible (instead of e.g. keeping an
|
||||||
|
/// atomic around that we check on each iteration of the event loop).
|
||||||
|
///
|
||||||
|
/// See <https://developer.apple.com/documentation/corefoundation/cfrunloopsource?language=objc>.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub struct EventLoopProxy {
|
||||||
|
source: CFRetained<CFRunLoopSource>,
|
||||||
|
/// Cached value of `CFRunLoopGetMain`.
|
||||||
|
main_loop: CFRetained<CFRunLoop>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// FIXME(madsmtm): Mark `CFRunLoopSource` + `CFRunLoop` as `Send` + `Sync`.
|
||||||
|
unsafe impl Send for EventLoopProxy {}
|
||||||
|
unsafe impl Sync for EventLoopProxy {}
|
||||||
|
|
||||||
|
impl EventLoopProxy {
|
||||||
|
/// Create a new proxy, registering it to be performed on the main thread.
|
||||||
|
///
|
||||||
|
/// The provided closure should call `proxy_wake_up` on the application.
|
||||||
|
pub fn new<F: Fn() + 'static>(mtm: MainThreadMarker, signaller: F) -> Self {
|
||||||
|
// We use an `Arc` here to make sure that the reference-counting of the signal container is
|
||||||
|
// atomic (`Retained`/`CFRetained` would be valid alternatives too).
|
||||||
|
let signaller = Arc::new(signaller);
|
||||||
|
|
||||||
|
unsafe extern "C-unwind" fn retain<F>(info: *const c_void) -> *const c_void {
|
||||||
|
// SAFETY: The pointer was passed to `CFRunLoopSourceContext.info` below.
|
||||||
|
unsafe { Arc::increment_strong_count(info.cast::<F>()) };
|
||||||
|
info
|
||||||
|
}
|
||||||
|
unsafe extern "C-unwind" fn release<F>(info: *const c_void) {
|
||||||
|
// SAFETY: The pointer was passed to `CFRunLoopSourceContext.info` below.
|
||||||
|
unsafe { Arc::decrement_strong_count(info.cast::<F>()) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pointer equality / hashing.
|
||||||
|
extern "C-unwind" fn equal(info1: *const c_void, info2: *const c_void) -> u8 {
|
||||||
|
(info1 == info2) as u8
|
||||||
|
}
|
||||||
|
extern "C-unwind" fn hash(info: *const c_void) -> usize {
|
||||||
|
info as usize
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call the provided closure.
|
||||||
|
unsafe extern "C-unwind" fn perform<F: Fn()>(info: *mut c_void) {
|
||||||
|
// SAFETY: The pointer was passed to `CFRunLoopSourceContext.info` below.
|
||||||
|
let signaller = unsafe { &*info.cast::<F>() };
|
||||||
|
(signaller)();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fire last.
|
||||||
|
let order = CFIndex::MAX - 1;
|
||||||
|
|
||||||
|
// This is marked `mut` to match the signature of `CFRunLoopSourceCreate`, but the
|
||||||
|
// information is copied, and not actually mutated.
|
||||||
|
let mut context = CFRunLoopSourceContext {
|
||||||
|
version: 0,
|
||||||
|
// This is retained on creation.
|
||||||
|
info: Arc::as_ptr(&signaller) as *mut c_void,
|
||||||
|
retain: Some(retain::<F>),
|
||||||
|
release: Some(release::<F>),
|
||||||
|
copyDescription: None,
|
||||||
|
equal: Some(equal),
|
||||||
|
hash: Some(hash),
|
||||||
|
schedule: None,
|
||||||
|
cancel: None,
|
||||||
|
perform: Some(perform::<F>),
|
||||||
|
};
|
||||||
|
|
||||||
|
// SAFETY: The normal callbacks are thread-safe (`retain`/`release` use atomics, and
|
||||||
|
// `equal`/`hash` only access a pointer).
|
||||||
|
//
|
||||||
|
// Note that the `perform` callback isn't thread-safe (we don't have `F: Send + Sync`), but
|
||||||
|
// that's okay, since we are on the main thread, and the source is only added to the main
|
||||||
|
// run loop (below), and hence only performed there.
|
||||||
|
//
|
||||||
|
// Keeping the closure alive beyond this scope is fine, because `F: 'static`.
|
||||||
|
let source = unsafe {
|
||||||
|
let _ = mtm;
|
||||||
|
CFRunLoopSource::new(None, order, &mut context).unwrap()
|
||||||
|
};
|
||||||
|
|
||||||
|
// Register the source to be performed on the main thread.
|
||||||
|
let main_loop = CFRunLoop::main().unwrap();
|
||||||
|
unsafe { main_loop.add_source(Some(&source), kCFRunLoopCommonModes) };
|
||||||
|
|
||||||
|
Self { source, main_loop }
|
||||||
|
}
|
||||||
|
|
||||||
|
// FIXME(madsmtm): Use this on macOS too.
|
||||||
|
// More difficult there, since the user can re-start the event loop.
|
||||||
|
pub fn invalidate(&self) {
|
||||||
|
// NOTE: We do NOT fire this on `Drop`, since we want the proxy to be cloneable, such that
|
||||||
|
// we only need to register a single source even if there's multiple proxies in use.
|
||||||
|
self.source.invalidate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopProxyProvider for EventLoopProxy {
|
||||||
|
fn wake_up(&self) {
|
||||||
|
// Signal the source, which ends up later invoking `perform` on the main thread.
|
||||||
|
//
|
||||||
|
// Multiple signals in quick succession are automatically coalesced into a single signal.
|
||||||
|
self.source.signal();
|
||||||
|
|
||||||
|
// Let the main thread know there's a new event.
|
||||||
|
//
|
||||||
|
// This is required since we may be (probably are) running on a different thread, and the
|
||||||
|
// main loop may be sleeping (and `CFRunLoopSourceSignal` won't wake it).
|
||||||
|
self.main_loop.wake_up();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn waker(&self) -> Waker {
|
||||||
|
const VTABLE: RawWakerVTable =
|
||||||
|
RawWakerVTable::new(clone_waker, wake, wake_by_ref, drop_waker);
|
||||||
|
|
||||||
|
unsafe fn clone_waker(data: *const ()) -> RawWaker {
|
||||||
|
// SAFETY: The poiner came from `CFRunLoopSource` and is valid and non-null.
|
||||||
|
let source = unsafe { &*data.cast::<CFRunLoopSource>() };
|
||||||
|
|
||||||
|
// Increment reference count.
|
||||||
|
let source = source.retain();
|
||||||
|
|
||||||
|
// Pass ownership to the raw waker.
|
||||||
|
let data: *const CFRunLoopSource = CFRetained::into_raw(source).as_ptr();
|
||||||
|
RawWaker::new(data.cast(), &VTABLE)
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn wake(data: *const ()) {
|
||||||
|
unsafe { wake_by_ref(data) };
|
||||||
|
unsafe { drop_waker(data) };
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn wake_by_ref(data: *const ()) {
|
||||||
|
// SAFETY: The poiner came from `CFRunLoopSource` and is valid and non-null.
|
||||||
|
let source = unsafe { &*data.cast::<CFRunLoopSource>() };
|
||||||
|
|
||||||
|
// Signal the source, which ends up later invoking `perform` on the main thread.
|
||||||
|
//
|
||||||
|
// Multiple signals in quick succession are automatically coalesced into a single
|
||||||
|
// signal.
|
||||||
|
source.signal();
|
||||||
|
|
||||||
|
let main_loop = CFRunLoop::main().unwrap();
|
||||||
|
// Let the main thread know there's a new event.
|
||||||
|
//
|
||||||
|
// This is required since we may be (probably are) running on a different thread, and
|
||||||
|
// the main loop may be sleeping (and `CFRunLoopSourceSignal` won't wake it).
|
||||||
|
main_loop.wake_up();
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn drop_waker(data: *const ()) {
|
||||||
|
let source = data.cast::<CFRunLoopSource>().cast_mut();
|
||||||
|
// SAFETY: The poiner came from `CFRunLoopSource` and is valid and non-null.
|
||||||
|
// We take ownership of a retain count here.
|
||||||
|
let _source = unsafe { CFRetained::from_raw(NonNull::new_unchecked(source)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
let data: *const CFRunLoopSource = CFRetained::into_raw(self.source.clone()).as_ptr();
|
||||||
|
unsafe { Waker::from_raw(RawWaker::new(data.cast(), &VTABLE)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
3
winit-common/src/core_foundation/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
mod event_loop_proxy;
|
||||||
|
|
||||||
|
pub use event_loop_proxy::*;
|
||||||
155
winit-common/src/event_handler.rs
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
use std::cell::RefCell;
|
||||||
|
use std::{fmt, mem};
|
||||||
|
|
||||||
|
use winit_core::application::ApplicationHandler;
|
||||||
|
|
||||||
|
/// A helper type for storing a reference to `ApplicationHandler`, allowing interior mutable access
|
||||||
|
/// to it within the execution of a closure.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct EventHandler {
|
||||||
|
/// This can be in the following states:
|
||||||
|
/// - Not registered by the event loop, or terminated (None).
|
||||||
|
/// - Present (Some(handler)).
|
||||||
|
/// - Currently executing the handler / in use (RefCell borrowed).
|
||||||
|
inner: RefCell<Option<Box<dyn ApplicationHandler + 'static>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for EventHandler {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
let state = match self.inner.try_borrow().as_deref() {
|
||||||
|
Ok(Some(_)) => "<available>",
|
||||||
|
Ok(None) => "<not set>",
|
||||||
|
Err(_) => "<in use>",
|
||||||
|
};
|
||||||
|
f.debug_struct("EventHandler").field("state", &state).finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventHandler {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self { inner: RefCell::new(None) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the event loop handler for the duration of the given closure.
|
||||||
|
///
|
||||||
|
/// This is similar to using the `scoped-tls` or `scoped-tls-hkt` crates
|
||||||
|
/// to store the handler in a thread local, such that it can be accessed
|
||||||
|
/// from within the closure.
|
||||||
|
pub fn set<'handler, R>(
|
||||||
|
&self,
|
||||||
|
app: Box<dyn ApplicationHandler + 'handler>,
|
||||||
|
closure: impl FnOnce() -> R,
|
||||||
|
) -> R {
|
||||||
|
// SAFETY: We extend the lifetime of the handler here so that we can
|
||||||
|
// store it in `EventHandler`'s `RefCell`.
|
||||||
|
//
|
||||||
|
// This is sound, since we make sure to unset the handler again at the
|
||||||
|
// end of this function, and as such the lifetime isn't actually
|
||||||
|
// extended beyond `'handler`.
|
||||||
|
let handler = unsafe {
|
||||||
|
mem::transmute::<
|
||||||
|
Box<dyn ApplicationHandler + 'handler>,
|
||||||
|
Box<dyn ApplicationHandler + 'static>,
|
||||||
|
>(app)
|
||||||
|
};
|
||||||
|
|
||||||
|
match self.inner.try_borrow_mut().as_deref_mut() {
|
||||||
|
Ok(Some(_)) => {
|
||||||
|
unreachable!("tried to set handler while another was already set");
|
||||||
|
},
|
||||||
|
Ok(data @ None) => {
|
||||||
|
*data = Some(handler);
|
||||||
|
},
|
||||||
|
Err(_) => {
|
||||||
|
unreachable!("tried to set handler that is currently in use");
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ClearOnDrop<'a>(&'a EventHandler);
|
||||||
|
|
||||||
|
impl Drop for ClearOnDrop<'_> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
match self.0.inner.try_borrow_mut().as_deref_mut() {
|
||||||
|
Ok(data @ Some(_)) => {
|
||||||
|
let handler = data.take();
|
||||||
|
// Explicitly `Drop` the application handler.
|
||||||
|
drop(handler);
|
||||||
|
},
|
||||||
|
Ok(None) => {
|
||||||
|
// Allowed, happens if the handler was cleared manually
|
||||||
|
// elsewhere (such as in `applicationWillTerminate:`).
|
||||||
|
},
|
||||||
|
Err(_) => {
|
||||||
|
// Note: This is not expected to ever happen, this
|
||||||
|
// module generally controls the `RefCell`, and
|
||||||
|
// prevents it from ever being borrowed outside of it.
|
||||||
|
//
|
||||||
|
// But if it _does_ happen, it is a serious error, and
|
||||||
|
// we must abort the process, it'd be unsound if we
|
||||||
|
// weren't able to unset the handler.
|
||||||
|
eprintln!("tried to clear handler that is currently in use");
|
||||||
|
std::process::abort();
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let _clear_on_drop = ClearOnDrop(self);
|
||||||
|
|
||||||
|
// Note: The RefCell should not be borrowed while executing the
|
||||||
|
// closure, that'd defeat the whole point.
|
||||||
|
closure()
|
||||||
|
|
||||||
|
// `_clear_on_drop` will be dropped here, or when unwinding, ensuring
|
||||||
|
// soundness.
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn in_use(&self) -> bool {
|
||||||
|
self.inner.try_borrow().is_err()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ready(&self) -> bool {
|
||||||
|
matches!(self.inner.try_borrow().as_deref(), Ok(Some(_)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn handle(&self, callback: impl FnOnce(&mut (dyn ApplicationHandler + '_))) {
|
||||||
|
match self.inner.try_borrow_mut().as_deref_mut() {
|
||||||
|
Ok(Some(ref mut user_app)) => {
|
||||||
|
// It is important that we keep the reference borrowed here,
|
||||||
|
// so that `in_use` can properly detect that the handler is
|
||||||
|
// still in use.
|
||||||
|
//
|
||||||
|
// If the handler unwinds, the `RefMut` will ensure that the
|
||||||
|
// handler is no longer borrowed.
|
||||||
|
callback(&mut **user_app);
|
||||||
|
},
|
||||||
|
Ok(None) => {
|
||||||
|
// `NSApplication`, our app state and this handler are all
|
||||||
|
// global state and so it's not impossible that we could get
|
||||||
|
// an event after the application has exited the `EventLoop`.
|
||||||
|
tracing::error!("tried to run event handler, but no handler was set");
|
||||||
|
},
|
||||||
|
Err(_) => {
|
||||||
|
// Prevent re-entrancy.
|
||||||
|
panic!("tried to handle event while another event is currently being handled");
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn terminate(&self) {
|
||||||
|
match self.inner.try_borrow_mut().as_deref_mut() {
|
||||||
|
Ok(data @ Some(_)) => {
|
||||||
|
let handler = data.take();
|
||||||
|
// Explicitly `Drop` the application handler.
|
||||||
|
drop(handler);
|
||||||
|
},
|
||||||
|
Ok(None) => {
|
||||||
|
// When terminating, we expect the application handler to still be registered.
|
||||||
|
tracing::error!("tried to clear handler, but no handler was set");
|
||||||
|
},
|
||||||
|
Err(_) => {
|
||||||
|
panic!("tried to clear handler while an event is currently being handled");
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
8
winit-common/src/lib.rs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
//! Winit implementation helpers.
|
||||||
|
|
||||||
|
#[cfg(feature = "core-foundation")]
|
||||||
|
pub mod core_foundation;
|
||||||
|
#[cfg(feature = "event-handler")]
|
||||||
|
pub mod event_handler;
|
||||||
|
#[cfg(feature = "xkb")]
|
||||||
|
pub mod xkb;
|
||||||
124
winit-common/src/xkb/compose.rs
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
//! XKB compose handling.
|
||||||
|
|
||||||
|
use std::env;
|
||||||
|
use std::ffi::CString;
|
||||||
|
use std::ops::Deref;
|
||||||
|
use std::os::unix::ffi::OsStringExt;
|
||||||
|
use std::ptr::NonNull;
|
||||||
|
|
||||||
|
use smol_str::SmolStr;
|
||||||
|
use xkbcommon_dl::{
|
||||||
|
xkb_compose_compile_flags, xkb_compose_feed_result, xkb_compose_state, xkb_compose_state_flags,
|
||||||
|
xkb_compose_status, xkb_compose_table, xkb_keysym_t,
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::{XkbContext, XKBCH};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct XkbComposeTable {
|
||||||
|
table: NonNull<xkb_compose_table>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl XkbComposeTable {
|
||||||
|
pub fn new(context: &XkbContext) -> Option<Self> {
|
||||||
|
let locale = env::var_os("LC_ALL")
|
||||||
|
.and_then(|v| if v.is_empty() { None } else { Some(v) })
|
||||||
|
.or_else(|| env::var_os("LC_CTYPE"))
|
||||||
|
.and_then(|v| if v.is_empty() { None } else { Some(v) })
|
||||||
|
.or_else(|| env::var_os("LANG"))
|
||||||
|
.and_then(|v| if v.is_empty() { None } else { Some(v) })
|
||||||
|
.unwrap_or_else(|| "C".into());
|
||||||
|
let locale = CString::new(locale.into_vec()).unwrap();
|
||||||
|
|
||||||
|
let table = unsafe {
|
||||||
|
(XKBCH.xkb_compose_table_new_from_locale)(
|
||||||
|
context.as_ptr(),
|
||||||
|
locale.as_ptr(),
|
||||||
|
xkb_compose_compile_flags::XKB_COMPOSE_COMPILE_NO_FLAGS,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
let table = NonNull::new(table)?;
|
||||||
|
Some(Self { table })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create new state with the given compose table.
|
||||||
|
pub fn new_state(&self) -> Option<XkbComposeState> {
|
||||||
|
let state = unsafe {
|
||||||
|
(XKBCH.xkb_compose_state_new)(
|
||||||
|
self.table.as_ptr(),
|
||||||
|
xkb_compose_state_flags::XKB_COMPOSE_STATE_NO_FLAGS,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
let state = NonNull::new(state)?;
|
||||||
|
Some(XkbComposeState { state })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deref for XkbComposeTable {
|
||||||
|
type Target = NonNull<xkb_compose_table>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.table
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for XkbComposeTable {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
(XKBCH.xkb_compose_table_unref)(self.table.as_ptr());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct XkbComposeState {
|
||||||
|
state: NonNull<xkb_compose_state>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl XkbComposeState {
|
||||||
|
pub fn get_string(&mut self, scratch_buffer: &mut Vec<u8>) -> Option<SmolStr> {
|
||||||
|
super::make_string_with(scratch_buffer, |ptr, len| unsafe {
|
||||||
|
(XKBCH.xkb_compose_state_get_utf8)(self.state.as_ptr(), ptr, len)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn feed(&mut self, keysym: xkb_keysym_t) -> ComposeStatus {
|
||||||
|
let feed_result = unsafe { (XKBCH.xkb_compose_state_feed)(self.state.as_ptr(), keysym) };
|
||||||
|
match feed_result {
|
||||||
|
xkb_compose_feed_result::XKB_COMPOSE_FEED_IGNORED => ComposeStatus::Ignored,
|
||||||
|
xkb_compose_feed_result::XKB_COMPOSE_FEED_ACCEPTED => {
|
||||||
|
ComposeStatus::Accepted(self.status())
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn reset(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
(XKBCH.xkb_compose_state_reset)(self.state.as_ptr());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn status(&mut self) -> xkb_compose_status {
|
||||||
|
unsafe { (XKBCH.xkb_compose_state_get_status)(self.state.as_ptr()) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for XkbComposeState {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
(XKBCH.xkb_compose_state_unref)(self.state.as_ptr());
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug)]
|
||||||
|
pub enum ComposeStatus {
|
||||||
|
Accepted(xkb_compose_status),
|
||||||
|
Ignored,
|
||||||
|
None,
|
||||||
|
}
|
||||||
@@ -1,6 +1,25 @@
|
|||||||
//! Convert XKB keys to Winit keys.
|
//! XKB keymap.
|
||||||
|
|
||||||
use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey};
|
use std::ffi::c_char;
|
||||||
|
use std::ops::Deref;
|
||||||
|
use std::ptr::{self, NonNull};
|
||||||
|
|
||||||
|
use winit_core::keyboard::{
|
||||||
|
Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey,
|
||||||
|
};
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
use x11_dl::xlib_xcb::xcb_connection_t;
|
||||||
|
use xkb::XKB_MOD_INVALID;
|
||||||
|
use xkbcommon_dl::{
|
||||||
|
self as xkb, xkb_keycode_t, xkb_keymap, xkb_keymap_compile_flags, xkb_keysym_t,
|
||||||
|
xkb_layout_index_t, xkb_mod_index_t,
|
||||||
|
};
|
||||||
|
#[cfg(feature = "wayland")]
|
||||||
|
use {memmap2::MmapOptions, std::os::unix::io::OwnedFd};
|
||||||
|
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
use super::XKBXH;
|
||||||
|
use super::{XkbContext, XKBH};
|
||||||
|
|
||||||
/// Map the raw X11-style keycode to the `KeyCode` enum.
|
/// Map the raw X11-style keycode to the `KeyCode` enum.
|
||||||
///
|
///
|
||||||
@@ -18,6 +37,9 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
// are defined by the Linux kernel. If Winit programs end up being run on other Unix-likes,
|
// are defined by the Linux kernel. If Winit programs end up being run on other Unix-likes,
|
||||||
// I can only hope they agree on what the keycodes mean.
|
// I can only hope they agree on what the keycodes mean.
|
||||||
//
|
//
|
||||||
|
// The mapping here is heavily influenced by Firefox' source:
|
||||||
|
// https://searchfox.org/mozilla-central/rev/c597e9c789ad36af84a0370d395be066b7dc94f4/widget/NativeKeyToDOMCodeName.h
|
||||||
|
//
|
||||||
// Some of the keycodes are likely superfluous for our purposes, and some are ones which are
|
// Some of the keycodes are likely superfluous for our purposes, and some are ones which are
|
||||||
// difficult to test the correctness of, or discover the purpose of. Because of this, they've
|
// difficult to test the correctness of, or discover the purpose of. Because of this, they've
|
||||||
// either been commented out here, or not included at all.
|
// either been commented out here, or not included at all.
|
||||||
@@ -146,26 +168,26 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
122 => KeyCode::Lang1,
|
122 => KeyCode::Lang1,
|
||||||
123 => KeyCode::Lang2,
|
123 => KeyCode::Lang2,
|
||||||
124 => KeyCode::IntlYen,
|
124 => KeyCode::IntlYen,
|
||||||
125 => KeyCode::SuperLeft,
|
125 => KeyCode::MetaLeft,
|
||||||
126 => KeyCode::SuperRight,
|
126 => KeyCode::MetaRight,
|
||||||
127 => KeyCode::ContextMenu,
|
127 => KeyCode::ContextMenu,
|
||||||
// 128 => KeyCode::STOP,
|
128 => KeyCode::BrowserStop,
|
||||||
// 129 => KeyCode::AGAIN,
|
129 => KeyCode::Again,
|
||||||
// 130 => KeyCode::PROPS,
|
130 => KeyCode::Props,
|
||||||
// 131 => KeyCode::UNDO,
|
131 => KeyCode::Undo,
|
||||||
// 132 => KeyCode::FRONT,
|
132 => KeyCode::Select, // FRONT
|
||||||
// 133 => KeyCode::COPY,
|
133 => KeyCode::Copy,
|
||||||
// 134 => KeyCode::OPEN,
|
134 => KeyCode::Open,
|
||||||
// 135 => KeyCode::PASTE,
|
135 => KeyCode::Paste,
|
||||||
// 136 => KeyCode::FIND,
|
136 => KeyCode::Find,
|
||||||
// 137 => KeyCode::CUT,
|
137 => KeyCode::Cut,
|
||||||
// 138 => KeyCode::HELP,
|
138 => KeyCode::Help,
|
||||||
// 139 => KeyCode::MENU,
|
// 139 => KeyCode::MENU,
|
||||||
// 140 => KeyCode::CALC,
|
140 => KeyCode::LaunchApp2, // CALC
|
||||||
// 141 => KeyCode::SETUP,
|
// 141 => KeyCode::SETUP,
|
||||||
// 142 => KeyCode::SLEEP,
|
// 142 => KeyCode::SLEEP,
|
||||||
// 143 => KeyCode::WAKEUP,
|
143 => KeyCode::WakeUp,
|
||||||
// 144 => KeyCode::FILE,
|
144 => KeyCode::LaunchApp1, // FILE
|
||||||
// 145 => KeyCode::SENDFILE,
|
// 145 => KeyCode::SENDFILE,
|
||||||
// 146 => KeyCode::DELETEFILE,
|
// 146 => KeyCode::DELETEFILE,
|
||||||
// 147 => KeyCode::XFER,
|
// 147 => KeyCode::XFER,
|
||||||
@@ -176,13 +198,13 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
// 152 => KeyCode::COFFEE,
|
// 152 => KeyCode::COFFEE,
|
||||||
// 153 => KeyCode::ROTATE_DISPLAY,
|
// 153 => KeyCode::ROTATE_DISPLAY,
|
||||||
// 154 => KeyCode::CYCLEWINDOWS,
|
// 154 => KeyCode::CYCLEWINDOWS,
|
||||||
// 155 => KeyCode::MAIL,
|
155 => KeyCode::LaunchMail,
|
||||||
// 156 => KeyCode::BOOKMARKS,
|
156 => KeyCode::BrowserFavorites, // BOOKMARKS
|
||||||
// 157 => KeyCode::COMPUTER,
|
// 157 => KeyCode::COMPUTER,
|
||||||
// 158 => KeyCode::BACK,
|
158 => KeyCode::BrowserBack,
|
||||||
// 159 => KeyCode::FORWARD,
|
159 => KeyCode::BrowserForward,
|
||||||
// 160 => KeyCode::CLOSECD,
|
// 160 => KeyCode::CLOSECD,
|
||||||
// 161 => KeyCode::EJECTCD,
|
161 => KeyCode::Eject, // EJECTCD
|
||||||
// 162 => KeyCode::EJECTCLOSECD,
|
// 162 => KeyCode::EJECTCLOSECD,
|
||||||
163 => KeyCode::MediaTrackNext,
|
163 => KeyCode::MediaTrackNext,
|
||||||
164 => KeyCode::MediaPlayPause,
|
164 => KeyCode::MediaPlayPause,
|
||||||
@@ -192,9 +214,9 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
// 168 => KeyCode::REWIND,
|
// 168 => KeyCode::REWIND,
|
||||||
// 169 => KeyCode::PHONE,
|
// 169 => KeyCode::PHONE,
|
||||||
// 170 => KeyCode::ISO,
|
// 170 => KeyCode::ISO,
|
||||||
// 171 => KeyCode::CONFIG,
|
171 => KeyCode::MediaSelect, // CONFIG
|
||||||
// 172 => KeyCode::HOMEPAGE,
|
172 => KeyCode::BrowserHome,
|
||||||
// 173 => KeyCode::REFRESH,
|
173 => KeyCode::BrowserRefresh,
|
||||||
// 174 => KeyCode::EXIT,
|
// 174 => KeyCode::EXIT,
|
||||||
// 175 => KeyCode::MOVE,
|
// 175 => KeyCode::MOVE,
|
||||||
// 176 => KeyCode::EDIT,
|
// 176 => KeyCode::EDIT,
|
||||||
@@ -233,7 +255,7 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
|||||||
// 214 => KeyCode::QUESTION,
|
// 214 => KeyCode::QUESTION,
|
||||||
// 215 => KeyCode::EMAIL,
|
// 215 => KeyCode::EMAIL,
|
||||||
// 216 => KeyCode::CHAT,
|
// 216 => KeyCode::CHAT,
|
||||||
// 217 => KeyCode::SEARCH,
|
217 => KeyCode::BrowserSearch,
|
||||||
// 218 => KeyCode::CONNECT,
|
// 218 => KeyCode::CONNECT,
|
||||||
// 219 => KeyCode::FINANCE,
|
// 219 => KeyCode::FINANCE,
|
||||||
// 220 => KeyCode::SPORT,
|
// 220 => KeyCode::SPORT,
|
||||||
@@ -278,7 +300,7 @@ pub fn physicalkey_to_scancode(key: PhysicalKey) -> Option<u32> {
|
|||||||
NativeKeyCode::Xkb(raw) => Some(raw),
|
NativeKeyCode::Xkb(raw) => Some(raw),
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
match code {
|
match code {
|
||||||
@@ -399,13 +421,35 @@ pub fn physicalkey_to_scancode(key: PhysicalKey) -> Option<u32> {
|
|||||||
KeyCode::Lang1 => Some(122),
|
KeyCode::Lang1 => Some(122),
|
||||||
KeyCode::Lang2 => Some(123),
|
KeyCode::Lang2 => Some(123),
|
||||||
KeyCode::IntlYen => Some(124),
|
KeyCode::IntlYen => Some(124),
|
||||||
KeyCode::SuperLeft => Some(125),
|
KeyCode::MetaLeft => Some(125),
|
||||||
KeyCode::SuperRight => Some(126),
|
KeyCode::MetaRight => Some(126),
|
||||||
KeyCode::ContextMenu => Some(127),
|
KeyCode::ContextMenu => Some(127),
|
||||||
|
KeyCode::BrowserStop => Some(128),
|
||||||
|
KeyCode::Again => Some(129),
|
||||||
|
KeyCode::Props => Some(130),
|
||||||
|
KeyCode::Undo => Some(131),
|
||||||
|
KeyCode::Select => Some(132),
|
||||||
|
KeyCode::Copy => Some(133),
|
||||||
|
KeyCode::Open => Some(134),
|
||||||
|
KeyCode::Paste => Some(135),
|
||||||
|
KeyCode::Find => Some(136),
|
||||||
|
KeyCode::Cut => Some(137),
|
||||||
|
KeyCode::Help => Some(138),
|
||||||
|
KeyCode::LaunchApp2 => Some(140),
|
||||||
|
KeyCode::WakeUp => Some(143),
|
||||||
|
KeyCode::LaunchApp1 => Some(144),
|
||||||
|
KeyCode::LaunchMail => Some(155),
|
||||||
|
KeyCode::BrowserFavorites => Some(156),
|
||||||
|
KeyCode::BrowserBack => Some(158),
|
||||||
|
KeyCode::BrowserForward => Some(159),
|
||||||
|
KeyCode::Eject => Some(161),
|
||||||
KeyCode::MediaTrackNext => Some(163),
|
KeyCode::MediaTrackNext => Some(163),
|
||||||
KeyCode::MediaPlayPause => Some(164),
|
KeyCode::MediaPlayPause => Some(164),
|
||||||
KeyCode::MediaTrackPrevious => Some(165),
|
KeyCode::MediaTrackPrevious => Some(165),
|
||||||
KeyCode::MediaStop => Some(166),
|
KeyCode::MediaStop => Some(166),
|
||||||
|
KeyCode::MediaSelect => Some(171),
|
||||||
|
KeyCode::BrowserHome => Some(172),
|
||||||
|
KeyCode::BrowserRefresh => Some(173),
|
||||||
KeyCode::F13 => Some(183),
|
KeyCode::F13 => Some(183),
|
||||||
KeyCode::F14 => Some(184),
|
KeyCode::F14 => Some(184),
|
||||||
KeyCode::F15 => Some(185),
|
KeyCode::F15 => Some(185),
|
||||||
@@ -418,6 +462,7 @@ pub fn physicalkey_to_scancode(key: PhysicalKey) -> Option<u32> {
|
|||||||
KeyCode::F22 => Some(192),
|
KeyCode::F22 => Some(192),
|
||||||
KeyCode::F23 => Some(193),
|
KeyCode::F23 => Some(193),
|
||||||
KeyCode::F24 => Some(194),
|
KeyCode::F24 => Some(194),
|
||||||
|
KeyCode::BrowserSearch => Some(217),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -579,16 +624,20 @@ pub fn keysym_to_key(keysym: u32) -> Key {
|
|||||||
keysyms::Control_R => NamedKey::Control,
|
keysyms::Control_R => NamedKey::Control,
|
||||||
keysyms::Caps_Lock => NamedKey::CapsLock,
|
keysyms::Caps_Lock => NamedKey::CapsLock,
|
||||||
// keysyms::Shift_Lock => NamedKey::ShiftLock,
|
// keysyms::Shift_Lock => NamedKey::ShiftLock,
|
||||||
|
|
||||||
// keysyms::Meta_L => NamedKey::Meta,
|
|
||||||
// keysyms::Meta_R => NamedKey::Meta,
|
|
||||||
keysyms::Alt_L => NamedKey::Alt,
|
keysyms::Alt_L => NamedKey::Alt,
|
||||||
keysyms::Alt_R => NamedKey::Alt,
|
keysyms::Alt_R => NamedKey::Alt,
|
||||||
keysyms::Super_L => NamedKey::Super,
|
#[allow(deprecated)]
|
||||||
keysyms::Super_R => NamedKey::Super,
|
|
||||||
keysyms::Hyper_L => NamedKey::Hyper,
|
keysyms::Hyper_L => NamedKey::Hyper,
|
||||||
|
#[allow(deprecated)]
|
||||||
keysyms::Hyper_R => NamedKey::Hyper,
|
keysyms::Hyper_R => NamedKey::Hyper,
|
||||||
|
|
||||||
|
// Browsers map X11's Super keys to Meta, so we do that as well.
|
||||||
|
keysyms::Super_L => NamedKey::Meta,
|
||||||
|
keysyms::Super_R => NamedKey::Meta,
|
||||||
|
// The actual Meta keys do not seem to be used by browsers, so we don't do that either.
|
||||||
|
// keysyms::Meta_L => NamedKey::Super,
|
||||||
|
// keysyms::Meta_R => NamedKey::Super,
|
||||||
|
|
||||||
// XKB function and modifier keys
|
// XKB function and modifier keys
|
||||||
// keysyms::ISO_Lock => NamedKey::IsoLock,
|
// keysyms::ISO_Lock => NamedKey::IsoLock,
|
||||||
// keysyms::ISO_Level2_Latch => NamedKey::IsoLevel2Latch,
|
// keysyms::ISO_Level2_Latch => NamedKey::IsoLevel2Latch,
|
||||||
@@ -609,7 +658,6 @@ pub fn keysym_to_key(keysym: u32) -> Key {
|
|||||||
// keysyms::ISO_First_Group_Lock => NamedKey::GroupFirstLock,
|
// keysyms::ISO_First_Group_Lock => NamedKey::GroupFirstLock,
|
||||||
keysyms::ISO_Last_Group => NamedKey::GroupLast,
|
keysyms::ISO_Last_Group => NamedKey::GroupLast,
|
||||||
// keysyms::ISO_Last_Group_Lock => NamedKey::GroupLastLock,
|
// keysyms::ISO_Last_Group_Lock => NamedKey::GroupLastLock,
|
||||||
//
|
|
||||||
keysyms::ISO_Left_Tab => NamedKey::Tab,
|
keysyms::ISO_Left_Tab => NamedKey::Tab,
|
||||||
// keysyms::ISO_Move_Line_Up => NamedKey::IsoMoveLineUp,
|
// keysyms::ISO_Move_Line_Up => NamedKey::IsoMoveLineUp,
|
||||||
// keysyms::ISO_Move_Line_Down => NamedKey::IsoMoveLineDown,
|
// keysyms::ISO_Move_Line_Down => NamedKey::IsoMoveLineDown,
|
||||||
@@ -622,7 +670,7 @@ pub fn keysym_to_key(keysym: u32) -> Key {
|
|||||||
// keysyms::ISO_Release_Margin_Left => NamedKey::IsoReleaseMarginLeft,
|
// keysyms::ISO_Release_Margin_Left => NamedKey::IsoReleaseMarginLeft,
|
||||||
// keysyms::ISO_Release_Margin_Right => NamedKey::IsoReleaseMarginRight,
|
// keysyms::ISO_Release_Margin_Right => NamedKey::IsoReleaseMarginRight,
|
||||||
// keysyms::ISO_Release_Both_Margins => NamedKey::IsoReleaseBothMargins,
|
// keysyms::ISO_Release_Both_Margins => NamedKey::IsoReleaseBothMargins,
|
||||||
// keysyms::ISO_Fast_Cursor_Left => NamedKey::IsoFastCursorLeft,
|
// keysyms::ISO_Fast_Cursor_Left => NamedKey::IsoFastPointerLeft,
|
||||||
// keysyms::ISO_Fast_Cursor_Right => NamedKey::IsoFastCursorRight,
|
// keysyms::ISO_Fast_Cursor_Right => NamedKey::IsoFastCursorRight,
|
||||||
// keysyms::ISO_Fast_Cursor_Up => NamedKey::IsoFastCursorUp,
|
// keysyms::ISO_Fast_Cursor_Up => NamedKey::IsoFastCursorUp,
|
||||||
// keysyms::ISO_Fast_Cursor_Down => NamedKey::IsoFastCursorDown,
|
// keysyms::ISO_Fast_Cursor_Down => NamedKey::IsoFastCursorDown,
|
||||||
@@ -682,7 +730,7 @@ pub fn keysym_to_key(keysym: u32) -> Key {
|
|||||||
keysyms::_3270_PrintScreen => NamedKey::PrintScreen,
|
keysyms::_3270_PrintScreen => NamedKey::PrintScreen,
|
||||||
keysyms::_3270_Enter => NamedKey::Enter,
|
keysyms::_3270_Enter => NamedKey::Enter,
|
||||||
|
|
||||||
keysyms::space => NamedKey::Space,
|
keysyms::space => return Key::Character(" ".into()),
|
||||||
// exclam..Sinh_kunddaliya
|
// exclam..Sinh_kunddaliya
|
||||||
|
|
||||||
// XFree86
|
// XFree86
|
||||||
@@ -791,18 +839,15 @@ pub fn keysym_to_key(keysym: u32) -> Key {
|
|||||||
keysyms::XF86_Music => NamedKey::LaunchMusicPlayer,
|
keysyms::XF86_Music => NamedKey::LaunchMusicPlayer,
|
||||||
|
|
||||||
// XF86_Battery..XF86_UWB
|
// XF86_Battery..XF86_UWB
|
||||||
//
|
|
||||||
keysyms::XF86_AudioForward => NamedKey::MediaFastForward,
|
keysyms::XF86_AudioForward => NamedKey::MediaFastForward,
|
||||||
// XF86_AudioRepeat
|
// XF86_AudioRepeat
|
||||||
keysyms::XF86_AudioRandomPlay => NamedKey::RandomToggle,
|
keysyms::XF86_AudioRandomPlay => NamedKey::RandomToggle,
|
||||||
keysyms::XF86_Subtitle => NamedKey::Subtitle,
|
keysyms::XF86_Subtitle => NamedKey::Subtitle,
|
||||||
keysyms::XF86_AudioCycleTrack => NamedKey::MediaAudioTrack,
|
keysyms::XF86_AudioCycleTrack => NamedKey::MediaAudioTrack,
|
||||||
// XF86_CycleAngle..XF86_Blue
|
// XF86_CycleAngle..XF86_Blue
|
||||||
//
|
|
||||||
keysyms::XF86_Suspend => NamedKey::Standby,
|
keysyms::XF86_Suspend => NamedKey::Standby,
|
||||||
keysyms::XF86_Hibernate => NamedKey::Hibernate,
|
keysyms::XF86_Hibernate => NamedKey::Hibernate,
|
||||||
// XF86_TouchpadToggle..XF86_TouchpadOff
|
// XF86_TouchpadToggle..XF86_TouchpadOff
|
||||||
//
|
|
||||||
keysyms::XF86_AudioMute => NamedKey::AudioVolumeMute,
|
keysyms::XF86_AudioMute => NamedKey::AudioVolumeMute,
|
||||||
|
|
||||||
// XF86_Switch_VT_1..XF86_Switch_VT_12
|
// XF86_Switch_VT_1..XF86_Switch_VT_12
|
||||||
@@ -835,7 +880,6 @@ pub fn keysym_to_key(keysym: u32) -> Key {
|
|||||||
keysyms::SUN_VideoLowerBrightness => NamedKey::BrightnessDown,
|
keysyms::SUN_VideoLowerBrightness => NamedKey::BrightnessDown,
|
||||||
keysyms::SUN_VideoRaiseBrightness => NamedKey::BrightnessUp,
|
keysyms::SUN_VideoRaiseBrightness => NamedKey::BrightnessUp,
|
||||||
// SunPowerSwitchShift
|
// SunPowerSwitchShift
|
||||||
//
|
|
||||||
0 => return Key::Unidentified(NativeKey::Unidentified),
|
0 => return Key::Unidentified(NativeKey::Unidentified),
|
||||||
_ => return Key::Unidentified(NativeKey::Xkb(keysym)),
|
_ => return Key::Unidentified(NativeKey::Xkb(keysym)),
|
||||||
})
|
})
|
||||||
@@ -894,3 +938,138 @@ pub fn keysym_location(keysym: u32) -> KeyLocation {
|
|||||||
_ => KeyLocation::Standard,
|
_ => KeyLocation::Standard,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct XkbKeymap {
|
||||||
|
keymap: NonNull<xkb_keymap>,
|
||||||
|
_mods_indices: ModsIndices,
|
||||||
|
pub _core_keyboard_id: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl XkbKeymap {
|
||||||
|
#[cfg(feature = "wayland")]
|
||||||
|
pub fn from_fd(context: &XkbContext, fd: OwnedFd, size: usize) -> Option<Self> {
|
||||||
|
let map = unsafe { MmapOptions::new().len(size).map_copy_read_only(&fd).ok()? };
|
||||||
|
|
||||||
|
let keymap = unsafe {
|
||||||
|
let keymap = (XKBH.xkb_keymap_new_from_string)(
|
||||||
|
(*context).as_ptr(),
|
||||||
|
map.as_ptr() as *const _,
|
||||||
|
xkb::xkb_keymap_format::XKB_KEYMAP_FORMAT_TEXT_V1,
|
||||||
|
xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS,
|
||||||
|
);
|
||||||
|
NonNull::new(keymap)?
|
||||||
|
};
|
||||||
|
|
||||||
|
Some(Self::new_inner(keymap, 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
pub fn from_x11_keymap(
|
||||||
|
context: &XkbContext,
|
||||||
|
xcb: *mut xcb_connection_t,
|
||||||
|
core_keyboard_id: i32,
|
||||||
|
) -> Option<Self> {
|
||||||
|
let keymap = unsafe {
|
||||||
|
(XKBXH.xkb_x11_keymap_new_from_device)(
|
||||||
|
context.as_ptr(),
|
||||||
|
xcb,
|
||||||
|
core_keyboard_id,
|
||||||
|
xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let keymap = NonNull::new(keymap)?;
|
||||||
|
Some(Self::new_inner(keymap, core_keyboard_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_inner(keymap: NonNull<xkb_keymap>, _core_keyboard_id: i32) -> Self {
|
||||||
|
let mods_indices = ModsIndices {
|
||||||
|
shift: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_SHIFT),
|
||||||
|
caps: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_CAPS),
|
||||||
|
ctrl: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_CTRL),
|
||||||
|
alt: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_ALT),
|
||||||
|
num: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_NUM),
|
||||||
|
mod3: mod_index_for_name(keymap, b"Mod3\0"),
|
||||||
|
logo: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_LOGO),
|
||||||
|
mod5: mod_index_for_name(keymap, b"Mod5\0"),
|
||||||
|
};
|
||||||
|
|
||||||
|
Self { keymap, _mods_indices: mods_indices, _core_keyboard_id }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
pub fn mods_indices(&self) -> ModsIndices {
|
||||||
|
self._mods_indices
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn first_keysym_by_level(
|
||||||
|
&mut self,
|
||||||
|
layout: xkb_layout_index_t,
|
||||||
|
keycode: xkb_keycode_t,
|
||||||
|
) -> xkb_keysym_t {
|
||||||
|
unsafe {
|
||||||
|
let mut keysyms = ptr::null();
|
||||||
|
let count = (XKBH.xkb_keymap_key_get_syms_by_level)(
|
||||||
|
self.keymap.as_ptr(),
|
||||||
|
keycode,
|
||||||
|
layout,
|
||||||
|
// NOTE: The level should be zero to ignore modifiers.
|
||||||
|
0,
|
||||||
|
&mut keysyms,
|
||||||
|
);
|
||||||
|
|
||||||
|
if count == 1 {
|
||||||
|
*keysyms
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check whether the given key repeats.
|
||||||
|
pub fn key_repeats(&mut self, keycode: xkb_keycode_t) -> bool {
|
||||||
|
unsafe { (XKBH.xkb_keymap_key_repeats)(self.keymap.as_ptr(), keycode) == 1 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for XkbKeymap {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
(XKBH.xkb_keymap_unref)(self.keymap.as_ptr());
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deref for XkbKeymap {
|
||||||
|
type Target = NonNull<xkb_keymap>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.keymap
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Modifier index in the keymap.
|
||||||
|
#[cfg_attr(not(feature = "x11"), allow(dead_code))]
|
||||||
|
#[derive(Default, Debug, Clone, Copy)]
|
||||||
|
pub struct ModsIndices {
|
||||||
|
pub shift: Option<xkb_mod_index_t>,
|
||||||
|
pub caps: Option<xkb_mod_index_t>,
|
||||||
|
pub ctrl: Option<xkb_mod_index_t>,
|
||||||
|
pub alt: Option<xkb_mod_index_t>,
|
||||||
|
pub num: Option<xkb_mod_index_t>,
|
||||||
|
pub mod3: Option<xkb_mod_index_t>,
|
||||||
|
pub logo: Option<xkb_mod_index_t>,
|
||||||
|
pub mod5: Option<xkb_mod_index_t>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mod_index_for_name(keymap: NonNull<xkb_keymap>, name: &[u8]) -> Option<xkb_mod_index_t> {
|
||||||
|
unsafe {
|
||||||
|
let mod_index =
|
||||||
|
(XKBH.xkb_keymap_mod_get_index)(keymap.as_ptr(), name.as_ptr() as *const c_char);
|
||||||
|
if mod_index == XKB_MOD_INVALID {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(mod_index)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
419
winit-common/src/xkb/mod.rs
Normal file
@@ -0,0 +1,419 @@
|
|||||||
|
use std::ops::Deref;
|
||||||
|
use std::os::raw::c_char;
|
||||||
|
#[cfg(feature = "wayland")]
|
||||||
|
use std::os::unix::io::OwnedFd;
|
||||||
|
use std::ptr::{self, NonNull};
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::sync::LazyLock;
|
||||||
|
|
||||||
|
use smol_str::SmolStr;
|
||||||
|
use winit_core::event::{ElementState, KeyEvent};
|
||||||
|
use winit_core::keyboard::{Key, KeyLocation};
|
||||||
|
use xkbcommon_dl::{
|
||||||
|
self as xkb, xkb_compose_status, xkb_context, xkb_context_flags, xkbcommon_compose_handle,
|
||||||
|
xkbcommon_handle, XkbCommon, XkbCommonCompose,
|
||||||
|
};
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
use {x11_dl::xlib_xcb::xcb_connection_t, xkbcommon_dl::x11::xkbcommon_x11_handle};
|
||||||
|
|
||||||
|
mod compose;
|
||||||
|
mod keymap;
|
||||||
|
mod state;
|
||||||
|
|
||||||
|
use compose::{ComposeStatus, XkbComposeState, XkbComposeTable};
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
pub use keymap::raw_keycode_to_physicalkey;
|
||||||
|
use keymap::XkbKeymap;
|
||||||
|
pub use keymap::{physicalkey_to_scancode, scancode_to_physicalkey};
|
||||||
|
pub use state::XkbState;
|
||||||
|
|
||||||
|
// TODO: Wire this up without using a static `AtomicBool`.
|
||||||
|
static RESET_DEAD_KEYS: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
static XKBH: LazyLock<&'static XkbCommon> = LazyLock::new(xkbcommon_handle);
|
||||||
|
static XKBCH: LazyLock<&'static XkbCommonCompose> = LazyLock::new(xkbcommon_compose_handle);
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
static XKBXH: LazyLock<&'static xkb::x11::XkbCommonX11> = LazyLock::new(xkbcommon_x11_handle);
|
||||||
|
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn reset_dead_keys() {
|
||||||
|
RESET_DEAD_KEYS.store(true, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum Error {
|
||||||
|
/// libxkbcommon is not available
|
||||||
|
XKBNotFound,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Context {
|
||||||
|
// NOTE: field order matters.
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
pub core_keyboard_id: i32,
|
||||||
|
state: Option<XkbState>,
|
||||||
|
keymap: Option<XkbKeymap>,
|
||||||
|
compose_state1: Option<XkbComposeState>,
|
||||||
|
compose_state2: Option<XkbComposeState>,
|
||||||
|
_compose_table: Option<XkbComposeTable>,
|
||||||
|
context: XkbContext,
|
||||||
|
scratch_buffer: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Context {
|
||||||
|
pub fn new() -> Result<Self, Error> {
|
||||||
|
if xkb::xkbcommon_option().is_none() {
|
||||||
|
return Err(Error::XKBNotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
let context = XkbContext::new()?;
|
||||||
|
let mut compose_table = XkbComposeTable::new(&context);
|
||||||
|
let mut compose_state1 = compose_table.as_ref().and_then(|table| table.new_state());
|
||||||
|
let mut compose_state2 = compose_table.as_ref().and_then(|table| table.new_state());
|
||||||
|
|
||||||
|
// Disable compose if anything compose related failed to initialize.
|
||||||
|
if compose_table.is_none() || compose_state1.is_none() || compose_state2.is_none() {
|
||||||
|
compose_state2 = None;
|
||||||
|
compose_state1 = None;
|
||||||
|
compose_table = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
state: None,
|
||||||
|
keymap: None,
|
||||||
|
compose_state1,
|
||||||
|
compose_state2,
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
core_keyboard_id: 0,
|
||||||
|
_compose_table: compose_table,
|
||||||
|
context,
|
||||||
|
scratch_buffer: Vec::with_capacity(8),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
pub fn from_x11_xkb(xcb: *mut xcb_connection_t) -> Result<Self, Error> {
|
||||||
|
let result = unsafe {
|
||||||
|
(XKBXH.xkb_x11_setup_xkb_extension)(
|
||||||
|
xcb,
|
||||||
|
1,
|
||||||
|
2,
|
||||||
|
xkbcommon_dl::x11::xkb_x11_setup_xkb_extension_flags::XKB_X11_SETUP_XKB_EXTENSION_NO_FLAGS,
|
||||||
|
ptr::null_mut(),
|
||||||
|
ptr::null_mut(),
|
||||||
|
ptr::null_mut(),
|
||||||
|
ptr::null_mut(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
if result != 1 {
|
||||||
|
return Err(Error::XKBNotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut this = Self::new()?;
|
||||||
|
this.core_keyboard_id = unsafe { (XKBXH.xkb_x11_get_core_keyboard_device_id)(xcb) };
|
||||||
|
this.set_keymap_from_x11(xcb);
|
||||||
|
Ok(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn state_mut(&mut self) -> Option<&mut XkbState> {
|
||||||
|
self.state.as_mut()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn keymap_mut(&mut self) -> Option<&mut XkbKeymap> {
|
||||||
|
self.keymap.as_mut()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "wayland")]
|
||||||
|
pub fn set_keymap_from_fd(&mut self, fd: OwnedFd, size: usize) {
|
||||||
|
let keymap = XkbKeymap::from_fd(&self.context, fd, size);
|
||||||
|
let state = keymap.as_ref().and_then(XkbState::new_wayland);
|
||||||
|
if keymap.is_none() || state.is_none() {
|
||||||
|
tracing::warn!("failed to update xkb keymap");
|
||||||
|
}
|
||||||
|
self.state = state;
|
||||||
|
self.keymap = keymap;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
pub fn set_keymap_from_x11(&mut self, xcb: *mut xcb_connection_t) {
|
||||||
|
let keymap = XkbKeymap::from_x11_keymap(&self.context, xcb, self.core_keyboard_id);
|
||||||
|
let state = keymap.as_ref().and_then(|keymap| XkbState::new_x11(xcb, keymap));
|
||||||
|
if keymap.is_none() || state.is_none() {
|
||||||
|
tracing::warn!("failed to update xkb keymap");
|
||||||
|
}
|
||||||
|
self.state = state;
|
||||||
|
self.keymap = keymap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Key builder context with the user provided xkb state.
|
||||||
|
pub fn key_context(&mut self) -> Option<KeyContext<'_>> {
|
||||||
|
let state = self.state.as_mut()?;
|
||||||
|
let keymap = self.keymap.as_mut()?;
|
||||||
|
let compose_state1 = self.compose_state1.as_mut();
|
||||||
|
let compose_state2 = self.compose_state2.as_mut();
|
||||||
|
let scratch_buffer = &mut self.scratch_buffer;
|
||||||
|
Some(KeyContext { state, keymap, compose_state1, compose_state2, scratch_buffer })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Key builder context with the user provided xkb state.
|
||||||
|
///
|
||||||
|
/// Should be used when the original context must not be altered.
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
pub fn key_context_with_state<'a>(
|
||||||
|
&'a mut self,
|
||||||
|
state: &'a mut XkbState,
|
||||||
|
) -> Option<KeyContext<'a>> {
|
||||||
|
let keymap = self.keymap.as_mut()?;
|
||||||
|
let compose_state1 = self.compose_state1.as_mut();
|
||||||
|
let compose_state2 = self.compose_state2.as_mut();
|
||||||
|
let scratch_buffer = &mut self.scratch_buffer;
|
||||||
|
Some(KeyContext { state, keymap, compose_state1, compose_state2, scratch_buffer })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct KeyContext<'a> {
|
||||||
|
pub state: &'a mut XkbState,
|
||||||
|
pub keymap: &'a mut XkbKeymap,
|
||||||
|
compose_state1: Option<&'a mut XkbComposeState>,
|
||||||
|
compose_state2: Option<&'a mut XkbComposeState>,
|
||||||
|
scratch_buffer: &'a mut Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KeyContext<'_> {
|
||||||
|
pub fn process_key_event(
|
||||||
|
&mut self,
|
||||||
|
keycode: u32,
|
||||||
|
state: ElementState,
|
||||||
|
repeat: bool,
|
||||||
|
) -> KeyEvent {
|
||||||
|
let mut event =
|
||||||
|
KeyEventResults::new(self, keycode, !repeat && state == ElementState::Pressed);
|
||||||
|
let physical_key = keymap::raw_keycode_to_physicalkey(keycode);
|
||||||
|
let (logical_key, location) = event.key();
|
||||||
|
let text = event.text();
|
||||||
|
let (key_without_modifiers, _) = event.key_without_modifiers();
|
||||||
|
let text_with_all_modifiers = event.text_with_all_modifiers();
|
||||||
|
|
||||||
|
KeyEvent {
|
||||||
|
physical_key,
|
||||||
|
logical_key,
|
||||||
|
text,
|
||||||
|
location,
|
||||||
|
state,
|
||||||
|
repeat,
|
||||||
|
text_with_all_modifiers,
|
||||||
|
key_without_modifiers,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keysym_to_utf8_raw(&mut self, keysym: u32) -> Option<SmolStr> {
|
||||||
|
self.scratch_buffer.clear();
|
||||||
|
self.scratch_buffer.reserve(8);
|
||||||
|
loop {
|
||||||
|
let bytes_written = unsafe {
|
||||||
|
(XKBH.xkb_keysym_to_utf8)(
|
||||||
|
keysym,
|
||||||
|
self.scratch_buffer.as_mut_ptr().cast(),
|
||||||
|
self.scratch_buffer.capacity(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
if bytes_written == 0 {
|
||||||
|
return None;
|
||||||
|
} else if bytes_written == -1 {
|
||||||
|
self.scratch_buffer.reserve(8);
|
||||||
|
} else {
|
||||||
|
unsafe { self.scratch_buffer.set_len(bytes_written.try_into().unwrap()) };
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove the null-terminator
|
||||||
|
self.scratch_buffer.pop();
|
||||||
|
byte_slice_to_smol_str(self.scratch_buffer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct KeyEventResults<'a, 'b> {
|
||||||
|
context: &'a mut KeyContext<'b>,
|
||||||
|
keycode: u32,
|
||||||
|
keysym: u32,
|
||||||
|
compose: ComposeStatus,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, 'b> KeyEventResults<'a, 'b> {
|
||||||
|
fn new(context: &'a mut KeyContext<'b>, keycode: u32, compose: bool) -> Self {
|
||||||
|
let keysym = context.state.get_one_sym_raw(keycode);
|
||||||
|
|
||||||
|
let compose = if let Some(state) = context.compose_state1.as_mut().filter(|_| compose) {
|
||||||
|
if RESET_DEAD_KEYS.swap(false, Ordering::SeqCst) {
|
||||||
|
state.reset();
|
||||||
|
context.compose_state2.as_mut().unwrap().reset();
|
||||||
|
}
|
||||||
|
state.feed(keysym)
|
||||||
|
} else {
|
||||||
|
ComposeStatus::None
|
||||||
|
};
|
||||||
|
|
||||||
|
KeyEventResults { context, keycode, keysym, compose }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn key(&mut self) -> (Key, KeyLocation) {
|
||||||
|
let (key, location) = match self.keysym_to_key(self.keysym) {
|
||||||
|
Ok(known) => return known,
|
||||||
|
Err(undefined) => undefined,
|
||||||
|
};
|
||||||
|
|
||||||
|
if let ComposeStatus::Accepted(xkb_compose_status::XKB_COMPOSE_COMPOSING) = self.compose {
|
||||||
|
let compose_state = self.context.compose_state2.as_mut().unwrap();
|
||||||
|
// When pressing a dead key twice, the non-combining variant of that character will
|
||||||
|
// be produced. Since this function only concerns itself with a single keypress, we
|
||||||
|
// simulate this double press here by feeding the keysym to the compose state
|
||||||
|
// twice.
|
||||||
|
|
||||||
|
compose_state.feed(self.keysym);
|
||||||
|
if matches!(compose_state.feed(self.keysym), ComposeStatus::Accepted(_)) {
|
||||||
|
// Extracting only a single `char` here *should* be fine, assuming that no
|
||||||
|
// dead key's non-combining variant ever occupies more than one `char`.
|
||||||
|
let text = compose_state.get_string(self.context.scratch_buffer);
|
||||||
|
let key = Key::Dead(text.and_then(|s| s.chars().next()));
|
||||||
|
(key, location)
|
||||||
|
} else {
|
||||||
|
(key, location)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let key = self
|
||||||
|
.composed_text()
|
||||||
|
.unwrap_or_else(|_| self.context.keysym_to_utf8_raw(self.keysym))
|
||||||
|
.map(Key::Character)
|
||||||
|
.unwrap_or(key);
|
||||||
|
(key, location)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn key_without_modifiers(&mut self) -> (Key, KeyLocation) {
|
||||||
|
// This will become a pointer to an array which libxkbcommon owns, so we don't need to
|
||||||
|
// deallocate it.
|
||||||
|
let layout = self.context.state.layout(self.keycode);
|
||||||
|
let keysym = self.context.keymap.first_keysym_by_level(layout, self.keycode);
|
||||||
|
|
||||||
|
match self.keysym_to_key(keysym) {
|
||||||
|
Ok((key, location)) => (key, location),
|
||||||
|
Err((key, location)) => {
|
||||||
|
let key =
|
||||||
|
self.context.keysym_to_utf8_raw(keysym).map(Key::Character).unwrap_or(key);
|
||||||
|
(key, location)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keysym_to_key(&self, keysym: u32) -> Result<(Key, KeyLocation), (Key, KeyLocation)> {
|
||||||
|
let location = keymap::keysym_location(keysym);
|
||||||
|
let key = keymap::keysym_to_key(keysym);
|
||||||
|
if matches!(key, Key::Unidentified(_)) {
|
||||||
|
Err((key, location))
|
||||||
|
} else {
|
||||||
|
Ok((key, location))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn text(&mut self) -> Option<SmolStr> {
|
||||||
|
self.composed_text().unwrap_or_else(|_| self.context.keysym_to_utf8_raw(self.keysym))
|
||||||
|
}
|
||||||
|
|
||||||
|
// The current behaviour makes it so composing a character overrides attempts to input a
|
||||||
|
// control character with the `Ctrl` key. We can potentially add a configuration option
|
||||||
|
// if someone specifically wants the opposite behaviour.
|
||||||
|
pub fn text_with_all_modifiers(&mut self) -> Option<SmolStr> {
|
||||||
|
match self.composed_text() {
|
||||||
|
Ok(text) => text,
|
||||||
|
Err(_) => self.context.state.get_utf8_raw(self.keycode, self.context.scratch_buffer),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn composed_text(&mut self) -> Result<Option<SmolStr>, ()> {
|
||||||
|
match self.compose {
|
||||||
|
ComposeStatus::Accepted(status) => match status {
|
||||||
|
xkb_compose_status::XKB_COMPOSE_COMPOSED => {
|
||||||
|
let state = self.context.compose_state1.as_mut().unwrap();
|
||||||
|
Ok(state.get_string(self.context.scratch_buffer))
|
||||||
|
},
|
||||||
|
xkb_compose_status::XKB_COMPOSE_COMPOSING
|
||||||
|
| xkb_compose_status::XKB_COMPOSE_CANCELLED => Ok(None),
|
||||||
|
xkb_compose_status::XKB_COMPOSE_NOTHING => Err(()),
|
||||||
|
},
|
||||||
|
_ => Err(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct XkbContext {
|
||||||
|
context: NonNull<xkb_context>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl XkbContext {
|
||||||
|
pub fn new() -> Result<Self, Error> {
|
||||||
|
let context = unsafe { (XKBH.xkb_context_new)(xkb_context_flags::XKB_CONTEXT_NO_FLAGS) };
|
||||||
|
|
||||||
|
let context = match NonNull::new(context) {
|
||||||
|
Some(context) => context,
|
||||||
|
None => return Err(Error::XKBNotFound),
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Self { context })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for XkbContext {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
(XKBH.xkb_context_unref)(self.context.as_ptr());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deref for XkbContext {
|
||||||
|
type Target = NonNull<xkb_context>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.context
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shared logic for constructing a string with `xkb_compose_state_get_utf8` and
|
||||||
|
/// `xkb_state_key_get_utf8`.
|
||||||
|
fn make_string_with<F>(scratch_buffer: &mut Vec<u8>, mut f: F) -> Option<SmolStr>
|
||||||
|
where
|
||||||
|
F: FnMut(*mut c_char, usize) -> i32,
|
||||||
|
{
|
||||||
|
let size = f(ptr::null_mut(), 0);
|
||||||
|
if size == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let size = usize::try_from(size).unwrap();
|
||||||
|
scratch_buffer.clear();
|
||||||
|
// The allocated buffer must include space for the null-terminator.
|
||||||
|
scratch_buffer.reserve(size + 1);
|
||||||
|
unsafe {
|
||||||
|
let written = f(scratch_buffer.as_mut_ptr().cast(), scratch_buffer.capacity());
|
||||||
|
if usize::try_from(written).unwrap() != size {
|
||||||
|
// This will likely never happen.
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
scratch_buffer.set_len(size);
|
||||||
|
};
|
||||||
|
|
||||||
|
byte_slice_to_smol_str(scratch_buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NOTE: This is track_caller so we can have more informative line numbers when logging
|
||||||
|
#[track_caller]
|
||||||
|
fn byte_slice_to_smol_str(bytes: &[u8]) -> Option<SmolStr> {
|
||||||
|
std::str::from_utf8(bytes)
|
||||||
|
.map(SmolStr::new)
|
||||||
|
.map_err(|e| {
|
||||||
|
tracing::warn!("UTF-8 received from libxkbcommon ({:?}) was invalid: {e}", bytes)
|
||||||
|
})
|
||||||
|
.ok()
|
||||||
|
}
|
||||||
190
winit-common/src/xkb/state.rs
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
//! XKB state.
|
||||||
|
|
||||||
|
use std::os::raw::c_char;
|
||||||
|
use std::ptr::NonNull;
|
||||||
|
|
||||||
|
use smol_str::SmolStr;
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
use x11_dl::xlib_xcb::xcb_connection_t;
|
||||||
|
use xkbcommon_dl::{
|
||||||
|
self as xkb, xkb_keycode_t, xkb_keysym_t, xkb_layout_index_t, xkb_state, xkb_state_component,
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::keymap::XkbKeymap;
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
use super::XKBXH;
|
||||||
|
use super::{make_string_with, XKBH};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct XkbState {
|
||||||
|
state: NonNull<xkb_state>,
|
||||||
|
modifiers: ModifiersState,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl XkbState {
|
||||||
|
#[cfg(feature = "wayland")]
|
||||||
|
pub fn new_wayland(keymap: &XkbKeymap) -> Option<Self> {
|
||||||
|
let state = NonNull::new(unsafe { (XKBH.xkb_state_new)(keymap.as_ptr()) })?;
|
||||||
|
Some(Self::new_inner(state))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
pub fn new_x11(xcb: *mut xcb_connection_t, keymap: &XkbKeymap) -> Option<Self> {
|
||||||
|
let state = unsafe {
|
||||||
|
(XKBXH.xkb_x11_state_new_from_device)(keymap.as_ptr(), xcb, keymap._core_keyboard_id)
|
||||||
|
};
|
||||||
|
let state = NonNull::new(state)?;
|
||||||
|
Some(Self::new_inner(state))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_inner(state: NonNull<xkb_state>) -> Self {
|
||||||
|
let modifiers = ModifiersState::default();
|
||||||
|
let mut this = Self { state, modifiers };
|
||||||
|
this.reload_modifiers();
|
||||||
|
this
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_one_sym_raw(&mut self, keycode: xkb_keycode_t) -> xkb_keysym_t {
|
||||||
|
unsafe { (XKBH.xkb_state_key_get_one_sym)(self.state.as_ptr(), keycode) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn layout(&mut self, key: xkb_keycode_t) -> xkb_layout_index_t {
|
||||||
|
unsafe { (XKBH.xkb_state_key_get_layout)(self.state.as_ptr(), key) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
pub fn depressed_modifiers(&mut self) -> xkb::xkb_mod_mask_t {
|
||||||
|
unsafe {
|
||||||
|
(XKBH.xkb_state_serialize_mods)(
|
||||||
|
self.state.as_ptr(),
|
||||||
|
xkb_state_component::XKB_STATE_MODS_DEPRESSED,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
pub fn latched_modifiers(&mut self) -> xkb::xkb_mod_mask_t {
|
||||||
|
unsafe {
|
||||||
|
(XKBH.xkb_state_serialize_mods)(
|
||||||
|
self.state.as_ptr(),
|
||||||
|
xkb_state_component::XKB_STATE_MODS_LATCHED,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "x11")]
|
||||||
|
pub fn locked_modifiers(&mut self) -> xkb::xkb_mod_mask_t {
|
||||||
|
unsafe {
|
||||||
|
(XKBH.xkb_state_serialize_mods)(
|
||||||
|
self.state.as_ptr(),
|
||||||
|
xkb_state_component::XKB_STATE_MODS_LOCKED,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_utf8_raw(
|
||||||
|
&mut self,
|
||||||
|
keycode: xkb_keycode_t,
|
||||||
|
scratch_buffer: &mut Vec<u8>,
|
||||||
|
) -> Option<SmolStr> {
|
||||||
|
make_string_with(scratch_buffer, |ptr, len| unsafe {
|
||||||
|
(XKBH.xkb_state_key_get_utf8)(self.state.as_ptr(), keycode, ptr, len)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn modifiers(&self) -> ModifiersState {
|
||||||
|
self.modifiers
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update_modifiers(
|
||||||
|
&mut self,
|
||||||
|
mods_depressed: u32,
|
||||||
|
mods_latched: u32,
|
||||||
|
mods_locked: u32,
|
||||||
|
depressed_group: u32,
|
||||||
|
latched_group: u32,
|
||||||
|
locked_group: u32,
|
||||||
|
) {
|
||||||
|
let mask = unsafe {
|
||||||
|
(XKBH.xkb_state_update_mask)(
|
||||||
|
self.state.as_ptr(),
|
||||||
|
mods_depressed,
|
||||||
|
mods_latched,
|
||||||
|
mods_locked,
|
||||||
|
depressed_group,
|
||||||
|
latched_group,
|
||||||
|
locked_group,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
if mask.contains(xkb_state_component::XKB_STATE_MODS_EFFECTIVE) {
|
||||||
|
// Effective value of mods have changed, we need to update our state.
|
||||||
|
self.reload_modifiers();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reload the modifiers.
|
||||||
|
fn reload_modifiers(&mut self) {
|
||||||
|
self.modifiers.ctrl = self.mod_name_is_active(xkb::XKB_MOD_NAME_CTRL);
|
||||||
|
self.modifiers.alt = self.mod_name_is_active(xkb::XKB_MOD_NAME_ALT);
|
||||||
|
self.modifiers.shift = self.mod_name_is_active(xkb::XKB_MOD_NAME_SHIFT);
|
||||||
|
self.modifiers.caps_lock = self.mod_name_is_active(xkb::XKB_MOD_NAME_CAPS);
|
||||||
|
self.modifiers.logo = self.mod_name_is_active(xkb::XKB_MOD_NAME_LOGO);
|
||||||
|
self.modifiers.num_lock = self.mod_name_is_active(xkb::XKB_MOD_NAME_NUM);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if the modifier is active within xkb.
|
||||||
|
fn mod_name_is_active(&mut self, name: &[u8]) -> bool {
|
||||||
|
unsafe {
|
||||||
|
(XKBH.xkb_state_mod_name_is_active)(
|
||||||
|
self.state.as_ptr(),
|
||||||
|
name.as_ptr() as *const c_char,
|
||||||
|
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
|
||||||
|
) > 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for XkbState {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
(XKBH.xkb_state_unref)(self.state.as_ptr());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Represents the current logical state of the keyboard modifiers
|
||||||
|
///
|
||||||
|
/// Each field of this struct represents a modifier and is `true` if this modifier is active.
|
||||||
|
///
|
||||||
|
/// For some modifiers, this means that the key is logically pressed, others are toggled (like Caps
|
||||||
|
/// Lock). But physically the key can be in any state (for example, released Shift when
|
||||||
|
/// it's active as a sticky modifier or released Caps Lock when it's toggled on)
|
||||||
|
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub struct ModifiersState {
|
||||||
|
/// The "control" key
|
||||||
|
pub ctrl: bool,
|
||||||
|
/// The "alt" key
|
||||||
|
pub alt: bool,
|
||||||
|
/// The "shift" key
|
||||||
|
pub shift: bool,
|
||||||
|
/// The "Caps lock" key
|
||||||
|
pub caps_lock: bool,
|
||||||
|
/// The "logo" key
|
||||||
|
///
|
||||||
|
/// Also known as the "windows" key on most keyboards
|
||||||
|
pub logo: bool,
|
||||||
|
/// The "Num lock" key
|
||||||
|
pub num_lock: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<ModifiersState> for winit_core::keyboard::ModifiersState {
|
||||||
|
fn from(mods: ModifiersState) -> winit_core::keyboard::ModifiersState {
|
||||||
|
let mut to_mods = winit_core::keyboard::ModifiersState::empty();
|
||||||
|
to_mods.set(winit_core::keyboard::ModifiersState::SHIFT, mods.shift);
|
||||||
|
to_mods.set(winit_core::keyboard::ModifiersState::CONTROL, mods.ctrl);
|
||||||
|
to_mods.set(winit_core::keyboard::ModifiersState::ALT, mods.alt);
|
||||||
|
to_mods.set(winit_core::keyboard::ModifiersState::META, mods.logo);
|
||||||
|
to_mods
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,32 +1,39 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "winit-core"
|
authors = ["The winit contributors", "Kirill Chibisov <contact@kchibisov.com>"]
|
||||||
version = "0.1.0"
|
|
||||||
authors = ["The winit contributors"]
|
|
||||||
description = "Base types for windowing libraries"
|
|
||||||
edition = "2021"
|
|
||||||
keywords = ["windowing"]
|
|
||||||
license = "Apache-2.0"
|
|
||||||
readme = "README.md"
|
|
||||||
repository = "https://github.com/rust-windowing/winit"
|
|
||||||
documentation = "https://docs.rs/winit"
|
|
||||||
categories = ["gui"]
|
categories = ["gui"]
|
||||||
rust-version = "1.70.0"
|
description = "winit core API."
|
||||||
|
documentation = "https://docs.rs/winit-core"
|
||||||
|
edition.workspace = true
|
||||||
|
keywords = ["windowing"]
|
||||||
|
license.workspace = true
|
||||||
|
name = "winit-core"
|
||||||
|
readme = "README.md"
|
||||||
|
repository.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
version.workspace = true
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["std"]
|
serde = [
|
||||||
std = ["alloc"]
|
"dep:serde",
|
||||||
alloc = []
|
"bitflags/serde",
|
||||||
serde = ["dep:serde", "cursor-icon/serde", "smol_str/serde"]
|
"cursor-icon/serde",
|
||||||
|
"dpi/serde",
|
||||||
|
"keyboard-types/serde",
|
||||||
|
"smol_str/serde",
|
||||||
|
]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
bitflags.workspace = true
|
bitflags.workspace = true
|
||||||
cursor-icon.workspace = true
|
cursor-icon.workspace = true
|
||||||
mint = { version = "0.5.6", optional = true }
|
dpi.workspace = true
|
||||||
|
keyboard-types.workspace = true
|
||||||
|
rwh_06.workspace = true
|
||||||
serde = { workspace = true, optional = true }
|
serde = { workspace = true, optional = true }
|
||||||
smol_str.workspace = true
|
smol_str.workspace = true
|
||||||
|
|
||||||
[target.'cfg(target_family = "wasm")'.dependencies]
|
# `wasm32-unknown-unknown` and `wasm32-none`, but not `wasm32-wasi`.
|
||||||
|
[target.'cfg(all(target_family = "wasm", any(target_os = "unknown", target_os = "none")))'.dependencies]
|
||||||
web-time.workspace = true
|
web-time.workspace = true
|
||||||
|
|
||||||
[build-dependencies]
|
[dev-dependencies]
|
||||||
cfg_aliases.workspace = true
|
winit.workspace = true
|
||||||
|
|||||||
1
winit-core/LICENSE
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
# winit-core - Base types for a windowing system
|
|
||||||
|
|
||||||
TODO
|
|
||||||
1
winit-core/README.md
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../README.md
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
use cfg_aliases::cfg_aliases;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
// The script doesn't depend on our code
|
|
||||||
println!("cargo:rerun-if-changed=build.rs");
|
|
||||||
|
|
||||||
// Setup cfg aliases
|
|
||||||
cfg_aliases! {
|
|
||||||
// Systems.
|
|
||||||
android_platform: { target_os = "android" },
|
|
||||||
web_platform: { all(target_family = "wasm", target_os = "unknown") },
|
|
||||||
macos_platform: { target_os = "macos" },
|
|
||||||
ios_platform: { target_os = "ios" },
|
|
||||||
windows_platform: { target_os = "windows" },
|
|
||||||
apple: { any(target_os = "ios", target_os = "macos") },
|
|
||||||
free_unix: { all(unix, not(apple), not(android_platform), not(target_os = "emscripten")) },
|
|
||||||
redox: { target_os = "redox" },
|
|
||||||
|
|
||||||
// Native displays.
|
|
||||||
x11_platform: { all(feature = "x11", free_unix, not(redox)) },
|
|
||||||
wayland_platform: { all(feature = "wayland", free_unix, not(redox)) },
|
|
||||||
orbital_platform: { redox },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
52
winit-core/src/application/macos.rs
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
use crate::application::ApplicationHandler;
|
||||||
|
use crate::event_loop::ActiveEventLoop;
|
||||||
|
use crate::window::WindowId;
|
||||||
|
|
||||||
|
/// Additional events on [`ApplicationHandler`] that are specific to macOS.
|
||||||
|
///
|
||||||
|
/// This can be registered with [`ApplicationHandler::macos_handler`].
|
||||||
|
pub trait ApplicationHandlerExtMacOS: ApplicationHandler {
|
||||||
|
/// The system interpreted a keypress as a standard key binding command.
|
||||||
|
///
|
||||||
|
/// Examples include inserting tabs and newlines, or moving the insertion point, see
|
||||||
|
/// [`NSStandardKeyBindingResponding`] for the full list of key bindings. They are often text
|
||||||
|
/// editing related.
|
||||||
|
///
|
||||||
|
/// This corresponds to the [`doCommandBySelector:`] method on `NSTextInputClient`.
|
||||||
|
///
|
||||||
|
/// The `action` parameter contains the string representation of the selector. Examples include
|
||||||
|
/// `"insertBacktab:"`, `"indent:"` and `"noop:"`.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```ignore
|
||||||
|
/// impl ApplicationHandlerExtMacOS for App {
|
||||||
|
/// fn standard_key_binding(
|
||||||
|
/// &mut self,
|
||||||
|
/// event_loop: &dyn ActiveEventLoop,
|
||||||
|
/// window_id: WindowId,
|
||||||
|
/// action: &str,
|
||||||
|
/// ) {
|
||||||
|
/// match action {
|
||||||
|
/// "moveBackward:" => self.cursor.position -= 1,
|
||||||
|
/// "moveForward:" => self.cursor.position += 1,
|
||||||
|
/// _ => {} // Ignore other actions
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// [`NSStandardKeyBindingResponding`]: https://developer.apple.com/documentation/appkit/nsstandardkeybindingresponding?language=objc
|
||||||
|
/// [`doCommandBySelector:`]: https://developer.apple.com/documentation/appkit/nstextinputclient/1438256-docommandbyselector?language=objc
|
||||||
|
#[doc(alias = "doCommandBySelector:")]
|
||||||
|
fn standard_key_binding(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &dyn ActiveEventLoop,
|
||||||
|
window_id: WindowId,
|
||||||
|
action: &str,
|
||||||
|
) {
|
||||||
|
let _ = event_loop;
|
||||||
|
let _ = window_id;
|
||||||
|
let _ = action;
|
||||||
|
}
|
||||||
|
}
|
||||||