mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 13:05:47 +00:00
Compare commits
1099
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d0b1a42b9 | ||
|
|
dafe5f13b5 | ||
|
|
4e25611f70 | ||
|
|
01f2463603 | ||
|
|
0e7818049a | ||
|
|
397d196102 | ||
|
|
1a37a6a28e | ||
|
|
bb64592f5f | ||
|
|
25f392383e | ||
|
|
afb9e3e823 | ||
|
|
9b0cafa3e9 | ||
|
|
14f23cbb52 | ||
|
|
b4c56096a4 | ||
|
|
a74ff3d67a | ||
|
|
92444946ea | ||
|
|
79889755fd | ||
|
|
ae1f90aaf0 | ||
|
|
e8595638fc | ||
|
|
0a92e0abf2 | ||
|
|
13cb2068f0 | ||
|
|
c44c12488e | ||
|
|
e5b44f95f6 | ||
|
|
cbc113ea3e | ||
|
|
69054b1962 | ||
|
|
276bfd7fa2 | ||
|
|
5f9acf51d4 | ||
|
|
975d6e260a | ||
|
|
606ba5a9db | ||
|
|
06a6fd96db | ||
|
|
9139524015 | ||
|
|
019a3700ff | ||
|
|
782bff4e87 | ||
|
|
6a0671d5bd | ||
|
|
ae6e4a3f80 | ||
|
|
3ecae47966 | ||
|
|
4969f31574 | ||
|
|
49446c7f01 | ||
|
|
1e33eee3f2 | ||
|
|
1f71cbd117 | ||
|
|
55d5e2191c | ||
|
|
11892c7ad1 | ||
|
|
0f1b82aa26 | ||
|
|
8b279001a5 | ||
|
|
61254786e6 | ||
|
|
ece1df0da8 | ||
|
|
49d1311808 | ||
|
|
197d31c2ed | ||
|
|
c0359d1c8c | ||
|
|
a38514afa0 | ||
|
|
a17a40db02 | ||
|
|
c4298e73b4 | ||
|
|
02e19b2fb8 | ||
|
|
f817af9607 | ||
|
|
31a6c3d033 | ||
|
|
003f4ecd3b | ||
|
|
99ab6dd64e | ||
|
|
9b5df0d224 | ||
|
|
aeb0fa57e3 | ||
|
|
ba582dea65 | ||
|
|
8074ec44e8 | ||
|
|
fdab3cea82 | ||
|
|
b26b43fbd0 | ||
|
|
4ba3e442a8 | ||
|
|
57799bef5a | ||
|
|
cee84fd12a | ||
|
|
48daa064c9 | ||
|
|
a42ad82bcb | ||
|
|
06e819f864 | ||
|
|
4c81c98f12 | ||
|
|
3a8d6aaabb | ||
|
|
64b966af49 | ||
|
|
583c6805fd | ||
|
|
e8ee11612f | ||
|
|
7855bec6a1 | ||
|
|
2a423a729a | ||
|
|
01f41e0553 | ||
|
|
3dd0045874 | ||
|
|
6bbcf3ad8b | ||
|
|
f5bba17f53 | ||
|
|
af57286c98 | ||
|
|
446452a97f | ||
|
|
868f54e425 | ||
|
|
c3bc3e6fbd | ||
|
|
1197be90d9 | ||
|
|
6f29018864 | ||
|
|
ac25283f04 | ||
|
|
2ecfe18f76 | ||
|
|
7515bb9898 | ||
|
|
4555fa266d | ||
|
|
60f40913a2 | ||
|
|
facaa18a3c | ||
|
|
8838cf28ed | ||
|
|
65f44e2b80 | ||
|
|
e321f5025d | ||
|
|
a105e4e49c | ||
|
|
2016a363f2 | ||
|
|
1873a9aee7 | ||
|
|
d5628f7b70 | ||
|
|
e10fc86a76 | ||
|
|
8baa16073f | ||
|
|
8178bf5099 | ||
|
|
a97a7d9058 | ||
|
|
3acf5db3f6 | ||
|
|
cffcbaae4a | ||
|
|
3c5e95afa8 | ||
|
|
351d66ed0b | ||
|
|
7d149acb00 | ||
|
|
69c88aa344 | ||
|
+13 |
219548f4b6 | ||
|
|
cf6cf168b0 | ||
|
|
7d21ba2233 | ||
|
|
ae94d9db54 | ||
|
|
45513c90d6 | ||
|
|
f3f3ba1a8a | ||
|
|
97f976ef6c | ||
|
+13 |
83eda433c8 | ||
|
|
e95a4226eb | ||
|
|
26ca374c47 | ||
|
|
64d78aa812 | ||
|
|
522e755b37 | ||
|
|
9c9486400b | ||
|
|
62192203e9 | ||
|
|
d8df18df82 | ||
|
|
953c11ed48 | ||
|
|
c796c7cd48 | ||
|
|
89a0e4d25f | ||
|
|
59a5afa21d | ||
|
|
66529d9026 | ||
|
|
abd89f9954 | ||
|
|
f7ffab1345 | ||
|
|
8886304894 | ||
|
|
0b8d55d434 | ||
|
|
99381a8f3e | ||
|
|
a422698f92 | ||
|
|
dce7e7ece6 | ||
|
|
e3fe63aee6 | ||
|
|
22c85c0cb4 | ||
|
|
a548d381b8 | ||
|
|
9abb21e389 | ||
|
|
4e4cc9d5e3 | ||
|
|
a353b15364 | ||
|
|
86b92c5d0e | ||
|
|
e24e07d0ce | ||
|
|
71da1c90c5 | ||
|
|
cd4a26b5f1 | ||
|
|
66ec776b0b | ||
|
|
2847910f22 | ||
|
|
d21466be6b | ||
|
|
21a78a1eb2 | ||
|
|
5aa245cf39 | ||
|
|
507ddac39d | ||
|
|
ef16de6280 | ||
|
|
d301148881 | ||
|
|
787cec2548 | ||
|
|
0a72690631 | ||
|
|
b539cc1111 | ||
|
|
acf66b2b0e | ||
|
|
892f400145 | ||
|
|
47e4f25346 | ||
|
|
e1ca869d8e | ||
|
|
9eb509b9e1 | ||
|
|
c39a521a28 | ||
|
|
58ab106da8 | ||
|
|
6e49c0c287 | ||
|
|
322040123d | ||
|
|
36a9cbfc13 | ||
|
|
a2486b2afc | ||
|
|
1bd3c64d01 | ||
|
|
7fc61b4c3d | ||
|
|
21e5fdfc63 | ||
|
|
f819988b0d | ||
|
|
39c8a0fe8c | ||
|
|
44331558cc | ||
|
|
d2bab8970d | ||
|
|
eb22557702 | ||
|
|
38d560cef1 | ||
|
|
45a808c80d | ||
|
|
929e049761 | ||
|
|
684f7407de | ||
|
|
00a106e2fa | ||
|
|
91dabdc1e7 | ||
|
|
f635e92498 | ||
|
|
eda1e9b9c6 | ||
|
|
fa9a9446bb | ||
|
|
3e3c4d69e4 | ||
|
|
913806f169 | ||
|
|
7b018e6c42 | ||
|
|
e45d6f7192 | ||
|
|
b3ff93e80f | ||
|
|
c035351b4f | ||
|
|
10cdf97480 | ||
|
|
f614483d01 | ||
|
|
f5eb5e7b81 | ||
|
|
bf99dbbe73 | ||
|
|
46fac69438 | ||
|
|
82f04fb22e | ||
|
|
9796525449 | ||
|
|
9838c83fc2 | ||
|
|
799be037e5 | ||
|
|
d99d728ba5 | ||
|
|
4b17bc9a23 | ||
|
|
4ac78621cc | ||
|
|
079261759e | ||
|
|
3fe03c0a88 | ||
|
|
6211faf6bc | ||
|
|
81e645a917 | ||
|
|
06b09b37bd | ||
|
|
0c3444afbc | ||
|
|
0988cdc43a | ||
|
|
06bd0de4d7 | ||
|
|
3a408058ba | ||
|
|
a074ba994b | ||
|
|
d310e59fce | ||
|
|
0d0465d19e | ||
|
|
83ec5708ed | ||
|
|
4163b31b02 | ||
|
|
02888834d4 | ||
|
|
ec537421ac | ||
|
|
5e23c668f3 | ||
|
|
a12ac8134a | ||
|
|
4562d61139 | ||
|
|
cc5ae4ff0b | ||
|
|
f0c52c273b | ||
|
|
975c76e3e8 | ||
|
|
a394dfd31b | ||
|
|
a2e555f4cc | ||
|
|
31d12a9f6c | ||
|
|
3820445561 | ||
|
|
75d7edd2c3 | ||
|
|
da8fe068d9 | ||
|
|
8f9ce19638 | ||
|
|
b74edb7e8d | ||
|
|
2503d69293 | ||
|
|
5e38e79c96 | ||
|
|
5e5ffee93e | ||
|
|
a7662ae13a | ||
|
|
a249e896f7 | ||
|
|
ca3743520e | ||
|
|
98822fdd27 | ||
|
|
8d0225932c | ||
|
|
40bca96db5 | ||
|
|
a2a9586b54 | ||
|
|
2fe6ba36c4 | ||
|
|
e4c84e6e24 | ||
|
|
10ef8c4bd6 | ||
|
|
8e01cfb2ef | ||
|
|
b25c4ea26b | ||
|
|
cebad5692d | ||
|
|
6b2c8ace09 | ||
|
|
4d1b8421fb | ||
|
|
ced4ac5db8 | ||
|
|
e190f57b53 | ||
|
|
22f02fb6bf | ||
|
|
52c67df4c7 | ||
|
|
de1a734fb5 | ||
|
|
be9939d82c | ||
|
|
e4c375ad0d | ||
|
|
0cafa83ea7 | ||
|
|
435beb7f19 | ||
|
|
78fcb60fd5 | ||
|
|
4995b3553b | ||
|
|
3c2878cc52 | ||
|
|
715032062d | ||
|
|
dde08414fc | ||
|
|
ec24b3a472 | ||
|
|
6455b1dade | ||
|
|
542ad3e060 | ||
|
|
910fb47692 | ||
|
|
3dd14dd625 | ||
|
|
d1b0ac4df1 | ||
|
|
0e225d0c6e | ||
|
|
d9cd0d2cc8 | ||
|
|
eadebc46d5 | ||
|
|
96d7c66535 | ||
|
|
90690d1c5c | ||
|
|
abbcb8e3ad | ||
|
|
fe60b3c279 | ||
|
|
c7455b74ff | ||
|
|
c875ceda4d | ||
|
|
666abd134f | ||
|
|
c115916962 | ||
|
|
0579e688ba | ||
|
|
bc50de3b55 | ||
|
|
6489232598 | ||
|
|
c23c436502 | ||
|
|
fad52ec125 | ||
|
|
d22e458d64 | ||
|
|
1b7cb4179d | ||
|
|
c1c22dfd37 | ||
|
|
0043cefab5 | ||
|
|
41f68ef1a1 | ||
|
|
9743ac3abc | ||
|
|
ca6cfcd193 | ||
|
|
d41424170a | ||
|
|
f4678935c4 | ||
|
|
416eb41d8d | ||
|
|
6e0d456dd7 | ||
|
|
8ac555664a | ||
|
|
4bf4e53ecf | ||
|
|
3d50e6b1ae | ||
|
|
846b20f78a | ||
|
|
a229d196bb | ||
|
|
61bfc04704 | ||
|
|
9b90386e73 | ||
|
|
ddc4c18faf | ||
|
|
fb8361b197 | ||
|
|
a5fd64f9f2 | ||
|
|
e0a7ce4f88 | ||
|
|
b213ae77b4 | ||
|
|
6e5932cb68 | ||
|
|
38e3fa2a33 | ||
|
|
8e1a676f19 | ||
|
|
7c946db440 | ||
|
|
eaf26c8a20 | ||
|
|
0a96767657 | ||
|
|
32054e156e | ||
|
|
fd6d6b7c46 | ||
|
|
c101a451e3 | ||
|
|
a76ba69217 | ||
|
|
d06caf9838 | ||
|
|
134fa167fe | ||
|
|
da42a5d7a7 | ||
|
|
b6c1d3c09c | ||
|
|
a58b0ac3e0 | ||
|
|
e1700ba982 | ||
|
|
736ac7db74 | ||
|
|
6e2966be43 | ||
|
|
679948e792 | ||
|
|
e0fc8362b8 | ||
|
|
9d8ff9615f | ||
|
|
1304809240 | ||
|
|
343a516e1a | ||
|
|
7c08cb58ae | ||
|
|
7e81668de2 | ||
|
|
d231564f8e | ||
|
|
37e89c5b4d | ||
|
|
e070bd72e0 | ||
|
|
9310d19857 | ||
|
|
4454a6d39a | ||
|
|
453f6f5180 | ||
|
|
6d0484941e | ||
|
|
cf47910881 | ||
|
|
4f0f0cf5b1 | ||
|
|
a78d5cb600 | ||
|
|
206c8a8846 | ||
|
|
bf17ce1151 | ||
|
|
ef38c975b9 | ||
|
|
61953c4f7b | ||
|
|
1f13285ab8 | ||
|
|
1bc23ac169 | ||
|
|
50f50b16e0 | ||
|
|
adc86fc7df | ||
|
|
f3fd3a2307 | ||
|
|
1e877fa602 | ||
|
|
906009a33a | ||
|
|
08559a02f8 | ||
|
|
1d93626453 | ||
|
|
9d0989374b | ||
|
|
3278afaa1a | ||
|
|
bf221ffbbd | ||
|
|
c636eea355 | ||
|
|
ffaa906cd1 | ||
|
|
d61af961c1 | ||
|
|
bc01b77752 | ||
|
|
a1b01a04a8 | ||
|
|
b44235c495 | ||
|
|
b80d5db176 | ||
|
|
d3c0d258b7 | ||
|
|
9dcdbf245a | ||
|
|
369e218afb | ||
|
|
119d24bf6b | ||
|
|
2a905510d5 | ||
|
|
da29919b5a | ||
|
|
05608ac4d4 | ||
|
|
135b84a501 | ||
|
|
e7cbba37d1 | ||
|
|
d9bb5e15b0 | ||
|
|
46cdc32cf1 | ||
|
|
387572e733 | ||
|
|
9f46c7a50b | ||
|
|
0607bb0b3a | ||
|
|
b89d87cbde | ||
|
|
06e06b9673 | ||
|
|
b896e7a3b9 | ||
|
|
c91daa9147 | ||
|
|
31ea194f3d | ||
|
|
472bb28c88 | ||
|
|
eaa4a7a047 | ||
|
|
4fa467c800 | ||
|
|
beb96e6f0c | ||
|
|
26cb9e2f03 | ||
|
|
6dc74523c3 | ||
|
|
3858a69867 | ||
|
|
49a5f4aa94 | ||
|
|
4cc9f2a3f3 | ||
|
|
b0d7fc01d8 | ||
|
|
9cc40246a3 | ||
|
|
423cf11919 | ||
|
|
33f7213599 | ||
|
|
6f1fb462ed | ||
|
|
336b8851f7 | ||
|
|
5da3cf673c | ||
|
|
9e54e094fb | ||
|
|
eb9ca4ab6b | ||
|
|
e7b6876877 | ||
|
|
c535f6ef6e | ||
|
|
db2e1d7da2 | ||
|
|
f5e204eb1d | ||
|
|
705a5e7b2a | ||
|
|
e60eae3646 | ||
|
|
b04900b1b2 | ||
|
|
6357543b44 | ||
|
|
67fb338e5d | ||
|
|
ba140c4ab5 | ||
|
|
f5fdbc7941 | ||
|
|
90ae85da4d | ||
|
|
f3600fa618 | ||
|
|
2d8befe1cb | ||
|
|
f982ffcaf7 | ||
|
|
255c64551e | ||
|
|
746f28c1b2 | ||
|
|
2b481ba250 | ||
|
|
49622623de | ||
|
|
69f99ade42 | ||
|
|
c236e9711f | ||
|
|
4c2efb6688 | ||
|
|
7eb2d1cf1a | ||
|
|
b4ff83cf9f | ||
|
|
7b20b70c6b | ||
|
|
86207f9d0e | ||
|
|
eda5ece382 | ||
|
|
3404bbc128 | ||
|
|
b5a431aa3c | ||
|
|
49249f6541 | ||
|
|
5614621d6e | ||
|
|
0816562065 | ||
|
|
39618e6862 | ||
|
|
c66e4ba4b3 | ||
|
|
e4b033861f | ||
|
|
85a07a556c | ||
|
|
8dfc48d58b | ||
|
|
82ebdaa0b5 | ||
|
|
ec016f85bc | ||
|
|
c2c812deaa | ||
|
|
eec3428f78 | ||
|
|
4a5e4b76e3 | ||
|
|
43f952b2fb | ||
|
|
0d86bec34d | ||
|
|
47a6f29ad7 | ||
|
|
84834f180e | ||
|
|
bfd445618a | ||
|
|
eddfd37b93 | ||
|
|
d7341863bf | ||
|
|
2f51be7b5a | ||
|
|
fbc0014d14 | ||
|
|
46df6171fc | ||
|
|
761b62914f | ||
|
|
91b0299f77 | ||
|
|
6d08e59d10 | ||
|
|
83cc0fe585 | ||
|
|
c711c627b8 | ||
|
|
0b34690721 | ||
|
|
b640734db5 | ||
|
|
f8feb63dde | ||
|
|
25a5d3fe5d | ||
|
|
41dd93fd25 | ||
|
|
adf3c9405d | ||
|
|
abf4f57b47 | ||
|
|
c1e36975d4 | ||
|
|
0bfa0915d4 | ||
|
|
4da87672a2 | ||
|
|
3ba0d287e9 | ||
|
|
b4a86cb5bb | ||
|
|
0fa1f2f868 | ||
|
|
71610ddfdb | ||
|
|
5c9e683769 | ||
|
|
32a5e83b88 | ||
|
|
88904c08f7 | ||
|
|
9928bfe780 | ||
|
|
a491dec5c4 | ||
|
|
17ef33ee31 | ||
|
|
06caaee343 | ||
|
|
1c161a76dd | ||
|
|
aa05ab03fa | ||
|
|
43ea3f3181 | ||
|
|
3966b27948 | ||
|
|
7e24327621 | ||
|
|
d025aa3c6d | ||
|
|
325f6893c5 | ||
|
|
466419407d | ||
|
|
cbd4ce6636 | ||
|
|
d4130181e7 | ||
|
|
16a9d0af2a | ||
|
|
e51698e01f | ||
|
|
519091dd86 | ||
|
|
972088f1b3 | ||
|
|
542d31daf0 | ||
|
|
8f9a849c48 | ||
|
|
e8bfe6e520 | ||
|
|
15618f357b | ||
|
|
b74010435a | ||
|
|
0a58a7faee | ||
|
|
0d21e2f913 | ||
|
|
ebb82d2dc9 | ||
|
|
557e346810 | ||
|
|
08b2cf0894 | ||
|
|
4e90e03536 | ||
|
|
11d997dc65 | ||
|
|
454193da9b | ||
|
|
cdd5c99bc7 | ||
|
|
fb1da1c39a | ||
|
|
b29ece82c8 | ||
|
|
1330fe4d6c | ||
|
|
0e1f6f15a1 | ||
|
|
4df0e012fd | ||
|
|
48054a86ab | ||
|
|
38d658abf5 | ||
|
|
5547391cfc | ||
|
|
6782e5a717 | ||
|
|
e1a80c1751 | ||
|
|
05933a5ee3 | ||
|
|
1f29cd92a5 | ||
|
|
4f30356c9b | ||
|
|
baebf50197 | ||
|
|
01674b7c6f | ||
|
|
728bfa2043 | ||
|
|
c4de482b6a | ||
|
|
55697535a1 | ||
|
|
65733c23a1 | ||
|
|
fd51b86060 | ||
|
|
d6e4ab1824 | ||
|
|
566c7d703a | ||
|
|
d7eb3256a5 | ||
|
|
c96f2d1070 | ||
|
|
cc8b743ecb | ||
|
|
45422b739b | ||
|
|
f58bf9b23c | ||
|
|
f0e8ef1274 | ||
|
|
bb6d6fee97 | ||
|
|
d59734e375 | ||
|
|
14db12290e | ||
|
|
1e476539df | ||
|
|
3c8e370744 | ||
|
|
3fcd01f536 | ||
|
|
0e2ee35b49 | ||
|
|
27920711f0 | ||
|
|
d4c16b5b59 | ||
|
|
e392364e30 | ||
|
|
3cdb77fd65 | ||
|
|
a91be68992 | ||
|
|
e16f351540 | ||
|
|
efdab60b22 | ||
|
|
8dc24f244c | ||
|
|
b565c4a6e5 | ||
|
|
a999fbdb38 | ||
|
|
52eee568f5 | ||
|
|
05cebd4a4f | ||
|
|
8cfd54a739 | ||
|
|
8565acf12b | ||
|
|
941a6c3ef9 | ||
|
|
fe84c050ad | ||
|
|
f13c885fec | ||
|
|
8ee1cbe3eb | ||
|
|
6c5d6cda73 | ||
|
|
2725ee4512 | ||
|
|
7cc1c93775 | ||
|
|
38c9b733b5 | ||
|
|
27e5f86793 | ||
|
|
a6331e44ae | ||
|
|
f53b844add | ||
|
|
fb34098006 | ||
|
|
c729f4c8e7 | ||
|
|
9f343278c3 | ||
|
|
6beeb29486 | ||
|
|
ade2e982b6 | ||
|
|
8a61a1898b | ||
|
|
dfa3b12f48 | ||
|
|
93382ff241 | ||
|
|
24b74d8346 | ||
|
|
9ed25d8ae5 | ||
|
|
b4b31d5a08 | ||
|
|
f394906726 | ||
|
|
b50dfa76d1 | ||
|
|
3f81ddff9b | ||
|
|
d1dec8d7a4 | ||
|
|
e60097e5cb | ||
|
|
7c7bf2dcbe | ||
|
|
75593cfd29 | ||
|
|
00d0f8cd2b | ||
|
|
faf4b4e8b5 | ||
|
|
5a61d37c5d | ||
|
|
25079ab819 | ||
|
|
736b7bed5e | ||
|
|
a3f4c911e5 | ||
|
|
caa7682c6f | ||
|
|
e217cbe66d | ||
|
|
4914b2cc69 | ||
|
|
051b9a320e | ||
|
|
6ecd6fa1d0 | ||
|
|
0f4e83eefd | ||
|
|
d62525f5af | ||
|
|
71057fefe1 | ||
|
|
f4d2c37fbd | ||
|
|
ffd9f92d7b | ||
|
|
213d110766 | ||
|
|
1a8c91b49b | ||
|
|
9644a4cc7f | ||
|
|
24c250fdb4 | ||
|
|
d4636afa97 | ||
|
|
32930e704e | ||
|
|
a8b18947a1 | ||
|
|
7c422577b6 | ||
|
|
1cc1ee994d | ||
|
|
d8d375cb9a | ||
|
|
49934ce933 | ||
|
|
221644e8be | ||
|
|
5179b54745 | ||
|
|
448feb30bc | ||
|
|
9d891d4db1 | ||
|
|
240f1194c0 | ||
|
|
7b74eebce2 | ||
|
|
7592684b6f | ||
|
|
7b78e1629b | ||
|
|
30741302fb | ||
|
|
645f7d0bf1 | ||
|
|
124f162ee8 | ||
|
|
3c577fd9dd | ||
|
|
659ff4817f | ||
|
|
626adb62af | ||
|
|
71cb100a40 | ||
|
|
68002f3fa7 | ||
|
|
dae7592788 | ||
|
|
e10f5b4430 | ||
|
|
3e32b75a63 | ||
|
|
435f7a1b03 | ||
|
|
1fd8c50225 | ||
|
|
e797bc5f01 | ||
|
|
0cc3fe6bca | ||
|
|
ab8542e4e5 | ||
|
|
c2bcf20172 | ||
|
|
2341659cea | ||
|
|
b2eaf380dc | ||
|
|
197fc3f163 | ||
|
|
9530e7b394 | ||
|
|
0e0f133496 | ||
|
|
d98c211168 | ||
|
|
614b4d4de4 | ||
|
|
43a19a831a | ||
|
|
0d308af024 | ||
|
|
128f73da8f | ||
|
|
e22a55e949 | ||
|
|
67cb005e6c | ||
|
|
73f76f6799 | ||
|
|
961a060461 | ||
|
|
dadbbf841a | ||
|
|
1ce8280371 | ||
|
|
78bdc0e3b5 | ||
|
|
ce5f2f5513 | ||
|
|
0f2792c7ac | ||
|
|
7185b775d4 | ||
|
|
cda6e89c12 | ||
|
|
5f80898c27 | ||
|
|
85560d6471 | ||
|
|
be6c875277 | ||
|
|
91beced154 | ||
|
|
ebc3da08b4 | ||
|
|
41eb780495 | ||
|
|
65fc2a38a3 | ||
|
|
359d1535ac | ||
|
|
4c3a9f027c | ||
|
|
5a6cc3c76e | ||
|
|
89bd7deceb | ||
|
|
169f2c3e34 | ||
|
|
e6a797695a | ||
|
|
f1a2ecc857 | ||
|
|
36916f6bde | ||
|
|
1b96d13a51 | ||
|
|
cb1d70bb14 | ||
|
|
37af590ca2 | ||
|
|
02f356f8c0 | ||
|
|
5448177814 | ||
|
|
ed6ce0ca41 | ||
|
|
9b440686c5 | ||
|
|
e7b7e9dc43 | ||
|
|
1120040aee | ||
|
|
3506a272da | ||
|
|
b752748b7d | ||
|
|
8990e7d7a4 | ||
|
|
c92a423ba1 | ||
|
|
3b82b3e1f8 | ||
|
|
e985ce1975 | ||
|
|
8496ce3e51 | ||
|
|
47188f40ed | ||
|
|
e186c9bc4c | ||
|
|
7705f3c222 | ||
|
|
5675b4897f | ||
|
|
1c87d92ef7 | ||
|
|
031e64dfe1 | ||
|
|
f590dd9763 | ||
|
|
af7dc40538 | ||
|
|
a28aae6e4a | ||
|
|
c024470cc7 | ||
|
|
16ae5ab84a | ||
|
|
144947305a | ||
|
|
563bc6cad7 | ||
|
|
59cde93821 | ||
|
|
c104e1c276 | ||
|
|
b5da0d0db6 | ||
|
|
5defc3e38b | ||
|
|
6a9f52f932 | ||
|
|
06a8d75769 | ||
|
|
ec12ddd0a8 | ||
|
|
570902d5f3 | ||
|
|
6120069975 | ||
|
|
3e337c9bda | ||
|
|
2869e76406 | ||
|
|
61fdb80823 | ||
|
|
fd180a108a | ||
|
|
4de74c740c | ||
|
|
b7c32c92d2 | ||
|
|
8610ca0928 | ||
|
|
a6b1ad37d0 | ||
|
|
97b13f7488 | ||
|
|
5d5b45a012 | ||
|
|
5ebafaabda | ||
|
|
56627a8aaf | ||
|
|
f59ced4e98 | ||
|
|
296e848718 | ||
|
|
8c63413019 | ||
|
|
2861c6d284 | ||
|
|
69c2d8e566 | ||
|
|
414fddf7b8 | ||
|
|
b5ca6145a6 | ||
|
|
5a5948b071 | ||
|
|
e58b5088b3 | ||
|
|
ecbce4c8d3 | ||
|
|
96bf0a3bf3 | ||
|
|
da7522a3ee | ||
|
|
5605e777ca | ||
|
|
a10e2e1fe8 | ||
|
|
4fb623fa33 | ||
|
|
3b4956d088 | ||
|
|
18deaafc34 | ||
|
|
0c4eede6d2 | ||
|
|
54681f2647 | ||
|
|
5271edd972 | ||
|
|
e4bb9856ef | ||
|
|
e462bbb24a | ||
|
|
d8f3090d9b | ||
|
|
d1af8b0114 | ||
|
|
dae64bbe69 | ||
|
|
8b127bed84 | ||
|
|
67187b1340 | ||
|
|
02cac57438 | ||
|
|
277dcd174c | ||
|
|
3c23ae7310 | ||
|
|
8cb13d40b5 | ||
|
|
c950d31960 | ||
|
|
ae570cd5b7 | ||
|
|
0fd1dc4fce | ||
|
|
f0854e8518 | ||
|
|
ceffd3f759 | ||
|
|
dc1816612c | ||
|
|
1d04a7e0e3 | ||
|
|
1e523c4e93 | ||
|
|
d83f766cf3 | ||
|
|
bb5e1ae63d | ||
|
|
f27a4f6c95 | ||
|
|
d7ff92106a | ||
|
|
34a17acaba | ||
|
|
110aec0b6f | ||
|
|
06502bb49b | ||
|
|
c20a166134 | ||
|
|
162fa8e2de | ||
|
|
ae5614d212 | ||
|
|
b72d8a8bab | ||
|
|
d4cf890d8a | ||
|
|
82e494269d | ||
|
|
c982d65675 | ||
|
|
f4e606fb15 | ||
|
|
9dbdb5e771 | ||
|
|
fa12478fdd | ||
|
|
c3b0d8ef03 | ||
|
|
cbb9a168e6 | ||
|
|
73e2fc58a0 | ||
|
|
500f4c69eb | ||
|
|
911ad29004 | ||
|
|
aa843b5a31 | ||
|
|
f249acc50f | ||
|
|
8cdedbe18a | ||
|
|
0f39d71f95 | ||
|
|
1dc49b527b | ||
|
|
9422608960 | ||
|
|
cc3fec0768 | ||
|
|
de37ddcfb5 | ||
|
|
4c90196890 | ||
|
|
5270574e5a | ||
|
|
30f6ca6ffc | ||
|
|
a8af973726 | ||
|
|
ed1f8dd2b6 | ||
|
|
e8aaae1343 | ||
|
|
ecff3240a6 | ||
|
|
ddd4a0c24d | ||
|
|
019949847a | ||
|
|
4dcbf269d2 | ||
|
|
036317f371 | ||
|
|
ce0da01163 | ||
|
|
75ae619e21 | ||
|
|
3efa5acfa6 | ||
|
|
9369dc3031 | ||
|
|
5d84d3fef7 | ||
|
|
51baf75af1 | ||
|
|
20f2c98d18 | ||
|
|
e3ceae412b | ||
|
|
7e6affed12 | ||
|
|
40fc5463f3 | ||
|
|
039948f4d2 | ||
|
|
bbb95e8a60 | ||
|
|
7763d00b78 | ||
|
|
3452730725 | ||
|
|
e50f61f5d9 | ||
|
|
a7a4308e3c | ||
|
|
e811576e79 | ||
|
|
960abec0ed | ||
|
|
855ab88d6c | ||
|
|
f7ee6e78f0 | ||
|
|
293c58aeba | ||
|
|
95b8a4c3c4 | ||
|
|
b7fd52de79 | ||
|
|
53ce764548 | ||
|
|
157e74907a | ||
|
|
015ac26e07 | ||
|
|
1fe7faaa8d | ||
|
|
2e7f99897d | ||
|
|
d7fa65ad20 | ||
|
|
ae614ce476 | ||
|
|
7d6e1cce2f | ||
|
|
bbf46cad9d | ||
|
|
68c7b4b3c8 | ||
|
|
5d38a6c8c5 | ||
|
|
99a0c44f98 | ||
|
|
1812ba20e2 | ||
|
|
771d3c399c | ||
|
|
af74a4449e | ||
|
|
8c171dd2c7 | ||
|
|
3292ed6f1a | ||
|
|
96bbe0c4cc | ||
|
|
039e14de5a | ||
|
|
a419c8097f | ||
|
|
3fac2e8945 | ||
|
|
c2d6d272a3 | ||
|
|
846630e300 | ||
|
|
cc1f3d256b | ||
|
|
243a760a12 | ||
|
|
4f744fc8fe | ||
|
|
54adf9ad68 | ||
|
|
8b66adb8a5 | ||
|
|
9f0c1fc797 | ||
|
|
4a46e16702 | ||
|
|
608d011b44 | ||
|
|
0d52ba66cd | ||
|
|
431fac1fca | ||
|
|
35006d6031 | ||
|
|
7ae66337ef | ||
|
|
b75e0f9800 | ||
|
|
ee3fd4d6b8 | ||
|
|
0352f4b832 | ||
|
|
7fbfeb2edd | ||
|
|
8db69f073b | ||
|
|
226fa1c1ea | ||
|
|
6f41ae58db | ||
|
|
ae9186392f | ||
|
|
4279ffd887 | ||
|
|
ac058ea112 | ||
|
|
5d42e5e87a | ||
|
|
96ac6967e6 | ||
|
|
0c301f3cec | ||
|
|
d7cadd05d6 | ||
|
|
2f8464b7f5 | ||
|
|
96314749da | ||
|
|
33f06d744f | ||
|
|
d6ca48d80a | ||
|
|
c8b628393b | ||
|
|
e9d4eb1e1b | ||
|
|
89f78a9969 | ||
|
|
94f9935ad4 | ||
|
|
66c7db5a47 | ||
|
|
b959de3d26 | ||
|
|
b802485e31 | ||
|
|
ee20fd60c4 | ||
|
|
52174e2ab0 | ||
|
|
216f3c1d62 | ||
|
|
7e6954304a | ||
|
|
8718ae0aa8 | ||
|
|
615311ecd6 | ||
|
|
3a4ef4f6d6 | ||
|
|
403cfa77ae | ||
|
|
c7998a82d5 | ||
|
|
86bc9f4a64 | ||
|
|
2f4c4624ae | ||
|
|
b83e5f87cf | ||
|
|
b49e2753df | ||
|
|
3c09e1d736 | ||
|
|
0f07dafb36 | ||
|
|
38fdca0b97 | ||
|
|
e8efe2d290 | ||
|
|
a1ae55125a | ||
|
|
706692c1fe | ||
|
|
582f031243 | ||
|
|
9c78373c73 | ||
|
|
e9f3416438 | ||
|
|
ea44a77f8a | ||
|
|
63d7051c4b | ||
|
|
4803c9d221 | ||
|
|
6388edb706 | ||
|
|
0774ade030 | ||
|
|
e5ee766961 | ||
|
|
274f3d0c7a | ||
|
|
21be683768 | ||
|
|
695923aed7 | ||
|
|
649153257d | ||
|
|
cbcd3f8023 | ||
|
|
41c5ce8d4e | ||
|
|
78ce23258b | ||
|
|
3e864fda17 | ||
|
|
0cdb945d9c | ||
|
|
15a113f783 | ||
|
|
67f00d2123 | ||
|
|
d68dcd14e1 | ||
|
|
32994210ab | ||
|
|
cfec8ab88a | ||
|
|
87c44c3218 | ||
|
|
35446df6d5 | ||
|
|
921b38bfb4 | ||
|
|
82bb924d0b | ||
|
|
08a6769bc0 | ||
|
|
dce87061d1 | ||
|
|
f4302e4fa9 | ||
|
|
0436953451 | ||
|
|
7165907ba9 | ||
|
|
e938127c7a | ||
|
|
b5c9d6bc50 | ||
|
|
f7af5091cf | ||
|
|
7ac1786a2e | ||
|
|
19a919e096 | ||
|
|
10f5506829 | ||
|
|
d3c6d54a58 | ||
|
|
6980428f82 | ||
|
|
1a3b16f614 | ||
|
|
e0b9f462ce | ||
|
|
f6f7470385 | ||
|
|
214c708b49 | ||
|
|
d567185fc0 | ||
|
|
24188bda10 | ||
|
|
1a870c5c07 | ||
|
|
fa964802d9 | ||
|
|
793180ce12 | ||
|
|
79e7be470c | ||
|
|
921f156128 | ||
|
|
c771fc67ac | ||
|
|
7f2d2ffa4a | ||
|
|
2d9e1c6d95 | ||
|
|
66dafa6021 | ||
|
|
2df3d054e8 | ||
|
|
c9cfa2126e | ||
|
|
2220578cd1 | ||
|
|
5b18807f0e | ||
|
|
d984a4ba31 | ||
|
|
7dc00d9b23 | ||
|
|
59123f1c89 | ||
|
|
aa1df93a22 | ||
|
|
c99617427a | ||
|
|
54a4677f11 | ||
|
|
edeb388233 | ||
|
|
034d484271 | ||
|
|
ebf5da9840 | ||
|
|
f9c9084584 | ||
|
|
d160f464b6 | ||
|
|
c013252a59 | ||
|
|
7fa71dc5c5 | ||
|
|
a19dfb88a0 | ||
|
|
738cd059a2 | ||
|
|
aaa6a0452f | ||
|
|
0cb18839a2 | ||
|
|
991e1af331 | ||
|
|
c8a278d009 | ||
|
|
39f5478ea9 | ||
|
|
d0b1686a84 | ||
|
|
95bd8ec2fe | ||
|
|
85b5151e1a | ||
|
|
a0be13adba | ||
|
|
a0fb8fd73d | ||
|
|
d3e70b99c0 | ||
|
|
0a0ec6acf5 | ||
|
|
50df100569 | ||
|
|
02489e617c | ||
|
|
2f22050add | ||
|
|
0081c8f7c7 | ||
|
|
12c1036f17 | ||
|
|
7ef7129f7a | ||
|
|
5cb6346017 | ||
|
|
5e599e5445 | ||
|
|
146c07a25e | ||
|
|
44265c3fcd | ||
|
|
90c7574e28 | ||
|
|
e4fbb6f956 | ||
|
|
ad2f9f8aa6 | ||
|
|
9c470950ea | ||
|
|
0ddb0be65a | ||
|
|
cbd3bc95a1 | ||
|
|
f43795714d | ||
|
|
586c9c28b4 | ||
|
|
f79dc2da43 | ||
|
|
3bb485a437 | ||
|
|
8dd0043072 | ||
|
|
4c43fe3502 | ||
|
|
92f7709a76 | ||
|
|
04f40282d2 | ||
|
|
4b1804847f | ||
|
|
4e791d486f | ||
|
|
9a8732fba4 | ||
|
|
adddbb4e50 | ||
|
|
af4df4177d | ||
|
|
fa54c5c5a0 | ||
|
|
768e6c8511 | ||
|
|
eb1b9e0d78 | ||
|
|
2f80d97e17 | ||
|
|
d9246c333e | ||
|
|
164a6e009b | ||
|
|
69aba7d0b7 | ||
|
|
60f393f878 | ||
|
|
a14451b5e9 | ||
|
|
946bbc3023 | ||
|
|
474e75f649 | ||
|
|
3c65fd8d9e | ||
|
|
066011c5fb | ||
|
|
e14fc55030 | ||
|
|
d7b61258ce | ||
|
|
ffd544c42a | ||
|
|
cb99269a6d | ||
|
|
74b9ea9f89 | ||
|
|
aa863662b8 | ||
|
|
118e78ceb2 | ||
|
|
b14cdf50e6 | ||
|
|
39dd9b03f9 | ||
|
|
5d55258383 | ||
|
|
3256809066 | ||
|
|
dfbb1e5b98 | ||
|
|
e9915c44f9 | ||
|
|
a90ba862df | ||
|
|
b6ab624862 | ||
|
|
f66138505f | ||
|
|
dab91bdfac | ||
|
|
101d155855 | ||
|
|
10d7b4905b | ||
|
|
3afad00a84 | ||
|
|
ab8b06bacd | ||
|
|
9cfb96e358 | ||
|
|
2fb79735c3 | ||
|
|
a4e59986a8 | ||
|
|
93b4ec47d1 | ||
|
|
a4b1d12f36 | ||
|
|
217485e021 | ||
|
|
1f41d6d282 | ||
|
|
6876a8d649 | ||
|
|
02c159c5fd | ||
|
|
a1e204c117 | ||
|
|
ece9f7cd46 | ||
|
|
16dab991e0 | ||
|
|
c17975943a | ||
|
|
9d9ee98eaf | ||
|
|
b0bcac6926 | ||
|
|
3b7ad53994 | ||
|
|
0fedfae1e6 | ||
|
|
3fa2a35c12 | ||
|
|
a39859a39e | ||
|
|
d2f4a84314 | ||
|
|
0959eacf39 | ||
|
|
78c4b3b264 | ||
|
|
9f4a841eb6 | ||
|
|
9b034fcbb2 | ||
|
|
81cf964168 | ||
|
|
b5158210a9 | ||
|
|
d1602710a8 | ||
|
|
ec1453831d | ||
|
|
c63af629ac | ||
|
|
916b1d46fc | ||
|
|
7df694fe49 | ||
|
|
071289b56e | ||
|
|
eca355016c | ||
|
|
0053d12407 | ||
|
|
4d6ee985b9 | ||
|
|
94d74d35db | ||
|
|
d6a157578d | ||
|
|
0b9f3106fe | ||
|
|
17c75bf671 | ||
|
|
d6a9c2ed90 | ||
|
|
9931dc13a7 | ||
|
|
4a3d5a7d66 |
No files matched your search
@@ -1,5 +0,0 @@
|
|||||||
# GitHub PR openers trusted for automatic release-signed test builds.
|
|
||||||
FX192
|
|
||||||
K11MCH1
|
|
||||||
kingokksa
|
|
||||||
ovurrsl
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
name: Build validation
|
|
||||||
|
|
||||||
on:
|
|
||||||
pull_request_target:
|
|
||||||
branches: [main]
|
|
||||||
types: [opened, synchronize, reopened, edited, ready_for_review]
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
workflow_run:
|
|
||||||
workflows: [Build APK]
|
|
||||||
types: [completed]
|
|
||||||
workflow_dispatch:
|
|
||||||
inputs:
|
|
||||||
pr_number:
|
|
||||||
description: Pull request to validate; empty for main
|
|
||||||
required: false
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
actions: read
|
|
||||||
pull-requests: read
|
|
||||||
statuses: write
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
validate:
|
|
||||||
name: Validate source and build result
|
|
||||||
runs-on: ubuntu-24.04
|
|
||||||
timeout-minutes: 5
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
ref: ${{ github.workflow_sha }}
|
|
||||||
fetch-depth: 0
|
|
||||||
persist-credentials: false
|
|
||||||
- name: Validate source and APK compilation
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ github.token }}
|
|
||||||
run: |
|
|
||||||
gh auth setup-git
|
|
||||||
python3 tools/release/validate_apk.py
|
|
||||||
+459
-343
@@ -8,8 +8,6 @@ on:
|
|||||||
- '**/*.md'
|
- '**/*.md'
|
||||||
- 'LICENSE'
|
- 'LICENSE'
|
||||||
- '.gitignore'
|
- '.gitignore'
|
||||||
- 'docs/**'
|
|
||||||
- '.github/ISSUE_TEMPLATE/**'
|
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [ main ]
|
branches: [ main ]
|
||||||
types: [ opened, synchronize, reopened, ready_for_review ]
|
types: [ opened, synchronize, reopened, ready_for_review ]
|
||||||
@@ -17,32 +15,27 @@ on:
|
|||||||
- '**/*.md'
|
- '**/*.md'
|
||||||
- 'LICENSE'
|
- 'LICENSE'
|
||||||
- '.gitignore'
|
- '.gitignore'
|
||||||
- 'docs/**'
|
|
||||||
- '.github/ISSUE_TEMPLATE/**'
|
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
|
||||||
rebuild_preloads:
|
|
||||||
description: Rebuild preloads instead of reusing the approved binary snapshot
|
|
||||||
type: boolean
|
|
||||||
default: false
|
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
actions: read
|
|
||||||
pull-requests: write
|
pull-requests: write
|
||||||
|
|
||||||
concurrency:
|
concurrency:
|
||||||
group: build-${{ github.event.pull_request.number || (github.event_name == 'push' && 'main') || github.run_id }}
|
group: build-${{ github.event.pull_request.number || github.run_id }}
|
||||||
cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' }}
|
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||||
|
|
||||||
|
env:
|
||||||
|
PRELOAD_CACHE_VERSION: v6
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
source:
|
xbox:
|
||||||
name: Pin source tree
|
name: Xbox ARM64 backend
|
||||||
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
|
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04-arm
|
||||||
timeout-minutes: 5
|
timeout-minutes: 30
|
||||||
outputs:
|
outputs:
|
||||||
base-sha: ${{ steps.merge.outputs.base-sha || steps.trusted.outputs.base-sha }}
|
base-sha: ${{ steps.merge.outputs.base-sha }}
|
||||||
tree-sha: ${{ steps.source.outputs.tree-sha }}
|
tree-sha: ${{ steps.source.outputs.tree-sha }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
@@ -60,46 +53,9 @@ jobs:
|
|||||||
git config user.name "ci"
|
git config user.name "ci"
|
||||||
git config user.email "ci@users.noreply.github.com"
|
git config user.email "ci@users.noreply.github.com"
|
||||||
git merge --no-ff --no-edit origin/main
|
git merge --no-ff --no-edit origin/main
|
||||||
- name: Resolve trusted manifest base
|
- name: Record backend source tree
|
||||||
id: trusted
|
|
||||||
if: github.event_name != 'pull_request'
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
git fetch --no-tags origin main
|
|
||||||
echo "base-sha=$(git rev-parse origin/main)" >> "$GITHUB_OUTPUT"
|
|
||||||
- name: Record pinned source tree
|
|
||||||
id: source
|
id: source
|
||||||
run: echo "tree-sha=$(git rev-parse 'HEAD^{tree}')" >> "$GITHUB_OUTPUT"
|
run: echo "tree-sha=$(git rev-parse 'HEAD^{tree}')" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
xbox:
|
|
||||||
name: Xbox ARM64 backend
|
|
||||||
needs: source
|
|
||||||
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
|
|
||||||
runs-on: ubuntu-24.04-arm
|
|
||||||
timeout-minutes: 30
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
|
||||||
fetch-depth: 0
|
|
||||||
persist-credentials: false
|
|
||||||
- name: Merge the pinned APK base
|
|
||||||
if: github.event_name == 'pull_request'
|
|
||||||
env:
|
|
||||||
BUILD_BASE_SHA: ${{ needs.source.outputs.base-sha }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
git fetch --no-tags origin "$BUILD_BASE_SHA"
|
|
||||||
git config user.name "ci"
|
|
||||||
git config user.email "ci@users.noreply.github.com"
|
|
||||||
git merge --no-ff --no-edit FETCH_HEAD
|
|
||||||
- name: Verify pinned source tree
|
|
||||||
env:
|
|
||||||
SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
|
|
||||||
run: test "$(git rev-parse 'HEAD^{tree}')" = "$SOURCE_TREE"
|
|
||||||
- name: Plan component identities
|
|
||||||
id: plan
|
|
||||||
run: python3 tools/components/prepare.py plan
|
|
||||||
- uses: actions/cache@v4
|
- uses: actions/cache@v4
|
||||||
id: xbox-cache
|
id: xbox-cache
|
||||||
with:
|
with:
|
||||||
@@ -107,10 +63,14 @@ jobs:
|
|||||||
app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
|
app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
|
||||||
app/build/xbox/xodus-droiddeck-source.tar.xz
|
app/build/xbox/xodus-droiddeck-source.tar.xz
|
||||||
app/build/xbox/runtime/*-source.tar.xz
|
app/build/xbox/runtime/*-source.tar.xz
|
||||||
key: xbox-v2-${{ steps.plan.outputs.xbox }}
|
key: xbox-arm64-${{ hashFiles('tools/xbox/**') }}
|
||||||
- name: Build Xbox backend
|
- name: Build Xbox backend
|
||||||
if: steps.xbox-cache.outputs.cache-hit != 'true'
|
if: steps.xbox-cache.outputs.cache-hit != 'true'
|
||||||
run: python3 tools/components/prepare.py xbox
|
run: |
|
||||||
|
rustup toolchain install 1.99.0 --profile minimal
|
||||||
|
sudo apt-get update -qq
|
||||||
|
sudo apt-get install -y build-essential pkg-config libssl-dev protobuf-compiler cmake xz-utils
|
||||||
|
bash tools/xbox/build.sh
|
||||||
- uses: actions/upload-artifact@v4
|
- uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: xbox-arm64
|
name: xbox-arm64
|
||||||
@@ -125,158 +85,9 @@ jobs:
|
|||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
retention-days: 14
|
retention-days: 14
|
||||||
|
|
||||||
components:
|
|
||||||
name: Prepare verified components
|
|
||||||
needs: source
|
|
||||||
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
|
|
||||||
runs-on: ubuntu-24.04
|
|
||||||
timeout-minutes: 40
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
|
||||||
fetch-depth: 0
|
|
||||||
persist-credentials: false
|
|
||||||
- name: Merge the pinned APK base
|
|
||||||
if: github.event_name == 'pull_request'
|
|
||||||
env:
|
|
||||||
BUILD_BASE_SHA: ${{ needs.source.outputs.base-sha }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
git fetch --no-tags origin "$BUILD_BASE_SHA"
|
|
||||||
git config user.name "ci"
|
|
||||||
git config user.email "ci@users.noreply.github.com"
|
|
||||||
git merge --no-ff --no-edit FETCH_HEAD
|
|
||||||
- name: Verify pinned source tree
|
|
||||||
env:
|
|
||||||
SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
|
|
||||||
run: test "$(git rev-parse 'HEAD^{tree}')" = "$SOURCE_TREE"
|
|
||||||
- name: Resolve the pinned Android NDK
|
|
||||||
run: bash tools/ci/resolve-ndk.sh
|
|
||||||
|
|
||||||
- name: Plan component identities
|
|
||||||
id: plan
|
|
||||||
run: python3 tools/components/prepare.py plan
|
|
||||||
- name: Cache remaining Linux runtime assets
|
|
||||||
id: preloads
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
app/src/main/assets/linuxfs
|
|
||||||
!app/src/main/assets/linuxfs/usr/local/lib/droiddeck-comet
|
|
||||||
!app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
|
|
||||||
!app/src/main/assets/linuxfs/i386/libblsession.so
|
|
||||||
!app/src/main/assets/linuxfs/i386/libfakeinput.so
|
|
||||||
!app/src/main/assets/linuxfs/i386/libfaultreport.so
|
|
||||||
!app/src/main/assets/linuxfs/libblaudit.so
|
|
||||||
!app/src/main/assets/linuxfs/libblfastpath.so
|
|
||||||
!app/src/main/assets/linuxfs/libblsession.so
|
|
||||||
!app/src/main/assets/linuxfs/libfakeinput.so
|
|
||||||
!app/src/main/assets/linuxfs/libssbs.so
|
|
||||||
!app/src/main/assets/linuxfs/usr/local/bin/droiddeck-clipboard
|
|
||||||
!app/src/main/assets/linuxfs/x86_64/libblsession.so
|
|
||||||
!app/src/main/assets/linuxfs/x86_64/libfakeinput.so
|
|
||||||
!app/src/main/assets/linuxfs/x86_64/libfaultreport.so
|
|
||||||
!app/src/main/assets/linuxfs/x86_64/libvulkan-thunk.so
|
|
||||||
!app/src/main/assets/linuxfs/x86_64/libwebkitinput.so
|
|
||||||
key: runtime-v9-${{ steps.plan.outputs.runtime }}
|
|
||||||
|
|
||||||
- name: Cache PulseAudio 13.0 source
|
|
||||||
id: pa-src
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: pa13
|
|
||||||
key: pulseaudio-src-${{ steps.plan.outputs.pulseaudio-source }}
|
|
||||||
- name: Cache proot
|
|
||||||
id: proot
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
app/src/main/jniLibs/arm64-v8a/libproot.so
|
|
||||||
app/src/main/jniLibs/arm64-v8a/libproot-loader.so
|
|
||||||
key: proot-v2-${{ steps.plan.outputs.proot }}
|
|
||||||
- name: Cache GOG Galaxy companion
|
|
||||||
id: comet
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-comet
|
|
||||||
key: comet-v2-${{ steps.plan.outputs.comet }}
|
|
||||||
|
|
||||||
- name: Restore verified preload snapshots
|
|
||||||
id: component-preloads
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ github.token }}
|
|
||||||
FORCE_PRELOAD_REBUILD: ${{ inputs.rebuild_preloads || 'false' }}
|
|
||||||
COMPONENT_TRUSTED_BASE: ${{ needs.source.outputs.base-sha }}
|
|
||||||
run: python3 tools/components/prepare.py preload-snapshot
|
|
||||||
|
|
||||||
- name: Prepare required Linux build tools once
|
|
||||||
env:
|
|
||||||
COMPONENTS_TO_BUILD: >-
|
|
||||||
${{ steps.preloads.outputs.cache-hit != 'true' && 'runtime' || '' }}
|
|
||||||
${{ steps.component-preloads.outputs.arm64 != 'true' && 'arm64-preloads' || '' }}
|
|
||||||
${{ steps.comet.outputs.cache-hit != 'true' && 'comet' || '' }}
|
|
||||||
run: python3 tools/components/prepare.py tools
|
|
||||||
|
|
||||||
- name: Build changed ARM64 preloads
|
|
||||||
if: steps.component-preloads.outputs.arm64 != 'true'
|
|
||||||
run: python3 tools/components/prepare.py arm64-preloads
|
|
||||||
|
|
||||||
- name: Prepare remaining Linux runtime assets
|
|
||||||
if: steps.preloads.outputs.cache-hit != 'true'
|
|
||||||
run: python3 tools/components/prepare.py runtime
|
|
||||||
|
|
||||||
- name: Fetch the Debian image the preloads build in
|
|
||||||
if: steps.component-preloads.outputs.x86 != 'true'
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ github.token }}
|
|
||||||
run: python3 tools/components/prepare.py debian-image
|
|
||||||
|
|
||||||
- name: Build the x86 preloads FEX guests load (glibc 2.31)
|
|
||||||
if: steps.component-preloads.outputs.x86 != 'true'
|
|
||||||
run: python3 tools/components/prepare.py x86-preloads
|
|
||||||
|
|
||||||
- name: Bundle the droiddeck-esync packs
|
|
||||||
run: python3 tools/components/prepare.py esync
|
|
||||||
|
|
||||||
- name: Fetch PulseAudio 13.0 source
|
|
||||||
if: steps.pa-src.outputs.cache-hit != 'true'
|
|
||||||
run: python3 tools/components/prepare.py pulseaudio-source
|
|
||||||
|
|
||||||
- name: Fetch DirectAudio (tools/directaudio/release.env)
|
|
||||||
run: python3 tools/components/prepare.py directaudio
|
|
||||||
|
|
||||||
- name: Build the AAudio sink into the audio bundle
|
|
||||||
run: python3 tools/components/prepare.py audio
|
|
||||||
|
|
||||||
- name: Build proot
|
|
||||||
if: steps.proot.outputs.cache-hit != 'true'
|
|
||||||
run: python3 tools/components/prepare.py proot
|
|
||||||
|
|
||||||
- name: Check the preloads
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
bash tools/linuxfs/check-preloads.sh app/src/main/assets/linuxfs
|
|
||||||
|
|
||||||
- name: Build GOG Galaxy companion
|
|
||||||
if: steps.comet.outputs.cache-hit != 'true'
|
|
||||||
run: python3 tools/components/prepare.py comet
|
|
||||||
|
|
||||||
- name: Prepare graphics driver variants
|
|
||||||
run: python3 tools/quest/build-driver.py "$ANDROID_HOME/ndk/$NDK_VERSION"
|
|
||||||
- name: Record and pack prepared components
|
|
||||||
run: python3 tools/components/prepare.py pack
|
|
||||||
- uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: prepared-components
|
|
||||||
path: app/build/prepared-components.tar.gz
|
|
||||||
if-no-files-found: error
|
|
||||||
compression-level: 0
|
|
||||||
retention-days: 14
|
|
||||||
|
|
||||||
build:
|
build:
|
||||||
needs: [source, components, xbox]
|
needs: xbox
|
||||||
name: Compile APK and Android tests
|
name: Build APK
|
||||||
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
|
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
timeout-minutes: 45
|
timeout-minutes: 45
|
||||||
@@ -289,22 +100,17 @@ jobs:
|
|||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
|
|
||||||
- name: Check human authorship
|
- name: Check co-authors
|
||||||
env:
|
if: github.event_name == 'pull_request'
|
||||||
EVENT_NAME: ${{ github.event_name }}
|
|
||||||
BEFORE: ${{ github.event.before }}
|
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
if [ "$EVENT_NAME" = pull_request ]; then
|
git fetch --no-tags origin main
|
||||||
git fetch --no-tags origin main
|
base=$(git merge-base origin/main HEAD)
|
||||||
base=$(git merge-base origin/main HEAD)
|
messages=$(git log --format=%B "$base..HEAD")
|
||||||
checker="$RUNNER_TEMP/droiddeck-check-authorship.py"
|
messages+=$'\n'"$(jq -r '.pull_request.title, (.pull_request.body // "")' "$GITHUB_EVENT_PATH")"
|
||||||
git show origin/main:tools/release/check_authorship.py > "$checker"
|
if grep -Eiq '^[[:space:]]*Co-authored-by:.*(Claude|Anthropic|OpenAI|ChatGPT|GPT|Copilot|Cursor|Gemini|Codex|Devin|Windsurf|Codeium|Amazon Q|Tabnine|Cody|\[bot\])' <<<"$messages"; then
|
||||||
python3 "$checker" "$base..HEAD" --event "$GITHUB_EVENT_PATH"
|
echo "::error::AI and bot identities cannot be co-authors; remove the Co-authored-by trailer."
|
||||||
elif [ "$EVENT_NAME" = push ] && [ "$BEFORE" != 0000000000000000000000000000000000000000 ]; then
|
exit 1
|
||||||
python3 tools/release/check_authorship.py "$BEFORE..HEAD"
|
|
||||||
else
|
|
||||||
python3 tools/release/check_authorship.py HEAD
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: The packages a signed build ships as
|
- name: The packages a signed build ships as
|
||||||
@@ -339,7 +145,7 @@ jobs:
|
|||||||
- name: Merge onto main, or say what conflicts
|
- name: Merge onto main, or say what conflicts
|
||||||
if: github.event_name == 'pull_request'
|
if: github.event_name == 'pull_request'
|
||||||
env:
|
env:
|
||||||
BUILD_BASE_SHA: ${{ needs.source.outputs.base-sha }}
|
BUILD_BASE_SHA: ${{ needs.xbox.outputs.base-sha }}
|
||||||
run: |
|
run: |
|
||||||
set -uo pipefail
|
set -uo pipefail
|
||||||
git config user.name "ci"
|
git config user.name "ci"
|
||||||
@@ -397,7 +203,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Verify backend and APK source match
|
- name: Verify backend and APK source match
|
||||||
env:
|
env:
|
||||||
XBOX_SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
|
XBOX_SOURCE_TREE: ${{ needs.xbox.outputs.tree-sha }}
|
||||||
run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
|
run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
|
||||||
|
|
||||||
- uses: actions/setup-java@v4
|
- uses: actions/setup-java@v4
|
||||||
@@ -407,11 +213,13 @@ jobs:
|
|||||||
|
|
||||||
- uses: gradle/actions/setup-gradle@v4
|
- uses: gradle/actions/setup-gradle@v4
|
||||||
with:
|
with:
|
||||||
cache-read-only: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }}
|
cache-cleanup: on-success
|
||||||
cache-cleanup: ${{ github.event_name == 'pull_request' && 'never' || 'on-success' }}
|
|
||||||
|
|
||||||
- name: Resolve the pinned Android NDK
|
- name: Resolve the runner's NDK
|
||||||
run: bash tools/ci/resolve-ndk.sh
|
run: |
|
||||||
|
NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
|
||||||
|
VERSION=$(sed -n 's/^Pkg.Revision *= *//p' "$NDK/source.properties")
|
||||||
|
echo "NDK_VERSION=$VERSION" >> "$GITHUB_ENV"
|
||||||
|
|
||||||
- name: Set the APK build label
|
- name: Set the APK build label
|
||||||
id: build-label
|
id: build-label
|
||||||
@@ -437,6 +245,251 @@ jobs:
|
|||||||
echo "DROIDDECK_PR_NUMBER=${PR_NUMBER:-0}" >> "$GITHUB_ENV"
|
echo "DROIDDECK_PR_NUMBER=${PR_NUMBER:-0}" >> "$GITHUB_ENV"
|
||||||
echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY"
|
echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
|
||||||
|
- name: Cache the preloads
|
||||||
|
id: preloads
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: app/src/main/assets/linuxfs
|
||||||
|
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h', 'tools/quest/*', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**', 'tools/comet/**', 'tools/xbox/**', 'tools/linuxfs/debian-image.env', 'tools/vr/**') }}
|
||||||
|
|
||||||
|
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
|
||||||
|
if: steps.preloads.outputs.cache-hit != 'true'
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
sudo apt-get -o Dir::Etc::sourcelist=sources.list.d/ubuntu.sources \
|
||||||
|
-o Dir::Etc::sourceparts=- -o Acquire::Retries=3 update -qq
|
||||||
|
sudo apt-get install -y -qq gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libvulkan1 mesa-vulkan-drivers >/dev/null
|
||||||
|
D=app/src/main/assets/linuxfs
|
||||||
|
mkdir -p "$D"
|
||||||
|
aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
|
||||||
|
-pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \
|
||||||
|
-o "$D/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
|
||||||
|
aarch64-linux-gnu-strip --strip-unneeded "$D/libfakeinput.so"
|
||||||
|
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||||
|
-o "$D/libblsession.so" tools/linuxfs/preload/*.c -ldl
|
||||||
|
aarch64-linux-gnu-strip --strip-unneeded "$D/libblsession.so"
|
||||||
|
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||||
|
-o "$D/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl
|
||||||
|
aarch64-linux-gnu-strip --strip-unneeded "$D/libblfastpath.so"
|
||||||
|
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -nostdlib -ffreestanding -fno-stack-protector \
|
||||||
|
-fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$D/libblaudit.so" tools/proot/fastpath/audit.c
|
||||||
|
aarch64-linux-gnu-strip --strip-unneeded "$D/libblaudit.so"
|
||||||
|
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||||
|
-o "$D/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
|
||||||
|
aarch64-linux-gnu-strip --strip-unneeded "$D/libssbs.so"
|
||||||
|
mkdir -p "$D/usr/local/bin"
|
||||||
|
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$D/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
|
||||||
|
aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/bin/droiddeck-clipboard"
|
||||||
|
VK_INCLUDE=$(ls -d "${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1) \
|
||||||
|
tools/vr/build.sh --native "$D/usr/local/lib/droiddeck-vr"
|
||||||
|
for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
|
||||||
|
install -Dm644 "$script" "$D/usr/local/bin/$(basename "$script")"
|
||||||
|
done
|
||||||
|
for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do
|
||||||
|
[ -f "$f" ] && install -Dm644 "$f" "$D/${f#tools/linuxfs/overlay/}"
|
||||||
|
done
|
||||||
|
if [ -f tools/gamescope/release.env ]; then
|
||||||
|
. tools/gamescope/release.env
|
||||||
|
curl -fsSL --retry 3 -o gamescope.tzst "https://github.com/${GAMESCOPE_REPO:-${GITHUB_REPOSITORY}}/releases/download/${GAMESCOPE_TAG}/gamescope.tzst"
|
||||||
|
echo "${GAMESCOPE_SHA256} gamescope.tzst" | sha256sum -c -
|
||||||
|
tar --use-compress-program=unzstd -xf gamescope.tzst -C "$D"
|
||||||
|
test -f "$D/usr/local/bin/gamescope"
|
||||||
|
rm gamescope.tzst
|
||||||
|
fi
|
||||||
|
. tools/linuxfs/uruntime.env
|
||||||
|
curl -fsSL --retry 3 -o uruntime "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}"
|
||||||
|
echo "${URUNTIME_SHA256} uruntime" | sha256sum -c -
|
||||||
|
install -Dm644 uruntime "$D/usr/local/lib/droiddeck/uruntime"
|
||||||
|
install -Dm644 tools/linuxfs/licenses/uruntime-LICENSE "$D/usr/local/share/licenses/uruntime/LICENSE"
|
||||||
|
rm uruntime
|
||||||
|
M="$D/usr/local/lib/mangoapp"
|
||||||
|
mkdir -p "$M" mango-pkgs
|
||||||
|
grep -v '^#' tools/mangoapp/packages.txt | while read -r sum url; do
|
||||||
|
[ -n "$url" ] || continue
|
||||||
|
curl -fsSL --retry 3 -o mango-pkgs/pkg.tar.zst "$url"
|
||||||
|
echo "$sum mango-pkgs/pkg.tar.zst" | sha256sum -c -
|
||||||
|
tar --use-compress-program=unzstd -xf mango-pkgs/pkg.tar.zst -C mango-pkgs
|
||||||
|
rm mango-pkgs/pkg.tar.zst
|
||||||
|
done
|
||||||
|
install -m644 mango-pkgs/usr/bin/mangoapp "$M/mangoapp"
|
||||||
|
for so in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do
|
||||||
|
cp -L "mango-pkgs/usr/lib/$so" "$M/$so"
|
||||||
|
done
|
||||||
|
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \
|
||||||
|
-o "$M/libtracefs.so.1" tools/mangoapp/libtracefs-shim.c
|
||||||
|
aarch64-linux-gnu-strip --strip-unneeded "$M/libtracefs.so.1"
|
||||||
|
install -Dm644 tools/mangoapp/mangoapp "$D/usr/local/bin/mangoapp"
|
||||||
|
rm -rf mango-pkgs
|
||||||
|
ls -l "$M"
|
||||||
|
T="$D/usr/local/lib/droiddeck-msitools"
|
||||||
|
mkdir -p "$T" msi-pkgs
|
||||||
|
grep -v '^#' tools/msitools/packages.txt | while read -r sum url; do
|
||||||
|
[ -n "$url" ] || continue
|
||||||
|
curl -fsSL --retry 3 -o msi-pkgs/pkg.tar.xz "$url"
|
||||||
|
echo "$sum msi-pkgs/pkg.tar.xz" | sha256sum -c -
|
||||||
|
tar -xJf msi-pkgs/pkg.tar.xz -C msi-pkgs
|
||||||
|
rm msi-pkgs/pkg.tar.xz
|
||||||
|
done
|
||||||
|
install -m644 msi-pkgs/usr/bin/msiinfo "$T/msiinfo"
|
||||||
|
install -m644 msi-pkgs/usr/bin/cabextract "$T/cabextract"
|
||||||
|
install -m644 msi-pkgs/usr/lib/7zip/7z "$T/7z"
|
||||||
|
install -m644 msi-pkgs/usr/lib/7zip/7z.so "$T/7z.so"
|
||||||
|
for so in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
|
||||||
|
cp -L "msi-pkgs/usr/lib/$so" "$T/$so"
|
||||||
|
done
|
||||||
|
for f in NOTICE GPL-2 GPL-3 LGPL-2.1 7zip-License 7zip-unRarLicense; do
|
||||||
|
install -Dm644 "tools/msitools/licenses/$f" "$D/usr/local/share/licenses/droiddeck-msitools/$f"
|
||||||
|
done
|
||||||
|
rm -rf msi-pkgs
|
||||||
|
ls -l "$T"
|
||||||
|
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop "$D/usr/local/bin/droiddeck-desktop"
|
||||||
|
install -Dm644 tools/linuxfs/desktop/droiddeck-gpu "$D/usr/local/bin/droiddeck-gpu"
|
||||||
|
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop-gpu "$D/usr/local/bin/droiddeck-desktop-gpu"
|
||||||
|
install -Dm644 tools/linuxfs/desktop/kwin_wayland_wrapper "$D/usr/local/bin/kwin_wayland_wrapper"
|
||||||
|
install -Dm644 tools/linuxfs/desktop/firefox-droiddeck.js "$D/usr/lib/firefox/defaults/pref/droiddeck.js"
|
||||||
|
ls -lR "$D"
|
||||||
|
|
||||||
|
- name: Fetch the Debian image the preloads build in
|
||||||
|
if: steps.preloads.outputs.cache-hit != 'true'
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
. tools/linuxfs/debian-image.env
|
||||||
|
image=public.ecr.aws/docker/library/debian:bullseye
|
||||||
|
if gh release download "$DEBIAN_IMAGE_TAG" -R "$GITHUB_REPOSITORY" -p "$DEBIAN_IMAGE_ASSET" -O /tmp/debian-image.tar.zst \
|
||||||
|
&& { [ -z "$DEBIAN_IMAGE_SHA256" ] || echo "$DEBIAN_IMAGE_SHA256 /tmp/debian-image.tar.zst" | sha256sum -c -; }; then
|
||||||
|
zstd -dc /tmp/debian-image.tar.zst | docker load
|
||||||
|
rm -f /tmp/debian-image.tar.zst
|
||||||
|
else
|
||||||
|
echo "::warning::the hosted Debian image could not be fetched; pulling from the registry instead"
|
||||||
|
for attempt in 1 2 3 4 5; do
|
||||||
|
docker pull "$image" && break
|
||||||
|
[ "$attempt" -lt 5 ] || { echo "::error::could not pull $image after $attempt attempts"; exit 1; }
|
||||||
|
echo "pull attempt $attempt failed (registry busy?); retrying in $((attempt * 30)) s"
|
||||||
|
sleep $((attempt * 30))
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
docker image ls "$image"
|
||||||
|
|
||||||
|
- name: Build the x86 preloads FEX guests load (glibc 2.31)
|
||||||
|
if: steps.preloads.outputs.cache-hit != 'true'
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
docker run --rm -v "$PWD:/src" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c '
|
||||||
|
set -euo pipefail
|
||||||
|
install_compilers() {
|
||||||
|
apt-get -o Acquire::Check-Valid-Until=false update -qq &&
|
||||||
|
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends gcc g++ gcc-multilib g++-multilib binutils >/dev/null
|
||||||
|
}
|
||||||
|
printf "deb http://deb.debian.org/debian bullseye main\ndeb http://security.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
|
||||||
|
if ! install_compilers; then
|
||||||
|
printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
|
||||||
|
install_compilers
|
||||||
|
fi
|
||||||
|
tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs
|
||||||
|
'
|
||||||
|
sudo chown -R "$(id -u):$(id -g)" app/src/main/assets/linuxfs
|
||||||
|
ls -l app/src/main/assets/linuxfs/x86_64 app/src/main/assets/linuxfs/i386
|
||||||
|
|
||||||
|
- name: Bundle the droiddeck-esync packs
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [ -f tools/droiddeck-esync/release.env ]; then
|
||||||
|
. tools/droiddeck-esync/release.env
|
||||||
|
release_url="https://github.com/${SYNC_BUNDLE_REPO}/releases/download/${SYNC_BUNDLE_TAG}"
|
||||||
|
curl -fsSL --retry 3 -o sync-bundle.tzst "$release_url/$SYNC_BUNDLE_ASSET"
|
||||||
|
echo "$SYNC_BUNDLE_SHA256 sync-bundle.tzst" | sha256sum -c -
|
||||||
|
mkdir -p app/src/main/assets/droiddeck-esync
|
||||||
|
tar --use-compress-program=unzstd -xf sync-bundle.tzst -C app/src/main/assets/droiddeck-esync
|
||||||
|
rm sync-bundle.tzst
|
||||||
|
curl -fsSL --retry 3 -o sync-index.json "$release_url/index.json"
|
||||||
|
revoked=$(python3 -c 'import json, sys; print(" ".join(p["id"] for p in json.load(open(sys.argv[1]))["packs"] if p.get("revoked") is True))' sync-index.json)
|
||||||
|
for id in $revoked; do
|
||||||
|
if [ -e "app/src/main/assets/droiddeck-esync/packs/$id.tzst" ]; then
|
||||||
|
echo "::warning::$SYNC_BUNDLE_ASSET carries revoked pack $id; it is left out of the APK (point tools/droiddeck-esync/release.env at a newer bundle)"
|
||||||
|
rm -f "app/src/main/assets/droiddeck-esync/packs/$id.tzst"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
rm sync-index.json
|
||||||
|
test -f app/src/main/assets/droiddeck-esync/index.json
|
||||||
|
test -f app/src/main/assets/droiddeck-esync/index.json.sig
|
||||||
|
ls -lR app/src/main/assets/droiddeck-esync
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Cache PulseAudio 13.0 source
|
||||||
|
id: pa-src
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: pa13
|
||||||
|
key: pulseaudio-src-13.0
|
||||||
|
- name: Fetch PulseAudio 13.0 source
|
||||||
|
if: steps.pa-src.outputs.cache-hit != 'true'
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
curl -fsSL -o pa.tar.gz https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz
|
||||||
|
mkdir -p pa13 && tar -xzf pa.tar.gz -C pa13 --strip-components=1 && rm pa.tar.gz
|
||||||
|
- name: Fetch DirectAudio (tools/directaudio/release.env)
|
||||||
|
run: tools/directaudio/fetch.sh "$PWD" "$PWD/sink-out"
|
||||||
|
- name: Build the AAudio sink into the audio bundle
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
|
||||||
|
tools/aaudio-sink/build.sh "$PWD/pa13" "$PWD/sink-out"
|
||||||
|
rm -rf pa-bundle && mkdir -p pa-bundle
|
||||||
|
tar --use-compress-program=unzstd -xf app/src/main/assets/pulseaudio.tzst -C pa-bundle
|
||||||
|
test ! -f pa-bundle/modules/arm64/module-aaudio-sink.so
|
||||||
|
install -m755 sink-out/module-aaudio-sink.so pa-bundle/modules/arm64/module-aaudio-sink.so
|
||||||
|
install -m755 sink-out/module-directaudio-native-sink.so pa-bundle/modules/arm64/module-directaudio-native-sink.so
|
||||||
|
(cd pa-bundle && tar --use-compress-program='zstd -19' -cf ../pulseaudio.tzst .)
|
||||||
|
mkdir -p app/build/prepared-assets
|
||||||
|
mv pulseaudio.tzst app/build/prepared-assets/pulseaudio.tzst
|
||||||
|
tar --use-compress-program=unzstd -tf app/build/prepared-assets/pulseaudio.tzst | grep -c '\.so$'
|
||||||
|
rm -rf pa-bundle sink-out
|
||||||
|
- name: Cache proot
|
||||||
|
id: proot
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
app/src/main/jniLibs/arm64-v8a/libproot.so
|
||||||
|
app/src/main/jniLibs/arm64-v8a/libproot-loader.so
|
||||||
|
key: proot-${{ env.NDK_VERSION }}-${{ hashFiles('tools/proot/**') }}
|
||||||
|
- name: Build proot
|
||||||
|
if: steps.proot.outputs.cache-hit != 'true'
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
|
||||||
|
tools/proot/build.sh app/src/main/jniLibs/arm64-v8a
|
||||||
|
|
||||||
|
- name: Check the preloads
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
bash tools/linuxfs/check-preloads.sh app/src/main/assets/linuxfs
|
||||||
|
|
||||||
|
- name: Check Quest tracking IPC
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
|
||||||
|
VK_INCLUDE=$(ls -d "$NDK"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1)
|
||||||
|
mkdir -p build/vr/include
|
||||||
|
cp -R "$VK_INCLUDE/vulkan" build/vr/include/
|
||||||
|
if [ -d "$VK_INCLUDE/vk_video" ]; then cp -R "$VK_INCLUDE/vk_video" build/vr/include/; fi
|
||||||
|
g++ -std=c++17 -Wall -Wextra -Werror -pthread tools/vr/tests/test_xr_tracking.cpp -o /tmp/test-xr-tracking
|
||||||
|
/tmp/test-xr-tracking
|
||||||
|
g++ -std=c++17 -Wall -Wextra -Werror tools/vr/tests/test_xr_touch.cpp -o /tmp/test-xr-touch
|
||||||
|
/tmp/test-xr-touch
|
||||||
|
g++ -std=c++17 -Wall -Wextra -Werror -pthread tools/vr/tests/test_xr_vsync.cpp -o /tmp/test-xr-vsync
|
||||||
|
/tmp/test-xr-vsync
|
||||||
|
g++ -std=c++17 -Wall -Wextra -Werror -pthread tools/vr/tests/test_xr_frames.cpp -o /tmp/test-xr-frames
|
||||||
|
/tmp/test-xr-frames
|
||||||
|
cc -Itools/vr/third_party/wayland -c tools/vr/src/wayland_client_stub.c -o /tmp/test-wayland-stub.o
|
||||||
|
cc -Itools/vr/third_party/wayland -c app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c -o /tmp/test-xdg-shell.o
|
||||||
|
g++ -std=c++17 -Wall -Wextra -Werror -Wno-unused-parameter -Wno-missing-field-initializers -pthread -Ibuild/vr/include \
|
||||||
|
-Itools/vr/third_party/wayland -Iapp/src/main/cpp/waylandcomp/generated \
|
||||||
|
tools/vr/tests/test_presenter_shutdown.cpp tools/vr/src/presenter.cpp /tmp/test-wayland-stub.o /tmp/test-xdg-shell.o \
|
||||||
|
-ldl -o /tmp/test-presenter-shutdown
|
||||||
|
timeout 10 /tmp/test-presenter-shutdown
|
||||||
|
|
||||||
- name: Rust toolchain for the store engines (aarch64-linux-android)
|
- name: Rust toolchain for the store engines (aarch64-linux-android)
|
||||||
id: rust
|
id: rust
|
||||||
run: |
|
run: |
|
||||||
@@ -454,10 +507,9 @@ jobs:
|
|||||||
~/.cargo/git/db
|
~/.cargo/git/db
|
||||||
~/.cargo/bin/cargo-ndk
|
~/.cargo/bin/cargo-ndk
|
||||||
app/src/main/rust/stores/target
|
app/src/main/rust/stores/target
|
||||||
key: stores-v2-${{ runner.os }}-${{ runner.arch }}-${{ env.NDK_VERSION }}-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}-${{ hashFiles('app/src/main/rust/stores/src/**', 'app/src/main/rust/stores/Cargo.toml', 'app/src/main/rust/stores/build.rs', 'app/src/main/rust/stores/.cargo/**', 'app/build.gradle') }}
|
key: stores-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}
|
||||||
restore-keys: |
|
restore-keys: |
|
||||||
stores-v2-${{ runner.os }}-${{ runner.arch }}-${{ env.NDK_VERSION }}-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}-
|
stores-${{ steps.rust.outputs.rustc }}-
|
||||||
stores-v2-${{ runner.os }}-${{ runner.arch }}-${{ env.NDK_VERSION }}-${{ steps.rust.outputs.rustc }}-
|
|
||||||
|
|
||||||
- name: cargo-ndk
|
- name: cargo-ndk
|
||||||
run: |
|
run: |
|
||||||
@@ -475,39 +527,21 @@ jobs:
|
|||||||
restore-keys: |
|
restore-keys: |
|
||||||
cxx-${{ env.NDK_VERSION }}-
|
cxx-${{ env.NDK_VERSION }}-
|
||||||
|
|
||||||
- uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
name: prepared-components
|
|
||||||
path: app/build
|
|
||||||
- name: Verify and unpack prepared components
|
|
||||||
env:
|
|
||||||
SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
|
|
||||||
run: python3 tools/components/prepare.py unpack --tree "$SOURCE_TREE"
|
|
||||||
|
|
||||||
- uses: actions/download-artifact@v4
|
- uses: actions/download-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: xbox-arm64
|
name: xbox-arm64
|
||||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
|
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
|
||||||
|
|
||||||
- name: Cache checksum-pinned pack inputs
|
- name: Build GOG Galaxy companion
|
||||||
uses: actions/cache@v4
|
if: steps.preloads.outputs.cache-hit != 'true'
|
||||||
with:
|
run: |
|
||||||
path: ~/.cache/droiddeck-pack-inputs
|
rustup toolchain install 1.90.0 --profile minimal
|
||||||
key: pack-inputs-v1-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env') }}
|
rustup target add --toolchain 1.90.0 aarch64-unknown-linux-gnu
|
||||||
restore-keys: pack-inputs-v1-
|
RUSTUP_TOOLCHAIN=1.90.0 bash tools/comet/build.sh
|
||||||
|
|
||||||
- name: Build the add-on packs
|
- name: Build the add-on packs
|
||||||
run: bash tools/packs/build.sh app/build/packs
|
run: bash tools/packs/build.sh app/build/packs
|
||||||
|
|
||||||
- name: Note when the proot pack pin is behind this build
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
# shellcheck disable=SC1091
|
|
||||||
source tools/packs/proot/release.env
|
|
||||||
sha=$(sha256sum app/build/packs/proot.tar.zst | cut -d' ' -f1)
|
|
||||||
if [ "$sha" != "$PROOT_PACK_SHA256" ]; then
|
|
||||||
echo "::warning::built proot pack $sha does not match tools/packs/proot/release.env ($PROOT_PACK_SHA256). This build publishes the pack it just built. Source builds keep downloading the pinned pack until release.env is updated."
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
id: build
|
id: build
|
||||||
env:
|
env:
|
||||||
@@ -515,6 +549,7 @@ jobs:
|
|||||||
SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }}
|
SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }}
|
||||||
run: |
|
run: |
|
||||||
set -o pipefail
|
set -o pipefail
|
||||||
|
python3 tools/quest/build-driver.py "$ANDROID_HOME/ndk/$NDK_VERSION"
|
||||||
python3 tools/release/runtime_inputs.py record
|
python3 tools/release/runtime_inputs.py record
|
||||||
./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log
|
./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log
|
||||||
python3 tools/release/check_session_assets.py app/build/outputs/apk/release/app-release.apk
|
python3 tools/release/check_session_assets.py app/build/outputs/apk/release/app-release.apk
|
||||||
@@ -545,11 +580,16 @@ jobs:
|
|||||||
path: app/src/main/rust/stores/Cargo.lock
|
path: app/src/main/rust/stores/Cargo.lock
|
||||||
if-no-files-found: ignore
|
if-no-files-found: ignore
|
||||||
|
|
||||||
|
- name: Install Python test dependencies
|
||||||
|
run: |
|
||||||
|
sudo apt-get update -qq
|
||||||
|
sudo apt-get install -y -qq python3-yaml
|
||||||
|
|
||||||
|
- name: Steam import and game environment tests
|
||||||
|
run: python3 -m unittest discover -s tools/tests -p 'test_*.py'
|
||||||
|
|
||||||
- name: Unit tests
|
- name: Unit tests
|
||||||
id: unit-tests
|
id: unit-tests
|
||||||
env:
|
|
||||||
DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }}
|
|
||||||
SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }}
|
|
||||||
run: |
|
run: |
|
||||||
set -o pipefail
|
set -o pipefail
|
||||||
mkdir -p app/build
|
mkdir -p app/build
|
||||||
@@ -624,84 +664,87 @@ jobs:
|
|||||||
UNIT_TEST_OUTCOME: ${{ steps.unit-tests.outcome }}
|
UNIT_TEST_OUTCOME: ${{ steps.unit-tests.outcome }}
|
||||||
TEST_DIAGNOSTICS_URL: ${{ steps.unit-test-diagnostics.outputs.artifact-url }}
|
TEST_DIAGNOSTICS_URL: ${{ steps.unit-test-diagnostics.outputs.artifact-url }}
|
||||||
APK_OUTCOME: ${{ steps.apk-upload.outcome }}
|
APK_OUTCOME: ${{ steps.apk-upload.outcome }}
|
||||||
run: bash tools/release/report-build.sh
|
SAME_REPO: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
|
||||||
|
|
||||||
python-tests:
|
|
||||||
name: Python and native regression tests
|
|
||||||
needs: source
|
|
||||||
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
|
|
||||||
runs-on: ubuntu-24.04
|
|
||||||
timeout-minutes: 15
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
|
||||||
fetch-depth: 0
|
|
||||||
persist-credentials: false
|
|
||||||
- name: Merge the pinned APK base
|
|
||||||
if: github.event_name == 'pull_request'
|
|
||||||
env:
|
|
||||||
BUILD_BASE_SHA: ${{ needs.source.outputs.base-sha }}
|
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -uo pipefail
|
||||||
git fetch --no-tags origin "$BUILD_BASE_SHA"
|
MARK="<!-- droiddeck-pr-build -->"
|
||||||
git config user.name "ci"
|
{
|
||||||
git config user.email "ci@users.noreply.github.com"
|
echo "$MARK"
|
||||||
git merge --no-ff --no-edit FETCH_HEAD
|
echo "## Build of this pull request"
|
||||||
- name: Verify backend and test source match
|
echo
|
||||||
env:
|
[ -f /tmp/pr-merge.md ] && cat /tmp/pr-merge.md
|
||||||
XBOX_SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
|
echo
|
||||||
run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
|
case "$BUILD_OUTCOME:$UNIT_TEST_OUTCOME:$APK_OUTCOME" in
|
||||||
- name: Install Python test dependencies
|
success:success:success)
|
||||||
timeout-minutes: 7
|
echo "### Build passed"
|
||||||
run: bash tools/ci/install-ubuntu-packages.sh python3-yaml gcc-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user libvulkan-dev mesa-vulkan-drivers
|
echo
|
||||||
- name: Resolve the pinned Android NDK
|
echo "The \`droiddeck-apk\` artifact is [on this run]($RUN_URL), signed with the public test key."
|
||||||
run: bash tools/ci/resolve-ndk.sh
|
echo
|
||||||
|
if [ "$SAME_REPO" = true ]; then
|
||||||
- name: Check Quest tracking IPC
|
echo "A release-signed tester build that installs over Stable or Preview is being published now and will appear in DroidDeck's **Test builds** list. Label the PR \`no-test-build\` to skip that."
|
||||||
run: |
|
else
|
||||||
set -euo pipefail
|
echo "**Maintainer:** add the \`publish-test\` label to publish a release-signed tester build that installs over Stable or Preview and appears in DroidDeck's **Test builds** list. The label is removed automatically after publishing."
|
||||||
NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
|
fi
|
||||||
VK_INCLUDE=$(ls -d "$NDK"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1)
|
echo
|
||||||
mkdir -p build/vr/include
|
echo "Fallback: [open **PR Release Publish**]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/workflows/pr-release-publish.yml) on \`main\` and enter PR \`$PR\`."
|
||||||
cp -R "$VK_INCLUDE/vulkan" build/vr/include/
|
;;
|
||||||
if [ -d "$VK_INCLUDE/vk_video" ]; then cp -R "$VK_INCLUDE/vk_video" build/vr/include/; fi
|
success:success:*)
|
||||||
g++ -std=c++17 -Wall -Wextra -Werror -pthread tools/vr/tests/test_xr_tracking.cpp -o /tmp/test-xr-tracking
|
echo "### APK publication incomplete"
|
||||||
/tmp/test-xr-tracking
|
echo
|
||||||
g++ -std=c++17 -Wall -Wextra -Werror tools/vr/tests/test_xr_touch.cpp -o /tmp/test-xr-touch
|
echo "Compilation and unit tests passed, but APK publication did not complete. See [the run]($RUN_URL)."
|
||||||
/tmp/test-xr-touch
|
;;
|
||||||
g++ -std=c++17 -Wall -Wextra -Werror tools/vr/tests/test_pad_controller_config.cpp -o /tmp/test-pad-controller-config
|
success:failure:*)
|
||||||
/tmp/test-pad-controller-config
|
echo "### ERROR: Unit tests failed"
|
||||||
g++ -std=c++17 -Wall -Wextra -Werror -pthread tools/vr/tests/test_xr_vsync.cpp -o /tmp/test-xr-vsync
|
echo
|
||||||
/tmp/test-xr-vsync
|
echo "The APK compiled, but unit tests failed. No installable artifact was published."
|
||||||
g++ -std=c++17 -Wall -Wextra -Werror -pthread tools/vr/tests/test_xr_frames.cpp -o /tmp/test-xr-frames
|
echo
|
||||||
/tmp/test-xr-frames
|
if [ -n "$TEST_DIAGNOSTICS_URL" ]; then
|
||||||
cc -Itools/vr/third_party/wayland -c tools/vr/src/wayland_client_stub.c -o /tmp/test-wayland-stub.o
|
echo "The [unit-test-results]($TEST_DIAGNOSTICS_URL) artifact contains the test log and any generated reports."
|
||||||
cc -Itools/vr/third_party/wayland -c app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c -o /tmp/test-xdg-shell.o
|
else
|
||||||
g++ -std=c++17 -Wall -Wextra -Werror -Wno-unused-parameter -Wno-missing-field-initializers -pthread -Ibuild/vr/include \
|
echo "The test diagnostics upload did not complete. See [the test log]($RUN_URL)."
|
||||||
-Itools/vr/third_party/wayland -Iapp/src/main/cpp/waylandcomp/generated \
|
fi
|
||||||
tools/vr/tests/test_presenter_shutdown.cpp tools/vr/src/presenter.cpp /tmp/test-wayland-stub.o /tmp/test-xdg-shell.o \
|
;;
|
||||||
-ldl -o /tmp/test-presenter-shutdown
|
success:*)
|
||||||
timeout 10 /tmp/test-presenter-shutdown
|
echo "### Build incomplete"
|
||||||
|
echo
|
||||||
- name: Steam import and game environment tests
|
echo "The APK compiled, but unit tests did not complete successfully. See [the run]($RUN_URL)."
|
||||||
run: bash tools/ci/run-python-tests.sh
|
;;
|
||||||
|
failure:*)
|
||||||
checks:
|
echo "### ERROR: Build failed"
|
||||||
name: Compile and test APK
|
echo
|
||||||
needs: [build, python-tests]
|
echo "The compiler's errors ([full log]($RUN_URL)):"
|
||||||
if: ${{ always() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }}
|
echo
|
||||||
runs-on: ubuntu-24.04
|
echo '```'
|
||||||
timeout-minutes: 5
|
{ grep -E '^e: |^w: .*error|error:|CMake Error|fatal error|ninja: error|FAILED|What went wrong|Execution failed for task|Unresolved reference|Type mismatch|Unresolved' /tmp/build.log 2>/dev/null \
|
||||||
steps:
|
| sed -e 's#file:///home/runner/work/[^/]*/[^/]*/##' -e 's#/home/runner/work/[^/]*/[^/]*/##' \
|
||||||
- name: Require compilation and every test job
|
| grep -v '^w: ' | awk '!seen[$0]++' | head -80; } || true
|
||||||
env:
|
echo '```'
|
||||||
BUILD_RESULT: ${{ needs.build.result }}
|
echo
|
||||||
PYTHON_RESULT: ${{ needs.python-tests.result }}
|
echo "<details><summary>What went wrong (Gradle)</summary>"
|
||||||
run: test "$BUILD_RESULT" = success && test "$PYTHON_RESULT" = success
|
echo
|
||||||
|
echo '```'
|
||||||
|
awk '/^\* What went wrong/{p=1} /^\* Try:/{p=0} p{print}' /tmp/build.log 2>/dev/null | head -60
|
||||||
|
echo '```'
|
||||||
|
echo "</details>"
|
||||||
|
;;
|
||||||
|
skipped:*|cancelled:*)
|
||||||
|
echo "### Not built"
|
||||||
|
echo
|
||||||
|
echo "The build did not run (see above, or [the run]($RUN_URL))."
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
echo
|
||||||
|
} > /tmp/pr-report.md
|
||||||
|
cat /tmp/pr-report.md >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
ID=$(gh api "repos/${GITHUB_REPOSITORY}/issues/${PR}/comments" --paginate --jq ".[] | select(.body | startswith(\"$MARK\")) | .id" | head -1 || true)
|
||||||
|
if [ -n "$ID" ]; then
|
||||||
|
gh api -X PATCH "repos/${GITHUB_REPOSITORY}/issues/comments/${ID}" -F body=@/tmp/pr-report.md >/dev/null
|
||||||
|
else
|
||||||
|
gh api -X POST "repos/${GITHUB_REPOSITORY}/issues/${PR}/comments" -F body=@/tmp/pr-report.md >/dev/null
|
||||||
|
fi
|
||||||
|
|
||||||
sign:
|
sign:
|
||||||
needs: [build, checks]
|
needs: build
|
||||||
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
@@ -713,7 +756,7 @@ jobs:
|
|||||||
secrets: inherit
|
secrets: inherit
|
||||||
|
|
||||||
packs:
|
packs:
|
||||||
needs: [build, checks]
|
needs: build
|
||||||
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
@@ -733,10 +776,6 @@ jobs:
|
|||||||
CI_REPO: Droid-Deck/DroidDeck-CI
|
CI_REPO: Droid-Deck/DroidDeck-CI
|
||||||
KEEP: 10
|
KEEP: 10
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
ref: ${{ github.sha }}
|
|
||||||
persist-credentials: false
|
|
||||||
- uses: actions/download-artifact@v4
|
- uses: actions/download-artifact@v4
|
||||||
with:
|
with:
|
||||||
pattern: droiddeck-signed-*
|
pattern: droiddeck-signed-*
|
||||||
@@ -754,13 +793,72 @@ jobs:
|
|||||||
- name: Describe the change
|
- name: Describe the change
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ github.token }}
|
GH_TOKEN: ${{ github.token }}
|
||||||
run: bash tools/release/describe-build.sh
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
pr=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA/pulls" \
|
||||||
|
--jq '[.[] | select(.merged_at != null and .base.ref == "main")] | first // empty')
|
||||||
|
if [ -n "$pr" ]; then
|
||||||
|
number=$(jq -r .number <<<"$pr")
|
||||||
|
title=$(jq -r .title <<<"$pr")
|
||||||
|
merged=$(jq -r '.merged_at[:10]' <<<"$pr")
|
||||||
|
summary=$(jq -r '.body // ""' <<<"$pr" | tr -d '\r' | { grep -v '^🤖' || true; } |
|
||||||
|
awk '!p && /^#/ { next } NF { p = 1; print; next } p { exit }' | head -n 6 | cut -c1-400)
|
||||||
|
{
|
||||||
|
echo "**Merged to main** - [PR #$number]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/pull/$number): $title (merged $merged)"
|
||||||
|
if [ -n "$summary" ]; then
|
||||||
|
echo
|
||||||
|
echo "$summary"
|
||||||
|
fi
|
||||||
|
} > notes-head.md
|
||||||
|
else
|
||||||
|
subject=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA" --jq '.commit.message | split("\n")[0]')
|
||||||
|
echo "**Pushed to main** without a PR - $subject" > notes-head.md
|
||||||
|
fi
|
||||||
|
cat notes-head.md
|
||||||
|
|
||||||
- name: Publish to DroidDeck-CI
|
- name: Publish to DroidDeck-CI
|
||||||
id: publish
|
id: publish
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ steps.ci-token.outputs.token }}
|
GH_TOKEN: ${{ steps.ci-token.outputs.token }}
|
||||||
run: bash tools/release/publish-ci.sh
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
tag=main-${GITHUB_SHA::7}
|
||||||
|
cat signed/SHA256SUMS-*.txt > signed/SHA256SUMS.txt
|
||||||
|
rm signed/SHA256SUMS-*.txt
|
||||||
|
notes="$(cat notes-head.md)
|
||||||
|
|
||||||
|
Signed build of $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/commit/$GITHUB_SHA - in main, not yet in a DroidDeck release; for testing.
|
||||||
|
Commit: $GITHUB_SHA
|
||||||
|
VersionCode: $(sed -n 's/^ *versionCode \([0-9][0-9]*\)$/\1/p' app/build.gradle)
|
||||||
|
Each apk installs over a DroidDeck release and keeps its data. \`standard\` is the normal app; the others are the same app under another package name, installed beside it.
|
||||||
|
|
||||||
|
SHA-256:
|
||||||
|
\`\`\`
|
||||||
|
$(cat signed/SHA256SUMS.txt)
|
||||||
|
\`\`\`"
|
||||||
|
gh release delete "$tag" -R "$CI_REPO" --yes --cleanup-tag 2>/dev/null || true
|
||||||
|
gh release create "$tag" -R "$CI_REPO" --target main --prerelease \
|
||||||
|
--title "main ${GITHUB_SHA::7}" --notes "$notes" signed/*
|
||||||
|
gh release list -R "$CI_REPO" -L 200 --json tagName,publishedAt \
|
||||||
|
--jq '[.[] | select(.tagName | startswith("main-"))] | sort_by(.publishedAt) | reverse | .['"$KEEP"':][] | .tagName' |
|
||||||
|
while IFS= read -r old; do
|
||||||
|
if [ "$old" = "$tag" ]; then
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
if ! gh release delete "$old" -R "$CI_REPO" --yes --cleanup-tag 2>/dev/null; then
|
||||||
|
if gh release view "$old" -R "$CI_REPO" >/dev/null 2>&1; then
|
||||||
|
echo "::error::Could not delete old release $old"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
published=$(gh release view "$tag" -R "$CI_REPO" --json tagName,assets)
|
||||||
|
jq -e --arg tag "$tag" '.tagName == $tag and (.assets | length) > 0' <<< "$published" >/dev/null
|
||||||
|
url="$GITHUB_SERVER_URL/$CI_REPO/releases/tag/$tag"
|
||||||
|
apk=$(cd signed && ls DroidDeck-*.apk | awk 'length(a) == 0 || length($0) < length(a) { a = $0 } END { print a }')
|
||||||
|
echo "release=$url" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "apk=$GITHUB_SERVER_URL/$CI_REPO/releases/download/$tag/$apk" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "Published $url"
|
||||||
|
|
||||||
- name: Post the Preview build to Discord
|
- name: Post the Preview build to Discord
|
||||||
env:
|
env:
|
||||||
@@ -768,8 +866,26 @@ jobs:
|
|||||||
GH_TOKEN: ${{ github.token }}
|
GH_TOKEN: ${{ github.token }}
|
||||||
RELEASE: ${{ steps.publish.outputs.release }}
|
RELEASE: ${{ steps.publish.outputs.release }}
|
||||||
APK: ${{ steps.publish.outputs.apk }}
|
APK: ${{ steps.publish.outputs.apk }}
|
||||||
run: bash tools/release/announce-preview.sh
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [ -z "$WEBHOOK" ]; then
|
||||||
|
echo "::notice::No DISCORD_BUILDS_WEBHOOK secret; nothing posted"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
commit=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA")
|
||||||
|
subject=$(jq -r '.commit.message | split("\n")[0]' <<<"$commit")
|
||||||
|
title=$(jq -r '.commit.message | split("\n") | map(select(length > 0)) | .[1] // ""' <<<"$commit")
|
||||||
|
pr=$(sed -n 's/^Merge pull request #\([0-9]*\).*/\1/p' <<<"$subject")
|
||||||
|
if [ -n "$pr" ]; then
|
||||||
|
what="[#$pr]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/pull/$pr): ${title:-$subject}"
|
||||||
|
else
|
||||||
|
what="[\`${GITHUB_SHA::7}\`]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/commit/$GITHUB_SHA): $subject"
|
||||||
|
fi
|
||||||
|
get=$(printf 'Download: [standard APK](<%s>) · [all variants](<%s>)' "$APK" "$RELEASE")
|
||||||
|
content=$(printf '**New signed Preview build** `main-%s`\n%s\nIn the app: **Updates → Preview**\n%s' "${GITHUB_SHA::7}" "$what" "$get")
|
||||||
|
jq -n --arg content "$content" '{content: $content, allowed_mentions: {parse: []}}' |
|
||||||
|
curl -fsS -H 'Content-Type: application/json' -d @- "$WEBHOOK" -o /dev/null
|
||||||
|
echo "Posted: $content"
|
||||||
|
|
||||||
catalog:
|
catalog:
|
||||||
needs: announce
|
needs: announce
|
||||||
|
|||||||
@@ -8,10 +8,6 @@ on:
|
|||||||
description: Open pull request number
|
description: Open pull request number
|
||||||
required: true
|
required: true
|
||||||
type: string
|
type: string
|
||||||
automatic_build_run_id:
|
|
||||||
description: Completed build run for automatic publishing
|
|
||||||
required: false
|
|
||||||
type: string
|
|
||||||
pull_request_target:
|
pull_request_target:
|
||||||
types: [labeled]
|
types: [labeled]
|
||||||
branches: [main]
|
branches: [main]
|
||||||
@@ -31,47 +27,16 @@ concurrency:
|
|||||||
queue: max
|
queue: max
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
dispatch-fork-builds:
|
|
||||||
if: >-
|
|
||||||
github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' &&
|
|
||||||
github.event.workflow_run.conclusion == 'success' &&
|
|
||||||
github.event.workflow_run.head_repository.full_name != github.repository
|
|
||||||
runs-on: ubuntu-24.04
|
|
||||||
timeout-minutes: 5
|
|
||||||
permissions:
|
|
||||||
actions: write
|
|
||||||
pull-requests: read
|
|
||||||
steps:
|
|
||||||
- name: Find fork PRs for the completed build
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ github.token }}
|
|
||||||
RUN_ID: ${{ github.event.workflow_run.id }}
|
|
||||||
RUN_SHA: ${{ github.event.workflow_run.head_sha }}
|
|
||||||
RUN_REPO: ${{ github.event.workflow_run.head_repository.full_name }}
|
|
||||||
RUN_BRANCH: ${{ github.event.workflow_run.head_branch }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
owner=${RUN_REPO%%/*}
|
|
||||||
gh api --paginate --slurp -X GET "repos/$GITHUB_REPOSITORY/pulls" \
|
|
||||||
-f state=open -f base=main -f "head=$owner:$RUN_BRANCH" -f per_page=100 |
|
|
||||||
jq -r --arg sha "$RUN_SHA" --arg repo "$RUN_REPO" --arg branch "$RUN_BRANCH" '
|
|
||||||
.[][] | select(.head.sha == $sha and .head.repo.full_name == $repo and .head.ref == $branch) | .number' |
|
|
||||||
while IFS= read -r number; do
|
|
||||||
gh workflow run pr-release-publish.yml -R "$GITHUB_REPOSITORY" --ref main \
|
|
||||||
-f "pr_number=$number" -f "automatic_build_run_id=$RUN_ID"
|
|
||||||
done
|
|
||||||
|
|
||||||
authorize:
|
authorize:
|
||||||
if: >-
|
if: >-
|
||||||
(github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') ||
|
(github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') ||
|
||||||
(github.event_name == 'pull_request_target' &&
|
(github.event_name == 'pull_request_target' && github.event.label.name == 'publish-test') ||
|
||||||
(github.event.action != 'labeled' || github.event.label.name == 'publish-test')) ||
|
|
||||||
(github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' &&
|
(github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' &&
|
||||||
github.event.workflow_run.conclusion == 'success' &&
|
github.event.workflow_run.conclusion == 'success' &&
|
||||||
github.event.workflow_run.head_repository.full_name == github.repository &&
|
github.event.workflow_run.head_repository.full_name == github.repository &&
|
||||||
github.event.workflow_run.pull_requests[0] != null)
|
github.event.workflow_run.pull_requests[0] != null)
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
timeout-minutes: 150
|
timeout-minutes: 45
|
||||||
outputs:
|
outputs:
|
||||||
pr_number: ${{ steps.gate.outputs.pr_number }}
|
pr_number: ${{ steps.gate.outputs.pr_number }}
|
||||||
run_id: ${{ steps.gate.outputs.run_id }}
|
run_id: ${{ steps.gate.outputs.run_id }}
|
||||||
@@ -85,7 +50,6 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: The packages a signed build ships as
|
- name: The packages a signed build ships as
|
||||||
id: variants
|
id: variants
|
||||||
@@ -97,14 +61,22 @@ jobs:
|
|||||||
EVENT_NAME: ${{ github.event_name }}
|
EVENT_NAME: ${{ github.event_name }}
|
||||||
REQUESTER: ${{ github.actor }}
|
REQUESTER: ${{ github.actor }}
|
||||||
PR_NUMBER: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'workflow_run' && github.event.workflow_run.pull_requests[0].number || inputs.pr_number }}
|
PR_NUMBER: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'workflow_run' && github.event.workflow_run.pull_requests[0].number || inputs.pr_number }}
|
||||||
ACTION: ${{ github.event.action }}
|
|
||||||
BUILT_SHA: ${{ github.event.workflow_run.head_sha }}
|
BUILT_SHA: ${{ github.event.workflow_run.head_sha }}
|
||||||
AUTO_RUN: ${{ inputs.automatic_build_run_id }}
|
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
[[ "$PR_NUMBER" =~ ^[1-9][0-9]*$ ]] || { echo "::error::Invalid PR number '$PR_NUMBER'"; exit 1; }
|
[[ "$PR_NUMBER" =~ ^[1-9][0-9]*$ ]] || { echo "::error::Invalid PR number '$PR_NUMBER'"; exit 1; }
|
||||||
skip() { echo "::notice::Not publishing PR #$PR_NUMBER: $1"; echo "skip=true" >> "$GITHUB_OUTPUT"; exit 0; }
|
skip() { echo "::notice::Not publishing PR #$PR_NUMBER: $1"; echo "skip=true" >> "$GITHUB_OUTPUT"; exit 0; }
|
||||||
if [ "$EVENT_NAME" = pull_request_target ] && [ "$ACTION" = labeled ]; then
|
if [ "$EVENT_NAME" = workflow_run ]; then
|
||||||
|
echo "automatic=true" >> "$GITHUB_OUTPUT"
|
||||||
|
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
|
||||||
|
[ "$(jq -r .state <<<"$pr")" = open ] || skip "it is not open"
|
||||||
|
[ "$(jq -r .draft <<<"$pr")" = false ] || skip "it is a draft"
|
||||||
|
[ "$(jq -r .base.ref <<<"$pr")" = main ] || skip "it does not target main"
|
||||||
|
[ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] || skip "it comes from a fork"
|
||||||
|
jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build"
|
||||||
|
[ "$(jq -r .head.sha <<<"$pr")" = "$BUILT_SHA" ] || skip "a newer push is building"
|
||||||
|
fi
|
||||||
|
if [ "$EVENT_NAME" = pull_request_target ]; then
|
||||||
permission=$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$REQUESTER/permission" --jq .permission)
|
permission=$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$REQUESTER/permission" --jq .permission)
|
||||||
case "$permission" in
|
case "$permission" in
|
||||||
admin|maintain|write) ;;
|
admin|maintain|write) ;;
|
||||||
@@ -113,59 +85,29 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
|
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
|
||||||
jq -e '.state == "open" and .draft == false and .base.ref == "main"' <<<"$pr" >/dev/null ||
|
jq -e '.state == "open" and .draft == false and .base.ref == "main"' <<<"$pr" >/dev/null ||
|
||||||
skip "it must be open, ready for review, and target main"
|
{ echo "::error::PR #$PR_NUMBER must be open, ready for review, and target main"; exit 1; }
|
||||||
if [ "$EVENT_NAME" = workflow_run ]; then
|
|
||||||
[ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] || skip "it comes from a fork"
|
|
||||||
[ "$(jq -r .head.sha <<<"$pr")" = "$BUILT_SHA" ] || skip "a newer push is building"
|
|
||||||
jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build"
|
|
||||||
echo "automatic=true" >> "$GITHUB_OUTPUT"
|
|
||||||
elif [ "$EVENT_NAME" = workflow_dispatch ] && [ -n "$AUTO_RUN" ]; then
|
|
||||||
[[ "$AUTO_RUN" =~ ^[1-9][0-9]*$ ]] || { echo '::error::Invalid automatic build run ID'; exit 1; }
|
|
||||||
jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build"
|
|
||||||
git fetch --no-tags origin main
|
|
||||||
opener=$(jq -r .user.login <<<"$pr")
|
|
||||||
git show origin/main:.github/trusted-test-builds.txt | grep -Fixq -- "$opener" || skip "PR opener @$opener is not trusted for automatic signing"
|
|
||||||
echo "automatic=true" >> "$GITHUB_OUTPUT"
|
|
||||||
fi
|
|
||||||
head=$(jq -r '.head.sha' <<<"$pr")
|
head=$(jq -r '.head.sha' <<<"$pr")
|
||||||
base=$(jq -r '.base.sha' <<<"$pr")
|
base=$(jq -r '.base.sha' <<<"$pr")
|
||||||
|
|
||||||
run_id=
|
run_id=
|
||||||
for attempt in $(seq 1 240); do
|
for attempt in $(seq 1 60); do
|
||||||
latest=$(gh api "repos/$GITHUB_REPOSITORY/actions/workflows/build.yml/runs?event=pull_request&head_sha=$head&per_page=100" |
|
latest=$(gh run list -R "$GITHUB_REPOSITORY" --workflow build.yml \
|
||||||
jq -c --arg head "$head" --arg repo "$(jq -r .head.repo.full_name <<<"$pr")" --arg ref "$(jq -r .head.ref <<<"$pr")" '
|
--event pull_request --commit "$head" \
|
||||||
[.workflow_runs[] | select(.head_sha == $head and .head_repository.full_name == $repo and .head_branch == $ref)] |
|
--json databaseId,headSha,status,conclusion,createdAt,attempt -L 100 |
|
||||||
sort_by([.created_at, .run_attempt]) | last // empty')
|
jq -c --arg head "$head" '[.[] | select(.headSha == $head)] |
|
||||||
if [[ -z "$latest" && "$attempt" == 1 ]]; then
|
sort_by([.createdAt, .attempt]) | last // empty')
|
||||||
git fetch --no-tags origin main
|
|
||||||
git fetch --no-tags origin "refs/pull/$PR_NUMBER/head"
|
|
||||||
git diff --no-renames --name-only -z "$base...FETCH_HEAD" > "$RUNNER_TEMP/pr-changed-paths"
|
|
||||||
excluded=true
|
|
||||||
while IFS= read -r -d '' path; do
|
|
||||||
case "$path" in
|
|
||||||
*.md|LICENSE|.gitignore) ;;
|
|
||||||
*) excluded=false; break ;;
|
|
||||||
esac
|
|
||||||
done < "$RUNNER_TEMP/pr-changed-paths"
|
|
||||||
[ "$excluded" = false ] || skip "its changes do not trigger the APK build"
|
|
||||||
fi
|
|
||||||
if [[ -n "$latest" && $(jq -r .status <<<"$latest") == completed ]]; then
|
if [[ -n "$latest" && $(jq -r .status <<<"$latest") == completed ]]; then
|
||||||
conclusion=$(jq -r .conclusion <<<"$latest")
|
conclusion=$(jq -r .conclusion <<<"$latest")
|
||||||
if [[ "$conclusion" == success ]]; then
|
[[ "$conclusion" == success ]] || { echo "::error::The latest PR build is not green ($conclusion)"; exit 1; }
|
||||||
run_id=$(jq -r .id <<<"$latest")
|
run_id=$(jq -r .databaseId <<<"$latest")
|
||||||
if [ -n "$AUTO_RUN" ] && [ "$run_id" != "$AUTO_RUN" ]; then
|
break
|
||||||
skip "a newer build exists"
|
|
||||||
fi
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
[[ "$conclusion" == action_required ]] || { echo "::error::The latest PR build is not green ($conclusion)"; exit 1; }
|
|
||||||
fi
|
fi
|
||||||
status=not-started
|
status=not-started
|
||||||
[[ -z "$latest" ]] || status=$(jq -r .status <<<"$latest")
|
[[ -z "$latest" ]] || status=$(jq -r .status <<<"$latest")
|
||||||
echo "Waiting for the PR build of ${head:0:7} to finish ($status)"
|
echo "Waiting for the PR build of ${head:0:7} to finish ($status)"
|
||||||
sleep 30
|
sleep 30
|
||||||
done
|
done
|
||||||
[[ -n "$run_id" ]] || { echo '::error::The PR build did not finish within 120 minutes'; exit 1; }
|
[[ -n "$run_id" ]] || { echo '::error::The PR build did not finish within 30 minutes'; exit 1; }
|
||||||
run=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id")
|
run=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id")
|
||||||
jq -e --arg head "$head" --arg repo "$(jq -r .head.repo.full_name <<<"$pr")" --arg ref "$(jq -r .head.ref <<<"$pr")" '
|
jq -e --arg head "$head" --arg repo "$(jq -r .head.repo.full_name <<<"$pr")" --arg ref "$(jq -r .head.ref <<<"$pr")" '
|
||||||
.event == "pull_request" and .head_sha == $head and .conclusion == "success" and
|
.event == "pull_request" and .head_sha == $head and .conclusion == "success" and
|
||||||
@@ -195,13 +137,6 @@ jobs:
|
|||||||
.head.sha == $head and .base.sha == $base
|
.head.sha == $head and .base.sha == $base
|
||||||
' <<<"$current" >/dev/null ||
|
' <<<"$current" >/dev/null ||
|
||||||
{ echo "::error::PR #$PR_NUMBER moved on while its build was checked; publish again"; exit 1; }
|
{ echo "::error::PR #$PR_NUMBER moved on while its build was checked; publish again"; exit 1; }
|
||||||
if [ "$EVENT_NAME" = workflow_run ] || { [ "$EVENT_NAME" = workflow_dispatch ] && [ -n "$AUTO_RUN" ]; }; then
|
|
||||||
jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$current" >/dev/null && skip "it is labelled no-test-build"
|
|
||||||
if [ "$EVENT_NAME" = workflow_dispatch ]; then
|
|
||||||
git fetch --no-tags origin main
|
|
||||||
git show origin/main:.github/trusted-test-builds.txt | grep -Fixq -- "$(jq -r .user.login <<<"$current")" || skip "the PR opener is no longer trusted"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
{
|
{
|
||||||
echo "pr_number=$PR_NUMBER"
|
echo "pr_number=$PR_NUMBER"
|
||||||
echo "run_id=$run_id"
|
echo "run_id=$run_id"
|
||||||
@@ -336,24 +271,17 @@ jobs:
|
|||||||
echo "release=$release" >> "$GITHUB_OUTPUT"
|
echo "release=$release" >> "$GITHUB_OUTPUT"
|
||||||
echo "apk=$GITHUB_SERVER_URL/$repo/releases/download/$tag/$apk" >> "$GITHUB_OUTPUT"
|
echo "apk=$GITHUB_SERVER_URL/$repo/releases/download/$tag/$apk" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
- name: Whether the PR opener is trusted
|
- name: Whether the PR's branch is in this repo
|
||||||
id: trusted-opener
|
id: same-repo
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ github.token }}
|
GH_TOKEN: ${{ github.token }}
|
||||||
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
|
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
|
||||||
run: |
|
run: |
|
||||||
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
|
head_repo=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq .head.repo.full_name)
|
||||||
opener=$(jq -r .user.login <<<"$pr")
|
echo "same=$([ "$head_repo" = "$GITHUB_REPOSITORY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
|
||||||
git fetch --no-tags origin main
|
|
||||||
if [ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] ||
|
|
||||||
git show origin/main:.github/trusted-test-builds.txt | grep -Fixq -- "$opener"; then
|
|
||||||
echo "trusted=true" >> "$GITHUB_OUTPUT"
|
|
||||||
else
|
|
||||||
echo "trusted=false" >> "$GITHUB_OUTPUT"
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Clear the publish request label
|
- name: Clear the publish request label
|
||||||
if: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && steps.publish.outcome == 'success' }}
|
if: ${{ github.event_name == 'pull_request_target' && steps.publish.outcome == 'success' }}
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ github.token }}
|
GH_TOKEN: ${{ github.token }}
|
||||||
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
|
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
|
||||||
@@ -367,12 +295,12 @@ jobs:
|
|||||||
HEAD_SHA: ${{ needs.authorize.outputs.head_sha }}
|
HEAD_SHA: ${{ needs.authorize.outputs.head_sha }}
|
||||||
RELEASE: ${{ steps.publish.outputs.release }}
|
RELEASE: ${{ steps.publish.outputs.release }}
|
||||||
APK: ${{ steps.publish.outputs.apk }}
|
APK: ${{ steps.publish.outputs.apk }}
|
||||||
TRUSTED_OPENER: ${{ steps.trusted-opener.outputs.trusted }}
|
SAME_REPO: ${{ steps.same-repo.outputs.same }}
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
short=${HEAD_SHA:0:7}
|
short=${HEAD_SHA:0:7}
|
||||||
mark='<!-- droiddeck-pr-release -->'
|
mark='<!-- droiddeck-pr-release -->'
|
||||||
if [ "$TRUSTED_OPENER" = true ]; then
|
if [ "$SAME_REPO" = true ]; then
|
||||||
NEXT='Each green build of a new push is signed and published here on its own. Label the PR `no-test-build` to stop that.'
|
NEXT='Each green build of a new push is signed and published here on its own. Label the PR `no-test-build` to stop that.'
|
||||||
else
|
else
|
||||||
NEXT='Pushes to this PR do not re-sign automatically. After a new green build, a maintainer can add the `publish-test` label again.'
|
NEXT='Pushes to this PR do not re-sign automatically. After a new green build, a maintainer can add the `publish-test` label again.'
|
||||||
|
|||||||
@@ -9,20 +9,6 @@ DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big
|
|||||||
|
|
||||||
<p align="center"><a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20the%20community-5865F2?logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a></p>
|
<p align="center"><a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20the%20community-5865F2?logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a></p>
|
||||||
|
|
||||||
<p align="center">
|
|
||||||
<a href="https://www.star-history.com/droid-deck/droiddeck"><img src="https://api.star-history.com/badge?repo=Droid-Deck/DroidDeck&type=rank&theme=dark" alt="Star History Rank" /></a>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<p align="center">
|
|
||||||
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=C" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
|
|
||||||
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=Kotlin" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<p align="center">
|
|
||||||
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/weekly?language=C" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
|
|
||||||
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/weekly?language=Kotlin" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<p align="center"><img src="docs/releases/media/0.2.0/launch-into-steam.gif" width="80%" alt="Tapping DroidDeck on the Android home screen and landing in Steam Big Picture"></p>
|
<p align="center"><img src="docs/releases/media/0.2.0/launch-into-steam.gif" width="80%" alt="Tapping DroidDeck on the Android home screen and landing in Steam Big Picture"></p>
|
||||||
|
|
||||||
> Note: DroidDeck does not have a stand-alone website. Do not click on any download links from websites claiming to be the DroidDeck team.
|
> Note: DroidDeck does not have a stand-alone website. Do not click on any download links from websites claiming to be the DroidDeck team.
|
||||||
@@ -35,7 +21,7 @@ On Android 14 and newer, before Steam launches, you must turn on **Disable child
|
|||||||
|
|
||||||
## Smart glasses
|
## Smart glasses
|
||||||
|
|
||||||
Use **Setup → Smart glasses** for app-wide virtual-screen settings across DroidDeck menus, launchers, desktop sessions, and games. Supported VITURE, RayNeo, XREAL, and Rokid connections provide 3DoF; Luma Ultra adds optional experimental 6DoF and stereo-assisted hand/Joy-Con tracking. Model support and SDK requirements differ: see the [smart-glasses support matrix](docs/smart-glasses-support.md) for supported devices, controls, setup, and limitations.
|
Use **Setup → Smart glasses** for app-wide virtual-screen settings across DroidDeck menus, launchers, desktop sessions, and games. Supported VITURE, RayNeo, and XREAL connections provide 3DoF; Luma Ultra adds optional experimental 6DoF and stereo-assisted hand/Joy-Con tracking. Model support and SDK requirements differ: see the [smart-glasses support matrix](docs/smart-glasses-support.md) for supported devices, controls, setup, and limitations.
|
||||||
|
|
||||||
## Community
|
## Community
|
||||||
|
|
||||||
@@ -61,18 +47,12 @@ Compatibility and performance vary by device; hardware validation is limited. De
|
|||||||
|
|
||||||
## Credits and licence
|
## Credits and licence
|
||||||
|
|
||||||
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. Battle.net support is [@kayakyakr](https://github.com/kayakyakr)'s: it runs Blizzard's own Battle.net client, downloaded from Blizzard and not included, in Proton, and shows the key art from each game's [Battle.net Shop](https://shop.battle.net) page; without the Steam client its games see DroidDeck's pad as an Xbox 360 controller through `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. Its games install from Stores through Blizzard's own Agent and the local HTTP API it serves, driven the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) drives it, with the requests described on [wowdev.wiki](https://wowdev.wiki/Agent); how other launchers find, install and start Blizzard games was read in [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader, without taking their code. The registry entries a GOG game's install script (`goggame-<id>.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. x86 AppImages packed with [sharun](https://github.com/VHSgunzo/sharun) by VHSgunzo (MIT) start because DroidDeck's own [FEX](https://github.com/FEX-Emu/FEX) build (MIT) puts the platform name under `AT_PLATFORM`, which sharun's [userland-execve](https://crates.io/crates/userland-execve) loader (MIT) requires; FEX filed it under `AT_BASE_PLATFORM`. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<pid>/mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultLine truncated
|
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. The registry entries a GOG game's install script (`goggame-<id>.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<pid>/mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve.
|
||||||
|
|
||||||
XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). Rokid support follows the Rokid protocol notes in [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) and @badicsalex's [Void Computing write-ups](https://voidcomputing.hu/blog/worse-better-prettier/), and [Monado](https://gitlab.freedesktop.org/monado/monado)'s Rokid driver. The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL, Rokid and REDMAGIC are trademarks of their owners; this project is not affiliated with them.
|
XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL and REDMAGIC are trademarks of their owners; this project is not affiliated with them.
|
||||||
|
|
||||||
Joy-Con VR controllers port the arm model of Google's [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk) (Apache-2.0), adapt the hand skeleton of Valve's [OpenVR](https://github.com/ValveSoftware/openvr) `handskeletonsimulation` sample (BSD-3-Clause), which follows Moshi Turner's hand simulation in [Monado](https://gitlab.freedesktop.org/monado/monado), and use the Index controller offsets from Monado's `vive_poses.c` (BSL-1.0). Joy-Con behaviour was researched in Linux's [hid-nintendo](https://github.com/torvalds/linux/blob/master/drivers/hid/hid-nintendo.c) driver by Daniel J. Ogorchock, [@dekuNukem](https://github.com/dekuNukem)'s [Nintendo_Switch_Reverse_Engineering](https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering), [SDL](https://github.com/libsdl-org/SDL) and the Android Open Source Project, and checked against [ALVR](https://github.com/alvr-org/ALVR), [OpenComposite](https://gitlab.com/znixian/OpenOVR), [PSMoveSteamVRBridge](https://github.com/HipsterSloth/PSMoveSteamVRBridge), [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr), [@krnelpan1c](https://github.com/krnelpan1c)'s [Daydream-Controller-SteamVR](https://github.com/krnelpan1c/Daydream-Controller-SteamVR), [@yoyobuae](https://github.com/yoyobuae)'s [joyconvr](https://github.com/yoyobuae/joyconvr), [Moonlight](https://github.com/moonlight-stream/moonlight-android) and [Dolphin](https://github.com/dolphin-emu/dolphin); see [docs/third-party/joycon](docs/third-party/joycon/README.md). Nintendo Switch and Joy-Con are trademarks of Nintendo; this project is not affiliated with Nintendo.
|
Joy-Con VR controllers port the arm model of Google's [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk) (Apache-2.0), adapt the hand skeleton of Valve's [OpenVR](https://github.com/ValveSoftware/openvr) `handskeletonsimulation` sample (BSD-3-Clause), which follows Moshi Turner's hand simulation in [Monado](https://gitlab.freedesktop.org/monado/monado), and use the Index controller offsets from Monado's `vive_poses.c` (BSL-1.0). Joy-Con behaviour was researched in Linux's [hid-nintendo](https://github.com/torvalds/linux/blob/master/drivers/hid/hid-nintendo.c) driver by Daniel J. Ogorchock, [@dekuNukem](https://github.com/dekuNukem)'s [Nintendo_Switch_Reverse_Engineering](https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering), [SDL](https://github.com/libsdl-org/SDL) and the Android Open Source Project, and checked against [ALVR](https://github.com/alvr-org/ALVR), [OpenComposite](https://gitlab.com/znixian/OpenOVR), [PSMoveSteamVRBridge](https://github.com/HipsterSloth/PSMoveSteamVRBridge), [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr), [@krnelpan1c](https://github.com/krnelpan1c)'s [Daydream-Controller-SteamVR](https://github.com/krnelpan1c/Daydream-Controller-SteamVR), [@yoyobuae](https://github.com/yoyobuae)'s [joyconvr](https://github.com/yoyobuae/joyconvr), [Moonlight](https://github.com/moonlight-stream/moonlight-android) and [Dolphin](https://github.com/dolphin-emu/dolphin); see [docs/third-party/joycon](docs/third-party/joycon/README.md). Nintendo Switch and Joy-Con are trademarks of Nintendo; this project is not affiliated with Nintendo.
|
||||||
|
|
||||||
Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge/mediapipe) Tasks Vision library with its Pose Landmarker (Lite) model, BlazePose GHUM 3D, and its Hand Landmarker model (all Apache-2.0), on frames from AndroidX [CameraX](https://developer.android.com/jetpack/androidx/releases/camera) (Apache-2.0); MediaPipe's usage reports are switched off. The design was checked against [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr) camera app (MIT), and the short Joy-Con movements follow the accelerometer mode of the [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk)'s arm model, Eric Foxlin's zero-velocity updates and Frosio, Pedersini and Borghese's accelerometer autocalibration, and the camera and Joy-Con are joined by a Kalman filter (R. E. Kalman, 1960). Bare camera hands take their gestures after [ALVR](https://github.com/alvr-org/ALVR)'s `hand_gestures.rs` (MIT) and Meta Quest's menu pinch, with distances checked on photos from the [HaGRID](https://github.com/hukenovs/hagrid) gesture set (CC BY-SA 4.0, not included), fit the palm with Horn's quaternion method (1987) and smooth it with the 1€ filter (Casiez, Roussel and Vogel, 2012); the white glove model follows Valve's OpenVR render model reference and Index controller poses, is meshed with surface nets (Gibson, 1998; Mikola Lysenko) and blends and shades it with Inigo Quilez's smooth minimum and distance-field ambient occlusion, porting his polygon distance (MIT); see [docs/third-party/handtracking](docs/third-party/handtracking/README.md).
|
Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge/mediapipe) Tasks Vision library with its Pose Landmarker (Lite) model, BlazePose GHUM 3D, and its Hand Landmarker model (all Apache-2.0), on frames from AndroidX [CameraX](https://developer.android.com/jetpack/androidx/releases/camera) (Apache-2.0); MediaPipe's usage reports are switched off. The design was checked against [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr) camera app (MIT), and the short Joy-Con movements follow the accelerometer mode of the [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk)'s arm model, Eric Foxlin's zero-velocity updates and Frosio, Pedersini and Borghese's accelerometer autocalibration, and the camera and Joy-Con are joined by a Kalman filter (R. E. Kalman, 1960). Bare camera hands take their gestures after [ALVR](https://github.com/alvr-org/ALVR)'s `hand_gestures.rs` (MIT) and Meta Quest's menu pinch, with distances checked on photos from the [HaGRID](https://github.com/hukenovs/hagrid) gesture set (CC BY-SA 4.0, not included), fit the palm with Horn's quaternion method (1987) and smooth it with the 1€ filter (Casiez, Roussel and Vogel, 2012); the white glove model follows Valve's OpenVR render model reference and Index controller poses, is meshed with surface nets (Gibson, 1998; Mikola Lysenko) and blends and shades it with Inigo Quilez's smooth minimum and distance-field ambient occlusion, porting his polygon distance (MIT); see [docs/third-party/handtracking](docs/third-party/handtracking/README.md).
|
||||||
|
|
||||||
The Store installs and runs apps with [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1). Its sandbox goes through DroidDeck's own bubblewrap shim, which follows how Flatpak hands bwrap its environment. Chromium and Electron apps from Flathub start their browser processes through [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause); its source was read to see that it always spawns them through Flatpak's spawn portal, which is why DroidDeck starts them directly without Chromium's sandbox instead.
|
The Store installs and runs apps with [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1). Its sandbox goes through DroidDeck's own bubblewrap shim, which follows how Flatpak hands bwrap its environment.
|
||||||
|
|
||||||
Remote Play from a PC to the arm64 Steam client goes through a stand-in for the V4L2 decoder and the libdrm dumb buffers that Steam's `streaming_client` expects: each frame is decoded by Android's MediaCodec through the app, or by the [FFmpeg](https://ffmpeg.org) (LGPL-2.1-or-later) that ships in Steam's own runtime, into dma-heap buffers that its Vulkan renderer imports. The Qualcomm low-latency decoder settings follow [Moonlight](https://github.com/moonlight-stream/moonlight-android) (GPL-3.0).
|
|
||||||
|
|
||||||
Steam's Browse buttons open a GTK 3 file chooser through PyGObject (LGPL-2.1-or-later). It runs under Steam's own `reaper` with Steam's app ID, which [gamescope](https://github.com/ValveSoftware/gamescope) (BSD-2-Clause) reads from the process tree (`GetAppIdFromReaper` in `src/Utils/Process.cpp`) to show it over Steam.
|
|
||||||
|
|
||||||
Black Ops III and Dark Souls Remastered start without [umu-protonfixes](https://github.com/Open-Wine-Components/umu-protonfixes) (BSD-2-Clause), whose fixes for them (`311210.py` sets ALSA audio, `570940.py` installs VC++ 2017) fail under ARM64 Proton.
|
|
||||||
+3
-18
@@ -80,25 +80,17 @@ def sourceCommit = providers.environmentVariable('DROIDDECK_SOURCE_COMMIT').getO
|
|||||||
def prNumber = (providers.environmentVariable('DROIDDECK_PR_NUMBER').getOrNull() ?: '0').with { it.isInteger() ? it : '0' }
|
def prNumber = (providers.environmentVariable('DROIDDECK_PR_NUMBER').getOrNull() ?: '0').with { it.isInteger() ? it : '0' }
|
||||||
def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true'
|
def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true'
|
||||||
def releaseSigner = rootProject.file('keystore/release-signer.sha256').text.trim()
|
def releaseSigner = rootProject.file('keystore/release-signer.sha256').text.trim()
|
||||||
def commitTime = (gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit]) ?: '0').with { it.isLong() ? it : '0' }
|
def commitTime = (gitValue(['show', '-s', '--format=%ct', 'HEAD']) ?: '0').with { it.isLong() ? it : '0' }
|
||||||
def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines()
|
def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines()
|
||||||
.findAll { it.contains('=') && !it.startsWith('#') }
|
.findAll { it.contains('=') && !it.startsWith('#') }
|
||||||
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
|
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
|
||||||
def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLines()
|
def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLines()
|
||||||
.findAll { it.contains('=') && !it.startsWith('#') }
|
.findAll { it.contains('=') && !it.startsWith('#') }
|
||||||
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
|
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
|
||||||
def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines()
|
|
||||||
.findAll { it.contains('=') && !it.startsWith('#') }
|
|
||||||
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
|
|
||||||
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet'].collectEntries { name ->
|
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet'].collectEntries { name ->
|
||||||
def pack = file("build/packs/${name}.tar.zst")
|
def pack = file("build/packs/${name}.tar.zst")
|
||||||
if (!pack.isFile()) {
|
if (!pack.isFile()) {
|
||||||
if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
|
if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
|
||||||
// A source build that did not compile proot still pins a published pack, so the app
|
|
||||||
// downloads the patched binary instead of falling back to the rootfs copy.
|
|
||||||
if (name == 'proot' && prootPackPin.PROOT_PACK_SHA256) {
|
|
||||||
return [(name): [sha256: prootPackPin.PROOT_PACK_SHA256, size: (prootPackPin.PROOT_PACK_SIZE ?: '0') as long]]
|
|
||||||
}
|
|
||||||
return [(name): [sha256: '', size: 0L]]
|
return [(name): [sha256: '', size: 0L]]
|
||||||
}
|
}
|
||||||
def digest = java.security.MessageDigest.getInstance('SHA-256')
|
def digest = java.security.MessageDigest.getInstance('SHA-256')
|
||||||
@@ -130,8 +122,8 @@ android {
|
|||||||
applicationId "com.droiddeck.launcher"
|
applicationId "com.droiddeck.launcher"
|
||||||
minSdkVersion 26
|
minSdkVersion 26
|
||||||
targetSdkVersion 28
|
targetSdkVersion 28
|
||||||
versionCode 15
|
versionCode 14
|
||||||
versionName "0.6.0"
|
versionName "0.5.0"
|
||||||
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
|
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
|
||||||
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
|
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
|
||||||
buildConfigField "int", "PR_NUMBER", "${prNumber}"
|
buildConfigField "int", "PR_NUMBER", "${prNumber}"
|
||||||
@@ -228,10 +220,6 @@ android {
|
|||||||
unitTests.returnDefaultValues = true
|
unitTests.returnDefaultValues = true
|
||||||
unitTests.includeAndroidResources = true
|
unitTests.includeAndroidResources = true
|
||||||
unitTests.all {
|
unitTests.all {
|
||||||
if (ciBuild) {
|
|
||||||
outputs.upToDateWhen { false }
|
|
||||||
outputs.doNotCacheIf('CI executes the test suite on every run') { true }
|
|
||||||
}
|
|
||||||
// Robolectric keeps a sandbox per SDK level the tests ask for; seven no longer fit in Gradle's default 512 MB.
|
// Robolectric keeps a sandbox per SDK level the tests ask for; seven no longer fit in Gradle's default 512 MB.
|
||||||
maxHeapSize = '2g'
|
maxHeapSize = '2g'
|
||||||
def logTarget = providers.systemProperty('robolectric.logging').orNull
|
def logTarget = providers.systemProperty('robolectric.logging').orNull
|
||||||
@@ -270,7 +258,6 @@ def runtimeAssetsDir = layout.buildDirectory.dir('runtimeAssets')
|
|||||||
def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) {
|
def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) {
|
||||||
dependsOn(stageSessionScripts)
|
dependsOn(stageSessionScripts)
|
||||||
from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' }
|
from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' }
|
||||||
from(rootProject.file('tools/linuxfs/innoextract'))
|
|
||||||
from(layout.buildDirectory.dir('prepared-assets'))
|
from(layout.buildDirectory.dir('prepared-assets'))
|
||||||
into(runtimeAssetsDir)
|
into(runtimeAssetsDir)
|
||||||
}
|
}
|
||||||
@@ -346,8 +333,6 @@ dependencies {
|
|||||||
implementation 'androidx.camera:camera-camera2:1.4.2'
|
implementation 'androidx.camera:camera-camera2:1.4.2'
|
||||||
implementation 'androidx.camera:camera-lifecycle:1.4.2'
|
implementation 'androidx.camera:camera-lifecycle:1.4.2'
|
||||||
implementation 'androidx.webkit:webkit:1.12.1'
|
implementation 'androidx.webkit:webkit:1.12.1'
|
||||||
// Google's WebRTC (BSD) for the native Xbox Cloud Gaming player (XboxNativePlayerActivity).
|
|
||||||
implementation 'io.github.webrtc-sdk:android:125.6422.07'
|
|
||||||
implementation("com.google.mediapipe:tasks-vision:${trackingPack.MEDIAPIPE_VERSION}") {
|
implementation("com.google.mediapipe:tasks-vision:${trackingPack.MEDIAPIPE_VERSION}") {
|
||||||
exclude group: 'com.google.auto.value', module: 'auto-value'
|
exclude group: 'com.google.auto.value', module: 'auto-value'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,15 +2,6 @@
|
|||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
xmlns:tools="http://schemas.android.com/tools">
|
xmlns:tools="http://schemas.android.com/tools">
|
||||||
|
|
||||||
<queries>
|
|
||||||
<intent>
|
|
||||||
<action android:name="android.content.pm.action.CONFIRM_INSTALL" />
|
|
||||||
</intent>
|
|
||||||
<intent>
|
|
||||||
<action android:name="android.content.pm.action.CONFIRM_PERMISSIONS" />
|
|
||||||
</intent>
|
|
||||||
</queries>
|
|
||||||
|
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
@@ -27,10 +18,7 @@
|
|||||||
<uses-permission android:name="android.permission.VIBRATE" />
|
<uses-permission android:name="android.permission.VIBRATE" />
|
||||||
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
|
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
|
||||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
|
||||||
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
|
|
||||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||||
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
|
|
||||||
<uses-permission android:name="android.permission.BLUETOOTH" />
|
<uses-permission android:name="android.permission.BLUETOOTH" />
|
||||||
<uses-permission android:name="android.permission.CAMERA" />
|
<uses-permission android:name="android.permission.CAMERA" />
|
||||||
|
|
||||||
@@ -46,7 +34,6 @@
|
|||||||
android:localeConfig="@xml/locales_config"
|
android:localeConfig="@xml/locales_config"
|
||||||
android:networkSecurityConfig="@xml/network_security_config"
|
android:networkSecurityConfig="@xml/network_security_config"
|
||||||
android:allowBackup="false"
|
android:allowBackup="false"
|
||||||
android:allowAudioPlaybackCapture="true"
|
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
android:label="@string/app_name"
|
android:label="@string/app_name"
|
||||||
android:theme="@style/AppTheme"
|
android:theme="@style/AppTheme"
|
||||||
@@ -59,15 +46,6 @@
|
|||||||
<meta-data android:name="android.game_mode_config" android:resource="@xml/game_mode_config" />
|
<meta-data android:name="android.game_mode_config" android:resource="@xml/game_mode_config" />
|
||||||
<service android:name=".glasses.LumaRgbCaptureService" android:exported="false"
|
<service android:name=".glasses.LumaRgbCaptureService" android:exported="false"
|
||||||
android:process=":rgb_diagnostic" />
|
android:process=":rgb_diagnostic" />
|
||||||
<service android:name=".input.HomeButtonService"
|
|
||||||
android:label="@string/integration_shortcuts_service"
|
|
||||||
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
|
|
||||||
android:exported="true">
|
|
||||||
<intent-filter>
|
|
||||||
<action android:name="android.accessibilityservice.AccessibilityService" />
|
|
||||||
</intent-filter>
|
|
||||||
<meta-data android:name="android.accessibilityservice" android:resource="@xml/home_button_service" />
|
|
||||||
</service>
|
|
||||||
<meta-data android:name="com.oculus.supportedDevices" android:value="quest2|quest3|quest3s" />
|
<meta-data android:name="com.oculus.supportedDevices" android:value="quest2|quest3|quest3s" />
|
||||||
<activity android:name=".QuestXrActivity" android:exported="true" android:launchMode="singleTask"
|
<activity android:name=".QuestXrActivity" android:exported="true" android:launchMode="singleTask"
|
||||||
android:permission="android.permission.DUMP"
|
android:permission="android.permission.DUMP"
|
||||||
@@ -83,20 +61,9 @@
|
|||||||
</activity>
|
</activity>
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
android:name=".PairingGuideActivity"
|
android:name=".MainActivity"
|
||||||
android:exported="false"
|
|
||||||
android:launchMode="singleTask"
|
|
||||||
android:taskAffinity="${applicationId}.pairingguide"
|
|
||||||
android:excludeFromRecents="true"
|
|
||||||
android:supportsPictureInPicture="true"
|
|
||||||
android:resizeableActivity="true"
|
|
||||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation"
|
|
||||||
android:theme="@style/AppTheme" />
|
|
||||||
|
|
||||||
<activity
|
|
||||||
android:name=".FrontEndActivity"
|
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
android:screenOrientation="user"
|
android:screenOrientation="sensorLandscape"
|
||||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation">
|
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.VIEW" />
|
<action android:name="android.intent.action.VIEW" />
|
||||||
@@ -117,8 +84,8 @@
|
|||||||
</activity>
|
</activity>
|
||||||
|
|
||||||
<activity-alias
|
<activity-alias
|
||||||
android:name=".MainActivity"
|
android:name=".LauncherDark"
|
||||||
android:targetActivity=".FrontEndActivity"
|
android:targetActivity=".MainActivity"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
android:exported="true">
|
android:exported="true">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
@@ -130,7 +97,7 @@
|
|||||||
|
|
||||||
<activity-alias
|
<activity-alias
|
||||||
android:name=".LauncherLight"
|
android:name=".LauncherLight"
|
||||||
android:targetActivity=".FrontEndActivity"
|
android:targetActivity=".MainActivity"
|
||||||
android:icon="@mipmap/ic_launcher_light"
|
android:icon="@mipmap/ic_launcher_light"
|
||||||
android:enabled="false"
|
android:enabled="false"
|
||||||
android:exported="true">
|
android:exported="true">
|
||||||
@@ -148,7 +115,7 @@
|
|||||||
android:excludeFromRecents="true"
|
android:excludeFromRecents="true"
|
||||||
android:noHistory="true"
|
android:noHistory="true"
|
||||||
android:taskAffinity="${applicationId}.home"
|
android:taskAffinity="${applicationId}.home"
|
||||||
android:screenOrientation="user"
|
android:screenOrientation="sensorLandscape"
|
||||||
android:theme="@android:style/Theme.Translucent.NoTitleBar">
|
android:theme="@android:style/Theme.Translucent.NoTitleBar">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.MAIN" />
|
<action android:name="android.intent.action.MAIN" />
|
||||||
@@ -158,18 +125,6 @@
|
|||||||
</activity>
|
</activity>
|
||||||
|
|
||||||
|
|
||||||
<activity
|
|
||||||
android:name=".PinRequestActivity"
|
|
||||||
android:exported="true"
|
|
||||||
android:excludeFromRecents="true"
|
|
||||||
android:taskAffinity="${applicationId}.pin"
|
|
||||||
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen">
|
|
||||||
<intent-filter>
|
|
||||||
<action android:name="android.content.pm.action.CONFIRM_PIN_SHORTCUT" />
|
|
||||||
<action android:name="android.content.pm.action.CONFIRM_PIN_APPWIDGET" />
|
|
||||||
</intent-filter>
|
|
||||||
</activity>
|
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
android:name=".input.ControllerEditorActivity"
|
android:name=".input.ControllerEditorActivity"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
@@ -181,14 +136,14 @@
|
|||||||
<activity
|
<activity
|
||||||
android:name=".files.FileManagerActivity"
|
android:name=".files.FileManagerActivity"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:screenOrientation="user"
|
android:screenOrientation="sensorLandscape"
|
||||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||||
android:theme="@style/AppTheme" />
|
android:theme="@style/AppTheme" />
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
android:name=".files.FilePickerActivity"
|
android:name=".files.FilePickerActivity"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:screenOrientation="user"
|
android:screenOrientation="sensorLandscape"
|
||||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||||
android:theme="@style/AppTheme" />
|
android:theme="@style/AppTheme" />
|
||||||
|
|
||||||
@@ -196,31 +151,10 @@
|
|||||||
android:process=":xboxlogin" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
android:process=":xboxlogin" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||||
android:theme="@style/AppTheme" />
|
android:theme="@style/AppTheme" />
|
||||||
|
|
||||||
<activity android:name=".stores.xbox.XboxCloudPlayerActivity" android:exported="false"
|
|
||||||
android:screenOrientation="sensorLandscape" android:hardwareAccelerated="true"
|
|
||||||
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
|
|
||||||
android:theme="@style/AppTheme" />
|
|
||||||
|
|
||||||
<service android:name=".stores.xbox.XboxCloudTokenService" android:exported="false" />
|
|
||||||
|
|
||||||
<activity android:name=".stores.xbox.XboxNativePlayerActivity" android:exported="false"
|
|
||||||
android:process=":xcloudnative" android:screenOrientation="sensorLandscape" android:hardwareAccelerated="true"
|
|
||||||
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
|
|
||||||
android:theme="@style/AppTheme" />
|
|
||||||
|
|
||||||
<activity android:name=".stores.xbox.XboxCloudActivity" android:exported="false"
|
|
||||||
android:process=":xboxcloud" android:launchMode="singleTop" android:screenOrientation="sensorLandscape"
|
|
||||||
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
|
|
||||||
android:theme="@style/AppTheme" />
|
|
||||||
|
|
||||||
<activity android:name=".stores.xbox.XboxCloudSettingsActivity" android:exported="false"
|
|
||||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
|
||||||
android:theme="@style/AppTheme" />
|
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
android:name=".stores.StoreLoginActivity"
|
android:name=".stores.StoreLoginActivity"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:screenOrientation="user"
|
android:screenOrientation="sensorLandscape"
|
||||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||||
android:theme="@style/AppTheme" />
|
android:theme="@style/AppTheme" />
|
||||||
|
|
||||||
@@ -243,6 +177,15 @@
|
|||||||
android:resizeableActivity="true"
|
android:resizeableActivity="true"
|
||||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
|
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
|
||||||
|
|
||||||
|
<activity
|
||||||
|
android:name=".ui.SecondScreenActivity"
|
||||||
|
android:exported="false"
|
||||||
|
android:excludeFromRecents="true"
|
||||||
|
android:theme="@style/SessionTheme"
|
||||||
|
android:screenOrientation="sensorLandscape"
|
||||||
|
android:resizeableActivity="true"
|
||||||
|
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
android:name=".gpu.SteamVrRestartActivity"
|
android:name=".gpu.SteamVrRestartActivity"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2026 Holger Bartnick
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
|
|
||||||
<style>
|
|
||||||
html, body { margin: 0; height: 100%; background: #000; overflow: hidden; }
|
|
||||||
#player { position: absolute; inset: 0; }
|
|
||||||
#status { position: absolute; left: 0; right: 0; bottom: 12%; text-align: center; color: #ddd;
|
|
||||||
font: 16px sans-serif; text-shadow: 0 0 4px #000; pointer-events: none; }
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div id="player"></div>
|
|
||||||
<div id="status"></div>
|
|
||||||
<script src="player.js"></script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -1,187 +0,0 @@
|
|||||||
/* DroidDeck Xbox Cloud Gaming player. Includes Greenlight's player (c) UnknownSKL (Jim Kroon), MIT. */
|
|
||||||
(()=>{var _=class{_player;_dataChannel;constructor(e){this._player=e,this._dataChannel=this._player._peerConnection.createDataChannel(this.getChannelName(),this.getChannelConfig()),this._dataChannel.onopen=this.onOpen.bind(this),this._dataChannel.onmessage=this.onMessage.bind(this),this._dataChannel.onclosing=this.onClosing.bind(this),this._dataChannel.onclose=this.onClose.bind(this),this._dataChannel.onerror=this.onError.bind(this)}getChannelName(){return"channel"}getChannelConfig(){return{}}onOpen(e){console.log(this.getChannelName(),"Opening channel:",e)}onMessage(e){console.log(this.getChannelName(),"Message channel:",e)}onClosing(e){console.log(this.getChannelName(),"Closing channel:",e)}onClose(e){console.log(this.getChannelName(),"Closed channel:",e)}onError(e){console.log(this.getChannelName(),"Error channel:",e)}send(e){if(this._dataChannel.readyState!=="open"){console.log("["+this.getChannelName()+"] Tried to send data while channel is not open. readyState is:",this._dataChannel.readyState);return}return typeof e=="string"&&(e=new TextEncoder().encode(e)),this._dataChannel.send(e)}getPlayer(){return this._player}destroy(){}};var S=class extends _{_micPermissions="prompt";_micStream;constructor(e){super(e),navigator.permissions.query({name:"microphone"}).then(t=>{this._micPermissions=t.state,t.onchange=()=>{this._micPermissions=t.state}})}getChannelName(){return"chat"}getChannelConfig(){return{ordered:!0,protocol:"chatV1"}}destroy(){}};var v=class r{_player;_index;_physicalGamepadId=-1;_rumbleInterval;_isFocused=!0;_gamepadOverride={buttons:{}};_options={enable_keyboard:!1,enable_gamepad:!0,enable_vibration:!0,keyboard_mapping:{A:"Enter",B:"Backspace",X:"x",Y:"y",DPadUp:"ArrowUp",DPadDown:"ArrowDown",DPadLeft:"ArrowLeft",DPadRight:"ArrowRight",LeftShoulder:"[",RightShoulder:"]",LeftThumb:"l",RightThumb:"r",LeftTrigger:"-",RightTrigger:"=",Menu:"m",View:"v",Nexus:"n"},gamepad_mapping:{A:"0",B:"1",X:"2",Y:"3",DPadUp:"12",DPadDown:"13",DPadLeft:"14",DPadRight:"15",LeftShoulder:"4",RightShoulder:"5",LeftThumb:"10",RightThumb:"11",LeftTrigger:"6",RightTrigger:"7",Menu:"9",View:"8",Nexus:"16"},gamepad_axes_mapping:{LeftThumbXAxis:"0",LeftThumbYAxis:"1",RightThumbXAxis:"2",RightThumbYAxis:"3"},gamepad_deadzone:.08,gamepad_force_capture:!1};_listener={keyDown:this.onKeyDown.bind(this),keyUp:this.onKeyUp.bind(this),gamepadConnected:this.onGamepadConnected.bind(this),gamepadDisconnected:this.onGamepadDisconnected.bind(this),windowFocus:this.onWindowFocus.bind(this),windowBlur:this.onWindowBlur.bind(this)};constructor(e,t={}){this._index=e,this._options={...this._options,...t}}attach(e){this._player=e,this._player._channels.control.sendGamepadState(this._index,!0,this),this._options.enable_keyboard===!0&&(window.addEventListener("keydown",this._listener.keyDown),window.addEventListener("keyup",this._listener.keyUp)),this._options.enable_gamepad===!0&&(window.addEventListener("gamepadconnected",this._listener.gamepadConnected),window.addEventListener("gamepaddisconnected",this._listener.gamepadDisconnected)),this._options.enable_gamepad===!0&&this._options.gamepad_force_capture===!1&&(window.addEventListener("blur",this._listener.windowBlur),window.addEventListener("focus",this._listener.windowFocus)),this.detectActiveGamepad()}detach(){if(this._player===void 0){console.log("[Gamepad] Player is not attached. this._player is:",this._player);return}this._player._channels.control.sendGamepadState(this._index,!1),this._physicalGamepadId=-1,this._rumbleInterval!==void 0&&clearInterval(this._rumbleInterval),this._options.enable_keyboard===!0&&(window.removeEventListener("keydown",this._listener.keyDown),window.removeEventListener("keyup",this._listener.keyUp)),this._options.enable_gamepad===!0&&(window.removeEventListener("gamepadconnected",this._listener.gamepadConnected),window.removeEventListener("gamepaddisconnected",this._listener.gamepadDisconnected)),this._options.enable_gamepad===!0&&this._options.gamepad_force_capture===!1&&(window.removeEventListener("blur",this._listener.windowBlur),window.removeEventListener("focus",this._listener.windowFocus))}sendButtonState(e,t){if(this._player===void 0){console.log("[Gamepad] Player is not attached. this._player is:",this._player);return}if(!(e in this.getDefaultFamepadFrame())){console.log("[Gamepad] Invalid button:",e);return}let n=this.getDefaultFamepadFrame();n.GamepadIndex=this._index,this._gamepadOverride.buttons[e]=t}onKeyDown(e){if(this._isFocused!==!1)for(let t in this._options.keyboard_mapping)this._options.keyboard_mapping[t]===e.key&&(this._gamepadOverride.buttons[t]=1,e.preventDefault())}onKeyUp(e){if(this._isFocused!==!1)for(let t in this._options.keyboard_mapping)this._options.keyboard_mapping[t]===e.key&&(this._gamepadOverride.buttons[t]=0,e.preventDefault())}onWindowFocus(){this._isFocused=!0}onWindowBlur(){}getDefaultFamepadFrame(){return{GamepadIndex:0,Nexus:0,Menu:0,View:0,A:0,B:0,X:0,Y:0,DPadUp:0,DPadDown:0,DPadLeft:0,DPadRight:0,LeftShoulder:0,Line truncated
|
|
||||||
|
|
||||||
`+t.ContentText)?this.completeTransaction(e.id,{Result:0}):this.completeTransaction(e.id,{Result:1})}};var M=class extends _{_handshakeCompleted=!1;getChannelName(){return"message"}getChannelConfig(){return{protocol:"messageV1",ordered:!0}}onOpen(){console.log("[MessageChannel] Sending handshake...");let e=JSON.stringify({type:"Handshake",version:"messageV1",id:"be0bfc6d-1e83-4c8a-90ed-fa8601c5a179",cv:"0"});this.send(e)}onMessage(e){let t=JSON.parse(e.data);switch(t.type){case"HandshakeAck":console.log("[MessageChannel] Handshake completed"),this._handshakeCompleted=!0,this.getPlayer()._channels.control.sendAuthorization(),this.getPlayer()._channels.input.start(),this.sendConfig();break;case"TransactionStart":case"Message":new D(this,t);break;default:console.log("[MessageChannel] Unhandled message type:",t.type,t)}}sendConfig(){let e=[],t=[0,2,0],n=JSON.stringify(this.generateMessage("/streaming/systemUi/configuration",{version:t,systemUis:e}));this.send(n);let i=JSON.stringify(this.generateMessage("/streaming/properties/clientappinstallidchanged",{clientAppInstallId:"c97d7ee0-73b2-4239-bf1d-9d805a338429"}));this.send(i);let a=JSON.stringify(this.generateMessage("/streaming/characteristics/orientationchanged",{orientation:0}));this.send(a);let s=JSON.stringify(this.generateMessage("/streaming/characteristics/touchinputenabledchanged",{touchInputEnabled:!1}));this.send(s);let o=JSON.stringify(this.generateMessage("/streaming/characteristics/clientdevicecapabilities",{}));this.send(o);let d=JSON.stringify(this.generateMessage("/streaming/characteristics/dimensionschanged",{horizontal:1920,vertical:1080,preferredWidth:1920,preferredHeight:1080,safeAreaLeft:0,safeAreaTop:0,safeAreaRight:1920,safeAreaBottom:1080,supportsCustomResolution:!0}));this.send(d)}generateMessage(e,t){return{type:"Message",content:JSON.stringify(t),id:Q(),target:e,cv:""}}destroy(){}};var E=class{_address;_ipv4Address;_ipv4Port;constructor(e){this._address=e;let t=this._address.split(":"),n=t[6]+t[7],i=t[5],a=~parseInt(n.substring(0,2),16)&255,s=~parseInt(n.substring(2,4),16)&255,o=~parseInt(n.substring(4,6),16)&255,d=~parseInt(n.substring(6,8),16)&255,u=~parseInt(i.substring(0,4),16)&65535;this._ipv4Address=a+"."+s+"."+o+"."+d,this._ipv4Port=u}getIpv4Address(){return this._ipv4Address}getIpv4Port(){return this._ipv4Port}};var R=class{_peerConnection;_iceCandidates=[];constructor(e){this._peerConnection=e._peerConnection,this._peerConnection.addEventListener("icecandidate",t=>{t.candidate&&this._iceCandidates.push(t.candidate)})}getCandidates(){return this._iceCandidates}setRemoteCandidates(e){e.length===0&&console.warn("Error: No candidates received!");for(let t in e){if(e[t].candidate==="a=end-of-candidates")continue;let n=e[t].candidate.split(" ");if(n.length>4&&n[4].substr(0,4)==="2001"){let i=new E(n[4]);this._peerConnection.addIceCandidate({candidate:"a=candidate:10 1 UDP 1 "+i.getIpv4Address()+" 9002 typ host ",sdpMLineIndex:e[t].sdpMLineIndex,sdpMid:e[t].sdpMid}),this._peerConnection.addIceCandidate({candidate:"a=candidate:11 1 UDP 1 "+i.getIpv4Address()+" "+i.getIpv4Port()+" typ host ",sdpMLineIndex:e[t].sdpMLineIndex,sdpMid:e[t].sdpMid})}this._peerConnection.addIceCandidate({candidate:e[t].candidate,sdpMid:e[t].sdpMid,sdpMLineIndex:e[t].sdpMLineIndex})}}};var I=class{_player;_peerConnection;constructor(e){this._player=e,this._peerConnection=e._peerConnection}getAvailableCodecs(){let e=RTCRtpReceiver.getCapabilities("video")?.codecs;if(e===void 0)return[];let t=[];for(let n in e)t.includes(e[n].mimeType)||t.push(e[n].mimeType);return t}setLocalSDP(e){return console.log("[SDP] setLocalSDP() Setting local SDP:",e),e.sdp=e.sdp?.replace("useinbandfec=1","useinbandfec=1; stereo=1"),e}setRemoteSDP(e){return console.log("[SDP] setRemoteSDP() Setting remote SDP:",e),e}getDefaultCodecPreferences(){let e=RTCRtpReceiver.getCapabilities("video")?.codecs;if(e===void 0)return[];let t=[],n=[],i=[],a=[];for(let o in e)e[o].mimeType.includes("H264")?e[o].sdpFmtpLine?.includes("profile-level-id=4d")?t.push(e[o]):e[o].sdpFmtpLine?.includes("profile-level-id=42e")?n.push(e[o]):e[o].sdpFmtpLine?.includes("profile-level-id=420")&&i.push(e[o]):(e[o].mimeType.includes("ulpfec")||e[o].mimeType.includes("flexfec")||e[o].mimeType.includes("VP9")||e[o].mimeType.includes("VP8"))&&a.push(e[o]);return[...t,...n,...i,...a]}_setBitrate(e,t,n){let i=e.split(`
|
|
||||||
`),a=-1;for(let o=0;o<i.length;o++)if(i[o].indexOf("m="+t)===0){a=o;break}if(a===-1)return console.debug("Could not find the m line for",t),e;for(a++;i[a].indexOf("i=")===0||i[a].indexOf("c=")===0;)a++;if(i[a].indexOf("b")===0)return i[a]="b=AS:"+n,i.join(`
|
|
||||||
`);let s=i.slice(0,a);return s.push("b=AS:"+n),s=s.concat(i.slice(a,i.length)),s.join(`
|
|
||||||
`)}};var P=class{_player;_peerConnection;_videoCodec="";_audioCodec="";_videoWidth=0;_videoHeight=0;_videoFps=0;_rtt=0;_remoteHost="";_remotePort=0;_remoteIsLocal=!1;_remoteIsIpv6=!1;_activeRemoteCandidate="";constructor(e){this._player=e,this._peerConnection=e._peerConnection,setInterval(this.loop.bind(this),1e3)}loop(){this._peerConnection.getStats().then(e=>{e.forEach(t=>{t.type==="inbound-rtp"?this.readInboundRtp(t):t.type==="candidate-pair"&&t.packetsReceived!==void 0&&t.packetsReceived>0?this.readCandidatePair(t):t.type==="remote-candidate"&&this.readRemoteCandidate(t)})})}readInboundRtp(e){e.kind==="video"&&e.codecId&&e.packetsReceived!==void 0&&e.packetsReceived>0?(e.codecId.includes("profile-level-id=4d")?this._videoCodec="H264 (High)":e.codecId.includes("profile-level-id=42e")?this._videoCodec="H264 (Normal)":e.codecId.includes("profile-level-id=420")?this._videoCodec="H264 (Low)":this._videoCodec="Other ("+e.codecId+")",e.frameWidth&&(this._videoWidth=e.frameWidth),e.frameHeight&&(this._videoHeight=e.frameHeight),e.framesPerSecond&&(this._videoFps=e.framesPerSecond)):e.kind==="audio"&&e.codecId&&e.packetsReceived!==void 0&&e.packetsReceived>0&&(this._audioCodec=e.codecId)}readCandidatePair(e){this._activeRemoteCandidate=e.remoteCandidateId,this._rtt=e.currentRoundTripTime}readRemoteCandidate(e){e.id===this._activeRemoteCandidate&&(this.isPrivateIP(e.address)?this._remoteIsLocal=!0:this._remoteIsLocal=!1,this.isIpv6(e.address)?this._remoteIsIpv6=!0:this._remoteIsIpv6=!1,this._remoteHost=e.address,this._remotePort=e.port)}isPrivateIP(e){let t=e.split(".");return t[0]==="10"||t[0]==="172"&&parseInt(t[1],10)>=16&&parseInt(t[1],10)<=31||t[0]==="192"&&t[1]==="168"}isIpv6(e){return e.split(":").length>3}};var G=class{_player;_videoComponent;_overlays={debug:void 0};constructor(e,t){this._videoComponent=e,this._player=t}toggleDebug(){this._overlays.debug===void 0?this.createDebugOverlay():this.destroy()}createDebugOverlay(){this._overlays.debug=document.createElement("div"),this._overlays.debug.id="playerDebugOverlay",this._overlays.debug.style.position="absolute",this._overlays.debug.style.top="0",this._overlays.debug.style.left="0",this._overlays.debug.style.width=this._videoComponent.getElement()?.style.width||"100%",this._overlays.debug.style.height=this._videoComponent.getElement()?.style.height||"auto",this._overlays.debug.style.background="linear-gradient(0deg, rgba(0,0,0, 0) 0%, rgba(0,0,0, 0) 75%, rgba(0,0,0, 0.5) 100%)",this._overlays.debug.style.padding="10px",this._overlays.debug.style.pointerEvents="none",document.getElementById(this._player.getElementId())?.appendChild(this._overlays.debug),setTimeout(()=>{this.refreshDebugOverlay()},500),this.refreshDebugOverlay()}destroy(){this._overlays.debug?.remove(),this._overlays.debug=void 0}refreshDebugOverlay(){if(this._overlays.debug!==void 0){this._overlays.debug.innerHTML="",this._overlays.debug.appendChild(this.createLabel("Local Play",this._player.getStats()._remoteIsLocal?"Local":"Remote","ok")),this._overlays.debug.appendChild(this.createLabel("Resolution",this._player.getStats()._videoWidth+"x"+this._player.getStats()._videoHeight,"ok")),this._overlays.debug.appendChild(this.createLabel("Stream FPS",this._player.getStats()._videoFps.toString(),this._player.getStats()._videoFps>=58?"ok":"warning"));let e=this._videoComponent.getFrameStats?.();e&&(this._overlays.debug.appendChild(this.createLabel("Render FPS",e.renderingFps.toString(),e.renderingFps>=58?"ok":"warning")),this._overlays.debug.appendChild(this.createLabel("Render Delay",e.renderDelayMs.toString()+" ms",e.renderDelayMs<16?"ok":e.renderDelayMs<33?"warning":"error")),this._overlays.debug.appendChild(this.createLabel("Dropped Frames",e.droppedFrames.toString(),e.droppedFrames===0?"ok":e.droppedFrames<30?"warning":"error"))),this._overlays.debug.appendChild(this.createLabel("Connection",this._player.getStats()._remoteIsIpv6?"IPv6":"IPv4","ok")),this._overlays.debug.appendChild(this.createLabel("Video",this._player.getStats()._videoCodec,"ok"));let t=this._player.getStats()._rtt*1e3>75?"error":this._player.getStats()._rtt*1e3>40?"warning":"ok";this._overlays.debug.appendChild(this.createLabel("RTT",(this._player.getStats()._rtt*1e3).toString()+" ms",t)),setTimeout(()=>{this.refreshDebugOverlay()},500)}}createLabel(e,t="",n=""){let i={borderRadius:"5px",background:"linear-gradient(0deg, rgba(28,26,26,1) 0%, rgba(47,45,45,1) 100%)",padding:"10px",fontSize:"12px",marginTop:"3px",marginRight:"10px",marginBottom:"2px",textTransform:"uppercase",color:"white",display:"inline-block"},a=document.createElement("span"),s={error:"rgb(220, 53, 69)",warning:"rgb(255, 193, 7)",ok:"rgb(25, 135, 84)"};t!==""?a.innerHTML=`${e}: <span style="background: ${s[n]}; border-radius: 5px; padding: 4px; padding-left: 8px; padding-right: 8px;">${t}</span>`:a.innerText=e;for(let o in i)a.style[o]=i[o];return a}};var L=class{_player;_element;_overlay;constructor(e){this._player=e,this._overlay=new G(this,this._pLine truncated
|
|
||||||
in vec2 position;
|
|
||||||
out vec2 vUV;
|
|
||||||
void main() { vUV = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`,j=`attribute vec2 position;
|
|
||||||
varying vec2 vUV;
|
|
||||||
void main() { vUV = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`,Z=`#version 300 es
|
|
||||||
precision mediump float;
|
|
||||||
uniform sampler2D screenTexture;
|
|
||||||
uniform vec2 resolution;
|
|
||||||
uniform int filterId;
|
|
||||||
uniform float sharpenFactor;
|
|
||||||
uniform float brightness;
|
|
||||||
uniform float contrast;
|
|
||||||
uniform float gamma;
|
|
||||||
uniform float saturation;
|
|
||||||
uniform float deband;
|
|
||||||
out vec4 fragColor;
|
|
||||||
const float CAS_CONTRAST_PEAK = 0.8 * -3.0 + 8.0;
|
|
||||||
|
|
||||||
vec3 sharpen(vec2 coord, vec3 e) {
|
|
||||||
vec2 px = 1.0 / resolution;
|
|
||||||
vec3 b = texture(screenTexture, coord + px * vec2(0, 1)).rgb;
|
|
||||||
vec3 d = texture(screenTexture, coord + px * vec2(-1, 0)).rgb;
|
|
||||||
vec3 f = texture(screenTexture, coord + px * vec2(1, 0)).rgb;
|
|
||||||
vec3 h = texture(screenTexture, coord + px * vec2(0, -1)).rgb;
|
|
||||||
vec3 a = texture(screenTexture, coord + px * vec2(-1, 1)).rgb;
|
|
||||||
vec3 c = texture(screenTexture, coord + px * vec2(1, 1)).rgb;
|
|
||||||
vec3 g = texture(screenTexture, coord + px * vec2(-1, -1)).rgb;
|
|
||||||
vec3 i = texture(screenTexture, coord + px * vec2(1, -1)).rgb;
|
|
||||||
if (filterId == 1) {
|
|
||||||
vec3 blur = ((a + c + g + i) + (b + d + f + h) * 2.0 + e * 4.0) / 16.0;
|
|
||||||
return e + (e - blur) * sharpenFactor / 3.0;
|
|
||||||
}
|
|
||||||
vec3 minRgb = min(min(min(d, e), min(f, b)), h) + min(min(a, c), min(g, i));
|
|
||||||
vec3 maxRgb = max(max(max(d, e), max(f, b)), h) + max(max(a, c), max(g, i));
|
|
||||||
vec3 amplify = inversesqrt(clamp(min(minRgb, 2.0 - maxRgb) / maxRgb, 0.0, 1.0));
|
|
||||||
vec3 weight = -(1.0 / (amplify * CAS_CONTRAST_PEAK));
|
|
||||||
vec3 outColor = clamp(((b + d + f + h) * weight + e) / (4.0 * weight + 1.0), 0.0, 1.0);
|
|
||||||
return mix(e, outColor, sharpenFactor / 2.0);
|
|
||||||
}
|
|
||||||
|
|
||||||
float ign(vec2 p) { return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); }
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
vec2 uv = gl_FragCoord.xy / resolution;
|
|
||||||
vec3 color = texture(screenTexture, uv).rgb;
|
|
||||||
if (sharpenFactor > 0.0) color = sharpen(uv, color);
|
|
||||||
color = clamp(color + brightness, 0.0, 1.0);
|
|
||||||
color = (color - 0.5) * clamp(contrast + 1.0, 0.5, 2.0) + 0.5;
|
|
||||||
color = mix(vec3(dot(color, vec3(0.2126, 0.7152, 0.0722))), color, saturation);
|
|
||||||
color = pow(max(color, 0.0), vec3(1.0 / gamma));
|
|
||||||
if (deband > 0.0) color += vec3(((ign(gl_FragCoord.xy) + ign(gl_FragCoord.xy + vec2(11.0, 17.0))) - 1.0) * (deband / 255.0));
|
|
||||||
fragColor = vec4(color, 1.0);
|
|
||||||
}`,ee=`precision highp float;
|
|
||||||
#define FXAA_MIN_REDUCE (1.0 / 128.0)
|
|
||||||
#define FXAA_MUL_REDUCE (1.0 / 8.0)
|
|
||||||
#define MAX_SPAN 8.0
|
|
||||||
uniform sampler2D screenTexture;
|
|
||||||
uniform vec2 resolution;
|
|
||||||
const vec3 luma = vec3(0.299, 0.587, 0.114);
|
|
||||||
void main() {
|
|
||||||
vec2 invResolution = 1.0 / resolution;
|
|
||||||
vec3 rgbNW = texture2D(screenTexture, (gl_FragCoord.xy + vec2(-1.0, -1.0)) * invResolution).rgb;
|
|
||||||
vec3 rgbNE = texture2D(screenTexture, (gl_FragCoord.xy + vec2( 1.0, -1.0)) * invResolution).rgb;
|
|
||||||
vec3 rgbSW = texture2D(screenTexture, (gl_FragCoord.xy + vec2(-1.0, 1.0)) * invResolution).rgb;
|
|
||||||
vec3 rgbSE = texture2D(screenTexture, (gl_FragCoord.xy + vec2( 1.0, 1.0)) * invResolution).rgb;
|
|
||||||
vec3 rgbM = texture2D(screenTexture, gl_FragCoord.xy * invResolution).rgb;
|
|
||||||
float lumaNW = dot(rgbNW, luma);
|
|
||||||
float lumaNE = dot(rgbNE, luma);
|
|
||||||
float lumaSW = dot(rgbSW, luma);
|
|
||||||
float lumaSE = dot(rgbSE, luma);
|
|
||||||
float lumaM = dot(rgbM, luma);
|
|
||||||
float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));
|
|
||||||
float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));
|
|
||||||
vec2 dir;
|
|
||||||
dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));
|
|
||||||
dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));
|
|
||||||
float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * 0.25 * FXAA_MUL_REDUCE, FXAA_MIN_REDUCE);
|
|
||||||
float minDirFactor = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);
|
|
||||||
dir = clamp(dir * minDirFactor, vec2(-MAX_SPAN), vec2(MAX_SPAN)) * invResolution;
|
|
||||||
vec4 rgbA = 0.5 * (
|
|
||||||
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * (1.0 / 3.0 - 0.5)) +
|
|
||||||
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * (2.0 / 3.0 - 0.5)));
|
|
||||||
vec4 rgbB = rgbA * 0.5 + 0.25 * (
|
|
||||||
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * -0.5) +
|
|
||||||
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * 0.5));
|
|
||||||
float lumaB = dot(rgbB, vec4(luma, 0.0));
|
|
||||||
gl_FragColor = lumaB < lumaMin || lumaB > lumaMax ? rgbA : rgbB;
|
|
||||||
}`,te=`precision highp float;
|
|
||||||
uniform sampler2D screenTexture;
|
|
||||||
uniform vec2 resolution;
|
|
||||||
void main() {
|
|
||||||
vec2 uv = gl_FragCoord.xy / resolution;
|
|
||||||
float edgeThreshold = 0.2;
|
|
||||||
vec2 offset = vec2(1.0) / resolution;
|
|
||||||
vec3 colorCenter = texture2D(screenTexture, uv).rgb;
|
|
||||||
vec3 colorLeft = texture2D(screenTexture, uv - vec2(offset.x, 0.0)).rgb;
|
|
||||||
vec3 colorRight = texture2D(screenTexture, uv + vec2(offset.x, 0.0)).rgb;
|
|
||||||
vec3 colorUp = texture2D(screenTexture, uv - vec2(0.0, offset.y)).rgb;
|
|
||||||
vec3 colorDown = texture2D(screenTexture, uv + vec2(0.0, offset.y)).rgb;
|
|
||||||
float diffHorizontal = length(colorRight - colorLeft);
|
|
||||||
float diffVertical = length(colorUp - colorDown);
|
|
||||||
float edgeFactor = step(edgeThreshold, diffHorizontal + diffVertical);
|
|
||||||
vec3 outlineColor = mix(colorCenter, vec3(0.0), edgeFactor);
|
|
||||||
gl_FragColor = vec4(outlineColor, 1.0);
|
|
||||||
}`,ne=`precision highp float;
|
|
||||||
#define CA_AMOUNT 1.0025
|
|
||||||
#define SCANLINE_INTENSITY_X 0.125
|
|
||||||
#define SCANLINE_INTENSITY_Y 0.375
|
|
||||||
#define SCANLINE_SIZE 1024.0
|
|
||||||
uniform sampler2D screenTexture;
|
|
||||||
varying vec2 vUV;
|
|
||||||
void main() {
|
|
||||||
vec4 finalColor = texture2D(screenTexture, vUV);
|
|
||||||
finalColor.rgb = vec3(
|
|
||||||
texture2D(screenTexture, (vUV - 0.5) * CA_AMOUNT + 0.5).r,
|
|
||||||
finalColor.g,
|
|
||||||
texture2D(screenTexture, (vUV - 0.5) / CA_AMOUNT + 0.5).b
|
|
||||||
);
|
|
||||||
float scanlineX = abs(sin(vUV.x * SCANLINE_SIZE) * 0.5 * SCANLINE_INTENSITY_X);
|
|
||||||
float scanlineY = abs(sin(vUV.y * SCANLINE_SIZE) * 0.5 * SCANLINE_INTENSITY_Y);
|
|
||||||
gl_FragColor = vec4(mix(finalColor.rgb, vec3(0.0), scanlineX + scanlineY), finalColor.a);
|
|
||||||
}`,ie=`precision highp float;
|
|
||||||
#define PI 3.14159265
|
|
||||||
#define SCANLINE_INTENSITY 0.35
|
|
||||||
#define CHROMA_OFFSET 0.005
|
|
||||||
#define BLUR_RADIUS 0.002
|
|
||||||
#define WARP_AMOUNT 0.01
|
|
||||||
#define SCANLINE_DARKEN 0.5
|
|
||||||
uniform sampler2D screenTexture;
|
|
||||||
uniform int FrameCount;
|
|
||||||
uniform vec2 TextureSize;
|
|
||||||
uniform vec2 resolution;
|
|
||||||
varying vec2 vUV;
|
|
||||||
const mat3 yiq_mat = mat3(
|
|
||||||
0.299, 0.587, 0.114,
|
|
||||||
0.596, -0.275, -0.321,
|
|
||||||
0.212, -0.523, 0.311
|
|
||||||
);
|
|
||||||
const mat3 yiq2rgb_mat = mat3(
|
|
||||||
1.0, 0.956, 0.621,
|
|
||||||
1.0, -0.272, -0.647,
|
|
||||||
1.0, -1.106, 1.705
|
|
||||||
);
|
|
||||||
vec3 applyNTSC(vec2 uv) {
|
|
||||||
vec3 col = texture2D(screenTexture, uv).rgb;
|
|
||||||
vec3 yiq = col * yiq_mat;
|
|
||||||
float chromaPhase = PI * (mod(uv.y * TextureSize.y, 2.0) + float(FrameCount));
|
|
||||||
yiq.y *= cos(chromaPhase * 0.5);
|
|
||||||
yiq.z *= sin(chromaPhase * 0.5);
|
|
||||||
vec3 rgb = yiq * yiq2rgb_mat;
|
|
||||||
vec3 finalColor;
|
|
||||||
finalColor.r = texture2D(screenTexture, uv + vec2(CHROMA_OFFSET, 0.0)).r;
|
|
||||||
finalColor.g = texture2D(screenTexture, uv + vec2(0.0, BLUR_RADIUS)).g;
|
|
||||||
finalColor.b = texture2D(screenTexture, uv - vec2(CHROMA_OFFSET, 0.0)).b;
|
|
||||||
return finalColor;
|
|
||||||
}
|
|
||||||
vec3 applyScanlines(vec2 uv) {
|
|
||||||
vec3 col = texture2D(screenTexture, uv).rgb;
|
|
||||||
float scanline = abs(sin(uv.y * resolution.y * 2.0)) * SCANLINE_INTENSITY;
|
|
||||||
col *= 1.0 - (scanline * SCANLINE_DARKEN);
|
|
||||||
return col;
|
|
||||||
}
|
|
||||||
vec2 applyWarp(vec2 uv) {
|
|
||||||
uv = uv * 2.0 - 1.0;
|
|
||||||
float r = sqrt(uv.x * uv.x + uv.y * uv.y);
|
|
||||||
uv += uv * (r * r) * WARP_AMOUNT;
|
|
||||||
return uv * 0.5 + 0.5;
|
|
||||||
}
|
|
||||||
void main() {
|
|
||||||
vec2 warpedUV = applyWarp(vUV);
|
|
||||||
vec3 ntscColor = applyNTSC(warpedUV);
|
|
||||||
vec3 scanlineColor = applyScanlines(warpedUV);
|
|
||||||
vec3 finalColor = mix(ntscColor, scanlineColor, 0.7);
|
|
||||||
gl_FragColor = vec4(finalColor, 1.0);
|
|
||||||
}`,H=class{constructor(e,t){this.video=e;this.effects=t;this.canvas=document.createElement("canvas"),Object.assign(this.canvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",objectFit:"contain",zIndex:"1"}),e.parentElement?.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,desynchronized:!0,powerPreference:"high-performance"});if(n===null)throw new Error("WebGL2 unavailable");this.gl=n;let i=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,i),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),n.STATIC_DRAW),this.passes.set("base",this.compile(J,Z,["screenTexture","resolution","filterId","sharpenFactor","brightness","contrast","gamma","saturation","deband"])),this.videoTexture=this.texture(),this.schedule()}canvas;gl;passes=new Map;videoTexture;targets=[];width=0;height=0;frame=0;lastDraw=0;stopped=!1;idle=!1;pending=!1;update(e){this.effects=e}pause(){this.idle||this.stopped||(this.idle=!0,this.canvas.style.display="none")}resume(e){this.effects=e,!(!this.idle||this.stopped)&&(this.idle=!1,this.canvas.style.display="",this.schedule())}schedule(){this.pending||(this.pending=!0,this.video.requestVideoFrameCallback(this.onFrame))}compile(e,t,n){let i=this.gl,a=(o,d)=>{let u=i.createShader(o);if(i.shaderSource(u,d),i.compileShader(u),!i.getShaderParameter(u,i.COMPILE_STATUS))throw new Error(`shader: ${i.getShaderInfoLog(u)}`);return u},s=i.createProgram();if(i.attachShader(s,a(i.VERTEX_SHADER,e)),i.attachShader(s,a(i.FRAGMENT_SHADER,t)),i.bindAttribLocation(s,0,"position"),i.linkProgram(s),!i.getProgramParameter(s,i.LINK_STATUS))throw new Error(`program: ${i.getProgramInfoLog(s)}`);return{program:s,uniforms:new Map(n.map(o=>[o,i.getUniformLocation(s,o)]))}}extra(e){let t=this.passes.get(e);if(t===void 0){let n={fxaa:ee,toon:te,crt:ne,ntsc:ie}[e];t=this.compile(j,n,["screenTexture","resolution","TextureSize","FrameCount"]),this.passes.set(e,t)}return t}texture(){let e=this.gl,t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),t}resize(e,t){let n=this.gl;this.width=e,this.height=t,this.canvas.width=e,this.canvas.height=t;for(let i of this.targets)n.deleteFramebuffer(i.framebuffer),n.deleteTexture(i.texture);this.targets=[0,1].map(()=>{let i=this.texture();n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e,t,0,n.RGBA,n.UNSIGNED_BYTE,null);let a=n.createFramebuffer();return n.bindFramebuffer(n.FRAMEBUFFER,a),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,i,0),{framebuffer:a,texture:i}}),n.bindFramebuffer(n.FRAMEBUFFER,null)}onFrame=e=>{if(this.pending=!1,this.stopped||this.idle)return;this.schedule();let t=this.effects.maxFps;if(!(t>0&&e-this.lastDraw<1e3/t-2)){this.lastDraw=e;try{this.draw()}catch(n){window.DDCloud?.log(`effects: ${String(n).slice(0,200)}`),this.destroy()}}};draw(){let e=this.gl,t=this.effects,n=this.video.videoWidth,i=this.video.videoHeight;if(n===0||i===0)return;(n!==this.width||i!==this.height)&&this.resize(n,i),this.frame++,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.videoTexture),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.video);let a=["fxaa","toon","crt","ntsc"].filter(d=>t[d]);e.viewport(0,0,n,i),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0);let s=this.passes.get("base");e.bindFramebuffer(e.FRAMEBUFFER,a.length>0?this.targets[0].framebuffer:null),e.useProgram(s.program);let o=s.uniforms;e.uniform1i(o.get("screenTexture"),0),e.uniform2f(o.get("resolution"),n,i),e.uniform1i(o.get("filterId"),t.sharpenMode==="usm"?1:2),e.uniform1f(o.get("sharpenFactor"),t.sharpen),e.uniform1f(o.get("brightness"),t.brightness/100),e.uniform1f(o.get("contrast"),t.contrast/100),e.uniform1f(o.get("gamma"),Math.min(5,Math.max(.1,t.gamma))),e.uniform1f(o.get("saturation"),t.saturation/100),e.uniform1f(o.get("deband"),t.deband),e.drawArrays(e.TRIANGLES,0,3),a.forEach((d,u)=>{let h=this.extra(d),g=this.targets[u%2],p=u===a.length-1;e.bindFramebuffer(e.FRAMEBUFFER,p?null:this.targets[(u+1)%2].framebuffer),e.useProgram(h.program),e.bindTexture(e.TEXTURE_2D,g.texture);let c=h.uniforms;e.uniform1i(c.get("screenTexture")??null,0),e.uniform2f(c.get("resolution")??null,n,i),e.uniform2f(c.get("TextureSize")??null,n,i),e.uniform1i(c.get("FrameCount")??null,this.frame),e.drawArrays(e.TRIANGLES,0,3)})}destroy(){this.stopped=!0,this.canvas.remove(),this.gl.getExtension("WEBGL_lose_context")?.loseContext()}};var V=class{constructor(e){this.pc=e;this.element=document.createElement("div"),Object.assign(this.element.style,{position:"absolute",top:"8px",right:"8px",zIndex:"3",padding:"4px 8px",borderRadius:"6px",background:"rgba(0,0,0,0.55)",color:"#e8e8e8",font:"12px monospace",lineHeight:"16px",pointerEvent
Line truncated
|
|
||||||
`:" \xB7 ")}destroy(){this.show(0,this.vertical,this.server,this.left),this.element.remove()}};function z(r,e){let t=e==="high"?"4d":e==="low"?"420":"42e",n=[];for(let d of r.matchAll(/a=fmtp:(\d+).*profile-level-id=([0-9a-f]{6})/g))d[2].startsWith(t)&&n.push(d[1]);if(n.length===0)return r;let i=r.split(`\r
|
|
||||||
`),a=i.findIndex(d=>d.startsWith("m=video"));if(a<0)return r;let s=i[a].trim().split(" "),o=s.slice(3).filter(d=>!n.includes(d));return i[a]=s.slice(0,3).concat(n,o).join(" "),i.join(`\r
|
|
||||||
`)}function K(r,e){let t=r.split(`\r
|
|
||||||
`),n=t.findIndex(a=>a.startsWith("m=video"));if(n<0)return r;let i=`b=AS:${e}`;for(let a=n+1;a<=t.length;a++){let s=t[a];if(s===void 0||s.startsWith("m=")){t.splice(a,0,i);break}if(!(s.startsWith("i=")||s.startsWith("c="))){if(s.startsWith("b=AS:")){t[a]=i;break}t.splice(a,0,i);break}}return t.join(`\r
|
|
||||||
`)}var m=JSON.parse(DDCloud.settings()),ae=RTCPeerConnection.prototype.setLocalDescription;RTCPeerConnection.prototype.setLocalDescription=function(r){return r?.sdp&&((m.codec==="high"||m.codec==="normal"||m.codec==="low")&&(r.sdp=z(r.sdp,m.codec)),m.bitrateMbps>0&&(r.sdp=K(r.sdp,m.bitrateMbps*1e3))),ae.call(this,r)};window.__ddRumble=m.rumble/100;window.addEventListener("error",r=>DDCloud.log(`error: ${r.message} @${r.lineno}`));window.addEventListener("unhandledrejection",r=>DDCloud.log(`rejection: ${String(r.reason).slice(0,200)}`));window.addEventListener("gamepadconnected",r=>DDCloud.log(`controller: ${r.gamepad.id.slice(0,60)} mapping=${r.gamepad.mapping||"none"} buttons=${r.gamepad.buttons.length} axes=${r.gamepad.axes.length}`));var W=new Map,re=1;window.__ddResolve=(r,e,t)=>{let n=W.get(r);W.delete(r),n&&n({status:e,body:t})};function C(r,e=""){return new Promise(t=>{let n=re++;W.set(n,t),DDCloud.call(n,r,typeof e=="string"?e:JSON.stringify(e))})}var B=r=>new Promise(e=>setTimeout(e,r)),se=r=>r.status>=200&&r.status<300;function x(r){let e=document.getElementById("status");e&&(e.textContent=r),DDCloud.status(r)}var T=class extends Error{constructor(t,n){super(t);this.stage=t;this.detail=n}};function k(r,e){if(!se(e))throw new T(r,`${e.status} ${e.body.slice(0,300)}`);return e}function oe(r,e){return new Promise(t=>{if(r.iceGatheringState==="complete")return t();let n=setTimeout(t,e);r.addEventListener("icegatheringstatechange",()=>{r.iceGatheringState==="complete"&&(clearTimeout(n),t())})})}async function de(){x("Starting the game on Xbox Cloud Gaming\u2026"),k("start",await C("start"));let r=!1,e=0;for(;;){let l=k("state",await C("state")),f=JSON.parse(l.body||"{}");if(f.state==="Provisioned")break;if(f.state==="Failed")throw new T("provision",JSON.stringify(f.errorDetails??{}).slice(0,300));f.state==="ReadyToConnect"&&!r?(r=!0,x("Signing in to the cloud console\u2026"),k("connect",await C("connect"))):f.state==="WaitingForResources"?x(`In the queue for a cloud console\u2026 ${Math.round(e/1e3)} s`):x(`Getting a cloud console ready\u2026 ${Math.round(e/1e3)} s`),await B(1e3),e+=1e3}x("Connecting\u2026");let t=new U("player");t.init();let n=t._peerConnection,i=t._channels.input,a=i.queueMetadataFrame.bind(i);i.queueMetadataFrame=l=>{if(m.preventDrops){let f=l.frameRenderedTimeMs-l.frameDecodedTimeMs;l.frameDecodedTimeMs=l.frameSubmittedTimeMs+10,l.frameRenderedTimeMs=l.frameDecodedTimeMs+f}a(l)};let s,o,d=()=>{if(!(o===void 0||s===void 0&&m.volume===100)){if(s===void 0){let l=new AudioContext;s=l.createGain(),l.createMediaStreamSource(o).connect(s).connect(l.destination);let f=document.querySelector("#player audio");f&&(f.muted=!0)}s.gain.value=m.volume/100}};n.addEventListener("track",l=>{l.track.kind==="audio"&&(o=l.streams[0],d())});let u=new V(n),h,g=()=>{let l=t.getVideoElement();if(l!==void 0){if(!X(m)){h?.pause();return}if(h===void 0)try{h=new H(l,m)}catch(f){DDCloud.log(`effects unavailable: ${String(f).slice(0,200)}`)}else h.resume(m)}};window.__ddApply=l=>{m=JSON.parse(l),window.__ddRumble=m.rumble/100,u.show(m.statsLevel,m.statsLayout==="vertical",m.server,m.statsCorner==="left"),d(),g()},n.addEventListener("connectionstatechange",()=>{n.connectionState==="connected"?(x(""),DDCloud.playing(),u.show(m.statsLevel,m.statsLayout==="vertical",m.server,m.statsCorner==="left"),setTimeout(g,500)):n.connectionState==="failed"?DDCloud.failed("webrtc","connection failed"):n.connectionState==="disconnected"&&x("Connection lost\u2026")});let p=await t.createOffer(),c=k("sdp",await C("sdp",p.sdp??"")),O=JSON.parse(JSON.parse(c.body).exchangeResponse);if(O.status&&O.status!=="success")throw new T("sdp-answer",JSON.stringify(O).slice(0,300));await t.setRemoteSDP(O.sdp),await oe(n,3e3);let Y=(await t.getICECandidates()).map(l=>JSON.stringify({candidate:l.candidate,sdpMid:l.sdpMid,sdpMLineIndex:l.sdpMLineIndex,usernameFragment:l.usernameFragment})),$=k("ice",await C("ice",Y));t.setRemoteIceCandidates(JSON.parse(JSON.parse($.body).exchangeResponse));let q=Date.now();for(;!t._channels.message._handshakeCompleted&&Date.now()-q<2e4;)await B(100);DDCloud.log(`handshake ${t._channels.message._handshakeCompleted?"done":"missing"} after ${Date.now()-q} ms`),await B(300);let b=new v(0,{enable_keyboard:!1});b.attach(t),DDCloud.log(`controllers at attach: ${Array.from(navigator.getGamepads()).filter(Boolean).length}`),window.__ddNexus=()=>{b.sendButtonState("Nexus",1),setTimeout(()=>b.sendButtonState("Nexus",0),200)},window.__ddButton=(l,f)=>b.sendButtonState(l,f),window.__ddInput=l=>{l?b.onWindowFocus():b.onWindowBlur()},setInterval(()=>{C("keepalive")},3e4),window.__ddStop=()=>{try{h?.destroy(),u.destroy(),b.detach(),t.destroy()}catch{}}}de().catch(r=>{r instanceof T?DDCloud.failed(r.stage,r.detail):DDCloud.failed("page",String(r).slice(0,300))});})();
|
|
||||||
@@ -39,10 +39,6 @@ target_link_libraries(deviceinfo dl)
|
|||||||
|
|
||||||
add_library(termux SHARED termux/termux.c)
|
add_library(termux SHARED termux/termux.c)
|
||||||
|
|
||||||
add_library(ddvenc SHARED venc/venc_server.cpp)
|
|
||||||
target_compile_features(ddvenc PRIVATE cxx_std_17)
|
|
||||||
target_link_libraries(ddvenc mediandk log)
|
|
||||||
|
|
||||||
# The optional proprietary SDK is supplied locally; its headers/libraries are not vendored.
|
# The optional proprietary SDK is supplied locally; its headers/libraries are not vendored.
|
||||||
if(DROIDDECK_VITURE_SDK_DIR)
|
if(DROIDDECK_VITURE_SDK_DIR)
|
||||||
add_library(droiddeck_viture SHARED viture/sdk_bridge.cpp)
|
add_library(droiddeck_viture SHARED viture/sdk_bridge.cpp)
|
||||||
|
|||||||
@@ -1184,9 +1184,8 @@ struct TritonSharedData {
|
|||||||
uint32_t input_length;
|
uint32_t input_length;
|
||||||
uint8_t input[64];
|
uint8_t input[64];
|
||||||
uint64_t output_seq;
|
uint64_t output_seq;
|
||||||
uint16_t output_feature;
|
uint32_t output_feature;
|
||||||
uint16_t output_length;
|
uint32_t output_length;
|
||||||
uint32_t output_ack;
|
|
||||||
uint8_t output[64];
|
uint8_t output[64];
|
||||||
uint64_t get_request;
|
uint64_t get_request;
|
||||||
uint64_t get_reply;
|
uint64_t get_reply;
|
||||||
@@ -1203,8 +1202,6 @@ static_assert(offsetof(TritonSharedData, report_id) == 16, "Triton report ID off
|
|||||||
static_assert(offsetof(TritonSharedData, input) == 24, "Triton input offset");
|
static_assert(offsetof(TritonSharedData, input) == 24, "Triton input offset");
|
||||||
static_assert(offsetof(TritonSharedData, output_seq) == 88, "Triton output sequence offset");
|
static_assert(offsetof(TritonSharedData, output_seq) == 88, "Triton output sequence offset");
|
||||||
static_assert(offsetof(TritonSharedData, output_feature) == 96, "Triton output feature offset");
|
static_assert(offsetof(TritonSharedData, output_feature) == 96, "Triton output feature offset");
|
||||||
static_assert(offsetof(TritonSharedData, output_length) == 98, "Triton output length offset");
|
|
||||||
static_assert(offsetof(TritonSharedData, output_ack) == 100, "Triton output ack offset");
|
|
||||||
static_assert(offsetof(TritonSharedData, output) == 104, "Triton output offset");
|
static_assert(offsetof(TritonSharedData, output) == 104, "Triton output offset");
|
||||||
static_assert(offsetof(TritonSharedData, get_request) == 168, "Triton feature request offset");
|
static_assert(offsetof(TritonSharedData, get_request) == 168, "Triton feature request offset");
|
||||||
static_assert(offsetof(TritonSharedData, get_reply) == 176, "Triton feature reply offset");
|
static_assert(offsetof(TritonSharedData, get_reply) == 176, "Triton feature reply offset");
|
||||||
@@ -1222,8 +1219,6 @@ static constexpr int TRITON_REPORT_ID_BYTES = 1;
|
|||||||
static constexpr int TRITON_STATE_BYTES = 45;
|
static constexpr int TRITON_STATE_BYTES = 45;
|
||||||
static constexpr int TRITON_REPORT_INTERVAL_US = 4000;
|
static constexpr int TRITON_REPORT_INTERVAL_US = 4000;
|
||||||
static constexpr int TRITON_FEATURE_TIMEOUT_MS = 500;
|
static constexpr int TRITON_FEATURE_TIMEOUT_MS = 500;
|
||||||
// The app clears output_length once it has taken a report; a writer waits this long for that before overwriting.
|
|
||||||
static constexpr int TRITON_OUTPUT_TIMEOUT_MS = 50;
|
|
||||||
static constexpr const char *TRITON_NAME = "Steam Controller";
|
static constexpr const char *TRITON_NAME = "Steam Controller";
|
||||||
static constexpr const char *TRITON_SERIAL = "DROIDDECKSC01";
|
static constexpr const char *TRITON_SERIAL = "DROIDDECKSC01";
|
||||||
static const uint8_t kTritonReportDescriptor[] = {
|
static const uint8_t kTritonReportDescriptor[] = {
|
||||||
@@ -2579,21 +2574,11 @@ __attribute__((visibility("hidden"))) static void triton_queue_output(DeckHidraw
|
|||||||
if (!data || !size || size > 64 || triton.mapping_size < TRITON_SHARED_OFFSET + TRITON_SHARED_BLOCK_SIZE) return;
|
if (!data || !size || size > 64 || triton.mapping_size < TRITON_SHARED_OFFSET + TRITON_SHARED_BLOCK_SIZE) return;
|
||||||
auto *shared = reinterpret_cast<TritonSharedData *>(reinterpret_cast<uint8_t *>(triton.ring) + TRITON_SHARED_OFFSET);
|
auto *shared = reinterpret_cast<TritonSharedData *>(reinterpret_cast<uint8_t *>(triton.ring) + TRITON_SHARED_OFFSET);
|
||||||
if (__atomic_load_n(&shared->magic, __ATOMIC_ACQUIRE) != TRITON_SHARED_MAGIC) return;
|
if (__atomic_load_n(&shared->magic, __ATOMIC_ACQUIRE) != TRITON_SHARED_MAGIC) return;
|
||||||
static std::mutex one_at_a_time;
|
|
||||||
std::lock_guard<std::mutex> guard(one_at_a_time);
|
|
||||||
for (int waited = 0;
|
|
||||||
static_cast<uint32_t>(__atomic_load_n(&shared->output_seq, __ATOMIC_ACQUIRE)) !=
|
|
||||||
__atomic_load_n(&shared->output_ack, __ATOMIC_ACQUIRE) &&
|
|
||||||
__atomic_load_n(&shared->connected, __ATOMIC_ACQUIRE) != 0 && waited < TRITON_OUTPUT_TIMEOUT_MS * 4;
|
|
||||||
waited++) {
|
|
||||||
struct timespec interval = {0, 250 * 1000L};
|
|
||||||
nanosleep(&interval, nullptr);
|
|
||||||
}
|
|
||||||
uint64_t seq = __atomic_load_n(&shared->output_seq, __ATOMIC_RELAXED);
|
uint64_t seq = __atomic_load_n(&shared->output_seq, __ATOMIC_RELAXED);
|
||||||
if (seq & 1) seq++;
|
if (seq & 1) seq++;
|
||||||
__atomic_store_n(&shared->output_seq, seq + 1, __ATOMIC_RELEASE);
|
__atomic_store_n(&shared->output_seq, seq + 1, __ATOMIC_RELEASE);
|
||||||
shared->output_feature = feature ? 1 : 0;
|
shared->output_feature = feature ? 1 : 0;
|
||||||
shared->output_length = static_cast<uint16_t>(size);
|
shared->output_length = static_cast<uint32_t>(size);
|
||||||
memcpy(shared->output, data, size);
|
memcpy(shared->output, data, size);
|
||||||
if (size < sizeof(shared->output)) memset(shared->output + size, 0, sizeof(shared->output) - size);
|
if (size < sizeof(shared->output)) memset(shared->output + size, 0, sizeof(shared->output) - size);
|
||||||
__atomic_thread_fence(__ATOMIC_RELEASE);
|
__atomic_thread_fence(__ATOMIC_RELEASE);
|
||||||
@@ -2650,38 +2635,6 @@ __attribute__((visibility("hidden"))) static int triton_get_feature(DeckHidraw &
|
|||||||
static constexpr uint32_t TRITON_HWID = 72;
|
static constexpr uint32_t TRITON_HWID = 72;
|
||||||
static constexpr uint32_t TRITON_FW_TIMESTAMP = 0x6AC686B3;
|
static constexpr uint32_t TRITON_FW_TIMESTAMP = 0x6AC686B3;
|
||||||
|
|
||||||
// Steam compares the controller's firmware with TRITON_FW_TS in its bundled hardwareupdater.cfg (and blocks
|
|
||||||
// with a required update below MUST_UPDATE_TRITON_FW_TS), so the emulated pad reports at least the build
|
|
||||||
// Steam ships.
|
|
||||||
static uint32_t triton_fw_timestamp() {
|
|
||||||
static const uint32_t timestamp = [] {
|
|
||||||
std::vector<std::string> roots;
|
|
||||||
char exe[PATH_MAX];
|
|
||||||
ssize_t n = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
|
|
||||||
if (n > 0) {
|
|
||||||
std::string path(exe, static_cast<size_t>(n));
|
|
||||||
size_t bin = path.rfind('/');
|
|
||||||
size_t root = bin == std::string::npos || bin == 0 ? std::string::npos : path.rfind('/', bin - 1);
|
|
||||||
if (bin != std::string::npos && bin > 0) roots.push_back(path.substr(0, bin));
|
|
||||||
if (root != std::string::npos) roots.push_back(path.substr(0, root));
|
|
||||||
}
|
|
||||||
if (const char *home = getenv("HOME")) roots.push_back(std::string(home) + "/.local/share/Steam");
|
|
||||||
uint32_t newest = TRITON_FW_TIMESTAMP;
|
|
||||||
for (const std::string &root : roots) {
|
|
||||||
std::ifstream cfg(root + "/bin/hardwareupdater/hardwareupdater.cfg");
|
|
||||||
std::string line;
|
|
||||||
while (std::getline(cfg, line)) {
|
|
||||||
if (line.rfind("TRITON_FW_TS:", 0) != 0) continue;
|
|
||||||
uint32_t shipped = static_cast<uint32_t>(strtoul(line.c_str() + 13, nullptr, 16));
|
|
||||||
if (shipped > newest) newest = shipped;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (newest != TRITON_FW_TIMESTAMP) Logger::log("triton: reporting firmware %08x, the build Steam ships\n", newest);
|
|
||||||
return newest;
|
|
||||||
}();
|
|
||||||
return timestamp;
|
|
||||||
}
|
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static int triton_pad_feature(DeckHidraw &triton, uint8_t *buf, size_t size, bool set) {
|
__attribute__((visibility("hidden"))) static int triton_pad_feature(DeckHidraw &triton, uint8_t *buf, size_t size, bool set) {
|
||||||
if (!buf || size < 2) {
|
if (!buf || size < 2) {
|
||||||
errno = EINVAL;
|
errno = EINVAL;
|
||||||
@@ -2702,7 +2655,7 @@ __attribute__((visibility("hidden"))) static int triton_pad_feature(DeckHidraw &
|
|||||||
switch (triton.pending_feature) {
|
switch (triton.pending_feature) {
|
||||||
case DECK_GET_ATTRIBUTES_VALUES: {
|
case DECK_GET_ATTRIBUTES_VALUES: {
|
||||||
static const uint8_t kIds[] = {0x01, 0x02, 0x04, 0x09, 0x0a, 0x0b};
|
static const uint8_t kIds[] = {0x01, 0x02, 0x04, 0x09, 0x0a, 0x0b};
|
||||||
const uint32_t values[] = {static_cast<uint32_t>(TRITON_WIRED_PRODUCT), 0, triton_fw_timestamp(), TRITON_HWID, 0, 4000};
|
const uint32_t values[] = {static_cast<uint32_t>(TRITON_WIRED_PRODUCT), 0, TRITON_FW_TIMESTAMP, TRITON_HWID, 0, 4000};
|
||||||
reply[2] = sizeof(kIds) * 5;
|
reply[2] = sizeof(kIds) * 5;
|
||||||
for (size_t i = 0; i < sizeof(kIds); i++) {
|
for (size_t i = 0; i < sizeof(kIds); i++) {
|
||||||
reply[3 + i * 5] = kIds[i];
|
reply[3 + i * 5] = kIds[i];
|
||||||
|
|||||||
@@ -184,9 +184,8 @@ bool FrameGen::onResize(VkExtent2D extent, VkFormat , bool force) {
|
|||||||
VkExtent2D e = levelExtent(extent, l);
|
VkExtent2D e = levelExtent(extent, l);
|
||||||
if (!makeImage(pyrA_[l], e, VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
|
if (!makeImage(pyrA_[l], e, VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
|
||||||
if (!makeImage(pyrB_[l], e, VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
|
if (!makeImage(pyrB_[l], e, VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
|
||||||
|
if (!makeImage(flowLvl_[l], e, VK_FORMAT_R16G16B16A16_SFLOAT, flowUsage)) return false;
|
||||||
}
|
}
|
||||||
for (int l = flowFinest_; l < kLevels; ++l)
|
|
||||||
if (!makeImage(flowLvl_[l], levelExtent(extent, l), VK_FORMAT_R16G16B16A16_SFLOAT, flowUsage)) return false;
|
|
||||||
pyrAs_.resize(kLevels);
|
pyrAs_.resize(kLevels);
|
||||||
for (int l = flowFinest_; l < kLevels; ++l)
|
for (int l = flowFinest_; l < kLevels; ++l)
|
||||||
if (!makeImage(pyrAs_[l], levelExtent(extent, l), VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
|
if (!makeImage(pyrAs_[l], levelExtent(extent, l), VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
|
||||||
|
|||||||
@@ -439,7 +439,7 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
|
|||||||
makeUbo(dd, dev, mp, sizeof(FlowRegUBO), S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr);
|
makeUbo(dd, dev, mp, sizeof(FlowRegUBO), S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr);
|
||||||
if (S.flowRegUboPtr) { FlowRegUBO fu{cfg.frDt, cfg.frLambda, cfg.frEdge, cfg.frEps}; std::memcpy(S.flowRegUboPtr, &fu, sizeof(fu)); }
|
if (S.flowRegUboPtr) { FlowRegUBO fu{cfg.frDt, cfg.frLambda, cfg.frEdge, cfg.frEps}; std::memcpy(S.flowRegUboPtr, &fu, sizeof(fu)); }
|
||||||
S.flowUbo.resize(kLevels); S.flowUboMem.resize(kLevels); S.flowUboPtr.resize(kLevels);
|
S.flowUbo.resize(kLevels); S.flowUboMem.resize(kLevels); S.flowUboPtr.resize(kLevels);
|
||||||
for (int l = fg->flowFinest(); l < kLevels; ++l) {
|
for (int l = 0; l < kLevels; ++l) {
|
||||||
makeUbo(dd, dev, mp, sizeof(FlowUBO), S.flowUbo[l], S.flowUboMem[l], S.flowUboPtr[l]);
|
makeUbo(dd, dev, mp, sizeof(FlowUBO), S.flowUbo[l], S.flowUboMem[l], S.flowUboPtr[l]);
|
||||||
if (S.flowUboPtr[l]) { FlowUBO u{cfg.flowScale, (uint32_t)l, 0.6f, 1.6f}; std::memcpy(S.flowUboPtr[l], &u, sizeof(u)); }
|
if (S.flowUboPtr[l]) { FlowUBO u{cfg.flowScale, (uint32_t)l, 0.6f, 1.6f}; std::memcpy(S.flowUboPtr[l], &u, sizeof(u)); }
|
||||||
}
|
}
|
||||||
@@ -464,12 +464,13 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
|
|||||||
}
|
}
|
||||||
|
|
||||||
S.sFlow.resize(kLevels);
|
S.sFlow.resize(kLevels);
|
||||||
for (int l = fg->flowFinest(); l < kLevels; ++l) {
|
for (int l = 0; l < kLevels; ++l) {
|
||||||
S.sFlow[l] = allocSet(dd, dev, pool, pFlow.setLayout);
|
S.sFlow[l] = allocSet(dd, dev, pool, pFlow.setLayout);
|
||||||
int pred = (l + 1 < kLevels) ? l + 1 : l;
|
int pred = (l + 1 < kLevels) ? l + 1 : l;
|
||||||
|
VkImageView currLvl = (l >= fg->flowFinest()) ? pyrAs[l].view : pyrA[l].view;
|
||||||
wUbo(dd, dev, S.sFlow[l], 0, S.flowUbo[l], sizeof(FlowUBO));
|
wUbo(dd, dev, S.sFlow[l], 0, S.flowUbo[l], sizeof(FlowUBO));
|
||||||
wImg(dd, dev, S.sFlow[l], 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrB[l].view, samp, GEN);
|
wImg(dd, dev, S.sFlow[l], 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrB[l].view, samp, GEN);
|
||||||
wImg(dd, dev, S.sFlow[l], 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrAs[l].view, samp, GEN);
|
wImg(dd, dev, S.sFlow[l], 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, currLvl, samp, GEN);
|
||||||
wImg(dd, dev, S.sFlow[l], 34, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, flowLvl[pred].view, samp, GEN);
|
wImg(dd, dev, S.sFlow[l], 34, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, flowLvl[pred].view, samp, GEN);
|
||||||
wImg(dd, dev, S.sFlow[l], 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, flowLvl[l].view, VK_NULL_HANDLE, GEN);
|
wImg(dd, dev, S.sFlow[l], 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, flowLvl[l].view, VK_NULL_HANDLE, GEN);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,81 +0,0 @@
|
|||||||
#ifndef DROIDDECK_VENC_PROTO_H
|
|
||||||
#define DROIDDECK_VENC_PROTO_H
|
|
||||||
|
|
||||||
#include <stdint.h>
|
|
||||||
|
|
||||||
/* SOCK_SEQPACKET between the guest's Remote Play hooks and the app: the emulated /dev/video-enc0 and
|
|
||||||
* MediaCodec encoder, and remote touches. A config carries the buffer memfds (inputs first) as SCM_RIGHTS;
|
|
||||||
* every frame gets one reply, touches get none. */
|
|
||||||
|
|
||||||
#define VENC_MAX_BUFFERS 16
|
|
||||||
|
|
||||||
enum venc_msg { VENC_CONFIG = 1, VENC_FRAME = 2, VENC_DONE = 3, VENC_BITRATE = 4, VENC_TOUCH = 5, VDEC_CONFIG = 6, VDEC_CAPTURE = 7, VDEC_PACKET = 8, VDEC_RESULT = 9 };
|
|
||||||
enum venc_touch_action { VENC_TOUCH_DOWN = 0, VENC_TOUCH_MOVE = 1, VENC_TOUCH_UP = 2 };
|
|
||||||
enum venc_codec { VENC_H264 = 0, VENC_HEVC = 1 };
|
|
||||||
|
|
||||||
struct venc_config {
|
|
||||||
uint32_t type;
|
|
||||||
uint32_t codec;
|
|
||||||
uint32_t width, height, stride, rows;
|
|
||||||
uint32_t fps_num, fps_den;
|
|
||||||
uint32_t bitrate, peak_bitrate, vbr;
|
|
||||||
uint32_t gop;
|
|
||||||
int32_t profile, level;
|
|
||||||
uint32_t inputs, outputs;
|
|
||||||
uint32_t input_size, output_size;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct venc_frame {
|
|
||||||
uint32_t type;
|
|
||||||
uint32_t input, output;
|
|
||||||
uint32_t bytes;
|
|
||||||
uint32_t keyframe;
|
|
||||||
int64_t pts_us;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct venc_done {
|
|
||||||
uint32_t type;
|
|
||||||
int32_t status;
|
|
||||||
uint32_t bytes;
|
|
||||||
uint32_t keyframe;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct venc_bitrate {
|
|
||||||
uint32_t type;
|
|
||||||
uint32_t bitrate;
|
|
||||||
};
|
|
||||||
|
|
||||||
/* Remote Play's touch-as-mouse turned back into a touch; x and y are fractions of the screen in 1/65535. */
|
|
||||||
struct venc_touch {
|
|
||||||
uint32_t type;
|
|
||||||
uint32_t action;
|
|
||||||
uint32_t x, y;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct vdec_config {
|
|
||||||
uint32_t type;
|
|
||||||
uint32_t codec;
|
|
||||||
uint32_t width, height;
|
|
||||||
uint32_t stride, rows;
|
|
||||||
uint32_t bitstreams, bitstream_size;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct vdec_capture {
|
|
||||||
uint32_t type;
|
|
||||||
uint32_t index;
|
|
||||||
uint32_t size;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct vdec_packet {
|
|
||||||
uint32_t type;
|
|
||||||
uint32_t input, bytes, capture;
|
|
||||||
int64_t pts_us;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct vdec_result {
|
|
||||||
uint32_t type;
|
|
||||||
int32_t status;
|
|
||||||
uint32_t frame;
|
|
||||||
};
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -1,585 +0,0 @@
|
|||||||
#include <android/log.h>
|
|
||||||
#include <dlfcn.h>
|
|
||||||
#include <jni.h>
|
|
||||||
#include <media/NdkMediaCodec.h>
|
|
||||||
#include <media/NdkMediaFormat.h>
|
|
||||||
#include <sys/ioctl.h>
|
|
||||||
#include <sys/mman.h>
|
|
||||||
#include <sys/socket.h>
|
|
||||||
#include <sys/stat.h>
|
|
||||||
#include <sys/un.h>
|
|
||||||
#include <unistd.h>
|
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <atomic>
|
|
||||||
#include <chrono>
|
|
||||||
#include <cerrno>
|
|
||||||
#include <cstring>
|
|
||||||
#include <string>
|
|
||||||
#include <thread>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#include "venc_proto.h"
|
|
||||||
|
|
||||||
#define LOG(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckVenc", __VA_ARGS__)
|
|
||||||
|
|
||||||
namespace {
|
|
||||||
|
|
||||||
struct Mapping {
|
|
||||||
uint8_t *data = nullptr;
|
|
||||||
size_t size = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
constexpr int32_t kColorFormatYuv420SemiPlanar = 21;
|
|
||||||
constexpr uint32_t kBufferFlagKeyFrame = 1;
|
|
||||||
constexpr uint32_t kBufferFlagCodecConfig = 2;
|
|
||||||
constexpr int kTouchWidth = 1920, kTouchHeight = 1080; // InputSpace.kt
|
|
||||||
constexpr int kRemoteTouchId = 31; // the compositor's last touch slot (MAX_TOUCH_POINTS 32)
|
|
||||||
|
|
||||||
int32_t avc_profile(int32_t v4l2) {
|
|
||||||
switch (v4l2) {
|
|
||||||
case 0: return 1;
|
|
||||||
case 1: return 0x10000;
|
|
||||||
case 2: return 2;
|
|
||||||
case 3: return 4;
|
|
||||||
case 4: return 8;
|
|
||||||
default: return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct DmaBufSync {
|
|
||||||
uint64_t flags;
|
|
||||||
};
|
|
||||||
constexpr unsigned long kDmaBufIoctlSync = _IOW('b', 0, DmaBufSync);
|
|
||||||
constexpr uint64_t kDmaBufSyncWrite = 2, kDmaBufSyncStart = 0, kDmaBufSyncEnd = 4;
|
|
||||||
constexpr int32_t kColorFormatYuv420Planar = 19;
|
|
||||||
|
|
||||||
class Decoder {
|
|
||||||
public:
|
|
||||||
~Decoder() { release(); }
|
|
||||||
|
|
||||||
void release() {
|
|
||||||
if (codec_) {
|
|
||||||
AMediaCodec_stop(codec_);
|
|
||||||
AMediaCodec_delete(codec_);
|
|
||||||
codec_ = nullptr;
|
|
||||||
}
|
|
||||||
if (bitstream_) munmap((void *)bitstream_, bitstream_size_);
|
|
||||||
bitstream_ = nullptr;
|
|
||||||
for (auto &c : captures_) drop(c);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool configure(const vdec_config &c, int fd) {
|
|
||||||
release();
|
|
||||||
if (c.width < 16 || c.height < 16 || c.stride < c.width || c.rows < c.height || c.bitstreams == 0 ||
|
|
||||||
c.bitstreams > VENC_MAX_BUFFERS || c.bitstream_size == 0) {
|
|
||||||
LOG("bad decoder config: %ux%u stride %u rows %u, %u bitstreams", c.width, c.height, c.stride, c.rows,
|
|
||||||
c.bitstreams);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
bitstream_size_ = (size_t)c.bitstreams * c.bitstream_size;
|
|
||||||
void *p = mmap(nullptr, bitstream_size_, PROT_READ, MAP_SHARED, fd, 0);
|
|
||||||
if (p == MAP_FAILED) {
|
|
||||||
LOG("could not map the bitstream buffers: %s", strerror(errno));
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
bitstream_ = (const uint8_t *)p;
|
|
||||||
config_ = c;
|
|
||||||
codec_ = create(c, true);
|
|
||||||
if (!codec_) codec_ = create(c, false);
|
|
||||||
if (!codec_) {
|
|
||||||
LOG("no %s decoder for %ux%u", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height);
|
|
||||||
release();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
src_stride_ = (int32_t)c.width;
|
|
||||||
src_rows_ = (int32_t)c.height;
|
|
||||||
src_width_ = (int32_t)c.width;
|
|
||||||
src_height_ = (int32_t)c.height;
|
|
||||||
src_planar_ = false;
|
|
||||||
shown_ = false;
|
|
||||||
using GetName = media_status_t (*)(AMediaCodec *, char **);
|
|
||||||
using ReleaseName = void (*)(AMediaCodec *, char *);
|
|
||||||
static auto get_name = (GetName)dlsym(RTLD_DEFAULT, "AMediaCodec_getName");
|
|
||||||
static auto release_name = (ReleaseName)dlsym(RTLD_DEFAULT, "AMediaCodec_releaseName");
|
|
||||||
char *name = nullptr;
|
|
||||||
if (get_name && get_name(codec_, &name) != AMEDIA_OK) name = nullptr;
|
|
||||||
LOG("decoding %s %ux%u with %s", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height,
|
|
||||||
name ? name : "MediaCodec");
|
|
||||||
if (name && release_name) release_name(codec_, name);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
void capture(const vdec_capture &c, int fd) {
|
|
||||||
if (c.index >= VENC_MAX_BUFFERS) {
|
|
||||||
close(fd);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Capture &cap = captures_[c.index];
|
|
||||||
drop(cap);
|
|
||||||
void *p = mmap(nullptr, c.size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
|
||||||
if (p == MAP_FAILED) {
|
|
||||||
LOG("could not map capture buffer %u: %s", c.index, strerror(errno));
|
|
||||||
close(fd);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
cap = {fd, (uint8_t *)p, c.size};
|
|
||||||
}
|
|
||||||
|
|
||||||
bool decode(const vdec_packet &p, bool *frame) {
|
|
||||||
*frame = false;
|
|
||||||
if (!codec_ || p.capture >= VENC_MAX_BUFFERS || !captures_[p.capture].data || p.input >= config_.bitstreams ||
|
|
||||||
p.bytes == 0 || p.bytes > config_.bitstream_size)
|
|
||||||
return false;
|
|
||||||
auto start = std::chrono::steady_clock::now();
|
|
||||||
ssize_t in = AMediaCodec_dequeueInputBuffer(codec_, 20000);
|
|
||||||
if (in < 0) return false;
|
|
||||||
size_t capacity = 0;
|
|
||||||
uint8_t *dst = AMediaCodec_getInputBuffer(codec_, (size_t)in, &capacity);
|
|
||||||
if (!dst || capacity < p.bytes) {
|
|
||||||
AMediaCodec_queueInputBuffer(codec_, (size_t)in, 0, 0, 0, 0);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
memcpy(dst, bitstream_ + (size_t)p.input * config_.bitstream_size, p.bytes);
|
|
||||||
if (AMediaCodec_queueInputBuffer(codec_, (size_t)in, 0, p.bytes, (uint64_t)std::max<int64_t>(p.pts_us, 0), 0) !=
|
|
||||||
AMEDIA_OK)
|
|
||||||
return false;
|
|
||||||
auto wait = std::chrono::milliseconds(shown_ ? 25 : 250);
|
|
||||||
while (std::chrono::steady_clock::now() - start < wait) {
|
|
||||||
AMediaCodecBufferInfo info;
|
|
||||||
ssize_t o = AMediaCodec_dequeueOutputBuffer(codec_, &info, 2000);
|
|
||||||
if (o == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
|
|
||||||
read_format();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (o < 0) continue;
|
|
||||||
size_t size = 0;
|
|
||||||
uint8_t *data = AMediaCodec_getOutputBuffer(codec_, (size_t)o, &size);
|
|
||||||
if (data && info.size > 0 && (size_t)info.offset + (size_t)info.size <= size)
|
|
||||||
*frame = copy(data + info.offset, (size_t)info.size, captures_[p.capture]) || *frame;
|
|
||||||
AMediaCodec_releaseOutputBuffer(codec_, (size_t)o, false);
|
|
||||||
if (info.presentationTimeUs >= p.pts_us) break;
|
|
||||||
}
|
|
||||||
shown_ = shown_ || *frame;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
struct Capture {
|
|
||||||
int fd = -1;
|
|
||||||
uint8_t *data = nullptr;
|
|
||||||
size_t size = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
static void drop(Capture &c) {
|
|
||||||
if (c.data) munmap(c.data, c.size);
|
|
||||||
if (c.fd >= 0) close(c.fd);
|
|
||||||
c = Capture();
|
|
||||||
}
|
|
||||||
|
|
||||||
AMediaCodec *create(const vdec_config &c, bool low_latency) {
|
|
||||||
const char *mime = c.codec == VENC_HEVC ? "video/hevc" : "video/avc";
|
|
||||||
AMediaCodec *codec = AMediaCodec_createDecoderByType(mime);
|
|
||||||
if (!codec) return nullptr;
|
|
||||||
AMediaFormat *f = AMediaFormat_new();
|
|
||||||
AMediaFormat_setString(f, AMEDIAFORMAT_KEY_MIME, mime);
|
|
||||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_WIDTH, (int32_t)c.width);
|
|
||||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_HEIGHT, (int32_t)c.height);
|
|
||||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_COLOR_FORMAT, kColorFormatYuv420SemiPlanar);
|
|
||||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_MAX_INPUT_SIZE, (int32_t)c.bitstream_size);
|
|
||||||
if (low_latency) {
|
|
||||||
AMediaFormat_setInt32(f, "low-latency", 1);
|
|
||||||
AMediaFormat_setInt32(f, "vendor.qti-ext-dec-low-latency.enable", 1);
|
|
||||||
AMediaFormat_setInt32(f, "vendor.qti-ext-dec-picture-order.enable", 1);
|
|
||||||
AMediaFormat_setInt32(f, "priority", 0);
|
|
||||||
AMediaFormat_setFloat(f, "operating-rate", 120.0f);
|
|
||||||
}
|
|
||||||
media_status_t s = AMediaCodec_configure(codec, f, nullptr, nullptr, 0);
|
|
||||||
AMediaFormat_delete(f);
|
|
||||||
if (s == AMEDIA_OK) s = AMediaCodec_start(codec);
|
|
||||||
if (s != AMEDIA_OK) {
|
|
||||||
AMediaCodec_delete(codec);
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
return codec;
|
|
||||||
}
|
|
||||||
|
|
||||||
void read_format() {
|
|
||||||
AMediaFormat *f = AMediaCodec_getOutputFormat(codec_);
|
|
||||||
if (!f) return;
|
|
||||||
int32_t v;
|
|
||||||
if (AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_WIDTH, &v) && v > 0) src_width_ = v;
|
|
||||||
if (AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_HEIGHT, &v) && v > 0) src_height_ = v;
|
|
||||||
src_stride_ = AMediaFormat_getInt32(f, "stride", &v) && v >= src_width_ ? v : src_width_;
|
|
||||||
src_rows_ = AMediaFormat_getInt32(f, "slice-height", &v) && v >= src_height_ ? v : src_height_;
|
|
||||||
src_planar_ = AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_COLOR_FORMAT, &v) && v == kColorFormatYuv420Planar;
|
|
||||||
LOG("decoder output %dx%d stride %d rows %d %s", src_width_, src_height_, src_stride_, src_rows_,
|
|
||||||
src_planar_ ? "planar" : "semi-planar");
|
|
||||||
AMediaFormat_delete(f);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool copy(const uint8_t *src, size_t size, const Capture &cap) {
|
|
||||||
size_t luma = (size_t)src_stride_ * src_rows_;
|
|
||||||
size_t chroma = src_planar_ ? 2 * (size_t)(src_stride_ / 2) * (src_rows_ / 2) : (size_t)src_stride_ * (src_rows_ / 2);
|
|
||||||
if (size < luma + chroma) return false;
|
|
||||||
uint32_t w = std::min<uint32_t>((uint32_t)src_width_, config_.stride);
|
|
||||||
uint32_t h = std::min<uint32_t>((uint32_t)src_height_, config_.rows);
|
|
||||||
if ((size_t)config_.stride * config_.rows * 3 / 2 > cap.size) return false;
|
|
||||||
DmaBufSync sync = {kDmaBufSyncStart | kDmaBufSyncWrite};
|
|
||||||
ioctl(cap.fd, kDmaBufIoctlSync, &sync);
|
|
||||||
uint8_t *y = cap.data, *uv = cap.data + (size_t)config_.stride * config_.rows;
|
|
||||||
for (uint32_t row = 0; row < h; row++)
|
|
||||||
memcpy(y + (size_t)row * config_.stride, src + (size_t)row * src_stride_, w);
|
|
||||||
const uint8_t *su = src + luma;
|
|
||||||
for (uint32_t row = 0; row < h / 2; row++) {
|
|
||||||
uint8_t *d = uv + (size_t)row * config_.stride;
|
|
||||||
if (!src_planar_) {
|
|
||||||
memcpy(d, su + (size_t)row * src_stride_, w & ~1u);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const uint8_t *u = su + (size_t)row * (src_stride_ / 2);
|
|
||||||
const uint8_t *vv = su + (size_t)(src_stride_ / 2) * (src_rows_ / 2) + (size_t)row * (src_stride_ / 2);
|
|
||||||
for (uint32_t x = 0; x < w / 2; x++) {
|
|
||||||
d[2 * x] = u[x];
|
|
||||||
d[2 * x + 1] = vv[x];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sync.flags = kDmaBufSyncEnd | kDmaBufSyncWrite;
|
|
||||||
ioctl(cap.fd, kDmaBufIoctlSync, &sync);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
AMediaCodec *codec_ = nullptr;
|
|
||||||
vdec_config config_ = {};
|
|
||||||
const uint8_t *bitstream_ = nullptr;
|
|
||||||
size_t bitstream_size_ = 0;
|
|
||||||
Capture captures_[VENC_MAX_BUFFERS];
|
|
||||||
int32_t src_width_ = 0, src_height_ = 0, src_stride_ = 0, src_rows_ = 0;
|
|
||||||
bool src_planar_ = false;
|
|
||||||
bool shown_ = false;
|
|
||||||
};
|
|
||||||
|
|
||||||
class Session {
|
|
||||||
public:
|
|
||||||
explicit Session(int fd) : fd_(fd) {}
|
|
||||||
~Session() {
|
|
||||||
release();
|
|
||||||
close(fd_);
|
|
||||||
}
|
|
||||||
|
|
||||||
void run() {
|
|
||||||
for (;;) {
|
|
||||||
uint8_t buf[256];
|
|
||||||
int fds[VENC_MAX_BUFFERS * 2];
|
|
||||||
int nfds = 0;
|
|
||||||
ssize_t n = receive(buf, sizeof buf, fds, &nfds);
|
|
||||||
if (n <= 0) return;
|
|
||||||
uint32_t type;
|
|
||||||
memcpy(&type, buf, sizeof type);
|
|
||||||
if (type == VENC_CONFIG && n == (ssize_t)sizeof(venc_config)) {
|
|
||||||
venc_config c;
|
|
||||||
memcpy(&c, buf, sizeof c);
|
|
||||||
bool ok = configure(c, fds, nfds);
|
|
||||||
for (int i = 0; i < nfds; i++) close(fds[i]);
|
|
||||||
reply(ok ? 0 : -1, 0, false);
|
|
||||||
} else if (type == VENC_FRAME && n == (ssize_t)sizeof(venc_frame)) {
|
|
||||||
venc_frame f;
|
|
||||||
memcpy(&f, buf, sizeof f);
|
|
||||||
uint32_t bytes = 0;
|
|
||||||
bool key = false;
|
|
||||||
bool ok = encode(f, &bytes, &key);
|
|
||||||
reply(ok ? 0 : -1, bytes, key);
|
|
||||||
} else if (type == VENC_TOUCH && n == (ssize_t)sizeof(venc_touch)) {
|
|
||||||
venc_touch t;
|
|
||||||
memcpy(&t, buf, sizeof t);
|
|
||||||
touch(t);
|
|
||||||
for (int i = 0; i < nfds; i++) close(fds[i]);
|
|
||||||
} else if (type == VENC_BITRATE && n == (ssize_t)sizeof(venc_bitrate)) {
|
|
||||||
venc_bitrate b;
|
|
||||||
memcpy(&b, buf, sizeof b);
|
|
||||||
set_bitrate(b.bitrate);
|
|
||||||
for (int i = 0; i < nfds; i++) close(fds[i]);
|
|
||||||
} else if (type == VDEC_CONFIG && n == (ssize_t)sizeof(vdec_config)) {
|
|
||||||
vdec_config c;
|
|
||||||
memcpy(&c, buf, sizeof c);
|
|
||||||
bool ok = nfds == 1 && decoder_.configure(c, fds[0]);
|
|
||||||
for (int i = 0; i < nfds; i++) close(fds[i]);
|
|
||||||
decoded(ok ? 0 : -1, false);
|
|
||||||
} else if (type == VDEC_CAPTURE && n == (ssize_t)sizeof(vdec_capture)) {
|
|
||||||
vdec_capture c;
|
|
||||||
memcpy(&c, buf, sizeof c);
|
|
||||||
if (nfds == 1) decoder_.capture(c, fds[0]);
|
|
||||||
else for (int i = 0; i < nfds; i++) close(fds[i]);
|
|
||||||
} else if (type == VDEC_PACKET && n == (ssize_t)sizeof(vdec_packet)) {
|
|
||||||
vdec_packet p;
|
|
||||||
memcpy(&p, buf, sizeof p);
|
|
||||||
bool frame = false;
|
|
||||||
bool ok = decoder_.decode(p, &frame);
|
|
||||||
for (int i = 0; i < nfds; i++) close(fds[i]);
|
|
||||||
decoded(ok ? 0 : -1, frame);
|
|
||||||
} else {
|
|
||||||
LOG("unexpected message %u of %zd bytes; closing", type, n);
|
|
||||||
for (int i = 0; i < nfds; i++) close(fds[i]);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
ssize_t receive(uint8_t *buf, size_t len, int *fds, int *nfds) {
|
|
||||||
char control[CMSG_SPACE(sizeof(int) * VENC_MAX_BUFFERS * 2)];
|
|
||||||
iovec iov = {buf, len};
|
|
||||||
msghdr m = {};
|
|
||||||
m.msg_iov = &iov;
|
|
||||||
m.msg_iovlen = 1;
|
|
||||||
m.msg_control = control;
|
|
||||||
m.msg_controllen = sizeof control;
|
|
||||||
ssize_t n = recvmsg(fd_, &m, MSG_CMSG_CLOEXEC);
|
|
||||||
for (cmsghdr *c = CMSG_FIRSTHDR(&m); n > 0 && c; c = CMSG_NXTHDR(&m, c)) {
|
|
||||||
if (c->cmsg_level != SOL_SOCKET || c->cmsg_type != SCM_RIGHTS) continue;
|
|
||||||
int count = (int)((c->cmsg_len - CMSG_LEN(0)) / sizeof(int));
|
|
||||||
memcpy(fds, CMSG_DATA(c), sizeof(int) * std::min(count, VENC_MAX_BUFFERS * 2));
|
|
||||||
*nfds = std::min(count, VENC_MAX_BUFFERS * 2);
|
|
||||||
}
|
|
||||||
return n;
|
|
||||||
}
|
|
||||||
|
|
||||||
void reply(int32_t status, uint32_t bytes, bool key) {
|
|
||||||
venc_done d = {VENC_DONE, status, bytes, key ? 1u : 0u};
|
|
||||||
send(fd_, &d, sizeof d, MSG_NOSIGNAL);
|
|
||||||
}
|
|
||||||
|
|
||||||
void decoded(int32_t status, bool frame) {
|
|
||||||
vdec_result r = {VDEC_RESULT, status, frame ? 1u : 0u};
|
|
||||||
send(fd_, &r, sizeof r, MSG_NOSIGNAL);
|
|
||||||
}
|
|
||||||
|
|
||||||
void release() {
|
|
||||||
decoder_.release();
|
|
||||||
if (codec_) {
|
|
||||||
AMediaCodec_stop(codec_);
|
|
||||||
AMediaCodec_delete(codec_);
|
|
||||||
codec_ = nullptr;
|
|
||||||
}
|
|
||||||
for (auto &m : inputs_) munmap(m.data, m.size);
|
|
||||||
for (auto &m : outputs_) munmap(m.data, m.size);
|
|
||||||
inputs_.clear();
|
|
||||||
outputs_.clear();
|
|
||||||
header_.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
AMediaCodec *create(const venc_config &c, bool with_profile) {
|
|
||||||
const char *mime = c.codec == VENC_HEVC ? "video/hevc" : "video/avc";
|
|
||||||
AMediaCodec *codec = AMediaCodec_createEncoderByType(mime);
|
|
||||||
if (!codec) return nullptr;
|
|
||||||
float fps = c.fps_num ? (float)c.fps_den / (float)c.fps_num : 60.0f;
|
|
||||||
AMediaFormat *f = AMediaFormat_new();
|
|
||||||
AMediaFormat_setString(f, AMEDIAFORMAT_KEY_MIME, mime);
|
|
||||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_WIDTH, (int32_t)c.width);
|
|
||||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_HEIGHT, (int32_t)c.height);
|
|
||||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_COLOR_FORMAT, kColorFormatYuv420SemiPlanar);
|
|
||||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_BIT_RATE, (int32_t)std::max(c.bitrate, 500000u));
|
|
||||||
AMediaFormat_setInt32(f, "bitrate-mode", c.vbr ? 1 : 2);
|
|
||||||
AMediaFormat_setFloat(f, AMEDIAFORMAT_KEY_FRAME_RATE, fps);
|
|
||||||
AMediaFormat_setFloat(f, "operating-rate", fps);
|
|
||||||
AMediaFormat_setInt32(f, "priority", 0);
|
|
||||||
AMediaFormat_setInt32(f, "latency", 1);
|
|
||||||
AMediaFormat_setInt32(f, "max-bframes", 0);
|
|
||||||
AMediaFormat_setInt32(f, "prepend-sps-pps-to-idr-frames", 1);
|
|
||||||
float gop_seconds = c.gop && c.gop < 0xffff ? (float)c.gop / fps : 3600.0f;
|
|
||||||
AMediaFormat_setFloat(f, AMEDIAFORMAT_KEY_I_FRAME_INTERVAL, std::max(gop_seconds, 0.1f));
|
|
||||||
if (with_profile) {
|
|
||||||
int32_t profile = c.codec == VENC_HEVC ? (c.profile == 2 ? 2 : 1) : avc_profile(c.profile);
|
|
||||||
if (profile) AMediaFormat_setInt32(f, "profile", profile);
|
|
||||||
}
|
|
||||||
media_status_t s = AMediaCodec_configure(codec, f, nullptr, nullptr, AMEDIACODEC_CONFIGURE_FLAG_ENCODE);
|
|
||||||
AMediaFormat_delete(f);
|
|
||||||
if (s == AMEDIA_OK) s = AMediaCodec_start(codec);
|
|
||||||
if (s != AMEDIA_OK) {
|
|
||||||
AMediaCodec_delete(codec);
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
return codec;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool configure(const venc_config &c, const int *fds, int nfds) {
|
|
||||||
release();
|
|
||||||
if (c.inputs + c.outputs != (uint32_t)nfds || c.width < 64 || c.height < 64 || c.stride < c.width ||
|
|
||||||
c.rows < c.height || (uint64_t)c.stride * c.rows * 3 / 2 > c.input_size) {
|
|
||||||
LOG("bad config: %u+%u buffers for %d fds, %ux%u stride %u", c.inputs, c.outputs, nfds, c.width, c.height,
|
|
||||||
c.stride);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
for (int i = 0; i < nfds; i++) {
|
|
||||||
bool input = (uint32_t)i < c.inputs;
|
|
||||||
size_t size = input ? c.input_size : c.output_size;
|
|
||||||
void *p = mmap(nullptr, size, input ? PROT_READ : PROT_READ | PROT_WRITE, MAP_SHARED, fds[i], 0);
|
|
||||||
if (p == MAP_FAILED) {
|
|
||||||
LOG("could not map buffer %d: %s", i, strerror(errno));
|
|
||||||
release();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
(input ? inputs_ : outputs_).push_back({(uint8_t *)p, size});
|
|
||||||
}
|
|
||||||
codec_ = create(c, true);
|
|
||||||
if (!codec_) codec_ = create(c, false);
|
|
||||||
if (!codec_) {
|
|
||||||
LOG("no %s encoder for %ux%u", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height);
|
|
||||||
release();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
config_ = c;
|
|
||||||
dst_stride_ = (int32_t)c.width;
|
|
||||||
dst_rows_ = (int32_t)c.height;
|
|
||||||
using InputFormat = AMediaFormat *(*)(AMediaCodec *);
|
|
||||||
static auto input_format = (InputFormat)dlsym(RTLD_DEFAULT, "AMediaCodec_getInputFormat");
|
|
||||||
if (AMediaFormat *in = input_format ? input_format(codec_) : nullptr) {
|
|
||||||
int32_t v;
|
|
||||||
if (AMediaFormat_getInt32(in, "stride", &v) && v >= (int32_t)c.width) dst_stride_ = v;
|
|
||||||
if (AMediaFormat_getInt32(in, "slice-height", &v) && v >= (int32_t)c.height) dst_rows_ = v;
|
|
||||||
AMediaFormat_delete(in);
|
|
||||||
}
|
|
||||||
LOG("%s %ux%u at %.2f fps, %u kbit/s %s, input stride %d rows %d", c.codec == VENC_HEVC ? "HEVC" : "H.264",
|
|
||||||
c.width, c.height, c.fps_num ? (double)c.fps_den / c.fps_num : 0.0, c.bitrate / 1000,
|
|
||||||
c.vbr ? "VBR" : "CBR", dst_stride_, dst_rows_);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void touch(const venc_touch &t) {
|
|
||||||
using SendTouch = void (*)(int, int, int, int);
|
|
||||||
static SendTouch send_touch = [] {
|
|
||||||
void *wayland = dlopen("libdroiddeckwayland.so", RTLD_NOW | RTLD_NOLOAD);
|
|
||||||
auto fn = wayland ? (SendTouch)dlsym(wayland, "droiddeck_wayland_send_touch") : nullptr;
|
|
||||||
if (!fn) LOG("remote touch unavailable: %s", dlerror());
|
|
||||||
return fn;
|
|
||||||
}();
|
|
||||||
if (!send_touch || t.action > VENC_TOUCH_UP) return;
|
|
||||||
int x = (int)((uint64_t)std::min(t.x, 65535u) * (kTouchWidth - 1) / 65535);
|
|
||||||
int y = (int)((uint64_t)std::min(t.y, 65535u) * (kTouchHeight - 1) / 65535);
|
|
||||||
send_touch((int)t.action, kRemoteTouchId, x, y);
|
|
||||||
}
|
|
||||||
|
|
||||||
void set_bitrate(uint32_t bitrate) {
|
|
||||||
if (!codec_) return;
|
|
||||||
AMediaFormat *p = AMediaFormat_new();
|
|
||||||
AMediaFormat_setInt32(p, "video-bitrate", (int32_t)std::max(bitrate, 500000u));
|
|
||||||
AMediaCodec_setParameters(codec_, p);
|
|
||||||
AMediaFormat_delete(p);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool encode(const venc_frame &f, uint32_t *bytes, bool *key) {
|
|
||||||
if (!codec_ || f.input >= inputs_.size() || f.output >= outputs_.size()) return false;
|
|
||||||
if (f.keyframe) {
|
|
||||||
AMediaFormat *p = AMediaFormat_new();
|
|
||||||
AMediaFormat_setInt32(p, "request-sync", 0);
|
|
||||||
AMediaCodec_setParameters(codec_, p);
|
|
||||||
AMediaFormat_delete(p);
|
|
||||||
}
|
|
||||||
ssize_t in = AMediaCodec_dequeueInputBuffer(codec_, 100000);
|
|
||||||
if (in < 0) return false;
|
|
||||||
size_t capacity = 0;
|
|
||||||
uint8_t *dst = AMediaCodec_getInputBuffer(codec_, (size_t)in, &capacity);
|
|
||||||
size_t need = (size_t)dst_stride_ * dst_rows_ + (size_t)dst_stride_ * ((config_.height + 1) / 2);
|
|
||||||
if (!dst || capacity < need) return false;
|
|
||||||
const uint8_t *src = inputs_[f.input].data;
|
|
||||||
for (uint32_t y = 0; y < config_.height; y++)
|
|
||||||
memcpy(dst + (size_t)y * dst_stride_, src + (size_t)y * config_.stride, config_.width);
|
|
||||||
const uint8_t *src_uv = src + (size_t)config_.stride * config_.rows;
|
|
||||||
uint8_t *dst_uv = dst + (size_t)dst_stride_ * dst_rows_;
|
|
||||||
for (uint32_t y = 0; y < (config_.height + 1) / 2; y++)
|
|
||||||
memcpy(dst_uv + (size_t)y * dst_stride_, src_uv + (size_t)y * config_.stride, config_.width);
|
|
||||||
if (AMediaCodec_queueInputBuffer(codec_, (size_t)in, 0, need, (uint64_t)std::max<int64_t>(f.pts_us, 0), 0) !=
|
|
||||||
AMEDIA_OK)
|
|
||||||
return false;
|
|
||||||
Mapping &out = outputs_[f.output];
|
|
||||||
for (int tries = 0; tries < 20; tries++) {
|
|
||||||
AMediaCodecBufferInfo info;
|
|
||||||
ssize_t o = AMediaCodec_dequeueOutputBuffer(codec_, &info, 20000);
|
|
||||||
if (o == AMEDIACODEC_INFO_TRY_AGAIN_LATER || o == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED ||
|
|
||||||
o == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED)
|
|
||||||
continue;
|
|
||||||
if (o < 0) return false;
|
|
||||||
size_t size = 0;
|
|
||||||
uint8_t *data = AMediaCodec_getOutputBuffer(codec_, (size_t)o, &size);
|
|
||||||
const uint8_t *payload = data ? data + info.offset : nullptr;
|
|
||||||
size_t length = data ? (size_t)info.size : 0;
|
|
||||||
if (info.flags & kBufferFlagCodecConfig) {
|
|
||||||
header_.assign(payload, payload + length);
|
|
||||||
AMediaCodec_releaseOutputBuffer(codec_, (size_t)o, false);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
*key = (info.flags & kBufferFlagKeyFrame) != 0;
|
|
||||||
bool prepend = *key && !header_.empty() &&
|
|
||||||
(length < header_.size() || memcmp(payload, header_.data(), header_.size()) != 0);
|
|
||||||
size_t total = length + (prepend ? header_.size() : 0);
|
|
||||||
bool fits = payload && total <= out.size;
|
|
||||||
if (fits) {
|
|
||||||
if (prepend) memcpy(out.data, header_.data(), header_.size());
|
|
||||||
memcpy(out.data + (prepend ? header_.size() : 0), payload, length);
|
|
||||||
*bytes = (uint32_t)total;
|
|
||||||
}
|
|
||||||
AMediaCodec_releaseOutputBuffer(codec_, (size_t)o, false);
|
|
||||||
return fits;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
int fd_;
|
|
||||||
AMediaCodec *codec_ = nullptr;
|
|
||||||
venc_config config_ = {};
|
|
||||||
int32_t dst_stride_ = 0, dst_rows_ = 0;
|
|
||||||
std::vector<Mapping> inputs_, outputs_;
|
|
||||||
std::vector<uint8_t> header_;
|
|
||||||
Decoder decoder_;
|
|
||||||
};
|
|
||||||
|
|
||||||
std::atomic<int> g_listener{-1};
|
|
||||||
|
|
||||||
void serve(int listener) {
|
|
||||||
for (;;) {
|
|
||||||
int fd = accept4(listener, nullptr, nullptr, SOCK_CLOEXEC);
|
|
||||||
if (fd < 0) {
|
|
||||||
if (errno == EINTR) continue;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
std::thread([fd] {
|
|
||||||
Session s(fd);
|
|
||||||
s.run();
|
|
||||||
}).detach();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
extern "C" JNIEXPORT jboolean JNICALL
|
|
||||||
Java_com_droiddeck_launcher_session_VideoEncodeBridge_nativeStart(JNIEnv *env, jobject, jstring jpath) {
|
|
||||||
if (g_listener.load() >= 0) return JNI_TRUE;
|
|
||||||
const char *path = env->GetStringUTFChars(jpath, nullptr);
|
|
||||||
sockaddr_un addr = {};
|
|
||||||
addr.sun_family = AF_UNIX;
|
|
||||||
bool fits = strlen(path) < sizeof addr.sun_path;
|
|
||||||
if (fits) strcpy(addr.sun_path, path);
|
|
||||||
int fd = fits ? socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0) : -1;
|
|
||||||
if (fd >= 0) {
|
|
||||||
unlink(path);
|
|
||||||
if (bind(fd, (sockaddr *)&addr, sizeof addr) != 0 || listen(fd, 4) != 0) {
|
|
||||||
LOG("could not listen on %s: %s", path, strerror(errno));
|
|
||||||
close(fd);
|
|
||||||
fd = -1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
env->ReleaseStringUTFChars(jpath, path);
|
|
||||||
if (fd < 0) return JNI_FALSE;
|
|
||||||
g_listener.store(fd);
|
|
||||||
std::thread(serve, fd).detach();
|
|
||||||
return JNI_TRUE;
|
|
||||||
}
|
|
||||||
|
|
||||||
extern "C" JNIEXPORT void JNICALL
|
|
||||||
Java_com_droiddeck_launcher_session_VideoEncodeBridge_nativeStop(JNIEnv *, jobject) {
|
|
||||||
int fd = g_listener.exchange(-1);
|
|
||||||
if (fd >= 0) {
|
|
||||||
shutdown(fd, SHUT_RDWR);
|
|
||||||
close(fd);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -8,7 +8,6 @@ add_library(droiddeckwayland SHARED
|
|||||||
src/sc_layer.c
|
src/sc_layer.c
|
||||||
src/ahb_swapchain.c
|
src/ahb_swapchain.c
|
||||||
src/waylandcomp_jni.c
|
src/waylandcomp_jni.c
|
||||||
src/gpu_clock_pin.c
|
|
||||||
src/droiddeck_ext.c
|
src/droiddeck_ext.c
|
||||||
src/wl_dmabuf.c
|
src/wl_dmabuf.c
|
||||||
src/wl_clipboard.c
|
src/wl_clipboard.c
|
||||||
@@ -95,5 +94,4 @@ target_link_libraries(droiddeckwayland
|
|||||||
dl
|
dl
|
||||||
log
|
log
|
||||||
android
|
android
|
||||||
nativewindow
|
|
||||||
)
|
)
|
||||||
@@ -371,8 +371,8 @@ void ahb_swapchain_set_mode(int on, int live) {
|
|||||||
: "; gralloc frames still in flight stay on the layer (or take the copy path) until then");
|
: "; gralloc frames still in flight stay on the layer (or take the copy path) until then");
|
||||||
else
|
else
|
||||||
droiddeck_log("layer", "zero-copy: %s at launch (%s)", on ? "on" : "off",
|
droiddeck_log("layer", "zero-copy: %s at launch (%s)", on ? "on" : "off",
|
||||||
on ? "HDR session: games present their own gralloc buffers on the display layer"
|
on ? "DROIDDECK_WAYLAND_ZERO_COPY=1: games present their own gralloc buffers on the display layer"
|
||||||
: "only HDR sessions turn it on");
|
: "the drawer's Zero-copy presentation switch turns it on live");
|
||||||
if (live) wl_display_flush_clients(droiddeck_get_display());
|
if (live) wl_display_flush_clients(droiddeck_get_display());
|
||||||
droiddeck_request_redraw();
|
droiddeck_request_redraw();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,6 @@
|
|||||||
#include <sys/syscall.h>
|
#include <sys/syscall.h>
|
||||||
#include <sys/sysmacros.h>
|
#include <sys/sysmacros.h>
|
||||||
#include <android/log.h>
|
#include <android/log.h>
|
||||||
#include <android/hardware_buffer.h>
|
|
||||||
#include <wayland-server.h>
|
#include <wayland-server.h>
|
||||||
|
|
||||||
#include "xdg-shell-server-protocol.h"
|
#include "xdg-shell-server-protocol.h"
|
||||||
@@ -186,9 +185,6 @@ static void on_client_created(struct wl_listener *l, void *data) {
|
|||||||
|
|
||||||
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE, ROLE_DESKTOP, ROLE_CURSOR };
|
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE, ROLE_DESKTOP, ROLE_CURSOR };
|
||||||
|
|
||||||
#define DAMAGE_RECTS 8
|
|
||||||
struct damage_list { int32_t r[DAMAGE_RECTS][4]; int n; };
|
|
||||||
|
|
||||||
struct surface {
|
struct surface {
|
||||||
struct wl_resource *resource;
|
struct wl_resource *resource;
|
||||||
struct wl_list link;
|
struct wl_list link;
|
||||||
@@ -207,11 +203,9 @@ struct surface {
|
|||||||
struct wl_resource *dmabuf;
|
struct wl_resource *dmabuf;
|
||||||
struct dmabuf_buffer *dmabuf_buf;
|
struct dmabuf_buffer *dmabuf_buf;
|
||||||
struct wl_listener dmabuf_destroy;
|
struct wl_listener dmabuf_destroy;
|
||||||
const void *last_dmabuf;
|
|
||||||
int buf_w, buf_h, has_content;
|
int buf_w, buf_h, has_content;
|
||||||
int buf_alpha;
|
int buf_alpha;
|
||||||
int opaque[4], pending_opaque[4], pending_opaque_set;
|
int opaque[4], pending_opaque[4], pending_opaque_set;
|
||||||
struct damage_list damage_buf, pending_damage_buf, damage_local, pending_damage_local;
|
|
||||||
int src_set, dst_set;
|
int src_set, dst_set;
|
||||||
float src[4];
|
float src[4];
|
||||||
int dst[2];
|
int dst[2];
|
||||||
@@ -262,26 +256,6 @@ static struct wl_event_source *g_render_idle, *g_frame_timer;
|
|||||||
|
|
||||||
|
|
||||||
static int g_dirty;
|
static int g_dirty;
|
||||||
static int64_t g_dirty_since_ns;
|
|
||||||
volatile int g_render_on_commit = 1;
|
|
||||||
static int64_t g_rendered_tick_ns;
|
|
||||||
static int g_tick_held;
|
|
||||||
static int64_t g_hold_missed_ns;
|
|
||||||
#define HOLD_RETRY_NS 1000000000LL
|
|
||||||
#define PACE_BUFFERS 32
|
|
||||||
static struct {
|
|
||||||
unsigned ticks, ticks_late_2ms, renders, commit_renders, null_attaches, reattaches, presented, replaced, undrawn, distinct;
|
|
||||||
int64_t tick_late_ns, tick_late_max_ns, wait_ns, wait_max_ns;
|
|
||||||
const void *buffers[PACE_BUFFERS];
|
|
||||||
uint64_t game_frames_seen;
|
|
||||||
} g_pace;
|
|
||||||
|
|
||||||
static void pace_note_buffer(const void *buffer) {
|
|
||||||
for (unsigned i = 0; i < g_pace.distinct && i < PACE_BUFFERS; i++)
|
|
||||||
if (g_pace.buffers[i] == buffer) return;
|
|
||||||
if (g_pace.distinct < PACE_BUFFERS) g_pace.buffers[g_pace.distinct] = buffer;
|
|
||||||
g_pace.distinct++;
|
|
||||||
}
|
|
||||||
static int64_t g_last_vsync_ns;
|
static int64_t g_last_vsync_ns;
|
||||||
static int64_t g_tick_vsync_ns;
|
static int64_t g_tick_vsync_ns;
|
||||||
static int64_t g_refresh_ns = 16666667;
|
static int64_t g_refresh_ns = 16666667;
|
||||||
@@ -289,8 +263,6 @@ static struct wl_event_source *g_fallback_timer;
|
|||||||
static int g_fallback_armed;
|
static int g_fallback_armed;
|
||||||
|
|
||||||
volatile int g_fps_limit;
|
volatile int g_fps_limit;
|
||||||
/* fps limit -1 (phone output, not mirrored): replaced buffers go back to the client at once instead of once per refresh. */
|
|
||||||
volatile int g_release_unpaced;
|
|
||||||
|
|
||||||
volatile int g_hide_shell;
|
volatile int g_hide_shell;
|
||||||
|
|
||||||
@@ -332,7 +304,6 @@ static struct {
|
|||||||
} g_perf;
|
} g_perf;
|
||||||
|
|
||||||
static void schedule_render(void);
|
static void schedule_render(void);
|
||||||
static void on_commit_idle(void *data);
|
|
||||||
|
|
||||||
static int64_t now_ns(void) {
|
static int64_t now_ns(void) {
|
||||||
struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
|
struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||||
@@ -399,7 +370,7 @@ static int on_release_timer(int fd, uint32_t mask, void *data) {
|
|||||||
static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns) {
|
static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns) {
|
||||||
const int limit = g_fps_limit;
|
const int limit = g_fps_limit;
|
||||||
const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns;
|
const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns;
|
||||||
if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
|
if (interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
|
||||||
int64_t now = now_ns();
|
int64_t now = now_ns();
|
||||||
int64_t at = s->next_release_ns + interval;
|
int64_t at = s->next_release_ns + interval;
|
||||||
int64_t latest = now + interval * (int64_t)(s->releases_pending + 1);
|
int64_t latest = now + interval * (int64_t)(s->releases_pending + 1);
|
||||||
@@ -650,68 +621,6 @@ static void fire_frames(struct wl_list *frames) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static void scene_size(int *w, int *h);
|
|
||||||
static int64_t damage_area(const struct damage_list *d, int bound_w, int bound_h);
|
|
||||||
static struct surface *g_hud_surface, *g_hud_shm;
|
|
||||||
static int64_t g_hud_shm_ns;
|
|
||||||
static int64_t g_hud_last_ns, g_hud_alive_ns;
|
|
||||||
static int g_hud_fresh;
|
|
||||||
static int g_hud_new;
|
|
||||||
#define HUD_TIMES 256
|
|
||||||
static pthread_mutex_t g_hud_times_lock = PTHREAD_MUTEX_INITIALIZER;
|
|
||||||
static float g_hud_times[HUD_TIMES];
|
|
||||||
static int64_t g_hud_times_total, g_hud_shown_ns;
|
|
||||||
|
|
||||||
static void hud_frame_shown(int64_t t) {
|
|
||||||
const int64_t previous = g_hud_shown_ns;
|
|
||||||
g_hud_shown_ns = t;
|
|
||||||
if (!previous || t <= previous) return;
|
|
||||||
pthread_mutex_lock(&g_hud_times_lock);
|
|
||||||
g_hud_times[g_hud_times_total % HUD_TIMES] = (float)((t - previous) / 1e6);
|
|
||||||
g_hud_times_total++;
|
|
||||||
pthread_mutex_unlock(&g_hud_times_lock);
|
|
||||||
}
|
|
||||||
|
|
||||||
static int tree_rank(const struct surface *s, const struct surface *want, int *rank, int depth) {
|
|
||||||
const struct surface *c;
|
|
||||||
if (depth > 8) return 0;
|
|
||||||
wl_list_for_each(c, &s->children, child_link)
|
|
||||||
if (c->below_parent && tree_rank(c, want, rank, depth + 1)) return 1;
|
|
||||||
if (s == want) return 1;
|
|
||||||
(*rank)++;
|
|
||||||
wl_list_for_each(c, &s->children, child_link)
|
|
||||||
if (!c->below_parent && tree_rank(c, want, rank, depth + 1)) return 1;
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
static int render_rank(const struct surface *want) {
|
|
||||||
const struct surface *s;
|
|
||||||
int rank = 0;
|
|
||||||
if (g_desktop && tree_rank(g_desktop, want, &rank, 0)) return rank;
|
|
||||||
wl_list_for_each(s, &g_toplevels, toplevel_link)
|
|
||||||
if (tree_rank(s, want, &rank, 0)) return rank;
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
static int below_surface(const struct surface *s, const struct surface *other) {
|
|
||||||
const int a = render_rank(s), b = render_rank(other);
|
|
||||||
return a >= 0 && b >= 0 && a < b;
|
|
||||||
}
|
|
||||||
|
|
||||||
int droiddeck_hud_frame_times(float *out, int len, int64_t *total) {
|
|
||||||
pthread_mutex_lock(&g_hud_times_lock);
|
|
||||||
*total = g_hud_times_total;
|
|
||||||
int64_t n = *total < len ? *total : len;
|
|
||||||
if (n > HUD_TIMES) n = HUD_TIMES;
|
|
||||||
for (int64_t i = 0; i < n; i++) out[i] = g_hud_times[(*total - n + i) % HUD_TIMES];
|
|
||||||
pthread_mutex_unlock(&g_hud_times_lock);
|
|
||||||
return (int)n;
|
|
||||||
}
|
|
||||||
static uint64_t g_game_frames;
|
|
||||||
extern void droiddeck_on_game_surface(const char *window, const char *gpu);
|
|
||||||
extern void droiddeck_on_game_frame(void);
|
|
||||||
extern void droiddeck_on_game_program(int pid, const char *program);
|
|
||||||
|
|
||||||
static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_resource *buffer) {
|
static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_resource *buffer) {
|
||||||
int32_t w = wl_shm_buffer_get_width(shm), h = wl_shm_buffer_get_height(shm);
|
int32_t w = wl_shm_buffer_get_width(shm), h = wl_shm_buffer_get_height(shm);
|
||||||
int32_t stride = wl_shm_buffer_get_stride(shm);
|
int32_t stride = wl_shm_buffer_get_stride(shm);
|
||||||
@@ -734,33 +643,6 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
|
|||||||
g_stat_shm++;
|
g_stat_shm++;
|
||||||
struct client_info *ci = client_info_of(wl_resource_get_client(s->resource));
|
struct client_info *ci = client_info_of(wl_resource_get_client(s->resource));
|
||||||
if (ci && ci->asked_feedback) ci->shm_frames++;
|
if (ci && ci->asked_feedback) ci->shm_frames++;
|
||||||
int local_w, local_h;
|
|
||||||
surface_size(s, &local_w, &local_h);
|
|
||||||
const double region = s->src_set ? (double)s->src[2] * s->src[3] : (double)w * h;
|
|
||||||
const int64_t local_max = damage_area(&s->damage_local, local_w, local_h);
|
|
||||||
const int64_t local = local_w > 0 && local_h > 0
|
|
||||||
? (int64_t)((double)local_max * region / ((double)local_w * local_h)) : local_max;
|
|
||||||
const int64_t buffer_max = damage_area(&s->damage_buf, w, h);
|
|
||||||
const int64_t area = (int64_t)w * h;
|
|
||||||
int64_t damaged = buffer_max > local ? buffer_max : local;
|
|
||||||
if (damaged > area) damaged = area;
|
|
||||||
const int64_t now = now_ns();
|
|
||||||
if (damaged * 16 >= area && (!g_hud_surface || now - g_hud_last_ns > 1000000000LL) &&
|
|
||||||
(s == g_hud_shm || !g_hud_shm || now - g_hud_shm_ns > 1000000000LL)) {
|
|
||||||
const struct surface *top = s;
|
|
||||||
int scene_w, scene_h, top_w, top_h, depth = 0;
|
|
||||||
while (top->parent && depth++ < 8) top = top->parent;
|
|
||||||
scene_size(&scene_w, &scene_h);
|
|
||||||
surface_size(top, &top_w, &top_h);
|
|
||||||
int64_t shown = (int64_t)local_w * local_h;
|
|
||||||
if ((int64_t)top_w * top_h > shown) shown = (int64_t)top_w * top_h;
|
|
||||||
if (top->role == ROLE_TOPLEVEL && top->mapped && shown * 2 >= (int64_t)scene_w * scene_h) {
|
|
||||||
g_hud_shm = s;
|
|
||||||
g_hud_shm_ns = now;
|
|
||||||
g_hud_new = 1;
|
|
||||||
droiddeck_on_game_frame();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) {
|
static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) {
|
||||||
@@ -777,12 +659,17 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou
|
|||||||
s->has_content = s->shm_img != NULL;
|
s->has_content = s->shm_img != NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static struct surface *g_hud_surface;
|
||||||
|
static int64_t g_hud_last_ns, g_hud_alive_ns;
|
||||||
|
static int g_hud_fresh;
|
||||||
|
static uint64_t g_game_frames;
|
||||||
|
extern void droiddeck_on_game_surface(const char *window, const char *gpu);
|
||||||
|
extern void droiddeck_on_game_frame(void);
|
||||||
|
extern void droiddeck_on_game_program(int pid, const char *program);
|
||||||
|
|
||||||
static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_resource *buffer) {
|
static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_resource *buffer) {
|
||||||
const int repeat = s->dmabuf == buffer && s->dmabuf_buf == b;
|
const int repeat = s->dmabuf == buffer && s->dmabuf_buf == b;
|
||||||
if (!repeat) {
|
if (!repeat) {
|
||||||
if (!s->dmabuf && s->last_dmabuf == buffer) g_pace.reattaches++;
|
|
||||||
s->last_dmabuf = buffer;
|
|
||||||
pace_note_buffer(buffer);
|
|
||||||
drop_dmabuf(s, 1);
|
drop_dmabuf(s, 1);
|
||||||
s->dmabuf = buffer;
|
s->dmabuf = buffer;
|
||||||
s->dmabuf_buf = b;
|
s->dmabuf_buf = b;
|
||||||
@@ -834,9 +721,8 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
|||||||
name, b->width, b->height, (unsigned long long)b->modifier);
|
name, b->width, b->height, (unsigned long long)b->modifier);
|
||||||
}
|
}
|
||||||
if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) &&
|
if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) &&
|
||||||
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL || (!repeat && below_surface(s, g_hud_surface)) ||
|
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL ||
|
||||||
(announced_now && !below_surface(g_hud_surface, s) &&
|
(announced_now && (int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
|
||||||
(int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
|
|
||||||
char name[160];
|
char name[160];
|
||||||
describe(s, name, sizeof(name));
|
describe(s, name, sizeof(name));
|
||||||
g_hud_surface = s;
|
g_hud_surface = s;
|
||||||
@@ -860,7 +746,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
|||||||
}
|
}
|
||||||
if (s == g_hud_surface) {
|
if (s == g_hud_surface) {
|
||||||
g_hud_alive_ns = now_ns();
|
g_hud_alive_ns = now_ns();
|
||||||
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; droiddeck_on_game_frame(); }
|
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_game_frames++; droiddeck_on_game_frame(); }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -897,45 +783,8 @@ static void surface_attach(struct wl_client *c, struct wl_resource *r,
|
|||||||
wl_resource_add_destroy_listener(buffer, &s->pending_buffer_destroy);
|
wl_resource_add_destroy_listener(buffer, &s->pending_buffer_destroy);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
static int64_t rect_area(const int32_t *r, int bound_w, int bound_h) {
|
|
||||||
int64_t x0 = r[0], y0 = r[1], x1 = (int64_t)r[0] + r[2], y1 = (int64_t)r[1] + r[3];
|
|
||||||
if (bound_w > 0 && bound_h > 0) {
|
|
||||||
if (x0 < 0) x0 = 0;
|
|
||||||
if (y0 < 0) y0 = 0;
|
|
||||||
if (x1 > bound_w) x1 = bound_w;
|
|
||||||
if (y1 > bound_h) y1 = bound_h;
|
|
||||||
}
|
|
||||||
if (x1 <= x0 || y1 <= y0) return 0;
|
|
||||||
const int64_t w = x1 - x0, h = y1 - y0;
|
|
||||||
return (w < 65536 ? w : 65536) * (h < 65536 ? h : 65536);
|
|
||||||
}
|
|
||||||
static void note_damage(struct damage_list *d, int32_t x, int32_t y, int32_t w, int32_t h) {
|
|
||||||
if (w <= 0 || h <= 0) return;
|
|
||||||
const int32_t rect[4] = { x, y, w, h };
|
|
||||||
int slot = d->n;
|
|
||||||
if (slot == DAMAGE_RECTS) {
|
|
||||||
slot = 0;
|
|
||||||
for (int i = 1; i < DAMAGE_RECTS; i++)
|
|
||||||
if (rect_area(d->r[i], 0, 0) < rect_area(d->r[slot], 0, 0)) slot = i;
|
|
||||||
if (rect_area(rect, 0, 0) <= rect_area(d->r[slot], 0, 0)) return;
|
|
||||||
} else {
|
|
||||||
d->n++;
|
|
||||||
}
|
|
||||||
memcpy(d->r[slot], rect, sizeof(rect));
|
|
||||||
}
|
|
||||||
static int64_t damage_area(const struct damage_list *d, int bound_w, int bound_h) {
|
|
||||||
int64_t max = 0;
|
|
||||||
for (int i = 0; i < d->n; i++) {
|
|
||||||
const int64_t area = rect_area(d->r[i], bound_w, bound_h);
|
|
||||||
if (area > max) max = area;
|
|
||||||
}
|
|
||||||
return max;
|
|
||||||
}
|
|
||||||
static void surface_damage(struct wl_client *c, struct wl_resource *r,
|
static void surface_damage(struct wl_client *c, struct wl_resource *r,
|
||||||
int32_t x, int32_t y, int32_t w, int32_t h) {
|
int32_t x, int32_t y, int32_t w, int32_t h) {}
|
||||||
struct surface *s = wl_resource_get_user_data(r);
|
|
||||||
note_damage(&s->pending_damage_local, x, y, w, h);
|
|
||||||
}
|
|
||||||
static void frame_callback_destroy(struct wl_resource *r) {
|
static void frame_callback_destroy(struct wl_resource *r) {
|
||||||
wl_list_remove(wl_resource_get_link(r));
|
wl_list_remove(wl_resource_get_link(r));
|
||||||
}
|
}
|
||||||
@@ -944,15 +793,12 @@ static void feedback_resource_destroy(struct wl_resource *r) {
|
|||||||
wl_list_remove(wl_resource_get_link(r));
|
wl_list_remove(wl_resource_get_link(r));
|
||||||
}
|
}
|
||||||
|
|
||||||
static unsigned feedback_discard_all(struct wl_list *list) {
|
static void feedback_discard_all(struct wl_list *list) {
|
||||||
struct wl_resource *fb, *tmp;
|
struct wl_resource *fb, *tmp;
|
||||||
unsigned n = 0;
|
|
||||||
wl_resource_for_each_safe(fb, tmp, list) {
|
wl_resource_for_each_safe(fb, tmp, list) {
|
||||||
wp_presentation_feedback_send_discarded(fb);
|
wp_presentation_feedback_send_discarded(fb);
|
||||||
wl_resource_destroy(fb);
|
wl_resource_destroy(fb);
|
||||||
n++;
|
|
||||||
}
|
}
|
||||||
return n;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static uint32_t nominal_refresh_ns(void) {
|
static uint32_t nominal_refresh_ns(void) {
|
||||||
@@ -962,14 +808,10 @@ static uint32_t nominal_refresh_ns(void) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static int64_t presented_ns(int64_t render_ns) {
|
static int64_t presented_ns(int64_t render_ns) {
|
||||||
int64_t tick = g_tick_vsync_ns;
|
if (!g_tick_vsync_ns || render_ns - g_last_vsync_ns > (int64_t)nominal_refresh_ns() ||
|
||||||
int64_t refresh = (int64_t)nominal_refresh_ns();
|
render_ns < g_tick_vsync_ns)
|
||||||
if (!tick || render_ns - g_last_vsync_ns > refresh)
|
|
||||||
return render_ns;
|
return render_ns;
|
||||||
int64_t delta = render_ns - tick;
|
return g_tick_vsync_ns;
|
||||||
if (delta > refresh || -delta > refresh)
|
|
||||||
return render_ns;
|
|
||||||
return tick;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static void feedback_present_all(struct wl_list *list, int64_t t) {
|
static void feedback_present_all(struct wl_list *list, int64_t t) {
|
||||||
@@ -981,7 +823,6 @@ static void feedback_present_all(struct wl_list *list, int64_t t) {
|
|||||||
nominal_refresh_ns(), 0, 0,
|
nominal_refresh_ns(), 0, 0,
|
||||||
WP_PRESENTATION_FEEDBACK_KIND_VSYNC);
|
WP_PRESENTATION_FEEDBACK_KIND_VSYNC);
|
||||||
wl_resource_destroy(fb);
|
wl_resource_destroy(fb);
|
||||||
g_pace.presented++;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1139,18 +980,13 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
|||||||
s->pending_opaque_set = 0;
|
s->pending_opaque_set = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
s->damage_buf = s->pending_damage_buf;
|
|
||||||
s->damage_local = s->pending_damage_local;
|
|
||||||
s->pending_damage_buf.n = s->pending_damage_local.n = 0;
|
|
||||||
if (s->pending_attach) {
|
if (s->pending_attach) {
|
||||||
struct wl_resource *buffer = s->pending_buffer;
|
struct wl_resource *buffer = s->pending_buffer;
|
||||||
struct dmabuf_buffer *db = get_dmabuf(buffer);
|
struct dmabuf_buffer *db = get_dmabuf(buffer);
|
||||||
struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL;
|
struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL;
|
||||||
uint8_t pixel[4];
|
uint8_t pixel[4];
|
||||||
|
|
||||||
g_pace.replaced += feedback_discard_all(&s->feedback);
|
feedback_discard_all(&s->feedback);
|
||||||
if (!buffer) g_pace.null_attaches++;
|
|
||||||
else if (!db) s->last_dmabuf = NULL;
|
|
||||||
|
|
||||||
if (buffer) {
|
if (buffer) {
|
||||||
wl_list_remove(&s->pending_buffer_destroy.link);
|
wl_list_remove(&s->pending_buffer_destroy.link);
|
||||||
@@ -1208,10 +1044,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
|||||||
static void surface_set_buffer_transform(struct wl_client *c, struct wl_resource *r, int32_t t) {}
|
static void surface_set_buffer_transform(struct wl_client *c, struct wl_resource *r, int32_t t) {}
|
||||||
static void surface_set_buffer_scale(struct wl_client *c, struct wl_resource *r, int32_t s) {}
|
static void surface_set_buffer_scale(struct wl_client *c, struct wl_resource *r, int32_t s) {}
|
||||||
static void surface_damage_buffer(struct wl_client *c, struct wl_resource *r,
|
static void surface_damage_buffer(struct wl_client *c, struct wl_resource *r,
|
||||||
int32_t x, int32_t y, int32_t w, int32_t h) {
|
int32_t x, int32_t y, int32_t w, int32_t h) {}
|
||||||
struct surface *s = wl_resource_get_user_data(r);
|
|
||||||
note_damage(&s->pending_damage_buf, x, y, w, h);
|
|
||||||
}
|
|
||||||
static void surface_offset(struct wl_client *c, struct wl_resource *r, int32_t x, int32_t y) {}
|
static void surface_offset(struct wl_client *c, struct wl_resource *r, int32_t x, int32_t y) {}
|
||||||
|
|
||||||
static const struct wl_surface_interface surface_impl = {
|
static const struct wl_surface_interface surface_impl = {
|
||||||
@@ -1254,7 +1087,6 @@ static void surface_resource_destroy(struct wl_resource *r) {
|
|||||||
droiddeck_text_input_surface_gone(r);
|
droiddeck_text_input_surface_gone(r);
|
||||||
if (g_desktop == s) { g_desktop = NULL; droiddeck_log("desktop", "the desktop closed"); }
|
if (g_desktop == s) { g_desktop = NULL; droiddeck_log("desktop", "the desktop closed"); }
|
||||||
if (g_hud_surface == s) { g_hud_surface = NULL; droiddeck_on_game_surface(NULL, NULL); }
|
if (g_hud_surface == s) { g_hud_surface = NULL; droiddeck_on_game_surface(NULL, NULL); }
|
||||||
if (g_hud_shm == s) g_hud_shm = NULL;
|
|
||||||
constraints_surface_gone(s);
|
constraints_surface_gone(s);
|
||||||
|
|
||||||
unmap_toplevel(s);
|
unmap_toplevel(s);
|
||||||
@@ -2009,137 +1841,14 @@ static void hdr_count_copied(const struct draw_list *dl, const char *reason) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Stream mode (the Xbox Cloud Gaming native player, in its own process): no Wayland clients, the scene is one
|
|
||||||
* picture handed over as AHardwareBuffers (ImageReader images of the decoded video). Each buffer is imported once
|
|
||||||
* and kept while the reader cycles through its few buffers; the newest frame is the scene, so the screen effects
|
|
||||||
* and frame generation apply to it as to a game.
|
|
||||||
*/
|
|
||||||
#define STREAM_SLOTS 6
|
|
||||||
static pthread_mutex_t g_stream_lock = PTHREAD_MUTEX_INITIALIZER;
|
|
||||||
static atomic_int g_stream_on;
|
|
||||||
static AHardwareBuffer *g_stream_pending;
|
|
||||||
static struct { AHardwareBuffer *ahb; struct vkp_image *img; uint64_t used; } g_stream_slots[STREAM_SLOTS];
|
|
||||||
static struct vkp_image *g_stream_img;
|
|
||||||
static uint64_t g_stream_seq;
|
|
||||||
static atomic_uint g_stream_frames;
|
|
||||||
|
|
||||||
static void stream_forget_all(void) {
|
|
||||||
vkp_wait_idle();
|
|
||||||
for (int i = 0; i < STREAM_SLOTS; i++) {
|
|
||||||
if (g_stream_slots[i].img) vkp_image_destroy(g_stream_slots[i].img);
|
|
||||||
if (g_stream_slots[i].ahb) AHardwareBuffer_release(g_stream_slots[i].ahb);
|
|
||||||
g_stream_slots[i].img = NULL; g_stream_slots[i].ahb = NULL; g_stream_slots[i].used = 0;
|
|
||||||
}
|
|
||||||
g_stream_img = NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Compositor thread: the newest handed-over buffer becomes the scene picture. */
|
|
||||||
static void stream_take(void) {
|
|
||||||
pthread_mutex_lock(&g_stream_lock);
|
|
||||||
AHardwareBuffer *ahb = g_stream_pending;
|
|
||||||
g_stream_pending = NULL;
|
|
||||||
pthread_mutex_unlock(&g_stream_lock);
|
|
||||||
if (!ahb) return;
|
|
||||||
if (!atomic_load(&g_stream_on)) { AHardwareBuffer_release(ahb); return; }
|
|
||||||
int slot = -1, oldest = 0;
|
|
||||||
for (int i = 0; i < STREAM_SLOTS; i++) {
|
|
||||||
if (g_stream_slots[i].ahb == ahb) { slot = i; break; }
|
|
||||||
if (g_stream_slots[i].used < g_stream_slots[oldest].used) oldest = i;
|
|
||||||
}
|
|
||||||
if (slot >= 0) {
|
|
||||||
AHardwareBuffer_release(ahb); /* the slot keeps its own reference */
|
|
||||||
} else {
|
|
||||||
struct vkp_image *img = vkp_image_from_ahb(ahb);
|
|
||||||
if (!img) {
|
|
||||||
static int said;
|
|
||||||
if (!said) { said = 1; droiddeck_log("stream", "a decoded frame could not be imported: nothing to show"); }
|
|
||||||
AHardwareBuffer_release(ahb);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
droiddeck_log("stream", "decoded frame buffer imported (%dx%d)", vkp_image_width(img), vkp_image_height(img));
|
|
||||||
slot = oldest;
|
|
||||||
if (g_stream_slots[slot].img) {
|
|
||||||
vkp_wait_idle(); /* the GPU may still read the picture being replaced */
|
|
||||||
if (g_stream_img == g_stream_slots[slot].img) g_stream_img = NULL;
|
|
||||||
vkp_image_destroy(g_stream_slots[slot].img);
|
|
||||||
}
|
|
||||||
if (g_stream_slots[slot].ahb) AHardwareBuffer_release(g_stream_slots[slot].ahb);
|
|
||||||
g_stream_slots[slot].ahb = ahb;
|
|
||||||
g_stream_slots[slot].img = img;
|
|
||||||
}
|
|
||||||
g_stream_slots[slot].used = ++g_stream_seq;
|
|
||||||
g_stream_img = g_stream_slots[slot].img;
|
|
||||||
atomic_fetch_add(&g_stream_frames, 1);
|
|
||||||
schedule_render();
|
|
||||||
}
|
|
||||||
|
|
||||||
static void render_stream(void) {
|
|
||||||
g_dirty = 0;
|
|
||||||
struct vkp_image *img = g_stream_img;
|
|
||||||
if (!img) return;
|
|
||||||
int w = vkp_image_width(img), h = vkp_image_height(img);
|
|
||||||
if (w != g_scene_w || h != g_scene_h) {
|
|
||||||
droiddeck_log("stream", "picture %dx%d", w, h);
|
|
||||||
g_scene_w = w;
|
|
||||||
g_scene_h = h;
|
|
||||||
}
|
|
||||||
struct vkp_draw d = {.img = img, .sx = 0, .sy = 0, .sw = (float)w, .sh = (float)h, .dx = 0, .dy = 0, .dw = w, .dh = h, .blend = 0};
|
|
||||||
vkp_apply_window_request();
|
|
||||||
sc_layer_hide();
|
|
||||||
int r = vkp_render(w, h, &d, 1);
|
|
||||||
if (r == 0) {
|
|
||||||
g_stat_frames++;
|
|
||||||
static int first;
|
|
||||||
if (!first) { first = 1; droiddeck_log("stream", "first stream frame presented"); }
|
|
||||||
} else {
|
|
||||||
static int failed;
|
|
||||||
if (failed++ % 600 == 0) droiddeck_log("stream", "presenting a stream frame failed (%d, %d times)", r, failed);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void droiddeck_stream_set(int on) {
|
|
||||||
atomic_store(&g_stream_on, on ? 1 : 0);
|
|
||||||
if (g_input_pipe[1] < 0) return;
|
|
||||||
struct input_msg m = { 21, on ? 1 : 0, 0, 0, 0 };
|
|
||||||
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
|
|
||||||
(void)n;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Any thread: hands over one decoded frame (acquires its own reference). */
|
|
||||||
void droiddeck_stream_frame(AHardwareBuffer *ahb) {
|
|
||||||
if (!ahb || !atomic_load(&g_stream_on) || g_input_pipe[1] < 0) return;
|
|
||||||
AHardwareBuffer_acquire(ahb);
|
|
||||||
pthread_mutex_lock(&g_stream_lock);
|
|
||||||
AHardwareBuffer *dropped = g_stream_pending;
|
|
||||||
g_stream_pending = ahb;
|
|
||||||
pthread_mutex_unlock(&g_stream_lock);
|
|
||||||
if (dropped) { AHardwareBuffer_release(dropped); return; } /* a wake-up is already queued */
|
|
||||||
struct input_msg m = { 20, 0, 0, 0, 0 };
|
|
||||||
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
|
|
||||||
(void)n;
|
|
||||||
}
|
|
||||||
|
|
||||||
unsigned droiddeck_stream_frames(void) { return atomic_load(&g_stream_frames); }
|
|
||||||
|
|
||||||
static void render_scene(void) {
|
static void render_scene(void) {
|
||||||
if (atomic_load(&g_stream_on)) { g_dirty_since_ns = 0; render_stream(); return; }
|
|
||||||
struct draw_list dl = {0};
|
struct draw_list dl = {0};
|
||||||
struct surface *s;
|
struct surface *s;
|
||||||
int w, h;
|
int w, h;
|
||||||
const int64_t t_scene = now_ns();
|
const int64_t t_scene = now_ns();
|
||||||
int copy = 0;
|
int copy = 0;
|
||||||
|
|
||||||
if (g_dirty_since_ns) {
|
|
||||||
const int64_t wait = t_scene - g_dirty_since_ns;
|
|
||||||
g_pace.wait_ns += wait;
|
|
||||||
if (wait > g_pace.wait_max_ns) g_pace.wait_max_ns = wait;
|
|
||||||
g_pace.renders++;
|
|
||||||
g_dirty_since_ns = 0;
|
|
||||||
}
|
|
||||||
g_dirty = 0;
|
g_dirty = 0;
|
||||||
g_rendered_tick_ns = g_tick_vsync_ns;
|
|
||||||
g_tick_held = 0;
|
|
||||||
g_hud_fresh = 0;
|
g_hud_fresh = 0;
|
||||||
g_hdr_unimported = NULL;
|
g_hdr_unimported = NULL;
|
||||||
wl_list_for_each(s, &g_surfaces, link) s->drawn = 0;
|
wl_list_for_each(s, &g_surfaces, link) s->drawn = 0;
|
||||||
@@ -2273,13 +1982,9 @@ static void render_scene(void) {
|
|||||||
if (rendered) {
|
if (rendered) {
|
||||||
int64_t t = presented_ns(t_scene);
|
int64_t t = presented_ns(t_scene);
|
||||||
g_stat_frames++;
|
g_stat_frames++;
|
||||||
if (g_hud_new) {
|
|
||||||
g_hud_new = 0;
|
|
||||||
hud_frame_shown(t);
|
|
||||||
}
|
|
||||||
wl_list_for_each(s, &g_surfaces, link) {
|
wl_list_for_each(s, &g_surfaces, link) {
|
||||||
if (s->drawn) feedback_present_all(&s->feedback, t);
|
if (s->drawn) feedback_present_all(&s->feedback, t);
|
||||||
else g_pace.undrawn += feedback_discard_all(&s->feedback);
|
else feedback_discard_all(&s->feedback);
|
||||||
}
|
}
|
||||||
fire_all_frames();
|
fire_all_frames();
|
||||||
} else {
|
} else {
|
||||||
@@ -2304,25 +2009,10 @@ static int on_fallback_timer(void *data) {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* A new frame is drawn when it arrives instead of at the next screen tick, at most once per refresh,
|
|
||||||
while frames go straight back to the game (no compositor limit), without streaming or frame generation. */
|
|
||||||
static int commit_renders_on(void) {
|
|
||||||
return g_render_on_commit && g_release_unpaced && !atomic_load(&g_stream_on) && !vkp_framegen_active();
|
|
||||||
}
|
|
||||||
|
|
||||||
static int render_on_commit(void) {
|
|
||||||
return commit_renders_on() && !g_render_idle && g_rendered_tick_ns != g_tick_vsync_ns;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void schedule_render(void) {
|
static void schedule_render(void) {
|
||||||
if (!g_dirty && !g_dirty_since_ns) g_dirty_since_ns = now_ns();
|
|
||||||
g_dirty = 1;
|
g_dirty = 1;
|
||||||
if (!g_display) return;
|
if (!g_display) return;
|
||||||
if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) {
|
if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) return;
|
||||||
if (render_on_commit())
|
|
||||||
g_render_idle = wl_event_loop_add_idle(wl_display_get_event_loop(g_display), on_commit_idle, NULL);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (g_fallback_armed) return;
|
if (g_fallback_armed) return;
|
||||||
if (!g_fallback_timer)
|
if (!g_fallback_timer)
|
||||||
g_fallback_timer = wl_event_loop_add_timer(wl_display_get_event_loop(g_display),
|
g_fallback_timer = wl_event_loop_add_timer(wl_display_get_event_loop(g_display),
|
||||||
@@ -2336,45 +2026,18 @@ static int scene_waits_for_game(int64_t now) {
|
|||||||
return g_hud_surface && !g_hud_fresh && now - g_hud_last_ns < 100000000LL && vkp_framegen_active();
|
return g_hud_surface && !g_hud_fresh && now - g_hud_last_ns < 100000000LL && vkp_framegen_active();
|
||||||
}
|
}
|
||||||
|
|
||||||
static void on_commit_idle(void *data) {
|
|
||||||
g_render_idle = NULL;
|
|
||||||
if (!g_dirty || !commit_renders_on() || g_rendered_tick_ns == g_tick_vsync_ns || scene_waits_for_game(now_ns())) return;
|
|
||||||
g_pace.commit_renders++;
|
|
||||||
render_scene();
|
|
||||||
}
|
|
||||||
|
|
||||||
static void on_vsync(int64_t frame_time_ns) {
|
static void on_vsync(int64_t frame_time_ns) {
|
||||||
int64_t now = now_ns();
|
int64_t now = now_ns();
|
||||||
g_perf.ticks++;
|
g_perf.ticks++;
|
||||||
if (frame_time_ns > 0 && now >= frame_time_ns) {
|
|
||||||
const int64_t late = now - frame_time_ns;
|
|
||||||
g_pace.ticks++;
|
|
||||||
g_pace.tick_late_ns += late;
|
|
||||||
if (late > g_pace.tick_late_max_ns) g_pace.tick_late_max_ns = late;
|
|
||||||
if (late > 2000000LL) g_pace.ticks_late_2ms++;
|
|
||||||
}
|
|
||||||
if (g_last_vsync_ns) {
|
if (g_last_vsync_ns) {
|
||||||
int64_t d = now - g_last_vsync_ns;
|
int64_t d = now - g_last_vsync_ns;
|
||||||
if (d > 3000000LL && d < 40000000LL) g_refresh_ns = (g_refresh_ns * 7 + d) / 8;
|
if (d > 3000000LL && d < 40000000LL) g_refresh_ns = (g_refresh_ns * 7 + d) / 8;
|
||||||
}
|
}
|
||||||
g_last_vsync_ns = now;
|
g_last_vsync_ns = now;
|
||||||
g_tick_vsync_ns = frame_time_ns;
|
g_tick_vsync_ns = frame_time_ns;
|
||||||
int tick_change = 0;
|
if (vkp_apply_window_request()) g_dirty = 1;
|
||||||
if (vkp_apply_window_request()) tick_change = 1;
|
if (vkp_effects_sync()) g_dirty = 1;
|
||||||
if (vkp_effects_sync()) tick_change = 1;
|
if (vkp_cardboard_pose_changed()) g_dirty = 1;
|
||||||
if (vkp_cardboard_pose_changed()) tick_change = 1;
|
|
||||||
if (tick_change) g_dirty = 1;
|
|
||||||
/* A frame that arrived after this refresh was already drawn is left for the next arrival to draw;
|
|
||||||
drawing it here would block that arrival too and keep every frame waiting for the tick. A client
|
|
||||||
that draws again only after its frame callback sends no such arrival: once a held frame is still
|
|
||||||
waiting at the next tick, the tick draws every frame for a second before holding one again. */
|
|
||||||
if (g_tick_held && g_dirty) g_hold_missed_ns = now;
|
|
||||||
g_tick_held = 0;
|
|
||||||
if (!tick_change && commit_renders_on() && g_dirty_since_ns && now - g_dirty_since_ns < g_refresh_ns &&
|
|
||||||
now - g_hold_missed_ns >= HOLD_RETRY_NS) {
|
|
||||||
g_tick_held = 1;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (g_dirty && !scene_waits_for_game(now)) render_scene();
|
if (g_dirty && !scene_waits_for_game(now)) render_scene();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3338,8 +3001,6 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
|
|||||||
break;
|
break;
|
||||||
case 10: break;
|
case 10: break;
|
||||||
case 11: axis_event(m.p1, m.p2); break;
|
case 11: axis_event(m.p1, m.p2); break;
|
||||||
case 20: stream_take(); break;
|
|
||||||
case 21: if (!m.p1) stream_forget_all(); schedule_render(); break;
|
|
||||||
default: deliver_pointer(&m); break;
|
default: deliver_pointer(&m); break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3478,24 +3139,6 @@ static int on_stats_timer(void *data) {
|
|||||||
#undef PERF_MS
|
#undef PERF_MS
|
||||||
memset(&g_perf, 0, sizeof(g_perf));
|
memset(&g_perf, 0, sizeof(g_perf));
|
||||||
}
|
}
|
||||||
const uint64_t game = g_game_frames - g_pace.game_frames_seen;
|
|
||||||
if (g_pace.ticks || g_pace.renders || game || g_pace.reattaches || g_pace.null_attaches || g_pace.distinct ||
|
|
||||||
g_pace.presented || g_pace.replaced || g_pace.undrawn) {
|
|
||||||
droiddeck_log("pacing", "last 10 s: tick reaches compositor %.2f/%.2f ms late (%u ticks, %u over 2 ms) | "
|
|
||||||
"new frame waits %.2f/%.2f ms to be drawn (%u scenes, %u on arrival) | %llu game frames, %u re-attached after an "
|
|
||||||
"empty attach, %u empty attaches, %u distinct buffers | feedback %u shown, %u replaced before drawing, "
|
|
||||||
"%u not drawn",
|
|
||||||
g_pace.ticks ? (double)g_pace.tick_late_ns / 1e6 / g_pace.ticks : 0.0, (double)g_pace.tick_late_max_ns / 1e6,
|
|
||||||
g_pace.ticks, g_pace.ticks_late_2ms,
|
|
||||||
g_pace.renders ? (double)g_pace.wait_ns / 1e6 / g_pace.renders : 0.0, (double)g_pace.wait_max_ns / 1e6,
|
|
||||||
g_pace.renders, g_pace.commit_renders, (unsigned long long)game, g_pace.reattaches, g_pace.null_attaches, g_pace.distinct,
|
|
||||||
g_pace.presented, g_pace.replaced, g_pace.undrawn);
|
|
||||||
}
|
|
||||||
{
|
|
||||||
const uint64_t seen = g_game_frames;
|
|
||||||
memset(&g_pace, 0, sizeof(g_pace));
|
|
||||||
g_pace.game_frames_seen = seen;
|
|
||||||
}
|
|
||||||
g_stat_frames = g_stat_dmabuf = g_stat_shm = 0;
|
g_stat_frames = g_stat_dmabuf = g_stat_shm = 0;
|
||||||
droiddeck_color_stats_tick();
|
droiddeck_color_stats_tick();
|
||||||
|
|
||||||
|
|||||||
@@ -238,7 +238,7 @@ static int ensure_ring(uint32_t w, uint32_t h, VkFormat fmt, uint32_t n) {
|
|||||||
}
|
}
|
||||||
g_ring_w = w; g_ring_h = h; g_ring_fmt = fmt;
|
g_ring_w = w; g_ring_h = h; g_ring_fmt = fmt;
|
||||||
LOGD("framegen: generation ring %ux%u x%u", w, h, n);
|
LOGD("framegen: generation ring %ux%u x%u", w, h, n);
|
||||||
return 2;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -350,7 +350,6 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view,
|
|||||||
fge_configure((uint32_t)mult, (uint32_t)atomic_load(&g_target), flow, hz,
|
fge_configure((uint32_t)mult, (uint32_t)atomic_load(&g_target), flow, hz,
|
||||||
atomic_load(&g_model), atomic_load(&g_preset));
|
atomic_load(&g_model), atomic_load(&g_preset));
|
||||||
}
|
}
|
||||||
const int size_changed = g_built_w != (uint32_t)w || g_built_h != (uint32_t)h || g_built_fmt != fmt;
|
|
||||||
if (!fge_prepare((uint32_t)w, (uint32_t)h, fmt)) {
|
if (!fge_prepare((uint32_t)w, (uint32_t)h, fmt)) {
|
||||||
if (fmt != VK_FORMAT_R8G8B8A8_UNORM && fge_unavailable()) {
|
if (fmt != VK_FORMAT_R8G8B8A8_UNORM && fge_unavailable()) {
|
||||||
refuse_format(fmt, kind, w, h, "build its chain");
|
refuse_format(fmt, kind, w, h, "build its chain");
|
||||||
@@ -362,25 +361,17 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view,
|
|||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
if (size_changed) {
|
if (g_built_w != (uint32_t)w || g_built_h != (uint32_t)h || g_built_fmt != fmt) {
|
||||||
g_built_w = (uint32_t)w; g_built_h = (uint32_t)h; g_built_fmt = fmt;
|
g_built_w = (uint32_t)w; g_built_h = (uint32_t)h; g_built_fmt = fmt;
|
||||||
g_generating_logged = 0;
|
g_generating_logged = 0;
|
||||||
}
|
}
|
||||||
uint32_t want = (uint32_t)(mult - 1);
|
uint32_t want = (uint32_t)(mult - 1);
|
||||||
const int ring = ensure_ring((uint32_t)w, (uint32_t)h, fmt, want);
|
if (!ensure_ring((uint32_t)w, (uint32_t)h, fmt, want)) {
|
||||||
if (!ring) {
|
|
||||||
if (fmt != VK_FORMAT_R8G8B8A8_UNORM) { refuse_format(fmt, kind, w, h, "make its generation ring"); return 0; }
|
if (fmt != VK_FORMAT_R8G8B8A8_UNORM) { refuse_format(fmt, kind, w, h, "make its generation ring"); return 0; }
|
||||||
FGLOG("no memory for the generation ring (%dx%d x%u); frame generation stays off", w, h, want);
|
FGLOG("no memory for the generation ring (%dx%d x%u); frame generation stays off", w, h, want);
|
||||||
mark_failed(kind);
|
mark_failed(kind);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
/* The ring and the engine's images are new on this frame. Dispatching into them now
|
|
||||||
* null-dereferenced Turnip (vkp_framegen_run, first Steam frame, 2560x1440 to the panel).
|
|
||||||
* Show this frame as it is; generation starts once the size has settled. */
|
|
||||||
if (size_changed || ring == 2) {
|
|
||||||
FGLOG("frame generation catches up at %dx%d; this frame is shown as it is", w, h);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* The pacer's source rate must be the game's, not this loop's: a loop slowed by its own
|
/* The pacer's source rate must be the game's, not this loop's: a loop slowed by its own
|
||||||
* generations would otherwise read as a slower game and justify even more generations. */
|
* generations would otherwise read as a slower game and justify even more generations. */
|
||||||
|
|||||||
@@ -1,170 +0,0 @@
|
|||||||
#include "gpu_clock_pin.h"
|
|
||||||
|
|
||||||
#include <android/log.h>
|
|
||||||
#include <errno.h>
|
|
||||||
#include <fcntl.h>
|
|
||||||
#include <pthread.h>
|
|
||||||
#include <stdatomic.h>
|
|
||||||
#include <stdint.h>
|
|
||||||
#include <string.h>
|
|
||||||
#include <sys/ioctl.h>
|
|
||||||
#include <sys/mman.h>
|
|
||||||
#include <unistd.h>
|
|
||||||
|
|
||||||
#include "../../adrenotools/src/hook/kgsl.h"
|
|
||||||
|
|
||||||
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
|
|
||||||
static pthread_t worker;
|
|
||||||
static bool joinable;
|
|
||||||
static atomic_bool running;
|
|
||||||
|
|
||||||
struct pin {
|
|
||||||
int fd;
|
|
||||||
unsigned int context;
|
|
||||||
unsigned int memory;
|
|
||||||
unsigned int timestamp;
|
|
||||||
unsigned long gpuaddr;
|
|
||||||
uint32_t nop;
|
|
||||||
void *commands;
|
|
||||||
size_t size;
|
|
||||||
};
|
|
||||||
|
|
||||||
static struct pin pin = { .fd = -1 };
|
|
||||||
|
|
||||||
static void release_pin(void) {
|
|
||||||
if (pin.context) {
|
|
||||||
struct kgsl_drawctxt_destroy destroy = { .drawctxt_id = pin.context };
|
|
||||||
ioctl(pin.fd, IOCTL_KGSL_DRAWCTXT_DESTROY, &destroy);
|
|
||||||
}
|
|
||||||
if (pin.commands) munmap(pin.commands, pin.size);
|
|
||||||
if (pin.memory) {
|
|
||||||
struct kgsl_gpumem_free_id free_memory = { .id = pin.memory };
|
|
||||||
ioctl(pin.fd, IOCTL_KGSL_GPUMEM_FREE_ID, &free_memory);
|
|
||||||
}
|
|
||||||
if (pin.fd >= 0) close(pin.fd);
|
|
||||||
pin = (struct pin) { .fd = -1 };
|
|
||||||
}
|
|
||||||
|
|
||||||
static bool submit_pin(void) {
|
|
||||||
struct kgsl_command_object object = {
|
|
||||||
.gpuaddr = pin.gpuaddr,
|
|
||||||
.size = 2 * sizeof(uint32_t),
|
|
||||||
.flags = KGSL_CMDLIST_IB,
|
|
||||||
.id = pin.memory,
|
|
||||||
};
|
|
||||||
struct kgsl_gpu_command command = {
|
|
||||||
.flags = KGSL_CMDBATCH_PWR_CONSTRAINT,
|
|
||||||
.cmdlist = (uintptr_t)&object,
|
|
||||||
.cmdsize = sizeof(object),
|
|
||||||
.numcmds = 1,
|
|
||||||
.context_id = pin.context,
|
|
||||||
};
|
|
||||||
if (ioctl(pin.fd, IOCTL_KGSL_GPU_COMMAND, &command) < 0) return false;
|
|
||||||
pin.timestamp = command.timestamp;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
static bool prepare_pin(void) {
|
|
||||||
pin.fd = open("/dev/kgsl-3d0", O_RDWR | O_CLOEXEC);
|
|
||||||
if (pin.fd < 0) return false;
|
|
||||||
struct kgsl_devinfo info = {0};
|
|
||||||
struct kgsl_device_getproperty device_info = {
|
|
||||||
.type = KGSL_PROP_DEVICE_INFO, .value = &info, .sizebytes = sizeof(info),
|
|
||||||
};
|
|
||||||
if (ioctl(pin.fd, IOCTL_KGSL_DEVICE_GETPROPERTY, &device_info) < 0) return false;
|
|
||||||
unsigned int core = info.chip_id >> 24;
|
|
||||||
if (!core) core = info.gpu_id / 100;
|
|
||||||
if (core < 3) { errno = ENODEV; return false; }
|
|
||||||
pin.nop = core >= 5 ? 0x70100001 : 0xc0001000;
|
|
||||||
struct kgsl_drawctxt_create context = {
|
|
||||||
.flags = KGSL_CONTEXT_NO_GMEM_ALLOC | KGSL_CONTEXT_PREAMBLE | KGSL_CONTEXT_PWR_CONSTRAINT,
|
|
||||||
};
|
|
||||||
if (ioctl(pin.fd, IOCTL_KGSL_DRAWCTXT_CREATE, &context) < 0) return false;
|
|
||||||
pin.context = context.drawctxt_id;
|
|
||||||
struct kgsl_device_constraint_pwrlevel level = { .level = KGSL_CONSTRAINT_PWR_MAX };
|
|
||||||
struct kgsl_device_constraint constraint = {
|
|
||||||
.type = KGSL_CONSTRAINT_PWRLEVEL,
|
|
||||||
.context_id = pin.context,
|
|
||||||
.data = &level,
|
|
||||||
.size = sizeof(level),
|
|
||||||
};
|
|
||||||
struct kgsl_device_getproperty property = {
|
|
||||||
.type = KGSL_PROP_PWR_CONSTRAINT,
|
|
||||||
.value = &constraint,
|
|
||||||
.sizebytes = sizeof(constraint),
|
|
||||||
};
|
|
||||||
if (ioctl(pin.fd, IOCTL_KGSL_SETPROPERTY, &property) < 0) return false;
|
|
||||||
struct kgsl_gpumem_alloc_id memory = { .size = 4096 };
|
|
||||||
if (ioctl(pin.fd, IOCTL_KGSL_GPUMEM_ALLOC_ID, &memory) < 0) return false;
|
|
||||||
pin.memory = memory.id;
|
|
||||||
pin.gpuaddr = memory.gpuaddr;
|
|
||||||
pin.size = memory.mmapsize;
|
|
||||||
void *commands = mmap(NULL, pin.size, PROT_READ | PROT_WRITE, MAP_SHARED, pin.fd,
|
|
||||||
(off_t)pin.memory << 12);
|
|
||||||
if (commands == MAP_FAILED) return false;
|
|
||||||
pin.commands = commands;
|
|
||||||
// A3xx/A4xx use type-3 CP_NOP; newer cores use type-7 with zero odd-parity bits.
|
|
||||||
uint32_t *words = commands;
|
|
||||||
words[0] = pin.nop;
|
|
||||||
words[1] = 0;
|
|
||||||
struct kgsl_gpumem_sync_cache sync = { .id = pin.memory, .op = KGSL_GPUMEM_CACHE_CLEAN };
|
|
||||||
if (ioctl(pin.fd, IOCTL_KGSL_GPUMEM_SYNC_CACHE, &sync) < 0) return false;
|
|
||||||
return submit_pin();
|
|
||||||
}
|
|
||||||
|
|
||||||
static void *hold_pin(void *unused) {
|
|
||||||
(void)unused;
|
|
||||||
while (atomic_load(&running)) {
|
|
||||||
struct kgsl_device_waittimestamp_ctxtid wait = {
|
|
||||||
.context_id = pin.context,
|
|
||||||
.timestamp = pin.timestamp,
|
|
||||||
.timeout = 100,
|
|
||||||
};
|
|
||||||
if (ioctl(pin.fd, IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, &wait) < 0) {
|
|
||||||
if (errno == EINTR || errno == ETIMEDOUT) continue;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
// Constraints expire after idle_timer (normally 80 ms); renew with a NOP, keeping devfreq alive.
|
|
||||||
usleep(25000);
|
|
||||||
if (atomic_load(&running) && !submit_pin()) break;
|
|
||||||
}
|
|
||||||
if (atomic_exchange(&running, false))
|
|
||||||
__android_log_print(ANDROID_LOG_WARN, "GpuClockPin", "constraint stopped: %s", strerror(errno));
|
|
||||||
release_pin();
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool gpu_clock_pin_set(bool on) {
|
|
||||||
pthread_mutex_lock(&lock);
|
|
||||||
if (joinable) {
|
|
||||||
if (on && atomic_load(&running)) {
|
|
||||||
pthread_mutex_unlock(&lock);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
atomic_store(&running, false);
|
|
||||||
pthread_join(worker, NULL);
|
|
||||||
joinable = false;
|
|
||||||
}
|
|
||||||
bool ok = true;
|
|
||||||
if (on) {
|
|
||||||
ok = prepare_pin();
|
|
||||||
if (ok) {
|
|
||||||
atomic_store(&running, true);
|
|
||||||
int error = pthread_create(&worker, NULL, hold_pin, NULL);
|
|
||||||
if (error) {
|
|
||||||
atomic_store(&running, false);
|
|
||||||
errno = error;
|
|
||||||
ok = false;
|
|
||||||
} else {
|
|
||||||
joinable = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!ok) {
|
|
||||||
int error = errno;
|
|
||||||
release_pin();
|
|
||||||
errno = error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pthread_mutex_unlock(&lock);
|
|
||||||
return ok;
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <stdbool.h>
|
|
||||||
|
|
||||||
bool gpu_clock_pin_set(bool on);
|
|
||||||
@@ -21,7 +21,7 @@
|
|||||||
X(BindImageMemory) X(DestroyImage) X(FreeMemory) X(AcquireNextImageKHR) \
|
X(BindImageMemory) X(DestroyImage) X(FreeMemory) X(AcquireNextImageKHR) \
|
||||||
X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \
|
X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \
|
||||||
X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \
|
X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \
|
||||||
X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) X(GetAndroidHardwareBufferPropertiesANDROID) \
|
X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) \
|
||||||
X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) \
|
X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) \
|
||||||
\
|
\
|
||||||
X(CreateShaderModule) X(DestroyShaderModule) X(CreatePipelineLayout) X(DestroyPipelineLayout) \
|
X(CreateShaderModule) X(DestroyShaderModule) X(CreatePipelineLayout) X(DestroyPipelineLayout) \
|
||||||
|
|||||||
@@ -19,7 +19,6 @@
|
|||||||
#include <time.h>
|
#include <time.h>
|
||||||
#include <pthread.h>
|
#include <pthread.h>
|
||||||
#include <android/log.h>
|
#include <android/log.h>
|
||||||
#include <android/hardware_buffer.h>
|
|
||||||
|
|
||||||
#define TAG "DroidDeckWayland"
|
#define TAG "DroidDeckWayland"
|
||||||
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
|
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
|
||||||
@@ -40,7 +39,6 @@ struct vkp_image {
|
|||||||
};
|
};
|
||||||
|
|
||||||
static ANativeWindow *g_window;
|
static ANativeWindow *g_window;
|
||||||
static int g_ahb_import;
|
|
||||||
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
|
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
|
||||||
static int g_dev_state;
|
static int g_dev_state;
|
||||||
static VkInstance g_inst;
|
static VkInstance g_inst;
|
||||||
@@ -461,19 +459,17 @@ static int dev_init(void) {
|
|||||||
}
|
}
|
||||||
g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops);
|
g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops);
|
||||||
|
|
||||||
static const char *const import_exts[4] = {"VK_KHR_external_memory_fd", "VK_EXT_external_memory_dma_buf",
|
const char *dev_exts[7] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME, "VK_KHR_external_memory_fd",
|
||||||
"VK_EXT_image_drm_format_modifier", "VK_KHR_image_format_list"};
|
"VK_EXT_external_memory_dma_buf", "VK_EXT_image_drm_format_modifier",
|
||||||
const char *dev_exts[9] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};
|
"VK_KHR_image_format_list", NULL, NULL};
|
||||||
uint32_t n_dev_exts = 1;
|
uint32_t n_dev_exts = 5;
|
||||||
uint32_t ne = 0;
|
uint32_t ne = 0;
|
||||||
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL);
|
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL);
|
||||||
VkExtensionProperties *exts = calloc(ne ? ne : 1, sizeof(*exts));
|
VkExtensionProperties *exts = calloc(ne ? ne : 1, sizeof(*exts));
|
||||||
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts);
|
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts);
|
||||||
/* Only what the driver has: the system driver lacks the dma-buf ones, which the cloud player never needs. */
|
for (unsigned i = 0; i < 5; i++)
|
||||||
for (unsigned i = 0; i < 4; i++) {
|
if (!has_ext(exts, ne, dev_exts[i]))
|
||||||
if (has_ext(exts, ne, import_exts[i])) dev_exts[n_dev_exts++] = import_exts[i];
|
LOGE("present: driver MISSING %s (dmabuf import will fail)", dev_exts[i]);
|
||||||
else LOGE("present: driver MISSING %s (dmabuf import will fail)", import_exts[i]);
|
|
||||||
}
|
|
||||||
int want_hdr_md = 0;
|
int want_hdr_md = 0;
|
||||||
if (droiddeck_color_requested()) {
|
if (droiddeck_color_requested()) {
|
||||||
want_hdr_md = has_ext(exts, ne, VK_EXT_HDR_METADATA_EXTENSION_NAME);
|
want_hdr_md = has_ext(exts, ne, VK_EXT_HDR_METADATA_EXTENSION_NAME);
|
||||||
@@ -481,13 +477,6 @@ static int dev_init(void) {
|
|||||||
}
|
}
|
||||||
const int want_sem_fd = has_ext(exts, ne, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME);
|
const int want_sem_fd = has_ext(exts, ne, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME);
|
||||||
if (want_sem_fd) dev_exts[n_dev_exts++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
|
if (want_sem_fd) dev_exts[n_dev_exts++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
|
||||||
/* The cloud player's decoded frames arrive as AHardwareBuffers (vkp_image_from_ahb). */
|
|
||||||
g_ahb_import = has_ext(exts, ne, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME) &&
|
|
||||||
has_ext(exts, ne, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
|
|
||||||
if (g_ahb_import) {
|
|
||||||
dev_exts[n_dev_exts++] = VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME;
|
|
||||||
dev_exts[n_dev_exts++] = VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME;
|
|
||||||
}
|
|
||||||
free(exts);
|
free(exts);
|
||||||
|
|
||||||
float prio = 1.0f;
|
float prio = 1.0f;
|
||||||
@@ -998,60 +987,6 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
|
|||||||
return img;
|
return img;
|
||||||
}
|
}
|
||||||
|
|
||||||
void vkp_wait_idle(void) {
|
|
||||||
if (g_dev && g_vk.DeviceWaitIdle) g_vk.DeviceWaitIdle(g_dev);
|
|
||||||
}
|
|
||||||
|
|
||||||
struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
|
|
||||||
if (!ahb || dev_init() != 0) return NULL;
|
|
||||||
if (!g_ahb_import || !g_vk.GetAndroidHardwareBufferPropertiesANDROID) {
|
|
||||||
static int said;
|
|
||||||
if (!said) { said = 1; LOGE("ahb: the driver cannot import AHardwareBuffers (VK_ANDROID_external_memory_android_hardware_buffer)"); }
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
AHardwareBuffer_Desc desc;
|
|
||||||
AHardwareBuffer_describe(ahb, &desc);
|
|
||||||
VkAndroidHardwareBufferFormatPropertiesANDROID fp = {
|
|
||||||
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
|
|
||||||
VkAndroidHardwareBufferPropertiesANDROID props = {
|
|
||||||
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, .pNext = &fp};
|
|
||||||
VkResult pr = g_vk.GetAndroidHardwareBufferPropertiesANDROID(g_dev, ahb, &props);
|
|
||||||
if (pr != VK_SUCCESS || fp.format == VK_FORMAT_UNDEFINED) {
|
|
||||||
LOGE("ahb: %ux%u format %u: properties %s, Vulkan format %d", desc.width, desc.height, desc.format,
|
|
||||||
vk_result_name(pr), (int)fp.format);
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
struct vkp_image *img = calloc(1, sizeof(*img));
|
|
||||||
if (!img) return NULL;
|
|
||||||
img->w = (int)desc.width; img->h = (int)desc.height; img->dmabuf = 1; img->fmt = fp.format; img->sampled = 1;
|
|
||||||
VkExternalMemoryImageCreateInfo ext = {
|
|
||||||
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
|
|
||||||
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
|
|
||||||
VkImageCreateInfo ici = {
|
|
||||||
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &ext,
|
|
||||||
.imageType = VK_IMAGE_TYPE_2D, .format = fp.format, .extent = {desc.width, desc.height, 1},
|
|
||||||
.mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
|
|
||||||
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
|
|
||||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
|
|
||||||
VkResult cr = g_vk.CreateImage(g_dev, &ici, NULL, &img->image);
|
|
||||||
if (cr != VK_SUCCESS) { LOGE("ahb: vkCreateImage %ux%u -> %s", desc.width, desc.height, vk_result_name(cr)); free(img); return NULL; }
|
|
||||||
int idx = -1;
|
|
||||||
for (int i = 0; i < 32; i++) if (props.memoryTypeBits & (1u << i)) { idx = i; break; }
|
|
||||||
VkImportAndroidHardwareBufferInfoANDROID imp = {
|
|
||||||
.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .buffer = ahb};
|
|
||||||
VkMemoryDedicatedAllocateInfo ded = {.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
|
|
||||||
.pNext = &imp, .image = img->image};
|
|
||||||
VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &ded,
|
|
||||||
.allocationSize = props.allocationSize, .memoryTypeIndex = (uint32_t)(idx < 0 ? 0 : idx)};
|
|
||||||
VkResult mr = idx < 0 ? VK_ERROR_FEATURE_NOT_PRESENT : g_vk.AllocateMemory(g_dev, &mai, NULL, &img->mem);
|
|
||||||
if (mr != VK_SUCCESS || g_vk.BindImageMemory(g_dev, img->image, img->mem, 0) != VK_SUCCESS) {
|
|
||||||
LOGE("ahb: importing %ux%u -> %s", desc.width, desc.height, vk_result_name(mr));
|
|
||||||
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
|
|
||||||
g_vk.DestroyImage(g_dev, img->image, NULL); free(img); return NULL;
|
|
||||||
}
|
|
||||||
return img;
|
|
||||||
}
|
|
||||||
|
|
||||||
static int shm_sampled(void) {
|
static int shm_sampled(void) {
|
||||||
static int known;
|
static int known;
|
||||||
if (!known) {
|
if (!known) {
|
||||||
@@ -1691,10 +1626,6 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
|||||||
VkImageLayout result_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
|
VkImageLayout result_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
|
||||||
if (fx) {
|
if (fx) {
|
||||||
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
|
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
|
||||||
/* Frame generation samples every output pixel. Upscaling first made it interpolate
|
|
||||||
* the whole panel (3200x1440 on a 1440p phone) and rebuild on Steam's first frame.
|
|
||||||
* Grade at the game's size instead; the screen blit still scales to the panel. */
|
|
||||||
if (fg) { mapped_w = scene_w; mapped_h = scene_h; }
|
|
||||||
vkp_effects_set_formats(scene_fmt, scene_fmt);
|
vkp_effects_set_formats(scene_fmt, scene_fmt);
|
||||||
result = vkp_effects_run(cmd, scene_img, scene_w, scene_h, mapped_w, mapped_h, &rw, &rh);
|
result = vkp_effects_run(cmd, scene_img, scene_w, scene_h, mapped_w, mapped_h, &rw, &rh);
|
||||||
result_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
|
result_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
|
||||||
|
|||||||
@@ -34,9 +34,6 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
|
|||||||
int vkp_image_is_dmabuf(const struct vkp_image *img);
|
int vkp_image_is_dmabuf(const struct vkp_image *img);
|
||||||
|
|
||||||
struct vkp_image *vkp_image_create_shm(int w, int h);
|
struct vkp_image *vkp_image_create_shm(int w, int h);
|
||||||
struct AHardwareBuffer;
|
|
||||||
struct vkp_image *vkp_image_from_ahb(struct AHardwareBuffer *ahb);
|
|
||||||
void vkp_wait_idle(void);
|
|
||||||
void vkp_image_upload_shm(struct vkp_image *img, const void *data, int stride);
|
void vkp_image_upload_shm(struct vkp_image *img, const void *data, int stride);
|
||||||
|
|
||||||
int vkp_image_width(const struct vkp_image *img);
|
int vkp_image_width(const struct vkp_image *img);
|
||||||
|
|||||||
@@ -9,7 +9,6 @@
|
|||||||
#include <sys/resource.h>
|
#include <sys/resource.h>
|
||||||
#include <android/log.h>
|
#include <android/log.h>
|
||||||
#include <android/native_window_jni.h>
|
#include <android/native_window_jni.h>
|
||||||
#include <android/hardware_buffer_jni.h>
|
|
||||||
#include "vk_present.h"
|
#include "vk_present.h"
|
||||||
#include "droiddeck_ext.h"
|
#include "droiddeck_ext.h"
|
||||||
#include "ahb_swapchain.h"
|
#include "ahb_swapchain.h"
|
||||||
@@ -17,7 +16,6 @@
|
|||||||
#include "effects_chain.h"
|
#include "effects_chain.h"
|
||||||
#include "cardboard.h"
|
#include "cardboard.h"
|
||||||
#include "droiddeck_color.h"
|
#include "droiddeck_color.h"
|
||||||
#include "gpu_clock_pin.h"
|
|
||||||
|
|
||||||
extern int droiddeck_wayland_run(void);
|
extern int droiddeck_wayland_run(void);
|
||||||
extern void droiddeck_wayland_set_scale_mode(int mode, int alignment);
|
extern void droiddeck_wayland_set_scale_mode(int mode, int alignment);
|
||||||
@@ -25,18 +23,12 @@ extern void droiddeck_wayland_send_pointer(int action, int x, int y);
|
|||||||
extern void droiddeck_wayland_send_touch(int action, int pointer_id, int x, int y);
|
extern void droiddeck_wayland_send_touch(int action, int pointer_id, int x, int y);
|
||||||
extern int droiddeck_cursor_snapshot(int *out, int cap);
|
extern int droiddeck_cursor_snapshot(int *out, int cap);
|
||||||
extern int droiddeck_cursor_serial(void);
|
extern int droiddeck_cursor_serial(void);
|
||||||
extern int droiddeck_hud_frame_times(float *out, int len, int64_t *total);
|
|
||||||
extern void droiddeck_wayland_send_key(int evdev, int state);
|
extern void droiddeck_wayland_send_key(int evdev, int state);
|
||||||
extern void droiddeck_wayland_send_scene_input(int type, int a, int b);
|
extern void droiddeck_wayland_send_scene_input(int type, int a, int b);
|
||||||
extern void droiddeck_wayland_vsync(int64_t frame_time_ns);
|
extern void droiddeck_wayland_vsync(int64_t frame_time_ns);
|
||||||
extern void droiddeck_stream_set(int on);
|
|
||||||
extern void droiddeck_stream_frame(AHardwareBuffer *ahb);
|
|
||||||
extern unsigned droiddeck_stream_frames(void);
|
|
||||||
extern void droiddeck_wayland_output_resized(void);
|
extern void droiddeck_wayland_output_resized(void);
|
||||||
extern void droiddeck_wayland_set_output_refresh_rate(int mhz);
|
extern void droiddeck_wayland_set_output_refresh_rate(int mhz);
|
||||||
extern volatile int g_fps_limit;
|
extern volatile int g_fps_limit;
|
||||||
extern volatile int g_release_unpaced;
|
|
||||||
extern volatile int g_render_on_commit;
|
|
||||||
extern volatile int g_hide_shell;
|
extern volatile int g_hide_shell;
|
||||||
extern volatile int g_zero_copy;
|
extern volatile int g_zero_copy;
|
||||||
extern volatile unsigned g_zero_copy_last;
|
extern volatile unsigned g_zero_copy_last;
|
||||||
@@ -270,20 +262,6 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot(
|
|||||||
return n;
|
return n;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jlong JNICALL
|
|
||||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHudFrameTimes(JNIEnv *env, jclass clazz, jfloatArray out) {
|
|
||||||
(void)clazz;
|
|
||||||
if (!out) return 0;
|
|
||||||
jint cap = (*env)->GetArrayLength(env, out);
|
|
||||||
float *buf = cap > 0 ? malloc(sizeof(float) * (size_t)cap) : NULL;
|
|
||||||
if (!buf) return 0;
|
|
||||||
int64_t total = 0;
|
|
||||||
int n = droiddeck_hud_frame_times(buf, cap, &total);
|
|
||||||
if (n > 0) (*env)->SetFloatArrayRegion(env, out, 0, n, buf);
|
|
||||||
free(buf);
|
|
||||||
return (jlong)total;
|
|
||||||
}
|
|
||||||
|
|
||||||
JNIEXPORT jint JNICALL
|
JNIEXPORT jint JNICALL
|
||||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSerial(JNIEnv *env, jclass clazz) {
|
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSerial(JNIEnv *env, jclass clazz) {
|
||||||
(void)env; (void)clazz;
|
(void)env; (void)clazz;
|
||||||
@@ -588,16 +566,9 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLookName(JNIEnv *
|
|||||||
free(s);
|
free(s);
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT void JNICALL
|
|
||||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetRenderOnCommit(JNIEnv *env, jclass clazz, jboolean on) {
|
|
||||||
g_render_on_commit = on ? 1 : 0;
|
|
||||||
__android_log_print(ANDROID_LOG_INFO, TAG, "render on commit %s", on ? "on" : "off");
|
|
||||||
}
|
|
||||||
|
|
||||||
JNIEXPORT void JNICALL
|
JNIEXPORT void JNICALL
|
||||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFpsLimit(JNIEnv *env, jclass clazz, jint fps) {
|
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFpsLimit(JNIEnv *env, jclass clazz, jint fps) {
|
||||||
g_fps_limit = fps > 0 ? fps : 0;
|
g_fps_limit = fps > 0 ? fps : 0;
|
||||||
g_release_unpaced = fps < 0;
|
|
||||||
__android_log_print(ANDROID_LOG_INFO, TAG, "fps limit %d", fps);
|
__android_log_print(ANDROID_LOG_INFO, TAG, "fps limit %d", fps);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -663,14 +634,8 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputDelete(JNIE
|
|||||||
extern void adrenotools_set_turbo(bool turbo);
|
extern void adrenotools_set_turbo(bool turbo);
|
||||||
JNIEXPORT void JNICALL
|
JNIEXPORT void JNICALL
|
||||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTurbo(JNIEnv *env, jclass clazz, jboolean on) {
|
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTurbo(JNIEnv *env, jclass clazz, jboolean on) {
|
||||||
(void)clazz;
|
(void)env; (void)clazz;
|
||||||
if (!gpu_clock_pin_set(on == JNI_TRUE)) {
|
adrenotools_set_turbo(on == JNI_TRUE);
|
||||||
int saved_errno = errno;
|
|
||||||
jclass error = (*env)->FindClass(env, "java/lang/IllegalStateException");
|
|
||||||
if (error) (*env)->ThrowNew(env, error, strerror(saved_errno));
|
|
||||||
}
|
|
||||||
// Clear a legacy global pin when recovering its marker after an app upgrade or crash.
|
|
||||||
if (on != JNI_TRUE) adrenotools_set_turbo(false);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jint JNICALL
|
JNIEXPORT jint JNICALL
|
||||||
@@ -695,21 +660,3 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCardboardSpatialP
|
|||||||
(*env)->GetFloatArrayRegion(env, pos, 0, 3, p);
|
(*env)->GetFloatArrayRegion(env, pos, 0, 3, p);
|
||||||
vkp_cardboard_set_spatial_pose(m, p, live ? 1 : 0);
|
vkp_cardboard_set_spatial_pose(m, p, live ? 1 : 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The Xbox Cloud Gaming native player: its decoded frames are the whole scene (no Wayland clients). */
|
|
||||||
JNIEXPORT void JNICALL
|
|
||||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamMode(JNIEnv *env, jclass clazz, jboolean on) {
|
|
||||||
droiddeck_stream_set(on ? 1 : 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
JNIEXPORT void JNICALL
|
|
||||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrame(JNIEnv *env, jclass clazz, jobject hardwareBuffer) {
|
|
||||||
if (!hardwareBuffer) return;
|
|
||||||
AHardwareBuffer *ahb = AHardwareBuffer_fromHardwareBuffer(env, hardwareBuffer);
|
|
||||||
if (ahb) droiddeck_stream_frame(ahb);
|
|
||||||
}
|
|
||||||
|
|
||||||
JNIEXPORT jint JNICALL
|
|
||||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrames(JNIEnv *env, jclass clazz) {
|
|
||||||
return (jint)droiddeck_stream_frames();
|
|
||||||
}
|
|
||||||
@@ -16,7 +16,6 @@ class App : Application() {
|
|||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
com.droiddeck.launcher.ui.Themes.loadGradient(this)
|
|
||||||
// Helper processes must not initialize the main USB provider or guest graphics context.
|
// Helper processes must not initialize the main USB provider or guest graphics context.
|
||||||
val process = if (android.os.Build.VERSION.SDK_INT >= 28) Application.getProcessName()
|
val process = if (android.os.Build.VERSION.SDK_INT >= 28) Application.getProcessName()
|
||||||
else (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)
|
else (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)
|
||||||
@@ -25,19 +24,9 @@ class App : Application() {
|
|||||||
if (android.os.Build.VERSION.SDK_INT >= 28) android.webkit.WebView.setDataDirectorySuffix("xbox")
|
if (android.os.Build.VERSION.SDK_INT >= 28) android.webkit.WebView.setDataDirectorySuffix("xbox")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (process == "$packageName:xboxcloud") {
|
|
||||||
if (android.os.Build.VERSION.SDK_INT >= 28) android.webkit.WebView.setDataDirectorySuffix("xboxcloud")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (process == "$packageName:xcloudnative") {
|
|
||||||
// The native cloud player: the stores log and nothing that touches the Linux session.
|
|
||||||
com.droiddeck.launcher.stores.StoresState.init(this)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic") return
|
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic") return
|
||||||
CrashHandler.install(this)
|
CrashHandler.install(this)
|
||||||
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
||||||
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
|
|
||||||
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
||||||
com.droiddeck.launcher.update.AppUpdates.init(this)
|
com.droiddeck.launcher.update.AppUpdates.init(this)
|
||||||
com.droiddeck.launcher.core.DownloadSource.init(this)
|
com.droiddeck.launcher.core.DownloadSource.init(this)
|
||||||
@@ -53,7 +42,6 @@ class App : Application() {
|
|||||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
|
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
|
||||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend)
|
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend)
|
||||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
|
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
|
||||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Fetches the packs an existing setup already relies on, so the first use after an update does not wait. */
|
/** Fetches the packs an existing setup already relies on, so the first use after an update does not wait. */
|
||||||
|
|||||||
@@ -11,46 +11,29 @@ import java.io.File
|
|||||||
|
|
||||||
internal class DeckyMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
|
internal class DeckyMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
|
||||||
var deckyInstalled by mutableStateOf<String?>(null)
|
var deckyInstalled by mutableStateOf<String?>(null)
|
||||||
var deckyLatest by mutableStateOf<DeckyManager.Release?>(null)
|
var deckyReleases by mutableStateOf<List<DeckyManager.Release>>(emptyList())
|
||||||
var deckyBranch by mutableIntStateOf(DeckyManager.BRANCH_STABLE)
|
|
||||||
private var deckyChannels = DeckyManager.ReleaseChannels(emptyList(), emptyList())
|
|
||||||
var deckyChecking by mutableStateOf(false)
|
var deckyChecking by mutableStateOf(false)
|
||||||
var deckyStage by mutableStateOf<String?>(null)
|
var deckyStage by mutableStateOf<String?>(null)
|
||||||
var deckyPercent by mutableIntStateOf(-1)
|
var deckyPercent by mutableIntStateOf(-1)
|
||||||
var deckyDownloadingBinary by mutableStateOf(false)
|
var deckyDownloadingBinary by mutableStateOf(false)
|
||||||
var deckySupervisor by mutableStateOf(false)
|
var deckySupervisor by mutableStateOf(false)
|
||||||
var deckyPendingZip by mutableStateOf<File?>(null)
|
|
||||||
var deckyReleaseRequest = 0
|
var deckyReleaseRequest = 0
|
||||||
|
|
||||||
fun refreshDecky() {
|
fun refreshDecky() {
|
||||||
val request = ++deckyReleaseRequest
|
val request = ++deckyReleaseRequest
|
||||||
deckyBranch = DeckyManager.branch(activity)
|
|
||||||
deckyChecking = true
|
deckyChecking = true
|
||||||
Thread({
|
Thread({
|
||||||
val channels = runCatching { DeckyManager.releaseChannels(activity) }
|
val channels = runCatching { DeckyManager.releaseChannels(activity) }
|
||||||
.getOrElse { DeckyManager.ReleaseChannels(emptyList(), emptyList()) }
|
.getOrElse { DeckyManager.ReleaseChannels(emptyList(), emptyList()) }
|
||||||
ui.post {
|
ui.post {
|
||||||
if (request == deckyReleaseRequest) {
|
if (request == deckyReleaseRequest) {
|
||||||
deckyChannels = channels
|
deckyReleases = channels.stable.ifEmpty { channels.prerelease }
|
||||||
deckyLatest = DeckyManager.latest(channels, deckyBranch)
|
|
||||||
deckyChecking = false
|
deckyChecking = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, "decky-releases").start()
|
}, "decky-releases").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun switchDeckyBranch(branch: Int) {
|
|
||||||
if (branch == deckyBranch || deckyStage != null || SessionState.running) return
|
|
||||||
val saved = runCatching { DeckyManager.setBranch(activity, branch) }
|
|
||||||
if (saved.isFailure) {
|
|
||||||
android.widget.Toast.makeText(activity, R.string.decky_channel_failed, android.widget.Toast.LENGTH_LONG).show()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
deckyBranch = branch
|
|
||||||
deckyLatest = DeckyManager.latest(deckyChannels, branch)
|
|
||||||
refreshDecky()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun installDecky(release: DeckyManager.Release) {
|
fun installDecky(release: DeckyManager.Release) {
|
||||||
if (deckyStage != null || SessionState.running) return
|
if (deckyStage != null || SessionState.running) return
|
||||||
deckyStage = activity.getString(R.string.store_starting); deckyPercent = -1
|
deckyStage = activity.getString(R.string.store_starting); deckyPercent = -1
|
||||||
@@ -66,17 +49,6 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun importPluginZip(archive: File) {
|
fun importPluginZip(archive: File) {
|
||||||
if (deckyStage != null || SessionState.running || deckyInstalled == null) return
|
|
||||||
deckyPendingZip = archive
|
|
||||||
}
|
|
||||||
|
|
||||||
fun cancelPluginZip() {
|
|
||||||
deckyPendingZip = null
|
|
||||||
}
|
|
||||||
|
|
||||||
fun confirmPluginZip() {
|
|
||||||
val archive = deckyPendingZip ?: return
|
|
||||||
deckyPendingZip = null
|
|
||||||
if (deckyStage != null || SessionState.running || deckyInstalled == null) return
|
if (deckyStage != null || SessionState.running || deckyInstalled == null) return
|
||||||
deckyStage = activity.getString(R.string.decky_plugin_starting); deckyPercent = -1
|
deckyStage = activity.getString(R.string.decky_plugin_starting); deckyPercent = -1
|
||||||
Thread({
|
Thread({
|
||||||
|
|||||||
@@ -55,8 +55,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
private set
|
private set
|
||||||
private var runtimePending by mutableStateOf(false)
|
private var runtimePending by mutableStateOf(false)
|
||||||
private var sessionRunning by mutableStateOf(false)
|
private var sessionRunning by mutableStateOf(false)
|
||||||
var tpUbwcMode: String by mutableStateOf(SessionPrefs.TP_UBWC_AUTO)
|
|
||||||
private set
|
|
||||||
|
|
||||||
val uiMode: String get() = when (mode) {
|
val uiMode: String get() = when (mode) {
|
||||||
SessionPrefs.GPU_DRIVERS_AUTO -> GPU_MODE_AUTO
|
SessionPrefs.GPU_DRIVERS_AUTO -> GPU_MODE_AUTO
|
||||||
@@ -75,16 +73,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
mode = uiMode, display = displaySlot(), runtime = runtimeSlot(),
|
mode = uiMode, display = displaySlot(), runtime = runtimeSlot(),
|
||||||
canRestart = !sessionRunning,
|
canRestart = !sessionRunning,
|
||||||
checkedAt = TurnipReleases.cached(activity)?.checkedAt ?: 0L,
|
checkedAt = TurnipReleases.cached(activity)?.checkedAt ?: 0L,
|
||||||
tpUbwcMode = tpUbwcMode.takeIf { gpu.model == 740 },
|
|
||||||
tpUbwcRestartRequired = com.droiddeck.launcher.gpu.TpUbwcHint.restartRequired(activity),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
fun chooseTpUbwcMode(mode: String) {
|
|
||||||
if (gpu.model != 740) return
|
|
||||||
SessionPrefs.setTpUbwcMode(activity, mode)
|
|
||||||
tpUbwcMode = mode
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun slotSource(chosenDefault: Boolean, defaultLabel: Int): String = activity.getString(when {
|
private fun slotSource(chosenDefault: Boolean, defaultLabel: Int): String = activity.getString(when {
|
||||||
uiMode == GPU_MODE_AUTO -> R.string.gpu_src_auto
|
uiMode == GPU_MODE_AUTO -> R.string.gpu_src_auto
|
||||||
uiMode == GPU_MODE_PAIR && pairRows.any { it.active } -> R.string.gpu_src_pair
|
uiMode == GPU_MODE_PAIR && pairRows.any { it.active } -> R.string.gpu_src_pair
|
||||||
@@ -134,7 +124,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
|||||||
var androidSelected by mutableStateOf("")
|
var androidSelected by mutableStateOf("")
|
||||||
|
|
||||||
fun refreshDrivers() {
|
fun refreshDrivers() {
|
||||||
tpUbwcMode = SessionPrefs.tpUbwcMode(activity)
|
|
||||||
val lm = LinuxVulkanDriverManager(activity)
|
val lm = LinuxVulkanDriverManager(activity)
|
||||||
fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
|
fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
|
||||||
val bundles = DriverBundle.all(activity)
|
val bundles = DriverBundle.all(activity)
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ class HomeActivity : Activity() {
|
|||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
||||||
routeHome()
|
routeHome()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ class HomeActivity : Activity() {
|
|||||||
.setAction(SessionService.ACTION_HOME_GUIDE)
|
.setAction(SessionService.ACTION_HOME_GUIDE)
|
||||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||||
} else {
|
} else {
|
||||||
Intent(this, FrontEndActivity::class.java)
|
Intent(this, MainActivity::class.java)
|
||||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||||
}
|
}
|
||||||
startActivity(destination)
|
startActivity(destination)
|
||||||
|
|||||||
@@ -6,41 +6,20 @@ import android.graphics.Bitmap
|
|||||||
import android.content.ComponentName
|
import android.content.ComponentName
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.pm.ApplicationInfo
|
|
||||||
import android.content.pm.LauncherApps
|
|
||||||
import android.content.pm.ShortcutInfo
|
|
||||||
import android.graphics.Rect
|
|
||||||
import android.os.Process
|
|
||||||
import android.os.UserHandle
|
|
||||||
import android.os.UserManager
|
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.net.Uri
|
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.provider.Settings
|
import android.provider.Settings
|
||||||
import androidx.core.graphics.drawable.toBitmap
|
import androidx.core.graphics.drawable.toBitmap
|
||||||
import com.droiddeck.launcher.session.SessionService
|
import com.droiddeck.launcher.session.SessionService
|
||||||
import com.droiddeck.launcher.session.SessionState
|
import com.droiddeck.launcher.session.SessionState
|
||||||
import kotlin.math.roundToInt
|
|
||||||
|
|
||||||
object HomeApp {
|
object HomeApp {
|
||||||
private const val ICON_DP = 72
|
|
||||||
|
|
||||||
data class LaunchableApp(
|
data class LaunchableApp(
|
||||||
val label: String,
|
val label: String,
|
||||||
val packageName: String,
|
val packageName: String,
|
||||||
val className: String,
|
val className: String,
|
||||||
val icon: Bitmap?,
|
val icon: Bitmap?,
|
||||||
val system: Boolean = false,
|
)
|
||||||
val game: Boolean = false,
|
|
||||||
val installedAt: Long = 0L,
|
|
||||||
val updatedAt: Long = 0L,
|
|
||||||
val user: UserHandle? = null,
|
|
||||||
val userSerial: Long = 0L,
|
|
||||||
) {
|
|
||||||
val component get() = ComponentName(packageName, className)
|
|
||||||
val key get() = "$packageName/$className" + if (userSerial != 0L) "#$userSerial" else ""
|
|
||||||
val work get() = userSerial != 0L
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isHomeScreenEnabled(context: Context): Boolean =
|
fun isHomeScreenEnabled(context: Context): Boolean =
|
||||||
context.packageManager.getComponentEnabledSetting(ComponentName(context, HomeActivity::class.java)) ==
|
context.packageManager.getComponentEnabledSetting(ComponentName(context, HomeActivity::class.java)) ==
|
||||||
@@ -90,79 +69,33 @@ object HomeApp {
|
|||||||
fun settingsIntent(): Intent = Intent(Settings.ACTION_HOME_SETTINGS)
|
fun settingsIntent(): Intent = Intent(Settings.ACTION_HOME_SETTINGS)
|
||||||
|
|
||||||
fun launchableApps(context: Context): List<LaunchableApp> {
|
fun launchableApps(context: Context): List<LaunchableApp> {
|
||||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
|
||||||
val users = context.getSystemService(UserManager::class.java)
|
|
||||||
val pm = context.packageManager
|
val pm = context.packageManager
|
||||||
val own = Process.myUserHandle()
|
val launch = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||||
val iconPx = (ICON_DP * context.resources.displayMetrics.density).roundToInt()
|
val apps = pm.queryIntentActivities(launch, 0)
|
||||||
val apps = users.userProfiles.flatMap { user ->
|
.asSequence()
|
||||||
val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
|
.mapNotNull { result ->
|
||||||
runCatching { launcher.getActivityList(null, user) }.getOrDefault(emptyList()).mapNotNull { info ->
|
val activity = result.activityInfo ?: return@mapNotNull null
|
||||||
val component = info.componentName
|
if (!activity.exported || activity.packageName == context.packageName) return@mapNotNull null
|
||||||
if (component.packageName == context.packageName && user == own) return@mapNotNull null
|
val label = result.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { activity.packageName }
|
||||||
val label = info.label?.toString()?.trim().orEmpty().ifEmpty { component.packageName }
|
val icon = runCatching { result.loadIcon(pm).toBitmap(48, 48) }.getOrNull()
|
||||||
val icon = runCatching { info.getBadgedIcon(0).toBitmap(iconPx, iconPx) }.getOrNull()
|
LaunchableApp(label, activity.packageName, activity.name, icon)
|
||||||
val app = info.applicationInfo
|
|
||||||
val updated = if (user == own) runCatching { pm.getPackageInfo(component.packageName, 0).lastUpdateTime }.getOrNull() else null
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
val game = app.category == ApplicationInfo.CATEGORY_GAME || app.flags and ApplicationInfo.FLAG_IS_GAME != 0
|
|
||||||
LaunchableApp(
|
|
||||||
label, component.packageName, component.className, icon,
|
|
||||||
system = app.flags and (ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0,
|
|
||||||
game = game,
|
|
||||||
installedAt = info.firstInstallTime,
|
|
||||||
updatedAt = updated ?: info.firstInstallTime,
|
|
||||||
user = user,
|
|
||||||
userSerial = serial,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
.distinctBy { it.packageName }
|
||||||
|
.toList()
|
||||||
|
return apps.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
|
||||||
|
}
|
||||||
|
|
||||||
|
fun launch(context: Context, app: LaunchableApp, displayId: Int? = null) {
|
||||||
|
val intent = Intent(Intent.ACTION_MAIN)
|
||||||
|
.addCategory(Intent.CATEGORY_LAUNCHER)
|
||||||
|
.setComponent(ComponentName(app.packageName, app.className))
|
||||||
|
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
if (displayId == null) {
|
||||||
|
context.startActivity(intent)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
return apps.distinctBy { it.key }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
|
val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId)
|
||||||
}
|
context.startActivity(intent, options.toBundle())
|
||||||
|
|
||||||
fun launch(context: Context, app: LaunchableApp, displayId: Int? = null, bounds: Rect? = null) {
|
|
||||||
val options = displayId?.let { ActivityOptions.makeBasic().setLaunchDisplayId(it).toBundle() }
|
|
||||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
|
||||||
launcher.startMainActivity(app.component, app.user ?: Process.myUserHandle(), bounds, options)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun canUseShortcuts(context: Context): Boolean =
|
|
||||||
runCatching { context.getSystemService(LauncherApps::class.java).hasShortcutHostPermission() }.getOrDefault(false)
|
|
||||||
|
|
||||||
fun shortcuts(context: Context, app: LaunchableApp): List<ShortcutInfo> {
|
|
||||||
if (!canUseShortcuts(context)) return emptyList()
|
|
||||||
val query = LauncherApps.ShortcutQuery()
|
|
||||||
.setPackage(app.packageName)
|
|
||||||
.setActivity(app.component)
|
|
||||||
.setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC or LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST)
|
|
||||||
return runCatching { context.getSystemService(LauncherApps::class.java).getShortcuts(query, app.user ?: Process.myUserHandle()) }
|
|
||||||
.getOrNull().orEmpty()
|
|
||||||
.filter { it.isEnabled }
|
|
||||||
.sortedWith(compareBy<ShortcutInfo> { if (it.isDeclaredInManifest) 0 else 1 }.thenBy { it.rank })
|
|
||||||
.take(5)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun shortcutIcon(context: Context, info: ShortcutInfo, px: Int = (ICON_DP * context.resources.displayMetrics.density).roundToInt()): Bitmap? = runCatching {
|
|
||||||
context.getSystemService(LauncherApps::class.java)
|
|
||||||
.getShortcutIconDrawable(info, context.resources.displayMetrics.densityDpi)?.toBitmap(px, px)
|
|
||||||
}.getOrNull()
|
|
||||||
|
|
||||||
fun startShortcut(context: Context, info: ShortcutInfo) {
|
|
||||||
context.getSystemService(LauncherApps::class.java).startShortcut(info, null, null)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun openAppInfo(context: Context, app: LaunchableApp) {
|
|
||||||
context.getSystemService(LauncherApps::class.java)
|
|
||||||
.startAppDetailsActivity(app.component, app.user ?: Process.myUserHandle(), null, null)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun canUninstall(app: LaunchableApp): Boolean = !app.system && !app.work
|
|
||||||
|
|
||||||
fun uninstall(context: Context, app: LaunchableApp) {
|
|
||||||
context.startActivity(
|
|
||||||
Intent(Intent.ACTION_DELETE, Uri.fromParts("package", app.packageName, null))
|
|
||||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun isActiveSteamSession(): Boolean =
|
fun isActiveSteamSession(): Boolean =
|
||||||
|
|||||||
@@ -1,65 +0,0 @@
|
|||||||
package com.droiddeck.launcher
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.runtime.setValue
|
|
||||||
import org.json.JSONArray
|
|
||||||
import org.json.JSONObject
|
|
||||||
import java.util.UUID
|
|
||||||
|
|
||||||
object HomeFolders {
|
|
||||||
data class Folder(val id: String, val name: String, val apps: List<String>)
|
|
||||||
|
|
||||||
private const val PREFS = "home_launcher"
|
|
||||||
private const val KEY = "folders"
|
|
||||||
|
|
||||||
var folders by mutableStateOf<List<Folder>>(emptyList())
|
|
||||||
private set
|
|
||||||
private var loaded = false
|
|
||||||
|
|
||||||
fun load(context: Context) {
|
|
||||||
if (loaded) return
|
|
||||||
loaded = true
|
|
||||||
val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return
|
|
||||||
folders = runCatching {
|
|
||||||
val array = JSONArray(raw)
|
|
||||||
(0 until array.length()).map { i ->
|
|
||||||
val o = array.getJSONObject(i)
|
|
||||||
val apps = o.getJSONArray("apps")
|
|
||||||
Folder(o.getString("id"), o.getString("name"), (0 until apps.length()).map { apps.getString(it) })
|
|
||||||
}
|
|
||||||
}.getOrDefault(emptyList())
|
|
||||||
}
|
|
||||||
|
|
||||||
fun create(context: Context, name: String, appKey: String): Folder {
|
|
||||||
val folder = Folder(UUID.randomUUID().toString(), name, listOf(appKey))
|
|
||||||
update(context, without(appKey) + folder)
|
|
||||||
return folder
|
|
||||||
}
|
|
||||||
|
|
||||||
fun add(context: Context, folderId: String, appKey: String) =
|
|
||||||
update(context, without(appKey).map { if (it.id == folderId) it.copy(apps = it.apps + appKey) else it })
|
|
||||||
|
|
||||||
fun remove(context: Context, appKey: String) = update(context, without(appKey))
|
|
||||||
|
|
||||||
fun rename(context: Context, folderId: String, name: String) =
|
|
||||||
update(context, folders.map { if (it.id == folderId) it.copy(name = name) else it })
|
|
||||||
|
|
||||||
fun delete(context: Context, folderId: String) = update(context, folders.filterNot { it.id == folderId })
|
|
||||||
|
|
||||||
fun migrateMembers(context: Context, keyFor: (String) -> String?) {
|
|
||||||
if (folders.none { f -> f.apps.any { '/' !in it } }) return
|
|
||||||
update(context, folders.map { f -> f.copy(apps = f.apps.map { if ('/' in it) it else keyFor(it) ?: it }.distinct()) })
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun without(appKey: String): List<Folder> =
|
|
||||||
folders.map { it.copy(apps = it.apps - appKey) }.filter { it.apps.isNotEmpty() }
|
|
||||||
|
|
||||||
private fun update(context: Context, next: List<Folder>) {
|
|
||||||
folders = next
|
|
||||||
val array = JSONArray()
|
|
||||||
for (f in next) array.put(JSONObject().put("id", f.id).put("name", f.name).put("apps", JSONArray(f.apps)))
|
|
||||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
package com.droiddeck.launcher
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.runtime.setValue
|
|
||||||
|
|
||||||
object HomeHidden {
|
|
||||||
private const val PREFS = "home_launcher"
|
|
||||||
private const val KEY = "hidden"
|
|
||||||
|
|
||||||
var keys by mutableStateOf<Set<String>>(emptySet())
|
|
||||||
private set
|
|
||||||
private var loaded = false
|
|
||||||
|
|
||||||
fun load(context: Context) {
|
|
||||||
if (loaded) return
|
|
||||||
loaded = true
|
|
||||||
keys = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getStringSet(KEY, emptySet()).orEmpty().toSet()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun set(context: Context, key: String, hidden: Boolean) {
|
|
||||||
keys = if (hidden) keys + key else keys - key
|
|
||||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putStringSet(KEY, keys).apply()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
package com.droiddeck.launcher
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.pm.LauncherApps
|
|
||||||
import android.content.pm.ShortcutInfo
|
|
||||||
import android.graphics.Bitmap
|
|
||||||
import android.os.Handler
|
|
||||||
import android.os.Looper
|
|
||||||
import android.os.Process
|
|
||||||
import android.os.UserManager
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.runtime.setValue
|
|
||||||
|
|
||||||
/** Shortcuts other apps asked to put on the home screen. The system keeps the pinned set per launcher. */
|
|
||||||
object HomePins {
|
|
||||||
class Pinned(val info: ShortcutInfo, val icon: Bitmap?, val appLabel: String, val userSerial: Long) {
|
|
||||||
val key get() = "pin:${info.`package`}/${info.id}" + if (userSerial != 0L) "#$userSerial" else ""
|
|
||||||
val label get() = info.shortLabel?.toString()?.trim().orEmpty().ifEmpty { appLabel }
|
|
||||||
val work get() = userSerial != 0L
|
|
||||||
}
|
|
||||||
|
|
||||||
var pinned by mutableStateOf<List<Pinned>>(emptyList())
|
|
||||||
private set
|
|
||||||
private val main = Handler(Looper.getMainLooper())
|
|
||||||
private var listing = 0
|
|
||||||
|
|
||||||
fun refresh(context: Context) {
|
|
||||||
val app = context.applicationContext
|
|
||||||
val seq = ++listing
|
|
||||||
Thread({
|
|
||||||
val list = runCatching { load(app) }.getOrDefault(emptyList())
|
|
||||||
main.post { if (seq == listing) pinned = list }
|
|
||||||
}, "home-pins").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun load(context: Context): List<Pinned> {
|
|
||||||
if (!HomeApp.canUseShortcuts(context)) return emptyList()
|
|
||||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
|
||||||
val users = context.getSystemService(UserManager::class.java)
|
|
||||||
val pm = context.packageManager
|
|
||||||
val own = Process.myUserHandle()
|
|
||||||
val query = LauncherApps.ShortcutQuery().setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
|
|
||||||
return users.userProfiles.flatMap { user ->
|
|
||||||
val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
|
|
||||||
runCatching { launcher.getShortcuts(query, user) }.getOrNull().orEmpty()
|
|
||||||
.filter { it.isEnabled && it.isPinned }
|
|
||||||
.map { info ->
|
|
||||||
val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.`package`, 0)).toString() }
|
|
||||||
.getOrDefault(info.`package`)
|
|
||||||
Pinned(info, HomeApp.shortcutIcon(context, info), appLabel, serial)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun accept(context: Context, request: LauncherApps.PinItemRequest): Boolean {
|
|
||||||
val ok = runCatching { request.isValid && request.accept() }.getOrDefault(false)
|
|
||||||
if (ok) refresh(context)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
fun unpin(context: Context, pinned: Pinned) {
|
|
||||||
val info = pinned.info
|
|
||||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
|
||||||
val query = LauncherApps.ShortcutQuery().setPackage(info.`package`).setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
|
|
||||||
val unpinned = runCatching {
|
|
||||||
val current = checkNotNull(launcher.getShortcuts(query, info.userHandle))
|
|
||||||
val keep = current.map { it.id } - info.id
|
|
||||||
launcher.pinShortcuts(info.`package`, keep, info.userHandle)
|
|
||||||
}.isSuccess
|
|
||||||
if (!unpinned) return
|
|
||||||
listing++
|
|
||||||
this.pinned = this.pinned.filterNot { it.key == pinned.key }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,317 +0,0 @@
|
|||||||
package com.droiddeck.launcher
|
|
||||||
|
|
||||||
import android.app.Activity
|
|
||||||
import android.appwidget.AppWidgetHost
|
|
||||||
import android.appwidget.AppWidgetHostView
|
|
||||||
import android.appwidget.AppWidgetManager
|
|
||||||
import android.appwidget.AppWidgetProviderInfo
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import android.content.pm.LauncherApps
|
|
||||||
import android.graphics.Bitmap
|
|
||||||
import android.os.Build
|
|
||||||
import android.os.Bundle
|
|
||||||
import android.os.Handler
|
|
||||||
import android.os.Looper
|
|
||||||
import android.util.SizeF
|
|
||||||
import android.view.HapticFeedbackConstants
|
|
||||||
import android.view.MotionEvent
|
|
||||||
import android.view.ViewConfiguration
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.runtime.setValue
|
|
||||||
import androidx.core.graphics.drawable.toBitmap
|
|
||||||
import org.json.JSONArray
|
|
||||||
import org.json.JSONObject
|
|
||||||
import kotlin.math.hypot
|
|
||||||
import kotlin.math.roundToInt
|
|
||||||
|
|
||||||
object HomeWidgets {
|
|
||||||
data class Placed(val id: Int, val widthDp: Int, val heightDp: Int)
|
|
||||||
|
|
||||||
data class Provider(
|
|
||||||
val info: AppWidgetProviderInfo,
|
|
||||||
val label: String,
|
|
||||||
val appLabel: String,
|
|
||||||
val preview: Bitmap?,
|
|
||||||
val widthDp: Int,
|
|
||||||
val heightDp: Int,
|
|
||||||
)
|
|
||||||
|
|
||||||
private const val HOST_ID = 0x0DDE
|
|
||||||
private const val PREFS = "home_launcher"
|
|
||||||
private const val KEY = "widgets"
|
|
||||||
private const val REQUEST_BIND = 0x0DD1
|
|
||||||
private const val REQUEST_CONFIGURE = 0x0DD2
|
|
||||||
private const val REQUEST_RECONFIGURE = 0x0DD3
|
|
||||||
const val MIN_WIDTH_DP = 96
|
|
||||||
const val MIN_HEIGHT_DP = 56
|
|
||||||
|
|
||||||
var widgets by mutableStateOf<List<Placed>>(emptyList())
|
|
||||||
private set
|
|
||||||
var providers by mutableStateOf<List<Provider>?>(null)
|
|
||||||
private set
|
|
||||||
private var loaded = false
|
|
||||||
private var host: Host? = null
|
|
||||||
private var pending: AppWidgetProviderInfo? = null
|
|
||||||
private var pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
|
|
||||||
private var pinRequest: LauncherApps.PinItemRequest? = null
|
|
||||||
private val main = Handler(Looper.getMainLooper())
|
|
||||||
|
|
||||||
private class Host(context: Context) : AppWidgetHost(context, HOST_ID) {
|
|
||||||
override fun onCreateView(context: Context, appWidgetId: Int, appWidget: AppWidgetProviderInfo?): AppWidgetHostView =
|
|
||||||
HomeWidgetView(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
class HomeWidgetView(context: Context) : AppWidgetHostView(context) {
|
|
||||||
var onLongPress: (() -> Unit)? = null
|
|
||||||
private var fired = false
|
|
||||||
private var downX = 0f
|
|
||||||
private var downY = 0f
|
|
||||||
private val slop = ViewConfiguration.get(context).scaledTouchSlop
|
|
||||||
private val longPress = Runnable {
|
|
||||||
fired = true
|
|
||||||
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
|
|
||||||
onLongPress?.invoke()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
|
|
||||||
when (ev.actionMasked) {
|
|
||||||
MotionEvent.ACTION_DOWN -> {
|
|
||||||
fired = false
|
|
||||||
downX = ev.x
|
|
||||||
downY = ev.y
|
|
||||||
postDelayed(longPress, ViewConfiguration.getLongPressTimeout().toLong())
|
|
||||||
}
|
|
||||||
MotionEvent.ACTION_MOVE -> if (hypot(ev.x - downX, ev.y - downY) > slop) removeCallbacks(longPress)
|
|
||||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_POINTER_DOWN -> removeCallbacks(longPress)
|
|
||||||
}
|
|
||||||
return fired
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
|
||||||
if (fired) {
|
|
||||||
if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) fired = false
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return super.onTouchEvent(event)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun host(context: Context): Host = host ?: Host(context.applicationContext).also { host = it }
|
|
||||||
|
|
||||||
fun load(context: Context) {
|
|
||||||
if (loaded) return
|
|
||||||
loaded = true
|
|
||||||
val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return
|
|
||||||
val manager = AppWidgetManager.getInstance(context)
|
|
||||||
val parsed = runCatching {
|
|
||||||
val array = JSONArray(raw)
|
|
||||||
(0 until array.length()).map { i ->
|
|
||||||
val o = array.getJSONObject(i)
|
|
||||||
Placed(o.getInt("id"), o.getInt("w"), o.getInt("h"))
|
|
||||||
}
|
|
||||||
}.getOrDefault(emptyList())
|
|
||||||
val live = parsed.filter { manager.getAppWidgetInfo(it.id) != null }
|
|
||||||
parsed.filterNot { it in live }.forEach { host(context).deleteAppWidgetId(it.id) }
|
|
||||||
widgets = live
|
|
||||||
if (live.size != parsed.size) save(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun startListening(context: Context) {
|
|
||||||
load(context)
|
|
||||||
runCatching { host(context).startListening() }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun stopListening(context: Context) {
|
|
||||||
runCatching { host(context).stopListening() }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun info(context: Context, id: Int): AppWidgetProviderInfo? = AppWidgetManager.getInstance(context).getAppWidgetInfo(id)
|
|
||||||
|
|
||||||
fun createView(context: Context, id: Int): HomeWidgetView? {
|
|
||||||
val info = info(context, id) ?: return null
|
|
||||||
return host(context).createView(context, id, info) as? HomeWidgetView
|
|
||||||
}
|
|
||||||
|
|
||||||
fun applySize(view: AppWidgetHostView, widthDp: Int, heightDp: Int) {
|
|
||||||
if (Build.VERSION.SDK_INT >= 31) {
|
|
||||||
view.updateAppWidgetSize(Bundle(), listOf(SizeF(widthDp.toFloat(), heightDp.toFloat())))
|
|
||||||
} else {
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
view.updateAppWidgetSize(null, widthDp, heightDp, widthDp, heightDp)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun loadProviders(context: Context) {
|
|
||||||
if (providers != null) return
|
|
||||||
val app = context.applicationContext
|
|
||||||
Thread({
|
|
||||||
val pm = app.packageManager
|
|
||||||
val manager = AppWidgetManager.getInstance(app)
|
|
||||||
val dpi = app.resources.displayMetrics.densityDpi
|
|
||||||
val list = manager.installedProviders.mapNotNull { info ->
|
|
||||||
runCatching {
|
|
||||||
val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.provider.packageName, 0)).toString() }
|
|
||||||
.getOrDefault(info.provider.packageName)
|
|
||||||
val drawable = info.loadPreviewImage(app, dpi) ?: info.loadIcon(app, dpi)
|
|
||||||
val preview = drawable?.let { d ->
|
|
||||||
val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192
|
|
||||||
val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192
|
|
||||||
val scale = minOf(1f, 360f / maxOf(w, h))
|
|
||||||
d.toBitmap((w * scale).roundToInt().coerceAtLeast(1), (h * scale).roundToInt().coerceAtLeast(1))
|
|
||||||
}
|
|
||||||
val (w, h) = defaultSize(app, info)
|
|
||||||
Provider(info, info.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { appLabel }, appLabel, preview, w, h)
|
|
||||||
}.getOrNull()
|
|
||||||
}.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, Provider::appLabel).thenBy(String.CASE_INSENSITIVE_ORDER, Provider::label))
|
|
||||||
main.post { providers = list }
|
|
||||||
}, "widget-providers").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun refreshProviders(context: Context) {
|
|
||||||
providers = null
|
|
||||||
loadProviders(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun defaultSize(context: Context, info: AppWidgetProviderInfo): Pair<Int, Int> {
|
|
||||||
val density = context.resources.displayMetrics.density
|
|
||||||
var w = (info.minWidth / density).roundToInt()
|
|
||||||
var h = (info.minHeight / density).roundToInt()
|
|
||||||
if (Build.VERSION.SDK_INT >= 31) {
|
|
||||||
if (info.targetCellWidth > 0) w = maxOf(w, info.targetCellWidth * 80)
|
|
||||||
if (info.targetCellHeight > 0) h = maxOf(h, info.targetCellHeight * 80)
|
|
||||||
}
|
|
||||||
return w.coerceIn(160, 560) to h.coerceIn(MIN_HEIGHT_DP, 360)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun minSize(context: Context, id: Int): Pair<Int, Int> {
|
|
||||||
val info = info(context, id) ?: return MIN_WIDTH_DP to MIN_HEIGHT_DP
|
|
||||||
val density = context.resources.displayMetrics.density
|
|
||||||
val w = (if (info.minResizeWidth > 0) info.minResizeWidth else info.minWidth) / density
|
|
||||||
val h = (if (info.minResizeHeight > 0) info.minResizeHeight else info.minHeight) / density
|
|
||||||
return w.roundToInt().coerceAtLeast(MIN_WIDTH_DP) to h.roundToInt().coerceAtLeast(MIN_HEIGHT_DP)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun add(activity: Activity, provider: Provider) {
|
|
||||||
if (pendingId == AppWidgetManager.INVALID_APPWIDGET_ID) add(activity, provider.info, null)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Places a widget another app asked for; its own app has already configured it. */
|
|
||||||
fun addPinned(activity: Activity, request: LauncherApps.PinItemRequest): Boolean {
|
|
||||||
if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) return false
|
|
||||||
val info = request.getAppWidgetProviderInfo(activity) ?: return false
|
|
||||||
load(activity)
|
|
||||||
add(activity, info, request)
|
|
||||||
return pending != null
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun add(activity: Activity, info: AppWidgetProviderInfo, request: LauncherApps.PinItemRequest?) {
|
|
||||||
val h = host(activity)
|
|
||||||
val id = h.allocateAppWidgetId()
|
|
||||||
pending = info
|
|
||||||
pendingId = id
|
|
||||||
pinRequest = request
|
|
||||||
val manager = AppWidgetManager.getInstance(activity)
|
|
||||||
val bound = runCatching { manager.bindAppWidgetIdIfAllowed(id, info.profile, info.provider, null) }.getOrDefault(false)
|
|
||||||
if (bound) {
|
|
||||||
bound(activity, id, info)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val bind = Intent(AppWidgetManager.ACTION_APPWIDGET_BIND)
|
|
||||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
|
|
||||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider)
|
|
||||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, info.profile)
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
runCatching { activity.startActivityForResult(bind, REQUEST_BIND) }.onFailure { abandon(activity) }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun bound(activity: Activity, id: Int, info: AppWidgetProviderInfo) {
|
|
||||||
val request = pinRequest
|
|
||||||
if (request == null) {
|
|
||||||
configure(activity, id, info)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val accepted = runCatching { request.isValid && request.accept(Bundle().apply { putInt(AppWidgetManager.EXTRA_APPWIDGET_ID, id) }) }
|
|
||||||
.getOrDefault(false)
|
|
||||||
if (accepted) place(activity, id, info) else abandon(activity)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun configure(activity: Activity, id: Int, info: AppWidgetProviderInfo) {
|
|
||||||
val optional = Build.VERSION.SDK_INT >= 31 &&
|
|
||||||
info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_CONFIGURATION_OPTIONAL != 0
|
|
||||||
if (info.configure == null || optional) {
|
|
||||||
place(activity, id, info)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_CONFIGURE, null) }
|
|
||||||
.onFailure { place(activity, id, info) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun canReconfigure(context: Context, id: Int): Boolean {
|
|
||||||
val info = info(context, id) ?: return false
|
|
||||||
if (info.configure == null) return false
|
|
||||||
return Build.VERSION.SDK_INT < 28 || info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_RECONFIGURABLE != 0
|
|
||||||
}
|
|
||||||
|
|
||||||
fun reconfigure(activity: Activity, id: Int) {
|
|
||||||
runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_RECONFIGURE, null) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int): Boolean {
|
|
||||||
when (requestCode) {
|
|
||||||
REQUEST_BIND -> {
|
|
||||||
val info = pending
|
|
||||||
if (resultCode == Activity.RESULT_OK && info != null) bound(activity, pendingId, info) else abandon(activity)
|
|
||||||
}
|
|
||||||
REQUEST_CONFIGURE -> {
|
|
||||||
val info = pending
|
|
||||||
if (resultCode == Activity.RESULT_OK && info != null) place(activity, pendingId, info) else abandon(activity)
|
|
||||||
}
|
|
||||||
REQUEST_RECONFIGURE -> Unit
|
|
||||||
else -> return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun abandon(context: Context) {
|
|
||||||
if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) host(context).deleteAppWidgetId(pendingId)
|
|
||||||
pending = null
|
|
||||||
pinRequest = null
|
|
||||||
pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun place(context: Context, id: Int, info: AppWidgetProviderInfo) {
|
|
||||||
val (w, h) = defaultSize(context, info)
|
|
||||||
pending = null
|
|
||||||
pinRequest = null
|
|
||||||
pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
|
|
||||||
widgets = widgets + Placed(id, w, h)
|
|
||||||
save(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun resize(context: Context, id: Int, widthDp: Int, heightDp: Int) {
|
|
||||||
widgets = widgets.map { if (it.id == id) it.copy(widthDp = widthDp, heightDp = heightDp) else it }
|
|
||||||
save(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun move(context: Context, id: Int, by: Int) {
|
|
||||||
val i = widgets.indexOfFirst { it.id == id }
|
|
||||||
val j = i + by
|
|
||||||
if (i < 0 || j !in widgets.indices) return
|
|
||||||
widgets = widgets.toMutableList().apply { add(j, removeAt(i)) }
|
|
||||||
save(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun remove(context: Context, id: Int) {
|
|
||||||
host(context).deleteAppWidgetId(id)
|
|
||||||
widgets = widgets.filterNot { it.id == id }
|
|
||||||
save(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun save(context: Context) {
|
|
||||||
val array = JSONArray()
|
|
||||||
for (w in widgets) array.put(JSONObject().put("id", w.id).put("w", w.widthDp).put("h", w.heightDp))
|
|
||||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -8,7 +8,7 @@ object LauncherIcon {
|
|||||||
const val DARK = "dark"
|
const val DARK = "dark"
|
||||||
const val LIGHT = "light"
|
const val LIGHT = "light"
|
||||||
|
|
||||||
private val aliases = linkedMapOf(DARK to "com.droiddeck.launcher.MainActivity", LIGHT to "com.droiddeck.launcher.LauncherLight")
|
private val aliases = linkedMapOf(DARK to "com.droiddeck.launcher.LauncherDark", LIGHT to "com.droiddeck.launcher.LauncherLight")
|
||||||
|
|
||||||
val options: List<Pair<String, Int>> = listOf(
|
val options: List<Pair<String, Int>> = listOf(
|
||||||
DARK to R.string.setup_launcher_icon_dark,
|
DARK to R.string.setup_launcher_icon_dark,
|
||||||
@@ -29,12 +29,6 @@ object LauncherIcon {
|
|||||||
|
|
||||||
fun activity(context: Context): ComponentName = component(context, current(context))
|
fun activity(context: Context): ComponentName = component(context, current(context))
|
||||||
|
|
||||||
fun repair(context: Context, launchedFrom: ComponentName?) {
|
|
||||||
if (!enabled(context, DARK) || !enabled(context, LIGHT) || launchedFrom == component(context, DARK)) return
|
|
||||||
context.packageManager.setComponentEnabledSetting(component(context, DARK),
|
|
||||||
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun set(context: Context, style: String) {
|
fun set(context: Context, style: String) {
|
||||||
if (style !in aliases || style == current(context)) return
|
if (style !in aliases || style == current(context)) return
|
||||||
val pm = context.packageManager
|
val pm = context.packageManager
|
||||||
|
|||||||
+68
-461
File diff suppressed because it is too large.
Load diff
@@ -1,328 +0,0 @@
|
|||||||
package com.droiddeck.launcher
|
|
||||||
|
|
||||||
import android.app.ActivityOptions
|
|
||||||
import android.app.AppOpsManager
|
|
||||||
import android.app.PictureInPictureParams
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import android.content.pm.PackageManager
|
|
||||||
import android.content.res.Configuration
|
|
||||||
import android.os.Build
|
|
||||||
import android.os.Bundle
|
|
||||||
import android.os.Process
|
|
||||||
import android.provider.Settings
|
|
||||||
import android.util.Rational
|
|
||||||
import androidx.activity.ComponentActivity
|
|
||||||
import androidx.activity.compose.BackHandler
|
|
||||||
import androidx.activity.compose.setContent
|
|
||||||
import androidx.compose.animation.core.LinearEasing
|
|
||||||
import androidx.compose.animation.core.RepeatMode
|
|
||||||
import androidx.compose.animation.core.animateFloat
|
|
||||||
import androidx.compose.animation.core.infiniteRepeatable
|
|
||||||
import androidx.compose.animation.core.rememberInfiniteTransition
|
|
||||||
import androidx.compose.animation.core.tween
|
|
||||||
import androidx.compose.foundation.background
|
|
||||||
import androidx.compose.foundation.border
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
|
||||||
import androidx.compose.foundation.layout.Box
|
|
||||||
import androidx.compose.foundation.layout.Column
|
|
||||||
import androidx.compose.foundation.layout.Row
|
|
||||||
import androidx.compose.foundation.layout.Spacer
|
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
|
||||||
import androidx.compose.foundation.layout.height
|
|
||||||
import androidx.compose.foundation.layout.padding
|
|
||||||
import androidx.compose.foundation.layout.size
|
|
||||||
import androidx.compose.foundation.layout.width
|
|
||||||
import androidx.compose.foundation.layout.widthIn
|
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
|
||||||
import androidx.compose.material3.Text
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
|
||||||
import androidx.compose.runtime.collectAsState
|
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.runtime.produceState
|
|
||||||
import androidx.compose.runtime.remember
|
|
||||||
import androidx.compose.runtime.setValue
|
|
||||||
import androidx.compose.ui.Alignment
|
|
||||||
import androidx.compose.ui.Modifier
|
|
||||||
import androidx.compose.ui.draw.alpha
|
|
||||||
import androidx.compose.ui.draw.scale
|
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.res.stringResource
|
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import com.droiddeck.launcher.core.AppLanguage
|
|
||||||
import com.droiddeck.launcher.core.GlobalSettings
|
|
||||||
import com.droiddeck.launcher.core.WirelessAdbPairingService
|
|
||||||
import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage
|
|
||||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
|
||||||
import com.droiddeck.launcher.ui.LocalPalette
|
|
||||||
import com.droiddeck.launcher.ui.PrimaryButton
|
|
||||||
import com.droiddeck.launcher.ui.SecondaryButton
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
|
|
||||||
class PairingGuideActivity : ComponentActivity() {
|
|
||||||
enum class Step { BUILD_NUMBER, WIRELESS_DEBUGGING, PAIR, CODE, WORKING, DONE, FAILED }
|
|
||||||
|
|
||||||
private var settingsDisplay: Int? = null
|
|
||||||
private var inPip by mutableStateOf(false)
|
|
||||||
private var launchPending = false
|
|
||||||
|
|
||||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
|
||||||
super.onCreate(savedInstanceState)
|
|
||||||
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
|
|
||||||
setContent { DroidDeckTheme { Guide() } }
|
|
||||||
launchPending = savedInstanceState == null
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onNewIntent(intent: Intent) {
|
|
||||||
super.onNewIntent(intent)
|
|
||||||
setIntent(intent)
|
|
||||||
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
|
|
||||||
launchPending = true
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onResume() {
|
|
||||||
super.onResume()
|
|
||||||
if (!launchPending) return
|
|
||||||
if (inPip || settingsDisplay != null) {
|
|
||||||
launchSettings()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
enterPip()
|
|
||||||
if (!inPip) launchSettings()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
|
|
||||||
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
|
|
||||||
inPip = isInPictureInPictureMode
|
|
||||||
if (isInPictureInPictureMode && launchPending) launchSettings()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launchSettings() {
|
|
||||||
launchPending = false
|
|
||||||
openSettings(stepFor(this, WirelessAdbPairingService.stage.value))
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun enterPip() {
|
|
||||||
inPip = runCatching {
|
|
||||||
enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(Rational(4, 3)).build())
|
|
||||||
}.getOrDefault(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun openSettings(step: Step) {
|
|
||||||
val intent = if (step == Step.BUILD_NUMBER) {
|
|
||||||
Intent(Settings.ACTION_DEVICE_INFO_SETTINGS).putExtra(HIGHLIGHT_KEY, "build_number")
|
|
||||||
} else {
|
|
||||||
Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS).putExtra(HIGHLIGHT_KEY, "toggle_adb_wireless")
|
|
||||||
}.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
|
||||||
val display = settingsDisplay
|
|
||||||
runCatching {
|
|
||||||
if (display == null) startActivity(intent)
|
|
||||||
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle())
|
|
||||||
}.onFailure {
|
|
||||||
runCatching { startActivity(Intent(Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun returnToApp() {
|
|
||||||
startActivity(Intent(this, FrontEndActivity::class.java)
|
|
||||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
|
|
||||||
finish()
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun Guide() {
|
|
||||||
val stage by WirelessAdbPairingService.stage.collectAsState()
|
|
||||||
val settingsState by produceState(SettingsState.read(this)) {
|
|
||||||
while (true) {
|
|
||||||
value = SettingsState.read(this@PairingGuideActivity)
|
|
||||||
delay(500)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val step = stepFor(settingsState, stage)
|
|
||||||
var previous by remember { mutableStateOf(step) }
|
|
||||||
LaunchedEffect(step) {
|
|
||||||
if (previous == Step.BUILD_NUMBER && step == Step.WIRELESS_DEBUGGING) openSettings(step)
|
|
||||||
previous = step
|
|
||||||
when (step) {
|
|
||||||
Step.DONE -> { delay(1_500); returnToApp() }
|
|
||||||
Step.FAILED -> { delay(3_000); returnToApp() }
|
|
||||||
else -> Unit
|
|
||||||
}
|
|
||||||
}
|
|
||||||
LaunchedEffect(stage) { if (stage == Stage.Idle) finish() }
|
|
||||||
BackHandler(enabled = !inPip && settingsDisplay == null) { enterPip() }
|
|
||||||
|
|
||||||
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center) {
|
|
||||||
if (inPip) CompactStep(step, stage)
|
|
||||||
else FullGuide(step, stage)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun CompactStep(step: Step, stage: Stage) {
|
|
||||||
Column(Modifier.fillMaxSize().padding(10.dp), verticalArrangement = Arrangement.SpaceBetween) {
|
|
||||||
Text(
|
|
||||||
instruction(step, stage), style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold,
|
|
||||||
color = MaterialTheme.colorScheme.onBackground, maxLines = 3, overflow = TextOverflow.Ellipsis,
|
|
||||||
)
|
|
||||||
StepVisual(step, compact = true)
|
|
||||||
StepDots(step)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun FullGuide(step: Step, stage: Stage) {
|
|
||||||
Column(
|
|
||||||
Modifier.widthIn(max = 520.dp).fillMaxWidth().padding(24.dp),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
|
||||||
) {
|
|
||||||
Text(stringResource(R.string.gate_title), style = MaterialTheme.typography.headlineSmall,
|
|
||||||
fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground)
|
|
||||||
Text(instruction(step, stage), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onBackground)
|
|
||||||
StepVisual(step, compact = false)
|
|
||||||
StepDots(step)
|
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
|
||||||
if (step == Step.DONE || step == Step.FAILED) {
|
|
||||||
PrimaryButton(stringResource(R.string.common_back), onClick = ::returnToApp)
|
|
||||||
} else {
|
|
||||||
PrimaryButton(stringResource(R.string.gate_open_dev), onClick = {
|
|
||||||
if (settingsDisplay == null) enterPip()
|
|
||||||
openSettings(step)
|
|
||||||
})
|
|
||||||
SecondaryButton(stringResource(R.string.common_cancel), onClick = {
|
|
||||||
WirelessAdbPairingService.cancel(this@PairingGuideActivity)
|
|
||||||
returnToApp()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun instruction(step: Step, stage: Stage): String = when (step) {
|
|
||||||
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_build_number)
|
|
||||||
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_wireless)
|
|
||||||
Step.PAIR -> stringResource(R.string.pairguide_pair)
|
|
||||||
Step.CODE -> (stage as? Stage.CodeNeeded)?.error ?: stringResource(R.string.gate_step3)
|
|
||||||
Step.WORKING -> (stage as? Stage.Working)?.step ?: stringResource(R.string.adbpair_title_working)
|
|
||||||
Step.DONE -> stringResource(R.string.adbpair_title_done)
|
|
||||||
Step.FAILED -> (stage as? Stage.Failed)?.error ?: stringResource(R.string.adbpair_title_failed)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun StepVisual(step: Step, compact: Boolean) {
|
|
||||||
val colors = MaterialTheme.colorScheme
|
|
||||||
val accent = LocalPalette.current.signal
|
|
||||||
val pulse = rememberInfiniteTransition(label = "guidePulse")
|
|
||||||
val beat by pulse.animateFloat(0f, 1f, infiniteRepeatable(tween(900, easing = LinearEasing), RepeatMode.Restart), label = "beat")
|
|
||||||
val label = when (step) {
|
|
||||||
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_row_build_number)
|
|
||||||
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_row_wireless)
|
|
||||||
Step.PAIR -> stringResource(R.string.pairguide_row_pair)
|
|
||||||
Step.CODE -> stringResource(R.string.adbpair_enter_code)
|
|
||||||
Step.WORKING, Step.DONE, Step.FAILED -> return
|
|
||||||
}
|
|
||||||
val rowHeight = if (compact) 34.dp else 56.dp
|
|
||||||
Row(
|
|
||||||
Modifier.fillMaxWidth().height(rowHeight).background(colors.surfaceVariant, RoundedCornerShape(10.dp))
|
|
||||||
.border(1.dp, accent.copy(alpha = 0.35f), RoundedCornerShape(10.dp)).padding(horizontal = 10.dp),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
) {
|
|
||||||
Text(label, style = if (compact) MaterialTheme.typography.labelMedium else MaterialTheme.typography.bodyLarge,
|
|
||||||
color = colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
|
||||||
when (step) {
|
|
||||||
Step.WIRELESS_DEBUGGING -> Toggle(on = beat > 0.5f, accent = accent, compact = compact)
|
|
||||||
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
|
||||||
if (step == Step.BUILD_NUMBER) Text("×7", style = MaterialTheme.typography.labelLarge, color = accent)
|
|
||||||
Box(contentAlignment = Alignment.Center) {
|
|
||||||
Box(Modifier.size(if (compact) 18.dp else 26.dp).scale(0.6f + beat * 0.8f).alpha(1f - beat)
|
|
||||||
.background(accent, CircleShape))
|
|
||||||
Box(Modifier.size(if (compact) 8.dp else 12.dp).background(accent, CircleShape))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun Toggle(on: Boolean, accent: Color, compact: Boolean) {
|
|
||||||
val width = if (compact) 26.dp else 40.dp
|
|
||||||
val knob = if (compact) 12.dp else 18.dp
|
|
||||||
Box(
|
|
||||||
Modifier.width(width).height(knob + 4.dp)
|
|
||||||
.background(if (on) accent.copy(alpha = 0.6f) else MaterialTheme.colorScheme.outline, CircleShape).padding(2.dp),
|
|
||||||
contentAlignment = if (on) Alignment.CenterEnd else Alignment.CenterStart,
|
|
||||||
) { Box(Modifier.size(knob).background(Color.White, CircleShape)) }
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
private fun StepDots(step: Step) {
|
|
||||||
val accent = LocalPalette.current.signal
|
|
||||||
val shown = listOf(Step.BUILD_NUMBER, Step.WIRELESS_DEBUGGING, Step.PAIR, Step.CODE)
|
|
||||||
val at = shown.indexOf(step).takeIf { it >= 0 } ?: shown.size
|
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
|
|
||||||
shown.forEachIndexed { index, _ ->
|
|
||||||
Box(Modifier.size(if (index == at) 8.dp else 6.dp)
|
|
||||||
.background(if (index <= at) accent else MaterialTheme.colorScheme.outline, CircleShape))
|
|
||||||
}
|
|
||||||
Spacer(Modifier.width(2.dp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private data class SettingsState(val developerOptions: Boolean, val wirelessDebugging: Boolean) {
|
|
||||||
companion object {
|
|
||||||
fun read(context: Context) = SettingsState(
|
|
||||||
GlobalSettings.developerOptionsOn(context),
|
|
||||||
GlobalSettings.wirelessDebuggingOn(context),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val EXTRA_DISPLAY = "settingsDisplay"
|
|
||||||
private const val HIGHLIGHT_KEY = ":settings:fragment_args_key"
|
|
||||||
|
|
||||||
private fun stepFor(context: Context, stage: Stage) = stepFor(SettingsState.read(context), stage)
|
|
||||||
|
|
||||||
private fun stepFor(settings: SettingsState, stage: Stage): Step = when (stage) {
|
|
||||||
is Stage.Working -> Step.WORKING
|
|
||||||
Stage.Done -> Step.DONE
|
|
||||||
is Stage.Failed -> Step.FAILED
|
|
||||||
is Stage.CodeNeeded -> Step.CODE
|
|
||||||
else -> when {
|
|
||||||
!settings.developerOptions -> Step.BUILD_NUMBER
|
|
||||||
!settings.wirelessDebugging -> Step.WIRELESS_DEBUGGING
|
|
||||||
else -> Step.PAIR
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun canFloat(context: Context): Boolean {
|
|
||||||
if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) return false
|
|
||||||
val ops = context.getSystemService(AppOpsManager::class.java) ?: return true
|
|
||||||
val mode = if (Build.VERSION.SDK_INT >= 29) {
|
|
||||||
ops.unsafeCheckOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName)
|
|
||||||
} else {
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
ops.checkOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName)
|
|
||||||
}
|
|
||||||
return mode == AppOpsManager.MODE_ALLOWED
|
|
||||||
}
|
|
||||||
|
|
||||||
fun start(context: Context, settingsDisplay: Int?): Boolean {
|
|
||||||
if (settingsDisplay == null && !canFloat(context)) return false
|
|
||||||
context.startActivity(Intent(context, PairingGuideActivity::class.java)
|
|
||||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
|
||||||
.apply { if (settingsDisplay != null) putExtra(EXTRA_DISPLAY, settingsDisplay) })
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
package com.droiddeck.launcher
|
|
||||||
|
|
||||||
import android.content.Intent
|
|
||||||
import android.content.pm.LauncherApps
|
|
||||||
import android.graphics.Bitmap
|
|
||||||
import android.os.Bundle
|
|
||||||
import androidx.activity.ComponentActivity
|
|
||||||
import androidx.activity.compose.setContent
|
|
||||||
import androidx.core.graphics.drawable.toBitmap
|
|
||||||
import com.droiddeck.launcher.core.AppUiPrefs
|
|
||||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
|
||||||
import com.droiddeck.launcher.ui.PinRequestPrompt
|
|
||||||
|
|
||||||
class PinRequestActivity : ComponentActivity() {
|
|
||||||
override fun attachBaseContext(newBase: android.content.Context) {
|
|
||||||
super.attachBaseContext(newBase)
|
|
||||||
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
|
||||||
super.onCreate(savedInstanceState)
|
|
||||||
val request = runCatching { getSystemService(LauncherApps::class.java).getPinItemRequest(intent) }.getOrNull()
|
|
||||||
if (request == null || !request.isValid) {
|
|
||||||
finish()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val prompt = when (request.requestType) {
|
|
||||||
LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT -> request.shortcutInfo?.let { info ->
|
|
||||||
val appLabel = appLabel(info.`package`)
|
|
||||||
Triple(info.shortLabel?.toString().orEmpty().ifEmpty { appLabel }, appLabel, HomeApp.shortcutIcon(this, info))
|
|
||||||
}
|
|
||||||
LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET -> request.getAppWidgetProviderInfo(this)?.let { info ->
|
|
||||||
val appLabel = appLabel(info.provider.packageName)
|
|
||||||
val dpi = resources.displayMetrics.densityDpi
|
|
||||||
val icon = runCatching { (info.loadPreviewImage(this, dpi) ?: info.loadIcon(this, dpi))?.let(::scaled) }.getOrNull()
|
|
||||||
Triple(info.loadLabel(packageManager)?.toString().orEmpty().ifEmpty { appLabel }, appLabel, icon)
|
|
||||||
}
|
|
||||||
else -> null
|
|
||||||
}
|
|
||||||
if (prompt == null) {
|
|
||||||
finish()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val (label, appLabel, icon) = prompt
|
|
||||||
val widget = request.requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET
|
|
||||||
setContent {
|
|
||||||
DroidDeckTheme(appScale = AppUiPrefs.scale(this)) {
|
|
||||||
PinRequestPrompt(
|
|
||||||
label = label, appLabel = appLabel, icon = icon, wide = widget,
|
|
||||||
onAdd = {
|
|
||||||
if (!widget) {
|
|
||||||
HomePins.accept(this, request)
|
|
||||||
finish()
|
|
||||||
} else if (!HomeWidgets.addPinned(this, request)) finish()
|
|
||||||
},
|
|
||||||
onCancel = { finish() },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Suppress("OVERRIDE_DEPRECATION")
|
|
||||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
|
||||||
if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) {
|
|
||||||
finish()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
super.onActivityResult(requestCode, resultCode, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun appLabel(packageName: String): String =
|
|
||||||
runCatching { packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, 0)).toString() }
|
|
||||||
.getOrDefault(packageName)
|
|
||||||
|
|
||||||
private fun scaled(d: android.graphics.drawable.Drawable): Bitmap {
|
|
||||||
val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192
|
|
||||||
val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192
|
|
||||||
val k = minOf(1f, 480f / maxOf(w, h))
|
|
||||||
return d.toBitmap((w * k).toInt().coerceAtLeast(1), (h * k).toInt().coerceAtLeast(1))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
package com.droiddeck.launcher
|
package com.droiddeck.launcher
|
||||||
|
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.util.Log
|
|
||||||
import androidx.annotation.VisibleForTesting
|
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableIntStateOf
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
@@ -10,59 +8,31 @@ import androidx.compose.runtime.setValue
|
|||||||
import com.droiddeck.launcher.session.ProtonExtras
|
import com.droiddeck.launcher.session.ProtonExtras
|
||||||
import com.droiddeck.launcher.ui.ProtonRow
|
import com.droiddeck.launcher.ui.ProtonRow
|
||||||
import com.droiddeck.launcher.session.SessionState
|
import com.droiddeck.launcher.session.SessionState
|
||||||
import com.droiddeck.launcher.session.SessionPhase
|
|
||||||
import com.droiddeck.launcher.frontend.AutoComponents
|
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
|
||||||
|
|
||||||
internal class ProtonMenu(
|
internal class ProtonMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
|
||||||
private val activity: android.app.Activity,
|
var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
|
||||||
private val ui: Handler,
|
var protonBusyId by mutableStateOf<String?>(null)
|
||||||
private val idle: () -> Boolean = { true },
|
var protonStage by mutableStateOf<String?>(null)
|
||||||
) {
|
var protonPercent by mutableIntStateOf(-1)
|
||||||
// Install workers and their results outlive the activity that starts them.
|
|
||||||
private object Operation {
|
|
||||||
val rows = mutableStateOf<List<ProtonRow>>(emptyList())
|
|
||||||
val busyId = mutableStateOf<String?>(null)
|
|
||||||
val stage = mutableStateOf<String?>(null)
|
|
||||||
val percent = mutableIntStateOf(-1)
|
|
||||||
val problem = mutableStateOf<String?>(null)
|
|
||||||
}
|
|
||||||
var protonRows by Operation.rows
|
|
||||||
var protonBusyId by Operation.busyId
|
|
||||||
var protonStage by Operation.stage
|
|
||||||
var protonPercent by Operation.percent
|
|
||||||
var protonProblem by Operation.problem
|
|
||||||
private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
|
private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||||
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
|
|
||||||
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
|
|
||||||
|
|
||||||
fun installProton(id: String, automatic: Boolean = false) {
|
fun installProton(id: String) {
|
||||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||||
if (protonBusyId != null || ProtonExtras.installInProgress || SessionState.running) return
|
if (protonBusyId != null || SessionState.running) return
|
||||||
ProtonExtras.unqueue(activity, tool)
|
ProtonExtras.unqueue(activity, tool)
|
||||||
protonBusyId = id
|
protonBusyId = id
|
||||||
protonProblem = null
|
|
||||||
protonStage = activity.getString(R.string.store_starting)
|
protonStage = activity.getString(R.string.store_starting)
|
||||||
protonPercent = -1
|
protonPercent = -1
|
||||||
Thread({
|
Thread({
|
||||||
val problem = runCatching {
|
val problem = ProtonExtras.install(activity, tool) { label, value ->
|
||||||
installer(tool) { label, value ->
|
ui.post { protonStage = label; protonPercent = value }
|
||||||
ui.post { protonStage = label; protonPercent = value }
|
}
|
||||||
}
|
|
||||||
}.getOrElse { it.message ?: it.javaClass.simpleName }
|
|
||||||
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
|
|
||||||
ui.post {
|
ui.post {
|
||||||
protonProblem = problem
|
|
||||||
protonBusyId = null
|
protonBusyId = null
|
||||||
protonStage = null
|
protonStage = null
|
||||||
protonPercent = -1
|
protonPercent = -1
|
||||||
refreshProtons()
|
refreshProtons()
|
||||||
if (problem != null) {
|
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
|
||||||
if (automatic) Log.w("ProtonMenu", "auto-update ${tool.id}: $problem")
|
|
||||||
else android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
|
|
||||||
}
|
|
||||||
if (automatic) ensureAutoUpdates()
|
|
||||||
}
|
}
|
||||||
}, "install-proton-$id").start()
|
}, "install-proton-$id").start()
|
||||||
}
|
}
|
||||||
@@ -71,12 +41,10 @@ internal class ProtonMenu(
|
|||||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||||
if (protonBusyId != null || SessionState.running) return
|
if (protonBusyId != null || SessionState.running) return
|
||||||
protonBusyId = id
|
protonBusyId = id
|
||||||
protonProblem = null
|
|
||||||
protonStage = activity.getString(R.string.main_removing_named, dir ?: tool.name)
|
protonStage = activity.getString(R.string.main_removing_named, dir ?: tool.name)
|
||||||
protonPercent = -1
|
protonPercent = -1
|
||||||
Thread({
|
Thread({
|
||||||
if (older) ProtonExtras.removeOlder(activity, tool) else ProtonExtras.remove(activity, tool, dir)
|
if (older) ProtonExtras.removeOlder(activity, tool) else ProtonExtras.remove(activity, tool, dir)
|
||||||
if (tool.id == ProtonExtras.OWN && ProtonExtras.installedAll(activity, tool).isEmpty()) ProtonExtras.setDeclined(activity, true)
|
|
||||||
ui.post {
|
ui.post {
|
||||||
protonBusyId = null
|
protonBusyId = null
|
||||||
protonStage = null
|
protonStage = null
|
||||||
@@ -96,39 +64,7 @@ internal class ProtonMenu(
|
|||||||
if (!checking.compareAndSet(false, true)) return
|
if (!checking.compareAndSet(false, true)) return
|
||||||
Thread({
|
Thread({
|
||||||
val asked = try { ProtonExtras.checkLatest(activity, force) } catch (_: Throwable) { false } finally { checking.set(false) }
|
val asked = try { ProtonExtras.checkLatest(activity, force) } catch (_: Throwable) { false } finally { checking.set(false) }
|
||||||
ui.post {
|
if (asked) ui.post { refreshProtons() }
|
||||||
if (asked) refreshProtons()
|
|
||||||
ensureAutoUpdates()
|
|
||||||
}
|
|
||||||
}, "proton-updates").start()
|
}, "proton-updates").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) {
|
|
||||||
if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null ||
|
|
||||||
ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
|
|
||||||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
|
|
||||||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
|
|
||||||
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
|
|
||||||
protonBusyId = ProtonExtras.OWN
|
|
||||||
protonProblem = null
|
|
||||||
Thread({
|
|
||||||
ProtonExtras.tidy(activity)
|
|
||||||
val tidied = ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size <= 1
|
|
||||||
ui.post {
|
|
||||||
protonBusyId = null
|
|
||||||
refreshProtons()
|
|
||||||
if (tidied) ensureAutoUpdates()
|
|
||||||
}
|
|
||||||
}, "proton-tidy").start()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val attempts = activity.getSharedPreferences("proton-auto-updates", android.content.Context.MODE_PRIVATE)
|
|
||||||
val (tool, update) = ProtonExtras.tools.firstNotNullOfOrNull { tool ->
|
|
||||||
val update = ProtonExtras.update(activity, tool) ?: ProtonExtras.missing(activity, tool) ?: return@firstNotNullOfOrNull null
|
|
||||||
val previous = attempts.getLong("${tool.id}.at", 0L)
|
|
||||||
if (attempts.getString("${tool.id}.tag", null) != update || now - previous !in 0 until 15L * 60 * 1000) tool to update else null
|
|
||||||
} ?: return
|
|
||||||
attempts.edit().putString("${tool.id}.tag", update).putLong("${tool.id}.at", now).apply()
|
|
||||||
installProton(tool.id, automatic = true)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -29,7 +29,6 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
|||||||
private var pending: AppUpdates.Release? = null
|
private var pending: AppUpdates.Release? = null
|
||||||
private var lastCheck = 0L
|
private var lastCheck = 0L
|
||||||
private var request = 0
|
private var request = 0
|
||||||
@Volatile private var session = -1
|
|
||||||
|
|
||||||
fun state() = UpdatesState(catalog, follow, checking, error, stage, percent, askPermission)
|
fun state() = UpdatesState(catalog, follow, checking, error, stage, percent, askPermission)
|
||||||
|
|
||||||
@@ -88,14 +87,13 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
|||||||
if (SessionState.running) { error = activity.getString(R.string.upd_stop_first); return }
|
if (SessionState.running) { error = activity.getString(R.string.upd_stop_first); return }
|
||||||
if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return }
|
if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return }
|
||||||
error = null
|
error = null
|
||||||
session = -1
|
|
||||||
stage = activity.getString(R.string.upd_stage_downloading)
|
stage = activity.getString(R.string.upd_stage_downloading)
|
||||||
percent = 0
|
percent = 0
|
||||||
Thread({
|
Thread({
|
||||||
val result = runCatching {
|
val result = runCatching {
|
||||||
val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
|
val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
|
||||||
ui.post { stage = activity.getString(R.string.upd_stage_installing); percent = -1 }
|
ui.post { stage = activity.getString(R.string.upd_stage_installing); percent = -1 }
|
||||||
SelfInstaller.install(activity, file) { id -> session = id }
|
SelfInstaller.install(activity, file)
|
||||||
}
|
}
|
||||||
result.onFailure { e -> ui.post { stage = null; error = e.message ?: activity.getString(R.string.upd_failed) } }
|
result.onFailure { e -> ui.post { stage = null; error = e.message ?: activity.getString(R.string.upd_failed) } }
|
||||||
}, "app-update-install").start()
|
}, "app-update-install").start()
|
||||||
@@ -103,15 +101,13 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
|||||||
|
|
||||||
private val receiver = object : BroadcastReceiver() {
|
private val receiver = object : BroadcastReceiver() {
|
||||||
override fun onReceive(context: Context, intent: Intent) {
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
if (intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1).let { it < 0 || it != session }) return
|
|
||||||
when (val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) {
|
when (val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) {
|
||||||
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
|
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
|
||||||
val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
|
val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
|
||||||
else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
|
else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
|
||||||
val safe = confirm?.let { SelfInstaller.safeConfirmIntent(activity, it) }
|
if (confirm == null) { stage = null; error = activity.getString(R.string.upd_not_offered); return }
|
||||||
if (safe == null) { stage = null; error = activity.getString(R.string.upd_not_offered); return }
|
|
||||||
stage = activity.getString(R.string.upd_stage_confirm)
|
stage = activity.getString(R.string.upd_stage_confirm)
|
||||||
if (runCatching { activity.startActivity(safe) }.isFailure) { stage = null; error = activity.getString(R.string.upd_not_offered) }
|
activity.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||||
}
|
}
|
||||||
PackageInstaller.STATUS_SUCCESS -> stage = null
|
PackageInstaller.STATUS_SUCCESS -> stage = null
|
||||||
else -> {
|
else -> {
|
||||||
|
|||||||
@@ -3,13 +3,9 @@ package com.droiddeck.launcher.agent
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
|
||||||
import com.droiddeck.launcher.session.SessionPhase
|
|
||||||
import com.droiddeck.launcher.session.SessionState
|
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.security.MessageDigest
|
|
||||||
import java.nio.file.Files
|
import java.nio.file.Files
|
||||||
import java.nio.file.LinkOption.NOFOLLOW_LINKS
|
import java.nio.file.LinkOption.NOFOLLOW_LINKS
|
||||||
import java.nio.file.StandardOpenOption.READ
|
import java.nio.file.StandardOpenOption.READ
|
||||||
@@ -59,9 +55,6 @@ object AgentEnv {
|
|||||||
fun override(context: Context, name: String): JSONObject = synchronized(lock) {
|
fun override(context: Context, name: String): JSONObject = synchronized(lock) {
|
||||||
AgentAccess.requireCommands(context)
|
AgentAccess.requireCommands(context)
|
||||||
if (NAME.matchEntire(name) == null || name in setOf(".", "..")) throw AgentException("INVALID_NAME", "Override names are letters, digits, '.', '_' and '-'")
|
if (NAME.matchEntire(name) == null || name in setOf(".", "..")) throw AgentException("INVALID_NAME", "Override names are letters, digits, '.', '_' and '-'")
|
||||||
if (name == "libblfastpath.so" && (SessionState.running || SessionState.guestPid > 0 || SessionState.phase == SessionPhase.STOPPING)) {
|
|
||||||
throw AgentException("SESSION_ACTIVE", "Stop the session before installing a fast-path library")
|
|
||||||
}
|
|
||||||
val source = File(inbox(context), name)
|
val source = File(inbox(context), name)
|
||||||
if (Files.isSymbolicLink(source.toPath())) throw AgentException("INVALID_NAME", "The override must be a regular file")
|
if (Files.isSymbolicLink(source.toPath())) throw AgentException("INVALID_NAME", "The override must be a regular file")
|
||||||
if (!source.isFile) throw AgentException("NO_SUCH_FILE", "Push the binary to ${source.path} first")
|
if (!source.isFile) throw AgentException("NO_SUCH_FILE", "Push the binary to ${source.path} first")
|
||||||
@@ -74,10 +67,6 @@ object AgentEnv {
|
|||||||
staged.delete()
|
staged.delete()
|
||||||
throw AgentException("OVERRIDE_FAILED", "Could not stage the override")
|
throw AgentException("OVERRIDE_FAILED", "Could not stage the override")
|
||||||
}
|
}
|
||||||
if (name == "libblfastpath.so" && !arm64SharedLibrary(staged)) {
|
|
||||||
staged.delete()
|
|
||||||
throw AgentException("INVALID_LIBRARY", "The fast path must be a 64-bit little-endian ARM64 ELF shared library")
|
|
||||||
}
|
|
||||||
if (!staged.setExecutable(true, false) || !staged.renameTo(target)) {
|
if (!staged.setExecutable(true, false) || !staged.renameTo(target)) {
|
||||||
staged.delete()
|
staged.delete()
|
||||||
throw AgentException("OVERRIDE_FAILED", "Could not install $name in the rootfs")
|
throw AgentException("OVERRIDE_FAILED", "Could not install $name in the rootfs")
|
||||||
@@ -87,40 +76,6 @@ object AgentEnv {
|
|||||||
state.put("pendingOverrides", JSONArray(merge(strings(state.optJSONArray("pendingOverrides")), listOf(name))))
|
state.put("pendingOverrides", JSONArray(merge(strings(state.optJSONArray("pendingOverrides")), listOf(name))))
|
||||||
save(context, state)
|
save(context, state)
|
||||||
state.put("installed", "$GUEST_BIN/$name")
|
state.put("installed", "$GUEST_BIN/$name")
|
||||||
if (name == "libblfastpath.so") {
|
|
||||||
val digest = MessageDigest.getInstance("SHA-256")
|
|
||||||
target.inputStream().use { input ->
|
|
||||||
val buffer = ByteArray(65536)
|
|
||||||
while (true) {
|
|
||||||
val count = input.read(buffer)
|
|
||||||
if (count < 0) break
|
|
||||||
digest.update(buffer, 0, count)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
state.put("sha256", digest.digest().joinToString("") { "%02x".format(it) })
|
|
||||||
}
|
|
||||||
state
|
|
||||||
}
|
|
||||||
|
|
||||||
fun fastPathLibrary(context: Context): String = synchronized(lock) {
|
|
||||||
if (!AgentAccess.commandsAllowed(context)) return@synchronized ProotFastPath.LIBRARY
|
|
||||||
if ("libblfastpath.so" !in strings(load(context).optJSONArray("activeOverrides"))) return@synchronized ProotFastPath.LIBRARY
|
|
||||||
val file = File(bin(context), "libblfastpath.so")
|
|
||||||
if (!file.isFile || Files.isSymbolicLink(file.toPath())) return@synchronized ProotFastPath.LIBRARY
|
|
||||||
"$GUEST_BIN/libblfastpath.so"
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun arm64SharedLibrary(file: File): Boolean = file.inputStream().use { input ->
|
|
||||||
val header = ByteArray(20)
|
|
||||||
var count = 0
|
|
||||||
while (count < header.size) {
|
|
||||||
val read = input.read(header, count, header.size - count)
|
|
||||||
if (read < 0) return@use false
|
|
||||||
count += read
|
|
||||||
}
|
|
||||||
header.take(7) == listOf<Byte>(0x7f, 0x45, 0x4c, 0x46, 2, 1, 1) &&
|
|
||||||
header[16] == 3.toByte() && header[17] == 0.toByte() &&
|
|
||||||
header[18] == 183.toByte() && header[19] == 0.toByte()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun beginSession(context: Context): List<String> = synchronized(lock) {
|
fun beginSession(context: Context): List<String> = synchronized(lock) {
|
||||||
@@ -131,13 +86,13 @@ object AgentEnv {
|
|||||||
val state = load(context)
|
val state = load(context)
|
||||||
val active = strings(state.optJSONArray("pending"))
|
val active = strings(state.optJSONArray("pending"))
|
||||||
val overrides = strings(state.optJSONArray("pendingOverrides"))
|
val overrides = strings(state.optJSONArray("pendingOverrides"))
|
||||||
bin(context).listFiles()
|
|
||||||
?.filter { it.name !in overrides }?.forEach { it.delete() }
|
|
||||||
val lines = strings(state.optJSONArray("persistent")) + active
|
|
||||||
val withPath = if (overrides.none { it != "libblfastpath.so" }) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}"
|
|
||||||
state.put("active", JSONArray(active)).put("pending", JSONArray())
|
state.put("active", JSONArray(active)).put("pending", JSONArray())
|
||||||
state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray())
|
state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray())
|
||||||
save(context, state)
|
save(context, state)
|
||||||
|
bin(context).listFiles()
|
||||||
|
?.filter { it.name !in overrides }?.forEach { it.delete() }
|
||||||
|
val lines = strings(state.optJSONArray("persistent")) + active
|
||||||
|
val withPath = if (overrides.isEmpty()) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}"
|
||||||
if (withPath.isNotEmpty()) Log.i(TAG, "agent environment keys for this session: ${withPath.map { it.substringBefore('=') }}")
|
if (withPath.isNotEmpty()) Log.i(TAG, "agent environment keys for this session: ${withPath.map { it.substringBefore('=') }}")
|
||||||
withPath
|
withPath
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.audio;
|
|||||||
import android.os.Process;
|
import android.os.Process;
|
||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
import com.droiddeck.launcher.core.FileUtils;
|
|
||||||
import com.droiddeck.launcher.core.SessionPart;
|
import com.droiddeck.launcher.core.SessionPart;
|
||||||
import com.droiddeck.launcher.core.HostProcess;
|
import com.droiddeck.launcher.core.HostProcess;
|
||||||
|
|
||||||
@@ -18,15 +17,10 @@ public class DirectAudioRelayComponent extends SessionPart {
|
|||||||
private File logFile;
|
private File logFile;
|
||||||
private final File micFifoPath;
|
private final File micFifoPath;
|
||||||
private volatile int pid = -1;
|
private volatile int pid = -1;
|
||||||
private final Object micLock = new Object();
|
|
||||||
private boolean micHot;
|
|
||||||
private final File micControl;
|
|
||||||
public java.util.function.Consumer<Boolean> onMicEnabled;
|
|
||||||
|
|
||||||
public DirectAudioRelayComponent(File socketPath, File micFifoPath) {
|
public DirectAudioRelayComponent(File socketPath, File micFifoPath) {
|
||||||
this.socketPath = socketPath;
|
this.socketPath = socketPath;
|
||||||
this.micFifoPath = micFifoPath;
|
this.micFifoPath = micFifoPath;
|
||||||
this.micControl = micFifoPath == null ? null : new File(micFifoPath.getParentFile(), "mic-enabled");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setLogFile(File file) {
|
public void setLogFile(File file) {
|
||||||
@@ -36,9 +30,6 @@ public class DirectAudioRelayComponent extends SessionPart {
|
|||||||
@Override
|
@Override
|
||||||
public void start() {
|
public void start() {
|
||||||
stop();
|
stop();
|
||||||
synchronized (micLock) {
|
|
||||||
micHot = false;
|
|
||||||
}
|
|
||||||
File binary = new File(app().getApplicationInfo().nativeLibraryDir, BINARY);
|
File binary = new File(app().getApplicationInfo().nativeLibraryDir, BINARY);
|
||||||
if (!binary.isFile()) {
|
if (!binary.isFile()) {
|
||||||
Log.w(TAG, "helper missing at " + binary + "; DirectAudio will report itself unavailable");
|
Log.w(TAG, "helper missing at " + binary + "; DirectAudio will report itself unavailable");
|
||||||
@@ -67,13 +58,8 @@ public class DirectAudioRelayComponent extends SessionPart {
|
|||||||
StringBuilder command = new StringBuilder(binary.getAbsolutePath());
|
StringBuilder command = new StringBuilder(binary.getAbsolutePath());
|
||||||
command.append(" --socket ").append(socketPath.getAbsolutePath());
|
command.append(" --socket ").append(socketPath.getAbsolutePath());
|
||||||
command.append(" --log");
|
command.append(" --log");
|
||||||
final boolean withMic = micFifoPath != null && setMicEnabled(true);
|
if (micFifoPath != null) {
|
||||||
if (withMic) {
|
|
||||||
command.append(" --mic-fifo ").append(micFifoPath.getAbsolutePath());
|
command.append(" --mic-fifo ").append(micFifoPath.getAbsolutePath());
|
||||||
command.append(" --mic-control ").append(micControl.getAbsolutePath());
|
|
||||||
} else if (micFifoPath != null) {
|
|
||||||
Log.w(TAG, "microphone control unavailable; starting with capture disabled");
|
|
||||||
command.append(" --mic-control /dev/null");
|
|
||||||
}
|
}
|
||||||
ArrayList<String> env = new ArrayList<>();
|
ArrayList<String> env = new ArrayList<>();
|
||||||
env.add("HOME=" + app().getFilesDir());
|
env.add("HOME=" + app().getFilesDir());
|
||||||
@@ -82,7 +68,7 @@ public class DirectAudioRelayComponent extends SessionPart {
|
|||||||
try {
|
try {
|
||||||
out = new java.io.PrintWriter(new java.io.FileWriter(logFile, true));
|
out = new java.io.PrintWriter(new java.io.FileWriter(logFile, true));
|
||||||
out.println("== DirectAudio relay helper starting"
|
out.println("== DirectAudio relay helper starting"
|
||||||
+ (withMic ? " with the microphone" : " (no microphone)"));
|
+ (micFifoPath != null ? " with the microphone" : " (no microphone)"));
|
||||||
out.flush();
|
out.flush();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
Log.w(TAG, "could not open " + logFile, e);
|
Log.w(TAG, "could not open " + logFile, e);
|
||||||
@@ -93,47 +79,10 @@ public class DirectAudioRelayComponent extends SessionPart {
|
|||||||
app().getFilesDir(), null,
|
app().getFilesDir(), null,
|
||||||
line -> {
|
line -> {
|
||||||
Log.i(TAG, line);
|
Log.i(TAG, line);
|
||||||
if (withMic) trackMic(line);
|
|
||||||
if (log != null) synchronized (log) { log.println(line); log.flush(); }
|
if (log != null) synchronized (log) { log.println(line); log.flush(); }
|
||||||
});
|
});
|
||||||
Log.i(TAG, "started pid=" + pid + " socket=" + socketPath
|
Log.i(TAG, "started pid=" + pid + " socket=" + socketPath
|
||||||
+ (withMic ? " mic=" + micFifoPath : " (no microphone)"));
|
+ (micFifoPath != null ? " mic=" + micFifoPath : " (no microphone)"));
|
||||||
}
|
|
||||||
|
|
||||||
public synchronized boolean setMicEnabled(boolean enabled) {
|
|
||||||
if (micControl == null) return false;
|
|
||||||
File next = new File(micControl.getPath() + ".new");
|
|
||||||
return FileUtils.writeString(next, enabled ? "1" : "0") && next.renameTo(micControl);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void trackMic(String line) {
|
|
||||||
if (line.startsWith("DA-Relay: mic enabled=") && onMicEnabled != null) {
|
|
||||||
onMicEnabled.accept(line.equals("DA-Relay: mic enabled=1"));
|
|
||||||
}
|
|
||||||
boolean start = line.startsWith("DA-Relay: mic start ");
|
|
||||||
if (!start && !line.startsWith("DA-Relay: mic stop ")) return;
|
|
||||||
synchronized (micLock) {
|
|
||||||
micHot = start;
|
|
||||||
micLock.notifyAll();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Android keeps the input stream's wake lock while a frozen helper still has it started.
|
|
||||||
public boolean awaitMicReleased(long timeoutMs) {
|
|
||||||
long deadline = System.currentTimeMillis() + timeoutMs;
|
|
||||||
synchronized (micLock) {
|
|
||||||
while (micHot) {
|
|
||||||
long left = deadline - System.currentTimeMillis();
|
|
||||||
if (left <= 0) return false;
|
|
||||||
try {
|
|
||||||
micLock.wait(left);
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -20,13 +20,11 @@ import java.util.concurrent.TimeUnit;
|
|||||||
public class PulseAudioComponent extends SessionPart {
|
public class PulseAudioComponent extends SessionPart {
|
||||||
private static final String TAG = "PulseAudio";
|
private static final String TAG = "PulseAudio";
|
||||||
public static final String SOCKET_NAME = "PS0";
|
public static final String SOCKET_NAME = "PS0";
|
||||||
private static final String MIC_SOURCE = "DirectAudioMic";
|
|
||||||
private static final String BUNDLE_STAMP = "2026-10-08-pa13-directaudio-native";
|
private static final String BUNDLE_STAMP = "2026-10-08-pa13-directaudio-native";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
private final File workingDir;
|
private final File workingDir;
|
||||||
private final File deviceControls;
|
|
||||||
private File logFile;
|
private File logFile;
|
||||||
private final String micFifoPath;
|
private final String micFifoPath;
|
||||||
private volatile int pid = -1;
|
private volatile int pid = -1;
|
||||||
@@ -37,8 +35,6 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
|
|
||||||
public PulseAudioComponent(Context context, String micFifoPath) {
|
public PulseAudioComponent(Context context, String micFifoPath) {
|
||||||
this.workingDir = new File(context.getFilesDir(), "pulseaudio");
|
this.workingDir = new File(context.getFilesDir(), "pulseaudio");
|
||||||
this.deviceControls = com.droiddeck.launcher.runtime.DeviceControlsComponent.directory(
|
|
||||||
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context));
|
|
||||||
this.micFifoPath = micFifoPath;
|
this.micFifoPath = micFifoPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,13 +93,13 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
config.add("load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0 socket=\""
|
config.add("load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0 socket=\""
|
||||||
+ socket().getAbsolutePath() + "\"");
|
+ socket().getAbsolutePath() + "\"");
|
||||||
config.add(".nofail");
|
config.add(".nofail");
|
||||||
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls);
|
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0");
|
||||||
config.add("set-default-sink DirectAudio");
|
config.add("set-default-sink DirectAudio");
|
||||||
config.add(".fail");
|
config.add(".fail");
|
||||||
if (micFifoPath != null && !micFifoPath.isEmpty()) {
|
if (micFifoPath != null && !micFifoPath.isEmpty()) {
|
||||||
config.add("load-module module-pipe-source source_name=" + MIC_SOURCE + " file=\""
|
config.add("load-module module-pipe-source source_name=DirectAudioMic file=\""
|
||||||
+ micFifoPath + "\" format=s16le rate=48000 channels=1");
|
+ micFifoPath + "\" format=s16le rate=48000 channels=1");
|
||||||
config.add("set-default-source " + MIC_SOURCE);
|
config.add("set-default-source DirectAudioMic");
|
||||||
}
|
}
|
||||||
FileUtils.writeString(new File(workingDir, "default.pa"), String.join("\n", config));
|
FileUtils.writeString(new File(workingDir, "default.pa"), String.join("\n", config));
|
||||||
|
|
||||||
@@ -142,7 +138,7 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
|
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
|
||||||
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
|
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
|
||||||
} else {
|
} else {
|
||||||
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
|
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null
|
||||||
&& pactl("set-default-sink", "AAudioSink") != null;
|
&& pactl("set-default-sink", "AAudioSink") != null;
|
||||||
line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
|
line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
|
||||||
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
|
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
|
||||||
@@ -206,24 +202,16 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean setSinkSuspended(boolean suspended) {
|
public boolean setSinkSuspended(boolean suspended) {
|
||||||
return suspend("sink", "@DEFAULT_SINK@", suspended);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean setMicSuspended(boolean suspended) {
|
|
||||||
return micFifoPath == null || micFifoPath.isEmpty() || suspend("source", MIC_SOURCE, suspended);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean suspend(String kind, String name, boolean suspended) {
|
|
||||||
File pactl = new File(workingDir, "pactl");
|
File pactl = new File(workingDir, "pactl");
|
||||||
if (!pactl.isFile() || pid <= 1) {
|
if (!pactl.isFile() || pid <= 1) {
|
||||||
Log.w(TAG, "cannot change " + kind + " state: PulseAudio control client or server unavailable");
|
Log.w(TAG, "cannot change sink state: PulseAudio control client or server unavailable");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
java.lang.Process process = null;
|
java.lang.Process process = null;
|
||||||
try {
|
try {
|
||||||
File modules = new File(workingDir, "modules/arm64");
|
File modules = new File(workingDir, "modules/arm64");
|
||||||
ProcessBuilder builder = new ProcessBuilder(
|
ProcessBuilder builder = new ProcessBuilder(
|
||||||
pactl.getAbsolutePath(), "suspend-" + kind, name, Boolean.toString(suspended));
|
pactl.getAbsolutePath(), "suspend-sink", "@DEFAULT_SINK@", Boolean.toString(suspended));
|
||||||
builder.directory(workingDir);
|
builder.directory(workingDir);
|
||||||
builder.redirectErrorStream(true);
|
builder.redirectErrorStream(true);
|
||||||
builder.redirectOutput(new File("/dev/null"));
|
builder.redirectOutput(new File("/dev/null"));
|
||||||
@@ -234,18 +222,18 @@ public class PulseAudioComponent extends SessionPart {
|
|||||||
process = builder.start();
|
process = builder.start();
|
||||||
if (!process.waitFor(5, TimeUnit.SECONDS)) {
|
if (!process.waitFor(5, TimeUnit.SECONDS)) {
|
||||||
process.destroyForcibly();
|
process.destroyForcibly();
|
||||||
Log.w(TAG, "timed out changing " + kind + " state to suspended=" + suspended);
|
Log.w(TAG, "timed out changing sink state to suspended=" + suspended);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
int status = process.exitValue();
|
int status = process.exitValue();
|
||||||
if (status != 0) Log.w(TAG, kind + " state change failed with exit " + status);
|
if (status != 0) Log.w(TAG, "sink state change failed with exit " + status);
|
||||||
return status == 0;
|
return status == 0;
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
Log.w(TAG, "interrupted changing " + kind + " state", e);
|
Log.w(TAG, "interrupted changing sink state", e);
|
||||||
return false;
|
return false;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
Log.w(TAG, "could not change " + kind + " state", e);
|
Log.w(TAG, "could not change sink state", e);
|
||||||
return false;
|
return false;
|
||||||
} finally {
|
} finally {
|
||||||
if (process != null && process.isAlive()) process.destroyForcibly();
|
if (process != null && process.isAlive()) process.destroyForcibly();
|
||||||
|
|||||||
@@ -19,10 +19,7 @@ import java.io.FileInputStream
|
|||||||
* yet to its pr-N release on DroidDeck-CI. The APK pins the pack's SHA-256, so only the bytes this build
|
* yet to its pr-N release on DroidDeck-CI. The APK pins the pack's SHA-256, so only the bytes this build
|
||||||
* was made with install, whichever host serves them.
|
* was made with install, whichever host serves them.
|
||||||
*/
|
*/
|
||||||
internal class AddonPack(
|
internal class AddonPack(val name: String, private val sha256: String, val size: Long, private val required: List<String>) {
|
||||||
val name: String, private val sha256: String, val size: Long, private val required: List<String>,
|
|
||||||
private val reuseDeviceCopy: Boolean = sha256.isEmpty() && !BuildConfig.CI_BUILD,
|
|
||||||
) {
|
|
||||||
sealed interface State {
|
sealed interface State {
|
||||||
data object Missing : State
|
data object Missing : State
|
||||||
data class Downloading(val progress: Float) : State
|
data class Downloading(val progress: Float) : State
|
||||||
@@ -43,20 +40,10 @@ internal class AddonPack(
|
|||||||
|
|
||||||
private fun root(context: Context) = File(context.filesDir, "addons/$name")
|
private fun root(context: Context) = File(context.filesDir, "addons/$name")
|
||||||
/** App-private and written only after the archive matched the pinned digest. */
|
/** App-private and written only after the archive matched the pinned digest. */
|
||||||
fun dir(context: Context) = File(root(context), version(context))
|
fun dir(context: Context) = File(root(context), sha256)
|
||||||
fun file(context: Context, relative: String) = File(dir(context), relative)
|
fun file(context: Context, relative: String) = File(dir(context), relative)
|
||||||
|
|
||||||
fun installed(context: Context): Boolean = version(context).isNotEmpty() && File(dir(context), COMPLETE).isFile
|
fun installed(context: Context): Boolean = available && File(dir(context), COMPLETE).isFile
|
||||||
|
|
||||||
// A build made outside CI pins no packs, so it runs the newest one a CI build already verified and installed.
|
|
||||||
private fun version(context: Context): String = if (!reuseDeviceCopy) sha256 else deviceCopy(context).orEmpty()
|
|
||||||
|
|
||||||
private fun deviceCopy(context: Context): String? = root(context).listFiles().orEmpty()
|
|
||||||
.filter { dir ->
|
|
||||||
dir.isDirectory && runCatching { File(dir, COMPLETE).readText().trim() }.getOrNull() == dir.name &&
|
|
||||||
required.all { File(dir, it).isFile }
|
|
||||||
}
|
|
||||||
.maxByOrNull { it.lastModified() }?.name
|
|
||||||
|
|
||||||
fun refresh(context: Context): State {
|
fun refresh(context: Context): State {
|
||||||
val now = mutableState.value
|
val now = mutableState.value
|
||||||
@@ -99,7 +86,7 @@ internal class AddonPack(
|
|||||||
|
|
||||||
private fun install(context: Context): Boolean {
|
private fun install(context: Context): Boolean {
|
||||||
if (!available) {
|
if (!available) {
|
||||||
Log.w(TAG, if (reuseDeviceCopy) "$name: this build has no pack and none is installed" else "$name: this build has no pack")
|
Log.w(TAG, "$name: this build has no pack")
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
val root = root(context).apply { mkdirs() }
|
val root = root(context).apply { mkdirs() }
|
||||||
|
|||||||
@@ -1,32 +1,11 @@
|
|||||||
package com.droiddeck.launcher.core
|
package com.droiddeck.launcher.core
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.pm.ActivityInfo
|
|
||||||
import com.droiddeck.launcher.R
|
|
||||||
|
|
||||||
object AppUiPrefs {
|
object AppUiPrefs {
|
||||||
const val DEFAULT_SCALE = 100
|
const val DEFAULT_SCALE = 100
|
||||||
val scales = listOf(75, 85, 100, 115, 125, 150)
|
val scales = listOf(75, 85, 100, 115, 125, 150)
|
||||||
|
|
||||||
val orientationOptions = listOf(
|
|
||||||
ActivityInfo.SCREEN_ORIENTATION_USER to R.string.setup_launcher_orientation_auto,
|
|
||||||
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT to R.string.setup_orientation_portrait,
|
|
||||||
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE to R.string.setup_orientation_auto,
|
|
||||||
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE to R.string.setup_orientation_landscape,
|
|
||||||
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE to R.string.setup_orientation_reverse,
|
|
||||||
)
|
|
||||||
|
|
||||||
fun orientation(context: Context): Int =
|
|
||||||
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE)
|
|
||||||
.getInt("orientation", ActivityInfo.SCREEN_ORIENTATION_USER)
|
|
||||||
.takeIf { value -> orientationOptions.any { it.first == value } }
|
|
||||||
?: ActivityInfo.SCREEN_ORIENTATION_USER
|
|
||||||
|
|
||||||
fun setOrientation(context: Context, value: Int) {
|
|
||||||
require(orientationOptions.any { it.first == value })
|
|
||||||
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", value).apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
|
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
|
||||||
|
|
||||||
fun scale(context: Context): Int = normalizeScale(
|
fun scale(context: Context): Int = normalizeScale(
|
||||||
|
|||||||
@@ -1,59 +0,0 @@
|
|||||||
package com.droiddeck.launcher.core
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.util.Log
|
|
||||||
import java.util.concurrent.Executors
|
|
||||||
|
|
||||||
object BackgroundAppLimit {
|
|
||||||
private const val TAG = "BackgroundAppLimit"
|
|
||||||
const val OFF = -1
|
|
||||||
val CHOICES = listOf(OFF, 4, 1, 0)
|
|
||||||
private const val KEY = "max_cached_processes"
|
|
||||||
private const val STATE = "background-app-limit"
|
|
||||||
private const val APPLIED = "applied"
|
|
||||||
private const val PREVIOUS = "previous"
|
|
||||||
|
|
||||||
private val worker = Executors.newSingleThreadExecutor { Thread(it, "background-app-limit").apply { isDaemon = true } }
|
|
||||||
|
|
||||||
internal fun readCommand() = "device_config get activity_manager $KEY"
|
|
||||||
internal fun setCommand(limit: Int): String {
|
|
||||||
require(limit in 0..1024)
|
|
||||||
return "device_config put activity_manager $KEY $limit"
|
|
||||||
}
|
|
||||||
internal fun restoreCommand(previous: String?) =
|
|
||||||
if (previous == null) "device_config delete activity_manager $KEY" else "device_config put activity_manager $KEY $previous"
|
|
||||||
|
|
||||||
internal fun parse(output: String): String? = output.trim().takeIf { it.toIntOrNull() != null }
|
|
||||||
|
|
||||||
private fun state(context: Context) = context.applicationContext.getSharedPreferences(STATE, Context.MODE_PRIVATE)
|
|
||||||
|
|
||||||
fun applied(context: Context): Boolean = state(context).getBoolean(APPLIED, false)
|
|
||||||
|
|
||||||
fun applyAsync(context: Context, limit: Int) {
|
|
||||||
val app = context.applicationContext
|
|
||||||
worker.execute {
|
|
||||||
runCatching {
|
|
||||||
if (!applied(app)) {
|
|
||||||
val previous = parse(WirelessAdbFix.shell(app, readCommand()))
|
|
||||||
check(state(app).edit().putBoolean(APPLIED, true).putString(PREVIOUS, previous).commit()) { "previous value not saved" }
|
|
||||||
}
|
|
||||||
WirelessAdbFix.shell(app, setCommand(limit))
|
|
||||||
}.onSuccess { Log.i(TAG, "at most $limit cached app(s) while the session runs") }
|
|
||||||
.onFailure { Log.w(TAG, "limit not set: ${it.message}") }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun restoreAsync(context: Context) {
|
|
||||||
val app = context.applicationContext
|
|
||||||
worker.execute {
|
|
||||||
if (!applied(app)) return@execute
|
|
||||||
val previous = state(app).getString(PREVIOUS, null)
|
|
||||||
runCatching { WirelessAdbFix.shell(app, restoreCommand(previous)) }
|
|
||||||
.onSuccess {
|
|
||||||
state(app).edit().putBoolean(APPLIED, false).remove(PREVIOUS).commit()
|
|
||||||
Log.i(TAG, "cached-app limit put back (${previous ?: "Android's own"})")
|
|
||||||
}
|
|
||||||
.onFailure { Log.w(TAG, "limit not put back yet: ${it.message}") }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package com.droiddeck.launcher.core
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.gpu.GpuInfo
|
||||||
|
import com.droiddeck.launcher.gpu.SocNames
|
||||||
|
|
||||||
|
object CpuAllocationDefaults {
|
||||||
|
data class Allocation(val client: String, val game: String)
|
||||||
|
|
||||||
|
val device: Allocation? by lazy {
|
||||||
|
forDevice(SocNames.model(), GpuInfo.systemProperty("ro.board.platform"),
|
||||||
|
CpuCores.all.associateWith(CpuCores::maxGhz))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun forDevice(model: String, platform: String, frequencies: Map<Int, Double?>): Allocation? {
|
||||||
|
val chip = model.trim().uppercase().substringBefore('-')
|
||||||
|
val gen2 = chip in setOf("SM8550", "QCS8550") ||
|
||||||
|
(chip.isEmpty() && platform.trim().equals("kalama", ignoreCase = true))
|
||||||
|
if (!gen2 || frequencies.size != 8 || frequencies.keys.any { it < 0 } ||
|
||||||
|
frequencies.values.any { it == null || !it.isFinite() || it <= 0.0 }) return null
|
||||||
|
val clusters = frequencies.entries.groupBy { it.value }.toSortedMap(compareBy { it ?: 0.0 }).values.toList()
|
||||||
|
if (clusters.map { it.size } != listOf(3, 4, 1)) return null
|
||||||
|
return Allocation(
|
||||||
|
client = CpuCores.format(clusters[2].map { it.key }.toSet()),
|
||||||
|
game = CpuCores.format(clusters[1].map { it.key }.toSet()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,11 +29,6 @@ import java.util.Locale
|
|||||||
object DeviceReport {
|
object DeviceReport {
|
||||||
private const val TAG = "DeviceReport"
|
private const val TAG = "DeviceReport"
|
||||||
|
|
||||||
internal fun cpuFeaturesSummary(cpuInfo: String): String = cpuInfo.lineSequence()
|
|
||||||
.filter { it.substringBefore(':').trim() == "Features" }
|
|
||||||
.map { it.substringAfter(':').trim().split(Regex("\\s+")).filter(String::isNotEmpty).joinToString(" ") }
|
|
||||||
.filter(String::isNotEmpty).distinct().joinToString(" | ").ifEmpty { "not reported" }
|
|
||||||
|
|
||||||
fun write(context: Context, target: File, mode: String) {
|
fun write(context: Context, target: File, mode: String) {
|
||||||
try {
|
try {
|
||||||
target.writeText(build(context, mode))
|
target.writeText(build(context, mode))
|
||||||
@@ -146,7 +141,6 @@ object DeviceReport {
|
|||||||
|
|
||||||
h("CPU and memory")
|
h("CPU and memory")
|
||||||
k("Cores", CpuCores.all.size)
|
k("Cores", CpuCores.all.size)
|
||||||
k("CPU features", cpuFeaturesSummary(FileUtils.readString(File("/proc/cpuinfo")).orEmpty()))
|
|
||||||
b.append("Core ceilings ")
|
b.append("Core ceilings ")
|
||||||
b.append(CpuCores.all.joinToString(", ") { c ->
|
b.append(CpuCores.all.joinToString(", ") { c ->
|
||||||
"cpu$c " + (CpuCores.maxGhz(c)?.let { String.format(Locale.US, "%.2f GHz", it) } ?: "?")
|
"cpu$c " + (CpuCores.maxGhz(c)?.let { String.format(Locale.US, "%.2f GHz", it) } ?: "?")
|
||||||
@@ -158,17 +152,13 @@ object DeviceReport {
|
|||||||
k("RAM total", FileUtils.sizeToString(mi.totalMem))
|
k("RAM total", FileUtils.sizeToString(mi.totalMem))
|
||||||
k("RAM available", FileUtils.sizeToString(mi.availMem))
|
k("RAM available", FileUtils.sizeToString(mi.availMem))
|
||||||
}
|
}
|
||||||
val pm = runCatching { context.getSystemService(Context.POWER_SERVICE) as? PowerManager }.getOrNull()
|
runCatching {
|
||||||
if (pm != null) {
|
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) k("Thermal status", thermalStatusName(pm.currentThermalStatus))
|
||||||
k("Thermal status", runCatching { thermalStatusName(pm.currentThermalStatus) }.getOrNull())
|
|
||||||
}
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||||
k("Thermal headroom (10 s)", runCatching {
|
k("Thermal headroom (10 s)", pm.getThermalHeadroom(10).let { if (it.isNaN()) "not reported" else String.format(Locale.US, "%.2f", it) })
|
||||||
pm.getThermalHeadroom(10).let { if (it.isNaN()) "not reported" else String.format(Locale.US, "%.2f", it) }
|
|
||||||
}.getOrNull())
|
|
||||||
}
|
}
|
||||||
k("Power saver", runCatching { pm.isPowerSaveMode }.getOrNull())
|
k("Power saver", pm.isPowerSaveMode)
|
||||||
}
|
}
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||||
val rate = runCatching { context.getSystemService(PerformanceHintManager::class.java)?.preferredUpdateRateNanos }.getOrNull()
|
val rate = runCatching { context.getSystemService(PerformanceHintManager::class.java)?.preferredUpdateRateNanos }.getOrNull()
|
||||||
@@ -210,12 +200,7 @@ object DeviceReport {
|
|||||||
h("Drivers")
|
h("Drivers")
|
||||||
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
|
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
|
||||||
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
|
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
|
||||||
if (gpu.model == 740) {
|
if (gpu.model == 740) k("TP UBWC hint", com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice() ?: "driver default")
|
||||||
val hint = com.droiddeck.launcher.gpu.TpUbwcHint
|
|
||||||
k("TP UBWC hint", hint.forThisDevice(context) ?: "driver default")
|
|
||||||
k("TP UBWC mode", hint.activeMode ?: SessionPrefs.TP_UBWC_AUTO)
|
|
||||||
if (hint.restartRequired(context)) k("TP UBWC pending", "${SessionPrefs.tpUbwcMode(context)} (restart required)")
|
|
||||||
}
|
|
||||||
k("Driver mode", SessionPrefs.gpuDriverMode(context) +
|
k("Driver mode", SessionPrefs.gpuDriverMode(context) +
|
||||||
(com.droiddeck.launcher.gpu.DriverPairs.recommendedKey(gpu, com.droiddeck.launcher.gpu.DriverPairs.from(
|
(com.droiddeck.launcher.gpu.DriverPairs.recommendedKey(gpu, com.droiddeck.launcher.gpu.DriverPairs.from(
|
||||||
com.droiddeck.launcher.gpu.TurnipReleases.cached(context)), com.droiddeck.launcher.gpu.TurnipReleases.autoPicks(context),
|
com.droiddeck.launcher.gpu.TurnipReleases.cached(context)), com.droiddeck.launcher.gpu.TurnipReleases.autoPicks(context),
|
||||||
@@ -262,17 +247,11 @@ object DeviceReport {
|
|||||||
EsyncPacks.status(LinuxRuntime.rootDir(context)).let { k("droiddeck-esync packs", "${it.installed} installed, ${it.wanted} wanted") }
|
EsyncPacks.status(LinuxRuntime.rootDir(context)).let { k("droiddeck-esync packs", "${it.installed} installed, ${it.wanted} wanted") }
|
||||||
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
|
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
|
||||||
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
|
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
|
||||||
k("zRAM: compress Steam during games", SessionPrefs.zramClient(context))
|
|
||||||
k("RAM cap", SessionPrefs.ramCapMb(context).let { if (it > 0) "$it MB" else "off" })
|
|
||||||
k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
|
|
||||||
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
|
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
|
||||||
k("proot fast path", SessionPrefs.prootFastPath(context))
|
k("proot fast path", SessionPrefs.prootFastPath(context))
|
||||||
k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path)
|
|
||||||
k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context))
|
|
||||||
k("Guest host name", SessionPrefs.guestHostname(context))
|
k("Guest host name", SessionPrefs.guestHostname(context))
|
||||||
k("DirectAudio for games", SessionPrefs.directAudio(context))
|
k("DirectAudio for games", SessionPrefs.directAudio(context))
|
||||||
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
||||||
k("Return to launcher after a game", SessionPrefs.returnAfterGame(context))
|
|
||||||
k("Microphone", SessionPrefs.micEnabled(context))
|
k("Microphone", SessionPrefs.micEnabled(context))
|
||||||
k("On-screen controls", SessionPrefs.oscMode(context))
|
k("On-screen controls", SessionPrefs.oscMode(context))
|
||||||
k("Touch mode", SessionPrefs.touchMode(context))
|
k("Touch mode", SessionPrefs.touchMode(context))
|
||||||
|
|||||||
@@ -3,8 +3,6 @@ package com.droiddeck.launcher.core
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.SharedPreferences
|
import android.content.SharedPreferences
|
||||||
import java.net.HttpURLConnection
|
import java.net.HttpURLConnection
|
||||||
import java.net.InetSocketAddress
|
|
||||||
import java.net.Proxy
|
|
||||||
import java.net.URL
|
import java.net.URL
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
import java.util.concurrent.CountDownLatch
|
import java.util.concurrent.CountDownLatch
|
||||||
@@ -22,7 +20,6 @@ object DownloadSource {
|
|||||||
private const val KEY_MODE = "mode"
|
private const val KEY_MODE = "mode"
|
||||||
private const val KEY_MIRROR = "mirror"
|
private const val KEY_MIRROR = "mirror"
|
||||||
private const val KEY_CUSTOM = "custom"
|
private const val KEY_CUSTOM = "custom"
|
||||||
private const val KEY_PROXY = "proxy"
|
|
||||||
private const val KEY_FASTEST = "fastest"
|
private const val KEY_FASTEST = "fastest"
|
||||||
|
|
||||||
private const val PROBE = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/README.md"
|
private const val PROBE = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/README.md"
|
||||||
@@ -178,22 +175,6 @@ object DownloadSource {
|
|||||||
prefs(context)?.edit()?.putString(KEY_CUSTOM, normalizePrefix(prefix))?.apply()
|
prefs(context)?.edit()?.putString(KEY_CUSTOM, normalizePrefix(prefix))?.apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun proxyHostPort(context: Context): String = prefs(context)?.getString(KEY_PROXY, "") ?: ""
|
|
||||||
|
|
||||||
fun setProxy(context: Context, value: String) {
|
|
||||||
prefs(context)?.edit()?.putString(KEY_PROXY, normalizeProxy(value))?.apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** An HTTP proxy every Downloader connection uses, or null when none is configured. */
|
|
||||||
fun httpProxy(): Proxy? = proxyOf(prefs()?.getString(KEY_PROXY, "") ?: "")
|
|
||||||
|
|
||||||
internal fun proxyOf(value: String): Proxy? {
|
|
||||||
val host = value.substringBefore(':')
|
|
||||||
val port = value.substringAfter(':', "").toIntOrNull() ?: return null
|
|
||||||
if (host.isEmpty()) return null
|
|
||||||
return Proxy(Proxy.Type.HTTP, InetSocketAddress(host, port))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun reset(context: Context) {
|
fun reset(context: Context) {
|
||||||
lastGood = null
|
lastGood = null
|
||||||
prefs(context)?.edit()?.clear()?.apply()
|
prefs(context)?.edit()?.clear()?.apply()
|
||||||
@@ -224,11 +205,4 @@ object DownloadSource {
|
|||||||
if (trimmed.isEmpty() || trimmed.startsWith("http://")) return ""
|
if (trimmed.isEmpty() || trimmed.startsWith("http://")) return ""
|
||||||
return if (trimmed.startsWith("https://")) trimmed else "https://$trimmed"
|
return if (trimmed.startsWith("https://")) trimmed else "https://$trimmed"
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun normalizeProxy(value: String): String {
|
|
||||||
val trimmed = value.trim().removePrefix("http://").trimEnd('/')
|
|
||||||
val host = trimmed.substringBefore(':')
|
|
||||||
val port = trimmed.substringAfter(':', "").toIntOrNull() ?: 0
|
|
||||||
return if (host.isNotEmpty() && port in 1..65535) "$host:$port" else ""
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -11,88 +11,24 @@ import java.io.IOException;
|
|||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.net.HttpURLConnection;
|
import java.net.HttpURLConnection;
|
||||||
import java.net.Proxy;
|
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
|
||||||
|
|
||||||
public final class Downloader {
|
public final class Downloader {
|
||||||
private static final String TAG = "Downloader";
|
private static final String TAG = "Downloader";
|
||||||
private static final int CONNECT_TIMEOUT_MS = 10_000;
|
private static final int CONNECT_TIMEOUT_MS = 10_000;
|
||||||
private static final int STALL_TIMEOUT_MS = 15_000;
|
private static final int STALL_TIMEOUT_MS = 15_000;
|
||||||
private static final int HTTP_RANGE_NOT_SATISFIABLE = 416;
|
private static final int HTTP_RANGE_NOT_SATISFIABLE = 416;
|
||||||
private static final java.util.concurrent.ExecutorService CANCEL_EXECUTOR =
|
|
||||||
java.util.concurrent.Executors.newCachedThreadPool(r -> {
|
|
||||||
Thread thread = new Thread(r, "download-cancel");
|
|
||||||
thread.setDaemon(true);
|
|
||||||
return thread;
|
|
||||||
});
|
|
||||||
|
|
||||||
private Downloader() {}
|
private Downloader() {}
|
||||||
|
|
||||||
public static final class Cancellation implements java.util.function.BooleanSupplier {
|
|
||||||
private final AtomicBoolean cancelled = new AtomicBoolean();
|
|
||||||
private final AtomicReference<HttpURLConnection> connection = new AtomicReference<>();
|
|
||||||
private final AtomicReference<InputStream> input = new AtomicReference<>();
|
|
||||||
private final java.util.function.BooleanSupplier external;
|
|
||||||
|
|
||||||
public Cancellation() { this(null); }
|
|
||||||
public Cancellation(java.util.function.BooleanSupplier external) { this.external = external; }
|
|
||||||
|
|
||||||
public void cancel() {
|
|
||||||
cancelled.set(true);
|
|
||||||
HttpURLConnection active = connection.get();
|
|
||||||
if (active != null) disconnectAsync(active);
|
|
||||||
InputStream activeInput = input.get();
|
|
||||||
if (activeInput != null) closeAsync(activeInput);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void disconnectAsync(HttpURLConnection active) {
|
|
||||||
CANCEL_EXECUTOR.execute(() -> {
|
|
||||||
try { active.disconnect(); } catch (RuntimeException ignored) { }
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void closeAsync(InputStream active) {
|
|
||||||
CANCEL_EXECUTOR.execute(() -> {
|
|
||||||
try { active.close(); } catch (IOException ignored) { }
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override public boolean getAsBoolean() {
|
|
||||||
return cancelled.get() || (external != null && external.getAsBoolean());
|
|
||||||
}
|
|
||||||
|
|
||||||
private void attach(HttpURLConnection active) {
|
|
||||||
connection.set(active);
|
|
||||||
if (getAsBoolean()) disconnectAsync(active);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void detach(HttpURLConnection active) { connection.compareAndSet(active, null); }
|
|
||||||
|
|
||||||
private void attach(InputStream active) {
|
|
||||||
input.set(active);
|
|
||||||
if (getAsBoolean()) closeAsync(active);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void detach(InputStream active) { input.compareAndSet(active, null); }
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String downloadString(String url) {
|
public static String downloadString(String url) {
|
||||||
return downloadString(url, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String downloadString(String url, java.util.function.BooleanSupplier cancelled) {
|
|
||||||
List<String> sources = DownloadSource.INSTANCE.candidates(url);
|
List<String> sources = DownloadSource.INSTANCE.candidates(url);
|
||||||
for (int i = 0; i < sources.size(); i++) {
|
for (int i = 0; i < sources.size(); i++) {
|
||||||
if (isCancelled(cancelled)) return null;
|
|
||||||
if (i > 0) Log.i(TAG, "retrying " + url + " via " + sources.get(i));
|
if (i > 0) Log.i(TAG, "retrying " + url + " via " + sources.get(i));
|
||||||
Fetch fetch = fetch(sources.get(i), cancelled);
|
Fetch fetch = fetch(sources.get(i));
|
||||||
// A cancelled fetch says nothing about the source, so it must not count as a failure.
|
|
||||||
if (isCancelled(cancelled)) return null;
|
|
||||||
if (fetch.body != null) {
|
if (fetch.body != null) {
|
||||||
DownloadSource.INSTANCE.succeeded(sources.get(i));
|
DownloadSource.INSTANCE.succeeded(sources.get(i));
|
||||||
return fetch.body;
|
return fetch.body;
|
||||||
@@ -116,52 +52,25 @@ public final class Downloader {
|
|||||||
/** Verify each candidate before accepting it, so a bad mirror can fall back. */
|
/** Verify each candidate before accepting it, so a bad mirror can fall back. */
|
||||||
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
|
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
|
||||||
java.util.function.Consumer<Float> progress) {
|
java.util.function.Consumer<Float> progress) {
|
||||||
return downloadFile(url, destination, resume, expectedSha256, null, progress);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** {@code cancelled} is polled while bytes arrive; a cancel stops at once and leaves the partial file for the caller. */
|
|
||||||
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
|
|
||||||
java.util.function.BooleanSupplier cancelled,
|
|
||||||
java.util.function.Consumer<Float> progress) {
|
|
||||||
if (expectedSha256 != null && !expectedSha256.matches("(?i)[0-9a-f]{64}"))
|
if (expectedSha256 != null && !expectedSha256.matches("(?i)[0-9a-f]{64}"))
|
||||||
throw new IllegalArgumentException("Expected SHA-256 must be 64 hex characters");
|
throw new IllegalArgumentException("Expected SHA-256 must be 64 hex characters");
|
||||||
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, cancelled, progress);
|
return downloadCandidates(url, DownloadSource.INSTANCE.candidates(url), destination, resume, expectedSha256, progress);
|
||||||
}
|
|
||||||
|
|
||||||
/** A third-party mirror may only serve bytes that can be checked against a digest from a direct source. */
|
|
||||||
static List<String> sources(String url, String expectedSha256) {
|
|
||||||
return expectedSha256 == null ? java.util.Collections.singletonList(url) : DownloadSource.INSTANCE.candidates(url);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Package-private for the local multi-source HTTP test.
|
// Package-private for the local multi-source HTTP test.
|
||||||
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
|
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
|
||||||
String expectedSha256, java.util.function.Consumer<Float> progress) {
|
String expectedSha256, java.util.function.Consumer<Float> progress) {
|
||||||
return downloadCandidates(original, sources, destination, resume, expectedSha256, null, progress);
|
|
||||||
}
|
|
||||||
|
|
||||||
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
|
|
||||||
String expectedSha256, java.util.function.BooleanSupplier cancelled,
|
|
||||||
java.util.function.Consumer<Float> progress) {
|
|
||||||
Identity identity = loadIdentity(destination, resume, expectedSha256);
|
Identity identity = loadIdentity(destination, resume, expectedSha256);
|
||||||
for (int i = 0; i < sources.size(); i++) {
|
for (int i = 0; i < sources.size(); i++) {
|
||||||
String source = sources.get(i);
|
String source = sources.get(i);
|
||||||
if (isCancelled(cancelled)) return false;
|
|
||||||
if (i > 0) Log.i(TAG, "retrying " + original + " via " + source);
|
if (i > 0) Log.i(TAG, "retrying " + original + " via " + source);
|
||||||
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, cancelled, progress);
|
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, progress);
|
||||||
// A cancel is not a source failure: no other mirror, and no DownloadSource.failed().
|
|
||||||
if (outcome == Outcome.CANCELLED) return false;
|
|
||||||
if (outcome == Outcome.DONE) {
|
if (outcome == Outcome.DONE) {
|
||||||
if (expectedSha256 != null) {
|
if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(Hashes.sha256(destination))) {
|
||||||
String actualSha256 = Hashes.sha256(destination);
|
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
|
||||||
if (isCancelled(cancelled)) return false;
|
if (!discardPartial(destination, identity)) return false;
|
||||||
if (!expectedSha256.equalsIgnoreCase(actualSha256)) {
|
continue;
|
||||||
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
|
|
||||||
if (!discardPartial(destination, identity)) return false;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (isCancelled(cancelled)) return false;
|
|
||||||
resumeFile(destination).delete();
|
resumeFile(destination).delete();
|
||||||
DownloadSource.INSTANCE.succeeded(source);
|
DownloadSource.INSTANCE.succeeded(source);
|
||||||
if (progress != null) progress.accept(1f);
|
if (progress != null) progress.accept(1f);
|
||||||
@@ -173,11 +82,7 @@ public final class Downloader {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private enum Outcome { DONE, RETRY, FATAL, CANCELLED }
|
private enum Outcome { DONE, RETRY, FATAL }
|
||||||
|
|
||||||
private static boolean isCancelled(java.util.function.BooleanSupplier cancelled) {
|
|
||||||
return cancelled != null && cancelled.getAsBoolean();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static final class Identity {
|
private static final class Identity {
|
||||||
private String source;
|
private String source;
|
||||||
@@ -245,9 +150,7 @@ public final class Downloader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static Outcome attempt(String url, File destination, boolean resume, Identity identity,
|
private static Outcome attempt(String url, File destination, boolean resume, Identity identity,
|
||||||
String expectedSha256, java.util.function.BooleanSupplier cancelled,
|
String expectedSha256, java.util.function.Consumer<Float> progress) {
|
||||||
java.util.function.Consumer<Float> progress) {
|
|
||||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
|
||||||
HttpURLConnection connection = null;
|
HttpURLConnection connection = null;
|
||||||
long have = resume && destination.isFile() ? destination.length() : 0;
|
long have = resume && destination.isFile() ? destination.length() : 0;
|
||||||
try {
|
try {
|
||||||
@@ -257,7 +160,6 @@ public final class Downloader {
|
|||||||
have = 0;
|
have = 0;
|
||||||
}
|
}
|
||||||
connection = open(url, STALL_TIMEOUT_MS);
|
connection = open(url, STALL_TIMEOUT_MS);
|
||||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(connection);
|
|
||||||
if (have > 0) {
|
if (have > 0) {
|
||||||
connection.setRequestProperty("Range", "bytes=" + have + "-");
|
connection.setRequestProperty("Range", "bytes=" + have + "-");
|
||||||
connection.setRequestProperty("If-Range", identity.etag);
|
connection.setRequestProperty("If-Range", identity.etag);
|
||||||
@@ -266,7 +168,7 @@ public final class Downloader {
|
|||||||
if (have > 0 && code == HTTP_RANGE_NOT_SATISFIABLE) {
|
if (have > 0 && code == HTTP_RANGE_NOT_SATISFIABLE) {
|
||||||
connection.disconnect();
|
connection.disconnect();
|
||||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||||
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
|
return attempt(url, destination, false, identity, expectedSha256, progress);
|
||||||
}
|
}
|
||||||
if (code / 100 != 2) {
|
if (code / 100 != 2) {
|
||||||
Log.w(TAG, url + " -> HTTP " + code);
|
Log.w(TAG, url + " -> HTTP " + code);
|
||||||
@@ -277,13 +179,13 @@ public final class Downloader {
|
|||||||
if (appending && !rangeStartsAt(connection.getHeaderField("Content-Range"), have)) {
|
if (appending && !rangeStartsAt(connection.getHeaderField("Content-Range"), have)) {
|
||||||
connection.disconnect();
|
connection.disconnect();
|
||||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||||
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
|
return attempt(url, destination, false, identity, expectedSha256, progress);
|
||||||
}
|
}
|
||||||
String etag = connection.getHeaderField("ETag");
|
String etag = connection.getHeaderField("ETag");
|
||||||
if (have > 0 && appending && (!strongETag(etag) || !etag.equals(identity.etag))) {
|
if (have > 0 && appending && (!strongETag(etag) || !etag.equals(identity.etag))) {
|
||||||
connection.disconnect();
|
connection.disconnect();
|
||||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||||
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
|
return attempt(url, destination, false, identity, expectedSha256, progress);
|
||||||
}
|
}
|
||||||
if (!appending && have > 0) {
|
if (!appending && have > 0) {
|
||||||
// If-Range may legitimately return full 200 when representation changed.
|
// If-Range may legitimately return full 200 when representation changed.
|
||||||
@@ -300,36 +202,26 @@ public final class Downloader {
|
|||||||
identity.etag = strongETag(etag) ? etag : null;
|
identity.etag = strongETag(etag) ? etag : null;
|
||||||
saveIdentity(destination, identity, expectedSha256);
|
saveIdentity(destination, identity, expectedSha256);
|
||||||
long written = have;
|
long written = have;
|
||||||
InputStream input = connection.getInputStream();
|
try (InputStream in = new BufferedInputStream(connection.getInputStream(), 1 << 16);
|
||||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(input);
|
|
||||||
try (InputStream in = new BufferedInputStream(input, 1 << 16);
|
|
||||||
OutputStream out = new FileOutputStream(destination, appending)) {
|
OutputStream out = new FileOutputStream(destination, appending)) {
|
||||||
byte[] buffer = new byte[1 << 16];
|
byte[] buffer = new byte[1 << 16];
|
||||||
long lastReport = 0;
|
long lastReport = 0;
|
||||||
for (int read = in.read(buffer); read > 0; read = in.read(buffer)) {
|
for (int read = in.read(buffer); read > 0; read = in.read(buffer)) {
|
||||||
out.write(buffer, 0, read);
|
out.write(buffer, 0, read);
|
||||||
written += read;
|
written += read;
|
||||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
|
||||||
if (progress != null && written - lastReport > (1 << 20)) {
|
if (progress != null && written - lastReport > (1 << 20)) {
|
||||||
lastReport = written;
|
lastReport = written;
|
||||||
progress.accept(total > 0 ? written / (float) total : -1f);
|
progress.accept(total > 0 ? written / (float) total : -1f);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(input);
|
|
||||||
}
|
}
|
||||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
|
||||||
if (total > 0 && written < total) return Outcome.RETRY;
|
if (total > 0 && written < total) return Outcome.RETRY;
|
||||||
return Outcome.DONE;
|
return Outcome.DONE;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
|
||||||
Log.w(TAG, "download " + url, e);
|
Log.w(TAG, "download " + url, e);
|
||||||
return Outcome.RETRY;
|
return Outcome.RETRY;
|
||||||
} finally {
|
} finally {
|
||||||
if (connection != null) {
|
if (connection != null) connection.disconnect();
|
||||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(connection);
|
|
||||||
connection.disconnect();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -358,15 +250,9 @@ public final class Downloader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static Fetch fetch(String url) {
|
private static Fetch fetch(String url) {
|
||||||
return fetch(url, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Fetch fetch(String url, java.util.function.BooleanSupplier cancelled) {
|
|
||||||
HttpURLConnection connection = null;
|
HttpURLConnection connection = null;
|
||||||
Cancellation token = cancelled instanceof Cancellation ? (Cancellation) cancelled : null;
|
|
||||||
try {
|
try {
|
||||||
connection = open(url, STALL_TIMEOUT_MS);
|
connection = open(url, STALL_TIMEOUT_MS);
|
||||||
if (token != null) token.attach(connection);
|
|
||||||
int code = connection.getResponseCode();
|
int code = connection.getResponseCode();
|
||||||
if (code / 100 != 2) {
|
if (code / 100 != 2) {
|
||||||
Log.w(TAG, url + " -> HTTP " + code);
|
Log.w(TAG, url + " -> HTTP " + code);
|
||||||
@@ -378,22 +264,15 @@ public final class Downloader {
|
|||||||
return new Fetch(new String(out.toByteArray(), StandardCharsets.UTF_8), false);
|
return new Fetch(new String(out.toByteArray(), StandardCharsets.UTF_8), false);
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
if (isCancelled(cancelled)) return new Fetch(null, false);
|
|
||||||
Log.w(TAG, "GET " + url, e);
|
Log.w(TAG, "GET " + url, e);
|
||||||
return new Fetch(null, false);
|
return new Fetch(null, false);
|
||||||
} finally {
|
} finally {
|
||||||
if (connection != null) {
|
if (connection != null) connection.disconnect();
|
||||||
if (token != null) token.detach(connection);
|
|
||||||
connection.disconnect();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static HttpURLConnection open(String url, int readTimeoutMs) throws java.io.IOException {
|
private static HttpURLConnection open(String url, int readTimeoutMs) throws java.io.IOException {
|
||||||
// An explicit Proxy routes the connection through the app setting instead of the system-wide proxy.
|
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
|
||||||
Proxy proxy = DownloadSource.INSTANCE.httpProxy();
|
|
||||||
HttpURLConnection connection = (HttpURLConnection) (proxy != null
|
|
||||||
? new URL(url).openConnection(proxy) : new URL(url).openConnection());
|
|
||||||
connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
|
connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
|
||||||
connection.setReadTimeout(readTimeoutMs);
|
connection.setReadTimeout(readTimeoutMs);
|
||||||
connection.setInstanceFollowRedirects(true);
|
connection.setInstanceFollowRedirects(true);
|
||||||
|
|||||||
@@ -14,8 +14,6 @@ object GameEnvironmentOptions {
|
|||||||
Option("MESA_SHADER_CACHE_MAX_SIZE", "1G", R.string.game_env_cache_size, Type.CHOICE, listOf("512M", "1G", "2G", "4G")),
|
Option("MESA_SHADER_CACHE_MAX_SIZE", "1G", R.string.game_env_cache_size, Type.CHOICE, listOf("512M", "1G", "2G", "4G")),
|
||||||
Option("PROTON_LOG", "1", R.string.game_env_proton_log, Type.TOGGLE, listOf("0", "1")),
|
Option("PROTON_LOG", "1", R.string.game_env_proton_log, Type.TOGGLE, listOf("0", "1")),
|
||||||
Option("PROTON_USE_WINED3D", "1", R.string.game_env_wined3d, Type.TOGGLE, listOf("0", "1")),
|
Option("PROTON_USE_WINED3D", "1", R.string.game_env_wined3d, Type.TOGGLE, listOf("0", "1")),
|
||||||
Option("PROTON_DXVK_D3D8", "1", R.string.game_env_dxvk_d3d8, Type.TOGGLE, listOf("0", "1")),
|
|
||||||
Option("WINE_D3D_CONFIG", "renderer=vulkan", R.string.game_env_wined3d_renderer, Type.CHOICE, listOf("renderer=vulkan", "renderer=gl")),
|
|
||||||
Option("PROTON_USE_XALIA", "0", R.string.game_env_xalia, Type.TOGGLE, listOf("0", "1")),
|
Option("PROTON_USE_XALIA", "0", R.string.game_env_xalia, Type.TOGGLE, listOf("0", "1")),
|
||||||
Option("PROTON_NO_NTSYNC", "1", R.string.game_env_no_ntsync, Type.TOGGLE, listOf("0", "1")),
|
Option("PROTON_NO_NTSYNC", "1", R.string.game_env_no_ntsync, Type.TOGGLE, listOf("0", "1")),
|
||||||
Option("PROTON_NO_ESYNC", "1", R.string.game_env_no_esync, Type.TOGGLE, listOf("0", "1")),
|
Option("PROTON_NO_ESYNC", "1", R.string.game_env_no_esync, Type.TOGGLE, listOf("0", "1")),
|
||||||
@@ -34,7 +32,6 @@ object GameEnvironmentOptions {
|
|||||||
Option("MESA_EXTENSION_MAX_YEAR", "", 0, Type.TEXT),
|
Option("MESA_EXTENSION_MAX_YEAR", "", 0, Type.TEXT),
|
||||||
Option("MESA_GL_VERSION_OVERRIDE", "", 0, Type.TEXT),
|
Option("MESA_GL_VERSION_OVERRIDE", "", 0, Type.TEXT),
|
||||||
Option("PULSE_LATENCY_MSEC", "", 0, Type.NUMBER),
|
Option("PULSE_LATENCY_MSEC", "", 0, Type.NUMBER),
|
||||||
Option("DROIDDECK_GAME_CORES", "", R.string.game_env_cores, Type.TEXT),
|
|
||||||
Option("DROIDDECK_ANTICHEAT_OFFLINE", "1", R.string.game_env_anticheat_offline, Type.TOGGLE, listOf("0", "1")),
|
Option("DROIDDECK_ANTICHEAT_OFFLINE", "1", R.string.game_env_anticheat_offline, Type.TOGGLE, listOf("0", "1")),
|
||||||
Option("WINE_LARGE_ADDRESS_AWARE", "0", 0, Type.TOGGLE, listOf("0", "1")),
|
Option("WINE_LARGE_ADDRESS_AWARE", "0", 0, Type.TOGGLE, listOf("0", "1")),
|
||||||
Option("WINEDLLOVERRIDES", "", 0, Type.TEXT),
|
Option("WINEDLLOVERRIDES", "", 0, Type.TEXT),
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
package com.droiddeck.launcher.core
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.net.Uri
|
|
||||||
import android.provider.Settings
|
|
||||||
|
|
||||||
object GlobalSettings {
|
|
||||||
// Settings.Global caches values in-process and misses deletions made over adb; ask the provider directly.
|
|
||||||
fun read(context: Context, name: String): String? {
|
|
||||||
val uri = Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
|
|
||||||
context.contentResolver.query(uri, arrayOf(Settings.NameValueTable.VALUE), null, null, null)?.use { cursor ->
|
|
||||||
return if (cursor.moveToFirst()) cursor.getString(0) else null
|
|
||||||
}
|
|
||||||
return Settings.Global.getString(context.contentResolver, name)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isOn(context: Context, name: String): Boolean =
|
|
||||||
runCatching { read(context, name)?.trim() == "1" }.getOrDefault(false)
|
|
||||||
|
|
||||||
fun developerOptionsOn(context: Context): Boolean = isOn(context, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED)
|
|
||||||
|
|
||||||
// Settings.Global.ADB_WIFI_ENABLED is hidden; the key is stable since Android 11.
|
|
||||||
fun wirelessDebuggingOn(context: Context): Boolean = isOn(context, "adb_wifi_enabled")
|
|
||||||
}
|
|
||||||
@@ -8,11 +8,7 @@ object HostProcess {
|
|||||||
private const val TAG = "HostProcess"
|
private const val TAG = "HostProcess"
|
||||||
|
|
||||||
@JvmStatic
|
@JvmStatic
|
||||||
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?): Int =
|
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?): Int {
|
||||||
start(command, env, dir, onExit, onLine, null)
|
|
||||||
|
|
||||||
@JvmStatic
|
|
||||||
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?, outputFile: File?): Int {
|
|
||||||
val argv = split(command)
|
val argv = split(command)
|
||||||
if (argv.isEmpty()) return -1
|
if (argv.isEmpty()) return -1
|
||||||
return try {
|
return try {
|
||||||
@@ -23,10 +19,7 @@ object HostProcess {
|
|||||||
if (eq > 0) builder.environment()[line.substring(0, eq)] = line.substring(eq + 1)
|
if (eq > 0) builder.environment()[line.substring(0, eq)] = line.substring(eq + 1)
|
||||||
}
|
}
|
||||||
builder.redirectErrorStream(true)
|
builder.redirectErrorStream(true)
|
||||||
if (onLine == null) {
|
if (onLine == null) builder.redirectOutput(File("/dev/null"))
|
||||||
if (outputFile == null) builder.redirectOutput(File("/dev/null"))
|
|
||||||
else builder.redirectOutput(ProcessBuilder.Redirect.appendTo(outputFile))
|
|
||||||
}
|
|
||||||
val process = builder.start()
|
val process = builder.start()
|
||||||
val pid = pidOf(process)
|
val pid = pidOf(process)
|
||||||
Log.i(TAG, "started pid $pid: ${argv.first()} (${argv.size - 1} arguments)")
|
Log.i(TAG, "started pid $pid: ${argv.first()} (${argv.size - 1} arguments)")
|
||||||
|
|||||||
@@ -1,96 +1,15 @@
|
|||||||
package com.droiddeck.launcher.core
|
package com.droiddeck.launcher.core
|
||||||
|
|
||||||
object LogRedactor {
|
object LogRedactor {
|
||||||
internal const val MAX_LINE_LENGTH = 64 * 1024
|
|
||||||
internal const val OVERSIZED_LINE = "<oversized log line withheld>"
|
|
||||||
|
|
||||||
private data class MatcherKey(val pattern: String, val options: Set<RegexOption>)
|
|
||||||
|
|
||||||
private class MatcherCache : LinkedHashMap<MatcherKey, java.util.regex.Matcher>(32, 0.75f, true) {
|
|
||||||
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<MatcherKey, java.util.regex.Matcher>?): Boolean =
|
|
||||||
size > 32
|
|
||||||
}
|
|
||||||
|
|
||||||
// Android matchers own native state, so reuse them instead of creating one for every log line.
|
|
||||||
private val matchers = object : ThreadLocal<MatcherCache>() {
|
|
||||||
override fun initialValue(): MatcherCache = MatcherCache()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun <T> withMatcher(
|
|
||||||
regex: Regex,
|
|
||||||
input: CharSequence,
|
|
||||||
action: (java.util.regex.Matcher) -> T,
|
|
||||||
): T {
|
|
||||||
val key = MatcherKey(regex.pattern, regex.options)
|
|
||||||
val matcher = matchers.get()!!.getOrPut(key) { regex.toPattern().matcher("") }
|
|
||||||
return try {
|
|
||||||
action(matcher.reset(input))
|
|
||||||
} finally {
|
|
||||||
matcher.reset("")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun replaceMatches(input: String, regex: Regex, replacement: String): String =
|
|
||||||
replaceMatches(input, regex) { replacement }
|
|
||||||
|
|
||||||
private fun replaceMatches(
|
|
||||||
input: String,
|
|
||||||
regex: Regex,
|
|
||||||
replacement: (java.util.regex.Matcher) -> String,
|
|
||||||
): String = withMatcher(regex, input) { matcher ->
|
|
||||||
if (!matcher.find()) return@withMatcher input
|
|
||||||
val out = StringBuffer(input.length)
|
|
||||||
do {
|
|
||||||
matcher.appendReplacement(out, java.util.regex.Matcher.quoteReplacement(replacement(matcher)))
|
|
||||||
} while (matcher.find())
|
|
||||||
matcher.appendTail(out)
|
|
||||||
out.toString()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun matchesEntire(input: String, regex: Regex): Boolean =
|
|
||||||
withMatcher(regex, input) { it.matches() }
|
|
||||||
|
|
||||||
private fun isHidlLoaderDiagnostic(input: String, match: java.util.regex.Matcher): Boolean {
|
|
||||||
if (!matchesEntire(match.group(), HIDL_SHARED_LIBRARY)) return false
|
|
||||||
val start = match.start()
|
|
||||||
val end = match.end()
|
|
||||||
val prefix = "library \""
|
|
||||||
val suffix = "\" not found"
|
|
||||||
val earliestQuote = (start - 4096).coerceAtLeast(0)
|
|
||||||
var quote = start - 1
|
|
||||||
while (quote >= earliestQuote && input[quote] != '"') {
|
|
||||||
val char = input[quote]
|
|
||||||
if (!char.isLetterOrDigit() && char !in "/._-") return false
|
|
||||||
quote--
|
|
||||||
}
|
|
||||||
if (quote < earliestQuote) return false
|
|
||||||
val pathStart = quote + 1
|
|
||||||
if (pathStart < start && (input[start - 1] != '/' ||
|
|
||||||
!(input.regionMatches(pathStart, "/vendor/", 0, 8) ||
|
|
||||||
input.regionMatches(pathStart, "/system/", 0, 8)))) return false
|
|
||||||
val prefixStart = quote - prefix.length + 1
|
|
||||||
val suffixEnd = end + suffix.length
|
|
||||||
return prefixStart >= 0 && suffixEnd <= input.length &&
|
|
||||||
input.regionMatches(prefixStart, prefix, 0, prefix.length, ignoreCase = true) &&
|
|
||||||
input.regionMatches(end, suffix, 0, suffix.length, ignoreCase = true) &&
|
|
||||||
(prefixStart == 0 || !(input[prefixStart - 1].isLetterOrDigit() || input[prefixStart - 1] == '_')) &&
|
|
||||||
(suffixEnd == input.length || !(input[suffixEnd].isLetterOrDigit() || input[suffixEnd] == '_'))
|
|
||||||
}
|
|
||||||
|
|
||||||
private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}")
|
private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}")
|
||||||
private val HIDL_SHARED_LIBRARY = Regex(
|
|
||||||
"(?:android\\.(?:hardware|frameworks|hidl|system)|vendor\\.[A-Za-z0-9_]+\\.hardware)" +
|
|
||||||
"(?:\\.[A-Za-z0-9_]+)+@[0-9]+\\.[0-9]+(?:-[A-Za-z0-9_]+)*\\.so"
|
|
||||||
)
|
|
||||||
|
|
||||||
private val JWT_LABELLED = Regex("(?i)(\\bJWT[\\s=:]+)(\\d{8,})")
|
private val JWT_LABELLED = Regex("(?i)(\\bJWT[\\s=:]+)(\\d{8,})")
|
||||||
private val JWT_BASE64 = Regex("ey[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}")
|
private val JWT_BASE64 = Regex("ey[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}")
|
||||||
private val GUID = Regex("\\b[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\\b")
|
private val GUID = Regex("\\b[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\\b")
|
||||||
private val SECRET_KV = Regex(
|
private val SECRET_KV = Regex(
|
||||||
"(?i)(\\b(?:access[_-]?token|refresh[_-]?token|auth[_-]?token|authtoken|token|authcode|" +
|
"(?i)\\b(access[_-]?token|refresh[_-]?token|auth[_-]?token|authtoken|token|authcode|" +
|
||||||
"auth[_-]?ticket|ticket|sessionid|steamloginsecure|webapikey|api[_-]?key|" +
|
"auth[_-]?ticket|ticket|sessionid|steamloginsecure|webapikey|api[_-]?key|" +
|
||||||
"machine[_-]?auth(?:[_-]?token)?|machineauth|password|passwd|pwd|secret)[\"']?\\s*[=:]\\s*)" +
|
"machine[_-]?auth(?:[_-]?token)?|machineauth|password|passwd|pwd|secret)" +
|
||||||
"(?:([\"'])((?:\\\\.|(?!\\2)[^\\\\\\r\\n]){4,})\\2|([^\\s\"'<>&;,]{4,}))"
|
"(\\s*[=:]\\s*|=)([^\\s\"'<>&;,]{4,})"
|
||||||
)
|
)
|
||||||
private val GUARD_CODE = Regex(
|
private val GUARD_CODE = Regex(
|
||||||
"(?i)((?:steam\\s*)?guard\\s*code[\\s:=]*|two[\\s-]?factor[\\s:=]*|2fa[\\s:=]*)([A-Za-z0-9]{5})"
|
"(?i)((?:steam\\s*)?guard\\s*code[\\s:=]*|two[\\s-]?factor[\\s:=]*|2fa[\\s:=]*)([A-Za-z0-9]{5})"
|
||||||
@@ -120,7 +39,7 @@ object LogRedactor {
|
|||||||
|
|
||||||
private const val ACCOUNT_VALUE = "(\"[^\"<\\r\\n]+\"|'[^'<\\r\\n]+'|[^\\s\"'<>&;,}]+)"
|
private const val ACCOUNT_VALUE = "(\"[^\"<\\r\\n]+\"|'[^'<\\r\\n]+'|[^\\s\"'<>&;,}]+)"
|
||||||
private val ACCOUNT_KV = Regex(
|
private val ACCOUNT_KV = Regex(
|
||||||
"(?i)(?<![A-Za-z0-9_])(account[_-]?name|account[_-]?id|user[_-]?name|epicusername)" +
|
"(?i)(?<![A-Za-z0-9_])(account[_-]?name|user[_-]?name|epicusername)" +
|
||||||
"([\"']?\\s*[=:]\\s*|[\"']\\s+)" + ACCOUNT_VALUE
|
"([\"']?\\s*[=:]\\s*|[\"']\\s+)" + ACCOUNT_VALUE
|
||||||
)
|
)
|
||||||
private val LOGIN_KV = Regex(
|
private val LOGIN_KV = Regex(
|
||||||
@@ -155,7 +74,6 @@ object LogRedactor {
|
|||||||
java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf"),
|
java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf"),
|
||||||
java.io.File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf"),
|
java.io.File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf"),
|
||||||
)
|
)
|
||||||
matchers.remove()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Volatile
|
@Volatile
|
||||||
@@ -223,8 +141,8 @@ object LogRedactor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun describeAddresses(text: String): String {
|
fun describeAddresses(text: String): String {
|
||||||
var out = replaceMatches(text, IPV6) { m -> kind(m.group())?.let { "<$it>" } ?: m.group() }
|
var out = IPV6.replace(text) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
|
||||||
out = replaceMatches(out, IPV4) { m -> kind(m.group())?.let { "<$it>" } ?: m.group() }
|
out = IPV4.replace(out) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -249,28 +167,23 @@ object LogRedactor {
|
|||||||
"(?<![\\d.])(?:10\\.\\d{1,3}|192\\.168|172\\.(?:1[6-9]|2\\d|3[01])|169\\.254)\\.\\d{1,3}\\.\\d{1,3}(?!\\.?\\d)"
|
"(?<![\\d.])(?:10\\.\\d{1,3}|192\\.168|172\\.(?:1[6-9]|2\\d|3[01])|169\\.254)\\.\\d{1,3}\\.\\d{1,3}(?!\\.?\\d)"
|
||||||
)
|
)
|
||||||
|
|
||||||
fun scrubTo(
|
fun scrubTo(src: java.io.File, out: java.io.Writer) {
|
||||||
src: java.io.File,
|
src.forEachLine { line -> out.write(redact(line)); out.write("\n") }
|
||||||
out: java.io.Writer,
|
}
|
||||||
shouldStop: () -> Boolean = { false },
|
|
||||||
): Boolean = scrubLines(src, out, ::redact, shouldStop)
|
|
||||||
|
|
||||||
fun redactForShare(line: String): String {
|
fun redactForShare(line: String): String {
|
||||||
if (line.isEmpty()) return line
|
if (line.isEmpty()) return line
|
||||||
if (line.length > MAX_LINE_LENGTH) return OVERSIZED_LINE
|
|
||||||
return try {
|
return try {
|
||||||
val out = SecretScrub.scrub(redact(line), SecretScrub.Urls.KEEP_PATH, "<redacted:token>")
|
val out = SecretScrub.scrub(redact(line), SecretScrub.Urls.KEEP_PATH, "<redacted:token>")
|
||||||
replaceMatches(out, LAN_IPV4, "<lan-address>")
|
LAN_IPV4.replace(out, "<lan-address>")
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
"<redaction failed; line withheld>"
|
"<redaction failed; line withheld>"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun scrubForShare(
|
private const val SHARE_LINE_MAX = 64 * 1024
|
||||||
src: java.io.File,
|
|
||||||
out: java.io.Writer,
|
fun scrubForShare(src: java.io.File, out: java.io.Writer) {
|
||||||
shouldStop: () -> Boolean = { false },
|
|
||||||
): Boolean {
|
|
||||||
src.inputStream().buffered().use { input ->
|
src.inputStream().buffered().use { input ->
|
||||||
input.mark(2)
|
input.mark(2)
|
||||||
val first = input.read()
|
val first = input.read()
|
||||||
@@ -278,30 +191,27 @@ object LogRedactor {
|
|||||||
input.reset()
|
input.reset()
|
||||||
if ((first == 0xff && second == 0xfe) || (first == 0xfe && second == 0xff)) {
|
if ((first == 0xff && second == 0xfe) || (first == 0xfe && second == 0xff)) {
|
||||||
out.write("<unsupported encoding; file withheld>\n")
|
out.write("<unsupported encoding; file withheld>\n")
|
||||||
return true
|
return
|
||||||
}
|
}
|
||||||
val decoder = Charsets.UTF_8.newDecoder()
|
val decoder = Charsets.UTF_8.newDecoder()
|
||||||
.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
|
.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
|
||||||
.onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT)
|
.onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT)
|
||||||
java.io.InputStreamReader(input, decoder).use { reader ->
|
java.io.InputStreamReader(input, decoder).use { reader ->
|
||||||
val buffer = CharArray(8192)
|
val buffer = CharArray(8192)
|
||||||
val line = StringBuilder(4096)
|
val line = StringBuilder()
|
||||||
var withheld: String? = null
|
var withheld = false
|
||||||
var afterCr = false
|
var afterCr = false
|
||||||
fun emit() {
|
fun emit() {
|
||||||
out.write(withheld ?: redactForShare(line.toString()))
|
out.write(if (withheld) "<unsupported or oversized line withheld>" else redactForShare(line.toString()))
|
||||||
out.write("\n")
|
out.write("\n")
|
||||||
line.setLength(0)
|
line.setLength(0)
|
||||||
withheld = null
|
withheld = false
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
while (true) {
|
while (true) {
|
||||||
if (shouldStop()) return false
|
|
||||||
val size = reader.read(buffer)
|
val size = reader.read(buffer)
|
||||||
if (size < 0) break
|
if (size < 0) break
|
||||||
if (shouldStop()) return false
|
|
||||||
for (i in 0 until size) {
|
for (i in 0 until size) {
|
||||||
if (shouldStop()) return false
|
|
||||||
val ch = buffer[i]
|
val ch = buffer[i]
|
||||||
if (afterCr) {
|
if (afterCr) {
|
||||||
afterCr = false
|
afterCr = false
|
||||||
@@ -310,79 +220,23 @@ object LogRedactor {
|
|||||||
if (ch == '\r' || ch == '\n') {
|
if (ch == '\r' || ch == '\n') {
|
||||||
emit()
|
emit()
|
||||||
afterCr = ch == '\r'
|
afterCr = ch == '\r'
|
||||||
} else if (withheld == null) {
|
} else if (!withheld) {
|
||||||
if (ch == '\u0000' || line.length == MAX_LINE_LENGTH) {
|
// Splitting a line can separate a credential from its label.
|
||||||
withheld = if (ch == '\u0000') "<unsupported or oversized line withheld>" else OVERSIZED_LINE
|
if (ch == '\u0000' || line.length == SHARE_LINE_MAX) {
|
||||||
|
withheld = true
|
||||||
line.setLength(0)
|
line.setLength(0)
|
||||||
} else line.append(ch)
|
} else {
|
||||||
|
line.append(ch)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (withheld != null || line.isNotEmpty()) emit()
|
if (withheld || line.isNotEmpty()) emit()
|
||||||
} catch (_: java.nio.charset.CharacterCodingException) {
|
} catch (_: java.nio.charset.CharacterCodingException) {
|
||||||
out.write("<unsupported encoding; file withheld>\n")
|
out.write("<unsupported encoding; file withheld>\n")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private fun scrubLines(
|
|
||||||
src: java.io.File,
|
|
||||||
out: java.io.Writer,
|
|
||||||
scrub: (String) -> String,
|
|
||||||
shouldStop: () -> Boolean,
|
|
||||||
): Boolean {
|
|
||||||
src.bufferedReader().use { input ->
|
|
||||||
val chunk = CharArray(8192)
|
|
||||||
val line = StringBuilder(4096)
|
|
||||||
var oversized = false
|
|
||||||
var pendingContent = false
|
|
||||||
var pendingCarriageReturn = false
|
|
||||||
|
|
||||||
fun emit() {
|
|
||||||
out.write(if (oversized) OVERSIZED_LINE else scrub(line.toString()))
|
|
||||||
out.write("\n")
|
|
||||||
line.setLength(0)
|
|
||||||
oversized = false
|
|
||||||
pendingContent = false
|
|
||||||
}
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
if (shouldStop()) return false
|
|
||||||
val count = input.read(chunk)
|
|
||||||
if (count < 0) break
|
|
||||||
if (shouldStop()) return false
|
|
||||||
for (i in 0 until count) {
|
|
||||||
val char = chunk[i]
|
|
||||||
if (pendingCarriageReturn) {
|
|
||||||
emit()
|
|
||||||
pendingCarriageReturn = false
|
|
||||||
if (char == '\n') continue
|
|
||||||
}
|
|
||||||
when (char) {
|
|
||||||
'\r' -> pendingCarriageReturn = true
|
|
||||||
'\n' -> emit()
|
|
||||||
else -> {
|
|
||||||
pendingContent = true
|
|
||||||
if (!oversized) {
|
|
||||||
if (line.length < MAX_LINE_LENGTH) line.append(char)
|
|
||||||
else {
|
|
||||||
line.setLength(0)
|
|
||||||
oversized = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (pendingCarriageReturn || pendingContent) {
|
|
||||||
if (shouldStop()) return false
|
|
||||||
emit()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun quoted(value: String): String {
|
private fun quoted(value: String): String {
|
||||||
@@ -424,51 +278,43 @@ object LogRedactor {
|
|||||||
|
|
||||||
fun redact(line: String): String {
|
fun redact(line: String): String {
|
||||||
if (line.isEmpty()) return line
|
if (line.isEmpty()) return line
|
||||||
if (line.length > MAX_LINE_LENGTH) return OVERSIZED_LINE
|
|
||||||
return try {
|
return try {
|
||||||
val out = Line(line)
|
val out = Line(line)
|
||||||
if (out.has("mac")) out.set(replaceMatches(out.text, MAC_FIELD) { "${it.group(1)}<redacted:mac>" })
|
if (out.has("mac")) out.set(MAC_FIELD.replace(out.text) { "${it.groupValues[1]}<redacted:mac>" })
|
||||||
if (out.holds(':', 5) || out.holds('-', 5)) out.set(replaceMatches(out.text, MAC, "<redacted:mac>"))
|
if (out.holds(':', 5) || out.holds('-', 5)) out.set(MAC.replace(out.text, "<redacted:mac>"))
|
||||||
if (out.has("serial", "android")) out.set(replaceMatches(out.text, DEVICE_IDENTIFIER) {
|
if (out.has("serial", "android")) out.set(DEVICE_IDENTIFIER.replace(out.text) {
|
||||||
val value = it.group(2)
|
val value = it.groupValues[2]
|
||||||
val quote = value.first().takeIf { char -> char == '\"' || char == '\'' }?.toString().orEmpty()
|
val quote = value.first().takeIf { char -> char == '\"' || char == '\'' }?.toString().orEmpty()
|
||||||
"${it.group(1)}${quote}<redacted:serial>${quote}"
|
"${it.groupValues[1]}${quote}<redacted:serial>${quote}"
|
||||||
})
|
})
|
||||||
if (out.holds('-', 4)) out.set(replaceMatches(out.text, GUID, "<redacted:guid>"))
|
if (out.holds('-', 4)) out.set(GUID.replace(out.text, "<redacted:guid>"))
|
||||||
if (out.has("jwt")) out.set(replaceMatches(out.text, JWT_LABELLED) { "${it.group(1)}<redacted:jwt>" })
|
if (out.has("jwt")) out.set(JWT_LABELLED.replace(out.text) { "${it.groupValues[1]}<redacted:jwt>" })
|
||||||
if ("ey" in out.text) out.set(replaceMatches(out.text, JWT_BASE64, "<redacted:jwt>"))
|
if ("ey" in out.text) out.set(JWT_BASE64.replace(out.text, "<redacted:jwt>"))
|
||||||
if (out.has("token", "auth", "ticket", "sessionid", "steamloginsecure", "api", "machine", "pass", "pwd", "secret")) {
|
if (out.has("token", "auth", "ticket", "sessionid", "steamloginsecure", "api", "machine", "pass", "pwd", "secret")) {
|
||||||
out.set(replaceMatches(out.text, SECRET_KV) {
|
out.set(SECRET_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}<redacted:token>" })
|
||||||
val quote = it.group(2).orEmpty()
|
|
||||||
"${it.group(1)}${quote}<redacted:token>${quote}"
|
|
||||||
})
|
|
||||||
|
|
||||||
}
|
}
|
||||||
if (out.has("guard", "factor", "2fa")) out.set(replaceMatches(out.text, GUARD_CODE) { "${it.group(1)}<redacted:code>" })
|
if (out.has("guard", "factor", "2fa")) out.set(GUARD_CODE.replace(out.text) { "${it.groupValues[1]}<redacted:code>" })
|
||||||
if (out.hasRun(32, ::isHex)) out.set(replaceMatches(out.text, WEBAPI_KEY, "<redacted:key>"))
|
if (out.hasRun(32, ::isHex)) out.set(WEBAPI_KEY.replace(out.text, "<redacted:key>"))
|
||||||
if ("76561" in out.text) out.set(replaceMatches(out.text, STEAMID64) { "${it.group(1)}********${it.group(3)}" })
|
if ("76561" in out.text) out.set(STEAMID64.replace(out.text) { "${it.groupValues[1]}********${it.groupValues[3]}" })
|
||||||
if ("[U:1:" in out.text) out.set(replaceMatches(out.text, STEAMID3) { m ->
|
if ("[U:1:" in out.text) out.set(STEAMID3.replace(out.text) { m ->
|
||||||
val id = m.group(1)
|
val id = m.groupValues[1]
|
||||||
"[U:1:${if (id.length > 4) "*".repeat(id.length - 4) + id.takeLast(4) else id}]"
|
"[U:1:${if (id.length > 4) "*".repeat(id.length - 4) + id.takeLast(4) else id}]"
|
||||||
})
|
})
|
||||||
if (out.has("external")) out.set(replaceMatches(out.text, EXTERNAL_ADDR) { "${it.group(1)}<redacted:ip>" })
|
if (out.has("external")) out.set(EXTERNAL_ADDR.replace(out.text) { "${it.groupValues[1]}<redacted:ip>" })
|
||||||
for (r in own) if (r.needs == null || out.has(r.needs)) out.set(replaceMatches(out.text, r.regex, "<redacted:ip>"))
|
for (r in own) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "<redacted:ip>"))
|
||||||
if (out.has("onloginstatechange")) out.set(replaceMatches(out.text, LOGIN_STATE) { "${it.group(1)}<redacted:account>" })
|
if (out.has("onloginstatechange")) out.set(LOGIN_STATE.replace(out.text) { "${it.groupValues[1]}<redacted:account>" })
|
||||||
if ("OnLoginUsersChanged " in out.text) out.set(replaceMatches(out.text, LOGIN_USERS) { "${it.group(1)}<redacted:account>" })
|
if ("OnLoginUsersChanged " in out.text) out.set(LOGIN_USERS.replace(out.text) { "${it.groupValues[1]}<redacted:account>" })
|
||||||
if (out.has("account", "user")) {
|
if (out.has("account", "user")) {
|
||||||
out.set(replaceMatches(out.text, ACCOUNT_KV) { "${it.group(1)}${it.group(2)}${quoted(it.group(3))}" })
|
out.set(ACCOUNT_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" })
|
||||||
}
|
}
|
||||||
if (out.has("login")) out.set(replaceMatches(out.text, LOGIN_KV) { "${it.group(1)}${it.group(2)}${quoted(it.group(3))}" })
|
if (out.has("login")) out.set(LOGIN_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" })
|
||||||
for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(replaceMatches(out.text, r.regex, "<redacted:account>"))
|
for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "<redacted:account>"))
|
||||||
if ('@' in out.text) out.set(replaceMatches(out.text, EMAIL) { m ->
|
if ('@' in out.text) out.set(EMAIL.replace(out.text, "<redacted:email>"))
|
||||||
m.group().takeIf { isHidlLoaderDiagnostic(out.text, m) } ?: "<redacted:email>"
|
|
||||||
|
|
||||||
})
|
|
||||||
if (out.has("jwt", "token", "ticket", "sessionid", "steamloginsecure", "machineauth")) {
|
if (out.has("jwt", "token", "ticket", "sessionid", "steamloginsecure", "machineauth")) {
|
||||||
out.set(replaceMatches(out.text, RESIDUAL) { "${it.group(1)}=<redacted:token>" })
|
out.set(RESIDUAL.replace(out.text) { "${it.groupValues[1]}=<redacted:token>" })
|
||||||
}
|
}
|
||||||
if (out.hasRun(88) { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '_' || it == '-' }) {
|
if (out.hasRun(88) { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '_' || it == '-' }) {
|
||||||
out.set(replaceMatches(out.text, LONG_TOKEN, "<redacted:token>"))
|
out.set(LONG_TOKEN.replace(out.text, "<redacted:token>"))
|
||||||
}
|
}
|
||||||
out.text
|
out.text
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
|
|||||||
@@ -60,14 +60,14 @@ object PhantomProcessLimit {
|
|||||||
if (usesDeviceConfig(sdk)) {
|
if (usesDeviceConfig(sdk)) {
|
||||||
val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false)
|
val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false)
|
||||||
val global = try {
|
val global = try {
|
||||||
GlobalSettings.read(context, SETTING)
|
Settings.Global.getString(context.contentResolver, SETTING)
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
return android12Status(off, global, systemProperty(OVERRIDE_PROPERTY))
|
return android12Status(off, global, systemProperty(OVERRIDE_PROPERTY))
|
||||||
}
|
}
|
||||||
val global = try {
|
val global = try {
|
||||||
GlobalSettings.read(context, SETTING)
|
Settings.Global.getString(context.contentResolver, SETTING)
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
return PhantomProcessStatus.UNREADABLE
|
return PhantomProcessStatus.UNREADABLE
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,72 +0,0 @@
|
|||||||
package com.droiddeck.launcher.core
|
|
||||||
|
|
||||||
import android.accessibilityservice.AccessibilityServiceInfo
|
|
||||||
import android.content.ComponentName
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import android.net.Uri
|
|
||||||
import android.provider.Settings
|
|
||||||
import android.view.accessibility.AccessibilityManager
|
|
||||||
import com.droiddeck.launcher.HomeApp
|
|
||||||
import com.droiddeck.launcher.input.HomeButtonService
|
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
|
||||||
|
|
||||||
object SteamIntegration {
|
|
||||||
const val ACTION_SETUP = "com.droiddeck.launcher.STEAM_INTEGRATION"
|
|
||||||
const val EXTRA_FEATURE = "integration_feature"
|
|
||||||
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
|
|
||||||
|
|
||||||
data class State(
|
|
||||||
val wifi: Boolean = false,
|
|
||||||
val locationPermission: Boolean = false,
|
|
||||||
val locationOn: Boolean = false,
|
|
||||||
val locationBlocked: Boolean = false,
|
|
||||||
val brightness: Boolean = false,
|
|
||||||
val home: Boolean = false,
|
|
||||||
val shortcuts: Boolean = false,
|
|
||||||
val shortcutsRestricted: Boolean = false,
|
|
||||||
val shortcutsTried: Boolean = false,
|
|
||||||
val suggested: Boolean = true,
|
|
||||||
)
|
|
||||||
|
|
||||||
fun read(context: Context) = State(
|
|
||||||
wifi = SessionPrefs.wifiDiscoveryEnabled(context),
|
|
||||||
locationPermission = WifiDiscovery.permissionGranted(context),
|
|
||||||
locationOn = WifiDiscovery.locationEnabled(context),
|
|
||||||
brightness = Settings.System.canWrite(context),
|
|
||||||
home = HomeApp.isDefault(context),
|
|
||||||
shortcuts = context.getSystemService(AccessibilityManager::class.java)
|
|
||||||
.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK).any {
|
|
||||||
val service = it.resolveInfo.serviceInfo
|
|
||||||
ComponentName(service.packageName, service.name) == ComponentName(context, HomeButtonService::class.java)
|
|
||||||
},
|
|
||||||
shortcutsRestricted = restrictedSettings(context),
|
|
||||||
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
|
|
||||||
)
|
|
||||||
|
|
||||||
// Android 13+ blocks accessibility services for sideloaded APKs until the user allows restricted settings in App info.
|
|
||||||
// MODE_DEFAULT is inconclusive on Android 15, so only an explicit denial counts here.
|
|
||||||
private fun restrictedSettings(context: Context): Boolean {
|
|
||||||
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
|
|
||||||
val mode = runCatching {
|
|
||||||
context.getSystemService(android.app.AppOpsManager::class.java)
|
|
||||||
.unsafeCheckOpNoThrow("android:access_restricted_settings", android.os.Process.myUid(), context.packageName)
|
|
||||||
}.getOrDefault(android.app.AppOpsManager.MODE_ALLOWED)
|
|
||||||
return mode == android.app.AppOpsManager.MODE_ERRORED || mode == android.app.AppOpsManager.MODE_IGNORED
|
|
||||||
}
|
|
||||||
|
|
||||||
fun dismissSuggestion(context: Context) {
|
|
||||||
SessionPrefs.sessionPrefs(context).edit().putBoolean("steam_integration_seen", true).apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun brightnessSettings(context: Context) = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
|
|
||||||
Uri.parse("package:${context.packageName}"))
|
|
||||||
|
|
||||||
// ACCESSIBILITY_DETAILS_SETTINGS is restricted to system apps; the fragment args key highlights our entry in the list.
|
|
||||||
fun shortcutSettings(context: Context): Intent {
|
|
||||||
val service = ComponentName(context, HomeButtonService::class.java).flattenToString()
|
|
||||||
return Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
|
||||||
.putExtra(":settings:fragment_args_key", service)
|
|
||||||
.putExtra(":settings:show_fragment_args", android.os.Bundle().apply { putString(":settings:fragment_args_key", service) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -182,47 +182,25 @@ object WirelessAdbFix {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun setUsingSavedPairing(context: Context, enabled: Boolean) {
|
fun setUsingSavedPairing(context: Context, enabled: Boolean) {
|
||||||
withSavedPairing(context) { appContext, host, port -> setChildProcessLimit(appContext, host, port, enabled) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun hasSavedPairing(context: Context): Boolean = savedConnection(context.applicationContext) != null
|
|
||||||
|
|
||||||
fun clearCachedApps(context: Context) {
|
|
||||||
shell(context, "am kill-all")
|
|
||||||
}
|
|
||||||
|
|
||||||
fun shell(context: Context, command: String): String {
|
|
||||||
var output = ""
|
|
||||||
withSavedPairing(context) { appContext, host, port ->
|
|
||||||
loadOrCreateIdentity(appContext)
|
|
||||||
Kadb.create(host, port).use { adb ->
|
|
||||||
val result = adb.shell(command)
|
|
||||||
check(result.exitCode == 0) { result.allOutput.ifBlank { appContext.getString(R.string.adbfix_command_failed, result.exitCode) } }
|
|
||||||
output = result.output
|
|
||||||
}
|
|
||||||
saveConnection(appContext, host, port)
|
|
||||||
}
|
|
||||||
return output
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun withSavedPairing(context: Context, action: (Context, String, Int) -> Unit) {
|
|
||||||
val appContext = context.applicationContext
|
val appContext = context.applicationContext
|
||||||
val saved = savedConnection(appContext)
|
val saved = savedConnection(appContext)
|
||||||
?: error(appContext.getString(R.string.adbfix_no_pairing))
|
?: error(appContext.getString(R.string.adbfix_no_pairing))
|
||||||
val cachedPort = saved.port
|
val cachedPort = saved.port
|
||||||
if (cachedPort != null) {
|
if (cachedPort != null) {
|
||||||
val cachedResult = runCatching { action(appContext, saved.host, cachedPort) }
|
val cachedResult = runCatching {
|
||||||
|
setChildProcessLimit(appContext, saved.host, cachedPort, enabled)
|
||||||
|
}
|
||||||
if (cachedResult.isSuccess) return
|
if (cachedResult.isSuccess) return
|
||||||
val discoveredPort = findConnectPort(appContext, saved.host)
|
val discoveredPort = findConnectPort(appContext, saved.host)
|
||||||
if (discoveredPort != null && discoveredPort != cachedPort) {
|
if (discoveredPort != null && discoveredPort != cachedPort) {
|
||||||
action(appContext, saved.host, discoveredPort)
|
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
|
||||||
} else {
|
} else {
|
||||||
cachedResult.getOrThrow()
|
cachedResult.getOrThrow()
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
val discoveredPort = findConnectPort(appContext, saved.host)
|
val discoveredPort = findConnectPort(appContext, saved.host)
|
||||||
?: error(appContext.getString(R.string.adbfix_enter_address))
|
?: error(appContext.getString(R.string.adbfix_enter_address))
|
||||||
action(appContext, saved.host, discoveredPort)
|
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,7 +14,7 @@ import android.os.Build
|
|||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.IBinder
|
import android.os.IBinder
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
import com.droiddeck.launcher.FrontEndActivity
|
import com.droiddeck.launcher.MainActivity
|
||||||
import com.droiddeck.launcher.R
|
import com.droiddeck.launcher.R
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
@@ -184,15 +184,12 @@ class WirelessAdbPairingService : Service() {
|
|||||||
setSound(null, null)
|
setSound(null, null)
|
||||||
enableVibration(false)
|
enableVibration(false)
|
||||||
})
|
})
|
||||||
manager?.createNotificationChannel(NotificationChannel(PROGRESS_CHANNEL_ID, getString(R.string.adbpair_progress_channel_name),
|
|
||||||
NotificationManager.IMPORTANCE_LOW).apply { setShowBadge(false) })
|
|
||||||
val open = PendingIntent.getActivity(this, 0,
|
val open = PendingIntent.getActivity(this, 0,
|
||||||
Intent(this, FrontEndActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
|
Intent(this, MainActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
|
||||||
PendingIntent.FLAG_IMMUTABLE)
|
PendingIntent.FLAG_IMMUTABLE)
|
||||||
val cancel = PendingIntent.getService(this, 1,
|
val cancel = PendingIntent.getService(this, 1,
|
||||||
Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE)
|
Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE)
|
||||||
val quiet = stage == Stage.Waiting || stage == Stage.Idle || stage is Stage.Working
|
val builder = Notification.Builder(this, CHANNEL_ID)
|
||||||
val builder = Notification.Builder(this, if (quiet) PROGRESS_CHANNEL_ID else CHANNEL_ID)
|
|
||||||
.setSmallIcon(R.drawable.ic_stat_session)
|
.setSmallIcon(R.drawable.ic_stat_session)
|
||||||
.setContentIntent(open)
|
.setContentIntent(open)
|
||||||
.setShowWhen(false)
|
.setShowWhen(false)
|
||||||
@@ -242,7 +239,6 @@ class WirelessAdbPairingService : Service() {
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val CHANNEL_ID = "wireless-adb-pairing"
|
private const val CHANNEL_ID = "wireless-adb-pairing"
|
||||||
private const val PROGRESS_CHANNEL_ID = "wireless-adb-pairing-progress"
|
|
||||||
private const val NOTIFICATION_ID = 3
|
private const val NOTIFICATION_ID = 3
|
||||||
private const val PAIRING_TYPE = "_adb-tls-pairing._tcp"
|
private const val PAIRING_TYPE = "_adb-tls-pairing._tcp"
|
||||||
private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
|
private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
|
||||||
|
|||||||
@@ -1,10 +1,26 @@
|
|||||||
package com.droiddeck.launcher.core
|
package com.droiddeck.launcher.core
|
||||||
|
|
||||||
|
import android.app.ActivityManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.Build
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
object ZramSupport {
|
object ZramSupport {
|
||||||
|
private const val GIB = 1L shl 30
|
||||||
|
|
||||||
fun supported(): Boolean = kernelAtLeast(System.getProperty("os.version").orEmpty(), 5, 4) && swapTotalKb() > 0
|
fun supported(): Boolean = kernelAtLeast(System.getProperty("os.version").orEmpty(), 5, 4) && swapTotalKb() > 0
|
||||||
|
|
||||||
|
fun recommended(context: Context): Boolean {
|
||||||
|
if (!supported()) return false
|
||||||
|
val memory = ActivityManager.MemoryInfo()
|
||||||
|
context.getSystemService(ActivityManager::class.java).getMemoryInfo(memory)
|
||||||
|
val advertised = if (Build.VERSION.SDK_INT >= 34) memory.advertisedMem else 0L
|
||||||
|
return belowTwelveGb(advertised, memory.totalMem)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun belowTwelveGb(advertisedBytes: Long, totalBytes: Long): Boolean =
|
||||||
|
if (advertisedBytes > 0) advertisedBytes < 11 * GIB else totalBytes < 10 * GIB
|
||||||
|
|
||||||
fun kernelAtLeast(release: String, major: Int, minor: Int): Boolean {
|
fun kernelAtLeast(release: String, major: Int, minor: Int): Boolean {
|
||||||
val parts = Regex("^(\\d+)\\.(\\d+)").find(release)?.groupValues ?: return false
|
val parts = Regex("^(\\d+)\\.(\\d+)").find(release)?.groupValues ?: return false
|
||||||
val ma = parts[1].toInt()
|
val ma = parts[1].toInt()
|
||||||
|
|||||||
@@ -1,14 +1,11 @@
|
|||||||
package com.droiddeck.launcher.files
|
package com.droiddeck.launcher.files
|
||||||
|
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import com.droiddeck.launcher.ui.focusGlide
|
|
||||||
import android.content.res.Configuration
|
import android.content.res.Configuration
|
||||||
import androidx.compose.animation.core.animateDpAsState
|
import androidx.compose.animation.core.animateDpAsState
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.border
|
import androidx.compose.foundation.border
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.rememberScrollState
|
import androidx.compose.foundation.rememberScrollState
|
||||||
import androidx.compose.foundation.selection.selectable
|
|
||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
@@ -183,14 +180,14 @@ fun CollapsibleRail(
|
|||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
if (!state.portraitLocked) {
|
if (!state.portraitLocked) {
|
||||||
IconButton(onClick = state.onToggle, modifier = Modifier.size(28.dp).focusGlide(CircleShape)) {
|
IconButton(onClick = state.onToggle, modifier = Modifier.size(28.dp)) {
|
||||||
Text("‹‹", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
|
Text("‹‹", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (collapsed && !state.portraitLocked) {
|
if (collapsed && !state.portraitLocked) {
|
||||||
IconButton(onClick = state.onToggle, modifier = Modifier.fillMaxWidth().height(24.dp).focusGlide(CircleShape)) {
|
IconButton(onClick = state.onToggle, modifier = Modifier.fillMaxWidth().height(24.dp)) {
|
||||||
Text("››", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
|
Text("››", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -199,14 +196,14 @@ fun CollapsibleRail(
|
|||||||
if (collapsed) {
|
if (collapsed) {
|
||||||
Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
|
Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
|
||||||
links.forEach { link ->
|
links.forEach { link ->
|
||||||
IconButton(onClick = link.onClick, modifier = Modifier.size(32.dp).focusGlide(CircleShape)) {
|
IconButton(onClick = link.onClick, modifier = Modifier.size(32.dp)) {
|
||||||
Icon(link.icon, link.label, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
Icon(link.icon, link.label, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
links.forEach { link ->
|
links.forEach { link ->
|
||||||
TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp).focusGlide(CircleShape)) {
|
TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp)) {
|
||||||
Icon(link.icon, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(15.dp))
|
Icon(link.icon, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(15.dp))
|
||||||
Spacer(Modifier.width(6.dp))
|
Spacer(Modifier.width(6.dp))
|
||||||
Text(link.label, fontSize = 12.sp)
|
Text(link.label, fontSize = 12.sp)
|
||||||
@@ -252,11 +249,11 @@ fun CollapsibleRail(
|
|||||||
if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
|
if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
|
||||||
shape,
|
shape,
|
||||||
)
|
)
|
||||||
.focusGlide(shape).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
|
.clickable(onClick = item.onClick)
|
||||||
.padding(horizontal = if (collapsed) 2.dp else 11.dp, vertical = if (collapsed) 6.dp else 9.dp)
|
.padding(horizontal = if (collapsed) 2.dp else 11.dp, vertical = if (collapsed) 6.dp else 9.dp)
|
||||||
} else {
|
} else {
|
||||||
base
|
base
|
||||||
.focusGlide(shape).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = item.onClick)
|
.clickable(onClick = item.onClick)
|
||||||
.background(if (active) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
.background(if (active) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
||||||
.padding(horizontal = if (collapsed) 2.dp else 13.dp, vertical = if (collapsed) 7.dp else 11.dp)
|
.padding(horizontal = if (collapsed) 2.dp else 13.dp, vertical = if (collapsed) 7.dp else 11.dp)
|
||||||
}
|
}
|
||||||
@@ -340,7 +337,7 @@ fun RailTopTabs(
|
|||||||
.background(MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)),
|
.background(MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)),
|
||||||
)
|
)
|
||||||
links.forEach { link ->
|
links.forEach { link ->
|
||||||
TopTabCell(link.icon, link.label, selected = false, onClick = link.onClick, isTab = false, modifier = Modifier.weight(1f))
|
TopTabCell(link.icon, link.label, selected = false, onClick = link.onClick, modifier = Modifier.weight(1f))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -355,7 +352,6 @@ private fun TopTabCell(
|
|||||||
selected: Boolean,
|
selected: Boolean,
|
||||||
onClick: () -> Unit,
|
onClick: () -> Unit,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
isTab: Boolean = true,
|
|
||||||
) {
|
) {
|
||||||
val tint = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
|
val tint = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
Column(
|
Column(
|
||||||
@@ -363,14 +359,7 @@ private fun TopTabCell(
|
|||||||
modifier = modifier
|
modifier = modifier
|
||||||
.clip(RoundedCornerShape(9.dp))
|
.clip(RoundedCornerShape(9.dp))
|
||||||
.background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
.background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent)
|
||||||
.focusGlide(RoundedCornerShape(9.dp))
|
.clickable(onClick = onClick)
|
||||||
.then(
|
|
||||||
if (isTab) {
|
|
||||||
Modifier.selectable(selected = selected, role = androidx.compose.ui.semantics.Role.Tab, onClick = onClick)
|
|
||||||
} else {
|
|
||||||
Modifier.clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onClick)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.padding(vertical = 6.dp, horizontal = 1.dp),
|
.padding(vertical = 6.dp, horizontal = 1.dp),
|
||||||
) {
|
) {
|
||||||
Icon(icon, contentDescription = label, tint = tint, modifier = Modifier.size(20.dp))
|
Icon(icon, contentDescription = label, tint = tint, modifier = Modifier.size(20.dp))
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ class FileManagerActivity : ComponentActivity() {
|
|||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
||||||
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||||
}
|
}
|
||||||
@@ -29,7 +29,7 @@ class FileManagerActivity : ComponentActivity() {
|
|||||||
setContent {
|
setContent {
|
||||||
DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)) {
|
DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)) {
|
||||||
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
|
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
|
||||||
FileManagerScreen(initialDir = initialDir, onExit = { finish() })
|
FileManagerScreen(initialDir = initialDir)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
package com.droiddeck.launcher.files
|
package com.droiddeck.launcher.files
|
||||||
|
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import com.droiddeck.launcher.ui.focusGlide
|
|
||||||
import androidx.compose.foundation.BorderStroke
|
import androidx.compose.foundation.BorderStroke
|
||||||
import androidx.compose.foundation.Image
|
import androidx.compose.foundation.Image
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
@@ -41,7 +39,7 @@ import androidx.compose.material.icons.filled.Storage
|
|||||||
import androidx.compose.material.icons.filled.Image
|
import androidx.compose.material.icons.filled.Image
|
||||||
import androidx.compose.material3.Card
|
import androidx.compose.material3.Card
|
||||||
import androidx.compose.material3.CardDefaults
|
import androidx.compose.material3.CardDefaults
|
||||||
import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu
|
import androidx.compose.material3.DropdownMenu
|
||||||
import androidx.compose.material3.DropdownMenuItem
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
@@ -107,14 +105,12 @@ private fun FileContextMenuItems(
|
|||||||
text = { Text(stringResource(R.string.fm_select)) },
|
text = { Text(stringResource(R.string.fm_select)) },
|
||||||
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
|
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
onClick = { onDismissMenu(); onSelect() },
|
onClick = { onDismissMenu(); onSelect() },
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
MenuItemDivider()
|
MenuItemDivider()
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text(stringResource(R.string.fm_properties)) },
|
text = { Text(stringResource(R.string.fm_properties)) },
|
||||||
leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) },
|
leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
onClick = { onDismissMenu(); onProperties() },
|
onClick = { onDismissMenu(); onProperties() },
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
MenuItemDivider()
|
MenuItemDivider()
|
||||||
if (isDir) {
|
if (isDir) {
|
||||||
@@ -128,7 +124,6 @@ private fun FileContextMenuItems(
|
|||||||
)
|
)
|
||||||
},
|
},
|
||||||
onClick = { onToggleFavorite() },
|
onClick = { onToggleFavorite() },
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
MenuItemDivider()
|
MenuItemDivider()
|
||||||
}
|
}
|
||||||
@@ -136,28 +131,24 @@ private fun FileContextMenuItems(
|
|||||||
text = { Text(stringResource(R.string.fm_rename)) },
|
text = { Text(stringResource(R.string.fm_rename)) },
|
||||||
leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) },
|
leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
onClick = { onDismissMenu(); onRename() },
|
onClick = { onDismissMenu(); onRename() },
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
MenuItemDivider()
|
MenuItemDivider()
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text(stringResource(R.string.fm_copy)) },
|
text = { Text(stringResource(R.string.fm_copy)) },
|
||||||
leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) },
|
leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
onClick = { onDismissMenu(); onCopy() },
|
onClick = { onDismissMenu(); onCopy() },
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
MenuItemDivider()
|
MenuItemDivider()
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text(stringResource(R.string.fm_cut)) },
|
text = { Text(stringResource(R.string.fm_cut)) },
|
||||||
leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) },
|
leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
onClick = { onDismissMenu(); onCut() },
|
onClick = { onDismissMenu(); onCut() },
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
MenuItemDivider()
|
MenuItemDivider()
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text(stringResource(R.string.common_delete)) },
|
text = { Text(stringResource(R.string.common_delete)) },
|
||||||
leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) },
|
leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
onClick = { onDismissMenu(); onDelete() },
|
onClick = { onDismissMenu(); onDelete() },
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -202,7 +193,7 @@ internal fun FileItemRow(
|
|||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||||
.focusGlide(RoundedCornerShape(10.dp)).combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
|
.combinedClickable(
|
||||||
onClick = { if (selectionMode) onToggleSelect() else onTap() },
|
onClick = { if (selectionMode) onToggleSelect() else onTap() },
|
||||||
onLongClick = onLongPress,
|
onLongClick = onLongPress,
|
||||||
),
|
),
|
||||||
@@ -221,7 +212,7 @@ internal fun FileItemRow(
|
|||||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = if (compact) 3.dp else 8.dp),
|
modifier = Modifier.padding(horizontal = 12.dp, vertical = if (compact) 3.dp else 8.dp),
|
||||||
) {
|
) {
|
||||||
if (selectionMode) {
|
if (selectionMode) {
|
||||||
androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() }, modifier = Modifier.focusGlide())
|
androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() })
|
||||||
Spacer(Modifier.width(4.dp))
|
Spacer(Modifier.width(4.dp))
|
||||||
}
|
}
|
||||||
when {
|
when {
|
||||||
@@ -279,7 +270,7 @@ internal fun FileItemRow(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (showActions) Box {
|
if (showActions) Box {
|
||||||
IconButton(onClick = onMenu, modifier = Modifier.focusGlide(CircleShape)) {
|
IconButton(onClick = onMenu) {
|
||||||
Icon(Icons.Filled.MoreVert, stringResource(R.string.fm_actions), tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
|
Icon(Icons.Filled.MoreVert, stringResource(R.string.fm_actions), tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
|
||||||
}
|
}
|
||||||
DropdownMenu(
|
DropdownMenu(
|
||||||
@@ -311,7 +302,7 @@ internal fun ParentFolderRow(compact: Boolean = false, onTap: () -> Unit) {
|
|||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||||
.focusGlide(RoundedCornerShape(10.dp)).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onTap),
|
.clickable(onClick = onTap),
|
||||||
shape = RoundedCornerShape(10.dp),
|
shape = RoundedCornerShape(10.dp),
|
||||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
|
||||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
|
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
|
||||||
@@ -379,7 +370,6 @@ internal fun FavoritesList(
|
|||||||
TextButton(
|
TextButton(
|
||||||
onClick = onPinCurrent,
|
onClick = onPinCurrent,
|
||||||
enabled = !currentAlreadyPinned,
|
enabled = !currentAlreadyPinned,
|
||||||
modifier = Modifier.focusGlide(CircleShape),
|
|
||||||
) {
|
) {
|
||||||
Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
||||||
Spacer(Modifier.width(6.dp))
|
Spacer(Modifier.width(6.dp))
|
||||||
@@ -432,7 +422,7 @@ private fun FavoriteCard(
|
|||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||||
.focusGlide(RoundedCornerShape(10.dp)).clickable(role = androidx.compose.ui.semantics.Role.Button, onClick = onJump),
|
.clickable(onClick = onJump),
|
||||||
shape = RoundedCornerShape(10.dp),
|
shape = RoundedCornerShape(10.dp),
|
||||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
|
||||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
|
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
|
||||||
@@ -490,7 +480,7 @@ private fun FavoriteCard(
|
|||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
IconButton(onClick = onUnpin, modifier = Modifier.focusGlide(CircleShape)) {
|
IconButton(onClick = onUnpin) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.Filled.Star,
|
Icons.Filled.Star,
|
||||||
contentDescription = stringResource(R.string.fm_unpin_favorite),
|
contentDescription = stringResource(R.string.fm_unpin_favorite),
|
||||||
@@ -536,7 +526,7 @@ internal fun FileGridTile(
|
|||||||
Card(
|
Card(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.padding(4.dp)
|
.padding(4.dp)
|
||||||
.focusGlide(RoundedCornerShape(10.dp)).combinedClickable(role = androidx.compose.ui.semantics.Role.Button,
|
.combinedClickable(
|
||||||
onClick = { if (selectionMode) onToggleSelect() else onTap() },
|
onClick = { if (selectionMode) onToggleSelect() else onTap() },
|
||||||
onLongClick = onLongPress,
|
onLongClick = onLongPress,
|
||||||
),
|
),
|
||||||
@@ -580,7 +570,7 @@ internal fun FileGridTile(
|
|||||||
androidx.compose.material3.Checkbox(
|
androidx.compose.material3.Checkbox(
|
||||||
checked = selected,
|
checked = selected,
|
||||||
onCheckedChange = { onToggleSelect() },
|
onCheckedChange = { onToggleSelect() },
|
||||||
modifier = Modifier.align(Alignment.TopStart).focusGlide(),
|
modifier = Modifier.align(Alignment.TopStart),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,9 @@
|
|||||||
package com.droiddeck.launcher.files
|
package com.droiddeck.launcher.files
|
||||||
|
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import com.droiddeck.launcher.ui.focusGlide
|
|
||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
import androidx.activity.compose.BackHandler
|
import androidx.activity.compose.BackHandler
|
||||||
import androidx.compose.foundation.BorderStroke
|
import androidx.compose.foundation.BorderStroke
|
||||||
import androidx.compose.foundation.Image
|
import androidx.compose.foundation.Image
|
||||||
import androidx.compose.foundation.horizontalScroll
|
|
||||||
import androidx.compose.foundation.rememberScrollState
|
|
||||||
import android.content.res.Configuration
|
import android.content.res.Configuration
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.border
|
import androidx.compose.foundation.border
|
||||||
@@ -23,7 +19,6 @@ import androidx.compose.foundation.layout.height
|
|||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.layout.widthIn
|
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.foundation.lazy.grid.GridCells
|
import androidx.compose.foundation.lazy.grid.GridCells
|
||||||
@@ -33,8 +28,6 @@ import androidx.compose.foundation.lazy.grid.items
|
|||||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.automirrored.filled.ExitToApp
|
|
||||||
import androidx.compose.material.icons.automirrored.filled.KeyboardReturn
|
|
||||||
import androidx.compose.material.icons.filled.ArrowBack
|
import androidx.compose.material.icons.filled.ArrowBack
|
||||||
import androidx.compose.material.icons.filled.ContentPaste
|
import androidx.compose.material.icons.filled.ContentPaste
|
||||||
import androidx.compose.material.icons.filled.CreateNewFolder
|
import androidx.compose.material.icons.filled.CreateNewFolder
|
||||||
@@ -55,7 +48,7 @@ import androidx.compose.material.icons.filled.Description
|
|||||||
import androidx.compose.material.icons.filled.Image
|
import androidx.compose.material.icons.filled.Image
|
||||||
import androidx.compose.material.icons.filled.SportsEsports
|
import androidx.compose.material.icons.filled.SportsEsports
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import com.droiddeck.launcher.ui.GlideDropdownMenu as DropdownMenu
|
import androidx.compose.material3.DropdownMenu
|
||||||
import androidx.compose.material3.DropdownMenuItem
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.HorizontalDivider
|
import androidx.compose.material3.HorizontalDivider
|
||||||
@@ -75,7 +68,6 @@ import androidx.compose.runtime.LaunchedEffect
|
|||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableFloatStateOf
|
import androidx.compose.runtime.mutableFloatStateOf
|
||||||
import androidx.compose.runtime.mutableIntStateOf
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
import androidx.compose.runtime.mutableStateListOf
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
@@ -98,20 +90,12 @@ import androidx.compose.ui.unit.dp
|
|||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.ensureActive
|
import kotlinx.coroutines.ensureActive
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
|
|
||||||
private enum class FileManagerNavigation { EXIT, RETURN_TO_START, BACK, UP }
|
|
||||||
|
|
||||||
private const val HISTORY_LIMIT = 50
|
|
||||||
|
|
||||||
internal fun canNavigateUp(currentDir: File, currentRoot: File): Boolean =
|
|
||||||
currentDir != currentRoot && currentDir.parentFile?.exists() == true
|
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun FileManagerScreen(
|
fun FileManagerScreen(
|
||||||
@@ -121,7 +105,6 @@ fun FileManagerScreen(
|
|||||||
initialDir: File? = null,
|
initialDir: File? = null,
|
||||||
pickerTitle: String? = null,
|
pickerTitle: String? = null,
|
||||||
onPick: ((File) -> Unit)? = null,
|
onPick: ((File) -> Unit)? = null,
|
||||||
onExit: (() -> Unit)? = null,
|
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
@@ -135,14 +118,12 @@ fun FileManagerScreen(
|
|||||||
|
|
||||||
val pickPrefs = remember { context.getSharedPreferences("file_manager", android.content.Context.MODE_PRIVATE) }
|
val pickPrefs = remember { context.getSharedPreferences("file_manager", android.content.Context.MODE_PRIVATE) }
|
||||||
val browsePrefs = pickPrefs
|
val browsePrefs = pickPrefs
|
||||||
val rootDir = remember(initialDir) {
|
val rootDir = remember {
|
||||||
initialDir?.takeIf { it.isDirectory } ?: File("/storage/emulated/0")
|
initialDir?.takeIf { it.isDirectory } ?: File("/storage/emulated/0")
|
||||||
}
|
}
|
||||||
val launchDir = remember(initialDir, pickMode) {
|
|
||||||
initialDir?.takeIf { !pickMode }
|
|
||||||
}
|
|
||||||
var currentDir by remember { mutableStateOf(rootDir) }
|
var currentDir by remember { mutableStateOf(rootDir) }
|
||||||
val initialRoot = remember(rootDir) {
|
var currentRoot by remember {
|
||||||
val abs = rootDir.absolutePath
|
val abs = rootDir.absolutePath
|
||||||
val internal = "/storage/emulated/0"
|
val internal = "/storage/emulated/0"
|
||||||
val vol = when {
|
val vol = when {
|
||||||
@@ -158,9 +139,8 @@ fun FileManagerScreen(
|
|||||||
?: rootDir
|
?: rootDir
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
vol
|
mutableStateOf(vol)
|
||||||
}
|
}
|
||||||
var currentRoot by remember { mutableStateOf(initialRoot) }
|
|
||||||
var entries by remember { mutableStateOf(listOf<File>()) }
|
var entries by remember { mutableStateOf(listOf<File>()) }
|
||||||
var selectedEntry by remember { mutableStateOf<File?>(null) }
|
var selectedEntry by remember { mutableStateOf<File?>(null) }
|
||||||
var showMenuFor by remember { mutableStateOf<File?>(null) }
|
var showMenuFor by remember { mutableStateOf<File?>(null) }
|
||||||
@@ -171,10 +151,8 @@ fun FileManagerScreen(
|
|||||||
var pendingConflict by remember { mutableStateOf<File?>(null) }
|
var pendingConflict by remember { mutableStateOf<File?>(null) }
|
||||||
var conflictChoice by remember { mutableStateOf<ConflictChoice?>(null) }
|
var conflictChoice by remember { mutableStateOf<ConflictChoice?>(null) }
|
||||||
var conflictApplyToAll by remember { mutableStateOf(false) }
|
var conflictApplyToAll by remember { mutableStateOf(false) }
|
||||||
var operationJob by remember { mutableStateOf<Job?>(null) }
|
var operationJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
|
||||||
var cancelledJob by remember { mutableStateOf<Job?>(null) }
|
var cancelledJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
|
||||||
var pendingNavigation by remember { mutableStateOf<FileManagerNavigation?>(null) }
|
|
||||||
var cancellingNavigation by remember { mutableStateOf(false) }
|
|
||||||
var pendingBulkDelete by remember { mutableStateOf<List<File>>(emptyList()) }
|
var pendingBulkDelete by remember { mutableStateOf<List<File>>(emptyList()) }
|
||||||
var searchQuery by remember { mutableStateOf("") }
|
var searchQuery by remember { mutableStateOf("") }
|
||||||
val visibleEntries = if (searchQuery.isBlank()) entries
|
val visibleEntries = if (searchQuery.isBlank()) entries
|
||||||
@@ -200,18 +178,10 @@ fun FileManagerScreen(
|
|||||||
var showFavorites by remember { mutableStateOf(false) }
|
var showFavorites by remember { mutableStateOf(false) }
|
||||||
var favTick by remember { mutableIntStateOf(0) }
|
var favTick by remember { mutableIntStateOf(0) }
|
||||||
|
|
||||||
var listingJob by remember { mutableStateOf<Job?>(null) }
|
var listingJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
|
||||||
val history = remember { mutableStateListOf<Pair<File, File>>() }
|
|
||||||
var shownRoot by remember { mutableStateOf(initialRoot) }
|
|
||||||
|
|
||||||
fun loadDirectory(dir: File, resetScroll: Boolean = true, record: Boolean = true) {
|
fun loadDirectory(dir: File, resetScroll: Boolean = true) {
|
||||||
if (cancellingNavigation) return
|
|
||||||
if (record && dir != currentDir) {
|
|
||||||
history.add(currentDir to shownRoot)
|
|
||||||
if (history.size > HISTORY_LIMIT) history.removeAt(0)
|
|
||||||
}
|
|
||||||
currentDir = dir
|
currentDir = dir
|
||||||
shownRoot = currentRoot
|
|
||||||
if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply()
|
if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply()
|
||||||
listingJob?.cancel()
|
listingJob?.cancel()
|
||||||
listingJob = scope.launch {
|
listingJob = scope.launch {
|
||||||
@@ -235,102 +205,25 @@ fun FileManagerScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun openDrive(dir: File) {
|
fun openDrive(dir: File) {
|
||||||
if (cancellingNavigation) return
|
|
||||||
currentRoot = dir
|
currentRoot = dir
|
||||||
loadDirectory(dir)
|
loadDirectory(dir)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun returnToStart() {
|
|
||||||
if (cancellingNavigation) return
|
|
||||||
val dir = launchDir ?: return
|
|
||||||
if (!dir.isDirectory) {
|
|
||||||
Toast.makeText(context, R.string.fm_start_unavailable, Toast.LENGTH_SHORT).show()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
showFavorites = false
|
|
||||||
showSearch = false
|
|
||||||
searchQuery = ""
|
|
||||||
currentRoot = initialRoot
|
|
||||||
loadDirectory(dir)
|
|
||||||
}
|
|
||||||
|
|
||||||
LaunchedEffect(Unit) { loadDirectory(rootDir) }
|
LaunchedEffect(Unit) { loadDirectory(rootDir) }
|
||||||
|
|
||||||
val canGoUp = currentDir != currentRoot && currentDir.parentFile?.exists() == true
|
BackHandler(enabled = showFavorites || currentDir != currentRoot) {
|
||||||
fun isOperationActive() = isOperationRunning || operationJob?.isCompleted == false || cancelledJob?.isCompleted == false
|
if (showFavorites) {
|
||||||
val operationActive = isOperationActive()
|
showFavorites = false
|
||||||
|
return@BackHandler
|
||||||
fun navigate(action: FileManagerNavigation) {
|
|
||||||
if (cancellingNavigation) return
|
|
||||||
when (action) {
|
|
||||||
FileManagerNavigation.EXIT -> onExit?.invoke()
|
|
||||||
FileManagerNavigation.RETURN_TO_START -> returnToStart()
|
|
||||||
FileManagerNavigation.BACK -> {
|
|
||||||
if (showFavorites) showFavorites = false
|
|
||||||
else {
|
|
||||||
while (history.isNotEmpty() && !history.last().first.isDirectory) history.removeAt(history.lastIndex)
|
|
||||||
val previous = history.removeLastOrNull()
|
|
||||||
if (previous != null) {
|
|
||||||
currentRoot = previous.second
|
|
||||||
loadDirectory(previous.first, record = false)
|
|
||||||
} else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it, record = false) }
|
|
||||||
else onExit?.invoke()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
FileManagerNavigation.UP -> {
|
|
||||||
if (showFavorites) showFavorites = false
|
|
||||||
else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it) }
|
|
||||||
else onExit?.invoke()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
val parent = currentDir.parentFile
|
||||||
|
if (parent != null && parent.exists()) loadDirectory(parent)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun requestNavigation(action: FileManagerNavigation) {
|
val canGoUp = currentDir != currentRoot && currentDir.parentFile?.exists() == true
|
||||||
if (cancellingNavigation) return
|
fun goUp() {
|
||||||
if (isOperationActive()) pendingNavigation = action else navigate(action)
|
val parent = currentDir.parentFile
|
||||||
}
|
if (currentDir != currentRoot && parent != null && parent.exists()) loadDirectory(parent)
|
||||||
|
|
||||||
BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) {
|
|
||||||
requestNavigation(FileManagerNavigation.BACK)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (pendingNavigation != null) {
|
|
||||||
OutlinedAlertDialog(
|
|
||||||
onDismissRequest = { pendingNavigation = null },
|
|
||||||
title = { Text(stringResource(R.string.fm_cancel_operation_title)) },
|
|
||||||
text = { Text(stringResource(R.string.fm_cancel_operation_confirmation)) },
|
|
||||||
confirmButton = {
|
|
||||||
TextButton(onClick = {
|
|
||||||
val action = pendingNavigation ?: return@TextButton
|
|
||||||
pendingNavigation = null
|
|
||||||
val job = operationJob?.takeUnless(Job::isCompleted)
|
|
||||||
?: cancelledJob?.takeUnless(Job::isCompleted)
|
|
||||||
if (job == null) {
|
|
||||||
navigate(action)
|
|
||||||
} else {
|
|
||||||
cancellingNavigation = true
|
|
||||||
cancelledJob = job
|
|
||||||
job.cancel()
|
|
||||||
scope.launch {
|
|
||||||
job.join()
|
|
||||||
if (operationJob === job) operationJob = null
|
|
||||||
if (cancelledJob === job) cancelledJob = null
|
|
||||||
pendingConflict = null
|
|
||||||
isOperationRunning = false
|
|
||||||
operationDeterminate = false
|
|
||||||
cancellingNavigation = false
|
|
||||||
if (action != FileManagerNavigation.EXIT) loadDirectory(currentDir, resetScroll = false)
|
|
||||||
navigate(action)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_accept)) }
|
|
||||||
},
|
|
||||||
dismissButton = {
|
|
||||||
TextButton(onClick = { pendingNavigation = null }, modifier = Modifier.focusGlide(CircleShape)) {
|
|
||||||
Text(stringResource(R.string.fm_decline))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun uniqueDestination(dir: File, name: String): File {
|
fun uniqueDestination(dir: File, name: String): File {
|
||||||
@@ -348,14 +241,11 @@ fun FileManagerScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun performDelete(file: File) {
|
fun performDelete(file: File) {
|
||||||
if (isOperationActive()) return
|
scope.launch {
|
||||||
operationJob = scope.launch {
|
|
||||||
isOperationRunning = true
|
isOperationRunning = true
|
||||||
operationLabel = context.getString(R.string.fm_op_deleting)
|
operationLabel = context.getString(R.string.fm_op_deleting)
|
||||||
val job = coroutineContext[Job]
|
val ok = withContext(Dispatchers.IO) { FileOps.delete(file) }
|
||||||
val ok = withContext(Dispatchers.IO) { FileOps.delete(file) { job?.isActive == false } }
|
|
||||||
isOperationRunning = false
|
isOperationRunning = false
|
||||||
if (operationJob === job) operationJob = null
|
|
||||||
loadDirectory(currentDir, resetScroll = false)
|
loadDirectory(currentDir, resetScroll = false)
|
||||||
if (!ok) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_SHORT).show()
|
if (!ok) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
@@ -370,7 +260,7 @@ fun FileManagerScreen(
|
|||||||
|
|
||||||
fun performPaste() {
|
fun performPaste() {
|
||||||
val sources = clipboardFiles
|
val sources = clipboardFiles
|
||||||
if (sources.isEmpty() || isOperationActive()) return
|
if (sources.isEmpty() || isOperationRunning || operationJob?.isActive == true || cancelledJob?.isCompleted == false) return
|
||||||
val dstDir = currentDir
|
val dstDir = currentDir
|
||||||
val cut = isCutOperation
|
val cut = isCutOperation
|
||||||
|
|
||||||
@@ -379,7 +269,7 @@ fun FileManagerScreen(
|
|||||||
operationDeterminate = true
|
operationDeterminate = true
|
||||||
operationLabel = context.getString(if (cut) R.string.fm_op_moving else R.string.fm_op_copying)
|
operationLabel = context.getString(if (cut) R.string.fm_op_moving else R.string.fm_op_copying)
|
||||||
isOperationRunning = true
|
isOperationRunning = true
|
||||||
val job = coroutineContext[Job]
|
val job = coroutineContext[kotlinx.coroutines.Job]
|
||||||
|
|
||||||
var applyToAll: ConflictChoice? = null
|
var applyToAll: ConflictChoice? = null
|
||||||
var failed = 0
|
var failed = 0
|
||||||
@@ -432,7 +322,7 @@ fun FileManagerScreen(
|
|||||||
|
|
||||||
isOperationRunning = false
|
isOperationRunning = false
|
||||||
operationDeterminate = false
|
operationDeterminate = false
|
||||||
if (operationJob === job) operationJob = null
|
operationJob = null
|
||||||
clipboardFiles = emptyList()
|
clipboardFiles = emptyList()
|
||||||
isCutOperation = false
|
isCutOperation = false
|
||||||
selectionMode = false
|
selectionMode = false
|
||||||
@@ -450,38 +340,32 @@ fun FileManagerScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun performRename(file: File, newName: String) {
|
fun performRename(file: File, newName: String) {
|
||||||
if (isOperationActive()) return
|
|
||||||
val target = File(file.parentFile, newName)
|
val target = File(file.parentFile, newName)
|
||||||
if (target.exists()) {
|
if (target.exists()) {
|
||||||
Toast.makeText(context, context.getString(R.string.fm_already_exists, newName), Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, context.getString(R.string.fm_already_exists, newName), Toast.LENGTH_SHORT).show()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
operationJob = scope.launch {
|
scope.launch {
|
||||||
val job = coroutineContext[Job]
|
|
||||||
isOperationRunning = true
|
isOperationRunning = true
|
||||||
operationLabel = context.getString(R.string.fm_op_renaming)
|
operationLabel = context.getString(R.string.fm_op_renaming)
|
||||||
val ok = withContext(Dispatchers.IO) { file.renameTo(target) }
|
val ok = withContext(Dispatchers.IO) { file.renameTo(target) }
|
||||||
isOperationRunning = false
|
isOperationRunning = false
|
||||||
if (operationJob === job) operationJob = null
|
|
||||||
loadDirectory(currentDir, resetScroll = false)
|
loadDirectory(currentDir, resetScroll = false)
|
||||||
if (!ok) Toast.makeText(context, R.string.fm_rename_failed, Toast.LENGTH_SHORT).show()
|
if (!ok) Toast.makeText(context, R.string.fm_rename_failed, Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun createFolder(parent: File, name: String) {
|
fun createFolder(parent: File, name: String) {
|
||||||
if (isOperationActive()) return
|
|
||||||
val target = File(parent, name)
|
val target = File(parent, name)
|
||||||
if (target.exists()) {
|
if (target.exists()) {
|
||||||
Toast.makeText(context, context.getString(R.string.fm_already_exists, name), Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, context.getString(R.string.fm_already_exists, name), Toast.LENGTH_SHORT).show()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
operationJob = scope.launch {
|
scope.launch {
|
||||||
val job = coroutineContext[Job]
|
|
||||||
isOperationRunning = true
|
isOperationRunning = true
|
||||||
operationLabel = context.getString(R.string.fm_op_creating_folder)
|
operationLabel = context.getString(R.string.fm_op_creating_folder)
|
||||||
val ok = withContext(Dispatchers.IO) { target.mkdirs() }
|
val ok = withContext(Dispatchers.IO) { target.mkdirs() }
|
||||||
isOperationRunning = false
|
isOperationRunning = false
|
||||||
if (operationJob === job) operationJob = null
|
|
||||||
loadDirectory(currentDir, resetScroll = false)
|
loadDirectory(currentDir, resetScroll = false)
|
||||||
if (!ok) Toast.makeText(context, R.string.fm_create_folder_failed, Toast.LENGTH_SHORT).show()
|
if (!ok) Toast.makeText(context, R.string.fm_create_folder_failed, Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
@@ -514,16 +398,15 @@ fun FileManagerScreen(
|
|||||||
onValueChange = { folderName = it },
|
onValueChange = { folderName = it },
|
||||||
label = { Text(stringResource(R.string.fm_folder_name)) },
|
label = { Text(stringResource(R.string.fm_folder_name)) },
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
confirmButton = {
|
confirmButton = {
|
||||||
TextButton(onClick = {
|
TextButton(onClick = {
|
||||||
showNewFolderDialog = false
|
showNewFolderDialog = false
|
||||||
if (folderName.isNotBlank()) createFolder(currentDir, folderName)
|
if (folderName.isNotBlank()) createFolder(currentDir, folderName)
|
||||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_create)) }
|
}) { Text(stringResource(R.string.fm_create)) }
|
||||||
},
|
},
|
||||||
dismissButton = { TextButton(onClick = { showNewFolderDialog = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
dismissButton = { TextButton(onClick = { showNewFolderDialog = false }) { Text(stringResource(R.string.common_cancel)) } },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -538,7 +421,6 @@ fun FileManagerScreen(
|
|||||||
onValueChange = { newName = it },
|
onValueChange = { newName = it },
|
||||||
label = { Text(stringResource(R.string.fm_new_name)) },
|
label = { Text(stringResource(R.string.fm_new_name)) },
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
confirmButton = {
|
confirmButton = {
|
||||||
@@ -546,9 +428,9 @@ fun FileManagerScreen(
|
|||||||
val file = renameTarget
|
val file = renameTarget
|
||||||
renameTarget = null
|
renameTarget = null
|
||||||
if (file != null && newName.isNotBlank()) performRename(file, newName)
|
if (file != null && newName.isNotBlank()) performRename(file, newName)
|
||||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_rename)) }
|
}) { Text(stringResource(R.string.fm_rename)) }
|
||||||
},
|
},
|
||||||
dismissButton = { TextButton(onClick = { renameTarget = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
dismissButton = { TextButton(onClick = { renameTarget = null }) { Text(stringResource(R.string.common_cancel)) } },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -570,9 +452,9 @@ fun FileManagerScreen(
|
|||||||
TextButton(onClick = {
|
TextButton(onClick = {
|
||||||
selectedEntry = null
|
selectedEntry = null
|
||||||
performDelete(file)
|
performDelete(file)
|
||||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete)) }
|
}) { Text(stringResource(R.string.common_delete)) }
|
||||||
},
|
},
|
||||||
dismissButton = { TextButton(onClick = { selectedEntry = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
dismissButton = { TextButton(onClick = { selectedEntry = null }) { Text(stringResource(R.string.common_cancel)) } },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -599,28 +481,26 @@ fun FileManagerScreen(
|
|||||||
},
|
},
|
||||||
confirmButton = {
|
confirmButton = {
|
||||||
TextButton(onClick = {
|
TextButton(onClick = {
|
||||||
if (isOperationActive()) return@TextButton
|
|
||||||
pendingBulkDelete = emptyList()
|
pendingBulkDelete = emptyList()
|
||||||
selectionMode = false
|
selectionMode = false
|
||||||
selectedPaths = emptySet()
|
selectedPaths = emptySet()
|
||||||
operationJob = scope.launch {
|
operationJob = scope.launch {
|
||||||
isOperationRunning = true
|
isOperationRunning = true
|
||||||
val job = coroutineContext[Job]
|
|
||||||
var failed = 0
|
var failed = 0
|
||||||
victims.forEachIndexed { i, f ->
|
victims.forEachIndexed { i, f ->
|
||||||
operationLabel = context.getString(R.string.fm_op_deleting_batch, i + 1, victims.size, f.name)
|
operationLabel = context.getString(R.string.fm_op_deleting_batch, i + 1, victims.size, f.name)
|
||||||
if (!withContext(Dispatchers.IO) { FileOps.delete(f) { job?.isActive == false } }) failed++
|
if (!withContext(Dispatchers.IO) { FileOps.delete(f) }) failed++
|
||||||
}
|
}
|
||||||
isOperationRunning = false
|
isOperationRunning = false
|
||||||
if (operationJob === job) operationJob = null
|
operationJob = null
|
||||||
loadDirectory(currentDir, resetScroll = false)
|
loadDirectory(currentDir, resetScroll = false)
|
||||||
if (failed > 0) {
|
if (failed > 0) {
|
||||||
Toast.makeText(context, context.resources.getQuantityString(R.plurals.fm_delete_some_failed, failed, failed), Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, context.resources.getQuantityString(R.plurals.fm_delete_some_failed, failed, failed), Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) }
|
}) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error) }
|
||||||
},
|
},
|
||||||
dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }) { Text(stringResource(R.string.common_cancel)) } },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -643,7 +523,6 @@ fun FileManagerScreen(
|
|||||||
androidx.compose.material3.Checkbox(
|
androidx.compose.material3.Checkbox(
|
||||||
checked = conflictApplyToAll,
|
checked = conflictApplyToAll,
|
||||||
onCheckedChange = { conflictApplyToAll = it },
|
onCheckedChange = { conflictApplyToAll = it },
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
Text(stringResource(R.string.fm_conflict_apply_all), fontSize = 12.sp)
|
Text(stringResource(R.string.fm_conflict_apply_all), fontSize = 12.sp)
|
||||||
}
|
}
|
||||||
@@ -656,7 +535,7 @@ fun FileManagerScreen(
|
|||||||
ConflictChoice.SKIP to stringResource(R.string.fm_conflict_skip),
|
ConflictChoice.SKIP to stringResource(R.string.fm_conflict_skip),
|
||||||
).forEach { (choice, label) ->
|
).forEach { (choice, label) ->
|
||||||
TextButton(
|
TextButton(
|
||||||
modifier = Modifier.fillMaxWidth().focusGlide(CircleShape),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
onClick = { conflictChoice = choice; pendingConflict = null },
|
onClick = { conflictChoice = choice; pendingConflict = null },
|
||||||
) { Text(label, modifier = Modifier.fillMaxWidth()) }
|
) { Text(label, modifier = Modifier.fillMaxWidth()) }
|
||||||
}
|
}
|
||||||
@@ -664,14 +543,13 @@ fun FileManagerScreen(
|
|||||||
},
|
},
|
||||||
confirmButton = {},
|
confirmButton = {},
|
||||||
dismissButton = {
|
dismissButton = {
|
||||||
TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }, modifier = Modifier.focusGlide(CircleShape)) {
|
TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }) {
|
||||||
Text(stringResource(R.string.common_cancel))
|
Text(stringResource(R.string.common_cancel))
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
val compactToolbar = LocalConfiguration.current.screenWidthDp < 600
|
|
||||||
Column(modifier = Modifier.fillMaxSize()) {
|
Column(modifier = Modifier.fillMaxSize()) {
|
||||||
if (pickMode && !pickerTitle.isNullOrEmpty()) {
|
if (pickMode && !pickerTitle.isNullOrEmpty()) {
|
||||||
Text(
|
Text(
|
||||||
@@ -690,7 +568,7 @@ fun FileManagerScreen(
|
|||||||
onClick = { onPick?.invoke(currentDir) },
|
onClick = { onPick?.invoke(currentDir) },
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(horizontal = 16.dp, vertical = 8.dp).focusGlide(CircleShape),
|
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
) {
|
) {
|
||||||
Icon(Icons.Filled.Folder, null, modifier = Modifier.size(18.dp))
|
Icon(Icons.Filled.Folder, null, modifier = Modifier.size(18.dp))
|
||||||
Spacer(Modifier.width(8.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
@@ -702,10 +580,9 @@ fun FileManagerScreen(
|
|||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.background(MaterialTheme.colorScheme.surfaceContainer)
|
.background(MaterialTheme.colorScheme.surfaceContainer)
|
||||||
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier)
|
|
||||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||||
) {
|
) {
|
||||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = canGoUp && !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
|
IconButton(onClick = { goUp() }, enabled = canGoUp) {
|
||||||
Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary)
|
Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -754,7 +631,6 @@ fun FileManagerScreen(
|
|||||||
).show()
|
).show()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
linuxRoot?.let { root ->
|
linuxRoot?.let { root ->
|
||||||
@@ -765,7 +641,6 @@ fun FileManagerScreen(
|
|||||||
Icon(Icons.Filled.Terminal, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
Icon(Icons.Filled.Terminal, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
||||||
},
|
},
|
||||||
onClick = { showDriveMenu = false; openDrive(root) },
|
onClick = { showDriveMenu = false; openDrive(root) },
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -781,10 +656,10 @@ fun FileManagerScreen(
|
|||||||
fontWeight = FontWeight.SemiBold,
|
fontWeight = FontWeight.SemiBold,
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
|
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
|
||||||
if (!compactToolbar) Spacer(Modifier.weight(1f))
|
Spacer(Modifier.weight(1f))
|
||||||
} else {
|
} else {
|
||||||
Text(
|
Text(
|
||||||
text = currentDir.name.ifBlank { currentDir.absolutePath },
|
text = currentDir.name.ifBlank { currentDir.absolutePath },
|
||||||
@@ -793,24 +668,17 @@ fun FileManagerScreen(
|
|||||||
fontWeight = FontWeight.SemiBold,
|
fontWeight = FontWeight.SemiBold,
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (launchDir != null) {
|
|
||||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
|
|
||||||
Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary)
|
|
||||||
}
|
|
||||||
if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp))
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!showFavorites) {
|
if (!showFavorites) {
|
||||||
if (!pickMode) {
|
if (!pickMode) {
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
onClick = { showNewFolderDialog = true },
|
onClick = { showNewFolderDialog = true },
|
||||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)),
|
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)),
|
||||||
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp),
|
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp),
|
||||||
modifier = Modifier.height(32.dp).focusGlide(CircleShape),
|
modifier = Modifier.height(32.dp),
|
||||||
) {
|
) {
|
||||||
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
||||||
Spacer(Modifier.width(5.dp))
|
Spacer(Modifier.width(5.dp))
|
||||||
@@ -820,18 +688,18 @@ fun FileManagerScreen(
|
|||||||
IconButton(onClick = {
|
IconButton(onClick = {
|
||||||
gridView = !gridView
|
gridView = !gridView
|
||||||
browsePrefs.edit().putBoolean("fmGridView", gridView).apply()
|
browsePrefs.edit().putBoolean("fmGridView", gridView).apply()
|
||||||
}, modifier = Modifier.focusGlide(CircleShape)) {
|
}) {
|
||||||
Icon(
|
Icon(
|
||||||
if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView,
|
if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView,
|
||||||
if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view),
|
if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view),
|
||||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }, modifier = Modifier.focusGlide(CircleShape)) {
|
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }) {
|
||||||
Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
}
|
}
|
||||||
Box {
|
Box {
|
||||||
IconButton(onClick = { showSortMenu = true }, modifier = Modifier.focusGlide(CircleShape)) {
|
IconButton(onClick = { showSortMenu = true }) {
|
||||||
Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
}
|
}
|
||||||
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
|
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
|
||||||
@@ -848,7 +716,6 @@ fun FileManagerScreen(
|
|||||||
showSortMenu = false
|
showSortMenu = false
|
||||||
loadDirectory(currentDir, resetScroll = false)
|
loadDirectory(currentDir, resetScroll = false)
|
||||||
},
|
},
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
|
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
|
||||||
@@ -859,7 +726,6 @@ fun FileManagerScreen(
|
|||||||
browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply()
|
browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply()
|
||||||
showSortMenu = false
|
showSortMenu = false
|
||||||
},
|
},
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
DropdownMenuItem(
|
DropdownMenuItem(
|
||||||
text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) },
|
text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) },
|
||||||
@@ -869,24 +735,18 @@ fun FileManagerScreen(
|
|||||||
showSortMenu = false
|
showSortMenu = false
|
||||||
loadDirectory(currentDir, resetScroll = false)
|
loadDirectory(currentDir, resetScroll = false)
|
||||||
},
|
},
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
IconButton(onClick = { showFavorites = !showFavorites }, modifier = Modifier.focusGlide(CircleShape)) {
|
IconButton(onClick = { showFavorites = !showFavorites }) {
|
||||||
if (showFavorites) {
|
if (showFavorites) {
|
||||||
Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary)
|
Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary)
|
||||||
} else {
|
} else {
|
||||||
Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!pickMode && onExit != null) {
|
|
||||||
IconButton(onClick = { requestNavigation(FileManagerNavigation.EXIT) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
|
|
||||||
Icon(Icons.AutoMirrored.Filled.ExitToApp, stringResource(R.string.fm_exit), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (showSearch && !showFavorites) {
|
if (showSearch && !showFavorites) {
|
||||||
@@ -895,7 +755,7 @@ fun FileManagerScreen(
|
|||||||
onValueChange = { searchQuery = it },
|
onValueChange = { searchQuery = it },
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
placeholder = { Text(stringResource(R.string.fm_filter_folder), fontSize = 13.sp) },
|
placeholder = { Text(stringResource(R.string.fm_filter_folder), fontSize = 13.sp) },
|
||||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp).focusGlide(),
|
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -933,14 +793,13 @@ fun FileManagerScreen(
|
|||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.background(MaterialTheme.colorScheme.primary.copy(alpha = 0.12f))
|
.background(MaterialTheme.colorScheme.primary.copy(alpha = 0.12f))
|
||||||
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier)
|
|
||||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
stringResource(R.string.fm_selected_count, selectedPaths.size),
|
stringResource(R.string.fm_selected_count, selectedPaths.size),
|
||||||
color = MaterialTheme.colorScheme.onBackground,
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
fontSize = 13.sp,
|
fontSize = 13.sp,
|
||||||
modifier = if (compactToolbar) Modifier.padding(end = 12.dp) else Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
val allVisibleSelected = visibleEntries.isNotEmpty() && visibleEntries.all { it.absolutePath in selectedPaths }
|
val allVisibleSelected = visibleEntries.isNotEmpty() && visibleEntries.all { it.absolutePath in selectedPaths }
|
||||||
val anyVisibleSelected = visibleEntries.any { it.absolutePath in selectedPaths }
|
val anyVisibleSelected = visibleEntries.any { it.absolutePath in selectedPaths }
|
||||||
@@ -951,7 +810,6 @@ fun FileManagerScreen(
|
|||||||
selectedPaths = if (allVisibleSelected) selectedPaths - shown.toSet() else selectedPaths + shown
|
selectedPaths = if (allVisibleSelected) selectedPaths - shown.toSet() else selectedPaths + shown
|
||||||
},
|
},
|
||||||
contentPadding = selBarPadding,
|
contentPadding = selBarPadding,
|
||||||
modifier = Modifier.focusGlide(CircleShape),
|
|
||||||
) { Text(if (allVisibleSelected) stringResource(R.string.fm_select_none) else stringResource(R.string.fm_select_all), fontSize = 12.sp) }
|
) { Text(if (allVisibleSelected) stringResource(R.string.fm_select_none) else stringResource(R.string.fm_select_all), fontSize = 12.sp) }
|
||||||
Spacer(Modifier.width(4.dp))
|
Spacer(Modifier.width(4.dp))
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
@@ -963,7 +821,6 @@ fun FileManagerScreen(
|
|||||||
selectedPaths = emptySet()
|
selectedPaths = emptySet()
|
||||||
},
|
},
|
||||||
contentPadding = selBarPadding,
|
contentPadding = selBarPadding,
|
||||||
modifier = Modifier.focusGlide(CircleShape),
|
|
||||||
) { Text(stringResource(R.string.fm_copy), fontSize = 12.sp) }
|
) { Text(stringResource(R.string.fm_copy), fontSize = 12.sp) }
|
||||||
Spacer(Modifier.width(4.dp))
|
Spacer(Modifier.width(4.dp))
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
@@ -975,7 +832,6 @@ fun FileManagerScreen(
|
|||||||
selectedPaths = emptySet()
|
selectedPaths = emptySet()
|
||||||
},
|
},
|
||||||
contentPadding = selBarPadding,
|
contentPadding = selBarPadding,
|
||||||
modifier = Modifier.focusGlide(CircleShape),
|
|
||||||
) { Text(stringResource(R.string.fm_cut), fontSize = 12.sp) }
|
) { Text(stringResource(R.string.fm_cut), fontSize = 12.sp) }
|
||||||
Spacer(Modifier.width(4.dp))
|
Spacer(Modifier.width(4.dp))
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
@@ -983,13 +839,11 @@ fun FileManagerScreen(
|
|||||||
onClick = { pendingBulkDelete = visibleEntries.filter { it.absolutePath in selectedPaths } },
|
onClick = { pendingBulkDelete = visibleEntries.filter { it.absolutePath in selectedPaths } },
|
||||||
contentPadding = selBarPadding,
|
contentPadding = selBarPadding,
|
||||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error),
|
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error),
|
||||||
modifier = Modifier.focusGlide(CircleShape),
|
|
||||||
) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error, fontSize = 12.sp) }
|
) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error, fontSize = 12.sp) }
|
||||||
Spacer(Modifier.width(4.dp))
|
Spacer(Modifier.width(4.dp))
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
onClick = { selectionMode = false; selectedPaths = emptySet() },
|
onClick = { selectionMode = false; selectedPaths = emptySet() },
|
||||||
contentPadding = selBarPadding,
|
contentPadding = selBarPadding,
|
||||||
modifier = Modifier.focusGlide(CircleShape),
|
|
||||||
) { Text(stringResource(R.string.fm_done), fontSize = 12.sp) }
|
) { Text(stringResource(R.string.fm_done), fontSize = 12.sp) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1011,7 +865,7 @@ fun FileManagerScreen(
|
|||||||
if (isCutOperation) stringResource(R.string.fm_paste_move_here, what) else stringResource(R.string.fm_paste_here, what),
|
if (isCutOperation) stringResource(R.string.fm_paste_move_here, what) else stringResource(R.string.fm_paste_here, what),
|
||||||
color = MaterialTheme.colorScheme.onBackground, fontSize = 13.sp, modifier = Modifier.weight(1f),
|
color = MaterialTheme.colorScheme.onBackground, fontSize = 13.sp, modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }, modifier = Modifier.focusGlide(CircleShape)) {
|
TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }) {
|
||||||
Text(stringResource(R.string.common_cancel), color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp)
|
Text(stringResource(R.string.common_cancel), color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1042,7 +896,7 @@ fun FileManagerScreen(
|
|||||||
isOperationRunning = false
|
isOperationRunning = false
|
||||||
operationDeterminate = false
|
operationDeterminate = false
|
||||||
loadDirectory(currentDir, resetScroll = false)
|
loadDirectory(currentDir, resetScroll = false)
|
||||||
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) }
|
}) { Text(stringResource(R.string.common_cancel), fontSize = 12.sp) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Spacer(Modifier.height(4.dp))
|
Spacer(Modifier.height(4.dp))
|
||||||
@@ -1132,7 +986,7 @@ fun FileManagerScreen(
|
|||||||
contentPadding = PaddingValues(8.dp),
|
contentPadding = PaddingValues(8.dp),
|
||||||
) {
|
) {
|
||||||
if (canGoUp) item(key = "..", span = { GridItemSpan(maxLineSpan) }) {
|
if (canGoUp) item(key = "..", span = { GridItemSpan(maxLineSpan) }) {
|
||||||
ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.UP) })
|
ParentFolderRow(compact = compactRows, onTap = { goUp() })
|
||||||
}
|
}
|
||||||
items(shownEntries, key = { it.absolutePath }) { file ->
|
items(shownEntries, key = { it.absolutePath }) { file ->
|
||||||
val isFav = remember(file.absolutePath, favTick) {
|
val isFav = remember(file.absolutePath, favTick) {
|
||||||
@@ -1198,7 +1052,7 @@ fun FileManagerScreen(
|
|||||||
} else
|
} else
|
||||||
LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {
|
LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {
|
||||||
if (canGoUp) item(key = "..") {
|
if (canGoUp) item(key = "..") {
|
||||||
ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.UP) })
|
ParentFolderRow(compact = compactRows, onTap = { goUp() })
|
||||||
}
|
}
|
||||||
if (entries.isEmpty()) {
|
if (entries.isEmpty()) {
|
||||||
item {
|
item {
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import java.io.FileOutputStream
|
|||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
import java.nio.file.Files
|
import java.nio.file.Files
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import java.util.concurrent.CancellationException
|
|
||||||
|
|
||||||
object FileOps {
|
object FileOps {
|
||||||
private const val TAG = "FileOps"
|
private const val TAG = "FileOps"
|
||||||
@@ -25,27 +24,24 @@ object FileOps {
|
|||||||
|
|
||||||
fun isSymlink(file: File): Boolean = try { Files.isSymbolicLink(file.toPath()) } catch (e: Exception) { false }
|
fun isSymlink(file: File): Boolean = try { Files.isSymbolicLink(file.toPath()) } catch (e: Exception) { false }
|
||||||
|
|
||||||
fun delete(target: File?, isCancelled: () -> Boolean = { false }): Boolean {
|
fun delete(target: File?): Boolean {
|
||||||
if (isCancelled()) throw CancellationException("Delete cancelled: $target")
|
|
||||||
if (target == null) return false
|
if (target == null) return false
|
||||||
if (target.isDirectory && !isSymlink(target)) {
|
if (target.isDirectory && !isSymlink(target)) {
|
||||||
if (!clear(target, isCancelled)) return false
|
if (!clear(target)) return false
|
||||||
}
|
}
|
||||||
if (isCancelled()) throw CancellationException("Delete cancelled: $target")
|
|
||||||
return target.delete()
|
return target.delete()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun clear(dir: File, isCancelled: () -> Boolean = { false }): Boolean {
|
fun clear(dir: File): Boolean {
|
||||||
val children = dir.listFiles() ?: return true
|
val children = dir.listFiles() ?: return true
|
||||||
var ok = true
|
var ok = true
|
||||||
for (child in children) if (!delete(child, isCancelled)) ok = false
|
for (child in children) if (!delete(child)) ok = false
|
||||||
return ok
|
return ok
|
||||||
}
|
}
|
||||||
|
|
||||||
fun totalSize(f: File?, isCancelled: () -> Boolean = { false }): Long {
|
fun totalSize(f: File?): Long {
|
||||||
if (isCancelled()) throw CancellationException("Size scan cancelled: $f")
|
|
||||||
if (f == null || !f.exists() || isSymlink(f)) return 0
|
if (f == null || !f.exists() || isSymlink(f)) return 0
|
||||||
if (f.isDirectory) return f.listFiles()?.sumOf { totalSize(it, isCancelled) } ?: 0
|
if (f.isDirectory) return f.listFiles()?.sumOf { totalSize(it) } ?: 0
|
||||||
return f.length()
|
return f.length()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,12 +53,12 @@ object FileOps {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if (!copyWithProgress(src, dst, progress, isCancelled)) return false
|
if (!copyWithProgress(src, dst, progress, isCancelled)) return false
|
||||||
// Once the destination is committed, finish deleting the source.
|
if (isCancelled()) return false
|
||||||
return delete(src)
|
return delete(src)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun copyWithProgress(src: File, dst: File, progress: ProgressCallback?, isCancelled: () -> Boolean = { false }): Boolean {
|
fun copyWithProgress(src: File, dst: File, progress: ProgressCallback?, isCancelled: () -> Boolean = { false }): Boolean {
|
||||||
val total = maxOf(totalSize(src, isCancelled), 1L)
|
val total = maxOf(totalSize(src), 1L)
|
||||||
return copyWithProgress(src, dst, longArrayOf(0), total, progress, isCancelled)
|
return copyWithProgress(src, dst, longArrayOf(0), total, progress, isCancelled)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,23 +71,15 @@ object FileOps {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if (src.isDirectory) {
|
if (src.isDirectory) {
|
||||||
val created = if (dst.exists()) false else {
|
if (!dst.exists() && !dst.mkdirs()) return false
|
||||||
if (!dst.mkdirs()) return false
|
var allOk = true
|
||||||
true
|
src.list()?.forEach { name ->
|
||||||
}
|
if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress, isCancelled)) {
|
||||||
try {
|
Log.e(TAG, "Failed to copy: ${File(src, name)}")
|
||||||
var allOk = true
|
allOk = false
|
||||||
src.list()?.forEach { name ->
|
|
||||||
if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress, isCancelled)) {
|
|
||||||
Log.e(TAG, "Failed to copy: ${File(src, name)}")
|
|
||||||
allOk = false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return allOk
|
|
||||||
} catch (e: CancellationException) {
|
|
||||||
if (created) delete(dst)
|
|
||||||
throw e
|
|
||||||
}
|
}
|
||||||
|
return allOk
|
||||||
}
|
}
|
||||||
val parent = dst.parentFile
|
val parent = dst.parentFile
|
||||||
if (!src.exists() || (parent != null && !parent.exists() && !parent.mkdirs())) return false
|
if (!src.exists() || (parent != null && !parent.exists() && !parent.mkdirs())) return false
|
||||||
@@ -130,7 +118,6 @@ object FileOps {
|
|||||||
val size = input.size()
|
val size = input.size()
|
||||||
var position = 0L
|
var position = 0L
|
||||||
while (position < size) {
|
while (position < size) {
|
||||||
if (isCancelled()) throw CancellationException("Copy cancelled: $src")
|
|
||||||
val transferred = input.transferTo(position, minOf(chunk, size - position), channel)
|
val transferred = input.transferTo(position, minOf(chunk, size - position), channel)
|
||||||
if (transferred <= 0) break
|
if (transferred <= 0) break
|
||||||
position += transferred
|
position += transferred
|
||||||
@@ -138,19 +125,12 @@ object FileOps {
|
|||||||
progress?.onProgress(done[0], total)
|
progress?.onProgress(done[0], total)
|
||||||
}
|
}
|
||||||
if (position < size) throw IOException("Incomplete copy: $position/$size bytes")
|
if (position < size) throw IOException("Incomplete copy: $position/$size bytes")
|
||||||
if (size > 0 && isCancelled()) throw CancellationException("Copy cancelled: $src")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
staging?.let { directory ->
|
staging?.let { directory ->
|
||||||
val copied = File(directory, "file").toPath()
|
val copied = File(directory, "file").toPath()
|
||||||
if (permissions != null) {
|
if (permissions != null && Files.getPosixFilePermissions(copied) != permissions) {
|
||||||
try {
|
Files.setPosixFilePermissions(copied, permissions)
|
||||||
if (Files.getPosixFilePermissions(copied) != permissions) {
|
|
||||||
Files.setPosixFilePermissions(copied, permissions)
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "Failed to restore destination permissions: $target", e)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (isCancelled()) throw java.util.concurrent.CancellationException("Copy cancelled: $src")
|
if (isCancelled()) throw java.util.concurrent.CancellationException("Copy cancelled: $src")
|
||||||
Files.move(copied, target.toPath(), java.nio.file.StandardCopyOption.ATOMIC_MOVE)
|
Files.move(copied, target.toPath(), java.nio.file.StandardCopyOption.ATOMIC_MOVE)
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ class FilePickerActivity : ComponentActivity() {
|
|||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
||||||
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||||
}
|
}
|
||||||
@@ -50,7 +50,6 @@ class FilePickerActivity : ComponentActivity() {
|
|||||||
setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_SELECTED_FILE, file.absolutePath))
|
setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_SELECTED_FILE, file.absolutePath))
|
||||||
finish()
|
finish()
|
||||||
},
|
},
|
||||||
onExit = { finish() },
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
package com.droiddeck.launcher.files
|
package com.droiddeck.launcher.files
|
||||||
|
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import com.droiddeck.launcher.ui.focusGlide
|
|
||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
import androidx.compose.foundation.rememberScrollState
|
import androidx.compose.foundation.rememberScrollState
|
||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
@@ -130,7 +128,7 @@ internal fun FilePropertiesDialog(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
confirmButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.fm_done)) } },
|
confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.fm_done)) } },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,7 +182,6 @@ private fun AttributeToggleRow(
|
|||||||
checked = checked,
|
checked = checked,
|
||||||
enabled = enabled,
|
enabled = enabled,
|
||||||
onCheckedChange = onToggle,
|
onCheckedChange = onToggle,
|
||||||
modifier = Modifier.focusGlide(),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
package com.droiddeck.launcher.files
|
package com.droiddeck.launcher.files
|
||||||
|
|
||||||
import androidx.compose.foundation.border
|
import androidx.compose.foundation.border
|
||||||
import com.droiddeck.launcher.ui.GlideAlertDialog as AlertDialog
|
import androidx.compose.material3.AlertDialog
|
||||||
import androidx.compose.material3.AlertDialogDefaults
|
import androidx.compose.material3.AlertDialogDefaults
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
|||||||
@@ -29,50 +29,6 @@ object StorageRoots {
|
|||||||
val seeds = LinkedHashSet<File>()
|
val seeds = LinkedHashSet<File>()
|
||||||
}
|
}
|
||||||
|
|
||||||
private val EXTERNAL_MOUNT_TYPES = setOf(
|
|
||||||
"vfat", "exfat", "texfat", "ntfs", "ntfs3", "fuseblk", "fuse", "sdcardfs",
|
|
||||||
)
|
|
||||||
|
|
||||||
internal data class MountPoint(val target: File, val type: String)
|
|
||||||
|
|
||||||
internal fun parseMountPoints(mounts: String): List<MountPoint> {
|
|
||||||
val out = ArrayList<MountPoint>()
|
|
||||||
for (line in mounts.lineSequence()) {
|
|
||||||
val parts = line.split(' ')
|
|
||||||
if (parts.size < 3) continue
|
|
||||||
out.add(MountPoint(File(parts[1].replace("\\040", " ")), parts[2].lowercase()))
|
|
||||||
}
|
|
||||||
return out.distinct()
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun isExternalMount(mount: MountPoint): Boolean {
|
|
||||||
val path = mount.target.path
|
|
||||||
val name = when {
|
|
||||||
path.startsWith("/storage/") -> path.removePrefix("/storage/")
|
|
||||||
path.startsWith("/mnt/media_rw/") -> path.removePrefix("/mnt/media_rw/")
|
|
||||||
path.startsWith("/mnt/") -> path.removePrefix("/mnt/")
|
|
||||||
else -> return false
|
|
||||||
}
|
|
||||||
if ('/' in name || name.isEmpty() || name == "emulated" || name == "self") return false
|
|
||||||
if (mount.type in EXTERNAL_MOUNT_TYPES) {
|
|
||||||
if (path.startsWith("/mnt/") && !path.startsWith("/mnt/media_rw/")) {
|
|
||||||
val lower = name.lowercase()
|
|
||||||
if (!lower.contains("usb") && !lower.contains("otg") &&
|
|
||||||
!lower.contains("udisk") && !lower.contains("disk")
|
|
||||||
) return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
// vold-managed locations only hold removable volumes, whatever the fstype is.
|
|
||||||
return path.startsWith("/storage/") || path.startsWith("/mnt/media_rw/")
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun parseExternalMounts(mounts: String): List<File> =
|
|
||||||
parseMountPoints(mounts).filter(::isExternalMount).map { it.target }
|
|
||||||
|
|
||||||
fun externalMounts(): List<File> =
|
|
||||||
runCatching { parseExternalMounts(File("/proc/mounts").readText()) }.getOrDefault(emptyList())
|
|
||||||
|
|
||||||
fun list(context: Context): List<StorageRoot> {
|
fun list(context: Context): List<StorageRoot> {
|
||||||
val volumes = LinkedHashMap<String, Volume>()
|
val volumes = LinkedHashMap<String, Volume>()
|
||||||
|
|
||||||
@@ -88,31 +44,21 @@ object StorageRoots {
|
|||||||
val storageManager = context.getSystemService(StorageManager::class.java)
|
val storageManager = context.getSystemService(StorageManager::class.java)
|
||||||
|
|
||||||
storageManager?.storageVolumes.orEmpty()
|
storageManager?.storageVolumes.orEmpty()
|
||||||
.filter { present(it.state) }
|
.filter { isMounted(it.state) }
|
||||||
.forEachIndexed { index, volume ->
|
.forEach { volume ->
|
||||||
val uuid = volume.uuid?.takeIf { it.isNotBlank() }
|
val uuid = volume.uuid?.takeIf { it.isNotBlank() }
|
||||||
val dirName = volume.directory?.name?.takeIf { it.isNotBlank() }
|
val entry = volumeOf(if (volume.isPrimary) PRIMARY_KEY else uuid ?: return@forEach)
|
||||||
// Unmounted volumes often report neither uuid nor directory; never drop the
|
|
||||||
// volume or a plugged-in drive stays invisible with no explanation.
|
|
||||||
val descSlug = volume.getDescription(context)?.trim()
|
|
||||||
?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
|
|
||||||
?.replace(Regex("[^A-Za-z0-9._-]+"), "-")
|
|
||||||
val entry = volumeOf(if (volume.isPrimary) PRIMARY_KEY else uuid ?: dirName ?: descSlug ?: "volume-$index")
|
|
||||||
entry.removable = !volume.isPrimary && volume.isRemovable
|
entry.removable = !volume.isPrimary && volume.isRemovable
|
||||||
if (entry.label == null) entry.label = labelFor(context, volume, uuid ?: dirName ?: descSlug)
|
if (entry.label == null) entry.label = labelFor(context, volume, uuid)
|
||||||
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||||
volume.directory?.let { entry.candidates += it }
|
volume.directory?.let { entry.candidates += it }
|
||||||
}
|
}
|
||||||
val name = uuid ?: dirName
|
if (uuid != null) {
|
||||||
if (name != null) {
|
entry.candidates += File("/storage/$uuid")
|
||||||
entry.candidates += File("/storage/$name")
|
entry.candidates += File("/mnt/media_rw/$uuid")
|
||||||
entry.candidates += File("/mnt/media_rw/$name")
|
|
||||||
// Only strict uuid matches own an app directory; a loose match would
|
|
||||||
// attach another volume's folder to this entry.
|
|
||||||
if (uuid != null) appDirs.filter { belongsTo(storageManager!!, it, volume) }
|
|
||||||
.forEach { entry.seeds += it }
|
|
||||||
}
|
}
|
||||||
|
appDirs.filter { belongsTo(storageManager!!, it, volume) }.forEach { entry.seeds += it }
|
||||||
}
|
}
|
||||||
|
|
||||||
File("/storage").listFiles().orEmpty().forEach { child ->
|
File("/storage").listFiles().orEmpty().forEach { child ->
|
||||||
@@ -122,13 +68,6 @@ object StorageRoots {
|
|||||||
File("/mnt/media_rw").listFiles().orEmpty().forEach { child ->
|
File("/mnt/media_rw").listFiles().orEmpty().forEach { child ->
|
||||||
if (child.isDirectory) volumeOf(child.name).candidates += child
|
if (child.isDirectory) volumeOf(child.name).candidates += child
|
||||||
}
|
}
|
||||||
// USB OTG drives do not always appear as storage volumes or under /storage for
|
|
||||||
// third-party apps, but their kernel mounts are still visible in /proc/mounts.
|
|
||||||
for (mount in externalMounts()) {
|
|
||||||
val entry = volumeOf(mount.name)
|
|
||||||
if (entry.label == null) entry.label = mount.name
|
|
||||||
entry.candidates += mount
|
|
||||||
}
|
|
||||||
|
|
||||||
appDirs.forEach { dir ->
|
appDirs.forEach { dir ->
|
||||||
val root = volumeRootOf(dir) ?: return@forEach
|
val root = volumeRootOf(dir) ?: return@forEach
|
||||||
@@ -202,19 +141,15 @@ object StorageRoots {
|
|||||||
|
|
||||||
private fun labelFor(context: Context, volume: StorageVolume, uuid: String?): String {
|
private fun labelFor(context: Context, volume: StorageVolume, uuid: String?): String {
|
||||||
if (volume.isPrimary) return context.getString(R.string.fm_drive_internal)
|
if (volume.isPrimary) return context.getString(R.string.fm_drive_internal)
|
||||||
val description = volume.getDescription(context)?.trim()
|
|
||||||
if (!description.isNullOrBlank() && !description.equals("android", ignoreCase = true)) return description
|
|
||||||
if (volume.isRemovable) return context.getString(R.string.fm_drive_sd)
|
if (volume.isRemovable) return context.getString(R.string.fm_drive_sd)
|
||||||
return uuid
|
val description = volume.getDescription(context)?.trim()
|
||||||
|
return description?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
|
||||||
|
?: uuid
|
||||||
?: context.getString(R.string.fm_drive_storage)
|
?: context.getString(R.string.fm_drive_storage)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun isEmulated(dir: File): Boolean = dir.absolutePath.startsWith(EMULATED_PREFIX)
|
private fun isEmulated(dir: File): Boolean = dir.absolutePath.startsWith(EMULATED_PREFIX)
|
||||||
|
|
||||||
private fun present(state: String?): Boolean =
|
|
||||||
isMounted(state) || state == Environment.MEDIA_UNMOUNTED || state == Environment.MEDIA_CHECKING ||
|
|
||||||
state == Environment.MEDIA_NOFS || state == Environment.MEDIA_UNMOUNTABLE
|
|
||||||
|
|
||||||
private fun isMounted(state: String?): Boolean =
|
private fun isMounted(state: String?): Boolean =
|
||||||
state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY
|
state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY
|
||||||
|
|
||||||
|
|||||||
@@ -4,11 +4,7 @@ import android.content.Context
|
|||||||
import android.graphics.Bitmap
|
import android.graphics.Bitmap
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.droiddeck.launcher.files.PeIconExtractor
|
import com.droiddeck.launcher.files.PeIconExtractor
|
||||||
import com.droiddeck.launcher.runtime.BattleNet
|
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
import com.droiddeck.launcher.stores.Store
|
|
||||||
import com.droiddeck.launcher.stores.StoreArt
|
|
||||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.net.HttpURLConnection
|
import java.net.HttpURLConnection
|
||||||
@@ -77,18 +73,14 @@ object AddedGameArt {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun storeArt(context: Context, game: AddedGames.Game): BattleNet.Art? =
|
|
||||||
if (game.source != Store.BATTLENET.id) null else game.storeId?.let(BattleNet::title)?.let { BattleNet.art(context, it) }
|
|
||||||
|
|
||||||
fun resolve(context: Context, game: AddedGames.Game): Art {
|
fun resolve(context: Context, game: AddedGames.Game): Art {
|
||||||
val own = local(game)
|
val own = local(game)
|
||||||
val cache = cacheDir(context, game)
|
val cache = cacheDir(context, game)
|
||||||
val store = storeArt(context, game)
|
|
||||||
fun cached(name: String) = File(cache, name).takeIf { it.isFile }
|
fun cached(name: String) = File(cache, name).takeIf { it.isFile }
|
||||||
return Art(
|
return Art(
|
||||||
portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: store?.cover ?: cached("p.jpg") ?: exeArt(context, game, cover = true),
|
portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: cached("p.jpg") ?: exeArt(context, game, cover = true),
|
||||||
header = chosen(cache, Slot.WIDE) ?: own.header ?: store?.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false),
|
header = chosen(cache, Slot.WIDE) ?: own.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false),
|
||||||
hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: store?.header ?: cached("hero.jpg"),
|
hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: cached("hero.jpg"),
|
||||||
logo = chosen(cache, Slot.LOGO) ?: own.logo ?: cached("logo.png"),
|
logo = chosen(cache, Slot.LOGO) ?: own.logo ?: cached("logo.png"),
|
||||||
icon = chosen(cache, Slot.ICON) ?: own.icon ?: cached("icon-sgdb.png") ?: exeIcon(context, game),
|
icon = chosen(cache, Slot.ICON) ?: own.icon ?: cached("icon-sgdb.png") ?: exeIcon(context, game),
|
||||||
)
|
)
|
||||||
@@ -97,16 +89,15 @@ object AddedGameArt {
|
|||||||
fun describe(context: Context, game: AddedGames.Game): List<SlotState> {
|
fun describe(context: Context, game: AddedGames.Game): List<SlotState> {
|
||||||
val own = local(game)
|
val own = local(game)
|
||||||
val cache = cacheDir(context, game)
|
val cache = cacheDir(context, game)
|
||||||
val store = storeArt(context, game)
|
|
||||||
fun cached(name: String): Pair<File, String>? = File(cache, name).takeIf { it.isFile }?.let { f ->
|
fun cached(name: String): Pair<File, String>? = File(cache, name).takeIf { it.isFile }?.let { f ->
|
||||||
f to (File(cache, "$name.src").takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: STEAM)
|
f to (File(cache, "$name.src").takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: STEAM)
|
||||||
}
|
}
|
||||||
return Slot.values().map { slot ->
|
return Slot.values().map { slot ->
|
||||||
chosen(cache, slot)?.let { return@map SlotState(slot, it, chosenSource(context, game, slot).first.ifEmpty { FILE }, true) }
|
chosen(cache, slot)?.let { return@map SlotState(slot, it, chosenSource(context, game, slot).first.ifEmpty { FILE }, true) }
|
||||||
val auto: Pair<File, String>? = when (slot) {
|
val auto: Pair<File, String>? = when (slot) {
|
||||||
Slot.COVER -> own.portrait?.let { it to FOLDER } ?: store?.cover?.let { it to AUTO } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE }
|
Slot.COVER -> own.portrait?.let { it to FOLDER } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE }
|
||||||
Slot.WIDE -> own.header?.let { it to FOLDER } ?: store?.header?.let { it to AUTO } ?: cached("header.jpg") ?: exeArt(context, game, cover = false)?.let { it to EXE }
|
Slot.WIDE -> own.header?.let { it to FOLDER } ?: cached("header.jpg") ?: exeArt(context, game, cover = false)?.let { it to EXE }
|
||||||
Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: store?.header?.let { it to AUTO } ?: cached("hero.jpg")
|
Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: cached("hero.jpg")
|
||||||
Slot.LOGO -> own.logo?.let { it to FOLDER } ?: cached("logo.png")
|
Slot.LOGO -> own.logo?.let { it to FOLDER } ?: cached("logo.png")
|
||||||
Slot.ICON -> own.icon?.let { it to FOLDER } ?: File(cache, "icon-sgdb.png").takeIf { it.isFile }?.let { it to SGDB }
|
Slot.ICON -> own.icon?.let { it to FOLDER } ?: File(cache, "icon-sgdb.png").takeIf { it.isFile }?.let { it to SGDB }
|
||||||
?: exeIcon(context, game)?.let { it to EXE }
|
?: exeIcon(context, game)?.let { it to EXE }
|
||||||
@@ -237,103 +228,46 @@ object AddedGameArt {
|
|||||||
return if (tmp.renameTo(png)) png else null
|
return if (tmp.renameTo(png)) png else null
|
||||||
}
|
}
|
||||||
|
|
||||||
internal class Sources(
|
fun fetchMissing(context: Context, games: List<AddedGames.Game>): Boolean {
|
||||||
val storeLogo: (AddedGames.Game) -> Boolean,
|
|
||||||
val steamSearch: (String) -> Int?,
|
|
||||||
val steam: (String, File, Set<Slot>) -> Boolean,
|
|
||||||
val sgdbGame: (String, Int?, String) -> Int?,
|
|
||||||
val sgdb: (String, Int, File, Set<Slot>) -> Boolean,
|
|
||||||
)
|
|
||||||
|
|
||||||
private val network = Sources(
|
|
||||||
storeLogo = ::storeLogo,
|
|
||||||
steamSearch = { name -> search(name)?.toIntOrNull() },
|
|
||||||
steam = ::download,
|
|
||||||
sgdbGame = SteamGridDb::gameId,
|
|
||||||
sgdb = SteamGridDb::download,
|
|
||||||
)
|
|
||||||
|
|
||||||
private val EXTRAS = setOf(Slot.LOGO, Slot.ICON)
|
|
||||||
private val STEAM_SLOTS = setOf(Slot.COVER, Slot.WIDE, Slot.BACKGROUND, Slot.LOGO)
|
|
||||||
internal const val EXTRAS_TRIED = "extras-tried"
|
|
||||||
|
|
||||||
internal fun missing(context: Context, game: AddedGames.Game): Set<Slot> {
|
|
||||||
val own = local(game)
|
|
||||||
val cache = cacheDir(context, game)
|
|
||||||
val store = storeArt(context, game)
|
|
||||||
fun has(slot: Slot, mine: File?, cached: String) = chosen(cache, slot) != null || mine != null || File(cache, cached).isFile
|
|
||||||
return Slot.values().filterNot { slot ->
|
|
||||||
when (slot) {
|
|
||||||
Slot.COVER -> has(slot, own.portrait ?: store?.cover, "p.jpg")
|
|
||||||
Slot.WIDE -> has(slot, own.header ?: store?.header, "header.jpg")
|
|
||||||
Slot.BACKGROUND -> has(slot, own.hero ?: store?.header, "hero.jpg")
|
|
||||||
Slot.LOGO -> has(slot, own.logo, "logo.png")
|
|
||||||
Slot.ICON -> has(slot, own.icon, "icon-sgdb.png")
|
|
||||||
}
|
|
||||||
}.toSet()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun storeLogo(game: AddedGames.Game): Boolean {
|
|
||||||
val url = StoreGameSidecar.read(game.folder)?.logo ?: return false
|
|
||||||
return StoreArt.fetchLogo(game.folder, url)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun fetchMissing(context: Context, games: List<AddedGames.Game>): Boolean =
|
|
||||||
fetchMissing(context, games, SteamGridDb.key(context), network)
|
|
||||||
|
|
||||||
internal fun fetchMissing(context: Context, games: List<AddedGames.Game>, sgdbKey: String, sources: Sources): Boolean {
|
|
||||||
if (!SessionPrefs.addedGamesArt(context)) return false
|
if (!SessionPrefs.addedGamesArt(context)) return false
|
||||||
|
val sgdbKey = SteamGridDb.key(context)
|
||||||
val keyChangedAt = SteamGridDb.keyChangedAt(context)
|
val keyChangedAt = SteamGridDb.keyChangedAt(context)
|
||||||
var sgdbDown = false
|
var sgdbDown = false
|
||||||
var changed = false
|
var changed = false
|
||||||
for (game in games) {
|
for (game in games) {
|
||||||
val start = missing(context, game)
|
if (local(game).portrait != null) continue
|
||||||
val full = Slot.COVER in start
|
|
||||||
val allowed = if (full) Slot.values().toSet() else EXTRAS
|
|
||||||
var need = start intersect allowed
|
|
||||||
if (need.isEmpty() || (need == setOf(Slot.ICON) && sgdbKey.isEmpty())) continue
|
|
||||||
val cache = cacheDir(context, game)
|
val cache = cacheDir(context, game)
|
||||||
val tried = File(cache, EXTRAS_TRIED)
|
if (File(cache, "p.jpg").isFile) continue
|
||||||
if (!full && tried.isFile && tried.lastModified() >= keyChangedAt && System.currentTimeMillis() - tried.lastModified() < RETRY_AFTER_MS) continue
|
|
||||||
cache.mkdirs()
|
cache.mkdirs()
|
||||||
if (Slot.LOGO in need && game.source != Library.ADDED && runCatching { sources.storeLogo(game) }.getOrDefault(false)) {
|
val match = steamMatch(context, game) { name ->
|
||||||
changed = true
|
runCatching { search(name) }.onFailure { Log.w(TAG, "${game.name}: store search failed (${it.message})") }.getOrNull()?.toIntOrNull()
|
||||||
need = need - Slot.LOGO
|
|
||||||
}
|
}
|
||||||
val match by lazy {
|
val appId = match.appId?.takeIf { match.certainty == SteamMatch.Certainty.FILES }
|
||||||
steamMatch(context, game) { name ->
|
val id = match.appId?.toString()
|
||||||
runCatching { sources.steamSearch(name) }.onFailure { Log.w(TAG, "${game.name}: store search failed (${it.message})") }.getOrNull()
|
if (id != null && download(id, cache)) changed = true
|
||||||
|
if (File(cache, "p.jpg").isFile || sgdbKey.isEmpty() || sgdbDown) continue
|
||||||
|
val stored: String? = try {
|
||||||
|
remembered(File(cache, "sgdb-id"), keyChangedAt) {
|
||||||
|
SteamGridDb.gameId(sgdbKey, appId ?: id?.toIntOrNull(), game.name)?.toString()
|
||||||
}
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "${game.name}: SteamGridDB lookup failed (${e.javaClass.simpleName}); not asking again this pass")
|
||||||
|
sgdbDown = true
|
||||||
|
null
|
||||||
}
|
}
|
||||||
val steamWant = need intersect STEAM_SLOTS
|
val gridId = stored?.toIntOrNull() ?: continue
|
||||||
if (steamWant.isNotEmpty()) {
|
val grabbed = try {
|
||||||
val id = match.appId?.toString()
|
SteamGridDb.download(sgdbKey, gridId, cache)
|
||||||
if (id != null && sources.steam(id, cache, steamWant)) changed = true
|
} catch (e: Exception) {
|
||||||
need = missing(context, game) intersect allowed
|
sgdbDown = true
|
||||||
|
false
|
||||||
}
|
}
|
||||||
var asked = true
|
if (grabbed) changed = true
|
||||||
if (need.isNotEmpty() && sgdbKey.isNotEmpty()) {
|
|
||||||
if (sgdbDown) asked = false else try {
|
|
||||||
val gridId = remembered(File(cache, "sgdb-id"), keyChangedAt) {
|
|
||||||
sources.sgdbGame(sgdbKey, match.appId, game.name)?.toString()
|
|
||||||
}?.toIntOrNull()
|
|
||||||
if (gridId != null && sources.sgdb(sgdbKey, gridId, cache, need)) changed = true
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "${game.name}: SteamGridDB failed (${e.javaClass.simpleName}); not asking again this pass")
|
|
||||||
sgdbDown = true
|
|
||||||
asked = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ((missing(context, game) intersect EXTRAS).isEmpty()) tried.delete() else if (asked) tried.writeText("")
|
|
||||||
}
|
}
|
||||||
return changed
|
return changed
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match {
|
internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match {
|
||||||
if (game.source == Store.BATTLENET.id) {
|
|
||||||
val id = game.storeId?.let(BattleNet::title)?.steam
|
|
||||||
return SteamMatch.Match(id, if (id == null) SteamMatch.Certainty.NONE else SteamMatch.Certainty.FILES, Store.BATTLENET.id, System.currentTimeMillis())
|
|
||||||
}
|
|
||||||
val match = SteamMatch.resolve(context, game.folder.path, game.exe, game.name, legacy = File(cacheDir(context, game), "steam-appid"), search = search)
|
val match = SteamMatch.resolve(context, game.folder.path, game.exe, game.name, legacy = File(cacheDir(context, game), "steam-appid"), search = search)
|
||||||
match.appId?.let { Log.i(TAG, "${game.name}: Steam app $it (${match.certainty.name.lowercase()})") }
|
match.appId?.let { Log.i(TAG, "${game.name}: Steam app $it (${match.certainty.name.lowercase()})") }
|
||||||
return match
|
return match
|
||||||
@@ -373,26 +307,24 @@ object AddedGameArt {
|
|||||||
.filter { it.second > 0 && it.first.isNotEmpty() }
|
.filter { it.second > 0 && it.first.isNotEmpty() }
|
||||||
.maxByOrNull { it.second }?.first
|
.maxByOrNull { it.second }?.first
|
||||||
|
|
||||||
internal fun search(name: String): String? {
|
private fun search(name: String): String? {
|
||||||
val term = name.replace(EDITION, " ").trim().ifEmpty { name }
|
val term = name.replace(EDITION, " ").trim().ifEmpty { name }
|
||||||
val json = get(STORE_SEARCH + URLEncoder.encode(term, "UTF-8"))?.toString(Charsets.UTF_8) ?: return null
|
val json = get(STORE_SEARCH + URLEncoder.encode(term, "UTF-8"))?.toString(Charsets.UTF_8) ?: return null
|
||||||
val items = JSONObject(json).optJSONArray("items") ?: return null
|
val items = JSONObject(json).optJSONArray("items") ?: return null
|
||||||
return pickStoreResult(name, (0 until items.length()).map { items.getJSONObject(it) }.map { it.optString("id") to it.optString("name") })
|
return pickStoreResult(name, (0 until items.length()).map { items.getJSONObject(it) }.map { it.optString("id") to it.optString("name") })
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun download(id: String, cache: File, slots: Set<Slot> = Slot.entries.toSet()): Boolean {
|
private fun download(id: String, cache: File): Boolean {
|
||||||
var got = false
|
var got = false
|
||||||
for ((slot, remote, localName) in listOf(
|
for ((remote, localName) in listOf(
|
||||||
Triple(Slot.COVER, "library_600x900.jpg", "p.jpg"), Triple(Slot.WIDE, "header.jpg", "header.jpg"),
|
"library_600x900.jpg" to "p.jpg", "header.jpg" to "header.jpg", "library_hero.jpg" to "hero.jpg", "logo.png" to "logo.png",
|
||||||
Triple(Slot.BACKGROUND, "library_hero.jpg", "hero.jpg"), Triple(Slot.LOGO, "logo.png", "logo.png"),
|
|
||||||
)) {
|
)) {
|
||||||
if (slot !in slots) continue
|
|
||||||
val dst = File(cache, localName)
|
val dst = File(cache, localName)
|
||||||
if (dst.isFile) continue
|
if (dst.isFile) continue
|
||||||
val bytes = get("$CDN$id/$remote") ?: steamAssetUrl(id, remote)?.let { get(it) } ?: continue
|
val bytes = get("$CDN$id/$remote") ?: steamAssetUrl(id, remote)?.let { get(it) } ?: continue
|
||||||
val tmp = File(cache, "$localName.tmp")
|
val tmp = File(cache, "$localName.tmp")
|
||||||
if (runCatching { tmp.writeBytes(bytes) }.isFailure) { tmp.delete(); continue }
|
tmp.writeBytes(bytes)
|
||||||
if (tmp.renameTo(dst)) { got = true; runCatching { File(cache, "$localName.src").writeText(STEAM) } }
|
if (tmp.renameTo(dst)) { got = true; File(cache, "$localName.src").writeText(STEAM) }
|
||||||
}
|
}
|
||||||
return got
|
return got
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,18 +79,6 @@ object AddedGames {
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
fun hostPath(context: Context, guest: String): File? {
|
|
||||||
if (!guest.startsWith("/") || guest.split('/').any { it == ".." }) return null
|
|
||||||
val mapped = roots(context).map { it.host to it.guest } + StoreInstallRoot.externalRoots(context) +
|
|
||||||
listOfNotNull(GameStorage.effective(context)?.let { File(it.path) to LIBRARY }) +
|
|
||||||
(android.os.Environment.getExternalStorageDirectory() to "/root/Storage")
|
|
||||||
for ((host, root) in mapped.sortedByDescending { it.second.length }) {
|
|
||||||
if (guest == root) return host
|
|
||||||
if (guest.startsWith("$root/")) return File(host, guest.removePrefix("$root/"))
|
|
||||||
}
|
|
||||||
return File(LinuxRuntime.rootDir(context), guest.removePrefix("/"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun candidates(folder: File): List<File> = rank(folder).exes
|
fun candidates(folder: File): List<File> = rank(folder).exes
|
||||||
|
|
||||||
fun rank(folder: File): GameExePicker.Ranking {
|
fun rank(folder: File): GameExePicker.Ranking {
|
||||||
@@ -189,9 +177,6 @@ object AddedGames {
|
|||||||
scanGame(context, folder, out, single = entry)
|
scanGame(context, folder, out, single = entry)
|
||||||
}
|
}
|
||||||
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out)
|
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out)
|
||||||
for (game in com.droiddeck.launcher.runtime.BattleNet.games(context)) {
|
|
||||||
if (game.folder.path !in removed) com.droiddeck.launcher.runtime.BattleNet.shortcut(context, game)?.let(out::add)
|
|
||||||
}
|
|
||||||
return out.distinctBy { it.folder.canonicalPath }
|
return out.distinctBy { it.folder.canonicalPath }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -289,7 +274,7 @@ object AddedGames {
|
|||||||
|
|
||||||
class FolderResult(val added: List<Game>, val already: Int)
|
class FolderResult(val added: List<Game>, val already: Int)
|
||||||
|
|
||||||
fun addFolder(context: Context, dir: File, onGame: (Game) -> Unit = {}, onChecking: (String?) -> Unit = {}, showHidden: Boolean = false): FolderResult {
|
fun addFolder(context: Context, dir: File, onGame: (Game) -> Unit = {}, onChecking: (String?) -> Unit = {}): FolderResult {
|
||||||
val app = context.applicationContext
|
val app = context.applicationContext
|
||||||
// Binds are mounted at session start, so a new one reaches the session from the next start.
|
// Binds are mounted at session start, so a new one reaches the session from the next start.
|
||||||
if (guestPath(app, dir) == null) bindFolder(app, dir)
|
if (guestPath(app, dir) == null) bindFolder(app, dir)
|
||||||
@@ -298,7 +283,7 @@ object AddedGames {
|
|||||||
var already = 0
|
var already = 0
|
||||||
val fresh = ArrayList<String>()
|
val fresh = ArrayList<String>()
|
||||||
val added = ArrayList<Game>()
|
val added = ArrayList<Game>()
|
||||||
for (sub in dir.listFiles { f -> f.isDirectory && (showHidden || !f.name.startsWith(".")) }?.sortedBy { it.name.lowercase() }.orEmpty()) {
|
for (sub in dir.listFiles { f -> f.isDirectory && !f.name.startsWith(".") }?.sortedBy { it.name.lowercase() }.orEmpty()) {
|
||||||
val path = canonical(sub)
|
val path = canonical(sub)
|
||||||
if (listed.any { it == path || inside(path, it) || inside(it, path) }) { already++; continue }
|
if (listed.any { it == path || inside(path, it) || inside(it, path) }) { already++; continue }
|
||||||
onChecking(sub.name)
|
onChecking(sub.name)
|
||||||
@@ -402,17 +387,11 @@ object AddedGames {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private class LoginUser(val id: String, val mostRecent: Boolean, val autoLogin: Boolean, val timestamp: Long)
|
|
||||||
|
|
||||||
internal fun accountConfig(root: File): File? {
|
internal fun accountConfig(root: File): File? {
|
||||||
val users = runCatching { File(root, "config/loginusers.vdf").readText() }.getOrDefault("")
|
val users = runCatching { File(root, "config/loginusers.vdf").readText() }.getOrDefault("")
|
||||||
val recent = Regex(""""(\d{5,})"\s*\{([^}]*)\}""").findAll(users).map {
|
val recent = Regex(""""(\d{5,})"\s*\{([^}]*)\}""").findAll(users)
|
||||||
val body = it.groupValues[2]
|
.lastOrNull { Regex(""""MostRecent"\s*"1"""").containsMatchIn(it.groupValues[2]) }
|
||||||
LoginUser(it.groupValues[1], Regex(""""MostRecent"\s*"1"""").containsMatchIn(body), Regex(""""AutoLogin"\s*"1"""").containsMatchIn(body),
|
val account = recent?.groupValues?.get(1)?.toLongOrNull()?.let { (it - 76561197960265728L).toString() }
|
||||||
Regex(""""timestamp"\s*"(\d+)"""").find(body)?.groupValues?.get(1)?.toLongOrNull() ?: 0L)
|
|
||||||
}.filter { it.mostRecent || it.autoLogin || it.timestamp > 0 }.toList().asReversed()
|
|
||||||
.maxWithOrNull(compareBy<LoginUser>({ it.mostRecent }, { it.autoLogin }, { it.timestamp }))
|
|
||||||
val account = recent?.id?.toLongOrNull()?.let { (it - 76561197960265728L).toString() }
|
|
||||||
?: File(root, "userdata").list()?.filter { it.isNotEmpty() && it.all(Char::isDigit) && it != "0" }?.singleOrNull()
|
?: File(root, "userdata").list()?.filter { it.isNotEmpty() && it.all(Char::isDigit) && it != "0" }?.singleOrNull()
|
||||||
return account?.let { File(root, "userdata/$it/config") }
|
return account?.let { File(root, "userdata/$it/config") }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -257,18 +257,14 @@ object AutoComponents {
|
|||||||
|
|
||||||
|
|
||||||
private const val FINDINGS = "wincomp-findings.json"
|
private const val FINDINGS = "wincomp-findings.json"
|
||||||
private const val DETECTORS = "d3"
|
|
||||||
|
|
||||||
internal fun signature(context: Context, game: Library.SteamGame): String {
|
internal fun signature(context: Context, game: Library.SteamGame): String {
|
||||||
val folder = game.gameFiles
|
val folder = game.gameFiles
|
||||||
val parts = listOfNotNull(
|
val parts = listOfNotNull(
|
||||||
DETECTORS,
|
|
||||||
folder?.lastModified(),
|
folder?.lastModified(),
|
||||||
folder?.let { SteamRedists.manifest(it, game.appId)?.lastModified() },
|
folder?.let { SteamRedists.manifest(it, game.appId)?.lastModified() },
|
||||||
folder?.let { StoreGameSidecar.file(it).lastModified() },
|
folder?.let { StoreGameSidecar.file(it).lastModified() },
|
||||||
folder?.let { File(it, "fuel.json").lastModified() },
|
folder?.let { File(it, "fuel.json").lastModified() },
|
||||||
folder?.listFiles { f -> f.name.lowercase().let { it.startsWith("installscript") && it.endsWith(".vdf") } }
|
|
||||||
?.maxOfOrNull { it.lastModified() },
|
|
||||||
SteamAppInfo.appinfoFile(context).lastModified(),
|
SteamAppInfo.appinfoFile(context).lastModified(),
|
||||||
folder?.let { SteamMatch.get(context, it.path) }?.let { "${it.appId}/${it.certainty}" },
|
folder?.let { SteamMatch.get(context, it.path) }?.let { "${it.appId}/${it.certainty}" },
|
||||||
steamAppOf(context, game)?.let { SteamAppInfo.state(context, it) },
|
steamAppOf(context, game)?.let { SteamAppInfo.state(context, it) },
|
||||||
|
|||||||
@@ -63,8 +63,7 @@ object CoverArt {
|
|||||||
missFile(context, rom).delete()
|
missFile(context, rom).delete()
|
||||||
found = true
|
found = true
|
||||||
} else {
|
} else {
|
||||||
runCatching { missFile(context, rom).apply { parentFile?.mkdirs(); writeText(url ?: "") } }
|
missFile(context, rom).apply { parentFile?.mkdirs(); writeText(url ?: "") }
|
||||||
.onFailure { Log.w(TAG, "${rom.name}: miss marker not written: $it") }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return found
|
return found
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ object GameRemoval {
|
|||||||
enum class Kind { STORE, SHORTCUT, LAUNCHER }
|
enum class Kind { STORE, SHORTCUT, LAUNCHER }
|
||||||
|
|
||||||
fun kind(game: Library.SteamGame): Kind = when {
|
fun kind(game: Library.SteamGame): Kind = when {
|
||||||
game.library == Library.EPIC_LAUNCHER || game.library == Library.BATTLENET_LAUNCHER -> Kind.LAUNCHER
|
game.library == Library.EPIC_LAUNCHER -> Kind.LAUNCHER
|
||||||
game.library == Library.ADDED && game.source == Library.ADDED -> Kind.SHORTCUT
|
game.library == Library.ADDED && game.source == Library.ADDED -> Kind.SHORTCUT
|
||||||
else -> Kind.STORE
|
else -> Kind.STORE
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,13 +11,13 @@ import android.graphics.drawable.Icon
|
|||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
import com.droiddeck.launcher.LauncherIcon
|
import com.droiddeck.launcher.LauncherIcon
|
||||||
import com.droiddeck.launcher.FrontEndActivity
|
import com.droiddeck.launcher.MainActivity
|
||||||
import com.droiddeck.launcher.R
|
import com.droiddeck.launcher.R
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
object GameShortcuts {
|
object GameShortcuts {
|
||||||
fun launchIntent(context: Context, gameId: String) = Intent(Intent.ACTION_VIEW,
|
fun launchIntent(context: Context, gameId: String) = Intent(Intent.ACTION_VIEW,
|
||||||
Uri.parse(GameLaunchLink.uri(gameId)), context, FrontEndActivity::class.java)
|
Uri.parse(GameLaunchLink.uri(gameId)), context, MainActivity::class.java)
|
||||||
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||||
|
|
||||||
private fun info(context: Context, game: Library.SteamGame): ShortcutInfo {
|
private fun info(context: Context, game: Library.SteamGame): ShortcutInfo {
|
||||||
|
|||||||
@@ -16,23 +16,16 @@ object Library {
|
|||||||
val icon: File? = null,
|
val icon: File? = null,
|
||||||
val source: String = SOURCE_STEAM,
|
val source: String = SOURCE_STEAM,
|
||||||
val storeId: String? = null,
|
val storeId: String? = null,
|
||||||
val logo: File? = null,
|
|
||||||
) {
|
) {
|
||||||
fun withArt(art: File?, hero: File?, icon: File?, logo: File? = this.logo) =
|
fun withArt(art: File?, hero: File?, icon: File?) =
|
||||||
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo)
|
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId)
|
||||||
|
|
||||||
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
|
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
|
||||||
val profileKey: String get() = when {
|
val profileKey: String get() = if (library == ADDED) java.lang.Integer.toUnsignedString(appId) else appId.toString()
|
||||||
source == com.droiddeck.launcher.stores.Store.BATTLENET.id -> com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString()
|
|
||||||
library == ADDED -> java.lang.Integer.toUnsignedString(appId)
|
|
||||||
else -> appId.toString()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
const val ADDED = "added"
|
const val ADDED = "added"
|
||||||
const val EPIC_LAUNCHER = "epic-launcher"
|
const val EPIC_LAUNCHER = "epic-launcher"
|
||||||
const val EPIC_LAUNCHER_NAME = "Epic Games Launcher"
|
const val EPIC_LAUNCHER_NAME = "Epic Games Launcher"
|
||||||
const val BATTLENET_LAUNCHER = "battlenet-launcher"
|
|
||||||
const val XBOX_CLOUD = "xbox-cloud"
|
|
||||||
const val SOURCE_STEAM = "steam"
|
const val SOURCE_STEAM = "steam"
|
||||||
|
|
||||||
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
|
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
|
||||||
@@ -52,14 +45,12 @@ object Library {
|
|||||||
1054830,
|
1054830,
|
||||||
1070560,
|
1070560,
|
||||||
1113280,
|
1113280,
|
||||||
1161040,
|
|
||||||
1245040,
|
1245040,
|
||||||
1391110,
|
1391110,
|
||||||
1420170,
|
1420170,
|
||||||
1493710,
|
1493710,
|
||||||
1580130,
|
1580130,
|
||||||
1628350,
|
1628350,
|
||||||
1826330,
|
|
||||||
1887720,
|
1887720,
|
||||||
2180100,
|
2180100,
|
||||||
228980,
|
228980,
|
||||||
@@ -77,7 +68,6 @@ object Library {
|
|||||||
)
|
)
|
||||||
private val STEAM_CAPSULES = listOf("library_capsule.jpg", "library_600x900.jpg")
|
private val STEAM_CAPSULES = listOf("library_capsule.jpg", "library_600x900.jpg")
|
||||||
private val STEAM_HEROES = listOf("library_hero.jpg")
|
private val STEAM_HEROES = listOf("library_hero.jpg")
|
||||||
internal val STEAM_LOGOS = listOf("logo.png")
|
|
||||||
private val STEAM_ICON = Regex("[a-fA-F0-9]{40}\\.(jpg|png)")
|
private val STEAM_ICON = Regex("[a-fA-F0-9]{40}\\.(jpg|png)")
|
||||||
private val NAME = Regex("^\\s*\"name\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
|
private val NAME = Regex("^\\s*\"name\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
|
||||||
private val STATE = Regex("^\\s*\"StateFlags\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
|
private val STATE = Regex("^\\s*\"StateFlags\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
|
||||||
@@ -112,10 +102,7 @@ object Library {
|
|||||||
.firstOrNull { it.isDirectory }
|
.firstOrNull { it.isDirectory }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun steamGames(
|
fun steamGames(context: Context, strictRead: Boolean = false, arch: String = SessionPrefs.activeSteamClientArch(context)): List<SteamGame> {
|
||||||
context: Context, strictRead: Boolean = false, arch: String = SessionPrefs.activeSteamClientArch(context),
|
|
||||||
withShared: Boolean = true,
|
|
||||||
): List<SteamGame> {
|
|
||||||
val root = SessionPrefs.steamRoot(context, arch)
|
val root = SessionPrefs.steamRoot(context, arch)
|
||||||
val cache = File(root, "appcache/librarycache")
|
val cache = File(root, "appcache/librarycache")
|
||||||
val libraries = steamLibraries(context, arch)
|
val libraries = steamLibraries(context, arch)
|
||||||
@@ -132,9 +119,8 @@ object Library {
|
|||||||
val name = NAME.find(text)?.groupValues?.get(1)?.trim().orEmpty()
|
val name = NAME.find(text)?.groupValues?.get(1)?.trim().orEmpty()
|
||||||
val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
|
val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
|
||||||
if (name.isEmpty() || flags and 4 == 0) return@forEach
|
if (name.isEmpty() || flags and 4 == 0) return@forEach
|
||||||
val images = SteamCacheImages(File(cache, appId.toString()))
|
val art = steamCacheImage(cache, appId, STEAM_CAPSULES)
|
||||||
val art = images.find(STEAM_CAPSULES)
|
val hero = steamCacheImage(cache, appId, STEAM_HEROES)
|
||||||
val hero = images.find(STEAM_HEROES)
|
|
||||||
val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
|
val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
|
||||||
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
|
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
|
||||||
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
|
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
|
||||||
@@ -143,25 +129,14 @@ object Library {
|
|||||||
appId, name, art, label, hero = hero, lastPlayed = lastPlayed,
|
appId, name, art, label, hero = hero, lastPlayed = lastPlayed,
|
||||||
gameFiles = gameFiles,
|
gameFiles = gameFiles,
|
||||||
protonPrefix = protonPrefix(context, appId.toLong(), library, roots),
|
protonPrefix = protonPrefix(context, appId.toLong(), library, roots),
|
||||||
icon = images.icon(),
|
icon = steamCacheImage(cache, appId, listOf("icon.jpg", "icon.png"))
|
||||||
logo = images.find(STEAM_LOGOS),
|
?: File(cache, appId.toString()).listFiles()?.firstOrNull { it.isFile && STEAM_ICON.matches(it.name) },
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (withShared) {
|
|
||||||
val other = if (arch == "x86_64") "arm64" else "x86_64"
|
|
||||||
val shared = sharedApps(context, arch) - out.keys
|
|
||||||
if (shared.isNotEmpty()) runCatching { steamGames(context, arch = other, withShared = false) }.getOrDefault(emptyList())
|
|
||||||
.filter { it.appId in shared }.forEach { out[it.appId] = it }
|
|
||||||
}
|
|
||||||
return out.values.toList()
|
return out.values.toList()
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun sharedApps(context: Context, arch: String): Set<Int> {
|
|
||||||
val view = File(LinuxRuntime.rootDir(context), "root/.droiddeck-x64/shared/${if (arch == "x86_64") "arm64" else "x86-64"}/steamapps")
|
|
||||||
return view.list().orEmpty().mapNotNull { Regex("appmanifest_(\\d+)\\.acf").matchEntire(it)?.groupValues?.get(1)?.toIntOrNull() }.toSet()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun steamLibraryArt(context: Context): List<Pair<Int, File>> {
|
fun steamLibraryArt(context: Context): List<Pair<Int, File>> {
|
||||||
val root = SessionPrefs.activeSteamRoot(context)
|
val root = SessionPrefs.activeSteamRoot(context)
|
||||||
val cache = File(root, "appcache/librarycache")
|
val cache = File(root, "appcache/librarycache")
|
||||||
@@ -209,24 +184,9 @@ object Library {
|
|||||||
(runCatching { g.folder.canonicalPath }.getOrDefault(g.folder.absolutePath) !in claimed &&
|
(runCatching { g.folder.canonicalPath }.getOrDefault(g.folder.absolutePath) !in claimed &&
|
||||||
AddedGames.guestPath(context, g.folder).let { it == null || it !in claimed })
|
AddedGames.guestPath(context, g.folder).let { it == null || it !in claimed })
|
||||||
}
|
}
|
||||||
val played = shortcutsLastPlayed(SessionPrefs.steamRoot(context, arch))
|
return (steam + own.map { g -> addedGame(context, g, roots) }).distinctBy { it.gameId }
|
||||||
return (steam + own.map { g -> addedGame(context, g, roots, played[g.appId] ?: 0L) }).distinctBy { it.gameId }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Steam's LastPlayTime for each non-Steam shortcut, by its unsigned shortcut app id. */
|
|
||||||
internal fun shortcutsLastPlayed(root: File): Map<Long, Long> = runCatching {
|
|
||||||
val config = AddedGames.accountConfig(root) ?: return emptyMap()
|
|
||||||
val bytes = File(config, "shortcuts.vdf").takeIf { it.isFile }?.readBytes() ?: return emptyMap()
|
|
||||||
val vdf = SteamAppInfo.readMap(java.nio.ByteBuffer.wrap(bytes).order(java.nio.ByteOrder.LITTLE_ENDIAN), null)
|
|
||||||
(vdf["shortcuts"] as? Map<*, *>)?.values?.filterIsInstance<Map<*, *>>()?.mapNotNull { s ->
|
|
||||||
fun int(key: String) = s.entries.firstOrNull { (it.key as? String).equals(key, ignoreCase = true) }
|
|
||||||
?.let { (it.value as? String)?.toLongOrNull() }?.and(0xFFFFFFFFL)
|
|
||||||
val id = int("appid") ?: return@mapNotNull null
|
|
||||||
val time = int("LastPlayTime")?.takeIf { it > 0L } ?: return@mapNotNull null
|
|
||||||
id to time
|
|
||||||
}?.toMap()
|
|
||||||
}.getOrNull().orEmpty()
|
|
||||||
|
|
||||||
fun claimedFolders(steam: List<SteamGame>): Set<String> = steam.filter(::fromSteamClient).flatMap { g ->
|
fun claimedFolders(steam: List<SteamGame>): Set<String> = steam.filter(::fromSteamClient).flatMap { g ->
|
||||||
val dir = g.gameFiles ?: return@flatMap emptyList()
|
val dir = g.gameFiles ?: return@flatMap emptyList()
|
||||||
listOfNotNull(
|
listOfNotNull(
|
||||||
@@ -235,35 +195,24 @@ object Library {
|
|||||||
)
|
)
|
||||||
}.toSet()
|
}.toSet()
|
||||||
|
|
||||||
fun addedGame(
|
fun addedGame(context: Context, g: AddedGames.Game, roots: List<File> = steamLibraries(context).map { it.first }): SteamGame =
|
||||||
context: Context, g: AddedGames.Game, roots: List<File> = steamLibraries(context).map { it.first },
|
|
||||||
lastPlayed: Long = 0L,
|
|
||||||
): SteamGame =
|
|
||||||
AddedGameArt.resolve(context, g).let { art ->
|
AddedGameArt.resolve(context, g).let { art ->
|
||||||
SteamGame(
|
SteamGame(
|
||||||
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
|
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
|
||||||
hero = art.hero ?: art.header, lastPlayed = lastPlayed, gameFiles = g.folder,
|
hero = art.hero ?: art.header, gameFiles = g.folder,
|
||||||
protonPrefix = if (g.source == com.droiddeck.launcher.stores.Store.BATTLENET.id) File(com.droiddeck.launcher.runtime.BattleNet.prefix(context), "pfx").takeIf { it.isDirectory }
|
protonPrefix = protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
|
||||||
else protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
|
|
||||||
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
|
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
|
||||||
source = g.source, storeId = g.storeId,
|
source = g.source, storeId = g.storeId,
|
||||||
logo = art.logo,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun steamCacheImage(cache: File, appId: Int, names: List<String>): File? =
|
internal fun steamCacheImage(cache: File, appId: Int, names: List<String>): File? {
|
||||||
SteamCacheImages(File(cache, appId.toString())).find(names)
|
val appDir = File(cache, appId.toString())
|
||||||
|
val dirs = listOf(appDir) + appDir.listFiles()
|
||||||
internal class SteamCacheImages(appDir: File) {
|
.orEmpty().filter { it.isDirectory }.sortedBy { it.name }
|
||||||
private val entries = appDir.listFiles().orEmpty()
|
return names.asSequence()
|
||||||
private val dirs = listOf(appDir) + entries.filter { it.isDirectory }.sortedBy { it.name }
|
|
||||||
|
|
||||||
fun find(names: List<String>): File? = names.asSequence()
|
|
||||||
.flatMap { name -> dirs.asSequence().map { File(it, name) } }
|
.flatMap { name -> dirs.asSequence().map { File(it, name) } }
|
||||||
.firstOrNull { it.isFile && it.length() > 0L }
|
.firstOrNull { it.isFile && it.length() > 0L }
|
||||||
|
|
||||||
fun icon(): File? = find(listOf("icon.jpg", "icon.png"))
|
|
||||||
?: entries.firstOrNull { it.isFile && STEAM_ICON.matches(it.name) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private class Spec(val id: String, val name: String, val system: String, val program: String, val folders: List<String>, val exts: Set<String>, val atPanel: Boolean = false)
|
private class Spec(val id: String, val name: String, val system: String, val program: String, val folders: List<String>, val exts: Set<String>, val atPanel: Boolean = false)
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ object LibraryCache {
|
|||||||
icon = o.file("icon"),
|
icon = o.file("icon"),
|
||||||
source = o.optString("source").ifEmpty { if (o.getString("library") == Library.ADDED) Library.ADDED else Library.SOURCE_STEAM },
|
source = o.optString("source").ifEmpty { if (o.getString("library") == Library.ADDED) Library.ADDED else Library.SOURCE_STEAM },
|
||||||
storeId = o.optString("storeId").ifEmpty { null },
|
storeId = o.optString("storeId").ifEmpty { null },
|
||||||
logo = o.file("logo"),
|
|
||||||
)
|
)
|
||||||
} to x64
|
} to x64
|
||||||
}.getOrElse { e -> Log.w(TAG, "unreadable, ignored: ${e.message}"); Pair(emptyList(), false) }
|
}.getOrElse { e -> Log.w(TAG, "unreadable, ignored: ${e.message}"); Pair(emptyList(), false) }
|
||||||
@@ -45,7 +44,7 @@ object LibraryCache {
|
|||||||
for (g in games) array.put(
|
for (g in games) array.put(
|
||||||
JSONObject().put("appId", g.appId).put("name", g.name).put("library", g.library).put("gameId", g.gameId)
|
JSONObject().put("appId", g.appId).put("name", g.name).put("library", g.library).put("gameId", g.gameId)
|
||||||
.put("lastPlayed", g.lastPlayed).putFile("art", g.art).putFile("hero", g.hero)
|
.put("lastPlayed", g.lastPlayed).putFile("art", g.art).putFile("hero", g.hero)
|
||||||
.putFile("gameFiles", g.gameFiles).putFile("protonPrefix", g.protonPrefix).putFile("icon", g.icon).putFile("logo", g.logo)
|
.putFile("gameFiles", g.gameFiles).putFile("protonPrefix", g.protonPrefix).putFile("icon", g.icon)
|
||||||
.put("source", g.source).apply { g.storeId?.let { put("storeId", it) } },
|
.put("source", g.source).apply { g.storeId?.let { put("storeId", it) } },
|
||||||
)
|
)
|
||||||
val f = file(context)
|
val f = file(context)
|
||||||
|
|||||||
@@ -22,12 +22,10 @@ object SteamGameArt {
|
|||||||
val cover = chosenFile(context, game.appId, AddedGameArt.Slot.COVER)
|
val cover = chosenFile(context, game.appId, AddedGameArt.Slot.COVER)
|
||||||
val hero = chosenFile(context, game.appId, AddedGameArt.Slot.BACKGROUND)
|
val hero = chosenFile(context, game.appId, AddedGameArt.Slot.BACKGROUND)
|
||||||
val icon = chosenFile(context, game.appId, AddedGameArt.Slot.ICON)
|
val icon = chosenFile(context, game.appId, AddedGameArt.Slot.ICON)
|
||||||
val logo = chosenFile(context, game.appId, AddedGameArt.Slot.LOGO)
|
if (cover == null && hero == null && icon == null) return game
|
||||||
if (cover == null && hero == null && icon == null && logo == null) return game
|
|
||||||
return Library.SteamGame(
|
return Library.SteamGame(
|
||||||
game.appId, game.name, cover ?: game.art, game.library, game.gameId,
|
game.appId, game.name, cover ?: game.art, game.library, game.gameId,
|
||||||
hero ?: game.hero, game.lastPlayed, game.gameFiles, game.protonPrefix, icon ?: game.icon, game.source, game.storeId,
|
hero ?: game.hero, game.lastPlayed, game.gameFiles, game.protonPrefix, icon ?: game.icon, game.source, game.storeId,
|
||||||
logo ?: game.logo,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import android.util.Log
|
|||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.util.UUID
|
|
||||||
|
|
||||||
/** Steam keeps a game's custom art in `userdata/<account>/config/grid`; this is where DroidDeck's choices and Steam's meet. */
|
/** Steam keeps a game's custom art in `userdata/<account>/config/grid`; this is where DroidDeck's choices and Steam's meet. */
|
||||||
object SteamGrid {
|
object SteamGrid {
|
||||||
@@ -42,42 +41,14 @@ object SteamGrid {
|
|||||||
|
|
||||||
private fun sigFile(context: Context, target: Target, slot: AddedGameArt.Slot) = File(target.artDir, sigName(context, slot.key))
|
private fun sigFile(context: Context, target: Target, slot: AddedGameArt.Slot) = File(target.artDir, sigName(context, slot.key))
|
||||||
|
|
||||||
private const val GRID_ID = ".droiddeck-grid"
|
private fun recorded(context: Context, target: Target, slot: AddedGameArt.Slot): String? =
|
||||||
private const val UNKNOWN_GRID = "?"
|
sigFile(context, target, slot).takeIf { it.isFile }?.readText()
|
||||||
|
|
||||||
/**
|
private fun record(context: Context, target: Target, slot: AddedGameArt.Slot, value: String) {
|
||||||
* A random id kept in the grid folder, so a record made against another account's folder, or one wiped with the
|
|
||||||
* runtime, reads as "not seen yet" instead of "removed in Steam". "?" never matches, so nothing is dropped.
|
|
||||||
*/
|
|
||||||
private fun gridId(grid: File): String = runCatching {
|
|
||||||
val f = File(grid, GRID_ID)
|
|
||||||
f.takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: UUID.randomUUID().toString().also { id ->
|
|
||||||
grid.mkdirs()
|
|
||||||
val tmp = File(grid, "$GRID_ID.tmp")
|
|
||||||
tmp.writeText(id)
|
|
||||||
if (f.isFile) f.delete()
|
|
||||||
if (!tmp.renameTo(f)) error("grid id")
|
|
||||||
}
|
|
||||||
}.getOrDefault(UNKNOWN_GRID)
|
|
||||||
|
|
||||||
private fun readRecord(grid: File, file: File): String? {
|
|
||||||
val text = file.takeIf { it.isFile }?.readText() ?: return null
|
|
||||||
val cut = text.indexOf('\n')
|
|
||||||
val id = gridId(grid)
|
|
||||||
return if (cut > 0 && id != UNKNOWN_GRID && text.substring(0, cut) == id) text.substring(cut + 1) else null
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun writeRecord(grid: File, target: Target, file: File, value: String) {
|
|
||||||
target.artDir.mkdirs()
|
target.artDir.mkdirs()
|
||||||
file.writeText("${gridId(grid)}\n$value")
|
sigFile(context, target, slot).writeText(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun recorded(context: Context, grid: File, target: Target, slot: AddedGameArt.Slot): String? =
|
|
||||||
readRecord(grid, sigFile(context, target, slot))
|
|
||||||
|
|
||||||
private fun record(context: Context, grid: File, target: Target, slot: AddedGameArt.Slot, value: String) =
|
|
||||||
writeRecord(grid, target, sigFile(context, target, slot), value)
|
|
||||||
|
|
||||||
private fun writtenByDroidDeck(grid: File): Set<String> = runCatching {
|
private fun writtenByDroidDeck(grid: File): Set<String> = runCatching {
|
||||||
val manifest = JSONObject(File(grid, MANIFEST).readText())
|
val manifest = JSONObject(File(grid, MANIFEST).readText())
|
||||||
manifest.keys().asSequence().filter { name -> File(grid, name).let { it.isFile && it.length() == manifest.optLong(name, -1L) } }.toSet()
|
manifest.keys().asSequence().filter { name -> File(grid, name).let { it.isFile && it.length() == manifest.optLong(name, -1L) } }.toSet()
|
||||||
@@ -91,7 +62,7 @@ object SteamGrid {
|
|||||||
val grid = dir(context) ?: return true
|
val grid = dir(context) ?: return true
|
||||||
if (file == null) {
|
if (file == null) {
|
||||||
if (files(grid, target.id, slot).map { it.delete() }.any { !it }) return false
|
if (files(grid, target.id, slot).map { it.delete() }.any { !it }) return false
|
||||||
record(context, grid, target, slot, "")
|
record(context, target, slot, "")
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
val ext = file.extension.lowercase().let { if (it == "jpeg") "jpg" else it }
|
val ext = file.extension.lowercase().let { if (it == "jpeg") "jpg" else it }
|
||||||
@@ -105,7 +76,7 @@ object SteamGrid {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if (files(grid, target.id, slot).filter { it != dst }.map { it.delete() }.any { !it }) return false
|
if (files(grid, target.id, slot).filter { it != dst }.map { it.delete() }.any { !it }) return false
|
||||||
record(context, grid, target, slot, signature(placed))
|
record(context, target, slot, signature(placed))
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,11 +90,13 @@ object SteamGrid {
|
|||||||
/** The logo position chosen here (or taken over from Steam) for a game; null when Steam's own default applies. */
|
/** The logo position chosen here (or taken over from Steam) for a game; null when Steam's own default applies. */
|
||||||
fun position(target: Target): LogoPosition.Value? = positionIn(File(target.artDir, POSITION))
|
fun position(target: Target): LogoPosition.Value? = positionIn(File(target.artDir, POSITION))
|
||||||
|
|
||||||
private fun positionRecorded(context: Context, grid: File, target: Target): String? =
|
private fun positionRecorded(context: Context, target: Target): String? =
|
||||||
readRecord(grid, File(target.artDir, sigName(context, POSITION_SIG)))
|
File(target.artDir, sigName(context, POSITION_SIG)).takeIf { it.isFile }?.readText()
|
||||||
|
|
||||||
private fun recordPosition(context: Context, grid: File, target: Target, value: String) =
|
private fun recordPosition(context: Context, target: Target, value: String) {
|
||||||
writeRecord(grid, target, File(target.artDir, sigName(context, POSITION_SIG)), value)
|
target.artDir.mkdirs()
|
||||||
|
File(target.artDir, sigName(context, POSITION_SIG)).writeText(value)
|
||||||
|
}
|
||||||
|
|
||||||
private fun storePosition(target: Target, value: LogoPosition.Value?): Boolean {
|
private fun storePosition(target: Target, value: LogoPosition.Value?): Boolean {
|
||||||
val file = File(target.artDir, POSITION)
|
val file = File(target.artDir, POSITION)
|
||||||
@@ -146,7 +119,7 @@ object SteamGrid {
|
|||||||
val next = if (value == null) existing?.let(LogoPosition::without) else LogoPosition.toJson(value, existing ?: JSONObject())
|
val next = if (value == null) existing?.let(LogoPosition::without) else LogoPosition.toJson(value, existing ?: JSONObject())
|
||||||
if (next == null) {
|
if (next == null) {
|
||||||
if (file.isFile && !file.delete()) return false
|
if (file.isFile && !file.delete()) return false
|
||||||
recordPosition(context, grid, target, "")
|
recordPosition(context, target, "")
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
grid.mkdirs()
|
grid.mkdirs()
|
||||||
@@ -156,7 +129,7 @@ object SteamGrid {
|
|||||||
tmp.delete()
|
tmp.delete()
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
recordPosition(context, grid, target, signature(file))
|
recordPosition(context, target, signature(file))
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,16 +144,16 @@ object SteamGrid {
|
|||||||
if (hasUnknownPosition(file)) return
|
if (hasUnknownPosition(file)) return
|
||||||
val theirs = positionIn(file)
|
val theirs = positionIn(file)
|
||||||
val now = if (theirs != null) signature(file) else ""
|
val now = if (theirs != null) signature(file) else ""
|
||||||
val before = positionRecorded(context, grid, target)
|
val before = positionRecorded(context, target)
|
||||||
val own = position(target)
|
val own = position(target)
|
||||||
when {
|
when {
|
||||||
before == null && own != null && theirs == null -> placePosition(context, target, own)
|
before == null && own != null && theirs == null -> placePosition(context, target, own)
|
||||||
before == null || now != before -> {
|
before == null || now != before -> {
|
||||||
// Recorded only once the local side agrees, so a failed take-over is tried again on the next scan.
|
// Recorded only once the local side agrees, so a failed take-over is tried again on the next scan.
|
||||||
if (theirs != null) {
|
if (theirs != null) {
|
||||||
if (own == theirs || storePosition(target, theirs)) recordPosition(context, grid, target, now)
|
if (own == theirs || storePosition(target, theirs)) recordPosition(context, target, now)
|
||||||
} else {
|
} else {
|
||||||
if (own == null || storePosition(target, null)) recordPosition(context, grid, target, "")
|
if (own == null || storePosition(target, null)) recordPosition(context, target, "")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
own != null && own != theirs -> placePosition(context, target, own)
|
own != null && own != theirs -> placePosition(context, target, own)
|
||||||
@@ -200,20 +173,20 @@ object SteamGrid {
|
|||||||
val present = files(grid, target.id, slot)
|
val present = files(grid, target.id, slot)
|
||||||
val theirs = present.filter { it.name !in ours }.maxByOrNull { it.lastModified() }
|
val theirs = present.filter { it.name !in ours }.maxByOrNull { it.lastModified() }
|
||||||
val now = signature(theirs)
|
val now = signature(theirs)
|
||||||
val before = recorded(context, grid, target, slot)
|
val before = recorded(context, target, slot)
|
||||||
when {
|
when {
|
||||||
before == null && own != null && theirs == null -> write(context, target, slot, own)
|
before == null && own != null && theirs == null -> write(context, target, slot, own)
|
||||||
before == null || now != before -> {
|
before == null || now != before -> {
|
||||||
if (theirs != null) {
|
if (theirs != null) {
|
||||||
if (own != null && own.length() == theirs.length() && own.readBytes().contentEquals(theirs.readBytes())) record(context, grid, target, slot, now)
|
if (own != null && own.length() == theirs.length() && own.readBytes().contentEquals(theirs.readBytes())) record(context, target, slot, now)
|
||||||
else if (AddedGameArt.store(target.artDir, slot, AddedGameArt.Option(AddedGameArt.STEAM, theirs.path, theirs.path))) {
|
else if (AddedGameArt.store(target.artDir, slot, AddedGameArt.Option(AddedGameArt.STEAM, theirs.path, theirs.path))) {
|
||||||
target.setSource(slot, AddedGameArt.STEAM + "|steam-client")
|
target.setSource(slot, AddedGameArt.STEAM + "|steam-client")
|
||||||
record(context, grid, target, slot, now)
|
record(context, target, slot, now)
|
||||||
changed = true
|
changed = true
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (own != null && present.isEmpty()) { own.delete(); target.setSource(slot, ""); changed = true }
|
if (own != null && present.isEmpty()) { own.delete(); target.setSource(slot, ""); changed = true }
|
||||||
record(context, grid, target, slot, "")
|
record(context, target, slot, "")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
own != null && theirs != null && now == before && own.length() != theirs.length() -> write(context, target, slot, own)
|
own != null && theirs != null && now == before && own.length() != theirs.length() -> write(context, target, slot, own)
|
||||||
|
|||||||
@@ -84,23 +84,18 @@ object SteamGridDb {
|
|||||||
.filter { it.second > 0 && it.first > 0 }
|
.filter { it.second > 0 && it.first > 0 }
|
||||||
.maxByOrNull { it.second }?.first
|
.maxByOrNull { it.second }?.first
|
||||||
|
|
||||||
internal fun cacheName(slot: AddedGameArt.Slot): String =
|
fun download(key: String, id: Int, cache: File): Boolean {
|
||||||
when (slot) {
|
|
||||||
AddedGameArt.Slot.COVER -> "p.jpg"
|
|
||||||
AddedGameArt.Slot.WIDE -> "header.jpg"
|
|
||||||
AddedGameArt.Slot.BACKGROUND -> "hero.jpg"
|
|
||||||
AddedGameArt.Slot.LOGO -> "logo.png"
|
|
||||||
AddedGameArt.Slot.ICON -> "icon-sgdb.png"
|
|
||||||
}
|
|
||||||
|
|
||||||
fun download(key: String, id: Int, cache: File, slots: Set<AddedGameArt.Slot> = AddedGameArt.Slot.values().toSet()): Boolean {
|
|
||||||
var got = false
|
var got = false
|
||||||
for (slot in AddedGameArt.Slot.values()) {
|
for ((path, local) in listOf(
|
||||||
if (slot !in slots) continue
|
"grids/game/$id?dimensions=600x900&$QUERY" to "p.jpg",
|
||||||
val local = cacheName(slot)
|
"grids/game/$id?dimensions=460x215,920x430&$QUERY" to "header.jpg",
|
||||||
|
"heroes/game/$id?$QUERY" to "hero.jpg",
|
||||||
|
"logos/game/$id?$QUERY" to "logo.png",
|
||||||
|
"icons/game/$id?$QUERY" to "icon-sgdb.png",
|
||||||
|
)) {
|
||||||
val dst = File(cache, local)
|
val dst = File(cache, local)
|
||||||
if (dst.isFile) continue
|
if (dst.isFile) continue
|
||||||
val items = json(key, "$API/${path(id, slot)}")?.optJSONArray("data") ?: continue
|
val items = json(key, "$API/$path")?.optJSONArray("data") ?: continue
|
||||||
val url = best(items, local.endsWith(".png")) ?: continue
|
val url = best(items, local.endsWith(".png")) ?: continue
|
||||||
val bytes = AddedGameArt.get(url) ?: continue
|
val bytes = AddedGameArt.get(url) ?: continue
|
||||||
val tmp = File(cache, "$local.tmp")
|
val tmp = File(cache, "$local.tmp")
|
||||||
|
|||||||
@@ -15,11 +15,6 @@ object SteamRedists {
|
|||||||
"228989" to ("vcredist2022_dll" to "VC++ 2022"),
|
"228989" to ("vcredist2022_dll" to "VC++ 2022"),
|
||||||
"228990" to ("d3dx9" to "DirectX (June 2010)"),
|
"228990" to ("d3dx9" to "DirectX (June 2010)"),
|
||||||
)
|
)
|
||||||
/** Redists a game's own install script runs on Windows that its shared depots don't name. */
|
|
||||||
val SCRIPTED = mapOf(
|
|
||||||
72850 to listOf("xact" to "DirectX XACT audio"),
|
|
||||||
489830 to listOf("xact_x64" to "DirectX XACT audio (64-bit)"),
|
|
||||||
)
|
|
||||||
private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE)
|
private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE)
|
||||||
private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"")
|
private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"")
|
||||||
|
|
||||||
@@ -28,17 +23,6 @@ object SteamRedists {
|
|||||||
return File(steamapps, "appmanifest_$appId.acf").takeIf { it.isFile }
|
return File(steamapps, "appmanifest_$appId.acf").takeIf { it.isFile }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Redists the game's own install script has Steam run on Windows, from its "Run Process" entries. */
|
|
||||||
fun installScript(gameDir: File?): List<Pair<String, String>> =
|
|
||||||
gameDir?.listFiles { f ->
|
|
||||||
f.isFile && f.length() < 1L shl 20 && f.name.lowercase().let { it.startsWith("installscript") && it.endsWith(".vdf") }
|
|
||||||
}.orEmpty().sortedBy { it.name }.flatMap { file ->
|
|
||||||
val root = runCatching { com.droiddeck.launcher.input.KeyValues.parse(file.readText()) }.getOrNull() ?: return@flatMap emptyList()
|
|
||||||
(root.child("InstallScript") ?: root).children("Run Process")
|
|
||||||
.flatMap { run -> run.entries.mapNotNull { (it.second as? com.droiddeck.launcher.input.KeyValues.Node)?.string("process 1") } }
|
|
||||||
.flatMap { path -> DependencyDetector.componentsFor(path).map { it to DependencyDetector.label(it) } }
|
|
||||||
}.distinctBy { it.first }
|
|
||||||
|
|
||||||
fun detect(gameDir: File?, appId: Int): List<DependencyDetector.Recommendation> {
|
fun detect(gameDir: File?, appId: Int): List<DependencyDetector.Recommendation> {
|
||||||
val text = try {
|
val text = try {
|
||||||
manifest(gameDir, appId)?.takeIf { it.length() < 1L shl 20 }?.readText() ?: return emptyList()
|
manifest(gameDir, appId)?.takeIf { it.length() < 1L shl 20 }?.readText() ?: return emptyList()
|
||||||
|
|||||||
@@ -3,13 +3,12 @@ package com.droiddeck.launcher.frontend
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import com.droiddeck.launcher.stores.Store
|
import com.droiddeck.launcher.stores.Store
|
||||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||||
import com.droiddeck.launcher.session.WinComponents
|
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
object WinCompSources {
|
object WinCompSources {
|
||||||
enum class Origin { STEAM, GOG, EPIC, AMAZON, STEAM_NAME, FOLDER, XBOX }
|
enum class Origin { STEAM, GOG, EPIC, AMAZON, STEAM_NAME, FOLDER }
|
||||||
|
|
||||||
data class Finding(val component: String?, val original: String, val origin: Origin, val auto: Boolean, val args: List<String> = emptyList())
|
data class Finding(val component: String?, val original: String, val origin: Origin, val auto: Boolean, val args: List<String> = emptyList())
|
||||||
|
|
||||||
@@ -50,17 +49,6 @@ object WinCompSources {
|
|||||||
|
|
||||||
fun installer(path: String): List<String> = if (UE_PREREQ.containsMatchIn(path)) listOf("vcredist2022", "d3dx9") else DependencyDetector.componentsFor(path)
|
fun installer(path: String): List<String> = if (UE_PREREQ.containsMatchIn(path)) listOf("vcredist2022", "d3dx9") else DependencyDetector.componentsFor(path)
|
||||||
|
|
||||||
private val XBOX_KNOWN = Regex("""<KnownDependency\s+Name="([A-Za-z0-9_.-]{1,40})"""")
|
|
||||||
// VC14 also registers the ARM64 runtime: launchers running as ARM64EC look for it and stop when it is missing.
|
|
||||||
private val XBOX_COMPONENTS = mapOf("VC14" to listOf("vcredist2022", WinComponents.VCREDIST_ARM64))
|
|
||||||
|
|
||||||
/** Microsoft installs a PC Game Pass game's declared runtimes with it; VC14 is wanted by nearly all and is always added. */
|
|
||||||
fun xbox(folder: File?): List<Pair<String, String>> {
|
|
||||||
val config = folder?.listFiles().orEmpty().firstOrNull { it.isFile && it.name.equals("MicrosoftGame.config", ignoreCase = true) && it.length() < 1L shl 20 }
|
|
||||||
val declared = config?.let { file -> runCatching { XBOX_KNOWN.findAll(file.readText()).map { it.groupValues[1] }.toList() }.getOrNull() }.orEmpty()
|
|
||||||
return (listOf("VC14") + declared).flatMap { name -> XBOX_COMPONENTS[name].orEmpty().map { it to name } }.distinctBy { it.first }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun steamDepots(ids: List<String>): List<Pair<String, String>> = ids.mapNotNull { SteamRedists.DEPOTS[it] }.distinctBy { it.first }
|
fun steamDepots(ids: List<String>): List<Pair<String, String>> = ids.mapNotNull { SteamRedists.DEPOTS[it] }.distinctBy { it.first }
|
||||||
|
|
||||||
|
|
||||||
@@ -77,10 +65,9 @@ object WinCompSources {
|
|||||||
|
|
||||||
fun steamList(context: Context, gameDir: File?, appId: Int, gameName: String, auto: Boolean): List<Finding> {
|
fun steamList(context: Context, gameDir: File?, appId: Int, gameName: String, auto: Boolean): List<Finding> {
|
||||||
val local = SteamRedists.detect(gameDir, appId)
|
val local = SteamRedists.detect(gameDir, appId)
|
||||||
val pairs = (if (local.isNotEmpty()) local.map { it.componentName to it.label }
|
val pairs = if (local.isNotEmpty()) local.map { it.componentName to it.label }
|
||||||
else SteamAppInfo.info(context, appId)?.let { steamDepots(it.sharedDepots) }.orEmpty()) +
|
else SteamAppInfo.info(context, appId)?.let { steamDepots(it.sharedDepots) }.orEmpty()
|
||||||
SteamRedists.installScript(gameDir) + SteamRedists.SCRIPTED[appId].orEmpty()
|
return pairs.map { (component, label) ->
|
||||||
return pairs.distinctBy { it.first.removeSuffix("_dll") }.map { (component, label) ->
|
|
||||||
Finding(component, label, if (auto) Origin.STEAM else Origin.STEAM_NAME, auto, listOf(label, gameName, appId.toString()))
|
Finding(component, label, if (auto) Origin.STEAM else Origin.STEAM_NAME, auto, listOf(label, gameName, appId.toString()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -107,7 +94,6 @@ object WinCompSources {
|
|||||||
parts.forEach { out += Finding(it, original, Origin.EPIC, true) }
|
parts.forEach { out += Finding(it, original, Origin.EPIC, true) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
store == Store.XBOX -> xbox(folder).forEach { (component, original) -> out += Finding(component, original, Origin.XBOX, true) }
|
|
||||||
store == Store.AMAZON -> folder?.let { amazonPostInstall(it) }?.forEach { command ->
|
store == Store.AMAZON -> folder?.let { amazonPostInstall(it) }?.forEach { command ->
|
||||||
val parts = installer(command)
|
val parts = installer(command)
|
||||||
val original = command.replace('\\', '/').substringAfterLast('/')
|
val original = command.replace('\\', '/').substringAfterLast('/')
|
||||||
|
|||||||
@@ -43,7 +43,6 @@ data class GlassesState(
|
|||||||
val volumeMax: Int = 8,
|
val volumeMax: Int = 8,
|
||||||
val sunblock: Boolean = false,
|
val sunblock: Boolean = false,
|
||||||
val hardwareControls: Boolean = true,
|
val hardwareControls: Boolean = true,
|
||||||
val supportsDisplayModeControl: Boolean = true,
|
|
||||||
val hasSunblock: Boolean = true,
|
val hasSunblock: Boolean = true,
|
||||||
val controlError: String? = null,
|
val controlError: String? = null,
|
||||||
val tracking: Boolean = false,
|
val tracking: Boolean = false,
|
||||||
@@ -51,7 +50,6 @@ data class GlassesState(
|
|||||||
val noSignal: Boolean = false,
|
val noSignal: Boolean = false,
|
||||||
val sbsSupport: Int = SBS_UNKNOWN,
|
val sbsSupport: Int = SBS_UNKNOWN,
|
||||||
val sbs90: Boolean = false,
|
val sbs90: Boolean = false,
|
||||||
val rates2d: List<Int> = listOf(60, 90, 120),
|
|
||||||
val experimental: Boolean = false,
|
val experimental: Boolean = false,
|
||||||
val supportsScreen3dof: Boolean = false,
|
val supportsScreen3dof: Boolean = false,
|
||||||
val supports30Hz: Boolean = false,
|
val supports30Hz: Boolean = false,
|
||||||
@@ -65,7 +63,7 @@ data class GlassesState(
|
|||||||
val spatialConnected: Boolean get() = canControl && supportsSpatial
|
val spatialConnected: Boolean get() = canControl && supportsSpatial
|
||||||
fun usesSpatialControllers(settings: GlassesSettings) = spatialConnected && settings.positionalTracking &&
|
fun usesSpatialControllers(settings: GlassesSettings) = spatialConnected && settings.positionalTracking &&
|
||||||
(settings.handControllers || settings.joyConTracking)
|
(settings.handControllers || settings.joyConTracking)
|
||||||
val can3d: Boolean get() = canControl && supportsDisplayModeControl && !noSignal && sbsSupport != SBS_FAILS
|
val can3d: Boolean get() = canControl && !noSignal && sbsSupport != SBS_FAILS
|
||||||
val verticalFovDeg: Float get() {
|
val verticalFovDeg: Float get() {
|
||||||
val half = Math.toRadians(diagonalFovDeg / 2.0)
|
val half = Math.toRadians(diagonalFovDeg / 2.0)
|
||||||
val aspect = if (width > 0 && height > 0)
|
val aspect = if (width > 0 && height > 0)
|
||||||
@@ -214,7 +212,7 @@ object Glasses {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun sendMode(mode: Int) = post {
|
fun sendMode(mode: Int) = post {
|
||||||
if (!_state.value.canControl || !_state.value.supportsDisplayModeControl) return@post
|
if (!_state.value.canControl) return@post
|
||||||
if (link?.send(VitureProtocol.MSG_DISPLAY, byteArrayOf(mode.toByte())) == true) lastModeSentAt = SystemClock.uptimeMillis()
|
if (link?.send(VitureProtocol.MSG_DISPLAY, byteArrayOf(mode.toByte())) == true) lastModeSentAt = SystemClock.uptimeMillis()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -471,7 +469,6 @@ object Glasses {
|
|||||||
.put("controlError", s.controlError ?: JSONObject.NULL)
|
.put("controlError", s.controlError ?: JSONObject.NULL)
|
||||||
.put("experimental", s.experimental)
|
.put("experimental", s.experimental)
|
||||||
.put("supportsScreen3dof", s.supportsScreen3dof)
|
.put("supportsScreen3dof", s.supportsScreen3dof)
|
||||||
.put("supportsDisplayModeControl", s.supportsDisplayModeControl)
|
|
||||||
.put("supportsSpatial", s.supportsSpatial)
|
.put("supportsSpatial", s.supportsSpatial)
|
||||||
.put("firmware", (link as? VitureSdkLink)?.firmware ?: JSONObject.NULL)
|
.put("firmware", (link as? VitureSdkLink)?.firmware ?: JSONObject.NULL)
|
||||||
.put("spatialSdk", (link as? VitureSdkLink)?.spatialDiagnostics()?.let {
|
.put("spatialSdk", (link as? VitureSdkLink)?.spatialDiagnostics()?.let {
|
||||||
@@ -616,16 +613,13 @@ object Glasses {
|
|||||||
switching3d = modeState.pendingStereo,
|
switching3d = modeState.pendingStereo,
|
||||||
brightnessMax = m?.brightnessMax ?: 8, volumeMax = m?.volumeMax ?: 8,
|
brightnessMax = m?.brightnessMax ?: 8, volumeMax = m?.volumeMax ?: 8,
|
||||||
sunblock = if (m === XrealModel) it.sunblock else _settings.value.sunblock ?: it.sunblock,
|
sunblock = if (m === XrealModel) it.sunblock else _settings.value.sunblock ?: it.sunblock,
|
||||||
hardwareControls = m?.hardwareControls == true &&
|
hardwareControls = device?.vendorId == VitureProtocol.VENDOR_ID || m === XrealModel,
|
||||||
(device?.vendorId == VitureProtocol.VENDOR_ID || m === XrealModel || m is RokidModel),
|
|
||||||
supportsDisplayModeControl = m?.supportsDisplayModeControl == true,
|
|
||||||
hasSunblock = m?.hasSunblock == true,
|
hasSunblock = m?.hasSunblock == true,
|
||||||
diagonalFovDeg = m?.diagonalFovDeg ?: 46f,
|
diagonalFovDeg = m?.diagonalFovDeg ?: 46f,
|
||||||
tracking = it.tracking && link != null,
|
tracking = it.tracking && link != null,
|
||||||
noSignal = noSignal,
|
noSignal = noSignal,
|
||||||
sbs90 = m?.sbs90 == true,
|
sbs90 = m?.sbs90 == true,
|
||||||
rates2d = m?.rates2d ?: listOf(60, 90, 120),
|
experimental = m === XrealModel,
|
||||||
experimental = m === XrealModel || (m is VitureProtocol.Model && m.family == VitureProtocol.Family.PRO2 && !m.needsSdk),
|
|
||||||
supportsScreen3dof = link?.hasImu == true,
|
supportsScreen3dof = link?.hasImu == true,
|
||||||
supports30Hz = display?.let(::supports30Hz) == true,
|
supports30Hz = display?.let(::supports30Hz) == true,
|
||||||
supportsSpatial = (link as? VitureSdkLink)?.isCarina == true,
|
supportsSpatial = (link as? VitureSdkLink)?.isCarina == true,
|
||||||
@@ -640,8 +634,7 @@ object Glasses {
|
|||||||
scheduleModeCheck()
|
scheduleModeCheck()
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun isGlassesVendor(vid: Int) = vid == VitureProtocol.VENDOR_ID || RayNeoModel.isVendor(vid) ||
|
internal fun isGlassesVendor(vid: Int) = vid == VitureProtocol.VENDOR_ID || RayNeoModel.isVendor(vid) || vid == XrealModel.VENDOR_ID
|
||||||
vid == XrealModel.VENDOR_ID || vid == RokidModel.VENDOR_ID
|
|
||||||
|
|
||||||
internal fun supports30Hz(display: Display): Boolean {
|
internal fun supports30Hz(display: Display): Boolean {
|
||||||
val current = display.mode
|
val current = display.mode
|
||||||
@@ -657,18 +650,15 @@ object Glasses {
|
|||||||
internal fun deviceModel(device: UsbDevice): GlassesModel? {
|
internal fun deviceModel(device: UsbDevice): GlassesModel? {
|
||||||
val name = runCatching { device.productName }.getOrNull()
|
val name = runCatching { device.productName }.getOrNull()
|
||||||
return if (device.vendorId == VitureProtocol.VENDOR_ID) {
|
return if (device.vendorId == VitureProtocol.VENDOR_ID) {
|
||||||
if (device.productId == VitureProtocol.PRO2_PRODUCT_ID) VitureProtocol.model(device.productId, name)
|
VitureSdk.marketName(device.productId)?.let(VitureProtocol::sdkModel)
|
||||||
else VitureSdk.marketName(device.productId)?.let(VitureProtocol::sdkModel)
|
|
||||||
?: VitureProtocol.model(device.productId, name)
|
?: VitureProtocol.model(device.productId, name)
|
||||||
}
|
}
|
||||||
else if (XrealModel.matches(device.vendorId, device.productId)) XrealModel
|
else if (XrealModel.matches(device.vendorId, device.productId)) XrealModel
|
||||||
else RokidModel.model(device.vendorId, device.productId, name)
|
else RayNeoModel.model(device.vendorId, device.productId, name)
|
||||||
?: RayNeoModel.model(device.vendorId, device.productId, name)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun isGlassesDisplayName(name: String) =
|
internal fun isGlassesDisplayName(name: String) =
|
||||||
name.contains("VITURE", ignoreCase = true) || RayNeoModel.isDisplay(name) || XrealModel.isDisplay(name) ||
|
name.contains("VITURE", ignoreCase = true) || RayNeoModel.isDisplay(name) || XrealModel.isDisplay(name)
|
||||||
RokidModel.isDisplay(name)
|
|
||||||
|
|
||||||
private fun findDisplay(usbPresent: Boolean): Display? {
|
private fun findDisplay(usbPresent: Boolean): Display? {
|
||||||
return selectGlassesDisplay(displays.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION).toList(), usbPresent)
|
return selectGlassesDisplay(displays.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION).toList(), usbPresent)
|
||||||
@@ -725,9 +715,7 @@ object Glasses {
|
|||||||
calibrationKey = calibrationStore.key(device.vendorId, device.productId,
|
calibrationKey = calibrationStore.key(device.vendorId, device.productId,
|
||||||
runCatching { device.serialNumber }.getOrNull(), model?.name.orEmpty())
|
runCatching { device.serialNumber }.getOrNull(), model?.name.orEmpty())
|
||||||
val l = if (device.vendorId == VitureProtocol.VENDOR_ID) {
|
val l = if (device.vendorId == VitureProtocol.VENDOR_ID) {
|
||||||
if (device.productId == VitureProtocol.PRO2_PRODUCT_ID) {
|
if ((model as? VitureProtocol.Model)?.needsSdk == true) {
|
||||||
VitureV2Link.open(usb, device, v2Listener(generation))
|
|
||||||
} else if ((model as? VitureProtocol.Model)?.needsSdk == true) {
|
|
||||||
// Android can evict cacheDir while the SDK is running.
|
// Android can evict cacheDir while the SDK is running.
|
||||||
Log.i(TAG, "opening VITURE SDK pid=0x%04X spatial=%s".format(device.productId, spatial))
|
Log.i(TAG, "opening VITURE SDK pid=0x%04X spatial=%s".format(device.productId, spatial))
|
||||||
VitureSdkLink.open(usb, device, File(app.noBackupFilesDir, "viture"), sdkListener(generation),
|
VitureSdkLink.open(usb, device, File(app.noBackupFilesDir, "viture"), sdkListener(generation),
|
||||||
@@ -735,8 +723,6 @@ object Glasses {
|
|||||||
} else VitureLink.open(usb, device, linkListener(generation))
|
} else VitureLink.open(usb, device, linkListener(generation))
|
||||||
} else if (model === XrealModel) {
|
} else if (model === XrealModel) {
|
||||||
XrealLink.open(app, xrealListener(generation))
|
XrealLink.open(app, xrealListener(generation))
|
||||||
} else if (model is RokidModel) {
|
|
||||||
RokidLink.open(usb, device, rokidListener(generation))
|
|
||||||
} else {
|
} else {
|
||||||
val baseKey = calibrationKey!!
|
val baseKey = calibrationKey!!
|
||||||
val gtUsb = RayNeoProtocol.isGt(device.vendorId, device.productId)
|
val gtUsb = RayNeoProtocol.isGt(device.vendorId, device.productId)
|
||||||
@@ -804,33 +790,6 @@ object Glasses {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun rokidListener(generation: Long) = object : RokidLink.Listener {
|
|
||||||
override fun onReady() = post {
|
|
||||||
if (generation != linkGeneration) return@post
|
|
||||||
publish { it.copy(connected = true, controlError = null) }
|
|
||||||
updateImu()
|
|
||||||
applyMode(force = false)
|
|
||||||
}
|
|
||||||
override fun onValue(message: Int, value: Int) = post {
|
|
||||||
if (generation != linkGeneration) return@post
|
|
||||||
when (message) {
|
|
||||||
VitureProtocol.MSG_GET_DISPLAY -> glassesMode = value
|
|
||||||
VitureProtocol.MSG_BRIGHTNESS -> publish { it.copy(brightness = value) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
override fun onPose(raw: ByteArray, pose: FloatArray, timeNs: Long) {
|
|
||||||
if (generation != linkGeneration) return
|
|
||||||
imuPackets++
|
|
||||||
probe?.invoke(raw, pose)
|
|
||||||
if (simulating.get() == null) deliver(pose, timeNs)
|
|
||||||
}
|
|
||||||
override fun onLost() = post {
|
|
||||||
if (generation != linkGeneration) return@post
|
|
||||||
closeLink()
|
|
||||||
refresh()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun sdkListener(generation: Long) = object : VitureSdkLink.Listener {
|
private fun sdkListener(generation: Long) = object : VitureSdkLink.Listener {
|
||||||
override fun onSpatial(pose: FloatArray, timeNs: Long, valid: Boolean) {
|
override fun onSpatial(pose: FloatArray, timeNs: Long, valid: Boolean) {
|
||||||
if (generation == linkGeneration) SpatialTracking.accept(pose, timeNs, generation, valid)
|
if (generation == linkGeneration) SpatialTracking.accept(pose, timeNs, generation, valid)
|
||||||
@@ -858,40 +817,6 @@ object Glasses {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun v2Listener(generation: Long) = object : VitureV2Link.Listener {
|
|
||||||
override fun onReady() = post {
|
|
||||||
if (generation != linkGeneration) return@post
|
|
||||||
val current = link as? VitureV2Link ?: return@post
|
|
||||||
publish { it.copy(connected = current.ready, supportsScreen3dof = current.hasImu,
|
|
||||||
tracking = current.trackingActive, controlError = null) }
|
|
||||||
updateImu()
|
|
||||||
}
|
|
||||||
override fun onValue(msgId: Int, value: Int) = post {
|
|
||||||
if (generation != linkGeneration) return@post
|
|
||||||
when (msgId) {
|
|
||||||
VitureProtocol.MSG_GET_DISPLAY -> glassesMode = value
|
|
||||||
VitureProtocol.MSG_GET_BRIGHTNESS -> publish { it.copy(brightness = value) }
|
|
||||||
VitureProtocol.MSG_GET_VOLUME -> publish { it.copy(volume = value) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
override fun onPose(raw: ByteArray, q: FloatArray, timeNs: Long) {
|
|
||||||
if (generation != linkGeneration) return
|
|
||||||
imuPackets++
|
|
||||||
probe?.invoke(raw, q)
|
|
||||||
if (simulating.get() == null) deliver(q, timeNs)
|
|
||||||
}
|
|
||||||
override fun onTracking(active: Boolean) = post {
|
|
||||||
if (generation != linkGeneration) return@post
|
|
||||||
val current = link as? VitureV2Link ?: return@post
|
|
||||||
publish { it.copy(tracking = active && current.trackingActive) }
|
|
||||||
}
|
|
||||||
override fun onLost() = post {
|
|
||||||
if (generation != linkGeneration) return@post
|
|
||||||
closeLink()
|
|
||||||
publish { it.copy(controlError = app.getString(R.string.glasses_connection_failed)) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun rayNeoListener(generation: Long) = object : RayNeoLink.Listener {
|
private fun rayNeoListener(generation: Long) = object : RayNeoLink.Listener {
|
||||||
override fun onDeviceInfo(boardId: Int, calibrationSaved: Boolean) = post {
|
override fun onDeviceInfo(boardId: Int, calibrationSaved: Boolean) = post {
|
||||||
if (generation != linkGeneration) return@post
|
if (generation != linkGeneration) return@post
|
||||||
@@ -967,7 +892,7 @@ object Glasses {
|
|||||||
private fun applyMode(force: Boolean) {
|
private fun applyMode(force: Boolean) {
|
||||||
val s = _state.value
|
val s = _state.value
|
||||||
val m = model ?: return
|
val m = model ?: return
|
||||||
if (!s.canControl || !s.supportsDisplayModeControl) return
|
if (!s.canControl) return
|
||||||
if (modeState.restorePending) {
|
if (modeState.restorePending) {
|
||||||
sendMode(false)
|
sendMode(false)
|
||||||
return
|
return
|
||||||
@@ -989,7 +914,6 @@ object Glasses {
|
|||||||
|
|
||||||
private fun sendMode(sbs: Boolean): Boolean {
|
private fun sendMode(sbs: Boolean): Boolean {
|
||||||
val m = model ?: return false
|
val m = model ?: return false
|
||||||
if (!m.supportsDisplayModeControl) return false
|
|
||||||
if (sbs && !_settings.value.gameOnGlasses) update { it.copy(gameOnGlasses = true) }
|
if (sbs && !_settings.value.gameOnGlasses) update { it.copy(gameOnGlasses = true) }
|
||||||
val g = _settings.value
|
val g = _settings.value
|
||||||
val resolution = GlassesDisplayModes.selected(g, _state.value, sbs)
|
val resolution = GlassesDisplayModes.selected(g, _state.value, sbs)
|
||||||
@@ -1022,11 +946,11 @@ object Glasses {
|
|||||||
val l = link ?: return
|
val l = link ?: return
|
||||||
if (!l.ready) return
|
if (!l.ready) return
|
||||||
val want = (sink != null || poseObservers.isNotEmpty() || probe != null || _calibration.value.running || SpatialTracking.enabled) && l.hasImu
|
val want = (sink != null || poseObservers.isNotEmpty() || probe != null || _calibration.value.running || SpatialTracking.enabled) && l.hasImu
|
||||||
if (l !is VitureV2Link && want == _state.value.tracking) return
|
if (want == _state.value.tracking) return
|
||||||
val accepted = l.send(VitureProtocol.MSG_IMU, byteArrayOf(if (want) 1 else 0))
|
val accepted = l.send(VitureProtocol.MSG_IMU, byteArrayOf(if (want) 1 else 0))
|
||||||
if (want && !accepted) return
|
if (want && !accepted) return
|
||||||
if (want) l.send(VitureProtocol.MSG_IMU_RATE, byteArrayOf(VitureProtocol.IMU_RATE_240.toByte()))
|
if (want) l.send(VitureProtocol.MSG_IMU_RATE, byteArrayOf(VitureProtocol.IMU_RATE_240.toByte()))
|
||||||
publish { it.copy(tracking = if (l is VitureV2Link) l.trackingActive else want) }
|
publish { it.copy(tracking = want) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun linkListener(generation: Long) = object : VitureLink.Listener {
|
private fun linkListener(generation: Long) = object : VitureLink.Listener {
|
||||||
|
|||||||
@@ -4,13 +4,10 @@ package com.droiddeck.launcher.glasses
|
|||||||
interface GlassesModel {
|
interface GlassesModel {
|
||||||
val name: String
|
val name: String
|
||||||
val controllable: Boolean
|
val controllable: Boolean
|
||||||
val hardwareControls: Boolean get() = true
|
|
||||||
val supportsDisplayModeControl: Boolean get() = true
|
|
||||||
val brightnessMax: Int
|
val brightnessMax: Int
|
||||||
val volumeMax: Int
|
val volumeMax: Int
|
||||||
val diagonalFovDeg: Float
|
val diagonalFovDeg: Float
|
||||||
val sbs90: Boolean
|
val sbs90: Boolean
|
||||||
val rates2d: List<Int> get() = listOf(60, 90, 120)
|
|
||||||
val hasSunblock: Boolean get() = true
|
val hasSunblock: Boolean get() = true
|
||||||
val resolutions: List<GlassesResolution> get() = emptyList()
|
val resolutions: List<GlassesResolution> get() = emptyList()
|
||||||
fun mode(hz: Int, sbs: Boolean, resolution: GlassesResolution?): Int = mode(hz, sbs)
|
fun mode(hz: Int, sbs: Boolean, resolution: GlassesResolution?): Int = mode(hz, sbs)
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ internal object GlassesRendering {
|
|||||||
fun refreshRates(settings: GlassesSettings, state: GlassesState): List<Int> = buildList {
|
fun refreshRates(settings: GlassesSettings, state: GlassesState): List<Int> = buildList {
|
||||||
if (native30HzAvailable(settings, state)) add(30)
|
if (native30HzAvailable(settings, state)) add(30)
|
||||||
add(60)
|
add(60)
|
||||||
if (state.sbs) { if (state.sbs90) add(90) }
|
if (!state.sbs || state.sbs90) add(90)
|
||||||
else addAll(state.rates2d.filter { it > 60 })
|
if (!state.sbs) add(120)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun outputHz(settings: GlassesSettings, state: GlassesState): Int {
|
fun outputHz(settings: GlassesSettings, state: GlassesState): Int {
|
||||||
@@ -21,7 +21,6 @@ internal object GlassesRendering {
|
|||||||
return when {
|
return when {
|
||||||
requested == 30 -> if (native30HzAvailable(settings, state)) 30 else 60
|
requested == 30 -> if (native30HzAvailable(settings, state)) 30 else 60
|
||||||
state.sbs && !state.sbs90 -> 60
|
state.sbs && !state.sbs90 -> 60
|
||||||
!state.sbs && requested !in state.rates2d -> state.rates2d.filter { it <= requested }.maxOrNull() ?: 60
|
|
||||||
else -> requested
|
else -> requested
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -32,6 +31,12 @@ internal object GlassesRendering {
|
|||||||
return if (hz == 30 && kotlin.math.abs(state.hz - 30f) >= 0.5f) 60 else hz
|
return if (hz == 30 && kotlin.math.abs(state.hz - 30f) >= 0.5f) 60 else hz
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun fpsLimit(requested: Int, mirrorRefreshLimit: Int): Int = when {
|
||||||
|
mirrorRefreshLimit <= 0 -> requested
|
||||||
|
requested <= 0 -> mirrorRefreshLimit
|
||||||
|
else -> minOf(requested, mirrorRefreshLimit)
|
||||||
|
}
|
||||||
|
|
||||||
fun usesGlasses(state: GlassesState, outputActive: Boolean, steamVrRunning: Boolean): Boolean =
|
fun usesGlasses(state: GlassesState, outputActive: Boolean, steamVrRunning: Boolean): Boolean =
|
||||||
outputActive || (steamVrRunning && state.usable)
|
outputActive || (steamVrRunning && state.usable)
|
||||||
|
|
||||||
|
|||||||
@@ -1,148 +0,0 @@
|
|||||||
package com.droiddeck.launcher.glasses
|
|
||||||
|
|
||||||
import android.hardware.usb.UsbConstants
|
|
||||||
import android.hardware.usb.UsbDevice
|
|
||||||
import android.hardware.usb.UsbDeviceConnection
|
|
||||||
import android.hardware.usb.UsbEndpoint
|
|
||||||
import android.hardware.usb.UsbInterface
|
|
||||||
import android.hardware.usb.UsbManager
|
|
||||||
import android.os.SystemClock
|
|
||||||
import android.util.Log
|
|
||||||
|
|
||||||
/** Controls are vendor control transfers; the HID interrupt endpoint streams IMU reports unprompted. */
|
|
||||||
internal class RokidLink private constructor(
|
|
||||||
private val connection: UsbDeviceConnection,
|
|
||||||
private val usbInterface: UsbInterface,
|
|
||||||
private val endpoint: UsbEndpoint,
|
|
||||||
private val listener: Listener,
|
|
||||||
) : GlassesLink {
|
|
||||||
interface Listener {
|
|
||||||
fun onReady()
|
|
||||||
fun onValue(message: Int, value: Int)
|
|
||||||
fun onPose(raw: ByteArray, pose: FloatArray, timeNs: Long)
|
|
||||||
fun onLost()
|
|
||||||
}
|
|
||||||
|
|
||||||
@Volatile private var running = true
|
|
||||||
@Volatile override var ready = false
|
|
||||||
private set
|
|
||||||
@Volatile private var tracking = false
|
|
||||||
private val controlLock = Any()
|
|
||||||
private lateinit var worker: Thread
|
|
||||||
override val hasImu = true
|
|
||||||
|
|
||||||
override fun send(msgId: Int, payload: ByteArray): Boolean {
|
|
||||||
if (!running) return false
|
|
||||||
val value = payload.firstOrNull()?.toInt()?.and(0xff) ?: -1
|
|
||||||
return when (msgId) {
|
|
||||||
VitureProtocol.MSG_IMU -> (value in 0..1).also { if (it) tracking = value == 1 }
|
|
||||||
VitureProtocol.MSG_GET_DISPLAY -> display()?.let { listener.onValue(msgId, it) } != null
|
|
||||||
VitureProtocol.MSG_DISPLAY -> value in RokidModel.MODES &&
|
|
||||||
control(RokidModel.REQUEST_SET_DISPLAY, value, RokidModel.INDEX_DISPLAY) &&
|
|
||||||
true.also { listener.onValue(VitureProtocol.MSG_GET_DISPLAY, value) }
|
|
||||||
VitureProtocol.MSG_GET_BRIGHTNESS -> read(RokidModel.REQUEST_GET_BRIGHTNESS, RokidModel.INDEX_BRIGHTNESS)
|
|
||||||
?.let { listener.onValue(VitureProtocol.MSG_BRIGHTNESS, RokidModel.brightnessStep(it)) } != null
|
|
||||||
VitureProtocol.MSG_BRIGHTNESS -> value in 0..RokidModel.BRIGHTNESS_STEPS &&
|
|
||||||
control(RokidModel.REQUEST_SET_BRIGHTNESS, RokidModel.brightnessRaw(value), RokidModel.INDEX_BRIGHTNESS)
|
|
||||||
else -> false // Volume is the glasses' USB audio device; there is no film or IMU-rate control.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun display(): Int? = read(RokidModel.REQUEST_GET_DISPLAY, RokidModel.INDEX_DISPLAY)
|
|
||||||
|
|
||||||
private fun read(request: Int, index: Int): Int? = synchronized(controlLock) {
|
|
||||||
if (!running) return null
|
|
||||||
val buffer = ByteArray(64)
|
|
||||||
val count = connection.controlTransfer(VENDOR_IN, request, 0, index, buffer, buffer.size, TIMEOUT_MS)
|
|
||||||
// Display mode is reported in the second byte, brightness in the first.
|
|
||||||
val offset = if (request == RokidModel.REQUEST_GET_DISPLAY) 1 else 0
|
|
||||||
if (count > offset) buffer[offset].toInt() and 0xff else null
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun control(request: Int, value: Int, index: Int): Boolean = synchronized(controlLock) {
|
|
||||||
running && connection.controlTransfer(VENDOR_OUT, request, value, index, byteArrayOf(1), 1, TIMEOUT_MS) >= 0
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun run() {
|
|
||||||
val buffer = ByteArray(maxOf(endpoint.maxPacketSize, 64))
|
|
||||||
val parser = RokidProtocol.Parser()
|
|
||||||
var fusion = ImuFusion()
|
|
||||||
var wasTracking = false
|
|
||||||
var brightness = -1
|
|
||||||
var lastSensor = SystemClock.elapsedRealtime()
|
|
||||||
try {
|
|
||||||
ready = true
|
|
||||||
listener.onReady()
|
|
||||||
while (running) {
|
|
||||||
val count = connection.bulkTransfer(endpoint, buffer, buffer.size, 250)
|
|
||||||
val now = SystemClock.elapsedRealtime()
|
|
||||||
val sample = if (count > 0) parser.parse(buffer, count) else null
|
|
||||||
if (sample == null) {
|
|
||||||
if (now - lastSensor > 3000) error("Rokid IMU stream stalled")
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
lastSensor = now
|
|
||||||
sample.brightness?.takeIf { it != brightness }?.let {
|
|
||||||
brightness = it
|
|
||||||
listener.onValue(VitureProtocol.MSG_BRIGHTNESS, RokidModel.brightnessStep(it))
|
|
||||||
}
|
|
||||||
val enabled = tracking
|
|
||||||
if (enabled && !wasTracking) fusion = ImuFusion()
|
|
||||||
wasTracking = enabled
|
|
||||||
if (!enabled) continue
|
|
||||||
// Max captures: already right/up/back; level gravity +Y, turn left +gyroY, look up +gyroX, roll right -gyroZ.
|
|
||||||
fusion.update(sample.timeNs, sample.accel, sample.gyro)?.let {
|
|
||||||
if (running && tracking) listener.onPose(buffer.copyOf(count), it, SystemClock.elapsedRealtimeNanos())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
if (running) Log.w(TAG, "Rokid stream failed", e)
|
|
||||||
} finally {
|
|
||||||
ready = false
|
|
||||||
if (running) listener.onLost()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun close() {
|
|
||||||
synchronized(controlLock) {
|
|
||||||
if (!running) return
|
|
||||||
running = false
|
|
||||||
}
|
|
||||||
if (Thread.currentThread() !== worker) worker.join(500)
|
|
||||||
runCatching { connection.releaseInterface(usbInterface) }
|
|
||||||
connection.close()
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val TAG = "RokidLink"
|
|
||||||
private const val TIMEOUT_MS = 250
|
|
||||||
private const val VENDOR_IN = UsbConstants.USB_DIR_IN or UsbConstants.USB_TYPE_VENDOR
|
|
||||||
private const val VENDOR_OUT = UsbConstants.USB_DIR_OUT or UsbConstants.USB_TYPE_VENDOR
|
|
||||||
|
|
||||||
internal fun sensorEndpoint(device: UsbDevice): Pair<UsbInterface, UsbEndpoint>? {
|
|
||||||
for (i in 0 until device.interfaceCount) {
|
|
||||||
val iface = device.getInterface(i)
|
|
||||||
if (iface.interfaceClass != UsbConstants.USB_CLASS_HID) continue
|
|
||||||
for (e in 0 until iface.endpointCount) {
|
|
||||||
val endpoint = iface.getEndpoint(e)
|
|
||||||
if (endpoint.direction == UsbConstants.USB_DIR_IN &&
|
|
||||||
endpoint.type == UsbConstants.USB_ENDPOINT_XFER_INT) return iface to endpoint
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
fun open(usb: UsbManager, device: UsbDevice, listener: Listener): RokidLink? {
|
|
||||||
val (iface, endpoint) = sensorEndpoint(device) ?: return null
|
|
||||||
val conn = usb.openDevice(device) ?: return null
|
|
||||||
if (!conn.claimInterface(iface, true)) {
|
|
||||||
conn.close()
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
return RokidLink(conn, iface, endpoint, listener).also { link ->
|
|
||||||
link.worker = Thread({ link.run() }, "rokid-imu").apply { isDaemon = true }
|
|
||||||
link.worker.start()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
package com.droiddeck.launcher.glasses
|
|
||||||
|
|
||||||
import java.nio.ByteBuffer
|
|
||||||
import java.nio.ByteOrder
|
|
||||||
|
|
||||||
/** Rokid Air/Max share one USB identity; Max 2 has a separate product ID. */
|
|
||||||
internal class RokidModel private constructor(override val name: String, private val max: Boolean) : GlassesModel {
|
|
||||||
override val controllable = true
|
|
||||||
override val brightnessMax = BRIGHTNESS_STEPS
|
|
||||||
override val volumeMax = 0
|
|
||||||
override val hasSunblock = false
|
|
||||||
override val diagonalFovDeg = if (max) 50f else 43f
|
|
||||||
override val sbs90 = max
|
|
||||||
override val rates2d = if (max) listOf(60, 120) else listOf(60)
|
|
||||||
override val resolutions = if (max) listOf(GlassesResolution(1920, 1080), GlassesResolution(1920, 1200))
|
|
||||||
else listOf(GlassesResolution(1920, 1080))
|
|
||||||
|
|
||||||
override fun mode(hz: Int, sbs: Boolean): Int = mode(hz, sbs, null)
|
|
||||||
|
|
||||||
override fun mode(hz: Int, sbs: Boolean, resolution: GlassesResolution?): Int = when {
|
|
||||||
!max -> if (sbs) MODE_SBS_1080_60 else MODE_2D_60
|
|
||||||
sbs && resolution?.height == 1080 -> MODE_SBS_1080_60
|
|
||||||
sbs -> if (hz >= 90) MODE_SBS_1200_90 else MODE_SBS_1200_60
|
|
||||||
hz >= 120 -> MODE_2D_120
|
|
||||||
else -> MODE_2D_60
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun modeForStep(step: Int): Int? = null
|
|
||||||
|
|
||||||
override fun equals(other: Any?) = other is RokidModel && other.name == name && other.max == max
|
|
||||||
override fun hashCode() = name.hashCode()
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
const val VENDOR_ID = 0x04d2
|
|
||||||
const val PRODUCT_ID = 0x162f
|
|
||||||
const val MAX2_PRODUCT_ID = 0x2002
|
|
||||||
const val BRIGHTNESS_STEPS = 10
|
|
||||||
|
|
||||||
// Vendor control requests, device recipient.
|
|
||||||
const val REQUEST_SET_DISPLAY = 0x01
|
|
||||||
const val REQUEST_GET_DISPLAY = 0x81
|
|
||||||
const val REQUEST_SET_BRIGHTNESS = 0x02
|
|
||||||
const val REQUEST_GET_BRIGHTNESS = 0x82
|
|
||||||
const val INDEX_DISPLAY = 0x01
|
|
||||||
const val INDEX_BRIGHTNESS = 0x02
|
|
||||||
|
|
||||||
const val MODE_2D_60 = 0
|
|
||||||
const val MODE_SBS_1080_60 = 1
|
|
||||||
const val MODE_2D_120 = 3
|
|
||||||
const val MODE_SBS_1200_90 = 4
|
|
||||||
const val MODE_SBS_1200_60 = 5
|
|
||||||
val MODES = setOf(MODE_2D_60, MODE_SBS_1080_60, MODE_2D_120, MODE_SBS_1200_90, MODE_SBS_1200_60)
|
|
||||||
|
|
||||||
// 0x04d2 is a shared vendor ID, so the Rokid product string is required too.
|
|
||||||
fun model(vid: Int, pid: Int, name: String?): GlassesModel? {
|
|
||||||
if (vid != VENDOR_ID || (pid != PRODUCT_ID && pid != MAX2_PRODUCT_ID)) return null
|
|
||||||
val product = name?.trim()?.takeIf { it.startsWith("Rokid", ignoreCase = true) } ?: return null
|
|
||||||
return RokidModel(product, pid == MAX2_PRODUCT_ID || product.contains("Max", ignoreCase = true))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isDisplay(name: String) = name.contains("Rokid", ignoreCase = true)
|
|
||||||
|
|
||||||
/** Device brightness is 0..100; the shared slider uses ten steps. */
|
|
||||||
fun brightnessStep(raw: Int): Int = ((raw.coerceIn(0, 100) + 5) / 10).coerceIn(0, BRIGHTNESS_STEPS)
|
|
||||||
fun brightnessRaw(step: Int): Int = step.coerceIn(0, BRIGHTNESS_STEPS) * 10
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal object RokidProtocol {
|
|
||||||
data class Sample(val timeNs: Long, val accel: Vec3, val gyro: Vec3, val brightness: Int?)
|
|
||||||
|
|
||||||
private const val COMBINED = 17
|
|
||||||
private const val SEPARATE = 4
|
|
||||||
private const val SENSOR_ACCEL = 1
|
|
||||||
private const val SENSOR_GYRO = 2
|
|
||||||
|
|
||||||
/** Max sends one combined report; Air sends accel and gyro reports that share a timestamp. */
|
|
||||||
class Parser {
|
|
||||||
private var accel: Vec3? = null
|
|
||||||
private var accelTime = -1L
|
|
||||||
private var gyro: Vec3? = null
|
|
||||||
private var gyroTime = -2L
|
|
||||||
|
|
||||||
fun parse(packet: ByteArray, length: Int = packet.size): Sample? {
|
|
||||||
if (length < 64) return null
|
|
||||||
val b = ByteBuffer.wrap(packet, 0, length).order(ByteOrder.LITTLE_ENDIAN)
|
|
||||||
return when (packet[0].toInt() and 0xff) {
|
|
||||||
COMBINED -> Sample(b.getLong(1), vec(b, 9), vec(b, 21), packet[59].toInt() and 0xff)
|
|
||||||
SEPARATE -> {
|
|
||||||
val time = b.getLong(9) * 1000 // Air reports microseconds; Max reports nanoseconds.
|
|
||||||
when (packet[1].toInt() and 0xff) {
|
|
||||||
SENSOR_ACCEL -> { accel = vec(b, 21); accelTime = time }
|
|
||||||
SENSOR_GYRO -> { gyro = vec(b, 21); gyroTime = time }
|
|
||||||
else -> return null
|
|
||||||
}
|
|
||||||
if (accelTime != gyroTime) return null
|
|
||||||
Sample(time, accel!!, gyro!!, null).also { accelTime = -1L; gyroTime = -2L }
|
|
||||||
}
|
|
||||||
else -> null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun vec(b: ByteBuffer, offset: Int) = Vec3(b.getFloat(offset), b.getFloat(offset + 4), b.getFloat(offset + 8))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -6,7 +6,6 @@ import kotlin.math.sqrt
|
|||||||
|
|
||||||
object VitureProtocol {
|
object VitureProtocol {
|
||||||
const val VENDOR_ID = 0x35CA
|
const val VENDOR_ID = 0x35CA
|
||||||
const val PRO2_PRODUCT_ID = 0x1301
|
|
||||||
const val PACKET_SIZE = 64
|
const val PACKET_SIZE = 64
|
||||||
private const val HEADER = 0x12
|
private const val HEADER = 0x12
|
||||||
|
|
||||||
@@ -34,19 +33,13 @@ object VitureProtocol {
|
|||||||
|
|
||||||
enum class Family { ONE, PRO, LUMA, ULTRA, BEAST, PRO2 }
|
enum class Family { ONE, PRO, LUMA, ULTRA, BEAST, PRO2 }
|
||||||
|
|
||||||
class Model(
|
class Model(override val name: String, val family: Family) : GlassesModel {
|
||||||
override val name: String,
|
|
||||||
val family: Family,
|
|
||||||
val needsSdk: Boolean = family == Family.ULTRA || family == Family.BEAST || family == Family.PRO2,
|
|
||||||
) : GlassesModel {
|
|
||||||
override val controllable: Boolean get() = true
|
override val controllable: Boolean get() = true
|
||||||
private val directPro2: Boolean get() = family == Family.PRO2 && !needsSdk
|
val needsSdk: Boolean get() = family == Family.ULTRA || family == Family.BEAST || family == Family.PRO2
|
||||||
override val hardwareControls: Boolean get() = !directPro2
|
|
||||||
override val supportsDisplayModeControl: Boolean get() = !directPro2
|
|
||||||
val tall: Boolean get() = family == Family.LUMA || family == Family.ULTRA || family == Family.BEAST
|
val tall: Boolean get() = family == Family.LUMA || family == Family.ULTRA || family == Family.BEAST
|
||||||
override val sbs90: Boolean get() = family == Family.ULTRA
|
override val sbs90: Boolean get() = family == Family.ULTRA
|
||||||
override val brightnessMax: Int get() = if (directPro2) 0 else 8
|
override val brightnessMax: Int get() = 8
|
||||||
override val volumeMax: Int get() = if (directPro2) 0 else if (family == Family.BEAST) 15 else 8
|
override val volumeMax: Int get() = if (family == Family.BEAST) 15 else 8
|
||||||
override val hasSunblock: Boolean get() = family != Family.PRO2
|
override val hasSunblock: Boolean get() = family != Family.PRO2
|
||||||
override val diagonalFovDeg: Float get() = when (family) {
|
override val diagonalFovDeg: Float get() = when (family) {
|
||||||
Family.ONE -> 43f
|
Family.ONE -> 43f
|
||||||
@@ -96,7 +89,6 @@ object VitureProtocol {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun model(productId: Int, productName: String?): Model? {
|
fun model(productId: Int, productName: String?): Model? {
|
||||||
if (productId == PRO2_PRODUCT_ID) return Model("VITURE Pro 2", Family.PRO2, needsSdk = false)
|
|
||||||
val family = when (productId) {
|
val family = when (productId) {
|
||||||
0x1011, 0x1013, 0x1015, 0x1017, 0x101b -> Family.ONE
|
0x1011, 0x1013, 0x1015, 0x1017, 0x101b -> Family.ONE
|
||||||
0x1019, 0x101d -> Family.PRO
|
0x1019, 0x101d -> Family.PRO
|
||||||
|
|||||||
@@ -1,288 +0,0 @@
|
|||||||
package com.droiddeck.launcher.glasses
|
|
||||||
|
|
||||||
import android.hardware.usb.UsbConstants
|
|
||||||
import android.hardware.usb.UsbDevice
|
|
||||||
import android.hardware.usb.UsbDeviceConnection
|
|
||||||
import android.hardware.usb.UsbEndpoint
|
|
||||||
import android.hardware.usb.UsbInterface
|
|
||||||
import android.hardware.usb.UsbManager
|
|
||||||
import android.hardware.usb.UsbRequest
|
|
||||||
import android.util.Log
|
|
||||||
import java.io.IOException
|
|
||||||
import java.nio.ByteBuffer
|
|
||||||
import java.util.concurrent.ArrayBlockingQueue
|
|
||||||
import java.util.concurrent.TimeoutException
|
|
||||||
import java.util.concurrent.atomic.AtomicLong
|
|
||||||
|
|
||||||
internal class VitureV2Link internal constructor(
|
|
||||||
private val transport: Transport,
|
|
||||||
private val listener: Listener,
|
|
||||||
) : GlassesLink {
|
|
||||||
interface Listener {
|
|
||||||
fun onReady()
|
|
||||||
fun onValue(msgId: Int, value: Int)
|
|
||||||
fun onPose(raw: ByteArray, q: FloatArray, timeNs: Long)
|
|
||||||
fun onTracking(active: Boolean)
|
|
||||||
fun onLost()
|
|
||||||
}
|
|
||||||
|
|
||||||
internal data class Received(val bytes: ByteArray, val timeNs: Long)
|
|
||||||
internal interface Transport {
|
|
||||||
fun write(packet: ByteArray): Boolean
|
|
||||||
fun read(timeoutMs: Long): Received?
|
|
||||||
fun close()
|
|
||||||
}
|
|
||||||
|
|
||||||
private data class Command(val packet: ByteArray, val stream: Boolean? = null)
|
|
||||||
private val commands = ArrayBlockingQueue<Command>(16)
|
|
||||||
private val stateLock = Any()
|
|
||||||
private val bad = AtomicLong()
|
|
||||||
@Volatile private var running = true
|
|
||||||
@Volatile private var wanted = true
|
|
||||||
@Volatile override var ready = false
|
|
||||||
private set
|
|
||||||
@Volatile var trackingActive = false
|
|
||||||
private set
|
|
||||||
override val hasImu: Boolean get() = ready
|
|
||||||
override val badFrames: Long get() = bad.get()
|
|
||||||
@Volatile private var streamOn = false
|
|
||||||
private var lastPoseAt = 0L
|
|
||||||
private var lastTick: Long? = null
|
|
||||||
private var poseNotBefore = 0L
|
|
||||||
private val worker = Thread(::run, "viture-v2").apply { isDaemon = true; start() }
|
|
||||||
|
|
||||||
override fun send(msgId: Int, payload: ByteArray): Boolean {
|
|
||||||
synchronized(stateLock) {
|
|
||||||
if (!running || !ready) return false
|
|
||||||
if (msgId == VitureProtocol.MSG_IMU) {
|
|
||||||
if (payload.size != 1 || payload[0].toInt() !in 0..1) return false
|
|
||||||
val enabled = payload[0].toInt() == 1
|
|
||||||
if (wanted == enabled) return true
|
|
||||||
val command = Command(VitureV2Protocol.imuControl(
|
|
||||||
if (enabled) VitureV2Protocol.STREAM_POSE else VitureV2Protocol.STREAM_OFF), enabled)
|
|
||||||
if (!commands.offer(command)) return false
|
|
||||||
wanted = enabled
|
|
||||||
if (!enabled) {
|
|
||||||
streamOn = false
|
|
||||||
tracking(false)
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if (msgId == VitureProtocol.MSG_GET_IMU) return true
|
|
||||||
// Keep the measured 120 Hz mode; the generic controller requests 240 Hz.
|
|
||||||
if (msgId == VitureProtocol.MSG_IMU_RATE) return false
|
|
||||||
val query = when (msgId) {
|
|
||||||
VitureProtocol.MSG_GET_BRIGHTNESS -> VitureV2Protocol.MSG_GET_BRIGHTNESS
|
|
||||||
VitureProtocol.MSG_GET_VOLUME -> VitureV2Protocol.MSG_GET_VOLUME
|
|
||||||
VitureProtocol.MSG_GET_DISPLAY -> VitureV2Protocol.MSG_GET_DISPLAY
|
|
||||||
else -> return false
|
|
||||||
}
|
|
||||||
return payload.isEmpty() && commands.offer(Command(VitureV2Protocol.packet(query)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun tracking(active: Boolean) {
|
|
||||||
if (trackingActive != active) {
|
|
||||||
trackingActive = active
|
|
||||||
listener.onTracking(active)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun run() {
|
|
||||||
try {
|
|
||||||
if (!transport.write(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_POSE)))
|
|
||||||
throw IOException("Could not start pose stream")
|
|
||||||
poseNotBefore = System.nanoTime()
|
|
||||||
streamOn = true
|
|
||||||
lastPoseAt = System.nanoTime()
|
|
||||||
while (running) {
|
|
||||||
commands.poll()?.let { command ->
|
|
||||||
if (!transport.write(command.packet)) throw IOException("USB command failed")
|
|
||||||
val completedAt = System.nanoTime()
|
|
||||||
synchronized(stateLock) {
|
|
||||||
command.stream?.let {
|
|
||||||
streamOn = it
|
|
||||||
lastTick = null
|
|
||||||
poseNotBefore = completedAt
|
|
||||||
lastPoseAt = System.nanoTime()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
transport.read(100)?.let(::receive)
|
|
||||||
if (streamOn && System.nanoTime() - lastPoseAt > POSE_TIMEOUT_NS)
|
|
||||||
throw IOException("No fresh valid pose samples")
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
if (running) {
|
|
||||||
ready = false
|
|
||||||
tracking(false)
|
|
||||||
Log.w(TAG, "V2 connection lost: ${e.message}")
|
|
||||||
listener.onLost()
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
running = false
|
|
||||||
ready = false
|
|
||||||
tracking(false)
|
|
||||||
runCatching { transport.write(VitureV2Protocol.imuControl(VitureV2Protocol.STREAM_OFF)) }
|
|
||||||
transport.close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun receive(received: Received) = synchronized(stateLock) {
|
|
||||||
if (!running) return
|
|
||||||
val frame = VitureV2Protocol.parse(received.bytes) ?: run { bad.incrementAndGet(); return }
|
|
||||||
if (frame.msgId == VitureV2Protocol.EVENT_POSE) {
|
|
||||||
val pose = VitureV2Protocol.pose(frame) ?: run { bad.incrementAndGet(); return }
|
|
||||||
if (!streamOn || !wanted || received.timeNs < poseNotBefore) return
|
|
||||||
val previous = lastTick
|
|
||||||
if (previous != null) {
|
|
||||||
val delta = (pose.deviceTick - previous) and 0xffffffffL
|
|
||||||
if (delta == 0L || delta >= 0x80000000L) return
|
|
||||||
}
|
|
||||||
lastTick = pose.deviceTick
|
|
||||||
lastPoseAt = System.nanoTime()
|
|
||||||
val becameReady = !ready
|
|
||||||
ready = true
|
|
||||||
tracking(true)
|
|
||||||
if (becameReady) listener.onReady()
|
|
||||||
val q = pose.quaternion
|
|
||||||
// Upstream right/up/back pose converted to the shared VITURE legacy basis.
|
|
||||||
val shared = floatArrayOf(-q[2], -q[0], q[1], q[3])
|
|
||||||
// Upstream does not establish device tick units; use host monotonic receipt time.
|
|
||||||
if (running && wanted && streamOn) listener.onPose(received.bytes, shared, received.timeNs)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
VitureV2Protocol.reply(frame, VitureV2Protocol.MSG_IMU_CONTROL)?.let {
|
|
||||||
if (!it.success) throw IOException("Pose stream rejected with status ${it.status}")
|
|
||||||
}
|
|
||||||
val queries = arrayOf(
|
|
||||||
VitureV2Protocol.MSG_GET_BRIGHTNESS to VitureProtocol.MSG_GET_BRIGHTNESS,
|
|
||||||
VitureV2Protocol.MSG_GET_VOLUME to VitureProtocol.MSG_GET_VOLUME,
|
|
||||||
VitureV2Protocol.MSG_GET_DISPLAY to VitureProtocol.MSG_GET_DISPLAY,
|
|
||||||
)
|
|
||||||
for ((query, internalId) in queries) {
|
|
||||||
val reply = VitureV2Protocol.reply(frame, query) ?: continue
|
|
||||||
if (reply.success && reply.body.size == 1) listener.onValue(internalId, reply.body[0].toInt() and 255)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun close() {
|
|
||||||
synchronized(stateLock) {
|
|
||||||
running = false
|
|
||||||
ready = false
|
|
||||||
wanted = false
|
|
||||||
commands.clear()
|
|
||||||
}
|
|
||||||
if (Thread.currentThread() !== worker) worker.join(1500)
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val TAG = "VitureV2Link"
|
|
||||||
private const val POSE_TIMEOUT_NS = 3_000_000_000L
|
|
||||||
const val PRODUCT_ID = 0x1301
|
|
||||||
|
|
||||||
fun open(usb: UsbManager, device: UsbDevice, listener: Listener): VitureV2Link? {
|
|
||||||
if (device.vendorId != VitureProtocol.VENDOR_ID || device.productId != PRODUCT_ID) return null
|
|
||||||
val candidates = (0 until device.interfaceCount).map(device::getInterface).filter {
|
|
||||||
it.interfaceClass == UsbConstants.USB_CLASS_HID && it.alternateSetting == 0 && it.endpointCount == 2
|
|
||||||
}.mapNotNull { intf ->
|
|
||||||
val endpoints = (0 until intf.endpointCount).map(intf::getEndpoint)
|
|
||||||
val input = endpoints.singleOrNull { it.direction == UsbConstants.USB_DIR_IN &&
|
|
||||||
it.type == UsbConstants.USB_ENDPOINT_XFER_INT && it.maxPacketSize == 64 }
|
|
||||||
val output = endpoints.singleOrNull { it.direction == UsbConstants.USB_DIR_OUT &&
|
|
||||||
it.type == UsbConstants.USB_ENDPOINT_XFER_INT && it.maxPacketSize == 64 }
|
|
||||||
if (input != null && output != null) Triple(intf, input, output) else null
|
|
||||||
}
|
|
||||||
val (intf, input, output) = candidates.singleOrNull() ?: return null
|
|
||||||
val connection = usb.openDevice(device) ?: return null
|
|
||||||
if (!connection.claimInterface(intf, true)) { connection.close(); return null }
|
|
||||||
return try {
|
|
||||||
VitureV2Link(AndroidTransport(connection, intf, input, output), listener)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
connection.releaseInterface(intf)
|
|
||||||
connection.close()
|
|
||||||
Log.w(TAG, "Could not initialize USB requests", e)
|
|
||||||
null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private class AndroidTransport(
|
|
||||||
private val connection: UsbDeviceConnection,
|
|
||||||
private val intf: UsbInterface,
|
|
||||||
input: UsbEndpoint,
|
|
||||||
output: UsbEndpoint,
|
|
||||||
) : Transport {
|
|
||||||
private val inputRequest = UsbRequest()
|
|
||||||
private val outputRequest = UsbRequest()
|
|
||||||
private val inputBuffer = ByteBuffer.allocateDirect(64)
|
|
||||||
private var outputBuffer: ByteBuffer? = null
|
|
||||||
private var outputPending = false
|
|
||||||
private val received = ArrayDeque<Received>()
|
|
||||||
|
|
||||||
init {
|
|
||||||
try {
|
|
||||||
if (!inputRequest.initialize(connection, input) || !outputRequest.initialize(connection, output))
|
|
||||||
throw IOException("USB request initialization failed")
|
|
||||||
queueInput()
|
|
||||||
} catch (e: Exception) {
|
|
||||||
inputRequest.close()
|
|
||||||
outputRequest.close()
|
|
||||||
throw e
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun queueInput() {
|
|
||||||
inputBuffer.clear()
|
|
||||||
if (!inputRequest.queue(inputBuffer)) throw IOException("USB input queue failed")
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun await(timeoutMs: Long) {
|
|
||||||
val completed = try { connection.requestWait(timeoutMs) } catch (_: TimeoutException) { return }
|
|
||||||
?: throw IOException("USB device disconnected")
|
|
||||||
if (completed === outputRequest) {
|
|
||||||
outputPending = false
|
|
||||||
} else if (completed === inputRequest) {
|
|
||||||
val count = inputBuffer.position()
|
|
||||||
if (count > 0) {
|
|
||||||
val bytes = ByteArray(count)
|
|
||||||
inputBuffer.flip()
|
|
||||||
inputBuffer.get(bytes)
|
|
||||||
if (received.size >= 512) throw IOException("USB input backlog overflow")
|
|
||||||
received.addLast(Received(bytes, System.nanoTime()))
|
|
||||||
}
|
|
||||||
queueInput()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun write(packet: ByteArray): Boolean {
|
|
||||||
if (outputPending) throw IOException("Previous USB output has not completed")
|
|
||||||
val buffer = ByteBuffer.allocateDirect(packet.size).apply { put(packet); flip() }
|
|
||||||
outputBuffer = buffer
|
|
||||||
outputPending = outputRequest.queue(buffer)
|
|
||||||
if (!outputPending) return false
|
|
||||||
val deadline = System.nanoTime() + 250_000_000L
|
|
||||||
while (outputPending && System.nanoTime() < deadline) await(25)
|
|
||||||
if (outputPending) {
|
|
||||||
outputRequest.cancel()
|
|
||||||
throw IOException("USB output timed out")
|
|
||||||
}
|
|
||||||
return buffer.position() == packet.size
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun read(timeoutMs: Long): Received? {
|
|
||||||
if (received.isEmpty()) await(timeoutMs)
|
|
||||||
return received.removeFirstOrNull()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun close() {
|
|
||||||
inputRequest.cancel()
|
|
||||||
if (outputPending) outputRequest.cancel()
|
|
||||||
connection.releaseInterface(intf)
|
|
||||||
connection.close()
|
|
||||||
inputRequest.close()
|
|
||||||
outputRequest.close()
|
|
||||||
outputBuffer = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,132 +0,0 @@
|
|||||||
// Adapted from elasticjava/viture-v2, MIT, Copyright (c) 2026 Holger Bartnick.
|
|
||||||
// Source: ece8c30485f7d357fefa362ae74f3eabac9b3899; see docs/third-party/viture-v2/.
|
|
||||||
package com.droiddeck.launcher.glasses
|
|
||||||
|
|
||||||
import kotlin.math.sqrt
|
|
||||||
|
|
||||||
object VitureV2Protocol {
|
|
||||||
const val PACKET_SIZE = 64
|
|
||||||
const val HEADER_SIZE = 8
|
|
||||||
const val RESPONSE_OFFSET = 0x2000
|
|
||||||
private const val PREAMBLE = 0x0010
|
|
||||||
private const val MAX_PAYLOAD_SIZE = PACKET_SIZE - HEADER_SIZE
|
|
||||||
|
|
||||||
const val MSG_IMU_CONTROL = 0x0301
|
|
||||||
const val MSG_GET_SERIAL = 0x3002
|
|
||||||
const val MSG_GET_VERSION = 0x3003
|
|
||||||
const val MSG_GET_BRIGHTNESS = 0x3122
|
|
||||||
const val MSG_GET_DUTY_CYCLE = 0x3125
|
|
||||||
const val MSG_GET_DISPLAY = 0x3141
|
|
||||||
const val MSG_GET_VOLUME = 0x3201
|
|
||||||
const val MSG_GET_WEAR = 0x3321
|
|
||||||
const val EVENT_POSE = 0x7308
|
|
||||||
const val EVENT_RAW = 0x7309
|
|
||||||
|
|
||||||
const val STREAM_OFF = 0
|
|
||||||
const val STREAM_POSE = 1
|
|
||||||
const val STREAM_RAW = 2
|
|
||||||
|
|
||||||
enum class Rate(val wireValue: Int, val hz: Int) {
|
|
||||||
HZ_60(0, 60), HZ_90(1, 90), HZ_120(2, 120),
|
|
||||||
HZ_240(3, 240), HZ_500(4, 500), HZ_1000(5, 1000),
|
|
||||||
}
|
|
||||||
|
|
||||||
class Frame internal constructor(val msgId: Int, val payload: ByteArray)
|
|
||||||
|
|
||||||
class Reply internal constructor(val status: Int, val body: ByteArray) {
|
|
||||||
val success: Boolean get() = status == 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// Device ticks have no established time unit; quaternion is xyzw with no axis remapping.
|
|
||||||
class Pose internal constructor(
|
|
||||||
val deviceTick: Long,
|
|
||||||
val quaternion: FloatArray,
|
|
||||||
val unknown: Long,
|
|
||||||
)
|
|
||||||
|
|
||||||
class RawSample internal constructor(
|
|
||||||
val deviceTick: Long,
|
|
||||||
val gyroRadPerSec: FloatArray,
|
|
||||||
val accelG: FloatArray,
|
|
||||||
val payload: ByteArray,
|
|
||||||
)
|
|
||||||
|
|
||||||
fun packet(msgId: Int, payload: ByteArray = ByteArray(0)): ByteArray {
|
|
||||||
require(msgId in 0..0xFFFF)
|
|
||||||
require(payload.size <= MAX_PAYLOAD_SIZE)
|
|
||||||
return ByteArray(HEADER_SIZE + payload.size).also { buffer ->
|
|
||||||
putU16(buffer, 0, PREAMBLE)
|
|
||||||
putU16(buffer, 2, msgId)
|
|
||||||
putU16(buffer, 4, payload.size)
|
|
||||||
putU16(buffer, 6, checksum(payload, 0, payload.size))
|
|
||||||
payload.copyInto(buffer, HEADER_SIZE)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun imuControl(streams: Int, rate: Rate = Rate.HZ_120): ByteArray {
|
|
||||||
// Upstream measured that stream mask 3 ACKs but produces no events on Pro 2.
|
|
||||||
require(streams == STREAM_OFF || streams == STREAM_POSE || streams == STREAM_RAW)
|
|
||||||
require(streams != STREAM_POSE || rate.hz <= 240)
|
|
||||||
val wireRate = if (streams == STREAM_OFF) 0 else rate.wireValue
|
|
||||||
return packet(MSG_IMU_CONTROL, byteArrayOf(streams.toByte(), wireRate.toByte()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun parse(buffer: ByteArray, size: Int = buffer.size): Frame? {
|
|
||||||
if (size < HEADER_SIZE || size > PACKET_SIZE || size > buffer.size) return null
|
|
||||||
if (u16(buffer, 0) != PREAMBLE) return null
|
|
||||||
val payloadSize = u16(buffer, 4)
|
|
||||||
if (payloadSize > MAX_PAYLOAD_SIZE || HEADER_SIZE + payloadSize > size) return null
|
|
||||||
if (checksum(buffer, HEADER_SIZE, payloadSize) != u16(buffer, 6)) return null
|
|
||||||
return Frame(u16(buffer, 2), buffer.copyOfRange(HEADER_SIZE, HEADER_SIZE + payloadSize))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun reply(frame: Frame, requestMsgId: Int): Reply? {
|
|
||||||
if (requestMsgId !in 0..0xFFFF || frame.msgId != ((requestMsgId + RESPONSE_OFFSET) and 0xFFFF)) return null
|
|
||||||
if (frame.payload.isEmpty()) return null
|
|
||||||
return Reply(u8(frame.payload[0]), frame.payload.copyOfRange(1, frame.payload.size))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun pose(frame: Frame): Pose? {
|
|
||||||
if (frame.msgId != EVENT_POSE || frame.payload.size != 24) return null
|
|
||||||
val payload = frame.payload
|
|
||||||
val w = float(payload, 8)
|
|
||||||
val x = float(payload, 12)
|
|
||||||
val y = float(payload, 16)
|
|
||||||
val z = float(payload, 20)
|
|
||||||
if (!w.isFinite() || !x.isFinite() || !y.isFinite() || !z.isFinite()) return null
|
|
||||||
val norm = sqrt(w.toDouble() * w + x.toDouble() * x + y.toDouble() * y + z.toDouble() * z)
|
|
||||||
if (norm !in 0.9..1.1) return null
|
|
||||||
val n = norm.toFloat()
|
|
||||||
return Pose(u32(payload, 4), floatArrayOf(x / n, y / n, z / n, w / n), u32(payload, 0))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun raw(frame: Frame): RawSample? {
|
|
||||||
if (frame.msgId != EVENT_RAW || frame.payload.size != 56) return null
|
|
||||||
val payload = frame.payload
|
|
||||||
val gyro = floatArrayOf(float(payload, 10), float(payload, 14), float(payload, 18))
|
|
||||||
val accel = floatArrayOf(float(payload, 22), float(payload, 26), float(payload, 30))
|
|
||||||
if (gyro.any { !it.isFinite() } || accel.any { !it.isFinite() }) return null
|
|
||||||
return RawSample(u32(payload, 4), gyro, accel, payload.copyOf())
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun checksum(buffer: ByteArray, offset: Int, size: Int): Int {
|
|
||||||
var sum = 0
|
|
||||||
for (i in offset until offset + size) sum += u8(buffer[i])
|
|
||||||
return sum and 0xFFFF
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun u8(value: Byte) = value.toInt() and 0xFF
|
|
||||||
|
|
||||||
private fun u16(buffer: ByteArray, offset: Int) =
|
|
||||||
u8(buffer[offset]) or (u8(buffer[offset + 1]) shl 8)
|
|
||||||
|
|
||||||
private fun u32(buffer: ByteArray, offset: Int): Long =
|
|
||||||
u16(buffer, offset).toLong() or (u16(buffer, offset + 2).toLong() shl 16)
|
|
||||||
|
|
||||||
private fun float(buffer: ByteArray, offset: Int): Float = Float.fromBits(u32(buffer, offset).toInt())
|
|
||||||
|
|
||||||
private fun putU16(buffer: ByteArray, offset: Int, value: Int) {
|
|
||||||
buffer[offset] = value.toByte()
|
|
||||||
buffer[offset + 1] = (value ushr 8).toByte()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,27 +4,20 @@ import kotlin.math.abs
|
|||||||
|
|
||||||
/** 1S radians/sec and device nanoseconds, mapped using directed hardware captures. */
|
/** 1S radians/sec and device nanoseconds, mapped using directed hardware captures. */
|
||||||
internal class XrealOrientationFilter {
|
internal class XrealOrientationFilter {
|
||||||
private val fusion = ImuFusion()
|
|
||||||
|
|
||||||
// 1S reports right/down/forward. Rotate 180 degrees about X into the
|
|
||||||
// shared right/up/back basis before either gravity alignment or fusion.
|
|
||||||
// Captures: level gravity -Y; looking left -gyroY; up +gyroX; right tilt +gyroZ.
|
|
||||||
fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs,
|
|
||||||
Vec3(sample.accel.x, -sample.accel.y, -sample.accel.z),
|
|
||||||
Vec3(sample.gyro.x, -sample.gyro.y, -sample.gyro.z))
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Gyro integration with gravity correction in the shared right/up/back basis, rad/s and device ns. */
|
|
||||||
internal class ImuFusion {
|
|
||||||
private var previous = 0L
|
private var previous = 0L
|
||||||
private var rotation = Quaternion.IDENTITY
|
private var rotation = Quaternion.IDENTITY
|
||||||
private var initialized = false
|
private var initialized = false
|
||||||
private var bias = Vec3(0f, 0f, 0f)
|
private var bias = Vec3(0f, 0f, 0f)
|
||||||
|
|
||||||
fun update(timeNs: Long, accel: Vec3, gyro: Vec3): FloatArray? {
|
fun update(sample: XrealProtocol.Sample): FloatArray? {
|
||||||
if (timeNs <= previous) return null
|
if (sample.timeNs <= previous) return null
|
||||||
val dt = if (previous == 0L) 0f else (timeNs - previous) * 1e-9f
|
val dt = if (previous == 0L) 0f else (sample.timeNs - previous) * 1e-9f
|
||||||
previous = timeNs
|
previous = sample.timeNs
|
||||||
|
// 1S reports right/down/forward. Rotate 180 degrees about X into the
|
||||||
|
// shared right/up/back basis before either gravity alignment or fusion.
|
||||||
|
// Captures: level gravity -Y; looking left -gyroY; up +gyroX; right tilt +gyroZ.
|
||||||
|
val accel = Vec3(sample.accel.x, -sample.accel.y, -sample.accel.z)
|
||||||
|
val gyro = Vec3(sample.gyro.x, -sample.gyro.y, -sample.gyro.z)
|
||||||
val norm = accel.length()
|
val norm = accel.length()
|
||||||
val gravityValid = abs(norm - 9.81f) < 1.5f
|
val gravityValid = abs(norm - 9.81f) < 1.5f
|
||||||
if (dt > 0.25f) initialized = false // Never integrate a reconnect/stall as motion.
|
if (dt > 0.25f) initialized = false // Never integrate a reconnect/stall as motion.
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ object AutoDriverTrial {
|
|||||||
release, p.getString("name", "").orEmpty(),
|
release, p.getString("name", "").orEmpty(),
|
||||||
p.getString("display", "").orEmpty(), p.getString("linux", "").orEmpty(),
|
p.getString("display", "").orEmpty(), p.getString("linux", "").orEmpty(),
|
||||||
p.getString("previousDisplay", "").orEmpty(), p.getString("previousLinux", "").orEmpty(),
|
p.getString("previousDisplay", "").orEmpty(), p.getString("previousLinux", "").orEmpty(),
|
||||||
maxOf(p.getInt("starts", 0), p.getInt("displayStarts", 0)),
|
p.getInt("starts", 0),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,7 +37,7 @@ object AutoDriverTrial {
|
|||||||
.putString("release", release).putString("name", name)
|
.putString("release", release).putString("name", name)
|
||||||
.putString("display", display).putString("linux", linux)
|
.putString("display", display).putString("linux", linux)
|
||||||
.putString("previousDisplay", previousDisplay).putString("previousLinux", previousLinux)
|
.putString("previousDisplay", previousDisplay).putString("previousLinux", previousLinux)
|
||||||
.putInt("starts", 0).putInt("displayStarts", 0)
|
.putInt("starts", 0)
|
||||||
.commit()
|
.commit()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,24 +48,13 @@ object AutoDriverTrial {
|
|||||||
|
|
||||||
fun bad(context: Context): Set<String> = prefs(context).getStringSet("bad", emptySet()).orEmpty()
|
fun bad(context: Context): Set<String> = prefs(context).getStringSet("bad", emptySet()).orEmpty()
|
||||||
|
|
||||||
/**
|
|
||||||
* Counted before the compositor loads the trial display driver, so a driver that kills the process during
|
|
||||||
* Vulkan init still counts towards a rollback; sessionStarting runs too late for that.
|
|
||||||
*/
|
|
||||||
fun displayStarting(context: Context, display: String) {
|
|
||||||
val p = prefs(context)
|
|
||||||
if (p.getString("release", null) == null || p.getString("display", "") != display) return
|
|
||||||
val counted = maxOf(p.getInt("displayStarts", 0), p.getInt("starts", 0))
|
|
||||||
p.edit().putInt("displayStarts", counted + 1).commit()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun sessionStarting(context: Context, display: String, linux: String) {
|
fun sessionStarting(context: Context, display: String, linux: String) {
|
||||||
val trial = current(context)
|
val trial = current(context)
|
||||||
watching = null
|
watching = null
|
||||||
if (trial == null || trial.display != display || trial.linux != linux) return
|
if (trial == null || trial.display != display || trial.linux != linux) return
|
||||||
app = context.applicationContext
|
app = context.applicationContext
|
||||||
watching = trial
|
watching = trial
|
||||||
prefs(context).edit().putInt("starts", prefs(context).getInt("starts", 0) + 1).commit()
|
prefs(context).edit().putInt("starts", trial.starts + 1).commit()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun sessionReady() {
|
fun sessionReady() {
|
||||||
|
|||||||
@@ -57,11 +57,10 @@ object DeviceInfo {
|
|||||||
add("Model found from", when (gpu.modelSource) {
|
add("Model found from", when (gpu.modelSource) {
|
||||||
"kernel" -> "the kernel's GPU name"
|
"kernel" -> "the kernel's GPU name"
|
||||||
"vulkan" -> "the Vulkan driver (the kernel's name has no model)"
|
"vulkan" -> "the Vulkan driver (the kernel's name has no model)"
|
||||||
"platform" -> "the platform or SoC (the kernel and Vulkan names have no model)"
|
"platform" -> "the platform (the kernel's name has no model)"
|
||||||
else -> "unknown"
|
else -> "unknown"
|
||||||
})
|
})
|
||||||
add("Kernel name", gpu.kgslName)
|
add("Kernel name", gpu.kgslName)
|
||||||
add("Kernel chip id", gpu.kgslChipId)
|
|
||||||
val kgsl = "/sys/class/kgsl/kgsl-3d0"
|
val kgsl = "/sys/class/kgsl/kgsl-3d0"
|
||||||
add("Clock range", gpuRange())
|
add("Clock range", gpuRange())
|
||||||
add("Load", read("$kgsl/gpu_busy_percentage")?.let { if (it.endsWith("%")) it else "$it %" })
|
add("Load", read("$kgsl/gpu_busy_percentage")?.let { if (it.endsWith("%")) it else "$it %" })
|
||||||
|
|||||||
@@ -50,10 +50,8 @@ object FrameGen {
|
|||||||
else -> context.getString(R.string.frame_gen_off)
|
else -> context.getString(R.string.frame_gen_off)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun apply(context: Context, refreshHz: Float): String? = apply(context, mode(context), refreshHz)
|
fun apply(context: Context, refreshHz: Float): String? {
|
||||||
|
val mode = mode(context)
|
||||||
/** Arms [mode] in this process's compositor; the cloud player passes its own mode and frame-rate cap. */
|
|
||||||
fun apply(context: Context, mode: Mode, refreshHz: Float): String? {
|
|
||||||
when (mode.engine) {
|
when (mode.engine) {
|
||||||
ENGINE_LSFG -> {
|
ENGINE_LSFG -> {
|
||||||
val status = Lossless.sync(context)
|
val status = Lossless.sync(context)
|
||||||
|
|||||||
@@ -14,8 +14,6 @@ data class GpuInfo(
|
|||||||
val oneUi8Gen2: Boolean,
|
val oneUi8Gen2: Boolean,
|
||||||
val kgslName: String = "",
|
val kgslName: String = "",
|
||||||
val modelSource: String = "",
|
val modelSource: String = "",
|
||||||
val kgslChipId: String = "",
|
|
||||||
val platformGpuModel: Int = 0,
|
|
||||||
) {
|
) {
|
||||||
enum class Family(val label: String) {
|
enum class Family(val label: String) {
|
||||||
A8XX("Adreno 8xx"),
|
A8XX("Adreno 8xx"),
|
||||||
@@ -30,12 +28,9 @@ data class GpuInfo(
|
|||||||
|
|
||||||
enum class Support { TESTED, UNTESTED, UNSUPPORTED }
|
enum class Support { TESTED, UNTESTED, UNSUPPORTED }
|
||||||
|
|
||||||
private val isA850: Boolean get() = model == 850 || platformGpuModel == 850
|
|
||||||
|
|
||||||
val support: Support
|
val support: Support
|
||||||
get() = when {
|
get() = when {
|
||||||
family == Family.NOT_ADRENO -> Support.UNSUPPORTED
|
family == Family.NOT_ADRENO -> Support.UNSUPPORTED
|
||||||
isA850 -> Support.UNTESTED
|
|
||||||
family == Family.A6XX && model == 650 -> Support.TESTED
|
family == Family.A6XX && model == 650 -> Support.TESTED
|
||||||
family == Family.A8XX -> Support.TESTED
|
family == Family.A8XX -> Support.TESTED
|
||||||
family == Family.A7XX && model >= 725 -> Support.TESTED
|
family == Family.A7XX && model >= 725 -> Support.TESTED
|
||||||
@@ -45,19 +40,14 @@ data class GpuInfo(
|
|||||||
val supportText: String
|
val supportText: String
|
||||||
get() = when (support) {
|
get() = when (support) {
|
||||||
Support.TESTED -> "Supported"
|
Support.TESTED -> "Supported"
|
||||||
Support.UNTESTED -> if (isA850) "Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device"
|
Support.UNTESTED -> if (family == Family.A7XX_LOW) "Experimental: its drivers are test builds"
|
||||||
else if (family == Family.A7XX_LOW) "Experimental: its drivers are test builds"
|
|
||||||
else "Outside tested hardware (Adreno 650, 725 and newer): it may not run"
|
else "Outside tested hardware (Adreno 650, 725 and newer): it may not run"
|
||||||
Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
|
Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
|
||||||
}
|
}
|
||||||
|
|
||||||
fun supportText(context: Context): String = context.getString(when (support) {
|
fun supportText(context: Context): String = context.getString(when (support) {
|
||||||
Support.TESTED -> R.string.gpuinfo_supported
|
Support.TESTED -> R.string.gpuinfo_supported
|
||||||
Support.UNTESTED -> when {
|
Support.UNTESTED -> if (family == Family.A7XX_LOW) R.string.gpuinfo_experimental else R.string.gpuinfo_below_tested
|
||||||
isA850 -> R.string.gpuinfo_a850_experimental
|
|
||||||
family == Family.A7XX_LOW -> R.string.gpuinfo_experimental
|
|
||||||
else -> R.string.gpuinfo_below_tested
|
|
||||||
}
|
|
||||||
Support.UNSUPPORTED -> R.string.gpuinfo_unsupported
|
Support.UNSUPPORTED -> R.string.gpuinfo_unsupported
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -68,49 +58,38 @@ data class GpuInfo(
|
|||||||
|
|
||||||
fun detect(): GpuInfo {
|
fun detect(): GpuInfo {
|
||||||
val adreno = File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
|
val adreno = File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
|
||||||
val raw = FileUtils.readString(File("/sys/class/kgsl/kgsl-3d0/gpu_model"))?.trim()
|
val raw = listOf("/sys/class/kgsl/kgsl-3d0/gpu_model", "/sys/class/kgsl/kgsl-3d0/gpu_chipid")
|
||||||
val chipId = FileUtils.readString(File("/sys/class/kgsl/kgsl-3d0/gpu_chipid"))?.trim().orEmpty()
|
.firstNotNullOfOrNull { FileUtils.readString(File(it))?.trim()?.takeIf(String::isNotEmpty) }
|
||||||
val soc = if (adreno) SocNames.label() else ""
|
val soc = if (adreno) SocNames.label() else ""
|
||||||
val platformGpuModel = if (adreno) platformModel() else 0
|
val fromKernel = raw?.let { threeDigits(it) } ?: 0
|
||||||
val (model, source) = if (adreno) modelFromNames(
|
val fromVulkan = if (fromKernel > 0 || !adreno) 0 else VulkanInfo.cachedOrNull()?.get("device")?.let { threeDigits(it) } ?: 0
|
||||||
raw,
|
val fromPlatform = if (fromKernel > 0 || fromVulkan > 0 || !adreno) 0 else platformModel()
|
||||||
{ VulkanInfo.cachedOrNull()?.get("device") },
|
val model = maxOf(fromKernel, fromVulkan, fromPlatform)
|
||||||
{ platformGpuModel },
|
val source = when {
|
||||||
) else 0 to ""
|
fromKernel > 0 -> "kernel"
|
||||||
|
fromVulkan > 0 -> "vulkan"
|
||||||
|
fromPlatform > 0 -> "platform"
|
||||||
|
else -> ""
|
||||||
|
}
|
||||||
val family = familyOf(adreno, model)
|
val family = familyOf(adreno, model)
|
||||||
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
|
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
|
||||||
return GpuInfo(
|
return GpuInfo(
|
||||||
name = if (!adreno) Build.HARDWARE.ifBlank { UNNAMED } else if (model > 0) "Adreno $model" else "Adreno",
|
name = if (!adreno) Build.HARDWARE.ifBlank { UNNAMED } else if (model > 0) "Adreno $model" else "Adreno",
|
||||||
model = model, family = family, soc = soc,
|
model = model, family = family, soc = soc,
|
||||||
oneUi8Gen2 = samsung && model == 740,
|
oneUi8Gen2 = samsung && model == 740,
|
||||||
kgslName = raw.orEmpty(), modelSource = source, kgslChipId = chipId,
|
kgslName = raw.orEmpty(), modelSource = source,
|
||||||
platformGpuModel = platformGpuModel,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun threeDigits(text: String): Int = Regex("""(?i)\badreno\s*(?:\(TM\)\s*)?(\d{3})(?!\d)""").find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
|
internal fun threeDigits(text: String): Int = Regex("""(\d{3})""").find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
|
||||||
|
|
||||||
internal fun modelFromNames(
|
|
||||||
kernelName: String?,
|
|
||||||
vulkanName: () -> String?,
|
|
||||||
fallback: () -> Int,
|
|
||||||
): Pair<Int, String> {
|
|
||||||
kernelName?.let { threeDigits(it) }?.takeIf { it > 0 }?.let { return it to "kernel" }
|
|
||||||
vulkanName()?.let { threeDigits(it) }?.takeIf { it > 0 }?.let { return it to "vulkan" }
|
|
||||||
return fallback().let { if (it > 0) it to "platform" else 0 to "" }
|
|
||||||
}
|
|
||||||
|
|
||||||
private val PLATFORMS = mapOf(
|
private val PLATFORMS = mapOf(
|
||||||
"msmnile" to 640, "kona" to 650, "lahaina" to 660, "taro" to 730, "cape" to 730,
|
"msmnile" to 640, "kona" to 650, "lahaina" to 660, "taro" to 730, "cape" to 730,
|
||||||
"kalama" to 740, "pineapple" to 750, "sun" to 830,
|
"kalama" to 740, "pineapple" to 750, "sun" to 830,
|
||||||
)
|
)
|
||||||
|
|
||||||
internal fun platformModel(
|
internal fun platformModel(platform: String = systemProperty("ro.board.platform")): Int =
|
||||||
platform: String = systemProperty("ro.board.platform"),
|
PLATFORMS[platform.lowercase()] ?: PLATFORMS[systemProperty("ro.vendor.qti.soc_name").lowercase()] ?: 0
|
||||||
qtiSocName: String = systemProperty("ro.vendor.qti.soc_name"),
|
|
||||||
socModel: String = SocNames.model(),
|
|
||||||
): Int = if (SocNames.normalizedModel(socModel) == "SM8975" || SocNames.normalizedModel(qtiSocName) == "SM8975") 850
|
|
||||||
else PLATFORMS[platform.lowercase()] ?: PLATFORMS[qtiSocName.lowercase()] ?: 0
|
|
||||||
|
|
||||||
fun systemProperty(name: String): String = try {
|
fun systemProperty(name: String): String = try {
|
||||||
Class.forName("android.os.SystemProperties").getMethod("get", String::class.java).invoke(null, name) as? String ?: ""
|
Class.forName("android.os.SystemProperties").getMethod("get", String::class.java).invoke(null, name) as? String ?: ""
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ object SocNames {
|
|||||||
"SM8350" to "Snapdragon 888", "SM8450" to "Snapdragon 8 Gen 1", "SM8475" to "Snapdragon 8+ Gen 1",
|
"SM8350" to "Snapdragon 888", "SM8450" to "Snapdragon 8 Gen 1", "SM8475" to "Snapdragon 8+ Gen 1",
|
||||||
"SM8550" to "Snapdragon 8 Gen 2", "QCS8550" to "Snapdragon 8 Gen 2", "SM8650" to "Snapdragon 8 Gen 3",
|
"SM8550" to "Snapdragon 8 Gen 2", "QCS8550" to "Snapdragon 8 Gen 2", "SM8650" to "Snapdragon 8 Gen 3",
|
||||||
"SM8750" to "Snapdragon 8 Elite", "SM8850" to "Snapdragon 8 Elite Gen 5",
|
"SM8750" to "Snapdragon 8 Elite", "SM8850" to "Snapdragon 8 Elite Gen 5",
|
||||||
"SM8975" to "Snapdragon 8 Elite Extreme Gen 6",
|
|
||||||
"SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3",
|
"SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3",
|
||||||
"SM6375" to "Snapdragon 695",
|
"SM6375" to "Snapdragon 695",
|
||||||
)
|
)
|
||||||
@@ -26,10 +25,8 @@ object SocNames {
|
|||||||
.firstOrNull { it.isNotEmpty() && !Regex("(?i)^msm_\\d").containsMatchIn(it) }.orEmpty()
|
.firstOrNull { it.isNotEmpty() && !Regex("(?i)^msm_\\d").containsMatchIn(it) }.orEmpty()
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun normalizedModel(model: String): String = model.trim().uppercase().removePrefix("QTI ").trim()
|
|
||||||
|
|
||||||
fun name(model: String, platform: String = GpuInfo.systemProperty("ro.board.platform")): String? =
|
fun name(model: String, platform: String = GpuInfo.systemProperty("ro.board.platform")): String? =
|
||||||
MODELS[normalizedModel(model)] ?: PLATFORMS[platform.lowercase()]?.let { "$it family" }
|
MODELS[model.uppercase()] ?: PLATFORMS[platform.lowercase()]?.let { "$it family" }
|
||||||
|
|
||||||
fun label(model: String = model(), platform: String = GpuInfo.systemProperty("ro.board.platform")): String {
|
fun label(model: String = model(), platform: String = GpuInfo.systemProperty("ro.board.platform")): String {
|
||||||
val name = name(model, platform)
|
val name = name(model, platform)
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
package com.droiddeck.launcher.gpu
|
package com.droiddeck.launcher.gpu
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
|
||||||
|
|
||||||
object TpUbwcHint {
|
object TpUbwcHint {
|
||||||
const val ENV = "FD_DEV_FEATURES"
|
const val ENV = "FD_DEV_FEATURES"
|
||||||
@@ -10,43 +8,31 @@ object TpUbwcHint {
|
|||||||
|
|
||||||
@Volatile private var resolved = false
|
@Volatile private var resolved = false
|
||||||
@Volatile private var cached: String? = null
|
@Volatile private var cached: String? = null
|
||||||
@Volatile var activeMode: String? = null
|
|
||||||
private set
|
|
||||||
|
|
||||||
// On Adreno 740, TPL1_DBG_ECO_CNTL1.TP_UBWC_FLAG_HINT is shared by every driver on the GPU and must
|
// On Adreno 740, TPL1_DBG_ECO_CNTL1.TP_UBWC_FLAG_HINT is shared by every driver on the GPU and must
|
||||||
// match the system driver. A mismatch corrupts Android UI.
|
// match the system driver: blob v6xx leaves it off, newer blobs set it. A mismatch corrupts Android UI.
|
||||||
// Samsung's One UI firmware sets it whatever blob version it reports.
|
// Samsung's One UI firmware sets it whatever blob version it reports.
|
||||||
internal fun features(model: Int, systemDriverVersion: String?, samsung: Boolean = false,
|
internal fun features(model: Int, systemDriverVersion: String?, samsung: Boolean = false): String? {
|
||||||
mode: String = SessionPrefs.TP_UBWC_AUTO): String? {
|
|
||||||
if (model != 740) return null
|
if (model != 740) return null
|
||||||
if (mode == SessionPrefs.TP_UBWC_ON) return "enable_tp_ubwc_flag_hint=1"
|
|
||||||
if (mode == SessionPrefs.TP_UBWC_OFF) return "enable_tp_ubwc_flag_hint=0"
|
|
||||||
if (samsung) return "enable_tp_ubwc_flag_hint=1"
|
if (samsung) return "enable_tp_ubwc_flag_hint=1"
|
||||||
val parts = systemDriverVersion?.split('.') ?: return null
|
val blob = systemDriverVersion?.split('.')?.getOrNull(1)?.toIntOrNull() ?: return null
|
||||||
val blob = parts.getOrNull(1)?.toIntOrNull() ?: return null
|
return "enable_tp_ubwc_flag_hint=" + if (blob >= 700) "1" else "0"
|
||||||
val patch = parts.getOrNull(2)?.toIntOrNull() ?: 0
|
|
||||||
val on = blob >= 700 || (blob == 676 && patch >= 76)
|
|
||||||
return "enable_tp_ubwc_flag_hint=" + if (on) "1" else "0"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun forThisDevice(context: Context): String? {
|
fun forThisDevice(): String? {
|
||||||
if (resolved) return cached
|
if (resolved) return cached
|
||||||
val mode = SessionPrefs.tpUbwcMode(context)
|
|
||||||
val gpu = GpuInfo.detect()
|
val gpu = GpuInfo.detect()
|
||||||
val model = gpu.model
|
val model = gpu.model
|
||||||
val version = if (model == 740) VulkanInfo.query()["driver_version"] else null
|
val version = if (model == 740) VulkanInfo.query()["driver_version"] else null
|
||||||
cached = features(model, version, gpu.oneUi8Gen2, mode)
|
cached = features(model, version, gpu.oneUi8Gen2)
|
||||||
activeMode = mode
|
|
||||||
resolved = true
|
resolved = true
|
||||||
Log.i(TAG, "Adreno $model${if (gpu.oneUi8Gen2) " (One UI)" else ""}, system driver ${version ?: "n/a"}, mode $mode: ${cached ?: "driver default"}")
|
Log.i(TAG, "Adreno $model${if (gpu.oneUi8Gen2) " (One UI)" else ""}, system driver ${version ?: "n/a"}: ${cached ?: "driver default"}")
|
||||||
return cached
|
return cached
|
||||||
}
|
}
|
||||||
|
|
||||||
fun restartRequired(context: Context): Boolean = resolved && activeMode != SessionPrefs.tpUbwcMode(context)
|
fun applyToProcess() {
|
||||||
|
val value = forThisDevice() ?: return
|
||||||
fun applyToProcess(context: Context) {
|
|
||||||
val value = forThisDevice(context) ?: return
|
|
||||||
runCatching { android.system.Os.setenv(ENV, value, true) }
|
runCatching { android.system.Os.setenv(ENV, value, true) }
|
||||||
.onFailure { Log.w(TAG, "setenv $ENV failed: ${it.javaClass.simpleName}") }
|
.onFailure { Log.w(TAG, "setenv $ENV failed: ${it.javaClass.simpleName}") }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ import java.util.ArrayList;
|
|||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.function.Supplier;
|
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
import java.util.zip.ZipInputStream;
|
import java.util.zip.ZipInputStream;
|
||||||
|
|
||||||
@@ -48,16 +47,10 @@ public final class TurnipDriver {
|
|||||||
|
|
||||||
private final Context context;
|
private final Context context;
|
||||||
private final File contentDir;
|
private final File contentDir;
|
||||||
private final Supplier<GpuInfo> gpuDetector;
|
|
||||||
|
|
||||||
public TurnipDriver(Context context) {
|
public TurnipDriver(Context context) {
|
||||||
this(context, GpuInfo.Companion::detect);
|
|
||||||
}
|
|
||||||
|
|
||||||
TurnipDriver(Context context, Supplier<GpuInfo> gpuDetector) {
|
|
||||||
this.context = context;
|
this.context = context;
|
||||||
this.contentDir = new File(context.getFilesDir(), "graphics_driver");
|
this.contentDir = new File(context.getFilesDir(), "graphics_driver");
|
||||||
this.gpuDetector = gpuDetector;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String driverPath(String driverId) {
|
public String driverPath(String driverId) {
|
||||||
@@ -291,20 +284,27 @@ public final class TurnipDriver {
|
|||||||
}
|
}
|
||||||
String quest = QuestExperimental.INSTANCE.defaultAndroidDriver();
|
String quest = QuestExperimental.INSTANCE.defaultAndroidDriver();
|
||||||
if (quest != null) return quest;
|
if (quest != null) return quest;
|
||||||
GpuInfo gpu = gpuDetector.get();
|
String model = gpuModel();
|
||||||
if (gpu.getFamily() == GpuInfo.Family.NOT_ADRENO) {
|
Log.i(TAG, "gpu model: " + (model == null ? "unknown" : model));
|
||||||
Log.i(TAG, "not an Adreno GPU; leaving the display driver to the system");
|
if (model != null) {
|
||||||
return null;
|
java.util.regex.Matcher m = java.util.regex.Pattern.compile("(\\d)\\d\\d").matcher(model);
|
||||||
|
if (m.find()) {
|
||||||
|
char generation = m.group(1).charAt(0);
|
||||||
|
if (generation >= '8') return DRIVER_A8XX;
|
||||||
|
if (generation == '7') return DRIVER_A7XX;
|
||||||
|
if (generation == '6') return DRIVER_A6XX;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
int model = gpu.getModel();
|
return android.os.Build.VERSION.SDK_INT >= 36 ? DRIVER_A8XX : DRIVER_A7XX;
|
||||||
Log.i(TAG, "gpu model: " + (model == 0 ? "unknown" : model));
|
|
||||||
return chooseByModel(model, android.os.Build.VERSION.SDK_INT);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static String chooseByModel(int model, int sdk) {
|
private static String gpuModel() {
|
||||||
if (model >= 800) return DRIVER_A8XX;
|
for (String path : new String[]{
|
||||||
if (model >= 700) return DRIVER_A7XX;
|
"/sys/class/kgsl/kgsl-3d0/gpu_model",
|
||||||
if (model >= 600) return DRIVER_A6XX;
|
"/sys/class/kgsl/kgsl-3d0/gpu_chipid"}) {
|
||||||
return sdk >= 36 ? DRIVER_A8XX : DRIVER_A7XX;
|
String value = FileUtils.readString(new File(path));
|
||||||
|
if (value != null && !value.trim().isEmpty()) return value.trim();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
package com.droiddeck.launcher.input
|
|
||||||
|
|
||||||
import android.view.KeyEvent
|
|
||||||
import android.os.Handler
|
|
||||||
import android.os.Looper
|
|
||||||
|
|
||||||
class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap: (Boolean) -> Unit,
|
|
||||||
private val doubleTapMs: () -> Long = { 500 }, private val onCancel: () -> Unit = {}) {
|
|
||||||
private class Press(val hold: Runnable, var held: Boolean = false, var used: Boolean = false)
|
|
||||||
private val handler = Handler(Looper.getMainLooper())
|
|
||||||
private val presses = mutableMapOf<Int, Press>()
|
|
||||||
private val cancelled = mutableSetOf<Int>()
|
|
||||||
private var tapPending = false
|
|
||||||
private val singleTap = Runnable { tapPending = false; onTap(false) }
|
|
||||||
|
|
||||||
private fun cancelTap() {
|
|
||||||
handler.removeCallbacks(singleTap)
|
|
||||||
tapPending = false
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onChordInput() {
|
|
||||||
if (presses.isEmpty()) return
|
|
||||||
val alreadyHeld = presses.values.any { it.held }
|
|
||||||
presses.values.forEach {
|
|
||||||
handler.removeCallbacks(it.hold)
|
|
||||||
it.held = true
|
|
||||||
it.used = true
|
|
||||||
}
|
|
||||||
cancelTap()
|
|
||||||
if (!alreadyHeld) setPressed(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean {
|
|
||||||
if (!enabled) cancel()
|
|
||||||
if (event.keyCode != KeyEvent.KEYCODE_BACK) return false
|
|
||||||
val device = event.deviceId
|
|
||||||
return when (event.action) {
|
|
||||||
KeyEvent.ACTION_DOWN -> {
|
|
||||||
if (event.repeatCount > 0) return enabled || device in presses || device in cancelled
|
|
||||||
cancelled.remove(device)
|
|
||||||
if (!enabled || event.isCanceled) return false
|
|
||||||
if (device in presses) return true
|
|
||||||
handler.removeCallbacks(singleTap)
|
|
||||||
val hold = Runnable {
|
|
||||||
val press = presses[device] ?: return@Runnable
|
|
||||||
val alreadyHeld = presses.values.any { it.held }
|
|
||||||
press.held = true
|
|
||||||
presses.values.forEach { it.used = true }
|
|
||||||
cancelTap()
|
|
||||||
if (!alreadyHeld) setPressed(true)
|
|
||||||
}
|
|
||||||
presses[device] = Press(hold, used = presses.values.any { it.held })
|
|
||||||
handler.postDelayed(hold, 700)
|
|
||||||
true
|
|
||||||
}
|
|
||||||
KeyEvent.ACTION_UP -> {
|
|
||||||
val press = presses.remove(device)
|
|
||||||
val wasCancelled = cancelled.remove(device)
|
|
||||||
if (press != null) {
|
|
||||||
handler.removeCallbacks(press.hold)
|
|
||||||
if (press.held && presses.values.none { it.held }) setPressed(false)
|
|
||||||
if (!press.used && !event.isCanceled) {
|
|
||||||
if (tapPending) { cancelTap(); onTap(true) }
|
|
||||||
else { tapPending = true; handler.postDelayed(singleTap, doubleTapMs()) }
|
|
||||||
} else if (event.isCanceled) cancelTap()
|
|
||||||
}
|
|
||||||
press != null || wasCancelled || enabled
|
|
||||||
}
|
|
||||||
else -> device in presses || device in cancelled
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun cancel() {
|
|
||||||
cancelTap()
|
|
||||||
val wasHeld = presses.values.any { it.held }
|
|
||||||
presses.values.forEach { handler.removeCallbacks(it.hold) }
|
|
||||||
cancelled.addAll(presses.keys)
|
|
||||||
presses.clear()
|
|
||||||
onCancel()
|
|
||||||
if (wasHeld) setPressed(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun onDeviceRemoved(device: Int) {
|
|
||||||
cancelled.remove(device)
|
|
||||||
val press = presses.remove(device) ?: return
|
|
||||||
handler.removeCallbacks(press.hold)
|
|
||||||
cancelTap()
|
|
||||||
if (press.held && presses.values.none { it.held }) {
|
|
||||||
onCancel()
|
|
||||||
setPressed(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Loaded 100 of 875 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user