Compare commits
1366 Commits
v0.17.0
...
split-exam
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
926fb051de | ||
|
|
21fecf2cb2 | ||
|
|
c6dfe620ff | ||
|
|
1bef238c2a | ||
|
|
1edf4f1238 | ||
|
|
72482048a0 | ||
|
|
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 | ||
|
|
56035e1f13 | ||
|
|
08fc4099e8 | ||
|
|
4d4d6e5052 | ||
|
|
cf5f4de19e | ||
|
|
21df84b7f4 | ||
|
|
dd13ccda4c | ||
|
|
df8805c0d2 | ||
|
|
db1ca45a17 | ||
|
|
ff731197dc | ||
|
|
f526a47152 | ||
|
|
f204467838 | ||
|
|
6641dfa412 | ||
|
|
c1168b4f58 | ||
|
|
f8b7c4b78f | ||
|
|
3830b492c4 | ||
|
|
8862ce0163 | ||
|
|
569c44a632 | ||
|
|
ef2ec904ce | ||
|
|
98d3391f2d | ||
|
|
d0a1917603 | ||
|
|
b36d8d1e52 | ||
|
|
a5b08fc48c | ||
|
|
0482d9cfce | ||
|
|
10a785019c | ||
|
|
0cc19716f3 | ||
|
|
572d7ee77c | ||
|
|
b0c59c8416 | ||
|
|
d7c7ba1d6c | ||
|
|
aec608f93c | ||
|
|
d1717b6a01 | ||
|
|
6b29253797 | ||
|
|
30775f4982 | ||
|
|
41070d7c67 | ||
|
|
6df972d108 | ||
|
|
73910d20cc | ||
|
|
16d860736b | ||
|
|
2ee44246ae | ||
|
|
14b418a3a7 | ||
|
|
c86b0daf7f | ||
|
|
40b61d2d92 | ||
|
|
22311802b5 | ||
|
|
169cd39f93 | ||
|
|
bdeb2574dc | ||
|
|
4fe38d8067 | ||
|
|
816798bfd1 | ||
|
|
f99c810bec | ||
|
|
d39528aa69 | ||
|
|
787b2d7362 | ||
|
|
37b6243289 | ||
|
|
8ea1da7879 | ||
|
|
b1209bc253 | ||
|
|
021fd23c34 | ||
|
|
dd127463c5 | ||
|
|
ac247cd081 | ||
|
|
ea1bfd254d | ||
|
|
178f5fda05 | ||
|
|
42dbc4748e | ||
|
|
8b3de7cedf | ||
|
|
8b0ffb7e7d | ||
|
|
c55a2c779b | ||
|
|
c5a422eed6 | ||
|
|
1893b0ec42 | ||
|
|
5e106b4dbb | ||
|
|
5a1d3e4656 | ||
|
|
8f6de4ef4b | ||
|
|
ad1843aea6 | ||
|
|
ca1674519a | ||
|
|
f78edc7ef1 | ||
|
|
4f295e0c94 | ||
|
|
658f49b014 | ||
|
|
34e42ff94d | ||
|
|
ba654bb61e | ||
|
|
f5c691467b | ||
|
|
a87cfb62c3 | ||
|
|
25d6a1d46d | ||
|
|
e0fea25b06 | ||
|
|
843d7904d6 | ||
|
|
28a811bbba | ||
|
|
61a873d79a | ||
|
|
be4a660011 | ||
|
|
34dd2cdba9 | ||
|
|
775c8ece70 | ||
|
|
c12c7b82e8 | ||
|
|
8cc5cb9d9b | ||
|
|
9a28bb4b49 | ||
|
|
4f6fd44c6c | ||
|
|
5a43ea8cd6 | ||
|
|
e9a25a4c91 | ||
|
|
674657efb6 | ||
|
|
7d5bee767c | ||
|
|
745cfaab2c | ||
|
|
a8f49dc8ef | ||
|
|
e5310ade08 | ||
|
|
37946e0a3a | ||
|
|
86b737f5e7 | ||
|
|
e37585e5bc | ||
|
|
4aeeb24745 | ||
|
|
8cd3aaa8a2 | ||
|
|
2c15de7cf9 | ||
|
|
0a7ea61834 | ||
|
|
4ee11018c2 | ||
|
|
4f669ebbd2 | ||
|
|
7761b2b16c | ||
|
|
ae41e3265f | ||
|
|
8702a09333 | ||
|
|
8b5c84f404 | ||
|
|
a676d0018b | ||
|
|
04ca85a909 | ||
|
|
cc33212479 | ||
|
|
f2c5127f27 | ||
|
|
af93167237 | ||
|
|
7f6b16a6af | ||
|
|
bf5806a9b2 | ||
|
|
2a9c593e01 | ||
|
|
becdd0dbd2 | ||
|
|
3eea505440 | ||
|
|
b863283c38 | ||
|
|
73718c9f2f | ||
|
|
f735f028a1 | ||
|
|
da947992ac | ||
|
|
e9784127df | ||
|
|
0be2bb0a8c | ||
|
|
075996b1fa | ||
|
|
a7241b3db3 | ||
|
|
17296e9878 | ||
|
|
b3c87caa7c | ||
|
|
81a1d9c396 | ||
|
|
5612626944 | ||
|
|
d3ca685b77 | ||
|
|
7bed5eecfd | ||
|
|
14140607d1 | ||
|
|
eab982c402 | ||
|
|
21701a33de | ||
|
|
c89e6df758 | ||
|
|
e9210555c1 | ||
|
|
0994b5ceb8 | ||
|
|
bcce5134e1 | ||
|
|
d333dd8664 | ||
|
|
52af1b4a77 | ||
|
|
3c9f9da19e | ||
|
|
075dfcea19 | ||
|
|
92b7dcccc1 | ||
|
|
5a3be586f4 | ||
|
|
12dbbf8012 | ||
|
|
53ca5af48f | ||
|
|
c235bd154a | ||
|
|
f4e71a1d9c | ||
|
|
62ed51a138 | ||
|
|
b2a2ec91ae | ||
|
|
d37d1a03b2 | ||
|
|
772b21ce09 | ||
|
|
2edcd09704 | ||
|
|
d35c3bea42 | ||
|
|
89a184ed84 | ||
|
|
36d4907da8 | ||
|
|
98b3508aca | ||
|
|
c0db53a516 | ||
|
|
52b7205b75 | ||
|
|
41dbbc27a0 | ||
|
|
c346fb7e61 | ||
|
|
6a041f84ba | ||
|
|
acfeff5327 | ||
|
|
b9e1e96eaa | ||
|
|
880238a24f | ||
|
|
f5b4d6938f | ||
|
|
c65e2247a1 | ||
|
|
801fddbfcf | ||
|
|
3ad64fb811 | ||
|
|
9bf4493a21 | ||
|
|
48f6582eb4 | ||
|
|
ef34692148 | ||
|
|
c48116a8fd | ||
|
|
b938fe9df5 | ||
|
|
b7e3649e8b | ||
|
|
844269d017 | ||
|
|
e41fac825c | ||
|
|
bbeacc46d5 | ||
|
|
61581ebb4f | ||
|
|
93f1000a05 | ||
|
|
1ea41a2ee2 | ||
|
|
42c9b7e40e | ||
|
|
0960635895 | ||
|
|
789a497980 | ||
|
|
fac6110cb6 | ||
|
|
0363be4776 | ||
|
|
f5dd1c008c | ||
|
|
48a1e84906 | ||
|
|
ee0db52ac4 | ||
|
|
c7cf0cfd83 | ||
|
|
8393d98940 | ||
|
|
af247eac0f | ||
|
|
b2b4564a5f | ||
|
|
cb58c49a90 | ||
|
|
ffb46dd61f | ||
|
|
8c8fb39fcd | ||
|
|
2422ea39d0 | ||
|
|
878d832d24 | ||
|
|
e2e01e1fc6 | ||
|
|
c8b685ddbc | ||
|
|
f10ae52385 | ||
|
|
e731041c15 | ||
|
|
9df7fc47a1 | ||
|
|
992aeb0ca0 | ||
|
|
0caba93b51 | ||
|
|
c00c1e9eb7 | ||
|
|
83950acd5a | ||
|
|
b99403b1b9 | ||
|
|
4f0ce7201d | ||
|
|
e648169861 | ||
|
|
8fdd81ecef | ||
|
|
7a2a2341c2 | ||
|
|
d68d9eab38 | ||
|
|
a06ea45c0f | ||
|
|
67b041e231 | ||
|
|
6dfc78fb50 | ||
|
|
477619c0a7 | ||
|
|
5f1a4b65ad | ||
|
|
bb9b629bc3 | ||
|
|
0c8cf94a70 | ||
|
|
1dfca5a395 | ||
|
|
7541220a41 | ||
|
|
7e11912d22 | ||
|
|
86baa1c99a | ||
|
|
d9f04780cc | ||
|
|
67d3fd28f7 | ||
|
|
a3cba838ea | ||
|
|
48abf52aac | ||
|
|
68ef9f707e | ||
|
|
9979441c82 | ||
|
|
309e6aa85a | ||
|
|
8b8556798e | ||
|
|
2d96480a89 | ||
|
|
6caff77abb | ||
|
|
af6c343d0e | ||
|
|
119462795a | ||
|
|
f801c4a00b | ||
|
|
f9758528f6 | ||
|
|
778d70c001 | ||
|
|
dc973883c9 | ||
|
|
2233edb9a0 | ||
|
|
bd2f1e8312 | ||
|
|
e9ebf1e5f4 | ||
|
|
5f7955cb2b | ||
|
|
793c535b01 | ||
|
|
ed26dd58fd | ||
|
|
584aab4cd0 | ||
|
|
8100a6a584 | ||
|
|
cad3277550 | ||
|
|
3c3a863cc9 | ||
|
|
8a7e18aaf0 | ||
|
|
57fad2ce15 | ||
|
|
7a58fe58ce | ||
|
|
38f28d5836 | ||
|
|
189a0080a6 | ||
|
|
b5aa96bea4 | ||
|
|
19e3906369 | ||
|
|
9ac3259a79 | ||
|
|
2b2dd6b65d | ||
|
|
75173118b0 | ||
|
|
e33d2bee6c | ||
|
|
ae7497e18f | ||
|
|
935146d299 | ||
|
|
755c533b08 | ||
|
|
ae9b02e097 | ||
|
|
e6c7cc297d | ||
|
|
b74cee8df1 | ||
|
|
e5eb253698 | ||
|
|
ec11b4877f | ||
|
|
9e46dffcc5 | ||
|
|
7501039d57 | ||
|
|
289ce32d77 | ||
|
|
0d366ffbda | ||
|
|
a6f414d732 | ||
|
|
c47d0846fa | ||
|
|
461efaf99f | ||
|
|
420840278b | ||
|
|
f5e73b0af4 | ||
|
|
f40b5f0dad | ||
|
|
c91402efb9 | ||
|
|
43acf7f42f | ||
|
|
c62e64060b | ||
|
|
f7a84a5b50 | ||
|
|
89aa7cc06e | ||
|
|
b166e1ff13 | ||
|
|
97434d8d80 | ||
|
|
06fb089633 | ||
|
|
4d6dbea74c | ||
|
|
c5941d105f | ||
|
|
b63164645b | ||
|
|
5b5ebc25d8 | ||
|
|
d7ec899d69 | ||
|
|
5379d60e4d | ||
|
|
44e2f95331 | ||
|
|
3b2d1a7643 | ||
|
|
50b17a3907 | ||
|
|
af26f01b95 | ||
|
|
c4d70d75c1 | ||
|
|
db8de03142 | ||
|
|
ff0ce9d065 | ||
|
|
42e492cde8 | ||
|
|
5e0e1e96bc | ||
|
|
bd890e69aa | ||
|
|
bca57ed0b4 | ||
|
|
4652d48105 | ||
|
|
96c0b267e2 | ||
|
|
81fd39485f | ||
|
|
6178acede8 | ||
|
|
a320702a71 | ||
|
|
b0106898f7 | ||
|
|
924f3323b5 | ||
|
|
b97df599c5 | ||
|
|
0defd747c8 | ||
|
|
e23186db8e | ||
|
|
059abb06fc | ||
|
|
bc216b8f67 | ||
|
|
864a1d5924 | ||
|
|
05444628e6 | ||
|
|
66ff52b012 | ||
|
|
7929999c1c | ||
|
|
7094a223af | ||
|
|
b2a46d0439 | ||
|
|
4748890935 | ||
|
|
6300cf915e | ||
|
|
9a9c9b15ba | ||
|
|
7ce86c3d2a | ||
|
|
a444637b18 | ||
|
|
f0d88c52a3 | ||
|
|
e17977d7c7 | ||
|
|
a7a8ff0bbb | ||
|
|
fc046add78 | ||
|
|
ab4a4a89e6 | ||
|
|
f7a400ddf6 | ||
|
|
07d39abddd | ||
|
|
0c8bf25ae4 | ||
|
|
b5785ba785 | ||
|
|
9797ed86f0 | ||
|
|
e220a75556 | ||
|
|
29d3729ac8 | ||
|
|
4a36741f9c | ||
|
|
ab46aa5b79 | ||
|
|
12fb37d827 | ||
|
|
c88a4ab221 | ||
|
|
8f7f3efc0d | ||
|
|
eb2d3894ef | ||
|
|
3f4f580181 | ||
|
|
d3aeff8838 | ||
|
|
0786d534f4 | ||
|
|
b4b2389d0a | ||
|
|
964e342f69 | ||
|
|
a134a59917 | ||
|
|
fbba203c4a | ||
|
|
61bd8b8254 | ||
|
|
587fa67571 | ||
|
|
7500a88230 | ||
|
|
82d0380ea6 | ||
|
|
642ce2bfa7 | ||
|
|
5bbe87960e | ||
|
|
cf77f82ae3 | ||
|
|
72cf4e577f | ||
|
|
4f3eacf01e | ||
|
|
31ebc5caf4 | ||
|
|
d273518ce9 | ||
|
|
2ade772ab0 | ||
|
|
4ac2006cbc | ||
|
|
ba5ad3be13 | ||
|
|
8092fa2440 | ||
|
|
8bb004a1d9 | ||
|
|
de5327477a | ||
|
|
8f959714cc | ||
|
|
035eebb19a | ||
|
|
b5af6bb266 | ||
|
|
1805124c54 | ||
|
|
0f64589dba | ||
|
|
5438a2a524 | ||
|
|
918430979f | ||
|
|
f3f46cb3f6 | ||
|
|
3c3be71a77 | ||
|
|
a7986b077f | ||
|
|
8a0edde5c8 | ||
|
|
a9e168e10d | ||
|
|
bd9cc2a9da | ||
|
|
596c0edf0f | ||
|
|
92592ec605 | ||
|
|
25c4e2e451 | ||
|
|
ad52c72e41 | ||
|
|
d15feb5cfa | ||
|
|
9938327066 | ||
|
|
f980ed7b83 | ||
|
|
2496098890 | ||
|
|
60e91b187a | ||
|
|
2486f0f1a1 | ||
|
|
fbea75d31f | ||
|
|
d4c9535af9 | ||
|
|
f0fcb346b0 | ||
|
|
77f8e511e9 | ||
|
|
3217eaa416 | ||
|
|
b18295a1ce | ||
|
|
fb9695d56d | ||
|
|
08bdca19b1 | ||
|
|
79ac236721 | ||
|
|
b870a11a99 | ||
|
|
2af1550bbb | ||
|
|
ed796dcd15 | ||
|
|
a006cd7dc8 | ||
|
|
a31f71ee07 | ||
|
|
0f89aac9f6 | ||
|
|
82df9531f4 | ||
|
|
265152355e | ||
|
|
37c0f615cf | ||
|
|
5ba6bdef49 | ||
|
|
69d6076310 | ||
|
|
7029ce6ecd | ||
|
|
1eb1a13a77 | ||
|
|
3fd73848dd | ||
|
|
4e1c46fe9e | ||
|
|
180a4c7a16 | ||
|
|
13613931cf | ||
|
|
483c1d40ae | ||
|
|
1b4045dcb2 | ||
|
|
8f8da0f8bb | ||
|
|
23b821285c | ||
|
|
c984476687 | ||
|
|
42c395e49d | ||
|
|
422c6b1987 | ||
|
|
b457329003 | ||
|
|
930df0ec45 | ||
|
|
e1b7fda409 | ||
|
|
e423802ed3 | ||
|
|
a82f66826b | ||
|
|
0f2fbe373b | ||
|
|
7341ee80ea | ||
|
|
d448d3e14f | ||
|
|
a867032e1e | ||
|
|
b711a11549 | ||
|
|
809162fbd0 | ||
|
|
de782504ab | ||
|
|
1886949efe | ||
|
|
b1a5fae1f5 | ||
|
|
a88d2e079d | ||
|
|
067535eb38 | ||
|
|
7d626d9dfd | ||
|
|
62ce14a013 | ||
|
|
6f60c7a6cc | ||
|
|
6cf0bf76da | ||
|
|
9225b2812e | ||
|
|
08ce3af3e1 | ||
|
|
490abcad14 | ||
|
|
4b22ca8daf | ||
|
|
66ca445caa | ||
|
|
2f52c23fa9 | ||
|
|
ee88e38f13 | ||
|
|
5e77d70245 | ||
|
|
58ec458877 | ||
|
|
94e4c394e7 | ||
|
|
f43ce2a131 | ||
|
|
402cbd55f9 | ||
|
|
da7422c6e1 | ||
|
|
8934d2765d | ||
|
|
89eea64a4a | ||
|
|
9f781bc422 | ||
|
|
4ed4e918f3 | ||
|
|
2e4d79f57a | ||
|
|
bf92f3e97b | ||
|
|
2a58b785fe | ||
|
|
32784af3c4 | ||
|
|
94688a62f0 | ||
|
|
28e34c2e1b | ||
|
|
9ae7498a8a | ||
|
|
1786c877ec | ||
|
|
101ac8908c | ||
|
|
ba4bf03675 | ||
|
|
a63b066ed5 | ||
|
|
f77f858e9b | ||
|
|
6d0cf6a275 | ||
|
|
12df8b6c0c | ||
|
|
65baae75c4 | ||
|
|
418cc44e93 | ||
|
|
ce6c6e8c95 | ||
|
|
bdcbd7d1f9 | ||
|
|
05484c5888 | ||
|
|
50bbc85dc3 | ||
|
|
8669c2e8df | ||
|
|
97d4c7b303 | ||
|
|
08f9e374e0 | ||
|
|
a7a7cc64cd | ||
|
|
04d9e081b8 | ||
|
|
8fc24c959a | ||
|
|
2fb15dbe8a | ||
|
|
92fdf5ba85 | ||
|
|
4f06cfcf5b | ||
|
|
462bb4d324 | ||
|
|
f6ca8515ab | ||
|
|
71094e5703 | ||
|
|
bb0f965c57 | ||
|
|
4d48c76da9 | ||
|
|
fafdedfb7d | ||
|
|
25b129362f | ||
|
|
48b843e42d | ||
|
|
58f2455aa9 | ||
|
|
155f1f9720 | ||
|
|
3b56b0e76f | ||
|
|
5d2aca90bd | ||
|
|
ba49db2cb9 | ||
|
|
a4695c5397 | ||
|
|
92ddb3483e | ||
|
|
fec52b028e | ||
|
|
d8c0ee733b | ||
|
|
fb248eaadc | ||
|
|
da7bf8e29b | ||
|
|
a6a8b12537 | ||
|
|
340f951d10 | ||
|
|
05dd31b8ea | ||
|
|
0fca8b088d | ||
|
|
ab56e9f57d | ||
|
|
97d2aaa953 | ||
|
|
29419d6c38 | ||
|
|
e517e468f8 | ||
|
|
d67c928120 | ||
|
|
112965b4ff | ||
|
|
e0018d0710 | ||
|
|
1ca8b65e85 | ||
|
|
a43a15b4a0 | ||
|
|
66aa6c945d | ||
|
|
dfecdc5762 | ||
|
|
8729119536 | ||
|
|
ec7e935248 | ||
|
|
fd72000a9a | ||
|
|
e91ee811cb | ||
|
|
b3b80166ce | ||
|
|
f9b41fd819 | ||
|
|
0d9c39029c | ||
|
|
da2cef97a3 | ||
|
|
76f158d310 | ||
|
|
2e4338bb8d | ||
|
|
ec2888b8b7 | ||
|
|
fa83bace12 | ||
|
|
ee7dc48e3b | ||
|
|
11d4a301e4 | ||
|
|
ad41eaf151 | ||
|
|
9b71df9f97 | ||
|
|
b1c9e4a6fa | ||
|
|
cdbaf4816a | ||
|
|
6b7ceedc91 | ||
|
|
c53a574bff | ||
|
|
95246d81c1 | ||
|
|
bf537009d9 | ||
|
|
50035643f7 | ||
|
|
64c22f9075 | ||
|
|
4895a29e92 | ||
|
|
6cdb3179c8 | ||
|
|
4fd52af682 | ||
|
|
5a0bad130d | ||
|
|
08d025968e | ||
|
|
1cd0e94c26 | ||
|
|
1ec976f95e | ||
|
|
f10ef5f331 | ||
|
|
653bc59813 | ||
|
|
3e991e13dc | ||
|
|
5397b53e04 | ||
|
|
f09259f6de | ||
|
|
430a49ebc2 | ||
|
|
1091a8ba1a | ||
|
|
9116b6c8cd | ||
|
|
990e34a129 | ||
|
|
472d7b9376 | ||
|
|
50dd7881b1 | ||
|
|
aa8f8db305 | ||
|
|
cdd9b1e1eb | ||
|
|
2d2ce70edc | ||
|
|
78f1d1df38 | ||
|
|
a06bb3f992 | ||
|
|
e289f30e5d | ||
|
|
4b10993970 | ||
|
|
d78a870e66 | ||
|
|
cb41c58f21 | ||
|
|
c55d97183d | ||
|
|
8646cbc9f5 | ||
|
|
64c1d4c5bb | ||
|
|
76b949c196 | ||
|
|
c93ef47b9b | ||
|
|
2b414cd825 | ||
|
|
ac42447459 | ||
|
|
401d20fa1f | ||
|
|
6b5b570b45 | ||
|
|
9e6f666616 | ||
|
|
8ef9fe44c7 | ||
|
|
3e0a544eb8 | ||
|
|
6474891f1e | ||
|
|
40abb526cc | ||
|
|
c532d910c0 | ||
|
|
44288f6280 | ||
|
|
eec84ade86 | ||
|
|
10419ff441 | ||
|
|
57981b533d | ||
|
|
c5eaa0ab69 | ||
|
|
2c01e9e747 | ||
|
|
4c39b3188c | ||
|
|
224872ce03 | ||
|
|
f10a984ba3 | ||
|
|
c7f7181388 | ||
|
|
92530299eb | ||
|
|
58cd23d1ac | ||
|
|
5d85c10a2c | ||
|
|
f11270dac0 | ||
|
|
bcd76d4718 | ||
|
|
4dd2b66aaa | ||
|
|
829a140d9b | ||
|
|
f04fa5d54f | ||
|
|
b4175c1454 | ||
|
|
0728105b2b | ||
|
|
ea09d1d10e | ||
|
|
e7f88588bf | ||
|
|
ce890c3455 | ||
|
|
cbba00d360 | ||
|
|
bf366cb99d | ||
|
|
142d55ff24 | ||
|
|
a58400a82c | ||
|
|
aac28d24ac | ||
|
|
d624a3e648 | ||
|
|
c57294b41a | ||
|
|
485e82dcb1 | ||
|
|
e8d910ffd3 | ||
|
|
ab1f636960 | ||
|
|
52c4670237 | ||
|
|
2ae12fb0a0 | ||
|
|
6c1d3c4fd8 | ||
|
|
08de2b3fc4 | ||
|
|
945a9e3122 | ||
|
|
6e28ba8927 | ||
|
|
7369551c02 | ||
|
|
e22c76b3ac | ||
|
|
a438091266 | ||
|
|
85baf79d17 | ||
|
|
1c68be0631 | ||
|
|
b222dde835 | ||
|
|
78e5a395da | ||
|
|
7846e6a31e | ||
|
|
b7e7755edd | ||
|
|
40f48cbeb4 | ||
|
|
fb8313aa97 | ||
|
|
f9643917d3 | ||
|
|
ac1c9b1218 | ||
|
|
daf0d6b9a7 | ||
|
|
fa14863284 | ||
|
|
cd9ec0afc7 | ||
|
|
f3f6f1008a | ||
|
|
0e52672f4a | ||
|
|
bc1dc1fd63 | ||
|
|
f93f2c158b | ||
|
|
9229e2d88b | ||
|
|
51bb6b751e | ||
|
|
2cc87cab65 | ||
|
|
7cd273ae58 | ||
|
|
001fb7ef60 | ||
|
|
cf4660841a | ||
|
|
a52f755ce8 | ||
|
|
2a2abc4843 | ||
|
|
8af222c1e3 | ||
|
|
d3e6949007 | ||
|
|
a033b25ecb | ||
|
|
39dd30c239 | ||
|
|
c5c99d2357 | ||
|
|
25ff30ee8c | ||
|
|
6b250a74f8 | ||
|
|
5331397c6c | ||
|
|
0b39024133 | ||
|
|
438d286fd5 | ||
|
|
18a61f1058 | ||
|
|
20d012ae3f | ||
|
|
efc54ab8ba | ||
|
|
ea1c031b54 | ||
|
|
11a44081df | ||
|
|
5eb9c9504b | ||
|
|
29a078f65c | ||
|
|
be61ca13fe | ||
|
|
e9d5b2007a | ||
|
|
f2de8475fc | ||
|
|
3ecbea3c39 | ||
|
|
c4df7ad7a5 | ||
|
|
387567a917 | ||
|
|
cfbe8462cc | ||
|
|
5f4df54895 | ||
|
|
ed698f2462 | ||
|
|
b4774861db | ||
|
|
9768f73bb7 | ||
|
|
805249e27e | ||
|
|
5f24c40d05 | ||
|
|
1b3b82a3c1 | ||
|
|
9e72396709 | ||
|
|
125ee0b446 | ||
|
|
3bfb580d7a | ||
|
|
b54d47796d | ||
|
|
b5d0d6ff3e | ||
|
|
c9520deef8 | ||
|
|
ceab0f8c40 | ||
|
|
b87757c552 | ||
|
|
1972eb952d | ||
|
|
f92803d80e | ||
|
|
8afeb910bd | ||
|
|
f16ed98af4 | ||
|
|
2a9916103b | ||
|
|
63ad47a7bf | ||
|
|
27e6548343 | ||
|
|
8c91986dd3 | ||
|
|
5a65347c4e | ||
|
|
635180c8be | ||
|
|
019ce9862f | ||
|
|
c7f46876a7 | ||
|
|
c916eb6137 | ||
|
|
67cca71524 | ||
|
|
1eff7ae004 | ||
|
|
982ad46c83 | ||
|
|
657b4fd59e | ||
|
|
b371b406d5 | ||
|
|
91591c4e94 | ||
|
|
078b9719cc | ||
|
|
41d9826ee9 | ||
|
|
0152508a39 | ||
|
|
cdeb1c3828 | ||
|
|
0986fae066 | ||
|
|
277515636d | ||
|
|
45aacd8407 | ||
|
|
e8cdf8b092 | ||
|
|
1c4d6e7613 | ||
|
|
04b4e48265 | ||
|
|
dabcb1834d | ||
|
|
629cd86c7c | ||
|
|
ba704c4eb4 | ||
|
|
0487876826 | ||
|
|
ca9c05368e | ||
|
|
0d634a0061 | ||
|
|
86748fbc68 | ||
|
|
599477d754 | ||
|
|
889258f538 | ||
|
|
ffe2143d14 | ||
|
|
98470393d1 | ||
|
|
4192d04a53 | ||
|
|
3571dcd68c | ||
|
|
952edcb804 | ||
|
|
10a94c0794 | ||
|
|
dd32ace9ab | ||
|
|
7e0c6ee097 | ||
|
|
b1be34c6a0 | ||
|
|
b9307a9967 | ||
|
|
b1d353180b | ||
|
|
bd99eb1347 | ||
|
|
f79c01b0cf | ||
|
|
3f1e09ec0e | ||
|
|
05125029c6 | ||
|
|
05fe983757 | ||
|
|
d1a7749df5 | ||
|
|
9d63fc7ca0 | ||
|
|
38fccebe1f | ||
|
|
c05952b813 | ||
|
|
932cbe40bf | ||
|
|
39573d65d0 | ||
|
|
6db308f1e9 | ||
|
|
6f70fd90b9 | ||
|
|
db038d943c | ||
|
|
c5620efc9c | ||
|
|
8fb7aa5cef | ||
|
|
6ddee9a8ac | ||
|
|
5700359a61 | ||
|
|
0861a353d6 | ||
|
|
f79efec7ef | ||
|
|
77d5d20391 | ||
|
|
165e51d850 | ||
|
|
1c38f113b3 | ||
|
|
66859607a3 | ||
|
|
edf396b1a4 | ||
|
|
cbeb51b436 | ||
|
|
45e4fd6ec1 | ||
|
|
3a077ff211 | ||
|
|
be850e483a | ||
|
|
33fb62bb25 | ||
|
|
66c117e599 | ||
|
|
8aa1be8336 | ||
|
|
037d4121a1 | ||
|
|
fbd3918d3a | ||
|
|
7c543a43a9 | ||
|
|
ee3996cac6 | ||
|
|
96809ac659 | ||
|
|
6343059bc0 | ||
|
|
5a78fe33e8 | ||
|
|
676fb947f2 | ||
|
|
d18afb4a50 | ||
|
|
fc336a76bf | ||
|
|
b9f3d333e4 | ||
|
|
3d85af04be | ||
|
|
471b1e003a | ||
|
|
be2e17d605 | ||
|
|
9d6b9797c0 | ||
|
|
3cd6a18048 | ||
|
|
c9558c5f0e | ||
|
|
71e3d25422 | ||
|
|
644dc13e00 | ||
|
|
47e7aa4209 | ||
|
|
1c97a310b1 | ||
|
|
d612a1b5a1 | ||
|
|
386ead15a3 | ||
|
|
83c95e774d | ||
|
|
e4754999b7 | ||
|
|
c66489dbb1 | ||
|
|
21f9aefc7e | ||
|
|
d103dc2631 | ||
|
|
cac627ed05 | ||
|
|
e2cf2a5754 | ||
|
|
658a9a4ea8 | ||
|
|
a2db4c0a32 | ||
|
|
02a34a167a | ||
|
|
bea60930b6 | ||
|
|
0f7c82d38f | ||
|
|
6ba583d198 | ||
|
|
89d4c06dec | ||
|
|
9c72cc2a98 | ||
|
|
412bd94ea4 | ||
|
|
514ab043f2 | ||
|
|
68100102be | ||
|
|
05fdcb5b27 | ||
|
|
7a49c88200 | ||
|
|
40232d48ba | ||
|
|
55dff53a98 | ||
|
|
6919c2fb2d | ||
|
|
3d5d05eac7 | ||
|
|
dd866a74a6 | ||
|
|
b1e22aa559 | ||
|
|
2191e9ecd5 | ||
|
|
bf62103417 | ||
|
|
4b1b314ce2 | ||
|
|
c1ea0dde92 | ||
|
|
5a6cfc314e | ||
|
|
a4121a2c2e | ||
|
|
03335cef85 | ||
|
|
ff66bdda7c | ||
|
|
6cfddfea21 | ||
|
|
49bcec1d27 | ||
|
|
878c179761 | ||
|
|
bc19c04339 | ||
|
|
c7a33f926b | ||
|
|
3c38afdb47 | ||
|
|
b8828105cf | ||
|
|
007b195a5e | ||
|
|
b4c6cdf9a3 | ||
|
|
26775fa0b6 | ||
|
|
114fe9d502 | ||
|
|
54bc41f68b | ||
|
|
47ff8d61d1 | ||
|
|
849b8f5dce | ||
|
|
aabe42d252 | ||
|
|
78a62ec547 | ||
|
|
6dae994bb4 | ||
|
|
4c4d0916fd | ||
|
|
d5609729cc | ||
|
|
1f24a09570 | ||
|
|
a8e777a5df | ||
|
|
0bc58f695b | ||
|
|
28023d9f5b | ||
|
|
c2aed1979d | ||
|
|
7e04273719 | ||
|
|
0683bdcd42 | ||
|
|
29ab0bb629 | ||
|
|
7a9c17a520 | ||
|
|
b208daa271 | ||
|
|
e85a80dd65 | ||
|
|
b1d8ce24e9 | ||
|
|
098fd5d602 | ||
|
|
2f27f64cdb | ||
|
|
cbb60d29a2 | ||
|
|
e707052f66 | ||
|
|
71bd6e73ca | ||
|
|
b8326f6452 | ||
|
|
ece2e70a53 | ||
|
|
2b14ec23d5 | ||
|
|
9999f53329 | ||
|
|
522a6e3298 | ||
|
|
76d0dd7ec3 | ||
|
|
d1073dcecb | ||
|
|
e88e8bc194 | ||
|
|
bc29931434 | ||
|
|
505f312d5f | ||
|
|
f0093d3c54 | ||
|
|
83b60beba6 | ||
|
|
5f52d7c9d0 | ||
|
|
a1b65f7080 | ||
|
|
96df858961 | ||
|
|
4eddd1e5bc | ||
|
|
28f0eb598d | ||
|
|
c1eb7f9629 | ||
|
|
2f8aa5c52a | ||
|
|
22dcc19898 | ||
|
|
e295104199 | ||
|
|
66fe69edd9 | ||
|
|
fd946feac4 | ||
|
|
8856b6ecb7 | ||
|
|
0ae78db6cb | ||
|
|
3e3bb8a8f1 | ||
|
|
e48262a797 | ||
|
|
d934f94704 | ||
|
|
1fe4a7a4ea | ||
|
|
9daa0738a9 | ||
|
|
ad7d4939a8 | ||
|
|
c4d07952cb | ||
|
|
dc302b0db4 | ||
|
|
a6d180cefb | ||
|
|
1ddceeb063 | ||
|
|
633d0deeae | ||
|
|
9e3844ddd9 | ||
|
|
4b618bd6a6 | ||
|
|
09c4ed0694 | ||
|
|
d15eb04f9e | ||
|
|
02ac7456e4 | ||
|
|
6b0875728c | ||
|
|
6a330a2894 | ||
|
|
627a127f1b | ||
|
|
ec1ae68cfc | ||
|
|
3aa3880e69 | ||
|
|
a1b8d265d0 | ||
|
|
9b122c3804 | ||
|
|
28b82fb9aa | ||
|
|
7753bbba94 | ||
|
|
ac69a9c0dc | ||
|
|
d29f7f34aa | ||
|
|
85ea3f1d5d | ||
|
|
55166da437 | ||
|
|
777d9edeaa | ||
|
|
28a20aec10 | ||
|
|
3a1e694c2f | ||
|
|
b16042a047 | ||
|
|
cbf61e5cb9 | ||
|
|
077ee4d851 | ||
|
|
7b43b0bc94 | ||
|
|
6bb7db7c11 | ||
|
|
6ffd78767f | ||
|
|
f379d069b9 | ||
|
|
2da24089de | ||
|
|
57f29aa6d7 | ||
|
|
028d3ec16d | ||
|
|
d1c6506865 | ||
|
|
c0b46a03b5 | ||
|
|
114c18e70d | ||
|
|
7367b8be6c | ||
|
|
dd768fe655 | ||
|
|
d9bda3e985 | ||
|
|
fa7a3025ec | ||
|
|
e4451d6786 | ||
|
|
468b6b83ec | ||
|
|
8a3a32f286 | ||
|
|
20e81695ca | ||
|
|
027c52171d | ||
|
|
cc206d31b7 | ||
|
|
5d99316c96 | ||
|
|
d59eec4633 | ||
|
|
25e018d1ce | ||
|
|
25123bed23 | ||
|
|
a8d6db0fc1 | ||
|
|
8a9a9cd92d | ||
|
|
530ff5420b | ||
|
|
133b11fa6d | ||
|
|
5b489284e4 | ||
|
|
cdc32eb817 | ||
|
|
eb38ff453a | ||
|
|
8eb7853a1a | ||
|
|
0c151f9fb3 | ||
|
|
c10c820311 | ||
|
|
82889e2367 | ||
|
|
92741aa4ec | ||
|
|
2f352ca5cf | ||
|
|
38c8cb9f4a | ||
|
|
73248bdced | ||
|
|
01203b247b | ||
|
|
3e1d169160 | ||
|
|
c1b93fc3d0 | ||
|
|
1f81e5c872 | ||
|
|
e5291c9e28 | ||
|
|
35505a3114 | ||
|
|
830d47a5f7 | ||
|
|
1a514dff38 | ||
|
|
2888d5c6cf | ||
|
|
400f75a2b3 | ||
|
|
07bdd3e218 | ||
|
|
35a11ae24f | ||
|
|
3d28283a81 | ||
|
|
aec5a9fa09 | ||
|
|
0f94f62025 | ||
|
|
a95ebc5ee6 | ||
|
|
a70ac1531e | ||
|
|
b6e8dd0d8a | ||
|
|
af80ce842d | ||
|
|
08bae037f0 | ||
|
|
cd39327ea2 | ||
|
|
9828f368d6 | ||
|
|
1ed15c7ec7 | ||
|
|
c66784995d | ||
|
|
dba21c06ed | ||
|
|
72fc6a74ec | ||
|
|
f916311744 | ||
|
|
05a1f4280c | ||
|
|
6608a0241d | ||
|
|
429bbfade0 | ||
|
|
28e3c35547 | ||
|
|
af3ef52252 | ||
|
|
2b5f9c52a6 | ||
|
|
5631cc2528 | ||
|
|
de33a92a1b | ||
|
|
1c6353aa3a | ||
|
|
08cb950226 | ||
|
|
765225d918 | ||
|
|
35bc65f6fa | ||
|
|
676268d461 | ||
|
|
34dce8069f | ||
|
|
f62bb33317 | ||
|
|
a557b3cfb6 | ||
|
|
3ff4834bd5 | ||
|
|
bedb889693 | ||
|
|
157ca9cd17 | ||
|
|
6f5e7e170c | ||
|
|
df7571b369 | ||
|
|
d69e41eba8 | ||
|
|
2d41a7d1b0 | ||
|
|
42e0ccfa1c | ||
|
|
55640a91ae | ||
|
|
4f6ca8792c | ||
|
|
5ced36e319 | ||
|
|
237e7ee2e6 | ||
|
|
02f281569d | ||
|
|
ab4d971c5e | ||
|
|
e21df5831e | ||
|
|
18a0119b06 | ||
|
|
34348435fd | ||
|
|
cf3b0f3b70 | ||
|
|
a336e9e959 | ||
|
|
ea93a0130d | ||
|
|
dcd9ddde50 | ||
|
|
86bafdc104 | ||
|
|
6732fa731d | ||
|
|
8cea3e262b | ||
|
|
3e8669ea7f | ||
|
|
7df040f451 | ||
|
|
472eddcc1b | ||
|
|
c0a7900341 | ||
|
|
28a50817af | ||
|
|
2c47c43f47 | ||
|
|
2ef39651eb | ||
|
|
eb20612d77 | ||
|
|
695547f4ca | ||
|
|
d35ee0d580 | ||
|
|
95581ab92f | ||
|
|
3716f13d8e | ||
|
|
c03ef852a4 | ||
|
|
28a5feef28 | ||
|
|
57a53bda74 | ||
|
|
36f4eccb5c | ||
|
|
b6de19e92e | ||
|
|
e87bc3db20 | ||
|
|
a3739d6bad | ||
|
|
068d114740 | ||
|
|
3273c14dea | ||
|
|
206c3c246c | ||
|
|
bfcd85ab15 | ||
|
|
c99bba1655 | ||
|
|
1e7376847b | ||
|
|
b03e589987 | ||
|
|
0b497b62d8 | ||
|
|
f085b7349c | ||
|
|
dd99b3bd73 | ||
|
|
f53683f01f | ||
|
|
7b707e7d75 | ||
|
|
31110be396 | ||
|
|
604016d69d | ||
|
|
7ee9d5639b | ||
|
|
1aab328e2a | ||
|
|
1366dc326a | ||
|
|
8e73287646 | ||
|
|
7eed52a97a | ||
|
|
31ada5a052 | ||
|
|
30b4f8dc9f | ||
|
|
dbdde3d781 | ||
|
|
cf0b8babbd | ||
|
|
c0c22c8ff1 | ||
|
|
73cf10e4f3 | ||
|
|
8a1c5277eb | ||
|
|
1e4c176506 | ||
|
|
3c27e7d88f | ||
|
|
5bc3cf18d9 | ||
|
|
131e67ddc1 | ||
|
|
e5ba79db04 | ||
|
|
f4e9bf51db | ||
|
|
03f9e8fce0 | ||
|
|
4ae9900363 | ||
|
|
454d4190b7 | ||
|
|
a28b60578d | ||
|
|
5a206de620 | ||
|
|
b547531499 | ||
|
|
39e668ffb0 | ||
|
|
bd1ac6cb1e | ||
|
|
8567758156 | ||
|
|
e897d70733 | ||
|
|
fe12996382 | ||
|
|
e8e4d4ce66 | ||
|
|
44af4f4f52 | ||
|
|
7daf146801 | ||
|
|
7b23d190b1 | ||
|
|
17b8310517 | ||
|
|
5ca828d445 | ||
|
|
1ea29b4de0 | ||
|
|
b00cdadb5b | ||
|
|
53e646dabc | ||
|
|
613fafdfdf | ||
|
|
5d0bc5f607 | ||
|
|
ce5cf97e17 | ||
|
|
3ee59696e5 | ||
|
|
f5c624bcd6 | ||
|
|
026b331ba5 | ||
|
|
93c36ccf78 | ||
|
|
c1f314ccdc | ||
|
|
53a89f28a0 | ||
|
|
f874d76289 | ||
|
|
76645f3b5a | ||
|
|
28775be115 | ||
|
|
7d3ff3d2d9 | ||
|
|
4a5d639d74 | ||
|
|
74a7cf55ea | ||
|
|
9393b14b01 | ||
|
|
f8bd671073 | ||
|
|
2af753f307 | ||
|
|
5cc84f32db | ||
|
|
e89674d337 | ||
|
|
de120280e3 | ||
|
|
7f2ba0ee3e | ||
|
|
5bf303fd26 | ||
|
|
e37e46b155 | ||
|
|
b8192ef6f6 | ||
|
|
23354cf1a5 | ||
|
|
dd38fab2f3 | ||
|
|
ac08601b40 | ||
|
|
ea73dac753 | ||
|
|
2a35646520 | ||
|
|
bb285984da | ||
|
|
34db2d7d4c | ||
|
|
0e20973bdb | ||
|
|
29e2481597 | ||
|
|
1596cc5d9e | ||
|
|
8f66d96915 | ||
|
|
8ad078b964 | ||
|
|
d5368d7979 | ||
|
|
9c5657b86c | ||
|
|
b79089ea57 | ||
|
|
3555de114a | ||
|
|
c5703eb00a | ||
|
|
dbe6a1bcdf | ||
|
|
eea9530f38 | ||
|
|
a195ce8146 | ||
|
|
a0f280e71f | ||
|
|
cf28751ae3 | ||
|
|
9dd15d00d8 | ||
|
|
2442305bb7 | ||
|
|
063648368d | ||
|
|
918b2efce7 | ||
|
|
2467a997f4 | ||
|
|
f457c6a0b8 | ||
|
|
1193cada46 | ||
|
|
b0e09b8ffe | ||
|
|
8d6e8bb8d1 | ||
|
|
e2c84725de | ||
|
|
b571362bf1 | ||
|
|
b1b5aefc4b | ||
|
|
06244dd492 | ||
|
|
de2f0740f7 | ||
|
|
c56a66cb90 | ||
|
|
c1329ff156 | ||
|
|
72509b5b42 | ||
|
|
c35fdc8d61 | ||
|
|
5d31f73302 | ||
|
|
7de1261555 | ||
|
|
91a511ba8c | ||
|
|
94f6294c0a | ||
|
|
77cd3adb01 | ||
|
|
7dabad4d71 | ||
|
|
54b4074369 | ||
|
|
e4d8e22846 | ||
|
|
403dcc02f4 | ||
|
|
64be6e5c5e | ||
|
|
c661006683 | ||
|
|
f879bca21c | ||
|
|
182beb4f8b | ||
|
|
2690306f4a | ||
|
|
b59e3c670b | ||
|
|
2e0bbc091f | ||
|
|
91f05e940f | ||
|
|
db794b976c | ||
|
|
9a11f90a02 | ||
|
|
412516159f | ||
|
|
65587ef43a | ||
|
|
cf713bef31 | ||
|
|
ea5c21950c | ||
|
|
47b5dfa034 | ||
|
|
2b89ddec15 | ||
|
|
f256ff7d58 | ||
|
|
07356b9634 | ||
|
|
f2b6ef2edd | ||
|
|
1409f83fb9 | ||
|
|
37dadab745 | ||
|
|
0eefa3ba42 | ||
|
|
08f8f89702 | ||
|
|
0df436901a | ||
|
|
ae63fbdbbb | ||
|
|
4f29618c73 | ||
|
|
76660f3621 | ||
|
|
3a7350cbb9 | ||
|
|
e5aa906b01 | ||
|
|
4b0162a013 | ||
|
|
5be88e79b0 | ||
|
|
93502e0cda | ||
|
|
8d6a857ba5 | ||
|
|
6ff1370035 | ||
|
|
d5391686ae | ||
|
|
70c7382a09 | ||
|
|
9f801cf79e | ||
|
|
062e0e52ee | ||
|
|
fa99b9ff5a | ||
|
|
8f6e80917f | ||
|
|
e087ebd1c7 | ||
|
|
0d3e75d6b0 | ||
|
|
873f7bcec7 | ||
|
|
e579a03035 | ||
|
|
94f998af0a | ||
|
|
fe5e300062 | ||
|
|
2253565db5 | ||
|
|
2ead1c1c59 | ||
|
|
746e99c958 | ||
|
|
47194b5f3c | ||
|
|
4515b77aa5 | ||
|
|
20b09c4514 | ||
|
|
9874181ccd | ||
|
|
cb93554938 | ||
|
|
6b7bd32c8e | ||
|
|
17a240cd43 | ||
|
|
fc481b6d6d | ||
|
|
09182dc093 | ||
|
|
b682c3dfb5 | ||
|
|
ab0a34012f | ||
|
|
f000b82d74 | ||
|
|
dad8de82fa | ||
|
|
3fea477bfd | ||
|
|
f7d7acb3c5 | ||
|
|
9e25561edf | ||
|
|
7c6bdcc459 | ||
|
|
b09629f1d4 | ||
|
|
85446d81f3 | ||
|
|
96786bbb87 | ||
|
|
a5166baba2 | ||
|
|
d1deba8620 | ||
|
|
aaee72422a | ||
|
|
3dd0e31cc4 | ||
|
|
283a8dec37 | ||
|
|
37d354cf7f | ||
|
|
f698d451df | ||
|
|
c088f8bd03 | ||
|
|
3cd40ef655 | ||
|
|
6513351e0c | ||
|
|
f44e98ddc9 | ||
|
|
fd4db4000c | ||
|
|
9602716ed2 | ||
|
|
7be1d16263 | ||
|
|
c91dfdd6fe | ||
|
|
8e733543cd | ||
|
|
26e37590e8 | ||
|
|
ddf133dd66 | ||
|
|
4584e7629a | ||
|
|
139686ddce | ||
|
|
5a0b4dba47 | ||
|
|
33c8aa660f | ||
|
|
cb76dcae2a | ||
|
|
d622de4797 | ||
|
|
9ae75c0c03 | ||
|
|
45a4281413 | ||
|
|
bfbcab3a01 | ||
|
|
4b4c73cee4 | ||
|
|
fd349f1822 | ||
|
|
cb0a085968 | ||
|
|
aabf0e13b7 | ||
|
|
92873b06ed | ||
|
|
04ca2cf9f4 | ||
|
|
b049a4dc66 | ||
|
|
5be52c9753 | ||
|
|
3c59283b3f | ||
|
|
3ba808e3c6 | ||
|
|
df5d66b5e8 | ||
|
|
7fe90e6c80 | ||
|
|
8dcd514393 | ||
|
|
2c3e420f82 | ||
|
|
917db35a84 | ||
|
|
dd52364d33 | ||
|
|
30aa5a5057 | ||
|
|
a46fcaee31 | ||
|
|
52e2748869 | ||
|
|
d2d127a4c4 | ||
|
|
0fca8e8cb5 | ||
|
|
6bec912961 | ||
|
|
214e157e5d | ||
|
|
da1d479e55 | ||
|
|
062bb0cef2 | ||
|
|
c744b016ce | ||
|
|
f486845f7f | ||
|
|
7baa96c5c7 | ||
|
|
ea07ec1fda | ||
|
|
26b70e457b | ||
|
|
5d5fcb3911 | ||
|
|
50008dff3d | ||
|
|
808638fee3 | ||
|
|
b0e3865562 | ||
|
|
bc03ffb317 | ||
|
|
1edbca1775 | ||
|
|
5a0bc016e7 | ||
|
|
bb66b7f28e | ||
|
|
0331491b2b | ||
|
|
54a782c8ae | ||
|
|
a70bc20829 | ||
|
|
102ed3b800 | ||
|
|
c8e339fe6d | ||
|
|
e4e53fe315 | ||
|
|
1c795c3f1c | ||
|
|
b2b740fed7 | ||
|
|
09550397d7 |
2
.cargo/config.toml
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
[alias]
|
||||||
|
run-wasm = ["run", "--release", "--package", "run-wasm", "--"]
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
version: 2
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
|
|
||||||
android-test:
|
|
||||||
working_directory: ~/winit
|
|
||||||
docker:
|
|
||||||
- image: tomaka/cargo-apk
|
|
||||||
steps:
|
|
||||||
- run: apt-get -qq update && apt-get install -y git
|
|
||||||
- checkout
|
|
||||||
- restore_cache:
|
|
||||||
key: android-test-cache-{{ checksum "Cargo.toml" }}
|
|
||||||
- run: cargo apk build --example window
|
|
||||||
- save_cache:
|
|
||||||
key: android-test-cache-{{ checksum "Cargo.toml" }}
|
|
||||||
paths:
|
|
||||||
- target
|
|
||||||
|
|
||||||
asmjs-test:
|
|
||||||
working_directory: ~/winit
|
|
||||||
docker:
|
|
||||||
- image: tomaka/rustc-emscripten
|
|
||||||
steps:
|
|
||||||
- run: apt-get -qq update && apt-get install -y git
|
|
||||||
- checkout
|
|
||||||
- restore_cache:
|
|
||||||
key: asmjs-test-cache-{{ checksum "Cargo.toml" }}
|
|
||||||
- run: cargo build --example window --target asmjs-unknown-emscripten
|
|
||||||
- save_cache:
|
|
||||||
key: asmjs-test-cache-{{ checksum "Cargo.toml" }}
|
|
||||||
paths:
|
|
||||||
- target
|
|
||||||
|
|
||||||
wasm-test:
|
|
||||||
working_directory: ~/winit
|
|
||||||
docker:
|
|
||||||
- image: tomaka/rustc-emscripten
|
|
||||||
steps:
|
|
||||||
- run: apt-get -qq update && apt-get install -y git
|
|
||||||
- checkout
|
|
||||||
- restore_cache:
|
|
||||||
key: wasm-test-cache-{{ checksum "Cargo.toml" }}
|
|
||||||
- run: cargo build --example window --target wasm32-unknown-emscripten
|
|
||||||
- save_cache:
|
|
||||||
key: wasm-test-cache-{{ checksum "Cargo.toml" }}
|
|
||||||
paths:
|
|
||||||
- target
|
|
||||||
|
|
||||||
workflows:
|
|
||||||
version: 2
|
|
||||||
build-test-and-deploy:
|
|
||||||
jobs:
|
|
||||||
- android-test
|
|
||||||
- asmjs-test
|
|
||||||
- wasm-test
|
|
||||||
34
.github/CODEOWNERS
vendored
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
# Android
|
||||||
|
/src/platform/android.rs @msiglreith @MarijnS95
|
||||||
|
/src/platform_impl/android @msiglreith @MarijnS95
|
||||||
|
|
||||||
|
# iOS
|
||||||
|
/src/platform/ios.rs @madsmtm
|
||||||
|
/src/platform_impl/ios @madsmtm
|
||||||
|
|
||||||
|
# Unix
|
||||||
|
/src/platform_impl/linux/mod.rs @kchibisov
|
||||||
|
|
||||||
|
# Wayland
|
||||||
|
/src/platform/wayland.rs @kchibisov
|
||||||
|
/src/platform_impl/linux/wayland @kchibisov
|
||||||
|
|
||||||
|
# X11
|
||||||
|
/src/platform/x11.rs @kchibisov @notgull
|
||||||
|
/src/platform_impl/linux/x11 @kchibisov @notgull
|
||||||
|
|
||||||
|
# macOS
|
||||||
|
/src/platform/macos.rs @madsmtm
|
||||||
|
/src/platform_impl/macos @madsmtm
|
||||||
|
|
||||||
|
# Web
|
||||||
|
/src/platform/web.rs @daxpedda
|
||||||
|
/src/platform_impl/web @daxpedda
|
||||||
|
|
||||||
|
# Windows
|
||||||
|
/src/platform/windows.rs @msiglreith
|
||||||
|
/src/platform_impl/windows @msiglreith
|
||||||
|
|
||||||
|
# Orbital (Redox OS)
|
||||||
|
/src/platform/orbital.rs @jackpot51
|
||||||
|
/src/platform_impl/orbital @jackpot51
|
||||||
3
.github/PULL_REQUEST_TEMPLATE.md
vendored
@@ -1,4 +1,5 @@
|
|||||||
- [ ] 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 `CHANGELOG.md` 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 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
|
||||||
|
|||||||
203
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,203 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
push:
|
||||||
|
branches: [master]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
fmt:
|
||||||
|
name: Check formatting
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
with:
|
||||||
|
components: rustfmt
|
||||||
|
- name: Check Formatting
|
||||||
|
run: cargo fmt -- --check
|
||||||
|
|
||||||
|
tests:
|
||||||
|
name: Test ${{ matrix.toolchain }} ${{ matrix.platform.name }}
|
||||||
|
runs-on: ${{ matrix.platform.os }}
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
toolchain: [stable, nightly, '1.70.0']
|
||||||
|
platform:
|
||||||
|
# Note: Make sure that we test all the `docs.rs` targets defined in Cargo.toml!
|
||||||
|
- { name: 'Windows 64bit MSVC', target: x86_64-pc-windows-msvc, os: windows-latest, }
|
||||||
|
- { name: 'Windows 32bit MSVC', target: i686-pc-windows-msvc, os: windows-latest, }
|
||||||
|
- { name: 'Windows 64bit GNU', target: x86_64-pc-windows-gnu, os: windows-latest, host: -x86_64-pc-windows-gnu }
|
||||||
|
- { name: 'Windows 32bit GNU', target: i686-pc-windows-gnu, os: windows-latest, host: -i686-pc-windows-gnu }
|
||||||
|
- { name: 'Linux 32bit', target: i686-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: 'Wayland', target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: '--no-default-features --features=wayland,wayland-dlopen' }
|
||||||
|
- { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
||||||
|
- { name: 'Redox OS', target: x86_64-unknown-redox, os: ubuntu-latest, }
|
||||||
|
- { name: 'macOS', target: x86_64-apple-darwin, os: macos-latest, }
|
||||||
|
- { name: 'iOS x86_64', target: x86_64-apple-ios, os: macos-latest, }
|
||||||
|
- { name: 'iOS Aarch64', target: aarch64-apple-ios, os: macos-latest, }
|
||||||
|
- { name: 'web', target: wasm32-unknown-unknown, os: ubuntu-latest, }
|
||||||
|
exclude:
|
||||||
|
# Android is tested on stable-3
|
||||||
|
- toolchain: '1.70.0'
|
||||||
|
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
||||||
|
include:
|
||||||
|
- toolchain: '1.70.0'
|
||||||
|
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package=winit --features=android-native-activity', cmd: 'apk --' }
|
||||||
|
- toolchain: 'nightly'
|
||||||
|
platform: {
|
||||||
|
name: 'web Atomic',
|
||||||
|
target: wasm32-unknown-unknown,
|
||||||
|
os: ubuntu-latest,
|
||||||
|
options: '-Zbuild-std=panic_abort,std',
|
||||||
|
rustflags: '-Ctarget-feature=+atomics,+bulk-memory',
|
||||||
|
components: rust-src,
|
||||||
|
}
|
||||||
|
|
||||||
|
env:
|
||||||
|
# Set more verbose terminal output
|
||||||
|
CARGO_TERM_VERBOSE: true
|
||||||
|
RUST_BACKTRACE: 1
|
||||||
|
|
||||||
|
# Faster compilation and error on warnings
|
||||||
|
RUSTFLAGS: '--codegen=debuginfo=0 --deny=warnings ${{ matrix.platform.rustflags }}'
|
||||||
|
|
||||||
|
OPTIONS: --target=${{ matrix.platform.target }} ${{ matrix.platform.options }}
|
||||||
|
CMD: ${{ matrix.platform.cmd }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Restore cache of cargo folder
|
||||||
|
# We use `restore` and later `save`, so that we can create the key after
|
||||||
|
# the cache has been downloaded.
|
||||||
|
#
|
||||||
|
# This could be avoided if we added Cargo.lock to the repository.
|
||||||
|
uses: actions/cache/restore@v3
|
||||||
|
with:
|
||||||
|
# https://doc.rust-lang.org/cargo/guide/cargo-home.html#caching-the-cargo-home-in-ci
|
||||||
|
path: |
|
||||||
|
~/.cargo/registry/index/
|
||||||
|
~/.cargo/registry/cache/
|
||||||
|
~/.cargo/git/db/
|
||||||
|
key: cargo-${{ matrix.toolchain }}-${{ matrix.platform.name }}-never-intended-to-be-found
|
||||||
|
restore-keys: cargo-${{ matrix.toolchain }}-${{ matrix.platform.name }}
|
||||||
|
|
||||||
|
- name: Generate lockfile
|
||||||
|
# Also updates the crates.io index
|
||||||
|
run: cargo generate-lockfile && cargo update -p ahash --precise 0.8.7 && cargo update -p bumpalo --precise 3.14.0
|
||||||
|
|
||||||
|
- name: Install GCC Multilib
|
||||||
|
if: (matrix.platform.os == 'ubuntu-latest') && contains(matrix.platform.target, 'i686')
|
||||||
|
run: sudo apt-get update && sudo apt-get install gcc-multilib
|
||||||
|
|
||||||
|
- name: Cache cargo-apk
|
||||||
|
if: contains(matrix.platform.target, 'android')
|
||||||
|
id: cargo-apk-cache
|
||||||
|
uses: actions/cache@v3
|
||||||
|
with:
|
||||||
|
path: ~/.cargo/bin/cargo-apk
|
||||||
|
# Change this key if we update the required cargo-apk version
|
||||||
|
key: cargo-apk-v0-9-7
|
||||||
|
|
||||||
|
- uses: dtolnay/rust-toolchain@master
|
||||||
|
if: contains(matrix.platform.target, 'android') && (steps.cargo-apk-cache.outputs.cache-hit != 'true')
|
||||||
|
with:
|
||||||
|
toolchain: stable
|
||||||
|
|
||||||
|
- name: Install cargo-apk
|
||||||
|
if: contains(matrix.platform.target, 'android') && (steps.cargo-apk-cache.outputs.cache-hit != 'true')
|
||||||
|
run: cargo install cargo-apk --version=^0.9.7 --locked
|
||||||
|
|
||||||
|
- uses: dtolnay/rust-toolchain@master
|
||||||
|
with:
|
||||||
|
toolchain: ${{ matrix.toolchain }}${{ matrix.platform.host }}
|
||||||
|
targets: ${{ matrix.platform.target }}
|
||||||
|
components: clippy, ${{ matrix.platform.components }}
|
||||||
|
|
||||||
|
- name: Check documentation
|
||||||
|
run: cargo doc --no-deps $OPTIONS --document-private-items
|
||||||
|
env:
|
||||||
|
RUSTDOCFLAGS: '--deny=warnings ${{ matrix.platform.rustflags }}'
|
||||||
|
|
||||||
|
- name: Build crate
|
||||||
|
run: cargo $CMD build $OPTIONS
|
||||||
|
|
||||||
|
- name: Build tests
|
||||||
|
if: >
|
||||||
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
|
matrix.toolchain != '1.70.0'
|
||||||
|
run: cargo $CMD test --no-run $OPTIONS
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
if: >
|
||||||
|
!contains(matrix.platform.target, 'android') &&
|
||||||
|
!contains(matrix.platform.target, 'ios') &&
|
||||||
|
!contains(matrix.platform.target, 'wasm32') &&
|
||||||
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
|
matrix.toolchain != '1.70.0'
|
||||||
|
run: cargo $CMD test $OPTIONS
|
||||||
|
|
||||||
|
- name: Lint with clippy
|
||||||
|
if: (matrix.toolchain == 'stable') && !contains(matrix.platform.options, '--no-default-features')
|
||||||
|
run: cargo clippy --all-targets $OPTIONS -- -Dwarnings
|
||||||
|
|
||||||
|
- name: Build tests with serde enabled
|
||||||
|
if: >
|
||||||
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
|
matrix.toolchain != '1.70.0'
|
||||||
|
run: cargo $CMD test --no-run $OPTIONS --features serde
|
||||||
|
|
||||||
|
- name: Run tests with serde enabled
|
||||||
|
if: >
|
||||||
|
!contains(matrix.platform.target, 'android') &&
|
||||||
|
!contains(matrix.platform.target, 'ios') &&
|
||||||
|
!contains(matrix.platform.target, 'wasm32') &&
|
||||||
|
!contains(matrix.platform.target, 'redox') &&
|
||||||
|
matrix.toolchain != '1.70.0'
|
||||||
|
run: cargo $CMD test $OPTIONS --features serde
|
||||||
|
|
||||||
|
- name: Check docs.rs documentation
|
||||||
|
if: matrix.toolchain == 'nightly'
|
||||||
|
run: cargo doc --no-deps $OPTIONS --features=rwh_04,rwh_05,rwh_06,serde,mint,android-native-activity
|
||||||
|
env:
|
||||||
|
RUSTDOCFLAGS: '--deny=warnings ${{ matrix.platform.rustflags }} --cfg=docsrs'
|
||||||
|
|
||||||
|
# See restore step above
|
||||||
|
- name: Save cache of cargo folder
|
||||||
|
uses: actions/cache/save@v3
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cargo/registry/index/
|
||||||
|
~/.cargo/registry/cache/
|
||||||
|
~/.cargo/git/db/
|
||||||
|
key: cargo-${{ matrix.toolchain }}-${{ matrix.platform.name }}-${{ hashFiles('Cargo.lock') }}
|
||||||
|
|
||||||
|
cargo-deny:
|
||||||
|
name: Run cargo-deny on ${{ matrix.platform.name }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
# TODO: remove this matrix when https://github.com/EmbarkStudios/cargo-deny/issues/324 is resolved
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
platform:
|
||||||
|
- { name: 'Android', target: aarch64-linux-android }
|
||||||
|
- { name: 'iOS', target: aarch64-apple-ios }
|
||||||
|
- { name: 'Linux', target: x86_64-unknown-linux-gnu }
|
||||||
|
- { name: 'macOS', target: x86_64-apple-darwin }
|
||||||
|
- { name: 'Redox OS', target: x86_64-unknown-redox }
|
||||||
|
- { name: 'web', target: wasm32-unknown-unknown }
|
||||||
|
- { name: 'Windows', target: x86_64-pc-windows-gnu }
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- uses: EmbarkStudios/cargo-deny-action@v1
|
||||||
|
with:
|
||||||
|
command: check
|
||||||
|
log-level: error
|
||||||
|
arguments: --all-features --target ${{ matrix.platform.target }}
|
||||||
50
.github/workflows/docs.yml
vendored
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
name: Docs
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [master]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
docs:
|
||||||
|
name: Documentation
|
||||||
|
environment:
|
||||||
|
name: github-pages
|
||||||
|
url: ${{ steps.deployment.outputs.page_url }}winit
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
pages: write
|
||||||
|
id-token: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- uses: dtolnay/rust-toolchain@master
|
||||||
|
with:
|
||||||
|
toolchain: nightly
|
||||||
|
|
||||||
|
- name: Run Rustdoc
|
||||||
|
env:
|
||||||
|
RUSTDOCFLAGS: --crate-version master --cfg=docsrs
|
||||||
|
run: |
|
||||||
|
cargo doc --no-deps -Z rustdoc-map -Z rustdoc-scrape-examples --features=rwh_04,rwh_05,rwh_06,serde,mint,android-native-activity
|
||||||
|
|
||||||
|
- name: Setup Pages
|
||||||
|
uses: actions/configure-pages@v4
|
||||||
|
|
||||||
|
- name: Fix permissions
|
||||||
|
run: |
|
||||||
|
chmod -c -R +rX "target/doc" | while read line; do
|
||||||
|
echo "::warning title=Invalid file permissions automatically fixed::$line"
|
||||||
|
done
|
||||||
|
|
||||||
|
- name: Upload artifact
|
||||||
|
uses: actions/upload-pages-artifact@v3
|
||||||
|
with:
|
||||||
|
path: target/doc
|
||||||
|
|
||||||
|
- name: Deploy to GitHub Pages
|
||||||
|
id: deployment
|
||||||
|
uses: actions/deploy-pages@v4
|
||||||
4
.gitignore
vendored
@@ -3,4 +3,8 @@ target/
|
|||||||
rls/
|
rls/
|
||||||
.vscode/
|
.vscode/
|
||||||
*~
|
*~
|
||||||
|
*.wasm
|
||||||
|
*.ts
|
||||||
|
*.js
|
||||||
#*#
|
#*#
|
||||||
|
.DS_Store
|
||||||
|
|||||||
3
.gitmodules
vendored
@@ -1,3 +0,0 @@
|
|||||||
[submodule "deps/apk-builder"]
|
|
||||||
path = deps/apk-builder
|
|
||||||
url = https://github.com/tomaka/android-rs-glue
|
|
||||||
75
.travis.yml
@@ -1,75 +0,0 @@
|
|||||||
language: rust
|
|
||||||
|
|
||||||
cache: cargo
|
|
||||||
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
# Linux 32bit
|
|
||||||
- env: TARGET=i686-unknown-linux-gnu
|
|
||||||
os: linux
|
|
||||||
rust: nightly
|
|
||||||
addons:
|
|
||||||
apt:
|
|
||||||
# Cross compiler and cross compiled C libraries
|
|
||||||
packages: &i686_packages
|
|
||||||
- gcc-multilib
|
|
||||||
- env: TARGET=i686-unknown-linux-gnu
|
|
||||||
os: linux
|
|
||||||
rust: stable
|
|
||||||
addons:
|
|
||||||
apt:
|
|
||||||
packages: *i686_packages
|
|
||||||
- env: TARGET=i686-unknown-linux-gnu
|
|
||||||
os: linux
|
|
||||||
rust: 1.24.1
|
|
||||||
addons:
|
|
||||||
apt:
|
|
||||||
packages: *i686_packages
|
|
||||||
|
|
||||||
# Linux 64bit
|
|
||||||
- env: TARGET=x86_64-unknown-linux-gnu
|
|
||||||
os: linux
|
|
||||||
rust: nightly
|
|
||||||
- env: TARGET=x86_64-unknown-linux-gnu
|
|
||||||
os: linux
|
|
||||||
rust: stable
|
|
||||||
- env: TARGET=x86_64-unknown-linux-gnu
|
|
||||||
os: linux
|
|
||||||
rust: 1.24.1
|
|
||||||
|
|
||||||
# macOS
|
|
||||||
- env: TARGET=x86_64-apple-darwin
|
|
||||||
os: osx
|
|
||||||
rust: nightly
|
|
||||||
- env: TARGET=x86_64-apple-darwin
|
|
||||||
os: osx
|
|
||||||
rust: stable
|
|
||||||
- env: TARGET=x86_64-apple-darwin
|
|
||||||
os: osx
|
|
||||||
rust: 1.24.1
|
|
||||||
|
|
||||||
# iOS
|
|
||||||
- env: TARGET=x86_64-apple-ios
|
|
||||||
os: osx
|
|
||||||
rust: nightly
|
|
||||||
- env: TARGET=x86_64-apple-ios
|
|
||||||
os: osx
|
|
||||||
rust: stable
|
|
||||||
- env: TARGET=x86_64-apple-ios
|
|
||||||
os: osx
|
|
||||||
rust: 1.24.1
|
|
||||||
|
|
||||||
install:
|
|
||||||
- rustup self update
|
|
||||||
- rustup target add $TARGET; true
|
|
||||||
|
|
||||||
script:
|
|
||||||
- cargo build --target $TARGET --verbose
|
|
||||||
# Running iOS apps on OSX requires the simulator so we skip that for now
|
|
||||||
- if [ "$TARGET" != "x86_64-apple-ios" ]; then cargo test --target $TARGET --verbose; fi
|
|
||||||
|
|
||||||
after_success:
|
|
||||||
- |
|
|
||||||
[ $TRAVIS_BRANCH = master ] &&
|
|
||||||
[ $TRAVIS_PULL_REQUEST = false ] &&
|
|
||||||
cargo publish --token ${CRATESIO_TOKEN}
|
|
||||||
1047
CHANGELOG.md
69
CONTRIBUTING.md
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
# Winit Contributing Guidelines
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
[See `FEATURES.md`](./FEATURES.md). When requesting or implementing a new Winit feature, you should
|
||||||
|
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.
|
||||||
|
|
||||||
|
|
||||||
|
## Reporting an issue
|
||||||
|
|
||||||
|
When reporting an issue, in order to help the maintainers understand what the problem is, please make
|
||||||
|
your description of the issue as detailed as possible:
|
||||||
|
|
||||||
|
- if it is a bug, please provide a clear explanation of what happens, what should happen, and how to
|
||||||
|
reproduce the issue, ideally by providing a minimal program exhibiting the problem
|
||||||
|
- 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
|
||||||
|
|
||||||
|
When making a code contribution to winit, before opening your pull request, please make sure that:
|
||||||
|
|
||||||
|
- your patch builds with Winit's minimal supported rust version - Rust 1.70.
|
||||||
|
- 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
|
||||||
|
handle those for you when merging (see below).
|
||||||
|
- if your PR affects the platform compatibility of one or more features or adds another feature, the
|
||||||
|
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
|
||||||
|
is that a PR must be approved by at least two maintainers of winit before being merged, including
|
||||||
|
at least a maintainer of the platform (a maintainer making a PR themselves counts as approving it).
|
||||||
|
|
||||||
|
Once your PR is deemed ready, the merging maintainer will take care of resolving conflicts in
|
||||||
|
`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
|
||||||
|
|
||||||
|
The current maintainers for each platform are listed in the [CODEOWNERS](.github/CODEOWNERS) file.
|
||||||
|
|
||||||
|
## Release process
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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:
|
||||||
|
1. Initially, the version on the latest master is `0.1.0`
|
||||||
|
2. A new `v0.2.x` branch is created for the release
|
||||||
|
3. In the branch, the version is bumped to `v0.2.0`
|
||||||
|
4. The new commit in the branch is tagged `v0.2.0`
|
||||||
|
5. The version is pushed to crates.io
|
||||||
|
6. A GitHub release is created for the `v0.2.0` tag
|
||||||
|
7. On master, the version is bumped to `0.2.0`, and the CHANGELOG is updated
|
||||||
|
|
||||||
|
When doing a patch release, the process is similar:
|
||||||
|
1. Initially, the version of the latest release is `0.2.0`
|
||||||
|
2. Checkout the `v0.2.x` branch
|
||||||
|
3. Cherry-pick the required non-breaking changes into the `v0.2.x`
|
||||||
|
4. Follow steps 3-7 of the regular release example
|
||||||
294
Cargo.toml
@@ -1,61 +1,277 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "winit"
|
name = "winit"
|
||||||
version = "0.17.0"
|
version = "0.29.11"
|
||||||
authors = ["The winit contributors, Pierre Krieger <pierre.krieger1708@gmail.com>"]
|
authors = ["The winit contributors", "Pierre Krieger <pierre.krieger1708@gmail.com>"]
|
||||||
description = "Cross-platform window creation library."
|
description = "Cross-platform window creation library."
|
||||||
keywords = ["windowing"]
|
keywords = ["windowing"]
|
||||||
license = "Apache-2.0"
|
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
repository = "https://github.com/tomaka/winit"
|
|
||||||
documentation = "https://docs.rs/winit"
|
documentation = "https://docs.rs/winit"
|
||||||
categories = ["gui"]
|
categories = ["gui"]
|
||||||
|
rust-version.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
features = ["icon_loading"]
|
features = [
|
||||||
|
"rwh_04",
|
||||||
|
"rwh_05",
|
||||||
|
"rwh_06",
|
||||||
|
"serde",
|
||||||
|
"mint",
|
||||||
|
# Enabled to get docs to compile
|
||||||
|
"android-native-activity",
|
||||||
|
]
|
||||||
|
# These are all tested in CI
|
||||||
|
targets = [
|
||||||
|
# Windows
|
||||||
|
"i686-pc-windows-msvc",
|
||||||
|
"x86_64-pc-windows-msvc",
|
||||||
|
# macOS
|
||||||
|
"x86_64-apple-darwin",
|
||||||
|
# Unix (X11 & Wayland)
|
||||||
|
"i686-unknown-linux-gnu",
|
||||||
|
"x86_64-unknown-linux-gnu",
|
||||||
|
# iOS
|
||||||
|
"x86_64-apple-ios",
|
||||||
|
# Android
|
||||||
|
"aarch64-linux-android",
|
||||||
|
# Web
|
||||||
|
"wasm32-unknown-unknown",
|
||||||
|
]
|
||||||
|
rustdoc-args = ["--cfg", "docsrs"]
|
||||||
|
|
||||||
|
# Features are documented in either `lib.rs` or under `winit::platform`.
|
||||||
[features]
|
[features]
|
||||||
icon_loading = ["image"]
|
default = ["rwh_06", "x11", "wayland", "wayland-dlopen", "wayland-csd-adwaita"]
|
||||||
|
x11 = ["x11-dl", "bytemuck", "percent-encoding", "xkbcommon-dl/x11", "x11rb"]
|
||||||
|
wayland = ["wayland-client", "wayland-backend", "wayland-protocols", "wayland-protocols-plasma", "sctk", "ahash", "memmap2"]
|
||||||
|
wayland-dlopen = ["wayland-backend/dlopen"]
|
||||||
|
wayland-csd-adwaita = ["sctk-adwaita", "sctk-adwaita/ab_glyph"]
|
||||||
|
wayland-csd-adwaita-crossfont = ["sctk-adwaita", "sctk-adwaita/crossfont"]
|
||||||
|
wayland-csd-adwaita-notitle = ["sctk-adwaita"]
|
||||||
|
android-native-activity = ["android-activity/native-activity"]
|
||||||
|
android-game-activity = ["android-activity/game-activity"]
|
||||||
|
serde = ["dep:serde", "cursor-icon/serde", "smol_str/serde", "dpi/serde"]
|
||||||
|
mint = ["dpi/mint"]
|
||||||
|
rwh_04 = ["dep:rwh_04", "ndk/rwh_04"]
|
||||||
|
rwh_05 = ["dep:rwh_05", "ndk/rwh_05"]
|
||||||
|
rwh_06 = ["dep:rwh_06", "ndk/rwh_06"]
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
cfg_aliases = "0.2.0"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
lazy_static = "1"
|
bitflags = "2"
|
||||||
libc = "0.2"
|
cursor-icon = "1.1.0"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
image = { version = "0.19", optional = true }
|
rwh_04 = { package = "raw-window-handle", version = "0.4", optional = true }
|
||||||
|
rwh_05 = { package = "raw-window-handle", version = "0.5.2", features = ["std"], optional = true }
|
||||||
|
rwh_06 = { package = "raw-window-handle", version = "0.6", features = ["std"], optional = true }
|
||||||
|
serde = { workspace = true, optional = true }
|
||||||
|
smol_str = "0.2.0"
|
||||||
|
dpi = { path = "dpi" }
|
||||||
|
|
||||||
[target.'cfg(target_os = "android")'.dependencies.android_glue]
|
[dev-dependencies]
|
||||||
version = "0.2"
|
image = { version = "0.24.0", default-features = false, features = ["png"] }
|
||||||
|
simple_logger = { version = "4.2.0", default_features = false }
|
||||||
|
winit = { path = ".", features = ["rwh_05"] }
|
||||||
|
|
||||||
[target.'cfg(target_os = "ios")'.dependencies]
|
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dev-dependencies]
|
||||||
objc = "0.2.3"
|
softbuffer = { version = "0.3.0", default-features = false, features = ["x11", "x11-dlopen", "wayland", "wayland-dlopen"] }
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "android")'.dependencies]
|
||||||
|
android-activity = "0.5.0"
|
||||||
|
ndk = { version = "0.8.0", default-features = false }
|
||||||
|
ndk-sys = "0.5.0"
|
||||||
|
|
||||||
|
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
|
||||||
|
core-foundation = "0.9.3"
|
||||||
|
objc2 = "0.5.0"
|
||||||
|
|
||||||
[target.'cfg(target_os = "macos")'.dependencies]
|
[target.'cfg(target_os = "macos")'.dependencies]
|
||||||
objc = "0.2.3"
|
core-graphics = "0.23.1"
|
||||||
cocoa = "0.17"
|
|
||||||
core-foundation = "0.6"
|
|
||||||
core-graphics = "0.16"
|
|
||||||
|
|
||||||
[target.'cfg(target_os = "windows")'.dependencies.winapi]
|
[target.'cfg(target_os = "macos")'.dependencies.icrate]
|
||||||
version = "0.3.5"
|
version = "0.1.0"
|
||||||
features = [
|
features = [
|
||||||
"combaseapi",
|
"dispatch",
|
||||||
"dwmapi",
|
"Foundation",
|
||||||
"hidusage",
|
"Foundation_NSArray",
|
||||||
"libloaderapi",
|
"Foundation_NSAttributedString",
|
||||||
"objbase",
|
"Foundation_NSMutableAttributedString",
|
||||||
"processthreadsapi",
|
"Foundation_NSData",
|
||||||
"shellapi",
|
"Foundation_NSDictionary",
|
||||||
"shellscalingapi",
|
"Foundation_NSString",
|
||||||
"shobjidl_core",
|
"Foundation_NSProcessInfo",
|
||||||
"unknwnbase",
|
"Foundation_NSThread",
|
||||||
"windowsx",
|
"Foundation_NSNumber",
|
||||||
"wingdi",
|
"AppKit",
|
||||||
"winnt",
|
"AppKit_NSAppearance",
|
||||||
"winuser",
|
"AppKit_NSApplication",
|
||||||
|
"AppKit_NSBitmapImageRep",
|
||||||
|
"AppKit_NSButton",
|
||||||
|
"AppKit_NSColor",
|
||||||
|
"AppKit_NSControl",
|
||||||
|
"AppKit_NSCursor",
|
||||||
|
"AppKit_NSEvent",
|
||||||
|
"AppKit_NSGraphicsContext",
|
||||||
|
"AppKit_NSImage",
|
||||||
|
"AppKit_NSImageRep",
|
||||||
|
"AppKit_NSMenu",
|
||||||
|
"AppKit_NSMenuItem",
|
||||||
|
"AppKit_NSPasteboard",
|
||||||
|
"AppKit_NSResponder",
|
||||||
|
"AppKit_NSScreen",
|
||||||
|
"AppKit_NSTextInputContext",
|
||||||
|
"AppKit_NSView",
|
||||||
|
"AppKit_NSWindow",
|
||||||
|
"AppKit_NSWindowTabGroup",
|
||||||
]
|
]
|
||||||
|
|
||||||
[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies]
|
[target.'cfg(target_os = "ios")'.dependencies.icrate]
|
||||||
wayland-client = { version = "0.20.10", features = [ "dlopen", "egl", "cursor"] }
|
version = "0.1.0"
|
||||||
smithay-client-toolkit = "0.2.6"
|
features = [
|
||||||
x11-dl = "2.17.5"
|
"dispatch",
|
||||||
parking_lot = "0.6"
|
"Foundation",
|
||||||
percent-encoding = "1.0"
|
"Foundation_NSArray",
|
||||||
|
"Foundation_NSString",
|
||||||
|
"Foundation_NSProcessInfo",
|
||||||
|
"Foundation_NSThread",
|
||||||
|
"Foundation_NSSet",
|
||||||
|
]
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "windows")'.dependencies]
|
||||||
|
unicode-segmentation = "1.7.1"
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "windows")'.dependencies.windows-sys]
|
||||||
|
version = "0.48"
|
||||||
|
features = [
|
||||||
|
"Win32_Devices_HumanInterfaceDevice",
|
||||||
|
"Win32_Foundation",
|
||||||
|
"Win32_Globalization",
|
||||||
|
"Win32_Graphics_Dwm",
|
||||||
|
"Win32_Graphics_Gdi",
|
||||||
|
"Win32_Media",
|
||||||
|
"Win32_System_Com_StructuredStorage",
|
||||||
|
"Win32_System_Com",
|
||||||
|
"Win32_System_LibraryLoader",
|
||||||
|
"Win32_System_Ole",
|
||||||
|
"Win32_System_SystemInformation",
|
||||||
|
"Win32_System_SystemServices",
|
||||||
|
"Win32_System_Threading",
|
||||||
|
"Win32_System_WindowsProgramming",
|
||||||
|
"Win32_UI_Accessibility",
|
||||||
|
"Win32_UI_Controls",
|
||||||
|
"Win32_UI_HiDpi",
|
||||||
|
"Win32_UI_Input_Ime",
|
||||||
|
"Win32_UI_Input_KeyboardAndMouse",
|
||||||
|
"Win32_UI_Input_Pointer",
|
||||||
|
"Win32_UI_Input_Touch",
|
||||||
|
"Win32_UI_Shell",
|
||||||
|
"Win32_UI_TextServices",
|
||||||
|
"Win32_UI_WindowsAndMessaging",
|
||||||
|
]
|
||||||
|
|
||||||
|
[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies]
|
||||||
|
ahash = { version = "0.8.7", features = ["no-rng"], optional = true }
|
||||||
|
bytemuck = { version = "1.13.1", default-features = false, optional = true }
|
||||||
|
calloop = "0.12.3"
|
||||||
|
libc = "0.2.64"
|
||||||
|
memmap2 = { version = "0.9.0", optional = true }
|
||||||
|
percent-encoding = { version = "2.0", optional = true }
|
||||||
|
rustix = { version = "0.38.4", default-features = false, features = ["std", "system", "thread", "process"] }
|
||||||
|
sctk = { package = "smithay-client-toolkit", version = "0.18.0", default-features = false, features = ["calloop"], optional = true }
|
||||||
|
sctk-adwaita = { version = "0.8.0", default_features = false, optional = true }
|
||||||
|
wayland-backend = { version = "0.3.0", default_features = false, features = ["client_system"], optional = true }
|
||||||
|
wayland-client = { version = "0.31.1", optional = true }
|
||||||
|
wayland-protocols = { version = "0.31.0", features = [ "staging"], optional = true }
|
||||||
|
wayland-protocols-plasma = { version = "0.2.0", features = [ "client" ], optional = true }
|
||||||
|
x11-dl = { version = "2.18.5", optional = true }
|
||||||
|
x11rb = { version = "0.13.0", default-features = false, features = ["allow-unsafe-code", "dl-libxcb", "randr", "resource_manager", "xinput", "xkb"], optional = true }
|
||||||
|
xkbcommon-dl = "0.4.2"
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "redox")'.dependencies]
|
||||||
|
orbclient = { version = "0.3.47", default-features = false }
|
||||||
|
redox_syscall = "0.4.1"
|
||||||
|
|
||||||
|
[target.'cfg(target_family = "wasm")'.dependencies.web_sys]
|
||||||
|
package = "web-sys"
|
||||||
|
version = "0.3.64"
|
||||||
|
features = [
|
||||||
|
'AbortController',
|
||||||
|
'AbortSignal',
|
||||||
|
'Blob',
|
||||||
|
'console',
|
||||||
|
'CssStyleDeclaration',
|
||||||
|
'Document',
|
||||||
|
'DomException',
|
||||||
|
'DomRect',
|
||||||
|
'DomRectReadOnly',
|
||||||
|
'Element',
|
||||||
|
'Event',
|
||||||
|
'EventTarget',
|
||||||
|
'FocusEvent',
|
||||||
|
'HtmlCanvasElement',
|
||||||
|
'HtmlElement',
|
||||||
|
'HtmlImageElement',
|
||||||
|
'ImageBitmap',
|
||||||
|
'ImageBitmapOptions',
|
||||||
|
'ImageBitmapRenderingContext',
|
||||||
|
'ImageData',
|
||||||
|
'IntersectionObserver',
|
||||||
|
'IntersectionObserverEntry',
|
||||||
|
'KeyboardEvent',
|
||||||
|
'MediaQueryList',
|
||||||
|
'MessageChannel',
|
||||||
|
'MessagePort',
|
||||||
|
'Node',
|
||||||
|
'PageTransitionEvent',
|
||||||
|
'PointerEvent',
|
||||||
|
'PremultiplyAlpha',
|
||||||
|
'ResizeObserver',
|
||||||
|
'ResizeObserverBoxOptions',
|
||||||
|
'ResizeObserverEntry',
|
||||||
|
'ResizeObserverOptions',
|
||||||
|
'ResizeObserverSize',
|
||||||
|
'VisibilityState',
|
||||||
|
'Window',
|
||||||
|
'WheelEvent',
|
||||||
|
'Url',
|
||||||
|
]
|
||||||
|
|
||||||
|
[target.'cfg(target_family = "wasm")'.dependencies]
|
||||||
|
js-sys = "0.3.64"
|
||||||
|
pin-project = "1"
|
||||||
|
wasm-bindgen = "0.2"
|
||||||
|
wasm-bindgen-futures = "0.4"
|
||||||
|
web-time = "1"
|
||||||
|
|
||||||
|
[target.'cfg(all(target_family = "wasm", target_feature = "atomics"))'.dependencies]
|
||||||
|
atomic-waker = "1"
|
||||||
|
concurrent-queue = { version = "2", default-features = false }
|
||||||
|
|
||||||
|
[target.'cfg(target_family = "wasm")'.dev-dependencies]
|
||||||
|
console_log = "1"
|
||||||
|
web-sys = { version = "0.3.22", features = ['CanvasRenderingContext2d'] }
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
doc-scrape-examples = true
|
||||||
|
name = "full"
|
||||||
|
|
||||||
|
[workspace]
|
||||||
|
resolver = "2"
|
||||||
|
members = [
|
||||||
|
"dpi",
|
||||||
|
"run-wasm",
|
||||||
|
]
|
||||||
|
|
||||||
|
[workspace.package]
|
||||||
|
rust-version = "1.70.0"
|
||||||
|
repository = "https://github.com/rust-windowing/winit"
|
||||||
|
license = "Apache-2.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[workspace.dependencies]
|
||||||
|
serde = { version = "1", features = ["serde_derive"] }
|
||||||
|
mint = "0.5.6"
|
||||||
|
|||||||
248
FEATURES.md
Normal file
@@ -0,0 +1,248 @@
|
|||||||
|
# Winit Scope
|
||||||
|
|
||||||
|
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:
|
||||||
|
- Desktop
|
||||||
|
- Windows
|
||||||
|
- macOS
|
||||||
|
- Unix
|
||||||
|
- via X11
|
||||||
|
- via Wayland
|
||||||
|
- Redox OS, via Orbital
|
||||||
|
- Mobile
|
||||||
|
- iOS
|
||||||
|
- Android
|
||||||
|
- Web
|
||||||
|
|
||||||
|
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
|
||||||
|
available everywhere. In this context, APIs exposed in winit can be split into different "support tiers":
|
||||||
|
|
||||||
|
- **Core:** Features that are essential to providing a well-formed abstraction over each platform's
|
||||||
|
windowing and input APIs.
|
||||||
|
- **Platform:** Platform-specific features that can't be meaningfully exposed through a common API and
|
||||||
|
cannot be implemented outside of Winit without exposing a significant amount of Winit's internals
|
||||||
|
or interfering with Winit's abstractions.
|
||||||
|
- **Usability:** Features that are not strictly essential to Winit's functionality, but provide meaningful
|
||||||
|
usability improvements and cannot be reasonably implemented in an external crate. These are
|
||||||
|
generally optional and exposed through Cargo features.
|
||||||
|
|
||||||
|
Core features are taken care of by the core Winit maintainers. Platform features are not.
|
||||||
|
When a platform feature is submitted, the submitter is considered the expert in the
|
||||||
|
feature and may be asked to support the feature should it break in the future.
|
||||||
|
|
||||||
|
Winit ***does not*** directly expose functionality for drawing inside windows or creating native
|
||||||
|
menus, but ***does*** commit to providing APIs that higher-level crates can use to implement that
|
||||||
|
functionality.
|
||||||
|
|
||||||
|
## `1.0` and stability
|
||||||
|
|
||||||
|
When all core features are implemented to the satisfaction of the Winit maintainers, Winit 1.0 will
|
||||||
|
be released and the library will enter maintenance mode. For the most part, new core features will not
|
||||||
|
be added past this point. New platform features may be accepted and exposed through point releases.
|
||||||
|
|
||||||
|
### Tier upgrades
|
||||||
|
Some platform features could, in theory, be exposed across multiple platforms, but have not gone
|
||||||
|
through the implementation work necessary to function on all platforms. When one of these features
|
||||||
|
gets implemented across all platforms, a PR can be opened to upgrade the feature to a core feature.
|
||||||
|
If that gets accepted, the platform-specific functions get deprecated and become permanently
|
||||||
|
exposed through the core, cross-platform API.
|
||||||
|
|
||||||
|
# Features
|
||||||
|
|
||||||
|
## Extending this section
|
||||||
|
|
||||||
|
If your PR makes notable changes to Winit's features, please update this section as follows:
|
||||||
|
|
||||||
|
- If your PR adds a new feature, add a brief description to the relevant section. If the feature is a core
|
||||||
|
feature, add a row to the feature matrix and describe what platforms the feature has been implemented on.
|
||||||
|
|
||||||
|
- If your PR begins a new API rework, add a row to the `Pending API Reworks` table. If the PR implements the
|
||||||
|
API rework on all relevant platforms, please move it to the `Completed API Reworks` table.
|
||||||
|
|
||||||
|
- If your PR implements an already-existing feature on a new platform, either mark the feature as *completed*,
|
||||||
|
or mark it as *mostly completed* and link to an issue describing the problems with the implementation.
|
||||||
|
|
||||||
|
## Core
|
||||||
|
|
||||||
|
### Windowing
|
||||||
|
- **Window initialization**: Winit allows the creation of a window
|
||||||
|
- **Providing pointer to init OpenGL**: Winit provides the necessary pointers to initialize a working opengl context
|
||||||
|
- **Providing pointer to init Vulkan**: Same as OpenGL but for Vulkan
|
||||||
|
- **Window decorations**: The windows created by winit are properly decorated, and the decorations can
|
||||||
|
be deactivated
|
||||||
|
- **Window decorations toggle**: Decorations can be turned on or off after window creation
|
||||||
|
- **Window resizing**: The windows created by winit can be resized and generate the appropriate events
|
||||||
|
when they are. The application can precisely control its window size if desired.
|
||||||
|
- **Window resize increments**: When the window gets resized, the application can choose to snap the window's
|
||||||
|
size to specific values.
|
||||||
|
- **Window transparency**: Winit allows the creation of windows with a transparent background.
|
||||||
|
- **Window maximization**: The windows created by winit can be maximized upon creation.
|
||||||
|
- **Window maximization toggle**: The windows created by winit can be maximized and unmaximized after
|
||||||
|
creation.
|
||||||
|
- **Window minimization**: The windows created by winit can be minimized after creation.
|
||||||
|
- **Fullscreen**: The windows created by winit can be put into fullscreen mode.
|
||||||
|
- **Fullscreen toggle**: The windows created by winit can be switched to and from fullscreen after
|
||||||
|
creation.
|
||||||
|
- **Exclusive fullscreen**: Winit allows changing the video mode of the monitor
|
||||||
|
for fullscreen windows and, if applicable, captures the monitor for exclusive
|
||||||
|
use by this application.
|
||||||
|
- **HiDPI support**: Winit assists developers in appropriately scaling HiDPI content.
|
||||||
|
- **Popup / modal windows**: Windows can be created relative to the client area of other windows, and parent
|
||||||
|
windows can be disabled in favor of popup windows. This feature also guarantees that popup windows
|
||||||
|
get drawn above their owner.
|
||||||
|
|
||||||
|
|
||||||
|
### System Information
|
||||||
|
- **Monitor list**: Retrieve the list of monitors and their metadata, including which one is primary.
|
||||||
|
- **Video mode query**: Monitors can be queried for their supported fullscreen video modes (consisting of resolution, refresh rate, and bit depth).
|
||||||
|
|
||||||
|
### Input Handling
|
||||||
|
- **Mouse events**: Generating mouse events associated with pointer motion, click, and scrolling events.
|
||||||
|
- **Mouse set location**: Forcibly changing the location of the pointer.
|
||||||
|
- **Cursor locking**: Locking the cursor inside the window so it cannot move.
|
||||||
|
- **Cursor confining**: Confining the cursor to the window bounds so it cannot leave them.
|
||||||
|
- **Cursor icon**: Changing the cursor icon or hiding the cursor.
|
||||||
|
- **Cursor image**: Changing the cursor to your own image.
|
||||||
|
- **Cursor hittest**: Handle or ignore mouse events for a window.
|
||||||
|
- **Touch events**: Single-touch events.
|
||||||
|
- **Touch pressure**: Touch events contain information about the amount of force being applied.
|
||||||
|
- **Multitouch**: Multi-touch events, including cancellation of a gesture.
|
||||||
|
- **Keyboard events**: Properly processing keyboard events using the user-specified keymap and
|
||||||
|
translating keypresses into UTF-8 characters, handling dead keys and IMEs.
|
||||||
|
- **Drag & Drop**: Dragging content into winit, detecting when content enters, drops, or if the drop is cancelled.
|
||||||
|
- **Raw Device Events**: Capturing input from input devices without any OS filtering.
|
||||||
|
- **Gamepad/Joystick events**: Capturing input from gamepads and joysticks.
|
||||||
|
- **Device movement events**: Capturing input from the device gyroscope and accelerometer.
|
||||||
|
|
||||||
|
## Platform
|
||||||
|
### Windows
|
||||||
|
* Setting the name of the internal window class
|
||||||
|
* Setting the taskbar icon
|
||||||
|
* Setting the parent window
|
||||||
|
* Setting a menu bar
|
||||||
|
* `WS_EX_NOREDIRECTIONBITMAP` support
|
||||||
|
* Theme the title bar according to Windows 10 Dark Mode setting or set a preferred theme
|
||||||
|
* Changing a system-drawn backdrop
|
||||||
|
* Setting the window border color
|
||||||
|
* Setting the title bar background color
|
||||||
|
* Setting the title color
|
||||||
|
* Setting the corner rounding preference
|
||||||
|
|
||||||
|
### macOS
|
||||||
|
* Window activation policy
|
||||||
|
* Window movable by background
|
||||||
|
* Transparent titlebar
|
||||||
|
* Hidden titlebar
|
||||||
|
* Hidden titlebar buttons
|
||||||
|
* Full-size content view
|
||||||
|
* Accepts first mouse
|
||||||
|
* Set a preferred theme and get current theme.
|
||||||
|
|
||||||
|
### Unix
|
||||||
|
* Window urgency
|
||||||
|
* X11 Window Class
|
||||||
|
* X11 Override Redirect Flag
|
||||||
|
* GTK Theme Variant
|
||||||
|
* Base window size
|
||||||
|
* Setting the X11 parent window
|
||||||
|
|
||||||
|
### iOS
|
||||||
|
* Get the `UIScreen` object pointer
|
||||||
|
* Setting the `UIView` hidpi factor
|
||||||
|
* Valid orientations
|
||||||
|
* Home indicator visibility
|
||||||
|
* Status bar visibility and style
|
||||||
|
* Deferring system gestures
|
||||||
|
* Getting the device idiom
|
||||||
|
* Getting the preferred video mode
|
||||||
|
|
||||||
|
### Web
|
||||||
|
* Get if the systems preferred color scheme is "dark"
|
||||||
|
|
||||||
|
## Compatibility Matrix
|
||||||
|
|
||||||
|
Legend:
|
||||||
|
|
||||||
|
- ✔️: Works as intended
|
||||||
|
- ▢: Mostly works, but some bugs are known
|
||||||
|
- ❌: Missing feature or large bugs making it unusable
|
||||||
|
- **N/A**: Not applicable for this platform
|
||||||
|
- ❓: Unknown status
|
||||||
|
|
||||||
|
### Windowing
|
||||||
|
|Feature |Windows|MacOS |Linux x11 |Linux Wayland |Android|iOS |Web |Redox OS|
|
||||||
|
|-------------------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
||||||
|
|Window initialization |✔️ |✔️ |▢[#5] |✔️ |▢[#33]|▢[#33] |✔️ |✔️ |
|
||||||
|
|Providing pointer to init OpenGL |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |
|
||||||
|
|Providing pointer to init Vulkan |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |**N/A**|**N/A** |
|
||||||
|
|Window decorations |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|✔️ |
|
||||||
|
|Window decorations toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||||
|
|Window resizing |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |✔️ |
|
||||||
|
|Window resize increments |❌ |✔️ |✔️ |❌ |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||||
|
|Window transparency |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|N/A |✔️ |
|
||||||
|
|Window blur |❌ |❌ |❌ |✔️ |**N/A**|**N/A**|N/A |❌ |
|
||||||
|
|Window maximization |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||||
|
|Window maximization toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||||
|
|Window minimization |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||||
|
|Fullscreen |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |✔️ |**N/A** |
|
||||||
|
|Fullscreen toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |✔️ |**N/A** |
|
||||||
|
|Exclusive fullscreen |✔️ |✔️ |✔️ |**N/A** |❌ |✔️ |**N/A**|**N/A** |
|
||||||
|
|HiDPI support |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |
|
||||||
|
|Popup windows |❌ |❌ |❌ |❌ |❌ |❌ |**N/A**|**N/A** |
|
||||||
|
|
||||||
|
### System information
|
||||||
|
|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
||||||
|
|---------------- | ----- | ---- | ------- | ----------- | ----- | ------- | -------- | ------ |
|
||||||
|
|Monitor list |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|❌ |
|
||||||
|
|Video mode query |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|❌ |
|
||||||
|
|
||||||
|
### Input handling
|
||||||
|
|Feature |Windows |MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
||||||
|
|----------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
||||||
|
|Mouse events |✔️ |▢[#63] |✔️ |✔️ |**N/A**|**N/A**|✔️ |✔️ |
|
||||||
|
|Mouse set location |✔️ |✔️ |✔️ |✔️(when locked) |**N/A**|**N/A**|**N/A**|**N/A** |
|
||||||
|
|Cursor locking |❌ |✔️ |❌ |✔️ |**N/A**|**N/A**|✔️ |❌ |
|
||||||
|
|Cursor confining |✔️ |❌ |✔️ |✔️ |**N/A**|**N/A**|❌ |❌ |
|
||||||
|
|Cursor icon |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |**N/A** |
|
||||||
|
|Cursor image |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |**N/A** |
|
||||||
|
|Cursor hittest |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|❌ |❌ |
|
||||||
|
|Touch events |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A** |
|
||||||
|
|Touch pressure |✔️ |❌ |❌ |❌ |❌ |✔️ |✔️ |**N/A** |
|
||||||
|
|Multitouch |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |❌ |**N/A** |
|
||||||
|
|Keyboard events |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |✔️ |✔️ |
|
||||||
|
|Drag & Drop |▢[#720] |▢[#720] |▢[#720] |▢[#720] |**N/A**|**N/A**|❓ |**N/A** |
|
||||||
|
|Raw Device Events |▢[#750] |▢[#750] |▢[#750] |❌ |❌ |❌ |❓ |**N/A** |
|
||||||
|
|Gamepad/Joystick events |❌[#804] |❌ |❌ |❌ |❌ |❌ |❓ |**N/A** |
|
||||||
|
|Device movement events |❓ |❓ |❓ |❓ |❌ |❌ |❓ |**N/A** |
|
||||||
|
|Drag window with cursor |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A** |**N/A** |
|
||||||
|
|Resize with cursor |✔️ |❌ |✔️ |✔️ |**N/A**|**N/A**|**N/A** |**N/A** |
|
||||||
|
|
||||||
|
### Pending API Reworks
|
||||||
|
Changes in the API that have been agreed upon but aren't implemented across all platforms.
|
||||||
|
|
||||||
|
|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
||||||
|
|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
||||||
|
|New API for HiDPI ([#315] [#319]) |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |❓ |
|
||||||
|
|Event Loop 2.0 ([#459]) |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |✔️ |
|
||||||
|
|Keyboard Input 2.0 ([#753]) |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |✔️ |✔️ |
|
||||||
|
|
||||||
|
### Completed API Reworks
|
||||||
|
|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS|
|
||||||
|
|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ |
|
||||||
|
|
||||||
|
[#165]: https://github.com/rust-windowing/winit/issues/165
|
||||||
|
[#219]: https://github.com/rust-windowing/winit/issues/219
|
||||||
|
[#242]: https://github.com/rust-windowing/winit/issues/242
|
||||||
|
[#306]: https://github.com/rust-windowing/winit/issues/306
|
||||||
|
[#315]: https://github.com/rust-windowing/winit/issues/315
|
||||||
|
[#319]: https://github.com/rust-windowing/winit/issues/319
|
||||||
|
[#33]: https://github.com/rust-windowing/winit/issues/33
|
||||||
|
[#459]: https://github.com/rust-windowing/winit/issues/459
|
||||||
|
[#5]: https://github.com/rust-windowing/winit/issues/5
|
||||||
|
[#63]: https://github.com/rust-windowing/winit/issues/63
|
||||||
|
[#720]: https://github.com/rust-windowing/winit/issues/720
|
||||||
|
[#721]: https://github.com/rust-windowing/winit/issues/721
|
||||||
|
[#750]: https://github.com/rust-windowing/winit/issues/750
|
||||||
|
[#753]: https://github.com/rust-windowing/winit/issues/753
|
||||||
|
[#804]: https://github.com/rust-windowing/winit/issues/804
|
||||||
25
HALL_OF_CHAMPIONS.md
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
# Hall of Champions
|
||||||
|
|
||||||
|
The winit maintainers would like to recognize the following former winit
|
||||||
|
contributors, without whom winit would not exist in its current form. We thank
|
||||||
|
them deeply for their time and efforts and wish them the best of luck in their
|
||||||
|
future endeavors:
|
||||||
|
|
||||||
|
* [@tomaka]: For creating the winit project and guiding it through its early
|
||||||
|
years of existence.
|
||||||
|
* [@vberger]: For diligently creating the Wayland backend and being its
|
||||||
|
extremely helpful and benevolent maintainer for years.
|
||||||
|
* [@francesca64]: For taking over the responsibility of maintaining almost every
|
||||||
|
winit backend and standardizing HiDPI support across all of them.
|
||||||
|
* [@Osspial]: For heroically landing EventLoop 2.0 and valiantly ushering in a
|
||||||
|
vastly more sustainable era of winit.
|
||||||
|
* [@goddessfreya]: For selflessly taking over maintainership of glutin and her
|
||||||
|
stellar dedication to improving both winit and glutin.
|
||||||
|
* [@ArturKovacs]: For consistently maintaining the macOS backend and for his immense involvement in designing and implementing the new keyboard API.
|
||||||
|
|
||||||
|
[@tomaka]: https://github.com/tomaka
|
||||||
|
[@vberger]: https://github.com/vberger
|
||||||
|
[@francesca64]: https://github.com/francesca64
|
||||||
|
[@Osspial]: https://github.com/Osspial
|
||||||
|
[@goddessfreya]: https://github.com/goddessfreya
|
||||||
|
[@ArturKovacs]: https://github.com/ArturKovacs
|
||||||
72
README.md
@@ -1,56 +1,66 @@
|
|||||||
# winit - Cross-platform window creation and management in Rust
|
# winit - Cross-platform window creation and management in Rust
|
||||||
|
|
||||||
[](https://crates.io/crates/winit)
|
[](https://crates.io/crates/winit)
|
||||||
|
|
||||||
[](https://docs.rs/winit)
|
[](https://docs.rs/winit)
|
||||||
|
[](https://travis-ci.org/tomaka/winit)
|
)](https://rust-windowing.github.io/winit/winit/index.html)
|
||||||
[](https://ci.appveyor.com/project/tomaka/winit/branch/master)
|
[](https://github.com/rust-windowing/winit/actions)
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[dependencies]
|
[dependencies]
|
||||||
winit = "0.17"
|
winit = "0.29.11"
|
||||||
```
|
```
|
||||||
|
|
||||||
## [Documentation](https://docs.rs/winit)
|
## [Documentation](https://docs.rs/winit)
|
||||||
|
|
||||||
|
For features _within_ the scope of winit, see [FEATURES.md](FEATURES.md).
|
||||||
|
|
||||||
|
For features _outside_ the scope of winit, see [Are we GUI Yet?](https://areweguiyet.com/) and [Are we game yet?](https://arewegameyet.rs/), depending on what kind of project you're looking to do.
|
||||||
|
|
||||||
|
## Contact Us
|
||||||
|
|
||||||
|
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).
|
||||||
|
|
||||||
|
The maintainers have a meeting every friday at UTC 15. The meeting notes can be found [here](https://hackmd.io/@winit-meetings).
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
Winit is a window creation and management library. It can create windows and lets you handle
|
Winit is a window creation and management library. It can create windows and lets you handle
|
||||||
events (for example: the window being resized, a key being pressed, a mouse movement, etc.)
|
events (for example: the window being resized, a key being pressed, a mouse movement, etc.)
|
||||||
produced by window.
|
produced by the window.
|
||||||
|
|
||||||
Winit is designed to be a low-level brick in a hierarchy of libraries. Consequently, in order to
|
Winit is designed to be a low-level brick in a hierarchy of libraries. Consequently, in order to
|
||||||
show something on the window you need to use the platform-specific getters provided by winit, or
|
show something on the window you need to use the platform-specific getters provided by winit, or
|
||||||
another library.
|
another library.
|
||||||
|
|
||||||
```rust
|
## MSRV Policy
|
||||||
extern crate winit;
|
|
||||||
|
|
||||||
fn main() {
|
This crate's Minimum Supported Rust Version (MSRV) is **1.70**. Changes to
|
||||||
let mut events_loop = winit::EventsLoop::new();
|
the MSRV will be accompanied by a minor version bump.
|
||||||
let window = winit::Window::new(&events_loop).unwrap();
|
|
||||||
|
As a **tentative** policy, the upper bound of the MSRV is given by the following
|
||||||
|
formula:
|
||||||
|
|
||||||
events_loop.run_forever(|event| {
|
|
||||||
match event {
|
|
||||||
winit::Event::WindowEvent {
|
|
||||||
event: winit::WindowEvent::CloseRequested,
|
|
||||||
..
|
|
||||||
} => winit::ControlFlow::Break,
|
|
||||||
_ => winit::ControlFlow::Continue,
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
min(sid, stable - 3)
|
||||||
|
```
|
||||||
|
|
||||||
|
Where `sid` is the current version of `rustc` provided by [Debian Sid], and
|
||||||
|
`stable` is the latest stable version of Rust. This bound may be broken in case of a major ecosystem shift or a security vulnerability.
|
||||||
|
|
||||||
|
[Debian Sid]: https://packages.debian.org/sid/rustc
|
||||||
|
|
||||||
|
The exception is for the Android platform, where a higher Rust version
|
||||||
|
must be used for certain Android features. In this case, the MSRV will be
|
||||||
|
capped at the latest stable version of Rust minus three. This inconsistency is
|
||||||
|
not reflected in Cargo metadata, as it is not powerful enough to expose this
|
||||||
|
restriction.
|
||||||
|
|
||||||
|
All crates in the [`rust-windowing`] organizations have the
|
||||||
|
same MSRV policy.
|
||||||
|
|
||||||
|
[`rust-windowing`]: https://github.com/rust-windowing
|
||||||
|
|
||||||
### Platform-specific usage
|
### Platform-specific usage
|
||||||
|
|
||||||
#### Emscripten and WebAssembly
|
Check out the [`winit::platform`](https://rust-windowing.github.io/winit/winit/platform/index.html) module for platform-specific usage.
|
||||||
|
|
||||||
Building a binary will yield a `.js` file. In order to use it in an HTML file, you need to:
|
|
||||||
|
|
||||||
- Put a `<canvas id="my_id"></canvas>` element somewhere. A canvas corresponds to a winit "window".
|
|
||||||
- Write a Javascript code that creates a global variable named `Module`. Set `Module.canvas` to
|
|
||||||
the element of the `<canvas>` element (in the example you would retrieve it via `document.getElementById("my_id")`).
|
|
||||||
More information [here](https://kripken.github.io/emscripten-site/docs/api_reference/module.html).
|
|
||||||
- Make sure that you insert the `.js` file generated by Rust after the `Module` variable is created.
|
|
||||||
|
|||||||
24
appveyor.yml
@@ -1,24 +0,0 @@
|
|||||||
environment:
|
|
||||||
matrix:
|
|
||||||
- TARGET: x86_64-pc-windows-msvc
|
|
||||||
CHANNEL: nightly
|
|
||||||
- TARGET: x86_64-pc-windows-msvc
|
|
||||||
CHANNEL: stable
|
|
||||||
- TARGET: x86_64-pc-windows-msvc
|
|
||||||
CHANNEL: 1.24.1
|
|
||||||
- TARGET: i686-pc-windows-msvc
|
|
||||||
CHANNEL: nightly
|
|
||||||
- TARGET: i686-pc-windows-gnu
|
|
||||||
CHANNEL: nightly
|
|
||||||
install:
|
|
||||||
- appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe
|
|
||||||
- rustup-init -yv --default-toolchain %CHANNEL% --default-host %TARGET%
|
|
||||||
- SET PATH=%PATH%;%USERPROFILE%\.cargo\bin
|
|
||||||
- SET PATH=%PATH%;C:\MinGW\bin
|
|
||||||
- rustc -V
|
|
||||||
- cargo -V
|
|
||||||
|
|
||||||
build: false
|
|
||||||
|
|
||||||
test_script:
|
|
||||||
- cargo test --verbose
|
|
||||||
24
build.rs
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
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 },
|
||||||
|
}
|
||||||
|
}
|
||||||
15
clippy.toml
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
disallowed-methods = [
|
||||||
|
{ path = "web_sys::window", reason = "is not available in every context" },
|
||||||
|
{ path = "web_sys::HtmlCanvasElement::width", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
|
{ path = "web_sys::HtmlCanvasElement::height", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
|
{ path = "web_sys::HtmlCanvasElement::set_width", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
|
{ path = "web_sys::HtmlCanvasElement::set_height", reason = "Winit shouldn't touch the internal canvas size" },
|
||||||
|
{ path = "web_sys::Window::document", reason = "cache this to reduce calls to JS" },
|
||||||
|
{ path = "web_sys::Window::get_computed_style", reason = "cache this to reduce calls to JS" },
|
||||||
|
{ path = "web_sys::HtmlElement::style", reason = "cache this to reduce calls to JS" },
|
||||||
|
{ path = "web_sys::Element::request_fullscreen", reason = "Doesn't account for compatibility with Safari" },
|
||||||
|
{ path = "web_sys::Document::exit_fullscreen", reason = "Doesn't account for compatibility with Safari" },
|
||||||
|
{ path = "web_sys::Document::fullscreen_element", reason = "Doesn't account for compatibility with Safari" },
|
||||||
|
{ path = "icrate::AppKit::NSView::visibleRect", reason = "We expose a render target to the user, and visibility is not really relevant to that (and can break if you don't use the rectangle position as well). Use `frame` instead." },
|
||||||
|
{ path = "icrate::AppKit::NSWindow::setFrameTopLeftPoint", reason = "Not sufficient when working with Winit's coordinate system, use `flip_window_screen_coordinates` instead" },
|
||||||
|
]
|
||||||
63
deny.toml
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
# https://embarkstudios.github.io/cargo-deny/
|
||||||
|
# cargo install cargo-deny
|
||||||
|
# cargo update && cargo deny --all-features --log-level error --target aarch64-apple-ios check
|
||||||
|
# Note: running just `cargo deny check` without a `--target` will result in
|
||||||
|
# false positives due to https://github.com/EmbarkStudios/cargo-deny/issues/324
|
||||||
|
targets = [
|
||||||
|
{ triple = "aarch64-apple-ios" },
|
||||||
|
{ triple = "aarch64-linux-android" },
|
||||||
|
{ triple = "i686-pc-windows-gnu" },
|
||||||
|
{ triple = "i686-pc-windows-msvc" },
|
||||||
|
{ triple = "i686-unknown-linux-gnu" },
|
||||||
|
{ triple = "wasm32-unknown-unknown" },
|
||||||
|
{ triple = "x86_64-apple-darwin" },
|
||||||
|
{ triple = "x86_64-apple-ios" },
|
||||||
|
{ triple = "x86_64-pc-windows-gnu" },
|
||||||
|
{ triple = "x86_64-pc-windows-msvc" },
|
||||||
|
{ triple = "x86_64-unknown-linux-gnu" },
|
||||||
|
{ triple = "x86_64-unknown-redox" },
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
[advisories]
|
||||||
|
vulnerability = "deny"
|
||||||
|
unmaintained = "warn"
|
||||||
|
yanked = "deny"
|
||||||
|
ignore = []
|
||||||
|
|
||||||
|
|
||||||
|
[bans]
|
||||||
|
multiple-versions = "deny"
|
||||||
|
wildcards = "allow" # at least until https://github.com/EmbarkStudios/cargo-deny/issues/241 is fixed
|
||||||
|
deny = []
|
||||||
|
skip = [
|
||||||
|
{ name = "raw-window-handle" }, # we intentionally have multiple versions of this
|
||||||
|
{ name = "bitflags" }, # the ecosystem is in the process of migrating.
|
||||||
|
{ name = "libloading" }, # x11rb uses a different version until the next update
|
||||||
|
]
|
||||||
|
skip-tree = []
|
||||||
|
|
||||||
|
|
||||||
|
[licenses]
|
||||||
|
private = { ignore = true }
|
||||||
|
unlicensed = "deny"
|
||||||
|
allow-osi-fsf-free = "neither"
|
||||||
|
confidence-threshold = 0.92 # We want really high confidence when inferring licenses from text
|
||||||
|
copyleft = "deny"
|
||||||
|
allow = [
|
||||||
|
"Apache-2.0 WITH LLVM-exception", # https://spdx.org/licenses/LLVM-exception.html
|
||||||
|
"Apache-2.0", # https://tldrlegal.com/license/apache-license-2.0-(apache-2.0)
|
||||||
|
"BSD-2-Clause", # https://tldrlegal.com/license/bsd-2-clause-license-(freebsd)
|
||||||
|
"BSD-3-Clause", # https://tldrlegal.com/license/bsd-3-clause-license-(revised)
|
||||||
|
"BSL-1.0", # https://tldrlegal.com/license/boost-software-license-1.0-explained
|
||||||
|
"CC0-1.0", # https://creativecommons.org/publicdomain/zero/1.0/
|
||||||
|
"ISC", # https://tldrlegal.com/license/-isc-license
|
||||||
|
"LicenseRef-UFL-1.0", # https://tldrlegal.com/license/ubuntu-font-license,-1.0 - no official SPDX, see https://github.com/emilk/egui/issues/2321
|
||||||
|
"MIT-0", # https://choosealicense.com/licenses/mit-0/
|
||||||
|
"MIT", # https://tldrlegal.com/license/mit-license
|
||||||
|
"MPL-2.0", # https://www.mozilla.org/en-US/MPL/2.0/FAQ/ - see Q11. Used by webpki-roots on Linux.
|
||||||
|
"OFL-1.1", # https://spdx.org/licenses/OFL-1.1.html
|
||||||
|
"OpenSSL", # https://www.openssl.org/source/license.html - used on Linux
|
||||||
|
"Unicode-DFS-2016", # https://spdx.org/licenses/Unicode-DFS-2016.html
|
||||||
|
"Zlib", # https://tldrlegal.com/license/zlib-libpng-license-(zlib)
|
||||||
|
]
|
||||||
11
docs/res/ATTRIBUTION.md
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
# Image Attribution
|
||||||
|
|
||||||
|
These images are used in the documentation of `winit`.
|
||||||
|
|
||||||
|
## keyboard_*.svg
|
||||||
|
|
||||||
|
These files are a modified version of "[ANSI US QWERTY (Windows)](https://commons.wikimedia.org/wiki/File:ANSI_US_QWERTY_(Windows).svg)"
|
||||||
|
by [Tomiĉo] (https://commons.wikimedia.org/wiki/User:Tomi%C4%89o). It was
|
||||||
|
originally released under the [CC-BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/deed.en)
|
||||||
|
License. Minor modifications have been made by [John Nunley](https://github.com/notgull),
|
||||||
|
which have been released under the same license as a derivative work.
|
||||||
1
docs/res/keyboard_left_shift_key.svg
Normal file
|
After Width: | Height: | Size: 73 KiB |
1
docs/res/keyboard_numpad_1_key.svg
Normal file
|
After Width: | Height: | Size: 73 KiB |
1
docs/res/keyboard_right_shift_key.svg
Normal file
|
After Width: | Height: | Size: 73 KiB |
1
docs/res/keyboard_standard_1_key.svg
Normal file
|
After Width: | Height: | Size: 73 KiB |
39
dpi/Cargo.toml
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
[package]
|
||||||
|
name = "dpi"
|
||||||
|
version = "0.0.0"
|
||||||
|
description = "Types for handling UI scaling"
|
||||||
|
keywords = ["DPI", "HiDPI", "scale-factor"]
|
||||||
|
categories = ["gui"]
|
||||||
|
rust-version.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
serde = ["dep:serde"]
|
||||||
|
mint = ["dep:mint"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
serde = { workspace = true, optional = true }
|
||||||
|
mint = { workspace = true, optional = true }
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
features = ["serde", "mint"]
|
||||||
|
# These are all tested in CI
|
||||||
|
targets = [
|
||||||
|
# Windows
|
||||||
|
"i686-pc-windows-msvc",
|
||||||
|
"x86_64-pc-windows-msvc",
|
||||||
|
# macOS
|
||||||
|
"x86_64-apple-darwin",
|
||||||
|
# Unix (X11 & Wayland)
|
||||||
|
"i686-unknown-linux-gnu",
|
||||||
|
"x86_64-unknown-linux-gnu",
|
||||||
|
# iOS
|
||||||
|
"x86_64-apple-ios",
|
||||||
|
# Android
|
||||||
|
"aarch64-linux-android",
|
||||||
|
# Web
|
||||||
|
"wasm32-unknown-unknown",
|
||||||
|
]
|
||||||
|
rustdoc-args = ["--cfg", "docsrs"]
|
||||||
1
dpi/LICENSE
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../LICENSE
|
||||||
939
dpi/src/lib.rs
Normal file
@@ -0,0 +1,939 @@
|
|||||||
|
//! # DPI
|
||||||
|
//!
|
||||||
|
//! ## Why should I care about UI scaling?
|
||||||
|
//!
|
||||||
|
//! Modern computer screens don't have a consistent relationship between resolution and size.
|
||||||
|
//! 1920x1080 is a common resolution for both desktop and mobile screens, despite mobile screens
|
||||||
|
//! typically being less than a quarter the size of their desktop counterparts. Moreover, neither
|
||||||
|
//! desktop nor mobile screens have consistent resolutions within their own size classes - common
|
||||||
|
//! mobile screens range from below 720p to above 1440p, and desktop screens range from 720p to 5K
|
||||||
|
//! and beyond.
|
||||||
|
//!
|
||||||
|
//! Given that, it's a mistake to assume that 2D content will only be displayed on screens with
|
||||||
|
//! a consistent pixel density. If you were to render a 96-pixel-square image on a 1080p screen and
|
||||||
|
//! then render the same image on a similarly-sized 4K screen, the 4K rendition would only take up
|
||||||
|
//! about a quarter of the physical space as it did on the 1080p screen. That issue is especially
|
||||||
|
//! problematic with text rendering, where quarter-sized text becomes a significant legibility
|
||||||
|
//! problem.
|
||||||
|
//!
|
||||||
|
//! Failure to account for the scale factor can create a significantly degraded user experience.
|
||||||
|
//! Most notably, it can make users feel like they have bad eyesight, which will potentially cause
|
||||||
|
//! them to think about growing elderly, resulting in them having an existential crisis. Once users
|
||||||
|
//! enter that state, they will no longer be focused on your application.
|
||||||
|
//!
|
||||||
|
//! ## How should I handle it?
|
||||||
|
//!
|
||||||
|
//! The solution to this problem is to account for the device's *scale factor*. The scale factor is
|
||||||
|
//! the factor UI elements should be scaled by to be consistent with the rest of the user's system -
|
||||||
|
//! for example, a button that's usually 50 pixels across would be 100 pixels across on a device
|
||||||
|
//! with a scale factor of `2.0`, or 75 pixels across with a scale factor of `1.5`.
|
||||||
|
//!
|
||||||
|
//! Many UI systems, such as CSS, expose DPI-dependent units like [points] or [picas]. That's
|
||||||
|
//! usually a mistake since there's no consistent mapping between the scale factor and the screen's
|
||||||
|
//! actual DPI. Unless printing to a physical medium, you should work in scaled pixels rather
|
||||||
|
//! than any DPI-dependent units.
|
||||||
|
//!
|
||||||
|
//! ### Position and Size types
|
||||||
|
//!
|
||||||
|
//! The [`PhysicalPosition`] / [`PhysicalSize`] types correspond with the actual pixels on the
|
||||||
|
//! device, and the [`LogicalPosition`] / [`LogicalSize`] types correspond to the physical pixels
|
||||||
|
//! divided by the scale factor.
|
||||||
|
//!
|
||||||
|
//! The position and size types are generic over their exact pixel type, `P`, to allow the
|
||||||
|
//! API to have integer precision where appropriate (e.g. most window manipulation functions) and
|
||||||
|
//! floating precision when necessary (e.g. logical sizes for fractional scale factors and touch
|
||||||
|
//! input). If `P` is a floating-point type, please do not cast the values with `as {int}`. Doing so
|
||||||
|
//! will truncate the fractional part of the float rather than properly round to the nearest
|
||||||
|
//! integer. Use the provided `cast` function or [`From`]/[`Into`] conversions, which handle the
|
||||||
|
//! rounding properly. Note that precision loss will still occur when rounding from a float to an
|
||||||
|
//! int, although rounding lessens the problem.
|
||||||
|
//!
|
||||||
|
//! ## Cargo Features
|
||||||
|
//!
|
||||||
|
//! This crate provides the following Cargo features:
|
||||||
|
//!
|
||||||
|
//! * `serde`: Enables serialization/deserialization of certain types with
|
||||||
|
//! [Serde](https://crates.io/crates/serde).
|
||||||
|
//! * `mint`: Enables mint (math interoperability standard types) conversions.
|
||||||
|
//!
|
||||||
|
//!
|
||||||
|
//! [points]: https://en.wikipedia.org/wiki/Point_(typography)
|
||||||
|
//! [picas]: https://en.wikipedia.org/wiki/Pica_(typography)
|
||||||
|
|
||||||
|
#![cfg_attr(
|
||||||
|
docsrs,
|
||||||
|
feature(doc_auto_cfg, doc_cfg_hide),
|
||||||
|
doc(cfg_hide(doc, docsrs))
|
||||||
|
)]
|
||||||
|
#![forbid(unsafe_code)]
|
||||||
|
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
pub trait Pixel: Copy + Into<f64> {
|
||||||
|
fn from_f64(f: f64) -> Self;
|
||||||
|
fn cast<P: Pixel>(self) -> P {
|
||||||
|
P::from_f64(self.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Pixel for u8 {
|
||||||
|
fn from_f64(f: f64) -> Self {
|
||||||
|
f.round() as u8
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Pixel for u16 {
|
||||||
|
fn from_f64(f: f64) -> Self {
|
||||||
|
f.round() as u16
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Pixel for u32 {
|
||||||
|
fn from_f64(f: f64) -> Self {
|
||||||
|
f.round() as u32
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Pixel for i8 {
|
||||||
|
fn from_f64(f: f64) -> Self {
|
||||||
|
f.round() as i8
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Pixel for i16 {
|
||||||
|
fn from_f64(f: f64) -> Self {
|
||||||
|
f.round() as i16
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Pixel for i32 {
|
||||||
|
fn from_f64(f: f64) -> Self {
|
||||||
|
f.round() as i32
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Pixel for f32 {
|
||||||
|
fn from_f64(f: f64) -> Self {
|
||||||
|
f as f32
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Pixel for f64 {
|
||||||
|
fn from_f64(f: f64) -> Self {
|
||||||
|
f
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks that the scale factor is a normal positive `f64`.
|
||||||
|
///
|
||||||
|
/// All functions that take a scale factor assert that this will return `true`. If you're sourcing scale factors from
|
||||||
|
/// anywhere other than winit, it's recommended to validate them using this function before passing them to winit;
|
||||||
|
/// otherwise, you risk panics.
|
||||||
|
#[inline]
|
||||||
|
pub fn validate_scale_factor(scale_factor: f64) -> bool {
|
||||||
|
scale_factor.is_sign_positive() && scale_factor.is_normal()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A position represented in logical pixels.
|
||||||
|
///
|
||||||
|
/// The position is stored as floats, so please be careful. Casting floats to integers truncates the
|
||||||
|
/// fractional part, which can cause noticeable issues. To help with that, an `Into<(i32, i32)>`
|
||||||
|
/// implementation is provided which does the rounding for you.
|
||||||
|
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
pub struct LogicalPosition<P> {
|
||||||
|
pub x: P,
|
||||||
|
pub y: P,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P> LogicalPosition<P> {
|
||||||
|
#[inline]
|
||||||
|
pub const fn new(x: P, y: P) -> Self {
|
||||||
|
LogicalPosition { x, y }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel> LogicalPosition<P> {
|
||||||
|
#[inline]
|
||||||
|
pub fn from_physical<T: Into<PhysicalPosition<X>>, X: Pixel>(
|
||||||
|
physical: T,
|
||||||
|
scale_factor: f64,
|
||||||
|
) -> Self {
|
||||||
|
physical.into().to_logical(scale_factor)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn to_physical<X: Pixel>(&self, scale_factor: f64) -> PhysicalPosition<X> {
|
||||||
|
assert!(validate_scale_factor(scale_factor));
|
||||||
|
let x = self.x.into() * scale_factor;
|
||||||
|
let y = self.y.into() * scale_factor;
|
||||||
|
PhysicalPosition::new(x, y).cast()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn cast<X: Pixel>(&self) -> LogicalPosition<X> {
|
||||||
|
LogicalPosition {
|
||||||
|
x: self.x.cast(),
|
||||||
|
y: self.y.cast(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<(X, X)> for LogicalPosition<P> {
|
||||||
|
fn from((x, y): (X, X)) -> LogicalPosition<P> {
|
||||||
|
LogicalPosition::new(x.cast(), y.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<LogicalPosition<P>> for (X, X) {
|
||||||
|
fn from(p: LogicalPosition<P>) -> (X, X) {
|
||||||
|
(p.x.cast(), p.y.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<[X; 2]> for LogicalPosition<P> {
|
||||||
|
fn from([x, y]: [X; 2]) -> LogicalPosition<P> {
|
||||||
|
LogicalPosition::new(x.cast(), y.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<LogicalPosition<P>> for [X; 2] {
|
||||||
|
fn from(p: LogicalPosition<P>) -> [X; 2] {
|
||||||
|
[p.x.cast(), p.y.cast()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "mint")]
|
||||||
|
impl<P: Pixel> From<mint::Point2<P>> for LogicalPosition<P> {
|
||||||
|
fn from(p: mint::Point2<P>) -> Self {
|
||||||
|
Self::new(p.x, p.y)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "mint")]
|
||||||
|
impl<P: Pixel> From<LogicalPosition<P>> for mint::Point2<P> {
|
||||||
|
fn from(p: LogicalPosition<P>) -> Self {
|
||||||
|
mint::Point2 { x: p.x, y: p.y }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A position represented in physical pixels.
|
||||||
|
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
pub struct PhysicalPosition<P> {
|
||||||
|
pub x: P,
|
||||||
|
pub y: P,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P> PhysicalPosition<P> {
|
||||||
|
#[inline]
|
||||||
|
pub const fn new(x: P, y: P) -> Self {
|
||||||
|
PhysicalPosition { x, y }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel> PhysicalPosition<P> {
|
||||||
|
#[inline]
|
||||||
|
pub fn from_logical<T: Into<LogicalPosition<X>>, X: Pixel>(
|
||||||
|
logical: T,
|
||||||
|
scale_factor: f64,
|
||||||
|
) -> Self {
|
||||||
|
logical.into().to_physical(scale_factor)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn to_logical<X: Pixel>(&self, scale_factor: f64) -> LogicalPosition<X> {
|
||||||
|
assert!(validate_scale_factor(scale_factor));
|
||||||
|
let x = self.x.into() / scale_factor;
|
||||||
|
let y = self.y.into() / scale_factor;
|
||||||
|
LogicalPosition::new(x, y).cast()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn cast<X: Pixel>(&self) -> PhysicalPosition<X> {
|
||||||
|
PhysicalPosition {
|
||||||
|
x: self.x.cast(),
|
||||||
|
y: self.y.cast(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<(X, X)> for PhysicalPosition<P> {
|
||||||
|
fn from((x, y): (X, X)) -> PhysicalPosition<P> {
|
||||||
|
PhysicalPosition::new(x.cast(), y.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<PhysicalPosition<P>> for (X, X) {
|
||||||
|
fn from(p: PhysicalPosition<P>) -> (X, X) {
|
||||||
|
(p.x.cast(), p.y.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<[X; 2]> for PhysicalPosition<P> {
|
||||||
|
fn from([x, y]: [X; 2]) -> PhysicalPosition<P> {
|
||||||
|
PhysicalPosition::new(x.cast(), y.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<PhysicalPosition<P>> for [X; 2] {
|
||||||
|
fn from(p: PhysicalPosition<P>) -> [X; 2] {
|
||||||
|
[p.x.cast(), p.y.cast()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "mint")]
|
||||||
|
impl<P: Pixel> From<mint::Point2<P>> for PhysicalPosition<P> {
|
||||||
|
fn from(p: mint::Point2<P>) -> Self {
|
||||||
|
Self::new(p.x, p.y)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "mint")]
|
||||||
|
impl<P: Pixel> From<PhysicalPosition<P>> for mint::Point2<P> {
|
||||||
|
fn from(p: PhysicalPosition<P>) -> Self {
|
||||||
|
mint::Point2 { x: p.x, y: p.y }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A size represented in logical pixels.
|
||||||
|
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
pub struct LogicalSize<P> {
|
||||||
|
pub width: P,
|
||||||
|
pub height: P,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P> LogicalSize<P> {
|
||||||
|
#[inline]
|
||||||
|
pub const fn new(width: P, height: P) -> Self {
|
||||||
|
LogicalSize { width, height }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel> LogicalSize<P> {
|
||||||
|
#[inline]
|
||||||
|
pub fn from_physical<T: Into<PhysicalSize<X>>, X: Pixel>(
|
||||||
|
physical: T,
|
||||||
|
scale_factor: f64,
|
||||||
|
) -> Self {
|
||||||
|
physical.into().to_logical(scale_factor)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn to_physical<X: Pixel>(&self, scale_factor: f64) -> PhysicalSize<X> {
|
||||||
|
assert!(validate_scale_factor(scale_factor));
|
||||||
|
let width = self.width.into() * scale_factor;
|
||||||
|
let height = self.height.into() * scale_factor;
|
||||||
|
PhysicalSize::new(width, height).cast()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn cast<X: Pixel>(&self) -> LogicalSize<X> {
|
||||||
|
LogicalSize {
|
||||||
|
width: self.width.cast(),
|
||||||
|
height: self.height.cast(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<(X, X)> for LogicalSize<P> {
|
||||||
|
fn from((x, y): (X, X)) -> LogicalSize<P> {
|
||||||
|
LogicalSize::new(x.cast(), y.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<LogicalSize<P>> for (X, X) {
|
||||||
|
fn from(s: LogicalSize<P>) -> (X, X) {
|
||||||
|
(s.width.cast(), s.height.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<[X; 2]> for LogicalSize<P> {
|
||||||
|
fn from([x, y]: [X; 2]) -> LogicalSize<P> {
|
||||||
|
LogicalSize::new(x.cast(), y.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<LogicalSize<P>> for [X; 2] {
|
||||||
|
fn from(s: LogicalSize<P>) -> [X; 2] {
|
||||||
|
[s.width.cast(), s.height.cast()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "mint")]
|
||||||
|
impl<P: Pixel> From<mint::Vector2<P>> for LogicalSize<P> {
|
||||||
|
fn from(v: mint::Vector2<P>) -> Self {
|
||||||
|
Self::new(v.x, v.y)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "mint")]
|
||||||
|
impl<P: Pixel> From<LogicalSize<P>> for mint::Vector2<P> {
|
||||||
|
fn from(s: LogicalSize<P>) -> Self {
|
||||||
|
mint::Vector2 {
|
||||||
|
x: s.width,
|
||||||
|
y: s.height,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A size represented in physical pixels.
|
||||||
|
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
pub struct PhysicalSize<P> {
|
||||||
|
pub width: P,
|
||||||
|
pub height: P,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P> PhysicalSize<P> {
|
||||||
|
#[inline]
|
||||||
|
pub const fn new(width: P, height: P) -> Self {
|
||||||
|
PhysicalSize { width, height }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel> PhysicalSize<P> {
|
||||||
|
#[inline]
|
||||||
|
pub fn from_logical<T: Into<LogicalSize<X>>, X: Pixel>(logical: T, scale_factor: f64) -> Self {
|
||||||
|
logical.into().to_physical(scale_factor)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn to_logical<X: Pixel>(&self, scale_factor: f64) -> LogicalSize<X> {
|
||||||
|
assert!(validate_scale_factor(scale_factor));
|
||||||
|
let width = self.width.into() / scale_factor;
|
||||||
|
let height = self.height.into() / scale_factor;
|
||||||
|
LogicalSize::new(width, height).cast()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn cast<X: Pixel>(&self) -> PhysicalSize<X> {
|
||||||
|
PhysicalSize {
|
||||||
|
width: self.width.cast(),
|
||||||
|
height: self.height.cast(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<(X, X)> for PhysicalSize<P> {
|
||||||
|
fn from((x, y): (X, X)) -> PhysicalSize<P> {
|
||||||
|
PhysicalSize::new(x.cast(), y.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<PhysicalSize<P>> for (X, X) {
|
||||||
|
fn from(s: PhysicalSize<P>) -> (X, X) {
|
||||||
|
(s.width.cast(), s.height.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<[X; 2]> for PhysicalSize<P> {
|
||||||
|
fn from([x, y]: [X; 2]) -> PhysicalSize<P> {
|
||||||
|
PhysicalSize::new(x.cast(), y.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel, X: Pixel> From<PhysicalSize<P>> for [X; 2] {
|
||||||
|
fn from(s: PhysicalSize<P>) -> [X; 2] {
|
||||||
|
[s.width.cast(), s.height.cast()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "mint")]
|
||||||
|
impl<P: Pixel> From<mint::Vector2<P>> for PhysicalSize<P> {
|
||||||
|
fn from(v: mint::Vector2<P>) -> Self {
|
||||||
|
Self::new(v.x, v.y)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "mint")]
|
||||||
|
impl<P: Pixel> From<PhysicalSize<P>> for mint::Vector2<P> {
|
||||||
|
fn from(s: PhysicalSize<P>) -> Self {
|
||||||
|
mint::Vector2 {
|
||||||
|
x: s.width,
|
||||||
|
y: s.height,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A size that's either physical or logical.
|
||||||
|
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
pub enum Size {
|
||||||
|
Physical(PhysicalSize<u32>),
|
||||||
|
Logical(LogicalSize<f64>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Size {
|
||||||
|
pub fn new<S: Into<Size>>(size: S) -> Size {
|
||||||
|
size.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_logical<P: Pixel>(&self, scale_factor: f64) -> LogicalSize<P> {
|
||||||
|
match *self {
|
||||||
|
Size::Physical(size) => size.to_logical(scale_factor),
|
||||||
|
Size::Logical(size) => size.cast(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_physical<P: Pixel>(&self, scale_factor: f64) -> PhysicalSize<P> {
|
||||||
|
match *self {
|
||||||
|
Size::Physical(size) => size.cast(),
|
||||||
|
Size::Logical(size) => size.to_physical(scale_factor),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clamp<S: Into<Size>>(input: S, min: S, max: S, scale_factor: f64) -> Size {
|
||||||
|
let (input, min, max) = (
|
||||||
|
input.into().to_physical::<f64>(scale_factor),
|
||||||
|
min.into().to_physical::<f64>(scale_factor),
|
||||||
|
max.into().to_physical::<f64>(scale_factor),
|
||||||
|
);
|
||||||
|
|
||||||
|
let width = input.width.clamp(min.width, max.width);
|
||||||
|
let height = input.height.clamp(min.height, max.height);
|
||||||
|
|
||||||
|
PhysicalSize::new(width, height).into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel> From<PhysicalSize<P>> for Size {
|
||||||
|
#[inline]
|
||||||
|
fn from(size: PhysicalSize<P>) -> Size {
|
||||||
|
Size::Physical(size.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel> From<LogicalSize<P>> for Size {
|
||||||
|
#[inline]
|
||||||
|
fn from(size: LogicalSize<P>) -> Size {
|
||||||
|
Size::Logical(size.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A position that's either physical or logical.
|
||||||
|
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
pub enum Position {
|
||||||
|
Physical(PhysicalPosition<i32>),
|
||||||
|
Logical(LogicalPosition<f64>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Position {
|
||||||
|
pub fn new<S: Into<Position>>(position: S) -> Position {
|
||||||
|
position.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_logical<P: Pixel>(&self, scale_factor: f64) -> LogicalPosition<P> {
|
||||||
|
match *self {
|
||||||
|
Position::Physical(position) => position.to_logical(scale_factor),
|
||||||
|
Position::Logical(position) => position.cast(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_physical<P: Pixel>(&self, scale_factor: f64) -> PhysicalPosition<P> {
|
||||||
|
match *self {
|
||||||
|
Position::Physical(position) => position.cast(),
|
||||||
|
Position::Logical(position) => position.to_physical(scale_factor),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel> From<PhysicalPosition<P>> for Position {
|
||||||
|
#[inline]
|
||||||
|
fn from(position: PhysicalPosition<P>) -> Position {
|
||||||
|
Position::Physical(position.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: Pixel> From<LogicalPosition<P>> for Position {
|
||||||
|
#[inline]
|
||||||
|
fn from(position: LogicalPosition<P>) -> Position {
|
||||||
|
Position::Logical(position.cast())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
macro_rules! test_pixel_int_impl {
|
||||||
|
($($name:ident => $ty:ty),*) => {$(
|
||||||
|
#[test]
|
||||||
|
fn $name() {
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.0),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.4),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.5),
|
||||||
|
38,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.9),
|
||||||
|
38,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u8>(37),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u16>(37),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u32>(37),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i8>(37),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i16>(37),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i32>(37),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
)*};
|
||||||
|
}
|
||||||
|
|
||||||
|
test_pixel_int_impl! {
|
||||||
|
test_pixel_int_u8 => u8,
|
||||||
|
test_pixel_int_u16 => u16,
|
||||||
|
test_pixel_int_u32 => u32,
|
||||||
|
test_pixel_int_i8 => i8,
|
||||||
|
test_pixel_int_i16 => i16
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! assert_approx_eq {
|
||||||
|
($a:expr, $b:expr $(,)?) => {
|
||||||
|
assert!(
|
||||||
|
($a - $b).abs() < 0.001,
|
||||||
|
"{} is not approximately equal to {}",
|
||||||
|
$a,
|
||||||
|
$b
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! test_pixel_float_impl {
|
||||||
|
($($name:ident => $ty:ty),*) => {$(
|
||||||
|
#[test]
|
||||||
|
fn $name() {
|
||||||
|
assert_approx_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.0),
|
||||||
|
37.0,
|
||||||
|
);
|
||||||
|
assert_approx_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.4),
|
||||||
|
37.4,
|
||||||
|
);
|
||||||
|
assert_approx_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.5),
|
||||||
|
37.5,
|
||||||
|
);
|
||||||
|
assert_approx_eq!(
|
||||||
|
<$ty as Pixel>::from_f64(37.9),
|
||||||
|
37.9,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u8>(37.0),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u8>(37.4),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u8>(37.5),
|
||||||
|
38,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u16>(37.0),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u16>(37.4),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u16>(37.5),
|
||||||
|
38,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u32>(37.0),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u32>(37.4),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<u32>(37.5),
|
||||||
|
38,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i8>(37.0),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i8>(37.4),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i8>(37.5),
|
||||||
|
38,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i16>(37.0),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i16>(37.4),
|
||||||
|
37,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
<$ty as Pixel>::cast::<i16>(37.5),
|
||||||
|
38,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
)*};
|
||||||
|
}
|
||||||
|
|
||||||
|
test_pixel_float_impl! {
|
||||||
|
test_pixel_float_f32 => f32,
|
||||||
|
test_pixel_float_f64 => f64
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_validate_scale_factor() {
|
||||||
|
assert!(validate_scale_factor(1.0));
|
||||||
|
assert!(validate_scale_factor(2.0));
|
||||||
|
assert!(validate_scale_factor(3.0));
|
||||||
|
assert!(validate_scale_factor(1.5));
|
||||||
|
assert!(validate_scale_factor(0.5));
|
||||||
|
|
||||||
|
assert!(!validate_scale_factor(0.0));
|
||||||
|
assert!(!validate_scale_factor(-1.0));
|
||||||
|
assert!(!validate_scale_factor(f64::INFINITY));
|
||||||
|
assert!(!validate_scale_factor(f64::NAN));
|
||||||
|
assert!(!validate_scale_factor(f64::NEG_INFINITY));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_logical_position() {
|
||||||
|
let log_pos = LogicalPosition::new(1.0, 2.0);
|
||||||
|
assert_eq!(log_pos.to_physical::<u32>(1.0), PhysicalPosition::new(1, 2));
|
||||||
|
assert_eq!(log_pos.to_physical::<u32>(2.0), PhysicalPosition::new(2, 4));
|
||||||
|
assert_eq!(log_pos.cast::<u32>(), LogicalPosition::new(1, 2));
|
||||||
|
assert_eq!(
|
||||||
|
log_pos,
|
||||||
|
LogicalPosition::from_physical(PhysicalPosition::new(1.0, 2.0), 1.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
log_pos,
|
||||||
|
LogicalPosition::from_physical(PhysicalPosition::new(2.0, 4.0), 2.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
LogicalPosition::from((2.0, 2.0)),
|
||||||
|
LogicalPosition::new(2.0, 2.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
LogicalPosition::from([2.0, 3.0]),
|
||||||
|
LogicalPosition::new(2.0, 3.0)
|
||||||
|
);
|
||||||
|
|
||||||
|
let x: (f64, f64) = log_pos.into();
|
||||||
|
assert_eq!(x, (1.0, 2.0));
|
||||||
|
let x: [f64; 2] = log_pos.into();
|
||||||
|
assert_eq!(x, [1.0, 2.0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_physical_position() {
|
||||||
|
assert_eq!(
|
||||||
|
PhysicalPosition::from_logical(LogicalPosition::new(1.0, 2.0), 1.0),
|
||||||
|
PhysicalPosition::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
PhysicalPosition::from_logical(LogicalPosition::new(2.0, 4.0), 0.5),
|
||||||
|
PhysicalPosition::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
PhysicalPosition::from((2.0, 2.0)),
|
||||||
|
PhysicalPosition::new(2.0, 2.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
PhysicalPosition::from([2.0, 3.0]),
|
||||||
|
PhysicalPosition::new(2.0, 3.0)
|
||||||
|
);
|
||||||
|
|
||||||
|
let x: (f64, f64) = PhysicalPosition::new(1, 2).into();
|
||||||
|
assert_eq!(x, (1.0, 2.0));
|
||||||
|
let x: [f64; 2] = PhysicalPosition::new(1, 2).into();
|
||||||
|
assert_eq!(x, [1.0, 2.0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_logical_size() {
|
||||||
|
let log_size = LogicalSize::new(1.0, 2.0);
|
||||||
|
assert_eq!(log_size.to_physical::<u32>(1.0), PhysicalSize::new(1, 2));
|
||||||
|
assert_eq!(log_size.to_physical::<u32>(2.0), PhysicalSize::new(2, 4));
|
||||||
|
assert_eq!(log_size.cast::<u32>(), LogicalSize::new(1, 2));
|
||||||
|
assert_eq!(
|
||||||
|
log_size,
|
||||||
|
LogicalSize::from_physical(PhysicalSize::new(1.0, 2.0), 1.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
log_size,
|
||||||
|
LogicalSize::from_physical(PhysicalSize::new(2.0, 4.0), 2.0)
|
||||||
|
);
|
||||||
|
assert_eq!(LogicalSize::from((2.0, 2.0)), LogicalSize::new(2.0, 2.0));
|
||||||
|
assert_eq!(LogicalSize::from([2.0, 3.0]), LogicalSize::new(2.0, 3.0));
|
||||||
|
|
||||||
|
let x: (f64, f64) = log_size.into();
|
||||||
|
assert_eq!(x, (1.0, 2.0));
|
||||||
|
let x: [f64; 2] = log_size.into();
|
||||||
|
assert_eq!(x, [1.0, 2.0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_physical_size() {
|
||||||
|
assert_eq!(
|
||||||
|
PhysicalSize::from_logical(LogicalSize::new(1.0, 2.0), 1.0),
|
||||||
|
PhysicalSize::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
PhysicalSize::from_logical(LogicalSize::new(2.0, 4.0), 0.5),
|
||||||
|
PhysicalSize::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(PhysicalSize::from((2.0, 2.0)), PhysicalSize::new(2.0, 2.0));
|
||||||
|
assert_eq!(PhysicalSize::from([2.0, 3.0]), PhysicalSize::new(2.0, 3.0));
|
||||||
|
|
||||||
|
let x: (f64, f64) = PhysicalSize::new(1, 2).into();
|
||||||
|
assert_eq!(x, (1.0, 2.0));
|
||||||
|
let x: [f64; 2] = PhysicalSize::new(1, 2).into();
|
||||||
|
assert_eq!(x, [1.0, 2.0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_size() {
|
||||||
|
assert_eq!(
|
||||||
|
Size::new(PhysicalSize::new(1, 2)),
|
||||||
|
Size::Physical(PhysicalSize::new(1, 2))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Size::new(LogicalSize::new(1.0, 2.0)),
|
||||||
|
Size::Logical(LogicalSize::new(1.0, 2.0))
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
Size::new(PhysicalSize::new(1, 2)).to_logical::<f64>(1.0),
|
||||||
|
LogicalSize::new(1.0, 2.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Size::new(PhysicalSize::new(1, 2)).to_logical::<f64>(2.0),
|
||||||
|
LogicalSize::new(0.5, 1.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Size::new(LogicalSize::new(1.0, 2.0)).to_logical::<f64>(1.0),
|
||||||
|
LogicalSize::new(1.0, 2.0)
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
Size::new(PhysicalSize::new(1, 2)).to_physical::<u32>(1.0),
|
||||||
|
PhysicalSize::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Size::new(PhysicalSize::new(1, 2)).to_physical::<u32>(2.0),
|
||||||
|
PhysicalSize::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Size::new(LogicalSize::new(1.0, 2.0)).to_physical::<u32>(1.0),
|
||||||
|
PhysicalSize::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Size::new(LogicalSize::new(1.0, 2.0)).to_physical::<u32>(2.0),
|
||||||
|
PhysicalSize::new(2, 4)
|
||||||
|
);
|
||||||
|
|
||||||
|
let small = Size::Physical((1, 2).into());
|
||||||
|
let medium = Size::Logical((3, 4).into());
|
||||||
|
let medium_physical = Size::new(medium.to_physical::<u32>(1.0));
|
||||||
|
let large = Size::Physical((5, 6).into());
|
||||||
|
assert_eq!(Size::clamp(medium, small, large, 1.0), medium_physical);
|
||||||
|
assert_eq!(Size::clamp(small, medium, large, 1.0), medium_physical);
|
||||||
|
assert_eq!(Size::clamp(large, small, medium, 1.0), medium_physical);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_position() {
|
||||||
|
assert_eq!(
|
||||||
|
Position::new(PhysicalPosition::new(1, 2)),
|
||||||
|
Position::Physical(PhysicalPosition::new(1, 2))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Position::new(LogicalPosition::new(1.0, 2.0)),
|
||||||
|
Position::Logical(LogicalPosition::new(1.0, 2.0))
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
Position::new(PhysicalPosition::new(1, 2)).to_logical::<f64>(1.0),
|
||||||
|
LogicalPosition::new(1.0, 2.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Position::new(PhysicalPosition::new(1, 2)).to_logical::<f64>(2.0),
|
||||||
|
LogicalPosition::new(0.5, 1.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Position::new(LogicalPosition::new(1.0, 2.0)).to_logical::<f64>(1.0),
|
||||||
|
LogicalPosition::new(1.0, 2.0)
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
Position::new(PhysicalPosition::new(1, 2)).to_physical::<u32>(1.0),
|
||||||
|
PhysicalPosition::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Position::new(PhysicalPosition::new(1, 2)).to_physical::<u32>(2.0),
|
||||||
|
PhysicalPosition::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Position::new(LogicalPosition::new(1.0, 2.0)).to_physical::<u32>(1.0),
|
||||||
|
PhysicalPosition::new(1, 2)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Position::new(LogicalPosition::new(1.0, 2.0)).to_physical::<u32>(2.0),
|
||||||
|
PhysicalPosition::new(2, 4)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Eat coverage for the Debug impls et al
|
||||||
|
#[test]
|
||||||
|
fn ensure_attrs_do_not_panic() {
|
||||||
|
let _ = format!("{:?}", LogicalPosition::<u32>::default().clone());
|
||||||
|
HashSet::new().insert(LogicalPosition::<u32>::default());
|
||||||
|
|
||||||
|
let _ = format!("{:?}", PhysicalPosition::<u32>::default().clone());
|
||||||
|
HashSet::new().insert(PhysicalPosition::<u32>::default());
|
||||||
|
|
||||||
|
let _ = format!("{:?}", LogicalSize::<u32>::default().clone());
|
||||||
|
HashSet::new().insert(LogicalSize::<u32>::default());
|
||||||
|
|
||||||
|
let _ = format!("{:?}", PhysicalSize::<u32>::default().clone());
|
||||||
|
HashSet::new().insert(PhysicalSize::<u32>::default());
|
||||||
|
|
||||||
|
let _ = format!("{:?}", Size::Physical((1, 2).into()).clone());
|
||||||
|
let _ = format!("{:?}", Position::Physical((1, 2).into()).clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
94
examples/child_window.rs
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
#[cfg(all(
|
||||||
|
feature = "rwh_06",
|
||||||
|
any(x11_platform, macos_platform, windows_platform)
|
||||||
|
))]
|
||||||
|
#[allow(deprecated)]
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use winit::dpi::{LogicalPosition, LogicalSize, Position};
|
||||||
|
use winit::event::{ElementState, Event, KeyEvent, WindowEvent};
|
||||||
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
|
use winit::raw_window_handle::HasRawWindowHandle;
|
||||||
|
use winit::window::Window;
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
fn spawn_child_window(parent: &Window, event_loop: &ActiveEventLoop) -> Window {
|
||||||
|
let parent = parent.raw_window_handle().unwrap();
|
||||||
|
let mut window_attributes = Window::default_attributes()
|
||||||
|
.with_title("child window")
|
||||||
|
.with_inner_size(LogicalSize::new(200.0f32, 200.0f32))
|
||||||
|
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
||||||
|
.with_visible(true);
|
||||||
|
// `with_parent_window` is unsafe. Parent window must be a valid window.
|
||||||
|
window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) };
|
||||||
|
|
||||||
|
event_loop.create_window(window_attributes).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut windows = HashMap::new();
|
||||||
|
|
||||||
|
let event_loop: EventLoop<()> = EventLoop::new().unwrap();
|
||||||
|
let mut parent_window_id = None;
|
||||||
|
|
||||||
|
event_loop.run(move |event: Event<()>, event_loop| {
|
||||||
|
match event {
|
||||||
|
Event::Resumed => {
|
||||||
|
let attributes = Window::default_attributes()
|
||||||
|
.with_title("parent window")
|
||||||
|
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
||||||
|
.with_inner_size(LogicalSize::new(640.0f32, 480.0f32));
|
||||||
|
let window = event_loop.create_window(attributes).unwrap();
|
||||||
|
|
||||||
|
parent_window_id = Some(window.id());
|
||||||
|
|
||||||
|
println!("Parent window id: {parent_window_id:?})");
|
||||||
|
windows.insert(window.id(), window);
|
||||||
|
}
|
||||||
|
Event::WindowEvent { window_id, event } => match event {
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
windows.clear();
|
||||||
|
event_loop.exit();
|
||||||
|
}
|
||||||
|
WindowEvent::CursorEntered { device_id: _ } => {
|
||||||
|
// On x11, println when the cursor entered in a window even if the child window is created
|
||||||
|
// by some key inputs.
|
||||||
|
// the child windows are always placed at (0, 0) with size (200, 200) in the parent window,
|
||||||
|
// so we also can see this log when we move the cursor around (200, 200) in parent window.
|
||||||
|
println!("cursor entered in the window {window_id:?}");
|
||||||
|
}
|
||||||
|
WindowEvent::KeyboardInput {
|
||||||
|
event:
|
||||||
|
KeyEvent {
|
||||||
|
state: ElementState::Pressed,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
let parent_window = windows.get(&parent_window_id.unwrap()).unwrap();
|
||||||
|
let child_window = spawn_child_window(parent_window, event_loop);
|
||||||
|
let child_id = child_window.id();
|
||||||
|
println!("Child window created with id: {child_id:?}");
|
||||||
|
windows.insert(child_id, child_window);
|
||||||
|
}
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
if let Some(window) = windows.get(&window_id) {
|
||||||
|
fill::fill_window(window);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
},
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(
|
||||||
|
feature = "rwh_06",
|
||||||
|
not(any(x11_platform, macos_platform, windows_platform))
|
||||||
|
))]
|
||||||
|
fn main() {
|
||||||
|
panic!("This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature enabled.");
|
||||||
|
}
|
||||||
133
examples/control_flow.rs
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
|
use std::thread;
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
use std::time;
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
use web_time as time;
|
||||||
|
|
||||||
|
use simple_logger::SimpleLogger;
|
||||||
|
use winit::{
|
||||||
|
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||||
|
event_loop::{ControlFlow, EventLoop},
|
||||||
|
keyboard::{Key, NamedKey},
|
||||||
|
window::Window,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum Mode {
|
||||||
|
Wait,
|
||||||
|
WaitUntil,
|
||||||
|
Poll,
|
||||||
|
}
|
||||||
|
|
||||||
|
const WAIT_TIME: time::Duration = time::Duration::from_millis(100);
|
||||||
|
const POLL_SLEEP_TIME: time::Duration = time::Duration::from_millis(100);
|
||||||
|
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
|
||||||
|
println!("Press '1' to switch to Wait mode.");
|
||||||
|
println!("Press '2' to switch to WaitUntil mode.");
|
||||||
|
println!("Press '3' to switch to Poll mode.");
|
||||||
|
println!("Press 'R' to toggle request_redraw() calls.");
|
||||||
|
println!("Press 'Esc' to close the window.");
|
||||||
|
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let mut mode = Mode::Wait;
|
||||||
|
let mut request_redraw = false;
|
||||||
|
let mut wait_cancelled = false;
|
||||||
|
let mut close_requested = false;
|
||||||
|
|
||||||
|
let mut window = None;
|
||||||
|
event_loop.run(move |event, event_loop| {
|
||||||
|
use winit::event::StartCause;
|
||||||
|
println!("{event:?}");
|
||||||
|
match event {
|
||||||
|
Event::NewEvents(start_cause) => {
|
||||||
|
wait_cancelled = match start_cause {
|
||||||
|
StartCause::WaitCancelled { .. } => mode == Mode::WaitUntil,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::Resumed => {
|
||||||
|
let window_attributes = Window::default_attributes().with_title(
|
||||||
|
"Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.",
|
||||||
|
);
|
||||||
|
window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||||
|
}
|
||||||
|
Event::WindowEvent { event, .. } => match event {
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
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") => {
|
||||||
|
mode = Mode::Wait;
|
||||||
|
println!("\nmode: {mode:?}\n");
|
||||||
|
}
|
||||||
|
Key::Character("2") => {
|
||||||
|
mode = Mode::WaitUntil;
|
||||||
|
println!("\nmode: {mode:?}\n");
|
||||||
|
}
|
||||||
|
Key::Character("3") => {
|
||||||
|
mode = Mode::Poll;
|
||||||
|
println!("\nmode: {mode:?}\n");
|
||||||
|
}
|
||||||
|
Key::Character("r") => {
|
||||||
|
request_redraw = !request_redraw;
|
||||||
|
println!("\nrequest_redraw: {request_redraw}\n");
|
||||||
|
}
|
||||||
|
Key::Named(NamedKey::Escape) => {
|
||||||
|
close_requested = true;
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
let window = window.as_ref().unwrap();
|
||||||
|
window.pre_present_notify();
|
||||||
|
fill::fill_window(window);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
},
|
||||||
|
Event::AboutToWait => {
|
||||||
|
if request_redraw && !wait_cancelled && !close_requested {
|
||||||
|
window.as_ref().unwrap().request_redraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
match mode {
|
||||||
|
Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
|
||||||
|
Mode::WaitUntil => {
|
||||||
|
if !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 close_requested {
|
||||||
|
event_loop.exit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
extern crate winit;
|
|
||||||
|
|
||||||
use winit::{Event, ElementState, MouseCursor, WindowEvent, KeyboardInput, ControlFlow};
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut events_loop = winit::EventsLoop::new();
|
|
||||||
|
|
||||||
let window = winit::WindowBuilder::new().build(&events_loop).unwrap();
|
|
||||||
window.set_title("A fantastic window!");
|
|
||||||
|
|
||||||
let cursors = [MouseCursor::Default, MouseCursor::Crosshair, MouseCursor::Hand, MouseCursor::Arrow, MouseCursor::Move, MouseCursor::Text, MouseCursor::Wait, MouseCursor::Help, MouseCursor::Progress, MouseCursor::NotAllowed, MouseCursor::ContextMenu, MouseCursor::Cell, MouseCursor::VerticalText, MouseCursor::Alias, MouseCursor::Copy, MouseCursor::NoDrop, MouseCursor::Grab, MouseCursor::Grabbing, MouseCursor::AllScroll, MouseCursor::ZoomIn, MouseCursor::ZoomOut, MouseCursor::EResize, MouseCursor::NResize, MouseCursor::NeResize, MouseCursor::NwResize, MouseCursor::SResize, MouseCursor::SeResize, MouseCursor::SwResize, MouseCursor::WResize, MouseCursor::EwResize, MouseCursor::NsResize, MouseCursor::NeswResize, MouseCursor::NwseResize, MouseCursor::ColResize, MouseCursor::RowResize];
|
|
||||||
let mut cursor_idx = 0;
|
|
||||||
|
|
||||||
events_loop.run_forever(|event| {
|
|
||||||
match event {
|
|
||||||
Event::WindowEvent { event: WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, .. }, .. }, .. } => {
|
|
||||||
println!("Setting cursor to \"{:?}\"", cursors[cursor_idx]);
|
|
||||||
window.set_cursor(cursors[cursor_idx]);
|
|
||||||
if cursor_idx < cursors.len() - 1 {
|
|
||||||
cursor_idx += 1;
|
|
||||||
} else {
|
|
||||||
cursor_idx = 0;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => {
|
|
||||||
return ControlFlow::Break;
|
|
||||||
},
|
|
||||||
_ => ()
|
|
||||||
}
|
|
||||||
ControlFlow::Continue
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
extern crate winit;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut events_loop = winit::EventsLoop::new();
|
|
||||||
|
|
||||||
let window = winit::WindowBuilder::new()
|
|
||||||
.with_title("Super Cursor Grab'n'Hide Simulator 9000")
|
|
||||||
.build(&events_loop)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
events_loop.run_forever(|event| {
|
|
||||||
if let winit::Event::WindowEvent { event, .. } = event {
|
|
||||||
use winit::WindowEvent::*;
|
|
||||||
match event {
|
|
||||||
CloseRequested => return winit::ControlFlow::Break,
|
|
||||||
KeyboardInput {
|
|
||||||
input: winit::KeyboardInput {
|
|
||||||
state: winit::ElementState::Released,
|
|
||||||
virtual_keycode: Some(key),
|
|
||||||
modifiers,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
use winit::VirtualKeyCode::*;
|
|
||||||
match key {
|
|
||||||
Escape => return winit::ControlFlow::Break,
|
|
||||||
G => window.grab_cursor(!modifiers.shift).unwrap(),
|
|
||||||
H => window.hide_cursor(!modifiers.shift),
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
winit::ControlFlow::Continue
|
|
||||||
});
|
|
||||||
}
|
|
||||||
BIN
examples/data/cross.png
Normal file
|
After Width: | Height: | Size: 159 B |
BIN
examples/data/cross2.png
Normal file
|
After Width: | Height: | Size: 129 B |
BIN
examples/data/gradient.png
Normal file
|
After Width: | Height: | Size: 229 B |
|
Before Width: | Height: | Size: 2.9 KiB After Width: | Height: | Size: 2.9 KiB |
847
examples/full.rs
Normal file
@@ -0,0 +1,847 @@
|
|||||||
|
//! An example showcasing various functionality that Winit has.
|
||||||
|
//!
|
||||||
|
//! Often used by Winit developers to test certain functionality, may be a bit
|
||||||
|
//! verbose.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::error::Error;
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
use std::num::NonZeroU32;
|
||||||
|
|
||||||
|
use cursor_icon::CursorIcon;
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
use rwh_05::HasRawDisplayHandle;
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
use softbuffer::{Context, Surface};
|
||||||
|
|
||||||
|
use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize};
|
||||||
|
use winit::event::{DeviceEvent, DeviceId, ElementState, Event, Ime, KeyEvent, WindowEvent};
|
||||||
|
use winit::event::{MouseButton, MouseScrollDelta};
|
||||||
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
|
use winit::keyboard::{Key, ModifiersState};
|
||||||
|
use winit::window::{
|
||||||
|
Cursor, CursorGrabMode, CustomCursor, Fullscreen, Icon, ResizeDirection, Theme,
|
||||||
|
};
|
||||||
|
use winit::window::{Window, WindowId};
|
||||||
|
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
use winit::platform::macos::{OptionAsAlt, WindowAttributesExtMacOS, WindowExtMacOS};
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
use winit::platform::startup_notify::{
|
||||||
|
self, EventLoopExtStartupNotify, WindowAttributesExtStartupNotify, WindowExtStartupNotify,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
let event_loop = EventLoop::<UserEvent>::with_user_event().build()?;
|
||||||
|
let _event_loop_proxy = event_loop.create_proxy();
|
||||||
|
|
||||||
|
// Wire the user event from another thread.
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
// Wake up the `event_loop` once every second and dispatch a custom event
|
||||||
|
// from a different thread.
|
||||||
|
println!("Starting to send user event every second");
|
||||||
|
loop {
|
||||||
|
let _ = _event_loop_proxy.send_event(UserEvent::WakeUp);
|
||||||
|
std::thread::sleep(std::time::Duration::from_secs(1));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut app = Application::new(&event_loop);
|
||||||
|
|
||||||
|
event_loop.run(move |event, event_loop| match event {
|
||||||
|
Event::NewEvents(_) => (),
|
||||||
|
Event::Resumed => {
|
||||||
|
println!("Resumed the event loop");
|
||||||
|
|
||||||
|
// Create initial window.
|
||||||
|
app.create_window(event_loop, None)
|
||||||
|
.expect("failed to create initial window");
|
||||||
|
|
||||||
|
app.print_help();
|
||||||
|
}
|
||||||
|
Event::AboutToWait => {
|
||||||
|
if app.windows.is_empty() {
|
||||||
|
println!("No windows left, exiting...");
|
||||||
|
event_loop.exit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::WindowEvent { window_id, event } => {
|
||||||
|
app.handle_window_event(event_loop, window_id, event)
|
||||||
|
}
|
||||||
|
Event::DeviceEvent { device_id, event } => {
|
||||||
|
app.handle_device_event(event_loop, device_id, event)
|
||||||
|
}
|
||||||
|
Event::UserEvent(event) => {
|
||||||
|
println!("User event: {event:?}");
|
||||||
|
}
|
||||||
|
Event::Suspended | Event::LoopExiting | Event::MemoryWarning => (),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
enum UserEvent {
|
||||||
|
WakeUp,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Application state and event handling.
|
||||||
|
struct Application {
|
||||||
|
/// Custom cursors assets.
|
||||||
|
custom_cursors: Vec<CustomCursor>,
|
||||||
|
/// Application icon.
|
||||||
|
icon: Icon,
|
||||||
|
windows: HashMap<WindowId, WindowState>,
|
||||||
|
/// Drawing context.
|
||||||
|
///
|
||||||
|
/// With OpenGL it could be EGLDisplay.
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
context: Context,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Application {
|
||||||
|
fn new<T>(event_loop: &EventLoop<T>) -> Self {
|
||||||
|
// SAFETY: the context is dropped inside the loop, since the state we're using
|
||||||
|
// is moved inside the closure.
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
let context = unsafe { Context::from_raw(event_loop.raw_display_handle()).unwrap() };
|
||||||
|
|
||||||
|
// You'll have to choose an icon size at your own discretion. On X11, the desired size varies
|
||||||
|
// by WM, and on Windows, you still have to account for screen scaling. Here we use 32px,
|
||||||
|
// since it seems to work well enough in most cases. Be careful about going too high, or
|
||||||
|
// you'll be bitten by the low-quality downscaling built into the WM.
|
||||||
|
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/data/icon.png");
|
||||||
|
|
||||||
|
// Load icon
|
||||||
|
let icon = {
|
||||||
|
let image = image::open(path)
|
||||||
|
.expect("Failed to open icon path")
|
||||||
|
.into_rgba8();
|
||||||
|
let (width, height) = image.dimensions();
|
||||||
|
let rgba = image.into_raw();
|
||||||
|
Icon::from_rgba(rgba, width, height).expect("Failed to open icon")
|
||||||
|
};
|
||||||
|
|
||||||
|
println!("Loading cursor assets");
|
||||||
|
let decode_cursor = |bytes| {
|
||||||
|
let img = image::load_from_memory(bytes).unwrap().to_rgba8();
|
||||||
|
let samples = img.into_flat_samples();
|
||||||
|
let (_, w, h) = samples.extents();
|
||||||
|
let (w, h) = (w as u16, h as u16);
|
||||||
|
CustomCursor::from_rgba(samples.samples, w, h, w / 2, h / 2).unwrap()
|
||||||
|
};
|
||||||
|
let custom_cursors = vec![
|
||||||
|
event_loop.create_custom_cursor(decode_cursor(include_bytes!("data/cross.png"))),
|
||||||
|
event_loop.create_custom_cursor(decode_cursor(include_bytes!("data/cross2.png"))),
|
||||||
|
event_loop.create_custom_cursor(decode_cursor(include_bytes!("data/gradient.png"))),
|
||||||
|
];
|
||||||
|
|
||||||
|
Self {
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
context,
|
||||||
|
custom_cursors,
|
||||||
|
icon,
|
||||||
|
windows: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_window(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &ActiveEventLoop,
|
||||||
|
_tab_id: Option<String>,
|
||||||
|
) -> Result<WindowId, Box<dyn Error>> {
|
||||||
|
// TODO read-out activation token.
|
||||||
|
|
||||||
|
#[allow(unused_mut)]
|
||||||
|
let mut window_attributes = Window::default_attributes()
|
||||||
|
.with_title("Winit window")
|
||||||
|
.with_transparent(true)
|
||||||
|
.with_window_icon(Some(self.icon.clone()));
|
||||||
|
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
if let Some(token) = event_loop.read_token_from_env() {
|
||||||
|
startup_notify::reset_activation_token_env();
|
||||||
|
println!("Using token {:?} to activate a window", token);
|
||||||
|
window_attributes = window_attributes.with_activation_token(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
if let Some(tab_id) = _tab_id {
|
||||||
|
window_attributes = window_attributes.with_tabbing_identifier(&tab_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
let window = event_loop.create_window(window_attributes)?;
|
||||||
|
|
||||||
|
#[cfg(ios_platform)]
|
||||||
|
{
|
||||||
|
use winit::platform::ios::WindowExtIOS;
|
||||||
|
window.recognize_doubletap_gesture(true);
|
||||||
|
window.recognize_pinch_gesture(true);
|
||||||
|
window.recognize_rotation_gesture(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
let surface = {
|
||||||
|
// SAFETY: the surface is dropped before the `window` which
|
||||||
|
// provided it with handle, thus it doesn't outlive it.
|
||||||
|
let mut surface = unsafe { Surface::new(&self.context, &window)? };
|
||||||
|
|
||||||
|
let size = window.inner_size();
|
||||||
|
if let (Some(width), Some(height)) =
|
||||||
|
(NonZeroU32::new(size.width), NonZeroU32::new(size.height))
|
||||||
|
{
|
||||||
|
surface
|
||||||
|
.resize(width, height)
|
||||||
|
.expect("failed to resize inner buffer");
|
||||||
|
};
|
||||||
|
|
||||||
|
surface
|
||||||
|
};
|
||||||
|
|
||||||
|
let theme = window.theme().unwrap_or(Theme::Dark);
|
||||||
|
println!("Theme: {theme:?}");
|
||||||
|
|
||||||
|
// Allow IME out of the box.
|
||||||
|
let ime = true;
|
||||||
|
window.set_ime_allowed(ime);
|
||||||
|
|
||||||
|
let state = WindowState {
|
||||||
|
window,
|
||||||
|
custom_idx: self.custom_cursors.len() - 1,
|
||||||
|
cursor_grab: CursorGrabMode::None,
|
||||||
|
named_idx: 0,
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
surface,
|
||||||
|
theme,
|
||||||
|
ime,
|
||||||
|
cursor_position: Default::default(),
|
||||||
|
cursor_hidden: Default::default(),
|
||||||
|
modifiers: Default::default(),
|
||||||
|
occluded: Default::default(),
|
||||||
|
rotated: Default::default(),
|
||||||
|
zoom: Default::default(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let window_id = state.window.id();
|
||||||
|
println!("Created new window with id={window_id:?}");
|
||||||
|
self.windows.insert(window_id, state);
|
||||||
|
Ok(window_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_action(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, action: Action) {
|
||||||
|
let state = self.windows.get_mut(&window_id).unwrap();
|
||||||
|
let window = &state.window;
|
||||||
|
|
||||||
|
println!("Executing action: {action:?}");
|
||||||
|
match action {
|
||||||
|
Action::CloseWindow => {
|
||||||
|
let _ = self.windows.remove(&window_id);
|
||||||
|
}
|
||||||
|
Action::CreateNewWindow => {
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
if let Err(err) = window.request_activation_token() {
|
||||||
|
println!("Failed to get activation token: {err}");
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Err(err) = self.create_window(event_loop, None) {
|
||||||
|
eprintln!("Error creating new window: {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Action::ToggleResizeIncrements => {
|
||||||
|
let new_increments = match window.resize_increments() {
|
||||||
|
Some(_) => None,
|
||||||
|
None => Some(LogicalSize::new(25.0, 25.0)),
|
||||||
|
};
|
||||||
|
println!("Had increments: {}", new_increments.is_none());
|
||||||
|
window.set_resize_increments(new_increments);
|
||||||
|
}
|
||||||
|
Action::ToggleCursorVisibility => {
|
||||||
|
state.cursor_hidden = !state.cursor_hidden;
|
||||||
|
window.set_cursor_visible(!state.cursor_hidden);
|
||||||
|
}
|
||||||
|
Action::ToggleResizable => {
|
||||||
|
let resizable = window.is_resizable();
|
||||||
|
window.set_resizable(!resizable);
|
||||||
|
}
|
||||||
|
Action::ToggleDecorations => {
|
||||||
|
let decorated = window.is_decorated();
|
||||||
|
window.set_decorations(!decorated);
|
||||||
|
}
|
||||||
|
Action::ToggleFullscreen => {
|
||||||
|
let fullscreen = if window.fullscreen().is_some() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(Fullscreen::Borderless(None))
|
||||||
|
};
|
||||||
|
|
||||||
|
window.set_fullscreen(fullscreen);
|
||||||
|
}
|
||||||
|
Action::ToggleMaximize => {
|
||||||
|
let maximized = window.is_maximized();
|
||||||
|
window.set_maximized(!maximized);
|
||||||
|
}
|
||||||
|
Action::ToggleImeInput => {
|
||||||
|
state.ime = !state.ime;
|
||||||
|
window.set_ime_allowed(state.ime);
|
||||||
|
if let Some(position) = state.ime.then_some(state.cursor_position).flatten() {
|
||||||
|
window.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Action::Minimize => {
|
||||||
|
window.set_minimized(true);
|
||||||
|
}
|
||||||
|
Action::NextCursor => {
|
||||||
|
// Cursor list to cycle through.
|
||||||
|
const CURSORS: &[CursorIcon] = &[
|
||||||
|
CursorIcon::Default,
|
||||||
|
CursorIcon::Crosshair,
|
||||||
|
CursorIcon::Pointer,
|
||||||
|
CursorIcon::Move,
|
||||||
|
CursorIcon::Text,
|
||||||
|
CursorIcon::Wait,
|
||||||
|
CursorIcon::Help,
|
||||||
|
CursorIcon::Progress,
|
||||||
|
CursorIcon::NotAllowed,
|
||||||
|
CursorIcon::ContextMenu,
|
||||||
|
CursorIcon::Cell,
|
||||||
|
CursorIcon::VerticalText,
|
||||||
|
CursorIcon::Alias,
|
||||||
|
CursorIcon::Copy,
|
||||||
|
CursorIcon::NoDrop,
|
||||||
|
CursorIcon::Grab,
|
||||||
|
CursorIcon::Grabbing,
|
||||||
|
CursorIcon::AllScroll,
|
||||||
|
CursorIcon::ZoomIn,
|
||||||
|
CursorIcon::ZoomOut,
|
||||||
|
CursorIcon::EResize,
|
||||||
|
CursorIcon::NResize,
|
||||||
|
CursorIcon::NeResize,
|
||||||
|
CursorIcon::NwResize,
|
||||||
|
CursorIcon::SResize,
|
||||||
|
CursorIcon::SeResize,
|
||||||
|
CursorIcon::SwResize,
|
||||||
|
CursorIcon::WResize,
|
||||||
|
CursorIcon::EwResize,
|
||||||
|
CursorIcon::NsResize,
|
||||||
|
CursorIcon::NeswResize,
|
||||||
|
CursorIcon::NwseResize,
|
||||||
|
CursorIcon::ColResize,
|
||||||
|
CursorIcon::RowResize,
|
||||||
|
];
|
||||||
|
|
||||||
|
// Pick the next cursor
|
||||||
|
state.named_idx = (state.named_idx + 1) % CURSORS.len();
|
||||||
|
println!("Setting cursor to \"{:?}\"", CURSORS[state.named_idx]);
|
||||||
|
window.set_cursor(Cursor::Icon(CURSORS[state.named_idx]));
|
||||||
|
}
|
||||||
|
Action::NextCustomCursor => {
|
||||||
|
state.custom_idx = (state.custom_idx + 1) % self.custom_cursors.len();
|
||||||
|
let cursor = Cursor::Custom(self.custom_cursors[state.custom_idx].clone());
|
||||||
|
window.set_cursor(cursor);
|
||||||
|
}
|
||||||
|
Action::CycleCursorGrab => {
|
||||||
|
state.cursor_grab = match state.cursor_grab {
|
||||||
|
CursorGrabMode::None => CursorGrabMode::Confined,
|
||||||
|
CursorGrabMode::Confined => CursorGrabMode::Locked,
|
||||||
|
CursorGrabMode::Locked => CursorGrabMode::None,
|
||||||
|
};
|
||||||
|
println!("Changing cursor grab mode to {:?}", state.cursor_grab);
|
||||||
|
if let Err(err) = window.set_cursor_grab(state.cursor_grab) {
|
||||||
|
eprintln!("Error setting cursor grab: {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Action::DragWindow => {
|
||||||
|
if let Err(err) = window.drag_window() {
|
||||||
|
println!("Error starting window drag: {err}");
|
||||||
|
} else {
|
||||||
|
println!("Dragging window Window={:?}", window.id());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Action::DragResizeWindow => {
|
||||||
|
let position = match state.cursor_position {
|
||||||
|
Some(position) => position,
|
||||||
|
None => {
|
||||||
|
println!("Drag-resize requires cursor to be inside the window");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// The amount of points around the window.
|
||||||
|
const BORDER_SIZE: f64 = 20.0;
|
||||||
|
|
||||||
|
let win_size = window.inner_size();
|
||||||
|
let border_size = BORDER_SIZE * window.scale_factor();
|
||||||
|
|
||||||
|
let x_direction = if position.x < border_size {
|
||||||
|
ResizeDirection::West
|
||||||
|
} else if position.x > (win_size.width as f64 - border_size) {
|
||||||
|
ResizeDirection::East
|
||||||
|
} else {
|
||||||
|
// Use arbitrary direction instead of None for simplicity.
|
||||||
|
ResizeDirection::SouthEast
|
||||||
|
};
|
||||||
|
|
||||||
|
let y_direction = if position.y < border_size {
|
||||||
|
ResizeDirection::North
|
||||||
|
} else if position.y > (win_size.height as f64 - border_size) {
|
||||||
|
ResizeDirection::South
|
||||||
|
} else {
|
||||||
|
// Use arbitrary direction instead of None for simplicity.
|
||||||
|
ResizeDirection::SouthEast
|
||||||
|
};
|
||||||
|
|
||||||
|
let direction = match (x_direction, y_direction) {
|
||||||
|
(ResizeDirection::West, ResizeDirection::North) => ResizeDirection::NorthWest,
|
||||||
|
(ResizeDirection::West, ResizeDirection::South) => ResizeDirection::SouthWest,
|
||||||
|
(ResizeDirection::West, _) => ResizeDirection::West,
|
||||||
|
(ResizeDirection::East, ResizeDirection::North) => ResizeDirection::NorthEast,
|
||||||
|
(ResizeDirection::East, ResizeDirection::South) => ResizeDirection::SouthEast,
|
||||||
|
(ResizeDirection::East, _) => ResizeDirection::East,
|
||||||
|
(_, ResizeDirection::South) => ResizeDirection::South,
|
||||||
|
(_, ResizeDirection::North) => ResizeDirection::North,
|
||||||
|
_ => return,
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Err(err) = window.drag_resize_window(direction) {
|
||||||
|
println!("Error starting window drag-resize: {err}");
|
||||||
|
} else {
|
||||||
|
println!("Drag-resizing window Window={:?}", window.id());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Action::ShowWindowMenu => {
|
||||||
|
if let Some(position) = state.cursor_position {
|
||||||
|
window.show_window_menu(position);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Action::PrintHelp => self.print_help(),
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
Action::CycleOptionAsAlt => {
|
||||||
|
let new = match window.option_as_alt() {
|
||||||
|
OptionAsAlt::None => OptionAsAlt::OnlyLeft,
|
||||||
|
OptionAsAlt::OnlyLeft => OptionAsAlt::OnlyRight,
|
||||||
|
OptionAsAlt::OnlyRight => OptionAsAlt::Both,
|
||||||
|
OptionAsAlt::Both => OptionAsAlt::None,
|
||||||
|
};
|
||||||
|
println!("Setting option as alt {:?}", new);
|
||||||
|
window.set_option_as_alt(new);
|
||||||
|
}
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
Action::CreateNewTab => {
|
||||||
|
let tab_id = window.tabbing_identifier();
|
||||||
|
if let Err(err) = self.create_window(event_loop, Some(tab_id)) {
|
||||||
|
eprintln!("Error creating new window: {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_window_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &ActiveEventLoop,
|
||||||
|
window_id: WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
let state = match self.windows.get_mut(&window_id) {
|
||||||
|
Some(state) => state,
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
let window = &state.window;
|
||||||
|
|
||||||
|
match event {
|
||||||
|
// Resize the surface to the new size
|
||||||
|
WindowEvent::Resized(_size) => {
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
{
|
||||||
|
let (width, height) =
|
||||||
|
match (NonZeroU32::new(_size.width), NonZeroU32::new(_size.height)) {
|
||||||
|
(Some(width), Some(height)) => (width, height),
|
||||||
|
_ => return,
|
||||||
|
};
|
||||||
|
state
|
||||||
|
.surface
|
||||||
|
.resize(width, height)
|
||||||
|
.expect("failed to resize inner buffer");
|
||||||
|
}
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
|
WindowEvent::Focused(focused) => {
|
||||||
|
if focused {
|
||||||
|
println!("Window={window_id:?} fosused");
|
||||||
|
} else {
|
||||||
|
println!("Window={window_id:?} unfosused");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
|
||||||
|
println!("Window={window_id:?} changed scale to {scale_factor}");
|
||||||
|
}
|
||||||
|
WindowEvent::ThemeChanged(theme) => {
|
||||||
|
println!("Theme changed to {theme:?}");
|
||||||
|
state.theme = theme;
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
// Draw the window contents.
|
||||||
|
|
||||||
|
if state.occluded {
|
||||||
|
println!("Skipping drawing occluded window={:?}", window_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const WHITE: u32 = 0xFFFFFFFF;
|
||||||
|
const DARK_GRAY: u32 = 0xFF181818;
|
||||||
|
|
||||||
|
let color = match state.theme {
|
||||||
|
Theme::Light => WHITE,
|
||||||
|
Theme::Dark => DARK_GRAY,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut buffer = state
|
||||||
|
.surface
|
||||||
|
.buffer_mut()
|
||||||
|
.expect("could not retrieve buffer");
|
||||||
|
buffer.fill(color);
|
||||||
|
window.pre_present_notify();
|
||||||
|
buffer.present().expect("failed presenting to window");
|
||||||
|
}
|
||||||
|
#[cfg(any(android_platform, ios_platform))]
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
println!("Drawing but without rendering...");
|
||||||
|
}
|
||||||
|
// Change window occlusion state.
|
||||||
|
WindowEvent::Occluded(occluded) => {
|
||||||
|
state.occluded = occluded;
|
||||||
|
if !occluded {
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
println!("Closing Window={window_id:?}");
|
||||||
|
self.windows.remove(&window_id);
|
||||||
|
}
|
||||||
|
WindowEvent::ModifiersChanged(modifiers) => {
|
||||||
|
state.modifiers = modifiers.state();
|
||||||
|
println!("Modifiers changed to {:?}", state.modifiers);
|
||||||
|
}
|
||||||
|
WindowEvent::MouseWheel { delta, .. } => match delta {
|
||||||
|
MouseScrollDelta::LineDelta(x, y) => {
|
||||||
|
println!("Mouse wheel Line Delta: ({x},{y})");
|
||||||
|
}
|
||||||
|
MouseScrollDelta::PixelDelta(px) => {
|
||||||
|
println!("Mouse wheel Pixel Delta: ({},{})", px.x, px.y);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
WindowEvent::KeyboardInput {
|
||||||
|
event:
|
||||||
|
KeyEvent {
|
||||||
|
// Dispatch actions only on press.
|
||||||
|
state: ElementState::Pressed,
|
||||||
|
logical_key,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
is_synthetic: false,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
if let Key::Character(ch) = logical_key.as_ref() {
|
||||||
|
let mods = state.modifiers;
|
||||||
|
if let Some(action) = Self::process_key_binding(&ch.to_uppercase(), &mods) {
|
||||||
|
self.handle_action(event_loop, window_id, action);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::KeyboardInput { .. } => {}
|
||||||
|
WindowEvent::MouseInput {
|
||||||
|
button,
|
||||||
|
state: ElementState::Pressed,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
if let Some(action) = Self::process_mouse_binding(button, &state.modifiers) {
|
||||||
|
self.handle_action(event_loop, window_id, action);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::MouseInput { .. } => {}
|
||||||
|
WindowEvent::CursorLeft { .. } => {
|
||||||
|
println!("Cursor left Window={window_id:?}");
|
||||||
|
state.cursor_position = None;
|
||||||
|
}
|
||||||
|
WindowEvent::CursorMoved { position, .. } => {
|
||||||
|
println!("Moved cursor to {position:?}");
|
||||||
|
state.cursor_position = Some(position);
|
||||||
|
if state.ime {
|
||||||
|
window.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::ActivationTokenDone { token: _token, .. } => {
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
{
|
||||||
|
startup_notify::set_activation_token_env(_token);
|
||||||
|
if let Err(err) = self.create_window(event_loop, None) {
|
||||||
|
eprintln!("Error creating new window: {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::Ime(event) => match event {
|
||||||
|
Ime::Enabled => println!("IME enabled for Window={window_id:?}"),
|
||||||
|
Ime::Preedit(text, caret_pos) => {
|
||||||
|
println!("Preedit: {}, with caret at {:?}", text, caret_pos);
|
||||||
|
}
|
||||||
|
Ime::Commit(text) => {
|
||||||
|
println!("Commited: {}", text);
|
||||||
|
}
|
||||||
|
Ime::Disabled => println!("IME disabled for Window={window_id:?}"),
|
||||||
|
},
|
||||||
|
WindowEvent::PinchGesture { delta, .. } => {
|
||||||
|
state.zoom += delta;
|
||||||
|
let zoom = state.zoom;
|
||||||
|
if delta > 0.0 {
|
||||||
|
println!("Zoomed in {delta:.5} (now: {zoom:.5})");
|
||||||
|
} else {
|
||||||
|
println!("Zoomed out {delta:.5} (now: {zoom:.5})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::RotationGesture { delta, .. } => {
|
||||||
|
state.rotated += delta;
|
||||||
|
let rotated = state.rotated;
|
||||||
|
if delta > 0.0 {
|
||||||
|
println!("Rotated counterclockwise {delta:.5} (now: {rotated:.5})");
|
||||||
|
} else {
|
||||||
|
println!("Rotated clockwise {delta:.5} (now: {rotated:.5})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::DoubleTapGesture { .. } => {
|
||||||
|
println!("Smart zoom");
|
||||||
|
}
|
||||||
|
WindowEvent::TouchpadPressure { .. }
|
||||||
|
| WindowEvent::HoveredFileCancelled
|
||||||
|
| WindowEvent::CursorEntered { .. }
|
||||||
|
| WindowEvent::AxisMotion { .. }
|
||||||
|
| WindowEvent::DroppedFile(_)
|
||||||
|
| WindowEvent::HoveredFile(_)
|
||||||
|
| WindowEvent::Destroyed
|
||||||
|
| WindowEvent::Touch(_)
|
||||||
|
| WindowEvent::Moved(_) => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_device_event(&mut self, _: &ActiveEventLoop, _: DeviceId, event: DeviceEvent) {
|
||||||
|
println!("Device event: {event:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Process the key binding.
|
||||||
|
fn process_key_binding(key: &str, mods: &ModifiersState) -> Option<Action> {
|
||||||
|
KEY_BINDINGS.iter().find_map(|binding| {
|
||||||
|
binding
|
||||||
|
.is_triggered_by(&key, mods)
|
||||||
|
.then_some(binding.action)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Process mouse binding.
|
||||||
|
fn process_mouse_binding(button: MouseButton, mods: &ModifiersState) -> Option<Action> {
|
||||||
|
MOUSE_BINDINGS.iter().find_map(|binding| {
|
||||||
|
binding
|
||||||
|
.is_triggered_by(&button, mods)
|
||||||
|
.then_some(binding.action)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn print_help(&self) {
|
||||||
|
fn modifiers_to_string(mods: ModifiersState) -> String {
|
||||||
|
let mut mods_line = String::new();
|
||||||
|
// Always add + since it's printed as a part of the bindings.
|
||||||
|
for (modifier, desc) in [
|
||||||
|
(ModifiersState::SUPER, "Super+"),
|
||||||
|
(ModifiersState::ALT, "Alt+"),
|
||||||
|
(ModifiersState::CONTROL, "Ctrl+"),
|
||||||
|
(ModifiersState::SHIFT, "Shift+"),
|
||||||
|
] {
|
||||||
|
if !mods.contains(modifier) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
mods_line.push_str(desc);
|
||||||
|
}
|
||||||
|
mods_line
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("Keyboard bindings:");
|
||||||
|
for binding in KEY_BINDINGS {
|
||||||
|
println!(
|
||||||
|
"{}{:<10} - {:?} ({})",
|
||||||
|
modifiers_to_string(binding.mods),
|
||||||
|
binding.trigger,
|
||||||
|
binding.action,
|
||||||
|
binding.action.help(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
println!("Mouse bindings:");
|
||||||
|
for binding in MOUSE_BINDINGS {
|
||||||
|
let button_name = match binding.trigger {
|
||||||
|
MouseButton::Left => "LMB",
|
||||||
|
MouseButton::Right => "RMB",
|
||||||
|
MouseButton::Middle => "MMB",
|
||||||
|
MouseButton::Back => "Back",
|
||||||
|
MouseButton::Forward => "Forward",
|
||||||
|
MouseButton::Other(_) => "",
|
||||||
|
};
|
||||||
|
|
||||||
|
println!(
|
||||||
|
"{}{:<10} - {:?} ({})",
|
||||||
|
modifiers_to_string(binding.mods),
|
||||||
|
button_name,
|
||||||
|
binding.action,
|
||||||
|
binding.action.help(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extra state on a window used in this example.
|
||||||
|
struct WindowState {
|
||||||
|
/// The actual Winit window.
|
||||||
|
window: Window,
|
||||||
|
/// IME input.
|
||||||
|
ime: bool,
|
||||||
|
/// Render surface.
|
||||||
|
///
|
||||||
|
/// NOTE: This surface must be dropped before the `Window`.
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
surface: Surface,
|
||||||
|
/// The window theme we're drawing with.
|
||||||
|
theme: Theme,
|
||||||
|
/// Cursor position over the window.
|
||||||
|
cursor_position: Option<PhysicalPosition<f64>>,
|
||||||
|
/// Window modifiers state.
|
||||||
|
modifiers: ModifiersState,
|
||||||
|
/// Occlusion state of the window.
|
||||||
|
occluded: bool,
|
||||||
|
/// Current cursor grab mode.
|
||||||
|
cursor_grab: CursorGrabMode,
|
||||||
|
/// The amount of zoom into window.
|
||||||
|
zoom: f64,
|
||||||
|
/// The amount of rotation of the window.
|
||||||
|
rotated: f32,
|
||||||
|
// Cursor states.
|
||||||
|
named_idx: usize,
|
||||||
|
custom_idx: usize,
|
||||||
|
cursor_hidden: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Binding<T: Eq> {
|
||||||
|
trigger: T,
|
||||||
|
mods: ModifiersState,
|
||||||
|
action: Action,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Eq> Binding<T> {
|
||||||
|
const fn new(trigger: T, mods: ModifiersState, action: Action) -> Self {
|
||||||
|
Self {
|
||||||
|
trigger,
|
||||||
|
mods,
|
||||||
|
action,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_triggered_by(&self, trigger: &T, mods: &ModifiersState) -> bool {
|
||||||
|
&self.trigger == trigger && &self.mods == mods
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper enum describing the different kinds of actions this example can do.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum Action {
|
||||||
|
CloseWindow,
|
||||||
|
ToggleCursorVisibility,
|
||||||
|
CreateNewWindow,
|
||||||
|
ToggleResizeIncrements,
|
||||||
|
ToggleImeInput,
|
||||||
|
ToggleDecorations,
|
||||||
|
ToggleResizable,
|
||||||
|
ToggleFullscreen,
|
||||||
|
ToggleMaximize,
|
||||||
|
Minimize,
|
||||||
|
NextCursor,
|
||||||
|
NextCustomCursor,
|
||||||
|
CycleCursorGrab,
|
||||||
|
PrintHelp,
|
||||||
|
DragWindow,
|
||||||
|
DragResizeWindow,
|
||||||
|
ShowWindowMenu,
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
CycleOptionAsAlt,
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
CreateNewTab,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Action {
|
||||||
|
fn help(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Action::CloseWindow => "Close window",
|
||||||
|
Action::ToggleCursorVisibility => "Hide cursor",
|
||||||
|
Action::CreateNewWindow => "Create new window",
|
||||||
|
Action::ToggleImeInput => "Toggle IME input",
|
||||||
|
Action::ToggleDecorations => "Toggle decorations",
|
||||||
|
Action::ToggleResizable => "Toggle window resizable state",
|
||||||
|
Action::ToggleFullscreen => "Toggle fullscreen",
|
||||||
|
Action::ToggleMaximize => "Maximize",
|
||||||
|
Action::Minimize => "Minimize",
|
||||||
|
Action::ToggleResizeIncrements => "Use resize increments when resizing window",
|
||||||
|
Action::NextCursor => "Advance the cursor to the next value",
|
||||||
|
Action::NextCustomCursor => "Advance custom cursor to the next value",
|
||||||
|
Action::CycleCursorGrab => "Cycle through cursor grab mode",
|
||||||
|
Action::PrintHelp => "Print help",
|
||||||
|
Action::DragWindow => "Start window drag",
|
||||||
|
Action::DragResizeWindow => "Start window drag-resize",
|
||||||
|
Action::ShowWindowMenu => "Show window menu",
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
Action::CycleOptionAsAlt => "Cycle option as alt mode",
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
Action::CreateNewTab => "Create new tab",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const KEY_BINDINGS: &[Binding<&'static str>] = &[
|
||||||
|
Binding::new("Q", ModifiersState::CONTROL, Action::CloseWindow),
|
||||||
|
Binding::new("H", ModifiersState::CONTROL, Action::PrintHelp),
|
||||||
|
Binding::new("F", ModifiersState::CONTROL, Action::ToggleFullscreen),
|
||||||
|
Binding::new("D", ModifiersState::CONTROL, Action::ToggleDecorations),
|
||||||
|
Binding::new("I", ModifiersState::CONTROL, Action::ToggleImeInput),
|
||||||
|
Binding::new("L", ModifiersState::CONTROL, Action::CycleCursorGrab),
|
||||||
|
Binding::new("P", ModifiersState::CONTROL, Action::ToggleResizeIncrements),
|
||||||
|
Binding::new("R", ModifiersState::CONTROL, Action::ToggleResizable),
|
||||||
|
// M.
|
||||||
|
Binding::new("M", ModifiersState::CONTROL, Action::ToggleMaximize),
|
||||||
|
Binding::new("M", ModifiersState::ALT, Action::Minimize),
|
||||||
|
// N.
|
||||||
|
Binding::new("N", ModifiersState::CONTROL, Action::CreateNewWindow),
|
||||||
|
// C.
|
||||||
|
Binding::new("C", ModifiersState::CONTROL, Action::NextCursor),
|
||||||
|
Binding::new("C", ModifiersState::ALT, Action::NextCustomCursor),
|
||||||
|
Binding::new("Z", ModifiersState::CONTROL, Action::ToggleCursorVisibility),
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
Binding::new("T", ModifiersState::SUPER, Action::CreateNewTab),
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
Binding::new("O", ModifiersState::CONTROL, Action::CycleOptionAsAlt),
|
||||||
|
];
|
||||||
|
|
||||||
|
const MOUSE_BINDINGS: &[Binding<MouseButton>] = &[
|
||||||
|
Binding::new(
|
||||||
|
MouseButton::Left,
|
||||||
|
ModifiersState::ALT,
|
||||||
|
Action::DragResizeWindow,
|
||||||
|
),
|
||||||
|
Binding::new(
|
||||||
|
MouseButton::Left,
|
||||||
|
ModifiersState::CONTROL,
|
||||||
|
Action::DragWindow,
|
||||||
|
),
|
||||||
|
Binding::new(
|
||||||
|
MouseButton::Right,
|
||||||
|
ModifiersState::CONTROL,
|
||||||
|
Action::ShowWindowMenu,
|
||||||
|
),
|
||||||
|
];
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
extern crate winit;
|
|
||||||
|
|
||||||
use std::io::{self, Write};
|
|
||||||
use winit::{ControlFlow, Event, WindowEvent};
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut events_loop = winit::EventsLoop::new();
|
|
||||||
|
|
||||||
// enumerating monitors
|
|
||||||
let monitor = {
|
|
||||||
for (num, monitor) in events_loop.get_available_monitors().enumerate() {
|
|
||||||
println!("Monitor #{}: {:?}", num, monitor.get_name());
|
|
||||||
}
|
|
||||||
|
|
||||||
print!("Please write the number of the monitor to use: ");
|
|
||||||
io::stdout().flush().unwrap();
|
|
||||||
|
|
||||||
let mut num = String::new();
|
|
||||||
io::stdin().read_line(&mut num).unwrap();
|
|
||||||
let num = num.trim().parse().ok().expect("Please enter a number");
|
|
||||||
let monitor = events_loop.get_available_monitors().nth(num).expect("Please enter a valid ID");
|
|
||||||
|
|
||||||
println!("Using {:?}", monitor.get_name());
|
|
||||||
|
|
||||||
monitor
|
|
||||||
};
|
|
||||||
|
|
||||||
let window = winit::WindowBuilder::new()
|
|
||||||
.with_title("Hello world!")
|
|
||||||
.with_fullscreen(Some(monitor))
|
|
||||||
.build(&events_loop)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let mut is_fullscreen = true;
|
|
||||||
let mut is_maximized = false;
|
|
||||||
let mut decorations = true;
|
|
||||||
|
|
||||||
events_loop.run_forever(|event| {
|
|
||||||
println!("{:?}", event);
|
|
||||||
|
|
||||||
match event {
|
|
||||||
Event::WindowEvent { event, .. } => match event {
|
|
||||||
WindowEvent::CloseRequested => return ControlFlow::Break,
|
|
||||||
WindowEvent::KeyboardInput {
|
|
||||||
input:
|
|
||||||
winit::KeyboardInput {
|
|
||||||
virtual_keycode: Some(virtual_code),
|
|
||||||
state,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
} => match (virtual_code, state) {
|
|
||||||
(winit::VirtualKeyCode::Escape, _) => return ControlFlow::Break,
|
|
||||||
(winit::VirtualKeyCode::F, winit::ElementState::Pressed) => {
|
|
||||||
is_fullscreen = !is_fullscreen;
|
|
||||||
if !is_fullscreen {
|
|
||||||
window.set_fullscreen(None);
|
|
||||||
} else {
|
|
||||||
window.set_fullscreen(Some(window.get_current_monitor()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
(winit::VirtualKeyCode::M, winit::ElementState::Pressed) => {
|
|
||||||
is_maximized = !is_maximized;
|
|
||||||
window.set_maximized(is_maximized);
|
|
||||||
}
|
|
||||||
(winit::VirtualKeyCode::D, winit::ElementState::Pressed) => {
|
|
||||||
decorations = !decorations;
|
|
||||||
window.set_decorations(decorations);
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
},
|
|
||||||
_ => (),
|
|
||||||
},
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
ControlFlow::Continue
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
extern crate winit;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut events_loop = winit::EventsLoop::new();
|
|
||||||
|
|
||||||
let _window = winit::WindowBuilder::new()
|
|
||||||
.with_title("Your faithful window")
|
|
||||||
.build(&events_loop)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let mut close_requested = false;
|
|
||||||
|
|
||||||
events_loop.run_forever(|event| {
|
|
||||||
use winit::WindowEvent::*;
|
|
||||||
use winit::ElementState::Released;
|
|
||||||
use winit::VirtualKeyCode::{N, Y};
|
|
||||||
|
|
||||||
match event {
|
|
||||||
winit::Event::WindowEvent { event, .. } => match event {
|
|
||||||
CloseRequested => {
|
|
||||||
// `CloseRequested` is sent when the close button on the window is pressed (or
|
|
||||||
// through whatever other mechanisms the window manager provides for closing a
|
|
||||||
// window). If you don't handle this event, the close button won't actually do
|
|
||||||
// anything.
|
|
||||||
|
|
||||||
// A common thing to do here is prompt the user if they have unsaved work.
|
|
||||||
// Creating a proper dialog box for that is far beyond the scope of this
|
|
||||||
// example, so here we'll just respond to the Y and N keys.
|
|
||||||
println!("Are you ready to bid your window farewell? [Y/N]");
|
|
||||||
close_requested = true;
|
|
||||||
|
|
||||||
// In applications where you can safely close the window without further
|
|
||||||
// action from the user, this is generally where you'd handle cleanup before
|
|
||||||
// closing the window. How to close the window is detailed in the handler for
|
|
||||||
// the Y key.
|
|
||||||
}
|
|
||||||
KeyboardInput {
|
|
||||||
input:
|
|
||||||
winit::KeyboardInput {
|
|
||||||
virtual_keycode: Some(virtual_code),
|
|
||||||
state: Released,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
} => match virtual_code {
|
|
||||||
Y => {
|
|
||||||
if close_requested {
|
|
||||||
// This is where you'll want to do any cleanup you need.
|
|
||||||
println!("Buh-bye!");
|
|
||||||
|
|
||||||
// For a single-window application like this, you'd normally just
|
|
||||||
// break out of the event loop here. If you wanted to keep running the
|
|
||||||
// event loop (i.e. if it's a multi-window application), you need to
|
|
||||||
// drop the window. That closes it, and results in `Destroyed` being
|
|
||||||
// sent.
|
|
||||||
return winit::ControlFlow::Break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
N => {
|
|
||||||
if close_requested {
|
|
||||||
println!("Your window will continue to stay by your side.");
|
|
||||||
close_requested = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
},
|
|
||||||
_ => (),
|
|
||||||
},
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
|
|
||||||
winit::ControlFlow::Continue
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
extern crate winit;
|
|
||||||
|
|
||||||
use winit::dpi::LogicalSize;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut events_loop = winit::EventsLoop::new();
|
|
||||||
|
|
||||||
let window = winit::WindowBuilder::new()
|
|
||||||
.build(&events_loop)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
window.set_min_dimensions(Some(LogicalSize::new(400.0, 200.0)));
|
|
||||||
window.set_max_dimensions(Some(LogicalSize::new(800.0, 400.0)));
|
|
||||||
|
|
||||||
events_loop.run_forever(|event| {
|
|
||||||
println!("{:?}", event);
|
|
||||||
|
|
||||||
match event {
|
|
||||||
winit::Event::WindowEvent { event: winit::WindowEvent::CloseRequested, .. } => winit::ControlFlow::Break,
|
|
||||||
_ => winit::ControlFlow::Continue,
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
extern crate winit;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let event_loop = winit::EventsLoop::new();
|
|
||||||
let window = winit::WindowBuilder::new().build(&event_loop).unwrap();
|
|
||||||
println!("{:#?}\nPrimary: {:#?}", window.get_available_monitors(), window.get_primary_monitor());
|
|
||||||
}
|
|
||||||
62
examples/monitors.rs
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use winit::{
|
||||||
|
event::{Event, StartCause},
|
||||||
|
event_loop::{ActiveEventLoop, EventLoop},
|
||||||
|
};
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
let event_loop = EventLoop::new()?;
|
||||||
|
|
||||||
|
Ok(event_loop.run(|event, event_loop| match event {
|
||||||
|
Event::NewEvents(StartCause::Init) => {
|
||||||
|
dump_monitors(event_loop);
|
||||||
|
event_loop.exit()
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
})?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dump_monitors(event_loop: &ActiveEventLoop) {
|
||||||
|
println!("Monitors information");
|
||||||
|
let primary_monitor = event_loop.primary_monitor();
|
||||||
|
for monitor in event_loop.available_monitors() {
|
||||||
|
let intro = if primary_monitor.as_ref() == Some(&monitor) {
|
||||||
|
"Primary monitor"
|
||||||
|
} else {
|
||||||
|
"Monitor"
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(name) = monitor.name() {
|
||||||
|
println!("{intro}: {name}");
|
||||||
|
} else {
|
||||||
|
println!("{intro}: [no name]");
|
||||||
|
}
|
||||||
|
|
||||||
|
let size = monitor.size();
|
||||||
|
print!(" Current mode: {}x{}", size.width, size.height);
|
||||||
|
if let Some(m_hz) = monitor.refresh_rate_millihertz() {
|
||||||
|
println!(" @ {}.{} Hz", m_hz / 1000, m_hz % 1000);
|
||||||
|
} else {
|
||||||
|
println!();
|
||||||
|
}
|
||||||
|
|
||||||
|
let position = monitor.position();
|
||||||
|
println!(" Position: {}, {}", position.x, position.y);
|
||||||
|
|
||||||
|
println!(" Scale factor: {}", monitor.scale_factor());
|
||||||
|
|
||||||
|
println!(" Available modes (width x height x bit-depth):");
|
||||||
|
for mode in monitor.video_modes() {
|
||||||
|
let size = mode.size();
|
||||||
|
let m_hz = mode.refresh_rate_millihertz();
|
||||||
|
println!(
|
||||||
|
" {:04}x{:04}x{:02} @ {:>3}.{} Hz",
|
||||||
|
size.width,
|
||||||
|
size.height,
|
||||||
|
mode.bit_depth(),
|
||||||
|
m_hz / 1000,
|
||||||
|
m_hz % 1000
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
extern crate winit;
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut events_loop = winit::EventsLoop::new();
|
|
||||||
|
|
||||||
let mut windows = HashMap::new();
|
|
||||||
for _ in 0..3 {
|
|
||||||
let window = winit::Window::new(&events_loop).unwrap();
|
|
||||||
windows.insert(window.id(), window);
|
|
||||||
}
|
|
||||||
|
|
||||||
events_loop.run_forever(|event| {
|
|
||||||
match event {
|
|
||||||
winit::Event::WindowEvent {
|
|
||||||
event: winit::WindowEvent::CloseRequested,
|
|
||||||
window_id,
|
|
||||||
} => {
|
|
||||||
println!("Window {:?} has received the signal to close", window_id);
|
|
||||||
|
|
||||||
// This drops the window, causing it to close.
|
|
||||||
windows.remove(&window_id);
|
|
||||||
|
|
||||||
if windows.is_empty() {
|
|
||||||
return winit::ControlFlow::Break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
winit::ControlFlow::Continue
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
extern crate winit;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut events_loop = winit::EventsLoop::new();
|
|
||||||
|
|
||||||
let _window = winit::WindowBuilder::new()
|
|
||||||
.with_title("A fantastic window!")
|
|
||||||
.build(&events_loop)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let proxy = events_loop.create_proxy();
|
|
||||||
|
|
||||||
std::thread::spawn(move || {
|
|
||||||
// Wake up the `events_loop` once every second.
|
|
||||||
loop {
|
|
||||||
std::thread::sleep(std::time::Duration::from_secs(1));
|
|
||||||
proxy.wakeup().unwrap();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
events_loop.run_forever(|event| {
|
|
||||||
println!("{:?}", event);
|
|
||||||
match event {
|
|
||||||
winit::Event::WindowEvent { event: winit::WindowEvent::CloseRequested, .. } =>
|
|
||||||
winit::ControlFlow::Break,
|
|
||||||
_ => winit::ControlFlow::Continue,
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
76
examples/pump_events.rs
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
|
// Limit this example to only compatible platforms.
|
||||||
|
#[cfg(any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform,
|
||||||
|
android_platform,
|
||||||
|
))]
|
||||||
|
fn main() -> std::process::ExitCode {
|
||||||
|
use std::{process::ExitCode, thread::sleep, time::Duration};
|
||||||
|
|
||||||
|
use simple_logger::SimpleLogger;
|
||||||
|
use winit::{
|
||||||
|
event::{Event, WindowEvent},
|
||||||
|
event_loop::EventLoop,
|
||||||
|
platform::pump_events::{EventLoopExtPumpEvents, PumpStatus},
|
||||||
|
window::Window,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
let mut event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
|
||||||
|
let mut window = None;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let timeout = Some(Duration::ZERO);
|
||||||
|
let status = event_loop.pump_events(timeout, |event, event_loop| {
|
||||||
|
if let Event::WindowEvent { event, .. } = &event {
|
||||||
|
// Print only Window events to reduce noise
|
||||||
|
println!("{event:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
match event {
|
||||||
|
Event::Resumed => {
|
||||||
|
let window_attributes =
|
||||||
|
Window::default_attributes().with_title("A fantastic window!");
|
||||||
|
window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||||
|
}
|
||||||
|
Event::WindowEvent { event, .. } => {
|
||||||
|
let window = window.as_ref().unwrap();
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => event_loop.exit(),
|
||||||
|
WindowEvent::RedrawRequested => fill::fill_window(window),
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::AboutToWait => {
|
||||||
|
window.as_ref().unwrap().request_redraw();
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
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.");
|
||||||
|
}
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
extern crate winit;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut events_loop = winit::EventsLoop::new();
|
|
||||||
|
|
||||||
let mut resizable = false;
|
|
||||||
|
|
||||||
let window = winit::WindowBuilder::new()
|
|
||||||
.with_title("Hit space to toggle resizability.")
|
|
||||||
.with_dimensions((400, 200).into())
|
|
||||||
.with_resizable(resizable)
|
|
||||||
.build(&events_loop)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
events_loop.run_forever(|event| {
|
|
||||||
match event {
|
|
||||||
winit::Event::WindowEvent { event, .. } => match event {
|
|
||||||
winit::WindowEvent::CloseRequested => return winit::ControlFlow::Break,
|
|
||||||
winit::WindowEvent::KeyboardInput {
|
|
||||||
input:
|
|
||||||
winit::KeyboardInput {
|
|
||||||
virtual_keycode: Some(winit::VirtualKeyCode::Space),
|
|
||||||
state: winit::ElementState::Released,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
resizable = !resizable;
|
|
||||||
println!("Resizable: {}", resizable);
|
|
||||||
window.set_resizable(resizable);
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
},
|
|
||||||
_ => (),
|
|
||||||
};
|
|
||||||
winit::ControlFlow::Continue
|
|
||||||
});
|
|
||||||
}
|
|
||||||
92
examples/run_on_demand.rs
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
|
// Limit this example to only compatible platforms.
|
||||||
|
#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform,))]
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use simple_logger::SimpleLogger;
|
||||||
|
|
||||||
|
use winit::{
|
||||||
|
error::EventLoopError,
|
||||||
|
event::{Event, WindowEvent},
|
||||||
|
event_loop::EventLoop,
|
||||||
|
platform::run_on_demand::EventLoopExtRunOnDemand,
|
||||||
|
window::{Window, WindowId},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct App {
|
||||||
|
window_id: Option<WindowId>,
|
||||||
|
window: Option<Window>,
|
||||||
|
}
|
||||||
|
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let mut event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
fn run_app(event_loop: &mut EventLoop<()>, idx: usize) -> Result<(), EventLoopError> {
|
||||||
|
let mut app = App::default();
|
||||||
|
|
||||||
|
event_loop.run_on_demand(move |event, event_loop| {
|
||||||
|
println!("Run {idx}: {:?}", event);
|
||||||
|
|
||||||
|
if let Some(window) = &app.window {
|
||||||
|
match event {
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::CloseRequested,
|
||||||
|
window_id,
|
||||||
|
} if window.id() == window_id => {
|
||||||
|
println!("--------------------------------------------------------- Window {idx} CloseRequested");
|
||||||
|
fill::cleanup_window(window);
|
||||||
|
app.window = None;
|
||||||
|
}
|
||||||
|
Event::AboutToWait => window.request_redraw(),
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::RedrawRequested,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
fill::fill_window(window);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
} else if let Some(id) = app.window_id {
|
||||||
|
match event {
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::Destroyed,
|
||||||
|
window_id,
|
||||||
|
} if id == window_id => {
|
||||||
|
println!("--------------------------------------------------------- Window {idx} Destroyed");
|
||||||
|
app.window_id = None;
|
||||||
|
event_loop.exit();
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
} else if let Event::Resumed = event {
|
||||||
|
let window_attributes = Window::default_attributes()
|
||||||
|
.with_title("Fantastic window number one!")
|
||||||
|
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0));
|
||||||
|
let window = event_loop.create_window(window_attributes).unwrap();
|
||||||
|
app.window_id = Some(window.id());
|
||||||
|
app.window = Some(window);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
run_app(&mut event_loop, 1)?;
|
||||||
|
|
||||||
|
println!("--------------------------------------------------------- Finished first loop");
|
||||||
|
println!("--------------------------------------------------------- Waiting 5 seconds");
|
||||||
|
std::thread::sleep(Duration::from_secs(5));
|
||||||
|
|
||||||
|
let ret = run_app(&mut event_loop, 2);
|
||||||
|
println!("--------------------------------------------------------- Finished second loop");
|
||||||
|
ret
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(any(windows_platform, macos_platform, x11_platform, wayland_platform,)))]
|
||||||
|
fn main() {
|
||||||
|
println!("This example is not supported on this platform");
|
||||||
|
}
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
extern crate winit;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut events_loop = winit::EventsLoop::new();
|
|
||||||
|
|
||||||
let window = winit::WindowBuilder::new().with_decorations(false)
|
|
||||||
.with_transparency(true)
|
|
||||||
.build(&events_loop).unwrap();
|
|
||||||
|
|
||||||
window.set_title("A fantastic window!");
|
|
||||||
|
|
||||||
events_loop.run_forever(|event| {
|
|
||||||
println!("{:?}", event);
|
|
||||||
|
|
||||||
match event {
|
|
||||||
winit::Event::WindowEvent { event: winit::WindowEvent::CloseRequested, .. } => winit::ControlFlow::Break,
|
|
||||||
_ => winit::ControlFlow::Continue,
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
116
examples/util/fill.rs
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
//! Fill the window buffer with a solid color.
|
||||||
|
//!
|
||||||
|
//! Launching a window without drawing to it has unpredictable results varying from platform to
|
||||||
|
//! platform. In order to have well-defined examples, this module provides an easy way to
|
||||||
|
//! fill the window buffer with a solid color.
|
||||||
|
//!
|
||||||
|
//! The `softbuffer` crate is used, largely because of its ease of use. `glutin` or `wgpu` could
|
||||||
|
//! also be used to fill the window buffer, but they are more complicated to use.
|
||||||
|
|
||||||
|
#[allow(unused_imports)]
|
||||||
|
pub use platform::cleanup_window;
|
||||||
|
pub use platform::fill_window;
|
||||||
|
|
||||||
|
#[cfg(all(feature = "rwh_05", not(any(target_os = "android", target_os = "ios"))))]
|
||||||
|
mod platform {
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::mem::ManuallyDrop;
|
||||||
|
use std::num::NonZeroU32;
|
||||||
|
|
||||||
|
use softbuffer::{Context, Surface};
|
||||||
|
use winit::window::Window;
|
||||||
|
use winit::window::WindowId;
|
||||||
|
|
||||||
|
thread_local! {
|
||||||
|
// NOTE: You should never do things like that, create context and drop it before
|
||||||
|
// you drop the event loop. We do this for brevity to not blow up examples. We use
|
||||||
|
// ManuallyDrop to prevent destructors from running.
|
||||||
|
//
|
||||||
|
// A static, thread-local map of graphics contexts to open windows.
|
||||||
|
static GC: ManuallyDrop<RefCell<Option<GraphicsContext>>> = const { ManuallyDrop::new(RefCell::new(None)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The graphics context used to draw to a window.
|
||||||
|
struct GraphicsContext {
|
||||||
|
/// The global softbuffer context.
|
||||||
|
context: Context,
|
||||||
|
|
||||||
|
/// The hash map of window IDs to surfaces.
|
||||||
|
surfaces: HashMap<WindowId, Surface>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GraphicsContext {
|
||||||
|
fn new(w: &Window) -> Self {
|
||||||
|
Self {
|
||||||
|
context: unsafe { Context::new(w) }.expect("Failed to create a softbuffer context"),
|
||||||
|
surfaces: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_surface(&mut self, window: &Window) -> &mut Surface {
|
||||||
|
self.surfaces.entry(window.id()).or_insert_with(|| {
|
||||||
|
unsafe { Surface::new(&self.context, window) }
|
||||||
|
.expect("Failed to create a softbuffer surface")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn destroy_surface(&mut self, window: &Window) {
|
||||||
|
self.surfaces.remove(&window.id());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fill_window(window: &Window) {
|
||||||
|
GC.with(|gc| {
|
||||||
|
let size = window.inner_size();
|
||||||
|
let (Some(width), Some(height)) =
|
||||||
|
(NonZeroU32::new(size.width), NonZeroU32::new(size.height))
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Either get the last context used or create a new one.
|
||||||
|
let mut gc = gc.borrow_mut();
|
||||||
|
let surface = gc
|
||||||
|
.get_or_insert_with(|| GraphicsContext::new(window))
|
||||||
|
.create_surface(window);
|
||||||
|
|
||||||
|
// Fill a buffer with a solid color.
|
||||||
|
const DARK_GRAY: u32 = 0xFF181818;
|
||||||
|
|
||||||
|
surface
|
||||||
|
.resize(width, height)
|
||||||
|
.expect("Failed to resize the softbuffer surface");
|
||||||
|
|
||||||
|
let mut buffer = surface
|
||||||
|
.buffer_mut()
|
||||||
|
.expect("Failed to get the softbuffer buffer");
|
||||||
|
buffer.fill(DARK_GRAY);
|
||||||
|
buffer
|
||||||
|
.present()
|
||||||
|
.expect("Failed to present the softbuffer buffer");
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn cleanup_window(window: &Window) {
|
||||||
|
GC.with(|gc| {
|
||||||
|
let mut gc = gc.borrow_mut();
|
||||||
|
if let Some(context) = gc.as_mut() {
|
||||||
|
context.destroy_surface(window);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(all(feature = "rwh_05", not(any(target_os = "android", target_os = "ios")))))]
|
||||||
|
mod platform {
|
||||||
|
pub fn fill_window(_window: &winit::window::Window) {
|
||||||
|
// No-op on mobile platforms.
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn cleanup_window(_window: &winit::window::Window) {
|
||||||
|
// No-op on mobile platforms.
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
extern crate winit;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut events_loop = winit::EventsLoop::new();
|
|
||||||
|
|
||||||
let _window = winit::WindowBuilder::new()
|
|
||||||
.with_title("A fantastic window!")
|
|
||||||
.build(&events_loop)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
events_loop.run_forever(|event| {
|
|
||||||
println!("{:?}", event);
|
|
||||||
|
|
||||||
match event {
|
|
||||||
winit::Event::WindowEvent {
|
|
||||||
event: winit::WindowEvent::CloseRequested,
|
|
||||||
..
|
|
||||||
} => winit::ControlFlow::Break,
|
|
||||||
_ => winit::ControlFlow::Continue,
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
// Heads up: you need to compile this example with `--features icon_loading`.
|
|
||||||
// `Icon::from_path` won't be available otherwise, though for your own applications, you could use
|
|
||||||
// `Icon::from_rgba` if you don't want to depend on the `image` crate.
|
|
||||||
|
|
||||||
extern crate winit;
|
|
||||||
#[cfg(feature = "icon_loading")]
|
|
||||||
extern crate image;
|
|
||||||
|
|
||||||
use winit::Icon;
|
|
||||||
|
|
||||||
#[cfg(feature = "icon_loading")]
|
|
||||||
fn main() {
|
|
||||||
// You'll have to choose an icon size at your own discretion. On X11, the desired size varies
|
|
||||||
// by WM, and on Windows, you still have to account for screen scaling. Here we use 32px,
|
|
||||||
// since it seems to work well enough in most cases. Be careful about going too high, or
|
|
||||||
// you'll be bitten by the low-quality downscaling built into the WM.
|
|
||||||
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/icon.png");
|
|
||||||
// While `Icon::from_path` is the most straightforward, you have a few other options. If you
|
|
||||||
// want to use the `include_bytes` macro, then pass the result to `Icon::from_bytes`. See the
|
|
||||||
// docs for the full list of options (you'll have to generate the docs with the `icon_loading`
|
|
||||||
// feature enabled).
|
|
||||||
let icon = Icon::from_path(path).expect("Failed to open icon");
|
|
||||||
|
|
||||||
let mut events_loop = winit::EventsLoop::new();
|
|
||||||
|
|
||||||
let window = winit::WindowBuilder::new()
|
|
||||||
.with_title("An iconic window!")
|
|
||||||
// At present, this only does anything on Windows and X11, so if you want to save load
|
|
||||||
// time, you can put icon loading behind a function that returns `None` on other platforms.
|
|
||||||
.with_window_icon(Some(icon))
|
|
||||||
.build(&events_loop)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
events_loop.run_forever(|event| {
|
|
||||||
if let winit::Event::WindowEvent { event, .. } = event {
|
|
||||||
use winit::WindowEvent::*;
|
|
||||||
match event {
|
|
||||||
CloseRequested => return winit::ControlFlow::Break,
|
|
||||||
DroppedFile(path) => {
|
|
||||||
use image::GenericImage;
|
|
||||||
|
|
||||||
let icon_image = image::open(path).expect("Failed to open window icon");
|
|
||||||
|
|
||||||
let (width, height) = icon_image.dimensions();
|
|
||||||
const DESIRED_SIZE: u32 = 32;
|
|
||||||
let (new_width, new_height) = if width == height {
|
|
||||||
(DESIRED_SIZE, DESIRED_SIZE)
|
|
||||||
} else {
|
|
||||||
// Note that this will never divide by zero, due to the previous condition.
|
|
||||||
let aspect_adjustment = DESIRED_SIZE as f64
|
|
||||||
/ std::cmp::max(width, height) as f64;
|
|
||||||
(
|
|
||||||
(width as f64 * aspect_adjustment) as u32,
|
|
||||||
(height as f64 * aspect_adjustment) as u32,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
|
|
||||||
// By scaling the icon ourselves, we get higher-quality filtering and save
|
|
||||||
// some memory.
|
|
||||||
let icon = image::imageops::resize(
|
|
||||||
&icon_image,
|
|
||||||
new_width,
|
|
||||||
new_height,
|
|
||||||
image::FilterType::Lanczos3,
|
|
||||||
);
|
|
||||||
|
|
||||||
let (offset_x, offset_y) = (
|
|
||||||
(DESIRED_SIZE - new_width) / 2,
|
|
||||||
(DESIRED_SIZE - new_height) / 2,
|
|
||||||
);
|
|
||||||
|
|
||||||
let mut canvas = image::ImageBuffer::new(DESIRED_SIZE, DESIRED_SIZE);
|
|
||||||
image::imageops::replace(
|
|
||||||
&mut canvas,
|
|
||||||
&icon,
|
|
||||||
offset_x,
|
|
||||||
offset_y,
|
|
||||||
);
|
|
||||||
|
|
||||||
window.set_window_icon(Some(canvas.into()));
|
|
||||||
},
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
winit::ControlFlow::Continue
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(feature = "icon_loading"))]
|
|
||||||
fn main() {
|
|
||||||
print!(
|
|
||||||
r#"This example requires the `icon_loading` feature:
|
|
||||||
cargo run --example window_icon --features icon_loading
|
|
||||||
"#);
|
|
||||||
}
|
|
||||||
62
examples/x11_embed.rs
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
//! 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 simple_logger::SimpleLogger;
|
||||||
|
|
||||||
|
use winit::{
|
||||||
|
event::{Event, WindowEvent},
|
||||||
|
event_loop::EventLoop,
|
||||||
|
platform::x11::WindowAttributesExtX11,
|
||||||
|
window::Window,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
// First argument should be a 32-bit X11 window ID.
|
||||||
|
let parent_window_id = std::env::args()
|
||||||
|
.nth(1)
|
||||||
|
.ok_or("Expected a 32-bit X11 window ID as the first argument.")?
|
||||||
|
.parse::<u32>()?;
|
||||||
|
|
||||||
|
SimpleLogger::new().init().unwrap();
|
||||||
|
let event_loop = EventLoop::new()?;
|
||||||
|
|
||||||
|
let mut window = None;
|
||||||
|
event_loop.run(move |event, event_loop| match event {
|
||||||
|
Event::Resumed => {
|
||||||
|
let window_attributes = Window::default_attributes()
|
||||||
|
.with_title("An embedded window!")
|
||||||
|
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
||||||
|
.with_embed_parent_window(parent_window_id);
|
||||||
|
|
||||||
|
window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||||
|
}
|
||||||
|
Event::WindowEvent { event, .. } => {
|
||||||
|
let window = window.as_ref().unwrap();
|
||||||
|
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => event_loop.exit(),
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
window.pre_present_notify();
|
||||||
|
fill::fill_window(window);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::AboutToWait => {
|
||||||
|
window.as_ref().unwrap().request_redraw();
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(x11_platform))]
|
||||||
|
fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
println!("This example is only supported on X11 platforms.");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
11
run-wasm/Cargo.toml
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
[package]
|
||||||
|
name = "run-wasm"
|
||||||
|
version = "0.1.0"
|
||||||
|
rust-version.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
cargo-run-wasm = "0.2.0"
|
||||||
3
run-wasm/src/main.rs
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
fn main() {
|
||||||
|
cargo_run_wasm::run_wasm_with_css("body { margin: 0px; }");
|
||||||
|
}
|
||||||
3
rustfmt.toml
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
force_explicit_abi=true
|
||||||
|
use_field_init_shorthand=true
|
||||||
|
# merge_imports=true
|
||||||
280
src/cursor.rs
Normal file
@@ -0,0 +1,280 @@
|
|||||||
|
use core::fmt;
|
||||||
|
use std::hash::Hasher;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::{error::Error, hash::Hash};
|
||||||
|
|
||||||
|
use cursor_icon::CursorIcon;
|
||||||
|
|
||||||
|
use crate::platform_impl::{PlatformCustomCursor, PlatformCustomCursorSource};
|
||||||
|
|
||||||
|
/// The maximum width and height for a cursor when using [`CustomCursor::from_rgba`].
|
||||||
|
pub const MAX_CURSOR_SIZE: u16 = 2048;
|
||||||
|
|
||||||
|
const PIXEL_SIZE: usize = 4;
|
||||||
|
|
||||||
|
/// See [`Window::set_cursor()`](crate::window::Window::set_cursor) for more details.
|
||||||
|
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||||
|
pub enum Cursor {
|
||||||
|
Icon(CursorIcon),
|
||||||
|
Custom(CustomCursor),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Cursor {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::Icon(CursorIcon::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<CursorIcon> for Cursor {
|
||||||
|
fn from(icon: CursorIcon) -> Self {
|
||||||
|
Self::Icon(icon)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<CustomCursor> for Cursor {
|
||||||
|
fn from(custom: CustomCursor) -> Self {
|
||||||
|
Self::Custom(custom)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Use a custom image as a cursor (mouse pointer).
|
||||||
|
///
|
||||||
|
/// Is guaranteed to be cheap to clone.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// **Web**: Some browsers have limits on cursor sizes usually at 128x128.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// # use winit::event_loop::ActiveEventLoop;
|
||||||
|
/// # use winit::window::Window;
|
||||||
|
/// # fn scope(event_loop: &ActiveEventLoop, window: &Window) {
|
||||||
|
/// use winit::window::CustomCursor;
|
||||||
|
///
|
||||||
|
/// let w = 10;
|
||||||
|
/// let h = 10;
|
||||||
|
/// let rgba = vec![255; (w * h * 4) as usize];
|
||||||
|
///
|
||||||
|
/// #[cfg(not(target_family = "wasm"))]
|
||||||
|
/// let source = CustomCursor::from_rgba(rgba, w, h, w / 2, h / 2).unwrap();
|
||||||
|
///
|
||||||
|
/// #[cfg(target_family = "wasm")]
|
||||||
|
/// let source = {
|
||||||
|
/// use winit::platform::web::CustomCursorExtWebSys;
|
||||||
|
/// CustomCursor::from_url(String::from("http://localhost:3000/cursor.png"), 0, 0)
|
||||||
|
/// };
|
||||||
|
///
|
||||||
|
/// let custom_cursor = event_loop.create_custom_cursor(source);
|
||||||
|
///
|
||||||
|
/// window.set_cursor(custom_cursor.clone());
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||||
|
pub struct CustomCursor {
|
||||||
|
/// Platforms should make sure this is cheap to clone.
|
||||||
|
pub(crate) inner: PlatformCustomCursor,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CustomCursor {
|
||||||
|
/// Creates a new cursor from an rgba buffer.
|
||||||
|
///
|
||||||
|
/// The alpha channel is assumed to be **not** premultiplied.
|
||||||
|
pub fn from_rgba(
|
||||||
|
rgba: impl Into<Vec<u8>>,
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
hotspot_x: u16,
|
||||||
|
hotspot_y: u16,
|
||||||
|
) -> Result<CustomCursorSource, BadImage> {
|
||||||
|
Ok(CustomCursorSource {
|
||||||
|
inner: PlatformCustomCursorSource::from_rgba(
|
||||||
|
rgba.into(),
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
hotspot_x,
|
||||||
|
hotspot_y,
|
||||||
|
)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Source for [`CustomCursor`].
|
||||||
|
///
|
||||||
|
/// See [`CustomCursor`] for more details.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct CustomCursorSource {
|
||||||
|
pub(crate) inner: PlatformCustomCursorSource,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An error produced when using [`CustomCursor::from_rgba`] with invalid arguments.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum BadImage {
|
||||||
|
/// Produced when the image dimensions are larger than [`MAX_CURSOR_SIZE`]. This doesn't
|
||||||
|
/// guarantee that the cursor will work, but should avoid many platform and device specific
|
||||||
|
/// limits.
|
||||||
|
TooLarge { width: u16, height: u16 },
|
||||||
|
/// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be
|
||||||
|
/// safely interpreted as 32bpp RGBA pixels.
|
||||||
|
ByteCountNotDivisibleBy4 { byte_count: usize },
|
||||||
|
/// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`.
|
||||||
|
/// At least one of your arguments is incorrect.
|
||||||
|
DimensionsVsPixelCount {
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
width_x_height: u64,
|
||||||
|
pixel_count: u64,
|
||||||
|
},
|
||||||
|
/// Produced when the hotspot is outside the image bounds
|
||||||
|
HotspotOutOfBounds {
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
hotspot_x: u16,
|
||||||
|
hotspot_y: u16,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for BadImage {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
BadImage::TooLarge { width, height } => write!(f,
|
||||||
|
"The specified dimensions ({width:?}x{height:?}) are too large. The maximum is {MAX_CURSOR_SIZE:?}x{MAX_CURSOR_SIZE:?}.",
|
||||||
|
),
|
||||||
|
BadImage::ByteCountNotDivisibleBy4 { byte_count } => write!(f,
|
||||||
|
"The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making it impossible to interpret as 32bpp RGBA pixels.",
|
||||||
|
),
|
||||||
|
BadImage::DimensionsVsPixelCount {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
width_x_height,
|
||||||
|
pixel_count,
|
||||||
|
} => write!(f,
|
||||||
|
"The specified dimensions ({width:?}x{height:?}) don't match the number of pixels supplied by the `rgba` argument ({pixel_count:?}). For those dimensions, the expected pixel count is {width_x_height:?}.",
|
||||||
|
),
|
||||||
|
BadImage::HotspotOutOfBounds {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
hotspot_x,
|
||||||
|
hotspot_y,
|
||||||
|
} => write!(f,
|
||||||
|
"The specified hotspot ({hotspot_x:?}, {hotspot_y:?}) is outside the image bounds ({width:?}x{height:?}).",
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for BadImage {}
|
||||||
|
|
||||||
|
/// Platforms export this directly as `PlatformCustomCursorSource` if they need to only work with
|
||||||
|
/// images.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(crate) struct OnlyCursorImageSource(pub(crate) CursorImage);
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl OnlyCursorImageSource {
|
||||||
|
pub(crate) fn from_rgba(
|
||||||
|
rgba: Vec<u8>,
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
hotspot_x: u16,
|
||||||
|
hotspot_y: u16,
|
||||||
|
) -> Result<Self, BadImage> {
|
||||||
|
CursorImage::from_rgba(rgba, width, height, hotspot_x, hotspot_y).map(Self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Platforms export this directly as `PlatformCustomCursor` if they don't implement caching.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub(crate) struct OnlyCursorImage(pub(crate) Arc<CursorImage>);
|
||||||
|
|
||||||
|
impl Hash for OnlyCursorImage {
|
||||||
|
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||||
|
Arc::as_ptr(&self.0).hash(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for OnlyCursorImage {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
Arc::ptr_eq(&self.0, &other.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Eq for OnlyCursorImage {}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) struct CursorImage {
|
||||||
|
pub(crate) rgba: Vec<u8>,
|
||||||
|
pub(crate) width: u16,
|
||||||
|
pub(crate) height: u16,
|
||||||
|
pub(crate) hotspot_x: u16,
|
||||||
|
pub(crate) hotspot_y: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CursorImage {
|
||||||
|
pub(crate) fn from_rgba(
|
||||||
|
rgba: Vec<u8>,
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
hotspot_x: u16,
|
||||||
|
hotspot_y: u16,
|
||||||
|
) -> Result<Self, BadImage> {
|
||||||
|
if width > MAX_CURSOR_SIZE || height > MAX_CURSOR_SIZE {
|
||||||
|
return Err(BadImage::TooLarge { width, height });
|
||||||
|
}
|
||||||
|
|
||||||
|
if rgba.len() % PIXEL_SIZE != 0 {
|
||||||
|
return Err(BadImage::ByteCountNotDivisibleBy4 {
|
||||||
|
byte_count: rgba.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let pixel_count = (rgba.len() / PIXEL_SIZE) as u64;
|
||||||
|
let width_x_height = width as u64 * height as u64;
|
||||||
|
if pixel_count != width_x_height {
|
||||||
|
return Err(BadImage::DimensionsVsPixelCount {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
width_x_height,
|
||||||
|
pixel_count,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if hotspot_x >= width || hotspot_y >= height {
|
||||||
|
return Err(BadImage::HotspotOutOfBounds {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
hotspot_x,
|
||||||
|
hotspot_y,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(CursorImage {
|
||||||
|
rgba,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
hotspot_x,
|
||||||
|
hotspot_y,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Platforms that don't support cursors will export this as `PlatformCustomCursor`.
|
||||||
|
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
|
||||||
|
pub(crate) struct NoCustomCursor;
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl NoCustomCursor {
|
||||||
|
pub(crate) fn from_rgba(
|
||||||
|
rgba: Vec<u8>,
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
hotspot_x: u16,
|
||||||
|
hotspot_y: u16,
|
||||||
|
) -> Result<Self, BadImage> {
|
||||||
|
CursorImage::from_rgba(rgba, width, height, hotspot_x, hotspot_y)?;
|
||||||
|
Ok(Self)
|
||||||
|
}
|
||||||
|
}
|
||||||
317
src/dpi.rs
@@ -1,317 +0,0 @@
|
|||||||
|
|
||||||
//! DPI is important, so read the docs for this module if you don't want to be confused.
|
|
||||||
//!
|
|
||||||
//! Originally, `winit` dealt entirely in physical pixels (excluding unintentional inconsistencies), but now all
|
|
||||||
//! window-related functions both produce and consume logical pixels. Monitor-related functions still use physical
|
|
||||||
//! pixels, as do any context-related functions in `glutin`.
|
|
||||||
//!
|
|
||||||
//! If you've never heard of these terms before, then you're not alone, and this documentation will explain the
|
|
||||||
//! concepts.
|
|
||||||
//!
|
|
||||||
//! Modern screens have a defined physical resolution, most commonly 1920x1080. Indepedent of that is the amount of
|
|
||||||
//! space the screen occupies, which is to say, the height and width in millimeters. The relationship between these two
|
|
||||||
//! measurements is the *pixel density*. Mobile screens require a high pixel density, as they're held close to the
|
|
||||||
//! eyes. Larger displays also require a higher pixel density, hence the growing presence of 1440p and 4K displays.
|
|
||||||
//!
|
|
||||||
//! So, this presents a problem. Let's say we want to render a square 100px button. It will occupy 100x100 of the
|
|
||||||
//! screen's pixels, which in many cases, seems perfectly fine. However, because this size doesn't account for the
|
|
||||||
//! screen's dimensions or pixel density, the button's size can vary quite a bit. On a 4K display, it would be unusably
|
|
||||||
//! small.
|
|
||||||
//!
|
|
||||||
//! That's a description of what happens when the button is 100x100 *physical* pixels. Instead, let's try using 100x100
|
|
||||||
//! *logical* pixels. To map logical pixels to physical pixels, we simply multiply by the DPI (dots per inch) factor.
|
|
||||||
//! On a "typical" desktop display, the DPI factor will be 1.0, so 100x100 logical pixels equates to 100x100 physical
|
|
||||||
//! pixels. However, a 1440p display may have a DPI factor of 1.25, so the button is rendered as 125x125 physical pixels.
|
|
||||||
//! Ideally, the button now has approximately the same perceived size across varying displays.
|
|
||||||
//!
|
|
||||||
//! Failure to account for the DPI factor can create a badly degraded user experience. Most notably, it can make users
|
|
||||||
//! feel like they have bad eyesight, which will potentially cause them to think about growing elderly, resulting in
|
|
||||||
//! them entering an existential panic. Once users enter that state, they will no longer be focused on your application.
|
|
||||||
//!
|
|
||||||
//! There are two ways to get the DPI factor:
|
|
||||||
//! - You can track the `WindowEvent::HiDpiFactorChanged` event of your windows. This event is sent any
|
|
||||||
//! time the DPI factor changes, be it because the window moved to another monitor, or because the
|
|
||||||
//! user changed the configuration of their screen.
|
|
||||||
//! - You can also retrieve the DPI factor of a monitor by calling
|
|
||||||
//! [`MonitorId::get_hidpi_factor`](../struct.MonitorId.html#method.get_hidpi_factor), or the
|
|
||||||
//! current DPI factor applied to a window by calling
|
|
||||||
//! [`Window::get_hidpi_factor`](../struct.Window.html#method.get_hidpi_factor), which is roughly equivalent
|
|
||||||
//! to `window.get_current_monitor().get_hidpi_factor()`.
|
|
||||||
//!
|
|
||||||
//! Depending on the platform, the window's actual DPI factor may only be known after
|
|
||||||
//! the event loop has started and your window has been drawn once. To properly handle these cases,
|
|
||||||
//! the most robust way is to monitor the `WindowEvent::HiDpiFactorChanged` event and dynamically
|
|
||||||
//! adapt your drawing logic to follow the DPI factor.
|
|
||||||
//!
|
|
||||||
//! Here's an overview of what sort of DPI factors you can expect, and where they come from:
|
|
||||||
//! - **Windows:** On Windows 8 and 10, per-monitor scaling is readily configured by users from the display settings.
|
|
||||||
//! While users are free to select any option they want, they're only given a selection of "nice" DPI factors, i.e.
|
|
||||||
//! 1.0, 1.25, 1.5... on Windows 7, the DPI factor is global and changing it requires logging out.
|
|
||||||
//! - **macOS:** The buzzword is "retina displays", which have a DPI factor of 2.0. Otherwise, the DPI factor is 1.0.
|
|
||||||
//! Intermediate DPI factors are never used, thus 1440p displays/etc. aren't properly supported. It's possible for any
|
|
||||||
//! display to use that 2.0 DPI factor, given the use of the command line.
|
|
||||||
//! - **X11:** On X11, we calcuate the DPI factor based on the millimeter dimensions provided by XRandR. This can
|
|
||||||
//! result in a wide range of possible values, including some interesting ones like 1.0833333333333333. This can be
|
|
||||||
//! overridden using the `WINIT_HIDPI_FACTOR` environment variable, though that's not recommended.
|
|
||||||
//! - **Wayland:** On Wayland, DPI factors are very much at the discretion of the user.
|
|
||||||
//! - **iOS:** DPI factors are both constant and device-specific on iOS.
|
|
||||||
//! - **Android:** This feature isn't yet implemented on Android, so the DPI factor will always be returned as 1.0.
|
|
||||||
//!
|
|
||||||
//! The window's logical size is conserved across DPI changes, resulting in the physical size changing instead. This
|
|
||||||
//! may be surprising on X11, but is quite standard elsewhere. Physical size changes produce a
|
|
||||||
//! [`Resized`](../enum.WindowEvent.html#variant.Resized) event, even on platforms where no resize actually occurs,
|
|
||||||
//! such as macOS and Wayland. As a result, it's not necessary to separately handle
|
|
||||||
//! [`HiDpiFactorChanged`](../enum.WindowEvent.html#variant.HiDpiFactorChanged) if you're only listening for size.
|
|
||||||
//!
|
|
||||||
//! Your GPU has no awareness of the concept of logical pixels, and unless you like wasting pixel density, your
|
|
||||||
//! framebuffer's size should be in physical pixels.
|
|
||||||
|
|
||||||
/// Checks that the DPI factor is a normal positive `f64`.
|
|
||||||
///
|
|
||||||
/// All functions that take a DPI factor assert that this will return `true`. If you're sourcing DPI factors from
|
|
||||||
/// anywhere other than winit, it's recommended to validate them using this function before passing them to winit;
|
|
||||||
/// otherwise, you risk panics.
|
|
||||||
#[inline]
|
|
||||||
pub fn validate_hidpi_factor(dpi_factor: f64) -> bool {
|
|
||||||
dpi_factor.is_sign_positive() && dpi_factor.is_normal()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A position represented in logical pixels.
|
|
||||||
///
|
|
||||||
/// The position is stored as floats, so please be careful. Casting floats to integers truncates the fractional part,
|
|
||||||
/// which can cause noticable issues. To help with that, an `Into<(i32, i32)>` implementation is provided which
|
|
||||||
/// does the rounding for you.
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
|
||||||
pub struct LogicalPosition {
|
|
||||||
pub x: f64,
|
|
||||||
pub y: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LogicalPosition {
|
|
||||||
#[inline]
|
|
||||||
pub fn new(x: f64, y: f64) -> Self {
|
|
||||||
LogicalPosition { x, y }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn from_physical<T: Into<PhysicalPosition>>(physical: T, dpi_factor: f64) -> Self {
|
|
||||||
physical.into().to_logical(dpi_factor)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn to_physical(&self, dpi_factor: f64) -> PhysicalPosition {
|
|
||||||
assert!(validate_hidpi_factor(dpi_factor));
|
|
||||||
let x = self.x * dpi_factor;
|
|
||||||
let y = self.y * dpi_factor;
|
|
||||||
PhysicalPosition::new(x, y)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<(f64, f64)> for LogicalPosition {
|
|
||||||
#[inline]
|
|
||||||
fn from((x, y): (f64, f64)) -> Self {
|
|
||||||
Self::new(x, y)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<(i32, i32)> for LogicalPosition {
|
|
||||||
#[inline]
|
|
||||||
fn from((x, y): (i32, i32)) -> Self {
|
|
||||||
Self::new(x as f64, y as f64)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Into<(f64, f64)> for LogicalPosition {
|
|
||||||
#[inline]
|
|
||||||
fn into(self) -> (f64, f64) {
|
|
||||||
(self.x, self.y)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Into<(i32, i32)> for LogicalPosition {
|
|
||||||
/// Note that this rounds instead of truncating.
|
|
||||||
#[inline]
|
|
||||||
fn into(self) -> (i32, i32) {
|
|
||||||
(self.x.round() as _, self.y.round() as _)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A position represented in physical pixels.
|
|
||||||
///
|
|
||||||
/// The position is stored as floats, so please be careful. Casting floats to integers truncates the fractional part,
|
|
||||||
/// which can cause noticable issues. To help with that, an `Into<(i32, i32)>` implementation is provided which
|
|
||||||
/// does the rounding for you.
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
|
||||||
pub struct PhysicalPosition {
|
|
||||||
pub x: f64,
|
|
||||||
pub y: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PhysicalPosition {
|
|
||||||
#[inline]
|
|
||||||
pub fn new(x: f64, y: f64) -> Self {
|
|
||||||
PhysicalPosition { x, y }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn from_logical<T: Into<LogicalPosition>>(logical: T, dpi_factor: f64) -> Self {
|
|
||||||
logical.into().to_physical(dpi_factor)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn to_logical(&self, dpi_factor: f64) -> LogicalPosition {
|
|
||||||
assert!(validate_hidpi_factor(dpi_factor));
|
|
||||||
let x = self.x / dpi_factor;
|
|
||||||
let y = self.y / dpi_factor;
|
|
||||||
LogicalPosition::new(x, y)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<(f64, f64)> for PhysicalPosition {
|
|
||||||
#[inline]
|
|
||||||
fn from((x, y): (f64, f64)) -> Self {
|
|
||||||
Self::new(x, y)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<(i32, i32)> for PhysicalPosition {
|
|
||||||
#[inline]
|
|
||||||
fn from((x, y): (i32, i32)) -> Self {
|
|
||||||
Self::new(x as f64, y as f64)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Into<(f64, f64)> for PhysicalPosition {
|
|
||||||
#[inline]
|
|
||||||
fn into(self) -> (f64, f64) {
|
|
||||||
(self.x, self.y)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Into<(i32, i32)> for PhysicalPosition {
|
|
||||||
/// Note that this rounds instead of truncating.
|
|
||||||
#[inline]
|
|
||||||
fn into(self) -> (i32, i32) {
|
|
||||||
(self.x.round() as _, self.y.round() as _)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A size represented in logical pixels.
|
|
||||||
///
|
|
||||||
/// The size is stored as floats, so please be careful. Casting floats to integers truncates the fractional part,
|
|
||||||
/// which can cause noticable issues. To help with that, an `Into<(u32, u32)>` implementation is provided which
|
|
||||||
/// does the rounding for you.
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
|
||||||
pub struct LogicalSize {
|
|
||||||
pub width: f64,
|
|
||||||
pub height: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LogicalSize {
|
|
||||||
#[inline]
|
|
||||||
pub fn new(width: f64, height: f64) -> Self {
|
|
||||||
LogicalSize { width, height }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn from_physical<T: Into<PhysicalSize>>(physical: T, dpi_factor: f64) -> Self {
|
|
||||||
physical.into().to_logical(dpi_factor)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn to_physical(&self, dpi_factor: f64) -> PhysicalSize {
|
|
||||||
assert!(validate_hidpi_factor(dpi_factor));
|
|
||||||
let width = self.width * dpi_factor;
|
|
||||||
let height = self.height * dpi_factor;
|
|
||||||
PhysicalSize::new(width, height)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<(f64, f64)> for LogicalSize {
|
|
||||||
#[inline]
|
|
||||||
fn from((width, height): (f64, f64)) -> Self {
|
|
||||||
Self::new(width, height)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<(u32, u32)> for LogicalSize {
|
|
||||||
#[inline]
|
|
||||||
fn from((width, height): (u32, u32)) -> Self {
|
|
||||||
Self::new(width as f64, height as f64)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Into<(f64, f64)> for LogicalSize {
|
|
||||||
#[inline]
|
|
||||||
fn into(self) -> (f64, f64) {
|
|
||||||
(self.width, self.height)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Into<(u32, u32)> for LogicalSize {
|
|
||||||
/// Note that this rounds instead of truncating.
|
|
||||||
#[inline]
|
|
||||||
fn into(self) -> (u32, u32) {
|
|
||||||
(self.width.round() as _, self.height.round() as _)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A size represented in physical pixels.
|
|
||||||
///
|
|
||||||
/// The size is stored as floats, so please be careful. Casting floats to integers truncates the fractional part,
|
|
||||||
/// which can cause noticable issues. To help with that, an `Into<(u32, u32)>` implementation is provided which
|
|
||||||
/// does the rounding for you.
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
|
||||||
pub struct PhysicalSize {
|
|
||||||
pub width: f64,
|
|
||||||
pub height: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PhysicalSize {
|
|
||||||
#[inline]
|
|
||||||
pub fn new(width: f64, height: f64) -> Self {
|
|
||||||
PhysicalSize { width, height }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn from_logical<T: Into<LogicalSize>>(logical: T, dpi_factor: f64) -> Self {
|
|
||||||
logical.into().to_physical(dpi_factor)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn to_logical(&self, dpi_factor: f64) -> LogicalSize {
|
|
||||||
assert!(validate_hidpi_factor(dpi_factor));
|
|
||||||
let width = self.width / dpi_factor;
|
|
||||||
let height = self.height / dpi_factor;
|
|
||||||
LogicalSize::new(width, height)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<(f64, f64)> for PhysicalSize {
|
|
||||||
#[inline]
|
|
||||||
fn from((width, height): (f64, f64)) -> Self {
|
|
||||||
Self::new(width, height)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<(u32, u32)> for PhysicalSize {
|
|
||||||
#[inline]
|
|
||||||
fn from((width, height): (u32, u32)) -> Self {
|
|
||||||
Self::new(width as f64, height as f64)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Into<(f64, f64)> for PhysicalSize {
|
|
||||||
#[inline]
|
|
||||||
fn into(self) -> (f64, f64) {
|
|
||||||
(self.width, self.height)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Into<(u32, u32)> for PhysicalSize {
|
|
||||||
/// Note that this rounds instead of truncating.
|
|
||||||
#[inline]
|
|
||||||
fn into(self) -> (u32, u32) {
|
|
||||||
(self.width.round() as _, self.height.round() as _)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
139
src/error.rs
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
use std::{error, fmt};
|
||||||
|
|
||||||
|
use crate::platform_impl;
|
||||||
|
|
||||||
|
// TODO: Rename
|
||||||
|
/// An error that may be generated when requesting Winit state
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum ExternalError {
|
||||||
|
/// The operation is not supported by the backend.
|
||||||
|
NotSupported(NotSupportedError),
|
||||||
|
/// The operation was ignored.
|
||||||
|
Ignored,
|
||||||
|
/// The OS cannot perform the operation.
|
||||||
|
Os(OsError),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The error type for when the requested operation is not supported by the backend.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct NotSupportedError {
|
||||||
|
_marker: (),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The error type for when the OS cannot perform the requested operation.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct OsError {
|
||||||
|
line: u32,
|
||||||
|
file: &'static str,
|
||||||
|
error: platform_impl::OsError,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A general error that may occur while running the Winit event loop
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum EventLoopError {
|
||||||
|
/// The operation is not supported by the backend.
|
||||||
|
NotSupported(NotSupportedError),
|
||||||
|
/// The OS cannot perform the operation.
|
||||||
|
Os(OsError),
|
||||||
|
/// The event loop can't be re-created.
|
||||||
|
RecreationAttempt,
|
||||||
|
/// Application has exit with an error status.
|
||||||
|
ExitFailure(i32),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<OsError> for EventLoopError {
|
||||||
|
fn from(value: OsError) -> Self {
|
||||||
|
Self::Os(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NotSupportedError {
|
||||||
|
#[inline]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) fn new() -> NotSupportedError {
|
||||||
|
NotSupportedError { _marker: () }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OsError {
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) fn new(line: u32, file: &'static str, error: platform_impl::OsError) -> OsError {
|
||||||
|
OsError { line, file, error }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(unused_macros)]
|
||||||
|
macro_rules! os_error {
|
||||||
|
($error:expr) => {{
|
||||||
|
crate::error::OsError::new(line!(), file!(), $error)
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for OsError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||||
|
f.pad(&format!(
|
||||||
|
"os error at {}:{}: {}",
|
||||||
|
self.file, self.line, self.error
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for ExternalError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||||
|
match self {
|
||||||
|
ExternalError::NotSupported(e) => e.fmt(f),
|
||||||
|
ExternalError::Ignored => write!(f, "Operation was ignored"),
|
||||||
|
ExternalError::Os(e) => e.fmt(f),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for NotSupportedError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||||
|
f.debug_struct("NotSupportedError").finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for NotSupportedError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||||
|
f.pad("the requested operation is not supported by Winit")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for EventLoopError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||||
|
match self {
|
||||||
|
EventLoopError::RecreationAttempt => write!(f, "EventLoop can't be recreated"),
|
||||||
|
EventLoopError::NotSupported(e) => e.fmt(f),
|
||||||
|
EventLoopError::Os(e) => e.fmt(f),
|
||||||
|
EventLoopError::ExitFailure(status) => write!(f, "Exit Failure: {status}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl error::Error for OsError {}
|
||||||
|
impl error::Error for ExternalError {}
|
||||||
|
impl error::Error for NotSupportedError {}
|
||||||
|
impl error::Error for EventLoopError {}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::redundant_clone)]
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
// Eat attributes for testing
|
||||||
|
#[test]
|
||||||
|
fn ensure_fmt_does_not_panic() {
|
||||||
|
let _ = format!(
|
||||||
|
"{:?}, {}",
|
||||||
|
NotSupportedError::new(),
|
||||||
|
NotSupportedError::new().clone()
|
||||||
|
);
|
||||||
|
let _ = format!(
|
||||||
|
"{:?}, {}",
|
||||||
|
ExternalError::NotSupported(NotSupportedError::new()),
|
||||||
|
ExternalError::NotSupported(NotSupportedError::new())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
1347
src/event.rs
Normal file
594
src/event_loop.rs
Normal file
@@ -0,0 +1,594 @@
|
|||||||
|
//! The [`EventLoop`] struct and assorted supporting types, including
|
||||||
|
//! [`ControlFlow`].
|
||||||
|
//!
|
||||||
|
//! If you want to send custom events to the event loop, use
|
||||||
|
//! [`EventLoop::create_proxy`] to acquire an [`EventLoopProxy`] and call its
|
||||||
|
//! [`send_event`](`EventLoopProxy::send_event`) method.
|
||||||
|
//!
|
||||||
|
//! See the root-level documentation for information on how to create and use an event loop to
|
||||||
|
//! handle events.
|
||||||
|
use std::marker::PhantomData;
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
|
use std::{error, fmt};
|
||||||
|
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
use web_time::{Duration, Instant};
|
||||||
|
|
||||||
|
use crate::error::{EventLoopError, OsError};
|
||||||
|
use crate::window::{CustomCursor, CustomCursorSource, Window, WindowAttributes};
|
||||||
|
use crate::{event::Event, monitor::MonitorHandle, platform_impl};
|
||||||
|
|
||||||
|
/// Provides a way to retrieve events from the system and from the windows that were registered to
|
||||||
|
/// the events loop.
|
||||||
|
///
|
||||||
|
/// An `EventLoop` can be seen more or less as a "context". Calling [`EventLoop::new`]
|
||||||
|
/// initializes everything that will be required to create windows. For example on Linux creating
|
||||||
|
/// an event loop opens a connection to the X or Wayland server.
|
||||||
|
///
|
||||||
|
/// To wake up an `EventLoop` from a another thread, see the [`EventLoopProxy`] docs.
|
||||||
|
///
|
||||||
|
/// Note that this cannot be shared across threads (due to platform-dependant logic
|
||||||
|
/// forbidding it), as such it is neither [`Send`] nor [`Sync`]. If you need cross-thread access, the
|
||||||
|
/// [`Window`] created from this _can_ be sent to an other thread, and the
|
||||||
|
/// [`EventLoopProxy`] allows you to wake up an `EventLoop` from another thread.
|
||||||
|
///
|
||||||
|
/// [`Window`]: crate::window::Window
|
||||||
|
pub struct EventLoop<T: 'static> {
|
||||||
|
pub(crate) event_loop: platform_impl::EventLoop<T>,
|
||||||
|
pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Target that associates windows with an [`EventLoop`].
|
||||||
|
///
|
||||||
|
/// This type exists to allow you to create new windows while Winit executes
|
||||||
|
/// your callback.
|
||||||
|
pub struct ActiveEventLoop {
|
||||||
|
pub(crate) p: platform_impl::ActiveEventLoop,
|
||||||
|
pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Object that allows building the event loop.
|
||||||
|
///
|
||||||
|
/// This is used to make specifying options that affect the whole application
|
||||||
|
/// easier. But note that constructing multiple event loops is not supported.
|
||||||
|
///
|
||||||
|
/// This can be created using [`EventLoop::new`] or [`EventLoop::with_user_event`].
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct EventLoopBuilder<T: 'static> {
|
||||||
|
pub(crate) platform_specific: platform_impl::PlatformSpecificEventLoopAttributes,
|
||||||
|
_p: PhantomData<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
static EVENT_LOOP_CREATED: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
impl EventLoopBuilder<()> {
|
||||||
|
/// Start building a new event loop.
|
||||||
|
#[inline]
|
||||||
|
#[deprecated = "use `EventLoop::builder` instead"]
|
||||||
|
pub fn new() -> Self {
|
||||||
|
EventLoop::builder()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopBuilder<T> {
|
||||||
|
/// Builds a new event loop.
|
||||||
|
///
|
||||||
|
/// ***For cross-platform compatibility, the [`EventLoop`] must be created on the main thread,
|
||||||
|
/// and only once per application.***
|
||||||
|
///
|
||||||
|
/// Calling this function will result in display backend initialisation.
|
||||||
|
///
|
||||||
|
/// ## Panics
|
||||||
|
///
|
||||||
|
/// Attempting to create the event loop off the main thread will panic. This
|
||||||
|
/// restriction isn't strictly necessary on all platforms, but is imposed to
|
||||||
|
/// eliminate any nasty surprises when porting to platforms that require it.
|
||||||
|
/// `EventLoopBuilderExt::any_thread` functions are exposed in the relevant
|
||||||
|
/// [`platform`] module if the target platform supports creating an event
|
||||||
|
/// loop on any thread.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **Wayland/X11:** to prevent running under `Wayland` or `X11` unset `WAYLAND_DISPLAY`
|
||||||
|
/// or `DISPLAY` respectively when building the event loop.
|
||||||
|
/// - **Android:** must be configured with an `AndroidApp` from `android_main()` by calling
|
||||||
|
/// [`.with_android_app(app)`] before calling `.build()`, otherwise it'll panic.
|
||||||
|
///
|
||||||
|
/// [`platform`]: crate::platform
|
||||||
|
#[cfg_attr(
|
||||||
|
android,
|
||||||
|
doc = "[`.with_android_app(app)`]: crate::platform::android::EventLoopBuilderExtAndroid::with_android_app"
|
||||||
|
)]
|
||||||
|
#[cfg_attr(
|
||||||
|
not(android),
|
||||||
|
doc = "[`.with_android_app(app)`]: #only-available-on-android"
|
||||||
|
)]
|
||||||
|
#[inline]
|
||||||
|
pub fn build(&mut self) -> Result<EventLoop<T>, EventLoopError> {
|
||||||
|
if EVENT_LOOP_CREATED.swap(true, Ordering::Relaxed) {
|
||||||
|
return Err(EventLoopError::RecreationAttempt);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Certain platforms accept a mutable reference in their API.
|
||||||
|
#[allow(clippy::unnecessary_mut_passed)]
|
||||||
|
Ok(EventLoop {
|
||||||
|
event_loop: platform_impl::EventLoop::new(&mut self.platform_specific)?,
|
||||||
|
_marker: PhantomData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
pub(crate) fn allow_event_loop_recreation() {
|
||||||
|
EVENT_LOOP_CREATED.store(false, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> fmt::Debug for EventLoop<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.pad("EventLoop { .. }")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for ActiveEventLoop {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.pad("ActiveEventLoop { .. }")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set through [`ActiveEventLoop::set_control_flow()`].
|
||||||
|
///
|
||||||
|
/// Indicates the desired behavior of the event loop after [`Event::AboutToWait`] is emitted.
|
||||||
|
///
|
||||||
|
/// Defaults to [`Wait`].
|
||||||
|
///
|
||||||
|
/// [`Wait`]: Self::Wait
|
||||||
|
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub enum ControlFlow {
|
||||||
|
/// When the current loop iteration finishes, immediately begin a new iteration regardless of
|
||||||
|
/// whether or not new events are available to process.
|
||||||
|
Poll,
|
||||||
|
|
||||||
|
/// When the current loop iteration finishes, suspend the thread until another event arrives.
|
||||||
|
#[default]
|
||||||
|
Wait,
|
||||||
|
|
||||||
|
/// When the current loop iteration finishes, suspend the thread until either another event
|
||||||
|
/// arrives or the given time is reached.
|
||||||
|
///
|
||||||
|
/// Useful for implementing efficient timers. Applications which want to render at the display's
|
||||||
|
/// native refresh rate should instead use [`Poll`] and the VSync functionality of a graphics API
|
||||||
|
/// to reduce odds of missed frames.
|
||||||
|
///
|
||||||
|
/// [`Poll`]: Self::Poll
|
||||||
|
WaitUntil(Instant),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ControlFlow {
|
||||||
|
/// Creates a [`ControlFlow`] that waits until a timeout has expired.
|
||||||
|
///
|
||||||
|
/// In most cases, this is set to [`WaitUntil`]. However, if the timeout overflows, it is
|
||||||
|
/// instead set to [`Wait`].
|
||||||
|
///
|
||||||
|
/// [`WaitUntil`]: Self::WaitUntil
|
||||||
|
/// [`Wait`]: Self::Wait
|
||||||
|
pub fn wait_duration(timeout: Duration) -> Self {
|
||||||
|
match Instant::now().checked_add(timeout) {
|
||||||
|
Some(instant) => Self::WaitUntil(instant),
|
||||||
|
None => Self::Wait,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoop<()> {
|
||||||
|
/// Create the event loop.
|
||||||
|
///
|
||||||
|
/// This is an alias of `EventLoop::builder().build()`.
|
||||||
|
#[inline]
|
||||||
|
pub fn new() -> Result<EventLoop<()>, EventLoopError> {
|
||||||
|
Self::builder().build()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start building a new event loop.
|
||||||
|
///
|
||||||
|
/// This returns an [`EventLoopBuilder`], to allow configuring the event loop before creation.
|
||||||
|
///
|
||||||
|
/// To get the actual event loop, call [`build`][EventLoopBuilder::build] on that.
|
||||||
|
#[inline]
|
||||||
|
pub fn builder() -> EventLoopBuilder<()> {
|
||||||
|
Self::with_user_event()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoop<T> {
|
||||||
|
/// Start building a new event loop, with the given type as the user event
|
||||||
|
/// type.
|
||||||
|
pub fn with_user_event() -> EventLoopBuilder<T> {
|
||||||
|
EventLoopBuilder {
|
||||||
|
platform_specific: Default::default(),
|
||||||
|
_p: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs the event loop in the calling thread and calls the given `event_handler` closure
|
||||||
|
/// to dispatch any pending events.
|
||||||
|
///
|
||||||
|
/// See the [`set_control_flow()`] docs on how to change the event loop's behavior.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **iOS:** Will never return to the caller and so values not passed to this function will
|
||||||
|
/// *not* be dropped before the process exits.
|
||||||
|
/// - **Web:** Will _act_ as if it never returns to the caller by throwing a Javascript exception
|
||||||
|
/// (that Rust doesn't see) that will also mean that the rest of the function is never executed
|
||||||
|
/// and any values not passed to this function will *not* be dropped.
|
||||||
|
///
|
||||||
|
/// Web applications are recommended to use
|
||||||
|
#[cfg_attr(
|
||||||
|
web_platform,
|
||||||
|
doc = "[`EventLoopExtWebSys::spawn()`][crate::platform::web::EventLoopExtWebSys::spawn()]"
|
||||||
|
)]
|
||||||
|
#[cfg_attr(not(web_platform), doc = "`EventLoopExtWebSys::spawn()`")]
|
||||||
|
/// [^1] instead of [`run()`] to avoid the need
|
||||||
|
/// for the Javascript exception trick, and to make it clearer that the event loop runs
|
||||||
|
/// asynchronously (via the browser's own, internal, event loop) and doesn't block the
|
||||||
|
/// current thread of execution like it does on other platforms.
|
||||||
|
///
|
||||||
|
/// This function won't be available with `target_feature = "exception-handling"`.
|
||||||
|
///
|
||||||
|
/// [`set_control_flow()`]: ActiveEventLoop::set_control_flow()
|
||||||
|
/// [`run()`]: Self::run()
|
||||||
|
/// [^1]: `EventLoopExtWebSys::spawn()` is only available on Web.
|
||||||
|
#[inline]
|
||||||
|
#[cfg(not(all(web_platform, target_feature = "exception-handling")))]
|
||||||
|
pub fn run<F>(self, event_handler: F) -> Result<(), EventLoopError>
|
||||||
|
where
|
||||||
|
F: FnMut(Event<T>, &ActiveEventLoop),
|
||||||
|
{
|
||||||
|
self.event_loop.run(event_handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates an [`EventLoopProxy`] that can be used to dispatch user events
|
||||||
|
/// to the main event loop, possibly from another thread.
|
||||||
|
pub fn create_proxy(&self) -> EventLoopProxy<T> {
|
||||||
|
EventLoopProxy {
|
||||||
|
event_loop_proxy: self.event_loop.create_proxy(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets a persistent reference to the underlying platform display.
|
||||||
|
///
|
||||||
|
/// See the [`OwnedDisplayHandle`] type for more information.
|
||||||
|
pub fn owned_display_handle(&self) -> OwnedDisplayHandle {
|
||||||
|
OwnedDisplayHandle {
|
||||||
|
platform: self.event_loop.window_target().p.owned_display_handle(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Change if or when [`DeviceEvent`]s are captured.
|
||||||
|
///
|
||||||
|
/// See [`ActiveEventLoop::listen_device_events`] for details.
|
||||||
|
///
|
||||||
|
/// [`DeviceEvent`]: crate::event::DeviceEvent
|
||||||
|
pub fn listen_device_events(&self, allowed: DeviceEvents) {
|
||||||
|
self.event_loop
|
||||||
|
.window_target()
|
||||||
|
.p
|
||||||
|
.listen_device_events(allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the [`ControlFlow`].
|
||||||
|
pub fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||||
|
self.event_loop
|
||||||
|
.window_target()
|
||||||
|
.p
|
||||||
|
.set_control_flow(control_flow)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a window.
|
||||||
|
///
|
||||||
|
/// Creating window without event loop running often leads to improper window creation;
|
||||||
|
/// use [`ActiveEventLoop::create_window`] instead.
|
||||||
|
#[deprecated = "use `ActiveEventLoop::create_window` instead"]
|
||||||
|
#[inline]
|
||||||
|
pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> {
|
||||||
|
let window =
|
||||||
|
platform_impl::Window::new(&self.event_loop.window_target().p, window_attributes)?;
|
||||||
|
Ok(Window { window })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create custom cursor.
|
||||||
|
pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor {
|
||||||
|
self.event_loop
|
||||||
|
.window_target()
|
||||||
|
.p
|
||||||
|
.create_custom_cursor(custom_cursor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_06")]
|
||||||
|
impl<T> rwh_06::HasDisplayHandle for EventLoop<T> {
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
rwh_06::HasDisplayHandle::display_handle(self.event_loop.window_target())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_05")]
|
||||||
|
unsafe impl<T> rwh_05::HasRawDisplayHandle for EventLoop<T> {
|
||||||
|
/// Returns a [`rwh_05::RawDisplayHandle`] for the event loop.
|
||||||
|
fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
|
||||||
|
rwh_05::HasRawDisplayHandle::raw_display_handle(self.event_loop.window_target())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
impl<T> AsFd for EventLoop<T> {
|
||||||
|
/// Get the underlying [EventLoop]'s `fd` which you can register
|
||||||
|
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
||||||
|
/// loop must be polled with the [`pump_events`] API.
|
||||||
|
///
|
||||||
|
/// [`calloop`]: https://crates.io/crates/calloop
|
||||||
|
/// [`mio`]: https://crates.io/crates/mio
|
||||||
|
/// [`pump_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_events
|
||||||
|
fn as_fd(&self) -> BorrowedFd<'_> {
|
||||||
|
self.event_loop.as_fd()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
impl<T> AsRawFd for EventLoop<T> {
|
||||||
|
/// Get the underlying [EventLoop]'s raw `fd` which you can register
|
||||||
|
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
||||||
|
/// loop must be polled with the [`pump_events`] API.
|
||||||
|
///
|
||||||
|
/// [`calloop`]: https://crates.io/crates/calloop
|
||||||
|
/// [`mio`]: https://crates.io/crates/mio
|
||||||
|
/// [`pump_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_events
|
||||||
|
fn as_raw_fd(&self) -> RawFd {
|
||||||
|
self.event_loop.as_raw_fd()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActiveEventLoop {
|
||||||
|
/// Create the window.
|
||||||
|
///
|
||||||
|
/// Possible causes of error include denied permission, incompatible system, and lack of memory.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **Web:** The window is created but not inserted into the web page automatically. Please
|
||||||
|
/// see the web platform module for more information.
|
||||||
|
#[inline]
|
||||||
|
pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> {
|
||||||
|
let window = platform_impl::Window::new(&self.p, window_attributes)?;
|
||||||
|
Ok(Window { window })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create custom cursor.
|
||||||
|
pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor {
|
||||||
|
self.p.create_custom_cursor(custom_cursor)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the list of all the monitors available on the system.
|
||||||
|
#[inline]
|
||||||
|
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
|
||||||
|
#[allow(clippy::useless_conversion)] // false positive on some platforms
|
||||||
|
self.p
|
||||||
|
.available_monitors()
|
||||||
|
.into_iter()
|
||||||
|
.map(|inner| MonitorHandle { inner })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the primary monitor of the system.
|
||||||
|
///
|
||||||
|
/// Returns `None` if it can't identify any monitor as a primary one.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// **Wayland / Web:** Always returns `None`.
|
||||||
|
#[inline]
|
||||||
|
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||||
|
self.p
|
||||||
|
.primary_monitor()
|
||||||
|
.map(|inner| MonitorHandle { inner })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Change if or when [`DeviceEvent`]s are captured.
|
||||||
|
///
|
||||||
|
/// Since the [`DeviceEvent`] capture can lead to high CPU usage for unfocused windows, winit
|
||||||
|
/// will ignore them by default for unfocused windows on Linux/BSD. This method allows changing
|
||||||
|
/// this at runtime to explicitly capture them again.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **Wayland / macOS / iOS / Android / Orbital:** Unsupported.
|
||||||
|
///
|
||||||
|
/// [`DeviceEvent`]: crate::event::DeviceEvent
|
||||||
|
pub fn listen_device_events(&self, allowed: DeviceEvents) {
|
||||||
|
self.p.listen_device_events(allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the [`ControlFlow`].
|
||||||
|
pub fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||||
|
self.p.set_control_flow(control_flow)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets the current [`ControlFlow`].
|
||||||
|
pub fn control_flow(&self) -> ControlFlow {
|
||||||
|
self.p.control_flow()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This exits the event loop.
|
||||||
|
///
|
||||||
|
/// See [`LoopExiting`](Event::LoopExiting).
|
||||||
|
pub fn exit(&self) {
|
||||||
|
self.p.exit()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns if the [`EventLoop`] is about to stop.
|
||||||
|
///
|
||||||
|
/// See [`exit()`](Self::exit).
|
||||||
|
pub fn exiting(&self) -> bool {
|
||||||
|
self.p.exiting()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets a persistent reference to the underlying platform display.
|
||||||
|
///
|
||||||
|
/// See the [`OwnedDisplayHandle`] type for more information.
|
||||||
|
pub fn owned_display_handle(&self) -> OwnedDisplayHandle {
|
||||||
|
OwnedDisplayHandle {
|
||||||
|
platform: self.p.owned_display_handle(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_06")]
|
||||||
|
impl rwh_06::HasDisplayHandle for ActiveEventLoop {
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let raw = self.p.raw_display_handle_rwh_06()?;
|
||||||
|
// SAFETY: The display will never be deallocated while the event loop is alive.
|
||||||
|
Ok(unsafe { rwh_06::DisplayHandle::borrow_raw(raw) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_05")]
|
||||||
|
unsafe impl rwh_05::HasRawDisplayHandle for ActiveEventLoop {
|
||||||
|
/// Returns a [`rwh_05::RawDisplayHandle`] for the event loop.
|
||||||
|
fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
|
||||||
|
self.p.raw_display_handle_rwh_05()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A proxy for the underlying display handle.
|
||||||
|
///
|
||||||
|
/// The purpose of this type is to provide a cheaply clonable handle to the underlying
|
||||||
|
/// display handle. This is often used by graphics APIs to connect to the underlying APIs.
|
||||||
|
/// It is difficult to keep a handle to the [`EventLoop`] type or the [`ActiveEventLoop`]
|
||||||
|
/// type. In contrast, this type involves no lifetimes and can be persisted for as long as
|
||||||
|
/// needed.
|
||||||
|
///
|
||||||
|
/// For all platforms, this is one of the following:
|
||||||
|
///
|
||||||
|
/// - A zero-sized type that is likely optimized out.
|
||||||
|
/// - A reference-counted pointer to the underlying type.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct OwnedDisplayHandle {
|
||||||
|
#[cfg_attr(not(any(feature = "rwh_05", feature = "rwh_06")), allow(dead_code))]
|
||||||
|
platform: platform_impl::OwnedDisplayHandle,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for OwnedDisplayHandle {
|
||||||
|
#[inline]
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("OwnedDisplayHandle").finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_06")]
|
||||||
|
impl rwh_06::HasDisplayHandle for OwnedDisplayHandle {
|
||||||
|
#[inline]
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let raw = self.platform.raw_display_handle_rwh_06()?;
|
||||||
|
|
||||||
|
// SAFETY: The underlying display handle should be safe.
|
||||||
|
let handle = unsafe { rwh_06::DisplayHandle::borrow_raw(raw) };
|
||||||
|
|
||||||
|
Ok(handle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_05")]
|
||||||
|
unsafe impl rwh_05::HasRawDisplayHandle for OwnedDisplayHandle {
|
||||||
|
#[inline]
|
||||||
|
fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
|
||||||
|
self.platform.raw_display_handle_rwh_05()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Used to send custom events to [`EventLoop`].
|
||||||
|
pub struct EventLoopProxy<T: 'static> {
|
||||||
|
event_loop_proxy: platform_impl::EventLoopProxy<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static> Clone for EventLoopProxy<T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self {
|
||||||
|
event_loop_proxy: self.event_loop_proxy.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static> EventLoopProxy<T> {
|
||||||
|
/// Send an event to the [`EventLoop`] from which this proxy was created. This emits a
|
||||||
|
/// `UserEvent(event)` event in the event loop, where `event` is the value passed to this
|
||||||
|
/// function.
|
||||||
|
///
|
||||||
|
/// Returns an `Err` if the associated [`EventLoop`] no longer exists.
|
||||||
|
///
|
||||||
|
/// [`UserEvent(event)`]: Event::UserEvent
|
||||||
|
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
|
||||||
|
self.event_loop_proxy.send_event(event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static> fmt::Debug for EventLoopProxy<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.pad("EventLoopProxy { .. }")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The error that is returned when an [`EventLoopProxy`] attempts to wake up an [`EventLoop`] that
|
||||||
|
/// no longer exists.
|
||||||
|
///
|
||||||
|
/// Contains the original event given to [`EventLoopProxy::send_event`].
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub struct EventLoopClosed<T>(pub T);
|
||||||
|
|
||||||
|
impl<T> fmt::Display for EventLoopClosed<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str("Tried to wake up a closed `EventLoop`")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: fmt::Debug> error::Error for EventLoopClosed<T> {}
|
||||||
|
|
||||||
|
/// Control when device events are captured.
|
||||||
|
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
|
||||||
|
pub enum DeviceEvents {
|
||||||
|
/// Report device events regardless of window focus.
|
||||||
|
Always,
|
||||||
|
/// Only capture device events while the window is focused.
|
||||||
|
#[default]
|
||||||
|
WhenFocused,
|
||||||
|
/// Never capture device events.
|
||||||
|
Never,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A unique identifier of the winit's async request.
|
||||||
|
///
|
||||||
|
/// This could be used to identify the async request once it's done
|
||||||
|
/// and a specific action must be taken.
|
||||||
|
///
|
||||||
|
/// One of the handling scenarios could be to maintain a working list
|
||||||
|
/// containing [`AsyncRequestSerial`] and some closure associated with it.
|
||||||
|
/// Then once event is arriving the working list is being traversed and a job
|
||||||
|
/// executed and removed from the list.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct AsyncRequestSerial {
|
||||||
|
serial: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsyncRequestSerial {
|
||||||
|
// TODO(kchibisov): Remove `cfg` when the clipboard will be added.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) fn get() -> Self {
|
||||||
|
static CURRENT_SERIAL: AtomicUsize = AtomicUsize::new(0);
|
||||||
|
// NOTE: We rely on wrap around here, while the user may just request
|
||||||
|
// in the loop usize::MAX times that's issue is considered on them.
|
||||||
|
let serial = CURRENT_SERIAL.fetch_add(1, Ordering::Relaxed);
|
||||||
|
Self { serial }
|
||||||
|
}
|
||||||
|
}
|
||||||
454
src/events.rs
@@ -1,454 +0,0 @@
|
|||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use {DeviceId, LogicalPosition, LogicalSize, WindowId};
|
|
||||||
|
|
||||||
/// Describes a generic event.
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub enum Event {
|
|
||||||
WindowEvent {
|
|
||||||
window_id: WindowId,
|
|
||||||
event: WindowEvent,
|
|
||||||
},
|
|
||||||
DeviceEvent {
|
|
||||||
device_id: DeviceId,
|
|
||||||
event: DeviceEvent,
|
|
||||||
},
|
|
||||||
Awakened,
|
|
||||||
|
|
||||||
/// The application has been suspended or resumed.
|
|
||||||
///
|
|
||||||
/// The parameter is true if app was suspended, and false if it has been resumed.
|
|
||||||
Suspended(bool),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Describes an event from a `Window`.
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub enum WindowEvent {
|
|
||||||
/// The size of the window has changed. Contains the client area's new dimensions.
|
|
||||||
Resized(LogicalSize),
|
|
||||||
|
|
||||||
/// The position of the window has changed. Contains the window's new position.
|
|
||||||
Moved(LogicalPosition),
|
|
||||||
|
|
||||||
/// The window has been requested to close.
|
|
||||||
CloseRequested,
|
|
||||||
|
|
||||||
/// The window has been destroyed.
|
|
||||||
Destroyed,
|
|
||||||
|
|
||||||
/// A file has been dropped into the window.
|
|
||||||
DroppedFile(PathBuf),
|
|
||||||
|
|
||||||
/// A file is being hovered over the window.
|
|
||||||
HoveredFile(PathBuf),
|
|
||||||
|
|
||||||
/// A file was hovered, but has exited the window.
|
|
||||||
HoveredFileCancelled,
|
|
||||||
|
|
||||||
/// The window received a unicode character.
|
|
||||||
ReceivedCharacter(char),
|
|
||||||
|
|
||||||
/// The window gained or lost focus.
|
|
||||||
///
|
|
||||||
/// The parameter is true if the window has gained focus, and false if it has lost focus.
|
|
||||||
Focused(bool),
|
|
||||||
|
|
||||||
/// An event from the keyboard has been received.
|
|
||||||
KeyboardInput { device_id: DeviceId, input: KeyboardInput },
|
|
||||||
|
|
||||||
/// The cursor has moved on the window.
|
|
||||||
CursorMoved {
|
|
||||||
device_id: DeviceId,
|
|
||||||
|
|
||||||
/// (x,y) coords in pixels relative to the top-left corner of the window. Because the range of this data is
|
|
||||||
/// limited by the display area and it may have been transformed by the OS to implement effects such as cursor
|
|
||||||
/// acceleration, it should not be used to implement non-cursor-like interactions such as 3D camera control.
|
|
||||||
position: LogicalPosition,
|
|
||||||
modifiers: ModifiersState
|
|
||||||
},
|
|
||||||
|
|
||||||
/// The cursor has entered the window.
|
|
||||||
CursorEntered { device_id: DeviceId },
|
|
||||||
|
|
||||||
/// The cursor has left the window.
|
|
||||||
CursorLeft { device_id: DeviceId },
|
|
||||||
|
|
||||||
/// A mouse wheel movement or touchpad scroll occurred.
|
|
||||||
MouseWheel { device_id: DeviceId, delta: MouseScrollDelta, phase: TouchPhase, modifiers: ModifiersState },
|
|
||||||
|
|
||||||
/// An mouse button press has been received.
|
|
||||||
MouseInput { device_id: DeviceId, state: ElementState, button: MouseButton, modifiers: ModifiersState },
|
|
||||||
|
|
||||||
|
|
||||||
/// Touchpad pressure event.
|
|
||||||
///
|
|
||||||
/// At the moment, only supported on Apple forcetouch-capable macbooks.
|
|
||||||
/// The parameters are: pressure level (value between 0 and 1 representing how hard the touchpad
|
|
||||||
/// is being pressed) and stage (integer representing the click level).
|
|
||||||
TouchpadPressure { device_id: DeviceId, pressure: f32, stage: i64 },
|
|
||||||
|
|
||||||
/// Motion on some analog axis. May report data redundant to other, more specific events.
|
|
||||||
AxisMotion { device_id: DeviceId, axis: AxisId, value: f64 },
|
|
||||||
|
|
||||||
/// The window needs to be redrawn.
|
|
||||||
Refresh,
|
|
||||||
|
|
||||||
/// Touch event has been received
|
|
||||||
Touch(Touch),
|
|
||||||
|
|
||||||
/// The DPI factor of the window has changed.
|
|
||||||
///
|
|
||||||
/// The following user actions can cause DPI changes:
|
|
||||||
///
|
|
||||||
/// * Changing the display's resolution.
|
|
||||||
/// * Changing the display's DPI factor (e.g. in Control Panel on Windows).
|
|
||||||
/// * Moving the window to a display with a different DPI factor.
|
|
||||||
///
|
|
||||||
/// For more information about DPI in general, see the [`dpi`](dpi/index.html) module.
|
|
||||||
HiDpiFactorChanged(f64),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Represents raw hardware events that are not associated with any particular window.
|
|
||||||
///
|
|
||||||
/// Useful for interactions that diverge significantly from a conventional 2D GUI, such as 3D camera or first-person
|
|
||||||
/// game controls. Many physical actions, such as mouse movement, can produce both device and window events. Because
|
|
||||||
/// window events typically arise from virtual devices (corresponding to GUI cursors and keyboard focus) the device IDs
|
|
||||||
/// may not match.
|
|
||||||
///
|
|
||||||
/// Note that these events are delivered regardless of input focus.
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub enum DeviceEvent {
|
|
||||||
Added,
|
|
||||||
Removed,
|
|
||||||
|
|
||||||
/// Change in physical position of a pointing device.
|
|
||||||
///
|
|
||||||
/// This represents raw, unfiltered physical motion. Not to be confused with `WindowEvent::CursorMoved`.
|
|
||||||
MouseMotion {
|
|
||||||
/// (x, y) change in position in unspecified units.
|
|
||||||
///
|
|
||||||
/// Different devices may use different units.
|
|
||||||
delta: (f64, f64),
|
|
||||||
},
|
|
||||||
|
|
||||||
/// Physical scroll event
|
|
||||||
MouseWheel {
|
|
||||||
delta: MouseScrollDelta,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// Motion on some analog axis. This event will be reported for all arbitrary input devices
|
|
||||||
/// that winit supports on this platform, including mouse devices. If the device is a mouse
|
|
||||||
/// device then this will be reported alongside the MouseMotion event.
|
|
||||||
Motion { axis: AxisId, value: f64 },
|
|
||||||
|
|
||||||
Button { button: ButtonId, state: ElementState },
|
|
||||||
Key(KeyboardInput),
|
|
||||||
Text { codepoint: char },
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Describes a keyboard input event.
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
|
||||||
pub struct KeyboardInput {
|
|
||||||
/// Identifies the physical key pressed
|
|
||||||
///
|
|
||||||
/// This should not change if the user adjusts the host's keyboard map. Use when the physical location of the
|
|
||||||
/// key is more important than the key's host GUI semantics, such as for movement controls in a first-person
|
|
||||||
/// game.
|
|
||||||
pub scancode: ScanCode,
|
|
||||||
|
|
||||||
pub state: ElementState,
|
|
||||||
|
|
||||||
/// Identifies the semantic meaning of the key
|
|
||||||
///
|
|
||||||
/// Use when the semantics of the key are more important than the physical location of the key, such as when
|
|
||||||
/// implementing appropriate behavior for "page up."
|
|
||||||
pub virtual_keycode: Option<VirtualKeyCode>,
|
|
||||||
|
|
||||||
/// Modifier keys active at the time of this input.
|
|
||||||
///
|
|
||||||
/// This is tracked internally to avoid tracking errors arising from modifier key state changes when events from
|
|
||||||
/// this device are not being delivered to the application, e.g. due to keyboard focus being elsewhere.
|
|
||||||
pub modifiers: ModifiersState
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Describes touch-screen input state.
|
|
||||||
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
|
|
||||||
pub enum TouchPhase {
|
|
||||||
Started,
|
|
||||||
Moved,
|
|
||||||
Ended,
|
|
||||||
Cancelled
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Represents touch event
|
|
||||||
///
|
|
||||||
/// Every time user touches screen new Start event with some finger id is generated.
|
|
||||||
/// When the finger is removed from the screen End event with same id is generated.
|
|
||||||
///
|
|
||||||
/// For every id there will be at least 2 events with phases Start and End (or Cancelled).
|
|
||||||
/// There may be 0 or more Move events.
|
|
||||||
///
|
|
||||||
///
|
|
||||||
/// Depending on platform implementation id may or may not be reused by system after End event.
|
|
||||||
///
|
|
||||||
/// Gesture regonizer using this event should assume that Start event received with same id
|
|
||||||
/// as previously received End event is a new finger and has nothing to do with an old one.
|
|
||||||
///
|
|
||||||
/// Touch may be cancelled if for example window lost focus.
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
|
||||||
pub struct Touch {
|
|
||||||
pub device_id: DeviceId,
|
|
||||||
pub phase: TouchPhase,
|
|
||||||
pub location: LogicalPosition,
|
|
||||||
/// unique identifier of a finger.
|
|
||||||
pub id: u64
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Hardware-dependent keyboard scan code.
|
|
||||||
pub type ScanCode = u32;
|
|
||||||
|
|
||||||
/// Identifier for a specific analog axis on some device.
|
|
||||||
pub type AxisId = u32;
|
|
||||||
|
|
||||||
/// Identifier for a specific button on some device.
|
|
||||||
pub type ButtonId = u32;
|
|
||||||
|
|
||||||
/// Describes the input state of a key.
|
|
||||||
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
|
|
||||||
pub enum ElementState {
|
|
||||||
Pressed,
|
|
||||||
Released,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Describes a button of a mouse controller.
|
|
||||||
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
|
|
||||||
pub enum MouseButton {
|
|
||||||
Left,
|
|
||||||
Right,
|
|
||||||
Middle,
|
|
||||||
Other(u8),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Describes a difference in the mouse scroll wheel state.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
|
||||||
pub enum MouseScrollDelta {
|
|
||||||
/// Amount in lines or rows to scroll in the horizontal
|
|
||||||
/// and vertical directions.
|
|
||||||
///
|
|
||||||
/// Positive values indicate movement forward
|
|
||||||
/// (away from the user) or rightwards.
|
|
||||||
LineDelta(f32, f32),
|
|
||||||
/// Amount in pixels to scroll in the horizontal and
|
|
||||||
/// vertical direction.
|
|
||||||
///
|
|
||||||
/// Scroll events are expressed as a PixelDelta if
|
|
||||||
/// supported by the device (eg. a touchpad) and
|
|
||||||
/// platform.
|
|
||||||
PixelDelta(LogicalPosition),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Symbolic name for a keyboard key.
|
|
||||||
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
|
|
||||||
#[repr(u32)]
|
|
||||||
pub enum VirtualKeyCode {
|
|
||||||
/// The '1' key over the letters.
|
|
||||||
Key1,
|
|
||||||
/// The '2' key over the letters.
|
|
||||||
Key2,
|
|
||||||
/// The '3' key over the letters.
|
|
||||||
Key3,
|
|
||||||
/// The '4' key over the letters.
|
|
||||||
Key4,
|
|
||||||
/// The '5' key over the letters.
|
|
||||||
Key5,
|
|
||||||
/// The '6' key over the letters.
|
|
||||||
Key6,
|
|
||||||
/// The '7' key over the letters.
|
|
||||||
Key7,
|
|
||||||
/// The '8' key over the letters.
|
|
||||||
Key8,
|
|
||||||
/// The '9' key over the letters.
|
|
||||||
Key9,
|
|
||||||
/// The '0' key over the 'O' and 'P' keys.
|
|
||||||
Key0,
|
|
||||||
|
|
||||||
A,
|
|
||||||
B,
|
|
||||||
C,
|
|
||||||
D,
|
|
||||||
E,
|
|
||||||
F,
|
|
||||||
G,
|
|
||||||
H,
|
|
||||||
I,
|
|
||||||
J,
|
|
||||||
K,
|
|
||||||
L,
|
|
||||||
M,
|
|
||||||
N,
|
|
||||||
O,
|
|
||||||
P,
|
|
||||||
Q,
|
|
||||||
R,
|
|
||||||
S,
|
|
||||||
T,
|
|
||||||
U,
|
|
||||||
V,
|
|
||||||
W,
|
|
||||||
X,
|
|
||||||
Y,
|
|
||||||
Z,
|
|
||||||
|
|
||||||
/// The Escape key, next to F1.
|
|
||||||
Escape,
|
|
||||||
|
|
||||||
F1,
|
|
||||||
F2,
|
|
||||||
F3,
|
|
||||||
F4,
|
|
||||||
F5,
|
|
||||||
F6,
|
|
||||||
F7,
|
|
||||||
F8,
|
|
||||||
F9,
|
|
||||||
F10,
|
|
||||||
F11,
|
|
||||||
F12,
|
|
||||||
F13,
|
|
||||||
F14,
|
|
||||||
F15,
|
|
||||||
|
|
||||||
/// Print Screen/SysRq.
|
|
||||||
Snapshot,
|
|
||||||
/// Scroll Lock.
|
|
||||||
Scroll,
|
|
||||||
/// Pause/Break key, next to Scroll lock.
|
|
||||||
Pause,
|
|
||||||
|
|
||||||
/// `Insert`, next to Backspace.
|
|
||||||
Insert,
|
|
||||||
Home,
|
|
||||||
Delete,
|
|
||||||
End,
|
|
||||||
PageDown,
|
|
||||||
PageUp,
|
|
||||||
|
|
||||||
Left,
|
|
||||||
Up,
|
|
||||||
Right,
|
|
||||||
Down,
|
|
||||||
|
|
||||||
/// The Backspace key, right over Enter.
|
|
||||||
// TODO: rename
|
|
||||||
Back,
|
|
||||||
/// The Enter key.
|
|
||||||
Return,
|
|
||||||
/// The space bar.
|
|
||||||
Space,
|
|
||||||
|
|
||||||
/// The "Compose" key on Linux.
|
|
||||||
Compose,
|
|
||||||
|
|
||||||
Caret,
|
|
||||||
|
|
||||||
Numlock,
|
|
||||||
Numpad0,
|
|
||||||
Numpad1,
|
|
||||||
Numpad2,
|
|
||||||
Numpad3,
|
|
||||||
Numpad4,
|
|
||||||
Numpad5,
|
|
||||||
Numpad6,
|
|
||||||
Numpad7,
|
|
||||||
Numpad8,
|
|
||||||
Numpad9,
|
|
||||||
|
|
||||||
AbntC1,
|
|
||||||
AbntC2,
|
|
||||||
Add,
|
|
||||||
Apostrophe,
|
|
||||||
Apps,
|
|
||||||
At,
|
|
||||||
Ax,
|
|
||||||
Backslash,
|
|
||||||
Calculator,
|
|
||||||
Capital,
|
|
||||||
Colon,
|
|
||||||
Comma,
|
|
||||||
Convert,
|
|
||||||
Decimal,
|
|
||||||
Divide,
|
|
||||||
Equals,
|
|
||||||
Grave,
|
|
||||||
Kana,
|
|
||||||
Kanji,
|
|
||||||
LAlt,
|
|
||||||
LBracket,
|
|
||||||
LControl,
|
|
||||||
LShift,
|
|
||||||
LWin,
|
|
||||||
Mail,
|
|
||||||
MediaSelect,
|
|
||||||
MediaStop,
|
|
||||||
Minus,
|
|
||||||
Multiply,
|
|
||||||
Mute,
|
|
||||||
MyComputer,
|
|
||||||
NavigateForward, // also called "Prior"
|
|
||||||
NavigateBackward, // also called "Next"
|
|
||||||
NextTrack,
|
|
||||||
NoConvert,
|
|
||||||
NumpadComma,
|
|
||||||
NumpadEnter,
|
|
||||||
NumpadEquals,
|
|
||||||
OEM102,
|
|
||||||
Period,
|
|
||||||
PlayPause,
|
|
||||||
Power,
|
|
||||||
PrevTrack,
|
|
||||||
RAlt,
|
|
||||||
RBracket,
|
|
||||||
RControl,
|
|
||||||
RShift,
|
|
||||||
RWin,
|
|
||||||
Semicolon,
|
|
||||||
Slash,
|
|
||||||
Sleep,
|
|
||||||
Stop,
|
|
||||||
Subtract,
|
|
||||||
Sysrq,
|
|
||||||
Tab,
|
|
||||||
Underline,
|
|
||||||
Unlabeled,
|
|
||||||
VolumeDown,
|
|
||||||
VolumeUp,
|
|
||||||
Wake,
|
|
||||||
WebBack,
|
|
||||||
WebFavorites,
|
|
||||||
WebForward,
|
|
||||||
WebHome,
|
|
||||||
WebRefresh,
|
|
||||||
WebSearch,
|
|
||||||
WebStop,
|
|
||||||
Yen,
|
|
||||||
Copy,
|
|
||||||
Paste,
|
|
||||||
Cut,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Represents the current state of the keyboard modifiers
|
|
||||||
///
|
|
||||||
/// Each field of this struct represents a modifier and is `true` if this modifier is active.
|
|
||||||
#[derive(Default, Debug, Hash, PartialEq, Eq, Clone, Copy)]
|
|
||||||
pub struct ModifiersState {
|
|
||||||
/// The "shift" key
|
|
||||||
pub shift: bool,
|
|
||||||
/// The "control" key
|
|
||||||
pub ctrl: bool,
|
|
||||||
/// The "alt" key
|
|
||||||
pub alt: bool,
|
|
||||||
/// The "logo" key
|
|
||||||
///
|
|
||||||
/// This is the "windows" key on PC and "command" key on Mac.
|
|
||||||
pub logo: bool
|
|
||||||
}
|
|
||||||
197
src/icon.rs
@@ -1,12 +1,5 @@
|
|||||||
use std::{fmt, mem};
|
use crate::platform_impl::PlatformIcon;
|
||||||
use std::error::Error;
|
use std::{error::Error, fmt, io, mem};
|
||||||
#[cfg(feature = "icon_loading")]
|
|
||||||
use std::io::{BufRead, Seek};
|
|
||||||
#[cfg(feature = "icon_loading")]
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
#[cfg(feature = "icon_loading")]
|
|
||||||
use image;
|
|
||||||
|
|
||||||
#[repr(C)]
|
#[repr(C)]
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -19,14 +12,12 @@ pub(crate) struct Pixel {
|
|||||||
|
|
||||||
pub(crate) const PIXEL_SIZE: usize = mem::size_of::<Pixel>();
|
pub(crate) const PIXEL_SIZE: usize = mem::size_of::<Pixel>();
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug)]
|
||||||
/// An error produced when using `Icon::from_rgba` with invalid arguments.
|
/// An error produced when using [`Icon::from_rgba`] with invalid arguments.
|
||||||
pub enum BadIcon {
|
pub enum BadIcon {
|
||||||
/// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be
|
/// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be
|
||||||
/// safely interpreted as 32bpp RGBA pixels.
|
/// safely interpreted as 32bpp RGBA pixels.
|
||||||
ByteCountNotDivisibleBy4 {
|
ByteCountNotDivisibleBy4 { byte_count: usize },
|
||||||
byte_count: usize,
|
|
||||||
},
|
|
||||||
/// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`.
|
/// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`.
|
||||||
/// At least one of your arguments is incorrect.
|
/// At least one of your arguments is incorrect.
|
||||||
DimensionsVsPixelCount {
|
DimensionsVsPixelCount {
|
||||||
@@ -35,136 +26,100 @@ pub enum BadIcon {
|
|||||||
width_x_height: usize,
|
width_x_height: usize,
|
||||||
pixel_count: usize,
|
pixel_count: usize,
|
||||||
},
|
},
|
||||||
|
/// Produced when underlying OS functionality failed to create the icon
|
||||||
|
OsError(io::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for BadIcon {
|
impl fmt::Display for BadIcon {
|
||||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
let msg = match self {
|
match self {
|
||||||
&BadIcon::ByteCountNotDivisibleBy4 { byte_count } => format!(
|
BadIcon::ByteCountNotDivisibleBy4 { byte_count } => write!(f,
|
||||||
"The length of the `rgba` argument ({:?}) isn't divisible by 4, making it impossible to interpret as 32bpp RGBA pixels.",
|
"The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making it impossible to interpret as 32bpp RGBA pixels.",
|
||||||
byte_count,
|
|
||||||
),
|
),
|
||||||
&BadIcon::DimensionsVsPixelCount {
|
BadIcon::DimensionsVsPixelCount {
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
width_x_height,
|
width_x_height,
|
||||||
pixel_count,
|
pixel_count,
|
||||||
} => format!(
|
} => write!(f,
|
||||||
"The specified dimensions ({:?}x{:?}) don't match the number of pixels supplied by the `rgba` argument ({:?}). For those dimensions, the expected pixel count is {:?}.",
|
"The specified dimensions ({width:?}x{height:?}) don't match the number of pixels supplied by the `rgba` argument ({pixel_count:?}). For those dimensions, the expected pixel count is {width_x_height:?}.",
|
||||||
width, height, pixel_count, width_x_height,
|
|
||||||
),
|
),
|
||||||
};
|
BadIcon::OsError(e) => write!(f, "OS error when instantiating the icon: {e:?}"),
|
||||||
write!(formatter, "{}", msg)
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Error for BadIcon {
|
impl Error for BadIcon {}
|
||||||
fn description(&self) -> &str {
|
|
||||||
"A valid icon cannot be created from these arguments"
|
|
||||||
}
|
|
||||||
|
|
||||||
fn cause(&self) -> Option<&Error> {
|
|
||||||
Some(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
/// An icon used for the window titlebar, taskbar, etc.
|
pub(crate) struct RgbaIcon {
|
||||||
///
|
|
||||||
/// Enabling the `icon_loading` feature provides you with several convenience methods for creating
|
|
||||||
/// an `Icon` from any format supported by the [image](https://github.com/PistonDevelopers/image)
|
|
||||||
/// crate.
|
|
||||||
pub struct Icon {
|
|
||||||
pub(crate) rgba: Vec<u8>,
|
pub(crate) rgba: Vec<u8>,
|
||||||
pub(crate) width: u32,
|
pub(crate) width: u32,
|
||||||
pub(crate) height: u32,
|
pub(crate) height: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// For platforms which don't have window icons (e.g. web)
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub(crate) struct NoIcon;
|
||||||
|
|
||||||
|
#[allow(dead_code)] // These are not used on every platform
|
||||||
|
mod constructors {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
impl RgbaIcon {
|
||||||
|
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
||||||
|
if rgba.len() % PIXEL_SIZE != 0 {
|
||||||
|
return Err(BadIcon::ByteCountNotDivisibleBy4 {
|
||||||
|
byte_count: rgba.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let pixel_count = rgba.len() / PIXEL_SIZE;
|
||||||
|
if pixel_count != (width * height) as usize {
|
||||||
|
Err(BadIcon::DimensionsVsPixelCount {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
width_x_height: (width * height) as usize,
|
||||||
|
pixel_count,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
Ok(RgbaIcon {
|
||||||
|
rgba,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NoIcon {
|
||||||
|
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
||||||
|
// Create the rgba icon anyway to validate the input
|
||||||
|
let _ = RgbaIcon::from_rgba(rgba, width, height)?;
|
||||||
|
Ok(NoIcon)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An icon used for the window titlebar, taskbar, etc.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Icon {
|
||||||
|
pub(crate) inner: PlatformIcon,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for Icon {
|
||||||
|
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||||
|
fmt::Debug::fmt(&self.inner, formatter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Icon {
|
impl Icon {
|
||||||
/// Creates an `Icon` from 32bpp RGBA data.
|
/// Creates an icon from 32bpp RGBA data.
|
||||||
///
|
///
|
||||||
/// The length of `rgba` must be divisible by 4, and `width * height` must equal
|
/// The length of `rgba` must be divisible by 4, and `width * height` must equal
|
||||||
/// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error.
|
/// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error.
|
||||||
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
||||||
if rgba.len() % PIXEL_SIZE != 0 {
|
Ok(Icon {
|
||||||
return Err(BadIcon::ByteCountNotDivisibleBy4 { byte_count: rgba.len() });
|
inner: PlatformIcon::from_rgba(rgba, width, height)?,
|
||||||
}
|
})
|
||||||
let pixel_count = rgba.len() / PIXEL_SIZE;
|
|
||||||
if pixel_count != (width * height) as usize {
|
|
||||||
Err(BadIcon::DimensionsVsPixelCount {
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
width_x_height: (width * height) as usize,
|
|
||||||
pixel_count,
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
Ok(Icon { rgba, width, height })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "icon_loading")]
|
|
||||||
/// Loads an `Icon` from the path of an image on the filesystem.
|
|
||||||
///
|
|
||||||
/// Requires the `icon_loading` feature.
|
|
||||||
pub fn from_path<P: AsRef<Path>>(path: P) -> image::ImageResult<Self> {
|
|
||||||
image::open(path).map(Into::into)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "icon_loading")]
|
|
||||||
/// Loads an `Icon` from anything implementing `BufRead` and `Seek`.
|
|
||||||
///
|
|
||||||
/// Requires the `icon_loading` feature.
|
|
||||||
pub fn from_reader<R: BufRead + Seek>(
|
|
||||||
reader: R,
|
|
||||||
format: image::ImageFormat,
|
|
||||||
) -> image::ImageResult<Self> {
|
|
||||||
image::load(reader, format).map(Into::into)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "icon_loading")]
|
|
||||||
/// Loads an `Icon` from the unprocessed bytes of an image file.
|
|
||||||
/// Uses heuristics to determine format.
|
|
||||||
///
|
|
||||||
/// Requires the `icon_loading` feature.
|
|
||||||
pub fn from_bytes(bytes: &[u8]) -> image::ImageResult<Self> {
|
|
||||||
image::load_from_memory(bytes).map(Into::into)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "icon_loading")]
|
|
||||||
/// Loads an `Icon` from the unprocessed bytes of an image.
|
|
||||||
///
|
|
||||||
/// Requires the `icon_loading` feature.
|
|
||||||
pub fn from_bytes_with_format(
|
|
||||||
bytes: &[u8],
|
|
||||||
format: image::ImageFormat,
|
|
||||||
) -> image::ImageResult<Self> {
|
|
||||||
image::load_from_memory_with_format(bytes, format).map(Into::into)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "icon_loading")]
|
|
||||||
/// Requires the `icon_loading` feature.
|
|
||||||
impl From<image::DynamicImage> for Icon {
|
|
||||||
fn from(image: image::DynamicImage) -> Self {
|
|
||||||
use image::{GenericImage, Pixel};
|
|
||||||
let (width, height) = image.dimensions();
|
|
||||||
let mut rgba = Vec::with_capacity((width * height) as usize * PIXEL_SIZE);
|
|
||||||
for (_, _, pixel) in image.pixels() {
|
|
||||||
rgba.extend_from_slice(&pixel.to_rgba().data);
|
|
||||||
}
|
|
||||||
Icon { rgba, width, height }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "icon_loading")]
|
|
||||||
/// Requires the `icon_loading` feature.
|
|
||||||
impl From<image::RgbaImage> for Icon {
|
|
||||||
fn from(buf: image::RgbaImage) -> Self {
|
|
||||||
let (width, height) = buf.dimensions();
|
|
||||||
let mut rgba = Vec::with_capacity((width * height) as usize * PIXEL_SIZE);
|
|
||||||
for (_, _, pixel) in buf.enumerate_pixels() {
|
|
||||||
rgba.extend_from_slice(&pixel.data);
|
|
||||||
}
|
|
||||||
Icon { rgba, width, height }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
1801
src/keyboard.rs
Normal file
635
src/lib.rs
@@ -1,484 +1,215 @@
|
|||||||
//! Winit allows you to build a window on as many platforms as possible.
|
//! Winit is a cross-platform window creation and event loop management library.
|
||||||
//!
|
//!
|
||||||
//! # Building a window
|
//! # Building windows
|
||||||
//!
|
//!
|
||||||
//! Before you can build a window, you first need to build an `EventsLoop`. This is done with the
|
//! Before you can create a [`Window`], you first need to build an [`EventLoop`]. This is done with
|
||||||
//! `EventsLoop::new()` function. Example:
|
//! the [`EventLoop::new()`] function.
|
||||||
//!
|
//!
|
||||||
//! ```no_run
|
//! ```no_run
|
||||||
//! use winit::EventsLoop;
|
//! use winit::event_loop::EventLoop;
|
||||||
//! let events_loop = EventsLoop::new();
|
//! let event_loop = EventLoop::new().unwrap();
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! Once this is done there are two ways to create a window:
|
//! Then you create a [`Window`] with [`create_window`].
|
||||||
//!
|
//!
|
||||||
//! - Calling `Window::new(&events_loop)`.
|
//! # Event handling
|
||||||
//! - Calling `let builder = WindowBuilder::new()` then `builder.build(&events_loop)`.
|
|
||||||
//!
|
//!
|
||||||
//! The first way is the simplest way and will give you default values for everything.
|
//! Once a [`Window`] has been created, it will generate different *events*. A [`Window`] object can
|
||||||
|
//! generate [`WindowEvent`]s when certain input events occur, such as a cursor moving over the
|
||||||
|
//! window or a key getting pressed while the window is focused. Devices can generate
|
||||||
|
//! [`DeviceEvent`]s, which contain unfiltered event data that isn't specific to a certain window.
|
||||||
|
//! Some user activity, like mouse movement, can generate both a [`WindowEvent`] *and* a
|
||||||
|
//! [`DeviceEvent`]. You can also create and handle your own custom [`Event::UserEvent`]s, if desired.
|
||||||
//!
|
//!
|
||||||
//! The second way allows you to customize the way your window will look and behave by modifying
|
//! You can retrieve events by calling [`EventLoop::run()`]. This function will
|
||||||
//! the fields of the `WindowBuilder` object before you create the window.
|
//! dispatch events for every [`Window`] that was created with that particular [`EventLoop`], and
|
||||||
|
//! will run until [`exit()`] is used, at which point [`Event::LoopExiting`].
|
||||||
//!
|
//!
|
||||||
//! # Events handling
|
//! Winit no longer uses a `EventLoop::poll_events() -> impl Iterator<Event>`-based event loop
|
||||||
|
//! model, since that can't be implemented properly on some platforms (e.g web, iOS) and works poorly on
|
||||||
|
//! most other platforms. However, this model can be re-implemented to an extent with
|
||||||
|
#![cfg_attr(
|
||||||
|
any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
android_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform
|
||||||
|
),
|
||||||
|
doc = "[`EventLoopExtPumpEvents::pump_events()`][platform::pump_events::EventLoopExtPumpEvents::pump_events()]"
|
||||||
|
)]
|
||||||
|
#![cfg_attr(
|
||||||
|
not(any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
android_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform
|
||||||
|
)),
|
||||||
|
doc = "`EventLoopExtPumpEvents::pump_events()`"
|
||||||
|
)]
|
||||||
|
//! [^1]. See that method's documentation for more reasons about why
|
||||||
|
//! it's discouraged beyond compatibility reasons.
|
||||||
//!
|
//!
|
||||||
//! Once a window has been created, it will *generate events*. For example whenever the user moves
|
|
||||||
//! the window, resizes the window, moves the mouse, etc. an event is generated.
|
|
||||||
//!
|
|
||||||
//! The events generated by a window can be retrieved from the `EventsLoop` the window was created
|
|
||||||
//! with.
|
|
||||||
//!
|
|
||||||
//! There are two ways to do so. The first is to call `events_loop.poll_events(...)`, which will
|
|
||||||
//! retrieve all the events pending on the windows and immediately return after no new event is
|
|
||||||
//! available. You usually want to use this method in application that render continuously on the
|
|
||||||
//! screen, such as video games.
|
|
||||||
//!
|
//!
|
||||||
//! ```no_run
|
//! ```no_run
|
||||||
//! use winit::{Event, WindowEvent};
|
//! use winit::{
|
||||||
//! use winit::dpi::LogicalSize;
|
//! event::{Event, WindowEvent},
|
||||||
//! # use winit::EventsLoop;
|
//! event_loop::{ControlFlow, EventLoop},
|
||||||
//! # let mut events_loop = EventsLoop::new();
|
//! window::Window,
|
||||||
|
//! };
|
||||||
//!
|
//!
|
||||||
//! loop {
|
//! let event_loop = EventLoop::new().unwrap();
|
||||||
//! events_loop.poll_events(|event| {
|
|
||||||
//! match event {
|
|
||||||
//! Event::WindowEvent {
|
|
||||||
//! event: WindowEvent::Resized(LogicalSize { width, height }),
|
|
||||||
//! ..
|
|
||||||
//! } => {
|
|
||||||
//! println!("The window was resized to {}x{}", width, height);
|
|
||||||
//! },
|
|
||||||
//! _ => ()
|
|
||||||
//! }
|
|
||||||
//! });
|
|
||||||
//! }
|
|
||||||
//! ```
|
|
||||||
//!
|
//!
|
||||||
//! The second way is to call `events_loop.run_forever(...)`. As its name tells, it will run
|
//! // ControlFlow::Poll continuously runs the event loop, even if the OS hasn't
|
||||||
//! forever unless it is stopped by returning `ControlFlow::Break`.
|
//! // dispatched any events. This is ideal for games and similar applications.
|
||||||
|
//! event_loop.set_control_flow(ControlFlow::Poll);
|
||||||
//!
|
//!
|
||||||
//! ```no_run
|
//! // ControlFlow::Wait pauses the event loop if no events are available to process.
|
||||||
//! use winit::{ControlFlow, Event, WindowEvent};
|
//! // This is ideal for non-game applications that only update in response to user
|
||||||
//! # use winit::EventsLoop;
|
//! // input, and uses significantly less power/CPU time than ControlFlow::Poll.
|
||||||
//! # let mut events_loop = EventsLoop::new();
|
//! event_loop.set_control_flow(ControlFlow::Wait);
|
||||||
//!
|
//!
|
||||||
//! events_loop.run_forever(|event| {
|
//! let mut window = None;
|
||||||
|
//!
|
||||||
|
//! event_loop.run(move |event, event_loop| {
|
||||||
//! match event {
|
//! match event {
|
||||||
//! Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => {
|
//! Event::Resumed => {
|
||||||
|
//! window = Some(event_loop.create_window(Window::default_attributes()).unwrap());
|
||||||
|
//! }
|
||||||
|
//! Event::WindowEvent {
|
||||||
|
//! event: WindowEvent::CloseRequested,
|
||||||
|
//! ..
|
||||||
|
//! } => {
|
||||||
//! println!("The close button was pressed; stopping");
|
//! println!("The close button was pressed; stopping");
|
||||||
//! ControlFlow::Break
|
//! event_loop.exit();
|
||||||
//! },
|
//! },
|
||||||
//! _ => ControlFlow::Continue,
|
//! Event::AboutToWait => {
|
||||||
|
//! // Application update code.
|
||||||
|
//!
|
||||||
|
//! // Queue a RedrawRequested event.
|
||||||
|
//! //
|
||||||
|
//! // You only need to call this if you've determined that you need to redraw in
|
||||||
|
//! // applications which do not always need to. Applications that redraw continuously
|
||||||
|
//! // can render here instead.
|
||||||
|
//! window.as_ref().unwrap().request_redraw();
|
||||||
|
//! },
|
||||||
|
//! Event::WindowEvent {
|
||||||
|
//! event: 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.
|
||||||
|
//! },
|
||||||
|
//! _ => ()
|
||||||
//! }
|
//! }
|
||||||
//! });
|
//! });
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! If you use multiple windows, the `WindowEvent` event has a member named `window_id`. You can
|
//! [`WindowEvent`] has a [`WindowId`] member. In multi-window environments, it should be
|
||||||
//! compare it with the value returned by the `id()` method of `Window` in order to know which
|
//! compared to the value returned by [`Window::id()`] to determine which [`Window`]
|
||||||
//! window has received the event.
|
//! dispatched the event.
|
||||||
//!
|
//!
|
||||||
//! # Drawing on the window
|
//! # Drawing on the window
|
||||||
//!
|
//!
|
||||||
//! Winit doesn't provide any function that allows drawing on a window. However it allows you to
|
//! Winit doesn't directly provide any methods for drawing on a [`Window`]. However, it allows you to
|
||||||
//! retrieve the raw handle of the window (see the `os` module for that), which in turn allows you
|
//! retrieve the raw handle of the window and display (see the [`platform`] module and/or the
|
||||||
//! to create an OpenGL/Vulkan/DirectX/Metal/etc. context that will draw on the window.
|
//! [`raw_window_handle`] and [`raw_display_handle`] methods), which in turn allows
|
||||||
|
//! you to create an OpenGL/Vulkan/DirectX/Metal/etc. context that can be used to render graphics.
|
||||||
//!
|
//!
|
||||||
|
//! Note that many platforms will display garbage data in the window's client area if the
|
||||||
|
//! application doesn't render anything to the window by the time the desktop compositor is ready to
|
||||||
|
//! display the window to the user. If you notice this happening, you should create the window with
|
||||||
|
//! [`visible` set to `false`](crate::window::WindowAttributes::with_visible) and explicitly make the
|
||||||
|
//! window visible only once you're ready to render into it.
|
||||||
|
//!
|
||||||
|
//! # UI scaling
|
||||||
|
//!
|
||||||
|
//! UI scaling is important, go read the docs for the [`dpi`] crate for an
|
||||||
|
//! introduction.
|
||||||
|
//!
|
||||||
|
//! All of Winit's functions return physical types, but can take either logical or physical
|
||||||
|
//! coordinates as input, allowing you to use the most convenient coordinate system for your
|
||||||
|
//! particular application.
|
||||||
|
//!
|
||||||
|
//! Winit will dispatch a [`ScaleFactorChanged`] event whenever a window's scale factor has changed.
|
||||||
|
//! This can happen if the user drags their window from a standard-resolution monitor to a high-DPI
|
||||||
|
//! monitor or if the user changes their DPI settings. This allows you to rescale your application's
|
||||||
|
//! UI elements and adjust how the platform changes the window's size to reflect the new scale
|
||||||
|
//! factor. If a window hasn't received a [`ScaleFactorChanged`] event, its scale factor
|
||||||
|
//! can be found by calling [`window.scale_factor()`].
|
||||||
|
//!
|
||||||
|
//! [`ScaleFactorChanged`]: event::WindowEvent::ScaleFactorChanged
|
||||||
|
//! [`window.scale_factor()`]: window::Window::scale_factor
|
||||||
|
//!
|
||||||
|
//! # Cargo Features
|
||||||
|
//!
|
||||||
|
//! Winit provides the following Cargo features:
|
||||||
|
//!
|
||||||
|
//! * `x11` (enabled by default): On Unix platforms, enables the X11 backend.
|
||||||
|
//! * `wayland` (enabled by default): On Unix platforms, enables the Wayland
|
||||||
|
//! backend.
|
||||||
|
//! * `rwh_04`: Implement `raw-window-handle v0.4` traits.
|
||||||
|
//! * `rwh_05`: Implement `raw-window-handle v0.5` traits.
|
||||||
|
//! * `rwh_06`: Implement `raw-window-handle v0.6` traits.
|
||||||
|
//! * `serde`: Enables serialization/deserialization of certain types with
|
||||||
|
//! [Serde](https://crates.io/crates/serde).
|
||||||
|
//! * `mint`: Enables mint (math interoperability standard types) conversions.
|
||||||
|
//!
|
||||||
|
//! See the [`platform`] module for documentation on platform-specific cargo
|
||||||
|
//! features.
|
||||||
|
//!
|
||||||
|
//! [`EventLoop`]: event_loop::EventLoop
|
||||||
|
//! [`EventLoop::new()`]: event_loop::EventLoop::new
|
||||||
|
//! [`EventLoop::run()`]: event_loop::EventLoop::run
|
||||||
|
//! [`exit()`]: event_loop::ActiveEventLoop::exit
|
||||||
|
//! [`Window`]: window::Window
|
||||||
|
//! [`WindowId`]: window::WindowId
|
||||||
|
//! [`WindowAttributes`]: window::WindowAttributes
|
||||||
|
//! [window_new]: window::Window::new
|
||||||
|
//! [`create_window`]: event_loop::ActiveEventLoop::create_window
|
||||||
|
//! [`Window::id()`]: window::Window::id
|
||||||
|
//! [`WindowEvent`]: event::WindowEvent
|
||||||
|
//! [`DeviceEvent`]: event::DeviceEvent
|
||||||
|
//! [`Event::UserEvent`]: event::Event::UserEvent
|
||||||
|
//! [`Event::LoopExiting`]: event::Event::LoopExiting
|
||||||
|
//! [`raw_window_handle`]: ./window/struct.Window.html#method.raw_window_handle
|
||||||
|
//! [`raw_display_handle`]: ./window/struct.Window.html#method.raw_display_handle
|
||||||
|
//! [^1]: `EventLoopExtPumpEvents::pump_events()` is only available on Windows, macOS, Android, X11 and Wayland.
|
||||||
|
|
||||||
|
#![deny(rust_2018_idioms)]
|
||||||
|
#![deny(rustdoc::broken_intra_doc_links)]
|
||||||
|
#![deny(clippy::all)]
|
||||||
|
#![deny(unsafe_op_in_unsafe_fn)]
|
||||||
|
#![cfg_attr(clippy, deny(warnings))]
|
||||||
|
// Doc feature labels can be tested locally by running RUSTDOCFLAGS="--cfg=docsrs" cargo +nightly doc
|
||||||
|
#![cfg_attr(
|
||||||
|
docsrs,
|
||||||
|
feature(doc_auto_cfg, doc_cfg_hide),
|
||||||
|
doc(cfg_hide(doc, docsrs))
|
||||||
|
)]
|
||||||
|
#![allow(clippy::missing_safety_doc)]
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_06")]
|
||||||
|
pub use rwh_06 as raw_window_handle;
|
||||||
|
|
||||||
|
// Re-export DPI types so that users don't have to put it in Cargo.toml.
|
||||||
|
#[doc(inline)]
|
||||||
|
pub use dpi;
|
||||||
|
|
||||||
#[allow(unused_imports)]
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate lazy_static;
|
pub mod error;
|
||||||
extern crate libc;
|
mod cursor;
|
||||||
#[macro_use]
|
pub mod event;
|
||||||
extern crate log;
|
pub mod event_loop;
|
||||||
#[cfg(feature = "icon_loading")]
|
|
||||||
extern crate image;
|
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
extern crate winapi;
|
|
||||||
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
|
||||||
#[macro_use]
|
|
||||||
extern crate objc;
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
extern crate cocoa;
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
extern crate core_foundation;
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
extern crate core_graphics;
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))]
|
|
||||||
extern crate x11_dl;
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))]
|
|
||||||
extern crate parking_lot;
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))]
|
|
||||||
extern crate percent_encoding;
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))]
|
|
||||||
extern crate smithay_client_toolkit as sctk;
|
|
||||||
|
|
||||||
pub(crate) use dpi::*; // TODO: Actually change the imports throughout the codebase.
|
|
||||||
pub use events::*;
|
|
||||||
pub use window::{AvailableMonitorsIter, MonitorId};
|
|
||||||
pub use icon::*;
|
|
||||||
|
|
||||||
pub mod dpi;
|
|
||||||
mod events;
|
|
||||||
mod icon;
|
mod icon;
|
||||||
mod platform;
|
pub mod keyboard;
|
||||||
mod window;
|
pub mod monitor;
|
||||||
|
mod platform_impl;
|
||||||
|
mod utils;
|
||||||
|
pub mod window;
|
||||||
|
|
||||||
pub mod os;
|
pub mod platform;
|
||||||
|
|
||||||
/// Represents a window.
|
|
||||||
///
|
|
||||||
/// # Example
|
|
||||||
///
|
|
||||||
/// ```no_run
|
|
||||||
/// use winit::{Event, EventsLoop, Window, WindowEvent, ControlFlow};
|
|
||||||
///
|
|
||||||
/// let mut events_loop = EventsLoop::new();
|
|
||||||
/// let window = Window::new(&events_loop).unwrap();
|
|
||||||
///
|
|
||||||
/// events_loop.run_forever(|event| {
|
|
||||||
/// match event {
|
|
||||||
/// Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => {
|
|
||||||
/// ControlFlow::Break
|
|
||||||
/// },
|
|
||||||
/// _ => ControlFlow::Continue,
|
|
||||||
/// }
|
|
||||||
/// });
|
|
||||||
/// ```
|
|
||||||
pub struct Window {
|
|
||||||
window: platform::Window,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Identifier of a window. Unique for each window.
|
|
||||||
///
|
|
||||||
/// Can be obtained with `window.id()`.
|
|
||||||
///
|
|
||||||
/// Whenever you receive an event specific to a window, this event contains a `WindowId` which you
|
|
||||||
/// can then compare to the ids of your windows.
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub struct WindowId(platform::WindowId);
|
|
||||||
|
|
||||||
/// Identifier of an input device.
|
|
||||||
///
|
|
||||||
/// Whenever you receive an event arising from a particular input device, this event contains a `DeviceId` which
|
|
||||||
/// identifies its origin. Note that devices may be virtual (representing an on-screen cursor and keyboard focus) or
|
|
||||||
/// physical. Virtual devices typically aggregate inputs from multiple physical devices.
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub struct DeviceId(platform::DeviceId);
|
|
||||||
|
|
||||||
/// Provides a way to retrieve events from the system and from the windows that were registered to
|
|
||||||
/// the events loop.
|
|
||||||
///
|
|
||||||
/// An `EventsLoop` can be seen more or less as a "context". Calling `EventsLoop::new()`
|
|
||||||
/// initializes everything that will be required to create windows. For example on Linux creating
|
|
||||||
/// an events loop opens a connection to the X or Wayland server.
|
|
||||||
///
|
|
||||||
/// To wake up an `EventsLoop` from a another thread, see the `EventsLoopProxy` docs.
|
|
||||||
///
|
|
||||||
/// Note that the `EventsLoop` cannot be shared accross threads (due to platform-dependant logic
|
|
||||||
/// forbiding it), as such it is neither `Send` nor `Sync`. If you need cross-thread access, the
|
|
||||||
/// `Window` created from this `EventsLoop` _can_ be sent to an other thread, and the
|
|
||||||
/// `EventsLoopProxy` allows you to wakeup an `EventsLoop` from an other thread.
|
|
||||||
pub struct EventsLoop {
|
|
||||||
events_loop: platform::EventsLoop,
|
|
||||||
_marker: ::std::marker::PhantomData<*mut ()> // Not Send nor Sync
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returned by the user callback given to the `EventsLoop::run_forever` method.
|
|
||||||
///
|
|
||||||
/// Indicates whether the `run_forever` method should continue or complete.
|
|
||||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub enum ControlFlow {
|
|
||||||
/// Continue looping and waiting for events.
|
|
||||||
Continue,
|
|
||||||
/// Break from the event loop.
|
|
||||||
Break,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventsLoop {
|
|
||||||
/// Builds a new events loop.
|
|
||||||
///
|
|
||||||
/// Usage will result in display backend initialisation, this can be controlled on linux
|
|
||||||
/// using an environment variable `WINIT_UNIX_BACKEND`. Legal values are `x11` and `wayland`.
|
|
||||||
/// If it is not set, winit will try to connect to a wayland connection, and if it fails will
|
|
||||||
/// fallback on x11. If this variable is set with any other value, winit will panic.
|
|
||||||
pub fn new() -> EventsLoop {
|
|
||||||
EventsLoop {
|
|
||||||
events_loop: platform::EventsLoop::new(),
|
|
||||||
_marker: ::std::marker::PhantomData,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the list of all the monitors available on the system.
|
|
||||||
///
|
|
||||||
// Note: should be replaced with `-> impl Iterator` once stable.
|
|
||||||
#[inline]
|
|
||||||
pub fn get_available_monitors(&self) -> AvailableMonitorsIter {
|
|
||||||
let data = self.events_loop.get_available_monitors();
|
|
||||||
AvailableMonitorsIter{ data: data.into_iter() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the primary monitor of the system.
|
|
||||||
#[inline]
|
|
||||||
pub fn get_primary_monitor(&self) -> MonitorId {
|
|
||||||
MonitorId { inner: self.events_loop.get_primary_monitor() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Fetches all the events that are pending, calls the callback function for each of them,
|
|
||||||
/// and returns.
|
|
||||||
#[inline]
|
|
||||||
pub fn poll_events<F>(&mut self, callback: F)
|
|
||||||
where F: FnMut(Event)
|
|
||||||
{
|
|
||||||
self.events_loop.poll_events(callback)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Calls `callback` every time an event is received. If no event is available, sleeps the
|
|
||||||
/// current thread and waits for an event. If the callback returns `ControlFlow::Break` then
|
|
||||||
/// `run_forever` will immediately return.
|
|
||||||
///
|
|
||||||
/// # Danger!
|
|
||||||
///
|
|
||||||
/// The callback is run after *every* event, so if its execution time is non-trivial the event queue may not empty
|
|
||||||
/// at a sufficient rate. Rendering in the callback with vsync enabled **will** cause significant lag.
|
|
||||||
#[inline]
|
|
||||||
pub fn run_forever<F>(&mut self, callback: F)
|
|
||||||
where F: FnMut(Event) -> ControlFlow
|
|
||||||
{
|
|
||||||
self.events_loop.run_forever(callback)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates an `EventsLoopProxy` that can be used to wake up the `EventsLoop` from another
|
|
||||||
/// thread.
|
|
||||||
pub fn create_proxy(&self) -> EventsLoopProxy {
|
|
||||||
EventsLoopProxy {
|
|
||||||
events_loop_proxy: self.events_loop.create_proxy(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Used to wake up the `EventsLoop` from another thread.
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct EventsLoopProxy {
|
|
||||||
events_loop_proxy: platform::EventsLoopProxy,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventsLoopProxy {
|
|
||||||
/// Wake up the `EventsLoop` from which this proxy was created.
|
|
||||||
///
|
|
||||||
/// This causes the `EventsLoop` to emit an `Awakened` event.
|
|
||||||
///
|
|
||||||
/// Returns an `Err` if the associated `EventsLoop` no longer exists.
|
|
||||||
pub fn wakeup(&self) -> Result<(), EventsLoopClosed> {
|
|
||||||
self.events_loop_proxy.wakeup()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The error that is returned when an `EventsLoopProxy` attempts to wake up an `EventsLoop` that
|
|
||||||
/// no longer exists.
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
|
||||||
pub struct EventsLoopClosed;
|
|
||||||
|
|
||||||
impl std::fmt::Display for EventsLoopClosed {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
|
||||||
write!(f, "{}", std::error::Error::description(self))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for EventsLoopClosed {
|
|
||||||
fn description(&self) -> &str {
|
|
||||||
"Tried to wake up a closed `EventsLoop`"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Object that allows you to build windows.
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct WindowBuilder {
|
|
||||||
/// The attributes to use to create the window.
|
|
||||||
pub window: WindowAttributes,
|
|
||||||
|
|
||||||
// Platform-specific configuration. Private.
|
|
||||||
platform_specific: platform::PlatformSpecificWindowBuilderAttributes,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Error that can happen while creating a window or a headless renderer.
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub enum CreationError {
|
|
||||||
OsError(String),
|
|
||||||
/// TODO: remove this error
|
|
||||||
NotSupported,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CreationError {
|
|
||||||
fn to_string(&self) -> &str {
|
|
||||||
match *self {
|
|
||||||
CreationError::OsError(ref text) => &text,
|
|
||||||
CreationError::NotSupported => "Some of the requested attributes are not supported",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Display for CreationError {
|
|
||||||
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
|
|
||||||
formatter.write_str(self.to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for CreationError {
|
|
||||||
fn description(&self) -> &str {
|
|
||||||
self.to_string()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Describes the appearance of the mouse cursor.
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
|
||||||
pub enum MouseCursor {
|
|
||||||
/// The platform-dependent default cursor.
|
|
||||||
Default,
|
|
||||||
/// A simple crosshair.
|
|
||||||
Crosshair,
|
|
||||||
/// A hand (often used to indicate links in web browsers).
|
|
||||||
Hand,
|
|
||||||
/// Self explanatory.
|
|
||||||
Arrow,
|
|
||||||
/// Indicates something is to be moved.
|
|
||||||
Move,
|
|
||||||
/// Indicates text that may be selected or edited.
|
|
||||||
Text,
|
|
||||||
/// Program busy indicator.
|
|
||||||
Wait,
|
|
||||||
/// Help indicator (often rendered as a "?")
|
|
||||||
Help,
|
|
||||||
/// Progress indicator. Shows that processing is being done. But in contrast
|
|
||||||
/// with "Wait" the user may still interact with the program. Often rendered
|
|
||||||
/// as a spinning beach ball, or an arrow with a watch or hourglass.
|
|
||||||
Progress,
|
|
||||||
|
|
||||||
/// Cursor showing that something cannot be done.
|
|
||||||
NotAllowed,
|
|
||||||
ContextMenu,
|
|
||||||
Cell,
|
|
||||||
VerticalText,
|
|
||||||
Alias,
|
|
||||||
Copy,
|
|
||||||
NoDrop,
|
|
||||||
Grab,
|
|
||||||
Grabbing,
|
|
||||||
AllScroll,
|
|
||||||
ZoomIn,
|
|
||||||
ZoomOut,
|
|
||||||
|
|
||||||
/// Indicate that some edge is to be moved. For example, the 'SeResize' cursor
|
|
||||||
/// is used when the movement starts from the south-east corner of the box.
|
|
||||||
EResize,
|
|
||||||
NResize,
|
|
||||||
NeResize,
|
|
||||||
NwResize,
|
|
||||||
SResize,
|
|
||||||
SeResize,
|
|
||||||
SwResize,
|
|
||||||
WResize,
|
|
||||||
EwResize,
|
|
||||||
NsResize,
|
|
||||||
NeswResize,
|
|
||||||
NwseResize,
|
|
||||||
ColResize,
|
|
||||||
RowResize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for MouseCursor {
|
|
||||||
fn default() -> Self {
|
|
||||||
MouseCursor::Default
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Attributes to use when creating a window.
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct WindowAttributes {
|
|
||||||
/// The dimensions of the window. If this is `None`, some platform-specific dimensions will be
|
|
||||||
/// used.
|
|
||||||
///
|
|
||||||
/// The default is `None`.
|
|
||||||
pub dimensions: Option<LogicalSize>,
|
|
||||||
|
|
||||||
/// The minimum dimensions a window can be, If this is `None`, the window will have no minimum dimensions (aside from reserved).
|
|
||||||
///
|
|
||||||
/// The default is `None`.
|
|
||||||
pub min_dimensions: Option<LogicalSize>,
|
|
||||||
|
|
||||||
/// The maximum dimensions a window can be, If this is `None`, the maximum will have no maximum or will be set to the primary monitor's dimensions by the platform.
|
|
||||||
///
|
|
||||||
/// The default is `None`.
|
|
||||||
pub max_dimensions: Option<LogicalSize>,
|
|
||||||
|
|
||||||
/// Whether the window is resizable or not.
|
|
||||||
///
|
|
||||||
/// The default is `true`.
|
|
||||||
pub resizable: bool,
|
|
||||||
|
|
||||||
/// Whether the window should be set as fullscreen upon creation.
|
|
||||||
///
|
|
||||||
/// The default is `None`.
|
|
||||||
pub fullscreen: Option<MonitorId>,
|
|
||||||
|
|
||||||
/// The title of the window in the title bar.
|
|
||||||
///
|
|
||||||
/// The default is `"winit window"`.
|
|
||||||
pub title: String,
|
|
||||||
|
|
||||||
/// Whether the window should be maximized upon creation.
|
|
||||||
///
|
|
||||||
/// The default is `false`.
|
|
||||||
pub maximized: bool,
|
|
||||||
|
|
||||||
/// Whether the window should be immediately visible upon creation.
|
|
||||||
///
|
|
||||||
/// The default is `true`.
|
|
||||||
pub visible: bool,
|
|
||||||
|
|
||||||
/// Whether the the window should be transparent. If this is true, writing colors
|
|
||||||
/// with alpha values different than `1.0` will produce a transparent window.
|
|
||||||
///
|
|
||||||
/// The default is `false`.
|
|
||||||
pub transparent: bool,
|
|
||||||
|
|
||||||
/// Whether the window should have borders and bars.
|
|
||||||
///
|
|
||||||
/// The default is `true`.
|
|
||||||
pub decorations: bool,
|
|
||||||
|
|
||||||
/// Whether the window should always be on top of other windows.
|
|
||||||
///
|
|
||||||
/// The default is `false`.
|
|
||||||
pub always_on_top: bool,
|
|
||||||
|
|
||||||
/// The window icon.
|
|
||||||
///
|
|
||||||
/// The default is `None`.
|
|
||||||
pub window_icon: Option<Icon>,
|
|
||||||
|
|
||||||
/// [iOS only] Enable multitouch,
|
|
||||||
/// see [multipleTouchEnabled](https://developer.apple.com/documentation/uikit/uiview/1622519-multipletouchenabled)
|
|
||||||
pub multitouch: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for WindowAttributes {
|
|
||||||
#[inline]
|
|
||||||
fn default() -> WindowAttributes {
|
|
||||||
WindowAttributes {
|
|
||||||
dimensions: None,
|
|
||||||
min_dimensions: None,
|
|
||||||
max_dimensions: None,
|
|
||||||
resizable: true,
|
|
||||||
title: "winit window".to_owned(),
|
|
||||||
maximized: false,
|
|
||||||
fullscreen: None,
|
|
||||||
visible: true,
|
|
||||||
transparent: false,
|
|
||||||
decorations: true,
|
|
||||||
always_on_top: false,
|
|
||||||
window_icon: None,
|
|
||||||
multitouch: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
173
src/monitor.rs
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
//! Types useful for interacting with a user's monitors.
|
||||||
|
//!
|
||||||
|
//! If you want to get basic information about a monitor, you can use the
|
||||||
|
//! [`MonitorHandle`] type. This is retrieved from one of the following
|
||||||
|
//! methods, which return an iterator of [`MonitorHandle`]:
|
||||||
|
//! - [`ActiveEventLoop::available_monitors`](crate::event_loop::ActiveEventLoop::available_monitors).
|
||||||
|
//! - [`Window::available_monitors`](crate::window::Window::available_monitors).
|
||||||
|
use crate::{
|
||||||
|
dpi::{PhysicalPosition, PhysicalSize},
|
||||||
|
platform_impl,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Deprecated! Use `VideoModeHandle` instead.
|
||||||
|
#[deprecated = "Renamed to `VideoModeHandle`"]
|
||||||
|
pub type VideoMode = VideoModeHandle;
|
||||||
|
|
||||||
|
/// Describes a fullscreen video mode of a monitor.
|
||||||
|
///
|
||||||
|
/// Can be acquired with [`MonitorHandle::video_modes`].
|
||||||
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub struct VideoModeHandle {
|
||||||
|
pub(crate) video_mode: platform_impl::VideoModeHandle,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for VideoModeHandle {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
self.video_mode.fmt(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialOrd for VideoModeHandle {
|
||||||
|
fn partial_cmp(&self, other: &VideoModeHandle) -> Option<std::cmp::Ordering> {
|
||||||
|
Some(self.cmp(other))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ord for VideoModeHandle {
|
||||||
|
fn cmp(&self, other: &VideoModeHandle) -> std::cmp::Ordering {
|
||||||
|
self.monitor().cmp(&other.monitor()).then(
|
||||||
|
self.size()
|
||||||
|
.cmp(&other.size())
|
||||||
|
.then(
|
||||||
|
self.refresh_rate_millihertz()
|
||||||
|
.cmp(&other.refresh_rate_millihertz())
|
||||||
|
.then(self.bit_depth().cmp(&other.bit_depth())),
|
||||||
|
)
|
||||||
|
.reverse(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VideoModeHandle {
|
||||||
|
/// Returns the resolution of this video mode.
|
||||||
|
#[inline]
|
||||||
|
pub fn size(&self) -> PhysicalSize<u32> {
|
||||||
|
self.video_mode.size()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the bit depth of this video mode, as in how many bits you have
|
||||||
|
/// available per color. This is generally 24 bits or 32 bits on modern
|
||||||
|
/// systems, depending on whether the alpha channel is counted or not.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **Wayland / Orbital:** Always returns 32.
|
||||||
|
/// - **iOS:** Always returns 32.
|
||||||
|
#[inline]
|
||||||
|
pub fn bit_depth(&self) -> u16 {
|
||||||
|
self.video_mode.bit_depth()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the refresh rate of this video mode in mHz.
|
||||||
|
#[inline]
|
||||||
|
pub fn refresh_rate_millihertz(&self) -> u32 {
|
||||||
|
self.video_mode.refresh_rate_millihertz()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the monitor that this video mode is valid for. Each monitor has
|
||||||
|
/// a separate set of valid video modes.
|
||||||
|
#[inline]
|
||||||
|
pub fn monitor(&self) -> MonitorHandle {
|
||||||
|
MonitorHandle {
|
||||||
|
inner: self.video_mode.monitor(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for VideoModeHandle {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(
|
||||||
|
f,
|
||||||
|
"{}x{} @ {} mHz ({} bpp)",
|
||||||
|
self.size().width,
|
||||||
|
self.size().height,
|
||||||
|
self.refresh_rate_millihertz(),
|
||||||
|
self.bit_depth()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handle to a monitor.
|
||||||
|
///
|
||||||
|
/// Allows you to retrieve information about a given monitor and can be used in [`Window`] creation.
|
||||||
|
///
|
||||||
|
/// [`Window`]: crate::window::Window
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
pub struct MonitorHandle {
|
||||||
|
pub(crate) inner: platform_impl::MonitorHandle,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonitorHandle {
|
||||||
|
/// Returns a human-readable name of the monitor.
|
||||||
|
///
|
||||||
|
/// Returns `None` if the monitor doesn't exist anymore.
|
||||||
|
#[inline]
|
||||||
|
pub fn name(&self) -> Option<String> {
|
||||||
|
self.inner.name()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the monitor's resolution.
|
||||||
|
#[inline]
|
||||||
|
pub fn size(&self) -> PhysicalSize<u32> {
|
||||||
|
self.inner.size()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the top-left corner position of the monitor relative to the larger full
|
||||||
|
/// screen area.
|
||||||
|
#[inline]
|
||||||
|
pub fn position(&self) -> PhysicalPosition<i32> {
|
||||||
|
self.inner.position()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The monitor refresh rate used by the system.
|
||||||
|
///
|
||||||
|
/// Return `Some` if succeed, or `None` if failed, which usually happens when the monitor
|
||||||
|
/// the window is on is removed.
|
||||||
|
///
|
||||||
|
/// When using exclusive fullscreen, the refresh rate of the [`VideoModeHandle`] that was
|
||||||
|
/// used to enter fullscreen should be used instead.
|
||||||
|
#[inline]
|
||||||
|
pub fn refresh_rate_millihertz(&self) -> Option<u32> {
|
||||||
|
self.inner.refresh_rate_millihertz()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the scale factor of the underlying monitor. To map logical pixels to physical
|
||||||
|
/// pixels and vice versa, use [`Window::scale_factor`].
|
||||||
|
///
|
||||||
|
/// See the [`dpi`] module for more information.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **X11:** Can be overridden using the `WINIT_X11_SCALE_FACTOR` environment variable.
|
||||||
|
/// - **Wayland:** May differ from [`Window::scale_factor`].
|
||||||
|
/// - **Android:** Always returns 1.0.
|
||||||
|
///
|
||||||
|
/// [`Window::scale_factor`]: crate::window::Window::scale_factor
|
||||||
|
#[inline]
|
||||||
|
pub fn scale_factor(&self) -> f64 {
|
||||||
|
self.inner.scale_factor()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns all fullscreen video modes supported by this monitor.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **Web:** Always returns an empty iterator
|
||||||
|
#[inline]
|
||||||
|
pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> {
|
||||||
|
self.inner
|
||||||
|
.video_modes()
|
||||||
|
.map(|video_mode| VideoModeHandle { video_mode })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
#![cfg(any(target_os = "android"))]
|
|
||||||
|
|
||||||
use std::os::raw::c_void;
|
|
||||||
use EventsLoop;
|
|
||||||
use Window;
|
|
||||||
use WindowBuilder;
|
|
||||||
|
|
||||||
/// Additional methods on `EventsLoop` that are specific to Android.
|
|
||||||
pub trait EventsLoopExt {
|
|
||||||
/// Makes it possible for glutin to register a callback when a suspend event happens on Android
|
|
||||||
fn set_suspend_callback(&self, cb: Option<Box<Fn(bool) -> ()>>);
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventsLoopExt for EventsLoop {
|
|
||||||
fn set_suspend_callback(&self, cb: Option<Box<Fn(bool) -> ()>>) {
|
|
||||||
self.events_loop.set_suspend_callback(cb);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on `Window` that are specific to Android.
|
|
||||||
pub trait WindowExt {
|
|
||||||
fn get_native_window(&self) -> *const c_void;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowExt for Window {
|
|
||||||
#[inline]
|
|
||||||
fn get_native_window(&self) -> *const c_void {
|
|
||||||
self.window.get_native_window()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on `WindowBuilder` that are specific to Android.
|
|
||||||
pub trait WindowBuilderExt {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowBuilderExt for WindowBuilder {
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
#![cfg(target_os = "ios")]
|
|
||||||
|
|
||||||
use std::os::raw::c_void;
|
|
||||||
|
|
||||||
use {MonitorId, Window, WindowBuilder};
|
|
||||||
|
|
||||||
/// Additional methods on `Window` that are specific to iOS.
|
|
||||||
pub trait WindowExt {
|
|
||||||
/// Returns a pointer to the `UIWindow` that is used by this window.
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the `Window` is destroyed.
|
|
||||||
fn get_uiwindow(&self) -> *mut c_void;
|
|
||||||
|
|
||||||
/// Returns a pointer to the `UIView` that is used by this window.
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the `Window` is destroyed.
|
|
||||||
fn get_uiview(&self) -> *mut c_void;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowExt for Window {
|
|
||||||
#[inline]
|
|
||||||
fn get_uiwindow(&self) -> *mut c_void {
|
|
||||||
self.window.get_uiwindow() as _
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn get_uiview(&self) -> *mut c_void {
|
|
||||||
self.window.get_uiview() as _
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on `WindowBuilder` that are specific to iOS.
|
|
||||||
pub trait WindowBuilderExt {
|
|
||||||
/// Sets the root view class used by the `Window`, otherwise a barebones `UIView` is provided.
|
|
||||||
///
|
|
||||||
/// The class will be initialized by calling `[root_view initWithFrame:CGRect]`
|
|
||||||
fn with_root_view_class(self, root_view_class: *const c_void) -> WindowBuilder;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowBuilderExt for WindowBuilder {
|
|
||||||
#[inline]
|
|
||||||
fn with_root_view_class(mut self, root_view_class: *const c_void) -> WindowBuilder {
|
|
||||||
self.platform_specific.root_view_class = unsafe { &*(root_view_class as *const _) };
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on `MonitorId` that are specific to iOS.
|
|
||||||
pub trait MonitorIdExt {
|
|
||||||
/// Returns a pointer to the `UIScreen` that is used by this monitor.
|
|
||||||
fn get_uiscreen(&self) -> *mut c_void;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorIdExt for MonitorId {
|
|
||||||
#[inline]
|
|
||||||
fn get_uiscreen(&self) -> *mut c_void {
|
|
||||||
self.inner.get_uiscreen() as _
|
|
||||||
}
|
|
||||||
}
|
|
||||||
159
src/os/macos.rs
@@ -1,159 +0,0 @@
|
|||||||
#![cfg(target_os = "macos")]
|
|
||||||
|
|
||||||
use std::convert::From;
|
|
||||||
use std::os::raw::c_void;
|
|
||||||
use cocoa::appkit::NSApplicationActivationPolicy;
|
|
||||||
use {LogicalSize, MonitorId, Window, WindowBuilder};
|
|
||||||
|
|
||||||
/// Additional methods on `Window` that are specific to MacOS.
|
|
||||||
pub trait WindowExt {
|
|
||||||
/// Returns a pointer to the cocoa `NSWindow` that is used by this window.
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the `Window` is destroyed.
|
|
||||||
fn get_nswindow(&self) -> *mut c_void;
|
|
||||||
|
|
||||||
/// Returns a pointer to the cocoa `NSView` that is used by this window.
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the `Window` is destroyed.
|
|
||||||
fn get_nsview(&self) -> *mut c_void;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowExt for Window {
|
|
||||||
#[inline]
|
|
||||||
fn get_nswindow(&self) -> *mut c_void {
|
|
||||||
self.window.get_nswindow()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn get_nsview(&self) -> *mut c_void {
|
|
||||||
self.window.get_nsview()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Corresponds to `NSApplicationActivationPolicy`.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
|
||||||
pub enum ActivationPolicy {
|
|
||||||
/// Corresponds to `NSApplicationActivationPolicyRegular`.
|
|
||||||
Regular,
|
|
||||||
/// Corresponds to `NSApplicationActivationPolicyAccessory`.
|
|
||||||
Accessory,
|
|
||||||
/// Corresponds to `NSApplicationActivationPolicyProhibited`.
|
|
||||||
Prohibited,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for ActivationPolicy {
|
|
||||||
fn default() -> Self {
|
|
||||||
ActivationPolicy::Regular
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<ActivationPolicy> for NSApplicationActivationPolicy {
|
|
||||||
fn from(activation_policy: ActivationPolicy) -> Self {
|
|
||||||
match activation_policy {
|
|
||||||
ActivationPolicy::Regular =>
|
|
||||||
NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
|
|
||||||
ActivationPolicy::Accessory =>
|
|
||||||
NSApplicationActivationPolicy::NSApplicationActivationPolicyAccessory,
|
|
||||||
ActivationPolicy::Prohibited =>
|
|
||||||
NSApplicationActivationPolicy::NSApplicationActivationPolicyProhibited,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on `WindowBuilder` that are specific to MacOS.
|
|
||||||
///
|
|
||||||
/// **Note:** Properties dealing with the titlebar will be overwritten by the `with_decorations` method
|
|
||||||
/// on the base `WindowBuilder`:
|
|
||||||
///
|
|
||||||
/// - `with_titlebar_transparent`
|
|
||||||
/// - `with_title_hidden`
|
|
||||||
/// - `with_titlebar_hidden`
|
|
||||||
/// - `with_titlebar_buttons_hidden`
|
|
||||||
/// - `with_fullsize_content_view`
|
|
||||||
pub trait WindowBuilderExt {
|
|
||||||
/// Sets the activation policy for the window being built.
|
|
||||||
fn with_activation_policy(self, activation_policy: ActivationPolicy) -> WindowBuilder;
|
|
||||||
/// Enables click-and-drag behavior for the entire window, not just the titlebar.
|
|
||||||
fn with_movable_by_window_background(self, movable_by_window_background: bool) -> WindowBuilder;
|
|
||||||
/// Makes the titlebar transparent and allows the content to appear behind it.
|
|
||||||
fn with_titlebar_transparent(self, titlebar_transparent: bool) -> WindowBuilder;
|
|
||||||
/// Hides the window title.
|
|
||||||
fn with_title_hidden(self, title_hidden: bool) -> WindowBuilder;
|
|
||||||
/// Hides the window titlebar.
|
|
||||||
fn with_titlebar_hidden(self, titlebar_hidden: bool) -> WindowBuilder;
|
|
||||||
/// Hides the window titlebar buttons.
|
|
||||||
fn with_titlebar_buttons_hidden(self, titlebar_buttons_hidden: bool) -> WindowBuilder;
|
|
||||||
/// Makes the window content appear behind the titlebar.
|
|
||||||
fn with_fullsize_content_view(self, fullsize_content_view: bool) -> WindowBuilder;
|
|
||||||
/// Build window with `resizeIncrements` property. Values must not be 0.
|
|
||||||
fn with_resize_increments(self, increments: LogicalSize) -> WindowBuilder;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowBuilderExt for WindowBuilder {
|
|
||||||
#[inline]
|
|
||||||
fn with_activation_policy(mut self, activation_policy: ActivationPolicy) -> WindowBuilder {
|
|
||||||
self.platform_specific.activation_policy = activation_policy;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_movable_by_window_background(mut self, movable_by_window_background: bool) -> WindowBuilder {
|
|
||||||
self.platform_specific.movable_by_window_background = movable_by_window_background;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> WindowBuilder {
|
|
||||||
self.platform_specific.titlebar_transparent = titlebar_transparent;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_titlebar_hidden(mut self, titlebar_hidden: bool) -> WindowBuilder {
|
|
||||||
self.platform_specific.titlebar_hidden = titlebar_hidden;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_titlebar_buttons_hidden(mut self, titlebar_buttons_hidden: bool) -> WindowBuilder {
|
|
||||||
self.platform_specific.titlebar_buttons_hidden = titlebar_buttons_hidden;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_title_hidden(mut self, title_hidden: bool) -> WindowBuilder {
|
|
||||||
self.platform_specific.title_hidden = title_hidden;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_fullsize_content_view(mut self, fullsize_content_view: bool) -> WindowBuilder {
|
|
||||||
self.platform_specific.fullsize_content_view = fullsize_content_view;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_resize_increments(mut self, increments: LogicalSize) -> WindowBuilder {
|
|
||||||
self.platform_specific.resize_increments = Some(increments.into());
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on `MonitorId` that are specific to MacOS.
|
|
||||||
pub trait MonitorIdExt {
|
|
||||||
/// Returns the identifier of the monitor for Cocoa.
|
|
||||||
fn native_id(&self) -> u32;
|
|
||||||
/// Returns a pointer to the NSScreen representing this monitor.
|
|
||||||
fn get_nsscreen(&self) -> Option<*mut c_void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorIdExt for MonitorId {
|
|
||||||
#[inline]
|
|
||||||
fn native_id(&self) -> u32 {
|
|
||||||
self.inner.get_native_identifier()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_nsscreen(&self) -> Option<*mut c_void> {
|
|
||||||
self.inner.get_nsscreen().map(|s| s as *mut c_void)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
//! Contains traits with platform-specific methods in them.
|
|
||||||
//!
|
|
||||||
//! Contains the follow modules:
|
|
||||||
//!
|
|
||||||
//! - `android`
|
|
||||||
//! - `ios`
|
|
||||||
//! - `macos`
|
|
||||||
//! - `unix`
|
|
||||||
//! - `windows`
|
|
||||||
//!
|
|
||||||
//! However only the module corresponding to the platform you're compiling to will be available.
|
|
||||||
//!
|
|
||||||
pub mod android;
|
|
||||||
pub mod ios;
|
|
||||||
pub mod macos;
|
|
||||||
pub mod unix;
|
|
||||||
pub mod windows;
|
|
||||||
285
src/os/unix.rs
@@ -1,285 +0,0 @@
|
|||||||
#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))]
|
|
||||||
|
|
||||||
use std::os::raw;
|
|
||||||
use std::ptr;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use {
|
|
||||||
EventsLoop,
|
|
||||||
LogicalSize,
|
|
||||||
MonitorId,
|
|
||||||
Window,
|
|
||||||
WindowBuilder,
|
|
||||||
};
|
|
||||||
use platform::{
|
|
||||||
EventsLoop as LinuxEventsLoop,
|
|
||||||
Window as LinuxWindow,
|
|
||||||
};
|
|
||||||
use platform::x11::XConnection;
|
|
||||||
use platform::x11::ffi::XVisualInfo;
|
|
||||||
|
|
||||||
// TODO: stupid hack so that glutin can do its work
|
|
||||||
#[doc(hidden)]
|
|
||||||
pub use platform::x11;
|
|
||||||
|
|
||||||
pub use platform::XNotSupported;
|
|
||||||
pub use platform::x11::util::WindowType as XWindowType;
|
|
||||||
|
|
||||||
/// Additional methods on `EventsLoop` that are specific to Linux.
|
|
||||||
pub trait EventsLoopExt {
|
|
||||||
/// Builds a new `EventsLoop` that is forced to use X11.
|
|
||||||
fn new_x11() -> Result<Self, XNotSupported>
|
|
||||||
where Self: Sized;
|
|
||||||
|
|
||||||
/// Builds a new `EventsLoop` that is forced to use Wayland.
|
|
||||||
fn new_wayland() -> Self
|
|
||||||
where Self: Sized;
|
|
||||||
|
|
||||||
/// True if the `EventsLoop` uses Wayland.
|
|
||||||
fn is_wayland(&self) -> bool;
|
|
||||||
|
|
||||||
/// True if the `EventsLoop` uses X11.
|
|
||||||
fn is_x11(&self) -> bool;
|
|
||||||
|
|
||||||
#[doc(hidden)]
|
|
||||||
fn get_xlib_xconnection(&self) -> Option<Arc<XConnection>>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventsLoopExt for EventsLoop {
|
|
||||||
#[inline]
|
|
||||||
fn new_x11() -> Result<Self, XNotSupported> {
|
|
||||||
LinuxEventsLoop::new_x11().map(|ev|
|
|
||||||
EventsLoop {
|
|
||||||
events_loop: ev,
|
|
||||||
_marker: ::std::marker::PhantomData,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn new_wayland() -> Self {
|
|
||||||
EventsLoop {
|
|
||||||
events_loop: match LinuxEventsLoop::new_wayland() {
|
|
||||||
Ok(e) => e,
|
|
||||||
Err(_) => panic!() // TODO: propagate
|
|
||||||
},
|
|
||||||
_marker: ::std::marker::PhantomData,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn is_wayland(&self) -> bool {
|
|
||||||
self.events_loop.is_wayland()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn is_x11(&self) -> bool {
|
|
||||||
!self.events_loop.is_wayland()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
#[doc(hidden)]
|
|
||||||
fn get_xlib_xconnection(&self) -> Option<Arc<XConnection>> {
|
|
||||||
self.events_loop.x_connection().cloned()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on `Window` that are specific to Unix.
|
|
||||||
pub trait WindowExt {
|
|
||||||
/// Returns the ID of the `Window` xlib object that is used by this window.
|
|
||||||
///
|
|
||||||
/// Returns `None` if the window doesn't use xlib (if it uses wayland for example).
|
|
||||||
fn get_xlib_window(&self) -> Option<raw::c_ulong>;
|
|
||||||
|
|
||||||
/// Returns a pointer to the `Display` object of xlib that is used by this window.
|
|
||||||
///
|
|
||||||
/// Returns `None` if the window doesn't use xlib (if it uses wayland for example).
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the glutin `Window` is destroyed.
|
|
||||||
fn get_xlib_display(&self) -> Option<*mut raw::c_void>;
|
|
||||||
|
|
||||||
fn get_xlib_screen_id(&self) -> Option<raw::c_int>;
|
|
||||||
|
|
||||||
#[doc(hidden)]
|
|
||||||
fn get_xlib_xconnection(&self) -> Option<Arc<XConnection>>;
|
|
||||||
|
|
||||||
/// Set window urgency hint (`XUrgencyHint`). Only relevant on X.
|
|
||||||
fn set_urgent(&self, is_urgent: bool);
|
|
||||||
|
|
||||||
/// This function returns the underlying `xcb_connection_t` of an xlib `Display`.
|
|
||||||
///
|
|
||||||
/// Returns `None` if the window doesn't use xlib (if it uses wayland for example).
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the glutin `Window` is destroyed.
|
|
||||||
fn get_xcb_connection(&self) -> Option<*mut raw::c_void>;
|
|
||||||
|
|
||||||
/// Returns a pointer to the `wl_surface` object of wayland that is used by this window.
|
|
||||||
///
|
|
||||||
/// Returns `None` if the window doesn't use wayland (if it uses xlib for example).
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the glutin `Window` is destroyed.
|
|
||||||
fn get_wayland_surface(&self) -> Option<*mut raw::c_void>;
|
|
||||||
|
|
||||||
/// Returns a pointer to the `wl_display` object of wayland that is used by this window.
|
|
||||||
///
|
|
||||||
/// Returns `None` if the window doesn't use wayland (if it uses xlib for example).
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the glutin `Window` is destroyed.
|
|
||||||
fn get_wayland_display(&self) -> Option<*mut raw::c_void>;
|
|
||||||
|
|
||||||
/// Check if the window is ready for drawing
|
|
||||||
///
|
|
||||||
/// It is a remnant of a previous implementation detail for the
|
|
||||||
/// wayland backend, and is no longer relevant.
|
|
||||||
///
|
|
||||||
/// Always return true.
|
|
||||||
#[deprecated]
|
|
||||||
fn is_ready(&self) -> bool;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowExt for Window {
|
|
||||||
#[inline]
|
|
||||||
fn get_xlib_window(&self) -> Option<raw::c_ulong> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::X(ref w) => Some(w.get_xlib_window()),
|
|
||||||
_ => None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn get_xlib_display(&self) -> Option<*mut raw::c_void> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::X(ref w) => Some(w.get_xlib_display()),
|
|
||||||
_ => None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn get_xlib_screen_id(&self) -> Option<raw::c_int> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::X(ref w) => Some(w.get_xlib_screen_id()),
|
|
||||||
_ => None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
#[doc(hidden)]
|
|
||||||
fn get_xlib_xconnection(&self) -> Option<Arc<XConnection>> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::X(ref w) => Some(w.get_xlib_xconnection()),
|
|
||||||
_ => None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn get_xcb_connection(&self) -> Option<*mut raw::c_void> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::X(ref w) => Some(w.get_xcb_connection()),
|
|
||||||
_ => None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn set_urgent(&self, is_urgent: bool) {
|
|
||||||
if let LinuxWindow::X(ref w) = self.window {
|
|
||||||
w.set_urgent(is_urgent);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn get_wayland_surface(&self) -> Option<*mut raw::c_void> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::Wayland(ref w) => Some(w.get_surface().c_ptr() as *mut _),
|
|
||||||
_ => None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn get_wayland_display(&self) -> Option<*mut raw::c_void> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::Wayland(ref w) => Some(w.get_display().c_ptr() as *mut _),
|
|
||||||
_ => None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn is_ready(&self) -> bool {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on `WindowBuilder` that are specific to Unix.
|
|
||||||
pub trait WindowBuilderExt {
|
|
||||||
fn with_x11_visual<T>(self, visual_infos: *const T) -> WindowBuilder;
|
|
||||||
fn with_x11_screen(self, screen_id: i32) -> WindowBuilder;
|
|
||||||
|
|
||||||
/// Build window with `WM_CLASS` hint; defaults to the name of the binary. Only relevant on X11.
|
|
||||||
fn with_class(self, class: String, instance: String) -> WindowBuilder;
|
|
||||||
/// Build window with override-redirect flag; defaults to false. Only relevant on X11.
|
|
||||||
fn with_override_redirect(self, override_redirect: bool) -> WindowBuilder;
|
|
||||||
/// Build window with `_NET_WM_WINDOW_TYPE` hint; defaults to `Normal`. Only relevant on X11.
|
|
||||||
fn with_x11_window_type(self, x11_window_type: XWindowType) -> WindowBuilder;
|
|
||||||
/// Build window with resize increment hint. Only implemented on X11.
|
|
||||||
fn with_resize_increments(self, increments: LogicalSize) -> WindowBuilder;
|
|
||||||
/// Build window with base size hint. Only implemented on X11.
|
|
||||||
fn with_base_size(self, base_size: LogicalSize) -> WindowBuilder;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowBuilderExt for WindowBuilder {
|
|
||||||
#[inline]
|
|
||||||
fn with_x11_visual<T>(mut self, visual_infos: *const T) -> WindowBuilder {
|
|
||||||
self.platform_specific.visual_infos = Some(
|
|
||||||
unsafe { ptr::read(visual_infos as *const XVisualInfo) }
|
|
||||||
);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_x11_screen(mut self, screen_id: i32) -> WindowBuilder {
|
|
||||||
self.platform_specific.screen_id = Some(screen_id);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_class(mut self, instance: String, class: String) -> WindowBuilder {
|
|
||||||
self.platform_specific.class = Some((instance, class));
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_override_redirect(mut self, override_redirect: bool) -> WindowBuilder {
|
|
||||||
self.platform_specific.override_redirect = override_redirect;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_x11_window_type(mut self, x11_window_type: XWindowType) -> WindowBuilder {
|
|
||||||
self.platform_specific.x11_window_type = x11_window_type;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_resize_increments(mut self, increments: LogicalSize) -> WindowBuilder {
|
|
||||||
self.platform_specific.resize_increments = Some(increments.into());
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_base_size(mut self, base_size: LogicalSize) -> WindowBuilder {
|
|
||||||
self.platform_specific.base_size = Some(base_size.into());
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on `MonitorId` that are specific to Linux.
|
|
||||||
pub trait MonitorIdExt {
|
|
||||||
/// Returns the inner identifier of the monitor.
|
|
||||||
fn native_id(&self) -> u32;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorIdExt for MonitorId {
|
|
||||||
#[inline]
|
|
||||||
fn native_id(&self) -> u32 {
|
|
||||||
self.inner.get_native_identifier()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
#![cfg(target_os = "windows")]
|
|
||||||
|
|
||||||
use std::os::raw::c_void;
|
|
||||||
|
|
||||||
use libc;
|
|
||||||
use winapi::shared::windef::HWND;
|
|
||||||
|
|
||||||
use {DeviceId, EventsLoop, Icon, MonitorId, Window, WindowBuilder};
|
|
||||||
use platform::EventsLoop as WindowsEventsLoop;
|
|
||||||
|
|
||||||
/// Additional methods on `EventsLoop` that are specific to Windows.
|
|
||||||
pub trait EventsLoopExt {
|
|
||||||
/// By default, winit on Windows will attempt to enable process-wide DPI awareness. If that's
|
|
||||||
/// undesirable, you can create an `EventsLoop` using this function instead.
|
|
||||||
fn new_dpi_unaware() -> Self where Self: Sized;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventsLoopExt for EventsLoop {
|
|
||||||
#[inline]
|
|
||||||
fn new_dpi_unaware() -> Self {
|
|
||||||
EventsLoop {
|
|
||||||
events_loop: WindowsEventsLoop::with_dpi_awareness(false),
|
|
||||||
_marker: ::std::marker::PhantomData,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on `Window` that are specific to Windows.
|
|
||||||
pub trait WindowExt {
|
|
||||||
/// Returns the native handle that is used by this window.
|
|
||||||
///
|
|
||||||
/// The pointer will become invalid when the native window was destroyed.
|
|
||||||
fn get_hwnd(&self) -> *mut libc::c_void;
|
|
||||||
|
|
||||||
/// This sets `ICON_BIG`. A good ceiling here is 256x256.
|
|
||||||
fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>);
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowExt for Window {
|
|
||||||
#[inline]
|
|
||||||
fn get_hwnd(&self) -> *mut libc::c_void {
|
|
||||||
self.window.hwnd() as *mut _
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>) {
|
|
||||||
self.window.set_taskbar_icon(taskbar_icon)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on `WindowBuilder` that are specific to Windows.
|
|
||||||
pub trait WindowBuilderExt {
|
|
||||||
/// Sets a parent to the window to be created.
|
|
||||||
fn with_parent_window(self, parent: HWND) -> WindowBuilder;
|
|
||||||
|
|
||||||
/// This sets `ICON_BIG`. A good ceiling here is 256x256.
|
|
||||||
fn with_taskbar_icon(self, taskbar_icon: Option<Icon>) -> WindowBuilder;
|
|
||||||
|
|
||||||
/// This sets `WS_EX_NOREDIRECTIONBITMAP`.
|
|
||||||
fn with_no_redirection_bitmap(self, flag: bool) -> WindowBuilder;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowBuilderExt for WindowBuilder {
|
|
||||||
#[inline]
|
|
||||||
fn with_parent_window(mut self, parent: HWND) -> WindowBuilder {
|
|
||||||
self.platform_specific.parent = Some(parent);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_taskbar_icon(mut self, taskbar_icon: Option<Icon>) -> WindowBuilder {
|
|
||||||
self.platform_specific.taskbar_icon = taskbar_icon;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn with_no_redirection_bitmap(mut self, flag: bool) -> WindowBuilder {
|
|
||||||
self.platform_specific.no_redirection_bitmap = flag;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on `MonitorId` that are specific to Windows.
|
|
||||||
pub trait MonitorIdExt {
|
|
||||||
/// Returns the name of the monitor adapter specific to the Win32 API.
|
|
||||||
fn native_id(&self) -> String;
|
|
||||||
|
|
||||||
/// Returns the handle of the monitor - `HMONITOR`.
|
|
||||||
fn hmonitor(&self) -> *mut c_void;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorIdExt for MonitorId {
|
|
||||||
#[inline]
|
|
||||||
fn native_id(&self) -> String {
|
|
||||||
self.inner.get_native_identifier()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn hmonitor(&self) -> *mut c_void {
|
|
||||||
self.inner.get_hmonitor() as *mut _
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on `DeviceId` that are specific to Windows.
|
|
||||||
pub trait DeviceIdExt {
|
|
||||||
/// Returns an identifier that persistently refers to this specific device.
|
|
||||||
///
|
|
||||||
/// Will return `None` if the device is no longer available.
|
|
||||||
fn get_persistent_identifier(&self) -> Option<String>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DeviceIdExt for DeviceId {
|
|
||||||
#[inline]
|
|
||||||
fn get_persistent_identifier(&self) -> Option<String> {
|
|
||||||
self.0.get_persistent_identifier()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
170
src/platform/android.rs
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
//! # 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.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.11", 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).
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
event_loop::{ActiveEventLoop, EventLoop, EventLoopBuilder},
|
||||||
|
window::{Window, WindowAttributes},
|
||||||
|
};
|
||||||
|
|
||||||
|
use self::activity::{AndroidApp, ConfigurationRef, Rect};
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoop`] that are specific to Android.
|
||||||
|
pub trait EventLoopExtAndroid {}
|
||||||
|
|
||||||
|
impl<T> EventLoopExtAndroid for EventLoop<T> {}
|
||||||
|
|
||||||
|
/// Additional methods on [`ActiveEventLoop`] that are specific to Android.
|
||||||
|
pub trait ActiveEventLoopExtAndroid {}
|
||||||
|
|
||||||
|
/// Additional methods on [`Window`] that are specific to Android.
|
||||||
|
pub trait WindowExtAndroid {
|
||||||
|
fn content_rect(&self) -> Rect;
|
||||||
|
|
||||||
|
fn config(&self) -> ConfigurationRef;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowExtAndroid for Window {
|
||||||
|
fn content_rect(&self) -> Rect {
|
||||||
|
self.window.content_rect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn config(&self) -> ConfigurationRef {
|
||||||
|
self.window.config()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActiveEventLoopExtAndroid for ActiveEventLoop {}
|
||||||
|
|
||||||
|
/// Additional methods on [`WindowAttributes`] that are specific to Android.
|
||||||
|
pub trait WindowAttributesExtAndroid {}
|
||||||
|
|
||||||
|
impl WindowAttributesExtAndroid for WindowAttributes {}
|
||||||
|
|
||||||
|
pub trait EventLoopBuilderExtAndroid {
|
||||||
|
/// Associates the `AndroidApp` that was passed to `android_main()` with the event loop
|
||||||
|
///
|
||||||
|
/// 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopBuilderExtAndroid for EventLoopBuilder<T> {
|
||||||
|
fn with_android_app(&mut self, app: AndroidApp) -> &mut Self {
|
||||||
|
self.platform_specific.android_app = Some(app);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_volume_keys(&mut self) -> &mut Self {
|
||||||
|
self.platform_specific.ignore_volume_keys = false;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-export of the `android_activity` API
|
||||||
|
///
|
||||||
|
/// Winit re-exports the `android_activity` API for convenience so that most
|
||||||
|
/// 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)]
|
||||||
|
#[cfg(android_platform)]
|
||||||
|
pub use android_activity::*;
|
||||||
|
|
||||||
|
#[cfg(not(android_platform))]
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub struct Rect;
|
||||||
|
#[cfg(not(android_platform))]
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub struct ConfigurationRef;
|
||||||
|
#[cfg(not(android_platform))]
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub struct AndroidApp;
|
||||||
|
}
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
#![allow(dead_code)]
|
|
||||||
#![allow(non_snake_case)]
|
|
||||||
#![allow(non_camel_case_types)]
|
|
||||||
#![allow(non_upper_case_globals)]
|
|
||||||
|
|
||||||
use libc;
|
|
||||||
use std::os::raw;
|
|
||||||
|
|
||||||
#[link(name = "android")]
|
|
||||||
#[link(name = "EGL")]
|
|
||||||
#[link(name = "GLESv2")]
|
|
||||||
extern {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* asset_manager.h
|
|
||||||
*/
|
|
||||||
pub type AAssetManager = raw::c_void;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* native_window.h
|
|
||||||
*/
|
|
||||||
pub type ANativeWindow = raw::c_void;
|
|
||||||
|
|
||||||
extern {
|
|
||||||
pub fn ANativeWindow_getHeight(window: *const ANativeWindow) -> libc::int32_t;
|
|
||||||
pub fn ANativeWindow_getWidth(window: *const ANativeWindow) -> libc::int32_t;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* native_activity.h
|
|
||||||
*/
|
|
||||||
pub type JavaVM = ();
|
|
||||||
pub type JNIEnv = ();
|
|
||||||
pub type jobject = *const libc::c_void;
|
|
||||||
|
|
||||||
pub type AInputQueue = (); // FIXME: wrong
|
|
||||||
pub type ARect = (); // FIXME: wrong
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
pub struct ANativeActivity {
|
|
||||||
pub callbacks: *mut ANativeActivityCallbacks,
|
|
||||||
pub vm: *mut JavaVM,
|
|
||||||
pub env: *mut JNIEnv,
|
|
||||||
pub clazz: jobject,
|
|
||||||
pub internalDataPath: *const libc::c_char,
|
|
||||||
pub externalDataPath: *const libc::c_char,
|
|
||||||
pub sdkVersion: libc::int32_t,
|
|
||||||
pub instance: *mut libc::c_void,
|
|
||||||
pub assetManager: *mut AAssetManager,
|
|
||||||
pub obbPath: *const libc::c_char,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
pub struct ANativeActivityCallbacks {
|
|
||||||
pub onStart: extern fn(*mut ANativeActivity),
|
|
||||||
pub onResume: extern fn(*mut ANativeActivity),
|
|
||||||
pub onSaveInstanceState: extern fn(*mut ANativeActivity, *mut libc::size_t),
|
|
||||||
pub onPause: extern fn(*mut ANativeActivity),
|
|
||||||
pub onStop: extern fn(*mut ANativeActivity),
|
|
||||||
pub onDestroy: extern fn(*mut ANativeActivity),
|
|
||||||
pub onWindowFocusChanged: extern fn(*mut ANativeActivity, libc::c_int),
|
|
||||||
pub onNativeWindowCreated: extern fn(*mut ANativeActivity, *const ANativeWindow),
|
|
||||||
pub onNativeWindowResized: extern fn(*mut ANativeActivity, *const ANativeWindow),
|
|
||||||
pub onNativeWindowRedrawNeeded: extern fn(*mut ANativeActivity, *const ANativeWindow),
|
|
||||||
pub onNativeWindowDestroyed: extern fn(*mut ANativeActivity, *const ANativeWindow),
|
|
||||||
pub onInputQueueCreated: extern fn(*mut ANativeActivity, *mut AInputQueue),
|
|
||||||
pub onInputQueueDestroyed: extern fn(*mut ANativeActivity, *mut AInputQueue),
|
|
||||||
pub onContentRectChanged: extern fn(*mut ANativeActivity, *const ARect),
|
|
||||||
pub onConfigurationChanged: extern fn(*mut ANativeActivity),
|
|
||||||
pub onLowMemory: extern fn(*mut ANativeActivity),
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* looper.h
|
|
||||||
*/
|
|
||||||
pub type ALooper = ();
|
|
||||||
|
|
||||||
#[link(name = "android")]
|
|
||||||
extern {
|
|
||||||
pub fn ALooper_forThread() -> *const ALooper;
|
|
||||||
pub fn ALooper_acquire(looper: *const ALooper);
|
|
||||||
pub fn ALooper_release(looper: *const ALooper);
|
|
||||||
pub fn ALooper_prepare(opts: libc::c_int) -> *const ALooper;
|
|
||||||
pub fn ALooper_pollOnce(timeoutMillis: libc::c_int, outFd: *mut libc::c_int,
|
|
||||||
outEvents: *mut libc::c_int, outData: *mut *mut libc::c_void) -> libc::c_int;
|
|
||||||
pub fn ALooper_pollAll(timeoutMillis: libc::c_int, outFd: *mut libc::c_int,
|
|
||||||
outEvents: *mut libc::c_int, outData: *mut *mut libc::c_void) -> libc::c_int;
|
|
||||||
pub fn ALooper_wake(looper: *const ALooper);
|
|
||||||
pub fn ALooper_addFd(looper: *const ALooper, fd: libc::c_int, ident: libc::c_int,
|
|
||||||
events: libc::c_int, callback: ALooper_callbackFunc, data: *mut libc::c_void)
|
|
||||||
-> libc::c_int;
|
|
||||||
pub fn ALooper_removeFd(looper: *const ALooper, fd: libc::c_int) -> libc::c_int;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const ALOOPER_PREPARE_ALLOW_NON_CALLBACKS: libc::c_int = 1 << 0;
|
|
||||||
|
|
||||||
pub const ALOOPER_POLL_WAKE: libc::c_int = -1;
|
|
||||||
pub const ALOOPER_POLL_CALLBACK: libc::c_int = -2;
|
|
||||||
pub const ALOOPER_POLL_TIMEOUT: libc::c_int = -3;
|
|
||||||
pub const ALOOPER_POLL_ERROR: libc::c_int = -4;
|
|
||||||
|
|
||||||
pub const ALOOPER_EVENT_INPUT: libc::c_int = 1 << 0;
|
|
||||||
pub const ALOOPER_EVENT_OUTPUT: libc::c_int = 1 << 1;
|
|
||||||
pub const ALOOPER_EVENT_ERROR: libc::c_int = 1 << 2;
|
|
||||||
pub const ALOOPER_EVENT_HANGUP: libc::c_int = 1 << 3;
|
|
||||||
pub const ALOOPER_EVENT_INVALID: libc::c_int = 1 << 4;
|
|
||||||
|
|
||||||
pub type ALooper_callbackFunc = extern fn(libc::c_int, libc::c_int, *mut libc::c_void) -> libc::c_int;
|
|
||||||
@@ -1,412 +0,0 @@
|
|||||||
#![cfg(target_os = "android")]
|
|
||||||
|
|
||||||
extern crate android_glue;
|
|
||||||
|
|
||||||
mod ffi;
|
|
||||||
|
|
||||||
use std::cell::RefCell;
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
use std::fmt;
|
|
||||||
use std::os::raw::c_void;
|
|
||||||
use std::sync::mpsc::{Receiver, channel};
|
|
||||||
|
|
||||||
use {
|
|
||||||
CreationError,
|
|
||||||
Event,
|
|
||||||
LogicalPosition,
|
|
||||||
LogicalSize,
|
|
||||||
MouseCursor,
|
|
||||||
PhysicalPosition,
|
|
||||||
PhysicalSize,
|
|
||||||
WindowAttributes,
|
|
||||||
WindowEvent,
|
|
||||||
WindowId as RootWindowId,
|
|
||||||
};
|
|
||||||
use CreationError::OsError;
|
|
||||||
use events::{Touch, TouchPhase};
|
|
||||||
use window::MonitorId as RootMonitorId;
|
|
||||||
|
|
||||||
pub struct EventsLoop {
|
|
||||||
event_rx: Receiver<android_glue::Event>,
|
|
||||||
suspend_callback: RefCell<Option<Box<Fn(bool) -> ()>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct EventsLoopProxy;
|
|
||||||
|
|
||||||
impl EventsLoop {
|
|
||||||
pub fn new() -> EventsLoop {
|
|
||||||
let (tx, rx) = channel();
|
|
||||||
android_glue::add_sender(tx);
|
|
||||||
EventsLoop {
|
|
||||||
event_rx: rx,
|
|
||||||
suspend_callback: Default::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_available_monitors(&self) -> VecDeque<MonitorId> {
|
|
||||||
let mut rb = VecDeque::with_capacity(1);
|
|
||||||
rb.push_back(MonitorId);
|
|
||||||
rb
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_primary_monitor(&self) -> MonitorId {
|
|
||||||
MonitorId
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn poll_events<F>(&mut self, mut callback: F)
|
|
||||||
where F: FnMut(::Event)
|
|
||||||
{
|
|
||||||
while let Ok(event) = self.event_rx.try_recv() {
|
|
||||||
let e = match event{
|
|
||||||
android_glue::Event::EventMotion(motion) => {
|
|
||||||
let dpi_factor = MonitorId.get_hidpi_factor();
|
|
||||||
let location = LogicalPosition::from_physical(
|
|
||||||
(motion.x as f64, motion.y as f64),
|
|
||||||
dpi_factor,
|
|
||||||
);
|
|
||||||
Some(Event::WindowEvent {
|
|
||||||
window_id: RootWindowId(WindowId),
|
|
||||||
event: WindowEvent::Touch(Touch {
|
|
||||||
phase: match motion.action {
|
|
||||||
android_glue::MotionAction::Down => TouchPhase::Started,
|
|
||||||
android_glue::MotionAction::Move => TouchPhase::Moved,
|
|
||||||
android_glue::MotionAction::Up => TouchPhase::Ended,
|
|
||||||
android_glue::MotionAction::Cancel => TouchPhase::Cancelled,
|
|
||||||
},
|
|
||||||
location,
|
|
||||||
id: motion.pointer_id as u64,
|
|
||||||
device_id: DEVICE_ID,
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
},
|
|
||||||
android_glue::Event::InitWindow => {
|
|
||||||
// The activity went to foreground.
|
|
||||||
if let Some(cb) = self.suspend_callback.borrow().as_ref() {
|
|
||||||
(*cb)(false);
|
|
||||||
}
|
|
||||||
Some(Event::Suspended(false))
|
|
||||||
},
|
|
||||||
android_glue::Event::TermWindow => {
|
|
||||||
// The activity went to background.
|
|
||||||
if let Some(cb) = self.suspend_callback.borrow().as_ref() {
|
|
||||||
(*cb)(true);
|
|
||||||
}
|
|
||||||
Some(Event::Suspended(true))
|
|
||||||
},
|
|
||||||
android_glue::Event::WindowResized |
|
|
||||||
android_glue::Event::ConfigChanged => {
|
|
||||||
// Activity Orientation changed or resized.
|
|
||||||
let native_window = unsafe { android_glue::get_native_window() };
|
|
||||||
if native_window.is_null() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
let dpi_factor = MonitorId.get_hidpi_factor();
|
|
||||||
let physical_size = MonitorId.get_dimensions();
|
|
||||||
let size = LogicalSize::from_physical(physical_size, dpi_factor);
|
|
||||||
Some(Event::WindowEvent {
|
|
||||||
window_id: RootWindowId(WindowId),
|
|
||||||
event: WindowEvent::Resized(size),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
},
|
|
||||||
android_glue::Event::WindowRedrawNeeded => {
|
|
||||||
// The activity needs to be redrawn.
|
|
||||||
Some(Event::WindowEvent {
|
|
||||||
window_id: RootWindowId(WindowId),
|
|
||||||
event: WindowEvent::Refresh,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
android_glue::Event::Wake => {
|
|
||||||
Some(Event::Awakened)
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some(event) = e {
|
|
||||||
callback(event);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_suspend_callback(&self, cb: Option<Box<Fn(bool) -> ()>>) {
|
|
||||||
*self.suspend_callback.borrow_mut() = cb;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn run_forever<F>(&mut self, mut callback: F)
|
|
||||||
where F: FnMut(::Event) -> ::ControlFlow,
|
|
||||||
{
|
|
||||||
// Yeah that's a very bad implementation.
|
|
||||||
loop {
|
|
||||||
let mut control_flow = ::ControlFlow::Continue;
|
|
||||||
self.poll_events(|e| {
|
|
||||||
if let ::ControlFlow::Break = callback(e) {
|
|
||||||
control_flow = ::ControlFlow::Break;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
if let ::ControlFlow::Break = control_flow {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
::std::thread::sleep(::std::time::Duration::from_millis(5));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn create_proxy(&self) -> EventsLoopProxy {
|
|
||||||
EventsLoopProxy
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventsLoopProxy {
|
|
||||||
pub fn wakeup(&self) -> Result<(), ::EventsLoopClosed> {
|
|
||||||
android_glue::wake_event_loop();
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub struct WindowId;
|
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub struct DeviceId;
|
|
||||||
|
|
||||||
pub struct Window {
|
|
||||||
native_window: *const c_void,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct MonitorId;
|
|
||||||
|
|
||||||
impl fmt::Debug for MonitorId {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct MonitorId {
|
|
||||||
name: Option<String>,
|
|
||||||
dimensions: PhysicalSize,
|
|
||||||
position: PhysicalPosition,
|
|
||||||
hidpi_factor: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
let monitor_id_proxy = MonitorId {
|
|
||||||
name: self.get_name(),
|
|
||||||
dimensions: self.get_dimensions(),
|
|
||||||
position: self.get_position(),
|
|
||||||
hidpi_factor: self.get_hidpi_factor(),
|
|
||||||
};
|
|
||||||
|
|
||||||
monitor_id_proxy.fmt(f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorId {
|
|
||||||
#[inline]
|
|
||||||
pub fn get_name(&self) -> Option<String> {
|
|
||||||
Some("Primary".to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_dimensions(&self) -> PhysicalSize {
|
|
||||||
unsafe {
|
|
||||||
let window = android_glue::get_native_window();
|
|
||||||
(
|
|
||||||
ffi::ANativeWindow_getWidth(window) as f64,
|
|
||||||
ffi::ANativeWindow_getHeight(window) as f64,
|
|
||||||
).into()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_position(&self) -> PhysicalPosition {
|
|
||||||
// Android assumes single screen
|
|
||||||
(0, 0).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_hidpi_factor(&self) -> f64 {
|
|
||||||
1.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Default)]
|
|
||||||
pub struct PlatformSpecificWindowBuilderAttributes;
|
|
||||||
#[derive(Clone, Default)]
|
|
||||||
pub struct PlatformSpecificHeadlessBuilderAttributes;
|
|
||||||
|
|
||||||
impl Window {
|
|
||||||
pub fn new(_: &EventsLoop, win_attribs: WindowAttributes,
|
|
||||||
_: PlatformSpecificWindowBuilderAttributes)
|
|
||||||
-> Result<Window, CreationError>
|
|
||||||
{
|
|
||||||
let native_window = unsafe { android_glue::get_native_window() };
|
|
||||||
if native_window.is_null() {
|
|
||||||
return Err(OsError(format!("Android's native window is null")));
|
|
||||||
}
|
|
||||||
|
|
||||||
android_glue::set_multitouch(win_attribs.multitouch);
|
|
||||||
|
|
||||||
Ok(Window {
|
|
||||||
native_window: native_window as *const _,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_native_window(&self) -> *const c_void {
|
|
||||||
self.native_window
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_title(&self, _: &str) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn show(&self) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn hide(&self) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_position(&self) -> Option<LogicalPosition> {
|
|
||||||
// N/A
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_inner_position(&self) -> Option<LogicalPosition> {
|
|
||||||
// N/A
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_position(&self, _position: LogicalPosition) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_min_dimensions(&self, _dimensions: Option<LogicalSize>) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_max_dimensions(&self, _dimensions: Option<LogicalSize>) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_resizable(&self, _resizable: bool) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_inner_size(&self) -> Option<LogicalSize> {
|
|
||||||
if self.native_window.is_null() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
let dpi_factor = self.get_hidpi_factor();
|
|
||||||
let physical_size = self.get_current_monitor().get_dimensions();
|
|
||||||
Some(LogicalSize::from_physical(physical_size, dpi_factor))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_outer_size(&self) -> Option<LogicalSize> {
|
|
||||||
self.get_inner_size()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_inner_size(&self, _size: LogicalSize) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_hidpi_factor(&self) -> f64 {
|
|
||||||
self.get_current_monitor().get_hidpi_factor()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor(&self, _: MouseCursor) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn grab_cursor(&self, _grab: bool) -> Result<(), String> {
|
|
||||||
Err("Cursor grabbing is not possible on Android.".to_owned())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn hide_cursor(&self, _hide: bool) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor_position(&self, _position: LogicalPosition) -> Result<(), String> {
|
|
||||||
Err("Setting cursor position is not possible on Android.".to_owned())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_maximized(&self, _maximized: bool) {
|
|
||||||
// N/A
|
|
||||||
// Android has single screen maximized apps so nothing to do
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_fullscreen(&self, _monitor: Option<RootMonitorId>) {
|
|
||||||
// N/A
|
|
||||||
// Android has single screen maximized apps so nothing to do
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_decorations(&self, _decorations: bool) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_always_on_top(&self, _always_on_top: bool) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_window_icon(&self, _icon: Option<::Icon>) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_ime_spot(&self, _spot: LogicalPosition) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_current_monitor(&self) -> RootMonitorId {
|
|
||||||
RootMonitorId { inner: MonitorId }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_available_monitors(&self) -> VecDeque<MonitorId> {
|
|
||||||
let mut rb = VecDeque::with_capacity(1);
|
|
||||||
rb.push_back(MonitorId);
|
|
||||||
rb
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_primary_monitor(&self) -> MonitorId {
|
|
||||||
MonitorId
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn id(&self) -> WindowId {
|
|
||||||
WindowId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe impl Send for Window {}
|
|
||||||
unsafe impl Sync for Window {}
|
|
||||||
|
|
||||||
// Constant device ID, to be removed when this backend is updated to report real device IDs.
|
|
||||||
const DEVICE_ID: ::DeviceId = ::DeviceId(DeviceId);
|
|
||||||
@@ -1,314 +0,0 @@
|
|||||||
#![allow(dead_code, non_camel_case_types, non_snake_case)]
|
|
||||||
|
|
||||||
use std::os::raw::{c_int, c_char, c_void, c_ulong, c_double, c_long, c_ushort};
|
|
||||||
#[cfg(test)]
|
|
||||||
use std::mem;
|
|
||||||
|
|
||||||
pub type EM_BOOL = c_int;
|
|
||||||
pub type EM_UTF8 = c_char;
|
|
||||||
pub type EMSCRIPTEN_RESULT = c_int;
|
|
||||||
|
|
||||||
pub const EM_TRUE: EM_BOOL = 1;
|
|
||||||
pub const EM_FALSE: EM_BOOL = 0;
|
|
||||||
|
|
||||||
// values for EMSCRIPTEN_RESULT
|
|
||||||
pub const EMSCRIPTEN_RESULT_SUCCESS: c_int = 0;
|
|
||||||
pub const EMSCRIPTEN_RESULT_DEFERRED: c_int = 1;
|
|
||||||
pub const EMSCRIPTEN_RESULT_NOT_SUPPORTED: c_int = -1;
|
|
||||||
pub const EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED: c_int = -2;
|
|
||||||
pub const EMSCRIPTEN_RESULT_INVALID_TARGET: c_int = -3;
|
|
||||||
pub const EMSCRIPTEN_RESULT_UNKNOWN_TARGET: c_int = -4;
|
|
||||||
pub const EMSCRIPTEN_RESULT_INVALID_PARAM: c_int = -5;
|
|
||||||
pub const EMSCRIPTEN_RESULT_FAILED: c_int = -6;
|
|
||||||
pub const EMSCRIPTEN_RESULT_NO_DATA: c_int = -7;
|
|
||||||
|
|
||||||
// values for EMSCRIPTEN EVENT
|
|
||||||
pub const EMSCRIPTEN_EVENT_KEYPRESS: c_int = 1;
|
|
||||||
pub const EMSCRIPTEN_EVENT_KEYDOWN: c_int = 2;
|
|
||||||
pub const EMSCRIPTEN_EVENT_KEYUP: c_int = 3;
|
|
||||||
pub const EMSCRIPTEN_EVENT_CLICK: c_int = 4;
|
|
||||||
pub const EMSCRIPTEN_EVENT_MOUSEDOWN: c_int = 5;
|
|
||||||
pub const EMSCRIPTEN_EVENT_MOUSEUP: c_int = 6;
|
|
||||||
pub const EMSCRIPTEN_EVENT_DBLCLICK: c_int = 7;
|
|
||||||
pub const EMSCRIPTEN_EVENT_MOUSEMOVE: c_int = 8;
|
|
||||||
pub const EMSCRIPTEN_EVENT_WHEEL: c_int = 9;
|
|
||||||
pub const EMSCRIPTEN_EVENT_RESIZE: c_int = 10;
|
|
||||||
pub const EMSCRIPTEN_EVENT_SCROLL: c_int = 11;
|
|
||||||
pub const EMSCRIPTEN_EVENT_BLUR: c_int = 12;
|
|
||||||
pub const EMSCRIPTEN_EVENT_FOCUS: c_int = 13;
|
|
||||||
pub const EMSCRIPTEN_EVENT_FOCUSIN: c_int = 14;
|
|
||||||
pub const EMSCRIPTEN_EVENT_FOCUSOUT: c_int = 15;
|
|
||||||
pub const EMSCRIPTEN_EVENT_DEVICEORIENTATION: c_int = 16;
|
|
||||||
pub const EMSCRIPTEN_EVENT_DEVICEMOTION: c_int = 17;
|
|
||||||
pub const EMSCRIPTEN_EVENT_ORIENTATIONCHANGE: c_int = 18;
|
|
||||||
pub const EMSCRIPTEN_EVENT_FULLSCREENCHANGE: c_int = 19;
|
|
||||||
pub const EMSCRIPTEN_EVENT_POINTERLOCKCHANGE: c_int = 20;
|
|
||||||
pub const EMSCRIPTEN_EVENT_VISIBILITYCHANGE: c_int = 21;
|
|
||||||
pub const EMSCRIPTEN_EVENT_TOUCHSTART: c_int = 22;
|
|
||||||
pub const EMSCRIPTEN_EVENT_TOUCHEND: c_int = 23;
|
|
||||||
pub const EMSCRIPTEN_EVENT_TOUCHMOVE: c_int = 24;
|
|
||||||
pub const EMSCRIPTEN_EVENT_TOUCHCANCEL: c_int = 25;
|
|
||||||
pub const EMSCRIPTEN_EVENT_GAMEPADCONNECTED: c_int = 26;
|
|
||||||
pub const EMSCRIPTEN_EVENT_GAMEPADDISCONNECTED: c_int = 27;
|
|
||||||
pub const EMSCRIPTEN_EVENT_BEFOREUNLOAD: c_int = 28;
|
|
||||||
pub const EMSCRIPTEN_EVENT_BATTERYCHARGINGCHANGE: c_int = 29;
|
|
||||||
pub const EMSCRIPTEN_EVENT_BATTERYLEVELCHANGE: c_int = 30;
|
|
||||||
pub const EMSCRIPTEN_EVENT_WEBGLCONTEXTLOST: c_int = 31;
|
|
||||||
pub const EMSCRIPTEN_EVENT_WEBGLCONTEXTRESTORED: c_int = 32;
|
|
||||||
pub const EMSCRIPTEN_EVENT_MOUSEENTER: c_int = 33;
|
|
||||||
pub const EMSCRIPTEN_EVENT_MOUSELEAVE: c_int = 34;
|
|
||||||
pub const EMSCRIPTEN_EVENT_MOUSEOVER: c_int = 35;
|
|
||||||
pub const EMSCRIPTEN_EVENT_MOUSEOUT: c_int = 36;
|
|
||||||
pub const EMSCRIPTEN_EVENT_CANVASRESIZED: c_int = 37;
|
|
||||||
pub const EMSCRIPTEN_EVENT_POINTERLOCKERROR: c_int = 38;
|
|
||||||
|
|
||||||
pub const EM_HTML5_SHORT_STRING_LEN_BYTES: usize = 32;
|
|
||||||
|
|
||||||
pub const DOM_KEY_LOCATION_STANDARD: c_ulong = 0x00;
|
|
||||||
pub const DOM_KEY_LOCATION_LEFT: c_ulong = 0x01;
|
|
||||||
pub const DOM_KEY_LOCATION_RIGHT: c_ulong = 0x02;
|
|
||||||
pub const DOM_KEY_LOCATION_NUMPAD: c_ulong = 0x03;
|
|
||||||
|
|
||||||
pub type em_callback_func = Option<unsafe extern "C" fn()>;
|
|
||||||
|
|
||||||
pub type em_key_callback_func = Option<unsafe extern "C" fn(
|
|
||||||
eventType: c_int,
|
|
||||||
keyEvent: *const EmscriptenKeyboardEvent,
|
|
||||||
userData: *mut c_void) -> EM_BOOL>;
|
|
||||||
|
|
||||||
pub type em_mouse_callback_func = Option<unsafe extern "C" fn(
|
|
||||||
eventType: c_int,
|
|
||||||
mouseEvent: *const EmscriptenMouseEvent,
|
|
||||||
userData: *mut c_void) -> EM_BOOL>;
|
|
||||||
|
|
||||||
pub type em_pointerlockchange_callback_func = Option<unsafe extern "C" fn(
|
|
||||||
eventType: c_int,
|
|
||||||
pointerlockChangeEvent: *const EmscriptenPointerlockChangeEvent,
|
|
||||||
userData: *mut c_void) -> EM_BOOL>;
|
|
||||||
|
|
||||||
pub type em_fullscreenchange_callback_func = Option<unsafe extern "C" fn(
|
|
||||||
eventType: c_int,
|
|
||||||
fullscreenChangeEvent: *const EmscriptenFullscreenChangeEvent,
|
|
||||||
userData: *mut c_void) -> EM_BOOL>;
|
|
||||||
|
|
||||||
pub type em_touch_callback_func = Option<unsafe extern "C" fn(
|
|
||||||
eventType: c_int,
|
|
||||||
touchEvent: *const EmscriptenTouchEvent,
|
|
||||||
userData: *mut c_void) -> EM_BOOL>;
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
pub struct EmscriptenFullscreenChangeEvent {
|
|
||||||
pub isFullscreen: c_int,
|
|
||||||
pub fullscreenEnabled: c_int,
|
|
||||||
pub nodeName: [c_char; 128usize],
|
|
||||||
pub id: [c_char; 128usize],
|
|
||||||
pub elementWidth: c_int,
|
|
||||||
pub elementHeight: c_int,
|
|
||||||
pub screenWidth: c_int,
|
|
||||||
pub screenHeight: c_int,
|
|
||||||
}
|
|
||||||
#[test]
|
|
||||||
fn bindgen_test_layout_EmscriptenFullscreenChangeEvent() {
|
|
||||||
assert_eq!(mem::size_of::<EmscriptenFullscreenChangeEvent>(), 280usize);
|
|
||||||
assert_eq!(mem::align_of::<EmscriptenFullscreenChangeEvent>(), 4usize);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Debug, Copy)]
|
|
||||||
pub struct EmscriptenKeyboardEvent {
|
|
||||||
pub key: [c_char; 32usize],
|
|
||||||
pub code: [c_char; 32usize],
|
|
||||||
pub location: c_ulong,
|
|
||||||
pub ctrlKey: c_int,
|
|
||||||
pub shiftKey: c_int,
|
|
||||||
pub altKey: c_int,
|
|
||||||
pub metaKey: c_int,
|
|
||||||
pub repeat: c_int,
|
|
||||||
pub locale: [c_char; 32usize],
|
|
||||||
pub charValue: [c_char; 32usize],
|
|
||||||
pub charCode: c_ulong,
|
|
||||||
pub keyCode: c_ulong,
|
|
||||||
pub which: c_ulong,
|
|
||||||
}
|
|
||||||
#[test]
|
|
||||||
fn bindgen_test_layout_EmscriptenKeyboardEvent() {
|
|
||||||
assert_eq!(mem::size_of::<EmscriptenKeyboardEvent>(), 184usize);
|
|
||||||
assert_eq!(mem::align_of::<EmscriptenKeyboardEvent>(), 8usize);
|
|
||||||
}
|
|
||||||
impl Clone for EmscriptenKeyboardEvent {
|
|
||||||
fn clone(&self) -> Self { *self }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Debug, Copy, Clone)]
|
|
||||||
pub struct EmscriptenMouseEvent {
|
|
||||||
pub timestamp: f64,
|
|
||||||
pub screenX: c_long,
|
|
||||||
pub screenY: c_long,
|
|
||||||
pub clientX: c_long,
|
|
||||||
pub clientY: c_long,
|
|
||||||
pub ctrlKey: c_int,
|
|
||||||
pub shiftKey: c_int,
|
|
||||||
pub altKey: c_int,
|
|
||||||
pub metaKey: c_int,
|
|
||||||
pub button: c_ushort,
|
|
||||||
pub buttons: c_ushort,
|
|
||||||
pub movementX: c_long,
|
|
||||||
pub movementY: c_long,
|
|
||||||
pub targetX: c_long,
|
|
||||||
pub targetY: c_long,
|
|
||||||
pub canvasX: c_long,
|
|
||||||
pub canvasY: c_long,
|
|
||||||
pub padding: c_long,
|
|
||||||
}
|
|
||||||
#[test]
|
|
||||||
fn bindgen_test_layout_EmscriptenMouseEvent() {
|
|
||||||
assert_eq!(mem::size_of::<EmscriptenMouseEvent>(), 120usize);
|
|
||||||
assert_eq!(mem::align_of::<EmscriptenMouseEvent>(), 8usize);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Debug, Copy, Clone)]
|
|
||||||
pub struct EmscriptenTouchPoint {
|
|
||||||
pub identifier: c_long,
|
|
||||||
pub screenX: c_long,
|
|
||||||
pub screenY: c_long,
|
|
||||||
pub clientX: c_long,
|
|
||||||
pub clientY: c_long,
|
|
||||||
pub pageX: c_long,
|
|
||||||
pub pageY: c_long,
|
|
||||||
pub isChanged: c_int,
|
|
||||||
pub onTarget: c_int,
|
|
||||||
pub targetX: c_long,
|
|
||||||
pub targetY: c_long,
|
|
||||||
pub canvasX: c_long,
|
|
||||||
pub canvasY: c_long,
|
|
||||||
}
|
|
||||||
#[test]
|
|
||||||
fn bindgen_test_layout_EmscriptenTouchPoint() {
|
|
||||||
assert_eq!(mem::size_of::<EmscriptenTouchPoint>(), 96usize);
|
|
||||||
assert_eq!(mem::align_of::<EmscriptenTouchPoint>(), 8usize);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Debug, Copy, Clone)]
|
|
||||||
pub struct EmscriptenTouchEvent {
|
|
||||||
pub numTouches: c_int,
|
|
||||||
pub ctrlKey: c_int,
|
|
||||||
pub shiftKey: c_int,
|
|
||||||
pub altKey: c_int,
|
|
||||||
pub metaKey: c_int,
|
|
||||||
pub touches: [EmscriptenTouchPoint; 32usize],
|
|
||||||
}
|
|
||||||
#[test]
|
|
||||||
fn bindgen_test_layout_EmscriptenTouchEvent() {
|
|
||||||
assert_eq!(mem::size_of::<EmscriptenTouchEvent>(), 3096usize);
|
|
||||||
assert_eq!(mem::align_of::<EmscriptenTouchEvent>(), 8usize);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
pub struct EmscriptenPointerlockChangeEvent {
|
|
||||||
pub isActive: c_int,
|
|
||||||
pub nodeName: [c_char; 128usize],
|
|
||||||
pub id: [c_char; 128usize],
|
|
||||||
}
|
|
||||||
#[test]
|
|
||||||
fn bindgen_test_layout_EmscriptenPointerlockChangeEvent() {
|
|
||||||
assert_eq!(mem::size_of::<EmscriptenPointerlockChangeEvent>(), 260usize);
|
|
||||||
assert_eq!(mem::align_of::<EmscriptenPointerlockChangeEvent>(), 4usize);
|
|
||||||
}
|
|
||||||
|
|
||||||
extern "C" {
|
|
||||||
pub fn emscripten_set_canvas_size(
|
|
||||||
width: c_int, height: c_int)
|
|
||||||
-> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_get_canvas_size(
|
|
||||||
width: *mut c_int, height: *mut c_int,
|
|
||||||
is_fullscreen: *mut c_int)
|
|
||||||
-> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_set_element_css_size(
|
|
||||||
target: *const c_char, width: c_double,
|
|
||||||
height: c_double) -> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_get_element_css_size(
|
|
||||||
target: *const c_char, width: *mut c_double,
|
|
||||||
height: *mut c_double) -> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_request_pointerlock(
|
|
||||||
target: *const c_char, deferUntilInEventHandler: EM_BOOL)
|
|
||||||
-> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_exit_pointerlock() -> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_request_fullscreen(
|
|
||||||
target: *const c_char, deferUntilInEventHandler: EM_BOOL)
|
|
||||||
-> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_exit_fullscreen() -> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_set_keydown_callback(
|
|
||||||
target: *const c_char, userData: *mut c_void,
|
|
||||||
useCapture: EM_BOOL, callback: em_key_callback_func)
|
|
||||||
-> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_set_keyup_callback(
|
|
||||||
target: *const c_char, userData: *mut c_void,
|
|
||||||
useCapture: EM_BOOL, callback: em_key_callback_func)
|
|
||||||
-> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_set_mousemove_callback(
|
|
||||||
target: *const c_char, user_data: *mut c_void,
|
|
||||||
use_capture: EM_BOOL, callback: em_mouse_callback_func)
|
|
||||||
-> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_set_mousedown_callback(
|
|
||||||
target: *const c_char, user_data: *mut c_void,
|
|
||||||
use_capture: EM_BOOL, callback: em_mouse_callback_func)
|
|
||||||
-> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_set_mouseup_callback(
|
|
||||||
target: *const c_char, user_data: *mut c_void,
|
|
||||||
use_capture: EM_BOOL, callback: em_mouse_callback_func)
|
|
||||||
-> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_hide_mouse();
|
|
||||||
|
|
||||||
pub fn emscripten_get_device_pixel_ratio() -> f64;
|
|
||||||
|
|
||||||
pub fn emscripten_set_pointerlockchange_callback(
|
|
||||||
target: *const c_char, userData: *mut c_void, useCapture: EM_BOOL,
|
|
||||||
callback: em_pointerlockchange_callback_func) -> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_set_fullscreenchange_callback(
|
|
||||||
target: *const c_char, userData: *mut c_void, useCapture: EM_BOOL,
|
|
||||||
callback: em_fullscreenchange_callback_func) -> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_asm_const(code: *const c_char);
|
|
||||||
|
|
||||||
pub fn emscripten_set_main_loop(
|
|
||||||
func: em_callback_func, fps: c_int, simulate_infinite_loop: EM_BOOL);
|
|
||||||
|
|
||||||
pub fn emscripten_cancel_main_loop();
|
|
||||||
|
|
||||||
pub fn emscripten_set_touchstart_callback(
|
|
||||||
target: *const c_char, userData: *mut c_void,
|
|
||||||
useCapture: c_int, callback: em_touch_callback_func)
|
|
||||||
-> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_set_touchend_callback(
|
|
||||||
target: *const c_char, userData: *mut c_void,
|
|
||||||
useCapture: c_int, callback: em_touch_callback_func)
|
|
||||||
-> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_set_touchmove_callback(
|
|
||||||
target: *const c_char, userData: *mut c_void,
|
|
||||||
useCapture: c_int, callback: em_touch_callback_func)
|
|
||||||
-> EMSCRIPTEN_RESULT;
|
|
||||||
|
|
||||||
pub fn emscripten_set_touchcancel_callback(
|
|
||||||
target: *const c_char, userData: *mut c_void,
|
|
||||||
useCapture: c_int, callback: em_touch_callback_func)
|
|
||||||
-> EMSCRIPTEN_RESULT;
|
|
||||||
}
|
|
||||||
404
src/platform/ios.rs
Normal file
@@ -0,0 +1,404 @@
|
|||||||
|
//! # iOS / UIKit
|
||||||
|
//!
|
||||||
|
//! Winit has an OS requirement of iOS 8 or higher, and is regularly tested on
|
||||||
|
//! iOS 9.3.
|
||||||
|
//!
|
||||||
|
//! iOS's main `UIApplicationMain` does some init work that's required by all
|
||||||
|
//! UI-related code (see issue [#1705]). It is best to create your windows
|
||||||
|
//! inside `Event::Resumed`.
|
||||||
|
//!
|
||||||
|
//! [#1705]: https://github.com/rust-windowing/winit/issues/1705
|
||||||
|
//!
|
||||||
|
//! ## Building app
|
||||||
|
//!
|
||||||
|
//! To build ios app you will need rustc built for this targets:
|
||||||
|
//!
|
||||||
|
//! - armv7-apple-ios
|
||||||
|
//! - armv7s-apple-ios
|
||||||
|
//! - i386-apple-ios
|
||||||
|
//! - aarch64-apple-ios
|
||||||
|
//! - x86_64-apple-ios
|
||||||
|
//!
|
||||||
|
//! Then
|
||||||
|
//!
|
||||||
|
//! ```
|
||||||
|
//! cargo build --target=...
|
||||||
|
//! ```
|
||||||
|
//! The simplest way to integrate your app into xcode environment is to build it
|
||||||
|
//! as a static library. Wrap your main function and export it.
|
||||||
|
//!
|
||||||
|
//! ```rust, ignore
|
||||||
|
//! #[no_mangle]
|
||||||
|
//! pub extern fn start_winit_app() {
|
||||||
|
//! start_inner()
|
||||||
|
//! }
|
||||||
|
//!
|
||||||
|
//! fn start_inner() {
|
||||||
|
//! ...
|
||||||
|
//! }
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! Compile project and then drag resulting .a into Xcode project. Add winit.h to xcode.
|
||||||
|
//!
|
||||||
|
//! ```ignore
|
||||||
|
//! void start_winit_app();
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! Use start_winit_app inside your xcode's main function.
|
||||||
|
//!
|
||||||
|
//!
|
||||||
|
//! ## App lifecycle and events
|
||||||
|
//!
|
||||||
|
//! iOS environment is very different from other platforms and you must be very
|
||||||
|
//! careful with it's events. Familiarize yourself with
|
||||||
|
//! [app lifecycle](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/).
|
||||||
|
//!
|
||||||
|
//! This is how those event are represented in winit:
|
||||||
|
//!
|
||||||
|
//! - applicationDidBecomeActive is Resumed
|
||||||
|
//! - applicationWillResignActive is Suspended
|
||||||
|
//! - applicationWillTerminate is LoopExiting
|
||||||
|
//!
|
||||||
|
//! Keep in mind that after LoopExiting event is received every attempt to draw with
|
||||||
|
//! opengl will result in segfault.
|
||||||
|
//!
|
||||||
|
//! Also note that app may not receive the LoopExiting event if suspended; it might be SIGKILL'ed.
|
||||||
|
|
||||||
|
use std::os::raw::c_void;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
event_loop::EventLoop,
|
||||||
|
monitor::{MonitorHandle, VideoModeHandle},
|
||||||
|
window::{Window, WindowAttributes},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoop`] that are specific to iOS.
|
||||||
|
pub trait EventLoopExtIOS {
|
||||||
|
/// Returns the [`Idiom`] (phone/tablet/tv/etc) for the current device.
|
||||||
|
fn idiom(&self) -> Idiom;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static> EventLoopExtIOS for EventLoop<T> {
|
||||||
|
fn idiom(&self) -> Idiom {
|
||||||
|
self.event_loop.idiom()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`Window`] that are specific to iOS.
|
||||||
|
pub trait WindowExtIOS {
|
||||||
|
/// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `scale_factor`.
|
||||||
|
///
|
||||||
|
/// The default value is device dependent, and it's recommended GLES or Metal applications set
|
||||||
|
/// this to [`MonitorHandle::scale_factor()`].
|
||||||
|
///
|
||||||
|
/// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc
|
||||||
|
/// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc
|
||||||
|
fn set_scale_factor(&self, scale_factor: f64);
|
||||||
|
|
||||||
|
/// Sets the valid orientations for the [`Window`].
|
||||||
|
///
|
||||||
|
/// The default value is [`ValidOrientations::LandscapeAndPortrait`].
|
||||||
|
///
|
||||||
|
/// This changes the value returned by
|
||||||
|
/// [`-[UIViewController supportedInterfaceOrientations]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621435-supportedinterfaceorientations?language=objc),
|
||||||
|
/// and then calls
|
||||||
|
/// [`-[UIViewController attemptRotationToDeviceOrientation]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621400-attemptrotationtodeviceorientati?language=objc).
|
||||||
|
fn set_valid_orientations(&self, valid_orientations: ValidOrientations);
|
||||||
|
|
||||||
|
/// Sets whether the [`Window`] prefers the home indicator hidden.
|
||||||
|
///
|
||||||
|
/// The default is to prefer showing the home indicator.
|
||||||
|
///
|
||||||
|
/// This changes the value returned by
|
||||||
|
/// [`-[UIViewController prefersHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887510-prefershomeindicatorautohidden?language=objc),
|
||||||
|
/// and then calls
|
||||||
|
/// [`-[UIViewController setNeedsUpdateOfHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887509-setneedsupdateofhomeindicatoraut?language=objc).
|
||||||
|
///
|
||||||
|
/// This only has an effect on iOS 11.0+.
|
||||||
|
fn set_prefers_home_indicator_hidden(&self, hidden: bool);
|
||||||
|
|
||||||
|
/// Sets the screen edges for which the system gestures will take a lower priority than the
|
||||||
|
/// application's touch handling.
|
||||||
|
///
|
||||||
|
/// This changes the value returned by
|
||||||
|
/// [`-[UIViewController preferredScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887512-preferredscreenedgesdeferringsys?language=objc),
|
||||||
|
/// and then calls
|
||||||
|
/// [`-[UIViewController setNeedsUpdateOfScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887507-setneedsupdateofscreenedgesdefer?language=objc).
|
||||||
|
///
|
||||||
|
/// This only has an effect on iOS 11.0+.
|
||||||
|
fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge);
|
||||||
|
|
||||||
|
/// Sets whether the [`Window`] prefers the status bar hidden.
|
||||||
|
///
|
||||||
|
/// The default is to prefer showing the status bar.
|
||||||
|
///
|
||||||
|
/// This sets the value of the
|
||||||
|
/// [`prefersStatusBarHidden`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621440-prefersstatusbarhidden?language=objc)
|
||||||
|
/// property.
|
||||||
|
///
|
||||||
|
/// [`setNeedsStatusBarAppearanceUpdate()`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621354-setneedsstatusbarappearanceupdat?language=objc)
|
||||||
|
/// is also called for you.
|
||||||
|
fn set_prefers_status_bar_hidden(&self, hidden: bool);
|
||||||
|
|
||||||
|
/// Sets the preferred status bar style for the [`Window`].
|
||||||
|
///
|
||||||
|
/// The default is system-defined.
|
||||||
|
///
|
||||||
|
/// This sets the value of the
|
||||||
|
/// [`preferredStatusBarStyle`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621416-preferredstatusbarstyle?language=objc)
|
||||||
|
/// property.
|
||||||
|
///
|
||||||
|
/// [`setNeedsStatusBarAppearanceUpdate()`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621354-setneedsstatusbarappearanceupdat?language=objc)
|
||||||
|
/// is also called for you.
|
||||||
|
fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle);
|
||||||
|
|
||||||
|
/// Sets whether the [`Window`] should recognize pinch gestures.
|
||||||
|
///
|
||||||
|
/// The default is to not recognize gestures.
|
||||||
|
fn recognize_pinch_gesture(&self, should_recognize: bool);
|
||||||
|
|
||||||
|
/// Sets whether the [`Window`] should recognize double tap gestures.
|
||||||
|
///
|
||||||
|
/// The default is to not recognize gestures.
|
||||||
|
fn recognize_doubletap_gesture(&self, should_recognize: bool);
|
||||||
|
|
||||||
|
/// Sets whether the [`Window`] should recognize rotation gestures.
|
||||||
|
///
|
||||||
|
/// The default is to not recognize gestures.
|
||||||
|
fn recognize_rotation_gesture(&self, should_recognize: bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowExtIOS for Window {
|
||||||
|
#[inline]
|
||||||
|
fn set_scale_factor(&self, scale_factor: f64) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_scale_factor(scale_factor))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_valid_orientations(&self, valid_orientations: ValidOrientations) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_valid_orientations(valid_orientations))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_prefers_home_indicator_hidden(&self, hidden: bool) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_prefers_home_indicator_hidden(hidden))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge) {
|
||||||
|
self.window.maybe_queue_on_main(move |w| {
|
||||||
|
w.set_preferred_screen_edges_deferring_system_gestures(edges)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_prefers_status_bar_hidden(&self, hidden: bool) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_prefers_status_bar_hidden(hidden))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_preferred_status_bar_style(status_bar_style))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn recognize_pinch_gesture(&self, should_recognize: bool) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.recognize_pinch_gesture(should_recognize));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn recognize_doubletap_gesture(&self, should_recognize: bool) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.recognize_doubletap_gesture(should_recognize));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn recognize_rotation_gesture(&self, should_recognize: bool) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.recognize_rotation_gesture(should_recognize));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`WindowAttributes`] that are specific to iOS.
|
||||||
|
pub trait WindowAttributesExtIOS {
|
||||||
|
/// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `scale_factor`.
|
||||||
|
///
|
||||||
|
/// The default value is device dependent, and it's recommended GLES or Metal applications set
|
||||||
|
/// this to [`MonitorHandle::scale_factor()`].
|
||||||
|
///
|
||||||
|
/// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc
|
||||||
|
/// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc
|
||||||
|
fn with_scale_factor(self, scale_factor: f64) -> Self;
|
||||||
|
|
||||||
|
/// Sets the valid orientations for the [`Window`].
|
||||||
|
///
|
||||||
|
/// The default value is [`ValidOrientations::LandscapeAndPortrait`].
|
||||||
|
///
|
||||||
|
/// This sets the initial value returned by
|
||||||
|
/// [`-[UIViewController supportedInterfaceOrientations]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621435-supportedinterfaceorientations?language=objc).
|
||||||
|
fn with_valid_orientations(self, valid_orientations: ValidOrientations) -> Self;
|
||||||
|
|
||||||
|
/// Sets whether the [`Window`] prefers the home indicator hidden.
|
||||||
|
///
|
||||||
|
/// The default is to prefer showing the home indicator.
|
||||||
|
///
|
||||||
|
/// This sets the initial value returned by
|
||||||
|
/// [`-[UIViewController prefersHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887510-prefershomeindicatorautohidden?language=objc).
|
||||||
|
///
|
||||||
|
/// This only has an effect on iOS 11.0+.
|
||||||
|
fn with_prefers_home_indicator_hidden(self, hidden: bool) -> Self;
|
||||||
|
|
||||||
|
/// Sets the screen edges for which the system gestures will take a lower priority than the
|
||||||
|
/// application's touch handling.
|
||||||
|
///
|
||||||
|
/// This sets the initial value returned by
|
||||||
|
/// [`-[UIViewController preferredScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887512-preferredscreenedgesdeferringsys?language=objc).
|
||||||
|
///
|
||||||
|
/// This only has an effect on iOS 11.0+.
|
||||||
|
fn with_preferred_screen_edges_deferring_system_gestures(self, edges: ScreenEdge) -> Self;
|
||||||
|
|
||||||
|
/// Sets whether the [`Window`] prefers the status bar hidden.
|
||||||
|
///
|
||||||
|
/// The default is to prefer showing the status bar.
|
||||||
|
///
|
||||||
|
/// This sets the initial value returned by
|
||||||
|
/// [`-[UIViewController prefersStatusBarHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621440-prefersstatusbarhidden?language=objc).
|
||||||
|
fn with_prefers_status_bar_hidden(self, hidden: bool) -> Self;
|
||||||
|
|
||||||
|
/// Sets the style of the [`Window`]'s status bar.
|
||||||
|
///
|
||||||
|
/// The default is system-defined.
|
||||||
|
///
|
||||||
|
/// This sets the initial value returned by
|
||||||
|
/// [`-[UIViewController preferredStatusBarStyle]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621416-preferredstatusbarstyle?language=objc),
|
||||||
|
fn with_preferred_status_bar_style(self, status_bar_style: StatusBarStyle) -> Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowAttributesExtIOS for WindowAttributes {
|
||||||
|
#[inline]
|
||||||
|
fn with_scale_factor(mut self, scale_factor: f64) -> Self {
|
||||||
|
self.platform_specific.scale_factor = Some(scale_factor);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_valid_orientations(mut self, valid_orientations: ValidOrientations) -> Self {
|
||||||
|
self.platform_specific.valid_orientations = valid_orientations;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_prefers_home_indicator_hidden(mut self, hidden: bool) -> Self {
|
||||||
|
self.platform_specific.prefers_home_indicator_hidden = hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_preferred_screen_edges_deferring_system_gestures(mut self, edges: ScreenEdge) -> Self {
|
||||||
|
self.platform_specific
|
||||||
|
.preferred_screen_edges_deferring_system_gestures = edges;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_prefers_status_bar_hidden(mut self, hidden: bool) -> Self {
|
||||||
|
self.platform_specific.prefers_status_bar_hidden = hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_preferred_status_bar_style(mut self, status_bar_style: StatusBarStyle) -> Self {
|
||||||
|
self.platform_specific.preferred_status_bar_style = status_bar_style;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`MonitorHandle`] that are specific to iOS.
|
||||||
|
pub trait MonitorHandleExtIOS {
|
||||||
|
/// Returns a pointer to the [`UIScreen`] that is used by this monitor.
|
||||||
|
///
|
||||||
|
/// [`UIScreen`]: https://developer.apple.com/documentation/uikit/uiscreen?language=objc
|
||||||
|
fn ui_screen(&self) -> *mut c_void;
|
||||||
|
|
||||||
|
/// Returns the preferred [`VideoModeHandle`] for this monitor.
|
||||||
|
///
|
||||||
|
/// This translates to a call to [`-[UIScreen preferredMode]`](https://developer.apple.com/documentation/uikit/uiscreen/1617823-preferredmode?language=objc).
|
||||||
|
fn preferred_video_mode(&self) -> VideoModeHandle;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonitorHandleExtIOS for MonitorHandle {
|
||||||
|
#[inline]
|
||||||
|
fn ui_screen(&self) -> *mut c_void {
|
||||||
|
// SAFETY: The marker is only used to get the pointer of the screen
|
||||||
|
let mtm = unsafe { icrate::Foundation::MainThreadMarker::new_unchecked() };
|
||||||
|
objc2::rc::Id::as_ptr(self.inner.ui_screen(mtm)) as *mut c_void
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn preferred_video_mode(&self) -> VideoModeHandle {
|
||||||
|
VideoModeHandle {
|
||||||
|
video_mode: self.inner.preferred_video_mode(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Valid orientations for a particular [`Window`].
|
||||||
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub enum ValidOrientations {
|
||||||
|
/// Excludes `PortraitUpsideDown` on iphone
|
||||||
|
#[default]
|
||||||
|
LandscapeAndPortrait,
|
||||||
|
|
||||||
|
Landscape,
|
||||||
|
|
||||||
|
/// Excludes `PortraitUpsideDown` on iphone
|
||||||
|
Portrait,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The device [idiom].
|
||||||
|
///
|
||||||
|
/// [idiom]: https://developer.apple.com/documentation/uikit/uidevice/1620037-userinterfaceidiom?language=objc
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub enum Idiom {
|
||||||
|
Unspecified,
|
||||||
|
|
||||||
|
/// iPhone and iPod touch.
|
||||||
|
Phone,
|
||||||
|
|
||||||
|
/// iPad.
|
||||||
|
Pad,
|
||||||
|
|
||||||
|
/// tvOS and Apple TV.
|
||||||
|
TV,
|
||||||
|
CarPlay,
|
||||||
|
}
|
||||||
|
|
||||||
|
bitflags::bitflags! {
|
||||||
|
/// The [edges] of a screen.
|
||||||
|
///
|
||||||
|
/// [edges]: https://developer.apple.com/documentation/uikit/uirectedge?language=objc
|
||||||
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub struct ScreenEdge: u8 {
|
||||||
|
const NONE = 0;
|
||||||
|
const TOP = 1 << 0;
|
||||||
|
const LEFT = 1 << 1;
|
||||||
|
const BOTTOM = 1 << 2;
|
||||||
|
const RIGHT = 1 << 3;
|
||||||
|
const ALL = ScreenEdge::TOP.bits() | ScreenEdge::LEFT.bits()
|
||||||
|
| ScreenEdge::BOTTOM.bits() | ScreenEdge::RIGHT.bits();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub enum StatusBarStyle {
|
||||||
|
#[default]
|
||||||
|
Default,
|
||||||
|
LightContent,
|
||||||
|
DarkContent,
|
||||||
|
}
|
||||||
@@ -1,110 +0,0 @@
|
|||||||
#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals)]
|
|
||||||
|
|
||||||
use std::ffi::CString;
|
|
||||||
use std::os::raw::*;
|
|
||||||
|
|
||||||
use objc::runtime::Object;
|
|
||||||
|
|
||||||
pub type id = *mut Object;
|
|
||||||
pub const nil: id = 0 as id;
|
|
||||||
|
|
||||||
pub type CFStringRef = *const c_void;
|
|
||||||
pub type CFTimeInterval = f64;
|
|
||||||
pub type Boolean = u32;
|
|
||||||
|
|
||||||
pub const kCFRunLoopRunHandledSource: i32 = 4;
|
|
||||||
|
|
||||||
#[cfg(target_pointer_width = "32")]
|
|
||||||
pub type CGFloat = f32;
|
|
||||||
#[cfg(target_pointer_width = "64")]
|
|
||||||
pub type CGFloat = f64;
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct CGPoint {
|
|
||||||
pub x: CGFloat,
|
|
||||||
pub y: CGFloat,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct CGRect {
|
|
||||||
pub origin: CGPoint,
|
|
||||||
pub size: CGSize,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[repr(C)]
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct CGSize {
|
|
||||||
pub width: CGFloat,
|
|
||||||
pub height: CGFloat,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[link(name = "UIKit", kind = "framework")]
|
|
||||||
#[link(name = "CoreFoundation", kind = "framework")]
|
|
||||||
#[link(name = "GlKit", kind = "framework")]
|
|
||||||
extern {
|
|
||||||
pub static kCFRunLoopDefaultMode: CFStringRef;
|
|
||||||
|
|
||||||
// int UIApplicationMain ( int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName );
|
|
||||||
pub fn UIApplicationMain(
|
|
||||||
argc: c_int,
|
|
||||||
argv: *const c_char,
|
|
||||||
principalClassName: id,
|
|
||||||
delegateClassName: id,
|
|
||||||
) -> c_int;
|
|
||||||
|
|
||||||
// SInt32 CFRunLoopRunInMode ( CFStringRef mode, CFTimeInterval seconds, Boolean returnAfterSourceHandled );
|
|
||||||
pub fn CFRunLoopRunInMode(
|
|
||||||
mode: CFStringRef,
|
|
||||||
seconds: CFTimeInterval,
|
|
||||||
returnAfterSourceHandled: Boolean,
|
|
||||||
) -> i32;
|
|
||||||
}
|
|
||||||
|
|
||||||
extern {
|
|
||||||
pub fn setjmp(env: *mut c_void) -> c_int;
|
|
||||||
pub fn longjmp(env: *mut c_void, val: c_int) -> !;
|
|
||||||
}
|
|
||||||
|
|
||||||
// values taken from "setjmp.h" header in xcode iPhoneOS/iPhoneSimulator SDK
|
|
||||||
#[cfg(any(target_arch = "x86_64"))]
|
|
||||||
pub const JBLEN: usize = (9 * 2) + 3 + 16;
|
|
||||||
#[cfg(any(target_arch = "x86"))]
|
|
||||||
pub const JBLEN: usize = 18;
|
|
||||||
#[cfg(target_arch = "arm")]
|
|
||||||
pub const JBLEN: usize = 10 + 16 + 2;
|
|
||||||
#[cfg(target_arch = "aarch64")]
|
|
||||||
pub const JBLEN: usize = (14 + 8 + 2) * 2;
|
|
||||||
|
|
||||||
pub type JmpBuf = [c_int; JBLEN];
|
|
||||||
|
|
||||||
pub trait NSString: Sized {
|
|
||||||
unsafe fn alloc(_: Self) -> id {
|
|
||||||
msg_send![class!(NSString), alloc]
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn initWithUTF8String_(self, c_string: *const c_char) -> id;
|
|
||||||
unsafe fn stringByAppendingString_(self, other: id) -> id;
|
|
||||||
unsafe fn init_str(self, string: &str) -> Self;
|
|
||||||
unsafe fn UTF8String(self) -> *const c_char;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl NSString for id {
|
|
||||||
unsafe fn initWithUTF8String_(self, c_string: *const c_char) -> id {
|
|
||||||
msg_send![self, initWithUTF8String:c_string as id]
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn stringByAppendingString_(self, other: id) -> id {
|
|
||||||
msg_send![self, stringByAppendingString:other]
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn init_str(self, string: &str) -> id {
|
|
||||||
let cstring = CString::new(string).unwrap();
|
|
||||||
self.initWithUTF8String_(cstring.as_ptr())
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn UTF8String(self) -> *const c_char {
|
|
||||||
msg_send![self, UTF8String]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,690 +0,0 @@
|
|||||||
//! iOS support
|
|
||||||
//!
|
|
||||||
//! # Building app
|
|
||||||
//! To build ios app you will need rustc built for this targets:
|
|
||||||
//!
|
|
||||||
//! - armv7-apple-ios
|
|
||||||
//! - armv7s-apple-ios
|
|
||||||
//! - i386-apple-ios
|
|
||||||
//! - aarch64-apple-ios
|
|
||||||
//! - x86_64-apple-ios
|
|
||||||
//!
|
|
||||||
//! Then
|
|
||||||
//!
|
|
||||||
//! ```
|
|
||||||
//! cargo build --target=...
|
|
||||||
//! ```
|
|
||||||
//! The simplest way to integrate your app into xcode environment is to build it
|
|
||||||
//! as a static library. Wrap your main function and export it.
|
|
||||||
//!
|
|
||||||
//! ```rust, ignore
|
|
||||||
//! #[no_mangle]
|
|
||||||
//! pub extern fn start_winit_app() {
|
|
||||||
//! start_inner()
|
|
||||||
//! }
|
|
||||||
//!
|
|
||||||
//! fn start_inner() {
|
|
||||||
//! ...
|
|
||||||
//! }
|
|
||||||
//!
|
|
||||||
//! ```
|
|
||||||
//!
|
|
||||||
//! Compile project and then drag resulting .a into Xcode project. Add winit.h to xcode.
|
|
||||||
//!
|
|
||||||
//! ```ignore
|
|
||||||
//! void start_winit_app();
|
|
||||||
//! ```
|
|
||||||
//!
|
|
||||||
//! Use start_winit_app inside your xcode's main function.
|
|
||||||
//!
|
|
||||||
//!
|
|
||||||
//! # App lifecycle and events
|
|
||||||
//!
|
|
||||||
//! iOS environment is very different from other platforms and you must be very
|
|
||||||
//! careful with it's events. Familiarize yourself with
|
|
||||||
//! [app lifecycle](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/).
|
|
||||||
//!
|
|
||||||
//!
|
|
||||||
//! This is how those event are represented in winit:
|
|
||||||
//!
|
|
||||||
//! - applicationDidBecomeActive is Focused(true)
|
|
||||||
//! - applicationWillResignActive is Focused(false)
|
|
||||||
//! - applicationDidEnterBackground is Suspended(true)
|
|
||||||
//! - applicationWillEnterForeground is Suspended(false)
|
|
||||||
//! - applicationWillTerminate is Destroyed
|
|
||||||
//!
|
|
||||||
//! Keep in mind that after Destroyed event is received every attempt to draw with
|
|
||||||
//! opengl will result in segfault.
|
|
||||||
//!
|
|
||||||
//! Also note that app will not receive Destroyed event if suspended, it will be SIGKILL'ed
|
|
||||||
|
|
||||||
#![cfg(target_os = "ios")]
|
|
||||||
|
|
||||||
use std::{fmt, mem, ptr};
|
|
||||||
use std::cell::RefCell;
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
use std::os::raw::*;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use objc::declare::ClassDecl;
|
|
||||||
use objc::runtime::{BOOL, Class, Object, Sel, YES};
|
|
||||||
|
|
||||||
use {
|
|
||||||
CreationError,
|
|
||||||
Event,
|
|
||||||
LogicalPosition,
|
|
||||||
LogicalSize,
|
|
||||||
MouseCursor,
|
|
||||||
PhysicalPosition,
|
|
||||||
PhysicalSize,
|
|
||||||
WindowAttributes,
|
|
||||||
WindowEvent,
|
|
||||||
WindowId as RootEventId,
|
|
||||||
};
|
|
||||||
use events::{Touch, TouchPhase};
|
|
||||||
use window::MonitorId as RootMonitorId;
|
|
||||||
|
|
||||||
mod ffi;
|
|
||||||
use self::ffi::{
|
|
||||||
CFTimeInterval,
|
|
||||||
CFRunLoopRunInMode,
|
|
||||||
CGFloat,
|
|
||||||
CGPoint,
|
|
||||||
CGRect,
|
|
||||||
id,
|
|
||||||
JBLEN,
|
|
||||||
JmpBuf,
|
|
||||||
kCFRunLoopDefaultMode,
|
|
||||||
kCFRunLoopRunHandledSource,
|
|
||||||
longjmp,
|
|
||||||
nil,
|
|
||||||
NSString,
|
|
||||||
setjmp,
|
|
||||||
UIApplicationMain,
|
|
||||||
};
|
|
||||||
|
|
||||||
static mut JMPBUF: Option<Box<JmpBuf>> = None;
|
|
||||||
|
|
||||||
pub struct Window {
|
|
||||||
_events_queue: Arc<RefCell<VecDeque<Event>>>,
|
|
||||||
delegate_state: Box<DelegateState>,
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe impl Send for Window {}
|
|
||||||
unsafe impl Sync for Window {}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct DelegateState {
|
|
||||||
window: id,
|
|
||||||
controller: id,
|
|
||||||
view: id,
|
|
||||||
size: LogicalSize,
|
|
||||||
scale: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DelegateState {
|
|
||||||
fn new(window: id, controller: id, view: id, size: LogicalSize, scale: f64) -> DelegateState {
|
|
||||||
DelegateState {
|
|
||||||
window,
|
|
||||||
controller,
|
|
||||||
view,
|
|
||||||
size,
|
|
||||||
scale,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for DelegateState {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
unsafe {
|
|
||||||
let _: () = msg_send![self.window, release];
|
|
||||||
let _: () = msg_send![self.controller, release];
|
|
||||||
let _: () = msg_send![self.view, release];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct MonitorId;
|
|
||||||
|
|
||||||
impl fmt::Debug for MonitorId {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct MonitorId {
|
|
||||||
name: Option<String>,
|
|
||||||
dimensions: PhysicalSize,
|
|
||||||
position: PhysicalPosition,
|
|
||||||
hidpi_factor: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
let monitor_id_proxy = MonitorId {
|
|
||||||
name: self.get_name(),
|
|
||||||
dimensions: self.get_dimensions(),
|
|
||||||
position: self.get_position(),
|
|
||||||
hidpi_factor: self.get_hidpi_factor(),
|
|
||||||
};
|
|
||||||
|
|
||||||
monitor_id_proxy.fmt(f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorId {
|
|
||||||
#[inline]
|
|
||||||
pub fn get_uiscreen(&self) -> id {
|
|
||||||
let class = class!(UIScreen);
|
|
||||||
unsafe { msg_send![class, mainScreen] }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_name(&self) -> Option<String> {
|
|
||||||
Some("Primary".to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_dimensions(&self) -> PhysicalSize {
|
|
||||||
let bounds: CGRect = unsafe { msg_send![self.get_uiscreen(), nativeBounds] };
|
|
||||||
(bounds.size.width as f64, bounds.size.height as f64).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_position(&self) -> PhysicalPosition {
|
|
||||||
// iOS assumes single screen
|
|
||||||
(0, 0).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_hidpi_factor(&self) -> f64 {
|
|
||||||
let scale: CGFloat = unsafe { msg_send![self.get_uiscreen(), nativeScale] };
|
|
||||||
scale as f64
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct EventsLoop {
|
|
||||||
events_queue: Arc<RefCell<VecDeque<Event>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct EventsLoopProxy;
|
|
||||||
|
|
||||||
impl EventsLoop {
|
|
||||||
pub fn new() -> EventsLoop {
|
|
||||||
unsafe {
|
|
||||||
if !msg_send![class!(NSThread), isMainThread] {
|
|
||||||
panic!("`EventsLoop` can only be created on the main thread on iOS");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
EventsLoop { events_queue: Default::default() }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_available_monitors(&self) -> VecDeque<MonitorId> {
|
|
||||||
let mut rb = VecDeque::with_capacity(1);
|
|
||||||
rb.push_back(MonitorId);
|
|
||||||
rb
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_primary_monitor(&self) -> MonitorId {
|
|
||||||
MonitorId
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn poll_events<F>(&mut self, mut callback: F)
|
|
||||||
where F: FnMut(::Event)
|
|
||||||
{
|
|
||||||
if let Some(event) = self.events_queue.borrow_mut().pop_front() {
|
|
||||||
callback(event);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe {
|
|
||||||
// jump hack, so we won't quit on willTerminate event before processing it
|
|
||||||
assert!(JMPBUF.is_some(), "`EventsLoop::poll_events` must be called after window creation on iOS");
|
|
||||||
if setjmp(mem::transmute_copy(&mut JMPBUF)) != 0 {
|
|
||||||
if let Some(event) = self.events_queue.borrow_mut().pop_front() {
|
|
||||||
callback(event);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe {
|
|
||||||
// run runloop
|
|
||||||
let seconds: CFTimeInterval = 0.000002;
|
|
||||||
while CFRunLoopRunInMode(kCFRunLoopDefaultMode, seconds, 1) == kCFRunLoopRunHandledSource {}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(event) = self.events_queue.borrow_mut().pop_front() {
|
|
||||||
callback(event)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn run_forever<F>(&mut self, mut callback: F)
|
|
||||||
where F: FnMut(::Event) -> ::ControlFlow,
|
|
||||||
{
|
|
||||||
// Yeah that's a very bad implementation.
|
|
||||||
loop {
|
|
||||||
let mut control_flow = ::ControlFlow::Continue;
|
|
||||||
self.poll_events(|e| {
|
|
||||||
if let ::ControlFlow::Break = callback(e) {
|
|
||||||
control_flow = ::ControlFlow::Break;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
if let ::ControlFlow::Break = control_flow {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
::std::thread::sleep(::std::time::Duration::from_millis(5));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn create_proxy(&self) -> EventsLoopProxy {
|
|
||||||
EventsLoopProxy
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventsLoopProxy {
|
|
||||||
pub fn wakeup(&self) -> Result<(), ::EventsLoopClosed> {
|
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub struct WindowId;
|
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub struct DeviceId;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct PlatformSpecificWindowBuilderAttributes {
|
|
||||||
pub root_view_class: &'static Class,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for PlatformSpecificWindowBuilderAttributes {
|
|
||||||
fn default() -> Self {
|
|
||||||
PlatformSpecificWindowBuilderAttributes {
|
|
||||||
root_view_class: class!(UIView),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: AFAIK transparency is enabled by default on iOS,
|
|
||||||
// so to be consistent with other platforms we have to change that.
|
|
||||||
impl Window {
|
|
||||||
pub fn new(
|
|
||||||
ev: &EventsLoop,
|
|
||||||
_attributes: WindowAttributes,
|
|
||||||
pl_attributes: PlatformSpecificWindowBuilderAttributes,
|
|
||||||
) -> Result<Window, CreationError> {
|
|
||||||
unsafe {
|
|
||||||
debug_assert!(mem::size_of_val(&JMPBUF) == mem::size_of::<Box<JmpBuf>>());
|
|
||||||
assert!(mem::replace(&mut JMPBUF, Some(Box::new([0; JBLEN]))).is_none(), "Only one `Window` is supported on iOS");
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe {
|
|
||||||
if setjmp(mem::transmute_copy(&mut JMPBUF)) != 0 {
|
|
||||||
let app_class = class!(UIApplication);
|
|
||||||
let app: id = msg_send![app_class, sharedApplication];
|
|
||||||
let delegate: id = msg_send![app, delegate];
|
|
||||||
let state: *mut c_void = *(&*delegate).get_ivar("winitState");
|
|
||||||
let mut delegate_state = Box::from_raw(state as *mut DelegateState);
|
|
||||||
let events_queue = &*ev.events_queue;
|
|
||||||
(&mut *delegate).set_ivar("eventsQueue", mem::transmute::<_, *mut c_void>(events_queue));
|
|
||||||
|
|
||||||
// easiest? way to get access to PlatformSpecificWindowBuilderAttributes to configure the view
|
|
||||||
let rect: CGRect = msg_send![MonitorId.get_uiscreen(), bounds];
|
|
||||||
|
|
||||||
let uiview_class = class!(UIView);
|
|
||||||
let root_view_class = pl_attributes.root_view_class;
|
|
||||||
let is_uiview: BOOL = msg_send![root_view_class, isSubclassOfClass:uiview_class];
|
|
||||||
assert!(is_uiview == YES, "`root_view_class` must inherit from `UIView`");
|
|
||||||
|
|
||||||
delegate_state.view = msg_send![root_view_class, alloc];
|
|
||||||
assert!(!delegate_state.view.is_null(), "Failed to create `UIView` instance");
|
|
||||||
delegate_state.view = msg_send![delegate_state.view, initWithFrame:rect];
|
|
||||||
assert!(!delegate_state.view.is_null(), "Failed to initialize `UIView` instance");
|
|
||||||
|
|
||||||
let _: () = msg_send![delegate_state.controller, setView:delegate_state.view];
|
|
||||||
let _: () = msg_send![delegate_state.window, makeKeyAndVisible];
|
|
||||||
|
|
||||||
return Ok(Window {
|
|
||||||
_events_queue: ev.events_queue.clone(),
|
|
||||||
delegate_state,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
create_delegate_class();
|
|
||||||
start_app();
|
|
||||||
|
|
||||||
panic!("Couldn't create `UIApplication`!")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_uiwindow(&self) -> id {
|
|
||||||
self.delegate_state.window
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_uiview(&self) -> id {
|
|
||||||
self.delegate_state.view
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_title(&self, _title: &str) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn show(&self) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn hide(&self) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_position(&self) -> Option<LogicalPosition> {
|
|
||||||
// N/A
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_inner_position(&self) -> Option<LogicalPosition> {
|
|
||||||
// N/A
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_position(&self, _position: LogicalPosition) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_inner_size(&self) -> Option<LogicalSize> {
|
|
||||||
Some(self.delegate_state.size)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_outer_size(&self) -> Option<LogicalSize> {
|
|
||||||
self.get_inner_size()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_inner_size(&self, _size: LogicalSize) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_min_dimensions(&self, _dimensions: Option<LogicalSize>) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_max_dimensions(&self, _dimensions: Option<LogicalSize>) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_resizable(&self, _resizable: bool) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor(&self, _cursor: MouseCursor) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn grab_cursor(&self, _grab: bool) -> Result<(), String> {
|
|
||||||
Err("Cursor grabbing is not possible on iOS.".to_owned())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn hide_cursor(&self, _hide: bool) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_hidpi_factor(&self) -> f64 {
|
|
||||||
self.delegate_state.scale
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor_position(&self, _position: LogicalPosition) -> Result<(), String> {
|
|
||||||
Err("Setting cursor position is not possible on iOS.".to_owned())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_maximized(&self, _maximized: bool) {
|
|
||||||
// N/A
|
|
||||||
// iOS has single screen maximized apps so nothing to do
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_fullscreen(&self, _monitor: Option<RootMonitorId>) {
|
|
||||||
// N/A
|
|
||||||
// iOS has single screen maximized apps so nothing to do
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_decorations(&self, _decorations: bool) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_always_on_top(&self, _always_on_top: bool) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_window_icon(&self, _icon: Option<::Icon>) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_ime_spot(&self, _logical_spot: LogicalPosition) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_current_monitor(&self) -> RootMonitorId {
|
|
||||||
RootMonitorId { inner: MonitorId }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_available_monitors(&self) -> VecDeque<MonitorId> {
|
|
||||||
let mut rb = VecDeque::with_capacity(1);
|
|
||||||
rb.push_back(MonitorId);
|
|
||||||
rb
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_primary_monitor(&self) -> MonitorId {
|
|
||||||
MonitorId
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn id(&self) -> WindowId {
|
|
||||||
WindowId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn create_delegate_class() {
|
|
||||||
extern fn did_finish_launching(this: &mut Object, _: Sel, _: id, _: id) -> BOOL {
|
|
||||||
let screen_class = class!(UIScreen);
|
|
||||||
let window_class = class!(UIWindow);
|
|
||||||
let controller_class = class!(UIViewController);
|
|
||||||
unsafe {
|
|
||||||
let main_screen: id = msg_send![screen_class, mainScreen];
|
|
||||||
let bounds: CGRect = msg_send![main_screen, bounds];
|
|
||||||
let scale: CGFloat = msg_send![main_screen, nativeScale];
|
|
||||||
|
|
||||||
let window: id = msg_send![window_class, alloc];
|
|
||||||
let window: id = msg_send![window, initWithFrame:bounds.clone()];
|
|
||||||
|
|
||||||
let size = (bounds.size.width as f64, bounds.size.height as f64).into();
|
|
||||||
|
|
||||||
let view_controller: id = msg_send![controller_class, alloc];
|
|
||||||
let view_controller: id = msg_send![view_controller, init];
|
|
||||||
|
|
||||||
let _: () = msg_send![window, setRootViewController:view_controller];
|
|
||||||
|
|
||||||
let state = Box::new(DelegateState::new(window, view_controller, ptr::null_mut(), size, scale as f64));
|
|
||||||
let state_ptr: *mut DelegateState = mem::transmute(state);
|
|
||||||
this.set_ivar("winitState", state_ptr as *mut c_void);
|
|
||||||
|
|
||||||
// The `UIView` is setup in `Window::new` which gets `longjmp`'ed to here.
|
|
||||||
// This makes it easier to configure the specific `UIView` type.
|
|
||||||
let _: () = msg_send![this, performSelector:sel!(postLaunch:) withObject:nil afterDelay:0.0];
|
|
||||||
}
|
|
||||||
YES
|
|
||||||
}
|
|
||||||
|
|
||||||
extern fn post_launch(_: &Object, _: Sel, _: id) {
|
|
||||||
unsafe { longjmp(mem::transmute_copy(&mut JMPBUF), 1); }
|
|
||||||
}
|
|
||||||
|
|
||||||
extern fn did_become_active(this: &Object, _: Sel, _: id) {
|
|
||||||
unsafe {
|
|
||||||
let events_queue: *mut c_void = *this.get_ivar("eventsQueue");
|
|
||||||
let events_queue = &*(events_queue as *const RefCell<VecDeque<Event>>);
|
|
||||||
events_queue.borrow_mut().push_back(Event::WindowEvent {
|
|
||||||
window_id: RootEventId(WindowId),
|
|
||||||
event: WindowEvent::Focused(true),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extern fn will_resign_active(this: &Object, _: Sel, _: id) {
|
|
||||||
unsafe {
|
|
||||||
let events_queue: *mut c_void = *this.get_ivar("eventsQueue");
|
|
||||||
let events_queue = &*(events_queue as *const RefCell<VecDeque<Event>>);
|
|
||||||
events_queue.borrow_mut().push_back(Event::WindowEvent {
|
|
||||||
window_id: RootEventId(WindowId),
|
|
||||||
event: WindowEvent::Focused(false),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extern fn will_enter_foreground(this: &Object, _: Sel, _: id) {
|
|
||||||
unsafe {
|
|
||||||
let events_queue: *mut c_void = *this.get_ivar("eventsQueue");
|
|
||||||
let events_queue = &*(events_queue as *const RefCell<VecDeque<Event>>);
|
|
||||||
events_queue.borrow_mut().push_back(Event::Suspended(false));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extern fn did_enter_background(this: &Object, _: Sel, _: id) {
|
|
||||||
unsafe {
|
|
||||||
let events_queue: *mut c_void = *this.get_ivar("eventsQueue");
|
|
||||||
let events_queue = &*(events_queue as *const RefCell<VecDeque<Event>>);
|
|
||||||
events_queue.borrow_mut().push_back(Event::Suspended(true));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extern fn will_terminate(this: &Object, _: Sel, _: id) {
|
|
||||||
unsafe {
|
|
||||||
let events_queue: *mut c_void = *this.get_ivar("eventsQueue");
|
|
||||||
let events_queue = &*(events_queue as *const RefCell<VecDeque<Event>>);
|
|
||||||
// push event to the front to garantee that we'll process it
|
|
||||||
// immidiatly after jump
|
|
||||||
events_queue.borrow_mut().push_front(Event::WindowEvent {
|
|
||||||
window_id: RootEventId(WindowId),
|
|
||||||
event: WindowEvent::Destroyed,
|
|
||||||
});
|
|
||||||
longjmp(mem::transmute_copy(&mut JMPBUF), 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extern fn handle_touches(this: &Object, _: Sel, touches: id, _:id) {
|
|
||||||
unsafe {
|
|
||||||
let events_queue: *mut c_void = *this.get_ivar("eventsQueue");
|
|
||||||
let events_queue = &*(events_queue as *const RefCell<VecDeque<Event>>);
|
|
||||||
|
|
||||||
let touches_enum: id = msg_send![touches, objectEnumerator];
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let touch: id = msg_send![touches_enum, nextObject];
|
|
||||||
if touch == nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
let location: CGPoint = msg_send![touch, locationInView:nil];
|
|
||||||
let touch_id = touch as u64;
|
|
||||||
let phase: i32 = msg_send![touch, phase];
|
|
||||||
|
|
||||||
events_queue.borrow_mut().push_back(Event::WindowEvent {
|
|
||||||
window_id: RootEventId(WindowId),
|
|
||||||
event: WindowEvent::Touch(Touch {
|
|
||||||
device_id: DEVICE_ID,
|
|
||||||
id: touch_id,
|
|
||||||
location: (location.x as f64, location.y as f64).into(),
|
|
||||||
phase: match phase {
|
|
||||||
0 => TouchPhase::Started,
|
|
||||||
1 => TouchPhase::Moved,
|
|
||||||
// 2 is UITouchPhaseStationary and is not expected here
|
|
||||||
3 => TouchPhase::Ended,
|
|
||||||
4 => TouchPhase::Cancelled,
|
|
||||||
_ => panic!("unexpected touch phase: {:?}", phase)
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let ui_responder = class!(UIResponder);
|
|
||||||
let mut decl = ClassDecl::new("AppDelegate", ui_responder).expect("Failed to declare class `AppDelegate`");
|
|
||||||
|
|
||||||
unsafe {
|
|
||||||
decl.add_method(sel!(application:didFinishLaunchingWithOptions:),
|
|
||||||
did_finish_launching as extern fn(&mut Object, Sel, id, id) -> BOOL);
|
|
||||||
|
|
||||||
decl.add_method(sel!(applicationDidBecomeActive:),
|
|
||||||
did_become_active as extern fn(&Object, Sel, id));
|
|
||||||
|
|
||||||
decl.add_method(sel!(applicationWillResignActive:),
|
|
||||||
will_resign_active as extern fn(&Object, Sel, id));
|
|
||||||
|
|
||||||
decl.add_method(sel!(applicationWillEnterForeground:),
|
|
||||||
will_enter_foreground as extern fn(&Object, Sel, id));
|
|
||||||
|
|
||||||
decl.add_method(sel!(applicationDidEnterBackground:),
|
|
||||||
did_enter_background as extern fn(&Object, Sel, id));
|
|
||||||
|
|
||||||
decl.add_method(sel!(applicationWillTerminate:),
|
|
||||||
will_terminate as extern fn(&Object, Sel, id));
|
|
||||||
|
|
||||||
|
|
||||||
decl.add_method(sel!(touchesBegan:withEvent:),
|
|
||||||
handle_touches as extern fn(this: &Object, _: Sel, _: id, _:id));
|
|
||||||
|
|
||||||
decl.add_method(sel!(touchesMoved:withEvent:),
|
|
||||||
handle_touches as extern fn(this: &Object, _: Sel, _: id, _:id));
|
|
||||||
|
|
||||||
decl.add_method(sel!(touchesEnded:withEvent:),
|
|
||||||
handle_touches as extern fn(this: &Object, _: Sel, _: id, _:id));
|
|
||||||
|
|
||||||
decl.add_method(sel!(touchesCancelled:withEvent:),
|
|
||||||
handle_touches as extern fn(this: &Object, _: Sel, _: id, _:id));
|
|
||||||
|
|
||||||
|
|
||||||
decl.add_method(sel!(postLaunch:),
|
|
||||||
post_launch as extern fn(&Object, Sel, id));
|
|
||||||
|
|
||||||
decl.add_ivar::<*mut c_void>("winitState");
|
|
||||||
decl.add_ivar::<*mut c_void>("eventsQueue");
|
|
||||||
|
|
||||||
decl.register();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn start_app() {
|
|
||||||
unsafe {
|
|
||||||
UIApplicationMain(0, ptr::null(), nil, NSString::alloc(nil).init_str("AppDelegate"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Constant device ID, to be removed when this backend is updated to report real device IDs.
|
|
||||||
const DEVICE_ID: ::DeviceId = ::DeviceId(DeviceId);
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))]
|
|
||||||
#![allow(dead_code)]
|
|
||||||
|
|
||||||
use std::os::raw::{c_void, c_char, c_int};
|
|
||||||
|
|
||||||
pub const RTLD_LAZY: c_int = 0x001;
|
|
||||||
pub const RTLD_NOW: c_int = 0x002;
|
|
||||||
|
|
||||||
#[link="dl"]
|
|
||||||
extern {
|
|
||||||
pub fn dlopen(filename: *const c_char, flag: c_int) -> *mut c_void;
|
|
||||||
pub fn dlerror() -> *mut c_char;
|
|
||||||
pub fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
|
|
||||||
pub fn dlclose(handle: *mut c_void) -> c_int;
|
|
||||||
}
|
|
||||||
@@ -1,531 +0,0 @@
|
|||||||
#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))]
|
|
||||||
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
use std::{env, mem};
|
|
||||||
use std::ffi::CStr;
|
|
||||||
use std::os::raw::*;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use parking_lot::Mutex;
|
|
||||||
use sctk::reexports::client::ConnectError;
|
|
||||||
|
|
||||||
use {
|
|
||||||
CreationError,
|
|
||||||
EventsLoopClosed,
|
|
||||||
Icon,
|
|
||||||
MouseCursor,
|
|
||||||
ControlFlow,
|
|
||||||
WindowAttributes,
|
|
||||||
};
|
|
||||||
use dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize};
|
|
||||||
use window::MonitorId as RootMonitorId;
|
|
||||||
use self::x11::{XConnection, XError};
|
|
||||||
use self::x11::ffi::XVisualInfo;
|
|
||||||
pub use self::x11::XNotSupported;
|
|
||||||
|
|
||||||
mod dlopen;
|
|
||||||
pub mod wayland;
|
|
||||||
pub mod x11;
|
|
||||||
|
|
||||||
/// Environment variable specifying which backend should be used on unix platform.
|
|
||||||
///
|
|
||||||
/// Legal values are x11 and wayland. If this variable is set only the named backend
|
|
||||||
/// will be tried by winit. If it is not set, winit will try to connect to a wayland connection,
|
|
||||||
/// and if it fails will fallback on x11.
|
|
||||||
///
|
|
||||||
/// If this variable is set with any other value, winit will panic.
|
|
||||||
const BACKEND_PREFERENCE_ENV_VAR: &str = "WINIT_UNIX_BACKEND";
|
|
||||||
|
|
||||||
#[derive(Clone, Default)]
|
|
||||||
pub struct PlatformSpecificWindowBuilderAttributes {
|
|
||||||
pub visual_infos: Option<XVisualInfo>,
|
|
||||||
pub screen_id: Option<i32>,
|
|
||||||
pub resize_increments: Option<(u32, u32)>,
|
|
||||||
pub base_size: Option<(u32, u32)>,
|
|
||||||
pub class: Option<(String, String)>,
|
|
||||||
pub override_redirect: bool,
|
|
||||||
pub x11_window_type: x11::util::WindowType,
|
|
||||||
}
|
|
||||||
|
|
||||||
lazy_static!(
|
|
||||||
pub static ref X11_BACKEND: Mutex<Result<Arc<XConnection>, XNotSupported>> = {
|
|
||||||
Mutex::new(XConnection::new(Some(x_error_callback)).map(Arc::new))
|
|
||||||
};
|
|
||||||
);
|
|
||||||
|
|
||||||
pub enum Window {
|
|
||||||
X(x11::Window),
|
|
||||||
Wayland(wayland::Window),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub enum WindowId {
|
|
||||||
X(x11::WindowId),
|
|
||||||
Wayland(wayland::WindowId),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub enum DeviceId {
|
|
||||||
X(x11::DeviceId),
|
|
||||||
Wayland(wayland::DeviceId),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub enum MonitorId {
|
|
||||||
X(x11::MonitorId),
|
|
||||||
Wayland(wayland::MonitorId),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorId {
|
|
||||||
#[inline]
|
|
||||||
pub fn get_name(&self) -> Option<String> {
|
|
||||||
match self {
|
|
||||||
&MonitorId::X(ref m) => m.get_name(),
|
|
||||||
&MonitorId::Wayland(ref m) => m.get_name(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_native_identifier(&self) -> u32 {
|
|
||||||
match self {
|
|
||||||
&MonitorId::X(ref m) => m.get_native_identifier(),
|
|
||||||
&MonitorId::Wayland(ref m) => m.get_native_identifier(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_dimensions(&self) -> PhysicalSize {
|
|
||||||
match self {
|
|
||||||
&MonitorId::X(ref m) => m.get_dimensions(),
|
|
||||||
&MonitorId::Wayland(ref m) => m.get_dimensions(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_position(&self) -> PhysicalPosition {
|
|
||||||
match self {
|
|
||||||
&MonitorId::X(ref m) => m.get_position(),
|
|
||||||
&MonitorId::Wayland(ref m) => m.get_position(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_hidpi_factor(&self) -> f64 {
|
|
||||||
match self {
|
|
||||||
&MonitorId::X(ref m) => m.get_hidpi_factor(),
|
|
||||||
&MonitorId::Wayland(ref m) => m.get_hidpi_factor() as f64,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Window {
|
|
||||||
#[inline]
|
|
||||||
pub fn new(
|
|
||||||
events_loop: &EventsLoop,
|
|
||||||
attribs: WindowAttributes,
|
|
||||||
pl_attribs: PlatformSpecificWindowBuilderAttributes,
|
|
||||||
) -> Result<Self, CreationError> {
|
|
||||||
match *events_loop {
|
|
||||||
EventsLoop::Wayland(ref events_loop) => {
|
|
||||||
wayland::Window::new(events_loop, attribs).map(Window::Wayland)
|
|
||||||
},
|
|
||||||
EventsLoop::X(ref events_loop) => {
|
|
||||||
x11::Window::new(events_loop, attribs, pl_attribs).map(Window::X)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn id(&self) -> WindowId {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => WindowId::X(w.id()),
|
|
||||||
&Window::Wayland(ref w) => WindowId::Wayland(w.id()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_title(&self, title: &str) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_title(title),
|
|
||||||
&Window::Wayland(ref w) => w.set_title(title),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn show(&self) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.show(),
|
|
||||||
&Window::Wayland(ref w) => w.show(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn hide(&self) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.hide(),
|
|
||||||
&Window::Wayland(ref w) => w.hide(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_position(&self) -> Option<LogicalPosition> {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.get_position(),
|
|
||||||
&Window::Wayland(ref w) => w.get_position(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_inner_position(&self) -> Option<LogicalPosition> {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref m) => m.get_inner_position(),
|
|
||||||
&Window::Wayland(ref m) => m.get_inner_position(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_position(&self, position: LogicalPosition) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_position(position),
|
|
||||||
&Window::Wayland(ref w) => w.set_position(position),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_inner_size(&self) -> Option<LogicalSize> {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.get_inner_size(),
|
|
||||||
&Window::Wayland(ref w) => w.get_inner_size(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_outer_size(&self) -> Option<LogicalSize> {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.get_outer_size(),
|
|
||||||
&Window::Wayland(ref w) => w.get_outer_size(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_inner_size(&self, size: LogicalSize) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_inner_size(size),
|
|
||||||
&Window::Wayland(ref w) => w.set_inner_size(size),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_min_dimensions(&self, dimensions: Option<LogicalSize>) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_min_dimensions(dimensions),
|
|
||||||
&Window::Wayland(ref w) => w.set_min_dimensions(dimensions),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_max_dimensions(&self, dimensions: Option<LogicalSize>) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_max_dimensions(dimensions),
|
|
||||||
&Window::Wayland(ref w) => w.set_max_dimensions(dimensions),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_resizable(&self, resizable: bool) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_resizable(resizable),
|
|
||||||
&Window::Wayland(ref w) => w.set_resizable(resizable),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor(&self, cursor: MouseCursor) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_cursor(cursor),
|
|
||||||
&Window::Wayland(ref w) => w.set_cursor(cursor)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn grab_cursor(&self, grab: bool) -> Result<(), String> {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref window) => window.grab_cursor(grab),
|
|
||||||
&Window::Wayland(ref window) => window.grab_cursor(grab),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn hide_cursor(&self, hide: bool) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref window) => window.hide_cursor(hide),
|
|
||||||
&Window::Wayland(ref window) => window.hide_cursor(hide),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_hidpi_factor(&self) -> f64 {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.get_hidpi_factor(),
|
|
||||||
&Window::Wayland(ref w) => w.hidpi_factor() as f64,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor_position(&self, position: LogicalPosition) -> Result<(), String> {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_cursor_position(position),
|
|
||||||
&Window::Wayland(ref w) => w.set_cursor_position(position),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_maximized(&self, maximized: bool) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_maximized(maximized),
|
|
||||||
&Window::Wayland(ref w) => w.set_maximized(maximized),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_fullscreen(&self, monitor: Option<RootMonitorId>) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_fullscreen(monitor),
|
|
||||||
&Window::Wayland(ref w) => w.set_fullscreen(monitor)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_decorations(&self, decorations: bool) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_decorations(decorations),
|
|
||||||
&Window::Wayland(ref w) => w.set_decorations(decorations)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_always_on_top(&self, always_on_top: bool) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_always_on_top(always_on_top),
|
|
||||||
&Window::Wayland(_) => (),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_window_icon(&self, window_icon: Option<Icon>) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_window_icon(window_icon),
|
|
||||||
&Window::Wayland(_) => (),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_ime_spot(&self, position: LogicalPosition) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_ime_spot(position),
|
|
||||||
&Window::Wayland(_) => (),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_current_monitor(&self) -> RootMonitorId {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref window) => RootMonitorId { inner: MonitorId::X(window.get_current_monitor()) },
|
|
||||||
&Window::Wayland(ref window) => RootMonitorId { inner: MonitorId::Wayland(window.get_current_monitor()) },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_available_monitors(&self) -> VecDeque<MonitorId> {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref window) => window.get_available_monitors()
|
|
||||||
.into_iter()
|
|
||||||
.map(MonitorId::X)
|
|
||||||
.collect(),
|
|
||||||
&Window::Wayland(ref window) => window.get_available_monitors()
|
|
||||||
.into_iter()
|
|
||||||
.map(MonitorId::Wayland)
|
|
||||||
.collect(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_primary_monitor(&self) -> MonitorId {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref window) => MonitorId::X(window.get_primary_monitor()),
|
|
||||||
&Window::Wayland(ref window) => MonitorId::Wayland(window.get_primary_monitor()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe extern "C" fn x_error_callback(
|
|
||||||
display: *mut x11::ffi::Display,
|
|
||||||
event: *mut x11::ffi::XErrorEvent,
|
|
||||||
) -> c_int {
|
|
||||||
let xconn_lock = X11_BACKEND.lock();
|
|
||||||
if let Ok(ref xconn) = *xconn_lock {
|
|
||||||
let mut buf: [c_char; 1024] = mem::uninitialized();
|
|
||||||
(xconn.xlib.XGetErrorText)(
|
|
||||||
display,
|
|
||||||
(*event).error_code as c_int,
|
|
||||||
buf.as_mut_ptr(),
|
|
||||||
buf.len() as c_int,
|
|
||||||
);
|
|
||||||
let description = CStr::from_ptr(buf.as_ptr()).to_string_lossy();
|
|
||||||
|
|
||||||
let error = XError {
|
|
||||||
description: description.into_owned(),
|
|
||||||
error_code: (*event).error_code,
|
|
||||||
request_code: (*event).request_code,
|
|
||||||
minor_code: (*event).minor_code,
|
|
||||||
};
|
|
||||||
|
|
||||||
eprintln!("[winit X11 error] {:#?}", error);
|
|
||||||
|
|
||||||
*xconn.latest_error.lock() = Some(error);
|
|
||||||
}
|
|
||||||
// Fun fact: this return value is completely ignored.
|
|
||||||
0
|
|
||||||
}
|
|
||||||
|
|
||||||
pub enum EventsLoop {
|
|
||||||
Wayland(wayland::EventsLoop),
|
|
||||||
X(x11::EventsLoop)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub enum EventsLoopProxy {
|
|
||||||
X(x11::EventsLoopProxy),
|
|
||||||
Wayland(wayland::EventsLoopProxy),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventsLoop {
|
|
||||||
pub fn new() -> EventsLoop {
|
|
||||||
if let Ok(env_var) = env::var(BACKEND_PREFERENCE_ENV_VAR) {
|
|
||||||
match env_var.as_str() {
|
|
||||||
"x11" => {
|
|
||||||
// TODO: propagate
|
|
||||||
return EventsLoop::new_x11().expect("Failed to initialize X11 backend");
|
|
||||||
},
|
|
||||||
"wayland" => {
|
|
||||||
return EventsLoop::new_wayland()
|
|
||||||
.expect("Failed to initialize Wayland backend");
|
|
||||||
},
|
|
||||||
_ => panic!(
|
|
||||||
"Unknown environment variable value for {}, try one of `x11`,`wayland`",
|
|
||||||
BACKEND_PREFERENCE_ENV_VAR,
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let wayland_err = match EventsLoop::new_wayland() {
|
|
||||||
Ok(event_loop) => return event_loop,
|
|
||||||
Err(err) => err,
|
|
||||||
};
|
|
||||||
|
|
||||||
let x11_err = match EventsLoop::new_x11() {
|
|
||||||
Ok(event_loop) => return event_loop,
|
|
||||||
Err(err) => err,
|
|
||||||
};
|
|
||||||
|
|
||||||
let err_string = format!(
|
|
||||||
r#"Failed to initialize any backend!
|
|
||||||
Wayland status: {:#?}
|
|
||||||
X11 status: {:#?}
|
|
||||||
"#,
|
|
||||||
wayland_err,
|
|
||||||
x11_err,
|
|
||||||
);
|
|
||||||
panic!(err_string);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_wayland() -> Result<EventsLoop, ConnectError> {
|
|
||||||
wayland::EventsLoop::new()
|
|
||||||
.map(EventsLoop::Wayland)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_x11() -> Result<EventsLoop, XNotSupported> {
|
|
||||||
X11_BACKEND
|
|
||||||
.lock()
|
|
||||||
.as_ref()
|
|
||||||
.map(Arc::clone)
|
|
||||||
.map(x11::EventsLoop::new)
|
|
||||||
.map(EventsLoop::X)
|
|
||||||
.map_err(|err| err.clone())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_available_monitors(&self) -> VecDeque<MonitorId> {
|
|
||||||
match *self {
|
|
||||||
EventsLoop::Wayland(ref evlp) => evlp
|
|
||||||
.get_available_monitors()
|
|
||||||
.into_iter()
|
|
||||||
.map(MonitorId::Wayland)
|
|
||||||
.collect(),
|
|
||||||
EventsLoop::X(ref evlp) => evlp
|
|
||||||
.x_connection()
|
|
||||||
.get_available_monitors()
|
|
||||||
.into_iter()
|
|
||||||
.map(MonitorId::X)
|
|
||||||
.collect(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_primary_monitor(&self) -> MonitorId {
|
|
||||||
match *self {
|
|
||||||
EventsLoop::Wayland(ref evlp) => MonitorId::Wayland(evlp.get_primary_monitor()),
|
|
||||||
EventsLoop::X(ref evlp) => MonitorId::X(evlp.x_connection().get_primary_monitor()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn create_proxy(&self) -> EventsLoopProxy {
|
|
||||||
match *self {
|
|
||||||
EventsLoop::Wayland(ref evlp) => EventsLoopProxy::Wayland(evlp.create_proxy()),
|
|
||||||
EventsLoop::X(ref evlp) => EventsLoopProxy::X(evlp.create_proxy()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn poll_events<F>(&mut self, callback: F)
|
|
||||||
where F: FnMut(::Event)
|
|
||||||
{
|
|
||||||
match *self {
|
|
||||||
EventsLoop::Wayland(ref mut evlp) => evlp.poll_events(callback),
|
|
||||||
EventsLoop::X(ref mut evlp) => evlp.poll_events(callback)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn run_forever<F>(&mut self, callback: F)
|
|
||||||
where F: FnMut(::Event) -> ControlFlow
|
|
||||||
{
|
|
||||||
match *self {
|
|
||||||
EventsLoop::Wayland(ref mut evlp) => evlp.run_forever(callback),
|
|
||||||
EventsLoop::X(ref mut evlp) => evlp.run_forever(callback)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn is_wayland(&self) -> bool {
|
|
||||||
match *self {
|
|
||||||
EventsLoop::Wayland(_) => true,
|
|
||||||
EventsLoop::X(_) => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn x_connection(&self) -> Option<&Arc<XConnection>> {
|
|
||||||
match *self {
|
|
||||||
EventsLoop::Wayland(_) => None,
|
|
||||||
EventsLoop::X(ref ev) => Some(ev.x_connection()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventsLoopProxy {
|
|
||||||
pub fn wakeup(&self) -> Result<(), EventsLoopClosed> {
|
|
||||||
match *self {
|
|
||||||
EventsLoopProxy::Wayland(ref proxy) => proxy.wakeup(),
|
|
||||||
EventsLoopProxy::X(ref proxy) => proxy.wakeup(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,504 +0,0 @@
|
|||||||
use std::cell::RefCell;
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
use std::fmt;
|
|
||||||
use std::sync::{Arc, Mutex, Weak};
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
|
||||||
|
|
||||||
use {ControlFlow, EventsLoopClosed, PhysicalPosition, PhysicalSize};
|
|
||||||
|
|
||||||
use super::WindowId;
|
|
||||||
use super::window::WindowStore;
|
|
||||||
|
|
||||||
use sctk::Environment;
|
|
||||||
use sctk::output::OutputMgr;
|
|
||||||
use sctk::reexports::client::{Display, EventQueue, GlobalEvent, Proxy, ConnectError};
|
|
||||||
use sctk::reexports::client::commons::Implementation;
|
|
||||||
use sctk::reexports::client::protocol::{wl_keyboard, wl_output, wl_pointer, wl_registry, wl_seat,
|
|
||||||
wl_touch};
|
|
||||||
|
|
||||||
use sctk::reexports::client::protocol::wl_display::RequestsTrait as DisplayRequests;
|
|
||||||
|
|
||||||
pub struct EventsLoopSink {
|
|
||||||
buffer: VecDeque<::Event>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventsLoopSink {
|
|
||||||
pub fn new() -> EventsLoopSink {
|
|
||||||
EventsLoopSink {
|
|
||||||
buffer: VecDeque::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn send_event(&mut self, evt: ::WindowEvent, wid: WindowId) {
|
|
||||||
let evt = ::Event::WindowEvent {
|
|
||||||
event: evt,
|
|
||||||
window_id: ::WindowId(::platform::WindowId::Wayland(wid)),
|
|
||||||
};
|
|
||||||
self.buffer.push_back(evt);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn send_raw_event(&mut self, evt: ::Event) {
|
|
||||||
self.buffer.push_back(evt);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn empty_with<F>(&mut self, callback: &mut F)
|
|
||||||
where
|
|
||||||
F: FnMut(::Event),
|
|
||||||
{
|
|
||||||
for evt in self.buffer.drain(..) {
|
|
||||||
callback(evt)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct EventsLoop {
|
|
||||||
// The Event Queue
|
|
||||||
pub evq: RefCell<EventQueue>,
|
|
||||||
// our sink, shared with some handlers, buffering the events
|
|
||||||
sink: Arc<Mutex<EventsLoopSink>>,
|
|
||||||
// Whether or not there is a pending `Awakened` event to be emitted.
|
|
||||||
pending_wakeup: Arc<AtomicBool>,
|
|
||||||
// The window store
|
|
||||||
pub store: Arc<Mutex<WindowStore>>,
|
|
||||||
// the env
|
|
||||||
pub env: Environment,
|
|
||||||
// a cleanup switch to prune dead windows
|
|
||||||
pub cleanup_needed: Arc<Mutex<bool>>,
|
|
||||||
// The wayland display
|
|
||||||
pub display: Arc<Display>,
|
|
||||||
// The list of seats
|
|
||||||
pub seats: Arc<Mutex<Vec<(u32, Proxy<wl_seat::WlSeat>)>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
// A handle that can be sent across threads and used to wake up the `EventsLoop`.
|
|
||||||
//
|
|
||||||
// We should only try and wake up the `EventsLoop` if it still exists, so we hold Weak ptrs.
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct EventsLoopProxy {
|
|
||||||
display: Weak<Display>,
|
|
||||||
pending_wakeup: Weak<AtomicBool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventsLoopProxy {
|
|
||||||
// Causes the `EventsLoop` to stop blocking on `run_forever` and emit an `Awakened` event.
|
|
||||||
//
|
|
||||||
// Returns `Err` if the associated `EventsLoop` no longer exists.
|
|
||||||
pub fn wakeup(&self) -> Result<(), EventsLoopClosed> {
|
|
||||||
let display = self.display.upgrade();
|
|
||||||
let wakeup = self.pending_wakeup.upgrade();
|
|
||||||
match (display, wakeup) {
|
|
||||||
(Some(display), Some(wakeup)) => {
|
|
||||||
// Update the `EventsLoop`'s `pending_wakeup` flag.
|
|
||||||
wakeup.store(true, Ordering::Relaxed);
|
|
||||||
// Cause the `EventsLoop` to break from `dispatch` if it is currently blocked.
|
|
||||||
let _ = display.sync();
|
|
||||||
display.flush().map_err(|_| EventsLoopClosed)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
_ => Err(EventsLoopClosed),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventsLoop {
|
|
||||||
pub fn new() -> Result<EventsLoop, ConnectError> {
|
|
||||||
let (display, mut event_queue) = Display::connect_to_env()?;
|
|
||||||
|
|
||||||
let sink = Arc::new(Mutex::new(EventsLoopSink::new()));
|
|
||||||
let store = Arc::new(Mutex::new(WindowStore::new()));
|
|
||||||
let seats = Arc::new(Mutex::new(Vec::new()));
|
|
||||||
|
|
||||||
let env = Environment::from_registry_with_cb(
|
|
||||||
display.get_registry().unwrap(),
|
|
||||||
&mut event_queue,
|
|
||||||
SeatManager {
|
|
||||||
sink: sink.clone(),
|
|
||||||
store: store.clone(),
|
|
||||||
seats: seats.clone(),
|
|
||||||
},
|
|
||||||
).unwrap();
|
|
||||||
|
|
||||||
Ok(EventsLoop {
|
|
||||||
display: Arc::new(display),
|
|
||||||
evq: RefCell::new(event_queue),
|
|
||||||
sink: sink,
|
|
||||||
pending_wakeup: Arc::new(AtomicBool::new(false)),
|
|
||||||
store: store,
|
|
||||||
env: env,
|
|
||||||
cleanup_needed: Arc::new(Mutex::new(false)),
|
|
||||||
seats: seats,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn create_proxy(&self) -> EventsLoopProxy {
|
|
||||||
EventsLoopProxy {
|
|
||||||
display: Arc::downgrade(&self.display),
|
|
||||||
pending_wakeup: Arc::downgrade(&self.pending_wakeup),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn poll_events<F>(&mut self, mut callback: F)
|
|
||||||
where
|
|
||||||
F: FnMut(::Event),
|
|
||||||
{
|
|
||||||
// send pending events to the server
|
|
||||||
self.display.flush().expect("Wayland connection lost.");
|
|
||||||
|
|
||||||
// dispatch any pre-buffered events
|
|
||||||
self.sink.lock().unwrap().empty_with(&mut callback);
|
|
||||||
|
|
||||||
// try to read pending events
|
|
||||||
if let Some(h) = self.evq.get_mut().prepare_read() {
|
|
||||||
h.read_events().expect("Wayland connection lost.");
|
|
||||||
}
|
|
||||||
// dispatch wayland events
|
|
||||||
self.evq
|
|
||||||
.get_mut()
|
|
||||||
.dispatch_pending()
|
|
||||||
.expect("Wayland connection lost.");
|
|
||||||
self.post_dispatch_triggers();
|
|
||||||
|
|
||||||
// dispatch buffered events to client
|
|
||||||
self.sink.lock().unwrap().empty_with(&mut callback);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn run_forever<F>(&mut self, mut callback: F)
|
|
||||||
where
|
|
||||||
F: FnMut(::Event) -> ControlFlow,
|
|
||||||
{
|
|
||||||
// send pending events to the server
|
|
||||||
self.display.flush().expect("Wayland connection lost.");
|
|
||||||
|
|
||||||
// Check for control flow by wrapping the callback.
|
|
||||||
let control_flow = ::std::cell::Cell::new(ControlFlow::Continue);
|
|
||||||
let mut callback = |event| {
|
|
||||||
if let ControlFlow::Break = callback(event) {
|
|
||||||
control_flow.set(ControlFlow::Break);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// dispatch any pre-buffered events
|
|
||||||
self.post_dispatch_triggers();
|
|
||||||
self.sink.lock().unwrap().empty_with(&mut callback);
|
|
||||||
|
|
||||||
loop {
|
|
||||||
// dispatch events blocking if needed
|
|
||||||
self.evq
|
|
||||||
.get_mut()
|
|
||||||
.dispatch()
|
|
||||||
.expect("Wayland connection lost.");
|
|
||||||
self.post_dispatch_triggers();
|
|
||||||
|
|
||||||
// empty buffer of events
|
|
||||||
self.sink.lock().unwrap().empty_with(&mut callback);
|
|
||||||
|
|
||||||
if let ControlFlow::Break = control_flow.get() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_primary_monitor(&self) -> MonitorId {
|
|
||||||
get_primary_monitor(&self.env.outputs)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_available_monitors(&self) -> VecDeque<MonitorId> {
|
|
||||||
get_available_monitors(&self.env.outputs)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Private EventsLoop Internals
|
|
||||||
*/
|
|
||||||
|
|
||||||
impl EventsLoop {
|
|
||||||
fn post_dispatch_triggers(&mut self) {
|
|
||||||
let mut sink = self.sink.lock().unwrap();
|
|
||||||
// process a possible pending wakeup call
|
|
||||||
if self.pending_wakeup.load(Ordering::Relaxed) {
|
|
||||||
sink.send_raw_event(::Event::Awakened);
|
|
||||||
self.pending_wakeup.store(false, Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
// prune possible dead windows
|
|
||||||
{
|
|
||||||
let mut cleanup_needed = self.cleanup_needed.lock().unwrap();
|
|
||||||
if *cleanup_needed {
|
|
||||||
let pruned = self.store.lock().unwrap().cleanup();
|
|
||||||
*cleanup_needed = false;
|
|
||||||
for wid in pruned {
|
|
||||||
sink.send_event(::WindowEvent::Destroyed, wid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// process pending resize/refresh
|
|
||||||
self.store.lock().unwrap().for_each(
|
|
||||||
|newsize, size, new_dpi, refresh, frame_refresh, closed, wid, frame| {
|
|
||||||
if let Some(frame) = frame {
|
|
||||||
if let Some((w, h)) = newsize {
|
|
||||||
frame.resize(w, h);
|
|
||||||
frame.refresh();
|
|
||||||
let logical_size = ::LogicalSize::new(w as f64, h as f64);
|
|
||||||
sink.send_event(::WindowEvent::Resized(logical_size), wid);
|
|
||||||
*size = (w, h);
|
|
||||||
} else if frame_refresh {
|
|
||||||
frame.refresh();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(dpi) = new_dpi {
|
|
||||||
sink.send_event(::WindowEvent::HiDpiFactorChanged(dpi as f64), wid);
|
|
||||||
}
|
|
||||||
if refresh {
|
|
||||||
sink.send_event(::WindowEvent::Refresh, wid);
|
|
||||||
}
|
|
||||||
if closed {
|
|
||||||
sink.send_event(::WindowEvent::CloseRequested, wid);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Wayland protocol implementations
|
|
||||||
*/
|
|
||||||
|
|
||||||
struct SeatManager {
|
|
||||||
sink: Arc<Mutex<EventsLoopSink>>,
|
|
||||||
store: Arc<Mutex<WindowStore>>,
|
|
||||||
seats: Arc<Mutex<Vec<(u32, Proxy<wl_seat::WlSeat>)>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Implementation<Proxy<wl_registry::WlRegistry>, GlobalEvent> for SeatManager {
|
|
||||||
fn receive(&mut self, evt: GlobalEvent, registry: Proxy<wl_registry::WlRegistry>) {
|
|
||||||
use self::wl_registry::RequestsTrait as RegistryRequests;
|
|
||||||
use self::wl_seat::RequestsTrait as SeatRequests;
|
|
||||||
match evt {
|
|
||||||
GlobalEvent::New {
|
|
||||||
id,
|
|
||||||
ref interface,
|
|
||||||
version,
|
|
||||||
} if interface == "wl_seat" =>
|
|
||||||
{
|
|
||||||
use std::cmp::min;
|
|
||||||
let seat = registry
|
|
||||||
.bind::<wl_seat::WlSeat>(min(version, 5), id)
|
|
||||||
.unwrap()
|
|
||||||
.implement(SeatData {
|
|
||||||
sink: self.sink.clone(),
|
|
||||||
store: self.store.clone(),
|
|
||||||
pointer: None,
|
|
||||||
keyboard: None,
|
|
||||||
touch: None,
|
|
||||||
});
|
|
||||||
self.store.lock().unwrap().new_seat(&seat);
|
|
||||||
self.seats.lock().unwrap().push((id, seat));
|
|
||||||
}
|
|
||||||
GlobalEvent::Removed { id, ref interface } if interface == "wl_seat" => {
|
|
||||||
let mut seats = self.seats.lock().unwrap();
|
|
||||||
if let Some(idx) = seats.iter().position(|&(i, _)| i == id) {
|
|
||||||
let (_, seat) = seats.swap_remove(idx);
|
|
||||||
if seat.version() >= 5 {
|
|
||||||
seat.release();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct SeatData {
|
|
||||||
sink: Arc<Mutex<EventsLoopSink>>,
|
|
||||||
store: Arc<Mutex<WindowStore>>,
|
|
||||||
pointer: Option<Proxy<wl_pointer::WlPointer>>,
|
|
||||||
keyboard: Option<Proxy<wl_keyboard::WlKeyboard>>,
|
|
||||||
touch: Option<Proxy<wl_touch::WlTouch>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Implementation<Proxy<wl_seat::WlSeat>, wl_seat::Event> for SeatData {
|
|
||||||
fn receive(&mut self, evt: wl_seat::Event, seat: Proxy<wl_seat::WlSeat>) {
|
|
||||||
use self::wl_seat::RequestsTrait as SeatRequests;
|
|
||||||
match evt {
|
|
||||||
wl_seat::Event::Name { .. } => (),
|
|
||||||
wl_seat::Event::Capabilities { capabilities } => {
|
|
||||||
// create pointer if applicable
|
|
||||||
if capabilities.contains(wl_seat::Capability::Pointer) && self.pointer.is_none() {
|
|
||||||
self.pointer = Some(super::pointer::implement_pointer(
|
|
||||||
seat.get_pointer().unwrap(),
|
|
||||||
self.sink.clone(),
|
|
||||||
self.store.clone(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
// destroy pointer if applicable
|
|
||||||
if !capabilities.contains(wl_seat::Capability::Pointer) {
|
|
||||||
if let Some(pointer) = self.pointer.take() {
|
|
||||||
if pointer.version() >= 3 {
|
|
||||||
use self::wl_pointer::RequestsTrait;
|
|
||||||
pointer.release();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// create keyboard if applicable
|
|
||||||
if capabilities.contains(wl_seat::Capability::Keyboard) && self.keyboard.is_none() {
|
|
||||||
self.keyboard = Some(super::keyboard::init_keyboard(
|
|
||||||
seat.get_keyboard().unwrap(),
|
|
||||||
self.sink.clone(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
// destroy keyboard if applicable
|
|
||||||
if !capabilities.contains(wl_seat::Capability::Keyboard) {
|
|
||||||
if let Some(kbd) = self.keyboard.take() {
|
|
||||||
if kbd.version() >= 3 {
|
|
||||||
use self::wl_keyboard::RequestsTrait;
|
|
||||||
kbd.release();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// create touch if applicable
|
|
||||||
if capabilities.contains(wl_seat::Capability::Touch) && self.touch.is_none() {
|
|
||||||
self.touch = Some(super::touch::implement_touch(
|
|
||||||
seat.get_touch().unwrap(),
|
|
||||||
self.sink.clone(),
|
|
||||||
self.store.clone(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
// destroy touch if applicable
|
|
||||||
if !capabilities.contains(wl_seat::Capability::Touch) {
|
|
||||||
if let Some(touch) = self.touch.take() {
|
|
||||||
if touch.version() >= 3 {
|
|
||||||
use self::wl_touch::RequestsTrait;
|
|
||||||
touch.release();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for SeatData {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
if let Some(pointer) = self.pointer.take() {
|
|
||||||
if pointer.version() >= 3 {
|
|
||||||
use self::wl_pointer::RequestsTrait;
|
|
||||||
pointer.release();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(kbd) = self.keyboard.take() {
|
|
||||||
if kbd.version() >= 3 {
|
|
||||||
use self::wl_keyboard::RequestsTrait;
|
|
||||||
kbd.release();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(touch) = self.touch.take() {
|
|
||||||
if touch.version() >= 3 {
|
|
||||||
use self::wl_touch::RequestsTrait;
|
|
||||||
touch.release();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Monitor stuff
|
|
||||||
*/
|
|
||||||
|
|
||||||
pub struct MonitorId {
|
|
||||||
pub(crate) proxy: Proxy<wl_output::WlOutput>,
|
|
||||||
pub(crate) mgr: OutputMgr,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Clone for MonitorId {
|
|
||||||
fn clone(&self) -> MonitorId {
|
|
||||||
MonitorId {
|
|
||||||
proxy: self.proxy.clone(),
|
|
||||||
mgr: self.mgr.clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Debug for MonitorId {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct MonitorId {
|
|
||||||
name: Option<String>,
|
|
||||||
native_identifier: u32,
|
|
||||||
dimensions: PhysicalSize,
|
|
||||||
position: PhysicalPosition,
|
|
||||||
hidpi_factor: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
let monitor_id_proxy = MonitorId {
|
|
||||||
name: self.get_name(),
|
|
||||||
native_identifier: self.get_native_identifier(),
|
|
||||||
dimensions: self.get_dimensions(),
|
|
||||||
position: self.get_position(),
|
|
||||||
hidpi_factor: self.get_hidpi_factor(),
|
|
||||||
};
|
|
||||||
|
|
||||||
monitor_id_proxy.fmt(f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorId {
|
|
||||||
pub fn get_name(&self) -> Option<String> {
|
|
||||||
self.mgr.with_info(&self.proxy, |_, info| {
|
|
||||||
format!("{} ({})", info.model, info.make)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_native_identifier(&self) -> u32 {
|
|
||||||
self.mgr.with_info(&self.proxy, |id, _| id).unwrap_or(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_dimensions(&self) -> PhysicalSize {
|
|
||||||
match self.mgr.with_info(&self.proxy, |_, info| {
|
|
||||||
info.modes
|
|
||||||
.iter()
|
|
||||||
.find(|m| m.is_current)
|
|
||||||
.map(|m| m.dimensions)
|
|
||||||
}) {
|
|
||||||
Some(Some((w, h))) => (w as u32, h as u32),
|
|
||||||
_ => (0, 0),
|
|
||||||
}.into()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_position(&self) -> PhysicalPosition {
|
|
||||||
self.mgr
|
|
||||||
.with_info(&self.proxy, |_, info| info.location)
|
|
||||||
.unwrap_or((0, 0))
|
|
||||||
.into()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_hidpi_factor(&self) -> i32 {
|
|
||||||
self.mgr
|
|
||||||
.with_info(&self.proxy, |_, info| info.scale_factor)
|
|
||||||
.unwrap_or(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_primary_monitor(outputs: &OutputMgr) -> MonitorId {
|
|
||||||
outputs.with_all(|list| {
|
|
||||||
if let Some(&(_, ref proxy, _)) = list.first() {
|
|
||||||
MonitorId {
|
|
||||||
proxy: proxy.clone(),
|
|
||||||
mgr: outputs.clone(),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("No monitor is available.")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_available_monitors(outputs: &OutputMgr) -> VecDeque<MonitorId> {
|
|
||||||
outputs.with_all(|list| {
|
|
||||||
list.iter()
|
|
||||||
.map(|&(_, ref proxy, _)| MonitorId {
|
|
||||||
proxy: proxy.clone(),
|
|
||||||
mgr: outputs.clone(),
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,312 +0,0 @@
|
|||||||
use std::sync::{Arc, Mutex};
|
|
||||||
|
|
||||||
use {ElementState, KeyboardInput, ModifiersState, VirtualKeyCode, WindowEvent};
|
|
||||||
|
|
||||||
use super::{make_wid, DeviceId, EventsLoopSink};
|
|
||||||
use sctk::keyboard::{self, map_keyboard_auto, Event as KbEvent};
|
|
||||||
use sctk::reexports::client::{NewProxy, Proxy};
|
|
||||||
use sctk::reexports::client::protocol::wl_keyboard;
|
|
||||||
|
|
||||||
pub fn init_keyboard(
|
|
||||||
keyboard: NewProxy<wl_keyboard::WlKeyboard>,
|
|
||||||
sink: Arc<Mutex<EventsLoopSink>>,
|
|
||||||
) -> Proxy<wl_keyboard::WlKeyboard> {
|
|
||||||
// { variables to be captured by the closure
|
|
||||||
let mut target = None;
|
|
||||||
let my_sink = sink.clone();
|
|
||||||
// }
|
|
||||||
let ret = map_keyboard_auto(keyboard, move |evt: KbEvent, _| match evt {
|
|
||||||
KbEvent::Enter { surface, .. } => {
|
|
||||||
let wid = make_wid(&surface);
|
|
||||||
my_sink
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.send_event(WindowEvent::Focused(true), wid);
|
|
||||||
target = Some(wid);
|
|
||||||
}
|
|
||||||
KbEvent::Leave { surface, .. } => {
|
|
||||||
let wid = make_wid(&surface);
|
|
||||||
my_sink
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.send_event(WindowEvent::Focused(false), wid);
|
|
||||||
target = None;
|
|
||||||
}
|
|
||||||
KbEvent::Key {
|
|
||||||
modifiers,
|
|
||||||
rawkey,
|
|
||||||
keysym,
|
|
||||||
state,
|
|
||||||
utf8,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
if let Some(wid) = target {
|
|
||||||
let state = match state {
|
|
||||||
wl_keyboard::KeyState::Pressed => ElementState::Pressed,
|
|
||||||
wl_keyboard::KeyState::Released => ElementState::Released,
|
|
||||||
};
|
|
||||||
let vkcode = key_to_vkey(rawkey, keysym);
|
|
||||||
let mut guard = my_sink.lock().unwrap();
|
|
||||||
guard.send_event(
|
|
||||||
WindowEvent::KeyboardInput {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
input: KeyboardInput {
|
|
||||||
state: state,
|
|
||||||
scancode: rawkey,
|
|
||||||
virtual_keycode: vkcode,
|
|
||||||
modifiers: modifiers.into(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
wid,
|
|
||||||
);
|
|
||||||
// send char event only on key press, not release
|
|
||||||
if let ElementState::Released = state {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if let Some(txt) = utf8 {
|
|
||||||
for chr in txt.chars() {
|
|
||||||
guard.send_event(WindowEvent::ReceivedCharacter(chr), wid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
KbEvent::RepeatInfo { .. } => { /* TODO: handle repeat info */ }
|
|
||||||
});
|
|
||||||
|
|
||||||
match ret {
|
|
||||||
Ok(keyboard) => keyboard,
|
|
||||||
Err((_, keyboard)) => {
|
|
||||||
// This is a fallback impl if libxkbcommon was not available
|
|
||||||
// This case should probably never happen, as most wayland
|
|
||||||
// compositors _need_ libxkbcommon anyway...
|
|
||||||
//
|
|
||||||
// In this case, we don't have the keymap information (it is
|
|
||||||
// supposed to be serialized by the compositor using libxkbcommon)
|
|
||||||
|
|
||||||
// { variables to be captured by the closure
|
|
||||||
let mut target = None;
|
|
||||||
let my_sink = sink;
|
|
||||||
// }
|
|
||||||
keyboard.implement(move |evt, _| match evt {
|
|
||||||
wl_keyboard::Event::Enter { surface, .. } => {
|
|
||||||
let wid = make_wid(&surface);
|
|
||||||
my_sink
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.send_event(WindowEvent::Focused(true), wid);
|
|
||||||
target = Some(wid);
|
|
||||||
}
|
|
||||||
wl_keyboard::Event::Leave { surface, .. } => {
|
|
||||||
let wid = make_wid(&surface);
|
|
||||||
my_sink
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.send_event(WindowEvent::Focused(false), wid);
|
|
||||||
target = None;
|
|
||||||
}
|
|
||||||
wl_keyboard::Event::Key { key, state, .. } => {
|
|
||||||
if let Some(wid) = target {
|
|
||||||
let state = match state {
|
|
||||||
wl_keyboard::KeyState::Pressed => ElementState::Pressed,
|
|
||||||
wl_keyboard::KeyState::Released => ElementState::Released,
|
|
||||||
};
|
|
||||||
my_sink.lock().unwrap().send_event(
|
|
||||||
WindowEvent::KeyboardInput {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
input: KeyboardInput {
|
|
||||||
state: state,
|
|
||||||
scancode: key,
|
|
||||||
virtual_keycode: None,
|
|
||||||
modifiers: ModifiersState::default(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
wid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn key_to_vkey(rawkey: u32, keysym: u32) -> Option<VirtualKeyCode> {
|
|
||||||
match rawkey {
|
|
||||||
1 => Some(VirtualKeyCode::Escape),
|
|
||||||
2 => Some(VirtualKeyCode::Key1),
|
|
||||||
3 => Some(VirtualKeyCode::Key2),
|
|
||||||
4 => Some(VirtualKeyCode::Key3),
|
|
||||||
5 => Some(VirtualKeyCode::Key4),
|
|
||||||
6 => Some(VirtualKeyCode::Key5),
|
|
||||||
7 => Some(VirtualKeyCode::Key6),
|
|
||||||
8 => Some(VirtualKeyCode::Key7),
|
|
||||||
9 => Some(VirtualKeyCode::Key8),
|
|
||||||
10 => Some(VirtualKeyCode::Key9),
|
|
||||||
11 => Some(VirtualKeyCode::Key0),
|
|
||||||
_ => keysym_to_vkey(keysym),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn keysym_to_vkey(keysym: u32) -> Option<VirtualKeyCode> {
|
|
||||||
use sctk::keyboard::keysyms;
|
|
||||||
match keysym {
|
|
||||||
// letters
|
|
||||||
keysyms::XKB_KEY_A | keysyms::XKB_KEY_a => Some(VirtualKeyCode::A),
|
|
||||||
keysyms::XKB_KEY_B | keysyms::XKB_KEY_b => Some(VirtualKeyCode::B),
|
|
||||||
keysyms::XKB_KEY_C | keysyms::XKB_KEY_c => Some(VirtualKeyCode::C),
|
|
||||||
keysyms::XKB_KEY_D | keysyms::XKB_KEY_d => Some(VirtualKeyCode::D),
|
|
||||||
keysyms::XKB_KEY_E | keysyms::XKB_KEY_e => Some(VirtualKeyCode::E),
|
|
||||||
keysyms::XKB_KEY_F | keysyms::XKB_KEY_f => Some(VirtualKeyCode::F),
|
|
||||||
keysyms::XKB_KEY_G | keysyms::XKB_KEY_g => Some(VirtualKeyCode::G),
|
|
||||||
keysyms::XKB_KEY_H | keysyms::XKB_KEY_h => Some(VirtualKeyCode::H),
|
|
||||||
keysyms::XKB_KEY_I | keysyms::XKB_KEY_i => Some(VirtualKeyCode::I),
|
|
||||||
keysyms::XKB_KEY_J | keysyms::XKB_KEY_j => Some(VirtualKeyCode::J),
|
|
||||||
keysyms::XKB_KEY_K | keysyms::XKB_KEY_k => Some(VirtualKeyCode::K),
|
|
||||||
keysyms::XKB_KEY_L | keysyms::XKB_KEY_l => Some(VirtualKeyCode::L),
|
|
||||||
keysyms::XKB_KEY_M | keysyms::XKB_KEY_m => Some(VirtualKeyCode::M),
|
|
||||||
keysyms::XKB_KEY_N | keysyms::XKB_KEY_n => Some(VirtualKeyCode::N),
|
|
||||||
keysyms::XKB_KEY_O | keysyms::XKB_KEY_o => Some(VirtualKeyCode::O),
|
|
||||||
keysyms::XKB_KEY_P | keysyms::XKB_KEY_p => Some(VirtualKeyCode::P),
|
|
||||||
keysyms::XKB_KEY_Q | keysyms::XKB_KEY_q => Some(VirtualKeyCode::Q),
|
|
||||||
keysyms::XKB_KEY_R | keysyms::XKB_KEY_r => Some(VirtualKeyCode::R),
|
|
||||||
keysyms::XKB_KEY_S | keysyms::XKB_KEY_s => Some(VirtualKeyCode::S),
|
|
||||||
keysyms::XKB_KEY_T | keysyms::XKB_KEY_t => Some(VirtualKeyCode::T),
|
|
||||||
keysyms::XKB_KEY_U | keysyms::XKB_KEY_u => Some(VirtualKeyCode::U),
|
|
||||||
keysyms::XKB_KEY_V | keysyms::XKB_KEY_v => Some(VirtualKeyCode::V),
|
|
||||||
keysyms::XKB_KEY_W | keysyms::XKB_KEY_w => Some(VirtualKeyCode::W),
|
|
||||||
keysyms::XKB_KEY_X | keysyms::XKB_KEY_x => Some(VirtualKeyCode::X),
|
|
||||||
keysyms::XKB_KEY_Y | keysyms::XKB_KEY_y => Some(VirtualKeyCode::Y),
|
|
||||||
keysyms::XKB_KEY_Z | keysyms::XKB_KEY_z => Some(VirtualKeyCode::Z),
|
|
||||||
// F--
|
|
||||||
keysyms::XKB_KEY_F1 => Some(VirtualKeyCode::F1),
|
|
||||||
keysyms::XKB_KEY_F2 => Some(VirtualKeyCode::F2),
|
|
||||||
keysyms::XKB_KEY_F3 => Some(VirtualKeyCode::F3),
|
|
||||||
keysyms::XKB_KEY_F4 => Some(VirtualKeyCode::F4),
|
|
||||||
keysyms::XKB_KEY_F5 => Some(VirtualKeyCode::F5),
|
|
||||||
keysyms::XKB_KEY_F6 => Some(VirtualKeyCode::F6),
|
|
||||||
keysyms::XKB_KEY_F7 => Some(VirtualKeyCode::F7),
|
|
||||||
keysyms::XKB_KEY_F8 => Some(VirtualKeyCode::F8),
|
|
||||||
keysyms::XKB_KEY_F9 => Some(VirtualKeyCode::F9),
|
|
||||||
keysyms::XKB_KEY_F10 => Some(VirtualKeyCode::F10),
|
|
||||||
keysyms::XKB_KEY_F11 => Some(VirtualKeyCode::F11),
|
|
||||||
keysyms::XKB_KEY_F12 => Some(VirtualKeyCode::F12),
|
|
||||||
keysyms::XKB_KEY_F13 => Some(VirtualKeyCode::F13),
|
|
||||||
keysyms::XKB_KEY_F14 => Some(VirtualKeyCode::F14),
|
|
||||||
keysyms::XKB_KEY_F15 => Some(VirtualKeyCode::F15),
|
|
||||||
// flow control
|
|
||||||
keysyms::XKB_KEY_Print => Some(VirtualKeyCode::Snapshot),
|
|
||||||
keysyms::XKB_KEY_Scroll_Lock => Some(VirtualKeyCode::Scroll),
|
|
||||||
keysyms::XKB_KEY_Pause => Some(VirtualKeyCode::Pause),
|
|
||||||
keysyms::XKB_KEY_Insert => Some(VirtualKeyCode::Insert),
|
|
||||||
keysyms::XKB_KEY_Home => Some(VirtualKeyCode::Home),
|
|
||||||
keysyms::XKB_KEY_Delete => Some(VirtualKeyCode::Delete),
|
|
||||||
keysyms::XKB_KEY_End => Some(VirtualKeyCode::End),
|
|
||||||
keysyms::XKB_KEY_Page_Down => Some(VirtualKeyCode::PageDown),
|
|
||||||
keysyms::XKB_KEY_Page_Up => Some(VirtualKeyCode::PageUp),
|
|
||||||
// arrows
|
|
||||||
keysyms::XKB_KEY_Left => Some(VirtualKeyCode::Left),
|
|
||||||
keysyms::XKB_KEY_Up => Some(VirtualKeyCode::Up),
|
|
||||||
keysyms::XKB_KEY_Right => Some(VirtualKeyCode::Right),
|
|
||||||
keysyms::XKB_KEY_Down => Some(VirtualKeyCode::Down),
|
|
||||||
//
|
|
||||||
keysyms::XKB_KEY_BackSpace => Some(VirtualKeyCode::Back),
|
|
||||||
keysyms::XKB_KEY_Return => Some(VirtualKeyCode::Return),
|
|
||||||
keysyms::XKB_KEY_space => Some(VirtualKeyCode::Space),
|
|
||||||
// keypad
|
|
||||||
keysyms::XKB_KEY_Num_Lock => Some(VirtualKeyCode::Numlock),
|
|
||||||
keysyms::XKB_KEY_KP_0 => Some(VirtualKeyCode::Numpad0),
|
|
||||||
keysyms::XKB_KEY_KP_1 => Some(VirtualKeyCode::Numpad1),
|
|
||||||
keysyms::XKB_KEY_KP_2 => Some(VirtualKeyCode::Numpad2),
|
|
||||||
keysyms::XKB_KEY_KP_3 => Some(VirtualKeyCode::Numpad3),
|
|
||||||
keysyms::XKB_KEY_KP_4 => Some(VirtualKeyCode::Numpad4),
|
|
||||||
keysyms::XKB_KEY_KP_5 => Some(VirtualKeyCode::Numpad5),
|
|
||||||
keysyms::XKB_KEY_KP_6 => Some(VirtualKeyCode::Numpad6),
|
|
||||||
keysyms::XKB_KEY_KP_7 => Some(VirtualKeyCode::Numpad7),
|
|
||||||
keysyms::XKB_KEY_KP_8 => Some(VirtualKeyCode::Numpad8),
|
|
||||||
keysyms::XKB_KEY_KP_9 => Some(VirtualKeyCode::Numpad9),
|
|
||||||
// misc
|
|
||||||
// => Some(VirtualKeyCode::AbntC1),
|
|
||||||
// => Some(VirtualKeyCode::AbntC2),
|
|
||||||
keysyms::XKB_KEY_plus => Some(VirtualKeyCode::Add),
|
|
||||||
keysyms::XKB_KEY_apostrophe => Some(VirtualKeyCode::Apostrophe),
|
|
||||||
// => Some(VirtualKeyCode::Apps),
|
|
||||||
// => Some(VirtualKeyCode::At),
|
|
||||||
// => Some(VirtualKeyCode::Ax),
|
|
||||||
keysyms::XKB_KEY_backslash => Some(VirtualKeyCode::Backslash),
|
|
||||||
// => Some(VirtualKeyCode::Calculator),
|
|
||||||
// => Some(VirtualKeyCode::Capital),
|
|
||||||
keysyms::XKB_KEY_colon => Some(VirtualKeyCode::Colon),
|
|
||||||
keysyms::XKB_KEY_comma => Some(VirtualKeyCode::Comma),
|
|
||||||
// => Some(VirtualKeyCode::Convert),
|
|
||||||
// => Some(VirtualKeyCode::Decimal),
|
|
||||||
// => Some(VirtualKeyCode::Divide),
|
|
||||||
keysyms::XKB_KEY_equal => Some(VirtualKeyCode::Equals),
|
|
||||||
// => Some(VirtualKeyCode::Grave),
|
|
||||||
// => Some(VirtualKeyCode::Kana),
|
|
||||||
// => Some(VirtualKeyCode::Kanji),
|
|
||||||
keysyms::XKB_KEY_Alt_L => Some(VirtualKeyCode::LAlt),
|
|
||||||
// => Some(VirtualKeyCode::LBracket),
|
|
||||||
keysyms::XKB_KEY_Control_L => Some(VirtualKeyCode::LControl),
|
|
||||||
keysyms::XKB_KEY_Shift_L => Some(VirtualKeyCode::LShift),
|
|
||||||
// => Some(VirtualKeyCode::LWin),
|
|
||||||
// => Some(VirtualKeyCode::Mail),
|
|
||||||
// => Some(VirtualKeyCode::MediaSelect),
|
|
||||||
// => Some(VirtualKeyCode::MediaStop),
|
|
||||||
keysyms::XKB_KEY_minus => Some(VirtualKeyCode::Minus),
|
|
||||||
keysyms::XKB_KEY_asterisk => Some(VirtualKeyCode::Multiply),
|
|
||||||
// => Some(VirtualKeyCode::Mute),
|
|
||||||
// => Some(VirtualKeyCode::MyComputer),
|
|
||||||
// => Some(VirtualKeyCode::NextTrack),
|
|
||||||
// => Some(VirtualKeyCode::NoConvert),
|
|
||||||
keysyms::XKB_KEY_KP_Separator => Some(VirtualKeyCode::NumpadComma),
|
|
||||||
keysyms::XKB_KEY_KP_Enter => Some(VirtualKeyCode::NumpadEnter),
|
|
||||||
keysyms::XKB_KEY_KP_Equal => Some(VirtualKeyCode::NumpadEquals),
|
|
||||||
// => Some(VirtualKeyCode::OEM102),
|
|
||||||
// => Some(VirtualKeyCode::Period),
|
|
||||||
// => Some(VirtualKeyCode::Playpause),
|
|
||||||
// => Some(VirtualKeyCode::Power),
|
|
||||||
// => Some(VirtualKeyCode::Prevtrack),
|
|
||||||
keysyms::XKB_KEY_Alt_R => Some(VirtualKeyCode::RAlt),
|
|
||||||
// => Some(VirtualKeyCode::RBracket),
|
|
||||||
keysyms::XKB_KEY_Control_R => Some(VirtualKeyCode::RControl),
|
|
||||||
keysyms::XKB_KEY_Shift_R => Some(VirtualKeyCode::RShift),
|
|
||||||
// => Some(VirtualKeyCode::RWin),
|
|
||||||
keysyms::XKB_KEY_semicolon => Some(VirtualKeyCode::Semicolon),
|
|
||||||
keysyms::XKB_KEY_slash => Some(VirtualKeyCode::Slash),
|
|
||||||
// => Some(VirtualKeyCode::Sleep),
|
|
||||||
// => Some(VirtualKeyCode::Stop),
|
|
||||||
// => Some(VirtualKeyCode::Subtract),
|
|
||||||
// => Some(VirtualKeyCode::Sysrq),
|
|
||||||
keysyms::XKB_KEY_Tab => Some(VirtualKeyCode::Tab),
|
|
||||||
keysyms::XKB_KEY_ISO_Left_Tab => Some(VirtualKeyCode::Tab),
|
|
||||||
// => Some(VirtualKeyCode::Underline),
|
|
||||||
// => Some(VirtualKeyCode::Unlabeled),
|
|
||||||
keysyms::XKB_KEY_XF86AudioLowerVolume => Some(VirtualKeyCode::VolumeDown),
|
|
||||||
keysyms::XKB_KEY_XF86AudioRaiseVolume => Some(VirtualKeyCode::VolumeUp),
|
|
||||||
// => Some(VirtualKeyCode::Wake),
|
|
||||||
// => Some(VirtualKeyCode::Webback),
|
|
||||||
// => Some(VirtualKeyCode::WebFavorites),
|
|
||||||
// => Some(VirtualKeyCode::WebForward),
|
|
||||||
// => Some(VirtualKeyCode::WebHome),
|
|
||||||
// => Some(VirtualKeyCode::WebRefresh),
|
|
||||||
// => Some(VirtualKeyCode::WebSearch),
|
|
||||||
// => Some(VirtualKeyCode::WebStop),
|
|
||||||
// => Some(VirtualKeyCode::Yen),
|
|
||||||
keysyms::XKB_KEY_XF86Copy => Some(VirtualKeyCode::Copy),
|
|
||||||
keysyms::XKB_KEY_XF86Paste => Some(VirtualKeyCode::Paste),
|
|
||||||
keysyms::XKB_KEY_XF86Cut => Some(VirtualKeyCode::Cut),
|
|
||||||
// fallback
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<keyboard::ModifiersState> for ModifiersState {
|
|
||||||
fn from(mods: keyboard::ModifiersState) -> ModifiersState {
|
|
||||||
ModifiersState {
|
|
||||||
shift: mods.shift,
|
|
||||||
ctrl: mods.ctrl,
|
|
||||||
alt: mods.alt,
|
|
||||||
logo: mods.logo,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd",
|
|
||||||
target_os = "netbsd", target_os = "openbsd"))]
|
|
||||||
|
|
||||||
pub use self::window::Window;
|
|
||||||
pub use self::event_loop::{EventsLoop, EventsLoopProxy, EventsLoopSink, MonitorId};
|
|
||||||
|
|
||||||
use sctk::reexports::client::protocol::wl_surface;
|
|
||||||
use sctk::reexports::client::Proxy;
|
|
||||||
|
|
||||||
mod event_loop;
|
|
||||||
mod pointer;
|
|
||||||
mod touch;
|
|
||||||
mod keyboard;
|
|
||||||
mod window;
|
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub struct DeviceId;
|
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub struct WindowId(usize);
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn make_wid(s: &Proxy<wl_surface::WlSurface>) -> WindowId {
|
|
||||||
WindowId(s.c_ptr() as usize)
|
|
||||||
}
|
|
||||||
@@ -1,190 +0,0 @@
|
|||||||
use std::sync::{Arc, Mutex};
|
|
||||||
|
|
||||||
use {ElementState, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent};
|
|
||||||
use events::ModifiersState;
|
|
||||||
|
|
||||||
use super::DeviceId;
|
|
||||||
use super::event_loop::EventsLoopSink;
|
|
||||||
use super::window::WindowStore;
|
|
||||||
|
|
||||||
use sctk::reexports::client::{NewProxy, Proxy};
|
|
||||||
use sctk::reexports::client::protocol::wl_pointer::{self, Event as PtrEvent, WlPointer};
|
|
||||||
|
|
||||||
pub fn implement_pointer(
|
|
||||||
pointer: NewProxy<WlPointer>,
|
|
||||||
sink: Arc<Mutex<EventsLoopSink>>,
|
|
||||||
store: Arc<Mutex<WindowStore>>,
|
|
||||||
) -> Proxy<WlPointer> {
|
|
||||||
let mut mouse_focus = None;
|
|
||||||
let mut axis_buffer = None;
|
|
||||||
let mut axis_discrete_buffer = None;
|
|
||||||
let mut axis_state = TouchPhase::Ended;
|
|
||||||
|
|
||||||
pointer.implement(move |evt, pointer: Proxy<_>| {
|
|
||||||
let mut sink = sink.lock().unwrap();
|
|
||||||
let store = store.lock().unwrap();
|
|
||||||
match evt {
|
|
||||||
PtrEvent::Enter {
|
|
||||||
surface,
|
|
||||||
surface_x,
|
|
||||||
surface_y,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
let wid = store.find_wid(&surface);
|
|
||||||
if let Some(wid) = wid {
|
|
||||||
mouse_focus = Some(wid);
|
|
||||||
sink.send_event(
|
|
||||||
WindowEvent::CursorEntered {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
},
|
|
||||||
wid,
|
|
||||||
);
|
|
||||||
sink.send_event(
|
|
||||||
WindowEvent::CursorMoved {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
position: (surface_x, surface_y).into(),
|
|
||||||
// TODO: replace dummy value with actual modifier state
|
|
||||||
modifiers: ModifiersState::default(),
|
|
||||||
},
|
|
||||||
wid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PtrEvent::Leave { surface, .. } => {
|
|
||||||
mouse_focus = None;
|
|
||||||
let wid = store.find_wid(&surface);
|
|
||||||
if let Some(wid) = wid {
|
|
||||||
sink.send_event(
|
|
||||||
WindowEvent::CursorLeft {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
},
|
|
||||||
wid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PtrEvent::Motion {
|
|
||||||
surface_x,
|
|
||||||
surface_y,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
if let Some(wid) = mouse_focus {
|
|
||||||
sink.send_event(
|
|
||||||
WindowEvent::CursorMoved {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
position: (surface_x, surface_y).into(),
|
|
||||||
// TODO: replace dummy value with actual modifier state
|
|
||||||
modifiers: ModifiersState::default(),
|
|
||||||
},
|
|
||||||
wid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PtrEvent::Button { button, state, .. } => {
|
|
||||||
if let Some(wid) = mouse_focus {
|
|
||||||
let state = match state {
|
|
||||||
wl_pointer::ButtonState::Pressed => ElementState::Pressed,
|
|
||||||
wl_pointer::ButtonState::Released => ElementState::Released,
|
|
||||||
};
|
|
||||||
let button = match button {
|
|
||||||
0x110 => MouseButton::Left,
|
|
||||||
0x111 => MouseButton::Right,
|
|
||||||
0x112 => MouseButton::Middle,
|
|
||||||
// TODO figure out the translation ?
|
|
||||||
_ => return,
|
|
||||||
};
|
|
||||||
sink.send_event(
|
|
||||||
WindowEvent::MouseInput {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
state: state,
|
|
||||||
button: button,
|
|
||||||
// TODO: replace dummy value with actual modifier state
|
|
||||||
modifiers: ModifiersState::default(),
|
|
||||||
},
|
|
||||||
wid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PtrEvent::Axis { axis, value, .. } => {
|
|
||||||
if let Some(wid) = mouse_focus {
|
|
||||||
if pointer.version() < 5 {
|
|
||||||
let (mut x, mut y) = (0.0, 0.0);
|
|
||||||
// old seat compatibility
|
|
||||||
match axis {
|
|
||||||
// wayland vertical sign convention is the inverse of winit
|
|
||||||
wl_pointer::Axis::VerticalScroll => y -= value as f32,
|
|
||||||
wl_pointer::Axis::HorizontalScroll => x += value as f32,
|
|
||||||
}
|
|
||||||
sink.send_event(
|
|
||||||
WindowEvent::MouseWheel {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
delta: MouseScrollDelta::PixelDelta((x as f64, y as f64).into()),
|
|
||||||
phase: TouchPhase::Moved,
|
|
||||||
// TODO: replace dummy value with actual modifier state
|
|
||||||
modifiers: ModifiersState::default(),
|
|
||||||
},
|
|
||||||
wid,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
let (mut x, mut y) = axis_buffer.unwrap_or((0.0, 0.0));
|
|
||||||
match axis {
|
|
||||||
// wayland vertical sign convention is the inverse of winit
|
|
||||||
wl_pointer::Axis::VerticalScroll => y -= value as f32,
|
|
||||||
wl_pointer::Axis::HorizontalScroll => x += value as f32,
|
|
||||||
}
|
|
||||||
axis_buffer = Some((x, y));
|
|
||||||
axis_state = match axis_state {
|
|
||||||
TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved,
|
|
||||||
_ => TouchPhase::Started,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PtrEvent::Frame => {
|
|
||||||
let axis_buffer = axis_buffer.take();
|
|
||||||
let axis_discrete_buffer = axis_discrete_buffer.take();
|
|
||||||
if let Some(wid) = mouse_focus {
|
|
||||||
if let Some((x, y)) = axis_discrete_buffer {
|
|
||||||
sink.send_event(
|
|
||||||
WindowEvent::MouseWheel {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
delta: MouseScrollDelta::LineDelta(x as f32, y as f32),
|
|
||||||
phase: axis_state,
|
|
||||||
// TODO: replace dummy value with actual modifier state
|
|
||||||
modifiers: ModifiersState::default(),
|
|
||||||
},
|
|
||||||
wid,
|
|
||||||
);
|
|
||||||
} else if let Some((x, y)) = axis_buffer {
|
|
||||||
sink.send_event(
|
|
||||||
WindowEvent::MouseWheel {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
delta: MouseScrollDelta::PixelDelta((x as f64, y as f64).into()),
|
|
||||||
phase: axis_state,
|
|
||||||
// TODO: replace dummy value with actual modifier state
|
|
||||||
modifiers: ModifiersState::default(),
|
|
||||||
},
|
|
||||||
wid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PtrEvent::AxisSource { .. } => (),
|
|
||||||
PtrEvent::AxisStop { .. } => {
|
|
||||||
axis_state = TouchPhase::Ended;
|
|
||||||
}
|
|
||||||
PtrEvent::AxisDiscrete { axis, discrete } => {
|
|
||||||
let (mut x, mut y) = axis_discrete_buffer.unwrap_or((0, 0));
|
|
||||||
match axis {
|
|
||||||
// wayland vertical sign convention is the inverse of winit
|
|
||||||
wl_pointer::Axis::VerticalScroll => y -= discrete,
|
|
||||||
wl_pointer::Axis::HorizontalScroll => x += discrete,
|
|
||||||
}
|
|
||||||
axis_discrete_buffer = Some((x, y));
|
|
||||||
axis_state = match axis_state {
|
|
||||||
TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved,
|
|
||||||
_ => TouchPhase::Started,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
use std::sync::{Arc, Mutex};
|
|
||||||
|
|
||||||
use {TouchPhase, WindowEvent};
|
|
||||||
|
|
||||||
use super::{DeviceId, WindowId};
|
|
||||||
use super::event_loop::EventsLoopSink;
|
|
||||||
use super::window::WindowStore;
|
|
||||||
|
|
||||||
use sctk::reexports::client::{NewProxy, Proxy};
|
|
||||||
use sctk::reexports::client::protocol::wl_touch::{Event as TouchEvent, WlTouch};
|
|
||||||
|
|
||||||
struct TouchPoint {
|
|
||||||
wid: WindowId,
|
|
||||||
location: (f64, f64),
|
|
||||||
id: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn implement_touch(
|
|
||||||
touch: NewProxy<WlTouch>,
|
|
||||||
sink: Arc<Mutex<EventsLoopSink>>,
|
|
||||||
store: Arc<Mutex<WindowStore>>,
|
|
||||||
) -> Proxy<WlTouch> {
|
|
||||||
let mut pending_ids = Vec::new();
|
|
||||||
touch.implement(move |evt, _| {
|
|
||||||
let mut sink = sink.lock().unwrap();
|
|
||||||
let store = store.lock().unwrap();
|
|
||||||
match evt {
|
|
||||||
TouchEvent::Down {
|
|
||||||
surface, id, x, y, ..
|
|
||||||
} => {
|
|
||||||
let wid = store.find_wid(&surface);
|
|
||||||
if let Some(wid) = wid {
|
|
||||||
sink.send_event(
|
|
||||||
WindowEvent::Touch(::Touch {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
phase: TouchPhase::Started,
|
|
||||||
location: (x, y).into(),
|
|
||||||
id: id as u64,
|
|
||||||
}),
|
|
||||||
wid,
|
|
||||||
);
|
|
||||||
pending_ids.push(TouchPoint {
|
|
||||||
wid: wid,
|
|
||||||
location: (x, y),
|
|
||||||
id: id,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
TouchEvent::Up { id, .. } => {
|
|
||||||
let idx = pending_ids.iter().position(|p| p.id == id);
|
|
||||||
if let Some(idx) = idx {
|
|
||||||
let pt = pending_ids.remove(idx);
|
|
||||||
sink.send_event(
|
|
||||||
WindowEvent::Touch(::Touch {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
phase: TouchPhase::Ended,
|
|
||||||
location: pt.location.into(),
|
|
||||||
id: id as u64,
|
|
||||||
}),
|
|
||||||
pt.wid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
TouchEvent::Motion { id, x, y, .. } => {
|
|
||||||
let pt = pending_ids.iter_mut().find(|p| p.id == id);
|
|
||||||
if let Some(pt) = pt {
|
|
||||||
pt.location = (x, y);
|
|
||||||
sink.send_event(
|
|
||||||
WindowEvent::Touch(::Touch {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
phase: TouchPhase::Moved,
|
|
||||||
location: (x, y).into(),
|
|
||||||
id: id as u64,
|
|
||||||
}),
|
|
||||||
pt.wid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
TouchEvent::Frame => (),
|
|
||||||
TouchEvent::Cancel => for pt in pending_ids.drain(..) {
|
|
||||||
sink.send_event(
|
|
||||||
WindowEvent::Touch(::Touch {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
phase: TouchPhase::Cancelled,
|
|
||||||
location: pt.location.into(),
|
|
||||||
id: pt.id as u64,
|
|
||||||
}),
|
|
||||||
pt.wid,
|
|
||||||
);
|
|
||||||
},
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,458 +0,0 @@
|
|||||||
use std::collections::VecDeque;
|
|
||||||
use std::sync::{Arc, Mutex, Weak};
|
|
||||||
|
|
||||||
use {CreationError, MouseCursor, WindowAttributes};
|
|
||||||
use dpi::{LogicalPosition, LogicalSize};
|
|
||||||
use platform::MonitorId as PlatformMonitorId;
|
|
||||||
use window::MonitorId as RootMonitorId;
|
|
||||||
|
|
||||||
use sctk::window::{BasicFrame, Event as WEvent, Window as SWindow};
|
|
||||||
use sctk::reexports::client::{Display, Proxy};
|
|
||||||
use sctk::reexports::client::protocol::{wl_seat, wl_surface, wl_output};
|
|
||||||
use sctk::reexports::client::protocol::wl_compositor::RequestsTrait as CompositorRequests;
|
|
||||||
use sctk::reexports::client::protocol::wl_surface::RequestsTrait as SurfaceRequests;
|
|
||||||
use sctk::output::OutputMgr;
|
|
||||||
|
|
||||||
use super::{make_wid, EventsLoop, MonitorId, WindowId};
|
|
||||||
use platform::platform::wayland::event_loop::{get_available_monitors, get_primary_monitor};
|
|
||||||
|
|
||||||
pub struct Window {
|
|
||||||
surface: Proxy<wl_surface::WlSurface>,
|
|
||||||
frame: Arc<Mutex<SWindow<BasicFrame>>>,
|
|
||||||
monitors: Arc<Mutex<MonitorList>>, // Monitors this window is currently on
|
|
||||||
outputs: OutputMgr, // Access to info for all monitors
|
|
||||||
size: Arc<Mutex<(u32, u32)>>,
|
|
||||||
kill_switch: (Arc<Mutex<bool>>, Arc<Mutex<bool>>),
|
|
||||||
display: Arc<Display>,
|
|
||||||
need_frame_refresh: Arc<Mutex<bool>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Window {
|
|
||||||
pub fn new(evlp: &EventsLoop, attributes: WindowAttributes) -> Result<Window, CreationError> {
|
|
||||||
let (width, height) = attributes.dimensions.map(Into::into).unwrap_or((800, 600));
|
|
||||||
// Create the window
|
|
||||||
let size = Arc::new(Mutex::new((width, height)));
|
|
||||||
|
|
||||||
// monitor tracking
|
|
||||||
let monitor_list = Arc::new(Mutex::new(MonitorList::new()));
|
|
||||||
|
|
||||||
let surface = evlp.env.compositor.create_surface().unwrap().implement({
|
|
||||||
let list = monitor_list.clone();
|
|
||||||
let omgr = evlp.env.outputs.clone();
|
|
||||||
let window_store = evlp.store.clone();
|
|
||||||
move |event, surface: Proxy<wl_surface::WlSurface>| match event {
|
|
||||||
wl_surface::Event::Enter { output } => {
|
|
||||||
let dpi_change = list.lock().unwrap().add_output(MonitorId {
|
|
||||||
proxy: output,
|
|
||||||
mgr: omgr.clone(),
|
|
||||||
});
|
|
||||||
if let Some(dpi) = dpi_change {
|
|
||||||
if surface.version() >= 3 {
|
|
||||||
// without version 3 we can't be dpi aware
|
|
||||||
window_store.lock().unwrap().dpi_change(&surface, dpi);
|
|
||||||
surface.set_buffer_scale(dpi);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
wl_surface::Event::Leave { output } => {
|
|
||||||
let dpi_change = list.lock().unwrap().del_output(&output);
|
|
||||||
if let Some(dpi) = dpi_change {
|
|
||||||
if surface.version() >= 3 {
|
|
||||||
// without version 3 we can't be dpi aware
|
|
||||||
window_store.lock().unwrap().dpi_change(&surface, dpi);
|
|
||||||
surface.set_buffer_scale(dpi);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let window_store = evlp.store.clone();
|
|
||||||
let my_surface = surface.clone();
|
|
||||||
let mut frame = SWindow::<BasicFrame>::init(
|
|
||||||
surface.clone(),
|
|
||||||
(width, height),
|
|
||||||
&evlp.env.compositor,
|
|
||||||
&evlp.env.subcompositor,
|
|
||||||
&evlp.env.shm,
|
|
||||||
&evlp.env.shell,
|
|
||||||
move |event, ()| match event {
|
|
||||||
WEvent::Configure { new_size, .. } => {
|
|
||||||
let mut store = window_store.lock().unwrap();
|
|
||||||
for window in &mut store.windows {
|
|
||||||
if window.surface.equals(&my_surface) {
|
|
||||||
window.newsize = new_size;
|
|
||||||
window.need_refresh = true;
|
|
||||||
*(window.need_frame_refresh.lock().unwrap()) = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
WEvent::Refresh => {
|
|
||||||
let store = window_store.lock().unwrap();
|
|
||||||
for window in &store.windows {
|
|
||||||
if window.surface.equals(&my_surface) {
|
|
||||||
*(window.need_frame_refresh.lock().unwrap()) = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
WEvent::Close => {
|
|
||||||
let mut store = window_store.lock().unwrap();
|
|
||||||
for window in &mut store.windows {
|
|
||||||
if window.surface.equals(&my_surface) {
|
|
||||||
window.closed = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
).unwrap();
|
|
||||||
|
|
||||||
for &(_, ref seat) in evlp.seats.lock().unwrap().iter() {
|
|
||||||
frame.new_seat(seat);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for fullscreen requirements
|
|
||||||
if let Some(RootMonitorId {
|
|
||||||
inner: PlatformMonitorId::Wayland(ref monitor_id),
|
|
||||||
}) = attributes.fullscreen
|
|
||||||
{
|
|
||||||
frame.set_fullscreen(Some(&monitor_id.proxy));
|
|
||||||
} else if attributes.maximized {
|
|
||||||
frame.set_maximized();
|
|
||||||
}
|
|
||||||
|
|
||||||
frame.set_resizable(attributes.resizable);
|
|
||||||
|
|
||||||
// set decorations
|
|
||||||
frame.set_decorate(attributes.decorations);
|
|
||||||
|
|
||||||
// min-max dimensions
|
|
||||||
frame.set_min_size(attributes.min_dimensions.map(Into::into));
|
|
||||||
frame.set_max_size(attributes.max_dimensions.map(Into::into));
|
|
||||||
|
|
||||||
let kill_switch = Arc::new(Mutex::new(false));
|
|
||||||
let need_frame_refresh = Arc::new(Mutex::new(true));
|
|
||||||
let frame = Arc::new(Mutex::new(frame));
|
|
||||||
|
|
||||||
evlp.store.lock().unwrap().windows.push(InternalWindow {
|
|
||||||
closed: false,
|
|
||||||
newsize: None,
|
|
||||||
size: size.clone(),
|
|
||||||
need_refresh: false,
|
|
||||||
need_frame_refresh: need_frame_refresh.clone(),
|
|
||||||
surface: surface.clone(),
|
|
||||||
kill_switch: kill_switch.clone(),
|
|
||||||
frame: Arc::downgrade(&frame),
|
|
||||||
current_dpi: 1,
|
|
||||||
new_dpi: None,
|
|
||||||
});
|
|
||||||
evlp.evq.borrow_mut().sync_roundtrip().unwrap();
|
|
||||||
|
|
||||||
Ok(Window {
|
|
||||||
display: evlp.display.clone(),
|
|
||||||
surface: surface,
|
|
||||||
frame: frame,
|
|
||||||
monitors: monitor_list,
|
|
||||||
outputs: evlp.env.outputs.clone(),
|
|
||||||
size: size,
|
|
||||||
kill_switch: (kill_switch, evlp.cleanup_needed.clone()),
|
|
||||||
need_frame_refresh: need_frame_refresh,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn id(&self) -> WindowId {
|
|
||||||
make_wid(&self.surface)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_title(&self, title: &str) {
|
|
||||||
self.frame.lock().unwrap().set_title(title.into());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn show(&self) {
|
|
||||||
// TODO
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn hide(&self) {
|
|
||||||
// TODO
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_position(&self) -> Option<LogicalPosition> {
|
|
||||||
// Not possible with wayland
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_inner_position(&self) -> Option<LogicalPosition> {
|
|
||||||
// Not possible with wayland
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_position(&self, _pos: LogicalPosition) {
|
|
||||||
// Not possible with wayland
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_inner_size(&self) -> Option<LogicalSize> {
|
|
||||||
Some(self.size.lock().unwrap().clone().into())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_outer_size(&self) -> Option<LogicalSize> {
|
|
||||||
let (w, h) = self.size.lock().unwrap().clone();
|
|
||||||
// let (w, h) = super::wayland_window::add_borders(w as i32, h as i32);
|
|
||||||
Some((w, h).into())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
// NOTE: This will only resize the borders, the contents must be updated by the user
|
|
||||||
pub fn set_inner_size(&self, size: LogicalSize) {
|
|
||||||
let (w, h) = size.into();
|
|
||||||
self.frame.lock().unwrap().resize(w, h);
|
|
||||||
*(self.size.lock().unwrap()) = (w, h);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_min_dimensions(&self, dimensions: Option<LogicalSize>) {
|
|
||||||
self.frame.lock().unwrap().set_min_size(dimensions.map(Into::into));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_max_dimensions(&self, dimensions: Option<LogicalSize>) {
|
|
||||||
self.frame.lock().unwrap().set_max_size(dimensions.map(Into::into));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_resizable(&self, resizable: bool) {
|
|
||||||
self.frame.lock().unwrap().set_resizable(resizable);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn hidpi_factor(&self) -> i32 {
|
|
||||||
self.monitors.lock().unwrap().compute_hidpi_factor()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_decorations(&self, decorate: bool) {
|
|
||||||
self.frame.lock().unwrap().set_decorate(decorate);
|
|
||||||
*(self.need_frame_refresh.lock().unwrap()) = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_maximized(&self, maximized: bool) {
|
|
||||||
if maximized {
|
|
||||||
self.frame.lock().unwrap().set_maximized();
|
|
||||||
} else {
|
|
||||||
self.frame.lock().unwrap().unset_maximized();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_fullscreen(&self, monitor: Option<RootMonitorId>) {
|
|
||||||
if let Some(RootMonitorId {
|
|
||||||
inner: PlatformMonitorId::Wayland(ref monitor_id),
|
|
||||||
}) = monitor
|
|
||||||
{
|
|
||||||
self.frame
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.set_fullscreen(Some(&monitor_id.proxy));
|
|
||||||
} else {
|
|
||||||
self.frame.lock().unwrap().unset_fullscreen();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor(&self, _cursor: MouseCursor) {
|
|
||||||
// TODO
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn hide_cursor(&self, _hide: bool) {
|
|
||||||
// TODO: This isn't possible on Wayland yet
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn grab_cursor(&self, _grab: bool) -> Result<(), String> {
|
|
||||||
Err("Cursor grabbing is not yet possible on Wayland.".to_owned())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor_position(&self, _pos: LogicalPosition) -> Result<(), String> {
|
|
||||||
Err("Setting the cursor position is not yet possible on Wayland.".to_owned())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_display(&self) -> &Display {
|
|
||||||
&*self.display
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_surface(&self) -> &Proxy<wl_surface::WlSurface> {
|
|
||||||
&self.surface
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_current_monitor(&self) -> MonitorId {
|
|
||||||
// we don't know how much each monitor sees us so...
|
|
||||||
// just return the most recent one ?
|
|
||||||
let guard = self.monitors.lock().unwrap();
|
|
||||||
guard.monitors.last().unwrap().clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_available_monitors(&self) -> VecDeque<MonitorId> {
|
|
||||||
get_available_monitors(&self.outputs)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_primary_monitor(&self) -> MonitorId {
|
|
||||||
get_primary_monitor(&self.outputs)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for Window {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
*(self.kill_switch.0.lock().unwrap()) = true;
|
|
||||||
*(self.kill_switch.1.lock().unwrap()) = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Internal store for windows
|
|
||||||
*/
|
|
||||||
|
|
||||||
struct InternalWindow {
|
|
||||||
surface: Proxy<wl_surface::WlSurface>,
|
|
||||||
newsize: Option<(u32, u32)>,
|
|
||||||
size: Arc<Mutex<(u32, u32)>>,
|
|
||||||
need_refresh: bool,
|
|
||||||
need_frame_refresh: Arc<Mutex<bool>>,
|
|
||||||
closed: bool,
|
|
||||||
kill_switch: Arc<Mutex<bool>>,
|
|
||||||
frame: Weak<Mutex<SWindow<BasicFrame>>>,
|
|
||||||
current_dpi: i32,
|
|
||||||
new_dpi: Option<i32>
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct WindowStore {
|
|
||||||
windows: Vec<InternalWindow>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowStore {
|
|
||||||
pub fn new() -> WindowStore {
|
|
||||||
WindowStore {
|
|
||||||
windows: Vec::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn find_wid(&self, surface: &Proxy<wl_surface::WlSurface>) -> Option<WindowId> {
|
|
||||||
for window in &self.windows {
|
|
||||||
if surface.equals(&window.surface) {
|
|
||||||
return Some(make_wid(surface));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn cleanup(&mut self) -> Vec<WindowId> {
|
|
||||||
let mut pruned = Vec::new();
|
|
||||||
self.windows.retain(|w| {
|
|
||||||
if *w.kill_switch.lock().unwrap() {
|
|
||||||
// window is dead, cleanup
|
|
||||||
pruned.push(make_wid(&w.surface));
|
|
||||||
w.surface.destroy();
|
|
||||||
false
|
|
||||||
} else {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
});
|
|
||||||
pruned
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_seat(&self, seat: &Proxy<wl_seat::WlSeat>) {
|
|
||||||
for window in &self.windows {
|
|
||||||
if let Some(w) = window.frame.upgrade() {
|
|
||||||
w.lock().unwrap().new_seat(seat);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dpi_change(&mut self, surface: &Proxy<wl_surface::WlSurface>, new: i32) {
|
|
||||||
for window in &mut self.windows {
|
|
||||||
if surface.equals(&window.surface) {
|
|
||||||
window.new_dpi = Some(new);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn for_each<F>(&mut self, mut f: F)
|
|
||||||
where
|
|
||||||
F: FnMut(Option<(u32, u32)>, &mut (u32, u32), Option<i32>, bool, bool, bool, WindowId, Option<&mut SWindow<BasicFrame>>),
|
|
||||||
{
|
|
||||||
for window in &mut self.windows {
|
|
||||||
let opt_arc = window.frame.upgrade();
|
|
||||||
let mut opt_mutex_lock = opt_arc.as_ref().map(|m| m.lock().unwrap());
|
|
||||||
f(
|
|
||||||
window.newsize.take(),
|
|
||||||
&mut *(window.size.lock().unwrap()),
|
|
||||||
window.new_dpi,
|
|
||||||
window.need_refresh,
|
|
||||||
::std::mem::replace(&mut *window.need_frame_refresh.lock().unwrap(), false),
|
|
||||||
window.closed,
|
|
||||||
make_wid(&window.surface),
|
|
||||||
opt_mutex_lock.as_mut().map(|m| &mut **m),
|
|
||||||
);
|
|
||||||
if let Some(dpi) = window.new_dpi.take() {
|
|
||||||
window.current_dpi = dpi;
|
|
||||||
}
|
|
||||||
window.need_refresh = false;
|
|
||||||
// avoid re-spamming the event
|
|
||||||
window.closed = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Monitor list with some covenience method to compute DPI
|
|
||||||
*/
|
|
||||||
|
|
||||||
struct MonitorList {
|
|
||||||
monitors: Vec<MonitorId>
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorList {
|
|
||||||
fn new() -> MonitorList {
|
|
||||||
MonitorList {
|
|
||||||
monitors: Vec::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn compute_hidpi_factor(&self) -> i32 {
|
|
||||||
let mut factor = 1;
|
|
||||||
for monitor_id in &self.monitors {
|
|
||||||
let monitor_dpi = monitor_id.get_hidpi_factor();
|
|
||||||
if monitor_dpi > factor { factor = monitor_dpi; }
|
|
||||||
}
|
|
||||||
factor
|
|
||||||
}
|
|
||||||
|
|
||||||
fn add_output(&mut self, monitor: MonitorId) -> Option<i32> {
|
|
||||||
let old_dpi = self.compute_hidpi_factor();
|
|
||||||
let monitor_dpi = monitor.get_hidpi_factor();
|
|
||||||
self.monitors.push(monitor);
|
|
||||||
if monitor_dpi > old_dpi {
|
|
||||||
Some(monitor_dpi)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn del_output(&mut self, output: &Proxy<wl_output::WlOutput>) -> Option<i32> {
|
|
||||||
let old_dpi = self.compute_hidpi_factor();
|
|
||||||
self.monitors.retain(|m| !m.proxy.equals(output));
|
|
||||||
let new_dpi = self.compute_hidpi_factor();
|
|
||||||
if new_dpi != old_dpi {
|
|
||||||
Some(new_dpi)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,219 +0,0 @@
|
|||||||
use std::io;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
use std::str::Utf8Error;
|
|
||||||
use std::os::raw::*;
|
|
||||||
|
|
||||||
use percent_encoding::percent_decode;
|
|
||||||
|
|
||||||
use super::{ffi, util, XConnection, XError};
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct DndAtoms {
|
|
||||||
pub aware: ffi::Atom,
|
|
||||||
pub enter: ffi::Atom,
|
|
||||||
pub leave: ffi::Atom,
|
|
||||||
pub drop: ffi::Atom,
|
|
||||||
pub position: ffi::Atom,
|
|
||||||
pub status: ffi::Atom,
|
|
||||||
pub action_private: ffi::Atom,
|
|
||||||
pub selection: ffi::Atom,
|
|
||||||
pub finished: ffi::Atom,
|
|
||||||
pub type_list: ffi::Atom,
|
|
||||||
pub uri_list: ffi::Atom,
|
|
||||||
pub none: ffi::Atom,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DndAtoms {
|
|
||||||
pub fn new(xconn: &Arc<XConnection>) -> Result<Self, XError> {
|
|
||||||
let names = [
|
|
||||||
b"XdndAware\0".as_ptr() as *mut c_char,
|
|
||||||
b"XdndEnter\0".as_ptr() as *mut c_char,
|
|
||||||
b"XdndLeave\0".as_ptr() as *mut c_char,
|
|
||||||
b"XdndDrop\0".as_ptr() as *mut c_char,
|
|
||||||
b"XdndPosition\0".as_ptr() as *mut c_char,
|
|
||||||
b"XdndStatus\0".as_ptr() as *mut c_char,
|
|
||||||
b"XdndActionPrivate\0".as_ptr() as *mut c_char,
|
|
||||||
b"XdndSelection\0".as_ptr() as *mut c_char,
|
|
||||||
b"XdndFinished\0".as_ptr() as *mut c_char,
|
|
||||||
b"XdndTypeList\0".as_ptr() as *mut c_char,
|
|
||||||
b"text/uri-list\0".as_ptr() as *mut c_char,
|
|
||||||
b"None\0".as_ptr() as *mut c_char,
|
|
||||||
];
|
|
||||||
let atoms = unsafe { xconn.get_atoms(&names) }?;
|
|
||||||
Ok(DndAtoms {
|
|
||||||
aware: atoms[0],
|
|
||||||
enter: atoms[1],
|
|
||||||
leave: atoms[2],
|
|
||||||
drop: atoms[3],
|
|
||||||
position: atoms[4],
|
|
||||||
status: atoms[5],
|
|
||||||
action_private: atoms[6],
|
|
||||||
selection: atoms[7],
|
|
||||||
finished: atoms[8],
|
|
||||||
type_list: atoms[9],
|
|
||||||
uri_list: atoms[10],
|
|
||||||
none: atoms[11],
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
|
||||||
pub enum DndState {
|
|
||||||
Accepted,
|
|
||||||
Rejected,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum DndDataParseError {
|
|
||||||
EmptyData,
|
|
||||||
InvalidUtf8(Utf8Error),
|
|
||||||
HostnameSpecified(String),
|
|
||||||
UnexpectedProtocol(String),
|
|
||||||
UnresolvablePath(io::Error),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<Utf8Error> for DndDataParseError {
|
|
||||||
fn from(e: Utf8Error) -> Self {
|
|
||||||
DndDataParseError::InvalidUtf8(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<io::Error> for DndDataParseError {
|
|
||||||
fn from(e: io::Error) -> Self {
|
|
||||||
DndDataParseError::UnresolvablePath(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Dnd {
|
|
||||||
xconn: Arc<XConnection>,
|
|
||||||
pub atoms: DndAtoms,
|
|
||||||
// Populated by XdndEnter event handler
|
|
||||||
pub version: Option<c_long>,
|
|
||||||
pub type_list: Option<Vec<c_ulong>>,
|
|
||||||
// Populated by XdndPosition event handler
|
|
||||||
pub source_window: Option<c_ulong>,
|
|
||||||
// Populated by SelectionNotify event handler (triggered by XdndPosition event handler)
|
|
||||||
pub result: Option<Result<Vec<PathBuf>, DndDataParseError>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Dnd {
|
|
||||||
pub fn new(xconn: Arc<XConnection>) -> Result<Self, XError> {
|
|
||||||
let atoms = DndAtoms::new(&xconn)?;
|
|
||||||
Ok(Dnd {
|
|
||||||
xconn,
|
|
||||||
atoms,
|
|
||||||
version: None,
|
|
||||||
type_list: None,
|
|
||||||
source_window: None,
|
|
||||||
result: None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn reset(&mut self) {
|
|
||||||
self.version = None;
|
|
||||||
self.type_list = None;
|
|
||||||
self.source_window = None;
|
|
||||||
self.result = None;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe fn send_status(
|
|
||||||
&self,
|
|
||||||
this_window: c_ulong,
|
|
||||||
target_window: c_ulong,
|
|
||||||
state: DndState,
|
|
||||||
) -> Result<(), XError> {
|
|
||||||
let (accepted, action) = match state {
|
|
||||||
DndState::Accepted => (1, self.atoms.action_private as c_long),
|
|
||||||
DndState::Rejected => (0, self.atoms.none as c_long),
|
|
||||||
};
|
|
||||||
self.xconn.send_client_msg(
|
|
||||||
target_window,
|
|
||||||
target_window,
|
|
||||||
self.atoms.status,
|
|
||||||
None,
|
|
||||||
[this_window as c_long, accepted, 0, 0, action],
|
|
||||||
).flush()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe fn send_finished(
|
|
||||||
&self,
|
|
||||||
this_window: c_ulong,
|
|
||||||
target_window: c_ulong,
|
|
||||||
state: DndState,
|
|
||||||
) -> Result<(), XError> {
|
|
||||||
let (accepted, action) = match state {
|
|
||||||
DndState::Accepted => (1, self.atoms.action_private as c_long),
|
|
||||||
DndState::Rejected => (0, self.atoms.none as c_long),
|
|
||||||
};
|
|
||||||
self.xconn.send_client_msg(
|
|
||||||
target_window,
|
|
||||||
target_window,
|
|
||||||
self.atoms.finished,
|
|
||||||
None,
|
|
||||||
[this_window as c_long, accepted, action, 0, 0],
|
|
||||||
).flush()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe fn get_type_list(
|
|
||||||
&self,
|
|
||||||
source_window: c_ulong,
|
|
||||||
) -> Result<Vec<ffi::Atom>, util::GetPropertyError> {
|
|
||||||
self.xconn.get_property(
|
|
||||||
source_window,
|
|
||||||
self.atoms.type_list,
|
|
||||||
ffi::XA_ATOM,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe fn convert_selection(&self, window: c_ulong, time: c_ulong) {
|
|
||||||
(self.xconn.xlib.XConvertSelection)(
|
|
||||||
self.xconn.display,
|
|
||||||
self.atoms.selection,
|
|
||||||
self.atoms.uri_list,
|
|
||||||
self.atoms.selection,
|
|
||||||
window,
|
|
||||||
time,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe fn read_data(
|
|
||||||
&self,
|
|
||||||
window: c_ulong,
|
|
||||||
) -> Result<Vec<c_uchar>, util::GetPropertyError> {
|
|
||||||
self.xconn.get_property(
|
|
||||||
window,
|
|
||||||
self.atoms.selection,
|
|
||||||
self.atoms.uri_list,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn parse_data(&self, data: &mut Vec<c_uchar>) -> Result<Vec<PathBuf>, DndDataParseError> {
|
|
||||||
if !data.is_empty() {
|
|
||||||
let mut path_list = Vec::new();
|
|
||||||
let decoded = percent_decode(data).decode_utf8()?.into_owned();
|
|
||||||
for uri in decoded.split("\r\n").filter(|u| !u.is_empty()) {
|
|
||||||
// The format is specified as protocol://host/path
|
|
||||||
// However, it's typically simply protocol:///path
|
|
||||||
let path_str = if uri.starts_with("file://") {
|
|
||||||
let path_str = uri.replace("file://", "");
|
|
||||||
if !path_str.starts_with('/') {
|
|
||||||
// A hostname is specified
|
|
||||||
// Supporting this case is beyond the scope of my mental health
|
|
||||||
return Err(DndDataParseError::HostnameSpecified(path_str));
|
|
||||||
}
|
|
||||||
path_str
|
|
||||||
} else {
|
|
||||||
// Only the file protocol is supported
|
|
||||||
return Err(DndDataParseError::UnexpectedProtocol(uri.to_owned()));
|
|
||||||
};
|
|
||||||
|
|
||||||
let path = Path::new(&path_str).canonicalize()?;
|
|
||||||
path_list.push(path);
|
|
||||||
}
|
|
||||||
Ok(path_list)
|
|
||||||
} else {
|
|
||||||
Err(DndDataParseError::EmptyData)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
pub use x11_dl::keysym::*;
|
|
||||||
pub use x11_dl::xcursor::*;
|
|
||||||
pub use x11_dl::xlib::*;
|
|
||||||
pub use x11_dl::xinput::*;
|
|
||||||
pub use x11_dl::xinput2::*;
|
|
||||||
pub use x11_dl::xlib_xcb::*;
|
|
||||||
pub use x11_dl::error::OpenError;
|
|
||||||
pub use x11_dl::xrandr::*;
|
|
||||||
@@ -1,185 +0,0 @@
|
|||||||
use std::ptr;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::os::raw::c_char;
|
|
||||||
|
|
||||||
use super::{ffi, XConnection, XError};
|
|
||||||
|
|
||||||
use super::inner::{close_im, ImeInner};
|
|
||||||
use super::input_method::PotentialInputMethods;
|
|
||||||
use super::context::{ImeContextCreationError, ImeContext};
|
|
||||||
|
|
||||||
pub unsafe fn xim_set_callback(
|
|
||||||
xconn: &Arc<XConnection>,
|
|
||||||
xim: ffi::XIM,
|
|
||||||
field: *const c_char,
|
|
||||||
callback: *mut ffi::XIMCallback,
|
|
||||||
) -> Result<(), XError> {
|
|
||||||
// It's advisable to wrap variadic FFI functions in our own functions, as we want to minimize
|
|
||||||
// access that isn't type-checked.
|
|
||||||
(xconn.xlib.XSetIMValues)(
|
|
||||||
xim,
|
|
||||||
field,
|
|
||||||
callback,
|
|
||||||
ptr::null_mut::<()>(),
|
|
||||||
);
|
|
||||||
xconn.check_errors()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set a callback for when an input method matching the current locale modifiers becomes
|
|
||||||
// available. Note that this has nothing to do with what input methods are open or able to be
|
|
||||||
// opened, and simply uses the modifiers that are set when the callback is set.
|
|
||||||
// * This is called per locale modifier, not per input method opened with that locale modifier.
|
|
||||||
// * Trying to set this for multiple locale modifiers causes problems, i.e. one of the rebuilt
|
|
||||||
// input contexts would always silently fail to use the input method.
|
|
||||||
pub unsafe fn set_instantiate_callback(
|
|
||||||
xconn: &Arc<XConnection>,
|
|
||||||
client_data: ffi::XPointer,
|
|
||||||
) -> Result<(), XError> {
|
|
||||||
(xconn.xlib.XRegisterIMInstantiateCallback)(
|
|
||||||
xconn.display,
|
|
||||||
ptr::null_mut(),
|
|
||||||
ptr::null_mut(),
|
|
||||||
ptr::null_mut(),
|
|
||||||
Some(xim_instantiate_callback),
|
|
||||||
client_data,
|
|
||||||
);
|
|
||||||
xconn.check_errors()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe fn unset_instantiate_callback(
|
|
||||||
xconn: &Arc<XConnection>,
|
|
||||||
client_data: ffi::XPointer,
|
|
||||||
) -> Result<(), XError> {
|
|
||||||
(xconn.xlib.XUnregisterIMInstantiateCallback)(
|
|
||||||
xconn.display,
|
|
||||||
ptr::null_mut(),
|
|
||||||
ptr::null_mut(),
|
|
||||||
ptr::null_mut(),
|
|
||||||
Some(xim_instantiate_callback),
|
|
||||||
client_data,
|
|
||||||
);
|
|
||||||
xconn.check_errors()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe fn set_destroy_callback(
|
|
||||||
xconn: &Arc<XConnection>,
|
|
||||||
im: ffi::XIM,
|
|
||||||
inner: &ImeInner,
|
|
||||||
) -> Result<(), XError> {
|
|
||||||
xim_set_callback(
|
|
||||||
&xconn,
|
|
||||||
im,
|
|
||||||
ffi::XNDestroyCallback_0.as_ptr() as *const _,
|
|
||||||
&inner.destroy_callback as *const _ as *mut _,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
enum ReplaceImError {
|
|
||||||
MethodOpenFailed(PotentialInputMethods),
|
|
||||||
ContextCreationFailed(ImeContextCreationError),
|
|
||||||
SetDestroyCallbackFailed(XError),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Attempt to replace current IM (which may or may not be presently valid) with a new one. This
|
|
||||||
// includes replacing all existing input contexts and free'ing resources as necessary. This only
|
|
||||||
// modifies existing state if all operations succeed.
|
|
||||||
unsafe fn replace_im(inner: *mut ImeInner) -> Result<(), ReplaceImError> {
|
|
||||||
let xconn = &(*inner).xconn;
|
|
||||||
|
|
||||||
let (new_im, is_fallback) = {
|
|
||||||
let new_im = (*inner).potential_input_methods.open_im(xconn, None);
|
|
||||||
let is_fallback = new_im.is_fallback();
|
|
||||||
(
|
|
||||||
new_im.ok().ok_or_else(|| {
|
|
||||||
ReplaceImError::MethodOpenFailed((*inner).potential_input_methods.clone())
|
|
||||||
})?,
|
|
||||||
is_fallback,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
|
|
||||||
// It's important to always set a destroy callback, since there's otherwise potential for us
|
|
||||||
// to try to use or free a resource that's already been destroyed on the server.
|
|
||||||
{
|
|
||||||
let result = set_destroy_callback(xconn, new_im.im, &*inner);
|
|
||||||
if result.is_err() {
|
|
||||||
let _ = close_im(xconn, new_im.im);
|
|
||||||
}
|
|
||||||
result
|
|
||||||
}.map_err(ReplaceImError::SetDestroyCallbackFailed)?;
|
|
||||||
|
|
||||||
let mut new_contexts = HashMap::new();
|
|
||||||
for (window, old_context) in (*inner).contexts.iter() {
|
|
||||||
let spot = old_context.as_ref().map(|old_context| old_context.ic_spot);
|
|
||||||
let new_context = {
|
|
||||||
let result = ImeContext::new(
|
|
||||||
xconn,
|
|
||||||
new_im.im,
|
|
||||||
*window,
|
|
||||||
spot,
|
|
||||||
);
|
|
||||||
if result.is_err() {
|
|
||||||
let _ = close_im(xconn, new_im.im);
|
|
||||||
}
|
|
||||||
result.map_err(ReplaceImError::ContextCreationFailed)?
|
|
||||||
};
|
|
||||||
new_contexts.insert(*window, Some(new_context));
|
|
||||||
}
|
|
||||||
|
|
||||||
// If we've made it this far, everything succeeded.
|
|
||||||
let _ = (*inner).destroy_all_contexts_if_necessary();
|
|
||||||
let _ = (*inner).close_im_if_necessary();
|
|
||||||
(*inner).im = new_im.im;
|
|
||||||
(*inner).contexts = new_contexts;
|
|
||||||
(*inner).is_destroyed = false;
|
|
||||||
(*inner).is_fallback = is_fallback;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe extern fn xim_instantiate_callback(
|
|
||||||
_display: *mut ffi::Display,
|
|
||||||
client_data: ffi::XPointer,
|
|
||||||
// This field is unsupplied.
|
|
||||||
_call_data: ffi::XPointer,
|
|
||||||
) {
|
|
||||||
let inner: *mut ImeInner = client_data as _;
|
|
||||||
if !inner.is_null() {
|
|
||||||
let xconn = &(*inner).xconn;
|
|
||||||
let result = replace_im(inner);
|
|
||||||
if result.is_ok() {
|
|
||||||
let _ = unset_instantiate_callback(xconn, client_data);
|
|
||||||
(*inner).is_fallback = false;
|
|
||||||
} else if result.is_err() && (*inner).is_destroyed {
|
|
||||||
// We have no usable input methods!
|
|
||||||
result.expect("Failed to reopen input method");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// This callback is triggered when the input method is closed on the server end. When this
|
|
||||||
// happens, XCloseIM/XDestroyIC doesn't need to be called, as the resources have already been
|
|
||||||
// free'd (attempting to do so causes our connection to freeze).
|
|
||||||
pub unsafe extern fn xim_destroy_callback(
|
|
||||||
_xim: ffi::XIM,
|
|
||||||
client_data: ffi::XPointer,
|
|
||||||
// This field is unsupplied.
|
|
||||||
_call_data: ffi::XPointer,
|
|
||||||
) {
|
|
||||||
let inner: *mut ImeInner = client_data as _;
|
|
||||||
if !inner.is_null() {
|
|
||||||
(*inner).is_destroyed = true;
|
|
||||||
let xconn = &(*inner).xconn;
|
|
||||||
if !(*inner).is_fallback {
|
|
||||||
let _ = set_instantiate_callback(xconn, client_data);
|
|
||||||
// Attempt to open fallback input method.
|
|
||||||
let result = replace_im(inner);
|
|
||||||
if result.is_ok() {
|
|
||||||
(*inner).is_fallback = true;
|
|
||||||
} else {
|
|
||||||
// We have no usable input methods!
|
|
||||||
result.expect("Failed to open fallback input method");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,134 +0,0 @@
|
|||||||
use std::ptr;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::os::raw::{c_short, c_void};
|
|
||||||
|
|
||||||
use super::{ffi, util, XConnection, XError};
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum ImeContextCreationError {
|
|
||||||
XError(XError),
|
|
||||||
Null,
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn create_pre_edit_attr<'a>(
|
|
||||||
xconn: &'a Arc<XConnection>,
|
|
||||||
ic_spot: &'a ffi::XPoint,
|
|
||||||
) -> util::XSmartPointer<'a, c_void> {
|
|
||||||
util::XSmartPointer::new(
|
|
||||||
xconn,
|
|
||||||
(xconn.xlib.XVaCreateNestedList)(
|
|
||||||
0,
|
|
||||||
ffi::XNSpotLocation_0.as_ptr() as *const _,
|
|
||||||
ic_spot,
|
|
||||||
ptr::null_mut::<()>(),
|
|
||||||
),
|
|
||||||
).expect("XVaCreateNestedList returned NULL")
|
|
||||||
}
|
|
||||||
|
|
||||||
// WARNING: this struct doesn't destroy its XIC resource when dropped.
|
|
||||||
// This is intentional, as it doesn't have enough information to know whether or not the context
|
|
||||||
// still exists on the server. Since `ImeInner` has that awareness, destruction must be handled
|
|
||||||
// through `ImeInner`.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct ImeContext {
|
|
||||||
pub ic: ffi::XIC,
|
|
||||||
pub ic_spot: ffi::XPoint,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ImeContext {
|
|
||||||
pub unsafe fn new(
|
|
||||||
xconn: &Arc<XConnection>,
|
|
||||||
im: ffi::XIM,
|
|
||||||
window: ffi::Window,
|
|
||||||
ic_spot: Option<ffi::XPoint>,
|
|
||||||
) -> Result<Self, ImeContextCreationError> {
|
|
||||||
let ic = if let Some(ic_spot) = ic_spot {
|
|
||||||
ImeContext::create_ic_with_spot(xconn, im, window, ic_spot)
|
|
||||||
} else {
|
|
||||||
ImeContext::create_ic(xconn, im, window)
|
|
||||||
};
|
|
||||||
|
|
||||||
let ic = ic.ok_or(ImeContextCreationError::Null)?;
|
|
||||||
xconn.check_errors().map_err(ImeContextCreationError::XError)?;
|
|
||||||
|
|
||||||
Ok(ImeContext {
|
|
||||||
ic,
|
|
||||||
ic_spot: ic_spot.unwrap_or_else(|| ffi::XPoint { x: 0, y: 0 }),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn create_ic(
|
|
||||||
xconn: &Arc<XConnection>,
|
|
||||||
im: ffi::XIM,
|
|
||||||
window: ffi::Window,
|
|
||||||
) -> Option<ffi::XIC> {
|
|
||||||
let ic = (xconn.xlib.XCreateIC)(
|
|
||||||
im,
|
|
||||||
ffi::XNInputStyle_0.as_ptr() as *const _,
|
|
||||||
ffi::XIMPreeditNothing | ffi::XIMStatusNothing,
|
|
||||||
ffi::XNClientWindow_0.as_ptr() as *const _,
|
|
||||||
window,
|
|
||||||
ptr::null_mut::<()>(),
|
|
||||||
);
|
|
||||||
if ic.is_null() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(ic)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn create_ic_with_spot(
|
|
||||||
xconn: &Arc<XConnection>,
|
|
||||||
im: ffi::XIM,
|
|
||||||
window: ffi::Window,
|
|
||||||
ic_spot: ffi::XPoint,
|
|
||||||
) -> Option<ffi::XIC> {
|
|
||||||
let pre_edit_attr = create_pre_edit_attr(xconn, &ic_spot);
|
|
||||||
let ic = (xconn.xlib.XCreateIC)(
|
|
||||||
im,
|
|
||||||
ffi::XNInputStyle_0.as_ptr() as *const _,
|
|
||||||
ffi::XIMPreeditNothing | ffi::XIMStatusNothing,
|
|
||||||
ffi::XNClientWindow_0.as_ptr() as *const _,
|
|
||||||
window,
|
|
||||||
ffi::XNPreeditAttributes_0.as_ptr() as *const _,
|
|
||||||
pre_edit_attr.ptr,
|
|
||||||
ptr::null_mut::<()>(),
|
|
||||||
);
|
|
||||||
if ic.is_null() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(ic)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn focus(&self, xconn: &Arc<XConnection>) -> Result<(), XError> {
|
|
||||||
unsafe {
|
|
||||||
(xconn.xlib.XSetICFocus)(self.ic);
|
|
||||||
}
|
|
||||||
xconn.check_errors()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn unfocus(&self, xconn: &Arc<XConnection>) -> Result<(), XError> {
|
|
||||||
unsafe {
|
|
||||||
(xconn.xlib.XUnsetICFocus)(self.ic);
|
|
||||||
}
|
|
||||||
xconn.check_errors()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_spot(&mut self, xconn: &Arc<XConnection>, x: c_short, y: c_short) {
|
|
||||||
if self.ic_spot.x == x && self.ic_spot.y == y {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
self.ic_spot = ffi::XPoint { x, y };
|
|
||||||
|
|
||||||
unsafe {
|
|
||||||
let pre_edit_attr = create_pre_edit_attr(xconn, &self.ic_spot);
|
|
||||||
(xconn.xlib.XSetICValues)(
|
|
||||||
self.ic,
|
|
||||||
ffi::XNPreeditAttributes_0.as_ptr() as *const _,
|
|
||||||
pre_edit_attr.ptr,
|
|
||||||
ptr::null_mut::<()>(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,269 +0,0 @@
|
|||||||
use std::os::raw::*;
|
|
||||||
|
|
||||||
use parking_lot::Mutex;
|
|
||||||
|
|
||||||
use {PhysicalPosition, PhysicalSize};
|
|
||||||
use super::{util, XConnection, XError};
|
|
||||||
use super::ffi::{
|
|
||||||
RRCrtcChangeNotifyMask,
|
|
||||||
RROutputPropertyNotifyMask,
|
|
||||||
RRScreenChangeNotifyMask,
|
|
||||||
True,
|
|
||||||
Window,
|
|
||||||
XRRScreenResources,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Used to test XRandR < 1.5 code path. This should always be committed as false.
|
|
||||||
const FORCE_RANDR_COMPAT: bool = false;
|
|
||||||
// Also used for testing. This should always be committed as false.
|
|
||||||
const DISABLE_MONITOR_LIST_CACHING: bool = false;
|
|
||||||
|
|
||||||
lazy_static! {
|
|
||||||
static ref XRANDR_VERSION: Mutex<Option<(c_int, c_int)>> = Mutex::default();
|
|
||||||
static ref MONITORS: Mutex<Option<Vec<MonitorId>>> = Mutex::default();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn version_is_at_least(major: c_int, minor: c_int) -> bool {
|
|
||||||
if let Some((avail_major, avail_minor)) = *XRANDR_VERSION.lock() {
|
|
||||||
if avail_major == major {
|
|
||||||
avail_minor >= minor
|
|
||||||
} else {
|
|
||||||
avail_major > major
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
unreachable!();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn invalidate_cached_monitor_list() -> Option<Vec<MonitorId>> {
|
|
||||||
// We update this lazily.
|
|
||||||
(*MONITORS.lock()).take()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct MonitorId {
|
|
||||||
/// The actual id
|
|
||||||
id: u32,
|
|
||||||
/// The name of the monitor
|
|
||||||
pub(crate) name: String,
|
|
||||||
/// The size of the monitor
|
|
||||||
dimensions: (u32, u32),
|
|
||||||
/// The position of the monitor in the X screen
|
|
||||||
position: (i32, i32),
|
|
||||||
/// If the monitor is the primary one
|
|
||||||
primary: bool,
|
|
||||||
/// The DPI scale factor
|
|
||||||
pub(crate) hidpi_factor: f64,
|
|
||||||
/// Used to determine which windows are on this monitor
|
|
||||||
pub(crate) rect: util::AaRect,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorId {
|
|
||||||
fn from_repr(
|
|
||||||
xconn: &XConnection,
|
|
||||||
resources: *mut XRRScreenResources,
|
|
||||||
id: u32,
|
|
||||||
repr: util::MonitorRepr,
|
|
||||||
primary: bool,
|
|
||||||
) -> Self {
|
|
||||||
let (name, hidpi_factor) = unsafe { xconn.get_output_info(resources, &repr) };
|
|
||||||
let (dimensions, position) = unsafe { (repr.get_dimensions(), repr.get_position()) };
|
|
||||||
let rect = util::AaRect::new(position, dimensions);
|
|
||||||
MonitorId {
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
hidpi_factor,
|
|
||||||
dimensions,
|
|
||||||
position,
|
|
||||||
primary,
|
|
||||||
rect,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_name(&self) -> Option<String> {
|
|
||||||
Some(self.name.clone())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_native_identifier(&self) -> u32 {
|
|
||||||
self.id as u32
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_dimensions(&self) -> PhysicalSize {
|
|
||||||
self.dimensions.into()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_position(&self) -> PhysicalPosition {
|
|
||||||
self.position.into()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_hidpi_factor(&self) -> f64 {
|
|
||||||
self.hidpi_factor
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl XConnection {
|
|
||||||
pub fn get_monitor_for_window(&self, window_rect: Option<util::AaRect>) -> MonitorId {
|
|
||||||
let monitors = self.get_available_monitors();
|
|
||||||
let default = monitors
|
|
||||||
.get(0)
|
|
||||||
.expect("[winit] Failed to find any monitors using XRandR.");
|
|
||||||
|
|
||||||
let window_rect = match window_rect {
|
|
||||||
Some(rect) => rect,
|
|
||||||
None => return default.to_owned(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut largest_overlap = 0;
|
|
||||||
let mut matched_monitor = default;
|
|
||||||
for monitor in &monitors {
|
|
||||||
let overlapping_area = window_rect.get_overlapping_area(&monitor.rect);
|
|
||||||
if overlapping_area > largest_overlap {
|
|
||||||
largest_overlap = overlapping_area;
|
|
||||||
matched_monitor = &monitor;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
matched_monitor.to_owned()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn query_monitor_list(&self) -> Vec<MonitorId> {
|
|
||||||
unsafe {
|
|
||||||
let root = (self.xlib.XDefaultRootWindow)(self.display);
|
|
||||||
// WARNING: this function is supposedly very slow, on the order of hundreds of ms.
|
|
||||||
// Upon failure, `resources` will be null.
|
|
||||||
let resources = (self.xrandr.XRRGetScreenResources)(self.display, root);
|
|
||||||
if resources.is_null() {
|
|
||||||
panic!("[winit] `XRRGetScreenResources` returned NULL. That should only happen if the root window doesn't exist.");
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut available;
|
|
||||||
let mut has_primary = false;
|
|
||||||
|
|
||||||
if self.xrandr_1_5.is_some() && version_is_at_least(1, 5) && !FORCE_RANDR_COMPAT {
|
|
||||||
// We're in XRandR >= 1.5, enumerate monitors. This supports things like MST and
|
|
||||||
// videowalls.
|
|
||||||
let xrandr_1_5 = self.xrandr_1_5.as_ref().unwrap();
|
|
||||||
let mut monitor_count = 0;
|
|
||||||
let monitors = (xrandr_1_5.XRRGetMonitors)(self.display, root, 1, &mut monitor_count);
|
|
||||||
assert!(monitor_count >= 0);
|
|
||||||
available = Vec::with_capacity(monitor_count as usize);
|
|
||||||
for monitor_index in 0..monitor_count {
|
|
||||||
let monitor = monitors.offset(monitor_index as isize);
|
|
||||||
let is_primary = (*monitor).primary != 0;
|
|
||||||
has_primary |= is_primary;
|
|
||||||
available.push(MonitorId::from_repr(
|
|
||||||
self,
|
|
||||||
resources,
|
|
||||||
monitor_index as u32,
|
|
||||||
monitor.into(),
|
|
||||||
is_primary,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
(xrandr_1_5.XRRFreeMonitors)(monitors);
|
|
||||||
} else {
|
|
||||||
// We're in XRandR < 1.5, enumerate CRTCs. Everything will work except MST and
|
|
||||||
// videowall setups will also show monitors that aren't in the logical groups the user
|
|
||||||
// cares about.
|
|
||||||
let primary = (self.xrandr.XRRGetOutputPrimary)(self.display, root);
|
|
||||||
available = Vec::with_capacity((*resources).ncrtc as usize);
|
|
||||||
for crtc_index in 0..(*resources).ncrtc {
|
|
||||||
let crtc_id = *((*resources).crtcs.offset(crtc_index as isize));
|
|
||||||
let crtc = (self.xrandr.XRRGetCrtcInfo)(self.display, resources, crtc_id);
|
|
||||||
let is_active = (*crtc).width > 0 && (*crtc).height > 0 && (*crtc).noutput > 0;
|
|
||||||
if is_active {
|
|
||||||
let crtc = util::MonitorRepr::from(crtc);
|
|
||||||
let is_primary = crtc.get_output() == primary;
|
|
||||||
has_primary |= is_primary;
|
|
||||||
available.push(MonitorId::from_repr(
|
|
||||||
self,
|
|
||||||
resources,
|
|
||||||
crtc_id as u32,
|
|
||||||
crtc,
|
|
||||||
is_primary,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
(self.xrandr.XRRFreeCrtcInfo)(crtc);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If no monitors were detected as being primary, we just pick one ourselves!
|
|
||||||
if !has_primary {
|
|
||||||
if let Some(ref mut fallback) = available.first_mut() {
|
|
||||||
// Setting this here will come in handy if we ever add an `is_primary` method.
|
|
||||||
fallback.primary = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
(self.xrandr.XRRFreeScreenResources)(resources);
|
|
||||||
available
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_available_monitors(&self) -> Vec<MonitorId> {
|
|
||||||
let mut monitors_lock = MONITORS.lock();
|
|
||||||
(*monitors_lock)
|
|
||||||
.as_ref()
|
|
||||||
.cloned()
|
|
||||||
.or_else(|| {
|
|
||||||
let monitors = Some(self.query_monitor_list());
|
|
||||||
if !DISABLE_MONITOR_LIST_CACHING {
|
|
||||||
(*monitors_lock) = monitors.clone();
|
|
||||||
}
|
|
||||||
monitors
|
|
||||||
})
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_primary_monitor(&self) -> MonitorId {
|
|
||||||
self.get_available_monitors()
|
|
||||||
.into_iter()
|
|
||||||
.find(|monitor| monitor.primary)
|
|
||||||
.expect("[winit] Failed to find any monitors using XRandR.")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn select_xrandr_input(&self, root: Window) -> Result<c_int, XError> {
|
|
||||||
{
|
|
||||||
let mut version_lock = XRANDR_VERSION.lock();
|
|
||||||
if version_lock.is_none() {
|
|
||||||
let mut major = 0;
|
|
||||||
let mut minor = 0;
|
|
||||||
let has_extension = unsafe {
|
|
||||||
(self.xrandr.XRRQueryVersion)(
|
|
||||||
self.display,
|
|
||||||
&mut major,
|
|
||||||
&mut minor,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
if has_extension != True {
|
|
||||||
panic!("[winit] XRandR extension not available.");
|
|
||||||
}
|
|
||||||
*version_lock = Some((major, minor));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut event_offset = 0;
|
|
||||||
let mut error_offset = 0;
|
|
||||||
let status = unsafe {
|
|
||||||
(self.xrandr.XRRQueryExtension)(
|
|
||||||
self.display,
|
|
||||||
&mut event_offset,
|
|
||||||
&mut error_offset,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
|
|
||||||
if status != True {
|
|
||||||
self.check_errors()?;
|
|
||||||
unreachable!("[winit] `XRRQueryExtension` failed but no error was received.");
|
|
||||||
}
|
|
||||||
|
|
||||||
let mask = RRCrtcChangeNotifyMask
|
|
||||||
| RROutputPropertyNotifyMask
|
|
||||||
| RRScreenChangeNotifyMask;
|
|
||||||
unsafe { (self.xrandr.XRRSelectInput)(self.display, root, mask) };
|
|
||||||
|
|
||||||
Ok(event_offset)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
use std::collections::HashMap;
|
|
||||||
use std::ffi::{CStr, CString};
|
|
||||||
use std::fmt::Debug;
|
|
||||||
use std::os::raw::*;
|
|
||||||
|
|
||||||
use parking_lot::Mutex;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
type AtomCache = HashMap<CString, ffi::Atom>;
|
|
||||||
|
|
||||||
lazy_static! {
|
|
||||||
static ref ATOM_CACHE: Mutex<AtomCache> = Mutex::new(HashMap::with_capacity(2048));
|
|
||||||
}
|
|
||||||
|
|
||||||
impl XConnection {
|
|
||||||
pub fn get_atom<T: AsRef<CStr> + Debug>(&self, name: T) -> ffi::Atom {
|
|
||||||
let name = name.as_ref();
|
|
||||||
let mut atom_cache_lock = ATOM_CACHE.lock();
|
|
||||||
let cached_atom = (*atom_cache_lock).get(name).cloned();
|
|
||||||
if let Some(atom) = cached_atom {
|
|
||||||
atom
|
|
||||||
} else {
|
|
||||||
let atom = unsafe { (self.xlib.XInternAtom)(
|
|
||||||
self.display,
|
|
||||||
name.as_ptr() as *const c_char,
|
|
||||||
ffi::False,
|
|
||||||
) };
|
|
||||||
if atom == 0 {
|
|
||||||
let msg = format!(
|
|
||||||
"`XInternAtom` failed, which really shouldn't happen. Atom: {:?}, Error: {:#?}",
|
|
||||||
name,
|
|
||||||
self.check_errors(),
|
|
||||||
);
|
|
||||||
panic!(msg);
|
|
||||||
}
|
|
||||||
/*println!(
|
|
||||||
"XInternAtom name:{:?} atom:{:?}",
|
|
||||||
name,
|
|
||||||
atom,
|
|
||||||
);*/
|
|
||||||
(*atom_cache_lock).insert(name.to_owned(), atom);
|
|
||||||
atom
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe fn get_atom_unchecked(&self, name: &[u8]) -> ffi::Atom {
|
|
||||||
debug_assert!(CStr::from_bytes_with_nul(name).is_ok());
|
|
||||||
let name = CStr::from_bytes_with_nul_unchecked(name);
|
|
||||||
self.get_atom(name)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Note: this doesn't use caching, for the sake of simplicity.
|
|
||||||
// If you're dealing with this many atoms, you'll usually want to cache them locally anyway.
|
|
||||||
pub unsafe fn get_atoms(&self, names: &[*mut c_char]) -> Result<Vec<ffi::Atom>, XError> {
|
|
||||||
let mut atoms = Vec::with_capacity(names.len());
|
|
||||||
(self.xlib.XInternAtoms)(
|
|
||||||
self.display,
|
|
||||||
names.as_ptr() as *mut _,
|
|
||||||
names.len() as c_int,
|
|
||||||
ffi::False,
|
|
||||||
atoms.as_mut_ptr(),
|
|
||||||
);
|
|
||||||
self.check_errors()?;
|
|
||||||
atoms.set_len(names.len());
|
|
||||||
/*println!(
|
|
||||||
"XInternAtoms atoms:{:?}",
|
|
||||||
atoms,
|
|
||||||
);*/
|
|
||||||
Ok(atoms)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
use super::*;
|
|
||||||
|
|
||||||
pub type ClientMsgPayload = [c_long; 5];
|
|
||||||
|
|
||||||
impl XConnection {
|
|
||||||
pub fn send_event<T: Into<ffi::XEvent>>(
|
|
||||||
&self,
|
|
||||||
target_window: c_ulong,
|
|
||||||
event_mask: Option<c_long>,
|
|
||||||
event: T,
|
|
||||||
) -> Flusher {
|
|
||||||
let event_mask = event_mask.unwrap_or(ffi::NoEventMask);
|
|
||||||
unsafe {
|
|
||||||
(self.xlib.XSendEvent)(
|
|
||||||
self.display,
|
|
||||||
target_window,
|
|
||||||
ffi::False,
|
|
||||||
event_mask,
|
|
||||||
&mut event.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Flusher::new(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn send_client_msg(
|
|
||||||
&self,
|
|
||||||
window: c_ulong, // The window this is "about"; not necessarily this window
|
|
||||||
target_window: c_ulong, // The window we're sending to
|
|
||||||
message_type: ffi::Atom,
|
|
||||||
event_mask: Option<c_long>,
|
|
||||||
data: ClientMsgPayload,
|
|
||||||
) -> Flusher {
|
|
||||||
let mut event: ffi::XClientMessageEvent = unsafe { mem::uninitialized() };
|
|
||||||
event.type_ = ffi::ClientMessage;
|
|
||||||
event.display = self.display;
|
|
||||||
event.window = window;
|
|
||||||
event.message_type = message_type;
|
|
||||||
event.format = c_long::FORMAT as c_int;
|
|
||||||
event.data = unsafe { mem::transmute(data) };
|
|
||||||
self.send_event(target_window, event_mask, event)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Prepare yourself for the ultimate in unsafety!
|
|
||||||
// You should favor `send_client_msg` whenever possible, but some protocols (i.e. startup notification) require you
|
|
||||||
// to send more than one message worth of data.
|
|
||||||
pub fn send_client_msg_multi<T: Formattable>(
|
|
||||||
&self,
|
|
||||||
window: c_ulong, // The window this is "about"; not necessarily this window
|
|
||||||
target_window: c_ulong, // The window we're sending to
|
|
||||||
message_type: ffi::Atom,
|
|
||||||
event_mask: Option<c_long>,
|
|
||||||
data: &[T],
|
|
||||||
) -> Flusher {
|
|
||||||
let format = T::FORMAT;
|
|
||||||
let size_of_t = mem::size_of::<T>();
|
|
||||||
debug_assert_eq!(size_of_t, format.get_actual_size());
|
|
||||||
let mut event: ffi::XClientMessageEvent = unsafe { mem::uninitialized() };
|
|
||||||
event.type_ = ffi::ClientMessage;
|
|
||||||
event.display = self.display;
|
|
||||||
event.window = window;
|
|
||||||
event.message_type = message_type;
|
|
||||||
event.format = format as c_int;
|
|
||||||
|
|
||||||
let t_per_payload = format.get_payload_size() / size_of_t;
|
|
||||||
assert!(t_per_payload > 0);
|
|
||||||
let payload_count = data.len() / t_per_payload;
|
|
||||||
let payload_remainder = data.len() % t_per_payload;
|
|
||||||
let payload_ptr = data.as_ptr() as *const ClientMsgPayload;
|
|
||||||
|
|
||||||
let mut payload_index = 0;
|
|
||||||
while payload_index < payload_count {
|
|
||||||
let payload = unsafe { payload_ptr.offset(payload_index as isize) };
|
|
||||||
payload_index += 1;
|
|
||||||
event.data = unsafe { mem::transmute(*payload) };
|
|
||||||
self.send_event(target_window, event_mask, &event).queue();
|
|
||||||
}
|
|
||||||
|
|
||||||
if payload_remainder > 0 {
|
|
||||||
let mut payload: ClientMsgPayload = [0; 5];
|
|
||||||
let t_payload = payload.as_mut_ptr() as *mut T;
|
|
||||||
let invalid_payload = unsafe { payload_ptr.offset(payload_index as isize) };
|
|
||||||
let invalid_t_payload = invalid_payload as *const T;
|
|
||||||
let mut t_index = 0;
|
|
||||||
while t_index < payload_remainder {
|
|
||||||
let valid_t = unsafe { invalid_t_payload.offset(t_index as isize) };
|
|
||||||
unsafe { (*t_payload.offset(t_index as isize)) = (*valid_t).clone() };
|
|
||||||
t_index += 1;
|
|
||||||
}
|
|
||||||
event.data = unsafe { mem::transmute(payload) };
|
|
||||||
self.send_event(target_window, event_mask, &event).queue();
|
|
||||||
}
|
|
||||||
|
|
||||||
Flusher::new(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
use std::fmt::Debug;
|
|
||||||
use std::mem;
|
|
||||||
use std::os::raw::*;
|
|
||||||
|
|
||||||
// This isn't actually the number of the bits in the format.
|
|
||||||
// X11 does a match on this value to determine which type to call sizeof on.
|
|
||||||
// Thus, we use 32 for c_long, since 32 maps to c_long which maps to 64.
|
|
||||||
// ...if that sounds confusing, then you know why this enum is here.
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
|
||||||
pub enum Format {
|
|
||||||
Char = 8,
|
|
||||||
Short = 16,
|
|
||||||
Long = 32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Format {
|
|
||||||
pub fn from_format(format: usize) -> Option<Self> {
|
|
||||||
match format {
|
|
||||||
8 => Some(Format::Char),
|
|
||||||
16 => Some(Format::Short),
|
|
||||||
32 => Some(Format::Long),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn is_same_size_as<T>(&self) -> bool {
|
|
||||||
mem::size_of::<T>() == self.get_actual_size()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_actual_size(&self) -> usize {
|
|
||||||
match self {
|
|
||||||
&Format::Char => mem::size_of::<c_char>(),
|
|
||||||
&Format::Short => mem::size_of::<c_short>(),
|
|
||||||
&Format::Long => mem::size_of::<c_long>(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_payload_size(&self) -> usize {
|
|
||||||
match self {
|
|
||||||
// Due to the wonders of X11, half the space goes unused if you're not using longs (on 64-bit).
|
|
||||||
&Format::Char => mem::size_of::<c_char>() * 20,
|
|
||||||
&Format::Short => mem::size_of::<c_short>() * 10,
|
|
||||||
&Format::Long => mem::size_of::<c_long>() * 5,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait Formattable: Debug + Clone + Copy + PartialEq + PartialOrd {
|
|
||||||
const FORMAT: Format;
|
|
||||||
}
|
|
||||||
|
|
||||||
// You might be surprised by the absence of c_int, but not as surprised as X11 would be by the presence of it.
|
|
||||||
impl Formattable for c_schar { const FORMAT: Format = Format::Char; }
|
|
||||||
impl Formattable for c_uchar { const FORMAT: Format = Format::Char; }
|
|
||||||
impl Formattable for c_short { const FORMAT: Format = Format::Short; }
|
|
||||||
impl Formattable for c_ushort { const FORMAT: Format = Format::Short; }
|
|
||||||
impl Formattable for c_long { const FORMAT: Format = Format::Long; }
|
|
||||||
impl Formattable for c_ulong { const FORMAT: Format = Format::Long; }
|
|
||||||
@@ -1,211 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
pub const MWM_HINTS_DECORATIONS: c_ulong = 2;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum StateOperation {
|
|
||||||
Remove = 0, // _NET_WM_STATE_REMOVE
|
|
||||||
Add = 1, // _NET_WM_STATE_ADD
|
|
||||||
Toggle = 2, // _NET_WM_STATE_TOGGLE
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<bool> for StateOperation {
|
|
||||||
fn from(op: bool) -> Self {
|
|
||||||
if op {
|
|
||||||
StateOperation::Add
|
|
||||||
} else {
|
|
||||||
StateOperation::Remove
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// X window type. Maps directly to
|
|
||||||
/// [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/1.3/ar01s05.html).
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
|
||||||
pub enum WindowType {
|
|
||||||
/// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the
|
|
||||||
/// screen, allowing the desktop environment to have full control of the desktop, without the need for proxying
|
|
||||||
/// root window clicks.
|
|
||||||
Desktop,
|
|
||||||
/// A dock or panel feature. Typically a Window Manager would keep such windows on top of all other windows.
|
|
||||||
Dock,
|
|
||||||
/// Toolbar windows. "Torn off" from the main application.
|
|
||||||
Toolbar,
|
|
||||||
/// Pinnable menu windows. "Torn off" from the main application.
|
|
||||||
Menu,
|
|
||||||
/// A small persistent utility window, such as a palette or toolbox.
|
|
||||||
Utility,
|
|
||||||
/// The window is a splash screen displayed as an application is starting up.
|
|
||||||
Splash,
|
|
||||||
/// This is a dialog window.
|
|
||||||
Dialog,
|
|
||||||
/// This is a normal, top-level window.
|
|
||||||
Normal,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for WindowType {
|
|
||||||
fn default() -> Self {
|
|
||||||
WindowType::Normal
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowType {
|
|
||||||
pub(crate) fn as_atom(&self, xconn: &Arc<XConnection>) -> ffi::Atom {
|
|
||||||
use self::WindowType::*;
|
|
||||||
let atom_name: &[u8] = match self {
|
|
||||||
&Desktop => b"_NET_WM_WINDOW_TYPE_DESKTOP\0",
|
|
||||||
&Dock => b"_NET_WM_WINDOW_TYPE_DOCK\0",
|
|
||||||
&Toolbar => b"_NET_WM_WINDOW_TYPE_TOOLBAR\0",
|
|
||||||
&Menu => b"_NET_WM_WINDOW_TYPE_MENU\0",
|
|
||||||
&Utility => b"_NET_WM_WINDOW_TYPE_UTILITY\0",
|
|
||||||
&Splash => b"_NET_WM_WINDOW_TYPE_SPLASH\0",
|
|
||||||
&Dialog => b"_NET_WM_WINDOW_TYPE_DIALOG\0",
|
|
||||||
&Normal => b"_NET_WM_WINDOW_TYPE_NORMAL\0",
|
|
||||||
};
|
|
||||||
unsafe { xconn.get_atom_unchecked(atom_name) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct NormalHints<'a> {
|
|
||||||
size_hints: XSmartPointer<'a, ffi::XSizeHints>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> NormalHints<'a> {
|
|
||||||
pub fn new(xconn: &'a XConnection) -> Self {
|
|
||||||
NormalHints { size_hints: xconn.alloc_size_hints() }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn has_flag(&self, flag: c_long) -> bool {
|
|
||||||
has_flag(self.size_hints.flags, flag)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn getter(&self, flag: c_long, field1: &c_int, field2: &c_int) -> Option<(u32, u32)> {
|
|
||||||
if self.has_flag(flag) {
|
|
||||||
Some((*field1 as _, *field2 as _))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_size(&self) -> Option<(u32, u32)> {
|
|
||||||
self.getter(ffi::PSize, &self.size_hints.width, &self.size_hints.height)
|
|
||||||
}
|
|
||||||
|
|
||||||
// WARNING: This hint is obsolete
|
|
||||||
pub fn set_size(&mut self, size: Option<(u32, u32)>) {
|
|
||||||
if let Some((width, height)) = size {
|
|
||||||
self.size_hints.flags |= ffi::PSize;
|
|
||||||
self.size_hints.width = width as c_int;
|
|
||||||
self.size_hints.height = height as c_int;
|
|
||||||
} else {
|
|
||||||
self.size_hints.flags &= !ffi::PSize;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_max_size(&self) -> Option<(u32, u32)> {
|
|
||||||
self.getter(ffi::PMaxSize, &self.size_hints.max_width, &self.size_hints.max_height)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_max_size(&mut self, max_size: Option<(u32, u32)>) {
|
|
||||||
if let Some((max_width, max_height)) = max_size {
|
|
||||||
self.size_hints.flags |= ffi::PMaxSize;
|
|
||||||
self.size_hints.max_width = max_width as c_int;
|
|
||||||
self.size_hints.max_height = max_height as c_int;
|
|
||||||
} else {
|
|
||||||
self.size_hints.flags &= !ffi::PMaxSize;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_min_size(&self) -> Option<(u32, u32)> {
|
|
||||||
self.getter(ffi::PMinSize, &self.size_hints.min_width, &self.size_hints.min_height)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_min_size(&mut self, min_size: Option<(u32, u32)>) {
|
|
||||||
if let Some((min_width, min_height)) = min_size {
|
|
||||||
self.size_hints.flags |= ffi::PMinSize;
|
|
||||||
self.size_hints.min_width = min_width as c_int;
|
|
||||||
self.size_hints.min_height = min_height as c_int;
|
|
||||||
} else {
|
|
||||||
self.size_hints.flags &= !ffi::PMinSize;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_resize_increments(&self) -> Option<(u32, u32)> {
|
|
||||||
self.getter(ffi::PResizeInc, &self.size_hints.width_inc, &self.size_hints.height_inc)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_resize_increments(&mut self, resize_increments: Option<(u32, u32)>) {
|
|
||||||
if let Some((width_inc, height_inc)) = resize_increments {
|
|
||||||
self.size_hints.flags |= ffi::PResizeInc;
|
|
||||||
self.size_hints.width_inc = width_inc as c_int;
|
|
||||||
self.size_hints.height_inc = height_inc as c_int;
|
|
||||||
} else {
|
|
||||||
self.size_hints.flags &= !ffi::PResizeInc;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_base_size(&self) -> Option<(u32, u32)> {
|
|
||||||
self.getter(ffi::PBaseSize, &self.size_hints.base_width, &self.size_hints.base_height)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_base_size(&mut self, base_size: Option<(u32, u32)>) {
|
|
||||||
if let Some((base_width, base_height)) = base_size {
|
|
||||||
self.size_hints.flags |= ffi::PBaseSize;
|
|
||||||
self.size_hints.base_width = base_width as c_int;
|
|
||||||
self.size_hints.base_height = base_height as c_int;
|
|
||||||
} else {
|
|
||||||
self.size_hints.flags &= !ffi::PBaseSize;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl XConnection {
|
|
||||||
pub fn get_wm_hints(&self, window: ffi::Window) -> Result<XSmartPointer<ffi::XWMHints>, XError> {
|
|
||||||
let wm_hints = unsafe { (self.xlib.XGetWMHints)(self.display, window) };
|
|
||||||
self.check_errors()?;
|
|
||||||
let wm_hints = if wm_hints.is_null() {
|
|
||||||
self.alloc_wm_hints()
|
|
||||||
} else {
|
|
||||||
XSmartPointer::new(self, wm_hints).unwrap()
|
|
||||||
};
|
|
||||||
Ok(wm_hints)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_wm_hints(&self, window: ffi::Window, wm_hints: XSmartPointer<ffi::XWMHints>) -> Flusher {
|
|
||||||
unsafe {
|
|
||||||
(self.xlib.XSetWMHints)(
|
|
||||||
self.display,
|
|
||||||
window,
|
|
||||||
wm_hints.ptr,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Flusher::new(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_normal_hints(&self, window: ffi::Window) -> Result<NormalHints, XError> {
|
|
||||||
let size_hints = self.alloc_size_hints();
|
|
||||||
let mut supplied_by_user: c_long = unsafe { mem::uninitialized() };
|
|
||||||
unsafe {
|
|
||||||
(self.xlib.XGetWMNormalHints)(
|
|
||||||
self.display,
|
|
||||||
window,
|
|
||||||
size_hints.ptr,
|
|
||||||
&mut supplied_by_user,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
self.check_errors().map(|_| NormalHints { size_hints })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_normal_hints(&self, window: ffi::Window, normal_hints: NormalHints) -> Flusher {
|
|
||||||
unsafe {
|
|
||||||
(self.xlib.XSetWMNormalHints)(
|
|
||||||
self.display,
|
|
||||||
window,
|
|
||||||
normal_hints.size_hints.ptr,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Flusher::new(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,159 +0,0 @@
|
|||||||
use std::str;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use events::ModifiersState;
|
|
||||||
|
|
||||||
pub const VIRTUAL_CORE_POINTER: c_int = 2;
|
|
||||||
pub const VIRTUAL_CORE_KEYBOARD: c_int = 3;
|
|
||||||
|
|
||||||
// A base buffer size of 1kB uses a negligible amount of RAM while preventing us from having to
|
|
||||||
// re-allocate (and make another round-trip) in the *vast* majority of cases.
|
|
||||||
// To test if `lookup_utf8` works correctly, set this to 1.
|
|
||||||
const TEXT_BUFFER_SIZE: usize = 1024;
|
|
||||||
|
|
||||||
impl From<ffi::XIModifierState> for ModifiersState {
|
|
||||||
fn from(mods: ffi::XIModifierState) -> Self {
|
|
||||||
let state = mods.effective as c_uint;
|
|
||||||
ModifiersState {
|
|
||||||
alt: state & ffi::Mod1Mask != 0,
|
|
||||||
shift: state & ffi::ShiftMask != 0,
|
|
||||||
ctrl: state & ffi::ControlMask != 0,
|
|
||||||
logo: state & ffi::Mod4Mask != 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct PointerState<'a> {
|
|
||||||
xconn: &'a XConnection,
|
|
||||||
root: ffi::Window,
|
|
||||||
child: ffi::Window,
|
|
||||||
pub root_x: c_double,
|
|
||||||
pub root_y: c_double,
|
|
||||||
win_x: c_double,
|
|
||||||
win_y: c_double,
|
|
||||||
buttons: ffi::XIButtonState,
|
|
||||||
modifiers: ffi::XIModifierState,
|
|
||||||
group: ffi::XIGroupState,
|
|
||||||
relative_to_window: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> PointerState<'a> {
|
|
||||||
pub fn get_modifier_state(&self) -> ModifiersState {
|
|
||||||
self.modifiers.into()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Drop for PointerState<'a> {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
if !self.buttons.mask.is_null() {
|
|
||||||
unsafe {
|
|
||||||
// This is why you need to read the docs carefully...
|
|
||||||
(self.xconn.xlib.XFree)(self.buttons.mask as _);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl XConnection {
|
|
||||||
pub fn select_xinput_events(&self, window: c_ulong, device_id: c_int, mask: i32) -> Flusher {
|
|
||||||
let mut event_mask = ffi::XIEventMask {
|
|
||||||
deviceid: device_id,
|
|
||||||
mask: &mask as *const _ as *mut c_uchar,
|
|
||||||
mask_len: mem::size_of_val(&mask) as c_int,
|
|
||||||
};
|
|
||||||
unsafe {
|
|
||||||
(self.xinput2.XISelectEvents)(
|
|
||||||
self.display,
|
|
||||||
window,
|
|
||||||
&mut event_mask as *mut ffi::XIEventMask,
|
|
||||||
1, // number of masks to read from pointer above
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Flusher::new(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn select_xkb_events(&self, device_id: c_uint, mask: c_ulong) -> Option<Flusher> {
|
|
||||||
let status = unsafe {
|
|
||||||
(self.xlib.XkbSelectEvents)(
|
|
||||||
self.display,
|
|
||||||
device_id,
|
|
||||||
mask,
|
|
||||||
mask,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
if status == ffi::True {
|
|
||||||
Some(Flusher::new(self))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn query_pointer(&self, window: ffi::Window, device_id: c_int) -> Result<PointerState, XError> {
|
|
||||||
unsafe {
|
|
||||||
let mut pointer_state: PointerState = mem::uninitialized();
|
|
||||||
pointer_state.xconn = self;
|
|
||||||
pointer_state.relative_to_window = (self.xinput2.XIQueryPointer)(
|
|
||||||
self.display,
|
|
||||||
device_id,
|
|
||||||
window,
|
|
||||||
&mut pointer_state.root,
|
|
||||||
&mut pointer_state.child,
|
|
||||||
&mut pointer_state.root_x,
|
|
||||||
&mut pointer_state.root_y,
|
|
||||||
&mut pointer_state.win_x,
|
|
||||||
&mut pointer_state.win_y,
|
|
||||||
&mut pointer_state.buttons,
|
|
||||||
&mut pointer_state.modifiers,
|
|
||||||
&mut pointer_state.group,
|
|
||||||
) == ffi::True;
|
|
||||||
if let Err(err) = self.check_errors() {
|
|
||||||
// Running the destrutor would be bad news for us...
|
|
||||||
mem::forget(pointer_state);
|
|
||||||
Err(err)
|
|
||||||
} else {
|
|
||||||
Ok(pointer_state)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn lookup_utf8_inner(
|
|
||||||
&self,
|
|
||||||
ic: ffi::XIC,
|
|
||||||
key_event: &mut ffi::XKeyEvent,
|
|
||||||
buffer: &mut [u8],
|
|
||||||
) -> (ffi::KeySym, ffi::Status, c_int) {
|
|
||||||
let mut keysym: ffi::KeySym = 0;
|
|
||||||
let mut status: ffi::Status = 0;
|
|
||||||
let count = unsafe {
|
|
||||||
(self.xlib.Xutf8LookupString)(
|
|
||||||
ic,
|
|
||||||
key_event,
|
|
||||||
buffer.as_mut_ptr() as *mut c_char,
|
|
||||||
buffer.len() as c_int,
|
|
||||||
&mut keysym,
|
|
||||||
&mut status,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
(keysym, status, count)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn lookup_utf8(&self, ic: ffi::XIC, key_event: &mut ffi::XKeyEvent) -> String {
|
|
||||||
let mut buffer: [u8; TEXT_BUFFER_SIZE] = unsafe { mem::uninitialized() };
|
|
||||||
let (_, status, count) = self.lookup_utf8_inner(ic, key_event, &mut buffer);
|
|
||||||
// The buffer overflowed, so we'll make a new one on the heap.
|
|
||||||
if status == ffi::XBufferOverflow {
|
|
||||||
let mut buffer = Vec::with_capacity(count as usize);
|
|
||||||
unsafe { buffer.set_len(count as usize) };
|
|
||||||
let (_, _, new_count) = self.lookup_utf8_inner(ic, key_event, &mut buffer);
|
|
||||||
debug_assert_eq!(count, new_count);
|
|
||||||
str::from_utf8(&buffer[..count as usize])
|
|
||||||
.unwrap_or("")
|
|
||||||
.to_string()
|
|
||||||
} else {
|
|
||||||
str::from_utf8(&buffer[..count as usize])
|
|
||||||
.unwrap_or("")
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
use std::{env, slice};
|
|
||||||
use std::str::FromStr;
|
|
||||||
|
|
||||||
use validate_hidpi_factor;
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
pub fn calc_dpi_factor(
|
|
||||||
(width_px, height_px): (u32, u32),
|
|
||||||
(width_mm, height_mm): (u64, u64),
|
|
||||||
) -> f64 {
|
|
||||||
// Override DPI if `WINIT_HIDPI_FACTOR` variable is set
|
|
||||||
let dpi_override = env::var("WINIT_HIDPI_FACTOR")
|
|
||||||
.ok()
|
|
||||||
.and_then(|var| f64::from_str(&var).ok());
|
|
||||||
if let Some(dpi_override) = dpi_override {
|
|
||||||
if !validate_hidpi_factor(dpi_override) {
|
|
||||||
panic!(
|
|
||||||
"`WINIT_HIDPI_FACTOR` invalid; DPI factors must be normal floats greater than 0. Got `{}`",
|
|
||||||
dpi_override,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return dpi_override;
|
|
||||||
}
|
|
||||||
|
|
||||||
// See http://xpra.org/trac/ticket/728 for more information.
|
|
||||||
if width_mm == 0 || width_mm == 0 {
|
|
||||||
warn!("XRandR reported that the display's 0mm in size, which is certifiably insane");
|
|
||||||
return 1.0;
|
|
||||||
}
|
|
||||||
|
|
||||||
let ppmm = (
|
|
||||||
(width_px as f64 * height_px as f64) / (width_mm as f64 * height_mm as f64)
|
|
||||||
).sqrt();
|
|
||||||
// Quantize 1/12 step size
|
|
||||||
let dpi_factor = ((ppmm * (12.0 * 25.4 / 96.0)).round() / 12.0).max(1.0);
|
|
||||||
assert!(validate_hidpi_factor(dpi_factor));
|
|
||||||
dpi_factor
|
|
||||||
}
|
|
||||||
|
|
||||||
pub enum MonitorRepr {
|
|
||||||
Monitor(*mut ffi::XRRMonitorInfo),
|
|
||||||
Crtc(*mut ffi::XRRCrtcInfo),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorRepr {
|
|
||||||
pub unsafe fn get_output(&self) -> ffi::RROutput {
|
|
||||||
match *self {
|
|
||||||
// Same member names, but different locations within the struct...
|
|
||||||
MonitorRepr::Monitor(monitor) => *((*monitor).outputs.offset(0)),
|
|
||||||
MonitorRepr::Crtc(crtc) => *((*crtc).outputs.offset(0)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe fn get_dimensions(&self) -> (u32, u32) {
|
|
||||||
match *self {
|
|
||||||
MonitorRepr::Monitor(monitor) => ((*monitor).width as u32, (*monitor).height as u32),
|
|
||||||
MonitorRepr::Crtc(crtc) => ((*crtc).width as u32, (*crtc).height as u32),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe fn get_position(&self) -> (i32, i32) {
|
|
||||||
match *self {
|
|
||||||
MonitorRepr::Monitor(monitor) => ((*monitor).x as i32, (*monitor).y as i32),
|
|
||||||
MonitorRepr::Crtc(crtc) => ((*crtc).x as i32, (*crtc).y as i32),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<*mut ffi::XRRMonitorInfo> for MonitorRepr {
|
|
||||||
fn from(monitor: *mut ffi::XRRMonitorInfo) -> Self {
|
|
||||||
MonitorRepr::Monitor(monitor)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<*mut ffi::XRRCrtcInfo> for MonitorRepr {
|
|
||||||
fn from(crtc: *mut ffi::XRRCrtcInfo) -> Self {
|
|
||||||
MonitorRepr::Crtc(crtc)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl XConnection {
|
|
||||||
pub unsafe fn get_output_info(&self, resources: *mut ffi::XRRScreenResources, repr: &MonitorRepr) -> (String, f64) {
|
|
||||||
let output_info = (self.xrandr.XRRGetOutputInfo)(
|
|
||||||
self.display,
|
|
||||||
resources,
|
|
||||||
repr.get_output(),
|
|
||||||
);
|
|
||||||
let name_slice = slice::from_raw_parts(
|
|
||||||
(*output_info).name as *mut u8,
|
|
||||||
(*output_info).nameLen as usize,
|
|
||||||
);
|
|
||||||
let name = String::from_utf8_lossy(name_slice).into();
|
|
||||||
let hidpi_factor = calc_dpi_factor(
|
|
||||||
repr.get_dimensions(),
|
|
||||||
((*output_info).mm_width as u64, (*output_info).mm_height as u64),
|
|
||||||
);
|
|
||||||
(self.xrandr.XRRFreeOutputInfo)(output_info);
|
|
||||||
(name, hidpi_factor)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,144 +0,0 @@
|
|||||||
use std;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
pub type Cardinal = c_long;
|
|
||||||
pub const CARDINAL_SIZE: usize = mem::size_of::<c_long>();
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub enum GetPropertyError {
|
|
||||||
XError(XError),
|
|
||||||
TypeMismatch(ffi::Atom),
|
|
||||||
FormatMismatch(c_int),
|
|
||||||
NothingAllocated,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GetPropertyError {
|
|
||||||
pub fn is_actual_property_type(&self, t: ffi::Atom) -> bool {
|
|
||||||
if let GetPropertyError::TypeMismatch(actual_type) = *self {
|
|
||||||
actual_type == t
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Number of 32-bit chunks to retrieve per iteration of get_property's inner loop.
|
|
||||||
// To test if `get_property` works correctly, set this to 1.
|
|
||||||
const PROPERTY_BUFFER_SIZE: c_long = 1024; // 4k of RAM ought to be enough for anyone!
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum PropMode {
|
|
||||||
Replace = ffi::PropModeReplace as isize,
|
|
||||||
Prepend = ffi::PropModePrepend as isize,
|
|
||||||
Append = ffi::PropModeAppend as isize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl XConnection {
|
|
||||||
pub fn get_property<T: Formattable>(
|
|
||||||
&self,
|
|
||||||
window: c_ulong,
|
|
||||||
property: ffi::Atom,
|
|
||||||
property_type: ffi::Atom,
|
|
||||||
) -> Result<Vec<T>, GetPropertyError> {
|
|
||||||
let mut data = Vec::new();
|
|
||||||
let mut offset = 0;
|
|
||||||
|
|
||||||
let mut done = false;
|
|
||||||
while !done {
|
|
||||||
unsafe {
|
|
||||||
let mut actual_type: ffi::Atom = mem::uninitialized();
|
|
||||||
let mut actual_format: c_int = mem::uninitialized();
|
|
||||||
let mut quantity_returned: c_ulong = mem::uninitialized();
|
|
||||||
let mut bytes_after: c_ulong = mem::uninitialized();
|
|
||||||
let mut buf: *mut c_uchar = ptr::null_mut();
|
|
||||||
(self.xlib.XGetWindowProperty)(
|
|
||||||
self.display,
|
|
||||||
window,
|
|
||||||
property,
|
|
||||||
// This offset is in terms of 32-bit chunks.
|
|
||||||
offset,
|
|
||||||
// This is the quanity of 32-bit chunks to receive at once.
|
|
||||||
PROPERTY_BUFFER_SIZE,
|
|
||||||
ffi::False,
|
|
||||||
property_type,
|
|
||||||
&mut actual_type,
|
|
||||||
&mut actual_format,
|
|
||||||
// This is the quantity of items we retrieved in our format, NOT of 32-bit chunks!
|
|
||||||
&mut quantity_returned,
|
|
||||||
// ...and this is a quantity of bytes. So, this function deals in 3 different units.
|
|
||||||
&mut bytes_after,
|
|
||||||
&mut buf,
|
|
||||||
);
|
|
||||||
|
|
||||||
if let Err(e) = self.check_errors() {
|
|
||||||
return Err(GetPropertyError::XError(e));
|
|
||||||
}
|
|
||||||
|
|
||||||
if actual_type != property_type {
|
|
||||||
return Err(GetPropertyError::TypeMismatch(actual_type));
|
|
||||||
}
|
|
||||||
|
|
||||||
let format_mismatch = Format::from_format(actual_format as _) != Some(T::FORMAT);
|
|
||||||
if format_mismatch {
|
|
||||||
return Err(GetPropertyError::FormatMismatch(actual_format));
|
|
||||||
}
|
|
||||||
|
|
||||||
if !buf.is_null() {
|
|
||||||
offset += PROPERTY_BUFFER_SIZE;
|
|
||||||
let new_data = std::slice::from_raw_parts(
|
|
||||||
buf as *mut T,
|
|
||||||
quantity_returned as usize,
|
|
||||||
);
|
|
||||||
/*println!(
|
|
||||||
"XGetWindowProperty prop:{:?} fmt:{:02} len:{:02} off:{:02} out:{:02}, buf:{:?}",
|
|
||||||
property,
|
|
||||||
mem::size_of::<T>() * 8,
|
|
||||||
data.len(),
|
|
||||||
offset,
|
|
||||||
quantity_returned,
|
|
||||||
new_data,
|
|
||||||
);*/
|
|
||||||
data.extend_from_slice(&new_data);
|
|
||||||
// Fun fact: XGetWindowProperty allocates one extra byte at the end.
|
|
||||||
(self.xlib.XFree)(buf as _); // Don't try to access new_data after this.
|
|
||||||
} else {
|
|
||||||
return Err(GetPropertyError::NothingAllocated);
|
|
||||||
}
|
|
||||||
|
|
||||||
done = bytes_after == 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn change_property<'a, T: Formattable>(
|
|
||||||
&'a self,
|
|
||||||
window: c_ulong,
|
|
||||||
property: ffi::Atom,
|
|
||||||
property_type: ffi::Atom,
|
|
||||||
mode: PropMode,
|
|
||||||
new_value: &[T],
|
|
||||||
) -> Flusher<'a> {
|
|
||||||
debug_assert_eq!(mem::size_of::<T>(), T::FORMAT.get_actual_size());
|
|
||||||
unsafe {
|
|
||||||
(self.xlib.XChangeProperty)(
|
|
||||||
self.display,
|
|
||||||
window,
|
|
||||||
property,
|
|
||||||
property_type,
|
|
||||||
T::FORMAT as c_int,
|
|
||||||
mode as c_int,
|
|
||||||
new_value.as_ptr() as *const c_uchar,
|
|
||||||
new_value.len() as c_int,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
/*println!(
|
|
||||||
"XChangeProperty prop:{:?} val:{:?}",
|
|
||||||
property,
|
|
||||||
new_value,
|
|
||||||
);*/
|
|
||||||
Flusher::new(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||