Compare commits
1468 Commits
v0.13.0
...
madsmtm/ch
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d7b6f0c63d | ||
|
|
f40f87ff12 | ||
|
|
aa3127e460 | ||
|
|
295a789c42 | ||
|
|
a63b04385a | ||
|
|
06f4e28de9 | ||
|
|
249d5d8bff | ||
|
|
66df2c22ba | ||
|
|
359a38844b | ||
|
|
563b0bf5e3 | ||
|
|
b2f9fad654 | ||
|
|
4ade1a7518 | ||
|
|
e06ecf4d72 | ||
|
|
4a8050289d | ||
|
|
99e238065e | ||
|
|
d123cd2f8e | ||
|
|
fc8a008b25 | ||
|
|
f6f1c45a72 | ||
|
|
388c40b1e0 | ||
|
|
7a40aa43dc | ||
|
|
944347696a | ||
|
|
96172693fe | ||
|
|
32004405ee | ||
|
|
22e932b5ab | ||
|
|
3d4c53459a | ||
|
|
f0b4889227 | ||
|
|
c81448e0b8 | ||
|
|
f498ff0369 | ||
|
|
c4e6e94b80 | ||
|
|
a5dbd3ee52 | ||
|
|
a4480a0652 | ||
|
|
e41f0eabb1 | ||
|
|
7e28d7615e | ||
|
|
010787a430 | ||
|
|
352e70b8ac | ||
|
|
990bbf178f | ||
|
|
97cfdd4b09 | ||
|
|
a127bd6f66 | ||
|
|
4a8648be57 | ||
|
|
a8c7109e89 | ||
|
|
7abd427216 | ||
|
|
3fb93b4f83 | ||
|
|
19190a95a0 | ||
|
|
c4310af83c | ||
|
|
542d1938ce | ||
|
|
31f8b816bd | ||
|
|
e61a7320a2 | ||
|
|
db41938deb | ||
|
|
2bc1943188 | ||
|
|
385c4b3c88 | ||
|
|
ea70f773d3 | ||
|
|
83012f4c1c | ||
|
|
6825fed073 | ||
|
|
273984a385 | ||
|
|
dbe0f852da | ||
|
|
d1902aa15a | ||
|
|
4112fccc12 | ||
|
|
bd6ce32860 | ||
|
|
8936fe1acd | ||
|
|
fedb86ea5a | ||
|
|
20687fef1c | ||
|
|
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 | ||
|
|
a32f7f2ec5 | ||
|
|
e8e9fa2418 | ||
|
|
1a119bdfe9 | ||
|
|
21ff2e0ffc | ||
|
|
df9b23c96a | ||
|
|
4c117aa282 | ||
|
|
88427262a6 | ||
|
|
72b24a9348 | ||
|
|
01cb8e59e3 | ||
|
|
3910326709 | ||
|
|
7ee46d80e6 | ||
|
|
0cb5450999 | ||
|
|
8c78013257 | ||
|
|
bd944898f0 | ||
|
|
c1ef1acfc0 | ||
|
|
040d3f5d8b | ||
|
|
ec393e4a90 | ||
|
|
1703d0417a | ||
|
|
fad72c0441 | ||
|
|
2f7321a076 | ||
|
|
85ee422acd | ||
|
|
089816d9ba | ||
|
|
c873c2db15 | ||
|
|
047c67baf3 | ||
|
|
8f394f117b | ||
|
|
fb7528c239 | ||
|
|
042f5fe4b3 | ||
|
|
289fb47a34 | ||
|
|
38bc6babb7 | ||
|
|
e7a8efcfa0 | ||
|
|
1b74822cfc | ||
|
|
f083dae328 | ||
|
|
23c384bd30 | ||
|
|
ced1616e51 | ||
|
|
233ac4aed2 | ||
|
|
be5a2b0e87 | ||
|
|
2b4b64f499 | ||
|
|
262490d074 | ||
|
|
8891cfd85e | ||
|
|
2cc8fa1eac | ||
|
|
79aebf06dc | ||
|
|
19dd961752 | ||
|
|
bf413ecb83 | ||
|
|
fd1a3eda1c | ||
|
|
0e2488db32 | ||
|
|
58a00bffbb | ||
|
|
bbfe57400d | ||
|
|
4372f6fdac | ||
|
|
30f798b246 | ||
|
|
282770f11a | ||
|
|
17373a4e91 | ||
|
|
a34147b602 | ||
|
|
cebd15bfd1 | ||
|
|
f51f7c0ca8 | ||
|
|
f6d26df64d | ||
|
|
fddfb2e2d6 | ||
|
|
dec728cfa2 | ||
|
|
8440091a4e | ||
|
|
2464a135b3 | ||
|
|
87fa120ebb | ||
|
|
d86f53a02c | ||
|
|
15a4fec3d9 | ||
|
|
1819be1173 | ||
|
|
ffa9b51d27 | ||
|
|
b4a8c08f43 | ||
|
|
741bcc4672 | ||
|
|
e48f1fc5f1 | ||
|
|
374f131f1e | ||
|
|
363261077f | ||
|
|
102dd07456 | ||
|
|
1e97103094 | ||
|
|
cc8907b956 | ||
|
|
c4b92ebd45 | ||
|
|
fee874b5b7 | ||
|
|
eba888207e | ||
|
|
ea28791da6 | ||
|
|
fe2d37fcdc | ||
|
|
3407a8dd78 | ||
|
|
5761fb6b30 | ||
|
|
7aeb2c083b | ||
|
|
8f47fdbe67 | ||
|
|
2ea42b3947 | ||
|
|
7510b95d8c |
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
|
||||||
5
.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
- [ ] Tested on all platforms changed
|
||||||
|
- [ ] 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
|
||||||
|
- [ ] 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
|
||||||
24
.github/workflows/check-commit-msg.yml
vendored
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
name: Check Commit Messages
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
length:
|
||||||
|
name: Check that length of commit messages are <72 characters
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Fetch branch data from origin
|
||||||
|
run: git fetch origin
|
||||||
|
- run: |
|
||||||
|
COMMIT_MESSAGES=$(git log --combined --format=%s origin/$GITHUB_BASE_REF..HEAD)
|
||||||
|
echo $COMMIT_MESSAGES
|
||||||
|
for MESSAGE in $COMMIT_MESSAGES; do
|
||||||
|
LENGTH=$(echo $MESSAGE | wc -c)
|
||||||
|
if [ $LENGTH -gt 72 ]; then
|
||||||
|
echo "Commit message \"$MESSAGE\" is too long ($LENGTH characters). Please keep commit messages under 72 characters."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
228
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,228 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
typos:
|
||||||
|
name: Check for typos
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 30
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: taiki-e/install-action@v2
|
||||||
|
with:
|
||||||
|
tool: typos-cli
|
||||||
|
- name: run typos
|
||||||
|
run: typos
|
||||||
|
- name: Typos info
|
||||||
|
if: failure()
|
||||||
|
run: |
|
||||||
|
echo 'To fix typos, please run `typos -w`'
|
||||||
|
echo 'To check for a diff, run `typos`'
|
||||||
|
echo 'You can find typos here: https://crates.io/crates/typos'
|
||||||
|
|
||||||
|
tests:
|
||||||
|
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
|
||||||
|
|
||||||
|
# Test only on Linux x86_64, so we avoid spending unnecessary CI hours.
|
||||||
|
- name: Test dpi crate
|
||||||
|
if: >
|
||||||
|
contains(matrix.platform.name, 'Linux 64bit') &&
|
||||||
|
matrix.toolchain != '1.70.0'
|
||||||
|
run: cargo test -p dpi
|
||||||
|
|
||||||
|
- 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
|
||||||
6
.gitignore
vendored
@@ -1,4 +1,10 @@
|
|||||||
Cargo.lock
|
Cargo.lock
|
||||||
target/
|
target/
|
||||||
|
rls/
|
||||||
|
.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
|
|
||||||
60
.travis.yml
@@ -1,60 +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
|
|
||||||
|
|
||||||
# Linux 64bit
|
|
||||||
- env: TARGET=x86_64-unknown-linux-gnu
|
|
||||||
os: linux
|
|
||||||
rust: nightly
|
|
||||||
- env: TARGET=x86_64-unknown-linux-gnu
|
|
||||||
os: linux
|
|
||||||
rust: stable
|
|
||||||
|
|
||||||
# macOS
|
|
||||||
- env: TARGET=x86_64-apple-darwin
|
|
||||||
os: osx
|
|
||||||
rust: nightly
|
|
||||||
- env: TARGET=x86_64-apple-darwin
|
|
||||||
os: osx
|
|
||||||
rust: stable
|
|
||||||
|
|
||||||
# iOS
|
|
||||||
- env: TARGET=x86_64-apple-ios
|
|
||||||
os: osx
|
|
||||||
rust: nightly
|
|
||||||
- env: TARGET=x86_64-apple-ios
|
|
||||||
os: osx
|
|
||||||
rust: stable
|
|
||||||
|
|
||||||
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}
|
|
||||||
1184
CHANGELOG.md
6
CODE_OF_CONDUCT.md
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
# Code of Conduct
|
||||||
|
|
||||||
|
The `rust-windowing` project adheres to the [Rust Code of Conduct]. This
|
||||||
|
describes the minimum behavior expected from all contributors.
|
||||||
|
|
||||||
|
[Rust Code of Conduct]: https://www.rust-lang.org/policies/code-of-conduct
|
||||||
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
|
||||||
296
Cargo.toml
@@ -1,52 +1,278 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "winit"
|
name = "winit"
|
||||||
version = "0.13.0"
|
version = "0.29.15"
|
||||||
authors = ["The winit contributors, Pierre Krieger <pierre.krieger1708@gmail.com>"]
|
authors = ["The winit contributors", "Pierre Krieger <pierre.krieger1708@gmail.com>"]
|
||||||
description = "Cross-platform window creation library."
|
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]
|
||||||
|
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]
|
||||||
|
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"
|
||||||
|
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" }
|
||||||
|
tracing = { version = "0.1.40", default_features = false }
|
||||||
|
|
||||||
[target.'cfg(target_os = "android")'.dependencies.android_glue]
|
[dev-dependencies]
|
||||||
version = "0.2"
|
image = { version = "0.24.0", default-features = false, features = ["png"] }
|
||||||
|
tracing = { version = "0.1.40", default_features = false, features = ["log"] }
|
||||||
|
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
|
||||||
|
winit = { path = ".", features = ["rwh_05"] }
|
||||||
|
|
||||||
[target.'cfg(target_os = "ios")'.dependencies]
|
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dev-dependencies]
|
||||||
objc = "0.2"
|
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"
|
core-graphics = "0.23.1"
|
||||||
cocoa = "0.14"
|
|
||||||
core-foundation = "0.5"
|
|
||||||
core-graphics = "0.13"
|
|
||||||
|
|
||||||
[target.'cfg(target_os = "windows")'.dependencies.winapi]
|
[target.'cfg(target_os = "macos")'.dependencies.icrate]
|
||||||
version = "0.3"
|
version = "0.1.0"
|
||||||
features = [
|
features = [
|
||||||
"winnt",
|
"dispatch",
|
||||||
"winuser",
|
"Foundation",
|
||||||
"wingdi",
|
"Foundation_NSArray",
|
||||||
"shellapi",
|
"Foundation_NSAttributedString",
|
||||||
"dwmapi",
|
"Foundation_NSMutableAttributedString",
|
||||||
"processthreadsapi",
|
"Foundation_NSData",
|
||||||
"libloaderapi",
|
"Foundation_NSDictionary",
|
||||||
"windowsx",
|
"Foundation_NSString",
|
||||||
"hidusage",
|
"Foundation_NSProcessInfo",
|
||||||
"combaseapi",
|
"Foundation_NSThread",
|
||||||
"objbase",
|
"Foundation_NSNumber",
|
||||||
"unknwnbase",
|
"AppKit",
|
||||||
|
"AppKit_NSAppearance",
|
||||||
|
"AppKit_NSApplication",
|
||||||
|
"AppKit_NSBitmapImageRep",
|
||||||
|
"AppKit_NSButton",
|
||||||
|
"AppKit_NSColor",
|
||||||
|
"AppKit_NSControl",
|
||||||
|
"AppKit_NSCursor",
|
||||||
|
"AppKit_NSEvent",
|
||||||
|
"AppKit_NSGraphicsContext",
|
||||||
|
"AppKit_NSImage",
|
||||||
|
"AppKit_NSImageRep",
|
||||||
|
"AppKit_NSMenu",
|
||||||
|
"AppKit_NSMenuItem",
|
||||||
|
"AppKit_NSPasteboard",
|
||||||
|
"AppKit_NSResponder",
|
||||||
|
"AppKit_NSScreen",
|
||||||
|
"AppKit_NSTextInputContext",
|
||||||
|
"AppKit_NSView",
|
||||||
|
"AppKit_NSWindow",
|
||||||
|
"AppKit_NSWindowTabGroup",
|
||||||
]
|
]
|
||||||
|
|
||||||
[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
|
[target.'cfg(target_os = "ios")'.dependencies.icrate]
|
||||||
wayland-client = { version = "0.12.0", features = ["dlopen"] }
|
version = "0.1.0"
|
||||||
wayland-protocols = { version = "0.12.0", features = ["unstable_protocols"] }
|
features = [
|
||||||
wayland-kbd = "0.13.0"
|
"dispatch",
|
||||||
wayland-window = "0.13.0"
|
"Foundation",
|
||||||
x11-dl = "2.17"
|
"Foundation_NSArray",
|
||||||
percent-encoding = "1.0"
|
"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.19.1", optional = true }
|
||||||
|
x11rb = { version = "0.13.0", default-features = false, features = ["allow-unsafe-code", "dl-libxcb", "randr", "resource_manager", "xinput", "xkb"], optional = true }
|
||||||
|
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 = "window"
|
||||||
|
|
||||||
|
[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.13"
|
winit = "0.29.15"
|
||||||
```
|
```
|
||||||
|
|
||||||
## [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.
|
|
||||||
|
|||||||
17
appveyor.yml
@@ -1,17 +0,0 @@
|
|||||||
environment:
|
|
||||||
matrix:
|
|
||||||
- TARGET: x86_64-pc-windows-msvc
|
|
||||||
- TARGET: i686-pc-windows-msvc
|
|
||||||
- TARGET: i686-pc-windows-gnu
|
|
||||||
install:
|
|
||||||
- ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe"
|
|
||||||
- rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust"
|
|
||||||
- SET PATH=%PATH%;C:\Program Files (x86)\Rust\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 |
16
dpi/CHANGELOG.md
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to this project will be documented in this file.
|
||||||
|
|
||||||
|
Please keep one empty line before and after all headers. (This is required for
|
||||||
|
`git` to produce a conflict when a release is made while a PR is open and the
|
||||||
|
PR's changelog entry would go into the wrong section).
|
||||||
|
|
||||||
|
And please only add new entries to the top of this list, right below the `#
|
||||||
|
Unreleased` header.
|
||||||
|
|
||||||
|
# Unreleased
|
||||||
|
|
||||||
|
# 0.1.0
|
||||||
|
|
||||||
|
- Add `LogicalUnit`, `PhysicalUnit` and `PixelUnit` types and related functions.
|
||||||
39
dpi/Cargo.toml
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
[package]
|
||||||
|
name = "dpi"
|
||||||
|
version = "0.1.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
|
||||||
1208
dpi/src/lib.rs
Normal file
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.");
|
||||||
|
}
|
||||||
147
examples/control_flow.rs
Normal file
@@ -0,0 +1,147 @@
|
|||||||
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
|
use std::thread;
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
use std::time;
|
||||||
|
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
use web_time as time;
|
||||||
|
|
||||||
|
use winit::application::ApplicationHandler;
|
||||||
|
use winit::event::{ElementState, KeyEvent, StartCause, WindowEvent};
|
||||||
|
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||||
|
use winit::keyboard::{Key, NamedKey};
|
||||||
|
use winit::window::{Window, WindowId};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
const WAIT_TIME: time::Duration = time::Duration::from_millis(100);
|
||||||
|
const POLL_SLEEP_TIME: time::Duration = time::Duration::from_millis(100);
|
||||||
|
|
||||||
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum Mode {
|
||||||
|
#[default]
|
||||||
|
Wait,
|
||||||
|
WaitUntil,
|
||||||
|
Poll,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<(), impl std::error::Error> {
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
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 app = ControlFlowDemo::default();
|
||||||
|
event_loop.run_app(&mut app)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct ControlFlowDemo {
|
||||||
|
mode: Mode,
|
||||||
|
request_redraw: bool,
|
||||||
|
wait_cancelled: bool,
|
||||||
|
close_requested: bool,
|
||||||
|
window: Option<Window>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for ControlFlowDemo {
|
||||||
|
fn new_events(&mut self, _event_loop: &ActiveEventLoop, cause: StartCause) {
|
||||||
|
println!("new_events: {cause:?}");
|
||||||
|
|
||||||
|
self.wait_cancelled = match cause {
|
||||||
|
StartCause::WaitCancelled { .. } => self.mode == Mode::WaitUntil,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
let window_attributes = Window::default_attributes().with_title(
|
||||||
|
"Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.",
|
||||||
|
);
|
||||||
|
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
_event_loop: &ActiveEventLoop,
|
||||||
|
_window_id: WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
println!("{event:?}");
|
||||||
|
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
self.close_requested = true;
|
||||||
|
}
|
||||||
|
WindowEvent::KeyboardInput {
|
||||||
|
event:
|
||||||
|
KeyEvent {
|
||||||
|
logical_key: key,
|
||||||
|
state: ElementState::Pressed,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
..
|
||||||
|
} => match key.as_ref() {
|
||||||
|
// WARNING: Consider using `key_without_modifiers()` if available on your platform.
|
||||||
|
// See the `key_binding` example
|
||||||
|
Key::Character("1") => {
|
||||||
|
self.mode = Mode::Wait;
|
||||||
|
println!("\nmode: {:?}\n", self.mode);
|
||||||
|
}
|
||||||
|
Key::Character("2") => {
|
||||||
|
self.mode = Mode::WaitUntil;
|
||||||
|
println!("\nmode: {:?}\n", self.mode);
|
||||||
|
}
|
||||||
|
Key::Character("3") => {
|
||||||
|
self.mode = Mode::Poll;
|
||||||
|
println!("\nmode: {:?}\n", self.mode);
|
||||||
|
}
|
||||||
|
Key::Character("r") => {
|
||||||
|
self.request_redraw = !self.request_redraw;
|
||||||
|
println!("\nrequest_redraw: {}\n", self.request_redraw);
|
||||||
|
}
|
||||||
|
Key::Named(NamedKey::Escape) => {
|
||||||
|
self.close_requested = true;
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
},
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
let window = self.window.as_ref().unwrap();
|
||||||
|
window.pre_present_notify();
|
||||||
|
fill::fill_window(window);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
if self.request_redraw && !self.wait_cancelled && !self.close_requested {
|
||||||
|
self.window.as_ref().unwrap().request_redraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
match self.mode {
|
||||||
|
Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
|
||||||
|
Mode::WaitUntil => {
|
||||||
|
if !self.wait_cancelled {
|
||||||
|
event_loop
|
||||||
|
.set_control_flow(ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Mode::Poll => {
|
||||||
|
thread::sleep(POLL_SLEEP_TIME);
|
||||||
|
event_loop.set_control_flow(ControlFlow::Poll);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if self.close_requested {
|
||||||
|
event_loop.exit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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::NoneCursor, 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
|
|
||||||
});
|
|
||||||
}
|
|
||||||
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 |
BIN
examples/data/icon.png
Normal file
|
After Width: | Height: | Size: 2.9 KiB |
@@ -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,45 +0,0 @@
|
|||||||
extern crate winit;
|
|
||||||
|
|
||||||
use winit::{ControlFlow, WindowEvent, ElementState, KeyboardInput};
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut events_loop = winit::EventsLoop::new();
|
|
||||||
|
|
||||||
let window = winit::WindowBuilder::new().build(&events_loop).unwrap();
|
|
||||||
window.set_title("winit - Cursor grabbing test");
|
|
||||||
|
|
||||||
let mut grabbed = false;
|
|
||||||
|
|
||||||
events_loop.run_forever(|event| {
|
|
||||||
println!("{:?}", event);
|
|
||||||
|
|
||||||
match event {
|
|
||||||
winit::Event::WindowEvent { event, .. } => {
|
|
||||||
match event {
|
|
||||||
WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, .. }, .. } => {
|
|
||||||
if grabbed {
|
|
||||||
grabbed = false;
|
|
||||||
window.set_cursor_state(winit::CursorState::Normal)
|
|
||||||
.ok().expect("could not ungrab mouse cursor");
|
|
||||||
} else {
|
|
||||||
grabbed = true;
|
|
||||||
window.set_cursor_state(winit::CursorState::Grab)
|
|
||||||
.ok().expect("could not grab mouse cursor");
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
WindowEvent::CloseRequested => return ControlFlow::Break,
|
|
||||||
|
|
||||||
a @ WindowEvent::CursorMoved { .. } => {
|
|
||||||
println!("{:?}", a);
|
|
||||||
},
|
|
||||||
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
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,21 +0,0 @@
|
|||||||
extern crate winit;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut events_loop = winit::EventsLoop::new();
|
|
||||||
|
|
||||||
let window = winit::WindowBuilder::new()
|
|
||||||
.build(&events_loop)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
window.set_min_dimensions(Some((400, 200)));
|
|
||||||
window.set_max_dimensions(Some((800, 400)));
|
|
||||||
|
|
||||||
events_loop.run_forever(|event| {
|
|
||||||
println!("{:?}", event);
|
|
||||||
|
|
||||||
match event {
|
|
||||||
winit::Event::WindowEvent { event: winit::WindowEvent::CloseRequested, .. } => winit::ControlFlow::Break,
|
|
||||||
_ => winit::ControlFlow::Continue,
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -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,
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
84
examples/pump_events.rs
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
#![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 winit::application::ApplicationHandler;
|
||||||
|
use winit::event::WindowEvent;
|
||||||
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
|
use winit::platform::pump_events::{EventLoopExtPumpEvents, PumpStatus};
|
||||||
|
use winit::window::{Window, WindowId};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct PumpDemo {
|
||||||
|
window: Option<Window>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for PumpDemo {
|
||||||
|
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
let window_attributes = Window::default_attributes().with_title("A fantastic window!");
|
||||||
|
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &ActiveEventLoop,
|
||||||
|
_window_id: WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
println!("{event:?}");
|
||||||
|
|
||||||
|
let window = match self.window.as_ref() {
|
||||||
|
Some(window) => window,
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => event_loop.exit(),
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(window);
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
let mut app = PumpDemo::default();
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let timeout = Some(Duration::ZERO);
|
||||||
|
let status = event_loop.pump_app_events(timeout, &mut app);
|
||||||
|
|
||||||
|
if let PumpStatus::Exit(exit_code) = status {
|
||||||
|
break ExitCode::from(exit_code as u8);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sleep for 1/60 second to simulate application work
|
||||||
|
//
|
||||||
|
// Since `pump_events` doesn't block it will be important to
|
||||||
|
// throttle the loop in the app somehow.
|
||||||
|
println!("Update()");
|
||||||
|
sleep(Duration::from_millis(16));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(ios_platform, web_platform, orbital_platform))]
|
||||||
|
fn main() {
|
||||||
|
println!("This platform doesn't support pump_events.");
|
||||||
|
}
|
||||||
98
examples/run_on_demand.rs
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
#![allow(clippy::single_match)]
|
||||||
|
|
||||||
|
// Limit this example to only compatible platforms.
|
||||||
|
#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform,))]
|
||||||
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use winit::application::ApplicationHandler;
|
||||||
|
use winit::event::WindowEvent;
|
||||||
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
|
use winit::platform::run_on_demand::EventLoopExtRunOnDemand;
|
||||||
|
use winit::window::{Window, WindowId};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct App {
|
||||||
|
idx: usize,
|
||||||
|
window_id: Option<WindowId>,
|
||||||
|
window: Option<Window>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for App {
|
||||||
|
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
|
||||||
|
if let Some(window) = self.window.as_ref() {
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
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();
|
||||||
|
self.window_id = Some(window.id());
|
||||||
|
self.window = Some(window);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &ActiveEventLoop,
|
||||||
|
window_id: WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
if event == WindowEvent::Destroyed && self.window_id == Some(window_id) {
|
||||||
|
println!(
|
||||||
|
"--------------------------------------------------------- Window {} Destroyed",
|
||||||
|
self.idx
|
||||||
|
);
|
||||||
|
self.window_id = None;
|
||||||
|
event_loop.exit();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let window = match self.window.as_mut() {
|
||||||
|
Some(window) => window,
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
println!("--------------------------------------------------------- Window {} CloseRequested", self.idx);
|
||||||
|
fill::cleanup_window(window);
|
||||||
|
self.window = None;
|
||||||
|
}
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
fill::fill_window(window);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
let mut event_loop = EventLoop::new().unwrap();
|
||||||
|
|
||||||
|
let mut app = App {
|
||||||
|
idx: 1,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
event_loop.run_app_on_demand(&mut app)?;
|
||||||
|
|
||||||
|
println!("--------------------------------------------------------- Finished first loop");
|
||||||
|
println!("--------------------------------------------------------- Waiting 5 seconds");
|
||||||
|
std::thread::sleep(Duration::from_secs(5));
|
||||||
|
|
||||||
|
app.idx += 1;
|
||||||
|
event_loop.run_app_on_demand(&mut app)?;
|
||||||
|
println!("--------------------------------------------------------- Finished second loop");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(any(windows_platform, macos_platform, x11_platform, wayland_platform,)))]
|
||||||
|
fn main() {
|
||||||
|
println!("This example is not supported on this platform");
|
||||||
|
}
|
||||||
@@ -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 +1,984 @@
|
|||||||
extern crate winit;
|
//! Simple winit application.
|
||||||
|
|
||||||
fn main() {
|
use std::collections::HashMap;
|
||||||
let mut events_loop = winit::EventsLoop::new();
|
use std::error::Error;
|
||||||
|
use std::fmt;
|
||||||
|
use std::fmt::Debug;
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
use std::num::NonZeroU32;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
let _window = winit::WindowBuilder::new()
|
use cursor_icon::CursorIcon;
|
||||||
.with_title("A fantastic window!")
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
.build(&events_loop)
|
use rwh_05::HasRawDisplayHandle;
|
||||||
.unwrap();
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
use softbuffer::{Context, Surface};
|
||||||
|
|
||||||
events_loop.run_forever(|event| {
|
use winit::application::ApplicationHandler;
|
||||||
println!("{:?}", event);
|
use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize};
|
||||||
|
use winit::event::{DeviceEvent, DeviceId, Ime, WindowEvent};
|
||||||
|
use winit::event::{MouseButton, MouseScrollDelta};
|
||||||
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
|
use winit::keyboard::{Key, ModifiersState};
|
||||||
|
use winit::window::{
|
||||||
|
Cursor, CursorGrabMode, CustomCursor, CustomCursorSource, Fullscreen, Icon, ResizeDirection,
|
||||||
|
Theme,
|
||||||
|
};
|
||||||
|
use winit::window::{Window, WindowId};
|
||||||
|
|
||||||
match event {
|
#[cfg(macos_platform)]
|
||||||
winit::Event::WindowEvent {
|
use winit::platform::macos::{OptionAsAlt, WindowAttributesExtMacOS, WindowExtMacOS};
|
||||||
event: winit::WindowEvent::CloseRequested,
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
..
|
use winit::platform::startup_notify::{
|
||||||
} => winit::ControlFlow::Break,
|
self, EventLoopExtStartupNotify, WindowAttributesExtStartupNotify, WindowExtStartupNotify,
|
||||||
_ => winit::ControlFlow::Continue,
|
};
|
||||||
|
|
||||||
|
/// The amount of points to around the window for drag resize direction calculations.
|
||||||
|
const BORDER_SIZE: f64 = 20.;
|
||||||
|
|
||||||
|
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 state = Application::new(&event_loop);
|
||||||
|
|
||||||
|
event_loop.run_app(&mut state).map_err(Into::into)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[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: Option<Context>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Application {
|
||||||
|
fn new<T>(event_loop: &EventLoop<T>) -> Self {
|
||||||
|
// SAFETY: we drop the context right before the event loop is stopped, thus making it safe.
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
let context = Some(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");
|
||||||
|
|
||||||
|
let icon = load_icon(Path::new(path));
|
||||||
|
|
||||||
|
println!("Loading cursor assets");
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
let window_state = WindowState::new(self, window)?;
|
||||||
|
let window_id = window_state.window.id();
|
||||||
|
println!("Created new window with id={window_id:?}");
|
||||||
|
self.windows.insert(window_id, window_state);
|
||||||
|
Ok(window_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_action(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, action: Action) {
|
||||||
|
// let cursor_position = self.cursor_position;
|
||||||
|
let window = self.windows.get_mut(&window_id).unwrap();
|
||||||
|
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.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 => window.toggle_resize_increments(),
|
||||||
|
Action::ToggleCursorVisibility => window.toggle_cursor_visibility(),
|
||||||
|
Action::ToggleResizable => window.toggle_resizable(),
|
||||||
|
Action::ToggleDecorations => window.toggle_decorations(),
|
||||||
|
Action::ToggleFullscreen => window.toggle_fullscreen(),
|
||||||
|
Action::ToggleMaximize => window.toggle_maximize(),
|
||||||
|
Action::ToggleImeInput => window.toggle_ime(),
|
||||||
|
Action::Minimize => window.minimize(),
|
||||||
|
Action::NextCursor => window.next_cursor(),
|
||||||
|
Action::NextCustomCursor => window.next_custom_cursor(&self.custom_cursors),
|
||||||
|
Action::CycleCursorGrab => window.cycle_cursor_grab(),
|
||||||
|
Action::DragWindow => window.drag_window(),
|
||||||
|
Action::DragResizeWindow => window.drag_resize_window(),
|
||||||
|
Action::ShowWindowMenu => window.show_menu(),
|
||||||
|
Action::PrintHelp => self.print_help(),
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
Action::CycleOptionAsAlt => window.cycle_option_as_alt(),
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
Action::CreateNewTab => {
|
||||||
|
let tab_id = window.window.tabbing_identifier();
|
||||||
|
if let Err(err) = self.create_window(event_loop, Some(tab_id)) {
|
||||||
|
eprintln!("Error creating new window: {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dump_monitors(&self, 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 PhysicalSize { width, height } = monitor.size();
|
||||||
|
print!(" Current mode: {width}x{height}");
|
||||||
|
if let Some(m_hz) = monitor.refresh_rate_millihertz() {
|
||||||
|
println!(" @ {}.{} Hz", m_hz / 1000, m_hz % 1000);
|
||||||
|
} else {
|
||||||
|
println!();
|
||||||
|
}
|
||||||
|
|
||||||
|
let PhysicalPosition { x, y } = monitor.position();
|
||||||
|
println!(" Position: {x},{y}");
|
||||||
|
|
||||||
|
println!(" Scale factor: {}", monitor.scale_factor());
|
||||||
|
|
||||||
|
println!(" Available modes (width x height x bit-depth):");
|
||||||
|
for mode in monitor.video_modes() {
|
||||||
|
let PhysicalSize { width, height } = mode.size();
|
||||||
|
let bits = mode.bit_depth();
|
||||||
|
let m_hz = mode.refresh_rate_millihertz();
|
||||||
|
println!(
|
||||||
|
" {width}x{height}x{bits} @ {}.{} Hz",
|
||||||
|
m_hz / 1000,
|
||||||
|
m_hz % 1000
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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) {
|
||||||
|
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 {
|
||||||
|
println!(
|
||||||
|
"{}{:<10} - {} ({})",
|
||||||
|
modifiers_to_string(binding.mods),
|
||||||
|
mouse_button_to_string(binding.trigger),
|
||||||
|
binding.action,
|
||||||
|
binding.action.help(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler<UserEvent> for Application {
|
||||||
|
fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: UserEvent) {
|
||||||
|
println!("User event: {event:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &ActiveEventLoop,
|
||||||
|
window_id: WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
let window = match self.windows.get_mut(&window_id) {
|
||||||
|
Some(window) => window,
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
|
||||||
|
match event {
|
||||||
|
WindowEvent::Resized(size) => {
|
||||||
|
window.resize(size);
|
||||||
|
}
|
||||||
|
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:?}");
|
||||||
|
window.set_theme(theme);
|
||||||
|
}
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
if let Err(err) = window.draw() {
|
||||||
|
eprintln!("Error drawing window: {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::Occluded(occluded) => {
|
||||||
|
window.set_occluded(occluded);
|
||||||
|
}
|
||||||
|
WindowEvent::CloseRequested => {
|
||||||
|
println!("Closing Window={window_id:?}");
|
||||||
|
self.windows.remove(&window_id);
|
||||||
|
}
|
||||||
|
WindowEvent::ModifiersChanged(modifiers) => {
|
||||||
|
window.modifiers = modifiers.state();
|
||||||
|
println!("Modifiers changed to {:?}", window.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,
|
||||||
|
is_synthetic: false,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
let mods = window.modifiers;
|
||||||
|
|
||||||
|
// Dispatch actions only on press.
|
||||||
|
if event.state.is_pressed() {
|
||||||
|
let action = if let Key::Character(ch) = event.logical_key.as_ref() {
|
||||||
|
Self::process_key_binding(&ch.to_uppercase(), &mods)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(action) = action {
|
||||||
|
self.handle_action(event_loop, window_id, action);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::MouseInput { button, state, .. } => {
|
||||||
|
let mods = window.modifiers;
|
||||||
|
if let Some(action) = state
|
||||||
|
.is_pressed()
|
||||||
|
.then(|| Self::process_mouse_binding(button, &mods))
|
||||||
|
.flatten()
|
||||||
|
{
|
||||||
|
self.handle_action(event_loop, window_id, action);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::CursorLeft { .. } => {
|
||||||
|
println!("Cursor left Window={window_id:?}");
|
||||||
|
window.cursor_left();
|
||||||
|
}
|
||||||
|
WindowEvent::CursorMoved { position, .. } => {
|
||||||
|
println!("Moved cursor to {position:?}");
|
||||||
|
window.cursor_moved(position);
|
||||||
|
}
|
||||||
|
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!("Committed: {}", text);
|
||||||
|
}
|
||||||
|
Ime::Disabled => println!("IME disabled for Window={window_id:?}"),
|
||||||
|
},
|
||||||
|
WindowEvent::PinchGesture { delta, .. } => {
|
||||||
|
window.zoom += delta;
|
||||||
|
let zoom = window.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, .. } => {
|
||||||
|
window.rotated += delta;
|
||||||
|
let rotated = window.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::KeyboardInput { .. }
|
||||||
|
| WindowEvent::CursorEntered { .. }
|
||||||
|
| WindowEvent::AxisMotion { .. }
|
||||||
|
| WindowEvent::DroppedFile(_)
|
||||||
|
| WindowEvent::HoveredFile(_)
|
||||||
|
| WindowEvent::Destroyed
|
||||||
|
| WindowEvent::Touch(_)
|
||||||
|
| WindowEvent::Moved(_) => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn device_event(
|
||||||
|
&mut self,
|
||||||
|
_event_loop: &ActiveEventLoop,
|
||||||
|
device_id: DeviceId,
|
||||||
|
event: DeviceEvent,
|
||||||
|
) {
|
||||||
|
println!("Device {device_id:?} event: {event:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
println!("Resumed the event loop");
|
||||||
|
self.dump_monitors(event_loop);
|
||||||
|
|
||||||
|
// Create initial window.
|
||||||
|
self.create_window(event_loop, None)
|
||||||
|
.expect("failed to create initial window");
|
||||||
|
|
||||||
|
self.print_help();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
if self.windows.is_empty() {
|
||||||
|
println!("No windows left, exiting...");
|
||||||
|
event_loop.exit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
|
||||||
|
// We must drop the context here.
|
||||||
|
self.context = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// State of the window.
|
||||||
|
struct WindowState {
|
||||||
|
/// 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 actual winit Window.
|
||||||
|
window: Window,
|
||||||
|
/// 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,
|
||||||
|
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
option_as_alt: OptionAsAlt,
|
||||||
|
|
||||||
|
// Cursor states.
|
||||||
|
named_idx: usize,
|
||||||
|
custom_idx: usize,
|
||||||
|
cursor_hidden: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowState {
|
||||||
|
fn new(app: &Application, window: Window) -> Result<Self, Box<dyn Error>> {
|
||||||
|
// SAFETY: the surface is dropped before the `window` which provided it with handle, thus
|
||||||
|
// it doesn't outlive it.
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
let surface = unsafe { Surface::new(app.context.as_ref().unwrap(), &window)? };
|
||||||
|
|
||||||
|
let theme = window.theme().unwrap_or(Theme::Dark);
|
||||||
|
println!("Theme: {theme:?}");
|
||||||
|
let named_idx = 0;
|
||||||
|
window.set_cursor(CURSORS[named_idx]);
|
||||||
|
|
||||||
|
// Allow IME out of the box.
|
||||||
|
let ime = true;
|
||||||
|
window.set_ime_allowed(ime);
|
||||||
|
|
||||||
|
let size = window.inner_size();
|
||||||
|
let mut state = Self {
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
option_as_alt: window.option_as_alt(),
|
||||||
|
custom_idx: app.custom_cursors.len() - 1,
|
||||||
|
cursor_grab: CursorGrabMode::None,
|
||||||
|
named_idx,
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
surface,
|
||||||
|
window,
|
||||||
|
theme,
|
||||||
|
ime,
|
||||||
|
cursor_position: Default::default(),
|
||||||
|
cursor_hidden: Default::default(),
|
||||||
|
modifiers: Default::default(),
|
||||||
|
occluded: Default::default(),
|
||||||
|
rotated: Default::default(),
|
||||||
|
zoom: Default::default(),
|
||||||
|
};
|
||||||
|
|
||||||
|
state.resize(size);
|
||||||
|
Ok(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn toggle_ime(&mut self) {
|
||||||
|
self.ime = !self.ime;
|
||||||
|
self.window.set_ime_allowed(self.ime);
|
||||||
|
if let Some(position) = self.ime.then_some(self.cursor_position).flatten() {
|
||||||
|
self.window
|
||||||
|
.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn minimize(&mut self) {
|
||||||
|
self.window.set_minimized(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cursor_moved(&mut self, position: PhysicalPosition<f64>) {
|
||||||
|
self.cursor_position = Some(position);
|
||||||
|
if self.ime {
|
||||||
|
self.window
|
||||||
|
.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cursor_left(&mut self) {
|
||||||
|
self.cursor_position = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggle maximized.
|
||||||
|
fn toggle_maximize(&self) {
|
||||||
|
let maximized = self.window.is_maximized();
|
||||||
|
self.window.set_maximized(!maximized);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggle window decorations.
|
||||||
|
fn toggle_decorations(&self) {
|
||||||
|
let decorated = self.window.is_decorated();
|
||||||
|
self.window.set_decorations(!decorated);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggle window resizable state.
|
||||||
|
fn toggle_resizable(&self) {
|
||||||
|
let resizable = self.window.is_resizable();
|
||||||
|
self.window.set_resizable(!resizable);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggle cursor visibility
|
||||||
|
fn toggle_cursor_visibility(&mut self) {
|
||||||
|
self.cursor_hidden = !self.cursor_hidden;
|
||||||
|
self.window.set_cursor_visible(!self.cursor_hidden);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggle resize increments on a window.
|
||||||
|
fn toggle_resize_increments(&mut self) {
|
||||||
|
let new_increments = match self.window.resize_increments() {
|
||||||
|
Some(_) => None,
|
||||||
|
None => Some(LogicalSize::new(25.0, 25.0)),
|
||||||
|
};
|
||||||
|
println!("Had increments: {}", new_increments.is_none());
|
||||||
|
self.window.set_resize_increments(new_increments);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggle fullscreen.
|
||||||
|
fn toggle_fullscreen(&self) {
|
||||||
|
let fullscreen = if self.window.fullscreen().is_some() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(Fullscreen::Borderless(None))
|
||||||
|
};
|
||||||
|
|
||||||
|
self.window.set_fullscreen(fullscreen);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cycle through the grab modes ignoring errors.
|
||||||
|
fn cycle_cursor_grab(&mut self) {
|
||||||
|
self.cursor_grab = match self.cursor_grab {
|
||||||
|
CursorGrabMode::None => CursorGrabMode::Confined,
|
||||||
|
CursorGrabMode::Confined => CursorGrabMode::Locked,
|
||||||
|
CursorGrabMode::Locked => CursorGrabMode::None,
|
||||||
|
};
|
||||||
|
println!("Changing cursor grab mode to {:?}", self.cursor_grab);
|
||||||
|
if let Err(err) = self.window.set_cursor_grab(self.cursor_grab) {
|
||||||
|
eprintln!("Error setting cursor grab: {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
fn cycle_option_as_alt(&mut self) {
|
||||||
|
self.option_as_alt = match self.option_as_alt {
|
||||||
|
OptionAsAlt::None => OptionAsAlt::OnlyLeft,
|
||||||
|
OptionAsAlt::OnlyLeft => OptionAsAlt::OnlyRight,
|
||||||
|
OptionAsAlt::OnlyRight => OptionAsAlt::Both,
|
||||||
|
OptionAsAlt::Both => OptionAsAlt::None,
|
||||||
|
};
|
||||||
|
println!("Setting option as alt {:?}", self.option_as_alt);
|
||||||
|
self.window.set_option_as_alt(self.option_as_alt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pick the next cursor.
|
||||||
|
fn next_cursor(&mut self) {
|
||||||
|
self.named_idx = (self.named_idx + 1) % CURSORS.len();
|
||||||
|
println!("Setting cursor to \"{:?}\"", CURSORS[self.named_idx]);
|
||||||
|
self.window
|
||||||
|
.set_cursor(Cursor::Icon(CURSORS[self.named_idx]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pick the next custom cursor.
|
||||||
|
fn next_custom_cursor(&mut self, custom_cursors: &[CustomCursor]) {
|
||||||
|
self.custom_idx = (self.custom_idx + 1) % custom_cursors.len();
|
||||||
|
let cursor = Cursor::Custom(custom_cursors[self.custom_idx].clone());
|
||||||
|
self.window.set_cursor(cursor);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resize the window to the new size.
|
||||||
|
fn resize(&mut self, _size: PhysicalSize<u32>) {
|
||||||
|
#[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,
|
||||||
|
};
|
||||||
|
self.surface
|
||||||
|
.resize(width, height)
|
||||||
|
.expect("failed to resize inner buffer");
|
||||||
|
}
|
||||||
|
self.window.request_redraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Change the theme.
|
||||||
|
fn set_theme(&mut self, theme: Theme) {
|
||||||
|
self.theme = theme;
|
||||||
|
self.window.request_redraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Show window menu.
|
||||||
|
fn show_menu(&self) {
|
||||||
|
if let Some(position) = self.cursor_position {
|
||||||
|
self.window.show_window_menu(position);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drag the window.
|
||||||
|
fn drag_window(&self) {
|
||||||
|
if let Err(err) = self.window.drag_window() {
|
||||||
|
println!("Error starting window drag: {err}");
|
||||||
|
} else {
|
||||||
|
println!("Dragging window Window={:?}", self.window.id());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drag-resize the window.
|
||||||
|
fn drag_resize_window(&self) {
|
||||||
|
let position = match self.cursor_position {
|
||||||
|
Some(position) => position,
|
||||||
|
None => {
|
||||||
|
println!("Drag-resize requires cursor to be inside the window");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let win_size = self.window.inner_size();
|
||||||
|
let border_size = BORDER_SIZE * self.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) = self.window.drag_resize_window(direction) {
|
||||||
|
println!("Error starting window drag-resize: {err}");
|
||||||
|
} else {
|
||||||
|
println!("Drag-resizing window Window={:?}", self.window.id());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Change window occlusion state.
|
||||||
|
fn set_occluded(&mut self, occluded: bool) {
|
||||||
|
self.occluded = occluded;
|
||||||
|
if !occluded {
|
||||||
|
self.window.request_redraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Draw the window contents.
|
||||||
|
#[cfg(not(any(android_platform, ios_platform)))]
|
||||||
|
fn draw(&mut self) -> Result<(), Box<dyn Error>> {
|
||||||
|
if self.occluded {
|
||||||
|
println!("Skipping drawing occluded window={:?}", self.window.id());
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
const WHITE: u32 = 0xFFFFFFFF;
|
||||||
|
const DARK_GRAY: u32 = 0xFF181818;
|
||||||
|
|
||||||
|
let color = match self.theme {
|
||||||
|
Theme::Light => WHITE,
|
||||||
|
Theme::Dark => DARK_GRAY,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut buffer = self.surface.buffer_mut()?;
|
||||||
|
buffer.fill(color);
|
||||||
|
self.window.pre_present_notify();
|
||||||
|
buffer.present()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(android_platform, ios_platform))]
|
||||||
|
fn draw(&mut self) -> Result<(), Box<dyn Error>> {
|
||||||
|
println!("Drawing but without rendering...");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for Action {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
Debug::fmt(&self, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode_cursor(bytes: &[u8]) -> CustomCursorSource {
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_icon(path: &Path) -> Icon {
|
||||||
|
let (icon_rgba, icon_width, icon_height) = {
|
||||||
|
let image = image::open(path)
|
||||||
|
.expect("Failed to open icon path")
|
||||||
|
.into_rgba8();
|
||||||
|
let (width, height) = image.dimensions();
|
||||||
|
let rgba = image.into_raw();
|
||||||
|
(rgba, width, height)
|
||||||
|
};
|
||||||
|
Icon::from_rgba(icon_rgba, icon_width, icon_height).expect("Failed to open icon")
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mouse_button_to_string(button: MouseButton) -> &'static str {
|
||||||
|
match button {
|
||||||
|
MouseButton::Left => "LMB",
|
||||||
|
MouseButton::Right => "RMB",
|
||||||
|
MouseButton::Middle => "MMB",
|
||||||
|
MouseButton::Back => "Back",
|
||||||
|
MouseButton::Forward => "Forward",
|
||||||
|
MouseButton::Other(_) => "",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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,
|
||||||
|
];
|
||||||
|
|
||||||
|
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,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|||||||
72
examples/x11_embed.rs
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
//! A demonstration of embedding a winit window in an existing X11 application.
|
||||||
|
use std::error::Error;
|
||||||
|
|
||||||
|
#[cfg(x11_platform)]
|
||||||
|
fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
use winit::application::ApplicationHandler;
|
||||||
|
use winit::event::WindowEvent;
|
||||||
|
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||||
|
use winit::platform::x11::WindowAttributesExtX11;
|
||||||
|
use winit::window::{Window, WindowId};
|
||||||
|
|
||||||
|
#[path = "util/fill.rs"]
|
||||||
|
mod fill;
|
||||||
|
|
||||||
|
pub struct XEmbedDemo {
|
||||||
|
parent_window_id: u32,
|
||||||
|
window: Option<Window>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for XEmbedDemo {
|
||||||
|
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
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(self.parent_window_id);
|
||||||
|
|
||||||
|
self.window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &ActiveEventLoop,
|
||||||
|
_window_id: WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
let window = self.window.as_ref().unwrap();
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => event_loop.exit(),
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
window.pre_present_notify();
|
||||||
|
fill::fill_window(window);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
|
||||||
|
self.window.as_ref().unwrap().request_redraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// First argument should be a 32-bit X11 window ID.
|
||||||
|
let parent_window_id = std::env::args()
|
||||||
|
.nth(1)
|
||||||
|
.ok_or("Expected a 32-bit X11 window ID as the first argument.")?
|
||||||
|
.parse::<u32>()?;
|
||||||
|
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
let event_loop = EventLoop::new()?;
|
||||||
|
|
||||||
|
let mut app = XEmbedDemo {
|
||||||
|
parent_window_id,
|
||||||
|
window: None,
|
||||||
|
};
|
||||||
|
event_loop.run_app(&mut app).map_err(Into::into)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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
|
||||||
221
src/application.rs
Normal file
@@ -0,0 +1,221 @@
|
|||||||
|
//! End user application handling.
|
||||||
|
|
||||||
|
use crate::event::{DeviceEvent, DeviceId, StartCause, WindowEvent};
|
||||||
|
use crate::event_loop::ActiveEventLoop;
|
||||||
|
use crate::window::WindowId;
|
||||||
|
|
||||||
|
/// The handler of the application events.
|
||||||
|
pub trait ApplicationHandler<T: 'static = ()> {
|
||||||
|
/// Emitted when new events arrive from the OS to be processed.
|
||||||
|
///
|
||||||
|
/// This is a useful place to put code that should be done before you start processing
|
||||||
|
/// events, such as updating frame timing information for benchmarking or checking the
|
||||||
|
/// [`StartCause`] to see if a timer set by
|
||||||
|
/// [`ControlFlow::WaitUntil`](crate::event_loop::ControlFlow::WaitUntil) has elapsed.
|
||||||
|
fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
|
||||||
|
let _ = (event_loop, cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emitted when the application has been resumed.
|
||||||
|
///
|
||||||
|
/// For consistency, all platforms emit a `Resumed` event even if they don't themselves have a
|
||||||
|
/// formal suspend/resume lifecycle. For systems without a formal suspend/resume lifecycle
|
||||||
|
/// the `Resumed` event is always emitted after the [`NewEvents(StartCause::Init)`][StartCause::Init]
|
||||||
|
/// event.
|
||||||
|
///
|
||||||
|
/// # Portability
|
||||||
|
///
|
||||||
|
/// It's recommended that applications should only initialize their graphics context and create
|
||||||
|
/// a window after they have received their first `Resumed` event. Some systems
|
||||||
|
/// (specifically Android) won't allow applications to create a render surface until they are
|
||||||
|
/// resumed.
|
||||||
|
///
|
||||||
|
/// Considering that the implementation of [`Suspended`] and `Resumed` events may be internally
|
||||||
|
/// driven by multiple platform-specific events, and that there may be subtle differences across
|
||||||
|
/// platforms with how these internal events are delivered, it's recommended that applications
|
||||||
|
/// be able to gracefully handle redundant (i.e. back-to-back) [`Suspended`] or `Resumed` events.
|
||||||
|
///
|
||||||
|
/// Also see [`Suspended`] notes.
|
||||||
|
///
|
||||||
|
/// ## Android
|
||||||
|
///
|
||||||
|
/// On Android, the `Resumed` event is sent when a new [`SurfaceView`] has been created. This is
|
||||||
|
/// expected to closely correlate with the [`onResume`] lifecycle event but there may technically
|
||||||
|
/// be a discrepancy.
|
||||||
|
///
|
||||||
|
/// [`onResume`]: https://developer.android.com/reference/android/app/Activity#onResume()
|
||||||
|
///
|
||||||
|
/// Applications that need to run on Android must wait until they have been `Resumed`
|
||||||
|
/// before they will be able to create a render surface (such as an `EGLSurface`,
|
||||||
|
/// [`VkSurfaceKHR`] or [`wgpu::Surface`]) which depend on having a
|
||||||
|
/// [`SurfaceView`]. Applications must also assume that if they are [`Suspended`], then their
|
||||||
|
/// render surfaces are invalid and should be dropped.
|
||||||
|
///
|
||||||
|
/// Also see [`Suspended`] notes.
|
||||||
|
///
|
||||||
|
/// [`SurfaceView`]: https://developer.android.com/reference/android/view/SurfaceView
|
||||||
|
/// [Activity lifecycle]: https://developer.android.com/guide/components/activities/activity-lifecycle
|
||||||
|
/// [`VkSurfaceKHR`]: https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/VkSurfaceKHR.html
|
||||||
|
/// [`wgpu::Surface`]: https://docs.rs/wgpu/latest/wgpu/struct.Surface.html
|
||||||
|
///
|
||||||
|
/// ## iOS
|
||||||
|
///
|
||||||
|
/// On iOS, the `Resumed` event is emitted in response to an [`applicationDidBecomeActive`]
|
||||||
|
/// callback which means the application is "active" (according to the
|
||||||
|
/// [iOS application lifecycle]).
|
||||||
|
///
|
||||||
|
/// [`applicationDidBecomeActive`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622956-applicationdidbecomeactive
|
||||||
|
/// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle
|
||||||
|
///
|
||||||
|
/// ## Web
|
||||||
|
///
|
||||||
|
/// On Web, the `Resumed` event is emitted in response to a [`pageshow`] event
|
||||||
|
/// with the property [`persisted`] being true, which means that the page is being
|
||||||
|
/// restored from the [`bfcache`] (back/forward cache) - an in-memory cache that
|
||||||
|
/// stores a complete snapshot of a page (including the JavaScript heap) as the
|
||||||
|
/// user is navigating away.
|
||||||
|
///
|
||||||
|
/// [`pageshow`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event
|
||||||
|
/// [`persisted`]: https://developer.mozilla.org/en-US/docs/Web/API/PageTransitionEvent/persisted
|
||||||
|
/// [`bfcache`]: https://web.dev/bfcache/
|
||||||
|
/// [`Suspended`]: Self::suspended
|
||||||
|
fn resumed(&mut self, event_loop: &ActiveEventLoop);
|
||||||
|
|
||||||
|
/// Emitted when an event is sent from [`EventLoopProxy::send_event`].
|
||||||
|
///
|
||||||
|
/// [`EventLoopProxy::send_event`]: crate::event_loop::EventLoopProxy::send_event
|
||||||
|
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: T) {
|
||||||
|
let _ = (event_loop, event);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emitted when the OS sends an event to a winit window.
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &ActiveEventLoop,
|
||||||
|
window_id: WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Emitted when the OS sends an event to a device.
|
||||||
|
fn device_event(
|
||||||
|
&mut self,
|
||||||
|
event_loop: &ActiveEventLoop,
|
||||||
|
device_id: DeviceId,
|
||||||
|
event: DeviceEvent,
|
||||||
|
) {
|
||||||
|
let _ = (event_loop, device_id, event);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emitted when the event loop is about to block and wait for new events.
|
||||||
|
///
|
||||||
|
/// Most applications shouldn't need to hook into this event since there is no real relationship
|
||||||
|
/// between how often the event loop needs to wake up and the dispatching of any specific events.
|
||||||
|
///
|
||||||
|
/// High frequency event sources, such as input devices could potentially lead to lots of wake
|
||||||
|
/// ups and also lots of corresponding `AboutToWait` events.
|
||||||
|
///
|
||||||
|
/// This is not an ideal event to drive application rendering from and instead applications
|
||||||
|
/// should render in response to [`WindowEvent::RedrawRequested`] events.
|
||||||
|
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
let _ = event_loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emitted when the application has been suspended.
|
||||||
|
///
|
||||||
|
/// # Portability
|
||||||
|
///
|
||||||
|
/// Not all platforms support the notion of suspending applications, and there may be no
|
||||||
|
/// technical way to guarantee being able to emit a `Suspended` event if the OS has
|
||||||
|
/// no formal application lifecycle (currently only Android, iOS, and Web do). For this reason,
|
||||||
|
/// Winit does not currently try to emit pseudo `Suspended` events before the application
|
||||||
|
/// quits on platforms without an application lifecycle.
|
||||||
|
///
|
||||||
|
/// Considering that the implementation of `Suspended` and [`Resumed`] events may be internally
|
||||||
|
/// driven by multiple platform-specific events, and that there may be subtle differences across
|
||||||
|
/// platforms with how these internal events are delivered, it's recommended that applications
|
||||||
|
/// be able to gracefully handle redundant (i.e. back-to-back) `Suspended` or [`Resumed`] events.
|
||||||
|
///
|
||||||
|
/// Also see [`Resumed`] notes.
|
||||||
|
///
|
||||||
|
/// ## Android
|
||||||
|
///
|
||||||
|
/// On Android, the `Suspended` event is only sent when the application's associated
|
||||||
|
/// [`SurfaceView`] is destroyed. This is expected to closely correlate with the [`onPause`]
|
||||||
|
/// lifecycle event but there may technically be a discrepancy.
|
||||||
|
///
|
||||||
|
/// [`onPause`]: https://developer.android.com/reference/android/app/Activity#onPause()
|
||||||
|
///
|
||||||
|
/// Applications that need to run on Android should assume their [`SurfaceView`] has been
|
||||||
|
/// destroyed, which indirectly invalidates any existing render surfaces that may have been
|
||||||
|
/// created outside of Winit (such as an `EGLSurface`, [`VkSurfaceKHR`] or [`wgpu::Surface`]).
|
||||||
|
///
|
||||||
|
/// After being `Suspended` on Android applications must drop all render surfaces before
|
||||||
|
/// the event callback completes, which may be re-created when the application is next [`Resumed`].
|
||||||
|
///
|
||||||
|
/// [`SurfaceView`]: https://developer.android.com/reference/android/view/SurfaceView
|
||||||
|
/// [Activity lifecycle]: https://developer.android.com/guide/components/activities/activity-lifecycle
|
||||||
|
/// [`VkSurfaceKHR`]: https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/VkSurfaceKHR.html
|
||||||
|
/// [`wgpu::Surface`]: https://docs.rs/wgpu/latest/wgpu/struct.Surface.html
|
||||||
|
///
|
||||||
|
/// ## iOS
|
||||||
|
///
|
||||||
|
/// On iOS, the `Suspended` event is currently emitted in response to an
|
||||||
|
/// [`applicationWillResignActive`] callback which means that the application is
|
||||||
|
/// about to transition from the active to inactive state (according to the
|
||||||
|
/// [iOS application lifecycle]).
|
||||||
|
///
|
||||||
|
/// [`applicationWillResignActive`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622950-applicationwillresignactive
|
||||||
|
/// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle
|
||||||
|
///
|
||||||
|
/// ## Web
|
||||||
|
///
|
||||||
|
/// On Web, the `Suspended` event is emitted in response to a [`pagehide`] event
|
||||||
|
/// with the property [`persisted`] being true, which means that the page is being
|
||||||
|
/// put in the [`bfcache`] (back/forward cache) - an in-memory cache that stores a
|
||||||
|
/// complete snapshot of a page (including the JavaScript heap) as the user is
|
||||||
|
/// navigating away.
|
||||||
|
///
|
||||||
|
/// [`pagehide`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event
|
||||||
|
/// [`persisted`]: https://developer.mozilla.org/en-US/docs/Web/API/PageTransitionEvent/persisted
|
||||||
|
/// [`bfcache`]: https://web.dev/bfcache/
|
||||||
|
/// [`Resumed`]: Self::resumed
|
||||||
|
fn suspended(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
let _ = event_loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emitted when the event loop is being shut down.
|
||||||
|
///
|
||||||
|
/// This is irreversible - if this method is called, it is guaranteed that the event loop
|
||||||
|
/// will exist right after.
|
||||||
|
fn exiting(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
let _ = event_loop;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emitted when the application has received a memory warning.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// ### Android
|
||||||
|
///
|
||||||
|
/// On Android, the `MemoryWarning` event is sent when [`onLowMemory`] was called. The application
|
||||||
|
/// must [release memory] or risk being killed.
|
||||||
|
///
|
||||||
|
/// [`onLowMemory`]: https://developer.android.com/reference/android/app/Application.html#onLowMemory()
|
||||||
|
/// [release memory]: https://developer.android.com/topic/performance/memory#release
|
||||||
|
///
|
||||||
|
/// ### iOS
|
||||||
|
///
|
||||||
|
/// On iOS, the `MemoryWarning` event is emitted in response to an [`applicationDidReceiveMemoryWarning`]
|
||||||
|
/// callback. The application must free as much memory as possible or risk being terminated, see
|
||||||
|
/// [how to respond to memory warnings].
|
||||||
|
///
|
||||||
|
/// [`applicationDidReceiveMemoryWarning`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623063-applicationdidreceivememorywarni
|
||||||
|
/// [how to respond to memory warnings]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle/responding_to_memory_warnings
|
||||||
|
///
|
||||||
|
/// ### Others
|
||||||
|
///
|
||||||
|
/// - **macOS / Orbital / Wayland / Web / Windows:** Unsupported.
|
||||||
|
fn memory_warning(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
let _ = event_loop;
|
||||||
|
}
|
||||||
|
}
|
||||||
290
src/cursor.rs
Normal file
@@ -0,0 +1,290 @@
|
|||||||
|
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> {
|
||||||
|
let _span = tracing::debug_span!(
|
||||||
|
"winit::Cursor::from_rgba",
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
hotspot_x,
|
||||||
|
hotspot_y
|
||||||
|
)
|
||||||
|
.entered();
|
||||||
|
|
||||||
|
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.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
#[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)
|
||||||
|
}
|
||||||
|
}
|
||||||
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())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
1229
src/event.rs
Normal file
663
src/event_loop.rs
Normal file
@@ -0,0 +1,663 @@
|
|||||||
|
//! The [`EventLoop`] struct and assorted supporting types, including
|
||||||
|
//! [`ControlFlow`].
|
||||||
|
//!
|
||||||
|
//! If you want to send custom events to the event loop, use
|
||||||
|
//! [`EventLoop::create_proxy`] to acquire an [`EventLoopProxy`] and call its
|
||||||
|
//! [`send_event`](`EventLoopProxy::send_event`) method.
|
||||||
|
//!
|
||||||
|
//! See the root-level documentation for information on how to create and use an event loop to
|
||||||
|
//! handle events.
|
||||||
|
use std::marker::PhantomData;
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
|
use std::{error, fmt};
|
||||||
|
|
||||||
|
#[cfg(not(web_platform))]
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
use web_time::{Duration, Instant};
|
||||||
|
|
||||||
|
use crate::application::ApplicationHandler;
|
||||||
|
use crate::error::{EventLoopError, OsError};
|
||||||
|
use crate::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> {
|
||||||
|
let _span = tracing::debug_span!("winit::EventLoopBuilder::build").entered();
|
||||||
|
|
||||||
|
if EVENT_LOOP_CREATED.swap(true, Ordering::Relaxed) {
|
||||||
|
return Err(EventLoopError::RecreationAttempt);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Certain platforms accept a mutable reference in their API.
|
||||||
|
#[allow(clippy::unnecessary_mut_passed)]
|
||||||
|
Ok(EventLoop {
|
||||||
|
event_loop: platform_impl::EventLoop::new(&mut self.platform_specific)?,
|
||||||
|
_marker: PhantomData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(web_platform)]
|
||||||
|
pub(crate) fn allow_event_loop_recreation() {
|
||||||
|
EVENT_LOOP_CREATED.store(false, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> fmt::Debug for EventLoop<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.pad("EventLoop { .. }")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for ActiveEventLoop {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.pad("ActiveEventLoop { .. }")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set through [`ActiveEventLoop::set_control_flow()`].
|
||||||
|
///
|
||||||
|
/// Indicates the desired behavior of the event loop after [`Event::AboutToWait`] is emitted.
|
||||||
|
///
|
||||||
|
/// Defaults to [`Wait`].
|
||||||
|
///
|
||||||
|
/// [`Wait`]: Self::Wait
|
||||||
|
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub enum ControlFlow {
|
||||||
|
/// When the current loop iteration finishes, immediately begin a new iteration regardless of
|
||||||
|
/// whether or not new events are available to process.
|
||||||
|
Poll,
|
||||||
|
|
||||||
|
/// When the current loop iteration finishes, suspend the thread until another event arrives.
|
||||||
|
#[default]
|
||||||
|
Wait,
|
||||||
|
|
||||||
|
/// When the current loop iteration finishes, suspend the thread until either another event
|
||||||
|
/// arrives or the given time is reached.
|
||||||
|
///
|
||||||
|
/// Useful for implementing efficient timers. Applications which want to render at the display's
|
||||||
|
/// native refresh rate should instead use [`Poll`] and the VSync functionality of a graphics API
|
||||||
|
/// to reduce odds of missed frames.
|
||||||
|
///
|
||||||
|
/// [`Poll`]: Self::Poll
|
||||||
|
WaitUntil(Instant),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ControlFlow {
|
||||||
|
/// Creates a [`ControlFlow`] that waits until a timeout has expired.
|
||||||
|
///
|
||||||
|
/// In most cases, this is set to [`WaitUntil`]. However, if the timeout overflows, it is
|
||||||
|
/// instead set to [`Wait`].
|
||||||
|
///
|
||||||
|
/// [`WaitUntil`]: Self::WaitUntil
|
||||||
|
/// [`Wait`]: Self::Wait
|
||||||
|
pub fn wait_duration(timeout: Duration) -> Self {
|
||||||
|
match Instant::now().checked_add(timeout) {
|
||||||
|
Some(instant) => Self::WaitUntil(instant),
|
||||||
|
None => Self::Wait,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoop<()> {
|
||||||
|
/// Create the event loop.
|
||||||
|
///
|
||||||
|
/// This is an alias of `EventLoop::builder().build()`.
|
||||||
|
#[inline]
|
||||||
|
pub fn new() -> Result<EventLoop<()>, EventLoopError> {
|
||||||
|
Self::builder().build()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start building a new event loop.
|
||||||
|
///
|
||||||
|
/// This returns an [`EventLoopBuilder`], to allow configuring the event loop before creation.
|
||||||
|
///
|
||||||
|
/// To get the actual event loop, call [`build`][EventLoopBuilder::build] on that.
|
||||||
|
#[inline]
|
||||||
|
pub fn builder() -> EventLoopBuilder<()> {
|
||||||
|
Self::with_user_event()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoop<T> {
|
||||||
|
/// Start building a new event loop, with the given type as the user event
|
||||||
|
/// type.
|
||||||
|
pub fn with_user_event() -> EventLoopBuilder<T> {
|
||||||
|
EventLoopBuilder {
|
||||||
|
platform_specific: Default::default(),
|
||||||
|
_p: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// See [`run_app`].
|
||||||
|
///
|
||||||
|
/// [`run_app`]: Self::run_app
|
||||||
|
#[inline]
|
||||||
|
#[deprecated = "use `EventLoop::run_app` instead"]
|
||||||
|
#[cfg(not(all(web_platform, target_feature = "exception-handling")))]
|
||||||
|
pub fn run<F>(self, event_handler: F) -> Result<(), EventLoopError>
|
||||||
|
where
|
||||||
|
F: FnMut(Event<T>, &ActiveEventLoop),
|
||||||
|
{
|
||||||
|
let _span = tracing::debug_span!("winit::EventLoop::run").entered();
|
||||||
|
|
||||||
|
self.event_loop.run(event_handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run the application with the event loop on the calling thread.
|
||||||
|
///
|
||||||
|
/// See the [`set_control_flow()`] docs on how to change the event loop's behavior.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **iOS:** Will never return to the caller and so values not passed to this function will
|
||||||
|
/// *not* be dropped before the process exits.
|
||||||
|
/// - **Web:** Will _act_ as if it never returns to the caller by throwing a Javascript exception
|
||||||
|
/// (that Rust doesn't see) that will also mean that the rest of the function is never executed
|
||||||
|
/// and any values not passed to this function will *not* be dropped.
|
||||||
|
///
|
||||||
|
/// Web applications are recommended to use
|
||||||
|
#[cfg_attr(
|
||||||
|
web_platform,
|
||||||
|
doc = "[`EventLoopExtWebSys::spawn_app()`][crate::platform::web::EventLoopExtWebSys::spawn_app()]"
|
||||||
|
)]
|
||||||
|
#[cfg_attr(not(web_platform), doc = "`EventLoopExtWebSys::spawn()`")]
|
||||||
|
/// [^1] instead of [`run_app()`] to avoid the need
|
||||||
|
/// for the Javascript exception trick, and to make it clearer that the event loop runs
|
||||||
|
/// asynchronously (via the browser's own, internal, event loop) and doesn't block the
|
||||||
|
/// current thread of execution like it does on other platforms.
|
||||||
|
///
|
||||||
|
/// This function won't be available with `target_feature = "exception-handling"`.
|
||||||
|
///
|
||||||
|
/// [`set_control_flow()`]: ActiveEventLoop::set_control_flow()
|
||||||
|
/// [`run_app()`]: Self::run_app()
|
||||||
|
/// [^1]: `EventLoopExtWebSys::spawn_app()` is only available on Web.
|
||||||
|
#[inline]
|
||||||
|
#[cfg(not(all(web_platform, target_feature = "exception-handling")))]
|
||||||
|
pub fn run_app<A: ApplicationHandler<T>>(self, app: &mut A) -> Result<(), EventLoopError> {
|
||||||
|
self.event_loop
|
||||||
|
.run(|event, event_loop| dispatch_event_for_app(app, event_loop, event))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates an [`EventLoopProxy`] that can be used to dispatch user events
|
||||||
|
/// to the main event loop, possibly from another thread.
|
||||||
|
pub fn create_proxy(&self) -> EventLoopProxy<T> {
|
||||||
|
EventLoopProxy {
|
||||||
|
event_loop_proxy: self.event_loop.create_proxy(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets a persistent reference to the underlying platform display.
|
||||||
|
///
|
||||||
|
/// See the [`OwnedDisplayHandle`] type for more information.
|
||||||
|
pub fn owned_display_handle(&self) -> OwnedDisplayHandle {
|
||||||
|
OwnedDisplayHandle {
|
||||||
|
platform: self.event_loop.window_target().p.owned_display_handle(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Change if or when [`DeviceEvent`]s are captured.
|
||||||
|
///
|
||||||
|
/// See [`ActiveEventLoop::listen_device_events`] for details.
|
||||||
|
///
|
||||||
|
/// [`DeviceEvent`]: crate::event::DeviceEvent
|
||||||
|
pub fn listen_device_events(&self, allowed: DeviceEvents) {
|
||||||
|
let _span = tracing::debug_span!(
|
||||||
|
"winit::EventLoop::listen_device_events",
|
||||||
|
allowed = ?allowed
|
||||||
|
)
|
||||||
|
.entered();
|
||||||
|
|
||||||
|
self.event_loop
|
||||||
|
.window_target()
|
||||||
|
.p
|
||||||
|
.listen_device_events(allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the [`ControlFlow`].
|
||||||
|
pub fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||||
|
self.event_loop
|
||||||
|
.window_target()
|
||||||
|
.p
|
||||||
|
.set_control_flow(control_flow)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a window.
|
||||||
|
///
|
||||||
|
/// Creating window without event loop running often leads to improper window creation;
|
||||||
|
/// use [`ActiveEventLoop::create_window`] instead.
|
||||||
|
#[deprecated = "use `ActiveEventLoop::create_window` instead"]
|
||||||
|
#[inline]
|
||||||
|
pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> {
|
||||||
|
let _span = tracing::debug_span!(
|
||||||
|
"winit::EventLoop::create_window",
|
||||||
|
window_attributes = ?window_attributes
|
||||||
|
)
|
||||||
|
.entered();
|
||||||
|
|
||||||
|
let window =
|
||||||
|
platform_impl::Window::new(&self.event_loop.window_target().p, window_attributes)?;
|
||||||
|
Ok(Window { window })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create custom cursor.
|
||||||
|
pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor {
|
||||||
|
self.event_loop
|
||||||
|
.window_target()
|
||||||
|
.p
|
||||||
|
.create_custom_cursor(custom_cursor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_06")]
|
||||||
|
impl<T> rwh_06::HasDisplayHandle for EventLoop<T> {
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
rwh_06::HasDisplayHandle::display_handle(self.event_loop.window_target())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_05")]
|
||||||
|
unsafe impl<T> rwh_05::HasRawDisplayHandle for EventLoop<T> {
|
||||||
|
/// Returns a [`rwh_05::RawDisplayHandle`] for the event loop.
|
||||||
|
fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
|
||||||
|
rwh_05::HasRawDisplayHandle::raw_display_handle(self.event_loop.window_target())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
impl<T> AsFd for EventLoop<T> {
|
||||||
|
/// Get the underlying [EventLoop]'s `fd` which you can register
|
||||||
|
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
||||||
|
/// loop must be polled with the [`pump_app_events`] API.
|
||||||
|
///
|
||||||
|
/// [`calloop`]: https://crates.io/crates/calloop
|
||||||
|
/// [`mio`]: https://crates.io/crates/mio
|
||||||
|
/// [`pump_app_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_app_events
|
||||||
|
fn as_fd(&self) -> BorrowedFd<'_> {
|
||||||
|
self.event_loop.as_fd()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
impl<T> AsRawFd for EventLoop<T> {
|
||||||
|
/// Get the underlying [EventLoop]'s raw `fd` which you can register
|
||||||
|
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
||||||
|
/// loop must be polled with the [`pump_app_events`] API.
|
||||||
|
///
|
||||||
|
/// [`calloop`]: https://crates.io/crates/calloop
|
||||||
|
/// [`mio`]: https://crates.io/crates/mio
|
||||||
|
/// [`pump_app_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_app_events
|
||||||
|
fn as_raw_fd(&self) -> RawFd {
|
||||||
|
self.event_loop.as_raw_fd()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActiveEventLoop {
|
||||||
|
/// Create the window.
|
||||||
|
///
|
||||||
|
/// Possible causes of error include denied permission, incompatible system, and lack of memory.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **Web:** The window is created but not inserted into the web page automatically. Please
|
||||||
|
/// see the web platform module for more information.
|
||||||
|
#[inline]
|
||||||
|
pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> {
|
||||||
|
let _span = tracing::debug_span!(
|
||||||
|
"winit::ActiveEventLoop::create_window",
|
||||||
|
window_attributes = ?window_attributes
|
||||||
|
)
|
||||||
|
.entered();
|
||||||
|
|
||||||
|
let window = platform_impl::Window::new(&self.p, window_attributes)?;
|
||||||
|
Ok(Window { window })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create custom cursor.
|
||||||
|
pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor {
|
||||||
|
let _span = tracing::debug_span!("winit::ActiveEventLoop::create_custom_cursor",).entered();
|
||||||
|
|
||||||
|
self.p.create_custom_cursor(custom_cursor)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the list of all the monitors available on the system.
|
||||||
|
#[inline]
|
||||||
|
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
|
||||||
|
let _span = tracing::debug_span!("winit::ActiveEventLoop::available_monitors",).entered();
|
||||||
|
|
||||||
|
#[allow(clippy::useless_conversion)] // false positive on some platforms
|
||||||
|
self.p
|
||||||
|
.available_monitors()
|
||||||
|
.into_iter()
|
||||||
|
.map(|inner| MonitorHandle { inner })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the primary monitor of the system.
|
||||||
|
///
|
||||||
|
/// Returns `None` if it can't identify any monitor as a primary one.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// **Wayland / Web:** Always returns `None`.
|
||||||
|
#[inline]
|
||||||
|
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||||
|
let _span = tracing::debug_span!("winit::ActiveEventLoop::primary_monitor",).entered();
|
||||||
|
|
||||||
|
self.p
|
||||||
|
.primary_monitor()
|
||||||
|
.map(|inner| MonitorHandle { inner })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Change if or when [`DeviceEvent`]s are captured.
|
||||||
|
///
|
||||||
|
/// Since the [`DeviceEvent`] capture can lead to high CPU usage for unfocused windows, winit
|
||||||
|
/// will ignore them by default for unfocused windows on Linux/BSD. This method allows changing
|
||||||
|
/// this at runtime to explicitly capture them again.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **Wayland / macOS / iOS / Android / Orbital:** Unsupported.
|
||||||
|
///
|
||||||
|
/// [`DeviceEvent`]: crate::event::DeviceEvent
|
||||||
|
pub fn listen_device_events(&self, allowed: DeviceEvents) {
|
||||||
|
let _span = tracing::debug_span!(
|
||||||
|
"winit::ActiveEventLoop::listen_device_events",
|
||||||
|
allowed = ?allowed
|
||||||
|
)
|
||||||
|
.entered();
|
||||||
|
|
||||||
|
self.p.listen_device_events(allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the [`ControlFlow`].
|
||||||
|
pub fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||||
|
self.p.set_control_flow(control_flow)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets the current [`ControlFlow`].
|
||||||
|
pub fn control_flow(&self) -> ControlFlow {
|
||||||
|
self.p.control_flow()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This exits the event loop.
|
||||||
|
///
|
||||||
|
/// See [`LoopExiting`](Event::LoopExiting).
|
||||||
|
pub fn exit(&self) {
|
||||||
|
let _span = tracing::debug_span!("winit::ActiveEventLoop::exit",).entered();
|
||||||
|
|
||||||
|
self.p.exit()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns if the [`EventLoop`] is about to stop.
|
||||||
|
///
|
||||||
|
/// See [`exit()`](Self::exit).
|
||||||
|
pub fn exiting(&self) -> bool {
|
||||||
|
self.p.exiting()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets a persistent reference to the underlying platform display.
|
||||||
|
///
|
||||||
|
/// See the [`OwnedDisplayHandle`] type for more information.
|
||||||
|
pub fn owned_display_handle(&self) -> OwnedDisplayHandle {
|
||||||
|
OwnedDisplayHandle {
|
||||||
|
platform: self.p.owned_display_handle(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_06")]
|
||||||
|
impl rwh_06::HasDisplayHandle for ActiveEventLoop {
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let raw = self.p.raw_display_handle_rwh_06()?;
|
||||||
|
// SAFETY: The display will never be deallocated while the event loop is alive.
|
||||||
|
Ok(unsafe { rwh_06::DisplayHandle::borrow_raw(raw) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_05")]
|
||||||
|
unsafe impl rwh_05::HasRawDisplayHandle for ActiveEventLoop {
|
||||||
|
/// Returns a [`rwh_05::RawDisplayHandle`] for the event loop.
|
||||||
|
fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
|
||||||
|
self.p.raw_display_handle_rwh_05()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A proxy for the underlying display handle.
|
||||||
|
///
|
||||||
|
/// The purpose of this type is to provide a cheaply 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>> {
|
||||||
|
let _span = tracing::debug_span!("winit::EventLoopProxy::send_event",).entered();
|
||||||
|
|
||||||
|
self.event_loop_proxy.send_event(event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static> fmt::Debug for EventLoopProxy<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.pad("EventLoopProxy { .. }")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The error that is returned when an [`EventLoopProxy`] attempts to wake up an [`EventLoop`] that
|
||||||
|
/// no longer exists.
|
||||||
|
///
|
||||||
|
/// Contains the original event given to [`EventLoopProxy::send_event`].
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub struct EventLoopClosed<T>(pub T);
|
||||||
|
|
||||||
|
impl<T> fmt::Display for EventLoopClosed<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str("Tried to wake up a closed `EventLoop`")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: fmt::Debug> error::Error for EventLoopClosed<T> {}
|
||||||
|
|
||||||
|
/// Control when device events are captured.
|
||||||
|
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
|
||||||
|
pub enum DeviceEvents {
|
||||||
|
/// Report device events regardless of window focus.
|
||||||
|
Always,
|
||||||
|
/// Only capture device events while the window is focused.
|
||||||
|
#[default]
|
||||||
|
WhenFocused,
|
||||||
|
/// Never capture device events.
|
||||||
|
Never,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A unique identifier of the winit's async request.
|
||||||
|
///
|
||||||
|
/// This could be used to identify the async request once it's done
|
||||||
|
/// and a specific action must be taken.
|
||||||
|
///
|
||||||
|
/// One of the handling scenarios could be to maintain a working list
|
||||||
|
/// containing [`AsyncRequestSerial`] and some closure associated with it.
|
||||||
|
/// Then once event is arriving the working list is being traversed and a job
|
||||||
|
/// executed and removed from the list.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct AsyncRequestSerial {
|
||||||
|
serial: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsyncRequestSerial {
|
||||||
|
// TODO(kchibisov): Remove `cfg` when the clipboard will be added.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) fn get() -> Self {
|
||||||
|
static CURRENT_SERIAL: AtomicUsize = AtomicUsize::new(0);
|
||||||
|
// NOTE: We rely on wrap around here, while the user may just request
|
||||||
|
// in the loop usize::MAX times that's issue is considered on them.
|
||||||
|
let serial = CURRENT_SERIAL.fetch_add(1, Ordering::Relaxed);
|
||||||
|
Self { serial }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shim for various run APIs.
|
||||||
|
#[inline(always)]
|
||||||
|
pub(crate) fn dispatch_event_for_app<T: 'static, A: ApplicationHandler<T>>(
|
||||||
|
app: &mut A,
|
||||||
|
event_loop: &ActiveEventLoop,
|
||||||
|
event: Event<T>,
|
||||||
|
) {
|
||||||
|
match event {
|
||||||
|
Event::NewEvents(cause) => app.new_events(event_loop, cause),
|
||||||
|
Event::WindowEvent { window_id, event } => app.window_event(event_loop, window_id, event),
|
||||||
|
Event::DeviceEvent { device_id, event } => app.device_event(event_loop, device_id, event),
|
||||||
|
Event::UserEvent(event) => app.user_event(event_loop, event),
|
||||||
|
Event::Suspended => app.suspended(event_loop),
|
||||||
|
Event::Resumed => app.resumed(event_loop),
|
||||||
|
Event::AboutToWait => app.about_to_wait(event_loop),
|
||||||
|
Event::LoopExiting => app.exiting(event_loop),
|
||||||
|
Event::MemoryWarning => app.memory_warning(event_loop),
|
||||||
|
}
|
||||||
|
}
|
||||||
451
src/events.rs
@@ -1,451 +0,0 @@
|
|||||||
use std::path::PathBuf;
|
|
||||||
use {WindowId, DeviceId};
|
|
||||||
|
|
||||||
/// 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.
|
|
||||||
Resized(u32, u32),
|
|
||||||
|
|
||||||
/// The position of the window has changed.
|
|
||||||
Moved(i32, i32),
|
|
||||||
|
|
||||||
/// 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: (f64, f64),
|
|
||||||
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),
|
|
||||||
|
|
||||||
/// DPI scaling factor of the window has changed.
|
|
||||||
///
|
|
||||||
/// The following actions cause DPI changes:
|
|
||||||
///
|
|
||||||
/// * A user changes the resolution.
|
|
||||||
/// * A user changes the desktop scaling value (e.g. in Control Panel on Windows).
|
|
||||||
/// * A user moves the application window to a display with a different DPI.
|
|
||||||
HiDPIFactorChanged(f32),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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: (f64,f64),
|
|
||||||
/// 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(f32, f32)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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,
|
|
||||||
LMenu,
|
|
||||||
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,
|
|
||||||
RMenu,
|
|
||||||
RShift,
|
|
||||||
RWin,
|
|
||||||
Semicolon,
|
|
||||||
Slash,
|
|
||||||
Sleep,
|
|
||||||
Stop,
|
|
||||||
Subtract,
|
|
||||||
Sysrq,
|
|
||||||
Tab,
|
|
||||||
Underline,
|
|
||||||
Unlabeled,
|
|
||||||
VolumeDown,
|
|
||||||
VolumeUp,
|
|
||||||
Wake,
|
|
||||||
WebBack,
|
|
||||||
WebFavorites,
|
|
||||||
WebForward,
|
|
||||||
WebHome,
|
|
||||||
WebRefresh,
|
|
||||||
WebSearch,
|
|
||||||
WebStop,
|
|
||||||
Yen,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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
|
|
||||||
}
|
|
||||||
127
src/icon.rs
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
use crate::platform_impl::PlatformIcon;
|
||||||
|
use std::{error::Error, fmt, io, mem};
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(crate) struct Pixel {
|
||||||
|
pub(crate) r: u8,
|
||||||
|
pub(crate) g: u8,
|
||||||
|
pub(crate) b: u8,
|
||||||
|
pub(crate) a: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) const PIXEL_SIZE: usize = mem::size_of::<Pixel>();
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
/// An error produced when using [`Icon::from_rgba`] with invalid arguments.
|
||||||
|
pub enum BadIcon {
|
||||||
|
/// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be
|
||||||
|
/// safely interpreted as 32bpp RGBA pixels.
|
||||||
|
ByteCountNotDivisibleBy4 { byte_count: usize },
|
||||||
|
/// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`.
|
||||||
|
/// At least one of your arguments is incorrect.
|
||||||
|
DimensionsVsPixelCount {
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
width_x_height: usize,
|
||||||
|
pixel_count: usize,
|
||||||
|
},
|
||||||
|
/// Produced when underlying OS functionality failed to create the icon
|
||||||
|
OsError(io::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for BadIcon {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
BadIcon::ByteCountNotDivisibleBy4 { byte_count } => write!(f,
|
||||||
|
"The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making it impossible to interpret as 32bpp RGBA pixels.",
|
||||||
|
),
|
||||||
|
BadIcon::DimensionsVsPixelCount {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
width_x_height,
|
||||||
|
pixel_count,
|
||||||
|
} => write!(f,
|
||||||
|
"The specified dimensions ({width:?}x{height:?}) don't match the number of pixels supplied by the `rgba` argument ({pixel_count:?}). For those dimensions, the expected pixel count is {width_x_height:?}.",
|
||||||
|
),
|
||||||
|
BadIcon::OsError(e) => write!(f, "OS error when instantiating the icon: {e:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for BadIcon {}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub(crate) struct RgbaIcon {
|
||||||
|
pub(crate) rgba: Vec<u8>,
|
||||||
|
pub(crate) width: u32,
|
||||||
|
pub(crate) height: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For platforms which don't have window icons (e.g. web)
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub(crate) struct NoIcon;
|
||||||
|
|
||||||
|
#[allow(dead_code)] // These are not used on every platform
|
||||||
|
mod constructors {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
impl RgbaIcon {
|
||||||
|
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
||||||
|
if rgba.len() % PIXEL_SIZE != 0 {
|
||||||
|
return Err(BadIcon::ByteCountNotDivisibleBy4 {
|
||||||
|
byte_count: rgba.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let pixel_count = rgba.len() / PIXEL_SIZE;
|
||||||
|
if pixel_count != (width * height) as usize {
|
||||||
|
Err(BadIcon::DimensionsVsPixelCount {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
width_x_height: (width * height) as usize,
|
||||||
|
pixel_count,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
Ok(RgbaIcon {
|
||||||
|
rgba,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NoIcon {
|
||||||
|
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
||||||
|
// Create the rgba icon anyway to validate the input
|
||||||
|
let _ = RgbaIcon::from_rgba(rgba, width, height)?;
|
||||||
|
Ok(NoIcon)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An icon used for the window titlebar, taskbar, etc.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Icon {
|
||||||
|
pub(crate) inner: PlatformIcon,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for Icon {
|
||||||
|
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||||
|
fmt::Debug::fmt(&self.inner, formatter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Icon {
|
||||||
|
/// Creates an icon from 32bpp RGBA data.
|
||||||
|
///
|
||||||
|
/// The length of `rgba` must be divisible by 4, and `width * height` must equal
|
||||||
|
/// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error.
|
||||||
|
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
||||||
|
let _span = tracing::debug_span!("winit::Icon::from_rgba", width, height).entered();
|
||||||
|
|
||||||
|
Ok(Icon {
|
||||||
|
inner: PlatformIcon::from_rgba(rgba, width, height)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
1801
src/keyboard.rs
Normal file
627
src/lib.rs
@@ -1,462 +1,217 @@
|
|||||||
//! 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 simpliest 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_app()`]. 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_app_events()`][platform::pump_events::EventLoopExtPumpEvents::pump_app_events()]"
|
||||||
|
)]
|
||||||
|
#![cfg_attr(
|
||||||
|
not(any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
android_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform
|
||||||
|
)),
|
||||||
|
doc = "`EventLoopExtPumpEvents::pump_app_events()`"
|
||||||
|
)]
|
||||||
|
//! [^1]. See that method's documentation for more reasons about why
|
||||||
|
//! it's discouraged beyond compatibility reasons.
|
||||||
//!
|
//!
|
||||||
//! 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 retreived 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
|
|
||||||
//! retreive 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::application::ApplicationHandler;
|
||||||
//! # use winit::EventsLoop;
|
//! use winit::event::WindowEvent;
|
||||||
//! # let mut events_loop = EventsLoop::new();
|
//! use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||||
|
//! use winit::window::{Window, WindowId};
|
||||||
//!
|
//!
|
||||||
//! loop {
|
//! #[derive(Default)]
|
||||||
//! events_loop.poll_events(|event| {
|
//! struct App {
|
||||||
//! match event {
|
//! window: Option<Window>,
|
||||||
//! Event::WindowEvent { event: WindowEvent::Resized(w, h), .. } => {
|
|
||||||
//! println!("The window was resized to {}x{}", w, h);
|
|
||||||
//! },
|
|
||||||
//! _ => ()
|
|
||||||
//! }
|
|
||||||
//! });
|
|
||||||
//! }
|
//! }
|
||||||
//! ```
|
|
||||||
//!
|
//!
|
||||||
//! The second way is to call `events_loop.run_forever(...)`. As its name tells, it will run
|
//! impl ApplicationHandler for App {
|
||||||
//! forever unless it is stopped by returning `ControlFlow::Break`.
|
//! fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
//!
|
//! self.window = Some(event_loop.create_window(Window::default_attributes()).unwrap());
|
||||||
//! ```no_run
|
|
||||||
//! use winit::{ControlFlow, Event, WindowEvent};
|
|
||||||
//! # use winit::EventsLoop;
|
|
||||||
//! # let mut events_loop = EventsLoop::new();
|
|
||||||
//!
|
|
||||||
//! events_loop.run_forever(|event| {
|
|
||||||
//! match event {
|
|
||||||
//! Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => {
|
|
||||||
//! println!("The close button was pressed; stopping");
|
|
||||||
//! ControlFlow::Break
|
|
||||||
//! },
|
|
||||||
//! _ => ControlFlow::Continue,
|
|
||||||
//! }
|
//! }
|
||||||
//! });
|
//!
|
||||||
|
//! fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
|
||||||
|
//! match event {
|
||||||
|
//! WindowEvent::CloseRequested => {
|
||||||
|
//! println!("The close button was pressed; stopping");
|
||||||
|
//! event_loop.exit();
|
||||||
|
//! },
|
||||||
|
//! WindowEvent::RedrawRequested => {
|
||||||
|
//! // Redraw the application.
|
||||||
|
//! //
|
||||||
|
//! // It's preferable for applications that do not render continuously to render in
|
||||||
|
//! // this event rather than in AboutToWait, since rendering in here allows
|
||||||
|
//! // the program to gracefully handle redraws requested by the OS.
|
||||||
|
//!
|
||||||
|
//! // Draw.
|
||||||
|
//!
|
||||||
|
//! // Queue a RedrawRequested event.
|
||||||
|
//! //
|
||||||
|
//! // You only need to call this if you've determined that you need to redraw in
|
||||||
|
//! // applications which do not always need to. Applications that redraw continuously
|
||||||
|
//! // can render here instead.
|
||||||
|
//! self.window.as_ref().unwrap().request_redraw();
|
||||||
|
//! }
|
||||||
|
//! _ => (),
|
||||||
|
//! }
|
||||||
|
//! }
|
||||||
|
//! }
|
||||||
|
//!
|
||||||
|
//! let event_loop = EventLoop::new().unwrap();
|
||||||
|
//!
|
||||||
|
//! // ControlFlow::Poll continuously runs the event loop, even if the OS hasn't
|
||||||
|
//! // dispatched any events. This is ideal for games and similar applications.
|
||||||
|
//! event_loop.set_control_flow(ControlFlow::Poll);
|
||||||
|
//!
|
||||||
|
//! // ControlFlow::Wait pauses the event loop if no events are available to process.
|
||||||
|
//! // This is ideal for non-game applications that only update in response to user
|
||||||
|
//! // input, and uses significantly less power/CPU time than ControlFlow::Poll.
|
||||||
|
//! event_loop.set_control_flow(ControlFlow::Wait);
|
||||||
|
//!
|
||||||
|
//! let mut app = App::default();
|
||||||
|
//! event_loop.run_app(&mut app);
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! 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
|
||||||
//! retreive 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_app()`]: event_loop::EventLoop::run_app
|
||||||
|
//! [`exit()`]: event_loop::ActiveEventLoop::exit
|
||||||
|
//! [`Window`]: window::Window
|
||||||
|
//! [`WindowId`]: window::WindowId
|
||||||
|
//! [`WindowAttributes`]: window::WindowAttributes
|
||||||
|
//! [window_new]: window::Window::new
|
||||||
|
//! [`create_window`]: event_loop::ActiveEventLoop::create_window
|
||||||
|
//! [`Window::id()`]: window::Window::id
|
||||||
|
//! [`WindowEvent`]: event::WindowEvent
|
||||||
|
//! [`DeviceEvent`]: event::DeviceEvent
|
||||||
|
//! [`Event::UserEvent`]: event::Event::UserEvent
|
||||||
|
//! [`Event::LoopExiting`]: event::Event::LoopExiting
|
||||||
|
//! [`raw_window_handle`]: ./window/struct.Window.html#method.raw_window_handle
|
||||||
|
//! [`raw_display_handle`]: ./window/struct.Window.html#method.raw_display_handle
|
||||||
|
//! [^1]: `EventLoopExtPumpEvents::pump_app_events()` is only available on Windows, macOS, Android, X11 and Wayland.
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "windows"))]
|
#![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;
|
||||||
|
|
||||||
|
pub mod application;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate lazy_static;
|
pub mod error;
|
||||||
|
mod cursor;
|
||||||
|
pub mod event;
|
||||||
|
pub mod event_loop;
|
||||||
|
mod icon;
|
||||||
|
pub mod keyboard;
|
||||||
|
pub mod monitor;
|
||||||
|
mod platform_impl;
|
||||||
|
mod utils;
|
||||||
|
pub mod window;
|
||||||
|
|
||||||
extern crate libc;
|
pub mod platform;
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
#[macro_use]
|
|
||||||
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 = "openbsd"))]
|
|
||||||
extern crate x11_dl;
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
extern crate percent_encoding;
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd"))]
|
|
||||||
#[macro_use]
|
|
||||||
extern crate wayland_client;
|
|
||||||
|
|
||||||
pub use events::*;
|
|
||||||
pub use window::{AvailableMonitorsIter, MonitorId};
|
|
||||||
|
|
||||||
mod platform;
|
|
||||||
mod events;
|
|
||||||
mod window;
|
|
||||||
|
|
||||||
pub mod os;
|
|
||||||
|
|
||||||
/// 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 retreive 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.
|
|
||||||
#[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,
|
|
||||||
NoneCursor,
|
|
||||||
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,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Describes how winit handles the cursor.
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
|
||||||
pub enum CursorState {
|
|
||||||
/// Normal cursor behavior.
|
|
||||||
Normal,
|
|
||||||
|
|
||||||
/// The cursor will be invisible when over the window.
|
|
||||||
Hide,
|
|
||||||
|
|
||||||
/// Grabs the mouse cursor. The cursor's motion will be confined to this
|
|
||||||
/// window and the window has exclusive access to further events regarding
|
|
||||||
/// the cursor.
|
|
||||||
///
|
|
||||||
/// This is useful for first-person cameras for example.
|
|
||||||
Grab,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Attributes to use when creating a window.
|
|
||||||
#[derive(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<(u32, u32)>,
|
|
||||||
|
|
||||||
/// 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<(u32, u32)>,
|
|
||||||
|
|
||||||
/// 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<(u32, u32)>,
|
|
||||||
|
|
||||||
/// 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,
|
|
||||||
|
|
||||||
/// [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,
|
|
||||||
title: "winit window".to_owned(),
|
|
||||||
maximized: false,
|
|
||||||
fullscreen: None,
|
|
||||||
visible: true,
|
|
||||||
transparent: false,
|
|
||||||
decorations: true,
|
|
||||||
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 {
|
|
||||||
}
|
|
||||||
151
src/os/macos.rs
@@ -1,151 +0,0 @@
|
|||||||
#![cfg(target_os = "macos")]
|
|
||||||
|
|
||||||
use std::convert::From;
|
|
||||||
use std::os::raw::c_void;
|
|
||||||
use cocoa::appkit::NSApplicationActivationPolicy;
|
|
||||||
use {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 {
|
|
||||||
fn with_activation_policy(self, activation_policy: ActivationPolicy) -> WindowBuilder;
|
|
||||||
fn with_movable_by_window_background(self, movable_by_window_background: bool) -> WindowBuilder;
|
|
||||||
fn with_titlebar_transparent(self, titlebar_transparent: bool) -> WindowBuilder;
|
|
||||||
fn with_title_hidden(self, title_hidden: bool) -> WindowBuilder;
|
|
||||||
fn with_titlebar_hidden(self, titlebar_hidden: bool) -> WindowBuilder;
|
|
||||||
fn with_titlebar_buttons_hidden(self, titlebar_buttons_hidden: bool) -> WindowBuilder;
|
|
||||||
fn with_fullsize_content_view(self, fullsize_content_view: bool) -> WindowBuilder;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowBuilderExt for WindowBuilder {
|
|
||||||
/// Sets the activation policy for the window being built
|
|
||||||
#[inline]
|
|
||||||
fn with_activation_policy(mut self, activation_policy: ActivationPolicy) -> WindowBuilder {
|
|
||||||
self.platform_specific.activation_policy = activation_policy;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Enables click-and-drag behavior for the entire window, not just the titlebar
|
|
||||||
#[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
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Makes the titlebar transparent and allows the content to appear behind it
|
|
||||||
#[inline]
|
|
||||||
fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> WindowBuilder {
|
|
||||||
self.platform_specific.titlebar_transparent = titlebar_transparent;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Hides the window titlebar
|
|
||||||
#[inline]
|
|
||||||
fn with_titlebar_hidden(mut self, titlebar_hidden: bool) -> WindowBuilder {
|
|
||||||
self.platform_specific.titlebar_hidden = titlebar_hidden;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Hides the window titlebar buttons
|
|
||||||
#[inline]
|
|
||||||
fn with_titlebar_buttons_hidden(mut self, titlebar_buttons_hidden: bool) -> WindowBuilder {
|
|
||||||
self.platform_specific.titlebar_buttons_hidden = titlebar_buttons_hidden;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Hides the window title
|
|
||||||
#[inline]
|
|
||||||
fn with_title_hidden(mut self, title_hidden: bool) -> WindowBuilder {
|
|
||||||
self.platform_specific.title_hidden = title_hidden;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Makes the window content appear behind the titlebar
|
|
||||||
#[inline]
|
|
||||||
fn with_fullsize_content_view(mut self, fullsize_content_view: bool) -> WindowBuilder {
|
|
||||||
self.platform_specific.fullsize_content_view = fullsize_content_view;
|
|
||||||
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,15 +0,0 @@
|
|||||||
//! Contains traits with platform-specific methods in them.
|
|
||||||
//!
|
|
||||||
//! Contains the follow modules:
|
|
||||||
//!
|
|
||||||
//! - `android`
|
|
||||||
//! - `macos`
|
|
||||||
//! - `unix`
|
|
||||||
//! - `windows`
|
|
||||||
//!
|
|
||||||
//! However only the module corresponding to the platform you're compiling to will be available.
|
|
||||||
//!
|
|
||||||
pub mod android;
|
|
||||||
pub mod macos;
|
|
||||||
pub mod unix;
|
|
||||||
pub mod windows;
|
|
||||||
231
src/os/unix.rs
@@ -1,231 +0,0 @@
|
|||||||
#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
|
|
||||||
use std::os::raw;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::ptr;
|
|
||||||
use EventsLoop;
|
|
||||||
use MonitorId;
|
|
||||||
use Window;
|
|
||||||
use platform::EventsLoop as LinuxEventsLoop;
|
|
||||||
use platform::Window as LinuxWindow;
|
|
||||||
use WindowBuilder;
|
|
||||||
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;
|
|
||||||
|
|
||||||
/// 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]
|
|
||||||
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>;
|
|
||||||
|
|
||||||
fn get_xlib_xconnection(&self) -> Option<Arc<XConnection>>;
|
|
||||||
|
|
||||||
fn send_xim_spot(&self, x: i16, y: i16);
|
|
||||||
|
|
||||||
/// 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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_xlib_screen_id(&self) -> Option<raw::c_int> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::X(ref w) => Some(w.get_xlib_screen_id()),
|
|
||||||
_ => None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_xlib_xconnection(&self) -> Option<Arc<XConnection>> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::X(ref w) => Some(w.get_xlib_xconnection()),
|
|
||||||
_ => None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_xcb_connection(&self) -> Option<*mut raw::c_void> {
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::X(ref w) => Some(w.get_xcb_connection()),
|
|
||||||
_ => None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn send_xim_spot(&self, x: i16, y: i16) {
|
|
||||||
if let LinuxWindow::X(ref w) = self.window {
|
|
||||||
w.send_xim_spot(x, y);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn get_wayland_surface(&self) -> Option<*mut raw::c_void> {
|
|
||||||
use wayland_client::Proxy;
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::Wayland(ref w) => Some(w.get_surface().ptr() as *mut _),
|
|
||||||
_ => None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn get_wayland_display(&self) -> Option<*mut raw::c_void> {
|
|
||||||
use wayland_client::Proxy;
|
|
||||||
match self.window {
|
|
||||||
LinuxWindow::Wayland(ref w) => Some(w.get_display().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;
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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,58 +0,0 @@
|
|||||||
#![cfg(target_os = "windows")]
|
|
||||||
|
|
||||||
use std::os::raw::c_void;
|
|
||||||
use libc;
|
|
||||||
use MonitorId;
|
|
||||||
use Window;
|
|
||||||
use WindowBuilder;
|
|
||||||
use winapi::shared::windef::HWND;
|
|
||||||
|
|
||||||
/// 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowExt for Window {
|
|
||||||
#[inline]
|
|
||||||
fn get_hwnd(&self) -> *mut libc::c_void {
|
|
||||||
self.window.hwnd() as *mut _
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Additional methods on `WindowBuilder` that are specific to Windows.
|
|
||||||
pub trait WindowBuilderExt {
|
|
||||||
fn with_parent_window(self, parent: HWND) -> WindowBuilder;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowBuilderExt for WindowBuilder {
|
|
||||||
/// Sets a parent to the window to be created.
|
|
||||||
#[inline]
|
|
||||||
fn with_parent_window(mut self, parent: HWND) -> WindowBuilder {
|
|
||||||
self.platform_specific.parent = Some(parent);
|
|
||||||
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 _
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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.15", 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,340 +0,0 @@
|
|||||||
#![cfg(target_os = "android")]
|
|
||||||
|
|
||||||
extern crate android_glue;
|
|
||||||
|
|
||||||
use libc;
|
|
||||||
use std::sync::mpsc::{Receiver, channel};
|
|
||||||
use std::os::raw::c_void;
|
|
||||||
use {CreationError, Event, WindowEvent, MouseCursor};
|
|
||||||
use CreationError::OsError;
|
|
||||||
use WindowId as RootWindowId;
|
|
||||||
use events::{Touch, TouchPhase};
|
|
||||||
use window::MonitorId as RootMonitorId;
|
|
||||||
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
use std::cell::RefCell;
|
|
||||||
|
|
||||||
use CursorState;
|
|
||||||
use WindowAttributes;
|
|
||||||
|
|
||||||
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: RefCell::new(None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_available_monitors(&self) -> VecDeque<MonitorId> {
|
|
||||||
let mut rb = VecDeque::new();
|
|
||||||
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) => {
|
|
||||||
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: (motion.x as f64, motion.y as f64),
|
|
||||||
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 w = unsafe { ffi::ANativeWindow_getWidth(native_window as *const _) } as u32;
|
|
||||||
let h = unsafe { ffi::ANativeWindow_getHeight(native_window as *const _) } as u32;
|
|
||||||
Some(Event::WindowEvent {
|
|
||||||
window_id: RootWindowId(WindowId),
|
|
||||||
event: WindowEvent::Resized(w, h),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
},
|
|
||||||
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;
|
|
||||||
|
|
||||||
mod ffi;
|
|
||||||
|
|
||||||
impl MonitorId {
|
|
||||||
#[inline]
|
|
||||||
pub fn get_name(&self) -> Option<String> {
|
|
||||||
Some("Primary".to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_dimensions(&self) -> (u32, u32) {
|
|
||||||
unsafe {
|
|
||||||
let window = android_glue::get_native_window();
|
|
||||||
(ffi::ANativeWindow_getWidth(window) as u32, ffi::ANativeWindow_getHeight(window) as u32)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_position(&self) -> (i32, i32) {
|
|
||||||
// Android assumes single screen
|
|
||||||
(0, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_hidpi_factor(&self) -> f32 {
|
|
||||||
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>
|
|
||||||
{
|
|
||||||
// not implemented
|
|
||||||
assert!(win_attribs.min_dimensions.is_none());
|
|
||||||
assert!(win_attribs.max_dimensions.is_none());
|
|
||||||
|
|
||||||
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) {
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn show(&self) {
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn hide(&self) {
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_position(&self) -> Option<(i32, i32)> {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_inner_position(&self) -> Option<(i32, i32)> {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_position(&self, _x: i32, _y: i32) {
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_min_dimensions(&self, _dimensions: Option<(u32, u32)>) { }
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_max_dimensions(&self, _dimensions: Option<(u32, u32)>) { }
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
|
|
||||||
if self.native_window.is_null() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some((
|
|
||||||
unsafe { ffi::ANativeWindow_getWidth(self.native_window as *const _) } as u32,
|
|
||||||
unsafe { ffi::ANativeWindow_getHeight(self.native_window as *const _) } as u32
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
|
|
||||||
self.get_inner_size()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_inner_size(&self, _x: u32, _y: u32) {
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn platform_display(&self) -> *mut libc::c_void {
|
|
||||||
unimplemented!();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn platform_window(&self) -> *mut libc::c_void {
|
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor(&self, _: MouseCursor) {
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor_state(&self, _state: CursorState) -> Result<(), String> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn hidpi_factor(&self) -> f32 {
|
|
||||||
1.0
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor_position(&self, _x: i32, _y: i32) -> Result<(), ()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_maximized(&self, _maximized: bool) {
|
|
||||||
// Android has single screen maximized apps so nothing to do
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_fullscreen(&self, _monitor: Option<RootMonitorId>) {
|
|
||||||
// Android has single screen maximized apps so nothing to do
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_decorations(&self, _decorations: bool) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_current_monitor(&self) -> RootMonitorId {
|
|
||||||
RootMonitorId{inner: MonitorId}
|
|
||||||
}
|
|
||||||
|
|
||||||
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,316 +0,0 @@
|
|||||||
#![allow(dead_code)]
|
|
||||||
#![allow(non_snake_case)]
|
|
||||||
#![allow(non_camel_case_types)]
|
|
||||||
|
|
||||||
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,107 +0,0 @@
|
|||||||
use std::ffi::CString;
|
|
||||||
|
|
||||||
use libc;
|
|
||||||
use objc::runtime::{ Object, Class };
|
|
||||||
|
|
||||||
#[allow(non_camel_case_types)]
|
|
||||||
pub type id = *mut Object;
|
|
||||||
|
|
||||||
#[allow(non_camel_case_types)]
|
|
||||||
#[allow(non_upper_case_globals)]
|
|
||||||
pub const nil: id = 0 as id;
|
|
||||||
|
|
||||||
pub type CFStringRef = *const libc::c_void;
|
|
||||||
pub type CFTimeInterval = f64;
|
|
||||||
pub type Boolean = u32;
|
|
||||||
|
|
||||||
#[allow(non_upper_case_globals)]
|
|
||||||
pub const kCFRunLoopRunHandledSource: i32 = 4;
|
|
||||||
|
|
||||||
#[cfg(target_pointer_width = "32")]
|
|
||||||
pub type CGFloat = f32;
|
|
||||||
#[cfg(target_pointer_width = "64")]
|
|
||||||
pub type CGFloat = f64;
|
|
||||||
|
|
||||||
#[cfg(target_pointer_width = "32")]
|
|
||||||
pub type NSUInteger = u32;
|
|
||||||
#[cfg(target_pointer_width = "64")]
|
|
||||||
pub type NSUInteger = u64;
|
|
||||||
|
|
||||||
#[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: libc::c_int, argv: *const libc::c_char, principalClassName: id, delegateClassName: id) -> libc::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 libc::c_void) -> libc::c_int;
|
|
||||||
pub fn longjmp(env: *mut libc::c_void, val: libc::c_int);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait NSString: Sized {
|
|
||||||
unsafe fn alloc(_: Self) -> id {
|
|
||||||
msg_send![class("NSString"), alloc]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
unsafe fn initWithUTF8String_(self, c_string: *const i8) -> id;
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
unsafe fn stringByAppendingString_(self, other: id) -> id;
|
|
||||||
unsafe fn init_str(self, string: &str) -> Self;
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
unsafe fn UTF8String(self) -> *const libc::c_char;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl NSString for id {
|
|
||||||
unsafe fn initWithUTF8String_(self, c_string: *const i8) -> 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 libc::c_char {
|
|
||||||
msg_send![self, UTF8String]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn class(name: &str) -> *mut Class {
|
|
||||||
unsafe {
|
|
||||||
::std::mem::transmute(Class::get(name))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,564 +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_glutin_app() {
|
|
||||||
//! start_inner()
|
|
||||||
//! }
|
|
||||||
//!
|
|
||||||
//! fn start_inner() {
|
|
||||||
//! ...
|
|
||||||
//! }
|
|
||||||
//!
|
|
||||||
//! ```
|
|
||||||
//!
|
|
||||||
//! Compile project and then drag resulting .a into Xcode project. Add glutin.h to xcode.
|
|
||||||
//!
|
|
||||||
//! ```ignore
|
|
||||||
//! void start_glutin_app();
|
|
||||||
//! ```
|
|
||||||
//!
|
|
||||||
//! Use start_glutin_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 glutin:
|
|
||||||
//!
|
|
||||||
//! - 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::collections::VecDeque;
|
|
||||||
use std::ptr;
|
|
||||||
use std::mem;
|
|
||||||
use std::os::raw::c_void;
|
|
||||||
|
|
||||||
use libc;
|
|
||||||
use libc::c_int;
|
|
||||||
use objc::runtime::{Class, Object, Sel, BOOL, YES };
|
|
||||||
use objc::declare::{ ClassDecl };
|
|
||||||
|
|
||||||
use { CreationError, CursorState, MouseCursor, WindowAttributes };
|
|
||||||
use WindowId as RootEventId;
|
|
||||||
use WindowEvent;
|
|
||||||
use Event;
|
|
||||||
use events::{ Touch, TouchPhase };
|
|
||||||
use window::MonitorId as RootMonitorId;
|
|
||||||
|
|
||||||
mod ffi;
|
|
||||||
use self::ffi::{
|
|
||||||
setjmp,
|
|
||||||
UIApplicationMain,
|
|
||||||
CFTimeInterval,
|
|
||||||
CFRunLoopRunInMode,
|
|
||||||
kCFRunLoopDefaultMode,
|
|
||||||
kCFRunLoopRunHandledSource,
|
|
||||||
id,
|
|
||||||
nil,
|
|
||||||
NSString,
|
|
||||||
CGFloat,
|
|
||||||
longjmp,
|
|
||||||
CGRect,
|
|
||||||
CGPoint
|
|
||||||
};
|
|
||||||
|
|
||||||
static mut jmpbuf: [c_int;27] = [0;27];
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct MonitorId;
|
|
||||||
|
|
||||||
pub struct Window {
|
|
||||||
delegate_state: *mut DelegateState
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct WindowProxy;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct DelegateState {
|
|
||||||
events_queue: VecDeque<Event>,
|
|
||||||
window: id,
|
|
||||||
controller: id,
|
|
||||||
size: (u32,u32),
|
|
||||||
scale: f32
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
impl DelegateState {
|
|
||||||
#[inline]
|
|
||||||
fn new(window: id, controller:id, size: (u32,u32), scale: f32) -> DelegateState {
|
|
||||||
DelegateState {
|
|
||||||
events_queue: VecDeque::new(),
|
|
||||||
window: window,
|
|
||||||
controller: controller,
|
|
||||||
size: size,
|
|
||||||
scale: scale
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorId {
|
|
||||||
#[inline]
|
|
||||||
pub fn get_name(&self) -> Option<String> {
|
|
||||||
Some("Primary".to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_dimensions(&self) -> (u32, u32) {
|
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_position(&self) -> (i32, i32) {
|
|
||||||
// iOS assumes single screen
|
|
||||||
(0, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_hidpi_factor(&self) -> f32 {
|
|
||||||
1.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct EventsLoop {
|
|
||||||
delegate_state: *mut DelegateState
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct EventsLoopProxy;
|
|
||||||
|
|
||||||
impl EventsLoop {
|
|
||||||
pub fn new() -> EventsLoop {
|
|
||||||
unsafe {
|
|
||||||
if setjmp(mem::transmute(&mut jmpbuf)) != 0 {
|
|
||||||
let app: id = msg_send![Class::get("UIApplication").unwrap(), sharedApplication];
|
|
||||||
let delegate: id = msg_send![app, delegate];
|
|
||||||
let state: *mut c_void = *(&*delegate).get_ivar("glutinState");
|
|
||||||
let state = state as *mut DelegateState;
|
|
||||||
|
|
||||||
let events_loop = EventsLoop {
|
|
||||||
delegate_state: state
|
|
||||||
};
|
|
||||||
|
|
||||||
return events_loop;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
create_delegate_class();
|
|
||||||
create_view_class();
|
|
||||||
start_app();
|
|
||||||
|
|
||||||
panic!("Couldn't create UIApplication")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_available_monitors(&self) -> VecDeque<MonitorId> {
|
|
||||||
let mut rb = VecDeque::new();
|
|
||||||
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)
|
|
||||||
{
|
|
||||||
unsafe {
|
|
||||||
let state = &mut *self.delegate_state;
|
|
||||||
|
|
||||||
if let Some(event) = state.events_queue.pop_front() {
|
|
||||||
callback(event);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// jump hack, so we won't quit on willTerminate event before processing it
|
|
||||||
if setjmp(mem::transmute(&mut jmpbuf)) != 0 {
|
|
||||||
if let Some(event) = state.events_queue.pop_front() {
|
|
||||||
callback(event);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// run runloop
|
|
||||||
let seconds: CFTimeInterval = 0.000002;
|
|
||||||
while CFRunLoopRunInMode(kCFRunLoopDefaultMode, seconds, 1) == kCFRunLoopRunHandledSource {}
|
|
||||||
|
|
||||||
if let Some(event) = state.events_queue.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, Default)]
|
|
||||||
pub struct PlatformSpecificWindowBuilderAttributes;
|
|
||||||
|
|
||||||
impl Window {
|
|
||||||
pub fn new(ev: &EventsLoop, _: &WindowAttributes, _: &PlatformSpecificWindowBuilderAttributes)
|
|
||||||
-> Result<Window, CreationError>
|
|
||||||
{
|
|
||||||
Ok(Window {
|
|
||||||
delegate_state: ev.delegate_state,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_title(&self, _: &str) {
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn show(&self) {
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn hide(&self) {
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_position(&self) -> Option<(i32, i32)> {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_inner_position(&self) -> Option<(i32, i32)> {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_position(&self, _x: i32, _y: i32) {
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
|
|
||||||
unsafe { Some((&*self.delegate_state).size) }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
|
|
||||||
self.get_inner_size()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_inner_size(&self, _x: u32, _y: u32) {
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_min_dimensions(&self, _dimensions: Option<(u32, u32)>) { }
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_max_dimensions(&self, _dimensions: Option<(u32, u32)>) { }
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn platform_display(&self) -> *mut libc::c_void {
|
|
||||||
unimplemented!();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn platform_window(&self) -> *mut libc::c_void {
|
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) {
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor(&self, _: MouseCursor) {
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor_state(&self, _: CursorState) -> Result<(), String> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn hidpi_factor(&self) -> f32 {
|
|
||||||
unsafe { (&*self.delegate_state) }.scale
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor_position(&self, _x: i32, _y: i32) -> Result<(), ()> {
|
|
||||||
unimplemented!();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn create_window_proxy(&self) -> WindowProxy {
|
|
||||||
WindowProxy
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_maximized(&self, _maximized: bool) {
|
|
||||||
// iOS has single screen maximized apps so nothing to do
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_fullscreen(&self, _monitor: Option<RootMonitorId>) {
|
|
||||||
// iOS has single screen maximized apps so nothing to do
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_decorations(&self, _decorations: bool) {
|
|
||||||
// N/A
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_current_monitor(&self) -> RootMonitorId {
|
|
||||||
RootMonitorId{inner: MonitorId}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn id(&self) -> WindowId {
|
|
||||||
WindowId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn create_delegate_class() {
|
|
||||||
extern fn did_finish_launching(this: &mut Object, _: Sel, _: id, _: id) -> BOOL {
|
|
||||||
unsafe {
|
|
||||||
let main_screen: id = msg_send![Class::get("UIScreen").unwrap(), mainScreen];
|
|
||||||
let bounds: CGRect = msg_send![main_screen, bounds];
|
|
||||||
let scale: CGFloat = msg_send![main_screen, nativeScale];
|
|
||||||
|
|
||||||
let window: id = msg_send![Class::get("UIWindow").unwrap(), alloc];
|
|
||||||
let window: id = msg_send![window, initWithFrame:bounds.clone()];
|
|
||||||
|
|
||||||
let size = (bounds.size.width as u32, bounds.size.height as u32);
|
|
||||||
|
|
||||||
let view_controller: id = msg_send![Class::get("MainViewController").unwrap(), alloc];
|
|
||||||
let view_controller: id = msg_send![view_controller, init];
|
|
||||||
|
|
||||||
let _: () = msg_send![window, setRootViewController:view_controller];
|
|
||||||
let _: () = msg_send![window, makeKeyAndVisible];
|
|
||||||
|
|
||||||
let state = Box::new(DelegateState::new(window, view_controller, size, scale as f32));
|
|
||||||
let state_ptr: *mut DelegateState = mem::transmute(state);
|
|
||||||
this.set_ivar("glutinState", state_ptr as *mut c_void);
|
|
||||||
|
|
||||||
|
|
||||||
let _: () = msg_send![this, performSelector:sel!(postLaunch:) withObject:nil afterDelay:0.0];
|
|
||||||
}
|
|
||||||
YES
|
|
||||||
}
|
|
||||||
|
|
||||||
extern fn post_launch(_: &Object, _: Sel, _: id) {
|
|
||||||
unsafe { longjmp(mem::transmute(&mut jmpbuf),1); }
|
|
||||||
}
|
|
||||||
|
|
||||||
extern fn did_become_active(this: &Object, _: Sel, _: id) {
|
|
||||||
unsafe {
|
|
||||||
let state: *mut c_void = *this.get_ivar("glutinState");
|
|
||||||
let state = &mut *(state as *mut DelegateState);
|
|
||||||
state.events_queue.push_back(Event::WindowEvent {
|
|
||||||
window_id: RootEventId(WindowId),
|
|
||||||
event: WindowEvent::Focused(true),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extern fn will_resign_active(this: &Object, _: Sel, _: id) {
|
|
||||||
unsafe {
|
|
||||||
let state: *mut c_void = *this.get_ivar("glutinState");
|
|
||||||
let state = &mut *(state as *mut DelegateState);
|
|
||||||
state.events_queue.push_back(Event::WindowEvent {
|
|
||||||
window_id: RootEventId(WindowId),
|
|
||||||
event: WindowEvent::Focused(false),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extern fn will_enter_foreground(this: &Object, _: Sel, _: id) {
|
|
||||||
unsafe {
|
|
||||||
let state: *mut c_void = *this.get_ivar("glutinState");
|
|
||||||
let state = &mut *(state as *mut DelegateState);
|
|
||||||
state.events_queue.push_back(Event::Suspended(false));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extern fn did_enter_background(this: &Object, _: Sel, _: id) {
|
|
||||||
unsafe {
|
|
||||||
let state: *mut c_void = *this.get_ivar("glutinState");
|
|
||||||
let state = &mut *(state as *mut DelegateState);
|
|
||||||
state.events_queue.push_back(Event::Suspended(true));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extern fn will_terminate(this: &Object, _: Sel, _: id) {
|
|
||||||
unsafe {
|
|
||||||
let state: *mut c_void = *this.get_ivar("glutinState");
|
|
||||||
let state = &mut *(state as *mut DelegateState);
|
|
||||||
// push event to the front to garantee that we'll process it
|
|
||||||
// immidiatly after jump
|
|
||||||
state.events_queue.push_front(Event::WindowEvent {
|
|
||||||
window_id: RootEventId(WindowId),
|
|
||||||
event: WindowEvent::Destroyed,
|
|
||||||
});
|
|
||||||
longjmp(mem::transmute(&mut jmpbuf),1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extern fn handle_touches(this: &Object, _: Sel, touches: id, _:id) {
|
|
||||||
unsafe {
|
|
||||||
let state: *mut c_void = *this.get_ivar("glutinState");
|
|
||||||
let state = &mut *(state as *mut DelegateState);
|
|
||||||
|
|
||||||
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];
|
|
||||||
|
|
||||||
state.events_queue.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),
|
|
||||||
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::get("UIResponder").unwrap();
|
|
||||||
let mut decl = ClassDecl::new("AppDelegate", ui_responder).unwrap();
|
|
||||||
|
|
||||||
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>("glutinState");
|
|
||||||
|
|
||||||
decl.register();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn create_view_class() {
|
|
||||||
let ui_view_controller = Class::get("UIViewController").unwrap();
|
|
||||||
let decl = ClassDecl::new("MainViewController", ui_view_controller).unwrap();
|
|
||||||
|
|
||||||
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 = "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,451 +0,0 @@
|
|||||||
#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::env;
|
|
||||||
|
|
||||||
use {CreationError, CursorState, EventsLoopClosed, MouseCursor, ControlFlow};
|
|
||||||
use libc;
|
|
||||||
|
|
||||||
use self::x11::XConnection;
|
|
||||||
use self::x11::XError;
|
|
||||||
use self::x11::ffi::XVisualInfo;
|
|
||||||
|
|
||||||
pub use self::x11::XNotSupported;
|
|
||||||
use window::MonitorId as RootMonitorId;
|
|
||||||
|
|
||||||
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>,
|
|
||||||
}
|
|
||||||
|
|
||||||
lazy_static!(
|
|
||||||
pub static ref X11_BACKEND: Result<Arc<XConnection>, XNotSupported> = {
|
|
||||||
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(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) -> (u32, u32) {
|
|
||||||
match self {
|
|
||||||
&MonitorId::X(ref m) => m.get_dimensions(),
|
|
||||||
&MonitorId::Wayland(ref m) => m.get_dimensions(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_position(&self) -> (i32, i32) {
|
|
||||||
match self {
|
|
||||||
&MonitorId::X(ref m) => m.get_position(),
|
|
||||||
&MonitorId::Wayland(ref m) => m.get_position(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_hidpi_factor(&self) -> f32 {
|
|
||||||
match self {
|
|
||||||
&MonitorId::X(ref m) => m.get_hidpi_factor(),
|
|
||||||
&MonitorId::Wayland(ref m) => m.get_hidpi_factor(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Window {
|
|
||||||
#[inline]
|
|
||||||
pub fn new(events_loop: &EventsLoop,
|
|
||||||
window: &::WindowAttributes,
|
|
||||||
pl_attribs: &PlatformSpecificWindowBuilderAttributes)
|
|
||||||
-> Result<Self, CreationError>
|
|
||||||
{
|
|
||||||
match *events_loop {
|
|
||||||
EventsLoop::Wayland(ref evlp) => {
|
|
||||||
wayland::Window::new(evlp, window).map(Window::Wayland)
|
|
||||||
},
|
|
||||||
|
|
||||||
EventsLoop::X(ref el) => {
|
|
||||||
x11::Window::new(el, window, 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<(i32, i32)> {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.get_position(),
|
|
||||||
&Window::Wayland(ref w) => w.get_position()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_inner_position(&self) -> Option<(i32, i32)> {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref m) => m.get_inner_position(),
|
|
||||||
&Window::Wayland(ref m) => m.get_inner_position(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_position(&self, x: i32, y: i32) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_position(x, y),
|
|
||||||
&Window::Wayland(ref w) => w.set_position(x, y)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
|
|
||||||
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<(u32, u32)> {
|
|
||||||
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, x: u32, y: u32) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_inner_size(x, y),
|
|
||||||
&Window::Wayland(ref w) => w.set_inner_size(x, y)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_min_dimensions(&self, dimensions: Option<(u32, u32)>) {
|
|
||||||
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<(u32, u32)>) {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_max_dimensions(dimensions),
|
|
||||||
&Window::Wayland(ref w) => w.set_max_dimensions(dimensions)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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 set_cursor_state(&self, state: CursorState) -> Result<(), String> {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_cursor_state(state),
|
|
||||||
&Window::Wayland(ref w) => w.set_cursor_state(state)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn hidpi_factor(&self) -> f32 {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.hidpi_factor(),
|
|
||||||
&Window::Wayland(ref w) => w.hidpi_factor()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.set_cursor_position(x, y),
|
|
||||||
&Window::Wayland(ref w) => w.set_cursor_position(x, y)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn platform_display(&self) -> *mut libc::c_void {
|
|
||||||
use wayland_client::Proxy;
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.platform_display(),
|
|
||||||
&Window::Wayland(ref w) => w.get_display().ptr() as *mut _
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn platform_window(&self) -> *mut libc::c_void {
|
|
||||||
use wayland_client::Proxy;
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => w.platform_window(),
|
|
||||||
&Window::Wayland(ref w) => w.get_surface().ptr() as *mut _
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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 get_current_monitor(&self) -> RootMonitorId {
|
|
||||||
match self {
|
|
||||||
&Window::X(ref w) => RootMonitorId{inner: MonitorId::X(w.get_current_monitor())},
|
|
||||||
&Window::Wayland(ref w) => RootMonitorId{inner: MonitorId::Wayland(w.get_current_monitor())},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe extern "C" fn x_error_callback(dpy: *mut x11::ffi::Display, event: *mut x11::ffi::XErrorEvent)
|
|
||||||
-> libc::c_int
|
|
||||||
{
|
|
||||||
use std::ffi::CStr;
|
|
||||||
|
|
||||||
if let Ok(ref x) = *X11_BACKEND {
|
|
||||||
let mut buff: Vec<u8> = Vec::with_capacity(1024);
|
|
||||||
(x.xlib.XGetErrorText)(dpy, (*event).error_code as i32, buff.as_mut_ptr() as *mut libc::c_char, buff.capacity() as i32);
|
|
||||||
let description = CStr::from_ptr(buff.as_mut_ptr() as *const libc::c_char).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,
|
|
||||||
};
|
|
||||||
|
|
||||||
*x.latest_error.lock().unwrap() = Some(error);
|
|
||||||
}
|
|
||||||
|
|
||||||
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" => {
|
|
||||||
return EventsLoop::new_x11().unwrap(); // TODO: propagate
|
|
||||||
},
|
|
||||||
"wayland" => {
|
|
||||||
match EventsLoop::new_wayland() {
|
|
||||||
Ok(e) => return e,
|
|
||||||
Err(_) => panic!() // TODO: propagate
|
|
||||||
}
|
|
||||||
},
|
|
||||||
_ => panic!("Unknown environment variable value for {}, try one of `x11`,`wayland`",
|
|
||||||
BACKEND_PREFERENCE_ENV_VAR),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Ok(el) = EventsLoop::new_wayland() {
|
|
||||||
return el;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Ok(el) = EventsLoop::new_x11() {
|
|
||||||
return el;
|
|
||||||
}
|
|
||||||
|
|
||||||
panic!("No backend is available")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_wayland() -> Result<EventsLoop, ()> {
|
|
||||||
wayland::EventsLoop::new()
|
|
||||||
.map(EventsLoop::Wayland)
|
|
||||||
.ok_or(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_x11() -> Result<EventsLoop, XNotSupported> {
|
|
||||||
match *X11_BACKEND {
|
|
||||||
Ok(ref x) => Ok(EventsLoop::X(x11::EventsLoop::new(x.clone()))),
|
|
||||||
Err(ref 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) => x11::get_available_monitors(evlp.x_connection())
|
|
||||||
.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(x11::get_primary_monitor(evlp.x_connection())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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,594 +0,0 @@
|
|||||||
use std::cell::RefCell;
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
use std::sync::{Arc, Mutex, Weak};
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
|
||||||
|
|
||||||
use {EventsLoopClosed, ControlFlow};
|
|
||||||
|
|
||||||
use super::WindowId;
|
|
||||||
use super::window::WindowStore;
|
|
||||||
use super::keyboard::init_keyboard;
|
|
||||||
|
|
||||||
use wayland_client::{EnvHandler, EnvNotify, default_connect, EventQueue, EventQueueHandle, Proxy, StateToken};
|
|
||||||
use wayland_client::protocol::{wl_compositor, wl_seat, wl_shell, wl_shm, wl_subcompositor,
|
|
||||||
wl_display, wl_registry, wl_output, wl_surface,
|
|
||||||
wl_pointer, wl_keyboard, wl_touch};
|
|
||||||
|
|
||||||
use super::wayland_window::{Frame, Shell, create_frame, FrameImplementation};
|
|
||||||
use super::wayland_protocols::unstable::xdg_shell::v6::client::zxdg_shell_v6;
|
|
||||||
|
|
||||||
pub struct EventsLoopSink {
|
|
||||||
buffer: VecDeque<::Event>
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe impl Send for EventsLoopSink { }
|
|
||||||
|
|
||||||
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: StateToken<WindowStore>,
|
|
||||||
// the env
|
|
||||||
env_token: StateToken<EnvHandler<InnerEnv>>,
|
|
||||||
// the ctxt
|
|
||||||
pub ctxt_token: StateToken<StateContext>,
|
|
||||||
// a cleanup switch to prune dead windows
|
|
||||||
pub cleanup_needed: Arc<Mutex<bool>>,
|
|
||||||
// The wayland display
|
|
||||||
pub display: Arc<wl_display::WlDisplay>,
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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<wl_display::WlDisplay>,
|
|
||||||
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.
|
|
||||||
display.sync();
|
|
||||||
display.flush().map_err(|_| EventsLoopClosed)?;
|
|
||||||
Ok(())
|
|
||||||
},
|
|
||||||
_ => Err(EventsLoopClosed),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventsLoop {
|
|
||||||
pub fn new() -> Option<EventsLoop> {
|
|
||||||
let (display, mut event_queue) = match default_connect() {
|
|
||||||
Ok(ret) => ret,
|
|
||||||
Err(_) => return None
|
|
||||||
};
|
|
||||||
|
|
||||||
let registry = display.get_registry();
|
|
||||||
let ctxt_token = event_queue.state().insert(
|
|
||||||
StateContext::new(registry.clone().unwrap())
|
|
||||||
);
|
|
||||||
let env_token = EnvHandler::init_with_notify(
|
|
||||||
&mut event_queue,
|
|
||||||
®istry,
|
|
||||||
env_notify(),
|
|
||||||
ctxt_token.clone()
|
|
||||||
);
|
|
||||||
|
|
||||||
// two round trips to fully initialize
|
|
||||||
event_queue.sync_roundtrip().expect("Wayland connection unexpectedly lost");
|
|
||||||
event_queue.sync_roundtrip().expect("Wayland connection unexpectedly lost");
|
|
||||||
|
|
||||||
event_queue.state().with_value(&ctxt_token, |proxy, ctxt| {
|
|
||||||
ctxt.ensure_shell(proxy.get_mut(&env_token))
|
|
||||||
});
|
|
||||||
|
|
||||||
let sink = Arc::new(Mutex::new(EventsLoopSink::new()));
|
|
||||||
|
|
||||||
let store = event_queue.state().insert(WindowStore::new());
|
|
||||||
|
|
||||||
let seat_idata = SeatIData {
|
|
||||||
sink: sink.clone(),
|
|
||||||
keyboard: None,
|
|
||||||
pointer: None,
|
|
||||||
touch: None,
|
|
||||||
windows_token: store.clone()
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut me = EventsLoop {
|
|
||||||
display: Arc::new(display),
|
|
||||||
evq: RefCell::new(event_queue),
|
|
||||||
sink: sink,
|
|
||||||
pending_wakeup: Arc::new(AtomicBool::new(false)),
|
|
||||||
store: store,
|
|
||||||
ctxt_token: ctxt_token,
|
|
||||||
env_token: env_token,
|
|
||||||
cleanup_needed: Arc::new(Mutex::new(false))
|
|
||||||
};
|
|
||||||
|
|
||||||
me.init_seat(|evqh, seat| {
|
|
||||||
evqh.register(seat, seat_implementation(), seat_idata);
|
|
||||||
});
|
|
||||||
|
|
||||||
Some(me)
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
|
||||||
let mut guard = self.evq.borrow_mut();
|
|
||||||
let state = guard.state();
|
|
||||||
let state_ctxt = state.get(&self.ctxt_token);
|
|
||||||
if let Some(info) = state_ctxt.monitors.iter().next() {
|
|
||||||
MonitorId {
|
|
||||||
info: info.clone()
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("No monitor is available.")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_available_monitors(&self) -> VecDeque<MonitorId> {
|
|
||||||
let mut guard = self.evq.borrow_mut();
|
|
||||||
let state = guard.state();
|
|
||||||
let state_ctxt = state.get(&self.ctxt_token);
|
|
||||||
state_ctxt.monitors.iter()
|
|
||||||
.map(|m| MonitorId { info: m.clone() })
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Private EventsLoop Internals
|
|
||||||
*/
|
|
||||||
|
|
||||||
wayland_env!(InnerEnv,
|
|
||||||
compositor: wl_compositor::WlCompositor,
|
|
||||||
shm: wl_shm::WlShm,
|
|
||||||
subcompositor: wl_subcompositor::WlSubcompositor
|
|
||||||
);
|
|
||||||
|
|
||||||
pub struct StateContext {
|
|
||||||
registry: wl_registry::WlRegistry,
|
|
||||||
seat: Option<wl_seat::WlSeat>,
|
|
||||||
shell: Option<Shell>,
|
|
||||||
monitors: Vec<Arc<Mutex<OutputInfo>>>
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StateContext {
|
|
||||||
fn new(registry: wl_registry::WlRegistry) -> StateContext {
|
|
||||||
StateContext {
|
|
||||||
registry: registry,
|
|
||||||
seat: None,
|
|
||||||
shell: None,
|
|
||||||
monitors: Vec::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Ensures a shell is available
|
|
||||||
///
|
|
||||||
/// If a shell is already bound, do nothing. Otherwise,
|
|
||||||
/// try to bind wl_shell as a fallback. If this fails,
|
|
||||||
/// panic, as this is a bug from the compositor.
|
|
||||||
fn ensure_shell(&mut self, env: &mut EnvHandler<InnerEnv>) {
|
|
||||||
if self.shell.is_some() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// xdg_shell is not available, so initialize wl_shell
|
|
||||||
for &(name, ref interface, _) in env.globals() {
|
|
||||||
if interface == "wl_shell" {
|
|
||||||
self.shell = Some(Shell::Wl(self.registry.bind::<wl_shell::WlShell>(1, name)));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// This is a compositor bug, it _must_ at least support wl_shell
|
|
||||||
panic!("Compositor didi not advertize xdg_shell not wl_shell.");
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn monitor_id_for(&self, output: &wl_output::WlOutput) -> MonitorId {
|
|
||||||
for info in &self.monitors {
|
|
||||||
let guard = info.lock().unwrap();
|
|
||||||
if guard.output.equals(output) {
|
|
||||||
return MonitorId {
|
|
||||||
info: info.clone()
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
panic!("Received an inexistent wl_output?!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EventsLoop {
|
|
||||||
pub fn init_seat<F>(&mut self, f: F)
|
|
||||||
where F: FnOnce(&mut EventQueueHandle, &wl_seat::WlSeat)
|
|
||||||
{
|
|
||||||
let mut guard = self.evq.borrow_mut();
|
|
||||||
if guard.state().get(&self.ctxt_token).seat.is_some() {
|
|
||||||
// seat has already been init
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// clone the token to make borrow checker happy
|
|
||||||
let ctxt_token = self.ctxt_token.clone();
|
|
||||||
let seat = guard.state().with_value(&self.env_token, |proxy, env| {
|
|
||||||
let ctxt = proxy.get(&ctxt_token);
|
|
||||||
for &(name, ref interface, _) in env.globals() {
|
|
||||||
if interface == wl_seat::WlSeat::interface_name() {
|
|
||||||
return Some(ctxt.registry.bind::<wl_seat::WlSeat>(5, name));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
});
|
|
||||||
|
|
||||||
if let Some(seat) = seat {
|
|
||||||
f(&mut *guard, &seat);
|
|
||||||
guard.state().get_mut(&self.ctxt_token).seat = Some(seat)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn post_dispatch_triggers(&mut self) {
|
|
||||||
let mut sink = self.sink.lock().unwrap();
|
|
||||||
let evq = self.evq.get_mut();
|
|
||||||
// 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 = evq.state().get_mut(&self.store).cleanup();
|
|
||||||
*cleanup_needed = false;
|
|
||||||
for wid in pruned {
|
|
||||||
sink.send_event(::WindowEvent::Destroyed, wid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// process pending resize/refresh
|
|
||||||
evq.state().get_mut(&self.store).for_each(
|
|
||||||
|newsize, refresh, frame_refresh, closed, wid, frame| {
|
|
||||||
if let Some(frame) = frame {
|
|
||||||
if let Some((w, h)) = newsize {
|
|
||||||
frame.resize(w as i32, h as i32);
|
|
||||||
frame.refresh();
|
|
||||||
sink.send_event(::WindowEvent::Resized(w as u32, h as u32), wid);
|
|
||||||
} else if frame_refresh {
|
|
||||||
frame.refresh();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if refresh {
|
|
||||||
sink.send_event(::WindowEvent::Refresh, wid);
|
|
||||||
}
|
|
||||||
if closed {
|
|
||||||
sink.send_event(::WindowEvent::CloseRequested, wid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create a new window with given dimensions
|
|
||||||
///
|
|
||||||
/// Grabs a lock on the event queue in the process
|
|
||||||
pub fn create_window<ID: 'static, F>(&self, width: u32, height: u32, implem: FrameImplementation<ID>, idata: F)
|
|
||||||
-> (wl_surface::WlSurface, Frame)
|
|
||||||
where F: FnOnce(&wl_surface::WlSurface) -> ID
|
|
||||||
{
|
|
||||||
let (surface, frame) = {
|
|
||||||
let mut guard = self.evq.borrow_mut();
|
|
||||||
let env = guard.state().get(&self.env_token).clone_inner().unwrap();
|
|
||||||
let shell = match guard.state().get(&self.ctxt_token).shell {
|
|
||||||
Some(Shell::Wl(ref wl_shell)) => Shell::Wl(wl_shell.clone().unwrap()),
|
|
||||||
Some(Shell::Xdg(ref xdg_shell)) => Shell::Xdg(xdg_shell.clone().unwrap()),
|
|
||||||
None => unreachable!()
|
|
||||||
};
|
|
||||||
let seat = guard.state().get(&self.ctxt_token).seat.as_ref().and_then(|s| s.clone());
|
|
||||||
let surface = env.compositor.create_surface();
|
|
||||||
let frame = create_frame(
|
|
||||||
&mut guard,
|
|
||||||
implem,
|
|
||||||
idata(&surface),
|
|
||||||
&surface, width as i32, height as i32,
|
|
||||||
&env.compositor,
|
|
||||||
&env.subcompositor,
|
|
||||||
&env.shm,
|
|
||||||
&shell,
|
|
||||||
seat
|
|
||||||
).expect("Failed to create a tmpfile buffer.");
|
|
||||||
(surface, frame)
|
|
||||||
};
|
|
||||||
|
|
||||||
(surface, frame)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Wayland protocol implementations
|
|
||||||
*/
|
|
||||||
|
|
||||||
fn env_notify() -> EnvNotify<StateToken<StateContext>> {
|
|
||||||
EnvNotify {
|
|
||||||
new_global: |evqh, token, registry, id, interface, version| {
|
|
||||||
use std::cmp::min;
|
|
||||||
if interface == wl_output::WlOutput::interface_name() {
|
|
||||||
// a new output is available
|
|
||||||
let output = registry.bind::<wl_output::WlOutput>(min(version, 3), id);
|
|
||||||
evqh.register(&output, output_impl(), token.clone());
|
|
||||||
evqh.state().get_mut(&token).monitors.push(
|
|
||||||
Arc::new(Mutex::new(OutputInfo::new(output, id)))
|
|
||||||
);
|
|
||||||
} else if interface == zxdg_shell_v6::ZxdgShellV6::interface_name() {
|
|
||||||
// We have an xdg_shell, bind it
|
|
||||||
let xdg_shell = registry.bind::<zxdg_shell_v6::ZxdgShellV6>(1, id);
|
|
||||||
evqh.register(&xdg_shell, xdg_ping_implementation(), ());
|
|
||||||
evqh.state().get_mut(&token).shell = Some(Shell::Xdg(xdg_shell));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
del_global: |evqh, token, _, id| {
|
|
||||||
// maybe this was a monitor, cleanup
|
|
||||||
evqh.state().get_mut(&token).monitors.retain(
|
|
||||||
|m| m.lock().unwrap().id != id
|
|
||||||
);
|
|
||||||
},
|
|
||||||
ready: |_, _, _| {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn xdg_ping_implementation() -> zxdg_shell_v6::Implementation<()> {
|
|
||||||
zxdg_shell_v6::Implementation {
|
|
||||||
ping: |_, _, shell, serial| {
|
|
||||||
shell.pong(serial);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct SeatIData {
|
|
||||||
sink: Arc<Mutex<EventsLoopSink>>,
|
|
||||||
pointer: Option<wl_pointer::WlPointer>,
|
|
||||||
keyboard: Option<wl_keyboard::WlKeyboard>,
|
|
||||||
touch: Option<wl_touch::WlTouch>,
|
|
||||||
windows_token: StateToken<WindowStore>
|
|
||||||
}
|
|
||||||
|
|
||||||
fn seat_implementation() -> wl_seat::Implementation<SeatIData> {
|
|
||||||
wl_seat::Implementation {
|
|
||||||
name: |_, _, _, _| {},
|
|
||||||
capabilities: |evqh, idata, seat, capabilities| {
|
|
||||||
// create pointer if applicable
|
|
||||||
if capabilities.contains(wl_seat::Capability::Pointer) && idata.pointer.is_none() {
|
|
||||||
let pointer = seat.get_pointer().expect("Seat is not dead");
|
|
||||||
let p_idata = super::pointer::PointerIData::new(
|
|
||||||
&idata.sink,
|
|
||||||
idata.windows_token.clone()
|
|
||||||
);
|
|
||||||
evqh.register(&pointer, super::pointer::pointer_implementation(), p_idata);
|
|
||||||
idata.pointer = Some(pointer);
|
|
||||||
}
|
|
||||||
// destroy pointer if applicable
|
|
||||||
if !capabilities.contains(wl_seat::Capability::Pointer) {
|
|
||||||
if let Some(pointer) = idata.pointer.take() {
|
|
||||||
pointer.release();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// create keyboard if applicable
|
|
||||||
if capabilities.contains(wl_seat::Capability::Keyboard) && idata.keyboard.is_none() {
|
|
||||||
let kbd = seat.get_keyboard().expect("Seat is not dead");
|
|
||||||
init_keyboard(evqh, &kbd, &idata.sink);
|
|
||||||
idata.keyboard = Some(kbd);
|
|
||||||
}
|
|
||||||
// destroy keyboard if applicable
|
|
||||||
if !capabilities.contains(wl_seat::Capability::Keyboard) {
|
|
||||||
if let Some(kbd) = idata.keyboard.take() {
|
|
||||||
kbd.release();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// create touch if applicable
|
|
||||||
if capabilities.contains(wl_seat::Capability::Touch) && idata.touch.is_none() {
|
|
||||||
let touch = seat.get_touch().expect("Seat is not dead");
|
|
||||||
let t_idata = super::touch::TouchIData::new(
|
|
||||||
&idata.sink,
|
|
||||||
idata.windows_token.clone()
|
|
||||||
);
|
|
||||||
evqh.register(&touch, super::touch::touch_implementation(), t_idata);
|
|
||||||
idata.touch = Some(touch);
|
|
||||||
}
|
|
||||||
// destroy touch if applicable
|
|
||||||
if !capabilities.contains(wl_seat::Capability::Touch) {
|
|
||||||
if let Some(touch) = idata.touch.take() {
|
|
||||||
touch.release();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Monitor stuff
|
|
||||||
*/
|
|
||||||
|
|
||||||
fn output_impl() -> wl_output::Implementation<StateToken<StateContext>> {
|
|
||||||
wl_output::Implementation {
|
|
||||||
geometry: |evqh, token, output, x, y, _, _, _, make, model, _| {
|
|
||||||
let ctxt = evqh.state().get_mut(token);
|
|
||||||
for info in &ctxt.monitors {
|
|
||||||
let mut guard = info.lock().unwrap();
|
|
||||||
if guard.output.equals(output) {
|
|
||||||
guard.pix_pos = (x, y);
|
|
||||||
guard.name = format!("{} - {}", make, model);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
mode: |evqh, token, output, flags, w, h, _refresh| {
|
|
||||||
if flags.contains(wl_output::Mode::Current) {
|
|
||||||
let ctxt = evqh.state().get_mut(token);
|
|
||||||
for info in &ctxt.monitors {
|
|
||||||
let mut guard = info.lock().unwrap();
|
|
||||||
if guard.output.equals(output) {
|
|
||||||
guard.pix_size = (w as u32, h as u32);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
done: |_, _, _| {},
|
|
||||||
scale: |evqh, token, output, scale| {
|
|
||||||
let ctxt = evqh.state().get_mut(token);
|
|
||||||
for info in &ctxt.monitors {
|
|
||||||
let mut guard = info.lock().unwrap();
|
|
||||||
if guard.output.equals(output) {
|
|
||||||
guard.scale = scale as f32;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct OutputInfo {
|
|
||||||
pub output: wl_output::WlOutput,
|
|
||||||
pub id: u32,
|
|
||||||
pub scale: f32,
|
|
||||||
pub pix_size: (u32, u32),
|
|
||||||
pub pix_pos: (i32, i32),
|
|
||||||
pub name: String
|
|
||||||
}
|
|
||||||
|
|
||||||
impl OutputInfo {
|
|
||||||
fn new(output: wl_output::WlOutput, id: u32) -> OutputInfo {
|
|
||||||
OutputInfo {
|
|
||||||
output: output,
|
|
||||||
id: id,
|
|
||||||
scale: 1.0,
|
|
||||||
pix_size: (0, 0),
|
|
||||||
pix_pos: (0, 0),
|
|
||||||
name: "".into()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct MonitorId {
|
|
||||||
pub info: Arc<Mutex<OutputInfo>>
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorId {
|
|
||||||
pub fn get_name(&self) -> Option<String> {
|
|
||||||
Some(self.info.lock().unwrap().name.clone())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_native_identifier(&self) -> u32 {
|
|
||||||
self.info.lock().unwrap().id
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_dimensions(&self) -> (u32, u32) {
|
|
||||||
self.info.lock().unwrap().pix_size
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_position(&self) -> (i32, i32) {
|
|
||||||
self.info.lock().unwrap().pix_pos
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_hidpi_factor(&self) -> f32 {
|
|
||||||
self.info.lock().unwrap().scale
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,296 +0,0 @@
|
|||||||
use std::sync::{Arc, Mutex};
|
|
||||||
|
|
||||||
use {VirtualKeyCode, ElementState, WindowEvent as Event, KeyboardInput, ModifiersState};
|
|
||||||
|
|
||||||
use super::{EventsLoopSink, WindowId, make_wid, DeviceId};
|
|
||||||
use super::wayland_kbd::{MappedKeyboardImplementation, register_kbd};
|
|
||||||
use wayland_client::protocol::wl_keyboard;
|
|
||||||
use wayland_client::EventQueueHandle;
|
|
||||||
|
|
||||||
pub fn init_keyboard(evq: &mut EventQueueHandle, keyboard: &wl_keyboard::WlKeyboard, sink: &Arc<Mutex<EventsLoopSink>>) {
|
|
||||||
let idata = KeyboardIData {
|
|
||||||
sink: sink.clone(),
|
|
||||||
target: None
|
|
||||||
};
|
|
||||||
|
|
||||||
if register_kbd(evq, keyboard, mapped_keyboard_impl(), idata).is_err() {
|
|
||||||
// initializing libxkbcommon failed :(
|
|
||||||
// fallback implementation
|
|
||||||
let idata = KeyboardIData {
|
|
||||||
sink: sink.clone(),
|
|
||||||
target: None
|
|
||||||
};
|
|
||||||
evq.register(keyboard, raw_keyboard_impl(), idata);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct KeyboardIData {
|
|
||||||
sink: Arc<Mutex<EventsLoopSink>>,
|
|
||||||
target: Option<WindowId>
|
|
||||||
}
|
|
||||||
|
|
||||||
fn mapped_keyboard_impl() -> MappedKeyboardImplementation<KeyboardIData> {
|
|
||||||
MappedKeyboardImplementation {
|
|
||||||
enter: |_, idata, _, _, surface, _, _, _| {
|
|
||||||
let wid = make_wid(surface);
|
|
||||||
idata.sink.lock().unwrap().send_event(Event::Focused(true), wid);
|
|
||||||
idata.target = Some(wid);
|
|
||||||
},
|
|
||||||
leave: |_, idata, _, _, surface| {
|
|
||||||
let wid = make_wid(surface);
|
|
||||||
idata.sink.lock().unwrap().send_event(Event::Focused(false), wid);
|
|
||||||
idata.target = None;
|
|
||||||
},
|
|
||||||
key: |_, idata, _, _, _, mods, rawkey, keysym, state, utf8| {
|
|
||||||
if let Some(wid) = idata.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 = idata.sink.lock().unwrap();
|
|
||||||
guard.send_event(
|
|
||||||
Event::KeyboardInput {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
input: KeyboardInput {
|
|
||||||
state: state,
|
|
||||||
scancode: rawkey,
|
|
||||||
virtual_keycode: vkcode,
|
|
||||||
modifiers: ModifiersState {
|
|
||||||
shift: mods.shift,
|
|
||||||
ctrl: mods.ctrl,
|
|
||||||
alt: mods.alt,
|
|
||||||
logo: mods.logo
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
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(Event::ReceivedCharacter(chr), wid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
repeat_info: |_, _idata, _, _rate, _delay| {
|
|
||||||
// TODO: handle repeat info
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// This is 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)
|
|
||||||
fn raw_keyboard_impl() -> wl_keyboard::Implementation<KeyboardIData> {
|
|
||||||
wl_keyboard::Implementation {
|
|
||||||
enter: |_, idata, _, _, surface, _| {
|
|
||||||
let wid = make_wid(surface);
|
|
||||||
idata.sink.lock().unwrap().send_event(Event::Focused(true), wid);
|
|
||||||
idata.target = Some(wid);
|
|
||||||
},
|
|
||||||
leave: |_, idata, _, _, surface| {
|
|
||||||
let wid = make_wid(surface);
|
|
||||||
idata.sink.lock().unwrap().send_event(Event::Focused(false), wid);
|
|
||||||
idata.target = None;
|
|
||||||
},
|
|
||||||
key: |_, idata, _, _, _, key, state| {
|
|
||||||
if let Some(wid) = idata.target {
|
|
||||||
let state = match state {
|
|
||||||
wl_keyboard::KeyState::Pressed => ElementState::Pressed,
|
|
||||||
wl_keyboard::KeyState::Released => ElementState::Released,
|
|
||||||
};
|
|
||||||
idata.sink.lock().unwrap().send_event(
|
|
||||||
Event::KeyboardInput {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
input: KeyboardInput {
|
|
||||||
state: state,
|
|
||||||
scancode: key,
|
|
||||||
virtual_keycode: None,
|
|
||||||
modifiers: ModifiersState::default(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
wid
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
repeat_info: |_, _idata, _, _rate, _delay| {},
|
|
||||||
keymap: |_, _, _, _, _, _| {},
|
|
||||||
modifiers: |_, _, _, _, _, _, _, _| {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 super::wayland_kbd::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),
|
|
||||||
// => Some(VirtualKeyCode::LMenu),
|
|
||||||
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),
|
|
||||||
// => Some(VirtualKeyCode::RMenu),
|
|
||||||
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),
|
|
||||||
// fallback
|
|
||||||
_ => None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))]
|
|
||||||
|
|
||||||
pub use self::window::Window;
|
|
||||||
pub use self::event_loop::{EventsLoop, EventsLoopProxy, EventsLoopSink, MonitorId};
|
|
||||||
|
|
||||||
extern crate wayland_kbd;
|
|
||||||
extern crate wayland_window;
|
|
||||||
extern crate wayland_protocols;
|
|
||||||
|
|
||||||
use wayland_client::protocol::wl_surface;
|
|
||||||
use wayland_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: &wl_surface::WlSurface) -> WindowId {
|
|
||||||
WindowId(s.ptr() as usize)
|
|
||||||
}
|
|
||||||
@@ -1,194 +0,0 @@
|
|||||||
use std::sync::{Arc, Mutex};
|
|
||||||
|
|
||||||
use {WindowEvent as Event, ElementState, MouseButton, MouseScrollDelta, TouchPhase};
|
|
||||||
use events::ModifiersState;
|
|
||||||
|
|
||||||
use super::{WindowId, DeviceId};
|
|
||||||
use super::event_loop::EventsLoopSink;
|
|
||||||
use super::window::WindowStore;
|
|
||||||
|
|
||||||
use wayland_client::{Proxy, StateToken};
|
|
||||||
use wayland_client::protocol::wl_pointer;
|
|
||||||
|
|
||||||
pub struct PointerIData {
|
|
||||||
sink: Arc<Mutex<EventsLoopSink>>,
|
|
||||||
windows_token: StateToken<WindowStore>,
|
|
||||||
mouse_focus: Option<WindowId>,
|
|
||||||
axis_buffer: Option<(f32, f32)>,
|
|
||||||
axis_discrete_buffer: Option<(i32, i32)>,
|
|
||||||
axis_state: TouchPhase,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PointerIData {
|
|
||||||
pub fn new(sink: &Arc<Mutex<EventsLoopSink>>, token: StateToken<WindowStore>)
|
|
||||||
-> PointerIData
|
|
||||||
{
|
|
||||||
PointerIData {
|
|
||||||
sink: sink.clone(),
|
|
||||||
windows_token: token,
|
|
||||||
mouse_focus: None,
|
|
||||||
axis_buffer: None,
|
|
||||||
axis_discrete_buffer: None,
|
|
||||||
axis_state: TouchPhase::Cancelled
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn pointer_implementation() -> wl_pointer::Implementation<PointerIData> {
|
|
||||||
wl_pointer::Implementation {
|
|
||||||
enter: |evqh, idata, _, _, surface, x, y| {
|
|
||||||
let wid = evqh.state().get(&idata.windows_token).find_wid(surface);
|
|
||||||
if let Some(wid) = wid {
|
|
||||||
idata.mouse_focus = Some(wid);
|
|
||||||
let mut guard = idata.sink.lock().unwrap();
|
|
||||||
guard.send_event(
|
|
||||||
Event::CursorEntered {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
},
|
|
||||||
wid,
|
|
||||||
);
|
|
||||||
guard.send_event(
|
|
||||||
Event::CursorMoved {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
position: (x, y),
|
|
||||||
// TODO: replace dummy value with actual modifier state
|
|
||||||
modifiers: ModifiersState::default(),
|
|
||||||
},
|
|
||||||
wid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
leave: |evqh, idata, _, _, surface| {
|
|
||||||
idata.mouse_focus = None;
|
|
||||||
let wid = evqh.state().get(&idata.windows_token).find_wid(surface);
|
|
||||||
if let Some(wid) = wid {
|
|
||||||
let mut guard = idata.sink.lock().unwrap();
|
|
||||||
guard.send_event(
|
|
||||||
Event::CursorLeft {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
},
|
|
||||||
wid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
motion: |_, idata, _, _, x, y| {
|
|
||||||
if let Some(wid) = idata.mouse_focus {
|
|
||||||
idata.sink.lock().unwrap().send_event(
|
|
||||||
Event::CursorMoved {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
position: (x, y),
|
|
||||||
// TODO: replace dummy value with actual modifier state
|
|
||||||
modifiers: ModifiersState::default(),
|
|
||||||
},
|
|
||||||
wid
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
button: |_, idata, _, _, _, button, state| {
|
|
||||||
if let Some(wid) = idata.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
|
|
||||||
};
|
|
||||||
idata.sink.lock().unwrap().send_event(
|
|
||||||
Event::MouseInput {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
state: state,
|
|
||||||
button: button,
|
|
||||||
// TODO: replace dummy value with actual modifier state
|
|
||||||
modifiers: ModifiersState::default(),
|
|
||||||
},
|
|
||||||
wid
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
axis: |_, idata, pointer, _, axis, value| {
|
|
||||||
if let Some(wid) = idata.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
|
|
||||||
}
|
|
||||||
idata.sink.lock().unwrap().send_event(
|
|
||||||
Event::MouseWheel {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
delta: MouseScrollDelta::PixelDelta(x as f32, y as f32),
|
|
||||||
phase: TouchPhase::Moved,
|
|
||||||
// TODO: replace dummy value with actual modifier state
|
|
||||||
modifiers: ModifiersState::default(),
|
|
||||||
},
|
|
||||||
wid
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
let (mut x, mut y) = idata.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
|
|
||||||
}
|
|
||||||
idata.axis_buffer = Some((x,y));
|
|
||||||
idata.axis_state = match idata.axis_state {
|
|
||||||
TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved,
|
|
||||||
_ => TouchPhase::Started
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
frame: |_, idata, _| {
|
|
||||||
let axis_buffer = idata.axis_buffer.take();
|
|
||||||
let axis_discrete_buffer = idata.axis_discrete_buffer.take();
|
|
||||||
if let Some(wid) = idata.mouse_focus {
|
|
||||||
if let Some((x, y)) = axis_discrete_buffer {
|
|
||||||
idata.sink.lock().unwrap().send_event(
|
|
||||||
Event::MouseWheel {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
delta: MouseScrollDelta::LineDelta(x as f32, y as f32),
|
|
||||||
phase: idata.axis_state,
|
|
||||||
// TODO: replace dummy value with actual modifier state
|
|
||||||
modifiers: ModifiersState::default(),
|
|
||||||
},
|
|
||||||
wid
|
|
||||||
);
|
|
||||||
} else if let Some((x, y)) = axis_buffer {
|
|
||||||
idata.sink.lock().unwrap().send_event(
|
|
||||||
Event::MouseWheel {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
delta: MouseScrollDelta::PixelDelta(x as f32, y as f32),
|
|
||||||
phase: idata.axis_state,
|
|
||||||
// TODO: replace dummy value with actual modifier state
|
|
||||||
modifiers: ModifiersState::default(),
|
|
||||||
},
|
|
||||||
wid
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
axis_source: |_, _, _, _| {},
|
|
||||||
axis_stop: |_, idata, _, _, _| {
|
|
||||||
idata.axis_state = TouchPhase::Ended;
|
|
||||||
},
|
|
||||||
axis_discrete: |_, idata, _, axis, discrete| {
|
|
||||||
let (mut x, mut y) = idata.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
|
|
||||||
}
|
|
||||||
idata.axis_discrete_buffer = Some((x,y));
|
|
||||||
idata.axis_state = match idata.axis_state {
|
|
||||||
TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved,
|
|
||||||
_ => TouchPhase::Started
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,106 +0,0 @@
|
|||||||
use std::sync::{Arc, Mutex};
|
|
||||||
|
|
||||||
use {WindowEvent as Event, TouchPhase};
|
|
||||||
|
|
||||||
use super::{WindowId, DeviceId};
|
|
||||||
use super::event_loop::EventsLoopSink;
|
|
||||||
use super::window::WindowStore;
|
|
||||||
|
|
||||||
use wayland_client::StateToken;
|
|
||||||
use wayland_client::protocol::wl_touch;
|
|
||||||
|
|
||||||
pub struct TouchIData {
|
|
||||||
sink: Arc<Mutex<EventsLoopSink>>,
|
|
||||||
windows_token: StateToken<WindowStore>,
|
|
||||||
pending_ids: Vec<TouchPoint>,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct TouchPoint {
|
|
||||||
wid: WindowId,
|
|
||||||
location: (f64, f64),
|
|
||||||
id: i32
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TouchIData {
|
|
||||||
pub fn new(sink: &Arc<Mutex<EventsLoopSink>>, token: StateToken<WindowStore>)
|
|
||||||
-> TouchIData
|
|
||||||
{
|
|
||||||
TouchIData {
|
|
||||||
sink: sink.clone(),
|
|
||||||
windows_token: token,
|
|
||||||
pending_ids: Vec::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn touch_implementation() -> wl_touch::Implementation<TouchIData> {
|
|
||||||
wl_touch::Implementation {
|
|
||||||
down: |evqh, idata, _, _serial, _time, surface, touch_id, x, y| {
|
|
||||||
let wid = evqh.state().get(&idata.windows_token).find_wid(surface);
|
|
||||||
if let Some(wid) = wid {
|
|
||||||
let mut guard = idata.sink.lock().unwrap();
|
|
||||||
guard.send_event(
|
|
||||||
Event::Touch(::Touch {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
phase: TouchPhase::Started,
|
|
||||||
location: (x, y),
|
|
||||||
id: touch_id as u64
|
|
||||||
}),
|
|
||||||
wid,
|
|
||||||
);
|
|
||||||
idata.pending_ids.push(TouchPoint {
|
|
||||||
wid: wid,
|
|
||||||
location: (x, y),
|
|
||||||
id: touch_id
|
|
||||||
});
|
|
||||||
}
|
|
||||||
},
|
|
||||||
up: |_, idata, _, _serial, _time, touch_id| {
|
|
||||||
let idx = idata.pending_ids.iter().position(|p| p.id == touch_id);
|
|
||||||
if let Some(idx) = idx {
|
|
||||||
let pt = idata.pending_ids.remove(idx);
|
|
||||||
let mut guard = idata.sink.lock().unwrap();
|
|
||||||
guard.send_event(
|
|
||||||
Event::Touch(::Touch {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
phase: TouchPhase::Ended,
|
|
||||||
location: pt.location,
|
|
||||||
id: touch_id as u64
|
|
||||||
}),
|
|
||||||
pt.wid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
motion: |_, idata, _, _time, touch_id, x, y| {
|
|
||||||
let pt = idata.pending_ids.iter_mut().find(|p| p.id == touch_id);
|
|
||||||
if let Some(pt) = pt {
|
|
||||||
let mut guard = idata.sink.lock().unwrap();
|
|
||||||
pt.location = (x, y);
|
|
||||||
guard.send_event(
|
|
||||||
Event::Touch(::Touch {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
phase: TouchPhase::Moved,
|
|
||||||
location: (x, y),
|
|
||||||
id: touch_id as u64
|
|
||||||
}),
|
|
||||||
pt.wid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
frame: |_, _, _| {},
|
|
||||||
cancel: |_, idata, _| {
|
|
||||||
let mut guard = idata.sink.lock().unwrap();
|
|
||||||
for pt in idata.pending_ids.drain(..) {
|
|
||||||
guard.send_event(
|
|
||||||
Event::Touch(::Touch {
|
|
||||||
device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)),
|
|
||||||
phase: TouchPhase::Cancelled,
|
|
||||||
location: pt.location,
|
|
||||||
id: pt.id as u64
|
|
||||||
}),
|
|
||||||
pt.wid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,364 +0,0 @@
|
|||||||
use std::sync::{Arc, Mutex, Weak};
|
|
||||||
|
|
||||||
use wayland_client::protocol::{wl_display,wl_surface};
|
|
||||||
use wayland_client::{Proxy, StateToken};
|
|
||||||
|
|
||||||
use {CreationError, MouseCursor, CursorState, WindowAttributes};
|
|
||||||
use platform::MonitorId as PlatformMonitorId;
|
|
||||||
use window::MonitorId as RootMonitorId;
|
|
||||||
|
|
||||||
use super::{EventsLoop, WindowId, make_wid, MonitorId};
|
|
||||||
use super::wayland_window::{Frame, FrameImplementation, State as FrameState};
|
|
||||||
use super::event_loop::StateContext;
|
|
||||||
|
|
||||||
pub struct Window {
|
|
||||||
surface: wl_surface::WlSurface,
|
|
||||||
frame: Arc<Mutex<Frame>>,
|
|
||||||
monitors: Arc<Mutex<MonitorList>>,
|
|
||||||
size: Arc<Mutex<(u32, u32)>>,
|
|
||||||
kill_switch: (Arc<Mutex<bool>>, Arc<Mutex<bool>>),
|
|
||||||
display: Arc<wl_display::WlDisplay>,
|
|
||||||
need_frame_refresh: Arc<Mutex<bool>>
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Window {
|
|
||||||
pub fn new(evlp: &EventsLoop, attributes: &WindowAttributes) -> Result<Window, CreationError>
|
|
||||||
{
|
|
||||||
let (width, height) = attributes.dimensions.unwrap_or((800,600));
|
|
||||||
|
|
||||||
// Create the decorated surface
|
|
||||||
let size = Arc::new(Mutex::new((width, height)));
|
|
||||||
let store_token = evlp.store.clone();
|
|
||||||
let (surface, mut frame) = evlp.create_window(
|
|
||||||
width, height, decorated_impl(),
|
|
||||||
|surface| FrameIData {
|
|
||||||
surface: surface.clone().unwrap(),
|
|
||||||
store_token: store_token.clone()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
// Check for fullscreen requirements
|
|
||||||
if let Some(RootMonitorId { inner: PlatformMonitorId::Wayland(ref monitor_id) }) = attributes.fullscreen {
|
|
||||||
let info = monitor_id.info.lock().unwrap();
|
|
||||||
frame.set_state(FrameState::Fullscreen(Some(&info.output)));
|
|
||||||
} else if attributes.maximized {
|
|
||||||
frame.set_state(FrameState::Maximized);
|
|
||||||
}
|
|
||||||
|
|
||||||
// set decorations
|
|
||||||
frame.set_decorate(attributes.decorations);
|
|
||||||
|
|
||||||
// min-max dimensions
|
|
||||||
frame.set_min_size(attributes.min_dimensions.map(|(w, h)| (w as i32, h as i32)));
|
|
||||||
frame.set_max_size(attributes.max_dimensions.map(|(w, h)| (w as i32, h as i32)));
|
|
||||||
|
|
||||||
// setup the monitor tracking
|
|
||||||
let monitor_list = Arc::new(Mutex::new(MonitorList::default()));
|
|
||||||
{
|
|
||||||
let mut evq = evlp.evq.borrow_mut();
|
|
||||||
let idata = (evlp.ctxt_token.clone(), monitor_list.clone());
|
|
||||||
evq.register(&surface, surface_impl(), idata);
|
|
||||||
}
|
|
||||||
|
|
||||||
let kill_switch = Arc::new(Mutex::new(false));
|
|
||||||
let need_frame_refresh = Arc::new(Mutex::new(true));
|
|
||||||
let frame = Arc::new(Mutex::new(frame));
|
|
||||||
|
|
||||||
{
|
|
||||||
let mut evq = evlp.evq.borrow_mut();
|
|
||||||
evq.state().get_mut(&store_token).windows.push(InternalWindow {
|
|
||||||
closed: false,
|
|
||||||
newsize: None,
|
|
||||||
need_refresh: false,
|
|
||||||
need_frame_refresh: need_frame_refresh.clone(),
|
|
||||||
surface: surface.clone().unwrap(),
|
|
||||||
kill_switch: kill_switch.clone(),
|
|
||||||
frame: Arc::downgrade(&frame)
|
|
||||||
});
|
|
||||||
evq.sync_roundtrip().unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Window {
|
|
||||||
display: evlp.display.clone(),
|
|
||||||
surface: surface,
|
|
||||||
frame: frame,
|
|
||||||
monitors: monitor_list,
|
|
||||||
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<(i32, i32)> {
|
|
||||||
// Not possible with wayland
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_inner_position(&self) -> Option<(i32, i32)> {
|
|
||||||
// Not possible with wayland
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_position(&self, _x: i32, _y: i32) {
|
|
||||||
// Not possible with wayland
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
|
|
||||||
Some(self.size.lock().unwrap().clone())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
|
|
||||||
let (w, h) = self.size.lock().unwrap().clone();
|
|
||||||
let (w, h) = super::wayland_window::add_borders(w as i32, h as i32);
|
|
||||||
Some((w as u32, h as u32))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
// NOTE: This will only resize the borders, the contents must be updated by the user
|
|
||||||
pub fn set_inner_size(&self, x: u32, y: u32) {
|
|
||||||
self.frame.lock().unwrap().resize(x as i32, y as i32);
|
|
||||||
*(self.size.lock().unwrap()) = (x, y);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_min_dimensions(&self, dimensions: Option<(u32, u32)>) {
|
|
||||||
self.frame.lock().unwrap().set_min_size(dimensions.map(|(w, h)| (w as i32, h as i32)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_max_dimensions(&self, dimensions: Option<(u32, u32)>) {
|
|
||||||
self.frame.lock().unwrap().set_max_size(dimensions.map(|(w, h)| (w as i32, h as i32)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor(&self, _cursor: MouseCursor) {
|
|
||||||
// TODO
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> {
|
|
||||||
use CursorState::{Grab, Normal, Hide};
|
|
||||||
// TODO : not yet possible on wayland to grab cursor
|
|
||||||
match state {
|
|
||||||
Grab => Err("Cursor cannot be grabbed on wayland yet.".to_string()),
|
|
||||||
Hide => Err("Cursor cannot be hidden on wayland yet.".to_string()),
|
|
||||||
Normal => Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn hidpi_factor(&self) -> f32 {
|
|
||||||
let mut factor = 1.0;
|
|
||||||
let guard = self.monitors.lock().unwrap();
|
|
||||||
for monitor_id in &guard.monitors {
|
|
||||||
let info = monitor_id.info.lock().unwrap();
|
|
||||||
if info.scale > factor { factor = info.scale; }
|
|
||||||
}
|
|
||||||
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_state(FrameState::Maximized);
|
|
||||||
} else {
|
|
||||||
self.frame.lock().unwrap().set_state(FrameState::Regular);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_fullscreen(&self, monitor: Option<RootMonitorId>) {
|
|
||||||
if let Some(RootMonitorId { inner: PlatformMonitorId::Wayland(ref monitor_id) }) = monitor {
|
|
||||||
let info = monitor_id.info.lock().unwrap();
|
|
||||||
self.frame.lock().unwrap().set_state(FrameState::Fullscreen(Some(&info.output)));
|
|
||||||
} else {
|
|
||||||
self.frame.lock().unwrap().set_state(FrameState::Regular);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn set_cursor_position(&self, _x: i32, _y: i32) -> Result<(), ()> {
|
|
||||||
// TODO: not yet possible on wayland
|
|
||||||
Err(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_display(&self) -> &wl_display::WlDisplay {
|
|
||||||
&*self.display
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_surface(&self) -> &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()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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: wl_surface::WlSurface,
|
|
||||||
newsize: Option<(i32, i32)>,
|
|
||||||
need_refresh: bool,
|
|
||||||
need_frame_refresh: Arc<Mutex<bool>>,
|
|
||||||
closed: bool,
|
|
||||||
kill_switch: Arc<Mutex<bool>>,
|
|
||||||
frame: Weak<Mutex<Frame>>
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct WindowStore {
|
|
||||||
windows: Vec<InternalWindow>
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowStore {
|
|
||||||
pub fn new() -> WindowStore {
|
|
||||||
WindowStore { windows: Vec::new() }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn find_wid(&self, surface: &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 for_each<F>(&mut self, mut f: F)
|
|
||||||
where F: FnMut(Option<(i32, i32)>, bool, bool, bool, WindowId, Option<&mut Frame>)
|
|
||||||
{
|
|
||||||
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(),
|
|
||||||
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)
|
|
||||||
);
|
|
||||||
window.need_refresh = false;
|
|
||||||
// avoid re-spamming the event
|
|
||||||
window.closed = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Protocol implementation
|
|
||||||
*/
|
|
||||||
|
|
||||||
struct FrameIData {
|
|
||||||
store_token: StateToken<WindowStore>,
|
|
||||||
surface: wl_surface::WlSurface
|
|
||||||
}
|
|
||||||
|
|
||||||
fn decorated_impl() -> FrameImplementation<FrameIData> {
|
|
||||||
FrameImplementation {
|
|
||||||
configure: |evqh, idata, _, newsize| {
|
|
||||||
let store = evqh.state().get_mut(&idata.store_token);
|
|
||||||
for window in &mut store.windows {
|
|
||||||
if window.surface.equals(&idata.surface) {
|
|
||||||
window.newsize = newsize;
|
|
||||||
window.need_refresh = true;
|
|
||||||
*(window.need_frame_refresh.lock().unwrap()) = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
close: |evqh, idata| {
|
|
||||||
let store = evqh.state().get_mut(&idata.store_token);
|
|
||||||
for window in &mut store.windows {
|
|
||||||
if window.surface.equals(&idata.surface) {
|
|
||||||
window.closed = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
refresh: |evqh, idata| {
|
|
||||||
let store = evqh.state().get_mut(&idata.store_token);
|
|
||||||
for window in &mut store.windows {
|
|
||||||
if window.surface.equals(&idata.surface) {
|
|
||||||
*(window.need_frame_refresh.lock().unwrap()) = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
struct MonitorList {
|
|
||||||
monitors: Vec<MonitorId>
|
|
||||||
}
|
|
||||||
|
|
||||||
fn surface_impl() -> wl_surface::Implementation<(StateToken<StateContext>, Arc<Mutex<MonitorList>>)> {
|
|
||||||
wl_surface::Implementation {
|
|
||||||
enter: |evqh, &mut (ref token, ref list), _, output| {
|
|
||||||
let mut guard = list.lock().unwrap();
|
|
||||||
let ctxt = evqh.state().get(token);
|
|
||||||
let monitor = ctxt.monitor_id_for(output);
|
|
||||||
guard.monitors.push(monitor);
|
|
||||||
},
|
|
||||||
leave: |evqh, &mut (ref token, ref list), _, output| {
|
|
||||||
let mut guard = list.lock().unwrap();
|
|
||||||
let ctxt = evqh.state().get(token);
|
|
||||||
let monitor = ctxt.monitor_id_for(output);
|
|
||||||
guard.monitors.retain(|m| !Arc::ptr_eq(&m.info, &monitor.info));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,240 +0,0 @@
|
|||||||
use std::io;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
use std::str::Utf8Error;
|
|
||||||
|
|
||||||
use libc::{c_char, c_int, c_long, c_uchar, c_ulong};
|
|
||||||
use percent_encoding::percent_decode;
|
|
||||||
|
|
||||||
use super::{ffi, util, XConnection, XError};
|
|
||||||
|
|
||||||
const DND_ATOMS_LEN: usize = 12;
|
|
||||||
|
|
||||||
#[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 mut atoms = Vec::with_capacity(DND_ATOMS_LEN);
|
|
||||||
|
|
||||||
let mut names = [
|
|
||||||
b"XdndAware\0".to_owned().as_mut_ptr() as *mut c_char,
|
|
||||||
b"XdndEnter\0".to_owned().as_mut_ptr() as *mut c_char,
|
|
||||||
b"XdndLeave\0".to_owned().as_mut_ptr() as *mut c_char,
|
|
||||||
b"XdndDrop\0".to_owned().as_mut_ptr() as *mut c_char,
|
|
||||||
b"XdndPosition\0".to_owned().as_mut_ptr() as *mut c_char,
|
|
||||||
b"XdndStatus\0".to_owned().as_mut_ptr() as *mut c_char,
|
|
||||||
b"XdndActionPrivate\0".to_owned().as_mut_ptr() as *mut c_char,
|
|
||||||
b"XdndSelection\0".to_owned().as_mut_ptr() as *mut c_char,
|
|
||||||
b"XdndFinished\0".to_owned().as_mut_ptr() as *mut c_char,
|
|
||||||
b"XdndTypeList\0".to_owned().as_mut_ptr() as *mut c_char,
|
|
||||||
b"text/uri-list\0".to_owned().as_mut_ptr() as *mut c_char,
|
|
||||||
b"None\0".to_owned().as_mut_ptr() as *mut c_char,
|
|
||||||
];
|
|
||||||
|
|
||||||
unsafe {
|
|
||||||
(xconn.xlib.XInternAtoms)(
|
|
||||||
xconn.display,
|
|
||||||
names.as_mut_ptr(),
|
|
||||||
DND_ATOMS_LEN as c_int,
|
|
||||||
ffi::False,
|
|
||||||
atoms.as_mut_ptr(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
xconn.check_errors()?;
|
|
||||||
unsafe {
|
|
||||||
atoms.set_len(DND_ATOMS_LEN);
|
|
||||||
}
|
|
||||||
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),
|
|
||||||
};
|
|
||||||
util::send_client_msg(
|
|
||||||
&self.xconn,
|
|
||||||
target_window,
|
|
||||||
target_window,
|
|
||||||
self.atoms.status,
|
|
||||||
None,
|
|
||||||
(this_window as c_long, accepted, 0, 0, action),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
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),
|
|
||||||
};
|
|
||||||
util::send_client_msg(
|
|
||||||
&self.xconn,
|
|
||||||
target_window,
|
|
||||||
target_window,
|
|
||||||
self.atoms.finished,
|
|
||||||
None,
|
|
||||||
(this_window as c_long, accepted, action, 0, 0),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe fn get_type_list(
|
|
||||||
&self,
|
|
||||||
source_window: c_ulong,
|
|
||||||
) -> Result<Vec<ffi::Atom>, util::GetPropertyError> {
|
|
||||||
util::get_property(
|
|
||||||
&self.xconn,
|
|
||||||
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> {
|
|
||||||
util::get_property(
|
|
||||||
&self.xconn,
|
|
||||||
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,129 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
use std::slice;
|
|
||||||
|
|
||||||
use super::XConnection;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct MonitorId {
|
|
||||||
/// The actual id
|
|
||||||
id: u32,
|
|
||||||
/// The name of the monitor
|
|
||||||
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 scaling factor
|
|
||||||
hidpi_factor: f32,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_available_monitors(x: &Arc<XConnection>) -> Vec<MonitorId> {
|
|
||||||
let mut available = Vec::new();
|
|
||||||
unsafe {
|
|
||||||
let root = (x.xlib.XDefaultRootWindow)(x.display);
|
|
||||||
let resources = (x.xrandr.XRRGetScreenResources)(x.display, root);
|
|
||||||
|
|
||||||
if let Some(ref xrandr_1_5) = x.xrandr_1_5 {
|
|
||||||
// We're in XRandR >= 1.5, enumerate Monitors to handle things like MST and videowalls
|
|
||||||
let mut nmonitors = 0;
|
|
||||||
let monitors = (xrandr_1_5.XRRGetMonitors)(x.display, root, 1, &mut nmonitors);
|
|
||||||
for i in 0..nmonitors {
|
|
||||||
let monitor = *(monitors.offset(i as isize));
|
|
||||||
let output = (xrandr_1_5.XRRGetOutputInfo)(x.display, resources, *(monitor.outputs.offset(0)));
|
|
||||||
let nameslice = slice::from_raw_parts((*output).name as *mut u8, (*output).nameLen as usize);
|
|
||||||
let name = String::from_utf8_lossy(nameslice).into_owned();
|
|
||||||
let hidpi_factor = {
|
|
||||||
let x_mm = (*output).mm_width as f32;
|
|
||||||
let y_mm = (*output).mm_height as f32;
|
|
||||||
let x_px = monitor.width as f32;
|
|
||||||
let y_px = monitor.height as f32;
|
|
||||||
let ppmm = ((x_px * y_px) / (x_mm * y_mm)).sqrt();
|
|
||||||
|
|
||||||
// Quantize 1/12 step size
|
|
||||||
((ppmm * (12.0 * 25.4 / 96.0)).round() / 12.0).max(1.0)
|
|
||||||
};
|
|
||||||
(xrandr_1_5.XRRFreeOutputInfo)(output);
|
|
||||||
available.push(MonitorId{
|
|
||||||
id: i as u32,
|
|
||||||
name,
|
|
||||||
hidpi_factor,
|
|
||||||
dimensions: (monitor.width as u32, monitor.height as u32),
|
|
||||||
position: (monitor.x as i32, monitor.y as i32),
|
|
||||||
primary: (monitor.primary != 0),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
(xrandr_1_5.XRRFreeMonitors)(monitors);
|
|
||||||
} else {
|
|
||||||
// We're in XRandR < 1.5, enumerate CRTCs. Everything will work but MST and
|
|
||||||
// videowall setups will show more monitors than the logical groups the user
|
|
||||||
// cares about
|
|
||||||
for i in 0..(*resources).ncrtc {
|
|
||||||
let crtcid = *((*resources).crtcs.offset(i as isize));
|
|
||||||
let crtc = (x.xrandr.XRRGetCrtcInfo)(x.display, resources, crtcid);
|
|
||||||
if (*crtc).width > 0 && (*crtc).height > 0 && (*crtc).noutput > 0 {
|
|
||||||
let output = (x.xrandr.XRRGetOutputInfo)(x.display, resources, *((*crtc).outputs.offset(0)));
|
|
||||||
let nameslice = slice::from_raw_parts((*output).name as *mut u8, (*output).nameLen as usize);
|
|
||||||
let name = String::from_utf8_lossy(nameslice).into_owned();
|
|
||||||
|
|
||||||
let hidpi_factor = {
|
|
||||||
let x_mm = (*output).mm_width as f32;
|
|
||||||
let y_mm = (*output).mm_height as f32;
|
|
||||||
let x_px = (*crtc).width as f32;
|
|
||||||
let y_px = (*crtc).height as f32;
|
|
||||||
let ppmm = ((x_px * y_px) / (x_mm * y_mm)).sqrt();
|
|
||||||
|
|
||||||
// Quantize 1/12 step size
|
|
||||||
((ppmm * (12.0 * 25.4 / 96.0)).round() / 12.0).max(1.0)
|
|
||||||
};
|
|
||||||
|
|
||||||
(x.xrandr.XRRFreeOutputInfo)(output);
|
|
||||||
available.push(MonitorId{
|
|
||||||
id: crtcid as u32,
|
|
||||||
name,
|
|
||||||
hidpi_factor,
|
|
||||||
dimensions: ((*crtc).width as u32, (*crtc).height as u32),
|
|
||||||
position: ((*crtc).x as i32, (*crtc).y as i32),
|
|
||||||
primary: true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
(x.xrandr.XRRFreeCrtcInfo)(crtc);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
(x.xrandr.XRRFreeScreenResources)(resources);
|
|
||||||
}
|
|
||||||
available
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_primary_monitor(x: &Arc<XConnection>) -> MonitorId {
|
|
||||||
get_available_monitors(x).into_iter().find(|m| m.primary)
|
|
||||||
// 'no primary' case is better handled picking some existing monitor
|
|
||||||
.or_else(|| get_available_monitors(x).into_iter().next())
|
|
||||||
.expect("[winit] Failed to find any x11 monitor")
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorId {
|
|
||||||
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) -> (u32, u32) {
|
|
||||||
self.dimensions
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_position(&self) -> (i32, i32) {
|
|
||||||
self.position
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_hidpi_factor(&self) -> f32 {
|
|
||||||
self.hidpi_factor
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,365 +0,0 @@
|
|||||||
use std::mem;
|
|
||||||
use std::ptr;
|
|
||||||
use std::str;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::ops::{Deref, DerefMut};
|
|
||||||
use std::os::raw::{c_char, c_double, c_int, c_long, c_short, c_uchar, c_uint, c_ulong};
|
|
||||||
|
|
||||||
use super::{ffi, XConnection, XError};
|
|
||||||
use events::ModifiersState;
|
|
||||||
|
|
||||||
pub struct XSmartPointer<'a, T> {
|
|
||||||
xconn: &'a Arc<XConnection>,
|
|
||||||
pub ptr: *mut T,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, T> XSmartPointer<'a, T> {
|
|
||||||
// You're responsible for only passing things to this that should be XFree'd.
|
|
||||||
// Returns None if ptr is null.
|
|
||||||
pub fn new(xconn: &'a Arc<XConnection>, ptr: *mut T) -> Option<Self> {
|
|
||||||
if !ptr.is_null() {
|
|
||||||
Some(XSmartPointer {
|
|
||||||
xconn,
|
|
||||||
ptr,
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, T> Deref for XSmartPointer<'a, T> {
|
|
||||||
type Target = T;
|
|
||||||
|
|
||||||
fn deref(&self) -> &T {
|
|
||||||
unsafe { &*self.ptr }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, T> DerefMut for XSmartPointer<'a, T> {
|
|
||||||
fn deref_mut(&mut self) -> &mut T {
|
|
||||||
unsafe { &mut *self.ptr }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, T> Drop for XSmartPointer<'a, T> {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
unsafe {
|
|
||||||
(self.xconn.xlib.XFree)(self.ptr as *mut _);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe fn get_atom(xconn: &Arc<XConnection>, name: &[u8]) -> Result<ffi::Atom, XError> {
|
|
||||||
let atom_name: *const c_char = name.as_ptr() as _;
|
|
||||||
let atom = (xconn.xlib.XInternAtom)(xconn.display, atom_name, ffi::False);
|
|
||||||
xconn.check_errors().map(|_| atom)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe fn send_client_msg(
|
|
||||||
xconn: &Arc<XConnection>,
|
|
||||||
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: (c_long, c_long, c_long, c_long, c_long),
|
|
||||||
) -> Result<(), XError> {
|
|
||||||
let mut event: ffi::XClientMessageEvent = mem::uninitialized();
|
|
||||||
event.type_ = ffi::ClientMessage;
|
|
||||||
event.display = xconn.display;
|
|
||||||
event.window = window;
|
|
||||||
event.message_type = message_type;
|
|
||||||
event.format = 32;
|
|
||||||
event.data = ffi::ClientMessageData::new();
|
|
||||||
event.data.set_long(0, data.0);
|
|
||||||
event.data.set_long(1, data.1);
|
|
||||||
event.data.set_long(2, data.2);
|
|
||||||
event.data.set_long(3, data.3);
|
|
||||||
event.data.set_long(4, data.4);
|
|
||||||
|
|
||||||
let event_mask = event_mask.unwrap_or(ffi::NoEventMask);
|
|
||||||
|
|
||||||
(xconn.xlib.XSendEvent)(
|
|
||||||
xconn.display,
|
|
||||||
target_window,
|
|
||||||
ffi::False,
|
|
||||||
event_mask,
|
|
||||||
&mut event.into(),
|
|
||||||
);
|
|
||||||
|
|
||||||
xconn.check_errors().map(|_| ())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe fn get_property<T>(
|
|
||||||
xconn: &Arc<XConnection>,
|
|
||||||
window: c_ulong,
|
|
||||||
property: ffi::Atom,
|
|
||||||
property_type: ffi::Atom,
|
|
||||||
) -> Result<Vec<T>, GetPropertyError> {
|
|
||||||
let mut data = Vec::new();
|
|
||||||
|
|
||||||
let mut done = false;
|
|
||||||
while !done {
|
|
||||||
let mut actual_type: ffi::Atom = mem::uninitialized();
|
|
||||||
let mut actual_format: c_int = mem::uninitialized();
|
|
||||||
let mut byte_count: c_ulong = mem::uninitialized();
|
|
||||||
let mut bytes_after: c_ulong = mem::uninitialized();
|
|
||||||
let mut buf: *mut c_uchar = ptr::null_mut();
|
|
||||||
(xconn.xlib.XGetWindowProperty)(
|
|
||||||
xconn.display,
|
|
||||||
window,
|
|
||||||
property,
|
|
||||||
(data.len() / 4) as c_long,
|
|
||||||
1024,
|
|
||||||
ffi::False,
|
|
||||||
property_type,
|
|
||||||
&mut actual_type,
|
|
||||||
&mut actual_format,
|
|
||||||
&mut byte_count,
|
|
||||||
&mut bytes_after,
|
|
||||||
&mut buf,
|
|
||||||
);
|
|
||||||
|
|
||||||
if let Err(e) = xconn.check_errors() {
|
|
||||||
return Err(GetPropertyError::XError(e));
|
|
||||||
}
|
|
||||||
|
|
||||||
if actual_type != property_type {
|
|
||||||
return Err(GetPropertyError::TypeMismatch(actual_type));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fun fact: actual_format ISN'T the size of the type; it's more like a really bad enum
|
|
||||||
let format_mismatch = match actual_format as usize {
|
|
||||||
8 => mem::size_of::<T>() != mem::size_of::<c_char>(),
|
|
||||||
16 => mem::size_of::<T>() != mem::size_of::<c_short>(),
|
|
||||||
32 => mem::size_of::<T>() != mem::size_of::<c_long>(),
|
|
||||||
_ => true, // this won't actually be reached; the XError condition above is triggered
|
|
||||||
};
|
|
||||||
|
|
||||||
if format_mismatch {
|
|
||||||
return Err(GetPropertyError::FormatMismatch(actual_format));
|
|
||||||
}
|
|
||||||
|
|
||||||
if !buf.is_null() {
|
|
||||||
let mut buf =
|
|
||||||
Vec::from_raw_parts(buf as *mut T, byte_count as usize, byte_count as usize);
|
|
||||||
data.append(&mut buf);
|
|
||||||
} else {
|
|
||||||
return Err(GetPropertyError::NothingAllocated);
|
|
||||||
}
|
|
||||||
|
|
||||||
done = bytes_after == 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
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,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct PointerState {
|
|
||||||
#[allow(dead_code)]
|
|
||||||
root: ffi::Window,
|
|
||||||
#[allow(dead_code)]
|
|
||||||
child: ffi::Window,
|
|
||||||
#[allow(dead_code)]
|
|
||||||
root_x: c_double,
|
|
||||||
#[allow(dead_code)]
|
|
||||||
root_y: c_double,
|
|
||||||
#[allow(dead_code)]
|
|
||||||
win_x: c_double,
|
|
||||||
#[allow(dead_code)]
|
|
||||||
win_y: c_double,
|
|
||||||
#[allow(dead_code)]
|
|
||||||
buttons: ffi::XIButtonState,
|
|
||||||
modifiers: ffi::XIModifierState,
|
|
||||||
#[allow(dead_code)]
|
|
||||||
group: ffi::XIGroupState,
|
|
||||||
#[allow(dead_code)]
|
|
||||||
relative_to_window: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PointerState {
|
|
||||||
pub fn get_modifier_state(&self) -> ModifiersState {
|
|
||||||
self.modifiers.into()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub unsafe fn query_pointer(
|
|
||||||
xconn: &Arc<XConnection>,
|
|
||||||
window: ffi::Window,
|
|
||||||
device_id: c_int,
|
|
||||||
) -> Result<PointerState, XError> {
|
|
||||||
let mut root_return = mem::uninitialized();
|
|
||||||
let mut child_return = mem::uninitialized();
|
|
||||||
let mut root_x_return = mem::uninitialized();
|
|
||||||
let mut root_y_return = mem::uninitialized();
|
|
||||||
let mut win_x_return = mem::uninitialized();
|
|
||||||
let mut win_y_return = mem::uninitialized();
|
|
||||||
let mut buttons_return = mem::uninitialized();
|
|
||||||
let mut modifiers_return = mem::uninitialized();
|
|
||||||
let mut group_return = mem::uninitialized();
|
|
||||||
|
|
||||||
let relative_to_window = (xconn.xinput2.XIQueryPointer)(
|
|
||||||
xconn.display,
|
|
||||||
device_id,
|
|
||||||
window,
|
|
||||||
&mut root_return,
|
|
||||||
&mut child_return,
|
|
||||||
&mut root_x_return,
|
|
||||||
&mut root_y_return,
|
|
||||||
&mut win_x_return,
|
|
||||||
&mut win_y_return,
|
|
||||||
&mut buttons_return,
|
|
||||||
&mut modifiers_return,
|
|
||||||
&mut group_return,
|
|
||||||
) == ffi::True;
|
|
||||||
|
|
||||||
xconn.check_errors()?;
|
|
||||||
|
|
||||||
Ok(PointerState {
|
|
||||||
root: root_return,
|
|
||||||
child: child_return,
|
|
||||||
root_x: root_x_return,
|
|
||||||
root_y: root_y_return,
|
|
||||||
win_x: win_x_return,
|
|
||||||
win_y: win_y_return,
|
|
||||||
buttons: buttons_return,
|
|
||||||
modifiers: modifiers_return,
|
|
||||||
group: group_return,
|
|
||||||
relative_to_window,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn lookup_utf8_inner(
|
|
||||||
xconn: &Arc<XConnection>,
|
|
||||||
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 = (xconn.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 unsafe fn lookup_utf8(
|
|
||||||
xconn: &Arc<XConnection>,
|
|
||||||
ic: ffi::XIC,
|
|
||||||
key_event: &mut ffi::XKeyEvent,
|
|
||||||
) -> String {
|
|
||||||
const INIT_BUFF_SIZE: usize = 16;
|
|
||||||
|
|
||||||
// Buffer allocated on heap instead of stack, due to the possible reallocation
|
|
||||||
let mut buffer: Vec<u8> = vec![mem::uninitialized(); INIT_BUFF_SIZE];
|
|
||||||
let (_, status, mut count) = lookup_utf8_inner(
|
|
||||||
xconn,
|
|
||||||
ic,
|
|
||||||
key_event,
|
|
||||||
&mut buffer,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Buffer overflowed, dynamically reallocate
|
|
||||||
if status == ffi::XBufferOverflow {
|
|
||||||
buffer = vec![mem::uninitialized(); count as usize];
|
|
||||||
let (_, _, new_count) = lookup_utf8_inner(
|
|
||||||
xconn,
|
|
||||||
ic,
|
|
||||||
key_event,
|
|
||||||
&mut buffer,
|
|
||||||
);
|
|
||||||
count = new_count;
|
|
||||||
}
|
|
||||||
|
|
||||||
str::from_utf8(&buffer[..count as usize]).unwrap_or("").to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct FrameExtents {
|
|
||||||
pub left: c_ulong,
|
|
||||||
pub right: c_ulong,
|
|
||||||
pub top: c_ulong,
|
|
||||||
pub bottom: c_ulong,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FrameExtents {
|
|
||||||
pub fn new(left: c_ulong, right: c_ulong, top: c_ulong, bottom: c_ulong) -> Self {
|
|
||||||
FrameExtents { left, right, top, bottom }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn from_border(border: c_ulong) -> Self {
|
|
||||||
Self::new(border, border, border, border)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct WindowGeometry {
|
|
||||||
pub x: c_int,
|
|
||||||
pub y: c_int,
|
|
||||||
pub width: c_uint,
|
|
||||||
pub height: c_uint,
|
|
||||||
pub frame: FrameExtents,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowGeometry {
|
|
||||||
pub fn get_position(&self) -> (i32, i32) {
|
|
||||||
(self.x as _, self.y as _)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_inner_position(&self) -> (i32, i32) {
|
|
||||||
(
|
|
||||||
self.x.saturating_add(self.frame.left as c_int) as _,
|
|
||||||
self.y.saturating_add(self.frame.top as c_int) as _,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_inner_size(&self) -> (u32, u32) {
|
|
||||||
(self.width as _, self.height as _)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_outer_size(&self) -> (u32, u32) {
|
|
||||||
(
|
|
||||||
self.width.saturating_add(
|
|
||||||
self.frame.left.saturating_add(self.frame.right) as c_uint
|
|
||||||
) as _,
|
|
||||||
self.height.saturating_add(
|
|
||||||
self.frame.top.saturating_add(self.frame.bottom) as c_uint
|
|
||||||
) as _,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,150 +0,0 @@
|
|||||||
use std::ptr;
|
|
||||||
use std::fmt;
|
|
||||||
use std::error::Error;
|
|
||||||
use std::sync::Mutex;
|
|
||||||
|
|
||||||
use libc;
|
|
||||||
|
|
||||||
use super::ffi;
|
|
||||||
|
|
||||||
/// A connection to an X server.
|
|
||||||
pub struct XConnection {
|
|
||||||
pub xlib: ffi::Xlib,
|
|
||||||
/// Exposes XRandR functions from version < 1.5
|
|
||||||
pub xrandr: ffi::Xrandr_2_2_0,
|
|
||||||
/// Exposes XRandR functions from version = 1.5
|
|
||||||
pub xrandr_1_5: Option<ffi::Xrandr>,
|
|
||||||
pub xcursor: ffi::Xcursor,
|
|
||||||
pub xinput2: ffi::XInput2,
|
|
||||||
pub xlib_xcb: ffi::Xlib_xcb,
|
|
||||||
pub display: *mut ffi::Display,
|
|
||||||
pub latest_error: Mutex<Option<XError>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe impl Send for XConnection {}
|
|
||||||
unsafe impl Sync for XConnection {}
|
|
||||||
|
|
||||||
pub type XErrorHandler = Option<unsafe extern fn(*mut ffi::Display, *mut ffi::XErrorEvent) -> libc::c_int>;
|
|
||||||
|
|
||||||
impl XConnection {
|
|
||||||
pub fn new(error_handler: XErrorHandler) -> Result<XConnection, XNotSupported> {
|
|
||||||
// opening the libraries
|
|
||||||
let xlib = try!(ffi::Xlib::open());
|
|
||||||
let xcursor = try!(ffi::Xcursor::open());
|
|
||||||
let xrandr = try!(ffi::Xrandr_2_2_0::open());
|
|
||||||
let xrandr_1_5 = ffi::Xrandr::open().ok();
|
|
||||||
let xinput2 = try!(ffi::XInput2::open());
|
|
||||||
let xlib_xcb = try!(ffi::Xlib_xcb::open());
|
|
||||||
|
|
||||||
unsafe { (xlib.XInitThreads)() };
|
|
||||||
unsafe { (xlib.XSetErrorHandler)(error_handler) };
|
|
||||||
|
|
||||||
// calling XOpenDisplay
|
|
||||||
let display = unsafe {
|
|
||||||
let display = (xlib.XOpenDisplay)(ptr::null());
|
|
||||||
if display.is_null() {
|
|
||||||
return Err(XNotSupported::XOpenDisplayFailed);
|
|
||||||
}
|
|
||||||
display
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(XConnection {
|
|
||||||
xlib: xlib,
|
|
||||||
xrandr: xrandr,
|
|
||||||
xrandr_1_5: xrandr_1_5,
|
|
||||||
xcursor: xcursor,
|
|
||||||
xinput2: xinput2,
|
|
||||||
xlib_xcb: xlib_xcb,
|
|
||||||
display: display,
|
|
||||||
latest_error: Mutex::new(None),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Checks whether an error has been triggered by the previous function calls.
|
|
||||||
#[inline]
|
|
||||||
pub fn check_errors(&self) -> Result<(), XError> {
|
|
||||||
let error = self.latest_error.lock().unwrap().take();
|
|
||||||
|
|
||||||
if let Some(error) = error {
|
|
||||||
Err(error)
|
|
||||||
} else {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Ignores any previous error.
|
|
||||||
#[inline]
|
|
||||||
pub fn ignore_error(&self) {
|
|
||||||
*self.latest_error.lock().unwrap() = None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for XConnection {
|
|
||||||
#[inline]
|
|
||||||
fn drop(&mut self) {
|
|
||||||
unsafe { (self.xlib.XCloseDisplay)(self.display) };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Error triggered by xlib.
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct XError {
|
|
||||||
pub description: String,
|
|
||||||
pub error_code: u8,
|
|
||||||
pub request_code: u8,
|
|
||||||
pub minor_code: u8,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Error for XError {
|
|
||||||
#[inline]
|
|
||||||
fn description(&self) -> &str {
|
|
||||||
&self.description
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for XError {
|
|
||||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
|
||||||
write!(formatter, "X error: {} (code: {}, request code: {}, minor code: {})",
|
|
||||||
self.description, self.error_code, self.request_code, self.minor_code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Error returned if this system doesn't have XLib or can't create an X connection.
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub enum XNotSupported {
|
|
||||||
/// Failed to load one or several shared libraries.
|
|
||||||
LibraryOpenError(ffi::OpenError),
|
|
||||||
/// Connecting to the X server with `XOpenDisplay` failed.
|
|
||||||
XOpenDisplayFailed, // TODO: add better message
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<ffi::OpenError> for XNotSupported {
|
|
||||||
#[inline]
|
|
||||||
fn from(err: ffi::OpenError) -> XNotSupported {
|
|
||||||
XNotSupported::LibraryOpenError(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Error for XNotSupported {
|
|
||||||
#[inline]
|
|
||||||
fn description(&self) -> &str {
|
|
||||||
match *self {
|
|
||||||
XNotSupported::LibraryOpenError(_) => "Failed to load one of xlib's shared libraries",
|
|
||||||
XNotSupported::XOpenDisplayFailed => "Failed to open connection to X server",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn cause(&self) -> Option<&Error> {
|
|
||||||
match *self {
|
|
||||||
XNotSupported::LibraryOpenError(ref err) => Some(err),
|
|
||||||
_ => None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for XNotSupported {
|
|
||||||
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
|
||||||
formatter.write_str(self.description())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
443
src/platform/macos.rs
Normal file
@@ -0,0 +1,443 @@
|
|||||||
|
//! # macOS / AppKit
|
||||||
|
//!
|
||||||
|
//! Winit has an OS requirement of macOS 10.11 or higher (same as Rust
|
||||||
|
//! itself), and is regularly tested on macOS 10.14.
|
||||||
|
//!
|
||||||
|
//! A lot of functionality expects the application to be ready before you
|
||||||
|
//! start doing anything; this includes creating windows, fetching monitors,
|
||||||
|
//! drawing, and so on, see issues [#2238], [#2051] and [#2087].
|
||||||
|
//!
|
||||||
|
//! If you encounter problems, you should try doing your initialization inside
|
||||||
|
//! `Event::Resumed`.
|
||||||
|
//!
|
||||||
|
//! [#2238]: https://github.com/rust-windowing/winit/issues/2238
|
||||||
|
//! [#2051]: https://github.com/rust-windowing/winit/issues/2051
|
||||||
|
//! [#2087]: https://github.com/rust-windowing/winit/issues/2087
|
||||||
|
|
||||||
|
use std::os::raw::c_void;
|
||||||
|
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
event_loop::{ActiveEventLoop, EventLoopBuilder},
|
||||||
|
monitor::MonitorHandle,
|
||||||
|
window::{Window, WindowAttributes},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Additional methods on [`Window`] that are specific to MacOS.
|
||||||
|
pub trait WindowExtMacOS {
|
||||||
|
/// Returns whether or not the window is in simple fullscreen mode.
|
||||||
|
fn simple_fullscreen(&self) -> bool;
|
||||||
|
|
||||||
|
/// Toggles a fullscreen mode that doesn't require a new macOS space.
|
||||||
|
/// Returns a boolean indicating whether the transition was successful (this
|
||||||
|
/// won't work if the window was already in the native fullscreen).
|
||||||
|
///
|
||||||
|
/// This is how fullscreen used to work on macOS in versions before Lion.
|
||||||
|
/// And allows the user to have a fullscreen window without using another
|
||||||
|
/// space or taking control over the entire monitor.
|
||||||
|
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool;
|
||||||
|
|
||||||
|
/// Returns whether or not the window has shadow.
|
||||||
|
fn has_shadow(&self) -> bool;
|
||||||
|
|
||||||
|
/// Sets whether or not the window has shadow.
|
||||||
|
fn set_has_shadow(&self, has_shadow: bool);
|
||||||
|
|
||||||
|
/// Group windows together by using the same tabbing identifier.
|
||||||
|
///
|
||||||
|
/// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
|
||||||
|
fn set_tabbing_identifier(&self, identifier: &str);
|
||||||
|
|
||||||
|
/// Returns the window's tabbing identifier.
|
||||||
|
fn tabbing_identifier(&self) -> String;
|
||||||
|
|
||||||
|
/// Select next tab.
|
||||||
|
fn select_next_tab(&self);
|
||||||
|
|
||||||
|
/// Select previous tab.
|
||||||
|
fn select_previous_tab(&self);
|
||||||
|
|
||||||
|
/// Select the tab with the given index.
|
||||||
|
///
|
||||||
|
/// Will no-op when the index is out of bounds.
|
||||||
|
fn select_tab_at_index(&self, index: usize);
|
||||||
|
|
||||||
|
/// Get the number of tabs in the window tab group.
|
||||||
|
fn num_tabs(&self) -> usize;
|
||||||
|
|
||||||
|
/// Get the window's edit state.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```ignore
|
||||||
|
/// WindowEvent::CloseRequested => {
|
||||||
|
/// if window.is_document_edited() {
|
||||||
|
/// // Show the user a save pop-up or similar
|
||||||
|
/// } else {
|
||||||
|
/// // Close the window
|
||||||
|
/// drop(window);
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
fn is_document_edited(&self) -> bool;
|
||||||
|
|
||||||
|
/// Put the window in a state which indicates a file save is required.
|
||||||
|
fn set_document_edited(&self, edited: bool);
|
||||||
|
|
||||||
|
/// Set option as alt behavior as described in [`OptionAsAlt`].
|
||||||
|
///
|
||||||
|
/// This will ignore diacritical marks and accent characters from
|
||||||
|
/// being processed as received characters. Instead, the input
|
||||||
|
/// device's raw character will be placed in event queues with the
|
||||||
|
/// Alt modifier set.
|
||||||
|
fn set_option_as_alt(&self, option_as_alt: OptionAsAlt);
|
||||||
|
|
||||||
|
/// Getter for the [`WindowExtMacOS::set_option_as_alt`].
|
||||||
|
fn option_as_alt(&self) -> OptionAsAlt;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowExtMacOS for Window {
|
||||||
|
#[inline]
|
||||||
|
fn simple_fullscreen(&self) -> bool {
|
||||||
|
self.window.maybe_wait_on_main(|w| w.simple_fullscreen())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool {
|
||||||
|
self.window
|
||||||
|
.maybe_wait_on_main(move |w| w.set_simple_fullscreen(fullscreen))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn has_shadow(&self) -> bool {
|
||||||
|
self.window.maybe_wait_on_main(|w| w.has_shadow())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_has_shadow(&self, has_shadow: bool) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_has_shadow(has_shadow))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_tabbing_identifier(&self, identifier: &str) {
|
||||||
|
self.window
|
||||||
|
.maybe_wait_on_main(|w| w.set_tabbing_identifier(identifier))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn tabbing_identifier(&self) -> String {
|
||||||
|
self.window.maybe_wait_on_main(|w| w.tabbing_identifier())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn select_next_tab(&self) {
|
||||||
|
self.window.maybe_queue_on_main(|w| w.select_next_tab())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn select_previous_tab(&self) {
|
||||||
|
self.window.maybe_queue_on_main(|w| w.select_previous_tab())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn select_tab_at_index(&self, index: usize) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.select_tab_at_index(index))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn num_tabs(&self) -> usize {
|
||||||
|
self.window.maybe_wait_on_main(|w| w.num_tabs())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn is_document_edited(&self) -> bool {
|
||||||
|
self.window.maybe_wait_on_main(|w| w.is_document_edited())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_document_edited(&self, edited: bool) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_document_edited(edited))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_option_as_alt(option_as_alt))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn option_as_alt(&self) -> OptionAsAlt {
|
||||||
|
self.window.maybe_wait_on_main(|w| w.option_as_alt())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Corresponds to `NSApplicationActivationPolicy`.
|
||||||
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub enum ActivationPolicy {
|
||||||
|
/// Corresponds to `NSApplicationActivationPolicyRegular`.
|
||||||
|
#[default]
|
||||||
|
Regular,
|
||||||
|
|
||||||
|
/// Corresponds to `NSApplicationActivationPolicyAccessory`.
|
||||||
|
Accessory,
|
||||||
|
|
||||||
|
/// Corresponds to `NSApplicationActivationPolicyProhibited`.
|
||||||
|
Prohibited,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`WindowAttributes`] that are specific to MacOS.
|
||||||
|
///
|
||||||
|
/// **Note:** Properties dealing with the titlebar will be overwritten by the [`WindowAttributes::with_decorations`] method:
|
||||||
|
/// - `with_titlebar_transparent`
|
||||||
|
/// - `with_title_hidden`
|
||||||
|
/// - `with_titlebar_hidden`
|
||||||
|
/// - `with_titlebar_buttons_hidden`
|
||||||
|
/// - `with_fullsize_content_view`
|
||||||
|
pub trait WindowAttributesExtMacOS {
|
||||||
|
/// Enables click-and-drag behavior for the entire window, not just the titlebar.
|
||||||
|
fn with_movable_by_window_background(self, movable_by_window_background: bool) -> Self;
|
||||||
|
/// Makes the titlebar transparent and allows the content to appear behind it.
|
||||||
|
fn with_titlebar_transparent(self, titlebar_transparent: bool) -> Self;
|
||||||
|
/// Hides the window title.
|
||||||
|
fn with_title_hidden(self, title_hidden: bool) -> Self;
|
||||||
|
/// Hides the window titlebar.
|
||||||
|
fn with_titlebar_hidden(self, titlebar_hidden: bool) -> Self;
|
||||||
|
/// Hides the window titlebar buttons.
|
||||||
|
fn with_titlebar_buttons_hidden(self, titlebar_buttons_hidden: bool) -> Self;
|
||||||
|
/// Makes the window content appear behind the titlebar.
|
||||||
|
fn with_fullsize_content_view(self, fullsize_content_view: bool) -> Self;
|
||||||
|
fn with_disallow_hidpi(self, disallow_hidpi: bool) -> Self;
|
||||||
|
fn with_has_shadow(self, has_shadow: bool) -> Self;
|
||||||
|
/// Window accepts click-through mouse events.
|
||||||
|
fn with_accepts_first_mouse(self, accepts_first_mouse: bool) -> Self;
|
||||||
|
/// Defines the window tabbing identifier.
|
||||||
|
///
|
||||||
|
/// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
|
||||||
|
fn with_tabbing_identifier(self, identifier: &str) -> Self;
|
||||||
|
/// Set how the <kbd>Option</kbd> keys are interpreted.
|
||||||
|
///
|
||||||
|
/// See [`WindowExtMacOS::set_option_as_alt`] for details on what this means if set.
|
||||||
|
fn with_option_as_alt(self, option_as_alt: OptionAsAlt) -> Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowAttributesExtMacOS for WindowAttributes {
|
||||||
|
#[inline]
|
||||||
|
fn with_movable_by_window_background(mut self, movable_by_window_background: bool) -> Self {
|
||||||
|
self.platform_specific.movable_by_window_background = movable_by_window_background;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> Self {
|
||||||
|
self.platform_specific.titlebar_transparent = titlebar_transparent;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_titlebar_hidden(mut self, titlebar_hidden: bool) -> Self {
|
||||||
|
self.platform_specific.titlebar_hidden = titlebar_hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_titlebar_buttons_hidden(mut self, titlebar_buttons_hidden: bool) -> Self {
|
||||||
|
self.platform_specific.titlebar_buttons_hidden = titlebar_buttons_hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_title_hidden(mut self, title_hidden: bool) -> Self {
|
||||||
|
self.platform_specific.title_hidden = title_hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_fullsize_content_view(mut self, fullsize_content_view: bool) -> Self {
|
||||||
|
self.platform_specific.fullsize_content_view = fullsize_content_view;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_disallow_hidpi(mut self, disallow_hidpi: bool) -> Self {
|
||||||
|
self.platform_specific.disallow_hidpi = disallow_hidpi;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_has_shadow(mut self, has_shadow: bool) -> Self {
|
||||||
|
self.platform_specific.has_shadow = has_shadow;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_accepts_first_mouse(mut self, accepts_first_mouse: bool) -> Self {
|
||||||
|
self.platform_specific.accepts_first_mouse = accepts_first_mouse;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_tabbing_identifier(mut self, tabbing_identifier: &str) -> Self {
|
||||||
|
self.platform_specific
|
||||||
|
.tabbing_identifier
|
||||||
|
.replace(tabbing_identifier.to_string());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_option_as_alt(mut self, option_as_alt: OptionAsAlt) -> Self {
|
||||||
|
self.platform_specific.option_as_alt = option_as_alt;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait EventLoopBuilderExtMacOS {
|
||||||
|
/// Sets the activation policy for the application.
|
||||||
|
///
|
||||||
|
/// It is set to [`ActivationPolicy::Regular`] by default.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// Set the activation policy to "accessory".
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use winit::event_loop::EventLoopBuilder;
|
||||||
|
/// #[cfg(target_os = "macos")]
|
||||||
|
/// use winit::platform::macos::{EventLoopBuilderExtMacOS, ActivationPolicy};
|
||||||
|
///
|
||||||
|
/// let mut builder = EventLoopBuilder::new();
|
||||||
|
/// #[cfg(target_os = "macos")]
|
||||||
|
/// builder.with_activation_policy(ActivationPolicy::Accessory);
|
||||||
|
/// # if false { // We can't test this part
|
||||||
|
/// let event_loop = builder.build();
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
fn with_activation_policy(&mut self, activation_policy: ActivationPolicy) -> &mut Self;
|
||||||
|
|
||||||
|
/// Used to control whether a default menubar menu is created.
|
||||||
|
///
|
||||||
|
/// Menu creation is enabled by default.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// Disable creating a default menubar.
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use winit::event_loop::EventLoopBuilder;
|
||||||
|
/// #[cfg(target_os = "macos")]
|
||||||
|
/// use winit::platform::macos::EventLoopBuilderExtMacOS;
|
||||||
|
///
|
||||||
|
/// let mut builder = EventLoopBuilder::new();
|
||||||
|
/// #[cfg(target_os = "macos")]
|
||||||
|
/// builder.with_default_menu(false);
|
||||||
|
/// # if false { // We can't test this part
|
||||||
|
/// let event_loop = builder.build();
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
fn with_default_menu(&mut self, enable: bool) -> &mut Self;
|
||||||
|
|
||||||
|
/// Used to prevent the application from automatically activating when launched if
|
||||||
|
/// another application is already active.
|
||||||
|
///
|
||||||
|
/// The default behavior is to ignore other applications and activate when launched.
|
||||||
|
fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopBuilderExtMacOS for EventLoopBuilder<T> {
|
||||||
|
#[inline]
|
||||||
|
fn with_activation_policy(&mut self, activation_policy: ActivationPolicy) -> &mut Self {
|
||||||
|
self.platform_specific.activation_policy = activation_policy;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_default_menu(&mut self, enable: bool) -> &mut Self {
|
||||||
|
self.platform_specific.default_menu = enable;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self {
|
||||||
|
self.platform_specific.activate_ignoring_other_apps = ignore;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`MonitorHandle`] that are specific to MacOS.
|
||||||
|
pub trait MonitorHandleExtMacOS {
|
||||||
|
/// Returns the identifier of the monitor for Cocoa.
|
||||||
|
fn native_id(&self) -> u32;
|
||||||
|
/// Returns a pointer to the NSScreen representing this monitor.
|
||||||
|
fn ns_screen(&self) -> Option<*mut c_void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonitorHandleExtMacOS for MonitorHandle {
|
||||||
|
#[inline]
|
||||||
|
fn native_id(&self) -> u32 {
|
||||||
|
self.inner.native_identifier()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ns_screen(&self) -> Option<*mut c_void> {
|
||||||
|
// SAFETY: We only use the marker to get a pointer
|
||||||
|
let mtm = unsafe { icrate::Foundation::MainThreadMarker::new_unchecked() };
|
||||||
|
self.inner
|
||||||
|
.ns_screen(mtm)
|
||||||
|
.map(|s| objc2::rc::Id::as_ptr(&s) as _)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`ActiveEventLoop`] that are specific to macOS.
|
||||||
|
pub trait ActiveEventLoopExtMacOS {
|
||||||
|
/// Hide the entire application. In most applications this is typically triggered with Command-H.
|
||||||
|
fn hide_application(&self);
|
||||||
|
/// Hide the other applications. In most applications this is typically triggered with Command+Option-H.
|
||||||
|
fn hide_other_applications(&self);
|
||||||
|
/// Set whether the system can automatically organize windows into tabs.
|
||||||
|
///
|
||||||
|
/// <https://developer.apple.com/documentation/appkit/nswindow/1646657-allowsautomaticwindowtabbing>
|
||||||
|
fn set_allows_automatic_window_tabbing(&self, enabled: bool);
|
||||||
|
/// Returns whether the system can automatically organize windows into tabs.
|
||||||
|
fn allows_automatic_window_tabbing(&self) -> bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActiveEventLoopExtMacOS for ActiveEventLoop {
|
||||||
|
fn hide_application(&self) {
|
||||||
|
self.p.hide_application()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hide_other_applications(&self) {
|
||||||
|
self.p.hide_other_applications()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_allows_automatic_window_tabbing(&self, enabled: bool) {
|
||||||
|
self.p.set_allows_automatic_window_tabbing(enabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn allows_automatic_window_tabbing(&self) -> bool {
|
||||||
|
self.p.allows_automatic_window_tabbing()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Option as alt behavior.
|
||||||
|
///
|
||||||
|
/// The default is `None`.
|
||||||
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
pub enum OptionAsAlt {
|
||||||
|
/// The left `Option` key is treated as `Alt`.
|
||||||
|
OnlyLeft,
|
||||||
|
|
||||||
|
/// The right `Option` key is treated as `Alt`.
|
||||||
|
OnlyRight,
|
||||||
|
|
||||||
|
/// Both `Option` keys are treated as `Alt`.
|
||||||
|
Both,
|
||||||
|
|
||||||
|
/// No special handling is applied for `Option` key.
|
||||||
|
#[default]
|
||||||
|
None,
|
||||||
|
}
|
||||||
@@ -1,774 +0,0 @@
|
|||||||
use {ControlFlow, EventsLoopClosed};
|
|
||||||
use cocoa::{self, appkit, foundation};
|
|
||||||
use cocoa::appkit::{NSApplication, NSEvent, NSEventMask, NSEventModifierFlags, NSEventPhase, NSView, NSWindow};
|
|
||||||
use events::{self, ElementState, Event, MouseButton, TouchPhase, WindowEvent, DeviceEvent, ModifiersState, KeyboardInput};
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
use std::sync::{Arc, Mutex, Weak};
|
|
||||||
use super::window::Window2;
|
|
||||||
use std;
|
|
||||||
use super::DeviceId;
|
|
||||||
|
|
||||||
|
|
||||||
pub struct EventsLoop {
|
|
||||||
modifiers: Modifiers,
|
|
||||||
pub shared: Arc<Shared>,
|
|
||||||
}
|
|
||||||
|
|
||||||
// State shared between the `EventsLoop` and its registered windows.
|
|
||||||
pub struct Shared {
|
|
||||||
pub windows: Mutex<Vec<Weak<Window2>>>,
|
|
||||||
pub pending_events: Mutex<VecDeque<Event>>,
|
|
||||||
// The user event callback given via either of the `poll_events` or `run_forever` methods.
|
|
||||||
//
|
|
||||||
// We store the user's callback here so that it may be accessed by each of the window delegate
|
|
||||||
// callbacks (e.g. resize, close, etc) for the duration of a call to either of the
|
|
||||||
// `poll_events` or `run_forever` methods.
|
|
||||||
//
|
|
||||||
// This is *only* `Some` for the duration of a call to either of these methods and will be
|
|
||||||
// `None` otherwise.
|
|
||||||
user_callback: UserCallback,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct Proxy {}
|
|
||||||
|
|
||||||
struct Modifiers {
|
|
||||||
shift_pressed: bool,
|
|
||||||
ctrl_pressed: bool,
|
|
||||||
win_pressed: bool,
|
|
||||||
alt_pressed: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wrapping the user callback in a type allows us to:
|
|
||||||
//
|
|
||||||
// - ensure the callback pointer is never accidentally cloned
|
|
||||||
// - ensure that only the `EventsLoop` can `store` and `drop` the callback pointer
|
|
||||||
// - Share access to the user callback with the NSWindow callbacks.
|
|
||||||
pub struct UserCallback {
|
|
||||||
mutex: Mutex<Option<*mut FnMut(Event)>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
impl Shared {
|
|
||||||
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Shared {
|
|
||||||
windows: Mutex::new(Vec::new()),
|
|
||||||
pending_events: Mutex::new(VecDeque::new()),
|
|
||||||
user_callback: UserCallback { mutex: Mutex::new(None) },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn call_user_callback_with_pending_events(&self) {
|
|
||||||
loop {
|
|
||||||
let event = match self.pending_events.lock().unwrap().pop_front() {
|
|
||||||
Some(event) => event,
|
|
||||||
None => return,
|
|
||||||
};
|
|
||||||
unsafe {
|
|
||||||
self.user_callback.call_with_event(event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Calls the user callback if one exists.
|
|
||||||
//
|
|
||||||
// Otherwise, stores the event in the `pending_events` queue.
|
|
||||||
//
|
|
||||||
// This is necessary for the case when `WindowDelegate` callbacks are triggered during a call
|
|
||||||
// to the user's callback.
|
|
||||||
pub fn call_user_callback_with_event_or_store_in_pending(&self, event: Event) {
|
|
||||||
if self.user_callback.mutex.lock().unwrap().is_some() {
|
|
||||||
unsafe {
|
|
||||||
self.user_callback.call_with_event(event);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
self.pending_events.lock().unwrap().push_back(event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Removes the window with the given `Id` from the `windows` list.
|
|
||||||
//
|
|
||||||
// This is called in response to `windowWillClose`.
|
|
||||||
pub fn find_and_remove_window(&self, id: super::window::Id) {
|
|
||||||
if let Ok(mut windows) = self.windows.lock() {
|
|
||||||
windows.retain(|w| match w.upgrade() {
|
|
||||||
Some(w) => w.id() != id,
|
|
||||||
None => true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
impl Modifiers {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Modifiers {
|
|
||||||
shift_pressed: false,
|
|
||||||
ctrl_pressed: false,
|
|
||||||
win_pressed: false,
|
|
||||||
alt_pressed: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
impl UserCallback {
|
|
||||||
|
|
||||||
// Here we store user's `callback` behind the mutex so that they may be safely shared between
|
|
||||||
// each of the window delegates.
|
|
||||||
//
|
|
||||||
// In order to make sure that the pointer is always valid, we must manually guarantee that it
|
|
||||||
// is dropped before the callback itself is dropped. Thus, this should *only* be called at the
|
|
||||||
// beginning of a call to `poll_events` and `run_forever`, both of which *must* drop the
|
|
||||||
// callback at the end of their scope using the `drop` method.
|
|
||||||
fn store<F>(&self, callback: &mut F)
|
|
||||||
where F: FnMut(Event)
|
|
||||||
{
|
|
||||||
let trait_object = callback as &mut FnMut(Event);
|
|
||||||
let trait_object_ptr = trait_object as *const FnMut(Event) as *mut FnMut(Event);
|
|
||||||
*self.mutex.lock().unwrap() = Some(trait_object_ptr);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Emits the given event via the user-given callback.
|
|
||||||
//
|
|
||||||
// This is unsafe as it requires dereferencing the pointer to the user-given callback. We
|
|
||||||
// guarantee this is safe by ensuring the `UserCallback` never lives longer than the user-given
|
|
||||||
// callback.
|
|
||||||
//
|
|
||||||
// Note that the callback may not always be `Some`. This is because some `NSWindowDelegate`
|
|
||||||
// callbacks can be triggered by means other than `NSApp().sendEvent`. For example, if a window
|
|
||||||
// is destroyed or created during a call to the user's callback, the `WindowDelegate` methods
|
|
||||||
// may be called with `windowShouldClose` or `windowDidResignKey`.
|
|
||||||
unsafe fn call_with_event(&self, event: Event) {
|
|
||||||
let callback = match self.mutex.lock().unwrap().take() {
|
|
||||||
Some(callback) => callback,
|
|
||||||
None => return,
|
|
||||||
};
|
|
||||||
(*callback)(event);
|
|
||||||
*self.mutex.lock().unwrap() = Some(callback);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Used to drop the user callback pointer at the end of the `poll_events` and `run_forever`
|
|
||||||
// methods. This is done to enforce our guarantee that the top callback will never live longer
|
|
||||||
// than the call to either `poll_events` or `run_forever` to which it was given.
|
|
||||||
fn drop(&self) {
|
|
||||||
self.mutex.lock().unwrap().take();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
impl EventsLoop {
|
|
||||||
|
|
||||||
pub fn new() -> Self {
|
|
||||||
// Mark this thread as the main thread of the Cocoa event system.
|
|
||||||
//
|
|
||||||
// This must be done before any worker threads get a chance to call it
|
|
||||||
// (e.g., via `EventsLoopProxy::wakeup()`), causing a wrong thread to be
|
|
||||||
// marked as the main thread.
|
|
||||||
unsafe { appkit::NSApp(); }
|
|
||||||
|
|
||||||
EventsLoop {
|
|
||||||
shared: Arc::new(Shared::new()),
|
|
||||||
modifiers: Modifiers::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn poll_events<F>(&mut self, mut callback: F)
|
|
||||||
where F: FnMut(Event),
|
|
||||||
{
|
|
||||||
unsafe {
|
|
||||||
if !msg_send![cocoa::base::class("NSThread"), isMainThread] {
|
|
||||||
panic!("Events can only be polled from the main thread on macOS");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self.shared.user_callback.store(&mut callback);
|
|
||||||
|
|
||||||
// Loop as long as we have pending events to return.
|
|
||||||
loop {
|
|
||||||
unsafe {
|
|
||||||
// First, yield all pending events.
|
|
||||||
self.shared.call_user_callback_with_pending_events();
|
|
||||||
|
|
||||||
let pool = foundation::NSAutoreleasePool::new(cocoa::base::nil);
|
|
||||||
|
|
||||||
// Poll for the next event, returning `nil` if there are none.
|
|
||||||
let ns_event = appkit::NSApp().nextEventMatchingMask_untilDate_inMode_dequeue_(
|
|
||||||
NSEventMask::NSAnyEventMask.bits() | NSEventMask::NSEventMaskPressure.bits(),
|
|
||||||
foundation::NSDate::distantPast(cocoa::base::nil),
|
|
||||||
foundation::NSDefaultRunLoopMode,
|
|
||||||
cocoa::base::YES);
|
|
||||||
|
|
||||||
let event = self.ns_event_to_event(ns_event);
|
|
||||||
|
|
||||||
let _: () = msg_send![pool, release];
|
|
||||||
|
|
||||||
match event {
|
|
||||||
// Call the user's callback.
|
|
||||||
Some(event) => self.shared.user_callback.call_with_event(event),
|
|
||||||
None => break,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self.shared.user_callback.drop();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn run_forever<F>(&mut self, mut callback: F)
|
|
||||||
where F: FnMut(Event) -> ControlFlow
|
|
||||||
{
|
|
||||||
unsafe {
|
|
||||||
if !msg_send![cocoa::base::class("NSThread"), isMainThread] {
|
|
||||||
panic!("Events can only be polled from the main thread on macOS");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Track whether or not control flow has changed.
|
|
||||||
let control_flow = std::cell::Cell::new(ControlFlow::Continue);
|
|
||||||
|
|
||||||
let mut callback = |event| {
|
|
||||||
if let ControlFlow::Break = callback(event) {
|
|
||||||
control_flow.set(ControlFlow::Break);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
self.shared.user_callback.store(&mut callback);
|
|
||||||
|
|
||||||
loop {
|
|
||||||
unsafe {
|
|
||||||
// First, yield all pending events.
|
|
||||||
self.shared.call_user_callback_with_pending_events();
|
|
||||||
if let ControlFlow::Break = control_flow.get() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
let pool = foundation::NSAutoreleasePool::new(cocoa::base::nil);
|
|
||||||
|
|
||||||
// Wait for the next event. Note that this function blocks during resize.
|
|
||||||
let ns_event = appkit::NSApp().nextEventMatchingMask_untilDate_inMode_dequeue_(
|
|
||||||
NSEventMask::NSAnyEventMask.bits() | NSEventMask::NSEventMaskPressure.bits(),
|
|
||||||
foundation::NSDate::distantFuture(cocoa::base::nil),
|
|
||||||
foundation::NSDefaultRunLoopMode,
|
|
||||||
cocoa::base::YES);
|
|
||||||
|
|
||||||
let maybe_event = self.ns_event_to_event(ns_event);
|
|
||||||
|
|
||||||
// Release the pool before calling the top callback in case the user calls either
|
|
||||||
// `run_forever` or `poll_events` within the callback.
|
|
||||||
let _: () = msg_send![pool, release];
|
|
||||||
|
|
||||||
if let Some(event) = maybe_event {
|
|
||||||
self.shared.user_callback.call_with_event(event);
|
|
||||||
if let ControlFlow::Break = control_flow.get() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self.shared.user_callback.drop();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert some given `NSEvent` into a winit `Event`.
|
|
||||||
unsafe fn ns_event_to_event(&mut self, ns_event: cocoa::base::id) -> Option<Event> {
|
|
||||||
if ns_event == cocoa::base::nil {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
// FIXME: Despite not being documented anywhere, an `NSEvent` is produced when a user opens
|
|
||||||
// Spotlight while the NSApplication is in focus. This `NSEvent` produces a `NSEventType`
|
|
||||||
// with value `21`. This causes a SEGFAULT as soon as we try to match on the `NSEventType`
|
|
||||||
// enum as there is no variant associated with the value. Thus, we return early if this
|
|
||||||
// sneaky event occurs. If someone does find some documentation on this, please fix this by
|
|
||||||
// adding an appropriate variant to the `NSEventType` enum in the cocoa-rs crate.
|
|
||||||
if ns_event.eventType() as u64 == 21 {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let event_type = ns_event.eventType();
|
|
||||||
let ns_window = ns_event.window();
|
|
||||||
let window_id = super::window::get_window_id(ns_window);
|
|
||||||
|
|
||||||
// FIXME: Document this. Why do we do this? Seems like it passes on events to window/app.
|
|
||||||
// If we don't do this, window does not become main for some reason.
|
|
||||||
match event_type {
|
|
||||||
appkit::NSKeyDown => (),
|
|
||||||
_ => appkit::NSApp().sendEvent_(ns_event),
|
|
||||||
}
|
|
||||||
|
|
||||||
let windows = self.shared.windows.lock().unwrap();
|
|
||||||
let maybe_window = windows.iter()
|
|
||||||
.filter_map(Weak::upgrade)
|
|
||||||
.find(|window| window_id == window.id());
|
|
||||||
|
|
||||||
let into_event = |window_event| Event::WindowEvent {
|
|
||||||
window_id: ::WindowId(window_id),
|
|
||||||
event: window_event,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Returns `Some` window if one of our windows is the key window.
|
|
||||||
let maybe_key_window = || windows.iter()
|
|
||||||
.filter_map(Weak::upgrade)
|
|
||||||
.find(|window| {
|
|
||||||
let is_key_window: cocoa::base::BOOL = msg_send![*window.window, isKeyWindow];
|
|
||||||
is_key_window == cocoa::base::YES
|
|
||||||
});
|
|
||||||
|
|
||||||
match event_type {
|
|
||||||
|
|
||||||
appkit::NSKeyDown => {
|
|
||||||
let mut events = std::collections::VecDeque::new();
|
|
||||||
let received_c_str = foundation::NSString::UTF8String(ns_event.characters());
|
|
||||||
let received_str = std::ffi::CStr::from_ptr(received_c_str);
|
|
||||||
|
|
||||||
let vkey = to_virtual_key_code(NSEvent::keyCode(ns_event));
|
|
||||||
let state = ElementState::Pressed;
|
|
||||||
let code = NSEvent::keyCode(ns_event) as u32;
|
|
||||||
let window_event = WindowEvent::KeyboardInput {
|
|
||||||
device_id: DEVICE_ID,
|
|
||||||
input: KeyboardInput {
|
|
||||||
state: state,
|
|
||||||
scancode: code,
|
|
||||||
virtual_keycode: vkey,
|
|
||||||
modifiers: event_mods(ns_event),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
for received_char in std::str::from_utf8(received_str.to_bytes()).unwrap().chars() {
|
|
||||||
let window_event = WindowEvent::ReceivedCharacter(received_char);
|
|
||||||
events.push_back(into_event(window_event));
|
|
||||||
}
|
|
||||||
self.shared.pending_events.lock().unwrap().extend(events.into_iter());
|
|
||||||
Some(into_event(window_event))
|
|
||||||
},
|
|
||||||
|
|
||||||
appkit::NSKeyUp => {
|
|
||||||
let vkey = to_virtual_key_code(NSEvent::keyCode(ns_event));
|
|
||||||
|
|
||||||
let state = ElementState::Released;
|
|
||||||
let code = NSEvent::keyCode(ns_event) as u32;
|
|
||||||
let window_event = WindowEvent::KeyboardInput {
|
|
||||||
device_id: DEVICE_ID,
|
|
||||||
input: KeyboardInput {
|
|
||||||
state: state,
|
|
||||||
scancode: code,
|
|
||||||
virtual_keycode: vkey,
|
|
||||||
modifiers: event_mods(ns_event),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
Some(into_event(window_event))
|
|
||||||
},
|
|
||||||
|
|
||||||
appkit::NSFlagsChanged => {
|
|
||||||
unsafe fn modifier_event(event: cocoa::base::id,
|
|
||||||
keymask: NSEventModifierFlags,
|
|
||||||
key: events::VirtualKeyCode,
|
|
||||||
key_pressed: bool) -> Option<WindowEvent>
|
|
||||||
{
|
|
||||||
if !key_pressed && NSEvent::modifierFlags(event).contains(keymask) {
|
|
||||||
let state = ElementState::Pressed;
|
|
||||||
let code = NSEvent::keyCode(event) as u32;
|
|
||||||
let window_event = WindowEvent::KeyboardInput {
|
|
||||||
device_id: DEVICE_ID,
|
|
||||||
input: KeyboardInput {
|
|
||||||
state: state,
|
|
||||||
scancode: code,
|
|
||||||
virtual_keycode: Some(key),
|
|
||||||
modifiers: event_mods(event),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
Some(window_event)
|
|
||||||
|
|
||||||
} else if key_pressed && !NSEvent::modifierFlags(event).contains(keymask) {
|
|
||||||
let state = ElementState::Released;
|
|
||||||
let code = NSEvent::keyCode(event) as u32;
|
|
||||||
let window_event = WindowEvent::KeyboardInput {
|
|
||||||
device_id: DEVICE_ID,
|
|
||||||
input: KeyboardInput {
|
|
||||||
state: state,
|
|
||||||
scancode: code,
|
|
||||||
virtual_keycode: Some(key),
|
|
||||||
modifiers: event_mods(event),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
Some(window_event)
|
|
||||||
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut events = std::collections::VecDeque::new();
|
|
||||||
if let Some(window_event) = modifier_event(ns_event,
|
|
||||||
NSEventModifierFlags::NSShiftKeyMask,
|
|
||||||
events::VirtualKeyCode::LShift,
|
|
||||||
self.modifiers.shift_pressed)
|
|
||||||
{
|
|
||||||
self.modifiers.shift_pressed = !self.modifiers.shift_pressed;
|
|
||||||
events.push_back(into_event(window_event));
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(window_event) = modifier_event(ns_event,
|
|
||||||
NSEventModifierFlags::NSControlKeyMask,
|
|
||||||
events::VirtualKeyCode::LControl,
|
|
||||||
self.modifiers.ctrl_pressed)
|
|
||||||
{
|
|
||||||
self.modifiers.ctrl_pressed = !self.modifiers.ctrl_pressed;
|
|
||||||
events.push_back(into_event(window_event));
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(window_event) = modifier_event(ns_event,
|
|
||||||
NSEventModifierFlags::NSCommandKeyMask,
|
|
||||||
events::VirtualKeyCode::LWin,
|
|
||||||
self.modifiers.win_pressed)
|
|
||||||
{
|
|
||||||
self.modifiers.win_pressed = !self.modifiers.win_pressed;
|
|
||||||
events.push_back(into_event(window_event));
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(window_event) = modifier_event(ns_event,
|
|
||||||
NSEventModifierFlags::NSAlternateKeyMask,
|
|
||||||
events::VirtualKeyCode::LAlt,
|
|
||||||
self.modifiers.alt_pressed)
|
|
||||||
{
|
|
||||||
self.modifiers.alt_pressed = !self.modifiers.alt_pressed;
|
|
||||||
events.push_back(into_event(window_event));
|
|
||||||
}
|
|
||||||
|
|
||||||
let event = events.pop_front();
|
|
||||||
self.shared.pending_events.lock().unwrap().extend(events.into_iter());
|
|
||||||
event
|
|
||||||
},
|
|
||||||
|
|
||||||
appkit::NSLeftMouseDown => { Some(into_event(WindowEvent::MouseInput { device_id: DEVICE_ID, state: ElementState::Pressed, button: MouseButton::Left, modifiers: event_mods(ns_event) })) },
|
|
||||||
appkit::NSLeftMouseUp => { Some(into_event(WindowEvent::MouseInput { device_id: DEVICE_ID, state: ElementState::Released, button: MouseButton::Left, modifiers: event_mods(ns_event) })) },
|
|
||||||
appkit::NSRightMouseDown => { Some(into_event(WindowEvent::MouseInput { device_id: DEVICE_ID, state: ElementState::Pressed, button: MouseButton::Right, modifiers: event_mods(ns_event) })) },
|
|
||||||
appkit::NSRightMouseUp => { Some(into_event(WindowEvent::MouseInput { device_id: DEVICE_ID, state: ElementState::Released, button: MouseButton::Right, modifiers: event_mods(ns_event) })) },
|
|
||||||
appkit::NSOtherMouseDown => { Some(into_event(WindowEvent::MouseInput { device_id: DEVICE_ID, state: ElementState::Pressed, button: MouseButton::Middle, modifiers: event_mods(ns_event) })) },
|
|
||||||
appkit::NSOtherMouseUp => { Some(into_event(WindowEvent::MouseInput { device_id: DEVICE_ID, state: ElementState::Released, button: MouseButton::Middle, modifiers: event_mods(ns_event) })) },
|
|
||||||
|
|
||||||
appkit::NSMouseEntered => {
|
|
||||||
let window = match maybe_window.or_else(maybe_key_window) {
|
|
||||||
Some(window) => window,
|
|
||||||
None => return None,
|
|
||||||
};
|
|
||||||
|
|
||||||
let window_point = ns_event.locationInWindow();
|
|
||||||
let view_point = if ns_window == cocoa::base::nil {
|
|
||||||
let ns_size = foundation::NSSize::new(0.0, 0.0);
|
|
||||||
let ns_rect = foundation::NSRect::new(window_point, ns_size);
|
|
||||||
let window_rect = window.window.convertRectFromScreen_(ns_rect);
|
|
||||||
window.view.convertPoint_fromView_(window_rect.origin, cocoa::base::nil)
|
|
||||||
} else {
|
|
||||||
window.view.convertPoint_fromView_(window_point, cocoa::base::nil)
|
|
||||||
};
|
|
||||||
let view_rect = NSView::frame(*window.view);
|
|
||||||
let scale_factor = window.hidpi_factor();
|
|
||||||
|
|
||||||
let x = (scale_factor * view_point.x as f32) as f64;
|
|
||||||
let y = (scale_factor * (view_rect.size.height - view_point.y) as f32) as f64;
|
|
||||||
let window_event = WindowEvent::CursorMoved { device_id: DEVICE_ID, position: (x, y), modifiers: event_mods(ns_event) };
|
|
||||||
let event = Event::WindowEvent { window_id: ::WindowId(window.id()), event: window_event };
|
|
||||||
|
|
||||||
self.shared.pending_events.lock().unwrap().push_back(event);
|
|
||||||
Some(into_event(WindowEvent::CursorEntered { device_id: DEVICE_ID }))
|
|
||||||
},
|
|
||||||
appkit::NSMouseExited => { Some(into_event(WindowEvent::CursorLeft { device_id: DEVICE_ID })) },
|
|
||||||
|
|
||||||
appkit::NSMouseMoved |
|
|
||||||
appkit::NSLeftMouseDragged |
|
|
||||||
appkit::NSOtherMouseDragged |
|
|
||||||
appkit::NSRightMouseDragged => {
|
|
||||||
// If the mouse movement was on one of our windows, use it.
|
|
||||||
// Otherwise, if one of our windows is the key window (receiving input), use it.
|
|
||||||
// Otherwise, return `None`.
|
|
||||||
let window = match maybe_window.or_else(maybe_key_window) {
|
|
||||||
Some(window) => window,
|
|
||||||
None => return None,
|
|
||||||
};
|
|
||||||
|
|
||||||
let window_point = ns_event.locationInWindow();
|
|
||||||
let view_point = if ns_window == cocoa::base::nil {
|
|
||||||
let ns_size = foundation::NSSize::new(0.0, 0.0);
|
|
||||||
let ns_rect = foundation::NSRect::new(window_point, ns_size);
|
|
||||||
let window_rect = window.window.convertRectFromScreen_(ns_rect);
|
|
||||||
window.view.convertPoint_fromView_(window_rect.origin, cocoa::base::nil)
|
|
||||||
} else {
|
|
||||||
window.view.convertPoint_fromView_(window_point, cocoa::base::nil)
|
|
||||||
};
|
|
||||||
let view_rect = NSView::frame(*window.view);
|
|
||||||
let scale_factor = window.hidpi_factor();
|
|
||||||
|
|
||||||
let mut events = std::collections::VecDeque::new();
|
|
||||||
|
|
||||||
{
|
|
||||||
let x = (scale_factor * view_point.x as f32) as f64;
|
|
||||||
let y = (scale_factor * (view_rect.size.height - view_point.y) as f32) as f64;
|
|
||||||
let window_event = WindowEvent::CursorMoved { device_id: DEVICE_ID, position: (x, y), modifiers: event_mods(ns_event) };
|
|
||||||
let event = Event::WindowEvent { window_id: ::WindowId(window.id()), event: window_event };
|
|
||||||
events.push_back(event);
|
|
||||||
}
|
|
||||||
|
|
||||||
let delta_x = (scale_factor * ns_event.deltaX() as f32) as f64;
|
|
||||||
if delta_x != 0.0 {
|
|
||||||
let motion_event = DeviceEvent::Motion { axis: 0, value: delta_x };
|
|
||||||
let event = Event::DeviceEvent{ device_id: DEVICE_ID, event: motion_event };
|
|
||||||
events.push_back(event);
|
|
||||||
}
|
|
||||||
|
|
||||||
let delta_y = (scale_factor * ns_event.deltaY() as f32) as f64;
|
|
||||||
if delta_y != 0.0 {
|
|
||||||
let motion_event = DeviceEvent::Motion { axis: 1, value: delta_y };
|
|
||||||
let event = Event::DeviceEvent{ device_id: DEVICE_ID, event: motion_event };
|
|
||||||
events.push_back(event);
|
|
||||||
}
|
|
||||||
|
|
||||||
if delta_x != 0.0 || delta_y != 0.0 {
|
|
||||||
let motion_event = DeviceEvent::MouseMotion { delta: (delta_x, delta_y) };
|
|
||||||
let event = Event::DeviceEvent{ device_id: DEVICE_ID, event: motion_event };
|
|
||||||
events.push_back(event);
|
|
||||||
}
|
|
||||||
|
|
||||||
let event = events.pop_front();
|
|
||||||
self.shared.pending_events.lock().unwrap().extend(events.into_iter());
|
|
||||||
event
|
|
||||||
},
|
|
||||||
|
|
||||||
appkit::NSScrollWheel => {
|
|
||||||
// If none of the windows received the scroll, return `None`.
|
|
||||||
let window = match maybe_window {
|
|
||||||
Some(window) => window,
|
|
||||||
None => return None,
|
|
||||||
};
|
|
||||||
|
|
||||||
use events::MouseScrollDelta::{LineDelta, PixelDelta};
|
|
||||||
let scale_factor = window.hidpi_factor();
|
|
||||||
let delta = if ns_event.hasPreciseScrollingDeltas() == cocoa::base::YES {
|
|
||||||
PixelDelta(scale_factor * ns_event.scrollingDeltaX() as f32,
|
|
||||||
scale_factor * ns_event.scrollingDeltaY() as f32)
|
|
||||||
} else {
|
|
||||||
LineDelta(scale_factor * ns_event.scrollingDeltaX() as f32,
|
|
||||||
scale_factor * ns_event.scrollingDeltaY() as f32)
|
|
||||||
};
|
|
||||||
let phase = match ns_event.phase() {
|
|
||||||
NSEventPhase::NSEventPhaseMayBegin | NSEventPhase::NSEventPhaseBegan => TouchPhase::Started,
|
|
||||||
NSEventPhase::NSEventPhaseEnded => TouchPhase::Ended,
|
|
||||||
_ => TouchPhase::Moved,
|
|
||||||
};
|
|
||||||
self.shared.pending_events.lock().unwrap().push_back(Event::DeviceEvent {
|
|
||||||
device_id: DEVICE_ID,
|
|
||||||
event: DeviceEvent::MouseWheel {
|
|
||||||
delta: if ns_event.hasPreciseScrollingDeltas() == cocoa::base::YES {
|
|
||||||
PixelDelta(ns_event.scrollingDeltaX() as f32,
|
|
||||||
ns_event.scrollingDeltaY() as f32)
|
|
||||||
} else {
|
|
||||||
LineDelta(ns_event.scrollingDeltaX() as f32,
|
|
||||||
ns_event.scrollingDeltaY() as f32)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
});
|
|
||||||
let window_event = WindowEvent::MouseWheel { device_id: DEVICE_ID, delta: delta, phase: phase, modifiers: event_mods(ns_event) };
|
|
||||||
Some(into_event(window_event))
|
|
||||||
},
|
|
||||||
|
|
||||||
appkit::NSEventTypePressure => {
|
|
||||||
let pressure = ns_event.pressure();
|
|
||||||
let stage = ns_event.stage();
|
|
||||||
let window_event = WindowEvent::TouchpadPressure { device_id: DEVICE_ID, pressure: pressure, stage: stage };
|
|
||||||
Some(into_event(window_event))
|
|
||||||
},
|
|
||||||
|
|
||||||
appkit::NSApplicationDefined => match ns_event.subtype() {
|
|
||||||
appkit::NSEventSubtype::NSApplicationActivatedEventType => {
|
|
||||||
Some(Event::Awakened)
|
|
||||||
},
|
|
||||||
_ => None,
|
|
||||||
},
|
|
||||||
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn create_proxy(&self) -> Proxy {
|
|
||||||
Proxy {}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Proxy {
|
|
||||||
pub fn wakeup(&self) -> Result<(), EventsLoopClosed> {
|
|
||||||
// Awaken the event loop by triggering `NSApplicationActivatedEventType`.
|
|
||||||
unsafe {
|
|
||||||
let pool = foundation::NSAutoreleasePool::new(cocoa::base::nil);
|
|
||||||
let event =
|
|
||||||
NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(
|
|
||||||
cocoa::base::nil,
|
|
||||||
appkit::NSApplicationDefined,
|
|
||||||
foundation::NSPoint::new(0.0, 0.0),
|
|
||||||
appkit::NSEventModifierFlags::empty(),
|
|
||||||
0.0,
|
|
||||||
0,
|
|
||||||
cocoa::base::nil,
|
|
||||||
appkit::NSEventSubtype::NSApplicationActivatedEventType,
|
|
||||||
0,
|
|
||||||
0);
|
|
||||||
appkit::NSApp().postEvent_atStart_(event, cocoa::base::NO);
|
|
||||||
foundation::NSAutoreleasePool::drain(pool);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
fn to_virtual_key_code(code: u16) -> Option<events::VirtualKeyCode> {
|
|
||||||
Some(match code {
|
|
||||||
0x00 => events::VirtualKeyCode::A,
|
|
||||||
0x01 => events::VirtualKeyCode::S,
|
|
||||||
0x02 => events::VirtualKeyCode::D,
|
|
||||||
0x03 => events::VirtualKeyCode::F,
|
|
||||||
0x04 => events::VirtualKeyCode::H,
|
|
||||||
0x05 => events::VirtualKeyCode::G,
|
|
||||||
0x06 => events::VirtualKeyCode::Z,
|
|
||||||
0x07 => events::VirtualKeyCode::X,
|
|
||||||
0x08 => events::VirtualKeyCode::C,
|
|
||||||
0x09 => events::VirtualKeyCode::V,
|
|
||||||
//0x0a => World 1,
|
|
||||||
0x0b => events::VirtualKeyCode::B,
|
|
||||||
0x0c => events::VirtualKeyCode::Q,
|
|
||||||
0x0d => events::VirtualKeyCode::W,
|
|
||||||
0x0e => events::VirtualKeyCode::E,
|
|
||||||
0x0f => events::VirtualKeyCode::R,
|
|
||||||
0x10 => events::VirtualKeyCode::Y,
|
|
||||||
0x11 => events::VirtualKeyCode::T,
|
|
||||||
0x12 => events::VirtualKeyCode::Key1,
|
|
||||||
0x13 => events::VirtualKeyCode::Key2,
|
|
||||||
0x14 => events::VirtualKeyCode::Key3,
|
|
||||||
0x15 => events::VirtualKeyCode::Key4,
|
|
||||||
0x16 => events::VirtualKeyCode::Key6,
|
|
||||||
0x17 => events::VirtualKeyCode::Key5,
|
|
||||||
0x18 => events::VirtualKeyCode::Equals,
|
|
||||||
0x19 => events::VirtualKeyCode::Key9,
|
|
||||||
0x1a => events::VirtualKeyCode::Key7,
|
|
||||||
0x1b => events::VirtualKeyCode::Minus,
|
|
||||||
0x1c => events::VirtualKeyCode::Key8,
|
|
||||||
0x1d => events::VirtualKeyCode::Key0,
|
|
||||||
0x1e => events::VirtualKeyCode::RBracket,
|
|
||||||
0x1f => events::VirtualKeyCode::O,
|
|
||||||
0x20 => events::VirtualKeyCode::U,
|
|
||||||
0x21 => events::VirtualKeyCode::LBracket,
|
|
||||||
0x22 => events::VirtualKeyCode::I,
|
|
||||||
0x23 => events::VirtualKeyCode::P,
|
|
||||||
0x24 => events::VirtualKeyCode::Return,
|
|
||||||
0x25 => events::VirtualKeyCode::L,
|
|
||||||
0x26 => events::VirtualKeyCode::J,
|
|
||||||
0x27 => events::VirtualKeyCode::Apostrophe,
|
|
||||||
0x28 => events::VirtualKeyCode::K,
|
|
||||||
0x29 => events::VirtualKeyCode::Semicolon,
|
|
||||||
0x2a => events::VirtualKeyCode::Backslash,
|
|
||||||
0x2b => events::VirtualKeyCode::Comma,
|
|
||||||
0x2c => events::VirtualKeyCode::Slash,
|
|
||||||
0x2d => events::VirtualKeyCode::N,
|
|
||||||
0x2e => events::VirtualKeyCode::M,
|
|
||||||
0x2f => events::VirtualKeyCode::Period,
|
|
||||||
0x30 => events::VirtualKeyCode::Tab,
|
|
||||||
0x31 => events::VirtualKeyCode::Space,
|
|
||||||
0x32 => events::VirtualKeyCode::Grave,
|
|
||||||
0x33 => events::VirtualKeyCode::Back,
|
|
||||||
//0x34 => unkown,
|
|
||||||
0x35 => events::VirtualKeyCode::Escape,
|
|
||||||
0x36 => events::VirtualKeyCode::RWin,
|
|
||||||
0x37 => events::VirtualKeyCode::LWin,
|
|
||||||
0x38 => events::VirtualKeyCode::LShift,
|
|
||||||
//0x39 => Caps lock,
|
|
||||||
//0x3a => Left alt,
|
|
||||||
0x3b => events::VirtualKeyCode::LControl,
|
|
||||||
0x3c => events::VirtualKeyCode::RShift,
|
|
||||||
//0x3d => Right alt,
|
|
||||||
0x3e => events::VirtualKeyCode::RControl,
|
|
||||||
//0x3f => Fn key,
|
|
||||||
//0x40 => F17 Key,
|
|
||||||
0x41 => events::VirtualKeyCode::Decimal,
|
|
||||||
//0x42 -> unkown,
|
|
||||||
0x43 => events::VirtualKeyCode::Multiply,
|
|
||||||
//0x44 => unkown,
|
|
||||||
0x45 => events::VirtualKeyCode::Add,
|
|
||||||
//0x46 => unkown,
|
|
||||||
0x47 => events::VirtualKeyCode::Numlock,
|
|
||||||
//0x48 => KeypadClear,
|
|
||||||
0x49 => events::VirtualKeyCode::VolumeUp,
|
|
||||||
0x4a => events::VirtualKeyCode::VolumeDown,
|
|
||||||
0x4b => events::VirtualKeyCode::Divide,
|
|
||||||
0x4c => events::VirtualKeyCode::NumpadEnter,
|
|
||||||
//0x4d => unkown,
|
|
||||||
0x4e => events::VirtualKeyCode::Subtract,
|
|
||||||
//0x4f => F18 key,
|
|
||||||
//0x50 => F19 Key,
|
|
||||||
0x51 => events::VirtualKeyCode::NumpadEquals,
|
|
||||||
0x52 => events::VirtualKeyCode::Numpad0,
|
|
||||||
0x53 => events::VirtualKeyCode::Numpad1,
|
|
||||||
0x54 => events::VirtualKeyCode::Numpad2,
|
|
||||||
0x55 => events::VirtualKeyCode::Numpad3,
|
|
||||||
0x56 => events::VirtualKeyCode::Numpad4,
|
|
||||||
0x57 => events::VirtualKeyCode::Numpad5,
|
|
||||||
0x58 => events::VirtualKeyCode::Numpad6,
|
|
||||||
0x59 => events::VirtualKeyCode::Numpad7,
|
|
||||||
//0x5a => F20 Key,
|
|
||||||
0x5b => events::VirtualKeyCode::Numpad8,
|
|
||||||
0x5c => events::VirtualKeyCode::Numpad9,
|
|
||||||
//0x5d => unkown,
|
|
||||||
//0x5e => unkown,
|
|
||||||
//0x5f => unkown,
|
|
||||||
0x60 => events::VirtualKeyCode::F5,
|
|
||||||
0x61 => events::VirtualKeyCode::F6,
|
|
||||||
0x62 => events::VirtualKeyCode::F7,
|
|
||||||
0x63 => events::VirtualKeyCode::F3,
|
|
||||||
0x64 => events::VirtualKeyCode::F8,
|
|
||||||
0x65 => events::VirtualKeyCode::F9,
|
|
||||||
//0x66 => unkown,
|
|
||||||
0x67 => events::VirtualKeyCode::F11,
|
|
||||||
//0x68 => unkown,
|
|
||||||
0x69 => events::VirtualKeyCode::F13,
|
|
||||||
//0x6a => F16 Key,
|
|
||||||
0x6b => events::VirtualKeyCode::F14,
|
|
||||||
//0x6c => unkown,
|
|
||||||
0x6d => events::VirtualKeyCode::F10,
|
|
||||||
//0x6e => unkown,
|
|
||||||
0x6f => events::VirtualKeyCode::F12,
|
|
||||||
//0x70 => unkown,
|
|
||||||
0x71 => events::VirtualKeyCode::F15,
|
|
||||||
0x72 => events::VirtualKeyCode::Insert,
|
|
||||||
0x73 => events::VirtualKeyCode::Home,
|
|
||||||
0x74 => events::VirtualKeyCode::PageUp,
|
|
||||||
0x75 => events::VirtualKeyCode::Delete,
|
|
||||||
0x76 => events::VirtualKeyCode::F4,
|
|
||||||
0x77 => events::VirtualKeyCode::End,
|
|
||||||
0x78 => events::VirtualKeyCode::F2,
|
|
||||||
0x79 => events::VirtualKeyCode::PageDown,
|
|
||||||
0x7a => events::VirtualKeyCode::F1,
|
|
||||||
0x7b => events::VirtualKeyCode::Left,
|
|
||||||
0x7c => events::VirtualKeyCode::Right,
|
|
||||||
0x7d => events::VirtualKeyCode::Down,
|
|
||||||
0x7e => events::VirtualKeyCode::Up,
|
|
||||||
//0x7f => unkown,
|
|
||||||
|
|
||||||
0xa => events::VirtualKeyCode::Caret,
|
|
||||||
_ => return None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn event_mods(event: cocoa::base::id) -> ModifiersState {
|
|
||||||
let flags = unsafe {
|
|
||||||
NSEvent::modifierFlags(event)
|
|
||||||
};
|
|
||||||
ModifiersState {
|
|
||||||
shift: flags.contains(NSEventModifierFlags::NSShiftKeyMask),
|
|
||||||
ctrl: flags.contains(NSEventModifierFlags::NSControlKeyMask),
|
|
||||||
alt: flags.contains(NSEventModifierFlags::NSAlternateKeyMask),
|
|
||||||
logo: flags.contains(NSEventModifierFlags::NSCommandKeyMask),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Constant device ID, to be removed when this backend is updated to report real device IDs.
|
|
||||||
const DEVICE_ID: ::DeviceId = ::DeviceId(DeviceId);
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
#![cfg(target_os = "macos")]
|
|
||||||
|
|
||||||
pub use self::events_loop::{EventsLoop, Proxy as EventsLoopProxy};
|
|
||||||
pub use self::monitor::MonitorId;
|
|
||||||
pub use self::window::{Id as WindowId, PlatformSpecificWindowBuilderAttributes, Window2};
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub struct DeviceId;
|
|
||||||
|
|
||||||
use {CreationError};
|
|
||||||
|
|
||||||
pub struct Window {
|
|
||||||
pub window: Arc<Window2>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ::std::ops::Deref for Window {
|
|
||||||
type Target = Window2;
|
|
||||||
#[inline]
|
|
||||||
fn deref(&self) -> &Window2 {
|
|
||||||
&*self.window
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Window {
|
|
||||||
|
|
||||||
pub fn new(events_loop: &EventsLoop,
|
|
||||||
attributes: &::WindowAttributes,
|
|
||||||
pl_attribs: &PlatformSpecificWindowBuilderAttributes) -> Result<Self, CreationError>
|
|
||||||
{
|
|
||||||
let weak_shared = Arc::downgrade(&events_loop.shared);
|
|
||||||
let window = Arc::new(try!(Window2::new(weak_shared, attributes, pl_attribs)));
|
|
||||||
let weak_window = Arc::downgrade(&window);
|
|
||||||
events_loop.shared.windows.lock().unwrap().push(weak_window);
|
|
||||||
Ok(Window { window: window })
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
mod events_loop;
|
|
||||||
mod monitor;
|
|
||||||
mod window;
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
use cocoa::appkit::NSScreen;
|
|
||||||
use cocoa::base::{id, nil};
|
|
||||||
use cocoa::foundation::{NSString, NSUInteger};
|
|
||||||
use core_graphics::display::{CGDirectDisplayID, CGDisplay};
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
use super::EventsLoop;
|
|
||||||
use super::window::IdRef;
|
|
||||||
|
|
||||||
#[derive(Clone, PartialEq)]
|
|
||||||
pub struct MonitorId(CGDirectDisplayID);
|
|
||||||
|
|
||||||
impl EventsLoop {
|
|
||||||
pub fn get_available_monitors(&self) -> VecDeque<MonitorId> {
|
|
||||||
let mut monitors = VecDeque::new();
|
|
||||||
if let Ok(displays) = CGDisplay::active_displays() {
|
|
||||||
for d in displays {
|
|
||||||
monitors.push_back(MonitorId(d));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
monitors
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_primary_monitor(&self) -> MonitorId {
|
|
||||||
let id = MonitorId(CGDisplay::main().id);
|
|
||||||
id
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn make_monitor_from_display(id: CGDirectDisplayID) -> MonitorId {
|
|
||||||
let id = MonitorId(id);
|
|
||||||
id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MonitorId {
|
|
||||||
pub fn get_name(&self) -> Option<String> {
|
|
||||||
let MonitorId(display_id) = *self;
|
|
||||||
let screen_num = CGDisplay::new(display_id).model_number();
|
|
||||||
Some(format!("Monitor #{}", screen_num))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_native_identifier(&self) -> u32 {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_dimensions(&self) -> (u32, u32) {
|
|
||||||
let MonitorId(display_id) = *self;
|
|
||||||
let display = CGDisplay::new(display_id);
|
|
||||||
let dimension = {
|
|
||||||
let height = display.pixels_high();
|
|
||||||
let width = display.pixels_wide();
|
|
||||||
(width as u32, height as u32)
|
|
||||||
};
|
|
||||||
dimension
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn get_position(&self) -> (i32, i32) {
|
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_hidpi_factor(&self) -> f32 {
|
|
||||||
let screen = match self.get_nsscreen() {
|
|
||||||
Some(screen) => screen,
|
|
||||||
None => return 1.0, // default to 1.0 when we can't find the screen
|
|
||||||
};
|
|
||||||
|
|
||||||
unsafe { NSScreen::backingScaleFactor(screen) as f32 }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn get_nsscreen(&self) -> Option<id> {
|
|
||||||
unsafe {
|
|
||||||
let native_id = self.get_native_identifier();
|
|
||||||
let screens = NSScreen::screens(nil);
|
|
||||||
let count: NSUInteger = msg_send![screens, count];
|
|
||||||
let key = IdRef::new(NSString::alloc(nil).init_str("NSScreenNumber"));
|
|
||||||
let mut matching_screen: Option<id> = None;
|
|
||||||
for i in 0..count {
|
|
||||||
let screen = msg_send![screens, objectAtIndex: i as NSUInteger];
|
|
||||||
let device_description = NSScreen::deviceDescription(screen);
|
|
||||||
let value: id = msg_send![device_description, objectForKey:*key];
|
|
||||||
if value != nil {
|
|
||||||
let screen_number: NSUInteger = msg_send![value, unsignedIntegerValue];
|
|
||||||
if screen_number as u32 == native_id {
|
|
||||||
matching_screen = Some(screen);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
matching_screen
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +1,61 @@
|
|||||||
pub use self::platform::*;
|
//! Contains traits with platform-specific methods in them.
|
||||||
|
//!
|
||||||
|
//! Only the modules corresponding to the platform you're compiling to will be available.
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(any(android_platform, docsrs))]
|
||||||
#[path="windows/mod.rs"]
|
pub mod android;
|
||||||
mod platform;
|
#[cfg(any(ios_platform, docsrs))]
|
||||||
#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))]
|
pub mod ios;
|
||||||
#[path="linux/mod.rs"]
|
#[cfg(any(macos_platform, docsrs))]
|
||||||
mod platform;
|
pub mod macos;
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(any(orbital_platform, docsrs))]
|
||||||
#[path="macos/mod.rs"]
|
pub mod orbital;
|
||||||
mod platform;
|
#[cfg(any(x11_platform, wayland_platform, docsrs))]
|
||||||
#[cfg(target_os = "android")]
|
pub mod startup_notify;
|
||||||
#[path="android/mod.rs"]
|
#[cfg(any(wayland_platform, docsrs))]
|
||||||
mod platform;
|
pub mod wayland;
|
||||||
#[cfg(target_os = "ios")]
|
#[cfg(any(web_platform, docsrs))]
|
||||||
#[path="ios/mod.rs"]
|
pub mod web;
|
||||||
mod platform;
|
#[cfg(any(windows_platform, docsrs))]
|
||||||
#[cfg(target_os = "emscripten")]
|
pub mod windows;
|
||||||
#[path="emscripten/mod.rs"]
|
#[cfg(any(x11_platform, docsrs))]
|
||||||
mod platform;
|
pub mod x11;
|
||||||
|
|
||||||
#[cfg(all(not(target_os = "ios"), not(target_os = "windows"), not(target_os = "linux"),
|
#[cfg(any(
|
||||||
not(target_os = "macos"), not(target_os = "android"), not(target_os = "dragonfly"),
|
windows_platform,
|
||||||
not(target_os = "freebsd"), not(target_os = "openbsd"), not(target_os = "emscripten")))]
|
macos_platform,
|
||||||
compile_error!("The platform you're compiling for is not supported by winit");
|
android_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform,
|
||||||
|
docsrs,
|
||||||
|
))]
|
||||||
|
pub mod run_on_demand;
|
||||||
|
|
||||||
|
#[cfg(any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
android_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform,
|
||||||
|
docsrs,
|
||||||
|
))]
|
||||||
|
pub mod pump_events;
|
||||||
|
|
||||||
|
#[cfg(any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform,
|
||||||
|
orbital_platform,
|
||||||
|
docsrs
|
||||||
|
))]
|
||||||
|
pub mod modifier_supplement;
|
||||||
|
|
||||||
|
#[cfg(any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform,
|
||||||
|
docsrs
|
||||||
|
))]
|
||||||
|
pub mod scancode;
|
||||||
|
|||||||
38
src/platform/modifier_supplement.rs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
use crate::event::KeyEvent;
|
||||||
|
use crate::keyboard::Key;
|
||||||
|
|
||||||
|
/// Additional methods for the `KeyEvent` which cannot be implemented on all
|
||||||
|
/// platforms.
|
||||||
|
pub trait KeyEventExtModifierSupplement {
|
||||||
|
/// Identical to `KeyEvent::text` but this is affected by <kbd>Ctrl</kbd>.
|
||||||
|
///
|
||||||
|
/// For example, pressing <kbd>Ctrl</kbd>+<kbd>a</kbd> produces `Some("\x01")`.
|
||||||
|
fn text_with_all_modifiers(&self) -> Option<&str>;
|
||||||
|
|
||||||
|
/// This value ignores all modifiers including,
|
||||||
|
/// but not limited to <kbd>Shift</kbd>, <kbd>Caps Lock</kbd>,
|
||||||
|
/// and <kbd>Ctrl</kbd>. In most cases this means that the
|
||||||
|
/// unicode character in the resulting string is lowercase.
|
||||||
|
///
|
||||||
|
/// This is useful for key-bindings / shortcut key combinations.
|
||||||
|
///
|
||||||
|
/// In case `logical_key` reports `Dead`, this will still report the
|
||||||
|
/// key as `Character` according to the current keyboard layout. This value
|
||||||
|
/// cannot be `Dead`.
|
||||||
|
fn key_without_modifiers(&self) -> Key;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KeyEventExtModifierSupplement for KeyEvent {
|
||||||
|
#[inline]
|
||||||
|
fn text_with_all_modifiers(&self) -> Option<&str> {
|
||||||
|
self.platform_specific
|
||||||
|
.text_with_all_modifiers
|
||||||
|
.as_ref()
|
||||||
|
.map(|s| s.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn key_without_modifiers(&self) -> Key {
|
||||||
|
self.platform_specific.key_without_modifiers.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||