mirror of
https://github.com/kunkundi/crossdesk.git
synced 2026-10-15 00:09:39 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
420e7a8cbb | ||
|
|
58ca67fa25 | ||
|
|
1f82bb39da | ||
|
|
587a1ef07b | ||
|
|
171de8b026 | ||
|
|
1dccbe42a3 | ||
|
|
be639eaf97 | ||
|
|
055d8424a6 | ||
|
|
5a7e816fb7 | ||
|
|
a06ed5806a | ||
|
|
d3ecbe2cc9 | ||
|
|
41aed0984f | ||
|
|
080b9760e3 | ||
|
|
4d65d12add | ||
|
|
dacdbc5c45 | ||
|
|
6d9230ff91 | ||
|
|
1d47256cbc | ||
|
|
9d613a5a13 | ||
|
|
06e23007ed | ||
|
|
3cfe7cbb80 | ||
|
|
5004c91a6c | ||
|
|
b0d6e8a520 | ||
|
|
abcdb214f2 | ||
|
|
f335f274ab | ||
|
|
5af7cc35e9 | ||
|
|
9550731681 | ||
|
|
ec6fe8ea98 | ||
|
|
ddefd14409 | ||
|
|
76eddc9f02 | ||
|
|
9489ede03c | ||
|
|
2f1c16c781 | ||
|
|
050394135a | ||
|
|
7f7b91851e | ||
|
|
b8f704abb9 | ||
|
|
115533cd62 | ||
|
|
6e36163eb9 | ||
|
|
9a1371879b | ||
|
|
42498ac33d | ||
|
|
ca89f2ddc3 | ||
|
|
638f829418 | ||
|
|
0f683168cf | ||
|
|
256e28c786 | ||
|
|
758bfaa7a0 | ||
|
|
ad343f2f8b | ||
|
|
da7dcbe8c4 | ||
|
|
13f4116825 | ||
|
|
bb3949a28e | ||
|
|
49e90adb60 | ||
|
|
3b5cbf0735 | ||
|
|
ff706857bd | ||
|
|
e76cfecac8 | ||
|
|
b2f6bd3204 | ||
|
|
b05a84198a | ||
|
|
b9448392a7 | ||
|
|
f08194f686 | ||
|
|
149d20cbd1 | ||
|
|
b935df917f | ||
|
|
fab7edeff1 | ||
|
|
85ca13aa75 | ||
|
|
ff7bda6988 | ||
|
|
380a2a225c | ||
|
|
a535ded76d | ||
|
|
fc67a1543c | ||
|
|
31acb6b2f0 | ||
|
|
2d1241c0a0 | ||
|
|
0031c411e5 | ||
|
|
bc8dbcbf68 | ||
|
|
2d49024bd6 | ||
|
|
597c1dd2c9 | ||
|
|
a83b6badd0 | ||
|
|
6a71a3173a | ||
|
|
c345c69e81 | ||
|
|
f8535a797b | ||
|
|
163506f81e | ||
|
|
a4baca222c | ||
|
|
3992ea56db | ||
|
|
51d392ef48 | ||
|
|
f347fc2387 | ||
|
|
0b28d1bc99 | ||
|
|
e894f4a763 | ||
|
|
e65a30e969 | ||
|
|
52f6f23f93 | ||
|
|
3d2235ad4e | ||
|
|
0b2eb5b106 | ||
|
|
94760b2a3c | ||
|
|
bbbcfb9d6f | ||
|
|
9ef64cc00f | ||
|
|
b8389a8aa0 | ||
|
|
7ac8163931 | ||
|
|
704938a157 | ||
|
|
572a018a72 | ||
|
|
41cab6fa0b | ||
|
|
f73a57baaa | ||
|
|
e62d473b64 | ||
|
|
3c5b3f8e38 | ||
|
|
191ba26772 | ||
|
|
c661319890 | ||
|
|
e0cd4c0567 | ||
|
|
88da1081ef | ||
|
|
b9efb5944c | ||
|
|
5f26a0e239 | ||
|
|
938ce01513 | ||
|
|
2235d5cb62 | ||
|
|
7e3e050edf | ||
|
|
b610a0ec7e | ||
|
|
120368e4f7 | ||
|
|
b34755c5ee | ||
|
|
6387f2e555 | ||
|
|
fb556a763d | ||
|
|
276385b816 | ||
|
|
1a59a6ac2e | ||
|
|
485e347337 | ||
|
|
89b39803e8 | ||
|
|
4797af9260 | ||
|
|
000b2e44e3 | ||
|
|
26217f9d18 | ||
|
|
c2ea90c740 | ||
|
|
0eadcf2855 | ||
|
|
e263aab10d | ||
|
|
9abdfbf684 | ||
|
|
31a0b86cee | ||
|
|
fb34f42744 | ||
|
|
4302ab291c | ||
|
|
4bf92c9e2c | ||
|
|
28de4cf938 | ||
|
|
ce7a3c178e | ||
|
|
d9116200fe | ||
|
|
1d9242515a | ||
|
|
ad62e60b9a | ||
|
|
c4aca303c8 | ||
|
|
57bb91dba3 | ||
|
|
57cab3979e | ||
|
|
d8ccdbaa38 | ||
|
|
f3e67d7d6e | ||
|
|
d648585891 | ||
|
|
e40c7fca98 | ||
|
|
f6324416ec | ||
|
|
0977bd4195 | ||
|
|
f4e094cb35 | ||
|
|
1fe706c5fc | ||
|
|
5fd928ddba | ||
|
|
977899b240 | ||
|
|
7fc1344756 | ||
|
|
73e3bf709d | ||
|
|
6d90c28513 | ||
|
|
c944db6519 | ||
|
|
fc921c9ca1 | ||
|
|
ba2afc982b | ||
|
|
c6635fbdc8 | ||
|
|
3c403f6162 | ||
|
|
b54d32ef41 | ||
|
|
28e9626e0d | ||
|
|
a6e325f190 | ||
|
|
23bf2ff8b8 | ||
|
|
56ebfdf8e7 | ||
|
|
99ae0fc811 | ||
|
|
9af7417c46 | ||
|
|
ceb0a1654a | ||
|
|
4f200095f4 | ||
|
|
bd0a7aa2f6 | ||
|
|
b87ab025be | ||
|
|
5b60695a52 | ||
|
|
0002bcea74 | ||
|
|
58225de7ea | ||
|
|
5f37d0e753 | ||
|
|
b518ea82e2 | ||
|
|
abc8f907f3 | ||
|
|
d498d3f0ef | ||
|
|
55806d9e82 | ||
|
|
2d3f1bb475 | ||
|
|
5d97d5a393 | ||
|
|
19218a57f9 | ||
|
|
af729144fe | ||
|
|
d381cbaa9b | ||
|
|
5aedb09c55 | ||
|
|
fe1178e26f | ||
|
|
e0cd761bdc | ||
|
|
2000654792 | ||
|
|
19800ef350 | ||
|
|
d10b65cc19 | ||
|
|
3a0179968c | ||
|
|
55f389b834 | ||
|
|
8a58166c59 | ||
|
|
aa2ee8ce7f | ||
|
|
b150d46501 | ||
|
|
010064d5b7 | ||
|
|
db3b26efe7 | ||
|
|
cd1b53ee65 | ||
|
|
b031a3953e | ||
|
|
3f537ae63c | ||
|
|
e716346b26 | ||
|
|
b7e1adbec6 | ||
|
|
58f2daa9c1 | ||
|
|
8752e51921 | ||
|
|
a8cb0e21ce | ||
|
|
90184f5251 | ||
|
|
fb0ab4f14e | ||
|
|
0e3f3cec00 | ||
|
|
72af49eb80 | ||
|
|
36f05834b5 | ||
|
|
1a190fbaf5 | ||
|
|
1fe236da76 | ||
|
|
3b989fb70d | ||
|
|
7595ab8bd8 | ||
|
|
126f455681 | ||
|
|
d6d0a548b2 | ||
|
|
74ac849efe | ||
|
|
e2cd18dba4 | ||
|
|
d2b1329eca | ||
|
|
0653a95250 | ||
|
|
bd73ef55f1 | ||
|
|
b854512c24 | ||
|
|
4528caf0f4 | ||
|
|
f6e89725aa | ||
|
|
62f79a8e44 | ||
|
|
096bc68d35 | ||
|
|
8ea4668305 | ||
|
|
21eec76008 | ||
|
|
3e63675787 | ||
|
|
439f137764 | ||
|
|
f537147f54 | ||
|
|
2186ebd7eb | ||
|
|
c11d48fc1f | ||
|
|
1690fc92a3 | ||
|
|
0d9d385d10 | ||
|
|
20f8137df2 | ||
|
|
29aae747c6 | ||
|
|
3f93dc05aa | ||
|
|
05885ecd48 | ||
|
|
ee92c4ce5f | ||
|
|
d94443330c | ||
|
|
df72204619 | ||
|
|
3678271577 | ||
|
|
6b5535ab3d | ||
|
|
078bd1e520 | ||
|
|
718705c352 | ||
|
|
1ca5852280 | ||
|
|
1eda6cc183 | ||
|
|
8d37f8f5fb | ||
|
|
05b8aa629e | ||
|
|
2cbceba953 | ||
|
|
89d3c8b53f | ||
|
|
51a4190e97 | ||
|
|
3737cd0dd5 | ||
|
|
00957d6740 | ||
|
|
6ec86322b2 | ||
|
|
ecc131b5ee | ||
|
|
1aa50e9ffa | ||
|
|
d49f5bc520 | ||
|
|
8818b9b8be | ||
|
|
3be283238c | ||
|
|
5d0453fff3 | ||
|
|
8a9775a571 | ||
|
|
7f4f1882ae | ||
|
|
23e24e3d47 | ||
|
|
7e1b9cb00e | ||
|
|
0c70acbdbf | ||
|
|
fcbbb0f51c | ||
|
|
f4be0700bf | ||
|
|
a45670b04d | ||
|
|
ff329cae81 | ||
|
|
092664784e | ||
|
|
1709eb0efb | ||
|
|
d27bb5d7a4 | ||
|
|
62c8f0a38d | ||
|
|
21eee5ccdc | ||
|
|
e6c26511cd | ||
|
|
c0b880e1eb | ||
|
|
c10f1499f2 | ||
|
|
d7a9c26ff9 | ||
|
|
f809ad173c | ||
|
|
34155d0266 | ||
|
|
9d544788b0 | ||
|
|
dd16e65b68 | ||
|
|
91eac61a90 | ||
|
|
941cc79af5 | ||
|
|
0d6ecfc730 | ||
|
|
d32974dc18 | ||
|
|
efd8b7c0ff | ||
|
|
383452ed3b | ||
|
|
2570e57958 | ||
|
|
eed90dad34 | ||
|
|
c53ce2a581 | ||
|
|
708c39bb99 | ||
|
|
cee249a25b | ||
|
|
7c3b13409c | ||
|
|
e3d15f8f9a | ||
|
|
a6e8038286 | ||
|
|
765452e3c9 | ||
|
|
7cd0d6a351 | ||
|
|
c01b52eac5 | ||
|
|
737cf9b558 | ||
|
|
6f5faa7111 | ||
|
|
3a72e4849e | ||
|
|
43e44af730 | ||
|
|
97e592861c | ||
|
|
31b8983328 | ||
|
|
522f519d38 | ||
|
|
37c4fe2e8a | ||
|
|
2c20599800 | ||
|
|
f5c4e2ba4a | ||
|
|
59f77c2820 | ||
|
|
eeb6a2a1ae | ||
|
|
1f86c43458 | ||
|
|
c487d3a62c | ||
|
|
aee5be5ee6 | ||
|
|
6ff2783105 | ||
|
|
d6d30b6842 | ||
|
|
5db309243b | ||
|
|
0681f6540d | ||
|
|
d843901550 | ||
|
|
b41630ebb4 | ||
|
|
a815eecc73 | ||
|
|
7e0984fe9c | ||
|
|
9c28cd2ab2 | ||
|
|
3c4000bdbb | ||
|
|
d8e9fa5bba | ||
|
|
e026491b9f | ||
|
|
009699b375 | ||
|
|
3677588a3d | ||
|
|
3d280053a7 | ||
|
|
fbde3f6a47 | ||
|
|
1c1a33fdce | ||
|
|
fea238722d | ||
|
|
178d958c08 | ||
|
|
f9633f366b | ||
|
|
7a81f3e767 | ||
|
|
bbbbbf7927 | ||
|
|
5735f84008 | ||
|
|
fe0cf42e5d | ||
|
|
04100584ce | ||
|
|
9d3a422916 | ||
|
|
65d8284fb8 | ||
|
|
eea107db66 | ||
|
|
67812957db | ||
|
|
69d77e59cc | ||
|
|
efcebfd82c | ||
|
|
32345f93bf | ||
|
|
193e4bd5bf | ||
|
|
53edf3d57e | ||
|
|
895e297771 | ||
|
|
8f3959e6c6 | ||
|
|
5ff6b601c7 | ||
|
|
4895ac9c23 | ||
|
|
f121aa47f7 | ||
|
|
00a8d59284 | ||
|
|
a30489e05b | ||
|
|
dfbeb3ed20 | ||
|
|
2eed1c974e | ||
|
|
63a79a90ac | ||
|
|
a61e74d97b | ||
|
|
54438a4aa1 | ||
|
|
7682ad63e4 | ||
|
|
06c53fdc9c | ||
|
|
665f4e684c | ||
|
|
52b894fe0e | ||
|
|
82c0cbbad4 | ||
|
|
ce004af379 | ||
|
|
15bd9e9fdc | ||
|
|
37aabeaf72 | ||
|
|
473737ac9b | ||
|
|
1e29ec708f | ||
|
|
515d517a99 | ||
|
|
a3aedcb624 | ||
|
|
98b7c6c966 | ||
|
|
b1d956af2c | ||
|
|
b7a031bb7f | ||
|
|
15cce07b6e | ||
|
|
1d5d6f5121 | ||
|
|
5f541f5c8b | ||
|
|
71bce08549 | ||
|
|
37b9badb2a | ||
|
|
4089e80fe8 | ||
|
|
2be6e727ce | ||
|
|
d3b886c3f6 | ||
|
|
97e48bfe71 | ||
|
|
a8769dee06 | ||
|
|
ffa94986d5 | ||
|
|
e4dfb61509 | ||
|
|
d42b6e3261 | ||
|
|
855b15025c | ||
|
|
3701b2c0d9 | ||
|
|
ecbec4d301 | ||
|
|
21425c7132 | ||
|
|
3e95a7ba29 | ||
|
|
c1394db285 | ||
|
|
eee6c588bd | ||
|
|
eca68f6c7a | ||
|
|
f4e28d8774 | ||
|
|
21b179e01c | ||
|
|
83cacf6f51 | ||
|
|
13c37f01b1 | ||
|
|
511831ced3 | ||
|
|
518e1afa58 | ||
|
|
43d03ac081 | ||
|
|
f7f62c5fe0 | ||
|
|
2bbddbca6b | ||
|
|
f0f8f27f4c | ||
|
|
262af263f2 | ||
|
|
38b7775b1b | ||
|
|
56c0bca62f | ||
|
|
4b1b09fd5b | ||
|
|
1d6425bbf4 | ||
|
|
5ec6552d25 | ||
|
|
79e4a0790a | ||
|
|
1d3cac54ab | ||
|
|
2f26334775 | ||
|
|
9270d528e3 | ||
|
|
91db3a7e34 | ||
|
|
d017561e54 | ||
|
|
8e8a85bae3 | ||
|
|
bea89e9111 | ||
|
|
499ce0190a | ||
|
|
91bde91238 | ||
|
|
3e31ba102d | ||
|
|
263c5eefd3 | ||
|
|
b230b851e4 | ||
|
|
ff32477ffe | ||
|
|
c6c60decdb | ||
|
|
7505adeca8 | ||
|
|
754f1fba88 | ||
|
|
8be46b870a | ||
|
|
81cb1d6c0b | ||
|
|
319416f1b7 | ||
|
|
d679c6251b | ||
|
|
a14baafda7 | ||
|
|
cfdc7d3106 | ||
|
|
33d51b8ce5 | ||
|
|
b13dac2093 | ||
|
|
a605c95e5a | ||
|
|
9a5553a636 | ||
|
|
ef02403da6 | ||
|
|
adfab363c1 | ||
|
|
123d4cf595 | ||
|
|
19feb8ff49 | ||
|
|
9223bf9d2d | ||
|
|
11b5f87841 | ||
|
|
cea59fb453 | ||
|
|
3a179bf480 | ||
|
|
b9c53024f1 | ||
|
|
62b37ad698 | ||
|
|
de56cd5d3b | ||
|
|
8d9d78185a | ||
|
|
b10a6512fe | ||
|
|
a94da8802f | ||
|
|
4e6f82d00c | ||
|
|
5e2ad99ec0 | ||
|
|
8ab50ea362 | ||
|
|
25e9958a69 | ||
|
|
410ea8b96b | ||
|
|
e656664cad | ||
|
|
0e6cee0961 | ||
|
|
42506b8c1d | ||
|
|
e35365d162 | ||
|
|
bf1c0f796d | ||
|
|
547532b28c | ||
|
|
a91e23abf6 | ||
|
|
2b324f636b | ||
|
|
103b8372e4 | ||
|
|
f7f1724bf1 | ||
|
|
5d70e11f17 | ||
|
|
fb7ae90d46 | ||
|
|
957792a7a0 | ||
|
|
2e8ce6a2f0 | ||
|
|
9927a56b78 | ||
|
|
db3da52f83 | ||
|
|
19a7c6978a | ||
|
|
b5e9ba03a1 | ||
|
|
cb5f8b91ad | ||
|
|
f627f60f1a | ||
|
|
e9fce5b8b8 | ||
|
|
a7820a79db | ||
|
|
b6a52dbcd4 | ||
|
|
7bbd10a50c | ||
|
|
ee08b231db | ||
|
|
619e54dc0e | ||
|
|
9b69596af1 | ||
|
|
f6e169c013 | ||
|
|
fd242d50c1 | ||
|
|
d6d8ecd6c5 | ||
|
|
669fac7f50 | ||
|
|
92d670916e | ||
|
|
0155413c12 | ||
|
|
8468be6532 | ||
|
|
78c82f778a | ||
|
|
ab89a3d41a | ||
|
|
5f320af6e6 | ||
|
|
17b7ba6b72 | ||
|
|
c70ebdfe15 | ||
|
|
a3e564f160 | ||
|
|
eea37424c9 | ||
|
|
b322181853 | ||
|
|
3ad66f5e0b | ||
|
|
4035e0dd13 | ||
|
|
832b820096 | ||
|
|
d337971de0 | ||
|
|
a967dc72d7 | ||
|
|
5066fcda48 | ||
|
|
e7bdf42694 | ||
|
|
875fea88ee | ||
|
|
b2654ea9db | ||
|
|
8f8e415262 | ||
|
|
5ff624f7b2 | ||
|
|
e09243f1ec | ||
|
|
f5941c7eda | ||
|
|
3c2ebe602e | ||
|
|
2f64172ead | ||
|
|
a83206a346 | ||
|
|
46e769976f |
@@ -0,0 +1,22 @@
|
||||
**
|
||||
|
||||
!.dockerignore
|
||||
!docker/
|
||||
!docker/linux-build/
|
||||
!docker/linux-build/**
|
||||
|
||||
# Dependency manifests and local xmake package recipes are the only project
|
||||
# files needed while pre-warming the build image.
|
||||
!xmake.lua
|
||||
!apps/
|
||||
!apps/desktop/
|
||||
!apps/desktop/xmake/
|
||||
!apps/desktop/xmake/**
|
||||
!deps/thirdparty/
|
||||
!deps/thirdparty/**
|
||||
!deps/submodules/
|
||||
!deps/submodules/xmake.lua
|
||||
!deps/submodules/minirtc/
|
||||
!deps/submodules/minirtc/xmake.lua
|
||||
!deps/submodules/minirtc/thirdparty/
|
||||
!deps/submodules/minirtc/thirdparty/**
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: 问题反馈
|
||||
about: Create a report to help us improve
|
||||
about: 请在此提交问题报告,以便持续优化产品。
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: kunkundi
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
name: 需求建议
|
||||
about: 请在此提交功能需求或改进建议,以便后续迭代参考。
|
||||
title: ''
|
||||
labels: enhancement
|
||||
assignees: kunkundi
|
||||
|
||||
---
|
||||
|
||||
**功能/改进建议描述**
|
||||
清晰简洁地描述希望新增的功能或改进的内容。
|
||||
|
||||
**使用场景 / 背景**
|
||||
说明该功能或改进的使用场景,以及解决后带来的价值。
|
||||
|
||||
**预期效果**
|
||||
描述你认为最理想的功能表现或改进效果。
|
||||
|
||||
**参考示例(可选)**
|
||||
提供类似功能截图、参考链接或其他说明,帮助更好理解需求。
|
||||
|
||||
**优先级(可选)**
|
||||
- [ ] 高
|
||||
- [ ] 中
|
||||
- [ ] 低
|
||||
|
||||
**补充信息(可选)**
|
||||
其他相关信息或特殊要求。
|
||||
@@ -0,0 +1,29 @@
|
||||
name: Ensure minimum Xmake version
|
||||
description: Keep a compatible Xmake installation, or install the minimum required version.
|
||||
|
||||
inputs:
|
||||
minimum-version:
|
||||
description: Minimum supported Xmake version (major.minor.patch).
|
||||
required: true
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Check installed Xmake version
|
||||
id: check
|
||||
shell: bash
|
||||
env:
|
||||
XMAKE_MIN_VERSION: ${{ inputs.minimum-version }}
|
||||
run: bash "$GITHUB_ACTION_PATH/check-version.sh"
|
||||
|
||||
- name: Install or upgrade Xmake
|
||||
if: steps.check.outputs.needs-upgrade == 'true'
|
||||
uses: xmake-io/github-action-setup-xmake@v1
|
||||
with:
|
||||
xmake-version: ${{ inputs.minimum-version }}
|
||||
|
||||
- name: Verify Xmake meets the minimum version
|
||||
shell: bash
|
||||
env:
|
||||
XMAKE_MIN_VERSION: ${{ inputs.minimum-version }}
|
||||
run: bash "$GITHUB_ACTION_PATH/check-version.sh" --verify
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
export LC_ALL=C
|
||||
|
||||
verify=false
|
||||
if [[ $# -eq 1 && "$1" == "--verify" ]]; then
|
||||
verify=true
|
||||
elif [[ $# -ne 0 ]]; then
|
||||
echo "Usage: $0 [--verify]" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
minimum_version="${XMAKE_MIN_VERSION:-}"
|
||||
if [[ ! "$minimum_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "XMAKE_MIN_VERSION must be a numeric major.minor.patch version, for example 3.1.1." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
version_at_least() {
|
||||
local -a installed_parts required_parts
|
||||
local index installed_component required_component
|
||||
IFS=. read -r -a installed_parts <<< "$1"
|
||||
IFS=. read -r -a required_parts <<< "$2"
|
||||
|
||||
for index in 0 1 2; do
|
||||
installed_component="${installed_parts[$index]}"
|
||||
required_component="${required_parts[$index]}"
|
||||
# Strip leading zeroes and compare lengths first, avoiding both octal
|
||||
# interpretation and integer overflow in Bash's arithmetic expansion.
|
||||
while [[ ${#installed_component} -gt 1 && "$installed_component" == 0* ]]; do
|
||||
installed_component="${installed_component#0}"
|
||||
done
|
||||
while [[ ${#required_component} -gt 1 && "$required_component" == 0* ]]; do
|
||||
required_component="${required_component#0}"
|
||||
done
|
||||
if [[ ${#installed_component} -gt ${#required_component} ]]; then
|
||||
return 0
|
||||
elif [[ ${#installed_component} -lt ${#required_component} ]]; then
|
||||
return 1
|
||||
elif [[ "$installed_component" > "$required_component" ]]; then
|
||||
return 0
|
||||
elif [[ "$installed_component" < "$required_component" ]]; then
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
detected_version=""
|
||||
needs_upgrade=true
|
||||
reason="xmake was not found on PATH"
|
||||
if command -v xmake >/dev/null 2>&1; then
|
||||
if version_output="$(xmake --root --version 2>&1)"; then
|
||||
# Xmake can color individual words and version components. Strip ANSI
|
||||
# CSI sequences before matching, using only Bash 3.2 builtins.
|
||||
ansi_pattern=$'\033''\[[0-?]*[ -/]*[@-~]'
|
||||
while [[ "$version_output" =~ $ansi_pattern ]]; do
|
||||
version_output="${version_output//"${BASH_REMATCH[0]}"/}"
|
||||
done
|
||||
version_pattern='(^|[[:space:]])xmake[[:space:]]+v([0-9]+\.[0-9]+\.[0-9]+)([+][[:alnum:].-]+)?([,[:space:]]|$)'
|
||||
while IFS= read -r line; do
|
||||
if [[ "$line" =~ $version_pattern ]]; then
|
||||
detected_version="${BASH_REMATCH[2]}"
|
||||
break
|
||||
fi
|
||||
done <<< "$version_output"
|
||||
|
||||
if [[ -z "$detected_version" ]]; then
|
||||
reason="xmake --root --version did not report a recognizable Xmake version"
|
||||
elif version_at_least "$detected_version" "$minimum_version"; then
|
||||
needs_upgrade=false
|
||||
else
|
||||
reason="installed Xmake $detected_version is below $minimum_version"
|
||||
fi
|
||||
else
|
||||
reason="xmake --root --version failed with exit code $?"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -n "${GITHUB_OUTPUT:-}" ]]; then
|
||||
{
|
||||
printf 'needs-upgrade=%s\n' "$needs_upgrade"
|
||||
printf 'detected-version=%s\n' "$detected_version"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
printf 'needs-upgrade=%s\n' "$needs_upgrade"
|
||||
printf 'detected-version=%s\n' "$detected_version"
|
||||
fi
|
||||
|
||||
if [[ "$needs_upgrade" == true ]]; then
|
||||
if [[ "$verify" == true ]]; then
|
||||
echo "Xmake verification failed: $reason. Ensure Xmake $minimum_version or newer is installed and on PATH." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Xmake upgrade required: $reason. Install Xmake $minimum_version or newer."
|
||||
else
|
||||
echo "Keeping installed Xmake $detected_version; it meets the minimum version $minimum_version."
|
||||
fi
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Regression coverage for independent and combined release metadata."""
|
||||
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import update_version_manifest as manifest
|
||||
|
||||
|
||||
class ManifestTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temporary = tempfile.TemporaryDirectory(prefix="crossdesk-manifest-")
|
||||
self.addCleanup(temporary.cleanup)
|
||||
self.root = Path(temporary.name)
|
||||
self.artifacts = self.root / "release"
|
||||
self.artifacts.mkdir()
|
||||
self.current = {
|
||||
"version": "1.6.0-20260930", "latest_version": "1.6.0-20260930",
|
||||
"releaseDate": "2026-09-30", "releaseNotes": "Desktop notes", "patch": 0,
|
||||
"downloads": {"windows-x64": {"url": "https://downloads.crossdesk.cn/existing.exe"}},
|
||||
"custom": {"keep": True},
|
||||
}
|
||||
|
||||
def files(self, *names):
|
||||
for path in self.artifacts.iterdir():
|
||||
path.unlink()
|
||||
for name in names:
|
||||
(self.artifacts / name).write_bytes(b"release fixture")
|
||||
return manifest.artifact_downloads(self.artifacts)
|
||||
|
||||
def merge(self, tag, downloads, current=None):
|
||||
return manifest.merge_release(current or self.current, tag, tag, "Release notes", downloads)
|
||||
|
||||
def test_mobile_preserves_desktop_metadata_and_downloads(self):
|
||||
downloads = self.files("crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk")
|
||||
original = copy.deepcopy(self.current)
|
||||
result = self.merge("android-v1.6.0-20261002", downloads)
|
||||
for key, value in original.items():
|
||||
if key != "downloads":
|
||||
self.assertEqual(result[key], value)
|
||||
self.assertEqual(result["downloads"]["windows-x64"], original["downloads"]["windows-x64"])
|
||||
self.assertEqual(result["downloads"]["android-arm64"]["url"],
|
||||
"https://downloads.crossdesk.cn/crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk")
|
||||
self.assertEqual(result["downloads"]["android-arm64"]["version"], "1.6.0-20261002")
|
||||
self.assertEqual(result["downloads"]["android-arm64"]["releaseDate"], "2026-10-02")
|
||||
self.assertNotIn("platforms", result)
|
||||
self.assertEqual(self.current, original)
|
||||
|
||||
def test_sequential_platform_releases_retain_each_other(self):
|
||||
for order in (("ios", "android"), ("android", "ios")):
|
||||
result = copy.deepcopy(self.current)
|
||||
for platform in order:
|
||||
version, extension = ("0.0.2", "zip") if platform == "ios" else ("1.6.0", "apk")
|
||||
downloads = self.files(f"crossdesk-{platform}-arm64-unsigned-v{version}-20261002.{extension}")
|
||||
result = self.merge(f"{platform}-v{version}-20261002", downloads, result)
|
||||
self.assertNotIn("platforms", result)
|
||||
self.assertEqual(result["version"], self.current["version"])
|
||||
self.assertTrue({"windows-x64", "ios-arm64", "android-arm64"} <= result["downloads"].keys())
|
||||
self.assertEqual(result["downloads"]["ios-arm64"]["version"], "0.0.2-20261002")
|
||||
self.assertEqual(result["downloads"]["android-arm64"]["version"], "1.6.0-20261002")
|
||||
|
||||
def test_combined_release_records_independent_mobile_versions(self):
|
||||
downloads = self.files("crossdesk-win-x64-v1.6.1-20261002.exe",
|
||||
"crossdesk-win-x64-portable-v1.6.1-20261002.zip",
|
||||
"crossdesk-ios-arm64-unsigned-v0.0.2-20261002.zip",
|
||||
"crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk")
|
||||
result = self.merge("v1.6.1-20261002", downloads)
|
||||
self.assertEqual(result["version"], "1.6.1-20261002")
|
||||
self.assertEqual(result["downloads"]["ios-arm64"]["version"], "0.0.2-20261002")
|
||||
self.assertEqual(result["downloads"]["android-arm64"]["version"], "1.6.0-20261002")
|
||||
self.assertNotIn("platforms", result)
|
||||
|
||||
def test_obsolete_platforms_are_removed_on_any_release(self):
|
||||
for tag, artifact in (
|
||||
("android-v1.6.0-20261002", "crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk"),
|
||||
("v1.6.1-20261002", "crossdesk-win-x64-v1.6.1-20261002.exe"),
|
||||
):
|
||||
downloads = self.files(artifact)
|
||||
expected = self.merge(tag, downloads)
|
||||
for obsolete in ({"ios": {"version": "0.0.1"}}, []):
|
||||
current = {**copy.deepcopy(self.current), "platforms": obsolete}
|
||||
original = copy.deepcopy(current)
|
||||
self.assertEqual(self.merge(tag, downloads, current), expected)
|
||||
self.assertEqual(current, original)
|
||||
|
||||
def test_mobile_tag_must_match_artifact_and_platform(self):
|
||||
downloads = self.files("crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk")
|
||||
for tag in ("android-v1.7.0-20261002", "ios-v1.6.0-20261002"):
|
||||
with self.assertRaises(ValueError):
|
||||
self.merge(tag, downloads)
|
||||
|
||||
def test_signed_android_release_updates_existing_unsigned_download(self):
|
||||
unsigned = self.files("crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk")
|
||||
current = self.merge("android-v1.6.0-20261002", unsigned)
|
||||
signed = self.files("crossdesk-android-arm64-v1.6.0-20261002.apk")
|
||||
result = self.merge("android-v1.6.0-20261002", signed, current)
|
||||
self.assertEqual(result["downloads"]["android-arm64"]["url"],
|
||||
"https://downloads.crossdesk.cn/crossdesk-android-arm64-v1.6.0-20261002.apk")
|
||||
self.assertEqual(result["version"], self.current["version"])
|
||||
self.assertEqual(result["downloads"]["windows-x64"], self.current["downloads"]["windows-x64"])
|
||||
self.assertNotIn("platforms", result)
|
||||
|
||||
def test_signed_android_is_preferred_when_release_retains_unsigned_apk(self):
|
||||
downloads = self.files("crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk",
|
||||
"crossdesk-android-arm64-v1.6.0-20261002.apk")
|
||||
self.assertEqual(downloads["android-arm64"]["filename"],
|
||||
"crossdesk-android-arm64-v1.6.0-20261002.apk")
|
||||
with self.assertRaises(ValueError):
|
||||
self.files("crossdesk-android-arm64-unsigned-v1.6.0-20261001.apk",
|
||||
"crossdesk-android-arm64-v1.6.0-20261002.apk")
|
||||
|
||||
def test_invalid_current_manifest_is_rejected(self):
|
||||
downloads = self.files("crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk")
|
||||
for current in ([], {}, {"downloads": []}):
|
||||
with self.assertRaises(ValueError):
|
||||
manifest.merge_release(current, "android-v1.6.0-20261002", "Android", "", downloads)
|
||||
|
||||
def test_missing_duplicate_and_invalid_artifacts_are_rejected(self):
|
||||
for names in ((), ("crossdesk-android-arm64-unsigned-v1.6.0-20260230.apk",),
|
||||
("crossdesk-android-arm64-unsigned-v1.6.0-20261001.apk",
|
||||
"crossdesk-android-arm64-unsigned-v1.6.0-20261002.apk")):
|
||||
with self.assertRaises(ValueError):
|
||||
self.files(*names)
|
||||
|
||||
def test_hotfix_version_and_date_formats(self):
|
||||
for value in ("v1.6.0-2-20261002", "v1.6.0-20261002-2"):
|
||||
info = manifest.version_info(value)
|
||||
self.assertEqual(info["patch"], 2)
|
||||
self.assertEqual(info["releaseDate"], "2026-10-02")
|
||||
|
||||
def test_cli_preserves_literal_notes_and_release_metadata(self):
|
||||
self.files("crossdesk-win-x64-v1.6.1-20261002.exe")
|
||||
notes = '中文 release notes\n"quoted" $(not-a-command) $HOME `literal`'
|
||||
release = {"tagName": "v1.6.1-20261002", "name": "Desktop release", "body": notes}
|
||||
(self.root / "current.json").write_text(json.dumps(self.current))
|
||||
(self.root / "release.json").write_text(json.dumps(release))
|
||||
output = self.root / "version.json"
|
||||
subprocess.run([sys.executable, str(Path(manifest.__file__)),
|
||||
"--current", str(self.root / "current.json"), "--output", str(output),
|
||||
"--artifacts", str(self.artifacts), "--release-json", str(self.root / "release.json")],
|
||||
check=True, capture_output=True, text=True)
|
||||
result = json.loads(output.read_text())
|
||||
self.assertEqual(result["releaseNotes"], notes)
|
||||
self.assertEqual(result["releaseName"], "Desktop release")
|
||||
self.assertEqual(result["tagName"], "v1.6.1-20261002")
|
||||
self.assertNotIn("platforms", result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Exercise CI Xmake selection with isolated executable and Actions-output mocks."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "actions/ensure-xmake/check-version.sh"
|
||||
BASH = shutil.which("bash")
|
||||
|
||||
|
||||
@unittest.skipUnless(BASH, "Bash is required to exercise the CI version check")
|
||||
class XmakeVersionCheckTest(unittest.TestCase):
|
||||
def check(self, version_output=None, *, minimum="3.1.1", status=0, arguments=()):
|
||||
with tempfile.TemporaryDirectory(prefix="crossdesk-xmake-check-") as directory:
|
||||
root = Path(directory)
|
||||
output_file = root / "github-output"
|
||||
output_file.write_text("existing-output=preserved\n", encoding="utf-8")
|
||||
arguments_file = root / "arguments"
|
||||
if version_output is not None:
|
||||
executable = root / "xmake"
|
||||
executable.write_text(
|
||||
"#!/bin/sh\n"
|
||||
'printf "%s\\n" "$@" > "$XMAKE_TEST_ARGUMENTS"\n'
|
||||
'printf "%s" "$XMAKE_TEST_OUTPUT"\n'
|
||||
'exit "$XMAKE_TEST_STATUS"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
executable.chmod(0o755)
|
||||
environment = {
|
||||
**os.environ,
|
||||
# The checker only needs shell builtins. Isolating PATH also
|
||||
# guarantees that missing-tool tests cannot find a real xmake.
|
||||
"PATH": str(root),
|
||||
"GITHUB_OUTPUT": str(output_file),
|
||||
"XMAKE_TEST_ARGUMENTS": str(arguments_file),
|
||||
"XMAKE_TEST_OUTPUT": version_output or "",
|
||||
"XMAKE_TEST_STATUS": str(status),
|
||||
}
|
||||
if minimum is None:
|
||||
environment.pop("XMAKE_MIN_VERSION", None)
|
||||
else:
|
||||
environment["XMAKE_MIN_VERSION"] = minimum
|
||||
result = subprocess.run(
|
||||
[BASH, str(SCRIPT), *arguments],
|
||||
env=environment,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
outputs = dict(
|
||||
line.split("=", 1)
|
||||
for line in output_file.read_text(encoding="utf-8").splitlines()
|
||||
)
|
||||
invocation = (
|
||||
arguments_file.read_text(encoding="utf-8").splitlines()
|
||||
if arguments_file.exists() else None
|
||||
)
|
||||
self.assertEqual(outputs["existing-output"], "preserved")
|
||||
return result, outputs, invocation
|
||||
|
||||
def test_keeps_minimum_and_newer_versions(self):
|
||||
for version in ("3.1.1", "3.1.2", "3.1.10", "3.2.0", "3.10.0", "4.0.0"):
|
||||
with self.subTest(version=version):
|
||||
result, outputs, invocation = self.check(f"xmake v{version}\n")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(outputs["needs-upgrade"], "false")
|
||||
self.assertEqual(outputs["detected-version"], version)
|
||||
self.assertEqual(invocation, ["--root", "--version"])
|
||||
self.assertIn("Keeping installed Xmake", result.stdout)
|
||||
|
||||
def test_older_versions_require_upgrade(self):
|
||||
for version in ("3.1.0", "3.0.99", "2.99.99"):
|
||||
with self.subTest(version=version):
|
||||
result, outputs, _ = self.check(f"xmake v{version}\n")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(outputs["needs-upgrade"], "true")
|
||||
self.assertIn("Install Xmake 3.1.1 or newer", result.stdout)
|
||||
|
||||
def test_components_are_compared_numerically(self):
|
||||
for installed, minimum, expected in (
|
||||
("3.1.10", "3.1.9", "false"),
|
||||
("3.1.9", "3.1.10", "true"),
|
||||
("3.2.0", "3.1.99", "false"),
|
||||
("3.1.99", "3.2.0", "true"),
|
||||
("3.01.009", "3.1.9", "false"),
|
||||
("3.1.999999999999999999999", "3.1.9", "false"),
|
||||
):
|
||||
with self.subTest(installed=installed, minimum=minimum):
|
||||
result, outputs, _ = self.check(f"xmake v{installed}", minimum=minimum)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(outputs["needs-upgrade"], expected)
|
||||
|
||||
def test_parses_ansi_colors_build_suffix_and_windows_line_endings(self):
|
||||
result, outputs, _ = self.check(
|
||||
"Xmake banner\r\n"
|
||||
"\x1b[1;38;5;10mxmake\x1b[0m v\x1b[1m3.1.10\x1b[0m+HEAD.abcdef, A build utility\r\n"
|
||||
)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(outputs["needs-upgrade"], "false")
|
||||
self.assertEqual(outputs["detected-version"], "3.1.10")
|
||||
|
||||
def test_missing_broken_and_unrecognizable_tools_require_upgrade(self):
|
||||
cases = (
|
||||
(None, 0),
|
||||
("xmake v9.9.9\n", 17),
|
||||
("", 0),
|
||||
("xmake version unknown\n", 0),
|
||||
("xmake v3.1\n", 0),
|
||||
("xmake v3.1.1invalid\n", 0),
|
||||
("xmake v3.1.1-rc.1\n", 0),
|
||||
("otherxmake v9.9.9\n", 0),
|
||||
)
|
||||
for output, status in cases:
|
||||
with self.subTest(output=output, status=status):
|
||||
result, outputs, _ = self.check(output, status=status)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(outputs["needs-upgrade"], "true")
|
||||
self.assertEqual(outputs["detected-version"], "")
|
||||
self.assertIn("Install Xmake 3.1.1 or newer", result.stdout)
|
||||
|
||||
def test_verification_fails_when_install_did_not_provide_required_version(self):
|
||||
for output, status in ((None, 0), ("xmake v3.1.0", 0), ("unknown", 0), ("xmake v3.1.1", 5)):
|
||||
with self.subTest(output=output, status=status):
|
||||
result, outputs, _ = self.check(output, status=status, arguments=("--verify",))
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertEqual(outputs["needs-upgrade"], "true")
|
||||
self.assertIn("Xmake verification failed", result.stderr)
|
||||
self.assertIn("3.1.1 or newer", result.stderr)
|
||||
|
||||
def test_verification_accepts_newer_version(self):
|
||||
result, outputs, _ = self.check("xmake v4.0.0", arguments=("--verify",))
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(outputs["needs-upgrade"], "false")
|
||||
|
||||
def test_invalid_minimum_fails_before_running_xmake(self):
|
||||
for minimum in (None, "", "3.1", "v3.1.1", "3.1.1+HEAD", "3.1.1\n", "3.a.1"):
|
||||
with self.subTest(minimum=minimum):
|
||||
result, outputs, invocation = self.check("xmake v3.1.1", minimum=minimum)
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertNotIn("needs-upgrade", outputs)
|
||||
self.assertIsNone(invocation)
|
||||
self.assertIn("XMAKE_MIN_VERSION", result.stderr)
|
||||
|
||||
def test_unknown_arguments_fail_before_running_xmake(self):
|
||||
result, outputs, invocation = self.check("xmake v3.1.1", arguments=("--install",))
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertNotIn("needs-upgrade", outputs)
|
||||
self.assertIsNone(invocation)
|
||||
self.assertIn("Usage:", result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Merge a release's server downloads into the shared version.json."""
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
|
||||
DOWNLOAD_BASE = "https://downloads.crossdesk.cn/"
|
||||
ARTIFACTS = {
|
||||
"windows-x64": ("win-x64", "exe"),
|
||||
"windows-x64-portable": ("win-x64-portable", "zip"),
|
||||
"macos-x64": ("macos-x64", "pkg"),
|
||||
"macos-arm64": ("macos-arm64", "pkg"),
|
||||
"linux-amd64": ("linux-amd64", "deb"),
|
||||
"linux-arm64": ("linux-arm64", "deb"),
|
||||
"linux-amd64-virtual-desktop-xfce": ("virtual-desktop-xfce-linux-amd64", "deb"),
|
||||
"linux-arm64-virtual-desktop-xfce": ("virtual-desktop-xfce-linux-arm64", "deb"),
|
||||
"ios-arm64": ("ios-arm64-unsigned", "zip"),
|
||||
"android-arm64": ("android-arm64(?:-unsigned)?", "apk"),
|
||||
}
|
||||
|
||||
|
||||
def version_info(version, fallback_date=None):
|
||||
version = version.removeprefix("v")
|
||||
base = r"[0-9]+(?:\.[0-9]+){1,3}"
|
||||
for pattern in (
|
||||
rf"(?P<base>{base})-(?P<patch>[0-9]+)-(?P<date>[0-9]{{8}})",
|
||||
rf"(?P<base>{base})-(?P<date>[0-9]{{8}})(?:-(?P<patch>[0-9]+))?",
|
||||
rf"(?P<base>{base})(?:-(?P<patch>[0-9]+))?",
|
||||
):
|
||||
match = re.fullmatch(pattern, version)
|
||||
if match:
|
||||
fields = match.groupdict()
|
||||
date = fields.get("date")
|
||||
release_date = (datetime.datetime.strptime(date, "%Y%m%d").date().isoformat()
|
||||
if date else fallback_date)
|
||||
if not release_date:
|
||||
raise ValueError(f"Release date is missing for {version}")
|
||||
datetime.date.fromisoformat(release_date)
|
||||
return {"latest_version": version, "version": version,
|
||||
"releaseDate": release_date, "patch": int(fields.get("patch") or 0)}
|
||||
raise ValueError(f"Invalid release version: {version}")
|
||||
|
||||
|
||||
def artifact_downloads(directory):
|
||||
downloads = {}
|
||||
for path in sorted(Path(directory).iterdir()):
|
||||
if not path.is_file():
|
||||
continue
|
||||
for key, (prefix, extension) in ARTIFACTS.items():
|
||||
match = re.fullmatch(rf"crossdesk-{prefix}-v([0-9][0-9.\-]*)\.{extension}", path.name)
|
||||
if not match:
|
||||
continue
|
||||
metadata = version_info(match[1])
|
||||
if key in downloads:
|
||||
previous = downloads[key]
|
||||
if (key != "android-arm64" or previous["version"] != metadata["version"]
|
||||
or ("-unsigned-" in previous["filename"]) == ("-unsigned-" in path.name)):
|
||||
raise ValueError(f"Multiple release artifacts for {key}")
|
||||
# Older releases may retain their unsigned APK after adding a signed one.
|
||||
if "-unsigned-" in path.name:
|
||||
continue
|
||||
downloads[key] = {"url": DOWNLOAD_BASE + path.name, "filename": path.name,
|
||||
"version": metadata["version"], "releaseDate": metadata["releaseDate"]}
|
||||
break
|
||||
if not downloads:
|
||||
raise ValueError("No supported release artifacts found")
|
||||
return downloads
|
||||
|
||||
|
||||
def merge_release(current, tag, name, notes, downloads, published_date=None):
|
||||
if not isinstance(current, dict) or not isinstance(current.get("downloads"), dict):
|
||||
raise ValueError("Current version.json must contain a downloads object")
|
||||
mobile = re.fullmatch(r"(ios|android)-(v.+)", tag)
|
||||
if mobile:
|
||||
platform, version = mobile.groups()
|
||||
expected_key = f"{platform}-arm64"
|
||||
if set(downloads) != {expected_key}:
|
||||
raise ValueError(f"{tag} must contain only the {expected_key} release artifact")
|
||||
metadata = version_info(version, published_date)
|
||||
if downloads[expected_key]["version"] != metadata["version"]:
|
||||
raise ValueError("Mobile source tag does not match the artifact version")
|
||||
else:
|
||||
if not tag.startswith("v"):
|
||||
raise ValueError(f"Expected a version tag, got {tag!r}")
|
||||
metadata = version_info(tag, published_date)
|
||||
|
||||
result = dict(current)
|
||||
result.pop("platforms", None)
|
||||
result["downloads"] = {**current["downloads"], **downloads}
|
||||
if not mobile:
|
||||
result.update({**metadata, "releaseName": name, "releaseNotes": notes, "tagName": tag})
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--current", required=True, type=Path)
|
||||
parser.add_argument("--output", required=True, type=Path)
|
||||
parser.add_argument("--artifacts", required=True, type=Path)
|
||||
parser.add_argument("--tag")
|
||||
parser.add_argument("--name")
|
||||
parser.add_argument("--notes", type=Path)
|
||||
parser.add_argument("--release-json", type=Path)
|
||||
args = parser.parse_args()
|
||||
if args.release_json:
|
||||
release = json.loads(args.release_json.read_text())
|
||||
tag = release["tagName"]
|
||||
name = release.get("name") or tag
|
||||
notes = release.get("body") or ""
|
||||
published_date = (release.get("publishedAt") or "").split("T")[0] or None
|
||||
else:
|
||||
if not args.tag or not args.name or not args.notes:
|
||||
parser.error("Supply --release-json or --tag, --name and --notes")
|
||||
tag, name, notes = args.tag, args.name, args.notes.read_text()
|
||||
published_date = None
|
||||
current = json.loads(args.current.read_text())
|
||||
downloads = artifact_downloads(args.artifacts)
|
||||
result = merge_release(current, tag, name, notes, downloads, published_date)
|
||||
args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
||||
print(f"Updated {tag}: {', '.join(downloads)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,224 @@
|
||||
name: Build Android
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
inputs:
|
||||
source_tag:
|
||||
description: "Existing source tag for a standalone Android release."
|
||||
required: false
|
||||
type: string
|
||||
default: ""
|
||||
outputs:
|
||||
version:
|
||||
description: "Independent Android version and build date."
|
||||
value: ${{ jobs.build.outputs.version }}
|
||||
pull_request:
|
||||
paths:
|
||||
- ".github/workflows/build-android.yml"
|
||||
- ".github/workflows/build.yml"
|
||||
- ".github/workflows/release-mobile.yml"
|
||||
- ".github/workflows/sign-android.yml"
|
||||
- ".gitmodules"
|
||||
- "LICENSE"
|
||||
- "PRIVACY.md"
|
||||
- "apps/android/**"
|
||||
- "apps/ios/CrossDeskMobile/Resources/ThirdPartyLicenses.json"
|
||||
- "apps/ios/licenses/**"
|
||||
- "apps/ios/scripts/generate_third_party_licenses.py"
|
||||
- "deps/submodules/minirtc"
|
||||
- "libs/wire/**"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build on Android (arm64)
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 120
|
||||
outputs:
|
||||
version: ${{ steps.package.outputs.version }}
|
||||
env:
|
||||
# Exercise the minimum supported version; local builds may use newer Xmake.
|
||||
XMAKE_MIN_VERSION: "3.1.1"
|
||||
CROSSDESK_SOURCE_TAG: ${{ inputs.source_tag || '' }}
|
||||
CROSSDESK_RELEASE_BUILD: ${{ inputs.source_tag && 'YES' || 'NO' }}
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ inputs.source_tag || github.ref }}
|
||||
submodules: recursive
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Java
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "17"
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.13"
|
||||
cache: pip
|
||||
# Python build dependencies are declared in this workflow. This file
|
||||
# also exists when source_tag checks out an older Android release.
|
||||
cache-dependency-path: .github/workflows/build-android.yml
|
||||
|
||||
- name: Install native build tools
|
||||
run: |
|
||||
crossdesk_missing_packages=()
|
||||
for crossdesk_package in build-essential cmake ninja-build pkg-config autoconf automake libtool nasm; do
|
||||
if [[ "$(dpkg-query -W -f='${Status}' "${crossdesk_package}" 2>/dev/null || true)" != "install ok installed" ]]; then
|
||||
crossdesk_missing_packages+=("${crossdesk_package}")
|
||||
fi
|
||||
done
|
||||
if (( ${#crossdesk_missing_packages[@]} )); then
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends "${crossdesk_missing_packages[@]}"
|
||||
fi
|
||||
python3 -m pip install setuptools wheel
|
||||
|
||||
# Use an isolated SDK directory so the cache contains only this toolchain,
|
||||
# rather than every SDK/NDK version preinstalled on the runner.
|
||||
- name: Select Android SDK directory
|
||||
run: |
|
||||
echo "ANDROID_HOME=${RUNNER_TEMP}/crossdesk-android-sdk" >> "${GITHUB_ENV}"
|
||||
echo "ANDROID_SDK_ROOT=${RUNNER_TEMP}/crossdesk-android-sdk" >> "${GITHUB_ENV}"
|
||||
|
||||
- name: Restore Android SDK
|
||||
id: android-sdk-cache
|
||||
uses: actions/cache/restore@v5
|
||||
with:
|
||||
path: ${{ env.ANDROID_HOME }}
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-ubuntu24.04-android-sdk-v1-cli12266719-api36-build36.0.0-ndk28.2.13676358
|
||||
|
||||
- name: Set up Android SDK
|
||||
if: steps.android-sdk-cache.outputs.cache-hit != 'true'
|
||||
uses: android-actions/setup-android@v3
|
||||
with:
|
||||
cmdline-tools-version: "12266719"
|
||||
log-accepted-android-sdk-licenses: false
|
||||
packages: "platform-tools platforms;android-36 build-tools;36.0.0 ndk;28.2.13676358"
|
||||
|
||||
# Save immediately after installation, even if a later APK build fails.
|
||||
- name: Save Android SDK
|
||||
if: steps.android-sdk-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v5
|
||||
with:
|
||||
path: ${{ env.ANDROID_HOME }}
|
||||
key: ${{ steps.android-sdk-cache.outputs.cache-primary-key }}
|
||||
|
||||
- name: Add Android tools to PATH
|
||||
run: |
|
||||
echo "${ANDROID_HOME}/cmdline-tools/16.0/bin" >> "${GITHUB_PATH}"
|
||||
echo "${ANDROID_HOME}/platform-tools" >> "${GITHUB_PATH}"
|
||||
|
||||
- name: Install xmake
|
||||
uses: xmake-io/github-action-setup-xmake@v1
|
||||
with:
|
||||
xmake-version: ${{ env.XMAKE_MIN_VERSION }}
|
||||
actions-cache-folder: .xmake-toolchain-cache
|
||||
actions-cache-key: ${{ runner.os }}-${{ runner.arch }}-ubuntu24.04-android-xmake${{ env.XMAKE_MIN_VERSION }}
|
||||
|
||||
- name: Cache Xmake package repository
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: apps/android/.native/global/.xmake/repositories/xmake-repo
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-android-xmake-repo-v1-${{ hashFiles('apps/android/scripts/build_native.py') }}
|
||||
|
||||
# Cache installed packages only. build_native.py checks Xmake >= 3.1.1 and pins
|
||||
# its own package repository; never reuse another platform's build/config.
|
||||
- name: Cache native dependencies
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: apps/android/.native/packages
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-android-arm64-native-v1-${{ hashFiles('apps/android/scripts/build_native.py', 'apps/android/native/xmake.lua', 'deps/submodules/minirtc/xmake.lua', 'deps/submodules/minirtc/thirdparty/**') }}
|
||||
|
||||
- name: Set up Gradle
|
||||
uses: gradle/actions/setup-gradle@v6
|
||||
with:
|
||||
cache-provider: basic
|
||||
cache-read-only: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
- name: Verify shared license catalog
|
||||
run: python3 -B apps/ios/scripts/generate_third_party_licenses.py
|
||||
|
||||
- name: Build APKs
|
||||
working-directory: apps/android
|
||||
run: |
|
||||
./gradlew --no-daemon --stacktrace \
|
||||
:app:assembleDebug :app:assembleRelease
|
||||
|
||||
- name: Verify APKs
|
||||
working-directory: apps/android
|
||||
run: |
|
||||
python3 -B test/verify_apk.py app/build/outputs/apk/debug/app-debug.apk
|
||||
python3 -B test/verify_apk.py app/build/outputs/apk/release/app-release-unsigned.apk
|
||||
"${ANDROID_HOME}/build-tools/36.0.0/apksigner" verify app/build/outputs/apk/debug/app-debug.apk
|
||||
|
||||
- name: Package APKs with the independent Android version
|
||||
id: package
|
||||
shell: python
|
||||
run: |
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
apk_dir = Path("apps/android/app/build/outputs/apk")
|
||||
metadata = json.loads((apk_dir / "release/output-metadata.json").read_text())
|
||||
version = metadata["elements"][0]["versionName"]
|
||||
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version):
|
||||
raise ValueError(f"Invalid Android version: {version!r}")
|
||||
build_date = datetime.datetime.now(ZoneInfo("Asia/Shanghai")).strftime("%Y%m%d")
|
||||
# Match the dated release tags used by the desktop and iOS jobs.
|
||||
tag = os.environ.get("CROSSDESK_SOURCE_TAG")
|
||||
if not tag and os.environ["GITHUB_REF_TYPE"] == "tag":
|
||||
tag = os.environ["GITHUB_REF_NAME"]
|
||||
if tag:
|
||||
tag = tag.removeprefix("android-")
|
||||
match = re.fullmatch(r"v?[0-9]+(?:\.[0-9]+){1,3}-(?:[0-9]+-)?([0-9]{8})(?:-[0-9]+)?", tag)
|
||||
if match:
|
||||
build_date = match[1]
|
||||
datetime.datetime.strptime(build_date, "%Y%m%d")
|
||||
version = f"v{version}-{build_date}"
|
||||
source_tag = os.environ.get("CROSSDESK_SOURCE_TAG", "")
|
||||
if source_tag.startswith("android-v") and source_tag.removeprefix("android-") != version:
|
||||
raise ValueError(f"Android source tag does not match the app version: {source_tag} vs {version}")
|
||||
output = Path(os.environ["RUNNER_TEMP"]) / "crossdesk-android"
|
||||
for variant, source in (
|
||||
("unsigned", "release/app-release-unsigned.apk"),
|
||||
("debug", "debug/app-debug.apk"),
|
||||
):
|
||||
destination = output / variant
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(apk_dir / source, destination / f"crossdesk-android-arm64-{variant}-{version}.apk")
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a") as stream:
|
||||
stream.write(f"version={version}\n")
|
||||
with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as stream:
|
||||
stream.write(f"Android {version}: arm64, API 26+, 16 KB aligned.\n\n"
|
||||
"Debug APK uses an ephemeral CI debug key; it is for testing and may require uninstalling an existing build. "
|
||||
"The Release APK is unsigned and needs your own signing before installation.\n\n"
|
||||
"Debug and Release APKs built and packaged; APK checks passed.\n")
|
||||
|
||||
- name: Upload unsigned Release APK
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: crossdesk-android-arm64-unsigned-${{ steps.package.outputs.version }}
|
||||
path: ${{ runner.temp }}/crossdesk-android/unsigned/*.apk
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload Debug APK
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: crossdesk-android-arm64-debug-${{ steps.package.outputs.version }}
|
||||
path: ${{ runner.temp }}/crossdesk-android/debug/*.apk
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
@@ -0,0 +1,272 @@
|
||||
name: Build iOS
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
patch:
|
||||
description: "Optional patch number, matching the main build workflow."
|
||||
required: false
|
||||
type: string
|
||||
default: "0"
|
||||
workflow_call:
|
||||
inputs:
|
||||
source_tag:
|
||||
description: "Existing source tag for a standalone iOS release."
|
||||
required: false
|
||||
type: string
|
||||
default: ""
|
||||
patch:
|
||||
description: "Optional patch number from the main build workflow."
|
||||
required: false
|
||||
type: string
|
||||
default: "0"
|
||||
outputs:
|
||||
version:
|
||||
description: "iOS artifact version; combined releases match the desktop tag."
|
||||
value: ${{ jobs.build.outputs.version }}
|
||||
pull_request:
|
||||
paths:
|
||||
- ".github/workflows/build-ios.yml"
|
||||
- ".github/workflows/build.yml"
|
||||
- ".github/workflows/release-mobile.yml"
|
||||
- ".gitmodules"
|
||||
- "LICENSE"
|
||||
- "apps/ios/**"
|
||||
- "deps/submodules/minirtc"
|
||||
- "libs/wire/**"
|
||||
- "xmake.lua"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build on iOS (arm64)
|
||||
runs-on: macos-26
|
||||
timeout-minutes: 120
|
||||
outputs:
|
||||
version: ${{ steps.ios_version.outputs.version }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
CROSSDESK_SOURCE_TAG: ${{ inputs.source_tag || '' }}
|
||||
IOS_DEPLOYMENT_TARGET: "16.0"
|
||||
EXPECTED_IOS_SDK: "26.5"
|
||||
# Exercise the minimum supported version; local builds may use newer Xmake.
|
||||
XMAKE_MIN_VERSION: "3.1.1"
|
||||
XMAKE_REPO_REVISION: "121109352da272cd1a3d4ed52f2dcda34f839955"
|
||||
|
||||
steps:
|
||||
- name: Extract version number
|
||||
shell: bash
|
||||
env:
|
||||
PATCH_NUMBER: ${{ inputs.patch || '0' }}
|
||||
run: |
|
||||
VERSION_REF="${CROSSDESK_SOURCE_TAG:-${GITHUB_REF##*/}}"
|
||||
VERSION_REF="${VERSION_REF#ios-}"
|
||||
VERSION_BASE="${VERSION_REF#v}"
|
||||
BUILD_DATE=$(TZ=Asia/Shanghai date +%Y%m%d)
|
||||
|
||||
if [[ ! "${PATCH_NUMBER}" =~ ^[0-9]+$ ]]; then
|
||||
PATCH_NUMBER=0
|
||||
fi
|
||||
|
||||
if [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)-([0-9]{8})$ ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
PATCH_NUMBER="${BASH_REMATCH[3]}"
|
||||
BUILD_DATE="${BASH_REMATCH[4]}"
|
||||
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})-([0-9]+)$ ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
BUILD_DATE="${BASH_REMATCH[3]}"
|
||||
PATCH_NUMBER="${BASH_REMATCH[4]}"
|
||||
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})$ ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
BUILD_DATE="${BASH_REMATCH[3]}"
|
||||
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)$ && "${PATCH_NUMBER}" == "0" ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
PATCH_NUMBER="${BASH_REMATCH[3]}"
|
||||
fi
|
||||
|
||||
if [[ "${PATCH_NUMBER}" != "0" ]]; then
|
||||
VERSION_NUM="v${VERSION_BASE}-${PATCH_NUMBER}-${BUILD_DATE}"
|
||||
else
|
||||
VERSION_NUM="v${VERSION_BASE}-${BUILD_DATE}"
|
||||
fi
|
||||
|
||||
echo "VERSION_NUM=${VERSION_NUM}" >> "${GITHUB_ENV}"
|
||||
echo "VERSION_NUM=${VERSION_NUM}"
|
||||
|
||||
- name: Select Xcode 26.6
|
||||
shell: bash
|
||||
run: |
|
||||
sudo xcode-select -s /Applications/Xcode_26.6.app/Contents/Developer
|
||||
xcodebuild -version
|
||||
SDK_VERSION="$(xcrun --sdk iphoneos --show-sdk-version)"
|
||||
if [[ "${SDK_VERSION}" != "${EXPECTED_IOS_SDK}" ]]; then
|
||||
echo "Unexpected iOS SDK: expected ${EXPECTED_IOS_SDK}, got ${SDK_VERSION}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ inputs.source_tag || github.ref }}
|
||||
|
||||
- name: Select corresponding source tag
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ -n "${CROSSDESK_SOURCE_TAG}" ]]; then
|
||||
echo "CROSSDESK_RELEASE_BUILD=YES" >> "${GITHUB_ENV}"
|
||||
elif [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then
|
||||
echo "CROSSDESK_SOURCE_TAG=${GITHUB_REF_NAME}" >> "${GITHUB_ENV}"
|
||||
echo "CROSSDESK_RELEASE_BUILD=YES" >> "${GITHUB_ENV}"
|
||||
fi
|
||||
|
||||
- name: Resolve iOS version
|
||||
id: ios_version
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${CROSSDESK_SOURCE_TAG}" == v* ]]; then
|
||||
# Combined releases share the desktop version, including the date
|
||||
# and optional hotfix suffix in the artifact filename.
|
||||
IOS_VERSION_BASE="${VERSION_NUM#v}"
|
||||
IOS_VERSION_BASE="${IOS_VERSION_BASE%%-*}"
|
||||
else
|
||||
IOS_VERSION_BASE="$(xcodebuild \
|
||||
-project apps/ios/CrossDeskMobile.xcodeproj \
|
||||
-scheme CrossDeskMobile \
|
||||
-configuration Release \
|
||||
-destination 'generic/platform=iOS' \
|
||||
-showBuildSettings CODE_SIGNING_ALLOWED=NO | \
|
||||
awk '$1 == "MARKETING_VERSION" && $2 == "=" { print $3 }')"
|
||||
VERSION_NUM="v${IOS_VERSION_BASE}-${VERSION_NUM##*-}"
|
||||
fi
|
||||
if [[ ! "${IOS_VERSION_BASE}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "Invalid iOS marketing version: ${IOS_VERSION_BASE}" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "${CROSSDESK_SOURCE_TAG}" == ios-v* && "${CROSSDESK_SOURCE_TAG#ios-}" != "${VERSION_NUM}" ]]; then
|
||||
echo "iOS source tag does not match the app version: ${CROSSDESK_SOURCE_TAG} vs ${VERSION_NUM}" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "IOS_VERSION_BASE=${IOS_VERSION_BASE}" >> "${GITHUB_ENV}"
|
||||
echo "VERSION_NUM=${VERSION_NUM}" >> "${GITHUB_ENV}"
|
||||
echo "version=${VERSION_NUM}" >> "${GITHUB_OUTPUT}"
|
||||
|
||||
- name: Initialize submodules
|
||||
run: git submodule update --init --recursive
|
||||
|
||||
- name: Cache xmake dependencies
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: apps/ios/.xmake/packages
|
||||
key: "${{ runner.os }}-xmake${{ env.XMAKE_MIN_VERSION }}-deps-ios-arm64-source-v1-xcode26.6-xrepo1211093-min16-${{ github.run_id }}"
|
||||
restore-keys: |
|
||||
${{ runner.os }}-xmake${{ env.XMAKE_MIN_VERSION }}-deps-ios-arm64-source-v1-xcode26.6-xrepo1211093-min16-
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.13"
|
||||
|
||||
- name: Verify iOS license catalog
|
||||
run: python3 -B apps/ios/scripts/generate_third_party_licenses.py
|
||||
|
||||
- name: Install xmake
|
||||
uses: xmake-io/github-action-setup-xmake@v1
|
||||
with:
|
||||
xmake-version: "${{ env.XMAKE_MIN_VERSION }}"
|
||||
|
||||
- name: Verify minimum xmake version
|
||||
shell: bash
|
||||
run: |
|
||||
xmake --version | tee "${RUNNER_TEMP}/xmake-version.txt"
|
||||
python3 -B apps/ios/scripts/generate_third_party_licenses.py \
|
||||
--xmake-version "${RUNNER_TEMP}/xmake-version.txt"
|
||||
|
||||
- name: Pin xmake package repository
|
||||
shell: bash
|
||||
run: |
|
||||
xmake repo -u
|
||||
XMAKE_REPO_DIR="${HOME}/.xmake/repositories/xmake-repo"
|
||||
git -C "${XMAKE_REPO_DIR}" fetch --depth=1 origin "${XMAKE_REPO_REVISION}"
|
||||
git -C "${XMAKE_REPO_DIR}" checkout --detach "${XMAKE_REPO_REVISION}"
|
||||
test "$(git -C "${XMAKE_REPO_DIR}" rev-parse HEAD)" = "${XMAKE_REPO_REVISION}"
|
||||
|
||||
- name: Build CrossDesk Mobile
|
||||
shell: bash
|
||||
run: |
|
||||
DERIVED_DATA="${RUNNER_TEMP}/CrossDeskMobileDerivedData"
|
||||
echo "DERIVED_DATA=${DERIVED_DATA}" >> "${GITHUB_ENV}"
|
||||
xcodebuild \
|
||||
-project apps/ios/CrossDeskMobile.xcodeproj \
|
||||
-scheme CrossDeskMobile \
|
||||
-configuration Release \
|
||||
-destination 'generic/platform=iOS' \
|
||||
-derivedDataPath "${DERIVED_DATA}" \
|
||||
CODE_SIGNING_ALLOWED=NO \
|
||||
CODE_SIGNING_REQUIRED=NO \
|
||||
COMPILER_INDEX_STORE_ENABLE=NO \
|
||||
MARKETING_VERSION="${IOS_VERSION_BASE}" \
|
||||
IPHONEOS_DEPLOYMENT_TARGET="${IOS_DEPLOYMENT_TARGET}" \
|
||||
build
|
||||
|
||||
- name: Verify CrossDesk Mobile
|
||||
shell: bash
|
||||
run: |
|
||||
APP_PATH="${DERIVED_DATA}/Build/Products/Release-iphoneos/CrossDeskMobile.app"
|
||||
EXECUTABLE_PATH="${APP_PATH}/CrossDeskMobile"
|
||||
INFO_PLIST="${APP_PATH}/Info.plist"
|
||||
|
||||
if [[ ! -x "${EXECUTABLE_PATH}" ]]; then
|
||||
echo "CrossDeskMobile executable is missing from ${APP_PATH}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
xcrun lipo "${EXECUTABLE_PATH}" -verify_arch arm64
|
||||
APP_VERSION=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "${INFO_PLIST}")
|
||||
if [[ "${APP_VERSION}" != "${IOS_VERSION_BASE}" ]]; then
|
||||
echo "Unexpected iOS app version: expected ${IOS_VERSION_BASE}, got ${APP_VERSION}" >&2
|
||||
exit 1
|
||||
fi
|
||||
MINIMUM_OS=$(/usr/libexec/PlistBuddy -c 'Print :MinimumOSVersion' "${INFO_PLIST}")
|
||||
if [[ "${MINIMUM_OS}" != "${IOS_DEPLOYMENT_TARGET}" ]]; then
|
||||
echo "Unexpected minimum iOS version: expected ${IOS_DEPLOYMENT_TARGET}, got ${MINIMUM_OS}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
VERIFY_FLAGS=()
|
||||
if [[ "${CROSSDESK_RELEASE_BUILD:-NO}" == "YES" ]]; then
|
||||
VERIFY_FLAGS+=(--require-release)
|
||||
fi
|
||||
python3 apps/ios/scripts/verify_app_bundle.py "${APP_PATH}" "${VERIFY_FLAGS[@]}"
|
||||
xcrun lipo -info "${EXECUTABLE_PATH}"
|
||||
echo "Minimum iOS version: ${MINIMUM_OS}"
|
||||
|
||||
- name: Package CrossDesk Mobile
|
||||
shell: bash
|
||||
run: |
|
||||
APP_PATH="${DERIVED_DATA}/Build/Products/Release-iphoneos/CrossDeskMobile.app"
|
||||
PACKAGE_DIR="${RUNNER_TEMP}/crossdesk-ios-arm64-unsigned-${VERSION_NUM}"
|
||||
PACKAGE_FILE="${GITHUB_WORKSPACE}/crossdesk-ios-arm64-unsigned-${VERSION_NUM}.zip"
|
||||
|
||||
mkdir -p "${PACKAGE_DIR}"
|
||||
cp -R "${APP_PATH}" "${PACKAGE_DIR}/"
|
||||
cp apps/ios/licenses/sources.json "${PACKAGE_DIR}/ThirdPartySources.json"
|
||||
cp apps/ios/licenses/OPEN_SOURCE_NOTICE.txt "${PACKAGE_DIR}/OPEN_SOURCE_NOTICE.txt"
|
||||
cp "${APP_PATH}/SourceMetadata.json" "${PACKAGE_DIR}/SourceMetadata.json"
|
||||
|
||||
DSYM_PATH="${DERIVED_DATA}/Build/Products/Release-iphoneos/CrossDeskMobile.app.dSYM"
|
||||
if [[ -d "${DSYM_PATH}" ]]; then
|
||||
cp -R "${DSYM_PATH}" "${PACKAGE_DIR}/"
|
||||
fi
|
||||
|
||||
ditto -c -k --sequesterRsrc --keepParent "${PACKAGE_DIR}" "${PACKAGE_FILE}"
|
||||
echo "PACKAGE_FILE=${PACKAGE_FILE}" >> "${GITHUB_ENV}"
|
||||
|
||||
- name: Upload build artifact
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: crossdesk-ios-arm64-unsigned-${{ env.VERSION_NUM }}
|
||||
path: ${{ env.PACKAGE_FILE }}
|
||||
if-no-files-found: error
|
||||
@@ -0,0 +1,157 @@
|
||||
name: Build Linux Build Image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- ci/linux-build-image
|
||||
paths:
|
||||
- .dockerignore
|
||||
- .gitmodules
|
||||
- .github/workflows/build-linux-image.yml
|
||||
- docker/linux-build/**
|
||||
- xmake.lua
|
||||
- xmake/**
|
||||
- deps/thirdparty/**
|
||||
- deps/submodules/xmake.lua
|
||||
- deps/submodules/minirtc
|
||||
- deps/submodules/minirtc/xmake.lua
|
||||
- deps/submodules/minirtc/thirdparty/**
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: linux-build-image-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
IMAGE_NAME: crossdesk/ubuntu20.04
|
||||
STACK_TAG: buildenv-cuda12.6.3-gcc10-cmake3.31.6-pipewire0.3.48-xmake3.1.1-rust1.92.0
|
||||
CMAKE_VERSION: 3.31.6
|
||||
XMAKE_VERSION: 3.1.1
|
||||
RUST_VERSION: 1.92.0
|
||||
RUSTUP_VERSION: 1.28.2
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build candidate (${{ matrix.arch }})
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 180
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: amd64
|
||||
platform: linux/amd64
|
||||
runner: ubuntu-24.04
|
||||
base_image: nvidia/cuda:12.6.3-devel-ubuntu20.04
|
||||
- arch: arm64
|
||||
platform: linux/arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
base_image: ubuntu:20.04
|
||||
steps:
|
||||
- name: Set candidate tag
|
||||
id: image
|
||||
run: |
|
||||
CANDIDATE_TAG="${IMAGE_NAME}:${STACK_TAG}-${GITHUB_SHA}-${{ matrix.arch }}"
|
||||
echo "CANDIDATE_TAG=${CANDIDATE_TAG}" >> "${GITHUB_ENV}"
|
||||
echo "candidate=${CANDIDATE_TAG}" >> "${GITHUB_OUTPUT}"
|
||||
|
||||
- name: Checkout source
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Build and push candidate
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: docker/linux-build/Dockerfile
|
||||
platforms: ${{ matrix.platform }}
|
||||
push: true
|
||||
pull: true
|
||||
tags: ${{ steps.image.outputs.candidate }}
|
||||
cache-from: type=registry,ref=${{ env.IMAGE_NAME }}:${{ env.STACK_TAG }}
|
||||
cache-to: type=inline
|
||||
provenance: false
|
||||
sbom: false
|
||||
build-args: |
|
||||
BASE_IMAGE=${{ matrix.base_image }}
|
||||
CMAKE_VERSION=${{ env.CMAKE_VERSION }}
|
||||
XMAKE_VERSION=${{ env.XMAKE_VERSION }}
|
||||
RUST_VERSION=${{ env.RUST_VERSION }}
|
||||
RUSTUP_VERSION=${{ env.RUSTUP_VERSION }}
|
||||
|
||||
verify:
|
||||
name: Verify candidate (${{ matrix.arch }})
|
||||
needs: build
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: amd64
|
||||
runner: ubuntu-24.04
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
steps:
|
||||
- name: Set candidate tag
|
||||
run: |
|
||||
CANDIDATE_TAG="${IMAGE_NAME}:${STACK_TAG}-${GITHUB_SHA}-${{ matrix.arch }}"
|
||||
echo "CANDIDATE_TAG=${CANDIDATE_TAG}" >> "${GITHUB_ENV}"
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Verify tools, architecture, and Ubuntu baseline
|
||||
run: |
|
||||
docker pull "${CANDIDATE_TAG}"
|
||||
docker run --rm \
|
||||
--env EXPECTED_ARCH="${{ matrix.arch }}" \
|
||||
"${CANDIDATE_TAG}" \
|
||||
verify-crossdesk-build-image
|
||||
|
||||
publish:
|
||||
name: Publish multi-arch image
|
||||
needs: verify
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Promote verified candidates
|
||||
run: |
|
||||
AMD64_IMAGE="${IMAGE_NAME}:${STACK_TAG}-${GITHUB_SHA}-amd64"
|
||||
ARM64_IMAGE="${IMAGE_NAME}:${STACK_TAG}-${GITHUB_SHA}-arm64"
|
||||
|
||||
docker buildx imagetools create \
|
||||
--tag "${IMAGE_NAME}:${STACK_TAG}" \
|
||||
--tag "${IMAGE_NAME}:sha-${GITHUB_SHA}" \
|
||||
--tag "${IMAGE_NAME}:latest" \
|
||||
"${AMD64_IMAGE}" \
|
||||
"${ARM64_IMAGE}"
|
||||
|
||||
- name: Inspect published manifest
|
||||
run: |
|
||||
docker buildx imagetools inspect "${IMAGE_NAME}:${STACK_TAG}"
|
||||
+501
-182
@@ -4,207 +4,326 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- "**"
|
||||
- "!ci/linux-build-image"
|
||||
tags:
|
||||
- "*"
|
||||
- "!ios-v*"
|
||||
- "!android-v*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
patch:
|
||||
description: "Hotfix patch number, for example 1 or 2. Use 0 for a normal build."
|
||||
required: false
|
||||
default: "0"
|
||||
sign_windows_test:
|
||||
description: "Submit the Windows installer to SignPath using test-signing."
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
contents: write
|
||||
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
XMAKE_MIN_VERSION: "3.1.1"
|
||||
|
||||
jobs:
|
||||
# Linux amd64
|
||||
build-linux-amd64:
|
||||
name: Build on Ubuntu 22.04 amd64
|
||||
runs-on: ubuntu-22.04
|
||||
container:
|
||||
image: crossdesk/ubuntu20.04:latest
|
||||
options: --user root
|
||||
steps:
|
||||
- name: Extract version number
|
||||
id: version
|
||||
run: |
|
||||
VERSION="${GITHUB_REF##*/}"
|
||||
VERSION_NUM="${VERSION#v}"
|
||||
echo "VERSION_NUM=${VERSION_NUM}" >> $GITHUB_ENV
|
||||
|
||||
- name: Set legal Debian version
|
||||
shell: bash
|
||||
id: set_deb_version
|
||||
run: |
|
||||
SHORT_SHA=$(echo "${GITHUB_SHA}" | cut -c1-7)
|
||||
BUILD_DATE=$(TZ=Asia/Shanghai date +%Y%m%d)
|
||||
if [[ ! "${VERSION_NUM}" =~ ^[0-9] ]]; then
|
||||
LEGAL_VERSION="v0.0.0-${VERSION_NUM}-${BUILD_DATE}-${SHORT_SHA}"
|
||||
else
|
||||
LEGAL_VERSION="v${VERSION_NUM}-${BUILD_DATE}-${SHORT_SHA}"
|
||||
fi
|
||||
echo "LEGAL_VERSION=${LEGAL_VERSION}" >> $GITHUB_ENV
|
||||
echo "BUILD_DATE=${BUILD_DATE}" >> $GITHUB_ENV
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Build CrossDesk
|
||||
env:
|
||||
CUDA_PATH: /usr/local/cuda
|
||||
XMAKE_GLOBALDIR: /data
|
||||
run: |
|
||||
ls -la $XMAKE_GLOBALDIR
|
||||
xmake f --CROSSDESK_VERSION=${LEGAL_VERSION} --USE_CUDA=true --root -y
|
||||
xmake b -vy --root crossdesk
|
||||
|
||||
- name: Decode and save certificate
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir -p certs
|
||||
echo "${{ secrets.CROSSDESK_CERT_BASE64 }}" | base64 --decode > certs/crossdesk.cn_root.crt
|
||||
|
||||
- name: Package
|
||||
run: |
|
||||
chmod +x ./scripts/linux/pkg_amd64.sh
|
||||
./scripts/linux/pkg_amd64.sh ${LEGAL_VERSION}
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: crossdesk-linux-amd64-${{ env.LEGAL_VERSION }}
|
||||
path: ${{ github.workspace }}/crossdesk-linux-amd64-${{ env.LEGAL_VERSION }}.deb
|
||||
|
||||
# Linux arm64
|
||||
build-linux-arm64:
|
||||
name: Build on Ubuntu 22.04 arm64
|
||||
runs-on: ubuntu-22.04-arm
|
||||
build-linux:
|
||||
name: Build Linux (${{ matrix.arch }})
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- arch: amd64
|
||||
runner: ubuntu-24.04
|
||||
# Keep using the published dependency image; upgrade Xmake if needed.
|
||||
image: crossdesk/ubuntu20.04:buildenv-cuda12.6.3-gcc10-cmake3.31.6-pipewire0.3.48-xmake3.0.9-rust1.92.0
|
||||
package_script: ./apps/desktop/scripts/linux/pkg_amd64.sh
|
||||
|
||||
- arch: arm64
|
||||
image: crossdesk/ubuntu20.04-arm64v8:latest
|
||||
package_script: ./scripts/linux/pkg_arm64.sh
|
||||
runner: ubuntu-24.04-arm
|
||||
image: crossdesk/ubuntu20.04:buildenv-cuda12.6.3-gcc10-cmake3.31.6-pipewire0.3.48-xmake3.0.9-rust1.92.0
|
||||
package_script: ./apps/desktop/scripts/linux/pkg_arm64.sh
|
||||
|
||||
container:
|
||||
image: ${{ matrix.image }}
|
||||
options: --user root
|
||||
|
||||
steps:
|
||||
- name: Extract version number
|
||||
id: version
|
||||
shell: bash
|
||||
run: |
|
||||
VERSION="${GITHUB_REF##*/}"
|
||||
VERSION_NUM="${VERSION#v}"
|
||||
echo "VERSION_NUM=${VERSION_NUM}" >> $GITHUB_ENV
|
||||
VERSION_REF="${GITHUB_REF##*/}"
|
||||
VERSION_BASE="${VERSION_REF#v}"
|
||||
PATCH_NUMBER="${{ github.event.inputs.patch }}"
|
||||
BUILD_DATE_OVERRIDE=""
|
||||
|
||||
if [[ ! "${PATCH_NUMBER}" =~ ^[0-9]+$ ]]; then
|
||||
PATCH_NUMBER=0
|
||||
fi
|
||||
|
||||
if [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)-([0-9]{8})$ ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
PATCH_NUMBER="${BASH_REMATCH[3]}"
|
||||
BUILD_DATE_OVERRIDE="${BASH_REMATCH[4]}"
|
||||
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})-([0-9]+)$ ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
BUILD_DATE_OVERRIDE="${BASH_REMATCH[3]}"
|
||||
PATCH_NUMBER="${BASH_REMATCH[4]}"
|
||||
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})$ ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
BUILD_DATE_OVERRIDE="${BASH_REMATCH[3]}"
|
||||
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)$ && "${PATCH_NUMBER}" == "0" ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
PATCH_NUMBER="${BASH_REMATCH[3]}"
|
||||
fi
|
||||
|
||||
echo "VERSION_BASE=${VERSION_BASE}" >> $GITHUB_ENV
|
||||
echo "PATCH_NUMBER=${PATCH_NUMBER}" >> $GITHUB_ENV
|
||||
echo "BUILD_DATE_OVERRIDE=${BUILD_DATE_OVERRIDE}" >> $GITHUB_ENV
|
||||
|
||||
- name: Set legal Debian version
|
||||
shell: bash
|
||||
id: set_deb_version
|
||||
run: |
|
||||
SHORT_SHA=$(echo "${GITHUB_SHA}" | cut -c1-7)
|
||||
BUILD_DATE=$(TZ=Asia/Shanghai date +%Y%m%d)
|
||||
if [[ ! "${VERSION_NUM}" =~ ^[0-9] ]]; then
|
||||
LEGAL_VERSION="v0.0.0-${VERSION_NUM}-${BUILD_DATE}-${SHORT_SHA}"
|
||||
else
|
||||
LEGAL_VERSION="v${VERSION_NUM}-${BUILD_DATE}-${SHORT_SHA}"
|
||||
BUILD_DATE="${BUILD_DATE_OVERRIDE}"
|
||||
if [[ -z "${BUILD_DATE}" ]]; then
|
||||
BUILD_DATE=$(TZ=Asia/Shanghai date +%Y%m%d)
|
||||
fi
|
||||
|
||||
if [[ ! "${VERSION_BASE}" =~ ^[0-9] ]]; then
|
||||
VERSION_BASE="0.0.0-${VERSION_BASE}"
|
||||
fi
|
||||
|
||||
if [[ "${PATCH_NUMBER}" != "0" ]]; then
|
||||
LEGAL_VERSION="v${VERSION_BASE}-${PATCH_NUMBER}-${BUILD_DATE}"
|
||||
else
|
||||
LEGAL_VERSION="v${VERSION_BASE}-${BUILD_DATE}"
|
||||
fi
|
||||
|
||||
echo "LEGAL_VERSION=${LEGAL_VERSION}" >> $GITHUB_ENV
|
||||
echo "BUILD_DATE=${BUILD_DATE}" >> $GITHUB_ENV
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Ensure minimum Xmake version
|
||||
uses: ./.github/actions/ensure-xmake
|
||||
with:
|
||||
minimum-version: ${{ env.XMAKE_MIN_VERSION }}
|
||||
|
||||
- name: Verify Linux build image
|
||||
shell: bash
|
||||
env:
|
||||
EXPECTED_ARCH: ${{ matrix.arch }}
|
||||
run: bash docker/linux-build/verify-build-image.sh
|
||||
|
||||
- name: Ensure Wayland build dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
if pkg-config --exists dbus-1 libdrm && \
|
||||
test -f /opt/crossdesk-pipewire-sdk/include/pipewire-0.3/pipewire/pipewire.h && \
|
||||
test -f /opt/crossdesk-pipewire-sdk/include/spa-0.2/spa/param/video/format-utils.h; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends \
|
||||
libdbus-1-dev \
|
||||
libdrm-dev
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
install-crossdesk-pipewire-sdk
|
||||
pkg-config --exists dbus-1 libdrm
|
||||
test -f /opt/crossdesk-pipewire-sdk/include/pipewire-0.3/pipewire/pipewire.h
|
||||
test -f /opt/crossdesk-pipewire-sdk/include/spa-0.2/spa/param/video/format-utils.h
|
||||
|
||||
- name: Build CrossDesk
|
||||
env:
|
||||
CUDA_PATH: /usr/local/cuda
|
||||
XMAKE_GLOBALDIR: /data
|
||||
run: |
|
||||
xmake f --CROSSDESK_VERSION=${LEGAL_VERSION} --USE_CUDA=true --root -y
|
||||
xmake f --CROSSDESK_VERSION=${LEGAL_VERSION} --USE_CUDA=true --USE_WAYLAND=true \
|
||||
--cc=gcc-10 --cxx=g++-10 --root -y
|
||||
xmake b -vy --root crossdesk
|
||||
|
||||
- name: Decode and save certificate
|
||||
shell: bash
|
||||
- name: Install Linux headless runtime dependencies
|
||||
run: |
|
||||
mkdir -p certs
|
||||
echo "${{ secrets.CROSSDESK_CERT_BASE64 }}" | base64 --decode > certs/crossdesk.cn_root.crt
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends xvfb xfce4 dbus
|
||||
|
||||
- name: Package
|
||||
run: |
|
||||
chmod +x ${{ matrix.package_script }}
|
||||
${{ matrix.package_script }} ${LEGAL_VERSION}
|
||||
|
||||
- name: Verify Ubuntu 20.04 package dependency resolution
|
||||
run: |
|
||||
apt-get update
|
||||
for PACKAGE in crossdesk crossdesk-virtual-desktop-xfce; do
|
||||
apt-get install --simulate "${GITHUB_WORKSPACE}/${PACKAGE}-linux-${{ matrix.arch }}-${LEGAL_VERSION}.deb"
|
||||
done
|
||||
|
||||
- name: Verify packaged Ubuntu 20.04 glibc baseline
|
||||
run: |
|
||||
for PACKAGE in crossdesk crossdesk-virtual-desktop-xfce; do
|
||||
PACKAGE_FILE="${GITHUB_WORKSPACE}/${PACKAGE}-linux-${{ matrix.arch }}-${LEGAL_VERSION}.deb"
|
||||
VERIFY_DIR="${RUNNER_TEMP}/${PACKAGE}-glibc-${{ matrix.arch }}"
|
||||
install -d "${VERIFY_DIR}"
|
||||
dpkg-deb --extract "${PACKAGE_FILE}" "${VERIFY_DIR}"
|
||||
verify-crossdesk-glibc-baseline "${VERIFY_DIR}" 2.31
|
||||
done
|
||||
|
||||
- name: Stage Linux release artifacts
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir -p linux-artifacts
|
||||
for PACKAGE in crossdesk crossdesk-virtual-desktop-xfce; do
|
||||
FILE="${PACKAGE}-linux-${{ matrix.arch }}-${LEGAL_VERSION}.deb"
|
||||
if [[ ! -s "${FILE}" ]]; then
|
||||
echo "::error::Missing or empty Linux package: ${FILE}"
|
||||
exit 1
|
||||
fi
|
||||
cp "${FILE}" linux-artifacts/
|
||||
done
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: crossdesk-linux-${{ matrix.arch }}-${{ env.LEGAL_VERSION }}
|
||||
path: ${{ github.workspace }}/crossdesk-linux-${{ matrix.arch }}-${{ env.LEGAL_VERSION }}.deb
|
||||
# A single relative directory avoids container translation of multiline
|
||||
# absolute paths and keeps both package filenames at the artifact root.
|
||||
path: linux-artifacts/
|
||||
if-no-files-found: error
|
||||
|
||||
# macOS
|
||||
build-macos:
|
||||
name: Build on macOS
|
||||
runs-on: ${{ matrix.runner }}
|
||||
env:
|
||||
MACOSX_DEPLOYMENT_TARGET: "14.0"
|
||||
EXPECTED_MACOS_SDK: "26.5"
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- arch: x64
|
||||
runner: macos-15-intel
|
||||
cache-key: intel
|
||||
binary_arch: x86_64
|
||||
runner: macos-26-intel
|
||||
cache-key: intel-macos26-xcode26.6-min14
|
||||
out-dir: ./build/macosx/x86_64/release/crossdesk
|
||||
package_script: ./scripts/macosx/pkg_x64.sh
|
||||
package_script: ./apps/desktop/scripts/macos/pkg_x64.sh
|
||||
- arch: arm64
|
||||
runner: macos-14
|
||||
cache-key: arm
|
||||
binary_arch: arm64
|
||||
runner: macos-26
|
||||
cache-key: arm-macos26-xcode26.6-min14
|
||||
out-dir: ./build/macosx/arm64/release/crossdesk
|
||||
package_script: ./scripts/macosx/pkg_arm64.sh
|
||||
package_script: ./apps/desktop/scripts/macos/pkg_arm64.sh
|
||||
|
||||
steps:
|
||||
- name: Extract version number
|
||||
id: version
|
||||
shell: bash
|
||||
run: |
|
||||
VERSION="${GITHUB_REF##*/}"
|
||||
SHORT_SHA=$(echo "${GITHUB_SHA}" | cut -c1-7)
|
||||
VERSION_REF="${GITHUB_REF##*/}"
|
||||
VERSION_BASE="${VERSION_REF#v}"
|
||||
BUILD_DATE=$(TZ=Asia/Shanghai date +%Y%m%d)
|
||||
VERSION_NUM="v${VERSION#v}-${BUILD_DATE}-${SHORT_SHA}"
|
||||
PATCH_NUMBER="${{ github.event.inputs.patch }}"
|
||||
|
||||
if [[ ! "${PATCH_NUMBER}" =~ ^[0-9]+$ ]]; then
|
||||
PATCH_NUMBER=0
|
||||
fi
|
||||
|
||||
if [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)-([0-9]{8})$ ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
PATCH_NUMBER="${BASH_REMATCH[3]}"
|
||||
BUILD_DATE="${BASH_REMATCH[4]}"
|
||||
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})-([0-9]+)$ ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
BUILD_DATE="${BASH_REMATCH[3]}"
|
||||
PATCH_NUMBER="${BASH_REMATCH[4]}"
|
||||
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})$ ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
BUILD_DATE="${BASH_REMATCH[3]}"
|
||||
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)$ && "${PATCH_NUMBER}" == "0" ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
PATCH_NUMBER="${BASH_REMATCH[3]}"
|
||||
fi
|
||||
|
||||
if [[ "${PATCH_NUMBER}" != "0" ]]; then
|
||||
VERSION_NUM="v${VERSION_BASE}-${PATCH_NUMBER}-${BUILD_DATE}"
|
||||
else
|
||||
VERSION_NUM="v${VERSION_BASE}-${BUILD_DATE}"
|
||||
fi
|
||||
|
||||
echo "VERSION_NUM=${VERSION_NUM}" >> $GITHUB_ENV
|
||||
echo "VERSION_NUM=${VERSION_NUM}"
|
||||
echo "BUILD_DATE=${BUILD_DATE}" >> $GITHUB_ENV
|
||||
echo "PATCH_NUMBER=${PATCH_NUMBER}" >> $GITHUB_ENV
|
||||
|
||||
- name: Select Xcode 26.6
|
||||
shell: bash
|
||||
run: |
|
||||
sudo xcode-select -s /Applications/Xcode_26.6.app/Contents/Developer
|
||||
xcodebuild -version
|
||||
SDK_VERSION="$(xcrun --sdk macosx --show-sdk-version)"
|
||||
if [[ "${SDK_VERSION}" != "${EXPECTED_MACOS_SDK}" ]]; then
|
||||
echo "Unexpected macOS SDK: expected ${EXPECTED_MACOS_SDK}, got ${SDK_VERSION}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Cache xmake dependencies
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.xmake/packages
|
||||
key: ${{ runner.os }}-xmake-deps-${{ matrix.cache-key }}-${{ github.sha }}
|
||||
key: "${{ runner.os }}-xmake-deps-${{ matrix.cache-key }}-${{ github.run_id }}"
|
||||
restore-keys: |
|
||||
${{ runner.os }}-xmake-deps-${{ matrix.cache-key }}-
|
||||
|
||||
- name: Install xmake
|
||||
run: brew install xmake
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Initialize submodules
|
||||
run: git submodule update --init --recursive
|
||||
|
||||
- name: Ensure minimum Xmake version
|
||||
uses: ./.github/actions/ensure-xmake
|
||||
with:
|
||||
minimum-version: ${{ env.XMAKE_MIN_VERSION }}
|
||||
|
||||
- name: Update xmake repositories
|
||||
run: xmake repo -u
|
||||
|
||||
- name: Build CrossDesk
|
||||
run: |
|
||||
xmake f --CROSSDESK_VERSION=${VERSION_NUM} --USE_CUDA=true -y
|
||||
xmake f --target_minver=${MACOSX_DEPLOYMENT_TARGET} --CROSSDESK_VERSION=${VERSION_NUM} --USE_CUDA=false -vyD
|
||||
xmake b -vy crossdesk
|
||||
|
||||
- name: Decode and save certificate
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir -p certs
|
||||
echo "${{ secrets.CROSSDESK_CERT_BASE64 }}" | base64 --decode > certs/crossdesk.cn_root.crt
|
||||
|
||||
- name: Package CrossDesk app
|
||||
run: |
|
||||
chmod +x ${{ matrix.package_script }}
|
||||
${{ matrix.package_script }} ${VERSION_NUM}
|
||||
|
||||
- name: Verify packaged app
|
||||
shell: bash
|
||||
run: |
|
||||
PACKAGE_FILE="${GITHUB_WORKSPACE}/crossdesk-macos-${{ matrix.arch }}-${VERSION_NUM}.pkg"
|
||||
VERIFY_DIR="$(mktemp -d "${RUNNER_TEMP}/crossdesk-macos-pkg.XXXXXX")"
|
||||
trap 'rm -rf "${VERIFY_DIR}"' EXIT
|
||||
|
||||
pkgutil --expand-full "${PACKAGE_FILE}" "${VERIFY_DIR}/expanded"
|
||||
APP_PATH="$(find "${VERIFY_DIR}/expanded" -type d -name 'CrossDesk.app' -print -quit)"
|
||||
if [[ -z "${APP_PATH}" ]]; then
|
||||
echo "CrossDesk.app is missing from ${PACKAGE_FILE}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
./apps/desktop/scripts/macos/verify_app.sh "${APP_PATH}" "${{ matrix.binary_arch }}" "${EXPECTED_MACOS_SDK}"
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: crossdesk-macos-${{ matrix.arch }}-${{ env.VERSION_NUM }}
|
||||
path: crossdesk-macos-${{ matrix.arch }}-${{ env.VERSION_NUM }}.pkg
|
||||
@@ -214,6 +333,22 @@ jobs:
|
||||
mkdir -p release
|
||||
cp crossdesk-macos-${{ matrix.arch }}-${{ env.VERSION_NUM }}.pkg release/
|
||||
|
||||
# iOS (also available as a standalone workflow)
|
||||
build-ios:
|
||||
name: Build iOS
|
||||
uses: ./.github/workflows/build-ios.yml
|
||||
with:
|
||||
patch: ${{ inputs.patch || '0' }}
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Android (also available as a standalone workflow)
|
||||
build-android:
|
||||
name: Build Android
|
||||
uses: ./.github/workflows/build-android.yml
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Windows
|
||||
build-windows-x64:
|
||||
name: Build on Windows x64
|
||||
@@ -228,25 +363,64 @@ jobs:
|
||||
$version = $ref -replace '^refs/(tags|heads)/', ''
|
||||
$version = $version -replace '^v', ''
|
||||
$version = $version -replace '/', '-'
|
||||
$SHORT_SHA = $env:GITHUB_SHA.Substring(0,7)
|
||||
$BUILD_DATE = ([System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), "China Standard Time")).ToString("yyyyMMdd")
|
||||
echo "VERSION_NUM=v$version-$BUILD_DATE-$SHORT_SHA" >> $env:GITHUB_ENV
|
||||
$PATCH_NUMBER = "${{ github.event.inputs.patch }}"
|
||||
|
||||
if ($PATCH_NUMBER -notmatch '^[0-9]+$') {
|
||||
$PATCH_NUMBER = "0"
|
||||
}
|
||||
|
||||
if ($version -match '^([0-9]+(\.[0-9]+){1,3})-([0-9]+)-([0-9]{8})$') {
|
||||
$version = $Matches[1]
|
||||
$PATCH_NUMBER = $Matches[3]
|
||||
$BUILD_DATE = $Matches[4]
|
||||
} elseif ($version -match '^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})-([0-9]+)$') {
|
||||
$version = $Matches[1]
|
||||
$BUILD_DATE = $Matches[3]
|
||||
$PATCH_NUMBER = $Matches[4]
|
||||
} elseif ($version -match '^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})$') {
|
||||
$version = $Matches[1]
|
||||
$BUILD_DATE = $Matches[3]
|
||||
} elseif ($version -match '^([0-9]+(\.[0-9]+){1,3})-([0-9]+)$' -and $PATCH_NUMBER -eq "0") {
|
||||
$version = $Matches[1]
|
||||
$PATCH_NUMBER = $Matches[3]
|
||||
}
|
||||
|
||||
if ($PATCH_NUMBER -ne "0") {
|
||||
$VERSION_NUM = "v$version-$PATCH_NUMBER-$BUILD_DATE"
|
||||
} else {
|
||||
$VERSION_NUM = "v$version-$BUILD_DATE"
|
||||
}
|
||||
|
||||
echo "VERSION_NUM=$VERSION_NUM" >> $env:GITHUB_ENV
|
||||
echo "BUILD_DATE=$BUILD_DATE" >> $env:GITHUB_ENV
|
||||
echo "PATCH_NUMBER=$PATCH_NUMBER" >> $env:GITHUB_ENV
|
||||
|
||||
- name: Cache xmake dependencies
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: D:\xmake_global\.xmake\packages
|
||||
key: ${{ runner.os }}-xmake-deps-intel-${{ github.sha }}
|
||||
key: "${{ runner.os }}-xmake-deps-intel-${{ github.run_id }}"
|
||||
restore-keys: |
|
||||
${{ runner.os }}-xmake-deps-intel-
|
||||
|
||||
- name: Install xmake
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Initialize submodules
|
||||
run: git submodule update --init --recursive
|
||||
|
||||
- name: Ensure minimum Xmake version
|
||||
uses: ./.github/actions/ensure-xmake
|
||||
with:
|
||||
minimum-version: ${{ env.XMAKE_MIN_VERSION }}
|
||||
|
||||
- name: Prepare CUDA dependencies
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
Invoke-Expression (Invoke-Webrequest 'https://raw.githubusercontent.com/tboox/xmake/master/scripts/get.ps1' -UseBasicParsing).Content
|
||||
echo "C:\Users\runneradmin\xmake" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
|
||||
xmake repo -u
|
||||
xmake create cuda
|
||||
Set-Location cuda
|
||||
Push-Location cuda
|
||||
xmake g --theme=plain
|
||||
$cudaPath = ""
|
||||
$packagesPath = "D:\xmake_global\.xmake\packages"
|
||||
@@ -285,80 +459,243 @@ jobs:
|
||||
Write-Host "Copying $source to $target"
|
||||
Copy-Item $source $target -Force
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Initialize submodules
|
||||
run: git submodule update --init --recursive
|
||||
|
||||
- name: Copy nsProcess plugin to NSIS folder
|
||||
run: |
|
||||
$nsisPluginDir = "C:\Program Files (x86)\NSIS\Plugins\x86-unicode"
|
||||
copy "${{ github.workspace }}\scripts\windows\nsProcess.dll" $nsisPluginDir
|
||||
copy "${{ github.workspace }}\apps\desktop\scripts\windows\nsProcess.dll" $nsisPluginDir
|
||||
|
||||
- name: Build CrossDesk
|
||||
run: |
|
||||
xmake f --CROSSDESK_VERSION=${{ env.VERSION_NUM }} --USE_CUDA=true -y
|
||||
xmake b -vy crossdesk
|
||||
|
||||
- name: Decode and save certificate
|
||||
shell: powershell
|
||||
run: |
|
||||
New-Item -ItemType Directory -Force -Path certs
|
||||
[System.IO.File]::WriteAllBytes('certs\crossdesk.cn_root.crt', [Convert]::FromBase64String('${{ secrets.CROSSDESK_CERT_BASE64 }}'))
|
||||
|
||||
- name: Package
|
||||
shell: pwsh
|
||||
run: |
|
||||
cd "${{ github.workspace }}\scripts\windows"
|
||||
makensis /DVERSION=$env:VERSION_NUM nsis_script.nsi
|
||||
& "${{ github.workspace }}\apps\desktop\scripts\windows\pkg_x64.ps1" $env:VERSION_NUM
|
||||
|
||||
- name: Upload unsigned Windows installer for test signing
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.sign_windows_test
|
||||
id: upload-unsigned-windows-installer
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
path: ${{ github.workspace }}/apps/desktop/scripts/windows/crossdesk-win-x64-${{ env.VERSION_NUM }}.exe
|
||||
archive: false
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
- name: Sign Windows installer with SignPath test certificate
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.sign_windows_test
|
||||
uses: signpath/github-action-submit-signing-request@v2
|
||||
with:
|
||||
api-token: ${{ secrets.SIGNPATH_API_TOKEN }}
|
||||
organization-id: ${{ vars.SIGNPATH_ORGANIZATION_ID }}
|
||||
project-slug: crossdesk
|
||||
signing-policy-slug: test-signing
|
||||
github-artifact-id: ${{ steps.upload-unsigned-windows-installer.outputs.artifact-id }}
|
||||
wait-for-completion: true
|
||||
output-artifact-directory: ${{ github.workspace }}\signpath\signed-installer
|
||||
skip-decompress: true
|
||||
parameters: |
|
||||
version: ${{ toJSON(env.VERSION_NUM) }}
|
||||
|
||||
- name: Verify and use test-signed Windows installer
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.sign_windows_test
|
||||
shell: pwsh
|
||||
run: |
|
||||
$installerName = "crossdesk-win-x64-${{ env.VERSION_NUM }}.exe"
|
||||
$signedInstaller = Join-Path "${{ github.workspace }}\signpath\signed-installer" $installerName
|
||||
$destination = Join-Path "${{ github.workspace }}\apps\desktop\scripts\windows" $installerName
|
||||
|
||||
if (!(Test-Path $signedInstaller)) {
|
||||
throw "SignPath did not return the signed installer: $signedInstaller"
|
||||
}
|
||||
|
||||
$signature = Get-AuthenticodeSignature $signedInstaller
|
||||
if (!$signature.SignerCertificate -or $signature.Status -eq "NotSigned") {
|
||||
throw "SignPath returned an installer without an Authenticode signature."
|
||||
}
|
||||
|
||||
Write-Host "Signer: $($signature.SignerCertificate.Subject)"
|
||||
Write-Host "Signature status: $($signature.Status)"
|
||||
Copy-Item $signedInstaller $destination -Force
|
||||
|
||||
- name: Build Portable CrossDesk
|
||||
run: |
|
||||
xmake f --CROSSDESK_VERSION=${{ env.VERSION_NUM }} --USE_CUDA=true --CROSSDESK_PORTABLE=true -y
|
||||
xmake b -vy crossdesk
|
||||
|
||||
- name: Package Portable
|
||||
shell: pwsh
|
||||
run: |
|
||||
$buildDir = "${{ github.workspace }}\build\windows\x64\release"
|
||||
$portableDir = "${{ github.workspace }}\portable"
|
||||
New-Item -ItemType Directory -Force -Path $portableDir
|
||||
|
||||
$portableFiles = @(
|
||||
@("crossdesk.exe", "CrossDesk.exe"),
|
||||
@("crossdesk_service.exe", "crossdesk_service.exe"),
|
||||
@("crossdesk_session_helper.exe", "crossdesk_session_helper.exe"),
|
||||
@("crossdesk_privacy_cursor_helper.exe", "crossdesk_privacy_cursor_helper.exe"),
|
||||
@("crossdesk_privacy_window.dll", "crossdesk_privacy_window.dll"),
|
||||
@("slint_cpp.dll", "slint_cpp.dll")
|
||||
)
|
||||
|
||||
foreach ($file in $portableFiles) {
|
||||
$source = Join-Path $buildDir $file[0]
|
||||
$destination = Join-Path $portableDir $file[1]
|
||||
if (!(Test-Path $source)) {
|
||||
throw "Missing portable package file: $source"
|
||||
}
|
||||
Copy-Item $source $destination -Force
|
||||
}
|
||||
|
||||
Copy-Item (Join-Path $buildDir "*.dll") $portableDir -Force
|
||||
|
||||
# Bundled Amyuni usbmmidd_v2 virtual display driver (headless hosts)
|
||||
$driverDir = Join-Path $buildDir "usbmmidd_v2"
|
||||
if (!(Test-Path (Join-Path $driverDir "deviceinstaller64.exe"))) {
|
||||
throw "Missing bundled usbmmidd_v2 driver package: $driverDir"
|
||||
}
|
||||
Copy-Item $driverDir (Join-Path $portableDir "usbmmidd_v2") -Recurse -Force
|
||||
|
||||
foreach ($file in $portableFiles) {
|
||||
$packagedFile = Join-Path $portableDir $file[1]
|
||||
if (!(Test-Path $packagedFile)) {
|
||||
throw "Portable package is missing: $packagedFile"
|
||||
}
|
||||
}
|
||||
|
||||
Compress-Archive -Path "$portableDir\*" -DestinationPath "${{ github.workspace }}\crossdesk-win-x64-portable-${{ env.VERSION_NUM }}.zip"
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: crossdesk-win-x64-${{ env.VERSION_NUM }}
|
||||
path: ${{ github.workspace }}/scripts/windows/crossdesk-win-x64-${{ env.VERSION_NUM }}.exe
|
||||
path: ${{ github.workspace }}/apps/desktop/scripts/windows/crossdesk-win-x64-${{ env.VERSION_NUM }}.exe
|
||||
|
||||
- name: Upload portable artifact
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: crossdesk-win-x64-portable-${{ env.VERSION_NUM }}
|
||||
path: ${{ github.workspace }}/crossdesk-win-x64-portable-${{ env.VERSION_NUM }}.zip
|
||||
|
||||
sign-android:
|
||||
name: Sign Android release
|
||||
needs: build-android
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
uses: ./.github/workflows/sign-android.yml
|
||||
with:
|
||||
version: ${{ needs.build-android.outputs.version }}
|
||||
secrets:
|
||||
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
|
||||
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
|
||||
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
|
||||
|
||||
release:
|
||||
name: Publish Release
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
needs:
|
||||
[build-linux-amd64, build-linux-arm64, build-macos, build-windows-x64]
|
||||
needs: [build-linux, build-macos, build-ios, build-android, sign-android, build-windows-x64]
|
||||
runs-on: ubuntu-latest
|
||||
concurrency:
|
||||
group: publish-release-metadata
|
||||
cancel-in-progress: false
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Download all artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: Extract version number
|
||||
id: version
|
||||
shell: bash
|
||||
run: |
|
||||
VERSION="${GITHUB_REF##*/}"
|
||||
SHORT_SHA=$(echo "${GITHUB_SHA}" | cut -c1-7)
|
||||
VERSION_REF="${GITHUB_REF##*/}"
|
||||
VERSION_BASE="${VERSION_REF#v}"
|
||||
BUILD_DATE=$(TZ=Asia/Shanghai date +%Y%m%d)
|
||||
BUILD_DATE_ISO=$(TZ=Asia/Shanghai date +%Y-%m-%d)
|
||||
VERSION_NUM="${VERSION#v}-${BUILD_DATE}-${SHORT_SHA}"
|
||||
PATCH_NUMBER="${{ github.event.inputs.patch }}"
|
||||
|
||||
if [[ ! "${PATCH_NUMBER}" =~ ^[0-9]+$ ]]; then
|
||||
PATCH_NUMBER=0
|
||||
fi
|
||||
|
||||
if [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)-([0-9]{8})$ ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
PATCH_NUMBER="${BASH_REMATCH[3]}"
|
||||
BUILD_DATE="${BASH_REMATCH[4]}"
|
||||
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})-([0-9]+)$ ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
BUILD_DATE="${BASH_REMATCH[3]}"
|
||||
PATCH_NUMBER="${BASH_REMATCH[4]}"
|
||||
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]{8})$ ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
BUILD_DATE="${BASH_REMATCH[3]}"
|
||||
elif [[ "${VERSION_BASE}" =~ ^([0-9]+(\.[0-9]+){1,3})-([0-9]+)$ && "${PATCH_NUMBER}" == "0" ]]; then
|
||||
VERSION_BASE="${BASH_REMATCH[1]}"
|
||||
PATCH_NUMBER="${BASH_REMATCH[3]}"
|
||||
fi
|
||||
|
||||
BUILD_DATE_ISO="${BUILD_DATE:0:4}-${BUILD_DATE:4:2}-${BUILD_DATE:6:2}"
|
||||
if [[ "${PATCH_NUMBER}" != "0" ]]; then
|
||||
VERSION_NUM="${VERSION_BASE}-${PATCH_NUMBER}-${BUILD_DATE}"
|
||||
else
|
||||
VERSION_NUM="${VERSION_BASE}-${BUILD_DATE}"
|
||||
fi
|
||||
|
||||
VERSION_WITH_V="v${VERSION_NUM}"
|
||||
VERSION_ONLY="${VERSION#v}"
|
||||
echo "VERSION_NUM=${VERSION_NUM}" >> $GITHUB_OUTPUT
|
||||
echo "VERSION_WITH_V=${VERSION_WITH_V}" >> $GITHUB_OUTPUT
|
||||
echo "VERSION_ONLY=${VERSION_ONLY}" >> $GITHUB_OUTPUT
|
||||
echo "VERSION_BASE=${VERSION_BASE}" >> $GITHUB_OUTPUT
|
||||
echo "BUILD_DATE=${BUILD_DATE}" >> $GITHUB_OUTPUT
|
||||
echo "BUILD_DATE_ISO=${BUILD_DATE_ISO}" >> $GITHUB_OUTPUT
|
||||
echo "PATCH_NUMBER=${PATCH_NUMBER}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Prepare release notes
|
||||
run: |
|
||||
cat > "$RUNNER_TEMP/release-notes.md" << EOF
|
||||
## Corresponding source
|
||||
|
||||
Source for these binaries: [${GITHUB_REF_NAME}](https://github.com/${GITHUB_REPOSITORY}/tree/${GITHUB_SHA}).
|
||||
Clone that version with recursive submodules. The repository includes the build scripts and dependency patches.
|
||||
[iOS source, modification and rebuild instructions](https://github.com/${GITHUB_REPOSITORY}/blob/${GITHUB_SHA}/apps/ios/README.md).
|
||||
The iOS archive also contains the exact source revision and third-party source catalog with archive checksums.
|
||||
[Android source and rebuild instructions](https://github.com/${GITHUB_REPOSITORY}/blob/${GITHUB_SHA}/apps/android/README.md).
|
||||
The Android arm64 Release APK is signed with the CrossDesk publishing key and can be installed directly.
|
||||
It includes the exact application and MiniRTC revisions, license documents and native build recipes.
|
||||
|
||||
## Linux packages
|
||||
|
||||
Choose one package for your architecture; both contain the complete CrossDesk application:
|
||||
- Standard (recommended): crossdesk-linux-ARCH-VERSION.deb, for existing desktops.
|
||||
- Virtual desktop: crossdesk-virtual-desktop-xfce-linux-ARCH-VERSION.deb, which additionally installs Xfce, Xvfb and D-Bus session tools through APT.
|
||||
The packages replace each other and preserve user settings. Installation does not switch your default desktop or start a virtual session.
|
||||
[Linux setup and switching packages](https://github.com/${GITHUB_REPOSITORY}/blob/${GITHUB_SHA}/docs/HEADLESS_EN.md).
|
||||
|
||||
## Code signing policy
|
||||
|
||||
Free code signing provided by [SignPath.io](https://signpath.io/), certificate by [SignPath Foundation](https://signpath.org/).
|
||||
EOF
|
||||
|
||||
- name: Rename artifacts
|
||||
run: |
|
||||
mkdir -p release
|
||||
cp artifacts/crossdesk-macos-x64-${{ steps.version.outputs.VERSION_WITH_V }}/* release/crossdesk-macos-x64-${{ steps.version.outputs.VERSION_WITH_V }}.pkg
|
||||
cp artifacts/crossdesk-macos-arm64-${{ steps.version.outputs.VERSION_WITH_V }}/* release/crossdesk-macos-arm64-${{ steps.version.outputs.VERSION_WITH_V }}.pkg
|
||||
cp artifacts/crossdesk-linux-amd64-${{ steps.version.outputs.VERSION_WITH_V }}/* release/crossdesk-linux-amd64-${{ steps.version.outputs.VERSION_WITH_V }}.deb
|
||||
cp artifacts/crossdesk-linux-arm64-${{ steps.version.outputs.VERSION_WITH_V }}/* release/crossdesk-linux-arm64-${{ steps.version.outputs.VERSION_WITH_V }}.deb
|
||||
for ARCH in amd64 arm64; do
|
||||
for PACKAGE in crossdesk crossdesk-virtual-desktop-xfce; do
|
||||
FILE="${PACKAGE}-linux-${ARCH}-${{ steps.version.outputs.VERSION_WITH_V }}.deb"
|
||||
cp "artifacts/crossdesk-linux-${ARCH}-${{ steps.version.outputs.VERSION_WITH_V }}/${FILE}" "release/${FILE}"
|
||||
done
|
||||
done
|
||||
cp artifacts/crossdesk-ios-arm64-unsigned-${{ needs.build-ios.outputs.version }}/* release/crossdesk-ios-arm64-unsigned-${{ needs.build-ios.outputs.version }}.zip
|
||||
cp artifacts/crossdesk-android-arm64-${{ needs.build-android.outputs.version }}/*.apk release/crossdesk-android-arm64-${{ needs.build-android.outputs.version }}.apk
|
||||
cp artifacts/crossdesk-win-x64-${{ steps.version.outputs.VERSION_WITH_V }}/* release/crossdesk-win-x64-${{ steps.version.outputs.VERSION_WITH_V }}.exe
|
||||
cp artifacts/crossdesk-win-x64-portable-${{ steps.version.outputs.VERSION_WITH_V }}/* release/crossdesk-win-x64-portable-${{ steps.version.outputs.VERSION_WITH_V }}.zip
|
||||
|
||||
- name: List release files
|
||||
run: ls -lh release/
|
||||
@@ -367,13 +704,14 @@ jobs:
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ steps.version.outputs.VERSION_WITH_V }}
|
||||
# The pushed tag already determines the release source commit.
|
||||
target_commitish: ${{ github.event.repository.default_branch }}
|
||||
name: Release ${{ steps.version.outputs.VERSION_WITH_V }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
files: release/*
|
||||
generate_release_notes: false
|
||||
body: |
|
||||
Binary release only. Source code is not included.
|
||||
body_path: ${{ runner.temp }}/release-notes.md
|
||||
|
||||
- name: Create or update 'latest' tag
|
||||
run: |
|
||||
@@ -391,56 +729,37 @@ jobs:
|
||||
prerelease: false
|
||||
files: release/*
|
||||
generate_release_notes: false
|
||||
body_path: ${{ runner.temp }}/release-notes.md
|
||||
|
||||
- name: Upload artifacts to server
|
||||
uses: burnett01/rsync-deployments@5.2
|
||||
with:
|
||||
switches: -avzr --progress --delete
|
||||
switches: -avzr --progress
|
||||
path: release/*
|
||||
remote_path: /var/www/html/downloads/
|
||||
remote_host: ${{ secrets.SERVER_HOST }}
|
||||
remote_user: ${{ secrets.SERVER_USER }}
|
||||
remote_key: ${{ secrets.SERVER_KEY }}
|
||||
|
||||
- name: Generate version.json
|
||||
- name: Download current version.json
|
||||
run: |
|
||||
cat > version.json << EOF
|
||||
{
|
||||
"version": "${{ steps.version.outputs.VERSION_ONLY }}",
|
||||
"releaseDate": "${{ steps.version.outputs.BUILD_DATE_ISO }}",
|
||||
"releaseName": "",
|
||||
"releaseNotes": "",
|
||||
"tagName": "${{ steps.version.outputs.VERSION_WITH_V }}",
|
||||
"downloads": {
|
||||
"windows-x64": {
|
||||
"url": "https://downloads.crossdesk.cn/crossdesk-win-x64-${{ steps.version.outputs.VERSION_WITH_V }}.exe",
|
||||
"filename": "crossdesk-win-x64-${{ steps.version.outputs.VERSION_WITH_V }}.exe"
|
||||
},
|
||||
"macos-x64": {
|
||||
"url": "https://downloads.crossdesk.cn/crossdesk-macos-x64-${{ steps.version.outputs.VERSION_WITH_V }}.pkg",
|
||||
"filename": "crossdesk-macos-x64-${{ steps.version.outputs.VERSION_WITH_V }}.pkg"
|
||||
},
|
||||
"macos-arm64": {
|
||||
"url": "https://downloads.crossdesk.cn/crossdesk-macos-arm64-${{ steps.version.outputs.VERSION_WITH_V }}.pkg",
|
||||
"filename": "crossdesk-macos-arm64-${{ steps.version.outputs.VERSION_WITH_V }}.pkg"
|
||||
},
|
||||
"linux-amd64": {
|
||||
"url": "https://downloads.crossdesk.cn/crossdesk-linux-amd64-${{ steps.version.outputs.VERSION_WITH_V }}.deb",
|
||||
"filename": "crossdesk-linux-amd64-${{ steps.version.outputs.VERSION_WITH_V }}.deb"
|
||||
},
|
||||
"linux-arm64": {
|
||||
"url": "https://downloads.crossdesk.cn/crossdesk-linux-arm64-${{ steps.version.outputs.VERSION_WITH_V }}.deb",
|
||||
"filename": "crossdesk-linux-arm64-${{ steps.version.outputs.VERSION_WITH_V }}.deb"
|
||||
}
|
||||
}
|
||||
}
|
||||
EOF
|
||||
cat version.json
|
||||
curl --fail --silent --show-error --retry 3 --max-time 30 \
|
||||
-H 'Cache-Control: no-cache' \
|
||||
https://version.crossdesk.cn/version.json -o current-version.json
|
||||
|
||||
- name: Generate version.json for all platforms
|
||||
env:
|
||||
RELEASE_TAG: ${{ steps.version.outputs.VERSION_WITH_V }}
|
||||
run: |
|
||||
python3 .github/scripts/update_version_manifest.py \
|
||||
--current current-version.json --output version.json --artifacts release \
|
||||
--tag "${RELEASE_TAG}" --name "Release ${RELEASE_TAG}" \
|
||||
--notes "${RUNNER_TEMP}/release-notes.md"
|
||||
|
||||
- name: Upload version.json to server
|
||||
uses: burnett01/rsync-deployments@5.2
|
||||
with:
|
||||
switches: -avzr --delete
|
||||
switches: -avzr
|
||||
path: version.json
|
||||
remote_path: /var/www/html/version/
|
||||
remote_host: ${{ secrets.SERVER_HOST }}
|
||||
|
||||
@@ -4,6 +4,7 @@ on:
|
||||
schedule:
|
||||
# run every day at midnight
|
||||
- cron: "0 0 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
@@ -15,19 +16,21 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check inactive issues and close them
|
||||
uses: actions/github-script@v6
|
||||
uses: actions/github-script@v7
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
script: |
|
||||
const { data: issues } = await github.rest.issues.listForRepo({
|
||||
const inactivePeriod = 7 * 24 * 60 * 60 * 1000; // 7 days
|
||||
const now = Date.now();
|
||||
|
||||
// paginate through all open issues (listForRepo also returns PRs)
|
||||
const issues = await github.paginate(github.rest.issues.listForRepo, {
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
state: 'open',
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
const now = new Date().getTime();
|
||||
const inactivePeriod = 7 * 24 * 60 * 60 * 1000; // 7 days
|
||||
|
||||
for (const issue of issues) {
|
||||
// skip pull requests (they are also returned by listForRepo)
|
||||
if (issue.pull_request) continue;
|
||||
@@ -38,26 +41,14 @@ jobs:
|
||||
continue;
|
||||
}
|
||||
|
||||
// fetch comments for this issue
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
// determine the "last activity" time
|
||||
let lastActivityTime;
|
||||
if (comments.length > 0) {
|
||||
const lastComment = comments[comments.length - 1];
|
||||
lastActivityTime = new Date(lastComment.updated_at).getTime();
|
||||
} else {
|
||||
lastActivityTime = new Date(issue.created_at).getTime();
|
||||
}
|
||||
// last activity time = the issue's own updated_at, which is
|
||||
// refreshed on comments, labels, etc. This avoids relying on
|
||||
// fetching comments and is accurate even when comments are edited.
|
||||
const lastActivityTime = new Date(issue.updated_at).getTime();
|
||||
|
||||
// check inactivity
|
||||
if (now - lastActivityTime > inactivePeriod) {
|
||||
console.log(`Closing inactive issue: #${issue.number} (No recent replies for 7 days)`);
|
||||
console.log(`Closing inactive issue: #${issue.number} (No activity for 7 days)`);
|
||||
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
@@ -76,5 +67,3 @@ jobs:
|
||||
console.log(`Skipping issue #${issue.number} (Active within 7 days).`);
|
||||
}
|
||||
}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
name: Release Mobile
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "ios-v*"
|
||||
- "android-v*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
source_tag:
|
||||
description: "Existing tag: ios-v0.0.1-20261002 or android-v0.1.0-20261002."
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
name: Validate mobile source tag
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
platform: ${{ steps.source.outputs.platform }}
|
||||
tag: ${{ steps.source.outputs.tag }}
|
||||
version: ${{ steps.source.outputs.version }}
|
||||
sha: ${{ steps.source.outputs.sha }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Resolve source tag
|
||||
id: source
|
||||
shell: python
|
||||
env:
|
||||
SOURCE_TAG: ${{ inputs.source_tag || github.ref_name }}
|
||||
run: |
|
||||
import datetime
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
tag = os.environ["SOURCE_TAG"]
|
||||
match = re.fullmatch(r"(ios|android)-(v[0-9]+\.[0-9]+\.[0-9]+-([0-9]{8}))", tag)
|
||||
if not match:
|
||||
raise ValueError("Use an existing ios-v<app-version>-YYYYMMDD or android-v<app-version>-YYYYMMDD tag")
|
||||
datetime.datetime.strptime(match[3], "%Y%m%d")
|
||||
sha = subprocess.check_output(
|
||||
["git", "rev-parse", "--verify", f"refs/tags/{tag}^{{commit}}"], text=True).strip()
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a") as stream:
|
||||
stream.write(f"platform={match[1]}\ntag={tag}\nversion={match[2]}\nsha={sha}\n")
|
||||
|
||||
build-ios:
|
||||
name: Build iOS release
|
||||
needs: prepare
|
||||
if: needs.prepare.outputs.platform == 'ios'
|
||||
uses: ./.github/workflows/build-ios.yml
|
||||
with:
|
||||
source_tag: ${{ needs.prepare.outputs.tag }}
|
||||
|
||||
build-android:
|
||||
name: Build Android release
|
||||
needs: prepare
|
||||
if: needs.prepare.outputs.platform == 'android'
|
||||
uses: ./.github/workflows/build-android.yml
|
||||
with:
|
||||
source_tag: ${{ needs.prepare.outputs.tag }}
|
||||
|
||||
sign-android:
|
||||
name: Sign Android release
|
||||
needs: [prepare, build-android]
|
||||
if: needs.prepare.outputs.platform == 'android'
|
||||
uses: ./.github/workflows/sign-android.yml
|
||||
with:
|
||||
version: ${{ needs.build-android.outputs.version }}
|
||||
secrets:
|
||||
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
|
||||
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
|
||||
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
|
||||
|
||||
release:
|
||||
name: Publish mobile release
|
||||
needs: [prepare, build-ios, build-android, sign-android]
|
||||
if: ${{ !cancelled() && (needs.build-ios.result == 'success' || needs.sign-android.result == 'success') }}
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: write
|
||||
concurrency:
|
||||
group: publish-release-metadata
|
||||
cancel-in-progress: false
|
||||
env:
|
||||
PLATFORM: ${{ needs.prepare.outputs.platform }}
|
||||
SOURCE_TAG: ${{ needs.prepare.outputs.tag }}
|
||||
SOURCE_SHA: ${{ needs.prepare.outputs.sha }}
|
||||
VERSION: ${{ needs.prepare.outputs.version }}
|
||||
BUILD_VERSION: ${{ needs.build-ios.outputs.version || needs.build-android.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout publishing scripts
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Verify release version
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${BUILD_VERSION}" != "${VERSION}" ]]; then
|
||||
echo "Source tag version ${VERSION} does not match the app version ${BUILD_VERSION}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Download mobile release artifact
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: crossdesk-${{ env.PLATFORM }}-arm64${{ env.PLATFORM == 'ios' && '-unsigned' || '' }}-${{ env.VERSION }}
|
||||
path: release
|
||||
|
||||
- name: Prepare release notes
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${PLATFORM}" == "ios" ]]; then
|
||||
PLATFORM_NAME="iOS"
|
||||
SIGNING_NOTE="The arm64 ZIP contains an unsigned app, source metadata, third-party sources and any generated dSYM. Sign the app before device installation."
|
||||
else
|
||||
PLATFORM_NAME="Android"
|
||||
SIGNING_NOTE="The arm64 Release APK is signed with the CrossDesk publishing key and can be installed directly. It includes source metadata, license documents and native build recipes."
|
||||
fi
|
||||
cat > "${RUNNER_TEMP}/mobile-release-notes.md" << EOF
|
||||
${PLATFORM_NAME} ${VERSION}
|
||||
|
||||
${SIGNING_NOTE}
|
||||
|
||||
Source: [${SOURCE_TAG}](https://github.com/${GITHUB_REPOSITORY}/tree/${SOURCE_SHA}).
|
||||
Clone this tag with recursive submodules to obtain the corresponding source.
|
||||
[Source and rebuild instructions](https://github.com/${GITHUB_REPOSITORY}/blob/${SOURCE_SHA}/apps/${PLATFORM}/README.md).
|
||||
EOF
|
||||
|
||||
- name: Publish GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ env.SOURCE_TAG }}
|
||||
# prepare requires an existing tag; this does not move its source commit.
|
||||
# Using the default branch lets GITHUB_TOKEN update older release metadata.
|
||||
target_commitish: ${{ github.event.repository.default_branch }}
|
||||
name: ${{ env.PLATFORM == 'ios' && 'iOS' || 'Android' }} ${{ env.VERSION }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
make_latest: "false"
|
||||
files: release/*
|
||||
fail_on_unmatched_files: true
|
||||
generate_release_notes: false
|
||||
body_path: ${{ runner.temp }}/mobile-release-notes.md
|
||||
|
||||
- name: Upload mobile artifact to download server
|
||||
uses: burnett01/rsync-deployments@5.2
|
||||
with:
|
||||
switches: -avzr --progress
|
||||
path: release/*
|
||||
remote_path: /var/www/html/downloads/
|
||||
remote_host: ${{ secrets.SERVER_HOST }}
|
||||
remote_user: ${{ secrets.SERVER_USER }}
|
||||
remote_key: ${{ secrets.SERVER_KEY }}
|
||||
|
||||
- name: Download current version.json
|
||||
shell: bash
|
||||
run: |
|
||||
curl --fail --silent --show-error --retry 3 --max-time 30 \
|
||||
-H 'Cache-Control: no-cache' \
|
||||
https://version.crossdesk.cn/version.json -o current-version.json
|
||||
|
||||
- name: Update mobile version and download URL
|
||||
shell: bash
|
||||
env:
|
||||
RELEASE_NAME: ${{ env.PLATFORM == 'ios' && 'iOS' || 'Android' }} ${{ env.VERSION }}
|
||||
run: |
|
||||
python3 .github/scripts/update_version_manifest.py \
|
||||
--current current-version.json --output version.json --artifacts release \
|
||||
--tag "${SOURCE_TAG}" --name "${RELEASE_NAME}" \
|
||||
--notes "${RUNNER_TEMP}/mobile-release-notes.md"
|
||||
|
||||
- name: Upload version.json to server
|
||||
uses: burnett01/rsync-deployments@5.2
|
||||
with:
|
||||
switches: -avzr
|
||||
path: version.json
|
||||
remote_path: /var/www/html/version/
|
||||
remote_host: ${{ secrets.SERVER_HOST }}
|
||||
remote_user: ${{ secrets.SERVER_USER }}
|
||||
remote_key: ${{ secrets.SERVER_KEY }}
|
||||
|
||||
- name: Summarize release
|
||||
shell: bash
|
||||
run: |
|
||||
echo "Published [${SOURCE_TAG}](https://github.com/${GITHUB_REPOSITORY}/releases/tag/${SOURCE_TAG}), uploaded its ${PLATFORM} artifact to the download server, and updated version.json." >> "${GITHUB_STEP_SUMMARY}"
|
||||
@@ -0,0 +1,153 @@
|
||||
name: Sign Android Release
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
version:
|
||||
description: "Android artifact version, for example v1.6.0-20261002."
|
||||
required: true
|
||||
type: string
|
||||
secrets:
|
||||
ANDROID_KEYSTORE_BASE64:
|
||||
required: true
|
||||
ANDROID_KEYSTORE_PASSWORD:
|
||||
required: true
|
||||
ANDROID_KEY_ALIAS:
|
||||
required: true
|
||||
ANDROID_KEY_PASSWORD:
|
||||
required: true
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
source_tag:
|
||||
description: "Existing Android release to sign without rebuilding, for example android-v1.6.0-20261002."
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
sign:
|
||||
name: Sign and verify Android APK
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
env:
|
||||
VERSION: ${{ inputs.version }}
|
||||
SOURCE_TAG: ${{ inputs.source_tag }}
|
||||
steps:
|
||||
- name: Validate signing configuration
|
||||
shell: python
|
||||
env:
|
||||
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
|
||||
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
|
||||
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
|
||||
run: |
|
||||
import os
|
||||
names = ("ANDROID_KEYSTORE_BASE64", "ANDROID_KEYSTORE_PASSWORD",
|
||||
"ANDROID_KEY_ALIAS", "ANDROID_KEY_PASSWORD")
|
||||
missing = [name for name in names if not os.environ.get(name)]
|
||||
if missing:
|
||||
raise ValueError("Missing repository signing secrets: " + ", ".join(missing))
|
||||
|
||||
- name: Resolve artifact version
|
||||
id: version
|
||||
shell: python
|
||||
run: |
|
||||
import datetime
|
||||
import os
|
||||
import re
|
||||
version = os.environ["VERSION"]
|
||||
if os.environ["GITHUB_EVENT_NAME"] == "workflow_dispatch" and not version:
|
||||
tag = os.environ["SOURCE_TAG"]
|
||||
if not tag.startswith("android-v"):
|
||||
raise ValueError("Use an existing android-v<app-version>-YYYYMMDD release")
|
||||
version = tag.removeprefix("android-")
|
||||
match = re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+-([0-9]{8})", version)
|
||||
if not match:
|
||||
raise ValueError("Invalid Android artifact version")
|
||||
datetime.datetime.strptime(match[1], "%Y%m%d")
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a") as stream:
|
||||
stream.write(f"version={version}\n")
|
||||
|
||||
- name: Download unsigned build artifact
|
||||
if: github.event_name != 'workflow_dispatch' || inputs.version != ''
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: crossdesk-android-arm64-unsigned-${{ steps.version.outputs.version }}
|
||||
path: unsigned
|
||||
|
||||
- name: Download unsigned APK from existing release
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.version == ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
APK_VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
gh release view "${SOURCE_TAG}" --repo "${GITHUB_REPOSITORY}" \
|
||||
--json isDraft,isPrerelease > release.json
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
from pathlib import Path
|
||||
release = json.loads(Path('release.json').read_text())
|
||||
if release['isDraft'] or release['isPrerelease']:
|
||||
raise ValueError('Use a published stable Android release')
|
||||
PY
|
||||
gh release download "${SOURCE_TAG}" --repo "${GITHUB_REPOSITORY}" \
|
||||
--pattern "crossdesk-android-arm64-unsigned-${APK_VERSION}.apk" --dir unsigned
|
||||
|
||||
- name: Set up Java
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "17"
|
||||
|
||||
- name: Set up Android signing tools
|
||||
uses: android-actions/setup-android@v3
|
||||
with:
|
||||
packages: "build-tools;36.0.0"
|
||||
|
||||
# This job never checks out or executes application source with the key present.
|
||||
- name: Align, sign and verify Release APK
|
||||
env:
|
||||
APK_VERSION: ${{ steps.version.outputs.version }}
|
||||
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
|
||||
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
|
||||
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
|
||||
run: |
|
||||
umask 077
|
||||
crossdesk_signing_dir="$(mktemp -d "${RUNNER_TEMP}/crossdesk-signing.XXXXXX")"
|
||||
trap 'rm -rf -- "${crossdesk_signing_dir}"' EXIT
|
||||
printf '%s' "${ANDROID_KEYSTORE_BASE64}" | base64 --decode > "${crossdesk_signing_dir}/release.keystore"
|
||||
crossdesk_tools="${ANDROID_HOME}/build-tools/36.0.0"
|
||||
crossdesk_output="${RUNNER_TEMP}/crossdesk-android-signed"
|
||||
mkdir -p "${crossdesk_output}"
|
||||
"${crossdesk_tools}/zipalign" -P 16 -f -v 4 \
|
||||
"unsigned/crossdesk-android-arm64-unsigned-${APK_VERSION}.apk" \
|
||||
"${crossdesk_signing_dir}/aligned.apk"
|
||||
"${crossdesk_tools}/apksigner" sign \
|
||||
--ks "${crossdesk_signing_dir}/release.keystore" \
|
||||
--ks-key-alias "${ANDROID_KEY_ALIAS}" \
|
||||
--ks-pass env:ANDROID_KEYSTORE_PASSWORD --key-pass env:ANDROID_KEY_PASSWORD \
|
||||
--out "${crossdesk_output}/crossdesk-android-arm64-${APK_VERSION}.apk" \
|
||||
"${crossdesk_signing_dir}/aligned.apk"
|
||||
"${crossdesk_tools}/apksigner" verify --verbose --print-certs \
|
||||
"${crossdesk_output}/crossdesk-android-arm64-${APK_VERSION}.apk"
|
||||
"${crossdesk_tools}/zipalign" -c -P 16 -v 4 \
|
||||
"${crossdesk_output}/crossdesk-android-arm64-${APK_VERSION}.apk"
|
||||
|
||||
- name: Upload signed Release APK
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: crossdesk-android-arm64-${{ steps.version.outputs.version }}
|
||||
path: ${{ runner.temp }}/crossdesk-android-signed/*.apk
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Summarize signing
|
||||
env:
|
||||
APK_VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
echo "Android ${APK_VERSION}: Release APK signed with the fixed publishing key; APK signature and 16 KB ZIP alignment verified." >> "${GITHUB_STEP_SUMMARY}"
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" && -z "${VERSION}" ]]; then
|
||||
echo "Signed an existing release without rebuilding. Download the signed Actions artifact to publish it." >> "${GITHUB_STEP_SUMMARY}"
|
||||
fi
|
||||
@@ -3,138 +3,84 @@ name: Update version.json from Release
|
||||
on:
|
||||
release:
|
||||
types: [published, edited]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
source_tag:
|
||||
description: "Existing version tag whose assets and metadata should be uploaded to the server."
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
update-version-json:
|
||||
name: Update version.json with release information
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
name: Upload release downloads and update version.json
|
||||
if: github.event_name == 'workflow_dispatch' || (github.event.release.tag_name != 'latest' && !github.event.release.prerelease)
|
||||
runs-on: ubuntu-24.04
|
||||
concurrency:
|
||||
group: publish-release-metadata
|
||||
cancel-in-progress: false
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: ${{ inputs.source_tag || github.event.release.tag_name }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Checkout publishing scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
|
||||
- name: Extract version from tag
|
||||
id: version
|
||||
- name: Download release information and assets
|
||||
shell: bash
|
||||
run: |
|
||||
TAG_NAME="${{ github.event.release.tag_name }}"
|
||||
VERSION_ONLY="${TAG_NAME#v}"
|
||||
echo "TAG_NAME=${TAG_NAME}" >> $GITHUB_OUTPUT
|
||||
echo "VERSION_ONLY=${VERSION_ONLY}" >> $GITHUB_OUTPUT
|
||||
|
||||
# Extract date from tag if available (format: v1.2.3-20251113-abc)
|
||||
if [[ "${TAG_NAME}" =~ -([0-9]{8})- ]]; then
|
||||
DATE_STR="${BASH_REMATCH[1]}"
|
||||
BUILD_DATE_ISO="${DATE_STR:0:4}-${DATE_STR:4:2}-${DATE_STR:6:2}"
|
||||
else
|
||||
# Use release published date
|
||||
BUILD_DATE_ISO=$(echo "${{ github.event.release.published_at }}" | cut -d'T' -f1)
|
||||
fi
|
||||
echo "BUILD_DATE_ISO=${BUILD_DATE_ISO}" >> $GITHUB_OUTPUT
|
||||
python3 - <<'PY'
|
||||
import os
|
||||
import re
|
||||
if not re.fullmatch(r'(?:ios-|android-)?v[0-9]+(?:\.[0-9]+){1,3}(?:-[0-9]+)*', os.environ['RELEASE_TAG']):
|
||||
raise ValueError('Use a desktop, iOS or Android version tag')
|
||||
PY
|
||||
gh release view "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" \
|
||||
--json tagName,name,body,publishedAt,isDraft,isPrerelease > release.json
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
from pathlib import Path
|
||||
release = json.loads(Path('release.json').read_text())
|
||||
if release['isDraft'] or release['isPrerelease']:
|
||||
raise ValueError('Only published stable releases update version.json')
|
||||
PY
|
||||
gh release download "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" \
|
||||
--pattern 'crossdesk-*' --dir release
|
||||
|
||||
- name: Install jq
|
||||
run: sudo apt-get update && sudo apt-get install -y jq
|
||||
- name: Upload release assets to download server
|
||||
uses: burnett01/rsync-deployments@5.2
|
||||
with:
|
||||
switches: -avzr --progress
|
||||
path: release/*
|
||||
remote_path: /var/www/html/downloads/
|
||||
remote_host: ${{ secrets.SERVER_HOST }}
|
||||
remote_user: ${{ secrets.SERVER_USER }}
|
||||
remote_key: ${{ secrets.SERVER_KEY }}
|
||||
|
||||
- name: Get release information
|
||||
id: release_info
|
||||
- name: Download current version.json
|
||||
shell: bash
|
||||
run: |
|
||||
# Use jq to properly escape JSON
|
||||
RELEASE_BODY="${{ github.event.release.body }}"
|
||||
RELEASE_NAME="${{ github.event.release.name }}"
|
||||
|
||||
# Handle empty values
|
||||
if [ -z "$RELEASE_BODY" ]; then
|
||||
RELEASE_BODY=""
|
||||
fi
|
||||
if [ -z "$RELEASE_NAME" ]; then
|
||||
RELEASE_NAME=""
|
||||
fi
|
||||
|
||||
# Save to temporary files for proper handling
|
||||
echo -n "$RELEASE_BODY" > /tmp/release_body.txt
|
||||
echo -n "$RELEASE_NAME" > /tmp/release_name.txt
|
||||
|
||||
# Use jq to escape JSON strings
|
||||
RELEASE_BODY_JSON=$(jq -Rs . < /tmp/release_body.txt)
|
||||
RELEASE_NAME_JSON=$(jq -Rs . < /tmp/release_name.txt)
|
||||
|
||||
echo "RELEASE_BODY=${RELEASE_BODY_JSON}" >> $GITHUB_OUTPUT
|
||||
echo "RELEASE_NAME=${RELEASE_NAME_JSON}" >> $GITHUB_OUTPUT
|
||||
curl --fail --silent --show-error --retry 3 --max-time 30 \
|
||||
-H 'Cache-Control: no-cache' \
|
||||
https://version.crossdesk.cn/version.json -o current-version.json
|
||||
|
||||
- name: Download current version.json from server
|
||||
id: download_version
|
||||
continue-on-error: true
|
||||
- name: Merge release version and download URLs
|
||||
shell: bash
|
||||
run: |
|
||||
# Try to download current version.json from server
|
||||
curl -f -s "https://version.crossdesk.cn/version.json" -o version.json || echo "Failed to download, will create new one"
|
||||
|
||||
- name: Generate or update version.json
|
||||
run: |
|
||||
# If version.json exists, try to preserve downloads section
|
||||
if [ -f version.json ] && jq -e '.downloads' version.json > /dev/null 2>&1; then
|
||||
EXISTING_DOWNLOADS=$(jq -c '.downloads' version.json)
|
||||
if [ "$EXISTING_DOWNLOADS" != "null" ] && [ "$EXISTING_DOWNLOADS" != "{}" ]; then
|
||||
DOWNLOADS_JSON="$EXISTING_DOWNLOADS"
|
||||
else
|
||||
DOWNLOADS_JSON=""
|
||||
fi
|
||||
else
|
||||
DOWNLOADS_JSON=""
|
||||
fi
|
||||
|
||||
# If downloads is empty, use default structure
|
||||
if [ -z "$DOWNLOADS_JSON" ]; then
|
||||
DOWNLOADS_JSON=$(cat << DOWNLOADS_EOF
|
||||
{
|
||||
"windows-x64": {
|
||||
"url": "https://downloads.crossdesk.cn/crossdesk-win-x64-${{ steps.version.outputs.TAG_NAME }}.exe",
|
||||
"filename": "crossdesk-win-x64-${{ steps.version.outputs.TAG_NAME }}.exe"
|
||||
},
|
||||
"macos-x64": {
|
||||
"url": "https://downloads.crossdesk.cn/crossdesk-macos-x64-${{ steps.version.outputs.TAG_NAME }}.pkg",
|
||||
"filename": "crossdesk-macos-x64-${{ steps.version.outputs.TAG_NAME }}.pkg"
|
||||
},
|
||||
"macos-arm64": {
|
||||
"url": "https://downloads.crossdesk.cn/crossdesk-macos-arm64-${{ steps.version.outputs.TAG_NAME }}.pkg",
|
||||
"filename": "crossdesk-macos-arm64-${{ steps.version.outputs.TAG_NAME }}.pkg"
|
||||
},
|
||||
"linux-amd64": {
|
||||
"url": "https://downloads.crossdesk.cn/crossdesk-linux-amd64-${{ steps.version.outputs.TAG_NAME }}.deb",
|
||||
"filename": "crossdesk-linux-amd64-${{ steps.version.outputs.TAG_NAME }}.deb"
|
||||
},
|
||||
"linux-arm64": {
|
||||
"url": "https://downloads.crossdesk.cn/crossdesk-linux-arm64-${{ steps.version.outputs.TAG_NAME }}.deb",
|
||||
"filename": "crossdesk-linux-arm64-${{ steps.version.outputs.TAG_NAME }}.deb"
|
||||
}
|
||||
}
|
||||
DOWNLOADS_EOF
|
||||
)
|
||||
fi
|
||||
|
||||
# Generate version.json using cat and heredoc
|
||||
cat > version.json << EOF
|
||||
{
|
||||
"version": "${{ steps.version.outputs.VERSION_ONLY }}",
|
||||
"releaseDate": "${{ steps.version.outputs.BUILD_DATE_ISO }}",
|
||||
"releaseName": ${{ steps.release_info.outputs.RELEASE_NAME }},
|
||||
"releaseNotes": ${{ steps.release_info.outputs.RELEASE_BODY }},
|
||||
"tagName": "${{ steps.version.outputs.TAG_NAME }}",
|
||||
"downloads": ${DOWNLOADS_JSON}
|
||||
}
|
||||
EOF
|
||||
|
||||
cat version.json
|
||||
python3 .github/scripts/update_version_manifest.py \
|
||||
--current current-version.json --output version.json --artifacts release \
|
||||
--release-json release.json
|
||||
|
||||
- name: Upload version.json to server
|
||||
uses: burnett01/rsync-deployments@5.2
|
||||
with:
|
||||
switches: -avzr --delete
|
||||
switches: -avzr
|
||||
path: version.json
|
||||
remote_path: /var/www/html/version/
|
||||
remote_host: ${{ secrets.SERVER_HOST }}
|
||||
remote_user: ${{ secrets.SERVER_USER }}
|
||||
remote_key: ${{ secrets.SERVER_KEY }}
|
||||
remote_key: ${{ secrets.SERVER_KEY }}
|
||||
|
||||
+7
-2
@@ -1,10 +1,15 @@
|
||||
# Xmake cache
|
||||
.xmake/
|
||||
.xmake-toolchain-cache/
|
||||
build/
|
||||
certs/
|
||||
apps/ios/Vendor/
|
||||
apps/ios/DerivedData*/
|
||||
apps/ios/.xmake/
|
||||
xcuserdata/
|
||||
*.xcuserstate
|
||||
|
||||
# MacOS Cache
|
||||
.DS_Store
|
||||
|
||||
# VSCode cache
|
||||
.vscode
|
||||
.vscode
|
||||
|
||||
+2
-2
@@ -1,3 +1,3 @@
|
||||
[submodule "submodules/minirtc"]
|
||||
path = submodules/minirtc
|
||||
[submodule "deps/submodules/minirtc"]
|
||||
path = deps/submodules/minirtc
|
||||
url = https://github.com/kunkundi/minirtc.git
|
||||
|
||||
@@ -1,165 +1,674 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
0. Additional Definitions.
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
0. Definitions.
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
4. Combined Works.
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
1. Source Code.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
d) Do one of the following:
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
5. Combined Libraries.
|
||||
2. Basic Permissions.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
# CrossDesk Privacy Policy
|
||||
|
||||
Last updated: October 10, 2026
|
||||
|
||||
[中文](#中文) | [English](#english)
|
||||
|
||||
## 中文
|
||||
|
||||
更新日期:2026 年 10 月 10 日
|
||||
|
||||
CrossDesk 重视您的个人信息与隐私保护。本政策说明我们在提供远程桌面服务时如何处理相关信息,以及您可以如何管理授权、保存的内容和数据请求。请在使用前阅读并了解本政策。
|
||||
|
||||
### 一、适用范围
|
||||
|
||||
本政策适用于 CrossDesk 桌面客户端、iOS 与 Android 客户端,以及由 CrossDesk 项目维护者(以下简称“我们”)提供的默认网络服务。
|
||||
|
||||
如果您选择自行部署或使用其他运营者提供的服务器,该服务器所处理的信息、保存期限及安全管理由相应运营者负责。请在使用前了解其隐私政策。本政策中有关客户端本地数据处理的说明仍适用。
|
||||
|
||||
### 二、我们处理的信息及用途
|
||||
|
||||
**设备连接与身份验证。** 为登记设备、验证连接权限、查询在线状态及建立远程连接,客户端与服务端会处理设备 ID、认证信息及在线状态。服务端还会保存设备身份及认证校验信息、在线与离线时间、客户端版本与平台、设备关联记录,并生成必要的运行和安全日志,用于维持服务、排查故障及防止滥用。
|
||||
|
||||
**必要的网络信息。** 建立连接、网络地址转换穿透及中继转发需要处理 IP 地址、端口等网络信息。这些信息用于通信和网络诊断,不等同于读取设备的定位权限。连接服务、中继服务及网络请求可能产生相应日志。
|
||||
|
||||
**远程会话内容。** 您发起或接受远程连接后,软件根据使用的功能在参与会话的设备之间传输画面、音频、键盘和鼠标操作、剪贴板文本及文件。会话内容可能包含个人或工作信息,请仅连接您拥有或已获授权使用的设备,并按需管理共享内容。
|
||||
|
||||
**版本检查。** 桌面客户端启动后会获取版本信息;iOS 与 Android 客户端在连接成功并收到远端版本信息后,会获取最新桌面版本信息,用于提示升级。该请求不携带设备 ID 或远端版本号,但网络服务会处理完成请求所必需的网络信息。
|
||||
|
||||
CrossDesk 未集成广告投放、广告追踪或用户行为分析功能。客户端不会主动上传诊断日志、崩溃报告或用户行为分析数据。您主动向我们提交问题或日志时,请先移除与问题无关的个人信息及连接凭据。
|
||||
|
||||
### 三、数据传输与相关服务
|
||||
|
||||
我们提供设备登记、连接协商、中继转发及版本检查服务。即使您使用自托管连接服务,客户端仍会按前述条件访问我们提供的版本服务。
|
||||
|
||||
远程会话内容优先在参与会话的设备间直接传输,必要时通过配置的中继服务器转发。中继服务用于实时转发,不提供会话录像或文件归档。客户端本地保存的画面预览和接收文件,按本政策相关说明处理。
|
||||
|
||||
自托管服务器由您选择的运营者管理。更换连接服务器后,设备登记、连接协商及中继数据将由相应运营者处理。
|
||||
|
||||
### 四、信息保存与安全措施
|
||||
|
||||
**客户端本地数据。** 软件会在本机保存连接设置、用户偏好、最近连接记录及必要的运行日志,以支持后续使用和故障排查。iOS 中的本机登录凭据及您选择记住的远程连接密码保存在系统钥匙串中,不通过 iCloud 钥匙串同步;旧版偏好中的本机登录凭据在成功迁入钥匙串后删除。
|
||||
|
||||
Android 中的设备身份及您选择保存的访问密码使用 Android Keystore 密钥加密后保存在本机,应用本地数据不纳入设备备份。
|
||||
|
||||
**远程画面预览。** iOS 与 Android 默认不保存远程画面预览。只有您在“设置 → 隐私”单独开启并确认后,才会从下一次连接起,每次连接保存一张远程画面,用于最近连接预览。预览仅保存在本机,不上传,并设置为不纳入设备备份。您可以单独清除预览;关闭保存或撤回隐私授权也会清除已有预览。旧版本未经此选择保存的预览会在升级后清理。
|
||||
|
||||
**接收的文件。** iOS 接收文件保存在本应用的文件目录中,您可通过系统“文件”应用管理或删除。清除画面预览不会删除接收文件或最近连接记录。
|
||||
|
||||
**服务端记录。** 为支持再次连接、服务运维和安全排查,设备身份、状态、关联记录及运行日志可能在连接结束后继续保存。保存范围和期限受服务运行需要、部署规则及适用的保留要求约束。您可以通过下述联系方式查询与您设备相关的信息及保存期限,或提出删除请求。撤回隐私授权、删除本地记录或卸载客户端,不会自动删除已产生的服务端记录;日志、备份和快照需分别核查和处理。
|
||||
|
||||
iOS 通过系统钥匙串和文件保护机制保护相应本地数据,默认信令连接进行 TLS 证书校验。请妥善保管设备和连接凭据,避免向无关人员共享访问密码。
|
||||
|
||||
Android 默认信令连接同样进行 TLS 证书校验。
|
||||
|
||||
### 五、移动端权限与授权选择
|
||||
|
||||
**隐私授权。** iOS 与 Android 首次使用,或从未提供此选择的旧版升级时,您需阅读本政策、主动勾选并点击同意后,客户端才会登记本机身份、连接信令服务和查询设备在线状态。拒绝后仍可查看设置、离线隐私政策和本地连接记录,远程连接功能暂不可用。未授权时,重新打开或从后台返回应用会再次提示。
|
||||
|
||||
**撤回同意。** 您可以在“设置 → 隐私 → 隐私与授权”中查看隐私政策、授权状态或撤回授权。客户端将停止远程会话、信令连接和版本检查,关闭并清除本地画面预览。再次使用连接功能前需重新同意;重新同意不会自动开启画面预览保存。撤回不影响撤回前已经发生的信息处理,也不等同于删除服务端数据。
|
||||
|
||||
**系统权限与会话功能。** iOS 客户端作为控制端接收远程电脑的画面与音频,不采集本机屏幕、摄像头或麦克风。局域网访问权限用于连接本地网络中的设备,您可在系统设置中管理。发送文件通过系统文件选择器选择,不要求开放整个文件库。当前 iOS 界面不读取或发送本机剪贴板文本;远端发送的剪贴板文本可在会话中写入本机剪贴板。
|
||||
|
||||
Android 客户端同样作为控制端接收远程画面与音频,不采集本机屏幕、摄像头或麦克风。发送及保存文件通过系统文件选择器完成,不要求开放整个文件库。剪贴板文本仅在您主动发送或复制远端文本时传输或写入本机,会话结束时清除应用内缓存的远端剪贴板文本。
|
||||
|
||||
Android 远程会话优先使用系统画中画在切换应用后继续显示画面。画中画不可用时,通过前台服务和连接通知保持您已建立的远程连接;后台暂停本地画面渲染和音频播放,不申请悬浮窗权限。通知权限用于提供返回及断开入口,CPU 唤醒锁用于会话后台期间维持连接,返回前台或会话结束时释放。您可以在应用或连接通知中断开,移除应用任务也会结束会话及保活服务。
|
||||
|
||||
应用及通信组件使用本地文件元数据、应用偏好和计时接口实现文件传输、设置保存及网络计时,不使用这些信息制作设备指纹或进行广告追踪。
|
||||
|
||||
### 六、查询与删除请求
|
||||
|
||||
您可以管理本地最近连接记录、保存的画面预览及接收文件。删除某条最近连接记录时,其预览及已保存的远程连接密码也会删除。
|
||||
|
||||
如需查询、获取数据摘要或删除默认服务中与您设备相关的记录,请通过下述邮箱联系我们,说明设备 ID 和请求范围。为避免未经授权的披露或删除,我们会核实请求权限;请勿通过邮件发送访问密码、私钥或其他敏感凭据。
|
||||
|
||||
删除服务端设备身份后,原身份及对应凭据将失效,再次连接可能登记为新设备。数据库记录的删除不表示日志、备份或其他设备上已接收的内容同时删除。使用自托管服务时,请向相应服务器运营者提出服务端数据请求。
|
||||
|
||||
### 七、政策更新与联系方式
|
||||
|
||||
本政策可能随功能及服务方式调整而更新,更新后的内容和日期将在隐私政策中公布。您可随时在应用设置中查阅当前随应用提供的政策文本。
|
||||
|
||||
如对本政策或个人信息处理有疑问,请联系:
|
||||
|
||||
邮箱:[junkun.di@hotmail.com](mailto:junkun.di@hotmail.com)
|
||||
|
||||
---
|
||||
|
||||
## English
|
||||
|
||||
Updated: October 2, 2026
|
||||
|
||||
CrossDesk respects your privacy. This policy explains how information is processed when we provide remote desktop services and how you can manage consent, locally saved content and data requests. Please read this policy before using the software.
|
||||
|
||||
### 1. Scope
|
||||
|
||||
This policy applies to the CrossDesk desktop, iOS and Android clients and the default network services provided by the CrossDesk project maintainers ("we" or "us").
|
||||
|
||||
If you deploy your own server or choose a server provided by another operator, that operator is responsible for its data processing, retention and security practices. Please review its privacy policy before use. The descriptions of local client data processing in this policy still apply.
|
||||
|
||||
### 2. Information processed and its purposes
|
||||
|
||||
**Device connections and authentication.** To register devices, verify connection permissions, query availability and establish remote connections, the clients and server process device IDs, authentication information and presence. The server also retains device identity and authentication verification records, online and offline times, client versions and platforms, and device associations. Necessary operational and security logs support service operation, troubleshooting and abuse prevention.
|
||||
|
||||
**Necessary network information.** Connections, network address translation traversal and relay forwarding require IP addresses, ports and other network information. This supports communication and network diagnostics and does not involve reading the device's location permission. Connection services, relay services and network requests may generate related logs.
|
||||
|
||||
**Remote-session content.** After you initiate or accept a remote connection, the software transfers content between participating devices according to the features used. This includes screens, audio, keyboard and mouse input, clipboard text and files. Such content may contain personal or work information. Connect only to devices you own or are authorized to access, and manage shared content accordingly.
|
||||
|
||||
**Version checks.** The desktop client retrieves release information after startup. After connecting and receiving the remote host's version, the iOS and Android clients retrieve the latest desktop release information to suggest updates. These requests do not contain device IDs or the remote host's version, but the service processes network information necessary to complete the request.
|
||||
|
||||
CrossDesk does not integrate advertising, advertising tracking or behavioral analytics. The clients do not proactively upload diagnostic logs, crash reports or behavioral analytics data. If you choose to submit an issue or logs, remove unrelated personal information and connection credentials first.
|
||||
|
||||
### 3. Data transmission and related services
|
||||
|
||||
We provide device registration, connection negotiation, relay forwarding and version checks. Even when you use a self-hosted connection service, the client still accesses our version service under the conditions described above.
|
||||
|
||||
Remote-session content is transmitted directly between participating devices where possible, or through the configured relay server when needed. The relay service forwards content in real time and does not provide session recording or file archiving. Locally saved previews and received files are handled as described in this policy.
|
||||
|
||||
Self-hosted servers are managed by the operator you choose. If you change the connection server, the corresponding operator will process device registration, connection negotiation and relay data.
|
||||
|
||||
### 4. Storage and security measures
|
||||
|
||||
**Local client data.** The software stores connection settings, preferences, recent connections and necessary operational logs on the device for subsequent use and troubleshooting. On iOS, local login credentials and remote connection passwords you choose to remember are stored in the system Keychain without iCloud Keychain synchronization. Legacy local login credentials in preferences are removed after successful migration to the Keychain.
|
||||
|
||||
On Android, device identities and access passwords you choose to save are encrypted with Android Keystore keys and stored locally. The app's local data is excluded from device backups.
|
||||
|
||||
**Remote desktop previews.** Saving previews is off by default on iOS and Android. Only after you separately enable and confirm it in Settings → Privacy will the app save one remote frame per connection, starting with the next connection, for recent-connection previews. Previews remain local, are not uploaded and are marked as excluded from device backups. You can clear them separately. Disabling saving or withdrawing network consent also clears them. Previews saved by older versions without this choice are cleared on upgrade.
|
||||
|
||||
**Received files.** Received files on iOS are stored in the app's file directory and can be managed or deleted through Files. Clearing previews does not delete received files or recent-connection records.
|
||||
|
||||
**Server records.** Device identities, presence, associations and operational logs may remain after a connection ends to support reconnection, service operation and security troubleshooting. Their scope and retention depend on operational needs, deployment rules and applicable retention requirements. You can contact us below to ask about records and retention periods related to your device or request deletion. Withdrawing network consent, deleting local records or uninstalling the client does not automatically delete existing server records. Logs, backups and snapshots require separate review and handling.
|
||||
|
||||
On iOS, the system Keychain and file protection mechanisms protect the relevant local data, and default signaling connections validate TLS certificates. Keep your devices and connection credentials secure and avoid sharing access passwords with unrelated people.
|
||||
|
||||
Default signaling connections on Android also validate TLS certificates.
|
||||
|
||||
### 5. Mobile permissions and consent choices
|
||||
|
||||
**Privacy authorization.** On first use of iOS or Android, or when upgrading from a version without this choice, you must read this policy, actively select the checkbox and agree before the client registers a local identity, connects to signaling or queries device presence. If you decline, settings, the offline policy and local connection history remain available, while remote connections are unavailable. Without consent, reopening the app or returning from the background presents the notice again.
|
||||
|
||||
**Withdrawal.** You can review the privacy policy and your authorization status or withdraw consent in Settings → Privacy → Privacy and Authorization. The client stops remote sessions, signaling and version checks, disables preview saving and clears local previews. Consent is required again before reconnecting. Agreeing again does not automatically enable preview saving. Withdrawal does not undo processing that already occurred or delete server data.
|
||||
|
||||
**System permissions and session features.** The iOS client receives remote computer screens and audio as a controller; it does not capture the local screen, camera or microphone. Local network access supports connections to devices on your network and can be managed in system settings. File sending uses the system document picker without requiring access to the entire file library. The current iOS interface does not read or send local clipboard text. Text sent by the remote device may be written to the local clipboard during a session.
|
||||
|
||||
The Android client also receives remote screens and audio as a controller and does not capture the local screen, camera or microphone. Sending and saving files uses the system document picker without requiring access to the entire file library. Clipboard text is transmitted or written locally only when you explicitly send text or copy remote text. The app clears cached remote clipboard text when the session ends.
|
||||
|
||||
Android remote sessions prefer system picture-in-picture to continue displaying video when you switch apps. If picture-in-picture is unavailable, a foreground service and connection notification maintain the remote connection you have established. Local video rendering and audio playback pause in the background; no overlay permission is requested. Notification permission provides return and disconnect actions. A CPU wake lock helps maintain the connection while the session is backgrounded and is released on foreground return or session end. You can disconnect in the app or its connection notification; removing the app task also ends the session and its foreground service.
|
||||
|
||||
The app and its communication components use local file metadata, preferences and timing APIs for file transfer, settings and network timing, not for device fingerprinting or advertising tracking.
|
||||
|
||||
### 6. Access and deletion requests
|
||||
|
||||
You can manage local recent connections, saved previews and received files. Removing a recent connection also removes its preview and remembered remote connection password.
|
||||
|
||||
To request access to information, a data summary or deletion of records associated with your device in the default service, contact the email address below with the device ID and scope of your request. We verify the requester's authority to avoid unauthorized disclosure or deletion. Do not send access passwords, private keys or other sensitive credentials by email.
|
||||
|
||||
Deleting a server-side device identity invalidates that identity and its credentials; reconnecting may register a new device. Deleting database records does not mean that logs, backups or content already received by other devices are also deleted. For a self-hosted service, direct server-side data requests to its operator.
|
||||
|
||||
### 7. Policy changes and contact
|
||||
|
||||
This policy may be updated as features and services change. Updated text and its date will be published in the privacy policy. You can review the policy bundled with your app in its settings at any time.
|
||||
|
||||
For questions about this policy or the processing of personal information, contact:
|
||||
|
||||
Email: [junkun.di@hotmail.com](mailto:junkun.di@hotmail.com)
|
||||
@@ -1,236 +1,287 @@
|
||||
# CrossDesk
|
||||
<div align="center">
|
||||
<img src="apps/desktop/resources/linux/crossdesk_128x128.png" width="80" alt="CrossDesk 标志" />
|
||||
<h1>CrossDesk</h1>
|
||||
<p>轻量、跨平台的远程桌面,让电脑、浏览器和 iPhone / iPad 连接到同一张桌面。</p>
|
||||
<p><a href="https://www.crossdesk.cn/">官方网站</a> · <a href="https://github.com/kunkundi/crossdesk/releases">下载客户端</a> · <a href="https://web.crossdesk.cn/">打开 Web 客户端</a> · <a href="README_EN.md">English</a></p>
|
||||
</div>
|
||||
|
||||
<a href="https://hellogithub.com/repository/kunkundi/crossdesk" target="_blank"><img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=55d41367570345f1838e02fd12be7961&claim_uid=cb0OpZRrBuGVAfL&theme=small" alt="Featured|HelloGitHub" /></a>
|
||||
[]()
|
||||
[](https://www.gnu.org/licenses/lgpl-3.0)
|
||||
[](https://github.com/kunkundi/crossdesk/commits/web-client)
|
||||
[](https://github.com/kunkundi/crossdesk/actions)
|
||||
[](https://hub.docker.com/r/crossdesk/crossdesk-server/tags)
|
||||
[]()
|
||||
[]()
|
||||
[]()
|
||||
<div align="center">
|
||||
|
||||
[ [English](README_EN.md) / 中文 ]
|
||||
[](#download)
|
||||
[](https://github.com/kunkundi/crossdesk/releases)
|
||||
[](https://github.com/kunkundi/crossdesk/actions/workflows/build.yml)
|
||||
[](LICENSE)
|
||||
[](https://github.com/kunkundi/crossdesk/stargazers)
|
||||
|
||||
PC 客户端
|
||||

|
||||
</div>
|
||||
|
||||
CrossDesk 支持 Windows、macOS、Linux 之间的远程访问,也可从浏览器或原生 iOS / Android 客户端控制电脑。项目基于 [MiniRTC](https://github.com/kunkundi/minirtc),提供实时音视频传输、键鼠控制、文件传输与自托管能力,仍在持续开发中。
|
||||
|
||||
> 本文按当前仓库代码整理。截图展示当前 Slint 桌面界面,使用演示 ID、密码、在线状态和连接记录;缩略图来自公开页面;下载包的功能与系统要求请同时核对对应 Release 说明。原生 iOS 客户端的构建、签名方式见下文。
|
||||
|
||||
[界面预览](#preview) · [下载与安装](#download) · [快速连接](#quick-start) · [会话操作](#session) · [设置](#settings) · [iOS](#ios) · [Android](#android) · [自托管](#self-hosting) · [源码构建](docs/BUILD.md) · [常见问题](docs/FAQ.md)
|
||||
|
||||
<a id="preview"></a>
|
||||
|
||||
## 界面预览
|
||||
|
||||
### 桌面客户端
|
||||
|
||||
主窗口集中展示本机 ID、连接密码、远程连接入口和近期连接记录。
|
||||
|
||||
Web 客户端
|
||||
<p align="center">
|
||||
<img width="850" height="550" alt="6bddcbed47ffd4b9988a4037c7f4f524" src="https://github.com/user-attachments/assets/e44f73f9-24ac-46a3-a189-b7f8b6669881" />
|
||||
<img src="docs/images/desktop-main-zh.png" width="800" alt="当前桌面客户端示例:已连接服务器,三台在线设备均显示页面缩略图" />
|
||||
</p>
|
||||
|
||||
## 简介
|
||||
|
||||
CrossDesk 是一个轻量级的跨平台远程桌面软件,支持 Web 端控制远程设备。
|
||||
|
||||
CrossDesk 是 [MiniRTC](https://github.com/kunkundi/minirtc.git) 实时音视频传输库的实验性应用。MiniRTC 是一个轻量级的跨平台实时音视频传输库。它具有网络透传([RFC5245](https://datatracker.ietf.org/doc/html/rfc5245)),视频软硬编解码(H264/AV1),音频编解码([Opus](https://github.com/xiph/opus)),信令交互,网络拥塞控制,传输加密([SRTP](https://tools.ietf.org/html/rfc3711))等基础能力。
|
||||
|
||||
## 系统要求
|
||||
|
||||
| 平台 | 最低版本 |
|
||||
|----------------|---------------------------|
|
||||
| **Windows** | Windows 10 及以上 (64 位) |
|
||||
| **macOS** | macOS Intel 15.0 及以上 ( 大于 14.0 小于 15.0 的版本可自行编译实现兼容 )<br> macOS Apple Silicon 14.0 及以上 |
|
||||
| **Linux** | Ubuntu 22.04 及以上 ( 低版本可自行编译实现兼容 ) |
|
||||
|
||||
## 使用
|
||||
|
||||
在菜单栏“对端ID”处输入远端桌面的ID,点击“→”即可发起远程连接。
|
||||
|
||||

|
||||
|
||||
如果远端桌面设置了连接密码,则本端需填写正确的连接密码才能成功发起远程连接。
|
||||
|
||||

|
||||
|
||||
发起连接前,可在设置中自定义配置项,如语言、视频编码格式等。
|
||||

|
||||
|
||||
### Web 客户端
|
||||
浏览器访问 [CrossDesk Web Client](https://web.crossdesk.cn/)。
|
||||
输入 **远程设备 ID** 与 **密码**,点击连接即可接入远程设备。如图,**iOS Safari 远程控制 Win11**:
|
||||
|
||||
<img width="645" height="300" alt="_cgi-bin_mmwebwx-bin_webwxgetmsgimg__ MsgID=932911462648581698 skey=@crypt_1f5153b1_b550ca7462b5009ce03c991cca2a92a7 mmweb_appid=wx_webfilehelper" src="https://github.com/user-attachments/assets/a5109e6f-752c-4654-9f4e-7e161bddf43e" />
|
||||
在浏览器中输入远程设备 ID 和密码,无需在控制端安装桌面客户端。
|
||||
|
||||
## 如何编译
|
||||
<p align="center">
|
||||
<img src="docs/images/web-client.png" width="800" alt="CrossDesk Web 客户端当前连接首页" />
|
||||
</p>
|
||||
|
||||
依赖:
|
||||
- [xmake](https://xmake.io/#/guide/installation)
|
||||
- [cmake](https://cmake.org/download/)
|
||||
图片来源与更新方式见 [截图说明](docs/images/README.md)。
|
||||
|
||||
Linux环境下需安装以下包:
|
||||
## 主要功能
|
||||
|
||||
```
|
||||
sudo apt-get install -y software-properties-common git curl unzip build-essential libx11-dev libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libxcb-randr0-dev libxcb-xtest0-dev libxcb-xinerama0-dev libxcb-shape0-dev libxcb-xkb-dev libxcb-xfixes0-dev libxfixes-dev libxv-dev libxtst-dev libasound2-dev libsndio-dev libxcb-shm0-dev libasound2-dev libpulse-dev
|
||||
| 能力 | 当前支持 |
|
||||
| --- | --- |
|
||||
| 跨平台控制 | Windows / macOS / Linux 桌面互控;浏览器与原生 iOS / Android 作为控制端 |
|
||||
| 实时画面与声音 | H.264 / AV1、硬件编解码、远端声音播放;会话中可调整画质、30 / 60 fps 与画面偏好 |
|
||||
| 多设备与多显示器 | 近期连接、设备别名、会话标签与远端显示器切换 |
|
||||
| 输入与协作 | 键鼠输入、远端光标同步、组合键、文本剪贴板同步、文件传输 |
|
||||
| 网络与部署 | P2P 直连、TURN 中继与强制中继、SRTP 媒体加密、自托管信令与中继服务 |
|
||||
| 隐私屏 | 被连接时自动开启,或在会话工具栏切换;可用性取决于被控端系统与采集方式 |
|
||||
| Windows 锁屏控制 | 通过 CrossDesk Service 支持锁屏、登录界面及安全桌面的输入转发 |
|
||||
| Linux 无头运行 | 复用已有桌面和应用,或创建独立 Xvfb 虚拟桌面;终端控制台可查看状态、修改密码和设置,见 [运行说明](docs/HEADLESS.md) |
|
||||
|
||||
各客户端的入口和能力有所不同;桌面会话操作见下文,iOS 的具体功能见 [开发说明](apps/ios/README.md)。
|
||||
|
||||
<a id="download"></a>
|
||||
|
||||
## 下载与安装
|
||||
|
||||
前往 [GitHub Releases](https://github.com/kunkundi/crossdesk/releases) 或 [官方网站](https://www.crossdesk.cn/),按系统与 CPU 架构选择安装包。
|
||||
|
||||
| 平台 | 当前源码 / CI 基线 | 安装方式 |
|
||||
| --- | --- | --- |
|
||||
| Windows | Windows 10+,x64 | `.exe` 安装包;便携构建也受支持 |
|
||||
| macOS | macOS 14.0+,Intel / Apple Silicon | 选择 x64 或 arm64 的 `.pkg` |
|
||||
| Linux | Ubuntu 20.04+,amd64 / arm64,glibc 2.31 基线 | 普通版 / Xfce 虚拟桌面版 `.deb` |
|
||||
| iOS / iPadOS | iOS 16.0+,arm64 真机 | 原生客户端;使用 Xcode 构建并签名,CI 产物为未签名应用 |
|
||||
| Android | Android 8.0+,arm64 | 原生控制端;使用 Gradle 构建 APK,见 [开发说明](apps/android/README.md) |
|
||||
| Web | 支持 WebRTC 的浏览器 | 访问 [web.crossdesk.cn](https://web.crossdesk.cn/) |
|
||||
|
||||
Linux 每个架构提供两个可独立安装的包,**选择其中一个**:
|
||||
|
||||
| 安装包 | 适用场景 |
|
||||
| --- | --- |
|
||||
| `crossdesk-linux-<arch>-<version>.deb`(推荐) | 已有桌面的电脑;不会额外安装 Xfce 或 Xvfb |
|
||||
| `crossdesk-virtual-desktop-xfce-linux-<arch>-<version>.deb` | 需要创建独立桌面的服务器;APT 会额外安装 **Xfce、Xvfb 和 D-Bus 会话工具** |
|
||||
|
||||
普通版安装示例(将文件名替换为实际下载名称,arm64 选择对应架构):
|
||||
|
||||
```bash
|
||||
sudo apt install "./crossdesk-linux-amd64-<version>.deb"
|
||||
```
|
||||
|
||||
编译
|
||||
```
|
||||
git clone https://github.com/kunkundi/crossdesk.git
|
||||
如需虚拟桌面版,改为安装:
|
||||
|
||||
cd crossdesk
|
||||
|
||||
git submodule init
|
||||
|
||||
git submodule update
|
||||
|
||||
xmake b -vy crossdesk
|
||||
```
|
||||
编译选项
|
||||
```
|
||||
--USE_CUDA=true/false: 启用 CUDA 硬件编解码,默认不启用
|
||||
--CROSSDESK_VERSION=xxx: 指定 CrossDesk 的版本
|
||||
|
||||
# 示例
|
||||
xmake f --CROSSDESK_VERSION=1.0.0 --USE_CUDA=true
|
||||
```
|
||||
运行
|
||||
```
|
||||
xmake r crossdesk
|
||||
```bash
|
||||
sudo apt install "./crossdesk-virtual-desktop-xfce-linux-amd64-<version>.deb"
|
||||
```
|
||||
|
||||
### 无 CUDA 环境下的开发支持
|
||||
两个包包含相同的完整程序,互相替换并保留用户配置;普通版自行补齐依赖后也能创建虚拟桌面。安装虚拟桌面版不会自动启动会话或切换默认桌面,启动方法见 [Linux 无头运行](docs/HEADLESS.md)。应用更新的下载按钮会选择已安装的包类型。已有版本升级后不会自动删除先前安装的 Xfce。
|
||||
|
||||
对于**未安装 CUDA 环境的 Linux 开发者,如果希望编译后的成果物拥有硬件编解码能力**,这里提供了预配置的 [Ubuntu 22.04 Docker 镜像](https://hub.docker.com/r/crossdesk/ubuntu22.04)。该镜像内置必要的构建依赖,可在容器中开箱即用,无需额外配置即可直接编译项目。
|
||||
**macOS 首次运行:** 按应用提示,在“系统设置 → 隐私与安全性”中授予 CrossDesk **屏幕录制**(新系统可能显示为“屏幕与系统音频录制”)及 **辅助功能**权限,再按系统提示重新打开应用。前者用于捕获桌面,后者用于远程键鼠输入。
|
||||
|
||||
进入容器,下载工程后执行:
|
||||
```
|
||||
export CUDA_PATH=/usr/local/cuda
|
||||
export XMAKE_GLOBALDIR=/data
|
||||
<a id="quick-start"></a>
|
||||
|
||||
xmake f --USE_CUDA=true
|
||||
xmake b --root -vy crossdesk
|
||||
## 快速连接
|
||||
|
||||
### 从另一台电脑连接
|
||||
|
||||
1. **准备被控电脑。** 安装并运行 CrossDesk,等待底部显示“已连接服务器”。在左侧“本桌面”查看 **本机 ID** 和 **密码**,提供给控制端。
|
||||
2. **输入对端 ID。** 在控制端右侧“远程桌面 → 对端 ID”输入被控电脑的 ID,点击 **→**。
|
||||
3. **完成密码验证。** 按弹窗输入被控电脑当前的连接密码,确认后等待远程画面出现。需要保存密码时勾选“记住密码”。
|
||||
4. **再次连接。** 成功连接过的设备会出现在“近期连接”中,可通过卡片重连,也可编辑别名或删除记录。
|
||||
|
||||
本机密码旁的眼睛按钮用于显示 / 隐藏密码,刷新按钮用于生成新的随机密码,铅笔按钮用于手动修改。密码统一为 **6 位数字或英文字母**。修改或刷新时需保持连接服务器;等待修改成功、客户端重新连接后,再复制当前密码。已保存旧密码的控制端需重新输入。
|
||||
|
||||
### 从浏览器连接
|
||||
|
||||
1. 保持被控电脑上的 CrossDesk 运行,并确认已连接服务器。
|
||||
2. 打开 [Web 客户端](https://web.crossdesk.cn/),输入 **远程设备 ID** 和 **密码**,点击“连接”。
|
||||
3. 连接后使用页面提供的显示器、鼠标模式和键盘控件操作远端;手机和平板也可通过浏览器访问。
|
||||
|
||||
如果使用自建服务器,需要让控制端与被控端接入同一服务;Web 部署配置见 [CrossDesk Web Client](https://github.com/kunkundi/crossdesk-web-client)。
|
||||
|
||||
<a id="session"></a>
|
||||
|
||||
## 会话中的常用操作
|
||||
|
||||
远程窗口通过会话标签切换设备,控制栏提供以下操作;控制栏收起时先点击展开按钮。将鼠标悬停在图标上可查看提示。
|
||||
|
||||
| 入口 | 用途 |
|
||||
| --- | --- |
|
||||
| 显示器 | 切换远端显示器 |
|
||||
| 键盘 | 发送组合键;Windows 的 `Ctrl+Alt+Del` 依赖远端服务 |
|
||||
| 鼠标 | 控制 / 释放远端鼠标 |
|
||||
| 扬声器 | 播放声音 / 静音 |
|
||||
| 文件夹 | 选择文件发送到远端,并查看传输进度 |
|
||||
| 画面设置 | 在当前会话中调整画面质量、采集帧率与画面偏好 |
|
||||
| 网络状态 | 查看流量、丢包率、帧率、分辨率、直连 / 中继及加密状态 |
|
||||
| 隐私屏 | 开启或关闭被控电脑的隐私屏;悬停查看当前状态与可用操作 |
|
||||
| 全屏 | 进入 / 退出全屏 |
|
||||
| 断开连接 | 结束当前远程会话 |
|
||||
|
||||
桌面端可同步文本剪贴板。接收文件的位置可在“设置 → 文件保存路径”调整。关闭主窗口会隐藏窗口并保持程序运行;需要完全退出时使用系统托盘或菜单栏中的退出入口。
|
||||
|
||||
### 在会话中调整画面
|
||||
|
||||
连接成功后,点击工具栏中的 **画面设置**(滑杆图标),直接选择低 / 中 / 高画质、**30 / 60 fps**,以及帧率优先 / 画质优先 / 平衡。选项会发送给当前被控端,无需断开重连;实际画面效果取决于网络、设备与编码器能力。旧版被控端不支持时,菜单会提示并禁用选项。
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-stream-video-settings-zh.png" width="800" alt="当前远程会话的画面设置菜单:画面质量、采集帧率与画面偏好;背景为公开页面演示图" />
|
||||
</p>
|
||||
|
||||
<a id="settings"></a>
|
||||
|
||||
## 客户端设置与更新
|
||||
|
||||
点击主窗口右上角 **☰ → 设置**,修改后点击“确认”保存。编码与连接选项建议在建立连接前调整;会话进行中部分选项不可修改。设置列表可向下滚动,查看自托管、启动方式与文件保存路径。画质、帧率和画面偏好在远程会话工具栏中调整。
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-settings-zh.png" width="720" alt="当前客户端设置:编码格式、硬件编解码、中继、强制中继与自动隐私屏" />
|
||||
</p>
|
||||
|
||||
| 设置 | 说明 |
|
||||
| --- | --- |
|
||||
| 语言 | 中文、English、Русский |
|
||||
| 采集方式(Windows) | 自动 / DXGI / WGC / GDI;无显示器主机使用“自动”启用自动适配 |
|
||||
| 视频编码格式 | H.264 / AV1;硬件编解码是否可用取决于平台、硬件与构建选项 |
|
||||
| 启用中继服务 | 允许借助 TURN 中继建立连接;P2P 连接失败时先检查此项 |
|
||||
| 强制中继连接 | 启用中继服务后可勾选,让连接通过中继建立;关闭中继服务会同时关闭此项 |
|
||||
| 保存远程画面预览 | 默认开启,保存远程画面预览;关闭后缩略图区域显示被控端平台,并清除已有预览,保留连接记录和密码 |
|
||||
| 被连接时开启隐私屏 | 设置本机被远程连接时是否自动启用隐私屏;会话中可从控制端工具栏切换 |
|
||||
| 自托管配置 | 填写服务器地址和信令服务端口,并勾选启用 |
|
||||
| 开机自启 / 启用守护进程 | 调整启动与进程守护行为,按界面提示重启后生效 |
|
||||
| 文件保存路径 | 选择接收文件的目录 |
|
||||
|
||||
### 检查更新
|
||||
|
||||
客户端启动后会在后台检查版本,发现新版本时自动弹出更新提示,可查看更新说明并前往下载页面。关闭提示后,本次运行中的后台检查不会再次弹窗,主窗口菜单入口仍会显示更新提示;重新启动客户端后,如仍有新版本则再次提示。打开 **☰ → 关于** 可查看版本;有新版本时,点击版本信息下方的 **更新日志** 可再次打开更新提示,也可点击 **检查更新** 手动检查。
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-about-zh.png" width="720" alt="关于窗口与检查更新按钮,版本号和检查结果为演示数据" />
|
||||
</p>
|
||||
|
||||
<a id="ios"></a>
|
||||
|
||||
## 原生 iOS / iPadOS 客户端
|
||||
|
||||
仓库的 [`apps/ios`](apps/ios/README.md) 提供原生控制端,与桌面端使用同一套 MiniRTC 协议。它可以控制远端电脑;当前不提供将 iPhone / iPad 作为被控桌面的功能。
|
||||
|
||||
1. 按 [iOS 开发说明](apps/ios/README.md) 使用 Xcode 构建并签名,安装到 iOS 16+ 的真机。
|
||||
2. 在首页输入对端 ID,点击连接并填写密码;成功连接后可从“最近连接”中重连。
|
||||
3. 在设置中选择鼠标模式:**相对位置**像触控板一样移动光标,**绝对位置**将触摸位置直接映射到远端画面。
|
||||
4. 点击悬浮图标展开菜单,可切换显示器、显示键盘、控制声音或发送文件。收到的文件位于应用的 `Documents/Received`,可通过传输状态旁的分享按钮导出。
|
||||
|
||||
当前支持接收远端文本到 iOS 剪贴板;界面暂未提供主动发送本机剪贴板的按钮。
|
||||
|
||||
当前支持单指点击、双指右键、长按拖动与捏合缩放;缩放后的双指平移用于移动视图。原生端与浏览器端分别维护,使用入口和手势可能不同。
|
||||
|
||||
<a id="android"></a>
|
||||
|
||||
## 原生 Android 控制端
|
||||
|
||||
[`apps/android`](apps/android/README.md) 提供独立 Android Studio / Gradle 工程,复用 MiniRTC 和桌面键鼠协议。支持连接电脑、H.264 / AV1 画面、声音、触控/外接键鼠、多屏切换和文本剪贴板。当前面向 Android 8.0+ arm64 设备,使用软件解码;尚未提供手机被控、文件传输和 iOS 全部附加功能。
|
||||
|
||||
按 [Android 开发说明](apps/android/README.md) 构建并安装 APK,在首页填写电脑端的设备 ID 和密码即可连接。长按右键、双指滚动,横屏可扩大画面;切换到后台会结束会话。
|
||||
|
||||
<a id="windows-service"></a>
|
||||
|
||||
## Windows 锁屏与登录界面
|
||||
|
||||
**CrossDesk Service**(服务名 `CrossDeskService`)提供锁屏、登录、凭据输入及安全桌面的状态上报、`Ctrl+Alt+Del` 发送和键鼠输入转发。
|
||||
|
||||
安装版默认注册按需启动的服务,客户端启动时尝试启动它;未启用无人值守时,本机没有 CrossDesk 客户端进程后服务会自动退出。便携版可在提示窗口或“设置 → 锁屏控制服务”中安装服务,需要管理员权限。
|
||||
|
||||
Windows 的“开机自启”在当前用户登录后启动客户端。安装版使用以最高权限运行的登录计划任务,后续登录无需再次确认 UAC;便携版和 Debug 构建使用当前用户的普通启动项。升级安装版或手动启动新版时,会自动迁移指向该程序的旧启动项。关闭自启会删除相应注册。登录前远控需要另外启用下面的无人值守模式。
|
||||
|
||||
### 开机后尚未登录时远控
|
||||
|
||||
安装版支持独立的无人值守被控端。在完整安装目录中打开**管理员 PowerShell**,一次性启用:
|
||||
|
||||
```powershell
|
||||
.\CrossDesk.exe --unattended-enable
|
||||
# 等待联网注册后,查看独立设备 ID、密码和 online 状态
|
||||
.\CrossDesk.exe --unattended-status
|
||||
```
|
||||
|
||||
对于**未安装 CUDA 环境的 Windows 开发者**,执行下面的命令安装 CUDA 编译环境:
|
||||
```
|
||||
xmake require -vy "cuda 12.6.3"
|
||||
```
|
||||
安装完成后执行:
|
||||
```
|
||||
xmake require --info "cuda 12.6.3"
|
||||
```
|
||||
输出如下:
|
||||
使用返回的 `device_id` 和 `password` 从另一台设备连接。首次启用时复制当前客户端的服务器和编码设置,单独生成无人值守凭据;它与普通客户端的设备 ID 不同,重启、注销和重新启用时保留。后续执行启用命令会复用机器配置,不会覆盖它。自建服务器的根证书需要安装到本地计算机的信任存储中。
|
||||
|
||||
<img width="860" height="226" alt="Image" src="https://github.com/user-attachments/assets/999ac365-581a-4b9a-806e-05eb3e4cf44d" />
|
||||
启用后,`CrossDeskService` 改为系统启动时自动运行,无需 Windows 自动登录,也不需要保存 Windows 登录密码。服务以 SYSTEM 身份在当前控制台会话中启动无界面的被控进程,复用登录界面抓屏、键鼠及 `Ctrl+Alt+Del` 支持。用户登录、锁屏和关闭普通客户端不会停止它;注销、切换用户或进程崩溃后服务会重新拉起,期间连接可能中断,需要重新连接同一设备 ID。启动时网络尚未就绪会继续重试。
|
||||
|
||||
根据上述输出获取到 CUDA 的安装目录,即 installdir 指向的位置。将 CUDA_PATH 加入系统环境变量,或在终端中输入:
|
||||
```
|
||||
set CUDA_PATH=path_to_cuda_installdir
|
||||
```
|
||||
重新执行:
|
||||
```
|
||||
xmake f --USE_CUDA=true
|
||||
xmake b -vy crossdesk
|
||||
无人值守模式提供画面、键鼠、多屏切换和安全桌面控制;不提供声音、文件传输、剪贴板或隐私遮罩。便携版和 Debug 构建不能启用此模式。设置和凭据位于 `%ProgramData%\CrossDeskUnattended`,只允许 SYSTEM 和管理员访问;日志位于其 `logs` 子目录。
|
||||
|
||||
```powershell
|
||||
# 停止无人值守被控端,并恢复服务按需启动
|
||||
.\CrossDesk.exe --unattended-disable
|
||||
```
|
||||
|
||||
#### 注意
|
||||
运行时如果客户端状态栏显示 **未连接服务器**,请先在 [CrossDesk 官方网站](https://www.crossdesk.cn/) 安装客户端,以便在环境中安装所需的证书文件。
|
||||
关闭普通“开机自启”不会关闭无人值守模式。禁用或卸载服务会取消无人值守启动,但保留受保护的机器配置;若需彻底清除凭据,在服务停止后由管理员删除该目录。
|
||||
|
||||
<img width="256" height="120" alt="image" src="https://github.com/user-attachments/assets/1812f7d6-516b-4b4f-8a3d-98bee505cc5a" />
|
||||
<details>
|
||||
<summary>手动部署与服务管理命令</summary>
|
||||
|
||||
## 关于 Xmake
|
||||
保留完整安装目录;自行部署构建产物时,将 `CrossDesk.exe`、`crossdesk_service.exe`、`crossdesk_session_helper.exe` 及同次构建输出的全部 `.dll` 放在同一目录。在该目录打开管理员 PowerShell,按需执行:
|
||||
|
||||
#### 安装 Xmake
|
||||
使用 curl:
|
||||
```
|
||||
curl -fsSL https://xmake.io/shget.text | bash
|
||||
```
|
||||
使用 wget:
|
||||
```
|
||||
wget https://xmake.io/shget.text -O - | bash
|
||||
```
|
||||
使用 powershell:
|
||||
```
|
||||
irm https://xmake.io/psget.text | iex
|
||||
```powershell
|
||||
.\CrossDesk.exe --service-install
|
||||
.\CrossDesk.exe --service-start
|
||||
.\CrossDesk.exe --service-status
|
||||
.\CrossDesk.exe --service-ping
|
||||
# 停止或卸载服务
|
||||
.\CrossDesk.exe --service-stop
|
||||
.\CrossDesk.exe --service-uninstall
|
||||
```
|
||||
|
||||
#### 编译选项
|
||||
```
|
||||
# 切换编译模式
|
||||
xmake f -m debug/release
|
||||
</details>
|
||||
|
||||
# 可选编译参数
|
||||
-r :重新构建目标
|
||||
-v :显示详细的构建日志
|
||||
-y :自动确认提示
|
||||
出现“远端 Windows 服务不可用”时,检查被控电脑的安装和服务状态;普通桌面连接仍可使用,受保护界面的控制能力会受限。
|
||||
|
||||
# 示例
|
||||
xmake b -vy crossdesk
|
||||
```
|
||||
|
||||
#### 运行选项
|
||||
```
|
||||
# 使用调试模式运行
|
||||
xmake r -d crossdesk
|
||||
```
|
||||
更多使用方法可参考 [Xmake官方文档](https://xmake.io/guide/quick-start.html) 。
|
||||
<a id="self-hosting"></a>
|
||||
|
||||
## 自托管服务器
|
||||
推荐使用Docker部署CrossDesk Server。
|
||||
```
|
||||
sudo docker run -d \
|
||||
--name crossdesk_server \
|
||||
--network host \
|
||||
-e EXTERNAL_IP=xxx.xxx.xxx.xxx \
|
||||
-e INTERNAL_IP=xxx.xxx.xxx.xxx \
|
||||
-e CROSSDESK_SERVER_PORT=xxxx \
|
||||
-e COTURN_PORT=xxxx \
|
||||
-e MIN_PORT=xxxxx \
|
||||
-e MAX_PORT=xxxxx \
|
||||
-v /var/lib/crossdesk:/var/lib/crossdesk \
|
||||
-v /var/log/crossdesk:/var/log/crossdesk \
|
||||
crossdesk/crossdesk-server:v1.1.2
|
||||
```
|
||||
|
||||
上述命令中,用户需注意的参数如下:
|
||||
可自行部署信令服务与 TURN 中继,并在桌面客户端 **☰ → 设置 → 自托管配置** 中填写连接信息。控制端与被控端都需要启用同一套配置。
|
||||
|
||||
**参数**
|
||||
- EXTERNAL_IP:服务器公网 IP , 对应 CrossDesk 客户端**自托管服务器配置**中填写的**服务器地址**
|
||||
- INTERNAL_IP:服务器内网 IP
|
||||
- CROSSDESK_SERVER_PORT:自托管服务使用的端口,对应 CrossDesk 客户端**自托管服务器配置**中填写的**服务器端口**
|
||||
- COTURN_PORT: COTURN 服务使用的端口, 对应 CrossDesk 客户端**自托管服务器配置**中填写的**中继服务端口**
|
||||
- MIN_PORT/MAX_PORT:COTURN 服务使用的端口范围,例如:MIN_PORT=50000, MAX_PORT=60000,范围可根据客户端数量调整。
|
||||
- `-v /var/lib/crossdesk:/var/lib/crossdesk`:持久化数据库和证书文件到宿主机
|
||||
- `-v /var/log/crossdesk:/var/log/crossdesk`:持久化日志文件到宿主机
|
||||
-
|
||||
**注意**:
|
||||
- **服务器需开放端口:3478/udp,3478/tcp,MIN_PORT-MAX_PORT/udp,CROSSDESK_SERVER_PORT/tcp。**
|
||||
- 如果不挂载 volume,容器删除后数据会丢失
|
||||
- 证书文件会在首次启动时自动生成并持久化到宿主机的 `/var/lib/crossdesk/certs` 路径下
|
||||
- 数据库文件会自动创建并持久化到宿主机的 `/var/lib/crossdesk/db/crossdesk-server.db` 路径下
|
||||
- 日志文件会自动创建并持久化到宿主机的 `/var/log/crossdesk/` 路径下
|
||||
- [自托管指南](docs/SELF_HOSTING.md):当前 Compose 部署入口、客户端设置、证书信任与排查。
|
||||
- [CrossDesk Server](https://github.com/kunkundi/crossdesk-server):服务端源码与发布配置。
|
||||
- [CrossDesk Web Client](https://github.com/kunkundi/crossdesk-web-client):浏览器端源码与自托管说明。
|
||||
|
||||
**权限注意**:如果 Docker 自动创建的目录权限不足(属于 root),容器内用户无法写入,会导致:
|
||||
- 证书生成失败,容器启动脚本会报错退出
|
||||
- 数据库目录创建失败,程序会抛出异常并崩溃
|
||||
- 日志目录创建失败,日志文件无法写入(但程序可能继续运行)
|
||||
|
||||
**解决方案**:在启动容器前手动设置权限:
|
||||
```bash
|
||||
sudo mkdir -p /var/lib/crossdesk /var/log/crossdesk
|
||||
sudo chown -R $(id -u):$(id -g) /var/lib/crossdesk /var/log/crossdesk
|
||||
```
|
||||
## 开发与反馈
|
||||
|
||||
## 证书文件
|
||||
在宿主机的 `/var/lib/crossdesk/certs` 路径下可找到证书文件 `crossdesk.cn_root.crt`,下载到你的客户端主机,并在客户端的**自托管服务器设置**中选择相应的**证书文件路径**。
|
||||
- [源码构建](docs/BUILD.md):Windows、macOS、Linux、可选编译参数与打包。
|
||||
- [iOS 开发说明](apps/ios/README.md):原生端构建和真机验证。
|
||||
- [Android 开发说明](apps/android/README.md):APK 构建、安装与模拟器验证。
|
||||
- [GUI 架构](docs/gui-architecture.md):桌面 UI、平台实现与工程结构。
|
||||
- [常见问题](docs/FAQ.md):连接失败、黑屏、文件位置与编译问题。
|
||||
- [提交问题](https://github.com/kunkundi/crossdesk/issues):请附上两端系统、客户端版本、连接方式和可复现步骤。
|
||||
|
||||
### 客户端
|
||||
1. 点击右上角设置进入设置页面。<br>
|
||||
<img width="600" height="210" alt="image" src="https://github.com/user-attachments/assets/6431131d-b32a-4726-8783-6788f47baa3b" /><br><br>
|
||||
## 致谢与许可
|
||||
|
||||
3. 点击点击**自托管服务器配置**。<br><br>
|
||||
<img width="600" height="160" alt="image" src="https://github.com/user-attachments/assets/24c761a3-1985-4d7e-84be-787383c2afb8" /><br><br>
|
||||
感谢 [HelloGitHub](https://hellogithub.com/)、[阮一峰的科技爱好者周刊](https://github.com/ruanyf/weekly) 与 [LinuxDo](https://linux.do) 社区的推荐、交流与支持。
|
||||
|
||||
5. 在**证书文件路径**选择框中找到 **crossdesk.cn_root.crt** 的存放路径,选中 **crossdesk.cn_root.crt**,点击确认。<br><br>
|
||||
<img width="600" height="220" alt="image" src="https://github.com/user-attachments/assets/4af7cd3a-c72e-44fb-b032-30e050019c2a" /><br><br>
|
||||
CrossDesk 使用 [GPL-3.0](LICENSE) 许可。隐私说明见 [隐私政策](PRIVACY.md#中文)。
|
||||
|
||||
7. 勾选使用**自托管服务器配置**,点击确认配置生效。<br><br>
|
||||
<img width="600" height="160" alt="image" src="https://github.com/user-attachments/assets/1e455dc3-4087-4f37-a544-1ff9f8789383" /><br><br>
|
||||
### Code signing policy
|
||||
|
||||
### Web 客户端
|
||||
详情见项目 [CrossDesk Web Client](https://github.com/kunkundi/crossdesk-web-client)。
|
||||
CrossDesk 使用 SignPath.io 为本仓库构建的官方 Windows 发布包提供代码签名。
|
||||
|
||||
# 常见问题
|
||||
见 [常见问题](https://github.com/kunkundi/crossdesk/blob/self-hosted-server/docs/FAQ.md) 。
|
||||
**Free code signing provided by [SignPath.io](https://signpath.io/), certificate by [SignPath Foundation](https://signpath.org/).**
|
||||
|
||||
- **Committers and reviewers(代码提交与审核):** [kunkundi](https://github.com/kunkundi)
|
||||
- **Approvers(签名审批):** [kunkundi](https://github.com/kunkundi)
|
||||
|
||||
+252
-218
@@ -1,249 +1,283 @@
|
||||
# CrossDesk
|
||||
<div align="center">
|
||||
<img src="apps/desktop/resources/linux/crossdesk_128x128.png" width="80" alt="CrossDesk logo" />
|
||||
<h1>CrossDesk</h1>
|
||||
<p>A lightweight, cross-platform remote desktop for computers, browsers, and iPhone / iPad.</p>
|
||||
<p><a href="https://www.crossdesk.cn/">Website</a> · <a href="https://github.com/kunkundi/crossdesk/releases">Download</a> · <a href="https://web.crossdesk.cn/">Open Web Client</a> · <a href="README.md">中文</a></p>
|
||||
</div>
|
||||
|
||||
<a href="https://hellogithub.com/repository/kunkundi/crossdesk" target="_blank"><img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=55d41367570345f1838e02fd12be7961&claim_uid=cb0OpZRrBuGVAfL&theme=small" alt="Featured|HelloGitHub" /></a>
|
||||
[]()
|
||||
[](https://www.gnu.org/licenses/lgpl-3.0)
|
||||
[](https://github.com/kunkundi/crossdesk/commits/web-client)
|
||||
[](https://github.com/kunkundi/crossdesk/actions)
|
||||
[](https://hub.docker.com/r/crossdesk/crossdesk-server/tags)
|
||||
[]()
|
||||
[]()
|
||||
[]()
|
||||
<div align="center">
|
||||
|
||||
[ [中文](README.md) / English ]
|
||||
[](#download)
|
||||
[](https://github.com/kunkundi/crossdesk/releases)
|
||||
[](https://github.com/kunkundi/crossdesk/actions/workflows/build.yml)
|
||||
[](LICENSE)
|
||||
[](https://github.com/kunkundi/crossdesk/stargazers)
|
||||
|
||||
PC Client
|
||||

|
||||
</div>
|
||||
|
||||
CrossDesk connects Windows, macOS, and Linux desktops, with browser and native iOS / Android clients for controlling computers. Built on [MiniRTC](https://github.com/kunkundi/minirtc), it supports real-time video and audio, keyboard and mouse control, file transfer, and self-hosting. The project is under active development.
|
||||
|
||||
> This guide follows the current repository source. Desktop screenshots render the current Slint UI with sample IDs, passwords, online statuses, and recent devices; thumbnails show public pages. Check each release's notes for the features and requirements of its binaries. Native iOS build and signing instructions are below.
|
||||
|
||||
[Preview](#preview) · [Download](#download) · [Quick start](#quick-start) · [Session controls](#session) · [Settings](#settings) · [iOS](#ios) · [Self-hosting](#self-hosting) · [Build](docs/BUILD_EN.md) · [FAQ](docs/FAQ.md#english)
|
||||
|
||||
<a id="preview"></a>
|
||||
|
||||
## Preview
|
||||
|
||||
### Desktop client
|
||||
|
||||
The main window brings together your device ID, connection password, remote connection entry, and recent devices.
|
||||
|
||||
Web Client
|
||||
<p align="center">
|
||||
<img width="850" height="550" alt="6bddcbed47ffd4b9988a4037c7f4f524" src="https://github.com/user-attachments/assets/e44f73f9-24ac-46a3-a189-b7f8b6669881" />
|
||||
<img src="docs/images/desktop-main-en.png" width="800" alt="Current desktop UI example showing a connected server and three online devices with page thumbnails" />
|
||||
</p>
|
||||
|
||||
# Intro
|
||||
### Web client
|
||||
|
||||
CrossDesk is a lightweight cross-platform remote desktop software.
|
||||
Enter a remote device ID and password in your browser without installing the desktop app on the controlling device.
|
||||
|
||||
CrossDesk is an experimental application of [MiniRTC](https://github.com/kunkundi/minirtc.git), a lightweight cross-platform real-time audio and video transmission library. MiniRTC provides fundamental capabilities including network traversal ([RFC5245](https://datatracker.ietf.org/doc/html/rfc5245)), video software/hardware encoding and decoding (H264/AV1), audio encoding/decoding ([Opus](https://github.com/xiph/opus)), signaling interaction, network congestion control, and transmission encryption ([SRTP](https://tools.ietf.org/html/rfc3711)).
|
||||
<p align="center">
|
||||
<img src="docs/images/web-client.png" width="800" alt="Current CrossDesk Web Client connection page in Chinese" />
|
||||
</p>
|
||||
|
||||
## System Requirements
|
||||
See the [screenshot notes](docs/images/README.md) for image sources and refresh instructions.
|
||||
|
||||
| Platform | Minimum Version |
|
||||
|-----------|-----------------|
|
||||
| **Windows** | Windows 10 or later (64-bit) |
|
||||
| **macOS** | macOS Intel 15.0 or later *(versions between 14.0 and 15.0 can be built manually for compatibility)*<br>macOS Apple Silicon 14.0 or later |
|
||||
| **Linux** | Ubuntu 22.04 or later *(older versions can be built manually for compatibility)* |
|
||||
## Features
|
||||
|
||||
| Capability | Current support |
|
||||
| --- | --- |
|
||||
| Cross-platform control | Windows / macOS / Linux desktop control; browser and native iOS / Android controllers |
|
||||
| Live video and audio | H.264 / AV1, hardware codecs, and remote audio; adjust quality, 30 / 60 fps, and video preference during a session |
|
||||
| Devices and displays | Recent connections, device aliases, session tabs, and remote display switching |
|
||||
| Input and sharing | Keyboard/mouse input, remote cursor synchronization, shortcuts, text clipboard synchronization, and file transfer |
|
||||
| Networking and deployment | Direct P2P connections, TURN relay and forced relay, SRTP media encryption, and self-hosted signaling/relay services |
|
||||
| Privacy screen | Enable automatically when connected to, or toggle from the session toolbar; availability depends on the host OS and capture method |
|
||||
| Windows protected desktops | CrossDesk Service forwards input on lock screens, sign-in screens, and secure desktops |
|
||||
| Linux headless operation | Reuse existing desktops and applications or create separate Xvfb desktops; use the terminal console to check status and change passwords or settings; see [setup](docs/HEADLESS_EN.md) |
|
||||
|
||||
## Usage
|
||||
Controls and capabilities vary by client. Desktop controls are described below; see the [iOS guide](apps/ios/README.md) for native mobile features.
|
||||
|
||||
Enter the remote desktop ID in the menu bar’s “Remote ID” field and click “→” to initiate a remote connection.
|
||||
<a id="download"></a>
|
||||
|
||||

|
||||
## Download and install
|
||||
|
||||
If the remote desktop requires a connection password, you must enter the correct password on your side to successfully establish the connection.
|
||||
Choose a package matching your OS and CPU architecture from [GitHub Releases](https://github.com/kunkundi/crossdesk/releases) or the [website](https://www.crossdesk.cn/).
|
||||
|
||||

|
||||
| Platform | Current source / CI baseline | Installation |
|
||||
| --- | --- | --- |
|
||||
| Windows | Windows 10+, x64 | `.exe` installer; portable builds are also supported |
|
||||
| macOS | macOS 14.0+, Intel / Apple Silicon | x64 or arm64 `.pkg` |
|
||||
| Linux | Ubuntu 20.04+, amd64 / arm64, glibc 2.31 baseline | Standard / Xfce virtual desktop `.deb` |
|
||||
| iOS / iPadOS | iOS 16.0+, arm64 physical device | Native controller; build and sign with Xcode, or sign the unsigned CI app |
|
||||
| Android | Android 8.0+, arm64 | Native controller; build an APK with Gradle ([guide](apps/android/README.md)) |
|
||||
| Web | A WebRTC-capable browser | Open [web.crossdesk.cn](https://web.crossdesk.cn/) |
|
||||
|
||||
Before connecting, you can customize configuration options in the settings, such as language and video encoding format.
|
||||
Linux provides two standalone packages per architecture. **Choose one**:
|
||||
|
||||

|
||||
| Package | Intended use |
|
||||
| --- | --- |
|
||||
| `crossdesk-linux-<arch>-<version>.deb` (recommended) | Computers with an existing desktop; does not install Xfce or Xvfb |
|
||||
| `crossdesk-virtual-desktop-xfce-linux-<arch>-<version>.deb` | Servers needing an independent desktop; APT additionally installs **Xfce, Xvfb and D-Bus session tools** |
|
||||
|
||||
### Web Client
|
||||
To install the standard package, replace the example filename with your download (use arm64 for that architecture):
|
||||
|
||||
Visit [CrossDesk Web Client](https://web.crossdesk.cn/).
|
||||
Enter the **Remote Device ID** and **Password**, then click Connect to access the remote device. As shown, **iOS Safari remotely controlling Windows 11**:
|
||||
|
||||
<img width="645" height="300" alt="_cgi-bin_mmwebwx-bin_webwxgetmsgimg__ MsgID=932911462648581698 skey=@crypt_1f5153b1_b550ca7462b5009ce03c991cca2a92a7 mmweb_appid=wx_webfilehelper" src="https://github.com/user-attachments/assets/a5109e6f-752c-4654-9f4e-7e161bddf43e" />
|
||||
|
||||
## How to build
|
||||
|
||||
Requirements:
|
||||
- [xmake](https://xmake.io/#/guide/installation)
|
||||
- [cmake](https://cmake.org/download/)
|
||||
|
||||
Following packages need to be installed on Linux:
|
||||
|
||||
```
|
||||
sudo apt-get install -y software-properties-common git curl unzip build-essential libx11-dev libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libxcb-randr0-dev libxcb-xtest0-dev libxcb-xinerama0-dev libxcb-shape0-dev libxcb-xkb-dev libxcb-xfixes0-dev libxfixes-dev libxv-dev libxtst-dev libasound2-dev libsndio-dev libxcb-shm0-dev libasound2-dev libpulse-dev
|
||||
```
|
||||
|
||||
Build:
|
||||
```
|
||||
git clone https://github.com/kunkundi/crossdesk.git
|
||||
|
||||
cd crossdesk
|
||||
|
||||
git submodule init
|
||||
|
||||
git submodule update
|
||||
|
||||
xmake b -vy crossdesk
|
||||
```
|
||||
Build options:
|
||||
```
|
||||
--USE_CUDA=true/false: enable CUDA acceleration codec, default: false
|
||||
--CROSSDESK_VERSION=xxx: set the version number
|
||||
|
||||
# example:
|
||||
xmake f --CROSSDESK_VERSION=1.0.0 --USE_CUDA=true
|
||||
```
|
||||
Run:
|
||||
```
|
||||
xmake r crossdesk
|
||||
```
|
||||
|
||||
#### Development Without CUDA Environment
|
||||
|
||||
For **Linux developers who do not have a CUDA environment installed and want to enable hardware codec feature**, a preconfigured [Ubuntu 22.04 Docker image](https://hub.docker.com/r/crossdesk/ubuntu22.04) is provided.
|
||||
This image comes with all required build dependencies and allows you to build the project directly inside the container without any additional setup.
|
||||
|
||||
After entering the container, download the project and run:
|
||||
```
|
||||
export CUDA_PATH=/usr/local/cuda
|
||||
export XMAKE_GLOBALDIR=/data
|
||||
|
||||
xmake f --USE_CUDA=true
|
||||
xmake b --root -vy crossdesk
|
||||
```
|
||||
|
||||
For **Windows developers without a CUDA environment** installed, run the following command to install the CUDA build environment:
|
||||
```
|
||||
xmake require -vy "cuda 12.6.3"
|
||||
```
|
||||
After the installation is complete, execute:
|
||||
```
|
||||
xmake require --info "cuda 12.6.3"
|
||||
```
|
||||
The output will look like this:
|
||||
|
||||
<img width="860" height="226" alt="Image" src="https://github.com/user-attachments/assets/999ac365-581a-4b9a-806e-05eb3e4cf44d" />
|
||||
|
||||
From the output above, locate the CUDA installation directory — this is the path pointed to by installdir.
|
||||
Add this path to your system environment variable CUDA_PATH, or set it in the terminal using:
|
||||
```
|
||||
set CUDA_PATH=path_to_cuda_installdir:
|
||||
```
|
||||
Then re-run:
|
||||
```
|
||||
xmake f --USE_CUDA=true
|
||||
xmake b -vy crossdesk
|
||||
```
|
||||
|
||||
#### Notice
|
||||
If the client status bar shows **Disconnected** during runtime, please first install the client from the [CrossDesk official website](https://www.crossdesk.cn/) to ensure the required certificate files are available in the environment.
|
||||
|
||||
<img width="256" height="120" alt="image" src="https://github.com/user-attachments/assets/1812f7d6-516b-4b4f-8a3d-98bee505cc5a" />
|
||||
|
||||
## About Xmake
|
||||
#### Installing Xmake
|
||||
|
||||
You can install Xmake using one of the following methods:
|
||||
|
||||
Using curl:
|
||||
```
|
||||
curl -fsSL https://xmake.io/shget.text | bash
|
||||
```
|
||||
Using wget:
|
||||
```
|
||||
wget https://xmake.io/shget.text -O - | bash
|
||||
```
|
||||
Using powershell:
|
||||
```
|
||||
irm https://xmake.io/psget.text | iex
|
||||
```
|
||||
|
||||
#### Build Options
|
||||
```
|
||||
# Switch build mode
|
||||
xmake f -m debug/release
|
||||
|
||||
# Optional build parameters
|
||||
-r : Rebuild the target
|
||||
-v : Show detailed build logs
|
||||
-y : Automatically confirm prompts
|
||||
|
||||
# Example
|
||||
xmake b -vy crossdesk
|
||||
```
|
||||
|
||||
#### Run Options
|
||||
```
|
||||
# Run in debug mode
|
||||
xmake r -d crossdesk
|
||||
```
|
||||
|
||||
For more information, please refer to the [official Xmake documentation](https://xmake.io/guide/quick-start.html) .
|
||||
|
||||
## Self-Hosted Server
|
||||
It is recommended to deploy CrossDesk Server using Docker.
|
||||
```
|
||||
sudo docker run -d \
|
||||
--name crossdesk_server \
|
||||
--network host \
|
||||
-e EXTERNAL_IP=xxx.xxx.xxx.xxx \
|
||||
-e INTERNAL_IP=xxx.xxx.xxx.xxx \
|
||||
-e CROSSDESK_SERVER_PORT=xxxx \
|
||||
-e COTURN_PORT=xxxx \
|
||||
-e MIN_PORT=xxxxx \
|
||||
-e MAX_PORT=xxxxx \
|
||||
-v /var/lib/crossdesk:/var/lib/crossdesk \
|
||||
-v /var/log/crossdesk:/var/log/crossdesk \
|
||||
crossdesk/crossdesk-server:v1.1.2
|
||||
```
|
||||
|
||||
The parameters you need to pay attention to are as follows:
|
||||
|
||||
**Parameters**
|
||||
- **EXTERNAL_IP**: The server’s public IP. This corresponds to **Server Address** in the CrossDesk client’s **Self-Hosted Server Configuration**.
|
||||
- **INTERNAL_IP**: The server’s internal IP.
|
||||
- **CROSSDESK_SERVER_PORT**: The port used by the self-hosted service. This corresponds to **Server Port** in the CrossDesk client’s **Self-Hosted Server Configuration**.
|
||||
- **COTURN_PORT**: The port used by the COTURN service. This corresponds to **Relay Service Port** in the CrossDesk client’s **Self-Hosted Server Configuration**.
|
||||
- **MIN_PORT / MAX_PORT**: The port range used by the COTURN service. Example: `MIN_PORT=50000`, `MAX_PORT=60000`. Adjust the range depending on the number of clients.
|
||||
- `-v /var/lib/crossdesk:/var/lib/crossdesk`: Persists database and certificate files on the host machine.
|
||||
- `-v /var/log/crossdesk:/var/log/crossdesk`: Persists log files on the host machine.
|
||||
|
||||
**Notes**
|
||||
- **The server must open the following ports: 3478/udp, 3478/tcp, MIN_PORT–MAX_PORT/udp, and CROSSDESK_SERVER_PORT/tcp.**
|
||||
- If you don’t mount volumes, all data will be lost when the container is removed.
|
||||
- Certificate files will be automatically generated on first startup and persisted to the host at `/var/lib/crossdesk/certs`.
|
||||
- The database file will be automatically created and stored at `/var/lib/crossdesk/db/crossdesk-server.db`.
|
||||
- Log files will be created and stored at `/var/log/crossdesk/`.
|
||||
|
||||
**Permission Notice**
|
||||
If the directories automatically created by Docker belong to root and have insufficient write permissions, the container user may not be able to write to them. This can cause:
|
||||
- Certificate generation failure, leading to startup script errors and container exit.
|
||||
- Database directory creation failure, causing the program to throw exceptions and crash.
|
||||
- Log directory creation failure, preventing logs from being written (though the program may continue running).
|
||||
|
||||
**Solution:** Manually set permissions before starting the container:
|
||||
```bash
|
||||
sudo mkdir -p /var/lib/crossdesk /var/log/crossdesk
|
||||
sudo chown -R $(id -u):$(id -g) /var/lib/crossdesk /var/log/crossdesk
|
||||
sudo apt install "./crossdesk-linux-amd64-<version>.deb"
|
||||
```
|
||||
|
||||
### Certificate Files
|
||||
You can find the certificate file `crossdesk.cn_root.crt` at `/var/lib/crossdesk/certs` on the host machine.
|
||||
Download it to your client device and select it in the **Certificate File Path** field under the CrossDesk client’s **Self-Hosted Server Settings**.
|
||||
For the virtual desktop package, install this file instead:
|
||||
|
||||
### Server Side
|
||||
Place **crossdesk.cn.key** and **crossdesk.cn_bundle.crt** into the **/path/to/your/certs** directory.
|
||||
```bash
|
||||
sudo apt install "./crossdesk-virtual-desktop-xfce-linux-amd64-<version>.deb"
|
||||
```
|
||||
|
||||
### Client Side
|
||||
1. Click the settings icon in the top-right corner to enter the settings page.<br>
|
||||
<img width="600" height="210" alt="image" src="https://github.com/user-attachments/assets/6431131d-b32a-4726-8783-6788f47baa3b" /><br><br>
|
||||
Both contain the same complete application, replace each other and preserve user settings. The standard package can also create virtual desktops after you install the optional dependencies. Installing the virtual desktop package does not start a session or change the default desktop; see [Linux headless operation](docs/HEADLESS_EN.md) to start one. The app's update download button selects the installed package type. Upgrading an existing installation does not automatically remove previously installed Xfce components.
|
||||
|
||||
2. Click **Self-Hosted Server Configuration**.<br><br>
|
||||
<img width="600" height="160" alt="image" src="https://github.com/user-attachments/assets/24c761a3-1985-4d7e-84be-787383c2afb8" /><br><br>
|
||||
**First launch on macOS:** follow the app prompts to grant **Screen Recording** (called **Screen & System Audio Recording** on newer systems) and **Accessibility** under **System Settings → Privacy & Security**. Reopen the app if prompted. These permissions allow desktop capture and remote keyboard/mouse input respectively.
|
||||
|
||||
3. In the **Certificate File Path** selection, locate and select the **crossdesk.cn_root.crt** file.<br><br>
|
||||
<img width="600" height="220" alt="image" src="https://github.com/user-attachments/assets/4af7cd3a-c72e-44fb-b032-30e050019c2a" /><br><br>
|
||||
<a id="quick-start"></a>
|
||||
|
||||
4. Check the option to use **Self-Hosted Server Configuration**.<br><br>
|
||||
<img width="600" height="160" alt="image" src="https://github.com/user-attachments/assets/1e455dc3-4087-4f37-a544-1ff9f8789383" /><br><br>
|
||||
## Quick start
|
||||
|
||||
### Web Client
|
||||
See [CrossDesk Web Client](https://github.com/kunkundi/crossdesk-web-client)。
|
||||
### Connect from another computer
|
||||
|
||||
# FAQ
|
||||
See [FAQ](https://github.com/kunkundi/crosssesk/blob/self-hosted-server/docs/FAQ.md) .
|
||||
1. **Prepare the host.** Install and run CrossDesk on the computer to control. Wait for the bottom status bar to show that the server is connected. Share the **Local ID** and **Password** shown under **Local Desktop** with the controller.
|
||||
2. **Enter the remote ID.** On the controlling computer, enter the host's ID in **Remote Desktop → Remote ID**, then click **→**.
|
||||
3. **Verify the password.** Enter the host's current connection password when prompted and confirm. Select **Remember password** if you want to save it.
|
||||
4. **Reconnect later.** Previously connected devices appear under **Recent Connections**. Reconnect from a card, edit its alias, or remove its record.
|
||||
|
||||
The eye button shows or hides the local password, the refresh button generates a new random password, and the pencil button lets you edit it. Passwords use **6 ASCII letters or digits**. Stay connected to the server when editing or refreshing a password. Wait for the change to succeed and the client to reconnect, then copy the current password. Controllers that saved the old password must enter it again.
|
||||
|
||||
### Connect from a browser
|
||||
|
||||
1. Keep CrossDesk running and connected to the server on the host computer.
|
||||
2. Open the [Web Client](https://web.crossdesk.cn/), enter the **Remote Device ID** and **Password**, and click **Connect**.
|
||||
3. Use the page's display, mouse-mode, and keyboard controls during the session. Phone and tablet browsers can also connect.
|
||||
|
||||
For self-hosting, connect both sides to the same service. Browser deployment is documented in [CrossDesk Web Client](https://github.com/kunkundi/crossdesk-web-client).
|
||||
|
||||
<a id="session"></a>
|
||||
|
||||
## Session controls
|
||||
|
||||
Switch devices using session tabs. Expand the control bar if it is collapsed, and hover over icons to see their tooltips.
|
||||
|
||||
| Control | Action |
|
||||
| --- | --- |
|
||||
| Display | Switch the remote monitor |
|
||||
| Keyboard | Send shortcuts; Windows `Ctrl+Alt+Del` requires the remote service |
|
||||
| Mouse | Enable / release remote mouse control |
|
||||
| Speaker | Play / mute remote audio |
|
||||
| Folder | Select a file to send and view transfer progress |
|
||||
| Video settings | Adjust video quality, capture frame rate, and video preference during the current session |
|
||||
| Network statistics | Inspect traffic, packet loss, frame rate, resolution, direct / relay mode, and encryption status |
|
||||
| Privacy screen | Enable or disable the host's privacy screen; hover to see its status and available actions |
|
||||
| Fullscreen | Enter / exit fullscreen |
|
||||
| Disconnect | End the current remote session |
|
||||
|
||||
Desktop clients synchronize text clipboard contents. Configure the receiving directory under **Settings → File Save Path**. Closing the main window hides it and keeps the app running; use the system tray or menu-bar exit command to quit completely.
|
||||
|
||||
### Adjust video during a session
|
||||
|
||||
After connecting, open **Video settings** (the sliders icon) in the toolbar. Choose low / medium / high quality, **30 / 60 fps**, and frame-rate priority / quality priority / balanced adaptation. Changes are sent to the current host without reconnecting; actual results depend on the network, device, and encoder. For older hosts that do not support live video settings, the menu explains the limitation and disables the options.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-stream-video-settings-en.png" width="800" alt="Current session video menu with quality, capture frame rate, and video preference; the background is a public page used for demonstration" />
|
||||
</p>
|
||||
|
||||
<a id="settings"></a>
|
||||
|
||||
## Client settings and updates
|
||||
|
||||
Open **☰ → Settings** in the top-right corner and click **OK** to save. Configure codecs and connections before connecting; some settings are disabled during an active session. Scroll down for self-hosting, startup behavior, and the file save path. Adjust quality, frame rate, and video preference from the remote session toolbar.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-settings-en.png" width="720" alt="Current client settings with codec, hardware codecs, TURN, forced relay, and automatic privacy screen options" />
|
||||
</p>
|
||||
|
||||
| Setting | Purpose |
|
||||
| --- | --- |
|
||||
| Language | 中文, English, Русский |
|
||||
| Capture Method (Windows) | Auto / DXGI / WGC / GDI; choose Auto for automatic headless adaptation |
|
||||
| Video Encode Format | H.264 / AV1; hardware codec availability depends on the platform, device, and build options |
|
||||
| Enable TURN Service | Allow relay-assisted connections; check this setting if P2P fails |
|
||||
| Force Relay | Require relay connections when TURN is enabled; turning TURN off also disables this option |
|
||||
| Save remote screen previews | On by default. When disabled, the thumbnail area shows the remote device’s platform and existing previews are cleared; connection records and passwords are preserved |
|
||||
| Privacy screen on connect | Automatically enable privacy when this computer is controlled remotely; the controller can toggle it from the session toolbar |
|
||||
| Self-Hosted Config | Set the server address and signaling port, then enable the checkbox |
|
||||
| Auto Start / Enable Daemon | Configure startup and process supervision; restart as indicated by the UI |
|
||||
| File Save Path | Choose where received files are saved |
|
||||
|
||||
### Check for updates
|
||||
|
||||
The client checks for updates in the background after launch and automatically opens the update dialog when a new version is found, showing release notes and a link to the download page. After you dismiss the dialog, background checks will not reopen it during the current run, while the main window menu keeps its update indicator. Restarting the client shows the dialog again if an update is still available. Open **☰ → About** to view the version. When an update is available, click **Release notes** below the new version to reopen the update dialog, or click **Check for updates** to check manually.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-about-en.png" width="720" alt="About dialog with the Check for updates button; version and check result are demonstration data" />
|
||||
</p>
|
||||
|
||||
<a id="ios"></a>
|
||||
|
||||
## Native iOS / iPadOS client
|
||||
|
||||
[`apps/ios`](apps/ios/README.md) contains a native controller using the same MiniRTC protocol as the desktop client. It controls remote computers; it does not expose an iPhone or iPad as a remotely controlled desktop.
|
||||
|
||||
1. Follow the [iOS guide](apps/ios/README.md) to build and sign the app with Xcode, then install it on an iOS 16+ physical device.
|
||||
2. Enter a remote ID on the home screen, connect, and enter its password. Successful connections become available in the recent devices list.
|
||||
3. Choose a mouse mode in Settings: **Relative Position** works like a trackpad; **Absolute Position** maps touches directly to the remote screen.
|
||||
4. Tap the floating icon to expand the menu, then switch displays, open the keyboard, toggle audio, or send files. Received files are stored in `Documents/Received` and can be exported using the share button beside the transfer status.
|
||||
|
||||
The app currently receives remote text into the iOS clipboard. Its UI does not yet expose a button to send the local clipboard.
|
||||
|
||||
Gestures include one-finger click, two-finger right-click, long-press drag, and pinch-to-zoom. When zoomed in, two-finger panning moves the viewport. The native and browser clients are maintained separately, so their controls and gestures may differ. The current native UI uses Chinese labels.
|
||||
|
||||
<a id="windows-service"></a>
|
||||
|
||||
## Windows lock screens and sign-in
|
||||
|
||||
**CrossDesk Service** (`CrossDeskService`) reports protected desktop states and forwards `Ctrl+Alt+Del`, keyboard, and mouse input on lock screens, sign-in screens, credential prompts, and secure desktops.
|
||||
|
||||
The installer registers an on-demand service by default. CrossDesk tries to start it on launch. Unless unattended mode is enabled, the service exits when no local CrossDesk client is running. Portable builds offer service installation in the prompt or **Settings → Lock Screen Service**, with administrator privileges.
|
||||
|
||||
On Windows, **Auto Start** launches the client after the current user signs in. Installed release builds use a logon scheduled task with highest privileges, so subsequent logons need no UAC confirmation; portable and Debug builds use a normal per-user startup entry. Upgrading the installed build or launching the new version manually migrates a legacy startup entry pointing to that executable. Turning Auto Start off removes its registration. Remote access before sign-in requires the separate unattended mode below.
|
||||
|
||||
### Remote access before Windows sign-in
|
||||
|
||||
The installed release supports a separate unattended host. Open an **administrator PowerShell** in the complete installation directory and enable it once:
|
||||
|
||||
```powershell
|
||||
.\CrossDesk.exe --unattended-enable
|
||||
# After network registration, show its separate device ID, password and online state
|
||||
.\CrossDesk.exe --unattended-status
|
||||
```
|
||||
|
||||
Connect from another device using the returned `device_id` and `password`. First-time setup copies the current client's server and codec preferences and creates separate credentials. This ID differs from the GUI client's ID and persists across reboots, logoffs and re-enabling. Subsequent enable commands retain the machine configuration. Self-hosted server root certificates must be trusted in the Local Computer certificate store.
|
||||
|
||||
Once enabled, `CrossDeskService` starts automatically at system boot. Windows automatic login and saved Windows login passwords are unnecessary. The service launches a windowless SYSTEM host in the active console session and reuses secure-desktop capture, keyboard/mouse input and `Ctrl+Alt+Del`. Signing in, locking Windows or closing the ordinary client does not stop it. Logoff, user switching or a host crash causes the service to restart the host; the connection may drop, and you can reconnect using the same ID. Network connections retry if networking is unavailable during boot.
|
||||
|
||||
Unattended mode supports screen viewing, keyboard/mouse input, monitor switching and secure desktops. Audio, file transfer, clipboard and privacy screens are unavailable. Portable and Debug builds cannot enable it. Configuration and credentials reside in `%ProgramData%\CrossDeskUnattended`, accessible only to SYSTEM and administrators; logs are in its `logs` subdirectory.
|
||||
|
||||
```powershell
|
||||
# Stop the unattended host and restore on-demand service startup
|
||||
.\CrossDesk.exe --unattended-disable
|
||||
```
|
||||
|
||||
Turning off ordinary Auto Start does not disable unattended mode. Disabling or uninstalling the service disarms unattended startup but retains the protected machine profile. To erase its credentials, stop the service and delete that directory as an administrator.
|
||||
|
||||
<details>
|
||||
<summary>Manual deployment and service commands</summary>
|
||||
|
||||
Keep the complete installation directory. For manual deployment, place `CrossDesk.exe`, `crossdesk_service.exe`, `crossdesk_session_helper.exe`, and all `.dll` files from the same build together. Open an administrator PowerShell in that directory and run the commands you need:
|
||||
|
||||
```powershell
|
||||
.\CrossDesk.exe --service-install
|
||||
.\CrossDesk.exe --service-start
|
||||
.\CrossDesk.exe --service-status
|
||||
.\CrossDesk.exe --service-ping
|
||||
# Stop or uninstall the service
|
||||
.\CrossDesk.exe --service-stop
|
||||
.\CrossDesk.exe --service-uninstall
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
If **Remote Windows service unavailable** appears, check installation and service status on the host. Ordinary desktop connections remain available, while control of protected screens is limited.
|
||||
|
||||
<a id="self-hosting"></a>
|
||||
|
||||
## Self-hosting
|
||||
|
||||
Host your own signaling and TURN services, then enter their connection details under **☰ → Settings → Self-Hosted Config**. Enable the same server configuration on both the controller and host.
|
||||
|
||||
- [Self-hosting guide](docs/SELF_HOSTING_EN.md): current Compose deployment, client settings, certificate trust, and troubleshooting.
|
||||
- [CrossDesk Server](https://github.com/kunkundi/crossdesk-server): server source and release configuration.
|
||||
- [CrossDesk Web Client](https://github.com/kunkundi/crossdesk-web-client): browser source and deployment instructions.
|
||||
|
||||
## Development and feedback
|
||||
|
||||
- [Build from source](docs/BUILD_EN.md): Windows, macOS, Linux, optional flags, and packaging.
|
||||
- [iOS development](apps/ios/README.md): native build and physical-device checks.
|
||||
- [Android development](apps/android/README.md): APK builds, installation, and emulator checks.
|
||||
- [GUI architecture](docs/gui-architecture.md): desktop UI and platform organization.
|
||||
- [FAQ](docs/FAQ.md#english): connection failures, blank video, received files, and build issues.
|
||||
- [Report an issue](https://github.com/kunkundi/crossdesk/issues): include both operating systems, client versions, connection mode, and reproduction steps.
|
||||
|
||||
## Acknowledgements and license
|
||||
|
||||
Thanks to [HelloGitHub](https://hellogithub.com/), [Ruanyf Weekly](https://github.com/ruanyf/weekly), and the [LinuxDo](https://linux.do) community for featuring CrossDesk and contributing feedback.
|
||||
|
||||
CrossDesk is licensed under [GPL-3.0](LICENSE). See the [Privacy Policy](PRIVACY.md#english).
|
||||
|
||||
### Code signing policy
|
||||
|
||||
CrossDesk uses SignPath.io to sign official Windows releases built from this repository.
|
||||
|
||||
**Free code signing provided by [SignPath.io](https://signpath.io/), certificate by [SignPath Foundation](https://signpath.org/).**
|
||||
|
||||
- **Committers and reviewers:** [kunkundi](https://github.com/kunkundi)
|
||||
- **Approvers:** [kunkundi](https://github.com/kunkundi)
|
||||
|
||||
## Native Android controller
|
||||
|
||||
The independent [Android project](apps/android/README.md) builds an APK for Android 8.0+ arm64 devices. It reuses MiniRTC and the desktop input protocol for remote video/audio, touch and external keyboard/mouse input, display switching, and text clipboard transfer. H.264 and AV1 currently use software decoding. Phone-as-host, file transfer, and full iOS feature parity are not included. See the [Android build guide](apps/android/README.md) for setup and validation.
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
gradlew text eol=lf
|
||||
gradlew.bat text eol=crlf
|
||||
@@ -0,0 +1,7 @@
|
||||
.gradle/
|
||||
.native/
|
||||
.idea/
|
||||
**/build/
|
||||
local.properties
|
||||
*.iml
|
||||
__pycache__/
|
||||
@@ -0,0 +1,248 @@
|
||||
# CrossDesk Android
|
||||
|
||||
原生 Android 控制端,使用 Java 界面、JNI 和 MiniRTC,与桌面端使用相同的信令、ICE、SRTP 和输入协议。没有 WebView。当前版本为 1.6.0,支持 Android 8.0(API 26)及以上的 arm64 手机和平板。
|
||||
|
||||
## 当前功能
|
||||
|
||||
- 官方或自托管 WSS 信令服务器;授权后进入前台即自动注册或登录本机身份,首页实时显示连接、重连及失败状态。发起桌面连接时复用该身份;切换服务器会重新登录,撤回授权会关闭连接。已有远程会话优先通过系统画中画保持连接,画中画不可用时由带连接通知的前台服务兜底;首页空闲信令在后台关闭。
|
||||
- 优先使用 MediaCodec 硬件解码 H.264 / AV1,硬件缓冲区直接提交 Surface;设备无对应硬件、分辨率超限或运行失败时,按原编码格式回退到 OpenH264 / dav1d。软件输出由独立显示线程将 NV12 转 RGBA;只保留最新待显示帧。MiniRTC 原有的通用压缩帧解码队列保持不变。
|
||||
- 48 kHz 单声道 PCM 播放,支持静音,音频队列有容量限制。
|
||||
- 相对鼠标(触控板)和绝对位置模式;单指点击、绝对模式按住拖动、长按右键,以及外接键盘、鼠标。画面手势与 iOS 一致:双指捏合以触点为中心缩放(1–10 倍),放大后双指拖动画面,原始比例下双指上下滑动控制滚轮。
|
||||
- 横竖屏等比例显示、远端多显示器切换。与 iOS 一致的画面质量(低/中/高)、采集帧率(30/60 fps)、画面偏好;支持能力检测、电脑端确认、失败/5 秒超时回退及连续操作的应答排序。
|
||||
- 根据常见移动设备解码能力和屏幕尺寸设置起始参数:显示长边不超过 1280 像素时默认低画质(最高 720p)/30 fps,其余默认中画质(最高 1080p)/30 fps。用户保存的画面偏好不变,仍可手动选择高画质或 60 fps。
|
||||
- 网络状态按视频、音频、数据、合计展示收发速率和丢包率,并显示实际提交帧率、分辨率、画面延时、平滑 RTT、P2P/TURN 和实际 SRTP 状态。每秒刷新,过期或无效测量显示“—”。
|
||||
- 可拖动的悬浮控制球、三列控制菜单和浮动 ASCII / 电脑键盘、常用快捷键;通过剪贴板发送中文等文本,再手动执行远端粘贴。
|
||||
- 悬浮菜单中的“虚拟鼠标”展开 140 × 48 dp 横向左键/滚轮/右键条,跟随悬浮球移动,可随时收起,不压缩远程画面。按住左键或右键后,同一根手指拖动即可拖拽,滑出按键范围仍继续,松开结束;也支持另一指在画面上移动光标。采用无文字的扁平分体按键,中间滚轮外观为 18 × 30 dp,三键均保留 44 × 44 dp 触控范围,通过留白分隔。无阴影、凹凸或按压位移,按压仅变色。等色横条随手指上下循环移动,松手停止;上下滑动可超出按键范围,在画面放大后仍控制远端滚动。切换模式、显示器、进入后台或取消触摸会释放按键。状态菜单按内容高度完整展开,只有安全区域空间不足时才滚动。
|
||||
- 悬浮控制栏支持选择并发送文件、接收电脑端文件、查看确认进度及保存收到的文件;Ctrl+Alt+Del 使用远端 Windows 系统服务,未启用服务时显示提示。
|
||||
- 设备身份与选择保存的连接密码使用 Android Keystore / AES-GCM 加密;首次联网需同意。远程会话在切换应用时自动使用系统画中画,不可用时自动使用通知保活。
|
||||
- 与 iOS 一致的首页卡片、顶部状态/公告/设置入口、密码弹层及分组设置页;最近连接按服务器隔离,长按可删除记录及密码。
|
||||
- 平板首页支持横竖屏和分屏,按当前可用宽度自动适配:900 dp 起连接与最近连接并排,较窄窗口纵向排列;最近连接随宽度显示 1–4 列,手机常规宽度仍为两列。首页最大宽度为 1200 dp,设置、公告及阅读页最大宽度为 720 dp,宽窗口中的密码和隐私弹窗居中限宽。旋转或调整分屏直接重排现有页面,保留输入、设置编辑和当前会话;手机全屏首页保持竖屏。
|
||||
- 页面转场沿用 iOS 的交互方式:设置、隐私、关于及公告页面进入时从右滑入,返回时反向滑出,背景页面轻微跟随;进入和退出远程会话使用 0.2 秒淡入淡出。遵循 Android 系统动画开关及速度设置。
|
||||
- 设置页的鼠标控制、画面偏好,以及悬浮控制栏的画质、帧率和画面偏好使用 0.2 秒的选中底块滑动动画;连续点击从当前位置转向,电脑端拒绝或超时后平滑回退,系统关闭动画时直接切换。
|
||||
- 通知公告与 iOS 共用信令协议,支持未读角标、分页、下拉刷新、更新推送、详情和网页链接;已读及删除状态按服务器、本机身份和公告版本保存在本机。
|
||||
- 连接建立并收到对端信息后,按 iOS 相同的版本号及补丁规则检查桌面端版本;旧版本弹出“升级提示”,点击“知道了”继续控制。每次连接最多检查、提醒一次;缺失或无效版本按旧版提醒,检查失败不打断连接。仅获取公共 HTTPS 版本元数据,不上传对端身份或版本;未授权不请求,断开及进入后台取消检查并忽略过期回复。
|
||||
- 可选保存远程画面预览:默认关闭,经确认开启后,从下一次连接起保存一张 640×360 预览,用于最近连接卡片。支持清除预览,关闭选项或撤回授权会清除已有图片。
|
||||
- “关于 CrossDesk”对齐 iOS 的版本、软件许可、开源组件及源码与构建说明页面,包含 OpenFEC 告知、组件详情和可离线选择复制的完整许可;版本号读取当前 APK,构建时记录应用与 MiniRTC 的基础版本。
|
||||
|
||||
当前不包含安卓被控端、隐私屏或 iOS 全部附加功能。硬件能力取决于设备和编码格式,软件回退时高分辨率或高帧率可能增加功耗;可通过悬浮菜单的画面设置降低画质或采集帧率。暂只构建 `arm64-v8a`,不支持 x86 模拟器或 32 位设备。
|
||||
|
||||
## 本机更新提示
|
||||
|
||||
完成联网授权后,每次启动或从后台返回时检查一次公共版本文件,前台远程连接结束后再检查一次;同时触发时复用正在进行的请求。不进行周期性检查或自动重试,失败时保留已发现的新版本提示,等待下一次触发或手动检查;进入后台或撤回授权时取消请求并忽略过期回复。
|
||||
|
||||
本机只读取 `downloads.android-arm64`,复用 PC 端的版本号及补丁比较规则;仅构建日期变化不提示升级,平台版本字段缺失按检查失败处理。发现新版本后,首页设置按钮右上角显示红底白色感叹号角标,大小和位置与通知角标一致,设置页“关于”显示“新版本”文字和红点;“关于”展示新版本号、官网更新入口,并提供“检查更新”。该功能独立于被控电脑的版本升级提示。
|
||||
|
||||
## 构建
|
||||
|
||||
在 macOS 或 Linux 安装:
|
||||
|
||||
- JDK 17 或更新版本(可使用 Android Studio 自带 JBR)。
|
||||
- Android SDK Platform 36、Build Tools 36.0.0、NDK `28.2.13676358`。
|
||||
- Xmake **3.1.1 或更新版本**、Python 3.9+、Git、CMake 和主机编译工具。
|
||||
- Python 的 setuptools、wheel,用于构建依赖的宿主工具。
|
||||
|
||||
先在仓库根目录初始化子模块:
|
||||
|
||||
```sh
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
macOS 命令行示例:
|
||||
|
||||
```sh
|
||||
export ANDROID_HOME="$HOME/Library/Android/sdk"
|
||||
export JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home"
|
||||
# 使用 PATH 中的 Xmake(最低 3.1.1),或通过 XMAKE_BIN 指定其他可执行文件。
|
||||
cd apps/android
|
||||
./gradlew :app:assembleDebug
|
||||
```
|
||||
|
||||
也可用 Android Studio 打开 `apps/android`。在 SDK Manager 安装上述版本;SDK 位置可由 IDE 写入被忽略的 `local.properties`。Xmake 不在 IDE 的 PATH 中时,启动 IDE 前设置 `XMAKE_BIN`。
|
||||
|
||||
输出为 `app/build/outputs/apk/debug/app-debug.apk`,已由本机 Android 调试密钥签名:
|
||||
|
||||
```sh
|
||||
"$ANDROID_HOME/platform-tools/adb" install -r app/build/outputs/apk/debug/app-debug.apk
|
||||
```
|
||||
|
||||
Release 构建使用 `./gradlew :app:assembleRelease`,默认输出未签名 APK;发行前需配置自己的签名。Debug APK 也使用优化后的 Release 原生库,以保证软件解码性能。
|
||||
|
||||
首次构建会下载并从源码编译依赖,耗时取决于网络。后续编译复用缓存。Android 直接编译 `deps/submodules/minirtc` 中的源码;构建产物和依赖缓存位于 `.native/`,Xmake 工程配置位于 `native/.xmake/`,与桌面和 iOS 分开保存:
|
||||
|
||||
- Gradle 9.3.1、AGP 9.1.0、NDK r28c 固定在工程中。
|
||||
- Xmake 包仓库固定到 `eda39de3fb99b420c168f1ab9ab2d1791e11b662`。
|
||||
- `scripts/build_native.py` 调用独立的 `native/xmake.lua`,直接包含 MiniRTC 子模块的构建定义。构建过程不复制 MiniRTC 源码,也不应用补丁。
|
||||
- MiniRTC 源码内的 Android 分支启用 OpenH264、SVT-AV1 和 dav1d 软件编解码及依赖配方,兼容 OpenFEC 的 Android 头文件,并关闭 UPnP。SVT-AV1 使用内置 ARM CPU 能力检测;当前应用作为控制端只接收视频,库同时提供 AV1 编码能力。TLS 校验位于 MiniRTC 内部。STUN、TURN UDP/TCP 与直接连接仍由 MiniRTC 提供。
|
||||
- MiniRTC 的 `thirdparty/openssl/xmake.lua` 统一维护 iOS 和 Android 配方;Android 显式使用 NDK 的归档索引工具,避免 macOS `ranlib` 损坏 ELF 静态库。
|
||||
- SVT-AV1 编码及 dav1d 解码已在 Android 15 arm64 / 16 KB 模拟器上完成验证,覆盖软件编码、请求硬件加速时的软件回退、码率更新、强制关键帧及 320×192 → 256×144 → 320×192 分辨率切换;两组测试各成功编码并解码 24 帧。这是编解码正确性验证,不代表真机实时编码性能。
|
||||
- 依赖静态链接到 `libcrossdesk_android.so`,保留 16 KB ELF / APK 对齐。
|
||||
|
||||
修改原生代码后重新运行 Gradle 即可;修改依赖版本或配方时同步检查许可证内容,必要时移除 `.native/packages` 重新构建。MiniRTC 的源码和依赖配方变更直接保存在子模块中;提交时先提交 MiniRTC,再更新主仓库的子模块引用。
|
||||
|
||||
## GitHub Actions
|
||||
|
||||
[`Build Android`](../../.github/workflows/build-android.yml) 可在 Actions 页面单独手动运行;修改 Android、MiniRTC、共享协议或许可证资料的 Pull Request 也会触发。仓库原有的 [`Build and Release`](../../.github/workflows/build.yml) 在分支推送、标签推送及手动运行时调用同一工作流,`v` 标签发布会等待安卓构建及签名成功,并将已签名 Release APK 加入 GitHub Release 和现有下载服务器的产物集合。推送主仓库前,先确保它引用的 MiniRTC 提交已推送到子模块远程仓库,否则 CI 无法完成检出。
|
||||
|
||||
单独发布使用 [`Release Mobile`](../../.github/workflows/release-mobile.yml)。先提交 `app/build.gradle` 中需要发布的 `versionName`,再为该提交创建 `android-v<versionName>-YYYYMMDD` 标签,例如:
|
||||
|
||||
```sh
|
||||
git tag android-v1.6.0-20261002
|
||||
git push origin android-v1.6.0-20261002
|
||||
```
|
||||
|
||||
该标签只触发安卓构建,使用固定发布密钥签名并验证 Release APK 后,再发布到独立的 GitHub Release 和现有下载服务器。签名失败或缺少签名 Secrets 时停止发布,不回退到未签名 APK。标签版本必须与应用版本一致,日期必须有效。重试发布时,在 Actions 页面手动运行 `Release Mobile`,将已有标签填入 `source_tag`;即使从其他分支触发,也会检出该标签的源码。APK 的源码资料记录安卓标签及准确的应用、MiniRTC 提交。
|
||||
|
||||
移动端独立发布保留桌面 `latest` 标签和 GitHub 的最新 Release 选择。APK 上传完成后,将服务器下载地址合并到共享 `https://version.crossdesk.cn/version.json` 的 `downloads.android-arm64`,并在该下载项中记录安卓版本和发布日期;保留顶层桌面版本信息和其他平台的下载项。下载服务器上传保留其他平台文件,复用仓库已有的 `SERVER_HOST`、`SERVER_USER`、`SERVER_KEY` Secrets。普通桌面版本标签仍通过 `Build and Release` 发布全部平台并更新各平台下载项;所有发布任务更新版本文件时使用同一队列。单独运行 `Build Android` 仍只上传 Actions 构建产物。
|
||||
|
||||
已有 Release 需要补传服务器或刷新下载信息时,可手动运行 `Update version.json from Release` 并填写已有 `source_tag`,无需重新构建。
|
||||
|
||||
工作流使用 Ubuntu 24.04、JDK 17、Python 3.13、SDK 36、Build Tools 36.0.0、NDK r28c,并使用最低支持的 Xmake 3.1.1 验证构建;本地允许使用更新的 Xmake。Gradle 使用工程内的 Wrapper,原生构建器固定 Xmake 包仓库版本。SDK/NDK 使用独立目录缓存,按宿主系统、架构和工具链版本区分;命中缓存时跳过 SDK 安装,未命中时在安装完成后立即保存,即使后续 APK 构建失败,下次也可复用。Xmake 可执行环境、固定版本的包仓库和 pip 下载也有各自的缓存;Ubuntu 系统工具只安装缺失项。
|
||||
|
||||
Gradle 缓存与 Android 原生依赖缓存分别管理;原生缓存按宿主架构、构建脚本及 MiniRTC 配方区分,不复用桌面或 iOS 的配置和目标文件。GitHub 托管 runner 每次启动仍是新环境;第一次运行或缓存失效时需要安装。不同分支和标签可读取默认分支的缓存,因此建议先在默认分支运行一次 `Build Android` 预热,再创建发布标签。
|
||||
|
||||
CI 仅构建和打包 Debug、Release APK,并校验 APK 的 arm64 ABI、16 KB ELF / ZIP 对齐、完整许可证及 Debug 签名。单元测试、本机 C++ 协议与画面队列测试、Lint 和设备测试改为按需在本地执行;设备测试使用下面的设备验证流程在 arm64 手机或模拟器上执行。
|
||||
|
||||
产物使用 Android 工程自己的 `versionName`,例如 `v1.6.0-20261002`,不跟随桌面版本号。构建日期采用上海时区;带日期的版本标签沿用标签中的日期,与 iOS 一致。Actions 提供:
|
||||
|
||||
- `crossdesk-android-arm64-<版本>.apk`:已签名 Release APK,独立安卓发布和全平台标签发布收集此 APK,可直接安装。
|
||||
- `crossdesk-android-arm64-unsigned-<版本>.apk`:构建工作流的中间产物,也可用于自行签名和验证修改后的构建。
|
||||
- `crossdesk-android-arm64-debug-<版本>.apk`:可安装的调试应用,保留 14 天。
|
||||
|
||||
Debug APK 使用每次运行的临时调试证书,可能无法覆盖手机上已有的其他签名版本;卸载原应用会清除本机连接记录和密码。需要持续覆盖升级时,应使用同一私钥签名 Release APK,并在发布新版本时递增 `app/build.gradle` 中的 `versionCode`。未签名 APK 已完成对齐,可通过 SDK 的 `apksigner sign --ks <自己的密钥库> --out <已签名.apk> <未签名.apk>` 签名,再用 `apksigner verify` 检查。
|
||||
|
||||
### Release 签名
|
||||
|
||||
[`Sign Android Release`](../../.github/workflows/sign-android.yml) 在独立 job 中签名,不检出或执行应用源码。构建 job 和 Pull Request 构建不接收发布密钥。签名 job 使用 Build Tools 36.0.0,先执行 `zipalign -P 16`,再通过环境变量向 `apksigner` 提供密码,验证签名和 16 KB 对齐后上传已签名 APK。临时密钥库在步骤结束时清理,产物中不包含密钥或密码。
|
||||
|
||||
首次发布前,在仓库 Settings → Secrets and variables → Actions 配置:
|
||||
|
||||
| Secret | 内容 |
|
||||
| --- | --- |
|
||||
| `ANDROID_KEYSTORE_BASE64` | 发布密钥库文件的 Base64 内容 |
|
||||
| `ANDROID_KEYSTORE_PASSWORD` | 密钥库密码 |
|
||||
| `ANDROID_KEY_ALIAS` | 发布私钥的 alias |
|
||||
| `ANDROID_KEY_PASSWORD` | 发布私钥密码 |
|
||||
|
||||
APK 签名不需要 Google Play 开发者账号。若没有已有发布密钥,可使用 JDK 的 `keytool` 创建一次,密钥库保存在工程之外,并备份密钥和密码:
|
||||
|
||||
```sh
|
||||
keytool -genkeypair -storetype PKCS12 -keystore /path/outside/repo/crossdesk-release.p12 \
|
||||
-alias crossdesk-release -keyalg RSA -keysize 4096 -validity 10000
|
||||
```
|
||||
|
||||
PKCS12 使用同一个密钥库和私钥密码,将它配置到两个密码 Secrets。可用 `gh secret set` 从标准输入写入 Secrets,避免把密码放进命令行参数。macOS 上传密钥库示例:
|
||||
|
||||
```sh
|
||||
base64 -i /path/outside/repo/crossdesk-release.p12 | gh secret set ANDROID_KEYSTORE_BASE64 --repo kunkundi/crossdesk
|
||||
gh secret set ANDROID_KEYSTORE_PASSWORD --repo kunkundi/crossdesk
|
||||
gh secret set ANDROID_KEY_ALIAS --repo kunkundi/crossdesk
|
||||
gh secret set ANDROID_KEY_PASSWORD --repo kunkundi/crossdesk
|
||||
```
|
||||
|
||||
后续版本沿用这些 Secrets,不能在每次构建时生成新密钥,也不能将密钥或密码提交到 Git。已有未签名安卓 Release 可单独运行 `Sign Android Release` 并填写其 `source_tag`,无需重新构建;该手动任务只上传已签名 Actions 产物,不修改已发布 Release。普通发布流程会自动签名、上传下载服务器,并将 `downloads.android-arm64` 指向已签名 APK。旧 Release 同时保留已签名和未签名 APK 时,版本文件优先选择相同版本的已签名文件。
|
||||
|
||||
## 使用与连接安全
|
||||
|
||||
授权后首页会自动连接服务器,绿色“已连接服务器”表示信令登录完成;失败时可点击状态重试。设置页显示本机 ID。电脑端保持在线,在 Android 首页填写 9 位设备 ID,首次点击“连接”后在底部弹层输入密码,可选择加密保存密码。成功保存后,点击最近连接或再次输入相同 ID 会直接使用该服务器下保存的密码,重启应用后仍然有效;密码无法读取或被远端拒绝时会重新显示输入弹层,新密码仅在连接成功后替换,取消或连接失败不会覆盖原密码。自托管服务器从“设置 → 服务器”展开修改主机名与端口,不能填写 `https://`、路径或完整 URL。默认是 `api.crossdesk.cn:9099`。
|
||||
|
||||
最近连接卡片与 iOS 一样,在设备 ID 旁显示已保存密码的钥匙图标和在线/离线状态,在线设备优先,同一状态内保留原来的最近连接顺序。授权并登录服务器后,通过身份信令订阅 `recent_connections_presence`,接收完整快照与 `presence_update`;每 30 秒刷新,状态超过 60 秒未更新则显示离线。断线、切换服务器或进入后台会清除在线状态,重连后等待新的快照。自托管服务需要支持相同的设备在线状态协议。
|
||||
|
||||
证书信任来自 Android 默认 TrustManager 导出的根证书。JNI 设置证书文件路径后,MiniRTC 的 Android 分支通过 `SSL_CTX_load_verify_locations` 显式加载,并校验证书链及 DNS / IP 主机名;不会跳过 TLS 验证。Android 应用进程带有 `AT_SECURE` 标记,不能依赖 OpenSSL 的默认路径加载器读取 `SSL_CERT_FILE`,否则会出现所有服务器均无法建立信任链的问题。自托管服务器应使用受系统信任的证书。当前没有在应用内导入自签名证书的入口。
|
||||
|
||||
身份按主机名和端口分开保存,备份与设备迁移不包含应用数据。密码不写入连接记录,仅在明确开启“保存密码”后写入独立加密存储;未开启时仅用于当前会话。连接成功通知只处理一次,重复的传输就绪回调不会再次保存密码或重建会话页面;密码存储拒绝空值覆盖。旧版本已被空值覆盖的密码无法恢复,遇到此记录时会提示重新输入一次,并保留“保存密码”开启状态。由于 MiniRTC 的诊断日志包含登录身份,Android 桥接层关闭其会话日志。身份存储损坏会显示错误,不会静默重新注册。
|
||||
|
||||
会话中的“剪贴板”发送用户输入的文本;收到的远端文本先留在会话内,点击“复制远端文本”才写入手机剪贴板。退出会话后清除会话内容。每次发送最多 128 KB。浮动键盘切换“电脑”后的“复制 / 粘贴 / 全选”根据远端平台选择 Ctrl 或 macOS Command。
|
||||
|
||||
“发送文件”调用系统文件选择器,后台读取所选文件后使用桌面端相同的 `file` / `file_feedback` 协议传输,支持空文件和中文文件名。每次发送一个文件,以 64 KiB 分块、最多 1 MiB 未确认数据限制发送队列;进度来自接收端确认,30 秒没有有效进展则报告失败。接收时校验大小并追踪完整字节范围,允许跨线程回调乱序,未完成的文件不会提供保存入口。同名文件分开存储,不覆盖已有文件;可通过“保存收到的文件”导出最近收到的文件,连续接收多个文件时应逐个保存。
|
||||
|
||||
选取或保存文件期间保留会话并暂时禁用自动画中画,取消选择不会断开;停留超过 5 分钟且应用仍不在前台时结束会话。发送副本和收到的文件暂存于应用私有缓存,结束会话后清除,需要保留的接收文件应在断开前导出;不申请全盘存储权限。
|
||||
|
||||
## 后台连接与画中画
|
||||
|
||||
与 iOS 一样,通过系统画中画显示真实远程视频并维持会话。连接成功且已显示远程画面后,Android 12 及以上启用系统自动画中画;Android 8–11 在离开应用时尝试进入。设备需支持画中画,系统需允许 CrossDesk 使用该功能。未连接、尚无画面或正在打开系统文件选择器时不自动进入。
|
||||
|
||||
Android 版本满足要求不代表固件提供画中画,部分低内存模式设备会禁用该功能。以系统的 `FEATURE_PICTURE_IN_PICTURE` 检测为准,单独允许画中画权限不能补齐系统能力。无系统画中画或权限被禁止时,连接建立后自动启动前台服务兜底;画中画进入失败也尝试使用该兜底。控制菜单不提供“画中画”或“后台保活”按钮,两者均在切换应用时自动处理。
|
||||
|
||||
画中画仅显示完整远程画面,隐藏本地光标、悬浮球、鼠标条和键盘,并释放远程按键。使用原有视频 Surface 和 RTC 连接,进入小窗时不会关闭音视频;通过系统小窗返回全屏继续操作。画面比例根据远端尺寸更新,超宽或超长画面在系统允许的比例范围内完整显示并留黑边。
|
||||
|
||||
正常画中画不启动兜底服务,可见的小窗使 Activity 保持在 started 状态,进入时仅暂停交互。关闭小窗会结束会话,不自动转为隐藏的后台连接。
|
||||
|
||||
兜底模式通过前台服务保留原 RTC/信令连接,并显示带“返回”和“断开”操作的常驻通知。后台停止本地画面渲染及音频播放,不创建悬浮窗;视频传输和解码不做协议层暂停。返回应用后重新绑定 Surface 并请求关键帧,恢复原静音状态、显示器和画面设置,不重新登录或连接远端。会话状态独立于 Activity,页面被系统回收后可恢复,整个进程被系统终止则不能恢复原连接。
|
||||
|
||||
服务仅用于用户主动建立且已成功连接的远程会话,不用于首页待机。Android 14 及以上使用 `specialUse` 前台服务类型并声明远程控制连接用途;Android 13 及以上在兜底首次启用时请求通知权限,拒绝后系统仅在活动应用管理中显示服务。CPU 部分唤醒锁仅在兜底会话后台期间持有,返回前台、断开、移除任务或服务销毁时释放。通知断开、远端断开、移除任务、撤回授权和强制停止均结束会话及服务,不自动重连。系统文件选择器仍有上述五分钟限制;系统强杀或网络中断仍可能结束连接。
|
||||
|
||||
首页设置里的“画面偏好”保存在本机,作为下一次连接的默认偏好;会话内画面设置与 iOS 一样只影响当前连接。初始质量按屏幕长边选择低(不超过 1280 像素)或中,采集帧率为 30 fps,电脑端报告支持后自动下发;旧版电脑未报告支持时禁用控件。网络页的 FPS 统计实际提交给 Android Surface 的帧,画面延时使用 MiniRTC 校准后的采集时间至提交时刻的估计值,未完成校准时显示“—”;RTT 使用 0.25 权重平滑,3 秒未更新的数据会过期。切换屏幕清除旧画面的帧率、分辨率和画面延时,保留网络统计。
|
||||
|
||||
采集时间的有效性在接收时检查,本机解码和显示等待计入画面延时;真实延时超过 5 秒也会继续显示,不会当成无效时间戳过滤。显示线程复用解码器的 CPU NV12 缓冲区,只保留一帧待显示画面,切换显示器或 Surface 时清除旧帧,会话结束时先停止显示线程再销毁原生连接。
|
||||
|
||||
## 隐私授权
|
||||
|
||||
未完成隐私授权时,首次打开或从后台返回应用会自动显示离线隐私政策;需要主动勾选阅读并同意后才能联网,与 iOS 一致。暂不同意后,本次停留不会反复弹窗,仍可浏览设置和本地连接记录。设置 → 隐私 → 隐私与授权可离线查看政策或撤回授权;撤回后下次进入应用会再次提示。
|
||||
|
||||
## 远程画面预览
|
||||
|
||||
设置 → 隐私中的“保存远程画面预览”默认关闭,完成联网授权后可开启。与 iOS 一致,开启前说明预览可能包含个人或工作信息;每次连接只在实际显示画面后保存一张预览,居中裁剪为 640×360、JPEG 质量 78。截图来自远程视频的 Surface,不包含悬浮菜单、键盘、本地光标或画面外的黑边;压缩、读写和解码在串行后台线程执行,不复制完整 4K 位图,也不连续截图。
|
||||
|
||||
图片保存在应用私有、不参与备份的 `RecentConnectionThumbnails` 目录,不上传、不写入系统相册。文件按服务器与远端 ID 隔离,最近连接卡片异步加载;未开启、没有预览或图片损坏时继续显示平台封面。删除或淘汰连接记录会删除对应预览。
|
||||
|
||||
“清除预览图”保留连接记录、密码和开关状态,下一次连接仍可保存新的预览。关闭保存选项或撤回联网授权会关闭保存并清除全部预览。清除时立即使未完成的截图和读取请求失效,删除与保存共用串行队列,防止已清除的图片被旧截图重新写回;清除失败会显示提示,可再次重试。
|
||||
|
||||
## 通知公告
|
||||
|
||||
首页铃铛展示全部未读公告的数量(超过 99 条显示 99+)。授权并连接服务器后,通过已有身份信令请求 `announcements_list`,摘要每页 200 条、正文每页 20 条;不依赖远程桌面连接。列表支持刷新、滚动加载更多、长按或左滑删除,删除前需确认,且仅隐藏本机的当前版本。打开详情即标记已读;服务器更新公告版本后会重新显示并计为未读。详情正文保留纯文本和换行,支持 HTTP(S) 地址及 `[文字](https://...)` 链接,不执行 HTML 或其他协议。
|
||||
|
||||
阅读和删除标记以原子文件保存在不参与备份的 `AnnouncementReads` 目录,按主机名、端口和本机设备 ID 隔离;写入失败会提示并保留原状态。内容只缓存于内存。收到 `announcements_changed` 时刷新,分页期间目录版本改变时重新获取;过期请求、断线前的回复不会覆盖新状态。请求失败或 12 秒超时可重试;未授权不联网,进入后台停止请求。自托管服务需要支持与桌面及 iOS 相同的公告协议。
|
||||
|
||||
## 验证
|
||||
|
||||
连接 arm64 设备或启动 arm64 模拟器后,在 `apps/android` 执行:
|
||||
|
||||
```sh
|
||||
./gradlew :app:assembleDebug :app:assembleDebugAndroidTest :app:lintDebug
|
||||
"$ANDROID_HOME/platform-tools/adb" install -r app/build/outputs/apk/debug/app-debug.apk
|
||||
"$ANDROID_HOME/platform-tools/adb" install -r app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk
|
||||
"$ANDROID_HOME/platform-tools/adb" shell am instrument -w -r cn.crossdesk.mobile.test/androidx.test.runner.AndroidJUnitRunner
|
||||
"$ANDROID_HOME/platform-tools/adb" uninstall cn.crossdesk.mobile.test
|
||||
python3 test/verify_apk.py app/build/outputs/apk/debug/app-debug.apk
|
||||
python3 test/run_native.py
|
||||
```
|
||||
|
||||
以上流程覆盖安装应用并只卸载测试包,保留已有应用数据;多台设备同时连接时,在每个 `adb` 命令中加上 `-s <设备序列号>`。`connectedDebugAndroidTest` 可能卸载被测应用及其数据,不用于已有连接记录或密码的设备。
|
||||
|
||||
测试源码、资源和检查入口统一位于 `test/`:
|
||||
|
||||
- `test/native/`:本机 C++ 协议、帧队列与画面延时回归,由 `test/run_native.py` 编译运行。
|
||||
- `test/android/java/`:非 UI 的 Android 功能回归,覆盖需要 Android API 或 JNI 的逻辑,包括设备在线状态刷新、过期与信令重连。Gradle 的 `androidTest` 源集显式引用此目录。
|
||||
- `test/android/assets/tls/`:本机环回 TLS 测试证书,仅进入测试 APK。
|
||||
- `test/verify_apk.py`:发布 APK 的 arm64 ABI、16 KB ELF / ZIP 对齐、许可证完整性和源码资料检查。
|
||||
|
||||
设备回归仅保留 TLS 证书校验、凭据加密及服务器隔离、原生连接生命周期、键盘映射、画面设置状态、缩放及输入坐标计算、网络采样、公告与预览数据持久化、版本兼容判断。预览存储测试使用生成的纯色位图,不采集屏幕或视频画面。
|
||||
|
||||
画面手势需在远程会话中人工验证:两种鼠标模式均检查捏合放大至 10 倍、缩回 1 倍、放大后的双指平移和边界限制;原始比例下双指滑动仍控制滚轮,捏合及平移不应产生远端点击或拖动。放大后检查点击与光标位置一致、横竖屏切换后位置正确,切换显示器或重新连接恢复 1 倍。自动化回归只验证几何计算,不注入 UI 手势。
|
||||
|
||||
UI 验证统一由人工完成,不维护页面导航、布局、动画、悬浮窗和截图采集的自动化用例。许可证和构建资料的完整性由 `test/verify_apk.py` 检查。
|
||||
|
||||
控制栏联调需在真实远程会话中验证文件选择及取消、收发文件内容一致性、接收后导出、传输中断线;Windows 远端分别检查系统服务开启与关闭时的 Ctrl+Alt+Del 行为。
|
||||
|
||||
画中画需在真实会话中检查切换应用自动进入、其他应用前台时画面持续更新、返回全屏、关闭小窗、静音、超宽及竖屏画面、文件选择器取消、系统禁用画中画和锁屏。
|
||||
|
||||
前台服务兜底需在无原生画中画的实机上验证后台往返、Activity 重建时复用会话、通知断开、旧通知隔离、远端断开时释放唤醒锁,以及实际网络和画面恢复。设备测试前后应备份、核对并恢复服务器等应用设置,避免中断的测试留下本地测试地址。
|
||||
|
||||
## MediaCodec 编解码
|
||||
|
||||
实现参照 MiniRTC 的 NVCodec 分层:`src/media/mediacodec/` 负责硬件后端、能力查询和 JNI/Surface 资源;`src/media/video/encode/mediacodec/` 与 `src/media/video/decode/mediacodec/` 分别接入编码器、解码器接口,并负责同编码格式的软件回退。Android 工程直接编译这些源码。通用 API 仅需启用 `hardware_acceleration` 和 `native_video_output`。JavaVM 由 Android JNI 适配层在 `JNI_OnLoad` 中设置到后端私有实现;该桥接不安装为 SDK 头文件,也不导出为动态库符号。当前能力查询和 SurfaceTexture 创建依赖 JNI,缺少 JavaVM 时仍可使用软件编解码。独立输出线程在画面停止更新后仍会取出最后一帧,空闲时休眠。
|
||||
|
||||
- H.264 / AV1 由系统能力查询选择硬件组件,支持编码码率调整、请求关键帧和分辨率变化。编码输入为 8 位 NV12,硬件需支持 NV12 / I420 ByteBuffer 输入;不满足时回退 OpenH264 / SVT-AV1。当前应用仍是控制端,库的编码能力不代表已实现安卓被控端。
|
||||
- 解码原生输出为可保留/释放的 MediaCodec 缓冲区,显示线程直接提交 Surface。切换显示器、销毁 Surface 和切回软件输出时解除旧 Surface 绑定。缓冲区在解码器重建或销毁后不可再次显示;未显示的缓冲区自动归还。
|
||||
- 关闭原生输出时,支持将硬件 NV12 / I420 输出按行距、填充高度和裁剪范围转换为紧凑 NV12;未知布局回退软件。
|
||||
- Retroid Pocket 2S 的 `OMX.sprd.av1.decoder` 实际加载软件 dav1d,虽被系统标成硬件组件,仍明确排除;AV1 使用软件回退。H.264 可使用 `OMX.sprd.h264.encoder` / `OMX.sprd.h264.decoder`。
|
||||
|
||||
AV1 硬件路径尚无对应实机验证;Retroid 上使用 dav1d 软件解码。
|
||||
|
||||
## 开源资料
|
||||
|
||||
应用为 GPL-3.0-only,MiniRTC 为 LGPL-3.0-only,其余组件保留各自许可证。`scripts/generate_notices.py` 复用仓库已有的依赖通知,选取 Android 实际使用的组件;`licenses/additional-notices.json` 补充 OpenH264、GNU libiconv 和 NDK / LLVM 运行时通知。APK 的开源信息页提供完整内容。可以修改库源码、重新链接,并使用自己的 Android 密钥签名安装。
|
||||
|
||||
设置 → 关于使用与 iOS 相同的分组及入口:版本、软件许可、开源组件、源码与构建说明。软件许可中可分别阅读 GNU GPL 第 3 版及开源软件权利说明;开源组件页单独展示 OpenFEC 告知,其余组件列出名称和许可证,详情包含版本、源码、适用的构建配方和每一份许可文档。内容按 Android 构建生成,不显示未使用的 iOS 依赖,Android 签名说明替换 Apple 签名说明。
|
||||
|
||||
APK 保留完整 `THIRD_PARTY_NOTICES.txt`,并生成轻量的 `ThirdPartyLicenses.json` 索引、72 份独立许可文档及 `SourceMetadata.json`。打开文档时才读取正文,长文按有限长度分块显示,支持文本选择、复制与网页链接;打包验证核对每份正文的 SHA-256。源码页面显示标签或提交版本及未发布修改提示,源码链接指向基础提交。当前 Android 构建说明、构建脚本、MiniRTC、OpenSSL 及 SVT-AV1 配方随 APK 离线提供,避免开发版链接指向基础提交中尚不存在的 Android 文件。
|
||||
@@ -0,0 +1,43 @@
|
||||
plugins { id 'com.android.application' }
|
||||
|
||||
android {
|
||||
namespace 'cn.crossdesk.mobile'
|
||||
compileSdk 36
|
||||
ndkVersion '28.2.13676358'
|
||||
defaultConfig {
|
||||
applicationId 'cn.crossdesk.mobile'
|
||||
minSdk 26
|
||||
targetSdk 36
|
||||
versionCode 2
|
||||
versionName '1.6.0'
|
||||
ndk { abiFilters 'arm64-v8a' }
|
||||
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_17
|
||||
targetCompatibility JavaVersion.VERSION_17
|
||||
}
|
||||
sourceSets.main.jniLibs.srcDirs = [layout.buildDirectory.dir('native')]
|
||||
sourceSets.main.assets.srcDirs += [layout.buildDirectory.dir('generated/notices')]
|
||||
sourceSets.androidTest.java.srcDirs = ['../test/android/java']
|
||||
sourceSets.androidTest.assets.srcDirs = ['../test/android/assets']
|
||||
buildTypes.release { minifyEnabled false }
|
||||
packaging.jniLibs.useLegacyPackaging = false
|
||||
}
|
||||
|
||||
dependencies {
|
||||
androidTestImplementation 'androidx.test:runner:1.7.0'
|
||||
androidTestImplementation 'androidx.test.ext:junit:1.3.0'
|
||||
}
|
||||
|
||||
tasks.register('buildMiniRtc', Exec) {
|
||||
workingDir rootProject.projectDir
|
||||
commandLine 'python3', 'scripts/build_native.py'
|
||||
environment 'ANDROID_HOME', androidComponents.sdkComponents.sdkDirectory.get().asFile.absolutePath
|
||||
}
|
||||
tasks.named('preBuild').configure { dependsOn 'buildMiniRtc' }
|
||||
tasks.register('generateNotices', Exec) {
|
||||
workingDir rootProject.projectDir
|
||||
commandLine 'python3', 'scripts/generate_notices.py'
|
||||
}
|
||||
tasks.named('preBuild').configure { dependsOn 'generateNotices' }
|
||||
@@ -0,0 +1,31 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<application android:theme="@style/AppTheme" android:label="CrossDesk"
|
||||
android:icon="@mipmap/ic_launcher" android:allowBackup="false"
|
||||
android:fullBackupContent="false"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:supportsRtl="true" android:usesCleartextTraffic="false">
|
||||
<service android:name=".RemoteSessionService" android:exported="false"
|
||||
android:foregroundServiceType="specialUse">
|
||||
<property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="Maintain a user-started remote desktop RTC/control session when picture-in-picture is unavailable. Background rendering and audio are suspended; the user can return or disconnect from the notification." />
|
||||
</service>
|
||||
<activity android:name=".MainActivity" android:exported="true"
|
||||
android:launchMode="singleTop"
|
||||
android:supportsPictureInPicture="true"
|
||||
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboard|keyboardHidden"
|
||||
android:resizeableActivity="true"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,138 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
import java.util.List;
|
||||
import static cn.crossdesk.mobile.MobileUi.*;
|
||||
|
||||
/** Mirrors the iOS About / component / source / document navigation. */
|
||||
final class AboutPages {
|
||||
private final MainActivity activity;
|
||||
private final MobileUi ui;
|
||||
private final Runnable settings;
|
||||
private final LicenseCatalog catalog;
|
||||
private final AppUpdateChecker updates;
|
||||
private TextView updateStatus, updateLink, checkButton;
|
||||
private LinearLayout updateRow;
|
||||
|
||||
AboutPages(MainActivity activity,MobileUi ui,Runnable settings,AppUpdateChecker updates){
|
||||
this.activity=activity;this.ui=ui;this.settings=settings;this.updates=updates;
|
||||
LicenseCatalog loaded;try{loaded=new LicenseCatalog(activity);}catch(Exception error){loaded=null;}catalog=loaded;
|
||||
}
|
||||
void show(){
|
||||
LinearLayout content=activity.formPage("about","关于 CrossDesk",settings);
|
||||
LinearLayout version=activity.section(content,"");value(version,"版本",applicationVersion());
|
||||
updateRow=ui.row();updateRow.setPadding(ui.dp(16),0,ui.dp(16),0);updateRow.addView(activity.updateDot(),ui.size(8,8));
|
||||
updateLink=ui.action("",BLUE,()->open("https://crossdesk.cn"));updateLink.setGravity(Gravity.START|Gravity.CENTER_VERTICAL);updateLink.setPadding(ui.dp(8),ui.dp(12),0,ui.dp(12));updateRow.addView(updateLink,new LinearLayout.LayoutParams(0,-2,1));version.addView(updateRow);
|
||||
updateStatus=ui.text("",13,false);updateStatus.setPadding(ui.dp(16),ui.dp(8),ui.dp(16),ui.dp(8));version.addView(updateStatus);
|
||||
checkButton=ui.action("检查更新",BLUE,activity::checkAppUpdates);version.addView(checkButton);renderUpdates();ui.gap(content,28);
|
||||
if(catalog==null){unavailable(content);return;}
|
||||
LinearLayout links=activity.section(content,"");
|
||||
activity.link(links,"软件许可","",()->component(catalog.find("crossdesk"),this::show));ui.divider(links);
|
||||
activity.link(links,"开源组件","",this::components);ui.divider(links);
|
||||
activity.link(links,"源码与构建说明","",this::source);
|
||||
activity.footer(content,"许可与版权声明可离线查阅。");
|
||||
}
|
||||
private String applicationVersion(){
|
||||
return activity.applicationVersion();
|
||||
}
|
||||
void renderUpdates(){
|
||||
if(updateStatus==null)return;
|
||||
updateRow.setVisibility(updates.updateAvailable()?View.VISIBLE:View.GONE);
|
||||
updateLink.setText("新版本可用:v"+updates.availableVersion);
|
||||
String status=!activity.hasNetworkConsent()?"完成隐私授权后可检查更新":switch(updates.status){
|
||||
case CHECKING -> "正在检查更新…";
|
||||
case UP_TO_DATE -> "当前已是最新版本";
|
||||
case FAILED -> "检查失败,请稍后重试";
|
||||
default -> "";
|
||||
};
|
||||
updateStatus.setText(status);updateStatus.setVisibility(status.isEmpty()?View.GONE:View.VISIBLE);
|
||||
updateStatus.setTextColor(updates.status==AppUpdateChecker.Status.FAILED?RED:SECONDARY);
|
||||
checkButton.setEnabled(updates.status!=AppUpdateChecker.Status.CHECKING);
|
||||
checkButton.setAlpha(checkButton.isEnabled()?1f:.5f);
|
||||
}
|
||||
private void components(){
|
||||
LinearLayout content=activity.formPage("open-source","开源组件",this::show);
|
||||
LinearLayout notice=activity.section(content,"OpenFEC 告知");
|
||||
paragraph(notice,"本应用使用 OpenFEC 提供前向纠错功能,遵循 CeCILL-C 1.0 许可。该许可规定了有限保证及责任限制,详情见许可全文。",SECONDARY);
|
||||
ui.divider(notice);paragraph(notice,"(c) Copyright 2009 - 2012 INRIA - All rights reserved",INK);ui.divider(notice);
|
||||
activity.link(notice,"OpenFEC 许可与源码","",()->component(catalog.find("openfec"),this::components));ui.gap(content,28);
|
||||
LinearLayout list=activity.section(content,"");boolean first=true;
|
||||
for(LicenseCatalog.Component item:catalog.components){
|
||||
if(item.id.equals("crossdesk")||item.id.equals("openfec"))continue;
|
||||
if(!first)ui.divider(list);first=false;
|
||||
LinearLayout row=ui.row();row.setPadding(ui.dp(16),ui.dp(12),ui.dp(12),ui.dp(12));
|
||||
LinearLayout labels=ui.column();labels.addView(ui.text(item.name,16,false));ui.gap(labels,4);
|
||||
TextView license=ui.text(item.license,12,false);license.setTextColor(SECONDARY);labels.addView(license);
|
||||
row.addView(labels,new LinearLayout.LayoutParams(0,-2,1));TextView chevron=ui.text(" ›",23,false);chevron.setTextColor(0xFFB7B7BD);row.addView(chevron);
|
||||
row.setContentDescription(item.name+","+item.license);row.setClickable(true);row.setFocusable(true);row.setOnClickListener(v->component(item,this::components));list.addView(row);
|
||||
}
|
||||
activity.footer(content,"各组件遵循所列开源许可证,其授予的权利不受本应用普通使用条款限制。查看源码需要网络连接。");
|
||||
}
|
||||
private void component(LicenseCatalog.Component item,Runnable back){
|
||||
LinearLayout content=activity.formPage("license:"+item.id,item.name,back);LinearLayout info=activity.section(content,"");
|
||||
String version=item.id.equals("crossdesk")?applicationVersion():item.version.length()==40?item.version.substring(0,12):item.version;
|
||||
value(info,"版本",version);ui.divider(info);value(info,"许可",item.license);ui.divider(info);
|
||||
external(info,"查看源码",item.sourceURL);
|
||||
if(!item.buildDocuments.isEmpty()||!item.buildSourceURL.isEmpty()){
|
||||
ui.divider(info);
|
||||
if(!item.buildDocuments.isEmpty())activity.link(info,"构建配方与项目补丁","",()->buildSources(item,back));
|
||||
else external(info,"构建配方与项目补丁",item.buildSourceURL);
|
||||
}
|
||||
ui.gap(content,16);LinearLayout docs=activity.section(content,"许可与版权声明");
|
||||
for(int i=0;i<item.documents.size();i++){
|
||||
if(i>0)ui.divider(docs);LicenseCatalog.Document document=item.documents.get(i);
|
||||
activity.link(docs,item.documentTitle(document),"",()->document(item.documentTitle(document),document,()->component(item,back)));
|
||||
}
|
||||
}
|
||||
private void source(){
|
||||
LinearLayout content=activity.formPage("source","源码与构建说明",this::show);
|
||||
LinearLayout info=activity.section(content,"本版本源码与构建说明");
|
||||
if(catalog.source==null){paragraph(info,"本版本源码信息暂不可用。",SECONDARY);ui.divider(info);external(info,"项目主页","https://github.com/kunkundi/crossdesk");return;}
|
||||
String revision=catalog.source.optString("revision","");String tag=catalog.source.isNull("tag")?"":catalog.source.optString("tag","");
|
||||
value(info,"源码版本",tag.isEmpty()?revision.substring(0,Math.min(12,revision.length())):tag);ui.divider(info);
|
||||
if(catalog.source.optBoolean("isModified")){paragraph(info,"开发版本包含尚未发布的修改,以下链接为基础版本源码。",SECONDARY);ui.divider(info);}
|
||||
external(info,"查看源码",catalog.source.optString("sourceURL",catalog.find("crossdesk").sourceURL));ui.divider(info);
|
||||
try{
|
||||
List<LicenseCatalog.Document> documents=LicenseCatalog.documents(catalog.source.optJSONArray("buildDocuments"));
|
||||
if(!documents.isEmpty())actionLink(info,"构建说明",()->document("构建说明",documents.get(0),this::source));
|
||||
else external(info,"构建说明",catalog.source.optString("buildInstructionsURL","https://github.com/kunkundi/crossdesk"));
|
||||
}catch(org.json.JSONException error){paragraph(info,"本版本源码信息暂不可用。",SECONDARY);}
|
||||
}
|
||||
private void buildSources(LicenseCatalog.Component item,Runnable back){
|
||||
LinearLayout content=activity.formPage("build:"+item.id,"构建配方与项目补丁",()->component(item,back));
|
||||
if(!item.buildSourceURL.isEmpty()){LinearLayout upstream=activity.section(content,"");external(upstream,"查看源码",item.buildSourceURL);ui.gap(content,28);}
|
||||
LinearLayout docs=activity.section(content,"");
|
||||
for(int i=0;i<item.buildDocuments.size();i++){
|
||||
if(i>0)ui.divider(docs);LicenseCatalog.Document document=item.buildDocuments.get(i);
|
||||
activity.link(docs,document.title,"",()->document(document.title,document,()->buildSources(item,back)));
|
||||
}
|
||||
}
|
||||
private void document(String title,LicenseCatalog.Document document,Runnable back){
|
||||
try{activity.licenseDocument(title,LicenseCatalog.read(activity,document.asset),back);}catch(java.io.IOException error){unavailable(activity.formPage("license-error",title,back));}
|
||||
}
|
||||
private void value(LinearLayout parent,String label,String value){
|
||||
LinearLayout row=ui.row();row.setPadding(ui.dp(16),ui.dp(14),ui.dp(16),ui.dp(14));
|
||||
TextView key=ui.text(label,16,false);key.setPadding(0,0,ui.dp(16),0);row.addView(key);
|
||||
TextView content=ui.text(value,16,false);content.setTextColor(SECONDARY);content.setGravity(Gravity.END);content.setTextIsSelectable(true);row.addView(content,new LinearLayout.LayoutParams(0,-2,1));parent.addView(row);
|
||||
}
|
||||
private void paragraph(LinearLayout parent,String text,int color){TextView view=ui.text(text,13,false);view.setTextColor(color);view.setPadding(ui.dp(16),ui.dp(12),ui.dp(16),ui.dp(12));view.setLineSpacing(ui.dp(3),1);parent.addView(view);}
|
||||
private void external(LinearLayout parent,String title,String url){
|
||||
actionLink(parent,title,()->open(url));
|
||||
}
|
||||
private void actionLink(LinearLayout parent,String title,Runnable action){TextView link=ui.action(title,BLUE,action);link.setTypeface(android.graphics.Typeface.DEFAULT);link.setGravity(Gravity.START|Gravity.CENTER_VERTICAL);link.setPadding(ui.dp(16),ui.dp(12),ui.dp(16),ui.dp(12));parent.addView(link);}
|
||||
private void open(String url){
|
||||
Uri uri=Uri.parse(url);if(!"https".equals(uri.getScheme())&&!"http".equals(uri.getScheme()))return;
|
||||
try{activity.startActivity(new Intent(Intent.ACTION_VIEW,uri).addCategory(Intent.CATEGORY_BROWSABLE));}catch(ActivityNotFoundException error){Toast.makeText(activity,"未找到可打开链接的浏览器",Toast.LENGTH_SHORT).show();}
|
||||
}
|
||||
private void unavailable(LinearLayout content){
|
||||
content.setGravity(Gravity.CENTER);ui.gap(content,32);TextView icon=ui.text("▤",36,false);icon.setTextColor(SECONDARY);content.addView(icon);ui.gap(content,12);
|
||||
content.addView(ui.text("无法读取开源许可",17,true));TextView message=ui.text("应用中的许可文件缺失或损坏,请重新安装应用。",14,false);message.setGravity(Gravity.CENTER);message.setTextColor(SECONDARY);content.addView(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.AtomicFile;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
|
||||
/** Main-thread inbox. The server owns content; this device owns read/dismissed revisions. */
|
||||
final class AnnouncementInbox implements AutoCloseable {
|
||||
interface Sender { void send(JSONObject request, String requestId); }
|
||||
static final class Item {
|
||||
final long id, revision, updatedAt;
|
||||
final String title, body;
|
||||
boolean read;
|
||||
Item(JSONObject json) throws Exception {
|
||||
id=integer(json,"id");revision=integer(json,"revision");updatedAt=integer(json,"updated_at");
|
||||
title=string(json,"title");body=string(json,"body");
|
||||
if(id<=0||revision<=0||updatedAt<=0||updatedAt>32_503_680_000L||
|
||||
title.getBytes(StandardCharsets.UTF_8).length>240||body.getBytes(StandardCharsets.UTF_8).length>8000)
|
||||
throw new IllegalArgumentException("Invalid announcement");
|
||||
}
|
||||
}
|
||||
final List<Item> items=new ArrayList<>();
|
||||
int total, unread;
|
||||
boolean loaded, loading, failed, readSaveFailed, deleteFailed;
|
||||
Sender sender;
|
||||
Runnable changed=()->{};
|
||||
private final File directory;
|
||||
private final Handler handler=new Handler(Looper.getMainLooper());
|
||||
private final Map<Long,Long> reads=new HashMap<>(), dismissed=new HashMap<>();
|
||||
private Map<Long,Long> catalog=new LinkedHashMap<>(), pendingCatalog=new LinkedHashMap<>();
|
||||
private final Map<Integer,List<Long>> pageIds=new HashMap<>();
|
||||
private final Map<Integer,List<Item>> pageBodies=new HashMap<>();
|
||||
private long catalogRevision=-1, pendingRevision=-1;
|
||||
private int pendingTotal, pageOffset, visibleLimit=20;
|
||||
private boolean summary=true, connected;
|
||||
private String scope="", requestId;
|
||||
private AtomicFile file;
|
||||
private Runnable timeout;
|
||||
|
||||
AnnouncementInbox(File directory){this.directory=directory;}
|
||||
boolean isConnected(){return connected;}
|
||||
void configure(String host,int port,String deviceId){
|
||||
if(host.isEmpty()||port<=0||deviceId.isEmpty())return;
|
||||
String canonical=host.toLowerCase(Locale.ROOT);
|
||||
if(canonical.endsWith("."))canonical=canonical.substring(0,canonical.length()-1);
|
||||
String next=new JSONArray().put(canonical).put(port).put(deviceId).toString();
|
||||
if(scope.equals(next))return;
|
||||
boolean wasConnected=connected;reset();connected=wasConnected;scope=next;
|
||||
try{
|
||||
byte[] hash=MessageDigest.getInstance("SHA-256").digest(scope.getBytes(StandardCharsets.UTF_8));
|
||||
StringBuilder name=new StringBuilder();for(byte b:hash)name.append(String.format(Locale.ROOT,"%02x",b&255));
|
||||
file=new AtomicFile(new File(directory,name+".json"));loadLocalState();
|
||||
}catch(Exception error){file=null;}
|
||||
refresh();
|
||||
}
|
||||
void reset(){
|
||||
cancelRequest();scope="";file=null;connected=false;items.clear();reads.clear();dismissed.clear();
|
||||
catalog.clear();pendingCatalog.clear();pageIds.clear();pageBodies.clear();
|
||||
catalogRevision=pendingRevision=-1;pendingTotal=pageOffset=total=unread=0;visibleLimit=20;
|
||||
loaded=failed=readSaveFailed=deleteFailed=false;changed.run();
|
||||
}
|
||||
void setConnected(boolean value){
|
||||
if(connected==value)return;connected=value;
|
||||
if(value)refresh();else{cancelRequest();changed.run();}
|
||||
}
|
||||
void refresh(){
|
||||
cancelRequest();pendingCatalog=new LinkedHashMap<>();pendingRevision=-1;pendingTotal=0;summary=true;
|
||||
request(0);changed.run();
|
||||
}
|
||||
void loadMore(){
|
||||
if(!connected||loading||failed||catalogRevision<0||visibleLimit>=total)return;
|
||||
visibleLimit+=Math.min(20,total-visibleLimit);rebuild();changed.run();
|
||||
}
|
||||
Item find(long id,long revision){
|
||||
for(Item item:items)if(item.id==id&&item.revision==revision)return item;return null;
|
||||
}
|
||||
void markRead(Item item){
|
||||
if(find(item.id,item.revision)==null||Objects.equals(reads.get(item.id),item.revision))return;
|
||||
Map<Long,Long> updated=new HashMap<>(reads);updated.put(item.id,item.revision);
|
||||
if(!saveLocalState(updated,dismissed)){readSaveFailed=true;changed.run();return;}
|
||||
reads.clear();reads.putAll(updated);readSaveFailed=deleteFailed=false;updateReadingState();changed.run();
|
||||
}
|
||||
void dismiss(Item item){
|
||||
if(find(item.id,item.revision)==null){deleteFailed=true;changed.run();return;}
|
||||
Map<Long,Long> updated=new HashMap<>(dismissed);updated.put(item.id,item.revision);
|
||||
if(!saveLocalState(reads,updated)){deleteFailed=true;changed.run();return;}
|
||||
dismissed.clear();dismissed.putAll(updated);deleteFailed=readSaveFailed=false;
|
||||
if(summary&&loading){items.removeIf(this::isDismissed);updateReadingState();}
|
||||
else{cancelRequest();rebuild();}
|
||||
changed.run();
|
||||
}
|
||||
void failed(String id){
|
||||
if(!Objects.equals(requestId,id)||id==null)return;
|
||||
cancelRequest();failed=true;changed.run();
|
||||
}
|
||||
void receive(JSONObject message){
|
||||
Object identifier=message.opt("request_id");
|
||||
if(!(identifier instanceof String)||!identifier.equals(requestId))return;
|
||||
String id=(String)identifier;
|
||||
try{
|
||||
if(!"announcements".equals(string(message,"type"))||message.has("error"))throw new IllegalArgumentException();
|
||||
Object summaryFlag=message.get("summary_only");
|
||||
long offsetValue=integer(message,"offset"), totalValue=integer(message,"total");
|
||||
long revision=integer(message,"catalog_revision");JSONArray entries=message.getJSONArray("items");
|
||||
if(!(summaryFlag instanceof Boolean)||((Boolean)summaryFlag)!=summary||offsetValue<0||
|
||||
totalValue<offsetValue||totalValue>Integer.MAX_VALUE||revision<0||
|
||||
entries.length()!=Math.min(summary?200:20,totalValue-offsetValue))throw new IllegalArgumentException();
|
||||
int offset=(int)offsetValue, count=(int)totalValue;
|
||||
LinkedHashMap<Long,Long> entriesById=new LinkedHashMap<>();
|
||||
for(int i=0;i<entries.length();i++){
|
||||
JSONObject entry=entries.getJSONObject(i);long key=integer(entry,"id"), version=integer(entry,"revision");
|
||||
if(key<=0||version<=0||entriesById.put(key,version)!=null)throw new IllegalArgumentException();
|
||||
}
|
||||
long expected=summary?pendingRevision:catalogRevision;
|
||||
if(expected>=0&&expected!=revision){refresh();return;}
|
||||
if(summary){
|
||||
if(offset!=pendingCatalog.size()||(pendingRevision>=0&&pendingTotal!=count))throw new IllegalArgumentException();
|
||||
for(Map.Entry<Long,Long> entry:entriesById.entrySet())
|
||||
if(pendingCatalog.put(entry.getKey(),entry.getValue())!=null)throw new IllegalArgumentException();
|
||||
pendingRevision=revision;pendingTotal=count;cancelRequest();
|
||||
if(pendingCatalog.size()<pendingTotal){request(pendingCatalog.size());changed.run();return;}
|
||||
if(catalogRevision!=pendingRevision){pageIds.clear();pageBodies.clear();}
|
||||
catalog=new LinkedHashMap<>(pendingCatalog);catalogRevision=pendingRevision;
|
||||
reads.keySet().retainAll(catalog.keySet());dismissed.keySet().retainAll(catalog.keySet());
|
||||
}else{
|
||||
if(offset!=pageOffset||count!=catalog.size())throw new IllegalArgumentException();
|
||||
List<Item> bodies=new ArrayList<>();
|
||||
for(int i=0;i<entries.length();i++){
|
||||
Item item=new Item(entries.getJSONObject(i));
|
||||
if(!Objects.equals(catalog.get(item.id),item.revision))throw new IllegalArgumentException();
|
||||
// A repeated ID on another body page must not create duplicate rows.
|
||||
for(Map.Entry<Integer,List<Long>> page:pageIds.entrySet())
|
||||
if(page.getKey()!=offset&&page.getValue().contains(item.id))throw new IllegalArgumentException();
|
||||
bodies.add(item);
|
||||
}
|
||||
cancelRequest();pageIds.put(offset,new ArrayList<>(entriesById.keySet()));pageBodies.put(offset,bodies);
|
||||
}
|
||||
failed=false;rebuild();changed.run();
|
||||
}catch(Exception error){failed(id);}
|
||||
}
|
||||
private void request(int offset){
|
||||
if(!connected||scope.isEmpty())return;
|
||||
String id=UUID.randomUUID().toString();
|
||||
try{
|
||||
JSONObject payload=new JSONObject().put("type","announcements_list").put("request_id",id)
|
||||
.put("summary_only",summary).put("offset",offset);
|
||||
requestId=id;loading=true;failed=false;timeout=()->failed(id);handler.postDelayed(timeout,12_000);
|
||||
if(sender!=null)sender.send(payload,id);else failed(id);
|
||||
}catch(Exception error){failed(id);}
|
||||
}
|
||||
private void cancelRequest(){
|
||||
if(timeout!=null)handler.removeCallbacks(timeout);timeout=null;requestId=null;loading=false;
|
||||
}
|
||||
private boolean isDismissed(Item item){return Objects.equals(dismissed.get(item.id),item.revision);}
|
||||
private void updateReadingState(){
|
||||
total=unread=0;
|
||||
for(Map.Entry<Long,Long> entry:catalog.entrySet()){
|
||||
if(Objects.equals(dismissed.get(entry.getKey()),entry.getValue()))continue;
|
||||
total++;if(!Objects.equals(reads.get(entry.getKey()),entry.getValue()))unread++;
|
||||
}
|
||||
for(Item item:items)item.read=Objects.equals(reads.get(item.id),item.revision);
|
||||
}
|
||||
private void rebuild(){
|
||||
updateReadingState();int wanted=Math.min(visibleLimit,total), position=0;Integer nextOffset=null;
|
||||
List<Item> visible=new ArrayList<>();Set<Integer> retainedPages=new HashSet<>();summary=false;
|
||||
if(wanted>0)for(int offset=0;offset<catalog.size();offset+=20){
|
||||
List<Long> ids=pageIds.get(offset);if(ids==null){nextOffset=offset;break;}
|
||||
Set<Long> selection=new HashSet<>();
|
||||
for(long id:ids){
|
||||
Long revision=catalog.get(id);if(revision==null||Objects.equals(dismissed.get(id),revision))continue;
|
||||
if(position<wanted)selection.add(id);position++;
|
||||
}
|
||||
if(selection.isEmpty()){pageBodies.remove(offset);continue;}
|
||||
retainedPages.add(offset);List<Item> bodies=pageBodies.get(offset);
|
||||
if(bodies==null){nextOffset=offset;break;}
|
||||
for(Item item:bodies)if(selection.contains(item.id))visible.add(item);
|
||||
if(visible.size()==wanted)break;
|
||||
}
|
||||
if(visible.size()==wanted)pageBodies.keySet().retainAll(retainedPages);
|
||||
else{
|
||||
Set<Long> retained=new HashSet<>();for(Item item:visible)retained.add(item.id);
|
||||
for(Item item:items)if(Objects.equals(catalog.get(item.id),item.revision)&&!isDismissed(item)&&retained.add(item.id)){
|
||||
visible.add(item);if(visible.size()==wanted)break;
|
||||
}
|
||||
}
|
||||
items.clear();items.addAll(visible);loaded=true;updateReadingState();
|
||||
if(nextOffset!=null){pageOffset=nextOffset;request(nextOffset);}
|
||||
}
|
||||
private void loadLocalState(){
|
||||
if(file==null||file.getBaseFile().length()>16*1024*1024)return;
|
||||
try{
|
||||
JSONObject saved=new JSONObject(new String(file.readFully(),StandardCharsets.UTF_8));
|
||||
long version=integer(saved,"version");
|
||||
if(!scope.equals(string(saved,"scope"))||(version!=1&&version!=2))return;
|
||||
loadRevisions(saved.optJSONObject("reads"),reads);loadRevisions(saved.optJSONObject("dismissed"),dismissed);
|
||||
}catch(Exception ignored){}
|
||||
}
|
||||
private static void loadRevisions(JSONObject json,Map<Long,Long> target){
|
||||
if(json==null)return;
|
||||
for(Iterator<String> keys=json.keys();keys.hasNext();){
|
||||
String key=keys.next();
|
||||
try{long id=Long.parseLong(key), revision=integer(json,key);if(id>0&&revision>0)target.put(id,revision);}catch(Exception ignored){}
|
||||
}
|
||||
}
|
||||
private boolean saveLocalState(Map<Long,Long> readValues,Map<Long,Long> dismissedValues){
|
||||
if(file==null)return false;FileOutputStream output=null;
|
||||
try{
|
||||
if(!directory.isDirectory()&&!directory.mkdirs())return false;
|
||||
JSONObject saved=new JSONObject().put("version",2).put("scope",scope)
|
||||
.put("reads",revisions(readValues)).put("dismissed",revisions(dismissedValues));
|
||||
byte[] bytes=saved.toString().getBytes(StandardCharsets.UTF_8);
|
||||
output=file.startWrite();output.write(bytes);output.getFD().sync();file.finishWrite(output);output=null;
|
||||
// AtomicFile logs some rename failures instead of throwing; verify the committed file.
|
||||
return Arrays.equals(bytes,file.readFully());
|
||||
}catch(Exception error){if(output!=null)file.failWrite(output);return false;}
|
||||
}
|
||||
private static JSONObject revisions(Map<Long,Long> values)throws Exception{
|
||||
JSONObject json=new JSONObject();for(Map.Entry<Long,Long> entry:values.entrySet())json.put(entry.getKey().toString(),entry.getValue());return json;
|
||||
}
|
||||
private static long integer(JSONObject json,String key)throws Exception{
|
||||
Object value=json.get(key);if(!(value instanceof Integer)&&!(value instanceof Long))throw new IllegalArgumentException(key);
|
||||
return ((Number)value).longValue();
|
||||
}
|
||||
private static String string(JSONObject json,String key)throws Exception{
|
||||
Object value=json.get(key);if(!(value instanceof String))throw new IllegalArgumentException(key);return (String)value;
|
||||
}
|
||||
@Override public void close(){cancelRequest();connected=false;sender=null;changed=()->{};}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.text.SpannableStringBuilder;
|
||||
import android.text.Spanned;
|
||||
import android.text.style.URLSpan;
|
||||
import android.view.View;
|
||||
import android.widget.Toast;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Plain text plus HTTP(S) links, matching iOS; never interpret HTML or arbitrary Markdown. */
|
||||
final class AnnouncementText {
|
||||
static CharSequence format(String body){
|
||||
String text=body.replace("\r\n","\n");SpannableStringBuilder result=new SpannableStringBuilder();
|
||||
for(int position=0;position<text.length();){
|
||||
if(text.charAt(position)=='['){
|
||||
int labelEnd=text.indexOf(']',position+1), start=labelEnd+2;
|
||||
if(labelEnd>position+1&&start<text.length()&&text.charAt(labelEnd+1)=='('&&
|
||||
!text.substring(position+1,labelEnd).matches("(?s).*[\\[\\]\\r\\n].*")&&hasScheme(text,start)){
|
||||
int end=urlEnd(text,start);
|
||||
if(end<text.length()&&text.charAt(end)==')'&&
|
||||
appendLink(result,text.substring(position+1,labelEnd),text.substring(start,end))){
|
||||
position=end+1;continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(hasScheme(text,position)){
|
||||
int end=urlEnd(text,position);
|
||||
while(end>position&&".,;:!?".indexOf(text.charAt(end-1))>=0)end--;
|
||||
String address=text.substring(position,end);
|
||||
if(appendLink(result,address,address)){position=end;continue;}
|
||||
}
|
||||
result.append(text.charAt(position++));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
static boolean isWebURL(String address){
|
||||
if(address==null)return false;
|
||||
for(int i=0;i<address.length();i++){char c=address.charAt(i);if(c<=0x20||c==0x7f||"\\<>\"".indexOf(c)>=0)return false;}
|
||||
Uri uri=Uri.parse(address);String scheme=uri.getScheme(),host=uri.getHost();
|
||||
return scheme!=null&&(scheme.equalsIgnoreCase("http")||scheme.equalsIgnoreCase("https"))&&host!=null&&!host.isEmpty();
|
||||
}
|
||||
private static boolean hasScheme(String text,int start){
|
||||
String prefix=text.substring(start,Math.min(text.length(),start+8)).toLowerCase(Locale.ROOT);
|
||||
return prefix.startsWith("https://")||prefix.startsWith("http://");
|
||||
}
|
||||
private static int urlEnd(String text,int start){
|
||||
int parentheses=0,brackets=0,end=start;
|
||||
for(;end<text.length();end++){
|
||||
char c=text.charAt(end);
|
||||
if(c<=0x20||c==0x7f||c=='\\'||c==96||"<>\"'{},。;:!?、()【】《》「」『』“”‘’".indexOf(c)>=0)break;
|
||||
if(c=='(')parentheses++;
|
||||
if(c==')'){if(parentheses==0)break;parentheses--;}
|
||||
if(c=='[')brackets++;
|
||||
if(c==']'){if(brackets==0)break;brackets--;}
|
||||
}
|
||||
return end;
|
||||
}
|
||||
private static boolean appendLink(SpannableStringBuilder result,String label,String destination){
|
||||
if(!isWebURL(destination))return false;
|
||||
int start=result.length();result.append(label);
|
||||
result.setSpan(new URLSpan(destination){
|
||||
@Override public void onClick(View widget){
|
||||
if(!isWebURL(getURL()))return;
|
||||
try{widget.getContext().startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(getURL())).addCategory(Intent.CATEGORY_BROWSABLE));}
|
||||
catch(android.content.ActivityNotFoundException error){Toast.makeText(widget.getContext(),"没有可打开网页的浏览器",Toast.LENGTH_SHORT).show();}
|
||||
}
|
||||
},start,result.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.app.AlertDialog;
|
||||
import android.content.res.ColorStateList;
|
||||
import android.graphics.Color;
|
||||
import android.text.TextUtils;
|
||||
import android.text.method.LinkMovementMethod;
|
||||
import android.view.*;
|
||||
import android.widget.*;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
import java.util.function.Consumer;
|
||||
import static cn.crossdesk.mobile.MobileUi.*;
|
||||
|
||||
/** Grouped announcement list and plain-text detail, sharing the iOS presentation. */
|
||||
@android.annotation.SuppressLint("ViewConstructor")
|
||||
final class AnnouncementView extends ScrollView {
|
||||
private final MobileUi ui;
|
||||
private final AnnouncementInbox inbox;
|
||||
private final LinearLayout content;
|
||||
private final Consumer<AnnouncementInbox.Item> open;
|
||||
private final Runnable authorize;
|
||||
private final boolean detail;
|
||||
private final long id,revision;
|
||||
private final SimpleDateFormat dates=new SimpleDateFormat("yyyy-MM-dd HH:mm",Locale.getDefault());
|
||||
private TextView countLabel;
|
||||
private AlertDialog deleteDialog;
|
||||
private float downX,downY;
|
||||
private boolean pulling,canPull;
|
||||
private final int slop;
|
||||
|
||||
AnnouncementView(MobileUi ui,AnnouncementInbox inbox,AnnouncementInbox.Item selected,
|
||||
Consumer<AnnouncementInbox.Item> open,Runnable authorize){
|
||||
super(ui.context);this.ui=ui;this.inbox=inbox;this.open=open;this.authorize=authorize;
|
||||
detail=selected!=null;id=detail?selected.id:0;revision=detail?selected.revision:0;
|
||||
slop=ViewConfiguration.get(getContext()).getScaledTouchSlop();
|
||||
setFillViewport(true);setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY);
|
||||
content=ui.column();content.setPadding(ui.dp(20),ui.dp(detail?20:16),ui.dp(20),ui.dp(28));
|
||||
addView(content,new ScrollView.LayoutParams(-1,-2));
|
||||
setOnScrollChangeListener((v,x,y,oldX,oldY)->{if(y>oldY)loadVisiblePage();});
|
||||
render();
|
||||
}
|
||||
void render(){
|
||||
int y=getScrollY();content.removeAllViews();countLabel=null;
|
||||
if(detail)renderDetail();else renderList();
|
||||
post(()->{if(isAttachedToWindow()){scrollTo(0,y);loadVisiblePage();}});
|
||||
}
|
||||
private String date(AnnouncementInbox.Item item){return dates.format(new Date(item.updatedAt*1000));}
|
||||
private TextView message(String value,int color){
|
||||
TextView text=ui.text(value,14,false);text.setTextColor(color);text.setLineSpacing(ui.dp(3),1);return text;
|
||||
}
|
||||
private void renderList(){
|
||||
if(inbox.deleteFailed){content.addView(message("无法删除这条公告,请重试。",RED));ui.gap(content,12);}
|
||||
if(!inbox.isConnected()){
|
||||
content.addView(message("连接服务器后可获取最新公告。",SECONDARY));
|
||||
content.addView(ui.action("连接服务器",BLUE,authorize));ui.gap(content,8);
|
||||
}else if(inbox.failed){
|
||||
LinearLayout error=ui.row();error.addView(message("公告加载失败,请重试。",SECONDARY),new LinearLayout.LayoutParams(0,-2,1));
|
||||
error.addView(ui.action("重试",BLUE,inbox::refresh),ui.size(64,48));content.addView(error);ui.gap(content,8);
|
||||
}
|
||||
countLabel=ui.text("共 "+inbox.total+" 条 · "+inbox.unread+" 条未读",13,false);
|
||||
countLabel.setTextColor(SECONDARY);countLabel.setPadding(ui.dp(16),ui.dp(8),0,ui.dp(8));content.addView(countLabel);
|
||||
LinearLayout card=ui.column();ui.card(card,12);content.addView(card);
|
||||
for(AnnouncementInbox.Item item:inbox.items){
|
||||
if(card.getChildCount()>0)ui.divider(card);
|
||||
card.addView(itemRow(item),ui.size(-1,-2));
|
||||
}
|
||||
if(inbox.loading){
|
||||
LinearLayout loading=ui.row();loading.setGravity(Gravity.CENTER);loading.setPadding(0,ui.dp(18),0,ui.dp(18));
|
||||
ProgressBar spinner=new ProgressBar(getContext());spinner.setIndeterminateTintList(ColorStateList.valueOf(BLUE));loading.addView(spinner,ui.size(20,20));
|
||||
TextView label=message("加载中…",SECONDARY);label.setPadding(ui.dp(10),0,0,0);loading.addView(label);card.addView(loading);
|
||||
}else if(inbox.items.size()<inbox.total&&!inbox.failed){
|
||||
TextView more=ui.action("加载更多",BLUE,inbox::loadMore);more.setEnabled(inbox.isConnected());card.addView(more,ui.size(-1,48));
|
||||
}else if(inbox.loaded&&inbox.total==0&&!inbox.failed&&inbox.isConnected()){
|
||||
TextView empty=message("暂无公告",SECONDARY);empty.setGravity(Gravity.CENTER);card.addView(empty,ui.size(-1,120));
|
||||
}
|
||||
}
|
||||
private View itemRow(AnnouncementInbox.Item item){
|
||||
LinearLayout row=ui.row();row.setBackgroundColor(Color.WHITE);row.setPadding(ui.dp(16),ui.dp(16),ui.dp(12),ui.dp(16));
|
||||
LinearLayout words=ui.column();
|
||||
LinearLayout top=ui.row();top.setGravity(Gravity.TOP);
|
||||
View dot=new View(getContext());dot.setBackground(ui.background(item.read?Color.TRANSPARENT:BLUE,4));
|
||||
LinearLayout.LayoutParams dotLayout=ui.size(7,7);dotLayout.topMargin=ui.dp(7);dotLayout.rightMargin=ui.dp(10);top.addView(dot,dotLayout);
|
||||
TextView title=ui.text(item.title,16,!item.read);title.setMaxLines(2);title.setEllipsize(TextUtils.TruncateAt.END);
|
||||
words.addView(title,ui.size(-1,-2));ui.gap(words,7);TextView date=ui.text(date(item),12,false);date.setTextColor(SECONDARY);words.addView(date);
|
||||
top.addView(words,new LinearLayout.LayoutParams(0,-2,1));row.addView(top,new LinearLayout.LayoutParams(0,-2,1));
|
||||
TextView chevron=ui.text("›",23,false);chevron.setTextColor(0xFFB7B7BD);chevron.setPadding(ui.dp(10),0,0,0);row.addView(chevron);
|
||||
row.setContentDescription(item.title+","+date(item)+","+(item.read?"已读":"未读"));row.setFocusable(true);
|
||||
row.setOnClickListener(v->open.accept(item));row.setOnLongClickListener(v->{confirmDelete(item);return true;});
|
||||
return new SwipeRow(row,()->confirmDelete(item));
|
||||
}
|
||||
private void confirmDelete(AnnouncementInbox.Item item){
|
||||
if(deleteDialog!=null)deleteDialog.dismiss();
|
||||
deleteDialog=new AlertDialog.Builder(getContext()).setTitle("删除公告").setMessage("删除这条公告?")
|
||||
.setNegativeButton("取消",null).setPositiveButton("删除",(dialog,which)->inbox.dismiss(item)).show();
|
||||
}
|
||||
private void renderDetail(){
|
||||
AnnouncementInbox.Item item=inbox.find(id,revision);
|
||||
if(item==null){content.addView(message("这条公告已更新或删除,请返回公告列表查看。",SECONDARY));return;}
|
||||
content.addView(ui.text(item.title,22,true));ui.gap(content,16);
|
||||
TextView date=ui.text(date(item)+" · "+(item.read?"已读":"未读"),12,false);date.setTextColor(SECONDARY);content.addView(date);ui.gap(content,16);
|
||||
if(inbox.readSaveFailed){
|
||||
content.addView(message("无法保存本地阅读状态,请重试。",RED));
|
||||
content.addView(ui.action("重试保存阅读状态",BLUE,()->inbox.markRead(item)));ui.gap(content,16);
|
||||
}
|
||||
TextView body=ui.text("",17,false);body.setText(AnnouncementText.format(item.body));body.setTextIsSelectable(true);
|
||||
body.setMovementMethod(LinkMovementMethod.getInstance());body.setLinksClickable(true);body.setLinkTextColor(BLUE);body.setLineSpacing(ui.dp(4),1);
|
||||
content.addView(body,ui.size(-1,-2));
|
||||
}
|
||||
private void loadVisiblePage(){
|
||||
if(!detail&&isAttachedToWindow()&&inbox.isConnected()&&!inbox.loading&&!inbox.failed&&inbox.items.size()<inbox.total&&
|
||||
content.getHeight()>0&&getHeight()>0&&getScrollY()+getHeight()>=content.getHeight()-ui.dp(48))inbox.loadMore();
|
||||
}
|
||||
private void trackPull(MotionEvent event){
|
||||
if(!detail&&inbox.isConnected()&&!inbox.loading){
|
||||
if(event.getActionMasked()==MotionEvent.ACTION_DOWN){downX=event.getX();downY=event.getY();pulling=false;canPull=getScrollY()==0;}
|
||||
else if(event.getActionMasked()==MotionEvent.ACTION_MOVE&&canPull&&getScrollY()==0&&
|
||||
event.getY()-downY>slop&&event.getY()-downY>Math.abs(event.getX()-downX))pulling=true;
|
||||
}
|
||||
}
|
||||
@Override public boolean onInterceptTouchEvent(MotionEvent event){
|
||||
trackPull(event);return pulling||super.onInterceptTouchEvent(event);
|
||||
}
|
||||
@android.annotation.SuppressLint("ClickableViewAccessibility") // Pull gesture only; toolbar refresh is the accessible action.
|
||||
@Override public boolean onTouchEvent(MotionEvent event){
|
||||
trackPull(event);
|
||||
if(!pulling)return super.onTouchEvent(event);
|
||||
boolean reached=event.getY()-downY>=ui.dp(72);
|
||||
if(event.getActionMasked()==MotionEvent.ACTION_MOVE&&countLabel!=null)countLabel.setText(reached?"松开刷新":"下拉刷新");
|
||||
if(event.getActionMasked()==MotionEvent.ACTION_UP||event.getActionMasked()==MotionEvent.ACTION_CANCEL){
|
||||
pulling=false;if(reached&&event.getActionMasked()==MotionEvent.ACTION_UP)inbox.refresh();else render();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@Override protected void onDetachedFromWindow(){if(deleteDialog!=null)deleteDialog.dismiss();super.onDetachedFromWindow();}
|
||||
|
||||
/** Reveal a delete action without interfering with vertical scrolling or row taps. */
|
||||
private final class SwipeRow extends FrameLayout {
|
||||
private final View front,remove;
|
||||
private float x,y,origin;
|
||||
private boolean dragging;
|
||||
SwipeRow(View front,Runnable delete){
|
||||
super(ui.context);this.front=front;setClipChildren(true);
|
||||
remove=ui.action("删除",Color.WHITE,delete);remove.setBackgroundColor(RED);
|
||||
remove.setVisibility(INVISIBLE);
|
||||
remove.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);remove.setFocusable(false);
|
||||
addView(remove,new FrameLayout.LayoutParams(ui.dp(76),-1,Gravity.END));addView(front,new FrameLayout.LayoutParams(-1,-2));
|
||||
}
|
||||
@Override public boolean onInterceptTouchEvent(MotionEvent event){
|
||||
if(event.getActionMasked()==MotionEvent.ACTION_DOWN){front.animate().cancel();x=event.getX();y=event.getY();origin=front.getTranslationX();dragging=false;}
|
||||
if(event.getActionMasked()==MotionEvent.ACTION_MOVE&&Math.abs(event.getX()-x)>slop&&Math.abs(event.getX()-x)>Math.abs(event.getY()-y)){
|
||||
dragging=true;remove.setVisibility(VISIBLE);getParent().requestDisallowInterceptTouchEvent(true);return true;
|
||||
}
|
||||
return super.onInterceptTouchEvent(event);
|
||||
}
|
||||
@android.annotation.SuppressLint("ClickableViewAccessibility") // Taps/long presses belong to the accessible row and delete button.
|
||||
@Override public boolean onTouchEvent(MotionEvent event){
|
||||
if(!dragging)return super.onTouchEvent(event);
|
||||
int direction=getLayoutDirection()==LAYOUT_DIRECTION_RTL?1:-1;
|
||||
if(event.getActionMasked()==MotionEvent.ACTION_MOVE)front.setTranslationX(direction*Math.max(0,Math.min(ui.dp(76),direction*(origin+event.getX()-x))));
|
||||
if(event.getActionMasked()==MotionEvent.ACTION_UP||event.getActionMasked()==MotionEvent.ACTION_CANCEL){
|
||||
boolean expanded=Math.abs(front.getTranslationX())>ui.dp(38);dragging=false;
|
||||
front.animate().translationX(expanded?direction*ui.dp(76):0).setDuration(150).withEndAction(()->{if(!expanded)remove.setVisibility(INVISIBLE);}).start();
|
||||
remove.setFocusable(expanded);remove.setImportantForAccessibility(expanded?IMPORTANT_FOR_ACCESSIBILITY_YES:IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
/** Main-thread local-app checks triggered by visits, session endings and manual requests. */
|
||||
final class AppUpdateChecker {
|
||||
enum Status { IDLE, CHECKING, UP_TO_DATE, AVAILABLE, FAILED }
|
||||
private final String currentVersion;
|
||||
private final RemoteVersionCheck.Fetcher fetcher;
|
||||
private final BiFunction<String, byte[], String> compare;
|
||||
private final Runnable changed;
|
||||
private RemoteVersionCheck.Cancellation request;
|
||||
private boolean enabled;
|
||||
private long generation;
|
||||
Status status = Status.IDLE;
|
||||
String availableVersion = "";
|
||||
|
||||
AppUpdateChecker(String currentVersion, Runnable changed) {
|
||||
this(currentVersion, RemoteVersionCheck.ReleaseRequest::start,
|
||||
NativeSession::nCheckMobileUpdate, changed);
|
||||
}
|
||||
|
||||
AppUpdateChecker(String currentVersion, RemoteVersionCheck.Fetcher fetcher,
|
||||
BiFunction<String, byte[], String> compare, Runnable changed) {
|
||||
this.currentVersion = currentVersion; this.fetcher = fetcher;
|
||||
this.compare = compare;
|
||||
this.changed = changed;
|
||||
}
|
||||
|
||||
boolean updateAvailable() { return !availableVersion.isEmpty(); }
|
||||
|
||||
void setEnabled(boolean value) {
|
||||
if (enabled == value) return;
|
||||
enabled = value;
|
||||
if (enabled) { checkNow(); return; }
|
||||
++generation;
|
||||
if (request != null) request.cancel();
|
||||
request = null;
|
||||
if (status == Status.CHECKING) {
|
||||
status = updateAvailable() ? Status.AVAILABLE : Status.IDLE;
|
||||
}
|
||||
changed.run();
|
||||
}
|
||||
|
||||
void checkNow() {
|
||||
if (!enabled || status == Status.CHECKING) return;
|
||||
status = Status.CHECKING;
|
||||
changed.run();
|
||||
long token = ++generation;
|
||||
request = fetcher.fetch(data -> {
|
||||
if (!enabled || token != generation) return;
|
||||
request = null;
|
||||
String result = data == null ? null : compare.apply(currentVersion, data);
|
||||
if (result == null) {
|
||||
status = Status.FAILED;
|
||||
} else {
|
||||
availableVersion = result;
|
||||
status = updateAvailable() ? Status.AVAILABLE : Status.UP_TO_DATE;
|
||||
}
|
||||
changed.run();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.media.AudioAttributes;
|
||||
import android.media.AudioFormat;
|
||||
import android.media.AudioTrack;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
|
||||
/** Bounded audio queue: network callbacks never block on the speaker. */
|
||||
final class AudioPlayer implements AutoCloseable {
|
||||
private final ArrayBlockingQueue<byte[]> queue = new ArrayBlockingQueue<>(20);
|
||||
private volatile boolean closed;
|
||||
private volatile boolean enabled = true;
|
||||
private final Thread thread = new Thread(this::play, "CrossDesk audio");
|
||||
AudioPlayer() { thread.start(); }
|
||||
void offer(byte[] pcm) {
|
||||
if (!closed && enabled && !queue.offer(pcm)) { queue.poll(); queue.offer(pcm); }
|
||||
}
|
||||
void setEnabled(boolean value) { enabled = value; queue.clear(); }
|
||||
private void play() {
|
||||
AudioTrack track = null;
|
||||
try {
|
||||
int minimum = AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
|
||||
track = new AudioTrack.Builder()
|
||||
.setAudioAttributes(new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_MOVIE).build())
|
||||
.setAudioFormat(new AudioFormat.Builder().setSampleRate(48000)
|
||||
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO).setEncoding(AudioFormat.ENCODING_PCM_16BIT).build())
|
||||
.setBufferSizeInBytes(Math.max(minimum, 9600)).setTransferMode(AudioTrack.MODE_STREAM).build();
|
||||
track.play();
|
||||
while (!closed) {
|
||||
byte[] data = queue.take();
|
||||
if (!enabled) continue;
|
||||
int offset = 0;
|
||||
while (!closed && enabled && offset < data.length) {
|
||||
int written = track.write(data, offset, data.length - offset, AudioTrack.WRITE_BLOCKING);
|
||||
if (written <= 0) break;
|
||||
offset += written;
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException ignored) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (IllegalArgumentException | IllegalStateException ignored) {
|
||||
// Devices with unavailable output can still operate as a silent controller.
|
||||
} finally {
|
||||
if (track != null) { track.release(); }
|
||||
}
|
||||
}
|
||||
@Override public void close() { closed = true; queue.clear(); thread.interrupt(); }
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.Context;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import java.io.File;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Main-thread session state; never retains a stopped Activity or its Views. */
|
||||
final class BackgroundSession implements NativeSession.Listener {
|
||||
final Context context;
|
||||
final NativeSession session;
|
||||
final String token = UUID.randomUUID().toString();
|
||||
final String host, remote;
|
||||
final int port;
|
||||
NativeSession.Listener view;
|
||||
String identity = "", platform = "", clipboard = "", fileStatus = "", endReason = "";
|
||||
JSONArray displays = new JSONArray();
|
||||
RemoteVideoSettings videoSettings;
|
||||
int signalState, selectedDisplay, width, height;
|
||||
boolean muted, remoteServiceAvailable, background, ended;
|
||||
File receivedFile;
|
||||
|
||||
BackgroundSession(Context context, NativeSession session, String host, int port, String remote) {
|
||||
this.context = context.getApplicationContext();
|
||||
this.session = session; this.host = host; this.port = port; this.remote = remote;
|
||||
}
|
||||
void attach(NativeSession.Listener listener) { view = listener; }
|
||||
void detach(NativeSession.Listener listener) { if (view == listener) view = null; }
|
||||
void setBackground(boolean value) {
|
||||
if (background == value || ended) return;
|
||||
background = value;
|
||||
// With no visible window, release rendering buffers and stop remote
|
||||
// audio. The RTC/control connection and file transfers remain alive.
|
||||
if (value) session.surface(null);
|
||||
session.control(2, value || muted ? 0 : 1);
|
||||
RemoteSessionService.refresh(this);
|
||||
}
|
||||
void finish(String reason) {
|
||||
if (ended) return;
|
||||
ended = true; endReason = reason; clipboard = "";
|
||||
session.close();
|
||||
RemoteSessionService.release(context, this);
|
||||
NativeSession.Listener listener = view; view = null;
|
||||
if (listener != null) listener.ended(reason);
|
||||
}
|
||||
@Override public void ended(String reason) { finish(reason); }
|
||||
@Override public void passwordRejected() { finish("远端访问密码已失效,请重新连接"); }
|
||||
@Override public void connected() { /* Already connected before the service takes ownership. */ }
|
||||
@Override public void status(String message) { if (view != null) view.status(message); }
|
||||
@Override public void signaling(int state, String id) {
|
||||
signalState = state; identity = id;
|
||||
if (view != null) view.signaling(state, id);
|
||||
}
|
||||
@Override public void data(JSONObject message) {
|
||||
if (view != null) { view.data(message); return; }
|
||||
if (message.optInt("type", -1) == 12 && videoSettings != null) videoSettings.receive(message);
|
||||
if (message.optInt("type", -1) == 5) {
|
||||
JSONObject service = message.optJSONObject("service_status");
|
||||
remoteServiceAvailable = service != null && service.optBoolean("available", false);
|
||||
}
|
||||
JSONObject info = message.optJSONObject("host_info");
|
||||
if (info != null) {
|
||||
platform = info.optString("platform", "");
|
||||
JSONArray values = info.optJSONArray("displays"); if (values != null) displays = values;
|
||||
if (videoSettings != null) videoSettings.setSupported(info.optBoolean("supports_video_settings", false));
|
||||
}
|
||||
}
|
||||
@Override public void videoSize(int w, int h) {
|
||||
width = w; height = h;
|
||||
if (view != null) view.videoSize(w, h);
|
||||
}
|
||||
@Override public void clipboard(String text) { clipboard = text; if (view != null) view.clipboard(text); }
|
||||
@Override public void statistics(RemoteNetworkStatistics.Snapshot value) { if (view != null) view.statistics(value); }
|
||||
@Override public void fileTransfer(String name, double progress, boolean sending, File received) {
|
||||
if (received != null) receivedFile = received;
|
||||
fileStatus = progress < 0 ? name + " 传输失败" : (sending ? "发送 " : "接收 ") + name
|
||||
+ (progress >= 1 ? " · 已完成" : " · " + (int)(progress * 100) + "%");
|
||||
if (view != null) view.fileTransfer(name, progress, sending, received);
|
||||
}
|
||||
@Override public void controlFeedback(String text) { if (view != null) view.controlFeedback(text); }
|
||||
@Override public void presence(JSONObject message) { if (view != null) view.presence(message); }
|
||||
@Override public void announcement(JSONObject message) { if (view != null) view.announcement(message); }
|
||||
@Override public void announcementFailed(String id) { if (view != null) view.announcementFailed(id); }
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ScrollView;
|
||||
|
||||
/** Reflows the existing panels, keeping text, focus and scroll state during window resizing. */
|
||||
@android.annotation.SuppressLint("ViewConstructor")
|
||||
final class HomeLayout extends ScrollView {
|
||||
final LinearLayout panels;
|
||||
private final MobileUi ui;
|
||||
private int panelHeight;
|
||||
|
||||
HomeLayout(MobileUi ui){
|
||||
super(ui.context);this.ui=ui;
|
||||
setFillViewport(true);setClipChildren(false);setClipToPadding(false);
|
||||
panels=new LinearLayout(ui.context){
|
||||
@Override protected void onMeasure(int widthSpec,int heightSpec){
|
||||
// ScrollView offers unbounded height even with an explicit LayoutParams height.
|
||||
super.onMeasure(widthSpec,MeasureSpec.makeMeasureSpec(panelHeight,MeasureSpec.EXACTLY));
|
||||
}
|
||||
};panels.setGravity(Gravity.TOP);
|
||||
panels.setPadding(ui.dp(20),ui.dp(24),ui.dp(20),ui.dp(12));
|
||||
panels.setClipChildren(false);panels.setClipToPadding(false);
|
||||
addView(panels,new LayoutParams(-1,-1));
|
||||
}
|
||||
|
||||
@Override protected void onMeasure(int widthSpec,int heightSpec){
|
||||
boolean wide=MeasureSpec.getSize(widthSpec)>=ui.dp(900);
|
||||
panels.setOrientation(wide?LinearLayout.HORIZONTAL:LinearLayout.VERTICAL);
|
||||
// A short split window or the IME can leave less room than the two panels need.
|
||||
// Keep the recent list usable and let the outer viewport scroll in that case.
|
||||
panelHeight=Math.max(ui.dp(wide?360:440),MeasureSpec.getSize(heightSpec));
|
||||
if(panels.getChildCount()==2){
|
||||
View connection=panels.getChildAt(0),recent=panels.getChildAt(1);
|
||||
LinearLayout.LayoutParams first=(LinearLayout.LayoutParams)connection.getLayoutParams();
|
||||
first.width=wide?ui.dp(360):-1;first.height=-2;first.weight=0;first.gravity=Gravity.TOP;
|
||||
LinearLayout.LayoutParams second=(LinearLayout.LayoutParams)recent.getLayoutParams();
|
||||
second.width=wide?0:-1;second.height=wide?-1:0;second.weight=1;
|
||||
second.topMargin=wide?0:ui.dp(20);second.setMarginStart(wide?ui.dp(24):0);
|
||||
second.resolveLayoutDirection(panels.getLayoutDirection());
|
||||
}
|
||||
super.onMeasure(widthSpec,heightSpec);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.view.KeyEvent;
|
||||
|
||||
final class KeyMap {
|
||||
static int windowsCode(int code) {
|
||||
if (code >= KeyEvent.KEYCODE_A && code <= KeyEvent.KEYCODE_Z) return 0x41 + code - KeyEvent.KEYCODE_A;
|
||||
if (code >= KeyEvent.KEYCODE_0 && code <= KeyEvent.KEYCODE_9) return 0x30 + code - KeyEvent.KEYCODE_0;
|
||||
if (code >= KeyEvent.KEYCODE_F1 && code <= KeyEvent.KEYCODE_F12) return 0x70 + code - KeyEvent.KEYCODE_F1;
|
||||
return switch (code) {
|
||||
case KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER -> 0x0D;
|
||||
case KeyEvent.KEYCODE_DEL -> 0x08;
|
||||
case KeyEvent.KEYCODE_FORWARD_DEL -> 0x2E;
|
||||
case KeyEvent.KEYCODE_TAB -> 0x09;
|
||||
case KeyEvent.KEYCODE_ESCAPE -> 0x1B;
|
||||
case KeyEvent.KEYCODE_SPACE -> 0x20;
|
||||
case KeyEvent.KEYCODE_SHIFT_LEFT, KeyEvent.KEYCODE_SHIFT_RIGHT -> 0x10;
|
||||
case KeyEvent.KEYCODE_CTRL_LEFT, KeyEvent.KEYCODE_CTRL_RIGHT -> 0x11;
|
||||
case KeyEvent.KEYCODE_ALT_LEFT, KeyEvent.KEYCODE_ALT_RIGHT -> 0x12;
|
||||
case KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_META_RIGHT -> 0x5B;
|
||||
case KeyEvent.KEYCODE_DPAD_LEFT -> 0x25;
|
||||
case KeyEvent.KEYCODE_DPAD_UP -> 0x26;
|
||||
case KeyEvent.KEYCODE_DPAD_RIGHT -> 0x27;
|
||||
case KeyEvent.KEYCODE_DPAD_DOWN -> 0x28;
|
||||
case KeyEvent.KEYCODE_MOVE_HOME -> 0x24;
|
||||
case KeyEvent.KEYCODE_MOVE_END -> 0x23;
|
||||
case KeyEvent.KEYCODE_PAGE_UP -> 0x21;
|
||||
case KeyEvent.KEYCODE_PAGE_DOWN -> 0x22;
|
||||
case KeyEvent.KEYCODE_MINUS -> 0xBD;
|
||||
case KeyEvent.KEYCODE_EQUALS -> 0xBB;
|
||||
case KeyEvent.KEYCODE_LEFT_BRACKET -> 0xDB;
|
||||
case KeyEvent.KEYCODE_RIGHT_BRACKET -> 0xDD;
|
||||
case KeyEvent.KEYCODE_BACKSLASH -> 0xDC;
|
||||
case KeyEvent.KEYCODE_SEMICOLON -> 0xBA;
|
||||
case KeyEvent.KEYCODE_APOSTROPHE -> 0xDE;
|
||||
case KeyEvent.KEYCODE_COMMA -> 0xBC;
|
||||
case KeyEvent.KEYCODE_PERIOD -> 0xBE;
|
||||
case KeyEvent.KEYCODE_SLASH -> 0xBF;
|
||||
case KeyEvent.KEYCODE_GRAVE -> 0xC0;
|
||||
default -> 0;
|
||||
};
|
||||
}
|
||||
// High bit is the Shift modifier; zero means use the clipboard for this text.
|
||||
static int ascii(char ch) {
|
||||
if (ch >= 'a' && ch <= 'z') return ch - 'a' + 0x41;
|
||||
if (ch >= 'A' && ch <= 'Z') return ch | 0x100;
|
||||
if (ch >= '0' && ch <= '9') return ch;
|
||||
if (ch == '\n') return 0x0D;
|
||||
if (ch == '\t') return 0x09;
|
||||
if (ch == ' ') return 0x20;
|
||||
String plain = "-=[]\\;',./`";
|
||||
String shifted = "_+{}|:\"<>?~";
|
||||
int[] codes = {0xBD,0xBB,0xDB,0xDD,0xDC,0xBA,0xDE,0xBC,0xBE,0xBF,0xC0};
|
||||
int i = plain.indexOf(ch);
|
||||
if (i >= 0) return codes[i];
|
||||
i = shifted.indexOf(ch);
|
||||
if (i >= 0) return codes[i] | 0x100;
|
||||
i = ")!@#$%^&*(".indexOf(ch);
|
||||
return i < 0 ? 0 : (0x30 + i) | 0x100;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.Context;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** Offline catalog; document bodies are loaded only when opened. */
|
||||
final class LicenseCatalog {
|
||||
static final class Document {
|
||||
final String title,asset;
|
||||
Document(JSONObject value)throws JSONException{
|
||||
title=value.getString("title");asset=value.getString("asset");
|
||||
if(!asset.startsWith("about/")||asset.contains(".."))throw new JSONException("Invalid asset");
|
||||
}
|
||||
}
|
||||
static final class Component {
|
||||
final String id,name,version,license,sourceURL,buildSourceURL;
|
||||
final List<Document> documents,buildDocuments;
|
||||
Component(JSONObject value)throws JSONException{
|
||||
id=value.getString("id");name=value.getString("name");version=value.getString("version");license=value.getString("license");
|
||||
sourceURL=value.getString("sourceURL");buildSourceURL=value.optString("buildSourceURL","");
|
||||
documents=documents(value.getJSONArray("documents"));buildDocuments=documents(value.optJSONArray("buildDocuments"));
|
||||
if(documents.isEmpty())throw new JSONException("Missing documents");
|
||||
}
|
||||
String documentTitle(Document document){
|
||||
if(document.title.equals("Source copyright and license notices"))return "版权与许可声明";
|
||||
if(document.title.equals("apps/android/licenses/OPEN_SOURCE_NOTICE.txt"))return "开源软件权利说明";
|
||||
if(id.equals("crossdesk")&&document.title.equals("LICENSE"))return "GNU GPL 第 3 版";
|
||||
return document.title;
|
||||
}
|
||||
}
|
||||
final List<Component> components=new ArrayList<>();
|
||||
final JSONObject source;
|
||||
LicenseCatalog(Context context)throws IOException,JSONException{
|
||||
JSONObject data=new JSONObject(read(context,"ThirdPartyLicenses.json"));
|
||||
if(data.getInt("schemaVersion")!=1)throw new JSONException("Unknown catalog");
|
||||
JSONArray entries=data.getJSONArray("components");
|
||||
for(int i=0;i<entries.length();i++)components.add(new Component(entries.getJSONObject(i)));
|
||||
if(find("crossdesk")==null||find("openfec")==null)throw new JSONException("Incomplete catalog");
|
||||
JSONObject metadata;
|
||||
try{metadata=new JSONObject(read(context,"SourceMetadata.json"));if(metadata.getInt("schemaVersion")!=1)metadata=null;}catch(IOException|JSONException error){metadata=null;}
|
||||
source=metadata;
|
||||
}
|
||||
Component find(String id){for(Component component:components)if(component.id.equals(id))return component;return null;}
|
||||
static List<Document> documents(JSONArray values)throws JSONException{
|
||||
List<Document> result=new ArrayList<>();if(values!=null)for(int i=0;i<values.length();i++)result.add(new Document(values.getJSONObject(i)));return result;
|
||||
}
|
||||
static String read(Context context,String asset)throws IOException{
|
||||
try(var input=context.getAssets().open(asset);var output=new ByteArrayOutputStream()){
|
||||
byte[] buffer=new byte[8192];int count;while((count=input.read(buffer))!=-1)output.write(buffer,0,count);return output.toString("UTF-8");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,771 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.AlertDialog;
|
||||
import android.app.Dialog;
|
||||
import android.content.ClipData;
|
||||
import android.content.Intent;
|
||||
import android.content.ClipboardManager;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.pm.ActivityInfo;
|
||||
import android.content.res.ColorStateList;
|
||||
import android.content.res.Configuration;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Typeface;
|
||||
import android.graphics.drawable.GradientDrawable;
|
||||
import android.os.Bundle;
|
||||
import android.text.*;
|
||||
import android.text.method.PasswordTransformationMethod;
|
||||
import android.view.*;
|
||||
import android.view.inputmethod.InputMethodManager;
|
||||
import android.widget.*;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import static cn.crossdesk.mobile.MobileUi.*;
|
||||
|
||||
public final class MainActivity extends Activity implements NativeSession.Listener {
|
||||
private MobileUi ui;
|
||||
private PageHost pageHost;
|
||||
private AboutPages aboutPages;
|
||||
private AppUpdateChecker appUpdates;
|
||||
private View settingsUpdateDot, aboutUpdateDot, settingsUpdateButton, aboutUpdateRow;
|
||||
private TextView aboutUpdateLabel;
|
||||
private boolean navigatingBack;
|
||||
private FrameLayout canvas;
|
||||
private LinearLayout root;
|
||||
private EditText remote;
|
||||
private TextView status, signalBadge, identitySummary;
|
||||
private AnnouncementInbox announcementInbox;
|
||||
private AnnouncementView announcementView;
|
||||
private TextView announcementBadge;
|
||||
private View announcementRefresh;
|
||||
private String announcementServer="";
|
||||
private SharedPreferences preferences;
|
||||
private RecentConnections history;
|
||||
private final RecentConnectionPresence recentPresence=new RecentConnectionPresence();
|
||||
private LinearLayout recentGrid;
|
||||
private int recentColumns=2;
|
||||
private final Runnable presenceTick=new Runnable(){public void run(){
|
||||
if(!recentPresence.isConnected())return;
|
||||
recentPresence.maintain(android.os.SystemClock.elapsedRealtime());
|
||||
mainHandler.postDelayed(this,1000);
|
||||
}};
|
||||
private RemotePreviewStore previews;
|
||||
private RemotePreviewStore.Capture previewCapture;
|
||||
private boolean previewCopying,updatingPreviewSwitch;
|
||||
private int previewAttempts;
|
||||
private Switch previewSwitch;
|
||||
private TextView clearPreviewsButton,previewCleanupError;
|
||||
private AlertDialog previewDialog;
|
||||
private final java.util.List<Runnable> previewCards=new java.util.ArrayList<>();
|
||||
private final Runnable previewChanged=this::renderPreviews;
|
||||
private NativeSession session, signaling;
|
||||
private String signalingServer="", localIdentity="", signalError="";
|
||||
private int signalState=-1;
|
||||
private boolean foreground;
|
||||
private boolean pictureInPictureUi;
|
||||
private boolean enteredPictureInPicture;
|
||||
private BackgroundSession backgroundSession;
|
||||
private int videoWidth,videoHeight;
|
||||
private final RemotePictureInPicture pictureInPicture=new RemotePictureInPicture();
|
||||
private RemoteVideoView video;
|
||||
private SessionControls controls;
|
||||
private Dialog passwordDialog, progressDialog, privacyDialog;
|
||||
private AlertDialog disconnectDialog;
|
||||
private AlertDialog connectionDialog;
|
||||
private String pendingConnectionMessage="";
|
||||
private AlertDialog remoteUpdateDialog;
|
||||
private RemoteVersionCheck remoteVersionCheck;
|
||||
private String host, connectedRemote="", hostPlatform="", remoteClipboard="", pendingPassword="", page="home";
|
||||
private int port,selectedDisplay;
|
||||
private JSONArray displays=new JSONArray();
|
||||
private boolean muted,ready,rememberPassword;
|
||||
private boolean remoteServiceAvailable;
|
||||
private static final int PICK_FILE=41,SAVE_FILE=42;
|
||||
private NativeSession documentSession;
|
||||
private java.io.File receivedFile,documentToSave;
|
||||
private final Runnable documentTimeout=()->{if(documentSession!=null&&!foreground)end("文件选择已超时,会话已结束");};
|
||||
private RemoteVideoSettings videoSettings=new RemoteVideoSettings(1);
|
||||
private final android.os.Handler mainHandler=new android.os.Handler(android.os.Looper.getMainLooper());
|
||||
private Runnable videoSettingsTimeout;
|
||||
private final Set<Integer> pressed=new HashSet<>();
|
||||
private Runnable backAction;
|
||||
|
||||
@Override public void onCreate(Bundle state){
|
||||
super.onCreate(state);ui=new MobileUi(this);history=new RecentConnections(this);
|
||||
pageHost=new PageHost(this);setContentView(pageHost);
|
||||
preferences=getSharedPreferences("settings",MODE_PRIVATE);host=preferences.getString("host","api.crossdesk.cn");port=preferences.getInt("port",9099);
|
||||
recentPresence.sender=ids->{if(signaling!=null&&!signaling.isClosed())signaling.presenceRequest(ids);};
|
||||
recentPresence.changed=this::renderRecentConnections;
|
||||
remoteVersionCheck=new RemoteVersionCheck(this::showRemoteUpdate);
|
||||
appUpdates=new AppUpdateChecker(applicationVersion(),this::renderAppUpdates);
|
||||
previews=RemotePreviewStore.get(this);previews.addListener(previewChanged);previews.enforceConsent();
|
||||
announcementInbox=new AnnouncementInbox(new java.io.File(getNoBackupFilesDir(),"AnnouncementReads"));
|
||||
announcementInbox.sender=(request,id)->{if(signaling!=null&&!signaling.isClosed())signaling.announcementRequest(request,id);else announcementInbox.failed(id);};
|
||||
announcementInbox.changed=this::renderAnnouncements;
|
||||
if(android.os.Build.VERSION.SDK_INT>=33)getOnBackInvokedDispatcher().registerOnBackInvokedCallback(android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT,this::back);
|
||||
home("");
|
||||
}
|
||||
private int dp(float value){return ui.dp(value);}
|
||||
private LinearLayout column(){return ui.column();}
|
||||
private LinearLayout row(){return ui.row();}
|
||||
private TextView text(String title,int size,boolean bold){return ui.text(title,size,bold);}
|
||||
private String serverKey(){return host+":"+port;}
|
||||
private void toast(String value){Toast.makeText(this,value,Toast.LENGTH_SHORT).show();}
|
||||
private void hideKeyboard(){((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(root.getWindowToken(),0);root.clearFocus();}
|
||||
private void installRoot(String nextPage,boolean dark){
|
||||
PageHost.Motion motion=PageHost.Motion.NONE;
|
||||
if(canvas!=null&&foreground&&!page.equals(nextPage)){
|
||||
if(nextPage.equals("session"))motion=PageHost.Motion.SESSION_IN;
|
||||
else if(page.equals("session"))motion=PageHost.Motion.SESSION_OUT;
|
||||
else motion=navigatingBack||nextPage.equals("home")?PageHost.Motion.POP:PageHost.Motion.PUSH;
|
||||
}
|
||||
if(root!=null)hideKeyboard();page=nextPage;
|
||||
signalBadge=null;identitySummary=null;announcementBadge=null;announcementView=null;announcementRefresh=null;
|
||||
settingsUpdateDot=null;aboutUpdateDot=null;settingsUpdateButton=null;aboutUpdateRow=null;aboutUpdateLabel=null;
|
||||
previewSwitch=null;clearPreviewsButton=null;previewCleanupError=null;previewCards.clear();recentGrid=null;
|
||||
canvas=new FrameLayout(this);canvas.setBackgroundColor(dark?Color.BLACK:BACKGROUND);
|
||||
FrameLayout safeArea=new FrameLayout(this);canvas.addView(safeArea,new FrameLayout.LayoutParams(-1,-1));
|
||||
root=ui.pageColumn(dark?0:nextPage.equals("home")?1200:720);
|
||||
safeArea.addView(root,new FrameLayout.LayoutParams(-1,-1,Gravity.TOP|Gravity.CENTER_HORIZONTAL));
|
||||
safeArea.setOnApplyWindowInsetsListener((view,insets)->{
|
||||
view.setPadding(insets.getSystemWindowInsetLeft(),insets.getSystemWindowInsetTop(),insets.getSystemWindowInsetRight(),insets.getSystemWindowInsetBottom());return insets;
|
||||
});
|
||||
root.setFocusableInTouchMode(true);pageHost.show(canvas,motion);
|
||||
applySystemBars(dark);
|
||||
}
|
||||
private void applySystemBars(boolean dark){
|
||||
if(android.os.Build.VERSION.SDK_INT>=30){
|
||||
android.view.WindowInsetsController controller=getWindow().getInsetsController();
|
||||
if(controller!=null){int light=android.view.WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS|android.view.WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS;controller.setSystemBarsAppearance(dark?0:light,light);}
|
||||
}else getWindow().getDecorView().setSystemUiVisibility(dark?0:View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR|View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
|
||||
}
|
||||
private EditText field(String hint,int type){
|
||||
EditText v=new EditText(this);v.setHint(hint);v.setContentDescription(hint);v.setInputType(type);v.setSingleLine(true);v.setTextSize(17);v.setTextColor(INK);v.setHintTextColor(SECONDARY);
|
||||
v.setPadding(dp(14),0,dp(14),0);v.setBackground(ui.background(BACKGROUND,12));v.setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO);return v;
|
||||
}
|
||||
private LinearLayout navigation(String title,Runnable back){
|
||||
LinearLayout bar=row();bar.setPadding(dp(12),0,dp(12),0);root.addView(bar,ui.size(-1,56));
|
||||
bar.addView(ui.iconButton("back","返回",this::navigateBack),ui.size(44,44));
|
||||
TextView label=text(title,17,true);label.setGravity(Gravity.CENTER);label.setSingleLine();label.setEllipsize(TextUtils.TruncateAt.END);bar.addView(label,new LinearLayout.LayoutParams(0,-1,1));
|
||||
bar.addView(new View(this),ui.size(44,44));backAction=back;return bar;
|
||||
}
|
||||
LinearLayout formPage(String name,String title,Runnable back){
|
||||
installRoot(name,false);navigation(title,back);ScrollView scroll=new ScrollView(this);scroll.setFillViewport(true);root.addView(scroll,new LinearLayout.LayoutParams(-1,0,1));
|
||||
LinearLayout content=column();content.setPadding(dp(20),dp(16),dp(20),dp(28));scroll.addView(content);return content;
|
||||
}
|
||||
LinearLayout section(LinearLayout content,String title){
|
||||
return section(content,title,12);
|
||||
}
|
||||
private LinearLayout section(LinearLayout content,String title,int radius){
|
||||
if(!title.isEmpty()){TextView label=text(title,13,false);label.setTextColor(SECONDARY);label.setPadding(dp(16),dp(12),0,dp(8));content.addView(label);}
|
||||
LinearLayout card=column();ui.card(card,radius);content.addView(card);return card;
|
||||
}
|
||||
void footer(LinearLayout content,String title){TextView v=text(title,12,false);v.setTextColor(SECONDARY);v.setLineSpacing(dp(3),1);v.setPadding(dp(16),dp(8),dp(16),dp(16));content.addView(v);}
|
||||
LinearLayout link(LinearLayout parent,String title,String detail,Runnable action){
|
||||
LinearLayout item=row();item.setPadding(dp(16),dp(14),dp(12),dp(14));item.setMinimumHeight(dp(48));
|
||||
item.addView(text(title,16,false),new LinearLayout.LayoutParams(0,-2,1));TextView value=text(detail,15,false);value.setTextColor(SECONDARY);item.addView(value);
|
||||
TextView chevron=text(" ›",23,false);chevron.setTextColor(0xFFB7B7BD);item.addView(chevron);item.setContentDescription(title+(detail.isEmpty()?"":","+detail));item.setClickable(true);item.setFocusable(true);item.setOnClickListener(v->action.run());parent.addView(item);
|
||||
return item;
|
||||
}
|
||||
@android.annotation.SuppressLint("SourceLockedOrientationActivity") // Phones keep the portrait home; tablets and multi-window follow user rotation settings.
|
||||
private void updateHomeOrientation(){
|
||||
boolean tablet=getResources().getConfiguration().smallestScreenWidthDp>=600;
|
||||
if(android.os.Build.VERSION.SDK_INT>=30){
|
||||
android.graphics.Rect bounds=getWindowManager().getMaximumWindowMetrics().getBounds();
|
||||
tablet|=Math.min(bounds.width(),bounds.height())>=dp(600);
|
||||
}
|
||||
int orientation=tablet||isInMultiWindowMode()?ActivityInfo.SCREEN_ORIENTATION_FULL_USER:ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
|
||||
if(getRequestedOrientation()!=orientation)setRequestedOrientation(orientation);
|
||||
}
|
||||
private void home(String message){
|
||||
backAction=null;updateHomeOrientation();installRoot("home",false);
|
||||
LinearLayout toolbar=row();toolbar.setPadding(dp(20),0,dp(20),0);root.addView(toolbar,ui.size(-1,56));
|
||||
signalBadge=text("",12,true);signalBadge.setGravity(Gravity.CENTER);signalBadge.setPadding(dp(11),0,dp(11),0);signalBadge.setSingleLine(true);
|
||||
signalBadge.setOnClickListener(v->{
|
||||
if(!preferences.getBoolean("networkConsent",false))consent(this::renderSignaling);
|
||||
else if(signalState==1)toast("已连接 "+serverKey());
|
||||
else {stopSignaling();ensureSignaling();}
|
||||
});renderSignaling();toolbar.addView(signalBadge,ui.size(-2,34));toolbar.addView(new View(this),new LinearLayout.LayoutParams(0,1,1));
|
||||
FrameLayout announcementButton=(FrameLayout)ui.iconButton("envelope","通知公告",this::announcements);announcementButton.setClipChildren(false);toolbar.setClipChildren(false);toolbar.setClipToPadding(false);
|
||||
announcementBadge=text("",10,true);announcementBadge.setTextColor(Color.WHITE);announcementBadge.setGravity(Gravity.CENTER);announcementBadge.setMinWidth(dp(16));announcementBadge.setPadding(dp(4),0,dp(4),0);announcementBadge.setBackground(ui.background(RED,12));announcementBadge.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
|
||||
FrameLayout.LayoutParams badgePosition=new FrameLayout.LayoutParams(-2,dp(16),Gravity.TOP|Gravity.END);badgePosition.topMargin=-dp(3);badgePosition.setMarginEnd(-dp(5));announcementButton.addView(announcementBadge,badgePosition);renderAnnouncements();
|
||||
toolbar.addView(announcementButton,ui.size(40,40));View spacer=new View(this);toolbar.addView(spacer,ui.size(12,1));
|
||||
FrameLayout settingsButton=(FrameLayout)ui.iconButton("settings","设置",this::settings);settingsButton.setClipChildren(false);settingsUpdateButton=settingsButton;
|
||||
TextView updateBadge=text("!",10,true);updateBadge.setTextColor(Color.WHITE);updateBadge.setGravity(Gravity.CENTER);updateBadge.setIncludeFontPadding(false);updateBadge.setBackground(ui.background(RED,8));updateBadge.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);settingsUpdateDot=updateBadge;
|
||||
FrameLayout.LayoutParams updatePosition=new FrameLayout.LayoutParams(dp(16),dp(16),Gravity.TOP|Gravity.END);updatePosition.topMargin=-dp(3);updatePosition.setMarginEnd(-dp(5));settingsButton.addView(settingsUpdateDot,updatePosition);
|
||||
toolbar.addView(settingsButton,ui.size(40,40));renderAppUpdates();
|
||||
HomeLayout layout=new HomeLayout(ui);root.addView(layout,new LinearLayout.LayoutParams(-1,0,1));LinearLayout content=layout.panels;
|
||||
LinearLayout connection=column();connection.setPadding(dp(18),dp(18),dp(18),dp(18));content.addView(ui.shadowCard(connection,20));
|
||||
connection.addView(text("远程桌面",20,true));ui.gap(connection,16);
|
||||
LinearLayout entry=row();connection.addView(entry,ui.size(-1,54));
|
||||
remote=field("对端 ID",InputType.TYPE_CLASS_NUMBER);remote.setTextSize(20);remote.setTypeface(Typeface.create("sans-serif-medium",Typeface.NORMAL));
|
||||
remote.setOnFocusChangeListener((view,focused)->{GradientDrawable shape=ui.background(BACKGROUND,12);shape.setStroke(dp(focused?2:1),focused?BLUE:LINE);remote.setBackground(shape);});
|
||||
remote.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});remote.setText(formatId(preferences.getString("lastRemote","")));
|
||||
entry.addView(remote,new LinearLayout.LayoutParams(0,-1,1));
|
||||
TextView connect=ui.primary("连接 →",()->promptConnection(id()));connect.setContentDescription("连接");LinearLayout.LayoutParams buttonParams=ui.size(96,54);buttonParams.leftMargin=dp(10);entry.addView(connect,buttonParams);
|
||||
Runnable update=()->{connect.setEnabled(!id().isEmpty());connect.setAlpha(id().isEmpty()?.45f:1);};update.run();
|
||||
remote.addTextChangedListener(new TextWatcher(){boolean editing;public void beforeTextChanged(CharSequence s,int start,int count,int after){}public void onTextChanged(CharSequence s,int start,int before,int count){update.run();}public void afterTextChanged(Editable value){if(editing)return;String formatted=formatId(value.toString());if(!formatted.equals(value.toString())){editing=true;int cursor=remote.getSelectionStart(),digits=value.subSequence(0,Math.max(0,cursor)).toString().replaceAll("[^0-9]","").length();remote.setText(formatted);remote.setSelection(Math.min(formatted.length(),digits+Math.max(0,digits-1)/3));editing=false;}}});
|
||||
LinearLayout recent=column();recent.setPadding(dp(16),dp(16),dp(16),dp(16));ui.card(recent,18);LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(-1,0,1);p.topMargin=dp(20);content.addView(recent,p);
|
||||
JSONArray records=history.list(serverKey());recentPresence.watch(records,android.os.SystemClock.elapsedRealtime());LinearLayout heading=row();heading.addView(text("最近连接",20,true),new LinearLayout.LayoutParams(0,-2,1));
|
||||
if(records.length()>0){TextView count=text(records.length()+" 台设备",12,false);count.setTextColor(SECONDARY);heading.addView(count);}recent.addView(heading);
|
||||
if(records.length()==0){
|
||||
LinearLayout empty=column();empty.setGravity(Gravity.CENTER);recent.addView(empty,new LinearLayout.LayoutParams(-1,0,1));empty.addView(ui.icon("history",0xFFB6B6BB),ui.size(34,34));ui.gap(empty,12);
|
||||
TextView emptyTitle=text("还没有连接记录",17,true);emptyTitle.setGravity(Gravity.CENTER);empty.addView(emptyTitle);ui.gap(empty,8);TextView hint=text("成功连接后,这里会显示最近的远程设备。",13,false);hint.setTextColor(SECONDARY);hint.setGravity(Gravity.CENTER);empty.addView(hint);
|
||||
}else{
|
||||
ui.gap(recent,14);ScrollView scroll=new ScrollView(this);recent.addView(scroll,new LinearLayout.LayoutParams(-1,0,1));recentGrid=column();scroll.addView(recentGrid);
|
||||
recentGrid.addOnLayoutChangeListener((view,left,top,right,bottom,oldLeft,oldTop,oldRight,oldBottom)->{
|
||||
int width=right-left;if(width<=0)return;
|
||||
int columns=width<dp(300)?1:Math.max(2,Math.min(4,(width+dp(12))/dp(192)));
|
||||
if(columns!=recentColumns){recentColumns=columns;view.post(()->{if(view==recentGrid)renderRecentConnections();});}
|
||||
});renderRecentConnections();
|
||||
}
|
||||
ensureSignaling();
|
||||
if(!message.isEmpty())pendingConnectionMessage=message;
|
||||
showConnectionMessage();
|
||||
}
|
||||
private void showConnectionMessage(){
|
||||
if(pendingConnectionMessage.isEmpty()||!foreground||isFinishing()||isDestroyed())return;
|
||||
if(connectionDialog!=null)connectionDialog.dismiss();
|
||||
connectionDialog=new AlertDialog.Builder(this).setTitle("连接提示").setMessage(pendingConnectionMessage).setPositiveButton("确定",null).create();
|
||||
connectionDialog.setOnDismissListener(dialog->connectionDialog=null);
|
||||
pendingConnectionMessage="";connectionDialog.show();
|
||||
}
|
||||
private String id(){return remote.getText().toString().replace(" ","");}
|
||||
static String formatId(String value){String digits=value.replaceAll("[^0-9]","");if(digits.length()>9)digits=digits.substring(0,9);return digits.replaceAll("(.{3})(?=.)","$1 ");}
|
||||
private void renderRecentConnections(){
|
||||
if(recentGrid==null)return;
|
||||
JSONArray records=recentPresence.ordered(history.list(serverKey()),android.os.SystemClock.elapsedRealtime());
|
||||
recentGrid.removeAllViews();previewCards.clear();
|
||||
for(int i=0;i<records.length();i+=recentColumns){LinearLayout line=row();line.setGravity(Gravity.TOP);recentGrid.addView(line);for(int j=i;j<i+recentColumns;j++){View card=j<records.length()?recentCard(records.optJSONObject(j)):new View(this);LinearLayout.LayoutParams cell=new LinearLayout.LayoutParams(0,-2,1);if(j>i)cell.setMarginStart(dp(12));line.addView(card,cell);}ui.gap(recentGrid,12);}
|
||||
}
|
||||
private View recentCard(JSONObject item){
|
||||
if(item==null)return new View(this);String id=item.optString("id"),platform=item.optString("platform");
|
||||
LinearLayout card=column();ui.card(card,14);FrameLayout preview=new FrameLayout(this){@Override protected void onMeasure(int w,int h){super.onMeasure(w,MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(w)*9/16,MeasureSpec.EXACTLY));}};
|
||||
int color=platform.equals("windows")?0xFF316AB7:platform.equals("macos")?0xFF8057B9:platform.equals("linux")?0xFFAE642B:0xFF677587;preview.setBackgroundColor(color);
|
||||
TextView label=text(platform.equals("windows")?"Windows":platform.equals("macos")?"macOS":platform.equals("linux")?"Linux":"远程电脑",19,true);label.setGravity(Gravity.CENTER);label.setTextColor(Color.WHITE);preview.addView(label,new FrameLayout.LayoutParams(-1,-1));card.addView(preview,ui.size(-1,80));
|
||||
ImageView image=new ImageView(this);image.setScaleType(ImageView.ScaleType.CENTER_CROP);image.setVisibility(View.GONE);image.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);preview.addView(image,new FrameLayout.LayoutParams(-1,-1));
|
||||
String server=serverKey();Runnable load=()->{if(!image.isAttachedToWindow())return;Object binding=new Object();image.setTag(binding);image.setImageDrawable(null);image.setVisibility(View.GONE);label.setVisibility(View.VISIBLE);
|
||||
previews.load(server,id,bitmap->{if(image.getTag()!=binding||!image.isAttachedToWindow()){if(bitmap!=null)bitmap.recycle();return;}if(bitmap!=null){image.setImageBitmap(bitmap);image.setVisibility(View.VISIBLE);label.setVisibility(View.GONE);}});};previewCards.add(load);image.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener(){public void onViewAttachedToWindow(View view){load.run();}public void onViewDetachedFromWindow(View view){image.setTag(null);}});if(image.isAttachedToWindow())load.run();
|
||||
LinearLayout caption=column();caption.setPadding(dp(9),dp(9),dp(9),dp(9));TextView name=text(item.optString("name",id),12,true);name.setSingleLine();name.setEllipsize(TextUtils.TruncateAt.END);caption.addView(name);ui.gap(caption,4);
|
||||
LinearLayout details=row();TextView detail=text("ID "+id,10,false);detail.setTypeface(Typeface.create("sans-serif",Typeface.NORMAL));detail.setTextColor(SECONDARY);detail.setSingleLine();detail.setEllipsize(TextUtils.TruncateAt.END);details.addView(detail,new LinearLayout.LayoutParams(0,-2,1));
|
||||
if(item.optBoolean("remember")){View key=ui.icon("key",SECONDARY);key.setContentDescription("已保存密码");LinearLayout.LayoutParams keySize=ui.size(10,10);keySize.leftMargin=dp(4);details.addView(key,keySize);}
|
||||
boolean online=recentPresence.isOnline(id,android.os.SystemClock.elapsedRealtime());String availability=online?"在线":"离线";TextView presence=text(availability,10,true);presence.setSingleLine();presence.setTextColor(online?GREEN:SECONDARY);LinearLayout.LayoutParams presenceSize=ui.size(-2,-2);presenceSize.leftMargin=dp(5);details.addView(presence,presenceSize);caption.addView(details);card.addView(caption);
|
||||
card.setContentDescription("连接 "+item.optString("name",id)+",ID "+id+(item.optBoolean("remember")?",已保存密码":"")+","+availability);card.setClickable(true);card.setFocusable(true);card.setOnClickListener(v->{remote.setText(formatId(id));promptConnection(id);});
|
||||
card.setOnLongClickListener(v->{new AlertDialog.Builder(this).setTitle(item.optString("name",id)).setItems(new String[]{"连接","删除记录"},(d,w)->{if(w==0)promptConnection(id);else{history.delete(serverKey(),id);home("");}}).show();return true;});return card;
|
||||
}
|
||||
private void promptConnection(String id){
|
||||
hideKeyboard();if(!id.matches("[0-9]{9}")){remote.setError("请输入 9 位设备 ID");remote.requestFocus();return;}
|
||||
if(!preferences.getBoolean("networkConsent",false)){consent(()->connectOrPrompt(id));return;}connectOrPrompt(id);
|
||||
}
|
||||
private void connectOrPrompt(String id){
|
||||
String stored;
|
||||
try{stored=history.password(serverKey(),id);}catch(Exception error){passwordSheet(id,"已保存密码无法读取,请重新输入",true);return;}
|
||||
if(!stored.isEmpty()){rememberPassword=true;begin(id,stored);return;}
|
||||
boolean remember=history.remembersPassword(serverKey(),id);
|
||||
passwordSheet(id,remember?"已保存的密码未能保留,请重新输入一次":"",remember);
|
||||
}
|
||||
private void consent(Runnable accepted){
|
||||
if(privacyDialog!=null&&privacyDialog.isShowing())return;
|
||||
Dialog dialog=new PrivacyConsentDialog(this,ui,()->{
|
||||
preferences.edit().putBoolean("networkConsent",true).apply();appUpdates.setEnabled(foreground);renderSignaling();ensureSignaling();accepted.run();
|
||||
});
|
||||
privacyDialog=dialog;dialog.setOnDismissListener(d->{if(privacyDialog==dialog)privacyDialog=null;});dialog.show();
|
||||
}
|
||||
private void passwordSheet(String id,String error,boolean rememberDefault){
|
||||
Dialog dialog=new Dialog(this);passwordDialog=dialog;LinearLayout sheet=column();sheet.setPadding(dp(22),dp(10),dp(22),dp(22));sheet.setBackground(ui.background(BACKGROUND,24));
|
||||
View handle=new View(this);handle.setBackground(ui.background(0xFFC6C6CB,3));LinearLayout.LayoutParams hp=ui.size(36,5);hp.gravity=Gravity.CENTER;sheet.addView(handle,hp);ui.gap(sheet,20);
|
||||
LinearLayout header=row(),titles=column();titles.addView(text("连接远程桌面",22,true));ui.gap(titles,5);TextView subtitle=text("对端 ID "+id,15,false);subtitle.setTextColor(SECONDARY);titles.addView(subtitle);header.addView(titles,new LinearLayout.LayoutParams(0,-2,1));header.addView(ui.iconButton("close","关闭",dialog::dismiss),ui.size(36,36));sheet.addView(header);ui.gap(sheet,18);
|
||||
LinearLayout passwordRow=row();ui.card(passwordRow,10);EditText password=field("访问密码",InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);password.setBackgroundColor(Color.TRANSPARENT);passwordRow.addView(password,new LinearLayout.LayoutParams(0,dp(50),1));
|
||||
View eye=ui.iconButton("eye","显示密码",()->{boolean hidden=password.getTransformationMethod()!=null;password.setTransformationMethod(hidden?null:PasswordTransformationMethod.getInstance());password.setSelection(password.length());});passwordRow.addView(eye,ui.size(44,44));sheet.addView(passwordRow);ui.gap(sheet,18);
|
||||
LinearLayout save=row(),saveText=column();saveText.addView(text("保存密码",15,true));ui.gap(saveText,3);TextView security=text("密码将加密保存在本机 Android Keystore 中",11,false);security.setTextColor(SECONDARY);saveText.addView(security);save.addView(saveText,new LinearLayout.LayoutParams(0,-2,1));Switch remember=new Switch(this);remember.setContentDescription("保存密码");save.addView(remember);sheet.addView(save);
|
||||
remember.setChecked(rememberDefault);
|
||||
ui.gap(sheet,18);TextView connect=ui.primary("连接 →",()->{
|
||||
String secret=password.getText().toString();if(secret.isEmpty()||secret.length()>128||secret.contains("@")){password.setError("请输入有效访问密码");return;}
|
||||
rememberPassword=remember.isChecked();password.setText("");dialog.dismiss();begin(id,secret);
|
||||
});connect.setContentDescription("确认连接");sheet.addView(connect,ui.size(-1,48));
|
||||
ScrollView scroll=new ScrollView(this);scroll.addView(sheet);
|
||||
dialog.setContentView(scroll);Window window=dialog.getWindow();if(window!=null){window.setBackgroundDrawableResource(android.R.color.transparent);window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);window.setDimAmount(.22f);}dialog.show();sizePasswordDialog();password.requestFocus();if(!error.isEmpty())password.setError(error);
|
||||
dialog.setOnDismissListener(d->{password.setText("");passwordDialog=null;});
|
||||
}
|
||||
private void sizePasswordDialog(){
|
||||
if(passwordDialog==null||passwordDialog.getWindow()==null)return;
|
||||
int width=getResources().getConfiguration().screenWidthDp;
|
||||
Window window=passwordDialog.getWindow();window.setLayout(width>=600?dp(Math.min(520,width-48)):-1,-2);
|
||||
window.setGravity(width>=600?Gravity.CENTER:Gravity.BOTTOM);
|
||||
}
|
||||
private void begin(String id,String secret){
|
||||
videoWidth=videoHeight=0;enteredPictureInPicture=false;
|
||||
pictureInPicture.disconnect();updatePictureInPicture();
|
||||
remoteServiceAvailable=false;receivedFile=null;
|
||||
resetRemoteVersionCheck();
|
||||
resetVideoSettings();
|
||||
previewCapture=previews.begin(serverKey(),id);previewCopying=false;previewAttempts=0;
|
||||
connectedRemote=id;pendingPassword=rememberPassword?secret:"";ready=false;muted=false;selectedDisplay=0;hostPlatform="";remoteClipboard="";displays=new JSONArray();preferences.edit().putString("lastRemote",id).apply();
|
||||
ensureSignaling();
|
||||
if(signaling==null){pendingPassword="";toast("请先完成联网授权");return;}
|
||||
session=signaling;showProgress();session.connect(id,secret);
|
||||
}
|
||||
private void showProgress(){
|
||||
Dialog dialog=new Dialog(this);progressDialog=dialog;LinearLayout card=column();ui.card(card,24);card.setGravity(Gravity.CENTER_HORIZONTAL);LinearLayout body=column();body.setGravity(Gravity.CENTER);body.setPadding(dp(26),dp(24),dp(26),dp(20));
|
||||
ProgressBar spinner=new ProgressBar(this);spinner.setIndeterminateTintList(ColorStateList.valueOf(BLUE));body.addView(spinner,ui.size(34,34));ui.gap(body,14);TextView title=text("正在连接",20,true);title.setGravity(Gravity.CENTER);body.addView(title);ui.gap(body,6);status=text("正在连接信令服务器…",14,false);status.setGravity(Gravity.CENTER);status.setTextColor(SECONDARY);status.setMinHeight(dp(36));body.addView(status);card.addView(body,ui.size(-1,-2));ui.divider(card);card.addView(ui.action("取消连接",RED,()->end("")),ui.size(-1,46));
|
||||
dialog.setContentView(card);dialog.setCanceledOnTouchOutside(false);dialog.setOnCancelListener(d->end(""));Window w=dialog.getWindow();if(w!=null){w.setBackgroundDrawableResource(android.R.color.transparent);w.setDimAmount(.08f);}dialog.show();if(w!=null)w.setLayout(dp(292),-2);
|
||||
}
|
||||
private void sessionScreen(){
|
||||
installRoot("session",true);setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);video=new RemoteVideoView(this,session);video.setRelative(preferences.getBoolean("relativeMouse",true));canvas.addView(video,0,new FrameLayout.LayoutParams(-1,-1));
|
||||
controls=new SessionControls(this,ui,new SessionControls.Actions(){
|
||||
public void disconnect(){confirmDisconnect();}public void display(){selectDisplay();}public void clipboard(){MainActivity.this.clipboard();}
|
||||
public void sendFile(){chooseFile();}public void saveFile(){saveReceivedFile();}public void secureAttention(){MainActivity.this.secureAttention();}
|
||||
public void key(int code){tapKey(code);}
|
||||
public void chord(int code,int[] modifiers){if(session==null)return;for(int modifier:modifiers)session.key(modifier,true);tapKey(code);for(int i=modifiers.length-1;i>=0;i--)session.key(modifiers[i],false);}public void shortcut(int code){MainActivity.this.shortcut(code);}public void text(String value){sendText(value);}
|
||||
public void mute(){muted=!muted;if(session!=null)session.control(2,muted?0:1);controls.setMuted(muted);}
|
||||
public void mouse(){boolean relative=!preferences.getBoolean("relativeMouse",true);preferences.edit().putBoolean("relativeMouse",relative).apply();video.setRelative(relative);controls.setRelative(relative);}
|
||||
public void videoSettings(int field,int value){RemoteVideoSettings.Values old=MainActivity.this.videoSettings.selection;updateVideoSettings(new RemoteVideoSettings.Values(field==0?value:old.quality,field==1?value:old.frameRate,field==2?value:old.preference));}
|
||||
});controls.setRelative(preferences.getBoolean("relativeMouse",true));controls.setMuted(muted);controls.videoSettings(videoSettings);root.addView(controls,new LinearLayout.LayoutParams(-1,-1));getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
controls.attachMouseBar(canvas,new VirtualMouseBar(ui,video.mouseInput));
|
||||
video.addOnLayoutChangeListener((view,left,top,right,bottom,oldLeft,oldTop,oldRight,oldBottom)->{
|
||||
if(!pictureInPictureUi&&!isInPictureInPictureMode())updatePictureInPicture();
|
||||
});
|
||||
pictureInPicture.connected();updatePictureInPicture();
|
||||
}
|
||||
private void confirmDisconnect(){disconnectDialog=new AlertDialog.Builder(this).setTitle("断开远程连接?").setMessage("断开后将返回首页").setNegativeButton("取消",null).setPositiveButton("断开连接",(d,w)->end("")).show();}
|
||||
private void end(String reason){
|
||||
if(backgroundSession!=null){BackgroundSession retained=backgroundSession;backgroundSession=null;retained.detach(this);retained.finish(reason);}
|
||||
boolean closeWindow=isInPictureInPictureMode();
|
||||
pictureInPicture.disconnect();updatePictureInPicture();
|
||||
if(controls!=null)controls.cancelMouseInput();if(video!=null)video.releaseMouse();
|
||||
mainHandler.removeCallbacks(documentTimeout);documentSession=null;documentToSave=null;receivedFile=null;remoteServiceAvailable=false;
|
||||
resetRemoteVersionCheck();
|
||||
resetVideoSettings();
|
||||
previewCapture=null;previewCopying=false;
|
||||
if(progressDialog!=null){progressDialog.dismiss();progressDialog=null;}if(session!=null){releaseKeys();session.close();session=null;}stopSignaling();pendingPassword="";remoteClipboard="";hostPlatform="";displays=new JSONArray();ready=false;video=null;controls=null;getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
if(closeWindow){finish();return;}
|
||||
home(reason);
|
||||
appUpdates.checkNow();
|
||||
}
|
||||
private void settings(){
|
||||
LinearLayout content=formPage("settings","设置",()->home(""));
|
||||
LinearLayout mouse=section(content,"鼠标控制",MobileUi.SETTINGS_CARD_RADIUS);mouse.setPadding(dp(12),dp(12),dp(12),dp(12));boolean relative=preferences.getBoolean("relativeMouse",true);
|
||||
mouse.addView(segments(new String[]{"相对位置","绝对位置"},relative?0:1,true,index->preferences.edit().putBoolean("relativeMouse",index==0).apply()));
|
||||
LinearLayout picture=section(content,"画面偏好",MobileUi.SETTINGS_CARD_RADIUS);picture.setPadding(dp(12),dp(12),dp(12),dp(12));int preference=Math.max(0,Math.min(2,preferences.getInt("videoPreference",1)));
|
||||
picture.addView(segments(RemoteVideoSettings.PREFERENCES,preference,true,index->preferences.edit().putInt("videoPreference",index).apply()));ui.gap(content,28);
|
||||
LinearLayout server=section(content,"",MobileUi.SETTINGS_CARD_RADIUS);LinearLayout fields=column();fields.setVisibility(View.GONE);boolean custom=!host.equals("api.crossdesk.cn")||port!=9099;
|
||||
link(server,"服务器",custom?"自定义":"默认",()->fields.setVisibility(fields.getVisibility()==View.VISIBLE?View.GONE:View.VISIBLE));server.addView(fields);
|
||||
LinearLayout toggleRow=row();toggleRow.setPadding(dp(16),dp(8),dp(16),dp(8));toggleRow.addView(text("使用自定义服务器",16,false),new LinearLayout.LayoutParams(0,-2,1));Switch toggle=new Switch(this);toggle.setContentDescription("使用自定义服务器");toggle.setChecked(custom);toggleRow.addView(toggle);fields.addView(toggleRow);
|
||||
LinearLayout inputs=column();inputs.setPadding(dp(12),0,dp(12),dp(12));EditText address=field("服务器地址",InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_URI),number=field("服务器端口",InputType.TYPE_CLASS_NUMBER);address.setText(custom?host:"");number.setText(custom?String.valueOf(port):"");inputs.addView(address,ui.size(-1,48));ui.gap(inputs,8);inputs.addView(number,ui.size(-1,48));ui.gap(inputs,8);
|
||||
inputs.addView(ui.action("完成",BLUE,()->{if(saveServer(address,number)){hideKeyboard();settings();}}));fields.addView(inputs);inputs.setVisibility(custom?View.VISIBLE:View.GONE);
|
||||
toggle.setOnCheckedChangeListener((button,checked)->{inputs.setVisibility(checked?View.VISIBLE:View.GONE);if(!checked){host="api.crossdesk.cn";port=9099;preferences.edit().putString("host",host).putInt("port",port).apply();ensureSignaling();} });
|
||||
backAction=()->{if(toggle.isChecked()&&!saveServer(address,number))return;hideKeyboard();home("");};
|
||||
identitySummary=text("",12,false);identitySummary.setTextColor(SECONDARY);identitySummary.setGravity(Gravity.CENTER);identitySummary.setPadding(dp(16),dp(12),dp(16),dp(16));identitySummary.setTextIsSelectable(true);content.addView(identitySummary);renderSignaling();
|
||||
LinearLayout privacy=section(content,"隐私",MobileUi.SETTINGS_CARD_RADIUS);link(privacy,"隐私与授权",preferences.getBoolean("networkConsent",false)?"已授权":"未授权",this::privacyPage);ui.divider(privacy);
|
||||
LinearLayout preview=row();preview.setPadding(dp(16),dp(10),dp(16),dp(10));preview.addView(text("保存远程画面预览",16,false),new LinearLayout.LayoutParams(0,-2,1));previewSwitch=new Switch(this);previewSwitch.setContentDescription("保存远程画面预览");preview.addView(previewSwitch);privacy.addView(preview);
|
||||
previewSwitch.setOnCheckedChangeListener((button,checked)->{if(updatingPreviewSwitch)return;if(checked){renderPreviews();confirmPreviewSaving();}else previews.setEnabled(false);});
|
||||
ui.divider(privacy);clearPreviewsButton=ui.action("清除预览图",RED,this::confirmClearPreviews);clearPreviewsButton.setGravity(Gravity.START|Gravity.CENTER_VERTICAL);clearPreviewsButton.setTypeface(Typeface.DEFAULT);clearPreviewsButton.setPadding(dp(16),0,dp(16),0);privacy.addView(clearPreviewsButton,ui.size(-1,48));
|
||||
previewCleanupError=text("",12,false);previewCleanupError.setTextColor(RED);previewCleanupError.setPadding(dp(16),dp(8),dp(16),dp(12));privacy.addView(previewCleanupError);renderPreviews();
|
||||
ui.gap(content,28);LinearLayout about=section(content,"",MobileUi.SETTINGS_CARD_RADIUS);LinearLayout aboutLink=link(about,"关于","新版本",this::about);aboutUpdateRow=aboutLink;
|
||||
aboutUpdateLabel=(TextView)aboutLink.getChildAt(1);aboutUpdateLabel.setPadding(0,0,dp(8),0);
|
||||
aboutUpdateDot=updateDot();LinearLayout.LayoutParams dotPosition=new LinearLayout.LayoutParams(dp(8),dp(8));dotPosition.setMarginEnd(dp(8));aboutLink.addView(aboutUpdateDot,2,dotPosition);renderAppUpdates();
|
||||
}
|
||||
private void confirmPreviewSaving(){
|
||||
previewDialog=new AlertDialog.Builder(this).setTitle("保存远程画面预览?")
|
||||
.setMessage("预览可能包含远程电脑上的个人或工作信息。开启后,每次连接会自动将一张画面保存在本机并显示在最近连接中。你可以随时关闭并清除。")
|
||||
.setNegativeButton("取消",null).setPositiveButton("开启保存",(d,w)->previews.setEnabled(true)).show();
|
||||
previewDialog.setOnDismissListener(d->{previewDialog=null;renderPreviews();});
|
||||
}
|
||||
private void confirmClearPreviews(){
|
||||
previewDialog=new AlertDialog.Builder(this).setTitle("清除预览图?")
|
||||
.setMessage("将删除本机保存的所有远程预览图,保留连接记录和密码。"+(previews.enabled()?"后续连接仍会保存新的预览图。":""))
|
||||
.setNegativeButton("取消",null).setPositiveButton("清除",(d,w)->previews.clear()).show();
|
||||
previewDialog.setOnDismissListener(d->previewDialog=null);
|
||||
}
|
||||
private void renderPreviews(){
|
||||
if(previews==null)return;
|
||||
if(!previews.enabled()||previews.cleaning)previewCapture=null;
|
||||
if(previewSwitch!=null){updatingPreviewSwitch=true;previewSwitch.setChecked(previews.enabled());previewSwitch.setEnabled(preferences.getBoolean("networkConsent",false)&&!previews.cleaning);updatingPreviewSwitch=false;}
|
||||
if(clearPreviewsButton!=null){clearPreviewsButton.setText(previews.cleaning?"正在清除…":"清除预览图");clearPreviewsButton.setEnabled(!previews.cleaning);}
|
||||
if(previewCleanupError!=null){previewCleanupError.setText(previews.cleanupError);previewCleanupError.setVisibility(previews.cleanupError.isEmpty()?View.GONE:View.VISIBLE);}
|
||||
for(Runnable card:previewCards)card.run();
|
||||
}
|
||||
private void capturePreviewIfNeeded(){
|
||||
if(!ready||video==null||previewCapture==null||previewCopying||!previews.current(previewCapture))return;
|
||||
if(!history.contains(serverKey(),connectedRemote)){previewCapture=null;return;}
|
||||
RemotePreviewStore.Capture capture=previewCapture;NativeSession source=session;previewCopying=true;
|
||||
video.capturePreview(bitmap->{
|
||||
if(session!=source||previewCapture!=capture||!previews.current(capture)){if(bitmap!=null)bitmap.recycle();return;}
|
||||
previewCopying=false;
|
||||
if(bitmap!=null){previewCapture=null;previews.save(capture,bitmap);}
|
||||
else if(++previewAttempts>=3)previewCapture=null;
|
||||
});
|
||||
}
|
||||
private View segments(String[] titles,int selected,boolean enabled,java.util.function.IntConsumer changed){
|
||||
return new SegmentedControl(ui,titles,selected,enabled,changed);
|
||||
}
|
||||
private boolean saveServer(EditText address,EditText number){
|
||||
String name=address.getText().toString().trim();int value;try{value=Integer.parseInt(number.getText().toString());}catch(NumberFormatException e){number.setError("请输入 1–65535 范围内的端口");return false;}
|
||||
if(name.length()>253||!name.matches("[A-Za-z0-9.-]+")||name.startsWith(".")||name.endsWith(".")){address.setError("填写主机名或 IPv4 地址,不含协议和路径");return false;}if(value<1||value>65535){number.setError("端口范围为 1–65535");return false;}host=name;port=value;preferences.edit().putString("host",host).putInt("port",port).apply();ensureSignaling();return true;
|
||||
}
|
||||
private void announcements(){
|
||||
installRoot("announcements",false);LinearLayout bar=navigation("通知公告",()->home(""));
|
||||
bar.removeViewAt(bar.getChildCount()-1);announcementRefresh=ui.iconButton("refresh","刷新公告",announcementInbox::refresh);bar.addView(announcementRefresh,ui.size(44,44));
|
||||
announcementView=new AnnouncementView(ui,announcementInbox,null,this::announcementDetail,this::connectAnnouncements);
|
||||
root.addView(announcementView,new LinearLayout.LayoutParams(-1,0,1));announcementInbox.refresh();renderAnnouncements();
|
||||
}
|
||||
private void announcementDetail(AnnouncementInbox.Item item){
|
||||
installRoot("announcement-detail",false);navigation("公告详情",this::announcements);
|
||||
announcementView=new AnnouncementView(ui,announcementInbox,item,this::announcementDetail,this::connectAnnouncements);
|
||||
root.addView(announcementView,new LinearLayout.LayoutParams(-1,0,1));announcementInbox.markRead(item);
|
||||
}
|
||||
private void connectAnnouncements(){
|
||||
if(!preferences.getBoolean("networkConsent",false))consent(()->{ensureSignaling();renderAnnouncements();});
|
||||
else{stopSignaling();ensureSignaling();}
|
||||
}
|
||||
private void renderAnnouncements(){
|
||||
if(announcementBadge!=null){int unread=announcementInbox.unread;announcementBadge.setText(unread>99?"99+":String.valueOf(unread));announcementBadge.setVisibility(unread>0?View.VISIBLE:View.GONE);
|
||||
if(android.os.Build.VERSION.SDK_INT>=30)((View)announcementBadge.getParent()).setStateDescription(unread>0?unread+" 条未读":"无未读公告");}
|
||||
if(announcementRefresh!=null){boolean enabled=announcementInbox.isConnected()&&!announcementInbox.loading;announcementRefresh.setEnabled(enabled);announcementRefresh.setAlpha(enabled?1:.4f);}
|
||||
if(announcementView!=null)announcementView.render();
|
||||
}
|
||||
@Override public void announcement(JSONObject message){
|
||||
if(!preferences.getBoolean("networkConsent",false)||signalState!=1)return;
|
||||
if("announcements_changed".equals(message.optString("type")))announcementInbox.refresh();else announcementInbox.receive(message);
|
||||
}
|
||||
@Override public void announcementFailed(String requestId){announcementInbox.failed(requestId);}
|
||||
private void privacyPage(){
|
||||
LinearLayout content=formPage("privacy","隐私与授权",this::settings);LinearLayout card=section(content,"");boolean consent=preferences.getBoolean("networkConsent",false);link(card,"授权状态",consent?"已授权":"未授权",()->{});ui.divider(card);link(card,"隐私政策","",this::privacyPolicyPage);
|
||||
footer(content,"设备身份及选择保存的访问密码使用 Android Keystore 加密。连接记录仅保存在本机,不纳入设备备份。剪贴板内容在结束会话时清除。离开应用后通过画中画或连接通知保持会话,可在应用或通知中断开。");
|
||||
if(consent)content.addView(ui.action("撤回联网授权",RED,()->new AlertDialog.Builder(this).setTitle("撤回联网授权?").setMessage("撤回后将停止远程连接、关闭画面预览保存并清除已有预览。连接记录和密码会保留,重新连接前需再次授权。").setNegativeButton("取消",null).setPositiveButton("撤回",(d,w)->{preferences.edit().putBoolean("networkConsent",false).apply();appUpdates.setEnabled(false);previews.setEnabled(false);stopSignaling();announcementInbox.reset();privacyPage();}).show()));else content.addView(ui.primary("阅读并授权",()->consent(this::privacyPage)));
|
||||
}
|
||||
private void privacyPolicyPage(){
|
||||
installRoot("privacy-policy",false);navigation("隐私政策",this::privacyPage);
|
||||
root.addView(new PrivacyPolicyDocument(this).view(ui),new LinearLayout.LayoutParams(-1,0,1));
|
||||
}
|
||||
String applicationVersion(){
|
||||
try{return getPackageManager().getPackageInfo(getPackageName(),0).versionName;}catch(android.content.pm.PackageManager.NameNotFoundException error){return "";}
|
||||
}
|
||||
View updateDot(){View dot=new View(this);dot.setBackground(ui.background(RED,4));dot.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);return dot;}
|
||||
boolean hasNetworkConsent(){return preferences.getBoolean("networkConsent",false);}
|
||||
void checkAppUpdates(){
|
||||
if(hasNetworkConsent())appUpdates.checkNow();
|
||||
else consent(appUpdates::checkNow);
|
||||
}
|
||||
private void renderAppUpdates(){
|
||||
boolean available=appUpdates.updateAvailable();
|
||||
if(settingsUpdateDot!=null)settingsUpdateDot.setVisibility(available?View.VISIBLE:View.GONE);
|
||||
if(aboutUpdateDot!=null)aboutUpdateDot.setVisibility(available?View.VISIBLE:View.GONE);
|
||||
if(aboutUpdateLabel!=null)aboutUpdateLabel.setVisibility(available?View.VISIBLE:View.GONE);
|
||||
if(settingsUpdateButton!=null)settingsUpdateButton.setContentDescription(available?"设置,有新版本":"设置");
|
||||
if(aboutUpdateRow!=null)aboutUpdateRow.setContentDescription(available?"关于,有新版本":"关于");
|
||||
if(aboutPages!=null&&page.equals("about"))aboutPages.renderUpdates();
|
||||
}
|
||||
private void about(){
|
||||
if(aboutPages==null)aboutPages=new AboutPages(this,ui,this::settings,appUpdates);aboutPages.show();
|
||||
}
|
||||
private void sendText(String value){if(session==null)return;if(value.length()>2048){toast("单次最多 2048 个字符");return;}for(char ch:value.toCharArray())if(KeyMap.ascii(ch)==0){toast("中文等文本请通过剪贴板发送,再点击粘贴");return;}for(char ch:value.toCharArray()){int code=KeyMap.ascii(ch);boolean shift=(code&0x100)!=0;if(shift)session.key(0x10,true);tapKey(code&0xFF);if(shift)session.key(0x10,false);}}
|
||||
private void tapKey(int code){if(session!=null){session.key(code,true);session.key(code,false);}}
|
||||
private void shortcut(int code){if(session!=null){int modifier=hostPlatform.equals("macos")?0x5B:0x11;session.key(modifier,true);tapKey(code);session.key(modifier,false);}}
|
||||
private void selectDisplay(){
|
||||
if(!ready)return;int count=Math.min(displays.length(),8);if(count==0){toast("等待远端屏幕信息");return;}String[] labels=new String[count];for(int i=0;i<count;i++){JSONObject display=displays.optJSONObject(i);labels[i]=(i+1)+" · "+(display==null?"显示器":display.optString("name","显示器"));}new AlertDialog.Builder(this).setTitle("显示器").setItems(labels,(d,w)->{if(session!=null){if(w!=selectedDisplay&&video!=null)video.resetViewport();selectedDisplay=w;session.control(4,w);if(controls!=null)controls.resetVideoStatistics();}}).show();
|
||||
}
|
||||
private void secureAttention(){
|
||||
if(!ready||session==null)return;
|
||||
if(!remoteServiceAvailable){controlFeedback(hostPlatform.equals("windows")?"请在远端启用 CrossDesk 系统服务后重试":"Ctrl+Alt+Del 需要远端 Windows 系统服务支持");return;}
|
||||
session.secureAttention();
|
||||
}
|
||||
private void chooseFile(){
|
||||
if(!ready||session==null)return;
|
||||
openDocument(new Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*"),PICK_FILE);
|
||||
}
|
||||
private void saveReceivedFile(){
|
||||
if(!ready||session==null||receivedFile==null)return;
|
||||
documentToSave=receivedFile;
|
||||
openDocument(new Intent(Intent.ACTION_CREATE_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("application/octet-stream").putExtra(Intent.EXTRA_TITLE,receivedFile.getName()),SAVE_FILE);
|
||||
}
|
||||
private void openDocument(Intent intent,int request){
|
||||
if(documentSession!=null)return;
|
||||
documentSession=session;releaseKeys();
|
||||
pictureInPicture.choosingDocument(true);updatePictureInPicture();
|
||||
try{startActivityForResult(intent,request);mainHandler.postDelayed(documentTimeout,5*60*1000);}
|
||||
catch(android.content.ActivityNotFoundException error){documentSession=null;documentToSave=null;pictureInPicture.choosingDocument(false);updatePictureInPicture();controlFeedback("此设备没有可用的文件选择器");}
|
||||
}
|
||||
@Override protected void onActivityResult(int request,int result,Intent data){
|
||||
super.onActivityResult(request,result,data);
|
||||
if(request!=PICK_FILE&&request!=SAVE_FILE)return;
|
||||
NativeSession source=documentSession;java.io.File saved=documentToSave;
|
||||
documentSession=null;documentToSave=null;mainHandler.removeCallbacks(documentTimeout);
|
||||
pictureInPicture.choosingDocument(false);updatePictureInPicture();
|
||||
if(source==null||source!=session||!ready||result!=RESULT_OK||data==null||data.getData()==null)return;
|
||||
if(request==PICK_FILE)source.sendFile(data.getData());else if(saved!=null)source.saveFile(saved,data.getData());
|
||||
}
|
||||
@Override public void fileTransfer(String name,double progress,boolean sending,java.io.File received){
|
||||
if(!ready)return;
|
||||
if(received!=null)receivedFile=received;
|
||||
String fileStatus=progress<0?name+" 传输失败":(sending?"发送 ":"接收 ")+name+(progress>=1?" · 已完成":" · "+(int)(progress*100)+"%");
|
||||
if(controls!=null)controls.fileStatus(fileStatus,receivedFile!=null);
|
||||
if(progress<0||progress>=1)toast(fileStatus);
|
||||
}
|
||||
@Override public void controlFeedback(String message){
|
||||
toast(message);
|
||||
}
|
||||
private void clipboard(){
|
||||
if(!ready)return;
|
||||
EditText input=field("要发送到远端的文本",InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_MULTI_LINE);input.setSingleLine(false);input.setMinLines(3);
|
||||
new AlertDialog.Builder(this).setTitle("剪贴板").setView(input)
|
||||
.setMessage("发送后,在远程键盘中点击“粘贴”。接收的远端文本可手动复制到本机。")
|
||||
.setNegativeButton("关闭",null).setNeutralButton("复制远端文本",(d,w)->{
|
||||
if(!remoteClipboard.isEmpty())((ClipboardManager)getSystemService(CLIPBOARD_SERVICE)).setPrimaryClip(ClipData.newPlainText("CrossDesk",remoteClipboard));
|
||||
}).setPositiveButton("发送文本",(d,w)->{
|
||||
String value=input.getText().toString();
|
||||
if(value.getBytes(java.nio.charset.StandardCharsets.UTF_8).length>128*1024){Toast.makeText(this,"文本超过 128 KB",Toast.LENGTH_SHORT).show();return;}
|
||||
if(session!=null)session.clipboard(value);
|
||||
}).show();
|
||||
}
|
||||
void licenseDocument(String title,String value,Runnable back){
|
||||
installRoot("document:"+title,false);navigation(title,back);
|
||||
// Bound each selectable accessibility node while keeping every character of long notices.
|
||||
java.util.List<String> chunks=new java.util.ArrayList<>();
|
||||
for(int start=0;start<value.length();){int end=Math.min(start+4000,value.length());if(end<value.length()){int newline=value.lastIndexOf('\n',end-1);if(newline>start)end=newline+1;else if(Character.isHighSurrogate(value.charAt(end-1)))end--;}chunks.add(value.substring(start,end));start=end;}
|
||||
ListView paragraphs=new ListView(this);paragraphs.setBackgroundColor(Color.WHITE);paragraphs.setDivider(null);paragraphs.setClipToPadding(false);paragraphs.setPadding(0,dp(8),0,dp(8));
|
||||
paragraphs.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,chunks){
|
||||
@Override public View getView(int position,View reuse,ViewGroup parent){
|
||||
TextView item=(TextView)super.getView(position,reuse,parent);item.setTextColor(INK);item.setTextSize(16);item.setAutoLinkMask(android.text.util.Linkify.WEB_URLS);item.setText(getItem(position));item.setTextIsSelectable(true);item.setLinksClickable(true);item.setLinkTextColor(BLUE);item.setPadding(dp(16),dp(8),dp(16),dp(8));return item;
|
||||
}
|
||||
});root.addView(paragraphs,new LinearLayout.LayoutParams(-1,0,1));
|
||||
}
|
||||
private void ensureSignaling(){
|
||||
if(!foreground||!preferences.getBoolean("networkConsent",false))return;
|
||||
if(signaling!=null&&!signaling.isClosed()&&signalingServer.equals(serverKey()))return;
|
||||
if(!announcementServer.equals(serverKey())){announcementInbox.reset();announcementServer=serverKey();}
|
||||
stopSignaling();signalState=0;signalError="";signalingServer=serverKey();
|
||||
signaling=new NativeSession(this,host,port,"","",this);
|
||||
renderSignaling();signaling.start();
|
||||
}
|
||||
private void stopSignaling(){
|
||||
if(backgroundSession!=null&&backgroundSession.session==signaling){BackgroundSession retained=backgroundSession;backgroundSession=null;retained.detach(this);retained.finish("");}
|
||||
mainHandler.removeCallbacks(presenceTick);recentPresence.setConnected(false,android.os.SystemClock.elapsedRealtime());
|
||||
announcementInbox.setConnected(false);
|
||||
if(signaling!=null)signaling.close();
|
||||
signaling=null;signalingServer="";localIdentity="";signalState=-1;signalError="";renderSignaling();
|
||||
}
|
||||
private void renderSignaling(){
|
||||
boolean consent=preferences.getBoolean("networkConsent",false);
|
||||
boolean connected=consent&&signalError.isEmpty()&&signalState==1;
|
||||
String label;int tint,background;
|
||||
if(!consent){label="等待隐私授权";tint=0xFFB76A00;background=0xFFFFEBD2;}
|
||||
else if(!signalError.isEmpty()){label=signalError.contains("TLS")?"证书校验失败 · 点击重试":"连接失败 · 点击重试";tint=RED;background=0xFFFFE8E6;}
|
||||
else if(connected){label="已连接服务器";tint=GREEN;background=0xFFE5F4E8;}
|
||||
else{label=signalState==0?"正在连接服务器…":signalState==4?"正在重连服务器…":"未连接服务器 · 点击重试";tint=0xFFB76A00;background=0xFFFFEBD2;}
|
||||
if(signalBadge!=null){
|
||||
android.graphics.drawable.Drawable icon=connected?getDrawable(R.drawable.ic_check_circle):null;
|
||||
if(icon!=null){int size=dp(14);icon.setBounds(0,0,size,size);}
|
||||
signalBadge.setCompoundDrawablesRelative(icon,null,null,null);signalBadge.setCompoundDrawablePadding(dp(6));
|
||||
signalBadge.setText(label);signalBadge.setTextColor(tint);signalBadge.setBackground(ui.background(background,20));signalBadge.setContentDescription(signalError.isEmpty()?label:signalError+",点击重试");
|
||||
}
|
||||
if(identitySummary!=null)identitySummary.setText(!consent?"完成隐私授权后登记本机身份":!localIdentity.isEmpty()?"本机 ID "+localIdentity:!signalError.isEmpty()?signalError:"正在获取本机 ID…");
|
||||
}
|
||||
@Override public void signaling(int state,String deviceId){
|
||||
signalState=state;localIdentity=deviceId;signalError="";renderSignaling();
|
||||
long now=android.os.SystemClock.elapsedRealtime();recentPresence.watch(history.list(serverKey()),now);
|
||||
recentPresence.setConnected(foreground&&preferences.getBoolean("networkConsent",false)&&state==1&&!deviceId.isEmpty(),now);
|
||||
mainHandler.removeCallbacks(presenceTick);if(recentPresence.isConnected())mainHandler.postDelayed(presenceTick,1000);
|
||||
if(preferences.getBoolean("networkConsent",false)){announcementInbox.configure(host,port,deviceId);announcementInbox.setConnected(state==1);}
|
||||
}
|
||||
@Override public void presence(JSONObject message){recentPresence.receive(message,android.os.SystemClock.elapsedRealtime());}
|
||||
@Override public void status(String value){if(session!=null&&status!=null)status.setText(value);}
|
||||
@Override public void connected(){
|
||||
// Transport readiness can be reported again after ICE changes its selected path.
|
||||
// The first success consumes pendingPassword; a duplicate must not save it again.
|
||||
if(session==null||ready)return;ready=true;if(progressDialog!=null){progressDialog.dismiss();progressDialog=null;}
|
||||
try{history.save(serverKey(),connectedRemote,connectedRemote,hostPlatform,rememberPassword,pendingPassword);}catch(Exception error){toast("密码保存失败,本次连接仍可使用");}pendingPassword="";sessionScreen();
|
||||
if(!canUsePictureInPicture())prepareBackgroundSession(true);
|
||||
if(videoSettings.supported&&videoSettings.requestId==0)updateVideoSettings(videoSettings.selection);
|
||||
if(foreground&&preferences.getBoolean("networkConsent",false))remoteVersionCheck.connected();
|
||||
}
|
||||
@Override public void ended(String reason){
|
||||
if(session!=null){end(reason);return;}
|
||||
stopSignaling();signalError=reason;renderSignaling();
|
||||
}
|
||||
@Override public void passwordRejected(){
|
||||
if(session==null)return;
|
||||
String id=connectedRemote;boolean remember=rememberPassword;
|
||||
end("");
|
||||
// Let the user replace an expired credential; never retry it automatically.
|
||||
if(foreground)passwordSheet(id,"访问密码错误,请重新输入",remember);
|
||||
}
|
||||
private void cancelVideoSettingsTimeout(){if(videoSettingsTimeout!=null)mainHandler.removeCallbacks(videoSettingsTimeout);videoSettingsTimeout=null;}
|
||||
private void showRemoteUpdate(){
|
||||
if(!ready||session==null||!foreground||pictureInPictureUi||isInPictureInPictureMode()||isFinishing()||!preferences.getBoolean("networkConsent",false))return;
|
||||
remoteUpdateDialog=new AlertDialog.Builder(this).setTitle("升级提示").setMessage(RemoteVersionCheck.NOTICE).setPositiveButton("知道了",null).create();
|
||||
remoteUpdateDialog.setOnDismissListener(dialog->remoteUpdateDialog=null);
|
||||
remoteUpdateDialog.setCanceledOnTouchOutside(false);
|
||||
remoteUpdateDialog.show();
|
||||
}
|
||||
private void resetRemoteVersionCheck(){
|
||||
remoteVersionCheck.reset();
|
||||
if(remoteUpdateDialog!=null){remoteUpdateDialog.dismiss();remoteUpdateDialog=null;}
|
||||
}
|
||||
private void resetVideoSettings(){
|
||||
cancelVideoSettingsTimeout();
|
||||
android.util.DisplayMetrics metrics=getResources().getDisplayMetrics();
|
||||
videoSettings=new RemoteVideoSettings(preferences.getInt("videoPreference",1),Math.max(metrics.widthPixels,metrics.heightPixels));
|
||||
}
|
||||
private void updateVideoSettings(RemoteVideoSettings.Values value){
|
||||
if(!ready||session==null||!preferences.getBoolean("networkConsent",false))return;
|
||||
long request=videoSettings.begin(value);if(request<0)return;
|
||||
cancelVideoSettingsTimeout();if(controls!=null)controls.videoSettings(videoSettings);session.videoSettings(value,request);
|
||||
videoSettingsTimeout=()->{videoSettings.expire(request);if(controls!=null)controls.videoSettings(videoSettings);};mainHandler.postDelayed(videoSettingsTimeout,5000);
|
||||
}
|
||||
@Override public void data(JSONObject message){
|
||||
if(session==null)return;
|
||||
if(message.optInt("type",-1)==5){JSONObject service=message.optJSONObject("service_status");remoteServiceAvailable=service!=null&&service.optBoolean("available",false);return;}
|
||||
if(message.optInt("type",-1)==12){if(!ready)return;videoSettings.receive(message);if(!videoSettings.pending)cancelVideoSettingsTimeout();if(controls!=null)controls.videoSettings(videoSettings);return;}
|
||||
JSONObject info=message.optJSONObject("host_info");
|
||||
if(info!=null){
|
||||
hostPlatform=info.optString("platform","");JSONArray list=info.optJSONArray("displays");if(list!=null)displays=list;history.metadata(serverKey(),connectedRemote,info.optString("host_name",connectedRemote),hostPlatform);
|
||||
boolean wasSupported=videoSettings.supported;videoSettings.setSupported(info.optBoolean("supports_video_settings",false));
|
||||
if(!videoSettings.supported)cancelVideoSettingsTimeout();
|
||||
if(controls!=null)controls.videoSettings(videoSettings);
|
||||
if(videoSettings.supported&&!wasSupported)updateVideoSettings(videoSettings.selection);
|
||||
if(foreground&&preferences.getBoolean("networkConsent",false))remoteVersionCheck.hostInfo(info);
|
||||
}
|
||||
}
|
||||
@Override public void videoSize(int width,int height){videoWidth=width;videoHeight=height;if(video!=null)video.videoSize(width,height);if(controls!=null)controls.videoSize(width,height);pictureInPicture.videoSize(width,height);updatePictureInPicture();}
|
||||
@Override public void clipboard(String value){remoteClipboard=value;}
|
||||
@Override public void statistics(RemoteNetworkStatistics.Snapshot value){if(controls!=null)controls.statistics(value);if(value.fps>0)capturePreviewIfNeeded();}
|
||||
@Override public boolean dispatchKeyEvent(KeyEvent event){
|
||||
if(ready&&session!=null&&!pictureInPictureUi&&hasWindowFocus()&&!(getCurrentFocus() instanceof EditText)&&event.getKeyCode()!=KeyEvent.KEYCODE_BACK){int code=KeyMap.windowsCode(event.getKeyCode());if(code!=0){boolean down=event.getAction()==KeyEvent.ACTION_DOWN;if(down)pressed.add(code);else pressed.remove(code);session.key(code,down);return true;}}return super.dispatchKeyEvent(event);
|
||||
}
|
||||
private void releaseKeys(){if(session!=null)for(int code:pressed)session.key(code,false);pressed.clear();}
|
||||
private void navigateBack(){if(backAction==null)return;navigatingBack=true;try{backAction.run();}finally{navigatingBack=false;}}
|
||||
private void back(){pageHost.finish();if(session!=null){if(ready)confirmDisconnect();else end("");}else if(backAction!=null)navigateBack();else finish();}
|
||||
@Override public void onWindowFocusChanged(boolean focus){super.onWindowFocusChanged(focus);if(!focus)releaseKeys();else applySystemBars(ready);}
|
||||
@android.annotation.SuppressLint("GestureBackNavigation") @Override public void onBackPressed(){back();}
|
||||
@Override public void onConfigurationChanged(Configuration config){
|
||||
super.onConfigurationChanged(config);
|
||||
releaseKeys();
|
||||
if(!page.equals("session"))updateHomeOrientation();
|
||||
sizePasswordDialog();
|
||||
if(privacyDialog instanceof PrivacyConsentDialog)((PrivacyConsentDialog)privacyDialog).updateSize();
|
||||
if(controls!=null&&!pictureInPictureUi)controls.post(controls::constrainPanels);
|
||||
if(video!=null)video.post(this::updatePictureInPicture);
|
||||
}
|
||||
private boolean supportsPictureInPicture(){return getPackageManager().hasSystemFeature(android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE);}
|
||||
private boolean canUsePictureInPicture(){
|
||||
if(!supportsPictureInPicture())return false;
|
||||
android.app.AppOpsManager ops=getSystemService(android.app.AppOpsManager.class);
|
||||
int mode=ops.checkOpNoThrow(android.app.AppOpsManager.OPSTR_PICTURE_IN_PICTURE,android.os.Process.myUid(),getPackageName());
|
||||
return mode==android.app.AppOpsManager.MODE_ALLOWED||mode==android.app.AppOpsManager.MODE_DEFAULT;
|
||||
}
|
||||
private void captureBackgroundSession(){
|
||||
BackgroundSession retained=backgroundSession;if(retained==null)return;
|
||||
retained.identity=localIdentity;retained.signalState=signalState;retained.platform=hostPlatform;retained.displays=displays;
|
||||
retained.muted=muted;retained.selectedDisplay=selectedDisplay;retained.remoteServiceAvailable=remoteServiceAvailable;
|
||||
retained.clipboard=remoteClipboard;retained.videoSettings=videoSettings;retained.receivedFile=receivedFile;
|
||||
retained.width=videoWidth;retained.height=videoHeight;
|
||||
}
|
||||
private boolean prepareBackgroundSession(boolean inform){
|
||||
if(!ready||session==null||session.isClosed()||isFinishing()||!hasNetworkConsent())return false;
|
||||
if(backgroundSession!=null&&!backgroundSession.ended)return RemoteSessionService.current()==backgroundSession;
|
||||
BackgroundSession retained=new BackgroundSession(this,session,host,port,connectedRemote);
|
||||
backgroundSession=retained;captureBackgroundSession();retained.attach(this);session.setListener(retained);
|
||||
if(!RemoteSessionService.retain(this,retained)){
|
||||
session.setListener(this);retained.detach(this);backgroundSession=null;
|
||||
if(inform)toast("后台保活未能启动,请保持应用在前台");return false;
|
||||
}
|
||||
if(inform){
|
||||
toast("已启用后台保活,可从连接通知返回或断开");
|
||||
requestBackgroundNotifications();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
private void requestBackgroundNotifications(){
|
||||
if(android.os.Build.VERSION.SDK_INT>=33&&checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS)!=android.content.pm.PackageManager.PERMISSION_GRANTED&&!preferences.getBoolean("notificationPermissionAsked",false)){
|
||||
preferences.edit().putBoolean("notificationPermissionAsked",true).apply();
|
||||
requestPermissions(new String[]{android.Manifest.permission.POST_NOTIFICATIONS},43);
|
||||
}
|
||||
}
|
||||
private boolean restoreBackgroundSession(){
|
||||
BackgroundSession retained=backgroundSession!=null?backgroundSession:RemoteSessionService.current();
|
||||
if(retained==null)return false;
|
||||
if(retained.ended||retained.session.isClosed()||!hasNetworkConsent()||!host.equals(retained.host)||port!=retained.port){
|
||||
retained.detach(this);retained.finish("后台连接已结束,请重新连接");backgroundSession=null;
|
||||
if(session==retained.session)end(retained.endReason);return false;
|
||||
}
|
||||
boolean rebuild=session!=retained.session||video==null||!page.equals("session");
|
||||
backgroundSession=retained;session=signaling=retained.session;signalingServer=serverKey();
|
||||
connectedRemote=retained.remote;localIdentity=retained.identity;signalState=retained.signalState;signalError="";
|
||||
hostPlatform=retained.platform;displays=retained.displays;muted=retained.muted;selectedDisplay=retained.selectedDisplay;
|
||||
remoteServiceAvailable=retained.remoteServiceAvailable;remoteClipboard=retained.clipboard;receivedFile=retained.receivedFile;
|
||||
videoSettings=retained.videoSettings;ready=true;retained.attach(this);
|
||||
if(rebuild)sessionScreen();
|
||||
if(retained.width>0&&retained.height>0)videoSize(retained.width,retained.height);
|
||||
if(controls!=null){controls.setMuted(muted);controls.videoSettings(videoSettings);controls.fileStatus(retained.fileStatus,receivedFile!=null);}
|
||||
retained.setBackground(false);signaling(signalState,localIdentity);
|
||||
return true;
|
||||
}
|
||||
private android.app.PictureInPictureParams pictureInPictureParams(){
|
||||
return pictureInPicture.parameters(video==null||pictureInPictureUi||isInPictureInPictureMode()?null:video.pictureInPictureBounds());
|
||||
}
|
||||
private void updatePictureInPicture(){
|
||||
if(!supportsPictureInPicture()||isDestroyed())return;
|
||||
try{setPictureInPictureParams(pictureInPictureParams());}
|
||||
catch(IllegalArgumentException|IllegalStateException error){android.util.Log.w("CrossDesk","Picture in Picture parameters unavailable",error);}
|
||||
}
|
||||
private void enterRemotePictureInPicture(){
|
||||
if(isInPictureInPictureMode())return;
|
||||
if(!canUsePictureInPicture()){
|
||||
prepareBackgroundSession(false);return;
|
||||
}
|
||||
if(!pictureInPicture.canEnter()||session==null||session.isClosed()||isFinishing())return;
|
||||
android.app.PictureInPictureParams params=pictureInPictureParams();
|
||||
setPictureInPictureUi(true);
|
||||
boolean entered=false;
|
||||
try{entered=enterPictureInPictureMode(params);}
|
||||
catch(IllegalArgumentException|IllegalStateException error){android.util.Log.w("CrossDesk","Picture in Picture could not start",error);}
|
||||
if(!entered){setPictureInPictureUi(false);prepareBackgroundSession(false);}
|
||||
}
|
||||
private void setPictureInPictureUi(boolean value){
|
||||
pictureInPictureUi=value;
|
||||
if(value){releaseKeys();hideKeyboard();pageHost.finish();if(disconnectDialog!=null)disconnectDialog.dismiss();if(remoteUpdateDialog!=null)remoteUpdateDialog.dismiss();}
|
||||
if(controls!=null)controls.setPictureInPicture(value);
|
||||
if(video!=null)video.setPictureInPicture(value);
|
||||
}
|
||||
@Override protected void onUserLeaveHint(){
|
||||
super.onUserLeaveHint();
|
||||
if(documentSession!=null)return;
|
||||
if(!canUsePictureInPicture()||!pictureInPicture.canEnter())prepareBackgroundSession(false);
|
||||
else if(android.os.Build.VERSION.SDK_INT<31)enterRemotePictureInPicture();
|
||||
}
|
||||
@Override public void onPictureInPictureModeChanged(boolean active,Configuration config){
|
||||
super.onPictureInPictureModeChanged(active,config);if(active)enteredPictureInPicture=true;setPictureInPictureUi(active);
|
||||
if(!active&&video!=null)video.post(this::updatePictureInPicture);
|
||||
}
|
||||
@android.annotation.TargetApi(31)
|
||||
@Override public void onPictureInPictureUiStateChanged(android.app.PictureInPictureUiState state){
|
||||
super.onPictureInPictureUiStateChanged(state);
|
||||
if(android.os.Build.VERSION.SDK_INT>=35&&state.isTransitioningToPip())setPictureInPictureUi(true);
|
||||
}
|
||||
@Override protected void onResume(){super.onResume();if(!isInPictureInPictureMode())enteredPictureInPicture=false;setPictureInPictureUi(isInPictureInPictureMode());updatePictureInPicture();if(ready&&!canUsePictureInPicture())prepareBackgroundSession(true);if(backgroundSession!=null)requestBackgroundNotifications();}
|
||||
// onStart marks a new visit; focus/resume callbacks must not reopen a refused notice.
|
||||
@Override protected void onPause(){releaseKeys();if(controls!=null)controls.cancelMouseInput();if(video!=null)video.releaseMouse();super.onPause();}
|
||||
@Override protected void onStart(){super.onStart();foreground=true;restoreBackgroundSession();appUpdates.setEnabled(preferences.getBoolean("networkConsent",false));if(!preferences.getBoolean("networkConsent",false))consent(this::renderSignaling);ensureSignaling();showConnectionMessage();}
|
||||
@Override protected void onStop(){foreground=false;appUpdates.setEnabled(false);if(privacyDialog!=null)privacyDialog.dismiss();pageHost.finish();
|
||||
if(connectionDialog!=null)connectionDialog.dismiss();
|
||||
// Closing native PiP is an explicit end, not a request for invisible
|
||||
// fallback. An unavailable/failed PiP can hand its live session off.
|
||||
if(!isFinishing()&&!enteredPictureInPicture&&ready&&(backgroundSession!=null||documentSession==null)&&prepareBackgroundSession(false)){
|
||||
captureBackgroundSession();backgroundSession.detach(this);backgroundSession.setBackground(true);
|
||||
mainHandler.removeCallbacks(presenceTick);recentPresence.setConnected(false,android.os.SystemClock.elapsedRealtime());announcementInbox.setConnected(false);
|
||||
cancelVideoSettingsTimeout();if(videoSettings.pending)videoSettings.expire(videoSettings.requestId);
|
||||
resetRemoteVersionCheck();if(disconnectDialog!=null)disconnectDialog.dismiss();
|
||||
}else if(documentSession==null||documentSession!=session||isFinishing()){if(session!=null)end(isFinishing()?"":"远程窗口已关闭,或后台保活未能启动,会话已结束");stopSignaling();}
|
||||
super.onStop();}
|
||||
@Override protected void onDestroy(){mainHandler.removeCallbacks(documentTimeout);documentSession=null;documentToSave=null;appUpdates.setEnabled(false);pageHost.finish();resetRemoteVersionCheck();cancelVideoSettingsTimeout();previews.removeListener(previewChanged);if(privacyDialog!=null)privacyDialog.dismiss();if(previewDialog!=null)previewDialog.dismiss();announcementInbox.close();if(disconnectDialog!=null)disconnectDialog.dismiss();if(passwordDialog!=null)passwordDialog.dismiss();if(progressDialog!=null)progressDialog.dismiss();
|
||||
if(connectionDialog!=null)connectionDialog.dismiss();
|
||||
boolean retained=!isFinishing()&&backgroundSession!=null&&!backgroundSession.ended&&RemoteSessionService.current()==backgroundSession;
|
||||
if(backgroundSession!=null)backgroundSession.detach(this);
|
||||
if(!retained){if(session!=null)session.close();stopSignaling();}else{mainHandler.removeCallbacks(presenceTick);session=signaling=null;}
|
||||
super.onDestroy();}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.*;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.graphics.drawable.GradientDrawable;
|
||||
import android.view.*;
|
||||
import android.widget.*;
|
||||
|
||||
/** Shared visual tokens matching the SwiftUI mobile screens. Values are in dp/sp. */
|
||||
final class MobileUi {
|
||||
static final int BACKGROUND=0xFFF2F2F7, INK=0xFF1C1C1E, SECONDARY=0xFF737378,
|
||||
LINE=0xFFE2E2E7, BLUE=0xFF2E7ADB, RED=0xFFFF3B30, GREEN=0xFF248A3D;
|
||||
// Match the iOS 26 Form sections and segmented Picker dimensions.
|
||||
static final int SETTINGS_CARD_RADIUS=26, SEGMENT_HEIGHT=32, SEGMENT_INSET=2;
|
||||
final Context context;
|
||||
MobileUi(Context context) { this.context=context; }
|
||||
int dp(float value) { return Math.round(value*context.getResources().getDisplayMetrics().density); }
|
||||
GradientDrawable background(int color,int radius) {
|
||||
GradientDrawable shape=new GradientDrawable();shape.setColor(color);shape.setCornerRadius(dp(radius));return shape;
|
||||
}
|
||||
void card(View view,int radius) { GradientDrawable shape=background(Color.WHITE,radius);shape.setStroke(dp(.5f),LINE);view.setBackground(shape);view.setClipToOutline(true); }
|
||||
FrameLayout shadowCard(View content,int radius) {
|
||||
card(content,radius);
|
||||
FrameLayout wrapper=new FrameLayout(context);
|
||||
wrapper.setClipChildren(false);wrapper.setClipToPadding(false);
|
||||
wrapper.setBackground(new CardShadow(dp(radius),dp(14),dp(5)));
|
||||
wrapper.addView(content,new FrameLayout.LayoutParams(-1,-2));
|
||||
return wrapper;
|
||||
}
|
||||
LinearLayout column() { LinearLayout v=new LinearLayout(context);v.setOrientation(LinearLayout.VERTICAL);return v; }
|
||||
LinearLayout pageColumn(int maxWidth) {
|
||||
LinearLayout v=new LinearLayout(context){
|
||||
@Override protected void onMeasure(int widthSpec,int heightSpec){
|
||||
if(maxWidth>0&&MeasureSpec.getSize(widthSpec)>dp(maxWidth))
|
||||
widthSpec=MeasureSpec.makeMeasureSpec(dp(maxWidth),MeasureSpec.EXACTLY);
|
||||
super.onMeasure(widthSpec,heightSpec);
|
||||
}
|
||||
};
|
||||
v.setOrientation(LinearLayout.VERTICAL);return v;
|
||||
}
|
||||
LinearLayout row() { LinearLayout v=new LinearLayout(context);v.setGravity(Gravity.CENTER_VERTICAL);return v; }
|
||||
TextView text(String title,int size,boolean bold) {
|
||||
TextView v=new TextView(context);v.setText(title);v.setTextSize(size);v.setTextColor(INK);v.setIncludeFontPadding(false);
|
||||
if(bold)v.setTypeface(null,Typeface.BOLD);return v;
|
||||
}
|
||||
TextView action(String title,int color,Runnable click) {
|
||||
TextView v=text(title,16,true);v.setGravity(Gravity.CENTER);v.setTextColor(color);
|
||||
v.setMinHeight(dp(48));v.setClickable(true);v.setFocusable(true);v.setOnClickListener(ignored->click.run());
|
||||
v.setAccessibilityDelegate(new View.AccessibilityDelegate(){@Override public void onInitializeAccessibilityNodeInfo(View host,android.view.accessibility.AccessibilityNodeInfo info){super.onInitializeAccessibilityNodeInfo(host,info);info.setClassName("android.widget.Button");}});
|
||||
return v;
|
||||
}
|
||||
TextView primary(String title,Runnable click) {
|
||||
TextView v=action(title,Color.WHITE,click);
|
||||
GradientDrawable gradient=new GradientDrawable(GradientDrawable.Orientation.TL_BR,new int[]{BLUE,0xFF1F61C7});gradient.setCornerRadius(dp(12));v.setBackground(gradient);return v;
|
||||
}
|
||||
View iconButton(String icon,String label,Runnable click) {
|
||||
FrameLayout box=new FrameLayout(context);box.setBackground(background(Color.WHITE,10));
|
||||
Icon glyph=new Icon(context,icon,INK);FrameLayout.LayoutParams p=new FrameLayout.LayoutParams(dp(22),dp(22),Gravity.CENTER);box.addView(glyph,p);
|
||||
box.setContentDescription(label);box.setClickable(true);box.setFocusable(true);box.setOnClickListener(v->click.run());return box;
|
||||
}
|
||||
View icon(String name,int color) { return new Icon(context,name,color); }
|
||||
void gap(LinearLayout parent,int height){parent.addView(new View(context),new LinearLayout.LayoutParams(1,dp(height)));}
|
||||
void divider(LinearLayout parent){View line=new View(context);line.setBackgroundColor(LINE);parent.addView(line,new LinearLayout.LayoutParams(-1,dp(.5f)));}
|
||||
LinearLayout.LayoutParams size(int width,int height){return new LinearLayout.LayoutParams(width<0?width:dp(width),height<0?height:dp(height));}
|
||||
/** The iOS connection panel uses black at 5.5%, blur 14, y 5, rather than elevation. */
|
||||
private static final class CardShadow extends Drawable {
|
||||
private final Paint bitmapPaint=new Paint(Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG);
|
||||
private final float cornerRadius,blurRadius,offsetY;
|
||||
private final int inset;
|
||||
private Bitmap bitmap;
|
||||
CardShadow(float cornerRadius,float blurRadius,float offsetY) {
|
||||
this.cornerRadius=cornerRadius;this.blurRadius=blurRadius;this.offsetY=offsetY;
|
||||
inset=(int)Math.ceil(blurRadius*2+Math.abs(offsetY));
|
||||
}
|
||||
@Override protected void onBoundsChange(Rect bounds) {
|
||||
bitmap=null;
|
||||
if(bounds.isEmpty())return;
|
||||
// Render once on a bitmap canvas: shadow layers need software rendering on API 26.
|
||||
bitmap=Bitmap.createBitmap(bounds.width()+inset*2,bounds.height()+inset*2,Bitmap.Config.ARGB_8888);
|
||||
bitmap.setDensity(Bitmap.DENSITY_NONE);
|
||||
Paint shadowPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
shadowPaint.setColor(Color.WHITE);
|
||||
shadowPaint.setShadowLayer(blurRadius,0,offsetY,Color.argb(Math.round(255*.055f),0,0,0));
|
||||
new Canvas(bitmap).drawRoundRect(inset,inset,inset+bounds.width(),inset+bounds.height(),cornerRadius,cornerRadius,shadowPaint);
|
||||
}
|
||||
@Override public void draw(Canvas canvas) {
|
||||
if(bitmap!=null)canvas.drawBitmap(bitmap,getBounds().left-inset,getBounds().top-inset,bitmapPaint);
|
||||
}
|
||||
@Override public void setAlpha(int alpha) { bitmapPaint.setAlpha(alpha);invalidateSelf(); }
|
||||
@Override public void setColorFilter(ColorFilter filter) { bitmapPaint.setColorFilter(filter);invalidateSelf(); }
|
||||
@Override public int getOpacity() { return PixelFormat.TRANSLUCENT; }
|
||||
}
|
||||
@android.annotation.SuppressLint("ViewConstructor") // Programmatic icon primitive, not inflated from XML.
|
||||
static final class Icon extends View {
|
||||
private final Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG); private final String name;
|
||||
Icon(Context context,String name,int color){super(context);this.name=name;paint.setColor(color);setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);}
|
||||
@Override protected void onDraw(Canvas c){
|
||||
c.save();c.scale(getWidth()/24f,getHeight()/24f);paint.setStyle(Paint.Style.STROKE);paint.setStrokeWidth(1.7f);paint.setStrokeCap(Paint.Cap.ROUND);paint.setStrokeJoin(Paint.Join.ROUND);
|
||||
switch(name){
|
||||
case "settings":
|
||||
Path gear=new Path();
|
||||
float[] toothAngles={-17,-10,10,17};
|
||||
for(int tooth=0;tooth<8;tooth++){
|
||||
for(int corner=0;corner<4;corner++){
|
||||
double angle=Math.toRadians(tooth*45-90+toothAngles[corner]);
|
||||
float radius=corner==0||corner==3?7.5f:10f;
|
||||
float x=12+radius*(float)Math.cos(angle),y=12+radius*(float)Math.sin(angle);
|
||||
if(tooth==0&&corner==0)gear.moveTo(x,y);else gear.lineTo(x,y);
|
||||
}
|
||||
}
|
||||
gear.close();c.drawPath(gear,paint);c.drawCircle(12,12,3.2f,paint);break;
|
||||
case "envelope":
|
||||
c.drawRoundRect(2,5,22,19,2,2,paint);path(c,3,6,12,13,21,6);break;
|
||||
case "history":
|
||||
c.drawArc(4,4,21,21,215,315,false,paint);path(c,3,4,3,10,9,10);path(c,12,7,12,13,16,15);break;
|
||||
case "back":path(c,15,4,7,12,15,20);break;
|
||||
case "refresh":c.drawArc(4,4,20,20,35,310,false,paint);path(c,20,3,20,9,14,9);break;
|
||||
case "close":path(c,6,6,18,18);path(c,18,6,6,18);break;
|
||||
case "arrow":path(c,4,12,20,12);path(c,14,6,20,12,14,18);break;
|
||||
case "keyboard":
|
||||
c.drawRoundRect(2,5,22,19,3,3,paint);for(int y=9;y<=12;y+=3)for(int x=6;x<=18;x+=4)c.drawPoint(x,y,paint);c.drawLine(7,16,17,16,paint);break;
|
||||
case "display":c.drawRoundRect(2,3,22,17,2,2,paint);path(c,12,17,12,21);path(c,7,21,17,21);break;
|
||||
case "sliders":
|
||||
for(int y=6;y<=18;y+=6){c.drawLine(3,y,21,y,paint);c.drawCircle(y==12?15:8,y,2,paint);}break;
|
||||
case "audio":path(c,3,9,7,9,12,4,12,20,7,15,3,15,3,9);c.drawArc(10,5,21,19,-65,130,false,paint);break;
|
||||
case "mouse":c.drawRoundRect(5,2,19,22,7,7,paint);path(c,12,3,12,10);break;
|
||||
case "folder":path(c,2,19,2,5,9,5,12,8,22,8,22,19,2,19);break;
|
||||
case "chart":path(c,3,3,3,21,22,21);path(c,7,17,7,13);path(c,12,17,12,8);path(c,18,17,18,4);break;
|
||||
case "lock":c.drawRoundRect(5,10,19,22,2,2,paint);c.drawArc(8,2,16,15,180,180,false,paint);c.drawPoint(12,16,paint);break;
|
||||
case "key":
|
||||
paint.setStyle(Paint.Style.FILL);c.drawCircle(7,8,5,paint);paint.setStyle(Paint.Style.STROKE);paint.setStrokeWidth(4);path(c,10,11,19,20);path(c,15,16,18,13);path(c,18,19,21,16);
|
||||
paint.setStyle(Paint.Style.FILL);int keyColor=paint.getColor();paint.setColor(Color.WHITE);c.drawCircle(6,7,1.5f,paint);paint.setColor(keyColor);break;
|
||||
case "unlock":c.drawRoundRect(5,10,19,22,2,2,paint);c.drawArc(8,2,16,15,180,150,false,paint);c.drawPoint(12,16,paint);break;
|
||||
case "clipboard":c.drawRoundRect(4,4,20,22,2,2,paint);c.drawRoundRect(8,2,16,7,2,2,paint);break;
|
||||
case "eye":path(c,2,12,6,7,12,5,18,7,22,12,18,17,12,19,6,17,2,12);c.drawCircle(12,12,3,paint);break;
|
||||
default:c.drawCircle(12,12,9,paint);path(c,12,10,12,17);c.drawPoint(12,6,paint);
|
||||
}c.restore();
|
||||
}
|
||||
private void path(Canvas c,float... values){Path p=new Path();p.moveTo(values[0],values[1]);for(int i=2;i<values.length;i+=2)p.lineTo(values[i],values[i+1]);c.drawPath(p,paint);}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Base64;
|
||||
import android.view.Surface;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import java.io.File;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.security.KeyStore;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
|
||||
final class NativeSession implements AutoCloseable {
|
||||
static { System.loadLibrary("crossdesk_android"); }
|
||||
interface Listener {
|
||||
void status(String message);
|
||||
void connected();
|
||||
void ended(String reason);
|
||||
void data(JSONObject message);
|
||||
void videoSize(int width, int height);
|
||||
void clipboard(String text);
|
||||
void statistics(RemoteNetworkStatistics.Snapshot value);
|
||||
default void fileTransfer(String name,double progress,boolean sending,File received) { }
|
||||
default void controlFeedback(String message) { }
|
||||
default void signaling(int state, String deviceId) { }
|
||||
default void presence(JSONObject message) { }
|
||||
default void announcement(JSONObject message) { }
|
||||
default void announcementFailed(String requestId) { }
|
||||
default void passwordRejected() { ended("远端密码错误"); }
|
||||
}
|
||||
// Serializes all peer creation/API calls/destruction, including across activities.
|
||||
private static final ExecutorService RTC = Executors.newSingleThreadExecutor(r -> new Thread(r, "CrossDesk RTC"));
|
||||
private final Handler main = new Handler(Looper.getMainLooper());
|
||||
private final Context context;
|
||||
private volatile Listener listener;
|
||||
private final SecretStore secrets;
|
||||
private final String host, scope;
|
||||
private volatile String remote;
|
||||
private String password, identity = "";
|
||||
private final int port;
|
||||
private long handle;
|
||||
private boolean signalReady, joining, connected, started;
|
||||
private int signalState;
|
||||
private volatile long signalGeneration;
|
||||
private boolean presenceRequested;
|
||||
private volatile boolean closed;
|
||||
private Surface surface;
|
||||
private volatile AudioPlayer audio;
|
||||
private final SessionDocuments documents;
|
||||
private boolean sendingFile;
|
||||
private final Runnable fileTick=new Runnable(){public void run(){
|
||||
execute(()->{boolean sending=connected&&handle!=0&&nPumpFiles(handle);if(!closed)main.postDelayed(this,sending?10:1000);});
|
||||
}};
|
||||
private final RemoteNetworkStatistics networkStatistics=new RemoteNetworkStatistics();
|
||||
private final Runnable statisticsTick=new Runnable(){public void run(){
|
||||
if(closed)return;
|
||||
listener.statistics(networkStatistics.snapshot(RemoteNetworkStatistics.now()));
|
||||
if(!closed)main.postDelayed(this,1000);
|
||||
}};
|
||||
private final Runnable timeout = () -> fail(remote.isEmpty()
|
||||
? "服务器连接超时,请检查服务器地址和网络"
|
||||
: "连接超时,请检查设备 ID、服务器及远端在线状态");
|
||||
|
||||
NativeSession(Context context, String host, int port, String remote, String password, Listener listener) {
|
||||
this.context = context.getApplicationContext(); this.listener = listener;
|
||||
this.host = host; this.port = port; this.remote = remote; this.password = password;
|
||||
scope = host.toLowerCase(java.util.Locale.ROOT) + ":" + port;
|
||||
secrets = new SecretStore(this.context);
|
||||
documents = new SessionDocuments(this.context);
|
||||
}
|
||||
void start() {
|
||||
if (started || closed) return;
|
||||
started = true;
|
||||
main.postDelayed(timeout, 40000);
|
||||
execute(() -> {
|
||||
try {
|
||||
identity = secrets.get(scope);
|
||||
File certificates = exportTrust();
|
||||
File logs = new File(context.getNoBackupFilesDir(), "logs");
|
||||
if (!logs.isDirectory() && !logs.mkdirs()) throw new IllegalStateException("Log directory unavailable");
|
||||
handle = nCreate(this, host, port, identity, logs.getAbsolutePath(), certificates.getAbsolutePath());
|
||||
if (handle == 0) { fail("原生连接初始化失败"); return; }
|
||||
nFileDirectory(handle,new File(documents.directory,"received").getAbsolutePath());
|
||||
if (surface != null && surface.isValid()) nSurface(handle, surface);
|
||||
} catch (Exception error) { fail("安全存储或证书初始化失败,请重试或清除应用数据"); }
|
||||
});
|
||||
}
|
||||
/** Promote the already registered identity peer to an outgoing desktop session. */
|
||||
void connect(String remoteId, String secret) {
|
||||
execute(() -> {
|
||||
if (joining || connected) return;
|
||||
remote = remoteId;
|
||||
password = secret;
|
||||
// Serialize arming with identity callbacks, which cancel the idle
|
||||
// login timeout. Otherwise a just-completed login can cancel this
|
||||
// outgoing connection's timeout before tryJoin runs.
|
||||
main.removeCallbacks(timeout);
|
||||
main.postDelayed(timeout, 40000);
|
||||
tryJoin();
|
||||
});
|
||||
}
|
||||
boolean isClosed() { return closed; }
|
||||
// UI callbacks run on the main thread. A service-owned state can replace
|
||||
// the Activity listener without recreating either native peer.
|
||||
void setListener(Listener value) { listener = java.util.Objects.requireNonNull(value); }
|
||||
private void publishSignaling() {
|
||||
int state = signalState;
|
||||
// Only expose the public device ID, never the identity's @password suffix.
|
||||
String deviceId = identity.split("@", 2)[0];
|
||||
ui(() -> listener.signaling(state, deviceId));
|
||||
}
|
||||
private File exportTrust() throws Exception {
|
||||
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
factory.init((KeyStore) null);
|
||||
StringBuilder pem = new StringBuilder();
|
||||
for (TrustManager manager : factory.getTrustManagers()) {
|
||||
if (manager instanceof X509TrustManager trust) {
|
||||
for (X509Certificate certificate : trust.getAcceptedIssuers()) {
|
||||
pem.append("-----BEGIN CERTIFICATE-----\n")
|
||||
.append(Base64.encodeToString(certificate.getEncoded(), Base64.NO_WRAP))
|
||||
.append("\n-----END CERTIFICATE-----\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pem.length() == 0) throw new IllegalStateException("Empty Android trust store");
|
||||
File output = new File(context.getNoBackupFilesDir(), "trusted-roots.pem");
|
||||
Files.write(output.toPath(), pem.toString().getBytes(StandardCharsets.US_ASCII));
|
||||
return output;
|
||||
}
|
||||
private void execute(Runnable task) { RTC.execute(() -> { if (!closed) task.run(); }); }
|
||||
private void ui(Runnable task) { main.post(() -> { if (!closed) task.run(); }); }
|
||||
private void fail(String reason) { ui(() -> { listener.ended(reason); close(); }); }
|
||||
private void tryJoin() {
|
||||
if (handle == 0 || joining || remote.isEmpty() || !signalReady || identity.isEmpty()) return;
|
||||
joining = true;
|
||||
String base = identity.split("@", 2)[0];
|
||||
if (!nConnect(handle, base, remote, password)) fail("无法发起远程连接");
|
||||
password = "";
|
||||
}
|
||||
// Called on arbitrary native callback threads; borrowed payloads were copied by JNI.
|
||||
@SuppressWarnings("unused") private void onNativeEvent(int type, byte[] bytes) {
|
||||
execute(() -> {
|
||||
String value = new String(bytes, StandardCharsets.UTF_8);
|
||||
try {
|
||||
if (type == 3) {
|
||||
if (value.contains("@")) {
|
||||
identity = value;
|
||||
secrets.put(scope, identity);
|
||||
} else if (!identity.startsWith(value + "@")) identity = value;
|
||||
publishSignaling(); tryJoin(); return;
|
||||
}
|
||||
if (type == 6) { ui(() -> listener.clipboard(value)); return; }
|
||||
JSONObject event = new JSONObject(value);
|
||||
if (type == 1) {
|
||||
int status = event.getInt("status");
|
||||
if (!event.getBoolean("controller")) {
|
||||
long generation=event.optLong("generation");
|
||||
if(signalGeneration!=generation){signalGeneration=generation;presenceRequested=false;}
|
||||
signalState = status;
|
||||
signalReady = status == 1;
|
||||
if (signalReady && remote.isEmpty()) main.removeCallbacks(timeout);
|
||||
publishSignaling();
|
||||
tryJoin();
|
||||
}
|
||||
if (status == 6) fail("服务器 TLS 证书校验失败");
|
||||
else if (status == 2) fail("服务器登录失败,请检查服务器地址和网络");
|
||||
else if (status >= 3 && connected) fail("信令连接中断,请重新连接");
|
||||
else if (status == 0 || status == 4) ui(() -> listener.status("正在连接信令服务器…"));
|
||||
} else if (type == 2) {
|
||||
int status = event.getInt("status");
|
||||
if (status == 1) {
|
||||
if (connected) return; // Repeated transport readiness is the same desktop session.
|
||||
connected = true; main.removeCallbacks(timeout); nReady(handle);
|
||||
audio = new AudioPlayer();
|
||||
nControl(handle, 2, 1);
|
||||
ui(() -> { listener.connected(); if(!closed){statisticsTick.run();fileTick.run();} });
|
||||
} else if (status == 0 || status == 2) ui(() -> listener.status("正在建立安全连接…"));
|
||||
else if (status == 6) ui(() -> { listener.passwordRejected(); close(); });
|
||||
else {
|
||||
String[] reasons = {"", "", "", "连接已断开", "连接失败", "远端已关闭连接",
|
||||
"远端密码错误", "找不到该设备 ID", "远端当前不可用"};
|
||||
fail(status >= 0 && status < reasons.length ? reasons[status] : "连接已结束");
|
||||
}
|
||||
} else if (type == 4) ui(() -> listener.data(event));
|
||||
else if (type == 5) {
|
||||
int width = event.getInt("width"), height = event.getInt("height");
|
||||
ui(() -> listener.videoSize(width, height));
|
||||
} else if (type == 7) networkStatistics.receive(new RemoteNetworkStatistics.Report(event),RemoteNetworkStatistics.now());
|
||||
else if (type == 8 && signalReady) ui(() -> listener.announcement(event));
|
||||
else if (type == 9 && signalReady && presenceRequested) {
|
||||
long generation=event.optLong("generation");
|
||||
if(generation==signalGeneration)ui(()->{if(generation==signalGeneration)listener.presence(event);});
|
||||
} else if(type==10){
|
||||
String name=event.getString("name"),path=event.optString("path");
|
||||
double progress=event.getDouble("progress");boolean sending=event.getBoolean("sending");
|
||||
ui(()->{if(sending&&(progress<0||progress>=1))sendingFile=false;
|
||||
listener.fileTransfer(name,progress,sending,path.isEmpty()?null:new File(path));});
|
||||
}
|
||||
} catch (Exception error) {
|
||||
if (type == 3) fail("设备身份保存失败,请检查安全存储");
|
||||
}
|
||||
});
|
||||
}
|
||||
@SuppressWarnings("unused") private void onNativeAudio(byte[] pcm) {
|
||||
AudioPlayer player = audio;
|
||||
if (!closed && player != null) player.offer(pcm);
|
||||
}
|
||||
@SuppressWarnings("unused") private void onNativeVideoFrame(long id,double latency,int width,int height){
|
||||
if(!closed)networkStatistics.frame(id,latency,width,height,RemoteNetworkStatistics.now());
|
||||
}
|
||||
void videoSettings(RemoteVideoSettings.Values settings,long requestId){
|
||||
if(!settings.valid()||requestId<0||requestId>0xffffffffL)return;
|
||||
execute(()->{if(connected&&!nVideoSettings(handle,settings.quality,settings.frameRate,settings.preference,requestId))ui(()->listener.data(settings.status(requestId,false)));});
|
||||
}
|
||||
void announcementRequest(JSONObject request,String requestId){
|
||||
byte[] bytes=request.toString().getBytes(StandardCharsets.UTF_8);
|
||||
execute(()->{if(!signalReady||identity.isEmpty()||!nAnnouncementRequest(handle,bytes))ui(()->listener.announcementFailed(requestId));});
|
||||
}
|
||||
void presenceRequest(JSONArray ids){
|
||||
// Own the caller's list before crossing to the serialized RTC executor.
|
||||
String devices=ids.toString();
|
||||
execute(()->{
|
||||
if(!signalReady||identity.isEmpty())return;
|
||||
try{
|
||||
JSONObject request=new JSONObject().put("type","recent_connections_presence")
|
||||
.put("user_id",identity.split("@",2)[0]).put("devices",new JSONArray(devices)).put("subscribe",true);
|
||||
if(nPresenceRequest(handle,request.toString().getBytes(StandardCharsets.UTF_8)))presenceRequested=true;
|
||||
}catch(org.json.JSONException ignored){ }
|
||||
});
|
||||
}
|
||||
void surface(Surface value) { execute(() -> { surface = value; if (handle != 0) nSurface(handle, value); }); }
|
||||
void pointer(float x, float y, int flag, int wheel) { execute(() -> { if (connected) nPointer(handle, x, y, flag, wheel); }); }
|
||||
void key(int code, boolean down) { execute(() -> { if (connected) nKey(handle, code, down); }); }
|
||||
void control(int type, int value) {
|
||||
AudioPlayer player = audio;
|
||||
if (type == 2 && player != null) player.setEnabled(value != 0);
|
||||
execute(() -> { if (connected){nControl(handle, type, value);if(type==4)networkStatistics.resetVideo();} });
|
||||
}
|
||||
void clipboard(String value) {
|
||||
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
|
||||
if (bytes.length == 0 || bytes.length > 128 * 1024) return;
|
||||
execute(() -> { if (connected) nClipboard(handle, bytes); });
|
||||
}
|
||||
void secureAttention(){execute(()->{
|
||||
boolean sent=connected&&nSecureAttention(handle);
|
||||
ui(()->listener.controlFeedback(sent?"已发送 Ctrl+Alt+Del":"指令发送失败,请重试"));
|
||||
});}
|
||||
void sendFile(android.net.Uri uri){
|
||||
if(closed)return;
|
||||
if(sendingFile){listener.controlFeedback("请等待当前文件发送完成");return;}
|
||||
sendingFile=true;listener.fileTransfer("正在读取所选文件…",0,true,null);
|
||||
documents.prepare(uri,new SessionDocuments.Prepared(){
|
||||
public void ready(File file,String name){execute(()->{
|
||||
if(!connected||!nSendFile(handle,file.getAbsolutePath(),name.getBytes(StandardCharsets.UTF_8))){
|
||||
file.delete();ui(()->{sendingFile=false;listener.fileTransfer(name,-1,true,null);});
|
||||
}
|
||||
});}
|
||||
public void failed(){ui(()->{sendingFile=false;listener.fileTransfer("所选文件(无法读取或空间不足)",-1,true,null);});}
|
||||
});
|
||||
}
|
||||
void saveFile(File file,android.net.Uri destination){
|
||||
if(closed)return;
|
||||
documents.save(file,destination,success->ui(()->listener.controlFeedback(success?"文件已保存":"文件保存失败,请重试")));
|
||||
}
|
||||
@Override public void close() {
|
||||
if (closed) return;
|
||||
closed = true; main.removeCallbacks(timeout);main.removeCallbacks(statisticsTick);main.removeCallbacks(fileTick);
|
||||
RTC.execute(() -> {
|
||||
main.removeCallbacks(timeout);
|
||||
if (audio != null) { audio.close(); audio = null; }
|
||||
password = "";
|
||||
if (handle != 0) { nDestroy(handle); handle = 0; }
|
||||
documents.close();
|
||||
surface = null;
|
||||
});
|
||||
}
|
||||
static native boolean nValidAppVersion(String version);
|
||||
static native boolean nHasAppUpdate(String version, byte[] releaseJson);
|
||||
static native String nCheckMobileUpdate(String version, byte[] releaseJson);
|
||||
private static native long nCreate(NativeSession owner, String host, int port, String identity, String logs, String roots);
|
||||
private static native boolean nConnect(long handle, String identity, String remote, String password);
|
||||
private static native void nReady(long handle);
|
||||
private static native void nPointer(long handle, float x, float y, int flag, int wheel);
|
||||
private static native void nKey(long handle, int code, boolean down);
|
||||
private static native void nControl(long handle, int type, int value);
|
||||
private static native boolean nVideoSettings(long handle,int quality,int frameRate,int preference,long requestId);
|
||||
private static native boolean nAnnouncementRequest(long handle,byte[] data);
|
||||
private static native boolean nPresenceRequest(long handle,byte[] data);
|
||||
private static native void nClipboard(long handle, byte[] data);
|
||||
private static native boolean nSecureAttention(long handle);
|
||||
private static native void nFileDirectory(long handle,String directory);
|
||||
private static native boolean nSendFile(long handle,String path,byte[] name);
|
||||
private static native boolean nPumpFiles(long handle);
|
||||
private static native void nSurface(long handle, Surface surface);
|
||||
private static native void nDestroy(long handle);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorListenerAdapter;
|
||||
import android.animation.ValueAnimator;
|
||||
import android.content.Context;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewTreeObserver;
|
||||
import android.view.animation.PathInterpolator;
|
||||
import android.widget.FrameLayout;
|
||||
|
||||
/** Retains only the current page and, during a transition, the outgoing page. */
|
||||
final class PageHost extends FrameLayout {
|
||||
enum Motion { NONE, PUSH, POP, SESSION_IN, SESSION_OUT }
|
||||
|
||||
private FrameLayout current, outgoing;
|
||||
private Motion motion=Motion.NONE;
|
||||
private ValueAnimator animator;
|
||||
private ViewTreeObserver pendingObserver;
|
||||
private ViewTreeObserver.OnPreDrawListener pendingStart;
|
||||
private int accessibility, focusability;
|
||||
private float distance;
|
||||
private long generation;
|
||||
|
||||
PageHost(Context context){super(context);setBackgroundColor(MobileUi.BACKGROUND);}
|
||||
|
||||
void show(FrameLayout page,Motion requested){
|
||||
finish();
|
||||
FrameLayout previous=current;current=page;
|
||||
if(previous==null||requested==Motion.NONE||!ValueAnimator.areAnimatorsEnabled()||!isAttachedToWindow()){
|
||||
removeAllViews();addView(page,new LayoutParams(-1,-1));page.requestApplyInsets();return;
|
||||
}
|
||||
outgoing=previous;motion=requested;
|
||||
accessibility=page.getImportantForAccessibility();
|
||||
focusability=page.getDescendantFocusability();
|
||||
previous.clearFocus();previous.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
|
||||
page.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
|
||||
page.setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS);
|
||||
boolean underneath=motion==Motion.POP||motion==Motion.SESSION_IN;
|
||||
addView(page,underneath?0:getChildCount(),new LayoutParams(-1,-1));
|
||||
// SurfaceView pages stay opaque and unlayered. Fade the ordinary UI above them.
|
||||
if(motion==Motion.PUSH||motion==Motion.POP){
|
||||
previous.setLayerType(LAYER_TYPE_HARDWARE,null);page.setLayerType(LAYER_TYPE_HARDWARE,null);
|
||||
(motion==Motion.PUSH?page:previous).setElevation(8*getResources().getDisplayMetrics().density);
|
||||
}else (motion==Motion.SESSION_IN?previous:page).setLayerType(LAYER_TYPE_HARDWARE,null);
|
||||
distance=getWidth()*(getLayoutDirection()==LAYOUT_DIRECTION_RTL?-1:1);
|
||||
progress(0);page.requestApplyInsets();
|
||||
// Wait for content and insets, so the first drawn frame already has the right position.
|
||||
long transition=generation;
|
||||
pendingObserver=getViewTreeObserver();
|
||||
pendingStart=()->{
|
||||
if(transition!=generation||outgoing==null)return true;
|
||||
clearPendingStart();distance=getWidth()*(getLayoutDirection()==LAYOUT_DIRECTION_RTL?-1:1);progress(0);
|
||||
ValueAnimator next=ValueAnimator.ofFloat(0,1);animator=next;
|
||||
boolean session=motion==Motion.SESSION_IN||motion==Motion.SESSION_OUT;
|
||||
next.setDuration(session?200:350);
|
||||
next.setInterpolator(session?new PathInterpolator(.42f,0,.58f,1):new PathInterpolator(.25f,.1f,.25f,1));
|
||||
next.addUpdateListener(value->{if(animator==value)progress((float)value.getAnimatedValue());});
|
||||
next.addListener(new AnimatorListenerAdapter(){@Override public void onAnimationEnd(Animator value){if(animator==value)finish();}});
|
||||
next.start();return true;
|
||||
};
|
||||
pendingObserver.addOnPreDrawListener(pendingStart);
|
||||
}
|
||||
|
||||
private void progress(float value){
|
||||
switch(motion){
|
||||
case PUSH -> {current.setTranslationX(distance*(1-value));outgoing.setTranslationX(-distance*.3f*value);}
|
||||
case POP -> {current.setTranslationX(-distance*.3f*(1-value));outgoing.setTranslationX(distance*value);}
|
||||
case SESSION_IN -> outgoing.setAlpha(1-value);
|
||||
case SESSION_OUT -> current.setAlpha(value);
|
||||
default -> {}
|
||||
}
|
||||
}
|
||||
|
||||
void finish(){
|
||||
generation++;
|
||||
clearPendingStart();
|
||||
ValueAnimator running=animator;animator=null;if(running!=null)running.cancel();
|
||||
if(outgoing==null)return;
|
||||
reset(outgoing);removeView(outgoing);outgoing=null;
|
||||
reset(current);current.setImportantForAccessibility(accessibility);
|
||||
current.setDescendantFocusability(focusability);motion=Motion.NONE;
|
||||
}
|
||||
private void clearPendingStart(){
|
||||
if(pendingObserver!=null&&pendingObserver.isAlive()&&pendingStart!=null)pendingObserver.removeOnPreDrawListener(pendingStart);
|
||||
pendingObserver=null;pendingStart=null;
|
||||
}
|
||||
private static void reset(View page){page.setTranslationX(0);page.setAlpha(1);page.setElevation(0);page.setLayerType(LAYER_TYPE_NONE,null);}
|
||||
@Override public boolean onInterceptTouchEvent(MotionEvent event){return outgoing!=null||super.onInterceptTouchEvent(event);}
|
||||
@android.annotation.SuppressLint("ClickableViewAccessibility") // A temporary input shield; the pages own all click actions.
|
||||
@Override public boolean onTouchEvent(MotionEvent event){return outgoing!=null||super.onTouchEvent(event);}
|
||||
@Override protected void onSizeChanged(int w,int h,int oldw,int oldh){super.onSizeChanged(w,h,oldw,oldh);if(oldw>0&&oldh>0&&(w!=oldw||h!=oldh))finish();}
|
||||
@Override protected void onDetachedFromWindow(){finish();super.onDetachedFromWindow();}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.Dialog;
|
||||
import android.view.Gravity;
|
||||
import android.view.Window;
|
||||
import android.widget.CheckBox;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.TextView;
|
||||
|
||||
import static cn.crossdesk.mobile.MobileUi.*;
|
||||
|
||||
/** Explicit agreement is required; refusal dismisses only the current visit. */
|
||||
final class PrivacyConsentDialog extends Dialog {
|
||||
private final Activity activity;
|
||||
private final MobileUi ui;
|
||||
PrivacyConsentDialog(Activity activity,MobileUi ui,Runnable accepted){
|
||||
this(activity,ui,new PrivacyPolicyDocument(activity),accepted);
|
||||
}
|
||||
PrivacyConsentDialog(Activity activity,MobileUi ui,PrivacyPolicyDocument policy,Runnable accepted){
|
||||
super(activity);this.activity=activity;this.ui=ui;requestWindowFeature(Window.FEATURE_NO_TITLE);setCancelable(false);setCanceledOnTouchOutside(false);
|
||||
LinearLayout sheet=ui.column();sheet.setBackground(ui.background(android.graphics.Color.WHITE,20));sheet.setClipToOutline(true);
|
||||
TextView title=ui.text("隐私政策",17,true);title.setGravity(Gravity.CENTER);sheet.addView(title,ui.size(-1,56));ui.divider(sheet);
|
||||
sheet.addView(policy.view(ui),new LinearLayout.LayoutParams(-1,0,1));ui.divider(sheet);
|
||||
LinearLayout actions=ui.column();actions.setPadding(ui.dp(20),ui.dp(12),ui.dp(20),ui.dp(12));sheet.addView(actions);
|
||||
CheckBox hasReadPolicy=new CheckBox(activity);hasReadPolicy.setText("我已阅读并同意《隐私政策》");hasReadPolicy.setTextColor(INK);hasReadPolicy.setTextSize(14);hasReadPolicy.setMinHeight(ui.dp(44));actions.addView(hasReadPolicy,ui.size(-1,-2));ui.gap(actions,12);
|
||||
TextView agree=ui.primary("同意并继续",()->{
|
||||
if(!hasReadPolicy.isChecked()||!policy.available)return;
|
||||
dismiss();accepted.run();
|
||||
});agree.setEnabled(false);agree.setAlpha(.45f);actions.addView(agree,ui.size(-1,48));
|
||||
hasReadPolicy.setOnCheckedChangeListener((button,checked)->{boolean enabled=checked&&policy.available;agree.setEnabled(enabled);agree.setAlpha(enabled?1:.45f);});
|
||||
ui.gap(actions,12);actions.addView(ui.action("暂不同意",SECONDARY,this::dismiss),ui.size(-1,44));
|
||||
setContentView(sheet);Window window=getWindow();if(window!=null){window.setBackgroundDrawableResource(android.R.color.transparent);window.setDimAmount(.22f);}
|
||||
}
|
||||
@Override public void show(){
|
||||
super.show();updateSize();
|
||||
}
|
||||
void updateSize(){
|
||||
android.content.res.Configuration configuration=activity.getResources().getConfiguration();
|
||||
boolean wide=configuration.screenWidthDp>=600;
|
||||
Window window=getWindow();if(window!=null){
|
||||
window.setLayout(wide?ui.dp(Math.min(640,configuration.screenWidthDp-48)):-1,
|
||||
Math.min(ui.dp(760),Math.round(ui.dp(configuration.screenHeightDp)*.9f)));
|
||||
window.setGravity(wide?Gravity.CENTER:Gravity.BOTTOM);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.Context;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ScrollView;
|
||||
import android.widget.TextView;
|
||||
import java.io.IOException;
|
||||
|
||||
import static cn.crossdesk.mobile.MobileUi.*;
|
||||
|
||||
/** The same bundled policy as iOS, readable before any network consent. */
|
||||
final class PrivacyPolicyDocument {
|
||||
final boolean available;
|
||||
final String text;
|
||||
|
||||
PrivacyPolicyDocument(Context context){this(load(context));}
|
||||
PrivacyPolicyDocument(String document){
|
||||
available=document!=null&&!document.trim().isEmpty();
|
||||
String value=available?document:"隐私政策暂时无法读取,请拒绝联网并重新安装应用。";
|
||||
int start=value.indexOf("## 中文\n"),end=start<0?-1:value.indexOf("## English",start);
|
||||
text=start>=0&&end>start?value.substring(start+"## 中文\n".length(),end).trim():value;
|
||||
}
|
||||
private static String load(Context context){
|
||||
try{return LicenseCatalog.read(context,"PRIVACY.md");}catch(IOException error){return null;}
|
||||
}
|
||||
ScrollView view(MobileUi ui){
|
||||
ScrollView scroll=new ScrollView(ui.context);scroll.setBackgroundColor(android.graphics.Color.WHITE);
|
||||
LinearLayout content=ui.column();content.setPadding(ui.dp(20),ui.dp(20),ui.dp(20),ui.dp(20));scroll.addView(content);
|
||||
for(String paragraph:text.split("\n\n")){
|
||||
paragraph=paragraph.trim();if(paragraph.isEmpty()||paragraph.equals("---"))continue;
|
||||
boolean heading=paragraph.startsWith("#"),date=paragraph.startsWith("更新日期:");
|
||||
String value=heading?paragraph.replaceFirst("^#+\\s*",""):paragraph.replace("**","");
|
||||
TextView label=ui.text(value,date?12:16,heading);label.setTextIsSelectable(true);label.setLineSpacing(ui.dp(4),1);
|
||||
if(date)label.setTextColor(SECONDARY);
|
||||
LinearLayout.LayoutParams spacing=new LinearLayout.LayoutParams(-1,-2);spacing.bottomMargin=ui.dp(14);content.addView(label,spacing);
|
||||
}
|
||||
return scroll;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Main-thread presence cache, with the same refresh and expiry intervals as iOS. */
|
||||
final class RecentConnectionPresence {
|
||||
private static final long REFRESH_INTERVAL=30_000, MAX_AGE=60_000;
|
||||
private final Set<String> watched=new LinkedHashSet<>();
|
||||
private final Map<String,Boolean> online=new HashMap<>();
|
||||
private final Map<String,Long> updatedAt=new HashMap<>();
|
||||
private boolean connected,awaitingSnapshot=true;
|
||||
private long lastRefresh;
|
||||
Consumer<JSONArray> sender=ids->{};
|
||||
Runnable changed=()->{};
|
||||
|
||||
void watch(JSONArray records,long now){
|
||||
Set<String> next=new LinkedHashSet<>();
|
||||
for(int i=0;i<records.length();i++){
|
||||
JSONObject record=records.optJSONObject(i);
|
||||
if(record!=null&&!record.optString("id").isEmpty())next.add(record.optString("id"));
|
||||
}
|
||||
if(watched.equals(next))return;
|
||||
watched.clear();watched.addAll(next);
|
||||
online.keySet().retainAll(watched);updatedAt.keySet().retainAll(watched);
|
||||
refresh(now);changed.run();
|
||||
}
|
||||
void setConnected(boolean value,long now){
|
||||
if(connected==value)return;
|
||||
connected=value;online.clear();updatedAt.clear();awaitingSnapshot=true;
|
||||
refresh(now);changed.run();
|
||||
}
|
||||
boolean isConnected(){return connected;}
|
||||
boolean isOnline(String id,long now){
|
||||
Long time=updatedAt.get(id);
|
||||
return connected&&!awaitingSnapshot&&Boolean.TRUE.equals(online.get(id))&&time!=null&&now-time<MAX_AGE;
|
||||
}
|
||||
void receive(JSONObject message,long now){
|
||||
if(!connected)return;
|
||||
boolean snapshot="presence".equals(message.optString("type"));
|
||||
Map<String,Boolean> values=new HashMap<>();
|
||||
if(snapshot){
|
||||
JSONArray devices=message.optJSONArray("devices");if(devices==null)return;
|
||||
for(int i=0;i<devices.length();i++){JSONObject device=devices.optJSONObject(i);if(device!=null)read(device,values);}
|
||||
}else{
|
||||
if(!"presence_update".equals(message.optString("type"))||awaitingSnapshot)return;
|
||||
read(message,values);
|
||||
}
|
||||
Map<String,Boolean> previous=new HashMap<>(online);
|
||||
if(snapshot){online.clear();updatedAt.clear();awaitingSnapshot=false;}
|
||||
for(var entry:values.entrySet()){online.put(entry.getKey(),entry.getValue());updatedAt.put(entry.getKey(),now);}
|
||||
if(!previous.equals(online))changed.run();
|
||||
}
|
||||
private void read(JSONObject device,Map<String,Boolean> values){
|
||||
Object id=device.opt("id"),value=device.opt("online");
|
||||
if(id instanceof String&&watched.contains(id)&&value instanceof Boolean)values.put((String)id,(Boolean)value);
|
||||
}
|
||||
private void refresh(long now){
|
||||
if(!connected)return;
|
||||
lastRefresh=now;JSONArray ids=new JSONArray();for(String id:watched)ids.put(id);sender.accept(ids);
|
||||
}
|
||||
void maintain(long now){
|
||||
if(!connected)return;
|
||||
boolean expired=updatedAt.entrySet().removeIf(entry->{
|
||||
if(now-entry.getValue()<MAX_AGE)return false;
|
||||
online.remove(entry.getKey());return true;
|
||||
});
|
||||
if(expired)changed.run();
|
||||
if(now-lastRefresh>=REFRESH_INTERVAL)refresh(now);
|
||||
}
|
||||
JSONArray ordered(JSONArray records,long now){
|
||||
JSONArray result=new JSONArray();
|
||||
// Preserve history order within each group, including when all devices are offline.
|
||||
for(boolean available:new boolean[]{true,false})for(int i=0;i<records.length();i++){
|
||||
JSONObject record=records.optJSONObject(i);
|
||||
if(record!=null&&isOnline(record.optString("id"),now)==available)result.put(record);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
/** History and encrypted passwords are isolated by server; history never contains secrets. */
|
||||
final class RecentConnections {
|
||||
private final SharedPreferences preferences;
|
||||
private final SecretStore secrets;
|
||||
private final Context context;
|
||||
RecentConnections(Context context){this.context=context.getApplicationContext();preferences=context.getSharedPreferences("settings",Context.MODE_PRIVATE);secrets=new SecretStore(context);}
|
||||
private String key(String server){return "recentList:"+server;}
|
||||
private String credential(String server,String id){return "remote-password:"+server+":"+id;}
|
||||
JSONArray list(String server){
|
||||
try {
|
||||
if(!preferences.contains(key(server))){
|
||||
String legacy=preferences.getString("recent:"+server,"");
|
||||
if(!legacy.isEmpty())return new JSONArray().put(new JSONObject().put("id",legacy).put("name",legacy));
|
||||
}
|
||||
return new JSONArray(preferences.getString(key(server),"[]"));
|
||||
}
|
||||
catch(org.json.JSONException error){return new JSONArray();}
|
||||
}
|
||||
boolean remembersPassword(String server,String id){
|
||||
JSONArray records=list(server);
|
||||
for(int i=0;i<records.length();i++){JSONObject item=records.optJSONObject(i);if(item!=null&&id.equals(item.optString("id")))return item.optBoolean("remember");}
|
||||
return false;
|
||||
}
|
||||
String password(String server,String id)throws Exception{return secrets.get(credential(server,id));}
|
||||
boolean contains(String server,String id){JSONArray all=list(server);for(int i=0;i<all.length();i++){JSONObject item=all.optJSONObject(i);if(item!=null&&id.equals(item.optString("id")))return true;}return false;}
|
||||
void save(String server,String id,String name,String platform,boolean remember,String password)throws Exception{
|
||||
if(remember&&password.isEmpty())throw new IllegalArgumentException("Cannot remember an empty password");
|
||||
if(remember)secrets.put(credential(server,id),password);else secrets.remove(credential(server,id));
|
||||
JSONObject item=new JSONObject().put("id",id).put("name",name.isEmpty()?id:name).put("platform",platform).put("remember",remember);
|
||||
JSONArray result=new JSONArray().put(item),old=list(server);
|
||||
for(int i=0;i<old.length();i++){JSONObject entry=old.optJSONObject(i);if(entry!=null&&!id.equals(entry.optString("id"))){if(result.length()<20)result.put(entry);else RemotePreviewStore.get(context).remove(server,entry.optString("id"));}}
|
||||
preferences.edit().putString(key(server),result.toString()).apply();
|
||||
}
|
||||
void metadata(String server,String id,String name,String platform){
|
||||
JSONArray all=list(server);
|
||||
try{for(int i=0;i<all.length();i++){JSONObject item=all.optJSONObject(i);if(item!=null&&id.equals(item.optString("id"))){item.put("name",name.isEmpty()?id:name);item.put("platform",platform);}}}
|
||||
catch(org.json.JSONException ignored){return;}
|
||||
preferences.edit().putString(key(server),all.toString()).apply();
|
||||
}
|
||||
void delete(String server,String id){
|
||||
JSONArray result=new JSONArray(),old=list(server);for(int i=0;i<old.length();i++){JSONObject entry=old.optJSONObject(i);if(entry!=null&&!id.equals(entry.optString("id")))result.put(entry);}
|
||||
preferences.edit().putString(key(server),result.toString()).apply();secrets.remove(credential(server,id));
|
||||
RemotePreviewStore.get(context).remove(server,id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
/** Shared button ownership and cursor position for the video surface and mouse bar. */
|
||||
final class RemoteMouseInput {
|
||||
interface Sender { void send(float x, float y, int flag, int wheel); }
|
||||
private final Sender sender;
|
||||
private float x = .5f, y = .5f;
|
||||
private boolean gestureLeft, virtualLeft, virtualRight;
|
||||
private long revision;
|
||||
Runnable didCancel;
|
||||
float viewportWidth, viewportHeight;
|
||||
|
||||
RemoteMouseInput(Sender sender) { this.sender = sender; }
|
||||
boolean hasVirtualButton() { return virtualLeft || virtualRight; }
|
||||
long revision() { return revision; }
|
||||
void move(float x, float y) {
|
||||
this.x = Math.max(0, Math.min(1, x)); this.y = Math.max(0, Math.min(1, y));
|
||||
send(0, 0);
|
||||
}
|
||||
void drag(float dx, float dy) {
|
||||
if (!hasVirtualButton() || viewportWidth <= 0 || viewportHeight <= 0) return;
|
||||
move(x + dx / viewportWidth, y + dy / viewportHeight);
|
||||
}
|
||||
void gestureLeft(boolean down) {
|
||||
if (down && hasVirtualButton()) return;
|
||||
if (gestureLeft == down) return;
|
||||
gestureLeft = down;
|
||||
send(down ? 1 : 2, 0);
|
||||
}
|
||||
void click(int down, int up) {
|
||||
if (hasVirtualButton()) return;
|
||||
send(down, 0); send(up, 0);
|
||||
}
|
||||
void virtualButton(boolean left, boolean down) {
|
||||
if ((left ? virtualLeft : virtualRight) == down) return;
|
||||
if (down) {
|
||||
gestureLeft(false);
|
||||
revision++;
|
||||
}
|
||||
if (left) virtualLeft = down; else virtualRight = down;
|
||||
send(left ? (down ? 1 : 2) : (down ? 3 : 4), 0);
|
||||
}
|
||||
void scroll(int direction) {
|
||||
if (direction != 0) send(7, direction > 0 ? 1 : -1);
|
||||
}
|
||||
void releaseAll() {
|
||||
gestureLeft(false);
|
||||
virtualButton(true, false);
|
||||
virtualButton(false, false);
|
||||
revision++;
|
||||
if (didCancel != null) didCancel.run();
|
||||
}
|
||||
private void send(int flag, int wheel) { sender.send(x, y, flag, wheel); }
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import org.json.JSONObject;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Monotonic, thread-safe measurements; the UI samples these once a second, as on iOS. */
|
||||
final class RemoteNetworkStatistics {
|
||||
static final class Traffic {
|
||||
final long inbound,outbound;final double loss;
|
||||
Traffic(JSONObject json){inbound=json.optLong("inbound",-1);outbound=json.optLong("outbound",-1);loss=json.optDouble("loss",Double.NaN);}
|
||||
}
|
||||
static final class Report {
|
||||
final Traffic[] traffic=new Traffic[4];final int mode;final boolean srtp;final double rtt;
|
||||
Report(JSONObject json){
|
||||
String[] keys={"video","audio","data","total"};
|
||||
for(int i=0;i<keys.length;i++){JSONObject item=json.optJSONObject(keys[i]);traffic[i]=item==null?null:new Traffic(item);}
|
||||
mode=json.optInt("mode",2);srtp=json.optBoolean("srtp");rtt=json.optDouble("rtt",Double.NaN);
|
||||
}
|
||||
}
|
||||
static final class Snapshot {
|
||||
final Report report;final int fps,width,height;final double latency,rtt;
|
||||
Snapshot(Report report,int fps,int width,int height,double latency,double rtt){this.report=report;this.fps=fps;this.width=width;this.height=height;this.latency=latency;this.rtt=rtt;}
|
||||
String mode(){return report==null?"—":report.mode==0?"P2P 直连":report.mode==1?"TURN 中继":"—";}
|
||||
String resolution(){return width>0&&height>0?width+" × "+height:"—";}
|
||||
String summary(){
|
||||
String value=mode()+(width>0&&height>0?" · "+width+"×"+height:"")+" · "+bitrate(report==null||report.traffic[3]==null?-1:report.traffic[3].inbound);
|
||||
if(report!=null&&report.traffic[0]!=null&&report.traffic[0].loss>0)value+=" · 丢包 "+loss(report.traffic[0].loss);return value;
|
||||
}
|
||||
}
|
||||
private static final class Frame {
|
||||
final double time,latency;Frame(double time,double latency){this.time=time;this.latency=latency;}
|
||||
}
|
||||
private Report report;
|
||||
private double reportTime,rttTime,averageRtt=Double.NaN;
|
||||
private long lastFrameId;
|
||||
private int width,height;
|
||||
private final ArrayDeque<Frame> frames=new ArrayDeque<>();
|
||||
static double now(){return System.nanoTime()/1_000_000_000.0;}
|
||||
synchronized void receive(Report value,double now){
|
||||
report=value;reportTime=now;
|
||||
if(!Double.isFinite(value.rtt)||value.rtt<0||value.rtt>2000)return;
|
||||
averageRtt=Double.isFinite(averageRtt)&&now-rttTime<3?averageRtt+.25*(value.rtt-averageRtt):value.rtt;rttTime=now;
|
||||
}
|
||||
synchronized void frame(long id,double latency,int width,int height,double now){
|
||||
if(id<=lastFrameId||width<=0||height<=0)return;lastFrameId=id;this.width=width;this.height=height;
|
||||
// Native code validates clock calibration before adding local decode/render waits.
|
||||
// A valid but slow frame must not disappear just because its delay exceeds 5 s.
|
||||
prune(now);frames.addLast(new Frame(now,Double.isFinite(latency)&&latency>=0?latency:Double.NaN));
|
||||
while(frames.size()>240)frames.removeFirst();
|
||||
}
|
||||
synchronized void resetVideo(){frames.clear();width=height=0;}
|
||||
synchronized Snapshot snapshot(double now){
|
||||
prune(now);double total=0;int count=0;
|
||||
for(Frame frame:frames)if(Double.isFinite(frame.latency)){total+=frame.latency;count++;}
|
||||
return new Snapshot(now-reportTime<3?report:null,frames.size(),width,height,count==0?Double.NaN:total/count,now-rttTime<3?averageRtt:Double.NaN);
|
||||
}
|
||||
private void prune(double now){while(!frames.isEmpty()&&now-frames.peekFirst().time>=1)frames.removeFirst();}
|
||||
static String bitrate(long value){return value<0?"—":value>=1_000_000?String.format(Locale.ROOT,"%.1f Mbps",value/1_000_000.0):value>=1000?String.format(Locale.ROOT,"%.0f Kbps",value/1000.0):value+" bps";}
|
||||
static String loss(double value){return Double.isFinite(value)&&value>=0?String.format(Locale.ROOT,"%.1f%%",value*100):"—";}
|
||||
static String latency(double value){return !Double.isFinite(value)||value<0?"—":value<1?"<1 ms":String.format(Locale.ROOT,"%.0f ms",value);}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.app.PictureInPictureParams;
|
||||
import android.graphics.Rect;
|
||||
import android.os.Build;
|
||||
import android.util.Rational;
|
||||
|
||||
/** Builds platform PiP parameters only for a live, visible desktop video. */
|
||||
final class RemotePictureInPicture {
|
||||
private boolean connected, choosingDocument;
|
||||
private int width, height;
|
||||
|
||||
void connected() { connected = true; }
|
||||
void videoSize(int width, int height) { this.width = width; this.height = height; }
|
||||
void choosingDocument(boolean value) { choosingDocument = value; }
|
||||
void clearVideo() { width = height = 0; }
|
||||
void disconnect() { connected = choosingDocument = false; clearVideo(); }
|
||||
|
||||
boolean canEnter() { return connected && !choosingDocument && width > 0 && height > 0; }
|
||||
|
||||
PictureInPictureParams parameters(Rect source) {
|
||||
PictureInPictureParams.Builder builder = new PictureInPictureParams.Builder()
|
||||
.setAspectRatio(aspectRatio(width, height));
|
||||
if (source != null && !source.isEmpty()) builder.setSourceRectHint(source);
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
builder.setAutoEnterEnabled(canEnter()).setSeamlessResizeEnabled(true);
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
static Rational aspectRatio(int width, int height) {
|
||||
if (width <= 0 || height <= 0) return new Rational(16, 9);
|
||||
// Android's standard PiP accepts only 1/2.39 through 2.39. Keep
|
||||
// ultrawide and portrait desktops valid, with letterboxing in the view.
|
||||
if ((long) width * 100 > (long) height * 239) return new Rational(239, 100);
|
||||
if ((long) height * 100 > (long) width * 239) return new Rational(100, 239);
|
||||
return new Rational(width, height);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.AtomicFile;
|
||||
import org.json.JSONArray;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Process-wide, serialized preview I/O. Clears invalidate even captures not yet queued for saving. */
|
||||
final class RemotePreviewStore {
|
||||
static final String OPTION="saveRemotePreviews";
|
||||
static final int WIDTH=640,HEIGHT=360;
|
||||
private static RemotePreviewStore instance;
|
||||
static synchronized RemotePreviewStore get(Context context){
|
||||
if(instance==null){
|
||||
Context app=context.getApplicationContext();
|
||||
instance=new RemotePreviewStore(new File(app.getNoBackupFilesDir(),"RecentConnectionThumbnails"),
|
||||
app.getSharedPreferences("settings",Context.MODE_PRIVATE),app.getSharedPreferences("remote-previews",Context.MODE_PRIVATE));
|
||||
instance.enforceConsent();
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
static final class Capture {
|
||||
final String key;final long generation,version;
|
||||
private Capture(String key,long generation,long version){this.key=key;this.generation=generation;this.version=version;}
|
||||
}
|
||||
final File directory;
|
||||
final ExecutorService io=Executors.newSingleThreadExecutor(r->new Thread(r,"CrossDesk previews"));
|
||||
private final Handler main=new Handler(Looper.getMainLooper());
|
||||
private final SharedPreferences options,index;
|
||||
private final Set<String> files=new HashSet<>();
|
||||
private final Map<String,Long> versions=new HashMap<>();
|
||||
private final Set<Runnable> listeners=new CopyOnWriteArraySet<>();
|
||||
private long generation;
|
||||
volatile boolean cleaning;
|
||||
volatile String cleanupError="";
|
||||
RemotePreviewStore(File directory,SharedPreferences options,SharedPreferences index){
|
||||
this.directory=directory;this.options=options;this.index=index;
|
||||
for(String key:index.getStringSet("files",Collections.emptySet()))if(key.matches("[a-f0-9]{64}"))files.add(key);
|
||||
}
|
||||
boolean enabled(){return options.getBoolean("networkConsent",false)&&options.getBoolean(OPTION,false);}
|
||||
void addListener(Runnable listener){listeners.add(listener);}
|
||||
void removeListener(Runnable listener){listeners.remove(listener);}
|
||||
private void changed(){main.post(()->{for(Runnable listener:listeners)listener.run();});}
|
||||
synchronized void enforceConsent(){
|
||||
if(!options.getBoolean("networkConsent",false))options.edit().putBoolean(OPTION,false).apply();
|
||||
if(!enabled()&&!cleaning)clear();
|
||||
}
|
||||
void setEnabled(boolean enabled){
|
||||
options.edit().putBoolean(OPTION,enabled&&options.getBoolean("networkConsent",false)).apply();
|
||||
if(!enabled())clear();else changed();
|
||||
}
|
||||
synchronized Capture begin(String server,String id){
|
||||
if(!enabled()||cleaning||id.isEmpty())return null;
|
||||
String key=key(server,id);long version=versions.getOrDefault(key,0L)+1;versions.put(key,version);
|
||||
return new Capture(key,generation,version);
|
||||
}
|
||||
synchronized boolean current(Capture capture){
|
||||
return capture!=null&&enabled()&&!cleaning&&capture.generation==generation&&
|
||||
capture.version==versions.getOrDefault(capture.key,0L);
|
||||
}
|
||||
/** Takes ownership of the small bitmap; JPEG compression and writes never run on the UI thread. */
|
||||
void save(Capture capture,Bitmap bitmap){
|
||||
io.execute(()->{
|
||||
boolean saved=false;
|
||||
try{
|
||||
if(current(capture)&&bitmap.getWidth()==WIDTH&&bitmap.getHeight()==HEIGHT)saved=write(capture.key,bitmap);
|
||||
}finally{bitmap.recycle();}
|
||||
synchronized(this){
|
||||
if(!saved||!current(capture))return;
|
||||
Set<String> next=new HashSet<>(files);next.add(capture.key);
|
||||
if(!index.edit().putStringSet("files",next).commit())return;
|
||||
files.add(capture.key);
|
||||
}
|
||||
changed();
|
||||
});
|
||||
}
|
||||
private boolean write(String key,Bitmap bitmap){
|
||||
AtomicFile file=new AtomicFile(new File(directory,key+".jpg"));FileOutputStream output=null;
|
||||
try{
|
||||
ByteArrayOutputStream encoded=new ByteArrayOutputStream();
|
||||
if(!bitmap.compress(Bitmap.CompressFormat.JPEG,78,encoded))return false;
|
||||
byte[] bytes=encoded.toByteArray();
|
||||
if(!directory.isDirectory()&&!directory.mkdirs())return false;
|
||||
output=file.startWrite();output.write(bytes);
|
||||
output.getFD().sync();file.finishWrite(output);output=null;
|
||||
return Arrays.equals(bytes,file.readFully());
|
||||
}catch(IOException|RuntimeException error){if(output!=null)file.failWrite(output);return false;}
|
||||
}
|
||||
void load(String server,String id,Consumer<Bitmap> receive){
|
||||
final Capture read;
|
||||
synchronized(this){
|
||||
String key=key(server,id);
|
||||
if(!enabled()||cleaning||!files.contains(key)){main.post(()->receive.accept(null));return;}
|
||||
read=new Capture(key,generation,versions.getOrDefault(key,0L));
|
||||
}
|
||||
io.execute(()->{
|
||||
Bitmap bitmap=null;
|
||||
if(current(read)){
|
||||
File file=new File(directory,read.key+".jpg");
|
||||
if(file.isFile()&&file.length()<=2*1024*1024){
|
||||
BitmapFactory.Options bounds=new BitmapFactory.Options();bounds.inJustDecodeBounds=true;
|
||||
BitmapFactory.decodeFile(file.getAbsolutePath(),bounds);
|
||||
if(bounds.outWidth==WIDTH&&bounds.outHeight==HEIGHT)bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
Bitmap image=bitmap;
|
||||
main.post(()->{
|
||||
boolean valid;synchronized(this){valid=current(read)&&files.contains(read.key);}
|
||||
if(valid)receive.accept(image);else if(image!=null)image.recycle();
|
||||
});
|
||||
});
|
||||
}
|
||||
synchronized void remove(String server,String id){
|
||||
String key=key(server,id);versions.put(key,versions.getOrDefault(key,0L)+1);files.remove(key);
|
||||
io.execute(()->{
|
||||
new AtomicFile(new File(directory,key+".jpg")).delete();
|
||||
synchronized(this){
|
||||
boolean saved=index.edit().putStringSet("files",new HashSet<>(files)).commit();
|
||||
if(!saved||new File(directory,key+".jpg").exists())cleanupError="部分预览图未能清除,请重试。";
|
||||
}
|
||||
changed();
|
||||
});changed();
|
||||
}
|
||||
synchronized void clear(){
|
||||
final long epoch=++generation;files.clear();cleaning=true;cleanupError="";changed();
|
||||
io.execute(()->{
|
||||
boolean success=index.edit().clear().commit();
|
||||
try{deleteTree(directory);}catch(IOException error){success=false;}
|
||||
synchronized(this){
|
||||
if(epoch!=generation)return;
|
||||
cleaning=false;cleanupError=success?"":"部分预览图未能清除,请重试。";
|
||||
}
|
||||
changed();
|
||||
});
|
||||
}
|
||||
private static void deleteTree(File file)throws IOException{
|
||||
if(!file.exists())return;
|
||||
if(file.isDirectory()&&!Files.isSymbolicLink(file.toPath())){
|
||||
File[] children=file.listFiles();if(children==null)throw new IOException("Cannot list previews");
|
||||
boolean failed=false;for(File child:children)try{deleteTree(child);}catch(IOException error){failed=true;}
|
||||
if(failed)throw new IOException("Cannot clear all previews");
|
||||
}
|
||||
if(!file.delete())throw new IOException("Cannot delete preview");
|
||||
}
|
||||
private static String key(String server,String id){
|
||||
try{
|
||||
byte[] bytes=new JSONArray().put(server).put(id).toString().getBytes(StandardCharsets.UTF_8);
|
||||
byte[] hash=MessageDigest.getInstance("SHA-256").digest(bytes);StringBuilder key=new StringBuilder();
|
||||
for(byte b:hash)key.append(String.format(Locale.ROOT,"%02x",b&255));return key.toString();
|
||||
}catch(Exception error){throw new IllegalStateException(error);}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.app.Service;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ServiceInfo;
|
||||
import android.os.Build;
|
||||
import android.os.IBinder;
|
||||
import android.os.PowerManager;
|
||||
import android.util.Log;
|
||||
|
||||
/** Foreground fallback for a user-started RTC session when native PiP is unavailable. */
|
||||
public final class RemoteSessionService extends Service {
|
||||
private static final String CHANNEL = "remote_connection";
|
||||
private static final String STOP = "cn.crossdesk.mobile.STOP_REMOTE_SESSION";
|
||||
private static final int NOTIFICATION = 41;
|
||||
private static BackgroundSession current;
|
||||
private static RemoteSessionService running;
|
||||
private BackgroundSession owned;
|
||||
private PowerManager.WakeLock wakeLock;
|
||||
|
||||
static BackgroundSession current() { return current; }
|
||||
static boolean retain(Context context, BackgroundSession value) {
|
||||
if (value.ended || value.session.isClosed()) return false;
|
||||
if (current == value) return true;
|
||||
if (current != null) return false;
|
||||
current = value;
|
||||
try {
|
||||
context.startForegroundService(new Intent(context, RemoteSessionService.class).putExtra("session", value.token));
|
||||
return true;
|
||||
} catch (RuntimeException error) {
|
||||
current = null;
|
||||
Log.w("CrossDesk", "Background session service could not start", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
static void release(Context context, BackgroundSession value) {
|
||||
if (current != value) return;
|
||||
current = null;
|
||||
if (running != null) running.releaseWakeLock();
|
||||
context.stopService(new Intent(context, RemoteSessionService.class));
|
||||
}
|
||||
static void refresh(BackgroundSession value) {
|
||||
if (current == value && running != null && running.owned == value) running.update();
|
||||
}
|
||||
@Override public IBinder onBind(Intent intent) { return null; }
|
||||
@Override public void onCreate() {
|
||||
super.onCreate(); running = this;
|
||||
getSystemService(NotificationManager.class).createNotificationChannel(
|
||||
new NotificationChannel(CHANNEL, "远程连接", NotificationManager.IMPORTANCE_LOW));
|
||||
wakeLock = getSystemService(PowerManager.class).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CrossDesk:RemoteSession");
|
||||
wakeLock.setReferenceCounted(false);
|
||||
}
|
||||
@Override public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
BackgroundSession value = current;
|
||||
if (value == null || value.ended || value.session.isClosed()) { stopSelf(startId); return START_NOT_STICKY; }
|
||||
if (intent == null || !value.token.equals(intent.getStringExtra("session"))) return START_NOT_STICKY;
|
||||
owned = value;
|
||||
if (STOP.equals(intent.getAction())) { value.finish("已从通知断开远程连接"); return START_NOT_STICKY; }
|
||||
try {
|
||||
Notification notification = notification();
|
||||
if (Build.VERSION.SDK_INT >= 34) startForeground(NOTIFICATION, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE);
|
||||
else startForeground(NOTIFICATION, notification);
|
||||
update();
|
||||
} catch (RuntimeException error) {
|
||||
Log.w("CrossDesk", "Background session foreground promotion failed", error);
|
||||
value.finish("后台保活未能启动,请保持应用在前台后重新连接");
|
||||
}
|
||||
return START_NOT_STICKY;
|
||||
}
|
||||
private Notification notification() {
|
||||
PendingIntent open = PendingIntent.getActivity(this, 0,
|
||||
new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
|
||||
Intent stopIntent = new Intent(this, RemoteSessionService.class).setAction(STOP)
|
||||
.setData(android.net.Uri.parse("crossdesk-session:" + owned.token)).putExtra("session", owned.token);
|
||||
PendingIntent stop = PendingIntent.getService(this, 1, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
|
||||
return new Notification.Builder(this, CHANNEL).setSmallIcon(R.drawable.ic_remote_session)
|
||||
.setContentTitle("CrossDesk 远程连接")
|
||||
.setContentText(owned.background ? "后台保持连接,点按返回远程桌面" : "已启用后台保活,切换应用可继续保持连接")
|
||||
.setContentIntent(open).setOngoing(true).setOnlyAlertOnce(true).setShowWhen(false)
|
||||
.setCategory(Notification.CATEGORY_SERVICE).setVisibility(Notification.VISIBILITY_PRIVATE)
|
||||
.addAction(new Notification.Action.Builder(null, "返回", open).build())
|
||||
.addAction(new Notification.Action.Builder(null, "断开", stop).build()).build();
|
||||
}
|
||||
@android.annotation.SuppressLint("WakelockTimeout") // Released on foreground return, disconnect, task removal and service destruction.
|
||||
private void update() {
|
||||
if (owned == null || owned.ended) return;
|
||||
if (owned.background) { if (!wakeLock.isHeld()) wakeLock.acquire(); }
|
||||
else releaseWakeLock();
|
||||
getSystemService(NotificationManager.class).notify(NOTIFICATION, notification());
|
||||
}
|
||||
private void releaseWakeLock() { if (wakeLock != null && wakeLock.isHeld()) wakeLock.release(); }
|
||||
@Override public void onTaskRemoved(Intent rootIntent) {
|
||||
if (current == owned && owned != null) owned.finish("远程任务已关闭");
|
||||
stopSelf();
|
||||
}
|
||||
@Override public void onDestroy() {
|
||||
if (running == this) running = null;
|
||||
releaseWakeLock(); stopForeground(STOP_FOREGROUND_REMOVE);
|
||||
BackgroundSession value = owned;
|
||||
if (current == value && value != null) { current = null; value.finish("后台连接服务已停止,请重新连接"); }
|
||||
super.onDestroy();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import org.json.JSONObject;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.util.function.Consumer;
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
|
||||
/** One check per desktop session. State and completion callbacks run on main. */
|
||||
final class RemoteVersionCheck {
|
||||
static final String NOTICE = "被控端版本过低,请升级到最新版本。";
|
||||
static final String RELEASE_URL = "https://version.crossdesk.cn/version.json";
|
||||
interface Cancellation { void cancel(); }
|
||||
interface Fetcher { Cancellation fetch(Consumer<byte[]> completion); }
|
||||
|
||||
private final Fetcher fetcher;
|
||||
private final Runnable notify;
|
||||
private boolean connected, receivedHostInfo, attempted;
|
||||
private String version = "";
|
||||
private long generation;
|
||||
private Cancellation request;
|
||||
|
||||
RemoteVersionCheck(Runnable notify) { this(ReleaseRequest::start, notify); }
|
||||
RemoteVersionCheck(Fetcher fetcher, Runnable notify) {
|
||||
this.fetcher = fetcher;
|
||||
this.notify = notify;
|
||||
}
|
||||
|
||||
void connected() { connected = true; check(); }
|
||||
|
||||
void hostInfo(JSONObject info) {
|
||||
receivedHostInfo = true;
|
||||
Object value = info.opt("app_version");
|
||||
version = value instanceof String && NativeSession.nValidAppVersion((String)value)
|
||||
? (String)value : "";
|
||||
check();
|
||||
}
|
||||
|
||||
private void check() {
|
||||
if (!connected || !receivedHostInfo || attempted) return;
|
||||
attempted = true;
|
||||
// iOS treats missing/invalid peer versions as legacy, without a request.
|
||||
if (version.isEmpty()) { notify.run(); return; }
|
||||
long currentGeneration = generation;
|
||||
String currentVersion = version;
|
||||
request = fetcher.fetch(data -> {
|
||||
if (generation != currentGeneration || !connected) return;
|
||||
request = null;
|
||||
if (data != null && NativeSession.nHasAppUpdate(currentVersion, data)) notify.run();
|
||||
});
|
||||
}
|
||||
|
||||
void reset() {
|
||||
++generation;
|
||||
connected = receivedHostInfo = attempted = false;
|
||||
version = "";
|
||||
if (request != null) request.cancel();
|
||||
request = null;
|
||||
}
|
||||
|
||||
static final class ReleaseRequest implements Cancellation, Runnable {
|
||||
private static final int MAX_BYTES = 256 * 1024;
|
||||
private final Handler main = new Handler(Looper.getMainLooper());
|
||||
private final Consumer<byte[]> completion;
|
||||
private final Runnable timeout = () -> finish(null);
|
||||
private volatile boolean cancelled;
|
||||
private HttpsURLConnection connection;
|
||||
|
||||
private ReleaseRequest(Consumer<byte[]> completion) { this.completion = completion; }
|
||||
static Cancellation start(Consumer<byte[]> completion) {
|
||||
ReleaseRequest request = new ReleaseRequest(completion);
|
||||
request.main.postDelayed(request.timeout, 15000);
|
||||
Thread worker = new Thread(request, "CrossDesk version check");
|
||||
worker.setDaemon(true);
|
||||
worker.start();
|
||||
return request;
|
||||
}
|
||||
|
||||
@Override public void run() {
|
||||
byte[] result = null;
|
||||
HttpsURLConnection opened = null;
|
||||
try {
|
||||
// Fetch public metadata only: no peer identity, version or credentials.
|
||||
opened = (HttpsURLConnection)new URL(RELEASE_URL).openConnection();
|
||||
synchronized (this) {
|
||||
if (cancelled) return;
|
||||
connection = opened;
|
||||
}
|
||||
opened.setConnectTimeout(5000);
|
||||
opened.setReadTimeout(10000);
|
||||
opened.setUseCaches(false);
|
||||
opened.setInstanceFollowRedirects(false);
|
||||
if (opened.getResponseCode() == 200 && opened.getContentLengthLong() <= MAX_BYTES) {
|
||||
try (InputStream input = opened.getInputStream();
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream()) {
|
||||
byte[] buffer = new byte[4096];
|
||||
int count;
|
||||
while (!cancelled && (count = input.read(buffer)) != -1) {
|
||||
if (output.size() + count > MAX_BYTES) return;
|
||||
output.write(buffer, 0, count);
|
||||
}
|
||||
if (!cancelled) result = output.toByteArray();
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// A failed check is silent, as on iOS; it never interrupts control.
|
||||
} finally {
|
||||
if (opened != null) opened.disconnect();
|
||||
byte[] response = result;
|
||||
main.post(() -> finish(response));
|
||||
}
|
||||
}
|
||||
|
||||
private void finish(byte[] response) {
|
||||
if (cancelled) return;
|
||||
cancel();
|
||||
completion.accept(response);
|
||||
}
|
||||
|
||||
@Override public void cancel() {
|
||||
HttpsURLConnection active;
|
||||
synchronized (this) { cancelled = true; active = connection; connection = null; }
|
||||
main.removeCallbacks(timeout);
|
||||
if (active != null) active.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
/** Same request/acknowledgement and rollback rules as the iOS controller. */
|
||||
final class RemoteVideoSettings {
|
||||
static final String[] PREFERENCES={"帧率优先","画质优先","平衡"};
|
||||
static final String[] DETAILS={
|
||||
"优先保持画面流畅,带宽或编码压力较大时会更积极地降低分辨率。",
|
||||
"始终保持较高分辨率,带宽不足时通过降低帧率来保证画面清晰度。",
|
||||
"兼顾清晰度和流畅度,只在持续压力下逐步降低分辨率。"};
|
||||
static final class Values {
|
||||
final int quality,frameRate,preference;
|
||||
Values(int quality,int frameRate,int preference){this.quality=quality;this.frameRate=frameRate;this.preference=preference;}
|
||||
boolean valid(){return quality>=0&&quality<=2&&(frameRate==30||frameRate==60)&&preference>=0&&preference<=2;}
|
||||
JSONObject status(long requestId,boolean accepted){
|
||||
try{return new JSONObject().put("type",12).put("video_settings",new JSONObject().put("quality",quality).put("frame_rate",frameRate).put("preference",preference).put("request_id",requestId).put("accepted",accepted));}
|
||||
catch(org.json.JSONException impossible){throw new IllegalStateException(impossible);}
|
||||
}
|
||||
}
|
||||
boolean supported,pending,failed;
|
||||
Values selection,applied;
|
||||
long requestId,appliedRequestId;
|
||||
RemoteVideoSettings(int preference){this(preference,1920);}
|
||||
RemoteVideoSettings(int preference,int displayLongEdge){
|
||||
// Start within common mobile decoder limits. Hardware availability and
|
||||
// maximum resolution vary, and AV1 may still need software fallback.
|
||||
// Small screens need no more than 720p; larger screens start at 1080p.
|
||||
// All quality/frame-rate choices remain available for manual adjustment.
|
||||
selection=applied=new Values(displayLongEdge>0&&displayLongEdge<=1280?0:1,30,preference>=0&&preference<=2?preference:1);
|
||||
}
|
||||
void setSupported(boolean value){supported=value;if(!value){selection=applied;pending=false;failed=false;}}
|
||||
long begin(Values value){
|
||||
if(!supported||!value.valid())return -1;
|
||||
requestId=(requestId+1)&0xffffffffL;selection=value;pending=true;failed=false;return requestId;
|
||||
}
|
||||
void receive(Values value,long responseId,boolean accepted){
|
||||
if(!supported||!value.valid()||responseId<0||responseId>0xffffffffL||(int)(requestId-responseId)<0)return;
|
||||
if(accepted&&(int)(responseId-appliedRequestId)>=0){applied=value;appliedRequestId=responseId;}
|
||||
if(responseId!=requestId)return;
|
||||
pending=false;failed=!accepted;selection=applied;
|
||||
}
|
||||
void receive(JSONObject message){
|
||||
try{
|
||||
if(message.getInt("type")!=12)return;
|
||||
JSONObject settings=message.getJSONObject("video_settings");
|
||||
for(String key:new String[]{"quality","frame_rate","preference","request_id"}){
|
||||
Object value=settings.get(key);if(!(value instanceof Integer)&&!(value instanceof Long))return;
|
||||
}
|
||||
long quality=settings.getLong("quality"),rate=settings.getLong("frame_rate"),preference=settings.getLong("preference");
|
||||
if(quality<0||quality>2||(rate!=30&&rate!=60)||preference<0||preference>2)return;
|
||||
Object accepted=settings.opt("accepted");if(accepted!=null&&!(accepted instanceof Boolean))return;
|
||||
receive(new Values((int)quality,(int)rate,(int)preference),settings.getLong("request_id"),Boolean.TRUE.equals(accepted));
|
||||
}catch(org.json.JSONException ignored){ }
|
||||
}
|
||||
void expire(long expiredId){if(pending&&expiredId==requestId){selection=applied;pending=false;failed=true;}}
|
||||
String feedback(){return !supported?"连接建立后可调整,需被控端支持。":failed?"调整失败,请重试。":"";}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Path;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Rect;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.PixelCopy;
|
||||
import android.view.GestureDetector;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.ScaleGestureDetector;
|
||||
import android.view.SurfaceHolder;
|
||||
import android.view.SurfaceView;
|
||||
import android.view.View;
|
||||
import android.widget.FrameLayout;
|
||||
|
||||
@android.annotation.SuppressLint("ViewConstructor") // Constructed only with a live session, never from XML.
|
||||
final class RemoteVideoView extends FrameLayout implements SurfaceHolder.Callback {
|
||||
private final SurfaceView video;
|
||||
private final Cursor cursor;
|
||||
private final NativeSession session;
|
||||
final RemoteMouseInput mouseInput;
|
||||
private final GestureDetector gestures;
|
||||
private final ScaleGestureDetector scales;
|
||||
private final RemoteViewport viewport = new RemoteViewport();
|
||||
private final RemoteViewport pictureInPictureViewport = new RemoteViewport();
|
||||
private boolean pictureInPicture;
|
||||
private int frameWidth = 16, frameHeight = 9;
|
||||
private float x = .5f, y = .5f, scrollY;
|
||||
private boolean dragging, twoFinger, relative, viewportGesture, viewportPanActive;
|
||||
private float lastX,lastY,twoFingerX,twoFingerY;
|
||||
private long touchRevision;
|
||||
private boolean suppressPointerGesture;
|
||||
void setRelative(boolean value) { releaseMouse(); relative=value; }
|
||||
void setPictureInPicture(boolean value) {
|
||||
if(pictureInPicture==value)return;
|
||||
releaseMouse();pictureInPicture=value;cursor.setVisibility(value?GONE:VISIBLE);fit();
|
||||
}
|
||||
Rect pictureInPictureBounds() {
|
||||
Rect bounds=new Rect();video.getGlobalVisibleRect(bounds);return bounds;
|
||||
}
|
||||
void releaseMouse() { mouseInput.releaseAll(); dragging=false; suppressPointerGesture=true; }
|
||||
private boolean suppressPointerGesture() {
|
||||
return suppressPointerGesture || mouseInput.hasVirtualButton() || touchRevision != mouseInput.revision();
|
||||
}
|
||||
RemoteVideoView(Context context, NativeSession session) {
|
||||
super(context); this.session = session;
|
||||
mouseInput = new RemoteMouseInput(this::sendMouse);
|
||||
setBackgroundColor(Color.BLACK);
|
||||
video = new SurfaceView(context); video.getHolder().addCallback(this);
|
||||
addView(video, new LayoutParams(1, 1, android.view.Gravity.CENTER));
|
||||
cursor = new Cursor(context);
|
||||
// Keep input in container coordinates so transforms never move its hit area.
|
||||
addView(cursor, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
|
||||
gestures = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
|
||||
@Override public boolean onDown(MotionEvent e) { return point(e); }
|
||||
@Override public boolean onSingleTapUp(MotionEvent e) {
|
||||
if (!twoFinger && !suppressPointerGesture() && point(e)) cursor.performClick(); return true;
|
||||
}
|
||||
@Override public void onLongPress(MotionEvent e) { if (!twoFinger && !dragging && !suppressPointerGesture() && point(e)) click(3, 4); }
|
||||
@Override public boolean onScroll(MotionEvent first, MotionEvent current, float dx, float dy) {
|
||||
if (twoFinger) return true;
|
||||
if (!relative && !dragging && !suppressPointerGesture()) {
|
||||
if (!point(first)) return true;
|
||||
mouseInput.gestureLeft(true); dragging = true;
|
||||
}
|
||||
point(current); return true;
|
||||
}
|
||||
});
|
||||
// Let the remote desktop detect double-clicks; the default listener consumes the second tap.
|
||||
gestures.setOnDoubleTapListener(null);
|
||||
scales = new ScaleGestureDetector(context, new ScaleGestureDetector.SimpleOnScaleGestureListener() {
|
||||
@Override public boolean onScaleBegin(ScaleGestureDetector detector) {
|
||||
if (mouseInput.hasVirtualButton()) return false;
|
||||
if (!viewport.contains(detector.getFocusX(), detector.getFocusY())) return false;
|
||||
viewportGesture = true;
|
||||
viewportPanActive = true;
|
||||
return true;
|
||||
}
|
||||
@Override public boolean onScale(ScaleGestureDetector detector) {
|
||||
viewport.zoomBy(detector.getScaleFactor(), detector.getFocusX(), detector.getFocusY());
|
||||
applyViewport();
|
||||
return true;
|
||||
}
|
||||
@Override public void onScaleEnd(ScaleGestureDetector detector) {
|
||||
viewport.finishGesture();
|
||||
applyViewport();
|
||||
}
|
||||
});
|
||||
scales.setQuickScaleEnabled(false);
|
||||
scales.setStylusScaleEnabled(false);
|
||||
cursor.setOnGenericMotionListener((v, event) -> {
|
||||
if (!point(event)) return true;
|
||||
if (event.getActionMasked() == MotionEvent.ACTION_SCROLL) {
|
||||
float delta = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
|
||||
if (delta != 0) session.pointer(x, y, 7, delta > 0 ? 1 : -1);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
setContentDescription("远程桌面:轻触点击,拖动移动,长按右键,双指捏合缩放,放大后双指拖动画面,原始比例下双指上下滑动滚动");
|
||||
}
|
||||
void videoSize(int width, int height) {
|
||||
if (width <= 0 || height <= 0) return;
|
||||
frameWidth = width; frameHeight = height; fit();
|
||||
}
|
||||
void resetViewport() { releaseMouse(); viewport.reset(); applyViewport(); }
|
||||
static Rect previewCrop(int width,int height){
|
||||
int w=width,h=height;
|
||||
if((long)width*RemotePreviewStore.HEIGHT>(long)height*RemotePreviewStore.WIDTH)w=Math.max(1,height*RemotePreviewStore.WIDTH/RemotePreviewStore.HEIGHT);
|
||||
else h=Math.max(1,width*RemotePreviewStore.HEIGHT/RemotePreviewStore.WIDTH);
|
||||
return new Rect((width-w)/2,(height-h)/2,(width+w)/2,(height+h)/2);
|
||||
}
|
||||
void capturePreview(java.util.function.Consumer<Bitmap> completion){
|
||||
// Copy only the decoded-video Surface, excluding cursor, controls, keyboard and black margins.
|
||||
if(!isAttachedToWindow()||!video.getHolder().getSurface().isValid()){completion.accept(null);return;}
|
||||
Bitmap image=Bitmap.createBitmap(RemotePreviewStore.WIDTH,RemotePreviewStore.HEIGHT,Bitmap.Config.ARGB_8888);
|
||||
try{
|
||||
PixelCopy.request(video.getHolder().getSurface(),previewCrop(frameWidth,frameHeight),image,result->{
|
||||
if(result==PixelCopy.SUCCESS)completion.accept(image);else{image.recycle();completion.accept(null);}
|
||||
},new Handler(Looper.getMainLooper()));
|
||||
}catch(IllegalArgumentException error){image.recycle();completion.accept(null);}
|
||||
}
|
||||
private void fit() {
|
||||
if (getWidth() == 0 || getHeight() == 0) return;
|
||||
RemoteViewport active=pictureInPicture?pictureInPictureViewport:viewport;
|
||||
active.fit(getWidth(), getHeight(), frameWidth, frameHeight);
|
||||
video.setLayoutParams(new LayoutParams(active.baseWidth(),active.baseHeight(),android.view.Gravity.CENTER));
|
||||
applyViewport();
|
||||
}
|
||||
private void applyViewport() {
|
||||
// Transform the existing Surface without enlarging its decoder buffers.
|
||||
RemoteViewport active=pictureInPicture?pictureInPictureViewport:viewport;
|
||||
video.setScaleX(active.scale()); video.setScaleY(active.scale());
|
||||
video.setTranslationX(active.offsetX()); video.setTranslationY(active.offsetY());
|
||||
mouseInput.viewportWidth = active.width(); mouseInput.viewportHeight = active.height();
|
||||
cursor.invalidate();
|
||||
}
|
||||
private void sendMouse(float x, float y, int flag, int wheel) {
|
||||
this.x = x; this.y = y;
|
||||
session.pointer(x,y,flag,wheel);
|
||||
cursor.invalidate();
|
||||
}
|
||||
@Override protected void onSizeChanged(int w,int h,int oldw,int oldh) { post(this::fit); }
|
||||
private boolean point(MotionEvent e) {
|
||||
boolean touchpad = relative && e.getToolType(0) != MotionEvent.TOOL_TYPE_MOUSE;
|
||||
float px=e.getX(),py=e.getY();
|
||||
if (!touchpad && !viewport.contains(px,py)) return false;
|
||||
if(touchpad){
|
||||
if(e.getActionMasked()==MotionEvent.ACTION_MOVE){
|
||||
x=Math.max(0,Math.min(1,x+(px-lastX)/Math.max(1,viewport.width())));
|
||||
y=Math.max(0,Math.min(1,y+(py-lastY)/Math.max(1,viewport.height())));
|
||||
}
|
||||
}else{
|
||||
x=viewport.normalizedX(px);
|
||||
y=viewport.normalizedY(py);
|
||||
}
|
||||
lastX=px;lastY=py;
|
||||
mouseInput.move(x,y); cursor.invalidate();
|
||||
return true;
|
||||
}
|
||||
private void click(int down, int up) { mouseInput.click(down,up); }
|
||||
private boolean touch(MotionEvent e) {
|
||||
int action = e.getActionMasked();
|
||||
if (action == MotionEvent.ACTION_DOWN) {
|
||||
twoFinger = viewportGesture = viewportPanActive = false;
|
||||
touchRevision = mouseInput.revision();
|
||||
suppressPointerGesture = mouseInput.hasVirtualButton();
|
||||
}
|
||||
if (action == MotionEvent.ACTION_POINTER_DOWN) {
|
||||
if (dragging) { mouseInput.gestureLeft(false); dragging = false; }
|
||||
twoFinger = true;
|
||||
twoFingerX = focus(e,true,-1); twoFingerY = scrollY = focus(e,false,-1);
|
||||
viewportPanActive = viewport.isZoomed() && viewport.contains(twoFingerX,twoFingerY);
|
||||
MotionEvent cancel = MotionEvent.obtain(e); cancel.setAction(MotionEvent.ACTION_CANCEL);
|
||||
gestures.onTouchEvent(cancel); cancel.recycle();
|
||||
}
|
||||
scales.onTouchEvent(e);
|
||||
if (twoFinger && action == MotionEvent.ACTION_MOVE && e.getPointerCount() >= 2) {
|
||||
if (mouseInput.hasVirtualButton()) return true;
|
||||
float focusX = focus(e,true,-1), focusY = focus(e,false,-1);
|
||||
if (viewport.isZoomed() || viewportGesture || scales.isInProgress()) {
|
||||
viewportGesture = true;
|
||||
if (!viewportPanActive) viewportPanActive = viewport.contains(focusX,focusY);
|
||||
if (viewportPanActive) {
|
||||
viewport.panBy(focusX-twoFingerX,focusY-twoFingerY);
|
||||
applyViewport();
|
||||
}
|
||||
} else if (viewport.contains(focusX,focusY)) {
|
||||
float delta = focusY - scrollY;
|
||||
if (Math.abs(delta) > 16 * getResources().getDisplayMetrics().density) {
|
||||
session.pointer(x,y,7,delta > 0 ? 1 : -1); scrollY = focusY;
|
||||
}
|
||||
}
|
||||
twoFingerX = focusX; twoFingerY = focusY;
|
||||
} else if (!twoFinger) {
|
||||
if ((e.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0 && action == MotionEvent.ACTION_DOWN) {
|
||||
if (point(e)) click(3,4); return true;
|
||||
}
|
||||
gestures.onTouchEvent(e);
|
||||
}
|
||||
if (action == MotionEvent.ACTION_POINTER_UP) {
|
||||
// Rebase when a finger lifts; never resume a click/drag until all lift.
|
||||
twoFingerX = focus(e,true,e.getActionIndex());
|
||||
twoFingerY = scrollY = focus(e,false,e.getActionIndex());
|
||||
}
|
||||
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
|
||||
if (dragging) mouseInput.gestureLeft(false);
|
||||
dragging = false;
|
||||
viewport.finishGesture(); applyViewport();
|
||||
viewportPanActive = false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
private static float focus(MotionEvent event, boolean horizontal, int excludedIndex) {
|
||||
float total = 0; int count = 0;
|
||||
for (int i=0;i<event.getPointerCount();i++) {
|
||||
if (i==excludedIndex) continue;
|
||||
total += horizontal ? event.getX(i) : event.getY(i); count++;
|
||||
}
|
||||
return total / Math.max(1,count);
|
||||
}
|
||||
@Override public boolean performClick() { super.performClick(); return true; }
|
||||
@Override public void surfaceCreated(SurfaceHolder holder) { session.surface(holder.getSurface()); }
|
||||
@Override public void surfaceChanged(SurfaceHolder holder,int format,int width,int height) { }
|
||||
@Override public void surfaceDestroyed(SurfaceHolder holder) { releaseMouse(); session.surface(null); }
|
||||
@Override protected void onDetachedFromWindow() { releaseMouse(); super.onDetachedFromWindow(); }
|
||||
private final class Cursor extends View {
|
||||
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final Path arrow = new Path();
|
||||
private final float arrowWidth = 12, arrowHeight = 15;
|
||||
Cursor(Context context) {
|
||||
super(context); setClickable(true); setContentDescription("远程桌面触控区域");
|
||||
// Match the iOS RemoteCursorArrowShape in density-independent units.
|
||||
arrow.moveTo(arrowWidth*.08f,arrowHeight*.04f);
|
||||
arrow.lineTo(arrowWidth*.08f,arrowHeight*.78f);
|
||||
arrow.lineTo(arrowWidth*.34f,arrowHeight*.60f);
|
||||
arrow.lineTo(arrowWidth*.55f,arrowHeight*.94f);
|
||||
arrow.lineTo(arrowWidth*.73f,arrowHeight*.84f);
|
||||
arrow.lineTo(arrowWidth*.52f,arrowHeight*.51f);
|
||||
arrow.lineTo(arrowWidth*.88f,arrowHeight*.49f);
|
||||
arrow.close();
|
||||
}
|
||||
// GestureDetector calls performClick only after resolving tap vs drag/long press.
|
||||
@android.annotation.SuppressLint("ClickableViewAccessibility")
|
||||
@Override public boolean onTouchEvent(MotionEvent event) { return touch(event); }
|
||||
@Override public boolean performClick() { super.performClick(); click(1, 2); return true; }
|
||||
@Override protected void onDraw(Canvas canvas) {
|
||||
int saved=canvas.save();
|
||||
canvas.translate(viewport.left()+x*viewport.width(),viewport.top()+y*viewport.height());
|
||||
float density=getResources().getDisplayMetrics().density;canvas.scale(density,density);
|
||||
// Anchor the arrow tip to the same normalized coordinate sent to the desktop.
|
||||
canvas.translate(-arrowWidth*.08f,-arrowHeight*.04f);
|
||||
paint.setStyle(Paint.Style.STROKE);paint.setStrokeWidth(1.75f);paint.setColor(Color.BLACK);canvas.drawPath(arrow,paint);
|
||||
paint.setStyle(Paint.Style.FILL);paint.setColor(Color.WHITE);canvas.drawPath(arrow,paint);
|
||||
canvas.restoreToCount(saved);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
/** Geometry shared by the video Surface, cursor and remote pointer input. */
|
||||
final class RemoteViewport {
|
||||
private static final float MAXIMUM_SCALE = 10;
|
||||
private int baseWidth, baseHeight, baseLeft, baseTop;
|
||||
private float scale = 1, offsetX, offsetY;
|
||||
|
||||
void fit(int width, int height, int videoWidth, int videoHeight) {
|
||||
if (width <= 0 || height <= 0 || videoWidth <= 0 || videoHeight <= 0) return;
|
||||
double fitScale = Math.min((double) width / videoWidth, (double) height / videoHeight);
|
||||
baseWidth = Math.max(1, (int) (videoWidth * fitScale));
|
||||
baseHeight = Math.max(1, (int) (videoHeight * fitScale));
|
||||
// Match the integer positioning of Gravity.CENTER, including odd margins.
|
||||
baseLeft = (width - baseWidth) / 2;
|
||||
baseTop = (height - baseHeight) / 2;
|
||||
constrainOffset();
|
||||
}
|
||||
|
||||
int baseWidth() { return baseWidth; }
|
||||
int baseHeight() { return baseHeight; }
|
||||
float scale() { return scale; }
|
||||
float offsetX() { return offsetX; }
|
||||
float offsetY() { return offsetY; }
|
||||
float width() { return baseWidth * scale; }
|
||||
float height() { return baseHeight * scale; }
|
||||
float left() { return baseLeft + baseWidth * (1 - scale) / 2 + offsetX; }
|
||||
float top() { return baseTop + baseHeight * (1 - scale) / 2 + offsetY; }
|
||||
boolean isZoomed() { return scale > 1.001f; }
|
||||
|
||||
boolean contains(float x, float y) {
|
||||
return baseWidth > 0 && baseHeight > 0 &&
|
||||
x >= left() && x < left() + width() && y >= top() && y < top() + height();
|
||||
}
|
||||
|
||||
float normalizedX(float x) { return clamp((x - left()) / Math.max(1, width()), 0, 1); }
|
||||
float normalizedY(float y) { return clamp((y - top()) / Math.max(1, height()), 0, 1); }
|
||||
|
||||
void zoomBy(float factor, float focusX, float focusY) {
|
||||
if (baseWidth == 0 || baseHeight == 0 || !Float.isFinite(factor) || factor <= 0) return;
|
||||
float nextScale = clamp(scale * factor, 1, MAXIMUM_SCALE);
|
||||
float ratio = nextScale / scale;
|
||||
float focusFromCenterX = focusX - (baseLeft + baseWidth / 2f);
|
||||
float focusFromCenterY = focusY - (baseTop + baseHeight / 2f);
|
||||
offsetX = focusFromCenterX - (focusFromCenterX - offsetX) * ratio;
|
||||
offsetY = focusFromCenterY - (focusFromCenterY - offsetY) * ratio;
|
||||
scale = nextScale;
|
||||
constrainOffset();
|
||||
}
|
||||
|
||||
void panBy(float dx, float dy) {
|
||||
offsetX += dx;
|
||||
offsetY += dy;
|
||||
constrainOffset();
|
||||
}
|
||||
|
||||
void finishGesture() {
|
||||
if (!isZoomed()) reset();
|
||||
}
|
||||
|
||||
void reset() { scale = 1; offsetX = offsetY = 0; }
|
||||
|
||||
private void constrainOffset() {
|
||||
// Keep the original fitted area covered, as on iOS, even with letterboxing.
|
||||
float maximumX = baseWidth * (scale - 1) / 2;
|
||||
float maximumY = baseHeight * (scale - 1) / 2;
|
||||
offsetX = clamp(offsetX, -maximumX, maximumX);
|
||||
offsetY = clamp(offsetY, -maximumY, maximumY);
|
||||
}
|
||||
|
||||
private static float clamp(float value, float minimum, float maximum) {
|
||||
return Math.max(minimum, Math.min(maximum, value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.security.keystore.KeyGenParameterSpec;
|
||||
import android.security.keystore.KeyProperties;
|
||||
import android.util.Base64;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyStore;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
|
||||
/** Server-scoped credentials encrypted with a non-exportable Android Keystore key. */
|
||||
final class SecretStore {
|
||||
private static final String ALIAS = "crossdesk.signaling.v1";
|
||||
private final SharedPreferences preferences;
|
||||
SecretStore(Context context) { preferences = context.getSharedPreferences("identities", Context.MODE_PRIVATE); }
|
||||
private SecretKey key() throws Exception {
|
||||
KeyStore store = KeyStore.getInstance("AndroidKeyStore");
|
||||
store.load(null);
|
||||
if (!store.containsAlias(ALIAS)) {
|
||||
KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
|
||||
generator.init(new KeyGenParameterSpec.Builder(ALIAS,
|
||||
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build());
|
||||
generator.generateKey();
|
||||
}
|
||||
return (SecretKey) store.getKey(ALIAS, null);
|
||||
}
|
||||
String get(String scope) throws Exception {
|
||||
String stored = preferences.getString(scope, "");
|
||||
if (stored.isEmpty()) return "";
|
||||
String[] parts = stored.split(":", 2);
|
||||
if (parts.length != 2) throw new IllegalStateException("Invalid credential record");
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, key(), new GCMParameterSpec(128, Base64.decode(parts[0], Base64.NO_WRAP)));
|
||||
cipher.updateAAD(scope.getBytes(StandardCharsets.UTF_8));
|
||||
return new String(cipher.doFinal(Base64.decode(parts[1], Base64.NO_WRAP)), StandardCharsets.UTF_8);
|
||||
}
|
||||
void remove(String scope) { preferences.edit().remove(scope).apply(); }
|
||||
void put(String scope, String credential) throws Exception {
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key());
|
||||
cipher.updateAAD(scope.getBytes(StandardCharsets.UTF_8));
|
||||
String value = Base64.encodeToString(cipher.getIV(), Base64.NO_WRAP) + ":" +
|
||||
Base64.encodeToString(cipher.doFinal(credential.getBytes(StandardCharsets.UTF_8)), Base64.NO_WRAP);
|
||||
if (!preferences.edit().putString(scope, value).commit()) throw new IllegalStateException("Credential save failed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorListenerAdapter;
|
||||
import android.animation.ValueAnimator;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.RectF;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.view.animation.PathInterpolator;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.TextView;
|
||||
import java.util.function.IntConsumer;
|
||||
|
||||
/** A single sliding selection highlight, matching the iOS segmented settings pickers. */
|
||||
@android.annotation.SuppressLint("ViewConstructor") // Programmatic control with labels and a change callback.
|
||||
final class SegmentedControl extends LinearLayout {
|
||||
private final Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final RectF highlight=new RectF(), destination=new RectF();
|
||||
private final float radius;
|
||||
private final IntConsumer changed;
|
||||
private int selected;
|
||||
private ValueAnimator animator;
|
||||
|
||||
SegmentedControl(MobileUi ui,String[] titles,int selection,boolean enabled,IntConsumer changed){
|
||||
super(ui.context);this.changed=changed;selected=Math.max(0,Math.min(titles.length-1,selection));
|
||||
int inset=ui.dp(MobileUi.SEGMENT_INSET),height=ui.dp(MobileUi.SEGMENT_HEIGHT)-inset*2;
|
||||
radius=height/2f;
|
||||
setGravity(Gravity.CENTER_VERTICAL);setPadding(inset,inset,inset,inset);setBackground(ui.background(0xFFE9E9EF,MobileUi.SEGMENT_HEIGHT/2));paint.setColor(Color.WHITE);
|
||||
for(int i=0;i<titles.length;i++){
|
||||
final int index=i;TextView choice=ui.action(titles[i],MobileUi.INK,()->select(index));
|
||||
choice.setTextSize(13);choice.setMinHeight(height);choice.setSelected(i==selected);choice.setEnabled(enabled);choice.setAlpha(enabled?1:.45f);
|
||||
addView(choice,new LayoutParams(0,height,1));
|
||||
}
|
||||
}
|
||||
|
||||
private RectF selectedBounds(){View choice=getChildAt(selected);return new RectF(choice.getLeft(),choice.getTop(),choice.getRight(),choice.getBottom());}
|
||||
private void select(int index){
|
||||
if(index==selected)return;
|
||||
setSelection(index);changed.accept(index);
|
||||
}
|
||||
void setSelection(int index){
|
||||
if(index==selected)return;
|
||||
selected=index;for(int i=0;i<getChildCount();i++)getChildAt(i).setSelected(i==selected);
|
||||
cancelAnimation();destination.set(selectedBounds());
|
||||
if(!isAttachedToWindow()||!isLaidOut()||highlight.isEmpty()||!ValueAnimator.areAnimatorsEnabled()){
|
||||
highlight.set(destination);invalidate();
|
||||
}else{
|
||||
// Restart from the displayed position, including when the user reverses mid-animation.
|
||||
RectF start=new RectF(highlight),end=new RectF(destination);ValueAnimator next=ValueAnimator.ofFloat(0,1);animator=next;
|
||||
next.setDuration(200);next.setInterpolator(new PathInterpolator(.25f,.1f,.25f,1));
|
||||
next.addUpdateListener(value->{
|
||||
if(animator!=value)return;float fraction=(float)value.getAnimatedValue();
|
||||
highlight.set(start.left+(end.left-start.left)*fraction,start.top+(end.top-start.top)*fraction,start.right+(end.right-start.right)*fraction,start.bottom+(end.bottom-start.bottom)*fraction);invalidate();
|
||||
});
|
||||
next.addListener(new AnimatorListenerAdapter(){@Override public void onAnimationEnd(Animator value){if(animator==value){animator=null;highlight.set(destination);invalidate();}}});next.start();
|
||||
}
|
||||
}
|
||||
void setOptionsEnabled(boolean enabled){
|
||||
for(int i=0;i<getChildCount();i++){getChildAt(i).setEnabled(enabled);getChildAt(i).setAlpha(enabled?1:.45f);}
|
||||
if(!enabled){cancelAnimation();highlight.set(destination);invalidate();}
|
||||
}
|
||||
private void cancelAnimation(){ValueAnimator old=animator;animator=null;if(old!=null)old.cancel();}
|
||||
@Override protected void onLayout(boolean changed,int left,int top,int right,int bottom){
|
||||
super.onLayout(changed,left,top,right,bottom);RectF bounds=selectedBounds();
|
||||
// Text below the picker can reflow without interrupting an unchanged highlight path.
|
||||
if(!destination.equals(bounds)){cancelAnimation();destination.set(bounds);highlight.set(bounds);}
|
||||
}
|
||||
@Override protected void dispatchDraw(Canvas canvas){canvas.drawRoundRect(highlight,radius,radius,paint);super.dispatchDraw(canvas);}
|
||||
@Override protected void onDetachedFromWindow(){cancelAnimation();highlight.set(destination);super.onDetachedFromWindow();}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Color;
|
||||
import android.view.*;
|
||||
import android.widget.*;
|
||||
import static cn.crossdesk.mobile.MobileUi.*;
|
||||
|
||||
/** Safe-area overlay: a draggable 54 dp orb, an adaptive menu and a floating keyboard. */
|
||||
@android.annotation.SuppressLint("ViewConstructor")
|
||||
final class SessionControls extends FrameLayout {
|
||||
interface Actions {
|
||||
void disconnect(); void display(); void clipboard(); void key(int code);
|
||||
void chord(int code,int[] modifiers); void shortcut(int code); void text(String value); void mute(); void mouse();
|
||||
void videoSettings(int field,int value);
|
||||
void sendFile(); void saveFile(); void secureAttention();
|
||||
}
|
||||
private final MobileUi ui;
|
||||
private final Actions actions;
|
||||
private final View orb;
|
||||
private final LinearLayout waiting;
|
||||
private View shield;
|
||||
private LinearLayout menu,keyboard;
|
||||
private VirtualMouseBar mouseBar;
|
||||
private FrameLayout mouseHost;
|
||||
private boolean mouseVisible,pictureInPicture;
|
||||
private ScrollView keyboardKeys;
|
||||
private ScrollView menuScroll;
|
||||
private int keyboardPreferredHeight;
|
||||
private int menuColumns=3;
|
||||
private TextView networkLabel,videoFeedback;
|
||||
private TextView transferLabel,saveFileButton;
|
||||
private String transferStatus="";
|
||||
private boolean hasReceivedFile;
|
||||
private String menuPage="controls";
|
||||
private RemoteNetworkStatistics.Snapshot network=new RemoteNetworkStatistics().snapshot(0);
|
||||
private RemoteVideoSettings settings=new RemoteVideoSettings(1);
|
||||
private final java.util.List<SettingRow> settingRows=new java.util.ArrayList<>();
|
||||
private TextView[][] trafficCells;
|
||||
private LinearLayout[] trafficRows;
|
||||
private TextView[] networkDetails;
|
||||
private View encryptionLock,encryptionOpen;
|
||||
private boolean muted,relative=true,shift,computerKeyboard,orbPositioned;
|
||||
private final java.util.Set<Integer> modifiers=new java.util.LinkedHashSet<>();
|
||||
SessionControls(Context context,MobileUi ui,Actions actions){
|
||||
super(context);this.ui=ui;this.actions=actions;
|
||||
// This container must remain transparent to remote touch outside its controls.
|
||||
waiting=ui.column();waiting.setMinimumWidth(ui.dp(200));waiting.setGravity(Gravity.CENTER);waiting.setPadding(ui.dp(20),ui.dp(20),ui.dp(20),ui.dp(20));waiting.setBackground(ui.background(0xB0202024,14));
|
||||
ProgressBar progress=new ProgressBar(context);progress.setIndeterminateTintList(android.content.res.ColorStateList.valueOf(Color.WHITE));waiting.addView(progress,ui.size(28,28));ui.gap(waiting,12);TextView message=ui.text("等待远端画面…",14,false);message.setTextColor(Color.WHITE);message.setGravity(Gravity.CENTER);waiting.addView(message);addView(waiting,new LayoutParams(-2,-2,Gravity.CENTER));
|
||||
orb=ui.iconButton("display","展开远程控制菜单",()->{if(menu==null)openMenu("controls");else closeMenu();});
|
||||
ImageView brand=new ImageView(context);brand.setImageResource(R.drawable.mobile_brand);brand.setScaleType(ImageView.ScaleType.CENTER_CROP);brand.setBackground(ui.background(Color.WHITE,23));brand.setClipToOutline(true);brand.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
|
||||
((FrameLayout)orb).removeAllViews();((FrameLayout)orb).addView(brand,new LayoutParams(ui.dp(46),ui.dp(46),Gravity.CENTER));
|
||||
orb.setBackground(ui.background(0xFFF5F5F7,27));orb.setElevation(ui.dp(7));addView(orb,new LayoutParams(ui.dp(54),ui.dp(54)));
|
||||
drag(orb,orb,()->{if(menu==null)openMenu("controls");else closeMenu();});
|
||||
}
|
||||
void setRelative(boolean value){relative=value;if(menu!=null&&menuPage.equals("controls"))openMenu("controls");}
|
||||
void attachMouseBar(FrameLayout host, VirtualMouseBar bar) {
|
||||
mouseHost=host;mouseBar=bar;
|
||||
// A direct, tightly bounded sibling of the video is essential: otherwise
|
||||
// an existing touch in this full-screen controls container captures the
|
||||
// second finger before Android can dispatch it to the remote surface.
|
||||
host.addView(bar,new FrameLayout.LayoutParams(ui.dp(140),ui.dp(48)));
|
||||
bar.setVisibility(GONE);
|
||||
}
|
||||
void cancelMouseInput(){if(mouseBar!=null)mouseBar.cancelInput();}
|
||||
void setPictureInPicture(boolean value){
|
||||
pictureInPicture=value;
|
||||
if(value){cancelMouseInput();closeMenu();closeKeyboard();modifiers.clear();}
|
||||
setVisibility(value?GONE:VISIBLE);positionMouse();
|
||||
}
|
||||
private void toggleMouse(){cancelMouseInput();mouseVisible=!mouseVisible;closeMenu();positionMouse();}
|
||||
private void positionMouse(){
|
||||
if(mouseBar==null)return;
|
||||
boolean visible=!pictureInPicture&&mouseVisible&&menu==null&&waiting.getVisibility()==GONE;
|
||||
if(!visible){if(mouseBar.getVisibility()==VISIBLE)cancelMouseInput();mouseBar.setVisibility(GONE);return;}
|
||||
int[] location=new int[2],hostLocation=new int[2];getLocationOnScreen(location);mouseHost.getLocationOnScreen(hostLocation);
|
||||
float width=ui.dp(140),height=ui.dp(48),gap=ui.dp(6),margin=ui.dp(8);
|
||||
float x=orb.getX()>=width+gap+margin?orb.getX()-gap-width:orb.getX()+orb.getWidth()+gap;
|
||||
float y=orb.getY()+(orb.getHeight()-height)/2;
|
||||
// When the orb is near the middle of a narrow phone, use the adjacent
|
||||
// row rather than letting the two controls overlap.
|
||||
if(x+width>getWidth()-margin){x=bound(orb.getX(),margin,getWidth()-width-margin);y=orb.getY()+orb.getHeight()+gap;if(y+height>getHeight()-margin)y=orb.getY()-gap-height;}
|
||||
if(keyboard!=null&&x<keyboard.getX()+keyboard.getWidth()&&x+width>keyboard.getX()&&y<keyboard.getY()+keyboard.getHeight()&&y+height>keyboard.getY()){
|
||||
y=keyboard.getY()-gap-height;if(y<margin)y=keyboard.getY()+keyboard.getHeight()+gap;
|
||||
}
|
||||
mouseBar.setX(location[0]-hostLocation[0]+bound(x,margin,getWidth()-width-margin));
|
||||
mouseBar.setY(location[1]-hostLocation[1]+bound(y,margin,getHeight()-height-margin));
|
||||
mouseBar.setVisibility(VISIBLE);
|
||||
}
|
||||
void setMuted(boolean value){muted=value;if(menu!=null&&menuPage.equals("controls"))openMenu("controls");}
|
||||
void videoSize(int width,int height){waiting.setVisibility(GONE);positionMouse();}
|
||||
void resetVideoStatistics(){statistics(new RemoteNetworkStatistics.Snapshot(network.report,0,0,0,Double.NaN,network.rtt));}
|
||||
void statistics(RemoteNetworkStatistics.Snapshot value){network=value;renderNetwork();}
|
||||
void videoSettings(RemoteVideoSettings value){settings=value;renderVideoSettings();}
|
||||
void fileStatus(String status,boolean received){transferStatus=status;hasReceivedFile=received;renderFileStatus();}
|
||||
private void renderFileStatus(){
|
||||
if(transferLabel!=null){transferLabel.setText(transferStatus);transferLabel.setVisibility(transferStatus.isEmpty()?GONE:VISIBLE);}
|
||||
if(saveFileButton!=null)saveFileButton.setVisibility(hasReceivedFile?VISIBLE:GONE);
|
||||
}
|
||||
private void closeMenu(){if(menu!=null){removeView(menu);menu=null;menuScroll=null;}if(shield!=null){removeView(shield);shield=null;}networkLabel=videoFeedback=transferLabel=saveFileButton=null;trafficCells=null;trafficRows=null;networkDetails=null;encryptionLock=encryptionOpen=null;settingRows.clear();orb.setContentDescription("展开远程控制菜单");positionMouse();}
|
||||
private void openMenu(String page){
|
||||
cancelMouseInput();
|
||||
closeMenu();menuPage=page;shield=new View(getContext());shield.setOnClickListener(v->closeMenu());addView(shield,new LayoutParams(-1,-1));
|
||||
menu=ui.column();menu.setPadding(ui.dp(12),ui.dp(12),ui.dp(12),ui.dp(12));ui.card(menu,18);menu.setElevation(ui.dp(12));
|
||||
LinearLayout header=ui.row();
|
||||
if(!page.equals("controls"))header.addView(ui.iconButton("back","返回控制栏",()->openMenu("controls")),ui.size(28,32));
|
||||
LinearLayout titles=ui.column();TextView title=ui.text(page.equals("controls")?"● 已连接":page.equals("video")?"画面设置":"网络状态",14,true);titles.addView(title);
|
||||
if(page.equals("controls")){ui.gap(titles,3);networkLabel=ui.text(network.summary(),10,false);networkLabel.setFontFeatureSettings("tnum");networkLabel.setTextColor(SECONDARY);titles.addView(networkLabel);}header.addView(titles,new LinearLayout.LayoutParams(0,-2,1));header.addView(ui.iconButton("close","关闭控制栏",this::closeMenu),ui.size(30,32));menu.addView(header);ui.gap(menu,9);
|
||||
if(page.equals("video")){videoFeedback=ui.text("",12,false);videoFeedback.setTextColor(SECONDARY);videoFeedback.setPadding(0,0,0,ui.dp(9));menu.addView(videoFeedback);}
|
||||
ScrollView scroll=new ScrollView(getContext());menuScroll=scroll;menu.addView(scroll,new LinearLayout.LayoutParams(-1,0,1));LinearLayout body=ui.column();scroll.addView(body);
|
||||
if(page.equals("network")){
|
||||
// Reserve the scrollbar's width plus a gap before right-aligned statistics.
|
||||
scroll.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);body.setPadding(0,0,ui.dp(6),0);
|
||||
}
|
||||
if(page.equals("controls")){
|
||||
String[] labels={"键盘",relative?"相对鼠标":"绝对鼠标",mouseVisible?"收起鼠标":"虚拟鼠标","显示器","画面设置",muted?"静音":"声音","发送文件","网络状态","Ctrl+Alt+Del","剪贴板"};
|
||||
String[] icons={"keyboard","mouse","mouse","display","sliders","audio","folder","chart","lock","clipboard"};
|
||||
Runnable[] clicks={()->{closeMenu();toggleKeyboard();},actions::mouse,this::toggleMouse,actions::display,()->openMenu("video"),actions::mute,actions::sendFile,()->openMenu("network"),actions::secureAttention,actions::clipboard};
|
||||
menuColumns=controlColumns();
|
||||
for(int row=0;row<(labels.length+menuColumns-1)/menuColumns;row++){LinearLayout line=ui.row();for(int col=0;col<menuColumns;col++){int index=row*menuColumns+col;if(index>=labels.length){View spacer=new View(getContext());LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(0,ui.dp(52),1);if(col>0)p.leftMargin=ui.dp(7);line.addView(spacer,p);continue;}LinearLayout control=ui.column();control.setGravity(Gravity.CENTER);control.setBackground(ui.background(0xFFF0F0F2,10));control.addView(ui.icon(icons[index],INK),ui.size(19,19));ui.gap(control,4);TextView caption=ui.text(labels[index],10,false);caption.setSingleLine();caption.setGravity(Gravity.CENTER);control.addView(caption);control.setContentDescription(labels[index]);control.setClickable(true);control.setFocusable(true);control.setOnClickListener(v->clicks[index].run());
|
||||
LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(0,ui.dp(52),1);if(col>0)p.leftMargin=ui.dp(7);line.addView(control,p);
|
||||
}body.addView(line);if((row+1)*menuColumns<labels.length)ui.gap(body,7);}
|
||||
ui.gap(body,7);transferLabel=ui.text(transferStatus,11,false);transferLabel.setTextColor(SECONDARY);transferLabel.setAccessibilityLiveRegion(ACCESSIBILITY_LIVE_REGION_POLITE);body.addView(transferLabel);
|
||||
saveFileButton=ui.action("保存收到的文件",BLUE,actions::saveFile);body.addView(saveFileButton);renderFileStatus();
|
||||
}else if(page.equals("network")){
|
||||
networkPage(body);
|
||||
}else{
|
||||
settingRows.add(new SettingRow(body,0,"画面质量",new String[]{"低","中","高"},new int[]{0,1,2}));ui.gap(body,12);
|
||||
settingRows.add(new SettingRow(body,1,"画面采集帧率",new String[]{"30 fps","60 fps"},new int[]{30,60}));ui.gap(body,12);
|
||||
settingRows.add(new SettingRow(body,2,"画面偏好",RemoteVideoSettings.PREFERENCES,new int[]{0,1,2}));renderVideoSettings();
|
||||
}
|
||||
ui.gap(menu,9);TextView disconnect=ui.action("断开连接",Color.WHITE,()->{closeMenu();closeKeyboard();actions.disconnect();});disconnect.setMinHeight(ui.dp(34));disconnect.setTextSize(14);disconnect.setBackground(ui.background(RED,8));menu.addView(disconnect,ui.size(-1,34));
|
||||
addView(menu,new LayoutParams(panelWidth(getWidth()),panelHeight(getHeight())));orb.bringToFront();orb.setContentDescription("收起远程控制菜单");
|
||||
positionMouse();
|
||||
}
|
||||
private final class SettingRow {
|
||||
final int field;final int[] values;final SegmentedControl group;
|
||||
SettingRow(LinearLayout body,int field,String title,String[] labels,int[] values){
|
||||
this.field=field;this.values=values;
|
||||
TextView label=ui.text(title,12,false);label.setTextColor(SECONDARY);body.addView(label);ui.gap(body,5);
|
||||
group=new SegmentedControl(ui,labels,selectionIndex(),settings.supported,index->actions.videoSettings(field,values[index]));
|
||||
group.setPadding(ui.dp(2),ui.dp(2),ui.dp(2),ui.dp(2));body.addView(group);
|
||||
for(int i=0;i<labels.length;i++){
|
||||
TextView button=(TextView)group.getChildAt(i);button.setTextSize(12);button.setMinHeight(ui.dp(28));button.setSingleLine();button.setContentDescription(title+","+labels[i]);
|
||||
button.setLayoutParams(new LinearLayout.LayoutParams(0,ui.dp(28),1));
|
||||
}
|
||||
}
|
||||
int selectionIndex(){int selected=field==0?settings.selection.quality:field==1?settings.selection.frameRate:settings.selection.preference;
|
||||
for(int i=0;i<values.length;i++)if(values[i]==selected)return i;return 0;
|
||||
}
|
||||
void render(){group.setSelection(selectionIndex());group.setOptionsEnabled(settings.supported);}
|
||||
}
|
||||
private void renderVideoSettings(){
|
||||
if(videoFeedback!=null){String feedback=settings.feedback();videoFeedback.setText(feedback);videoFeedback.setVisibility(feedback.isEmpty()?GONE:VISIBLE);}
|
||||
for(SettingRow row:settingRows)row.render();
|
||||
}
|
||||
private void networkPage(LinearLayout body){
|
||||
trafficCells=new TextView[4][3];trafficRows=new LinearLayout[4];String[] names={"视频","音频","数据","合计"};
|
||||
LinearLayout heading=trafficRow(body,"",new TextView[3],false);((TextView)heading.getChildAt(1)).setText("接收");((TextView)heading.getChildAt(2)).setText("发送");((TextView)heading.getChildAt(3)).setText("丢包率");
|
||||
for(int i=0;i<heading.getChildCount();i++)((TextView)heading.getChildAt(i)).setTextColor(SECONDARY);
|
||||
for(int i=0;i<4;i++)trafficRows[i]=trafficRow(body,names[i],trafficCells[i],i==3);
|
||||
ui.gap(body,10);ui.divider(body);ui.gap(body,10);
|
||||
String[] titles={"帧率","分辨率","画面延时","连接延时(RTT)","连接方式","媒体加密"};networkDetails=new TextView[titles.length];
|
||||
for(int i=0;i<titles.length;i++){LinearLayout row=ui.row();TextView title=ui.text(titles[i],12,false);title.setTextColor(SECONDARY);row.addView(title,new LinearLayout.LayoutParams(0,-2,1));
|
||||
if(i==5){encryptionLock=ui.icon("lock",GREEN);encryptionOpen=ui.icon("unlock",SECONDARY);for(View icon:new View[]{encryptionLock,encryptionOpen}){LinearLayout.LayoutParams p=ui.size(14,14);p.rightMargin=ui.dp(4);row.addView(icon,p);}}
|
||||
TextView value=ui.text("—",12,false);value.setFontFeatureSettings("tnum");row.addView(value);networkDetails[i]=value;body.addView(row);if(i<titles.length-1)ui.gap(body,7);}
|
||||
renderNetwork();
|
||||
}
|
||||
private LinearLayout trafficRow(LinearLayout body,String title,TextView[] cells,boolean total){
|
||||
LinearLayout row=ui.row();row.setPadding(ui.dp(4),ui.dp(5),ui.dp(4),ui.dp(5));body.addView(row);if(total)row.setBackground(ui.background(0x122E7ADB,5));
|
||||
TextView label=ui.text(title,11,total);row.addView(label,ui.size(28,-2));
|
||||
for(int i=0;i<3;i++){TextView cell=ui.text("—",11,total);cell.setGravity(Gravity.END);cell.setSingleLine();cell.setFontFeatureSettings("tnum");cell.setAutoSizeTextTypeUniformWithConfiguration(8,11,1,android.util.TypedValue.COMPLEX_UNIT_SP);
|
||||
LinearLayout.LayoutParams p=i==2?ui.size(46,16):new LinearLayout.LayoutParams(0,ui.dp(16),1);p.leftMargin=ui.dp(4);row.addView(cell,p);cells[i]=cell;}
|
||||
return row;
|
||||
}
|
||||
private void renderNetwork(){
|
||||
if(networkLabel!=null)networkLabel.setText(network.summary());
|
||||
if(trafficCells==null)return;
|
||||
String[] names={"视频","音频","数据","合计"};
|
||||
for(int i=0;i<4;i++){
|
||||
RemoteNetworkStatistics.Traffic traffic=network.report==null?null:network.report.traffic[i];
|
||||
String in=RemoteNetworkStatistics.bitrate(traffic==null?-1:traffic.inbound),out=RemoteNetworkStatistics.bitrate(traffic==null?-1:traffic.outbound),loss=RemoteNetworkStatistics.loss(traffic==null?Double.NaN:traffic.loss);
|
||||
trafficCells[i][0].setText(in);trafficCells[i][1].setText(out);trafficCells[i][2].setText(loss);trafficRows[i].setContentDescription(names[i]+",接收 "+in+",发送 "+out+",丢包率 "+loss);
|
||||
}
|
||||
String[] values={network.fps+" FPS",network.resolution(),RemoteNetworkStatistics.latency(network.latency),RemoteNetworkStatistics.latency(network.rtt),network.mode(),network.report==null?"—":network.report.srtp?"SRTP 已启用":"未启用"};
|
||||
for(int i=0;i<values.length;i++)networkDetails[i].setText(values[i]);networkDetails[5].setTextColor(network.report!=null&&network.report.srtp?GREEN:SECONDARY);
|
||||
encryptionLock.setVisibility(network.report!=null&&network.report.srtp?VISIBLE:GONE);encryptionOpen.setVisibility(network.report!=null&&!network.report.srtp?VISIBLE:GONE);
|
||||
}
|
||||
private int controlColumns(){return getMeasuredHeight()<ui.dp(400)&&getMeasuredWidth()>=ui.dp(400)?4:3;}
|
||||
private int panelWidth(int width){return Math.max(1,Math.min(width-ui.dp(16),controlColumns()==4?ui.dp(380):Math.max(ui.dp(280),Math.min(ui.dp(340),width-ui.dp(160)))));}
|
||||
private int panelHeight(int height){
|
||||
// First measure every row at its natural height, then cap only to the
|
||||
// safe viewport. The weighted ScrollView takes any remaining space.
|
||||
LinearLayout.LayoutParams scrollParams=(LinearLayout.LayoutParams)menuScroll.getLayoutParams();
|
||||
scrollParams.height=LayoutParams.WRAP_CONTENT;scrollParams.weight=0;
|
||||
menu.measure(MeasureSpec.makeMeasureSpec(panelWidth(getMeasuredWidth()),MeasureSpec.EXACTLY),
|
||||
MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED));
|
||||
int contentHeight=menu.getMeasuredHeight();
|
||||
scrollParams.height=0;scrollParams.weight=1;
|
||||
menu.forceLayout();menuScroll.forceLayout();
|
||||
return Math.min(contentHeight,Math.max(1,height-ui.dp(16)));
|
||||
}
|
||||
private void positionMenu(){if(menu==null)return;float ox=orb.getX()+orb.getWidth()/2f;float x=ox>getWidth()/2f?orb.getX()-ui.dp(12)-menu.getWidth():orb.getX()+orb.getWidth()+ui.dp(12);menu.setX(bound(x,ui.dp(8),getWidth()-menu.getWidth()-ui.dp(8)));menu.setY(bound(orb.getY(),ui.dp(8),getHeight()-menu.getHeight()-ui.dp(8)));}
|
||||
private int keyboardWidth(int width){return Math.min(ui.dp(computerKeyboard?520:440),Math.max(1,width-ui.dp(16)));}
|
||||
private int keyboardHeight(int height){return Math.min(keyboardPreferredHeight,Math.max(1,height-ui.dp(16)));}
|
||||
private void positionKeyboard(){if(keyboard!=null){keyboard.setX(bound(keyboard.getX(),ui.dp(8),getWidth()-keyboard.getWidth()-ui.dp(8)));keyboard.setY(bound(keyboard.getY(),ui.dp(8),getHeight()-keyboard.getHeight()-ui.dp(8)));}positionMouse();}
|
||||
private void closeKeyboard(){if(keyboard!=null){removeView(keyboard);keyboard=null;keyboardKeys=null;}}
|
||||
private void toggleKeyboard(){if(keyboard!=null){closeKeyboard();modifiers.clear();return;}modifiers.clear();showKeyboard();}
|
||||
private void showKeyboard(){
|
||||
float oldX=keyboard==null?-1:keyboard.getX(),oldY=keyboard==null?-1:keyboard.getY();int oldScroll=keyboardKeys==null?0:keyboardKeys.getScrollY();closeKeyboard();keyboard=ui.column();keyboard.setPadding(ui.dp(5),ui.dp(5),ui.dp(5),ui.dp(5));keyboard.setBackground(ui.background(0xFFD1D6DE,12));keyboard.setElevation(ui.dp(10));
|
||||
LinearLayout top=ui.row();TextView handle=ui.text("━",19,true);handle.setGravity(Gravity.CENTER);handle.setTextColor(SECONDARY);handle.setContentDescription("拖动键盘");top.addView(handle,new LinearLayout.LayoutParams(0,ui.dp(28),1));top.addView(ui.iconButton("close","收起键盘",this::closeKeyboard),ui.size(30,28));keyboard.addView(top);drag(handle,keyboard,()->{});
|
||||
// Keep the drag/close row fixed while short split windows can scroll every key into view.
|
||||
keyboardKeys=new ScrollView(getContext());keyboard.addView(keyboardKeys,new LinearLayout.LayoutParams(-1,0,1));LinearLayout keys=ui.column();keyboardKeys.addView(keys);
|
||||
String[][] rows=computerKeyboard?new String[][]{{"Esc","F1","F2","F3","F4","F5","F6"},{"Tab","Ctrl","Alt","Win","↑","⌫"},{"复制","粘贴","全选","←","↓","→"},{"ABC","空格","Enter"}}:new String[][]{{"1","2","3","4","5","6","7","8","9","0"},{"q","w","e","r","t","y","u","i","o","p"},{"a","s","d","f","g","h","j","k","l"},{"⇧","z","x","c","v","b","n","m","⌫"},{"电脑","剪贴板","空格",".","Enter"}};
|
||||
for(String[] values:rows){LinearLayout line=ui.row();for(String value:values){String shown=shift&&value.length()==1?value.toUpperCase(java.util.Locale.ROOT):value;TextView key=ui.action(shown,INK,()->keyboardKey(value));key.setTextSize(value.length()>2?11:14);key.setMinHeight(ui.dp(31));int modifier=value.equals("Ctrl")?17:value.equals("Alt")?18:value.equals("Win")?91:0;key.setBackground(ui.background(modifiers.contains(modifier)?0xFF9BC7F7:value.length()>1||value.equals("⇧")?0xFFAFB8C5:Color.WHITE,5));LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(0,ui.dp(31),value.equals("空格")?3:1);p.setMargins(ui.dp(1.5f),0,ui.dp(1.5f),0);line.addView(key,p);}keys.addView(line);ui.gap(keys,3);}
|
||||
keyboardPreferredHeight=ui.dp(5)*2+ui.dp(28)+rows.length*(ui.dp(31)+ui.dp(3));
|
||||
addView(keyboard,new LayoutParams(keyboardWidth(getWidth()),keyboardHeight(getHeight())));LinearLayout shownKeyboard=keyboard;ScrollView shownKeys=keyboardKeys;
|
||||
keyboard.post(()->{if(keyboard==shownKeyboard){keyboard.setX(oldX<0?(getWidth()-keyboard.getWidth())/2f:oldX);keyboard.setY(oldY<0?getHeight()-keyboard.getHeight()-ui.dp(20):oldY);shownKeys.scrollTo(0,oldScroll);constrainPanels();}});
|
||||
}
|
||||
private void keyboardKey(String value){
|
||||
switch(value){
|
||||
case "⇧":shift=!shift;showKeyboard();return;
|
||||
case "电脑":computerKeyboard=true;showKeyboard();return;
|
||||
case "ABC":computerKeyboard=false;showKeyboard();return;
|
||||
case "剪贴板":actions.clipboard();return;
|
||||
case "复制":actions.shortcut(0x43);return;case "粘贴":actions.shortcut(0x56);return;case "全选":actions.shortcut(0x41);return;
|
||||
case "空格":sendKey(32);return;case "⌫":sendKey(8);return;case "Enter":sendKey(13);return;case "Esc":sendKey(27);return;case "Tab":sendKey(9);return;
|
||||
case "↑":sendKey(38);return;case "↓":sendKey(40);return;case "←":sendKey(37);return;case "→":sendKey(39);return;
|
||||
// Latch locally; the next key sends a complete chord without leaving remote modifiers down.
|
||||
case "Ctrl":toggleModifier(17);return;case "Alt":toggleModifier(18);return;case "Win":toggleModifier(91);return;
|
||||
default:if(value.matches("F[1-6]")){sendKey(111+Integer.parseInt(value.substring(1)));return;}if(!modifiers.isEmpty())sendKey(KeyMap.ascii(value.charAt(0))&255);else actions.text(shift?value.toUpperCase(java.util.Locale.ROOT):value);
|
||||
}
|
||||
}
|
||||
private void toggleModifier(int code){if(!modifiers.add(code))modifiers.remove(code);showKeyboard();}
|
||||
private void sendKey(int code){if(modifiers.isEmpty())actions.key(code);else{actions.chord(code,modifiers.stream().mapToInt(Integer::intValue).toArray());modifiers.clear();showKeyboard();}}
|
||||
@android.annotation.SuppressLint("ClickableViewAccessibility") // Tap dispatches performClick; dragging is an additional action.
|
||||
private void drag(View handle,View target,Runnable tap){
|
||||
handle.setOnClickListener(v->tap.run());handle.setOnTouchListener(new View.OnTouchListener(){float startX,startY,originX,originY;boolean moved;
|
||||
public boolean onTouch(View v,MotionEvent event){
|
||||
switch(event.getActionMasked()){
|
||||
case MotionEvent.ACTION_DOWN:if(target==orb)cancelMouseInput();startX=event.getRawX();startY=event.getRawY();originX=target.getX();originY=target.getY();moved=false;return true;
|
||||
case MotionEvent.ACTION_MOVE:float dx=event.getRawX()-startX,dy=event.getRawY()-startY;if(Math.hypot(dx,dy)>ui.dp(4))moved=true;if(moved){if(target==orb)closeMenu();target.setX(bound(originX+dx,ui.dp(8),getWidth()-target.getWidth()-ui.dp(8)));target.setY(bound(originY+dy,ui.dp(8),getHeight()-target.getHeight()-ui.dp(8)));positionMouse();}return true;
|
||||
case MotionEvent.ACTION_UP:if(!moved)v.performClick();return true;
|
||||
case MotionEvent.ACTION_CANCEL:return true;
|
||||
default:return false;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
void constrainPanels(){
|
||||
cancelMouseInput();
|
||||
if(menu!=null&&menuPage.equals("controls")&&menuColumns!=controlColumns())openMenu("controls");
|
||||
orb.setX(bound(orb.getX(),ui.dp(8),getWidth()-orb.getWidth()-ui.dp(8)));orb.setY(bound(orb.getY(),ui.dp(8),getHeight()-orb.getHeight()-ui.dp(8)));
|
||||
if(menu!=null||keyboard!=null)requestLayout();
|
||||
positionKeyboard();
|
||||
positionMouse();
|
||||
}
|
||||
@Override protected void onMeasure(int widthSpec,int heightSpec){
|
||||
super.onMeasure(widthSpec,heightSpec);
|
||||
boolean resized=false;
|
||||
if(menu!=null){
|
||||
// Use this traversal's viewport, including rotation/inset changes, before drawing.
|
||||
ViewGroup.LayoutParams p=menu.getLayoutParams();int width=panelWidth(getMeasuredWidth()),height=panelHeight(getMeasuredHeight());
|
||||
// panelHeight performed an unconstrained measurement; always
|
||||
// measure again with the final cap, even when it did not change.
|
||||
p.width=width;p.height=height;resized=true;
|
||||
}
|
||||
if(keyboard!=null){
|
||||
ViewGroup.LayoutParams p=keyboard.getLayoutParams();int width=keyboardWidth(getMeasuredWidth()),height=keyboardHeight(getMeasuredHeight());
|
||||
if(p.width!=width||p.height!=height){p.width=width;p.height=height;resized=true;}
|
||||
}
|
||||
if(resized)super.onMeasure(widthSpec,heightSpec);
|
||||
}
|
||||
@Override protected void onLayout(boolean changed,int left,int top,int right,int bottom){
|
||||
super.onLayout(changed,left,top,right,bottom);
|
||||
if(!orbPositioned){orb.setX(Math.max(ui.dp(12),getWidth()-ui.dp(66)));orb.setY(ui.dp(17));orbPositioned=true;}
|
||||
orb.setX(bound(orb.getX(),ui.dp(8),getWidth()-orb.getWidth()-ui.dp(8)));orb.setY(bound(orb.getY(),ui.dp(8),getHeight()-orb.getHeight()-ui.dp(8)));
|
||||
// New/rebuilt menus have real dimensions now; position them in the same frame.
|
||||
positionMenu();
|
||||
positionKeyboard();
|
||||
positionMouse();
|
||||
}
|
||||
@Override protected void onDetachedFromWindow(){cancelMouseInput();super.onDetachedFromWindow();}
|
||||
@Override protected void onSizeChanged(int width,int height,int oldWidth,int oldHeight){super.onSizeChanged(width,height,oldWidth,oldHeight);post(this::constrainPanels);}
|
||||
private static float bound(float value,float min,float max){return Math.max(min,Math.min(value,Math.max(min,max)));}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.Context;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.provider.OpenableColumns;
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/** Private session files; document-provider reads/writes never run on UI/RTC threads. */
|
||||
final class SessionDocuments {
|
||||
interface Prepared { void ready(File file,String name); void failed(); }
|
||||
private final Context context;
|
||||
private final ExecutorService io=Executors.newSingleThreadExecutor(r->new Thread(r,"CrossDesk documents"));
|
||||
final File directory;
|
||||
private volatile boolean closed;
|
||||
SessionDocuments(Context context){
|
||||
this.context=context.getApplicationContext();
|
||||
directory=new File(context.getCacheDir(),"transfers/"+UUID.randomUUID());
|
||||
}
|
||||
void prepare(Uri uri,Prepared callback){
|
||||
io.execute(()->{
|
||||
File staged=null;
|
||||
try{
|
||||
if(closed)return;
|
||||
String name="file";
|
||||
try(Cursor cursor=context.getContentResolver().query(uri,new String[]{OpenableColumns.DISPLAY_NAME},null,null,null)){
|
||||
if(cursor!=null&&cursor.moveToFirst())name=cursor.getString(0);
|
||||
}
|
||||
name=safeName(name);
|
||||
Files.createDirectories(directory.toPath());
|
||||
staged=File.createTempFile("sending-",".part",directory);
|
||||
try(InputStream input=context.getContentResolver().openInputStream(uri);OutputStream output=new FileOutputStream(staged)){
|
||||
if(input==null)throw new IOException("No input");
|
||||
copy(input,output);
|
||||
}
|
||||
if(closed){Files.deleteIfExists(staged.toPath());return;}
|
||||
callback.ready(staged,name);
|
||||
}catch(Exception error){
|
||||
if(staged!=null)staged.delete();
|
||||
if(!closed)callback.failed();
|
||||
}
|
||||
});
|
||||
}
|
||||
void save(File file,Uri uri,java.util.function.Consumer<Boolean> completion){
|
||||
io.execute(()->{
|
||||
boolean success=false;
|
||||
try{
|
||||
if(closed)return;
|
||||
try(InputStream input=new FileInputStream(file);OutputStream output=context.getContentResolver().openOutputStream(uri,"wt")){
|
||||
if(output==null)throw new IOException("No output");
|
||||
copy(input,output);
|
||||
}
|
||||
success=true;
|
||||
}catch(Exception ignored){ }
|
||||
if(!closed)completion.accept(success);
|
||||
});
|
||||
}
|
||||
private void copy(InputStream input,OutputStream output)throws IOException{
|
||||
byte[] bytes=new byte[64*1024];int count;
|
||||
while((count=input.read(bytes))!=-1){if(closed)throw new IOException("Session closed");output.write(bytes,0,count);}
|
||||
}
|
||||
static String safeName(String value){
|
||||
if(value==null)return "file";
|
||||
value=value.replace('\\','/');value=value.substring(value.lastIndexOf('/')+1).replaceAll("[\\p{Cntrl}:]","_");
|
||||
return value.isEmpty()||value.equals(".")||value.equals("..")||value.getBytes(StandardCharsets.UTF_8).length>240?"file":value;
|
||||
}
|
||||
// Called after native file handles have closed. Queue cleanup behind any provider I/O.
|
||||
void close(){closed=true;io.execute(()->remove(directory));io.shutdown();}
|
||||
private static void remove(File file){File[] children=file.listFiles();if(children!=null)for(File child:children)remove(child);file.delete();}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Path;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.drawable.GradientDrawable;
|
||||
import android.graphics.drawable.InsetDrawable;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.TextView;
|
||||
|
||||
/** A 140 × 48 dp bar. Touch ownership continues outside the original key bounds. */
|
||||
@SuppressLint("ViewConstructor")
|
||||
final class VirtualMouseBar extends LinearLayout {
|
||||
private final RemoteMouseInput input;
|
||||
private final MobileUi ui;
|
||||
private final TextView[] keys = new TextView[3];
|
||||
private int generation;
|
||||
|
||||
VirtualMouseBar(MobileUi ui, RemoteMouseInput input) {
|
||||
super(ui.context); this.ui = ui; this.input = input;
|
||||
setOrientation(HORIZONTAL);
|
||||
setPadding(ui.dp(4), ui.dp(2), ui.dp(4), ui.dp(2));
|
||||
GradientDrawable shell = ui.background(Color.WHITE, 18);
|
||||
shell.setStroke(ui.dp(.5f), 0xFFD4DAE2);
|
||||
setBackground(shell);
|
||||
setMotionEventSplittingEnabled(true);
|
||||
keys[0] = key("鼠标左键,按住并拖动,松开结束拖拽", 0);
|
||||
keys[1] = key("鼠标滚轮,上下滑动,可滑出按键范围", 1);
|
||||
keys[2] = key("鼠标右键,按住并拖动,松开结束拖拽", 2);
|
||||
input.didCancel = this::resetTouches;
|
||||
setContentDescription("虚拟鼠标");
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility") // Touch sends real down/up; performClick serves accessibility only.
|
||||
private TextView key(String description, int index) {
|
||||
TextView key = index == 1 ? new WheelKey(ui) : new TextView(ui.context);
|
||||
key.setGravity(android.view.Gravity.CENTER);
|
||||
key.setContentDescription(description);
|
||||
key.setClickable(true); key.setFocusable(true);
|
||||
highlight(key, index, false);
|
||||
addView(key, new LayoutParams(0, ui.dp(44), 1));
|
||||
key.setOnClickListener(v -> {
|
||||
if (index == 1) { ((WheelKey)key).advance(ui.dp(10)); input.scroll(-1); }
|
||||
else { input.virtualButton(index == 0, true); input.virtualButton(index == 0, false); }
|
||||
});
|
||||
if (index == 1) {
|
||||
key.setAccessibilityDelegate(new View.AccessibilityDelegate() {
|
||||
@Override public void onInitializeAccessibilityNodeInfo(View host, android.view.accessibility.AccessibilityNodeInfo info) {
|
||||
super.onInitializeAccessibilityNodeInfo(host, info);
|
||||
info.setScrollable(true);
|
||||
info.addAction(android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD);
|
||||
info.addAction(android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD);
|
||||
}
|
||||
@Override public boolean performAccessibilityAction(View host, int action, android.os.Bundle args) {
|
||||
if (action == android.view.accessibility.AccessibilityNodeInfo.ACTION_SCROLL_FORWARD || action == android.view.accessibility.AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD) {
|
||||
int direction = action == android.view.accessibility.AccessibilityNodeInfo.ACTION_SCROLL_FORWARD ? -1 : 1;
|
||||
((WheelKey)key).advance(-direction * ui.dp(10));
|
||||
input.scroll(direction); return true;
|
||||
}
|
||||
return super.performAccessibilityAction(host, action, args);
|
||||
}
|
||||
});
|
||||
}
|
||||
key.setOnTouchListener(new View.OnTouchListener() {
|
||||
int pointer = -1, startedGeneration;
|
||||
float lastX, lastY, remainder;
|
||||
@Override public boolean onTouch(View v, MotionEvent event) {
|
||||
int action = event.getActionMasked();
|
||||
if (action == MotionEvent.ACTION_DOWN) {
|
||||
pointer = event.getPointerId(0); startedGeneration = generation;
|
||||
lastX = event.getX(); lastY = event.getY(); remainder = 0;
|
||||
highlight(key, index, true);
|
||||
if (index != 1) input.virtualButton(index == 0, true);
|
||||
return true;
|
||||
}
|
||||
if (startedGeneration != generation || pointer == -1) return true;
|
||||
if (action == MotionEvent.ACTION_MOVE) {
|
||||
int p = event.findPointerIndex(pointer);
|
||||
if (p < 0) return true;
|
||||
float dx = event.getX(p) - lastX, dy = event.getY(p) - lastY;
|
||||
lastX = event.getX(p); lastY = event.getY(p);
|
||||
if (index != 1) { input.drag(dx, dy); return true; }
|
||||
((WheelKey)key).advance(dy);
|
||||
remainder += dy;
|
||||
float step = ui.dp(10);
|
||||
int ticks = (int)(remainder / step);
|
||||
// Positive protocol wheel values scroll up; finger-down scrolls down.
|
||||
for (int i = 0; i < Math.min(Math.abs(ticks), 32); i++) input.scroll(ticks > 0 ? -1 : 1);
|
||||
remainder -= ticks * step;
|
||||
}
|
||||
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL ||
|
||||
(action == MotionEvent.ACTION_POINTER_UP && event.getPointerId(event.getActionIndex()) == pointer)) {
|
||||
if (index != 1) input.virtualButton(index == 0, false);
|
||||
pointer = -1; remainder = 0; highlight(key, index, false);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
return key;
|
||||
}
|
||||
private void highlight(TextView key, int index, boolean pressed) {
|
||||
key.setPressed(pressed);
|
||||
key.setTextColor(pressed ? Color.WHITE : 0xB8303640);
|
||||
// Narrow only the wheel's visible face; its 44 × 44 dp target remains.
|
||||
GradientDrawable face = ui.background(pressed ? MobileUi.BLUE : 0xFFEDF0F4, 6);
|
||||
float left = ui.dp(index == 0 ? 14 : 6), right = ui.dp(index == 2 ? 14 : 6);
|
||||
face.setCornerRadii(new float[]{left,left,right,right,right,right,left,left});
|
||||
int horizontal = ui.dp(index == 1 ? 13 : 1), vertical = ui.dp(index == 1 ? 7 : 2);
|
||||
key.setBackground(new InsetDrawable(face, horizontal, vertical, horizontal, vertical));
|
||||
}
|
||||
void cancelInput() {
|
||||
input.releaseAll();
|
||||
}
|
||||
private void resetTouches() {
|
||||
generation++;
|
||||
for (int i=0;i<keys.length;i++) if (keys[i] != null) highlight(keys[i], i, false);
|
||||
}
|
||||
/** Flat, uniformly colored treads follow the finger, wrapping every 5 dp. */
|
||||
private static final class WheelKey extends TextView {
|
||||
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final Path clip = new Path();
|
||||
private final float density;
|
||||
private float phase = 2;
|
||||
WheelKey(MobileUi ui) {
|
||||
super(ui.context); density = getResources().getDisplayMetrics().density;
|
||||
clip.addRoundRect(new RectF(0,0,12,24),2,2,Path.Direction.CW);
|
||||
}
|
||||
void advance(float distance) {
|
||||
phase = (phase + distance / density * .65f) % 5;
|
||||
invalidate();
|
||||
}
|
||||
@Override protected void onDraw(Canvas canvas) {
|
||||
super.onDraw(canvas);
|
||||
canvas.save();
|
||||
canvas.translate((getWidth()-12*density)/2f, (getHeight()-24*density)/2f);
|
||||
canvas.scale(density,density);
|
||||
canvas.clipPath(clip);
|
||||
paint.setColor(getCurrentTextColor());
|
||||
for (int i=-1;i<=6;i++) {
|
||||
float y=i*5+phase;
|
||||
canvas.drawRect(0,y,12,y+1.5f,paint);
|
||||
}
|
||||
canvas.restore();
|
||||
}
|
||||
}
|
||||
@Override protected void onDetachedFromWindow() { cancelInput(); super.onDetachedFromWindow(); }
|
||||
@Override public void onWindowFocusChanged(boolean focused) { super.onWindowFocusChanged(focused); if (!focused) cancelInput(); }
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 217 KiB |
@@ -0,0 +1,10 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="14dp"
|
||||
android:height="14dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="#FF248A3D"
|
||||
android:fillType="evenOdd"
|
||||
android:pathData="M12,2A10,10 0,1 0,12 22A10,10 0,1 0,12 2Z M6.5,11.5L10.3,15.3L17.5,8.1L16.1,6.7L10.3,12.5L7.9,10.1Z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,4 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M3,3h18v14h-8v3h4v2H7v-2h4v-3H3zM5,5v10h14V5z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,6 @@
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@android:color/white" />
|
||||
<foreground>
|
||||
<inset android:drawable="@drawable/mobile_brand" android:inset="16%" />
|
||||
</foreground>
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,9 @@
|
||||
<resources>
|
||||
<style name="AppTheme" parent="android:style/Theme.Material.Light.NoActionBar">
|
||||
<item name="android:fontFamily">sans</item>
|
||||
<item name="android:colorAccent">#2E7ADB</item>
|
||||
<item name="android:windowLightStatusBar">true</item>
|
||||
<item name="android:windowActionModeOverlay">true</item>
|
||||
<item name="android:windowBackground">#F2F2F7</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,14 @@
|
||||
<data-extraction-rules>
|
||||
<cloud-backup>
|
||||
<exclude domain="root" path="." />
|
||||
<exclude domain="sharedpref" path="." />
|
||||
<exclude domain="database" path="." />
|
||||
<exclude domain="file" path="." />
|
||||
</cloud-backup>
|
||||
<device-transfer>
|
||||
<exclude domain="root" path="." />
|
||||
<exclude domain="sharedpref" path="." />
|
||||
<exclude domain="database" path="." />
|
||||
<exclude domain="file" path="." />
|
||||
</device-transfer>
|
||||
</data-extraction-rules>
|
||||
@@ -0,0 +1 @@
|
||||
plugins { id 'com.android.application' version '9.1.0' apply false }
|
||||
@@ -0,0 +1,2 @@
|
||||
org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8
|
||||
android.useAndroidX=true
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,8 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip
|
||||
distributionSha256Sum=17f277867f6914d61b1aa02efab1ba7bb439ad652ca485cd8ca6842fccec6e43
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+93
@@ -0,0 +1,93 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1,24 @@
|
||||
CrossDesk 开源软件权利说明 / Open-source software rights
|
||||
|
||||
CrossDesk 按 GNU GPL 第 3 版发布,MiniRTC 按 GNU LGPL 第 3 版发布。
|
||||
其他组件适用各自列明的许可证。使用、复制、修改及再分发这些组件的权利,
|
||||
以相应许可证为准;本应用的普通使用条款不限制开源许可证授予你的权利。
|
||||
许可证中的保证、责任限制及其他条件仍然适用。
|
||||
|
||||
“本版本源码与构建说明”提供与发行版本对应的源码入口、子模块信息、
|
||||
依赖配方、补丁及构建说明。可以修改相关库后重新构建和链接应用。
|
||||
在自己的 Android 设备上运行修改版时,可以使用自己的 Android 签名密钥,
|
||||
并按构建文档生成和安装 APK。
|
||||
|
||||
CrossDesk is distributed under GNU GPL version 3; MiniRTC is distributed
|
||||
under GNU LGPL version 3. Other components are governed by their listed
|
||||
licenses. Your rights to use, copy, modify and redistribute those components
|
||||
are governed by the applicable licenses. The application's ordinary terms
|
||||
of use do not restrict rights granted by those open-source licenses.
|
||||
The licenses' warranty, liability and other provisions continue to apply.
|
||||
|
||||
The version-specific source and build links identify the application source,
|
||||
submodules, dependency recipes, patches and build instructions. You can
|
||||
modify the libraries and rebuild and relink the application. Running a
|
||||
modified build on your own Android device can use your own Android signing
|
||||
key. Build and install the APK as described in the build guide.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-02
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _CONTROLLER_PROTOCOL_H_
|
||||
#define _CONTROLLER_PROTOCOL_H_
|
||||
|
||||
#include <minirtc.h>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <remote_action.h>
|
||||
|
||||
namespace crossdesk::android_controller {
|
||||
inline std::string SecureAttentionMessage() {
|
||||
RemoteAction action{};
|
||||
action.type = service_command;
|
||||
action.c.flag = send_sas;
|
||||
return action.to_json();
|
||||
}
|
||||
inline std::string VideoSettingsMessage(int quality, int frame_rate, int preference,
|
||||
uint32_t request_id) {
|
||||
RemoteAction action{};
|
||||
action.type = video_settings;
|
||||
action.vs = {quality, frame_rate, preference, request_id, false};
|
||||
return action.to_json();
|
||||
}
|
||||
|
||||
inline nlohmann::json NetworkReport(const MiniRtcNetTrafficStats& stats, TraversalMode mode) {
|
||||
const auto traffic = [](const MiniRtcInboundStats& in, const MiniRtcOutboundStats& out) {
|
||||
return nlohmann::json{{"inbound", in.bitrate}, {"outbound", out.bitrate}, {"loss", in.loss_rate}};
|
||||
};
|
||||
return {{"rtt", stats.rtt_ms}, {"mode", mode}, {"srtp", stats.srtp_active},
|
||||
{"video", traffic(stats.video_inbound_stats, stats.video_outbound_stats)},
|
||||
{"audio", traffic(stats.audio_inbound_stats, stats.audio_outbound_stats)},
|
||||
{"data", traffic(stats.data_inbound_stats, stats.data_outbound_stats)},
|
||||
{"total", traffic(stats.total_inbound_stats, stats.total_outbound_stats)}};
|
||||
}
|
||||
} // namespace crossdesk::android_controller
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,271 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-09
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _FILE_TRANSFER_SESSION_H_
|
||||
#define _FILE_TRANSFER_SESSION_H_
|
||||
|
||||
#include <file_transfer_format.h>
|
||||
#include <stream_names.h>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
|
||||
namespace crossdesk::android_controller {
|
||||
|
||||
// File I/O is bounded to one chunk per pump. Feedback is delivered by MiniRTC
|
||||
// callback threads; no callback waits for the RTC executor or for a remote ACK.
|
||||
class FileTransferSession {
|
||||
public:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
using Send = std::function<int(const char*, const char*, size_t)>;
|
||||
using Progress = std::function<void(const std::string&, double, bool,
|
||||
const std::string&)>;
|
||||
FileTransferSession(Send send, Progress progress)
|
||||
: send_(std::move(send)), progress_(std::move(progress)) {}
|
||||
~FileTransferSession() {
|
||||
if (outgoing_) {
|
||||
outgoing_->input.close();
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(outgoing_->path, ec);
|
||||
}
|
||||
for (auto& entry : incoming_) Remove(entry.second);
|
||||
}
|
||||
|
||||
void SetDirectory(std::filesystem::path directory) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
directory_ = std::move(directory);
|
||||
}
|
||||
|
||||
bool Start(const std::filesystem::path& path, const std::string& name,
|
||||
Clock::time_point now = Clock::now()) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (outgoing_ || name.empty() || name.size() > UINT16_MAX) return false;
|
||||
std::error_code ec;
|
||||
if (!std::filesystem::is_regular_file(path, ec)) return false;
|
||||
const auto size = std::filesystem::file_size(path, ec);
|
||||
if (ec) return false;
|
||||
Outgoing file;
|
||||
file.input.open(path, std::ios::binary);
|
||||
if (!file.input) return false;
|
||||
file.id = ++next_id_;
|
||||
file.name = name;
|
||||
file.path = path;
|
||||
file.total = size;
|
||||
file.updated = now;
|
||||
outgoing_ = std::move(file);
|
||||
progress_(name, 0, true, "");
|
||||
return true;
|
||||
}
|
||||
|
||||
void Pump(Clock::time_point now = Clock::now()) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
for (auto it = incoming_.begin(); it != incoming_.end();) {
|
||||
if (now - it->second.updated < timeout_) { ++it; continue; }
|
||||
Reject(it->first, it->second.total, it->second.received);
|
||||
progress_(it->second.name, -1, false, "");
|
||||
Remove(it->second);
|
||||
it = incoming_.erase(it);
|
||||
}
|
||||
if (!outgoing_) return;
|
||||
auto& file = *outgoing_;
|
||||
if (now - file.updated >= timeout_) { FinishSend(false); return; }
|
||||
if (file.last || file.sent - file.acked >= 1024 * 1024) return;
|
||||
std::array<char, kFileChunkSize> payload{};
|
||||
const auto size = static_cast<uint32_t>(std::min<uint64_t>(payload.size(), file.total - file.sent));
|
||||
if (size) {
|
||||
file.input.read(payload.data(), size);
|
||||
if (file.input.gcount() != size) { FinishSend(false); return; }
|
||||
}
|
||||
const bool first = file.sent == 0;
|
||||
const bool last = file.sent + size == file.total;
|
||||
const auto chunk = EncodeFileChunk(file.id, file.sent, file.total,
|
||||
payload.data(), size, first ? &file.name : nullptr, first, last);
|
||||
if (chunk.empty() || send_(kFileStream, chunk.data(), chunk.size()) != 0) {
|
||||
FinishSend(false); return;
|
||||
}
|
||||
file.sent += size;
|
||||
file.last = last;
|
||||
}
|
||||
|
||||
void Ack(const char* data, size_t size, Clock::time_point now = Clock::now()) {
|
||||
FileTransferAck ack{};
|
||||
if (!DecodeFileTransferAck(data, size, &ack)) return;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!outgoing_ || ack.file_id != outgoing_->id) return;
|
||||
auto& file = *outgoing_;
|
||||
if (ack.total_size != file.total || ack.acked_offset > file.sent ||
|
||||
(ack.flags & ~3u)) return;
|
||||
if (ack.flags & 2) { FinishSend(false); return; }
|
||||
if (ack.flags & 1) {
|
||||
if (file.last && ack.acked_offset == file.total) FinishSend(true);
|
||||
return;
|
||||
}
|
||||
if (ack.acked_offset <= file.acked) return;
|
||||
file.acked = ack.acked_offset;
|
||||
file.updated = now;
|
||||
Report(file.name, file.acked, file.total, true, file.percent);
|
||||
}
|
||||
|
||||
void Receive(const char* data, size_t size, Clock::time_point now = Clock::now()) {
|
||||
FileChunkView chunk;
|
||||
if (!DecodeFileChunk(data, size, &chunk)) return;
|
||||
const auto& h = chunk.header;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
auto it = incoming_.find(h.file_id);
|
||||
const bool first = h.flags & 1, last = h.flags & 2;
|
||||
const bool invalid = (h.flags & ~3u) || h.total_size > INT64_MAX ||
|
||||
(first && h.offset != 0) || chunk.payload_size > kFileChunkSize ||
|
||||
size != sizeof(FileChunkHeader) + h.name_len + chunk.payload_size ||
|
||||
(!first && h.name_len) || (!chunk.payload_size && !last) ||
|
||||
last != (h.offset + chunk.payload_size == h.total_size);
|
||||
if (invalid || (it == incoming_.end() && incoming_.size() >= 4)) {
|
||||
Reject(h.file_id, h.total_size, h.offset);
|
||||
if (it != incoming_.end()) { progress_(it->second.name, -1, false, ""); Remove(it->second); incoming_.erase(it); }
|
||||
return;
|
||||
}
|
||||
if (it == incoming_.end()) {
|
||||
Incoming file;
|
||||
file.name = SafeName(chunk.file_name);
|
||||
file.total = h.total_size;
|
||||
std::error_code ec;
|
||||
if (!directory_.empty()) std::filesystem::create_directories(directory_, ec);
|
||||
// A per-transfer directory avoids overwrites, even for duplicate names.
|
||||
auto folder = directory_ / (std::to_string(h.file_id) + "-" + std::to_string(++receive_id_));
|
||||
if (directory_.empty() || ec || !std::filesystem::create_directory(folder, ec)) {
|
||||
Reject(h.file_id, h.total_size, 0); progress_(file.name, -1, false, ""); return;
|
||||
}
|
||||
file.path = folder / file.name;
|
||||
file.partial = folder / ".partial";
|
||||
file.output.open(file.partial, std::ios::binary | std::ios::trunc);
|
||||
if (!file.output) {
|
||||
Reject(h.file_id, h.total_size, 0); progress_(file.name, -1, false, ""); Remove(file); return;
|
||||
}
|
||||
it = incoming_.emplace(h.file_id, std::move(file)).first;
|
||||
}
|
||||
auto& file = it->second;
|
||||
if (h.total_size != file.total || (first && file.first) ||
|
||||
!AddRange(file, h.offset, h.offset + chunk.payload_size)) {
|
||||
Reject(h.file_id, h.total_size, h.offset);
|
||||
progress_(file.name, -1, false, ""); Remove(file); incoming_.erase(it); return;
|
||||
}
|
||||
if (first) {
|
||||
file.first = true;
|
||||
file.name = SafeName(chunk.file_name);
|
||||
file.path = file.path.parent_path() / file.name;
|
||||
}
|
||||
file.last |= last;
|
||||
// KCP removes messages in order, but delivers batches outside its lock on
|
||||
// both RTP and timer threads. Track coverage instead of assuming callbacks
|
||||
// arrive in order; ACK only the contiguous prefix and never expose holes.
|
||||
file.received = !file.ranges.empty() && file.ranges.begin()->first == 0
|
||||
? file.ranges.begin()->second : 0;
|
||||
const bool complete = file.first && file.last && file.received == file.total;
|
||||
file.output.seekp(static_cast<std::streamoff>(h.offset));
|
||||
file.output.write(chunk.payload, chunk.payload_size);
|
||||
if (complete) { file.output.flush(); file.output.close(); }
|
||||
std::error_code ec;
|
||||
if (complete && !file.output.fail()) std::filesystem::rename(file.partial, file.path, ec);
|
||||
if (file.output.fail() || ec) {
|
||||
Reject(h.file_id, h.total_size, h.offset);
|
||||
progress_(file.name, -1, false, ""); Remove(file); incoming_.erase(it); return;
|
||||
}
|
||||
file.updated = now;
|
||||
const FileTransferAck ack{kFileAckMagic, h.file_id, file.received, file.total, complete ? 1u : 0u};
|
||||
const auto packet = EncodeFileTransferAck(ack);
|
||||
send_(kFileFeedbackStream, packet.data(), packet.size());
|
||||
if (complete) {
|
||||
progress_(file.name, 1, false, file.path.string());
|
||||
incoming_.erase(it);
|
||||
} else Report(file.name, file.received, file.total, false, file.percent);
|
||||
}
|
||||
|
||||
bool Sending() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return outgoing_.has_value();
|
||||
}
|
||||
|
||||
private:
|
||||
struct Outgoing {
|
||||
uint32_t id = 0;
|
||||
std::string name;
|
||||
std::filesystem::path path;
|
||||
std::ifstream input;
|
||||
uint64_t total = 0, sent = 0, acked = 0;
|
||||
bool last = false;
|
||||
int percent = -1;
|
||||
Clock::time_point updated;
|
||||
};
|
||||
struct Incoming {
|
||||
std::string name;
|
||||
std::filesystem::path path, partial;
|
||||
std::ofstream output;
|
||||
uint64_t total = 0, received = 0;
|
||||
bool first = false, last = false;
|
||||
std::map<uint64_t, uint64_t> ranges;
|
||||
int percent = -1;
|
||||
Clock::time_point updated;
|
||||
};
|
||||
static bool AddRange(Incoming& file, uint64_t start, uint64_t end) {
|
||||
if (start == end) return true;
|
||||
auto next = file.ranges.lower_bound(start);
|
||||
if (next != file.ranges.end() && next->first < end) return false;
|
||||
if (next != file.ranges.begin()) {
|
||||
auto previous = std::prev(next);
|
||||
if (previous->second > start) return false;
|
||||
if (previous->second == start) { start = previous->first; file.ranges.erase(previous); }
|
||||
}
|
||||
if (next != file.ranges.end() && next->first == end) { end = next->second; file.ranges.erase(next); }
|
||||
file.ranges.emplace(start, end);
|
||||
return file.ranges.size() <= 1024;
|
||||
}
|
||||
static std::string SafeName(std::string name) {
|
||||
const auto slash = name.find_last_of("/\\");
|
||||
if (slash != std::string::npos) name.erase(0, slash + 1);
|
||||
for (auto& ch : name) if (static_cast<unsigned char>(ch) < 32 || ch == ':') ch = '_';
|
||||
if (name.empty() || name == "." || name == ".." || name == ".partial" || name.size() > 240) return "received_file";
|
||||
return name;
|
||||
}
|
||||
static void Remove(Incoming& file) {
|
||||
file.output.close();
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(file.partial, ec);
|
||||
std::filesystem::remove(file.path.parent_path(), ec);
|
||||
}
|
||||
void Reject(uint32_t id, uint64_t total, uint64_t offset) {
|
||||
const auto packet = EncodeFileTransferAck({kFileAckMagic, id, offset, total, 2});
|
||||
send_(kFileFeedbackStream, packet.data(), packet.size());
|
||||
}
|
||||
void Report(const std::string& name, uint64_t offset, uint64_t total, bool sending, int& previous) {
|
||||
const double progress = total ? static_cast<double>(offset) / total : 0;
|
||||
const int percent = static_cast<int>(progress * 100);
|
||||
if (percent != previous) { previous = percent; progress_(name, std::min(progress, .99), sending, ""); }
|
||||
}
|
||||
void FinishSend(bool success) {
|
||||
progress_(outgoing_->name, success ? 1 : -1, true, "");
|
||||
outgoing_->input.close();
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(outgoing_->path, ec);
|
||||
outgoing_.reset();
|
||||
}
|
||||
const std::chrono::seconds timeout_{30};
|
||||
std::mutex mutex_;
|
||||
Send send_;
|
||||
Progress progress_;
|
||||
std::filesystem::path directory_;
|
||||
std::optional<Outgoing> outgoing_;
|
||||
std::map<uint32_t, Incoming> incoming_;
|
||||
uint32_t next_id_ = 0;
|
||||
uint64_t receive_id_ = 0;
|
||||
};
|
||||
} // namespace crossdesk::android_controller
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-02
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _LATEST_FRAME_WORKER_H_
|
||||
#define _LATEST_FRAME_WORKER_H_
|
||||
|
||||
#include <condition_variable>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
|
||||
namespace crossdesk::android_controller {
|
||||
// Rendering may wait for Surface buffers. Never hold up the decoder or build
|
||||
// a FIFO of obsolete pictures: keep at most one pending decoded frame.
|
||||
template <typename Frame>
|
||||
class LatestFrameWorker {
|
||||
public:
|
||||
explicit LatestFrameWorker(std::function<void(Frame)> render)
|
||||
: render_(std::move(render)), thread_([this] { Run(); }) {}
|
||||
~LatestFrameWorker() { Stop(); }
|
||||
LatestFrameWorker(const LatestFrameWorker&) = delete;
|
||||
LatestFrameWorker& operator=(const LatestFrameWorker&) = delete;
|
||||
|
||||
bool Submit(Frame frame) {
|
||||
std::lock_guard lock(mutex_);
|
||||
if (stopped_) return false;
|
||||
pending_ = std::move(frame);
|
||||
changed_.notify_one();
|
||||
return true;
|
||||
}
|
||||
void Clear() {
|
||||
std::lock_guard lock(mutex_);
|
||||
pending_.reset();
|
||||
}
|
||||
// Called by the session owner, before destroying the peer or Surface.
|
||||
void Stop() {
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
stopped_ = true;
|
||||
pending_.reset();
|
||||
}
|
||||
changed_.notify_one();
|
||||
if (thread_.joinable()) thread_.join();
|
||||
}
|
||||
|
||||
private:
|
||||
void Run() {
|
||||
for (;;) {
|
||||
std::unique_lock lock(mutex_);
|
||||
changed_.wait(lock, [this] { return stopped_ || pending_.has_value(); });
|
||||
if (stopped_) return;
|
||||
Frame frame = std::move(*pending_);
|
||||
pending_.reset();
|
||||
lock.unlock();
|
||||
render_(std::move(frame));
|
||||
}
|
||||
}
|
||||
const std::function<void(Frame)> render_;
|
||||
std::mutex mutex_;
|
||||
std::condition_variable changed_;
|
||||
std::optional<Frame> pending_;
|
||||
bool stopped_ = false;
|
||||
std::thread thread_;
|
||||
};
|
||||
} // namespace crossdesk::android_controller
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,486 @@
|
||||
#include <jni.h>
|
||||
#include <android/native_window_jni.h>
|
||||
#include <libyuv.h>
|
||||
#include <minirtc.h>
|
||||
#include <log.h>
|
||||
#include <remote_action.h>
|
||||
#include <app_version.h>
|
||||
#include <stream_names.h>
|
||||
#include <display_stream_id.h>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <atomic>
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
#include "controller_protocol.h"
|
||||
#include "file_transfer_session.h"
|
||||
#include "android_codec_support.h"
|
||||
#include "latest_frame_worker.h"
|
||||
#include "video_picture.h"
|
||||
#include "video_timing.h"
|
||||
|
||||
namespace {
|
||||
using namespace crossdesk;
|
||||
using nlohmann::json;
|
||||
JavaVM* vm = nullptr;
|
||||
struct Environment {
|
||||
JNIEnv* env = nullptr;
|
||||
bool attached = false;
|
||||
Environment() {
|
||||
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
|
||||
attached = vm->AttachCurrentThread(&env, nullptr) == JNI_OK;
|
||||
}
|
||||
}
|
||||
~Environment() { if (attached) vm->DetachCurrentThread(); }
|
||||
};
|
||||
std::string String(JNIEnv* env, jstring value) {
|
||||
if (!value) return {};
|
||||
const char* bytes = env->GetStringUTFChars(value, nullptr);
|
||||
std::string result = bytes ? bytes : "";
|
||||
if (bytes) env->ReleaseStringUTFChars(value, bytes);
|
||||
return result;
|
||||
}
|
||||
struct Session;
|
||||
using android_controller::VideoPicture;
|
||||
void RenderVideo(Session* s, VideoPicture picture);
|
||||
struct CallbackContext { Session* owner; bool controller; };
|
||||
struct Session {
|
||||
jobject owner = nullptr;
|
||||
jmethodID event_method, audio_method, frame_method;
|
||||
PeerPtr* identity = nullptr;
|
||||
PeerPtr* controller = nullptr;
|
||||
CallbackContext identity_context{this, false}, controller_context{this, true};
|
||||
std::string host, log_path, identity_login, controller_login, remote;
|
||||
int port;
|
||||
std::atomic<bool> stopping{false};
|
||||
std::atomic<uint64_t> signal_generation{0};
|
||||
std::atomic<int> signal_status{-1};
|
||||
std::atomic<int> display{0};
|
||||
std::atomic<bool> surface_ready{false};
|
||||
std::atomic<uint64_t> video_generation{0};
|
||||
std::mutex render_mutex;
|
||||
ANativeWindow* window = nullptr;
|
||||
uint32_t width = 0, height = 0;
|
||||
uint64_t frame_id = 0;
|
||||
std::optional<VideoPicture> surface_picture;
|
||||
void DetachDecoderSurface() {
|
||||
if (surface_picture) surface_picture->RenderSurface(nullptr);
|
||||
surface_picture.reset();
|
||||
}
|
||||
std::set<int> pressed_keys;
|
||||
unsigned pressed_buttons = 0;
|
||||
float pointer_x = .5f, pointer_y = .5f;
|
||||
android_controller::LatestFrameWorker<VideoPicture> renderer{
|
||||
[this](VideoPicture picture) { RenderVideo(this, std::move(picture)); }};
|
||||
android_controller::FileTransferSession files{
|
||||
[this](const char* stream, const char* data, size_t size) {
|
||||
return controller && !stopping
|
||||
? SendReliableDataFrame(controller, data, size, stream) : -1;
|
||||
},
|
||||
[this](const std::string& name, double progress, bool sending, const std::string& path) {
|
||||
Event(10, {{"name", name}, {"progress", progress}, {"sending", sending}, {"path", path}});
|
||||
}};
|
||||
|
||||
void Event(int type, const char* data, size_t size) {
|
||||
if (stopping || size > 1024 * 1024) return;
|
||||
Environment scope;
|
||||
if (!scope.env) return;
|
||||
jbyteArray bytes = scope.env->NewByteArray(static_cast<jsize>(size));
|
||||
if (!bytes) return;
|
||||
scope.env->SetByteArrayRegion(bytes, 0, size, reinterpret_cast<const jbyte*>(data));
|
||||
scope.env->CallVoidMethod(owner, event_method, type, bytes);
|
||||
scope.env->DeleteLocalRef(bytes);
|
||||
if (scope.env->ExceptionCheck()) scope.env->ExceptionClear();
|
||||
}
|
||||
void Event(int type, const json& value) {
|
||||
const std::string data = value.dump(-1, ' ', false, json::error_handler_t::replace); Event(type, data.data(), data.size());
|
||||
}
|
||||
void Send(const char* stream, const std::string& data) {
|
||||
if (controller && !stopping && !data.empty())
|
||||
SendReliableDataFrame(controller, data.data(), data.size(), stream);
|
||||
}
|
||||
void Surface(JNIEnv* env, jobject surface) {
|
||||
std::lock_guard<std::mutex> lock(render_mutex);
|
||||
++video_generation;
|
||||
renderer.Clear();
|
||||
DetachDecoderSurface();
|
||||
if (window) ANativeWindow_release(window);
|
||||
window = surface ? ANativeWindow_fromSurface(env, surface) : nullptr;
|
||||
surface_ready = window != nullptr;
|
||||
width = height = 0;
|
||||
}
|
||||
~Session() {
|
||||
// API calls and destruction share the Java RTC executor. Release any
|
||||
// delivered input even when queued Java key-up events were cancelled.
|
||||
if (controller) {
|
||||
for (int key : pressed_keys) {
|
||||
RemoteAction action{}; action.type = keyboard;
|
||||
action.k = {static_cast<size_t>(key), 0, false, key_up};
|
||||
Send(kKeyboardStream, action.to_json());
|
||||
}
|
||||
for (int button = 0; button < 3; ++button) {
|
||||
if (!(pressed_buttons & (1u << button))) continue;
|
||||
RemoteAction action{}; action.type = mouse;
|
||||
action.m = {pointer_x, pointer_y, 0, static_cast<MouseFlag>(2 + button * 2)};
|
||||
Send(kMouseStream, action.to_json());
|
||||
}
|
||||
}
|
||||
stopping = true;
|
||||
renderer.Stop();
|
||||
if (controller) {
|
||||
LeaveConnection(controller, remote.c_str());
|
||||
DestroyPeer(&controller);
|
||||
}
|
||||
if (identity) DestroyPeer(&identity);
|
||||
Environment scope;
|
||||
Surface(scope.env, nullptr);
|
||||
if (scope.env) scope.env->DeleteGlobalRef(owner);
|
||||
}
|
||||
};
|
||||
|
||||
void Signal(SignalStatus status, const char*, size_t, void* user) {
|
||||
auto* ctx = static_cast<CallbackContext*>(user);
|
||||
if (!ctx->controller && status == SignalStatus::SignalConnected &&
|
||||
!ctx->owner->stopping && ctx->owner->identity) {
|
||||
// Report after every identity login, including reconnects. The server
|
||||
// ignores client_info sent through the temporary C- controller peer.
|
||||
constexpr char info[] =
|
||||
R"({"type":"client_info","version":"android-native","platform":"android"})";
|
||||
SendSignalMessage(ctx->owner->identity, info, sizeof(info) - 1);
|
||||
}
|
||||
if (!ctx->controller && ctx->owner->signal_status.exchange(status) != status)
|
||||
++ctx->owner->signal_generation;
|
||||
const auto generation = ctx->owner->signal_generation.load();
|
||||
ctx->owner->Event(1, {{"controller", ctx->controller}, {"status", status}, {"generation", generation}});
|
||||
}
|
||||
void SignalMessage(const char* data, size_t size, void* user) {
|
||||
auto* ctx = static_cast<CallbackContext*>(user);
|
||||
if (ctx->controller || !data || !size || size > 1024 * 1024) return;
|
||||
const auto generation = ctx->owner->signal_generation.load();
|
||||
auto message = json::parse(data, data + size, nullptr, false);
|
||||
if (!message.is_object() || !message.contains("type") || !message["type"].is_string()) return;
|
||||
const auto type = message["type"].get<std::string>();
|
||||
if (type == "announcements" || type == "announcements_changed") ctx->owner->Event(8, data, size);
|
||||
else if (type == "presence" || type == "presence_update") {
|
||||
message["generation"] = generation;
|
||||
ctx->owner->Event(9, message);
|
||||
}
|
||||
}
|
||||
void Connection(ConnectionStatus status, const char*, size_t, void* user) {
|
||||
auto* ctx = static_cast<CallbackContext*>(user);
|
||||
if (ctx->controller) ctx->owner->Event(2, {{"status", status}});
|
||||
}
|
||||
void Network(const char* id, size_t size, TraversalMode mode,
|
||||
const MiniRtcNetTrafficStats* stats, const char*, size_t, void* user) {
|
||||
auto* ctx = static_cast<CallbackContext*>(user);
|
||||
if (!ctx->controller && mode == UnknownMode && id && size) {
|
||||
ctx->owner->Event(3, id, size);
|
||||
} else if (ctx->controller && stats) {
|
||||
ctx->owner->Event(7, android_controller::NetworkReport(*stats, mode));
|
||||
}
|
||||
}
|
||||
void Data(const char* data, size_t size, const char*, size_t,
|
||||
const char* stream, size_t stream_size, void* user) {
|
||||
auto* ctx = static_cast<CallbackContext*>(user);
|
||||
if (!ctx->controller || !data || !stream || size > kMaxClipboardBytes) return;
|
||||
const std::string name(stream, stream_size);
|
||||
if (name == kFileStream) { ctx->owner->files.Receive(data, size); return; }
|
||||
if (name == kFileFeedbackStream) { ctx->owner->files.Ack(data, size); return; }
|
||||
if (name == kControlStream) {
|
||||
RemoteAction action{};
|
||||
if (action.from_json(std::string(data, size))) {
|
||||
const auto message = action.to_json();
|
||||
ctx->owner->Event(4, message.data(), message.size());
|
||||
FreeRemoteAction(action);
|
||||
}
|
||||
}
|
||||
if (name == kClipboardStream) ctx->owner->Event(6, data, size);
|
||||
}
|
||||
void Audio(const char* data, size_t size, const char*, size_t,
|
||||
const char*, size_t, void* user) {
|
||||
auto* ctx = static_cast<CallbackContext*>(user);
|
||||
auto* s = ctx->owner;
|
||||
if (!ctx->controller || s->stopping || !data || !size || size > 23040) return;
|
||||
Environment scope;
|
||||
if (!scope.env) return;
|
||||
auto bytes = scope.env->NewByteArray(size);
|
||||
if (!bytes) return;
|
||||
scope.env->SetByteArrayRegion(bytes, 0, size, reinterpret_cast<const jbyte*>(data));
|
||||
scope.env->CallVoidMethod(s->owner, s->audio_method, bytes);
|
||||
scope.env->DeleteLocalRef(bytes);
|
||||
if (scope.env->ExceptionCheck()) scope.env->ExceptionClear();
|
||||
}
|
||||
void Video(const MiniRtcVideoFrame* frame, const char*, size_t,
|
||||
const char* stream, size_t stream_size, void* user) {
|
||||
auto* ctx = static_cast<CallbackContext*>(user);
|
||||
auto* s = ctx->owner;
|
||||
const auto generation = s->video_generation.load();
|
||||
if (!ctx->controller || s->stopping || !s->surface_ready || !frame || !stream ||
|
||||
std::string(stream, stream_size) != MakeDisplayStreamId(s->display.load())) return;
|
||||
auto picture = VideoPicture::RetainOrCopy(*frame, generation);
|
||||
if (picture) s->renderer.Submit(std::move(*picture));
|
||||
}
|
||||
void RenderVideo(Session* s, VideoPicture picture) {
|
||||
const auto w = picture.width, h = picture.height;
|
||||
std::lock_guard<std::mutex> lock(s->render_mutex);
|
||||
if (s->stopping || !s->window || picture.generation != s->video_generation) return;
|
||||
const bool size_changed = s->width != w || s->height != h;
|
||||
if (picture.IsSurface()) {
|
||||
if (picture.RenderSurface(s->window) != 0) return;
|
||||
// Keep a consumed token to detach the codec before Surface destruction,
|
||||
// monitor switching, or CPU rendering after a software fallback.
|
||||
s->surface_picture = picture;
|
||||
} else {
|
||||
const bool was_surface = s->surface_picture.has_value();
|
||||
s->DetachDecoderSurface();
|
||||
if ((size_changed || was_surface) &&
|
||||
ANativeWindow_setBuffersGeometry(s->window, w, h, WINDOW_FORMAT_RGBA_8888) != 0) return;
|
||||
ANativeWindow_Buffer buffer{};
|
||||
if (ANativeWindow_lock(s->window, &buffer, nullptr) != 0) return;
|
||||
const bool rendered = buffer.width == static_cast<int>(w) && buffer.height == static_cast<int>(h) &&
|
||||
libyuv::NV12ToABGR(picture.Y(), picture.YStride(), picture.UV(), picture.UVStride(),
|
||||
static_cast<uint8_t*>(buffer.bits), buffer.stride * 4, w, h) == 0;
|
||||
if (ANativeWindow_unlockAndPost(s->window) != 0 || !rendered) return;
|
||||
}
|
||||
if (size_changed) {
|
||||
s->width = w; s->height = h;
|
||||
s->Event(5, {{"width", w}, {"height", h}});
|
||||
}
|
||||
// Measure through display submission, using MiniRTC's calibrated capture clock.
|
||||
const auto now = GetSystemTimeMicros(s->controller);
|
||||
const double latency = android_controller::VideoLatencyMilliseconds(
|
||||
picture.captured_us, picture.received_us, now);
|
||||
Environment scope;
|
||||
if (scope.env) {
|
||||
scope.env->CallVoidMethod(s->owner, s->frame_method, static_cast<jlong>(++s->frame_id), latency, static_cast<jint>(w), static_cast<jint>(h));
|
||||
if (scope.env->ExceptionCheck()) scope.env->ExceptionClear();
|
||||
}
|
||||
}
|
||||
Params Parameters(Session* s, bool controller) {
|
||||
Params p{};
|
||||
std::snprintf(p.signal_server_ip, sizeof(p.signal_server_ip), "%s", s->host.c_str());
|
||||
std::snprintf(p.log_path, sizeof(p.log_path), "%s", s->log_path.c_str());
|
||||
p.signal_server_port = s->port;
|
||||
p.hardware_acceleration = true;
|
||||
// MediaCodec returns retained Surface buffers; software fallback returns
|
||||
// pooled CPU NV12 with the same ownership contract.
|
||||
p.native_video_output = controller;
|
||||
p.turn_mode = TurnAutoUdpTcp;
|
||||
p.enable_srtp = true;
|
||||
p.video_content_type = VideoContentType::ScreenContent;
|
||||
p.video_quality = QualityMedium;
|
||||
p.video_frame_rate = 30;
|
||||
p.video_degradation_preference = VideoDegradationPreference::Balanced;
|
||||
p.on_signal_status = Signal; p.on_connection_status = Connection;
|
||||
p.on_signal_message = SignalMessage;
|
||||
p.on_net_status_report = Network; p.on_receive_data_buffer = Data;
|
||||
p.on_receive_video_frame = Video; p.on_receive_audio_buffer = Audio;
|
||||
p.user_id = (controller ? s->controller_login : s->identity_login).c_str();
|
||||
p.user_data = controller ? &s->controller_context : &s->identity_context;
|
||||
return p;
|
||||
}
|
||||
Session* From(jlong handle) { return reinterpret_cast<Session*>(handle); }
|
||||
} // namespace
|
||||
|
||||
extern "C" JNIEXPORT jint JNI_OnLoad(JavaVM* java_vm, void*) {
|
||||
vm = java_vm;
|
||||
minirtc::android::SetJavaVm(java_vm);
|
||||
return JNI_VERSION_1_6;
|
||||
}
|
||||
#define JNI_METHOD(name) Java_cn_crossdesk_mobile_NativeSession_##name
|
||||
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nValidAppVersion)(
|
||||
JNIEnv* env, jclass, jstring version) {
|
||||
return version && env->GetStringUTFLength(version) < 64 &&
|
||||
crossdesk::IsValidAppVersion(String(env, version));
|
||||
}
|
||||
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nHasAppUpdate)(
|
||||
JNIEnv* env, jclass, jstring version, jbyteArray release_json) {
|
||||
if (!release_json) return false;
|
||||
const auto size = env->GetArrayLength(release_json);
|
||||
if (size <= 0 || size > 256 * 1024) return false;
|
||||
std::string data(size, '\0');
|
||||
env->GetByteArrayRegion(release_json, 0, size, reinterpret_cast<jbyte*>(data.data()));
|
||||
if (env->ExceptionCheck()) return false;
|
||||
const auto latest = crossdesk::ParseVersionInfoJSON(data);
|
||||
return latest && crossdesk::AvailableAppUpdate(String(env, version), *latest).has_value();
|
||||
}
|
||||
extern "C" JNIEXPORT jstring JNICALL JNI_METHOD(nCheckMobileUpdate)(
|
||||
JNIEnv* env, jclass, jstring version, jbyteArray release_json) {
|
||||
if (!version || !release_json) return nullptr;
|
||||
const auto size = env->GetArrayLength(release_json);
|
||||
if (size <= 0 || size > 256 * 1024) return nullptr;
|
||||
std::string data(size, '\0');
|
||||
env->GetByteArrayRegion(release_json, 0, size, reinterpret_cast<jbyte*>(data.data()));
|
||||
if (env->ExceptionCheck()) return nullptr;
|
||||
const auto result = crossdesk::CheckPlatformAppUpdate(
|
||||
String(env, version), data, "android-arm64");
|
||||
return result ? env->NewStringUTF(result->c_str()) : nullptr;
|
||||
}
|
||||
extern "C" JNIEXPORT jlong JNICALL JNI_METHOD(nCreate)(
|
||||
JNIEnv* env, jclass, jobject owner, jstring host, jint port, jstring identity,
|
||||
jstring log_path, jstring certificates) {
|
||||
try {
|
||||
auto s = std::make_unique<Session>();
|
||||
s->owner = env->NewGlobalRef(owner);
|
||||
auto cls = env->GetObjectClass(owner);
|
||||
s->event_method = env->GetMethodID(cls, "onNativeEvent", "(I[B)V");
|
||||
s->audio_method = env->GetMethodID(cls, "onNativeAudio", "([B)V");
|
||||
s->frame_method = env->GetMethodID(cls, "onNativeVideoFrame", "(JDII)V");
|
||||
env->DeleteLocalRef(cls);
|
||||
s->host = String(env, host); s->port = port;
|
||||
s->identity_login = String(env, identity); s->log_path = String(env, log_path);
|
||||
// The bundle is exported from Android's default TrustManager, never the
|
||||
// build machine's certificate store. MiniRTC on Android explicitly
|
||||
// loads this path: OpenSSL's default loader ignores SSL_CERT_FILE in an
|
||||
// Android app process (AT_SECURE=1). Chain and hostname checks stay enabled.
|
||||
const auto bundle = String(env, certificates);
|
||||
if (bundle.empty() || setenv("SSL_CERT_FILE", bundle.c_str(), 1) != 0)
|
||||
throw std::runtime_error("Unable to configure Android trust bundle");
|
||||
// MiniRTC's diagnostic log includes login identities. Keep credentials
|
||||
// solely in Keystore-backed storage; do not persist its session logging.
|
||||
minirtc::InitLogger(s->log_path);
|
||||
minirtc::get_logger()->set_level(spdlog::level::off);
|
||||
auto params = Parameters(s.get(), false);
|
||||
s->identity = CreatePeer(¶ms);
|
||||
if (!s->identity || Init(s->identity) != 0) return 0;
|
||||
return reinterpret_cast<jlong>(s.release());
|
||||
} catch (const std::exception&) { return 0; }
|
||||
}
|
||||
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nConnect)(
|
||||
JNIEnv* env, jclass, jlong handle, jstring identity, jstring remote, jstring password) {
|
||||
auto* s = From(handle);
|
||||
if (!s || s->controller) return false;
|
||||
s->controller_login = "C-" + String(env, identity);
|
||||
s->remote = String(env, remote);
|
||||
auto params = Parameters(s, true);
|
||||
s->controller = CreatePeer(¶ms);
|
||||
if (!s->controller) return false;
|
||||
AddAudioStream(s->controller, kAudioStream);
|
||||
AddDataStream(s->controller, kDataStream, false);
|
||||
for (const char* name : {kMouseStream, kKeyboardStream, kControlStream,
|
||||
kClipboardStream, kFileStream, kFileFeedbackStream}) AddDataStream(s->controller, name, true);
|
||||
if (Init(s->controller) != 0) return false;
|
||||
const auto join = s->remote + "@" + String(env, password);
|
||||
return JoinConnection(s->controller, join.c_str()) == 0;
|
||||
}
|
||||
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nReady)(JNIEnv*, jclass, jlong handle) {
|
||||
auto* s = From(handle); if (!s || !s->controller) return;
|
||||
auto action = MakeHostInformation("CrossDesk Android", {}, false, "1.6.0", HostPlatform::Android);
|
||||
s->Send(kControlStream, action.to_json()); FreeRemoteAction(action);
|
||||
}
|
||||
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nPointer)(
|
||||
JNIEnv*, jclass, jlong handle, jfloat x, jfloat y, jint flag, jint wheel) {
|
||||
auto* s = From(handle); if (!s || flag < 0 || flag > 8) return;
|
||||
RemoteAction action{}; action.type = mouse;
|
||||
action.m = {std::clamp(x, 0.f, 1.f), std::clamp(y, 0.f, 1.f), wheel, static_cast<MouseFlag>(flag)};
|
||||
s->pointer_x = action.m.x; s->pointer_y = action.m.y;
|
||||
if (flag >= 1 && flag <= 6) {
|
||||
const unsigned bit = 1u << ((flag - 1) / 2);
|
||||
if (flag & 1) s->pressed_buttons |= bit; else s->pressed_buttons &= ~bit;
|
||||
}
|
||||
s->Send(kMouseStream, action.to_json());
|
||||
}
|
||||
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nKey)(JNIEnv*, jclass, jlong handle, jint key, jboolean down) {
|
||||
auto* s = From(handle); if (!s) return;
|
||||
RemoteAction action{}; action.type = keyboard;
|
||||
action.k = {static_cast<size_t>(key), 0, false, down ? key_down : key_up};
|
||||
if (down) s->pressed_keys.insert(key); else s->pressed_keys.erase(key);
|
||||
s->Send(kKeyboardStream, action.to_json());
|
||||
}
|
||||
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nControl)(
|
||||
JNIEnv*, jclass, jlong handle, jint type, jint value) {
|
||||
auto* s = From(handle); if (!s) return;
|
||||
RemoteAction action{};
|
||||
if (type == display_id && value >= 0 && value < 8) {
|
||||
{ std::lock_guard<std::mutex> lock(s->render_mutex); s->display = value; ++s->video_generation; s->renderer.Clear(); s->DetachDecoderSurface(); s->width = s->height = 0; }
|
||||
action.type = display_id; action.d = value;
|
||||
} else if (type == audio_capture) {
|
||||
action.type = audio_capture; action.a = value != 0;
|
||||
} else return;
|
||||
s->Send(kControlStream, action.to_json());
|
||||
}
|
||||
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nVideoSettings)(
|
||||
JNIEnv*, jclass, jlong handle, jint quality, jint rate, jint preference, jlong request_id) {
|
||||
auto* s = From(handle);
|
||||
if (!s || !s->controller || s->stopping || request_id < 0 || request_id > UINT32_MAX) return false;
|
||||
const auto data = android_controller::VideoSettingsMessage(quality, rate, preference, static_cast<uint32_t>(request_id));
|
||||
if (data.empty()) return false;
|
||||
return SendReliableDataFrame(s->controller, data.data(), data.size(), kControlStream) == 0;
|
||||
}
|
||||
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nSecureAttention)(JNIEnv*, jclass, jlong handle) {
|
||||
auto* s = From(handle);
|
||||
if (!s || !s->controller || s->stopping) return false;
|
||||
const auto data = android_controller::SecureAttentionMessage();
|
||||
return SendReliableDataFrame(s->controller, data.data(), data.size(), kControlStream) == 0;
|
||||
}
|
||||
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nFileDirectory)(JNIEnv* env, jclass, jlong handle, jstring directory) {
|
||||
auto* s = From(handle); if (s) s->files.SetDirectory(String(env, directory));
|
||||
}
|
||||
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nSendFile)(JNIEnv* env, jclass, jlong handle, jstring path, jbyteArray name) {
|
||||
auto* s = From(handle);
|
||||
if (!s || !s->controller || s->stopping || !name) return false;
|
||||
const auto size = env->GetArrayLength(name);
|
||||
if (!size || size > UINT16_MAX) return false;
|
||||
std::string label(size, '\0');
|
||||
env->GetByteArrayRegion(name, 0, size, reinterpret_cast<jbyte*>(label.data()));
|
||||
return !env->ExceptionCheck() && s->files.Start(String(env, path), label);
|
||||
}
|
||||
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nPumpFiles)(JNIEnv*, jclass, jlong handle) {
|
||||
auto* s = From(handle);
|
||||
if (!s || s->stopping) return false;
|
||||
s->files.Pump();
|
||||
return s->files.Sending();
|
||||
}
|
||||
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nAnnouncementRequest)(
|
||||
JNIEnv* env, jclass, jlong handle, jbyteArray data) {
|
||||
auto* s = From(handle);
|
||||
if (!s || !s->identity || s->stopping || !data) return false;
|
||||
const auto size = env->GetArrayLength(data);
|
||||
if (size <= 0 || size > 4096) return false;
|
||||
std::string bytes(size, '\0');
|
||||
env->GetByteArrayRegion(data, 0, size, reinterpret_cast<jbyte*>(bytes.data()));
|
||||
if (env->ExceptionCheck()) return false;
|
||||
auto message = json::parse(bytes, nullptr, false);
|
||||
if (!message.is_object() || !message.contains("type") ||
|
||||
!message["type"].is_string() || message["type"] != "announcements_list") return false;
|
||||
return SendSignalMessage(s->identity, bytes.data(), bytes.size()) == 0;
|
||||
}
|
||||
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nPresenceRequest)(
|
||||
JNIEnv* env, jclass, jlong handle, jbyteArray data) {
|
||||
auto* s = From(handle);
|
||||
if (!s || !s->identity || s->stopping || !data) return false;
|
||||
const auto size = env->GetArrayLength(data);
|
||||
if (size <= 0 || size > 4096) return false;
|
||||
std::string bytes(size, '\0');
|
||||
env->GetByteArrayRegion(data, 0, size, reinterpret_cast<jbyte*>(bytes.data()));
|
||||
if (env->ExceptionCheck()) return false;
|
||||
auto message = json::parse(bytes, nullptr, false);
|
||||
if (!message.is_object() || !message.contains("type") || !message["type"].is_string() ||
|
||||
message["type"] != "recent_connections_presence" ||
|
||||
!message.contains("user_id") || !message["user_id"].is_string() ||
|
||||
!message.contains("devices") || !message["devices"].is_array() ||
|
||||
!message.contains("subscribe") || message["subscribe"] != true) return false;
|
||||
return SendSignalMessage(s->identity, bytes.data(), bytes.size()) == 0;
|
||||
}
|
||||
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nClipboard)(
|
||||
JNIEnv* env, jclass, jlong handle, jbyteArray data) {
|
||||
auto* s = From(handle); if (!s || !data) return;
|
||||
const auto size = env->GetArrayLength(data);
|
||||
if (!size || size > static_cast<int>(kMaxClipboardBytes)) return;
|
||||
std::string bytes(size, '\0');
|
||||
env->GetByteArrayRegion(data, 0, size, reinterpret_cast<jbyte*>(bytes.data()));
|
||||
s->Send(kClipboardStream, bytes);
|
||||
}
|
||||
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nSurface)(JNIEnv* env, jclass, jlong handle, jobject surface) {
|
||||
if (auto* s = From(handle)) {
|
||||
s->Surface(env, surface);
|
||||
if (surface && s->controller && !s->stopping)
|
||||
RequestVideoKeyFrame(s->controller, MakeDisplayStreamId(s->display.load()).c_str());
|
||||
}
|
||||
}
|
||||
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nDestroy)(JNIEnv*, jclass, jlong handle) { delete From(handle); }
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-02
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _VIDEO_PICTURE_H_
|
||||
#define _VIDEO_PICTURE_H_
|
||||
|
||||
#include <minirtc.h>
|
||||
#include <climits>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
namespace crossdesk::android_controller {
|
||||
struct VideoPicture {
|
||||
uint32_t width, height;
|
||||
uint64_t captured_us, received_us, generation;
|
||||
std::vector<uint8_t> pixels;
|
||||
std::shared_ptr<void> native_owner;
|
||||
MiniRtcCpuNv12Frame planes{};
|
||||
MiniRtcAndroidMediaCodecFrame media_codec{};
|
||||
|
||||
bool IsSurface() const { return media_codec.render && native_owner; }
|
||||
int RenderSurface(void* window) const {
|
||||
return IsSurface() ? media_codec.render(native_owner.get(), window) : -1;
|
||||
}
|
||||
|
||||
const uint8_t* Y() const { return native_owner ? planes.y_plane : pixels.data(); }
|
||||
const uint8_t* UV() const { return native_owner ? planes.uv_plane : pixels.data() + size_t(width) * height; }
|
||||
int YStride() const { return native_owner ? planes.y_stride : width; }
|
||||
int UVStride() const { return native_owner ? planes.uv_stride : width; }
|
||||
|
||||
static std::optional<VideoPicture> RetainOrCopy(const MiniRtcVideoFrame& frame,
|
||||
uint64_t generation) {
|
||||
const auto w = frame.width, h = frame.height;
|
||||
if (!w || !h || w > 8192 || h > 8192 || (w & 1) || (h & 1) ||
|
||||
static_cast<uint64_t>(w) * h > 33554432) return std::nullopt;
|
||||
VideoPicture result{w, h, frame.captured_timestamp, frame.received_timestamp,
|
||||
generation, {}, {}, {}, {}};
|
||||
const auto* native = frame.native_frame;
|
||||
const bool valid_native = native && native->struct_size >= sizeof(*native) &&
|
||||
native->width == w && native->height == h && native->owner;
|
||||
if (valid_native && native->type == MiniRtcNativeVideoFrameAndroidMediaCodec &&
|
||||
native->retain && native->release && native->payload.android_media_codec.render) {
|
||||
native->retain(native->owner);
|
||||
result.native_owner = std::shared_ptr<void>(native->owner, native->release);
|
||||
result.media_codec = native->payload.android_media_codec;
|
||||
return result;
|
||||
}
|
||||
if (valid_native && native->type == MiniRtcNativeVideoFrameCpuNv12 &&
|
||||
native->retain && native->release) {
|
||||
const auto& planes = native->payload.cpu_nv12;
|
||||
if (planes.y_plane && planes.uv_plane && planes.y_stride >= w &&
|
||||
planes.uv_stride >= w && planes.y_stride <= INT_MAX && planes.uv_stride <= INT_MAX) {
|
||||
native->retain(native->owner);
|
||||
result.native_owner = std::shared_ptr<void>(native->owner, native->release);
|
||||
result.planes = planes;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
const size_t size = size_t(w) * h * 3 / 2;
|
||||
if (frame.data && frame.size >= size) {
|
||||
result.pixels.resize(size);
|
||||
std::memcpy(result.pixels.data(), frame.data, size);
|
||||
} else if (valid_native && native->copy_to_nv12) {
|
||||
result.pixels.resize(size);
|
||||
if (native->copy_to_nv12(native->owner, result.pixels.data(), size) != 0)
|
||||
return std::nullopt;
|
||||
} else {
|
||||
return std::nullopt;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
};
|
||||
} // namespace crossdesk::android_controller
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-02
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _VIDEO_TIMING_H_
|
||||
#define _VIDEO_TIMING_H_
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace crossdesk::android_controller {
|
||||
inline double VideoLatencyMilliseconds(uint64_t captured_us,
|
||||
uint64_t received_us,
|
||||
int64_t submitted_us) {
|
||||
// MiniRTC calibrates capture time when the frame is reassembled. Validate
|
||||
// that mapping at reception, not after decoding/Surface waits: a real local
|
||||
// backlog over five seconds must remain visible in the latency measurement.
|
||||
if (!captured_us || received_us < captured_us || submitted_us <= 0 ||
|
||||
received_us > static_cast<uint64_t>(submitted_us) ||
|
||||
received_us - captured_us > 5'000'000)
|
||||
return -1;
|
||||
return (static_cast<uint64_t>(submitted_us) - captured_us) / 1000.0;
|
||||
}
|
||||
} // namespace crossdesk::android_controller
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,19 @@
|
||||
set_project("crossdesk_android")
|
||||
set_xmakever("3.1.1")
|
||||
set_languages("c++17")
|
||||
add_rules("mode.release", "mode.debug")
|
||||
set_policy("package.precompiled", false)
|
||||
add_cxflags("-fPIC")
|
||||
includes("../../../deps/submodules/minirtc")
|
||||
|
||||
target("crossdesk_android")
|
||||
set_kind("shared")
|
||||
add_deps("minirtc")
|
||||
add_packages("nlohmann_json", "libyuv", "spdlog")
|
||||
add_files("rtc_bridge.cpp", "../../../libs/wire/src/remote_action.cpp", "../../../libs/wire/src/app_version.cpp", "../../../libs/wire/src/file_transfer.cpp")
|
||||
add_includedirs("../../../deps/submodules/minirtc/src/api", "../../../libs/wire/include")
|
||||
-- This source-level JNI adapter is the only application layer using MiniRTC internals.
|
||||
add_includedirs("../../../deps/submodules/minirtc/src/media/mediacodec")
|
||||
add_syslinks("android", "log")
|
||||
add_shflags("-Wl,-z,max-page-size=16384", "-Wl,-z,common-page-size=16384", {force = true})
|
||||
set_targetdir("../app/build/native/arm64-v8a")
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the native controller in isolation from desktop and iOS caches."""
|
||||
import fcntl
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import re
|
||||
|
||||
ANDROID = Path(__file__).resolve().parents[1]
|
||||
ROOT = ANDROID.parents[1]
|
||||
SOURCE = ROOT / 'deps/submodules/minirtc'
|
||||
CACHE = ANDROID / '.native'
|
||||
PACKAGE_REVISION = 'eda39de3fb99b420c168f1ab9ab2d1791e11b662'
|
||||
XMAKE_MIN_VERSION = (3, 1, 1)
|
||||
|
||||
|
||||
def find_xmake():
|
||||
xmake = os.environ.get('XMAKE_BIN') or shutil.which('xmake')
|
||||
minimum = '.'.join(map(str, XMAKE_MIN_VERSION))
|
||||
if not xmake:
|
||||
raise SystemExit(f'Xmake {minimum} or newer is required; install it or set XMAKE_BIN.')
|
||||
output = subprocess.check_output([xmake, '--version'], text=True)
|
||||
version = re.search(r'xmake v(\d+)\.(\d+)\.(\d+)(?:\+|[,\s]|$)', output)
|
||||
if not version or tuple(map(int, version.groups())) < XMAKE_MIN_VERSION:
|
||||
raise SystemExit(f'Use Xmake {minimum} or newer (set XMAKE_BIN to its executable).')
|
||||
return xmake
|
||||
|
||||
|
||||
def main():
|
||||
sdk = Path(os.environ.get('ANDROID_HOME') or os.environ.get('ANDROID_SDK_ROOT')
|
||||
or Path.home() / 'Library/Android/sdk')
|
||||
ndk = sdk / 'ndk/28.2.13676358'
|
||||
if not ndk.is_dir():
|
||||
raise SystemExit('Install Android NDK 28.2.13676358 using SDK Manager.')
|
||||
xmake = find_xmake()
|
||||
if not (SOURCE / 'xmake.lua').is_file():
|
||||
raise SystemExit('Initialize the MiniRTC submodule before building.')
|
||||
env = os.environ.copy()
|
||||
env['XMAKE_PKG_INSTALLDIR'] = str(CACHE / 'packages')
|
||||
env['XMAKE_GLOBALDIR'] = str(CACHE / 'global')
|
||||
env['ANDROID_NDK_HOME'] = str(ndk)
|
||||
env['ANDROID_NDK_ROOT'] = str(ndk)
|
||||
env['NO_COLOR'] = '1'
|
||||
work = ANDROID / 'native'
|
||||
repository = CACHE / 'global/.xmake/repositories/xmake-repo'
|
||||
if not (repository / '.git').is_dir():
|
||||
subprocess.run([xmake, 'repo', '--update'], cwd=work, env=env, check=True)
|
||||
revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repository, text=True).strip()
|
||||
if revision != PACKAGE_REVISION:
|
||||
subprocess.run(['git', 'fetch', 'origin', PACKAGE_REVISION], cwd=repository, check=True)
|
||||
subprocess.run(['git', 'checkout', '--detach', PACKAGE_REVISION], cwd=repository, check=True)
|
||||
subprocess.run([xmake, 'f', '-P', str(work), '-y', '-p', 'android', '-a', 'arm64-v8a',
|
||||
'-m', 'release', '--ndk=' + str(ndk), '--ndk_sdkver=26',
|
||||
'--runtimes=c++_static', '--policies=package.precompiled:n',
|
||||
'-o', str(CACHE / 'build')], cwd=work, env=env, check=True)
|
||||
subprocess.run([xmake, '-P', str(work), '-y', 'crossdesk_android'], cwd=work, env=env, check=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
CACHE.mkdir(parents=True, exist_ok=True)
|
||||
with (CACHE / 'build.lock').open('w') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
main()
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Package existing reviewed notices for the Android runtime dependency set."""
|
||||
import json
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from urllib.parse import quote
|
||||
|
||||
ANDROID = Path(__file__).resolve().parents[1]
|
||||
ROOT = ANDROID.parents[1]
|
||||
COMPONENTS = {
|
||||
'asio', 'concurrentqueue', 'dav1d', 'glib', 'inih', 'nlohmann_json',
|
||||
'kcp', 'libdatachannel', 'libffi', 'libnice', 'libsrtp', 'libyuv',
|
||||
'minirtc', 'openfec', 'openssl3', 'libopus', 'pcre2', 'plog',
|
||||
'proxy-libintl', 'spdlog', 'svt-av1', 'usrsctp', 'webrtc', 'websocketpp', 'zlib',
|
||||
}
|
||||
|
||||
|
||||
def git(*args, cwd=ROOT):
|
||||
return subprocess.check_output(['git', *args], cwd=cwd, text=True).strip()
|
||||
|
||||
|
||||
def write_pages(output, catalog, additional, revision, minirtc):
|
||||
"""Small navigation catalog and separate, offline-selectable license documents."""
|
||||
source = f'https://github.com/kunkundi/crossdesk/tree/{revision}'
|
||||
mini_source = f'https://github.com/kunkundi/minirtc/tree/{minirtc}'
|
||||
components = []
|
||||
for entry in catalog['components']:
|
||||
if entry['id'] not in COMPONENTS | {'crossdesk'}:
|
||||
continue
|
||||
component = dict(entry)
|
||||
if component['id'] == 'crossdesk':
|
||||
component['sourceURL'] = source
|
||||
component['documents'] = [
|
||||
{'title': 'LICENSE', 'text': (ROOT / 'LICENSE').read_text()},
|
||||
{'title': 'apps/android/licenses/OPEN_SOURCE_NOTICE.txt',
|
||||
'text': (ANDROID / 'licenses/OPEN_SOURCE_NOTICE.txt').read_text()},
|
||||
]
|
||||
if component['id'] in {'minirtc', 'inih', 'webrtc'}:
|
||||
component.update(version=minirtc, sourceURL=mini_source)
|
||||
if '/thirdparty/' in component.get('buildSourceURL', ''):
|
||||
recipe = component['buildSourceURL'].split('/thirdparty/', 1)[1]
|
||||
component['buildSourceURL'] = f'{mini_source}/thirdparty/{recipe}'
|
||||
components.append(component)
|
||||
components += additional
|
||||
# Ship the actual build instructions and recipes used by this local build. The Android
|
||||
# directory may not exist at the public base commit of an unpublished checkout.
|
||||
bundled = [
|
||||
('构建说明', ANDROID / 'README.md'),
|
||||
('原生构建配方', ANDROID / 'native/xmake.lua'),
|
||||
('OpenSSL 构建配方', ROOT / 'deps/submodules/minirtc/thirdparty/openssl/xmake.lua'),
|
||||
('MiniRTC 构建配方', ROOT / 'deps/submodules/minirtc/xmake.lua'),
|
||||
('原生构建脚本', ANDROID / 'scripts/build_native.py'),
|
||||
('SVT-AV1 构建配方', ROOT / 'deps/submodules/minirtc/thirdparty/svt-av1/xmake.lua'),
|
||||
]
|
||||
build_documents = []
|
||||
for index, (title, path) in enumerate(bundled):
|
||||
asset = f'about/build/{index}.txt'
|
||||
target = output / asset
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(path.read_text(), encoding='utf-8')
|
||||
build_documents.append({'title': title, 'asset': asset})
|
||||
for component in components:
|
||||
if component['id'] in {'minirtc', 'glib', 'libnice', 'openfec', 'openh264', 'openssl3', 'svt-av1'}:
|
||||
component['buildDocuments'] = build_documents[1:]
|
||||
documents = []
|
||||
for index, document in enumerate(component['documents']):
|
||||
asset = f"about/licenses/{component['id']}/{index}.txt"
|
||||
target = output / asset
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(document['text'], encoding='utf-8')
|
||||
documents.append({'title': document['title'], 'asset': asset,
|
||||
'sha256': hashlib.sha256(document['text'].encode('utf-8')).hexdigest()})
|
||||
component['documents'] = documents
|
||||
(output / 'ThirdPartyLicenses.json').write_text(json.dumps(
|
||||
{'schemaVersion': 1, 'components': components}, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
|
||||
tags = git('tag', '--points-at', 'HEAD').splitlines()
|
||||
tag = os.environ.get('CROSSDESK_SOURCE_TAG')
|
||||
if tag and tag not in tags:
|
||||
raise ValueError(f'Source tag {tag!r} does not point to the build commit')
|
||||
if not tag:
|
||||
versions = sorted(value for value in tags if value.startswith(('v', 'android-v')))
|
||||
tag = versions[0] if versions else None
|
||||
dirty = bool(git('status', '--porcelain', '--untracked-files=normal', '--ignore-submodules=none'))
|
||||
if os.environ.get('CROSSDESK_RELEASE_BUILD') == 'YES' and (dirty or not tag or not tag.startswith(('v', 'android-v'))):
|
||||
raise ValueError('Release source must be a clean checkout of a version tag, with matching submodules')
|
||||
metadata = {
|
||||
'schemaVersion': 1, 'revision': revision, 'tag': tag,
|
||||
'isModified': dirty,
|
||||
'sourceURL': source,
|
||||
'buildInstructionsURL': f'https://github.com/kunkundi/crossdesk/blob/{quote(revision, safe="")}/apps/android/README.md',
|
||||
'buildDocuments': build_documents, 'miniRTCRevision': minirtc,
|
||||
}
|
||||
(output / 'SourceMetadata.json').write_text(json.dumps(metadata, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
|
||||
|
||||
|
||||
def main():
|
||||
output = ANDROID / 'app/build/generated/notices'
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
(output / 'PRIVACY.md').write_text((ROOT / 'PRIVACY.md').read_text(encoding='utf-8'), encoding='utf-8')
|
||||
catalog = json.loads((ROOT / 'apps/ios/CrossDeskMobile/Resources/ThirdPartyLicenses.json').read_text())
|
||||
revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
|
||||
minirtc = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT / 'deps/submodules/minirtc', text=True).strip()
|
||||
parts = [
|
||||
'CrossDesk Android — open-source notices\n',
|
||||
'CrossDesk: GPL-3.0-only; MiniRTC: LGPL-3.0-only. Other components retain their own licenses.\n'
|
||||
'Open-source licenses govern use, modification and redistribution; their warranty limitations apply.\n'
|
||||
'You can rebuild/relink modified libraries and install an APK signed with your own key.\n',
|
||||
f'Application base revision: {revision}\nMiniRTC base revision: {minirtc}\n'
|
||||
'This development build may contain local changes in CrossDesk and the MiniRTC submodule.\n'
|
||||
'Source: https://github.com/kunkundi/crossdesk\n'
|
||||
'Build: apps/android/README.md; native source: deps/submodules/minirtc\n',
|
||||
(ROOT / 'LICENSE').read_text(),
|
||||
]
|
||||
for component in catalog['components']:
|
||||
if component['id'] not in COMPONENTS:
|
||||
continue
|
||||
parts.append(f"\n{component['name']} — {component['license']}\n{component['sourceURL']}\n")
|
||||
for document in component['documents']:
|
||||
parts.extend([document['title'], document['text']])
|
||||
additional = json.loads((ANDROID / 'licenses/additional-notices.json').read_text())
|
||||
for component in additional:
|
||||
parts.append(component['name']+' '+component['version'])
|
||||
for document in component['documents']:
|
||||
parts.extend([document['title'], document['text']])
|
||||
(output / 'THIRD_PARTY_NOTICES.txt').write_text('\n\n'.join(parts), encoding='utf-8')
|
||||
write_pages(output, catalog, additional, revision, minirtc)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,7 @@
|
||||
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
|
||||
dependencyResolutionManagement {
|
||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||
repositories { google(); mavenCentral() }
|
||||
}
|
||||
rootProject.name = 'CrossDeskAndroid'
|
||||
include ':app'
|
||||
@@ -0,0 +1,20 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDLTCCAhWgAwIBAgIUAl+BaiMSPm1zRwBr0qnyzpufOaIwDQYJKoZIhvcNAQEL
|
||||
BQAwJjEkMCIGA1UEAwwbQ3Jvc3NEZXNrIGxvY2FsIFRMUyB0ZXN0IENBMB4XDTI2
|
||||
MTAwMTA4MjYyMVoXDTM2MDkyODA4MjYyMVowJjEkMCIGA1UEAwwbQ3Jvc3NEZXNr
|
||||
IGxvY2FsIFRMUyB0ZXN0IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
|
||||
AQEAmEAURCIgoeNOGiXcII2v/0SEN8UJ3ItdQrU4A5jOQe2fD12mjOJsQAUQrq/j
|
||||
Bpz3cglAafJlOusgHqYyhFjHn58yZ1I+Z1jPa2CKeyWFYnmFUoL2yyNFmr3YMdkh
|
||||
3caTehZ0+dit6bDYwTvhUwI9CFXLacAZ60tzvnPn+IHmszNNH89mgfr/aJcuXZb/
|
||||
kSiJ/gUiiwp/PJznO9b0kjoJK6eZNoNNcqUyiVsBb0nL2+950GCbwvAA0px3PF/R
|
||||
/qtNstkMPFB6WuMvw/DsxKFDZ8/XbfjJBXi0Rpr+DEW+BOadlTH6Q+CcKxC/YG6q
|
||||
x2oxDGGr1Glz4SYE/OowCS7SaQIDAQABo1MwUTAdBgNVHQ4EFgQU9lut5DDz8k4A
|
||||
MUDIioygb+l+z64wHwYDVR0jBBgwFoAU9lut5DDz8k4AMUDIioygb+l+z64wDwYD
|
||||
VR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAJauLQRg5mnORh3fjenif
|
||||
nGmHMOlvuBtOFdHGcUYyzkfPuRBp2rCd2mL2rdnJfcyZJAaWQhP9ZZtThbioczTj
|
||||
Kf8UUTv2WYLKIWcZ1jyEEmukBhYxRpUfn4FqQG1yCqmF112coSCCY+7aGjl/Tcnx
|
||||
E5SKS/FhARnXwObBaiG4sZoOQ4fbC70I94xfY8uSu6h9uVnnZS05tVbUD2gATn57
|
||||
1snZUoJYTHi15QPZM3H/UViSYq2Inkw9yOcV3FRs6f8klePGVmUUDvT+I48jGjSz
|
||||
cg2zgNErBYvLEJ8FxHX5oxJZzVZAuVxugYu1Ru5kEl1XO1GRHRf4/8JIl1nyat0a
|
||||
hQ==
|
||||
-----END CERTIFICATE-----
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,71 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import org.json.*;
|
||||
import org.junit.*;
|
||||
import java.io.File;
|
||||
import java.nio.file.Files;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.FutureTask;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class AnnouncementInboxTest {
|
||||
private AnnouncementInbox inbox;
|
||||
private File directory;
|
||||
private final ArrayDeque<JSONObject> sent=new ArrayDeque<>();
|
||||
private interface Checked { void run() throws Exception; }
|
||||
private void main(Checked action)throws Exception {
|
||||
FutureTask<Void> task=new FutureTask<>(()->{action.run();return null;});
|
||||
InstrumentationRegistry.getInstrumentation().runOnMainSync(task);task.get();
|
||||
}
|
||||
@Before public void setup()throws Exception {
|
||||
directory=Files.createTempDirectory(InstrumentationRegistry.getInstrumentation().getTargetContext().getCacheDir().toPath(),"announcements-").toFile();
|
||||
main(()->{inbox=new AnnouncementInbox(directory);inbox.sender=(message,id)->sent.add(message);inbox.configure("Example.test.",9099,"123456789");inbox.setConnected(true);});
|
||||
}
|
||||
@After public void cleanup()throws Exception {
|
||||
main(()->inbox.close());
|
||||
try(var paths=Files.walk(directory.toPath())){for(var path:paths.sorted(Comparator.reverseOrder()).toList())Files.delete(path);}
|
||||
}
|
||||
private static JSONObject answer(JSONObject request,int count,long revision)throws Exception {
|
||||
int offset=request.getInt("offset");boolean summary=request.getBoolean("summary_only");JSONArray items=new JSONArray();
|
||||
for(int i=offset;i<Math.min(count,offset+(summary?200:20));i++){
|
||||
JSONObject item=new JSONObject().put("id",i+1).put("revision",revision);
|
||||
if(!summary)item.put("title",i==0?"欢迎使用 CrossDesk":"公告 "+(i+1)).put("body","安卓公告与 iOS 保持一致。\n\n访问 [CrossDesk 官网](https://crossdesk.cn) 了解更多。\n支持中文、换行与网页链接。").put("updated_at",1790812800L);
|
||||
items.put(item);
|
||||
}
|
||||
return new JSONObject().put("type","announcements").put("request_id",request.getString("request_id"))
|
||||
.put("summary_only",summary).put("offset",offset).put("total",count).put("catalog_revision",revision).put("items",items);
|
||||
}
|
||||
private void drain(int count,long revision)throws Exception {
|
||||
int limit=100;while(!sent.isEmpty()){assertTrue("Request loop",limit-->0);inbox.receive(answer(sent.remove(),count,revision));}
|
||||
}
|
||||
@Test public void summariesCountAllUnreadAndBodiesPageInTwenties()throws Exception {main(()->{
|
||||
JSONObject first=sent.remove();inbox.receive(answer(first,203,1));assertEquals(200,sent.peek().getInt("offset"));assertEquals(0,inbox.items.size());
|
||||
inbox.receive(answer(sent.remove(),203,1));assertEquals(203,inbox.unread);assertFalse(sent.peek().getBoolean("summary_only"));
|
||||
drain(203,1);assertEquals(20,inbox.items.size());assertEquals(203,inbox.total);assertFalse(inbox.loading);assertTrue(inbox.loaded);
|
||||
inbox.loadMore();assertEquals(20,sent.peek().getInt("offset"));drain(203,1);assertEquals(40,inbox.items.size());
|
||||
});}
|
||||
@Test public void readAndDeletePersistPerRevisionAndScope()throws Exception {main(()->{
|
||||
drain(3,1);inbox.markRead(inbox.items.get(0));inbox.dismiss(inbox.items.get(1));assertEquals(1,inbox.unread);assertEquals(2,inbox.total);
|
||||
inbox.close();inbox=new AnnouncementInbox(directory);inbox.sender=(message,id)->sent.add(message);
|
||||
inbox.configure("example.TEST",9099,"123456789");inbox.setConnected(true);drain(3,1);
|
||||
assertEquals(2,inbox.items.size());assertTrue(inbox.items.get(0).read);assertEquals(1,inbox.unread);
|
||||
inbox.refresh();drain(3,2);assertEquals(3,inbox.total);assertEquals(3,inbox.unread);assertEquals(3,inbox.items.size());
|
||||
inbox.configure("other.test",9099,"123456789");drain(3,1);assertEquals(3,inbox.unread);
|
||||
inbox.configure("example.test",9099,"different-device");drain(3,1);assertEquals(3,inbox.unread);
|
||||
inbox.configure("example.test",9999,"123456789");drain(3,1);assertEquals(3,inbox.unread);
|
||||
inbox.configure("example.test",9099,"123456789");drain(3,1);assertEquals(1,inbox.unread);
|
||||
});}
|
||||
|
||||
@Test public void malformedResponseFailsWithoutLosingVisibleRowsAndCanRetry()throws Exception {main(()->{
|
||||
drain(2,1);inbox.refresh();JSONObject invalid=answer(sent.remove(),2,1);invalid.put("total","2");inbox.receive(invalid);
|
||||
assertTrue(inbox.failed);assertFalse(inbox.loading);assertEquals(2,inbox.items.size());
|
||||
inbox.refresh();drain(2,2);assertFalse(inbox.failed);
|
||||
inbox.refresh();JSONObject summary=answer(sent.remove(),2,3);summary.getJSONArray("items").getJSONObject(1).put("id",1);inbox.receive(summary);
|
||||
assertTrue(inbox.failed);inbox.refresh();drain(2,3);assertFalse(inbox.failed);
|
||||
inbox.refresh();inbox.receive(answer(sent.remove(),2,4));JSONObject body=answer(sent.remove(),2,4);
|
||||
body.getJSONArray("items").getJSONObject(0).put("body","中".repeat(2667));inbox.receive(body);assertTrue(inbox.failed);assertEquals(0,inbox.items.size());
|
||||
inbox.refresh();drain(2,4);assertFalse(inbox.failed);
|
||||
});}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
import androidx.test.core.app.ActivityScenario;
|
||||
import androidx.lifecycle.Lifecycle;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import android.app.Dialog;
|
||||
import android.content.Context;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.TextView;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
public class AppUpdateCheckerTest {
|
||||
private static final class Fixture implements RemoteVersionCheck.Fetcher {
|
||||
int cancelled;
|
||||
final List<Consumer<byte[]>> replies = new ArrayList<>();
|
||||
final AppUpdateChecker checker = new AppUpdateChecker("1.6.0", this,
|
||||
(version, data) -> new String(data, StandardCharsets.UTF_8), () -> {});
|
||||
public RemoteVersionCheck.Cancellation fetch(Consumer<byte[]> reply) {
|
||||
replies.add(reply); return () -> cancelled++;
|
||||
}
|
||||
void reply(String result) { replies.get(replies.size()-1).accept(result == null ? null : result.getBytes(StandardCharsets.UTF_8)); }
|
||||
}
|
||||
|
||||
@Test public void everyVisitChecksOnceAndConcurrentTriggersDeduplicate() {
|
||||
Fixture f = new Fixture();
|
||||
f.checker.checkNow(); assertTrue(f.replies.isEmpty());
|
||||
f.checker.setEnabled(true); f.checker.checkNow(); f.checker.setEnabled(true);
|
||||
assertEquals(1, f.replies.size());
|
||||
f.reply("1.7.0"); assertTrue(f.checker.updateAvailable());
|
||||
f.checker.setEnabled(true); assertEquals(1, f.replies.size());
|
||||
f.checker.setEnabled(false); f.checker.setEnabled(true);
|
||||
assertEquals(2, f.replies.size());
|
||||
f.reply(""); assertFalse(f.checker.updateAvailable());
|
||||
assertEquals(AppUpdateChecker.Status.UP_TO_DATE, f.checker.status);
|
||||
f.checker.checkNow(); assertEquals(3, f.replies.size());
|
||||
}
|
||||
|
||||
@Test public void failedChecksRetainBadgeUntilAnotherExplicitCheck() {
|
||||
Fixture f = new Fixture(); f.checker.setEnabled(true); f.reply("1.7.0");
|
||||
f.checker.checkNow(); f.reply(null);
|
||||
assertEquals(AppUpdateChecker.Status.FAILED, f.checker.status);
|
||||
assertTrue(f.checker.updateAvailable());
|
||||
f.checker.setEnabled(true); assertEquals(2, f.replies.size());
|
||||
f.checker.checkNow(); assertEquals(3, f.replies.size());
|
||||
f.reply(""); assertFalse(f.checker.updateAvailable());
|
||||
}
|
||||
|
||||
@Test public void backgroundAndRevocationCancelAndIgnoreStaleReplies() {
|
||||
Fixture f = new Fixture(); f.checker.setEnabled(true); f.checker.setEnabled(false);
|
||||
assertEquals(1, f.cancelled);
|
||||
f.reply("9.0.0"); assertFalse(f.checker.updateAvailable());
|
||||
f.checker.setEnabled(true); assertEquals(2, f.replies.size());
|
||||
f.replies.get(0).accept("9.0.0".getBytes(StandardCharsets.UTF_8));
|
||||
assertEquals(AppUpdateChecker.Status.CHECKING, f.checker.status);
|
||||
f.reply("1.7.0"); f.checker.setEnabled(false); f.checker.checkNow();
|
||||
assertEquals(2, f.replies.size()); f.checker.setEnabled(true);
|
||||
assertEquals(3, f.replies.size()); assertTrue(f.checker.updateAvailable());
|
||||
}
|
||||
|
||||
@Test public void nativeParserSeparatesMobileFromDesktopAndInvalidMetadata() {
|
||||
byte[] manifest = "{\"latest_version\":\"99.0.0\",\"patch\":99,\"downloads\":{\"ios-arm64\":{\"version\":\"0.0.2\"},\"android-arm64\":{\"version\":\"1.6.0-2-20261002\"}}}".getBytes(StandardCharsets.UTF_8);
|
||||
assertEquals("1.6.0-2", NativeSession.nCheckMobileUpdate("1.6.0", manifest));
|
||||
assertEquals("", NativeSession.nCheckMobileUpdate("1.6.0-2", manifest));
|
||||
assertEquals("", NativeSession.nCheckMobileUpdate("1.7.0", manifest));
|
||||
assertNull(NativeSession.nCheckMobileUpdate("", manifest));
|
||||
assertNull(NativeSession.nCheckMobileUpdate("1.6.0", "{\"version\":\"99.0.0\"}".getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
@Test public void settingsAndAboutReflectUpdatesWithoutReopeningThePage() {
|
||||
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
|
||||
var preferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
|
||||
boolean hadConsent = preferences.contains("networkConsent");
|
||||
boolean consent = preferences.getBoolean("networkConsent", false);
|
||||
preferences.edit().putBoolean("networkConsent", false).commit();
|
||||
try (ActivityScenario<MainActivity> scenario = ActivityScenario.launch(MainActivity.class)) {
|
||||
scenario.onActivity(activity -> {
|
||||
((Dialog)field(activity, "privacyDialog")).dismiss();
|
||||
List<Consumer<byte[]>> replies = new ArrayList<>();
|
||||
AppUpdateChecker checker = new AppUpdateChecker("1.6.0",
|
||||
reply -> { replies.add(reply); return () -> {}; },
|
||||
(version, data) -> new String(data, StandardCharsets.UTF_8),
|
||||
() -> invoke(activity, "renderAppUpdates"));
|
||||
try {
|
||||
var field = MainActivity.class.getDeclaredField("appUpdates");
|
||||
field.setAccessible(true); field.set(activity, checker);
|
||||
} catch (Exception error) { throw new AssertionError(error); }
|
||||
assertEquals(View.GONE, ((View)field(activity, "settingsUpdateDot")).getVisibility());
|
||||
checker.setEnabled(true);
|
||||
replies.get(0).accept("1.7.0".getBytes(StandardCharsets.UTF_8));
|
||||
assertEquals(View.VISIBLE, ((View)field(activity, "settingsUpdateDot")).getVisibility());
|
||||
assertEquals("设置,有新版本", ((View)field(activity, "settingsUpdateButton")).getContentDescription());
|
||||
((View)field(activity, "settingsUpdateButton")).performClick();
|
||||
assertEquals(View.VISIBLE, ((View)field(activity, "aboutUpdateDot")).getVisibility());
|
||||
((View)field(activity, "aboutUpdateRow")).performClick();
|
||||
assertNotNull(findText(activity.getWindow().getDecorView(), "新版本可用:v1.7.0"));
|
||||
checker.checkNow(); replies.get(1).accept(null);
|
||||
assertNotNull(findText(activity.getWindow().getDecorView(), "新版本可用:v1.7.0"));
|
||||
checker.checkNow(); replies.get(2).accept(new byte[0]);
|
||||
invoke(activity, "settings");
|
||||
assertEquals(View.GONE, ((View)field(activity, "aboutUpdateDot")).getVisibility());
|
||||
checker.setEnabled(false);
|
||||
});
|
||||
} finally {
|
||||
if (hadConsent) preferences.edit().putBoolean("networkConsent", consent).commit();
|
||||
else preferences.edit().remove("networkConsent").commit();
|
||||
}
|
||||
}
|
||||
|
||||
@Test public void activityVisitsAndConnectionTeardownTriggerChecks() {
|
||||
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
|
||||
var preferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
|
||||
boolean hadConsent = preferences.contains("networkConsent");
|
||||
boolean consent = preferences.getBoolean("networkConsent", false);
|
||||
preferences.edit().putBoolean("networkConsent", false).commit();
|
||||
Fixture f = new Fixture();
|
||||
try (ActivityScenario<MainActivity> scenario = ActivityScenario.launch(MainActivity.class)) {
|
||||
scenario.onActivity(activity -> {
|
||||
((Dialog)field(activity, "privacyDialog")).dismiss();
|
||||
try {
|
||||
var field = MainActivity.class.getDeclaredField("appUpdates");
|
||||
field.setAccessible(true); field.set(activity, f.checker);
|
||||
} catch (Exception error) { throw new AssertionError(error); }
|
||||
});
|
||||
scenario.moveToState(Lifecycle.State.CREATED);
|
||||
preferences.edit().putBoolean("networkConsent", true).commit();
|
||||
scenario.moveToState(Lifecycle.State.RESUMED);
|
||||
scenario.onActivity(activity -> {
|
||||
assertEquals(1, f.replies.size()); f.reply("1.7.0");
|
||||
endConnection(activity);
|
||||
assertEquals(2, f.replies.size()); f.reply(null);
|
||||
assertTrue(f.checker.updateAvailable());
|
||||
endConnection(activity);
|
||||
assertEquals(3, f.replies.size()); f.reply("");
|
||||
assertFalse(f.checker.updateAvailable());
|
||||
});
|
||||
scenario.moveToState(Lifecycle.State.CREATED);
|
||||
scenario.onActivity(activity -> {
|
||||
endConnection(activity); assertEquals(3, f.replies.size());
|
||||
});
|
||||
scenario.moveToState(Lifecycle.State.RESUMED);
|
||||
scenario.onActivity(activity -> assertEquals(4, f.replies.size()));
|
||||
} finally {
|
||||
if (hadConsent) preferences.edit().putBoolean("networkConsent", consent).commit();
|
||||
else preferences.edit().remove("networkConsent").commit();
|
||||
}
|
||||
}
|
||||
|
||||
private static void endConnection(MainActivity activity) {
|
||||
try {
|
||||
var method = MainActivity.class.getDeclaredMethod("end", String.class);
|
||||
method.setAccessible(true); method.invoke(activity, "");
|
||||
} catch (Exception error) { throw new AssertionError(error); }
|
||||
}
|
||||
|
||||
private static Object field(MainActivity activity, String name) {
|
||||
try { var field = MainActivity.class.getDeclaredField(name); field.setAccessible(true); return field.get(activity); }
|
||||
catch (Exception error) { throw new AssertionError(error); }
|
||||
}
|
||||
private static void invoke(MainActivity activity, String name) {
|
||||
try { var method = MainActivity.class.getDeclaredMethod(name); method.setAccessible(true); method.invoke(activity); }
|
||||
catch (Exception error) { throw new AssertionError(error); }
|
||||
}
|
||||
private static TextView findText(View view, String text) {
|
||||
if (view instanceof TextView && ((TextView)view).getText().toString().equals(text)) return (TextView)view;
|
||||
if (view instanceof ViewGroup) for (int i = 0; i < ((ViewGroup)view).getChildCount(); i++) {
|
||||
TextView found = findText(((ViewGroup)view).getChildAt(i), text);
|
||||
if (found != null) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.Context;
|
||||
import android.view.KeyEvent;
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
public class ControllerTest {
|
||||
|
||||
@Test public void presenceCallbacksRejectDisconnectedAndPreviousSignalingGeneration()throws Exception{
|
||||
var instrumentation=InstrumentationRegistry.getInstrumentation();
|
||||
var delivered=new java.util.concurrent.atomic.AtomicInteger();
|
||||
NativeSession.Listener listener=new NativeSession.Listener(){
|
||||
public void status(String value){}public void connected(){}public void ended(String reason){}
|
||||
public void data(JSONObject value){}public void videoSize(int width,int height){}public void clipboard(String value){}public void statistics(RemoteNetworkStatistics.Snapshot value){}
|
||||
public void presence(JSONObject value){delivered.incrementAndGet();}
|
||||
};
|
||||
NativeSession session=new NativeSession(instrumentation.getTargetContext(),"127.0.0.1",1,"","",listener);
|
||||
Field workerField=NativeSession.class.getDeclaredField("RTC"),requestedField=NativeSession.class.getDeclaredField("presenceRequested");workerField.setAccessible(true);requestedField.setAccessible(true);
|
||||
ExecutorService worker=(ExecutorService)workerField.get(null);
|
||||
var event=NativeSession.class.getDeclaredMethod("onNativeEvent",int.class,byte[].class);event.setAccessible(true);
|
||||
java.util.function.BiConsumer<Integer,String> send=(type,json)->{
|
||||
try{event.invoke(session,type,json.getBytes(java.nio.charset.StandardCharsets.UTF_8));}catch(Exception error){throw new RuntimeException(error);}
|
||||
};
|
||||
try{
|
||||
send.accept(1,"{\"controller\":false,\"status\":1,\"generation\":1}");
|
||||
worker.submit(()->{requestedField.setBoolean(session,true);return null;}).get(5,TimeUnit.SECONDS);
|
||||
send.accept(9,"{\"type\":\"presence\",\"devices\":[],\"generation\":1}");
|
||||
worker.submit(()->{}).get(5,TimeUnit.SECONDS);instrumentation.waitForIdleSync();assertEquals(1,delivered.get());
|
||||
send.accept(1,"{\"controller\":false,\"status\":4,\"generation\":2}");
|
||||
send.accept(9,"{\"type\":\"presence\",\"devices\":[],\"generation\":1}");
|
||||
send.accept(1,"{\"controller\":false,\"status\":1,\"generation\":3}");
|
||||
worker.submit(()->{requestedField.setBoolean(session,true);return null;}).get(5,TimeUnit.SECONDS);
|
||||
send.accept(9,"{\"type\":\"presence\",\"devices\":[],\"generation\":1}");
|
||||
worker.submit(()->{}).get(5,TimeUnit.SECONDS);instrumentation.waitForIdleSync();assertEquals(1,delivered.get());
|
||||
send.accept(1,"{\"controller\":false,\"status\":1,\"generation\":3}");
|
||||
send.accept(9,"{\"type\":\"presence_update\",\"id\":\"123456789\",\"online\":true,\"generation\":3}");
|
||||
worker.submit(()->{}).get(5,TimeUnit.SECONDS);instrumentation.waitForIdleSync();assertEquals("Repeated login readiness keeps the current subscription",2,delivered.get());
|
||||
}finally{session.close();worker.submit(()->{}).get(5,TimeUnit.SECONDS);}
|
||||
}
|
||||
|
||||
@Test public void repeatedNativeConnectedEventsNotifyAndInitializeOnlyOnce()throws Exception{
|
||||
var instrumentation=InstrumentationRegistry.getInstrumentation();
|
||||
var notifications=new java.util.concurrent.atomic.AtomicInteger();
|
||||
NativeSession.Listener listener=new NativeSession.Listener(){
|
||||
public void status(String value){}public void connected(){notifications.incrementAndGet();}public void ended(String reason){}
|
||||
public void data(JSONObject value){}public void videoSize(int width,int height){}public void clipboard(String value){}public void statistics(RemoteNetworkStatistics.Snapshot value){}
|
||||
};
|
||||
NativeSession session=new NativeSession(instrumentation.getTargetContext(),"127.0.0.1",1,"123456789","test",listener);
|
||||
Field workerField=NativeSession.class.getDeclaredField("RTC"),audioField=NativeSession.class.getDeclaredField("audio");workerField.setAccessible(true);audioField.setAccessible(true);
|
||||
ExecutorService worker=(ExecutorService)workerField.get(null);
|
||||
var event=NativeSession.class.getDeclaredMethod("onNativeEvent",int.class,byte[].class);event.setAccessible(true);
|
||||
byte[] connected="{\"status\":1}".getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
try{
|
||||
// Exercise the Java native-callback path without starting a network peer.
|
||||
event.invoke(session,2,connected);Object audio=worker.submit(()->audioField.get(session)).get(5,TimeUnit.SECONDS);
|
||||
instrumentation.waitForIdleSync();assertEquals(1,notifications.get());assertNotNull(audio);
|
||||
event.invoke(session,2,connected);event.invoke(session,2,connected);
|
||||
assertSame("Duplicate readiness must not replace the audio player",audio,worker.submit(()->audioField.get(session)).get(5,TimeUnit.SECONDS));
|
||||
instrumentation.waitForIdleSync();assertEquals("One desktop connection must notify the UI only once",1,notifications.get());
|
||||
}finally{session.close();worker.submit(()->{}).get(5,TimeUnit.SECONDS);}
|
||||
}
|
||||
@Test public void keyboardSupportsDesktopVirtualKeys() {
|
||||
assertEquals(0x41, KeyMap.windowsCode(KeyEvent.KEYCODE_A));
|
||||
assertEquals(0x2E, KeyMap.windowsCode(KeyEvent.KEYCODE_FORWARD_DEL));
|
||||
assertEquals(0x11, KeyMap.windowsCode(KeyEvent.KEYCODE_CTRL_LEFT));
|
||||
assertEquals(0x5B, KeyMap.windowsCode(KeyEvent.KEYCODE_META_LEFT));
|
||||
assertEquals(0xDB | 0x100, KeyMap.ascii('{'));
|
||||
assertEquals(0x31 | 0x100, KeyMap.ascii('!'));
|
||||
assertEquals(0, KeyMap.ascii('中'));
|
||||
}
|
||||
|
||||
@Test public void credentialsRemainEncryptedAndServerScoped() throws Exception {
|
||||
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
|
||||
SecretStore store = new SecretStore(context);
|
||||
String scope = "instrumentation.invalid:9099";
|
||||
try {
|
||||
store.put(scope, "test-id@temporary-test-password");
|
||||
assertEquals("test-id@temporary-test-password", store.get(scope));
|
||||
assertEquals("", store.get("instrumentation.invalid:9100"));
|
||||
String persisted = context.getSharedPreferences("identities", Context.MODE_PRIVATE).getString(scope, "");
|
||||
assertFalse(persisted.contains("temporary-test-password"));
|
||||
} finally {
|
||||
context.getSharedPreferences("identities", Context.MODE_PRIVATE).edit().remove(scope).commit();
|
||||
}
|
||||
}
|
||||
|
||||
@Test public void nativePeerCanStartAndCancelRepeatedly() throws Exception {
|
||||
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
|
||||
Field workerField = NativeSession.class.getDeclaredField("RTC"); workerField.setAccessible(true);
|
||||
ExecutorService worker = (ExecutorService) workerField.get(null);
|
||||
Field handleField = NativeSession.class.getDeclaredField("handle"); handleField.setAccessible(true);
|
||||
NativeSession.Listener listener = new NativeSession.Listener() {
|
||||
public void status(String value) { }
|
||||
public void connected() { fail("Loopback port 1 must not establish a session"); }
|
||||
public void ended(String reason) { }
|
||||
public void data(JSONObject data) { }
|
||||
public void videoSize(int width, int height) { }
|
||||
public void clipboard(String value) { }
|
||||
public void statistics(RemoteNetworkStatistics.Snapshot value) { }
|
||||
};
|
||||
for (int i = 0; i < 3; i++) {
|
||||
NativeSession session = new NativeSession(context, "127.0.0.1", 1, "invalid", "test", listener);
|
||||
session.start();
|
||||
assertTrue(worker.submit(() -> handleField.getLong(session)).get(15, TimeUnit.SECONDS) != 0);
|
||||
session.surface(null);
|
||||
session.close(); session.close();
|
||||
assertEquals(0L, (long) worker.submit(() -> handleField.getLong(session)).get(15, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import org.json.JSONObject;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class NetworkStatisticsTest {
|
||||
static JSONObject report(int mode,boolean srtp,double rtt)throws Exception{
|
||||
return new JSONObject().put("mode",mode).put("srtp",srtp).put("rtt",rtt).put("video",traffic(8000000,0,.02)).put("audio",traffic(64000,0,.01)).put("data",traffic(2000,3000,.03)).put("total",traffic(8066000,3000,.06));
|
||||
}
|
||||
private static JSONObject traffic(long in,long out,double loss)throws Exception{return new JSONObject().put("inbound",in).put("outbound",out).put("loss",loss);}
|
||||
|
||||
@Test public void staleReportsAndRttExpireIndependently()throws Exception{
|
||||
RemoteNetworkStatistics state=new RemoteNetworkStatistics();state.receive(new RemoteNetworkStatistics.Report(report(0,true,20)),10);state.receive(new RemoteNetworkStatistics.Report(report(0,true,100)),11);assertEquals(40,state.snapshot(11).rtt,.0001);
|
||||
for(double invalid:new double[]{-1,2001})state.receive(new RemoteNetworkStatistics.Report(report(0,true,invalid)),12);
|
||||
assertEquals(40,state.snapshot(13.99).rtt,.0001);assertTrue(Double.isNaN(state.snapshot(14).rtt));assertNotNull(state.snapshot(14).report);assertNull(state.snapshot(15).report);
|
||||
state.receive(new RemoteNetworkStatistics.Report(report(0,true,0)),16);assertEquals(0,state.snapshot(16).rtt,0);
|
||||
}
|
||||
@Test public void submittedFramesAreCountedOnceAndIdleVideoExpires(){
|
||||
RemoteNetworkStatistics state=new RemoteNetworkStatistics();state.frame(1,100,1920,1080,10);state.frame(1,100,1920,1080,10.1);state.frame(2,200,1920,1080,10.2);
|
||||
assertEquals(2,state.snapshot(10.3).fps);assertEquals(150,state.snapshot(10.3).latency,.0001);assertEquals("1920 × 1080",state.snapshot(10.3).resolution());assertEquals(1,state.snapshot(11).fps);assertEquals(0,state.snapshot(11.3).fps);assertTrue(Double.isNaN(state.snapshot(11.3).latency));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.app.Dialog;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.CheckBox;
|
||||
import android.widget.TextView;
|
||||
import androidx.lifecycle.Lifecycle;
|
||||
import androidx.test.core.app.ActivityScenario;
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
public class PrivacyConsentTest {
|
||||
private SharedPreferences preferences;
|
||||
private Map<String,?> saved;
|
||||
|
||||
@Before public void prepare(){
|
||||
Context context=InstrumentationRegistry.getInstrumentation().getTargetContext();
|
||||
preferences=context.getSharedPreferences("settings",Context.MODE_PRIVATE);saved=preferences.getAll();
|
||||
preferences.edit().remove("networkConsent").putString("host","127.0.0.1").putInt("port",1).commit();
|
||||
}
|
||||
@After public void restore(){
|
||||
SharedPreferences.Editor edit=preferences.edit();
|
||||
for(String key:new String[]{"networkConsent","host","port"}){
|
||||
edit.remove(key);Object value=saved.get(key);
|
||||
if(value instanceof Boolean)edit.putBoolean(key,(Boolean)value);
|
||||
else if(value instanceof String)edit.putString(key,(String)value);
|
||||
else if(value instanceof Integer)edit.putInt(key,(Integer)value);
|
||||
}
|
||||
edit.commit();
|
||||
}
|
||||
private static Object field(MainActivity activity,String name){
|
||||
try{var field=MainActivity.class.getDeclaredField(name);field.setAccessible(true);return field.get(activity);}
|
||||
catch(Exception error){throw new AssertionError(error);}
|
||||
}
|
||||
private static Dialog notice(MainActivity activity){
|
||||
Dialog dialog=(Dialog)field(activity,"privacyDialog");assertNotNull("An unconsented visit must prompt",dialog);assertTrue(dialog.isShowing());return dialog;
|
||||
}
|
||||
private static TextView findText(View view,String text){
|
||||
if(view instanceof TextView&&((TextView)view).getText().toString().equals(text))return (TextView)view;
|
||||
if(view instanceof ViewGroup){ViewGroup parent=(ViewGroup)view;for(int i=0;i<parent.getChildCount();i++){TextView found=findText(parent.getChildAt(i),text);if(found!=null)return found;}}
|
||||
return null;
|
||||
}
|
||||
private static TextView action(Dialog dialog,String text){
|
||||
TextView view=findText(dialog.getWindow().getDecorView(),text);assertNotNull(text,view);return view;
|
||||
}
|
||||
private static void decline(MainActivity activity){action(notice(activity),"暂不同意").performClick();}
|
||||
private static void agree(MainActivity activity){
|
||||
Dialog dialog=notice(activity);action(dialog,"我已阅读并同意《隐私政策》").performClick();action(dialog,"同意并继续").performClick();
|
||||
}
|
||||
|
||||
@Test public void coldLaunchRequiresExplicitAgreementBeforeNetworking(){
|
||||
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
|
||||
scenario.onActivity(activity->{
|
||||
Dialog dialog=notice(activity);
|
||||
assertFalse(((CheckBox)action(dialog,"我已阅读并同意《隐私政策》")).isChecked());
|
||||
assertFalse(action(dialog,"同意并继续").isEnabled());
|
||||
action(dialog,"同意并继续").performClick();
|
||||
assertTrue(dialog.isShowing());assertFalse(preferences.getBoolean("networkConsent",false));
|
||||
assertNull(field(activity,"signaling"));
|
||||
decline(activity);assertFalse(dialog.isShowing());assertNull(field(activity,"signaling"));
|
||||
assertNotNull(findText(activity.getWindow().getDecorView(),"等待隐私授权"));
|
||||
});
|
||||
scenario.onActivity(activity->assertNull(field(activity,"privacyDialog")));
|
||||
}
|
||||
}
|
||||
@Test public void refusalPromptsOnBackgroundReturnButNotTransientInactivity(){
|
||||
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
|
||||
scenario.onActivity(PrivacyConsentTest::decline);
|
||||
scenario.moveToState(Lifecycle.State.STARTED).moveToState(Lifecycle.State.RESUMED);
|
||||
scenario.onActivity(activity->{assertNull(field(activity,"privacyDialog"));assertNull(field(activity,"signaling"));});
|
||||
for(int visit=0;visit<3;visit++){
|
||||
scenario.moveToState(Lifecycle.State.CREATED).moveToState(Lifecycle.State.RESUMED);
|
||||
scenario.onActivity(activity->{notice(activity);assertNull(field(activity,"signaling"));decline(activity);});
|
||||
}
|
||||
}
|
||||
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
|
||||
scenario.onActivity(activity->{notice(activity);assertNull(field(activity,"signaling"));});
|
||||
}
|
||||
}
|
||||
@Test public void backgroundDismissesOldDialogAndClearsTheCheckbox(){
|
||||
Dialog[] original={null};
|
||||
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
|
||||
scenario.onActivity(activity->{original[0]=notice(activity);action(original[0],"我已阅读并同意《隐私政策》").performClick();assertTrue(action(original[0],"同意并继续").isEnabled());});
|
||||
scenario.moveToState(Lifecycle.State.CREATED);
|
||||
assertFalse(original[0].isShowing());
|
||||
scenario.moveToState(Lifecycle.State.RESUMED);
|
||||
scenario.onActivity(activity->{Dialog next=notice(activity);assertNotSame(original[0],next);assertFalse(action(next,"同意并继续").isEnabled());assertNull(field(activity,"signaling"));});
|
||||
}
|
||||
}
|
||||
@Test public void agreementPersistsAndStopsAutomaticPrompts(){
|
||||
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
|
||||
scenario.onActivity(activity->{Dialog dialog=notice(activity);agree(activity);assertTrue(preferences.getBoolean("networkConsent",false));assertFalse(dialog.isShowing());assertNotNull(field(activity,"signaling"));});
|
||||
scenario.onActivity(activity->assertNull(field(activity,"privacyDialog")));
|
||||
scenario.moveToState(Lifecycle.State.CREATED).moveToState(Lifecycle.State.RESUMED);
|
||||
scenario.onActivity(activity->assertNull(field(activity,"privacyDialog")));
|
||||
}
|
||||
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
|
||||
scenario.onActivity(activity->assertNull(field(activity,"privacyDialog")));
|
||||
scenario.moveToState(Lifecycle.State.CREATED);
|
||||
preferences.edit().putBoolean("networkConsent",false).commit();
|
||||
scenario.moveToState(Lifecycle.State.RESUMED);
|
||||
scenario.onActivity(activity->{notice(activity);assertNull(field(activity,"signaling"));});
|
||||
}
|
||||
}
|
||||
@Test public void existingLocalRecordsDoNotImplyConsent(){
|
||||
Context context=InstrumentationRegistry.getInstrumentation().getTargetContext();
|
||||
SharedPreferences identities=context.getSharedPreferences("identities",Context.MODE_PRIVATE);
|
||||
String key="privacy-upgrade.invalid:1";
|
||||
try{
|
||||
identities.edit().putString(key,"existing-device-identity").commit();
|
||||
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
|
||||
scenario.onActivity(activity->{notice(activity);assertNull(field(activity,"signaling"));});
|
||||
}
|
||||
}finally{identities.edit().remove(key).commit();}
|
||||
}
|
||||
@Test public void bundledChinesePolicyIsOfflineAndMissingPolicyCannotAuthorize(){
|
||||
Context context=InstrumentationRegistry.getInstrumentation().getTargetContext();
|
||||
PrivacyPolicyDocument policy=new PrivacyPolicyDocument(context);
|
||||
assertTrue(policy.available);assertTrue(policy.text.contains("更新日期:"));assertTrue(policy.text.contains("查询与删除请求"));assertFalse(policy.text.contains("## English"));
|
||||
assertFalse(new PrivacyPolicyDocument(" \n").available);
|
||||
try(ActivityScenario<MainActivity> scenario=ActivityScenario.launch(MainActivity.class)){
|
||||
scenario.onActivity(activity->{
|
||||
decline(activity);int[] accepted={0};
|
||||
Dialog missing=new PrivacyConsentDialog(activity,new MobileUi(activity),new PrivacyPolicyDocument((String)null),()->accepted[0]++);
|
||||
try{
|
||||
missing.show();action(missing,"我已阅读并同意《隐私政策》").performClick();
|
||||
assertFalse(action(missing,"同意并继续").isEnabled());action(missing,"同意并继续").performClick();
|
||||
assertEquals(0,accepted[0]);assertFalse(preferences.getBoolean("networkConsent",false));assertNull(field(activity,"signaling"));
|
||||
action(missing,"暂不同意").performClick();assertFalse(missing.isShowing());
|
||||
}finally{missing.dismiss();}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.Test;
|
||||
import java.util.ArrayList;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class RecentConnectionPresenceTest {
|
||||
private static JSONArray records(String... ids)throws Exception{
|
||||
JSONArray result=new JSONArray();for(String id:ids)result.put(new JSONObject().put("id",id));return result;
|
||||
}
|
||||
private static JSONObject device(String id,boolean online)throws Exception{return new JSONObject().put("id",id).put("online",online);}
|
||||
private static JSONObject snapshot(JSONObject... devices)throws Exception{
|
||||
JSONArray values=new JSONArray();for(JSONObject device:devices)values.put(device);return new JSONObject().put("type","presence").put("devices",values);
|
||||
}
|
||||
private static JSONObject update(String id,boolean online)throws Exception{return device(id,online).put("type","presence_update");}
|
||||
|
||||
@Test public void snapshotAndUpdatesOnlyAffectWatchedDevicesAndSortStably()throws Exception{
|
||||
RecentConnectionPresence presence=new RecentConnectionPresence();JSONArray history=records("111111111","222222222","333333333");
|
||||
presence.watch(history,0);presence.setConnected(true,0);
|
||||
presence.receive(update("111111111",true),1);assertFalse(presence.isOnline("111111111",1));
|
||||
presence.receive(snapshot(device("222222222",true),device("333333333",true),device("999999999",true)),2);
|
||||
assertFalse(presence.isOnline("999999999",2));assertTrue(presence.isOnline("222222222",2));
|
||||
JSONArray ordered=presence.ordered(history,2);assertEquals("222222222",ordered.getJSONObject(0).getString("id"));assertEquals("333333333",ordered.getJSONObject(1).getString("id"));
|
||||
presence.receive(update("222222222",false),3);assertFalse(presence.isOnline("222222222",3));
|
||||
assertEquals("333333333",presence.ordered(history,3).getJSONObject(0).getString("id"));
|
||||
presence.receive(snapshot(device("111111111",true)),4);assertFalse("A full snapshot replaces missing devices",presence.isOnline("333333333",4));
|
||||
}
|
||||
|
||||
@Test public void refreshExpiryAndReconnectRequireFreshSnapshot()throws Exception{
|
||||
RecentConnectionPresence presence=new RecentConnectionPresence();ArrayList<JSONArray> requests=new ArrayList<>();presence.sender=requests::add;
|
||||
presence.watch(records("111111111"),0);assertTrue(requests.isEmpty());presence.setConnected(true,0);assertEquals(1,requests.size());
|
||||
presence.receive(snapshot(device("111111111",true)),0);presence.maintain(29_999);assertEquals(1,requests.size());
|
||||
presence.maintain(30_000);assertEquals(2,requests.size());assertTrue(presence.isOnline("111111111",59_999));
|
||||
presence.maintain(60_000);assertEquals(3,requests.size());assertFalse(presence.isOnline("111111111",60_000));
|
||||
presence.receive(update("111111111",true),60_001);assertTrue(presence.isOnline("111111111",60_001));
|
||||
presence.setConnected(false,60_002);presence.receive(snapshot(device("111111111",true)),60_003);presence.maintain(120_000);assertEquals(3,requests.size());assertFalse(presence.isOnline("111111111",120_000));
|
||||
presence.setConnected(true,120_001);assertEquals(4,requests.size());presence.receive(update("111111111",true),120_002);assertFalse(presence.isOnline("111111111",120_002));
|
||||
presence.receive(snapshot(device("111111111",true)),120_003);assertTrue(presence.isOnline("111111111",120_003));
|
||||
}
|
||||
|
||||
@Test public void changedHistoryResubscribesAndMalformedStatesDoNotBecomeOnline()throws Exception{
|
||||
RecentConnectionPresence presence=new RecentConnectionPresence();ArrayList<JSONArray> requests=new ArrayList<>();presence.sender=requests::add;
|
||||
presence.watch(records("111111111","111111111"),0);presence.setConnected(true,0);assertEquals(1,requests.get(0).length());
|
||||
presence.receive(snapshot(device("111111111",true)),1);presence.watch(records("222222222"),2);assertEquals(2,requests.size());assertFalse(presence.isOnline("111111111",2));
|
||||
presence.receive(snapshot(new JSONObject().put("id","222222222").put("online","true")),3);assertFalse(presence.isOnline("222222222",3));
|
||||
presence.receive(snapshot(device("222222222",true)),4);presence.receive(new JSONObject().put("type","presence").put("devices","invalid"),5);assertTrue(presence.isOnline("222222222",5));
|
||||
presence.watch(records(),6);assertEquals(0,requests.get(2).length());assertFalse(presence.isOnline("222222222",6));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.*;
|
||||
import android.graphics.*;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import org.junit.*;
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class RemotePreviewStoreTest {
|
||||
private Context context;
|
||||
private File root;
|
||||
private SharedPreferences options,index;
|
||||
private String prefix;
|
||||
private RemotePreviewStore store;
|
||||
@Before public void setup()throws Exception{
|
||||
context=InstrumentationRegistry.getInstrumentation().getTargetContext();prefix="preview-test-"+UUID.randomUUID();
|
||||
options=context.getSharedPreferences(prefix,0);index=context.getSharedPreferences(prefix+"-index",0);
|
||||
root=Files.createTempDirectory(context.getCacheDir().toPath(),"previews-").toFile();
|
||||
store=new RemotePreviewStore(new File(root,"images"),options,index);
|
||||
}
|
||||
@After public void cleanup()throws Exception{
|
||||
store.clear();flush();store.io.shutdown();
|
||||
try(var paths=Files.walk(root.toPath())){for(var path:paths.sorted(Comparator.reverseOrder()).toList())Files.delete(path);}
|
||||
context.deleteSharedPreferences(prefix);context.deleteSharedPreferences(prefix+"-index");
|
||||
}
|
||||
private void flush()throws Exception{store.io.submit(()->{}).get(5,TimeUnit.SECONDS);InstrumentationRegistry.getInstrumentation().waitForIdleSync();}
|
||||
private void enable(){options.edit().putBoolean("networkConsent",true).commit();store.setEnabled(true);}
|
||||
private static Bitmap solid(int color){Bitmap image=Bitmap.createBitmap(640,360,Bitmap.Config.ARGB_8888);image.eraseColor(color);return image;}
|
||||
private Bitmap load(String server,String id)throws Exception{
|
||||
var result=new java.util.concurrent.atomic.AtomicReference<Bitmap>();var done=new CountDownLatch(1);
|
||||
store.load(server,id,image->{result.set(image);done.countDown();});assertTrue(done.await(5,TimeUnit.SECONDS));return result.get();
|
||||
}
|
||||
@Test public void offByDefaultAndConsentCannotBeBypassed()throws Exception{
|
||||
assertFalse(store.enabled());assertNull(store.begin("server","1"));store.setEnabled(true);flush();assertFalse(store.enabled());
|
||||
options.edit().putBoolean("networkConsent",true).commit();assertFalse(store.enabled());
|
||||
enable();assertNotNull(store.begin("server","1"));
|
||||
options.edit().putBoolean("networkConsent",false).commit();store.enforceConsent();flush();
|
||||
assertFalse(options.getBoolean(RemotePreviewStore.OPTION,true));assertNull(store.begin("server","1"));
|
||||
}
|
||||
@Test public void jpegPersistsAcrossStoreRecreationAndRemainsServerScoped()throws Exception{
|
||||
enable();var capture=store.begin("server:1","123456789");store.save(capture,solid(Color.GREEN));flush();
|
||||
assertTrue(new File(store.directory,capture.key+".jpg").isFile());
|
||||
assertNull(load("server:2","123456789"));assertNull(load("server:1","other"));
|
||||
store.io.shutdown();store=new RemotePreviewStore(store.directory,options,index);
|
||||
Bitmap loaded=load("server:1","123456789");assertNotNull(loaded);assertEquals(640,loaded.getWidth());assertEquals(360,loaded.getHeight());assertTrue(Color.green(loaded.getPixel(320,180))>240);loaded.recycle();
|
||||
}
|
||||
|
||||
@Test public void disablingDeletesFilesAndInvalidatesInFlightCapture()throws Exception{
|
||||
enable();var capture=store.begin("server","1");store.save(capture,solid(Color.BLUE));flush();
|
||||
store.setEnabled(false);store.save(capture,solid(Color.RED));flush();
|
||||
assertFalse(store.enabled());assertFalse(store.directory.exists());assertTrue(index.getAll().isEmpty());assertNull(load("server","1"));
|
||||
store.setEnabled(true);assertNull(load("server","1"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
public class RemoteVersionCheckTest {
|
||||
private static byte[] json(String value) { return value.getBytes(StandardCharsets.UTF_8); }
|
||||
private static JSONObject host(Object version) {
|
||||
try { return new JSONObject().put("app_version", version); }
|
||||
catch (Exception error) { throw new AssertionError(error); }
|
||||
}
|
||||
private static final class Fetches implements RemoteVersionCheck.Fetcher {
|
||||
final List<Consumer<byte[]>> replies = new ArrayList<>();
|
||||
int cancellations;
|
||||
public RemoteVersionCheck.Cancellation fetch(Consumer<byte[]> reply) {
|
||||
replies.add(reply);
|
||||
return () -> cancellations++;
|
||||
}
|
||||
}
|
||||
|
||||
@Test public void sharedNativeComparisonMatchesIosReleaseOrdering() {
|
||||
byte[] release = json("{\"latest_version\":\"v1.5.3-20260928\",\"patch\":2}");
|
||||
for (String version : new String[]{"1.5.2", "v1.5.3-20260928", "1.5.3-1-20260929", "1.5.3-20260928-1"}) {
|
||||
assertTrue(NativeSession.nValidAppVersion(version));
|
||||
assertTrue(version, NativeSession.nHasAppUpdate(version, release));
|
||||
}
|
||||
for (String version : new String[]{"1.5.3-2-20260927", "1.5.3-3-20260928", "1.6.0"})
|
||||
assertFalse(version, NativeSession.nHasAppUpdate(version, release));
|
||||
assertFalse(NativeSession.nHasAppUpdate("1.5.3-20260927", json("{\"version\":\"1.5.3-20261001\"}")));
|
||||
assertTrue(NativeSession.nHasAppUpdate("1.5.3-9", json("{\"version\":\"1.5.3\",\"patch\":\"10\"}")));
|
||||
}
|
||||
|
||||
@Test public void legacyVersionWaitsForConnectionAndNeverFetches() {
|
||||
for (Object version : new Object[]{null, JSONObject.NULL, 123, "", " ", "unknown", "ios-native", "1..5", "1.5-"}) {
|
||||
Fetches fetches = new Fetches(); int[] notices = {0};
|
||||
RemoteVersionCheck check = new RemoteVersionCheck(fetches, () -> notices[0]++);
|
||||
check.hostInfo(host(version)); assertEquals(0, notices[0]);
|
||||
check.connected(); assertEquals(1, notices[0]);
|
||||
check.hostInfo(host(version)); check.connected(); assertEquals(1, notices[0]);
|
||||
assertTrue(fetches.replies.isEmpty()); check.reset();
|
||||
}
|
||||
}
|
||||
|
||||
@Test public void disconnectCancelsAndOldReplyCannotAffectANewPeer() {
|
||||
Fetches fetches = new Fetches(); int[] notices = {0};
|
||||
RemoteVersionCheck check = new RemoteVersionCheck(fetches, () -> notices[0]++);
|
||||
check.hostInfo(host("1.0.0")); check.connected(); check.reset();
|
||||
assertEquals(1, fetches.cancellations);
|
||||
fetches.replies.get(0).accept(json("{\"version\":\"2.0.0\"}")); assertEquals(0, notices[0]);
|
||||
check.connected(); check.hostInfo(host("3.0.0"));
|
||||
fetches.replies.get(0).accept(json("{\"version\":\"2.0.0\"}"));
|
||||
fetches.replies.get(1).accept(json("{\"version\":\"2.0.0\"}")); assertEquals(0, notices[0]);
|
||||
check.reset(); assertEquals(1, fetches.cancellations);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/** Non-UI regression checks for zoom and remote input geometry. */
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
public class RemoteViewportTest {
|
||||
private static final float EPSILON = .0001f;
|
||||
|
||||
@Test public void fittedVideoRejectsLetterboxingAndMapsItsEdges() {
|
||||
RemoteViewport viewport = new RemoteViewport();
|
||||
viewport.fit(1080,1920,1920,1080);
|
||||
assertEquals(1080,viewport.baseWidth());
|
||||
assertEquals(607,viewport.baseHeight());
|
||||
assertEquals(656,viewport.top(),EPSILON);
|
||||
assertFalse(viewport.contains(540,200));
|
||||
assertTrue(viewport.contains(0,656));
|
||||
assertFalse(viewport.contains(1080,1263));
|
||||
assertEquals(.5f,viewport.normalizedX(540),EPSILON);
|
||||
assertEquals(.5f,viewport.normalizedY(959.5f),EPSILON);
|
||||
}
|
||||
|
||||
@Test public void pinchKeepsTheRemotePointUnderAnOffCenterFocus() {
|
||||
RemoteViewport viewport = new RemoteViewport();
|
||||
viewport.fit(1000,600,1000,600);
|
||||
viewport.zoomBy(2,750,350);
|
||||
assertEquals(2,viewport.scale(),EPSILON);
|
||||
assertEquals(-250,viewport.offsetX(),EPSILON);
|
||||
assertEquals(-50,viewport.offsetY(),EPSILON);
|
||||
assertEquals(.75f,viewport.normalizedX(750),EPSILON);
|
||||
assertEquals(350f/600,viewport.normalizedY(350),EPSILON);
|
||||
viewport.zoomBy(.5f,750,350);
|
||||
assertEquals(1,viewport.scale(),EPSILON);
|
||||
assertEquals(0,viewport.offsetX(),EPSILON);
|
||||
assertEquals(0,viewport.offsetY(),EPSILON);
|
||||
}
|
||||
|
||||
@Test public void zoomAndPanUseTheSameInverseTransformForRemoteInput() {
|
||||
RemoteViewport viewport = new RemoteViewport();
|
||||
viewport.fit(1200,800,1920,1080);
|
||||
viewport.zoomBy(3,600,399.5f);
|
||||
viewport.panBy(200,100);
|
||||
assertEquals(-1000,viewport.left(),EPSILON);
|
||||
assertEquals(-513,viewport.top(),EPSILON);
|
||||
assertEquals(1380f/3600,viewport.normalizedX(380),EPSILON);
|
||||
assertEquals(.28f,viewport.normalizedY(54),EPSILON);
|
||||
// Trackpad deltas use the zoomed dimensions, too.
|
||||
assertEquals(.01f,36/viewport.width(),EPSILON);
|
||||
assertEquals(.01f,20.25f/viewport.height(),EPSILON);
|
||||
}
|
||||
|
||||
@Test public void panCannotMoveTheImagePastTheOriginalFittedArea() {
|
||||
RemoteViewport viewport = new RemoteViewport();
|
||||
viewport.fit(1000,800,1600,900);
|
||||
viewport.zoomBy(2,500,400);
|
||||
viewport.panBy(10000,-10000);
|
||||
assertEquals(500,viewport.offsetX(),EPSILON);
|
||||
assertEquals(-281,viewport.offsetY(),EPSILON);
|
||||
assertEquals(0,viewport.left(),EPSILON);
|
||||
assertEquals(119,viewport.top()+viewport.height()-viewport.baseHeight(),EPSILON);
|
||||
viewport.panBy(-20000,20000);
|
||||
assertEquals(-500,viewport.offsetX(),EPSILON);
|
||||
assertEquals(281,viewport.offsetY(),EPSILON);
|
||||
}
|
||||
|
||||
@Test public void scaleMatchesIosLimitsAndFinishingNearOneRestoresFit() {
|
||||
RemoteViewport viewport = new RemoteViewport();
|
||||
viewport.fit(1000,600,1000,600);
|
||||
viewport.zoomBy(100,500,300);
|
||||
assertEquals(10,viewport.scale(),EPSILON);
|
||||
viewport.zoomBy(.10005f,500,300);
|
||||
viewport.panBy(.1f,.1f);
|
||||
viewport.finishGesture();
|
||||
assertEquals(1,viewport.scale(),EPSILON);
|
||||
assertEquals(0,viewport.offsetX(),EPSILON);
|
||||
assertEquals(0,viewport.offsetY(),EPSILON);
|
||||
assertFalse(viewport.isZoomed());
|
||||
viewport.zoomBy(.01f,500,300);
|
||||
assertEquals(1,viewport.scale(),EPSILON);
|
||||
}
|
||||
|
||||
@Test public void rotationAndResolutionChangesConstrainExistingPan() {
|
||||
RemoteViewport viewport = new RemoteViewport();
|
||||
viewport.fit(1000,600,1000,600);
|
||||
viewport.zoomBy(2,500,300);
|
||||
viewport.panBy(500,300);
|
||||
viewport.fit(600,1000,1000,600);
|
||||
assertEquals(2,viewport.scale(),EPSILON);
|
||||
assertEquals(300,viewport.offsetX(),EPSILON);
|
||||
assertEquals(180,viewport.offsetY(),EPSILON);
|
||||
viewport.fit(600,1000,600,1000);
|
||||
assertEquals(2,viewport.scale(),EPSILON);
|
||||
assertEquals(1000,viewport.baseHeight());
|
||||
viewport.reset();
|
||||
assertEquals(1,viewport.scale(),EPSILON);
|
||||
assertEquals(0,viewport.offsetX(),EPSILON);
|
||||
assertEquals(0,viewport.offsetY(),EPSILON);
|
||||
}
|
||||
|
||||
@Test public void oddMarginsShareTheActualSurfaceCenterAtMaximumZoom() {
|
||||
RemoteViewport viewport = new RemoteViewport();
|
||||
viewport.fit(801,603,800,600);
|
||||
assertEquals(801,viewport.baseWidth());
|
||||
assertEquals(600,viewport.baseHeight());
|
||||
assertEquals(1,viewport.top(),EPSILON);
|
||||
viewport.zoomBy(10,400.5f,301);
|
||||
assertEquals(-3604.5f,viewport.left(),EPSILON);
|
||||
assertEquals(-2699,viewport.top(),EPSILON);
|
||||
assertEquals(.5f,viewport.normalizedX(400.5f),EPSILON);
|
||||
assertEquals(.5f,viewport.normalizedY(301),EPSILON);
|
||||
}
|
||||
|
||||
@Test public void invalidGeometryAndScaleDoNotCorruptViewport() {
|
||||
RemoteViewport viewport = new RemoteViewport();
|
||||
viewport.fit(0,0,1920,1080);
|
||||
assertFalse(viewport.contains(0,0));
|
||||
viewport.zoomBy(2,0,0);
|
||||
assertEquals(1,viewport.scale(),EPSILON);
|
||||
viewport.fit(1000,600,1000,600);
|
||||
viewport.zoomBy(Float.NaN,500,300);
|
||||
viewport.zoomBy(Float.POSITIVE_INFINITY,500,300);
|
||||
viewport.zoomBy(-1,500,300);
|
||||
assertEquals(1,viewport.scale(),EPSILON);
|
||||
assertEquals(0,viewport.offsetX(),EPSILON);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import android.content.Context;
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.net.InetAddress;
|
||||
import java.nio.file.Files;
|
||||
import java.security.KeyStore;
|
||||
import java.util.concurrent.*;
|
||||
import javax.net.ssl.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/** Exercises the actual MiniRTC TLS path inside an Android app process (AT_SECURE=1).
|
||||
* The bundled PKCS12 keys are public test fixtures, only served on loopback. No
|
||||
* websocket upgrade/login or external server is involved in these tests. */
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
public class TlsTrustTest {
|
||||
@Test public void explicitlyTrustedCertificateCompletesHandshake() throws Exception {
|
||||
assertTrue("The app must load the supplied trust bundle despite AT_SECURE", handshake("valid",true));
|
||||
}
|
||||
@Test public void untrustedCertificateIsRejected() throws Exception {
|
||||
assertFalse("A test CA absent from the system store must not be trusted",handshake("valid",false));
|
||||
}
|
||||
@Test public void certificateForAnotherHostIsRejected() throws Exception {
|
||||
assertFalse("Trusting the CA must not bypass hostname verification",handshake("wrong-host",true));
|
||||
}
|
||||
private boolean handshake(String certificate,boolean trustFixture) throws Exception {
|
||||
var instrumentation=InstrumentationRegistry.getInstrumentation();Context context=instrumentation.getTargetContext();
|
||||
KeyStore keyStore=KeyStore.getInstance("PKCS12");char[] password="local-test-only".toCharArray();
|
||||
try(InputStream input=instrumentation.getContext().getAssets().open("tls/"+certificate+".p12")){keyStore.load(input,password);}
|
||||
KeyManagerFactory keys=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());keys.init(keyStore,password);
|
||||
SSLContext tls=SSLContext.getInstance("TLS");tls.init(keys.getKeyManagers(),null,null);
|
||||
ExecutorService serverWorker=Executors.newSingleThreadExecutor();
|
||||
NativeSession session=new NativeSession(context,"127.0.0.1",1,"unused","unused",new NativeSession.Listener(){
|
||||
public void status(String value){} public void connected(){fail("Test server never opens a desktop session");}
|
||||
public void ended(String value){} public void data(JSONObject value){}public void videoSize(int w,int h){}
|
||||
public void clipboard(String value){}public void statistics(RemoteNetworkStatistics.Snapshot value){}
|
||||
});
|
||||
File roots=new File(context.getCacheDir(),"tls-test-roots.pem");
|
||||
Field rtcField=NativeSession.class.getDeclaredField("RTC");rtcField.setAccessible(true);ExecutorService rtc=(ExecutorService)rtcField.get(null);
|
||||
try(SSLServerSocket server=(SSLServerSocket)tls.getServerSocketFactory().createServerSocket(0,1,InetAddress.getByName("127.0.0.1"))){
|
||||
server.setSoTimeout(10000);
|
||||
if(trustFixture){try(InputStream input=instrumentation.getContext().getAssets().open("tls/root.pem")){Files.copy(input,roots.toPath(),java.nio.file.StandardCopyOption.REPLACE_EXISTING);}}
|
||||
else{Method export=NativeSession.class.getDeclaredMethod("exportTrust");export.setAccessible(true);File systemRoots=(File)export.invoke(session);Files.copy(systemRoots.toPath(),roots.toPath(),java.nio.file.StandardCopyOption.REPLACE_EXISTING);}
|
||||
Future<Boolean> request=serverWorker.submit(()->{
|
||||
try(SSLSocket socket=(SSLSocket)server.accept()){
|
||||
socket.setSoTimeout(10000);socket.startHandshake();
|
||||
String first=new BufferedReader(new InputStreamReader(socket.getInputStream(),java.nio.charset.StandardCharsets.US_ASCII)).readLine();
|
||||
return first!=null&&first.startsWith("GET ");
|
||||
}catch(SSLException expected){return false;}
|
||||
});
|
||||
Method create=NativeSession.class.getDeclaredMethod("nCreate",NativeSession.class,String.class,int.class,String.class,String.class,String.class);create.setAccessible(true);
|
||||
Field handle=NativeSession.class.getDeclaredField("handle");handle.setAccessible(true);
|
||||
rtc.submit(()->{try{long value=(long)create.invoke(null,session,"127.0.0.1",server.getLocalPort(),"",context.getCacheDir().getAbsolutePath(),roots.getAbsolutePath());handle.setLong(session,value);assertNotEquals(0L,value);}catch(ReflectiveOperationException error){throw new RuntimeException(error);}}).get(10,TimeUnit.SECONDS);
|
||||
return request.get(15,TimeUnit.SECONDS);
|
||||
}finally{session.close();rtc.submit(()->{}).get(10,TimeUnit.SECONDS);serverWorker.shutdownNow();roots.delete();}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package cn.crossdesk.mobile;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class VideoSettingsTest {
|
||||
private final RemoteVideoSettings.Values first=new RemoteVideoSettings.Values(1,30,2),second=new RemoteVideoSettings.Values(0,60,1);
|
||||
private void same(RemoteVideoSettings.Values expected,RemoteVideoSettings.Values actual){assertEquals(expected.quality,actual.quality);assertEquals(expected.frameRate,actual.frameRate);assertEquals(expected.preference,actual.preference);}
|
||||
|
||||
@Test public void acknowledgementCommitsAndRejectionRollsBack(){
|
||||
RemoteVideoSettings state=new RemoteVideoSettings(1);state.setSupported(true);long id=state.begin(first);assertTrue(state.pending);same(new RemoteVideoSettings.Values(1,30,1),state.applied);
|
||||
state.receive(first,id,true);same(first,state.selection);assertFalse(state.pending);assertFalse(state.failed);state.expire(id);assertFalse(state.failed);
|
||||
id=state.begin(second);state.receive(second,id,false);same(first,state.selection);assertTrue(state.failed);state.begin(second);assertFalse(state.failed);
|
||||
}
|
||||
|
||||
@Test public void timeoutLateReplyAndCapabilityLoss(){
|
||||
RemoteVideoSettings state=new RemoteVideoSettings(1);state.setSupported(true);long id=state.begin(first);state.expire(id);assertTrue(state.failed);same(new RemoteVideoSettings.Values(1,30,1),state.selection);
|
||||
state.receive(first,id,true);same(first,state.selection);assertFalse(state.failed);
|
||||
id=state.begin(second);state.setSupported(false);state.receive(second,id,true);state.expire(id);same(first,state.selection);assertFalse(state.failed);assertFalse(state.pending);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Check Xmake discovery and the minimum supported version before native builds."""
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
source = Path(__file__).resolve().parents[1] / "scripts/build_native.py"
|
||||
spec = importlib.util.spec_from_file_location("build_native", source)
|
||||
build_native = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(build_native)
|
||||
|
||||
|
||||
class XmakeSelectionTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
for patcher in (
|
||||
patch.dict(os.environ, {}, clear=True),
|
||||
patch.object(build_native.shutil, "which", return_value="/tools/xmake"),
|
||||
patch.object(build_native.subprocess, "check_output", return_value="xmake v3.1.1\n"),
|
||||
):
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def test_path_tool_accepts_minimum_and_newer_versions(self):
|
||||
for output in ("xmake v3.1.1", "xmake v3.1.2\n", "xmake v3.1.10, A build utility\n",
|
||||
"xmake v3.2.0\n", "xmake v3.10.0\n", "xmake v4.0.0\n",
|
||||
"\x1b[1mxmake v3.1.1+HEAD.3ba37a0d4, A build utility\x1b[0m\n"):
|
||||
with self.subTest(output=output):
|
||||
build_native.subprocess.check_output.return_value = output
|
||||
self.assertEqual(build_native.find_xmake(), "/tools/xmake")
|
||||
|
||||
def test_explicit_tool_takes_precedence_over_path(self):
|
||||
os.environ["XMAKE_BIN"] = "/custom/xmake"
|
||||
self.assertEqual(build_native.find_xmake(), "/custom/xmake")
|
||||
build_native.shutil.which.assert_not_called()
|
||||
build_native.subprocess.check_output.assert_called_once_with(
|
||||
["/custom/xmake", "--version"], text=True)
|
||||
|
||||
def test_missing_tool_reports_minimum_requirement(self):
|
||||
build_native.shutil.which.return_value = None
|
||||
with self.assertRaisesRegex(SystemExit, "Xmake 3.1.1 or newer is required"):
|
||||
build_native.find_xmake()
|
||||
build_native.subprocess.check_output.assert_not_called()
|
||||
|
||||
def test_older_or_unrecognized_versions_are_rejected(self):
|
||||
for output in ("xmake v3.1.0\n", "xmake v3.0.99\n", "xmake v2.99.99\n",
|
||||
"xmake version unknown\n", "xmake v3.1\n", "xmake v3.1.1invalid\n", ""):
|
||||
with self.subTest(output=output):
|
||||
build_native.subprocess.check_output.return_value = output
|
||||
with self.assertRaisesRegex(SystemExit, "Use Xmake 3.1.1 or newer"):
|
||||
build_native.find_xmake()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,39 @@
|
||||
#include "controller_protocol.h"
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
int main() {
|
||||
using namespace crossdesk;
|
||||
for (int quality = -1; quality <= 3; ++quality)
|
||||
for (int rate : {0, 24, 30, 60, 120})
|
||||
for (int preference = -1; preference <= 3; ++preference) {
|
||||
const auto message = android_controller::VideoSettingsMessage(quality, rate, preference, UINT32_MAX);
|
||||
const bool valid = quality >= 0 && quality <= 2 && (rate == 30 || rate == 60) && preference >= 0 && preference <= 2;
|
||||
assert(message.empty() != valid);
|
||||
if (!valid) continue;
|
||||
// Decode the actual Android outgoing message with the desktop's wire parser.
|
||||
RemoteAction desktop{};
|
||||
assert(desktop.from_json(message) && desktop.type == video_settings);
|
||||
assert(desktop.vs.quality == quality && desktop.vs.frame_rate == rate && desktop.vs.preference == preference);
|
||||
assert(desktop.vs.request_id == UINT32_MAX && !desktop.vs.accepted);
|
||||
desktop.type = video_settings_status; desktop.vs.accepted = true;
|
||||
RemoteAction reply{}; assert(reply.from_json(desktop.to_json()));
|
||||
assert(reply.type == video_settings_status && reply.vs.accepted && reply.vs.request_id == UINT32_MAX);
|
||||
}
|
||||
MiniRtcNetTrafficStats stats{};
|
||||
stats.video_inbound_stats.bitrate = 8'000'000; stats.video_inbound_stats.loss_rate = .02f;
|
||||
stats.audio_inbound_stats.bitrate = 64'000; stats.audio_outbound_stats.bitrate = 128'000;
|
||||
stats.data_inbound_stats.bitrate = 2000; stats.data_outbound_stats.bitrate = 3000;
|
||||
stats.total_inbound_stats.bitrate = UINT32_MAX; stats.total_outbound_stats.bitrate = 131'000;
|
||||
stats.total_inbound_stats.loss_rate = 1.2f; stats.rtt_ms = 40; stats.srtp_active = true;
|
||||
auto json = android_controller::NetworkReport(stats, Relay);
|
||||
assert(json.at("mode") == 1 && json.at("srtp") == true && json.at("rtt") == 40);
|
||||
assert(json.at("video").at("inbound") == 8'000'000 && json.at("audio").at("outbound") == 128'000);
|
||||
assert(json.at("data").at("inbound") == 2000 && json.at("data").at("outbound") == 3000);
|
||||
assert(json.at("total").at("inbound").get<uint32_t>() == UINT32_MAX);
|
||||
assert(std::abs(json.at("total").at("loss").get<double>() - 1.2) < .001);
|
||||
stats.rtt_ms = -1; stats.srtp_active = false;
|
||||
json = android_controller::NetworkReport(stats, UnknownMode);
|
||||
assert(json.at("mode") == 2 && json.at("srtp") == false && json.at("rtt") == -1);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
#include "latest_frame_worker.h"
|
||||
#include "video_timing.h"
|
||||
#include "video_picture.h"
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
int main() {
|
||||
using namespace crossdesk::android_controller;
|
||||
using namespace std::chrono_literals;
|
||||
assert(VideoLatencyMilliseconds(1'000'000, 1'020'000, 1'050'000) == 50);
|
||||
// Reproduce a valid frame delayed in the local decode/Surface queue.
|
||||
// The old submission-time five-second cutoff hid both of these samples.
|
||||
assert(VideoLatencyMilliseconds(1'000'000, 1'020'000, 7'000'000) == 6000);
|
||||
assert(VideoLatencyMilliseconds(1'000'000, 1'020'000, 31'000'000) == 30000);
|
||||
assert(VideoLatencyMilliseconds(0, 1'020'000, 7'000'000) < 0);
|
||||
assert(VideoLatencyMilliseconds(1'030'000, 1'020'000, 7'000'000) < 0);
|
||||
assert(VideoLatencyMilliseconds(1'000'000, 6'000'001, 7'000'000) < 0);
|
||||
assert(VideoLatencyMilliseconds(1'000'000, 1'020'000, 1'010'000) < 0);
|
||||
assert(VideoLatencyMilliseconds(1'000'000, 1'020'000, -1) < 0);
|
||||
|
||||
struct Owner { int references = 1; uint8_t pixels[12]{}; } owner;
|
||||
MiniRtcNativeVideoFrame native{};
|
||||
native.struct_size = sizeof(native); native.type = MiniRtcNativeVideoFrameCpuNv12;
|
||||
native.width = native.height = 2; native.owner = &owner;
|
||||
native.retain = [](void* p) { ++static_cast<Owner*>(p)->references; };
|
||||
native.release = [](void* p) { --static_cast<Owner*>(p)->references; };
|
||||
native.payload.cpu_nv12 = {owner.pixels, owner.pixels + 8, 4, 4};
|
||||
MiniRtcVideoFrame source{}; source.width = source.height = 2;
|
||||
source.native_frame = &native; source.captured_timestamp = 100; source.received_timestamp = 120;
|
||||
{
|
||||
auto retained = VideoPicture::RetainOrCopy(source, 3);
|
||||
assert(retained && owner.references == 2 && retained->pixels.empty());
|
||||
assert(retained->Y() == owner.pixels && retained->UV() == owner.pixels + 8);
|
||||
assert(retained->YStride() == 4 && retained->UVStride() == 4);
|
||||
assert(retained->captured_us == 100 && retained->received_us == 120 && retained->generation == 3);
|
||||
auto moved = std::move(*retained); retained.reset(); assert(owner.references == 2);
|
||||
}
|
||||
assert(owner.references == 1);
|
||||
uint8_t borrowed[6]{1, 2, 3, 4, 5, 6};
|
||||
source.native_frame = nullptr; source.data = reinterpret_cast<const char*>(borrowed); source.size = 6;
|
||||
auto copied = VideoPicture::RetainOrCopy(source, 4); borrowed[0] = 0;
|
||||
assert(copied && copied->Y()[0] == 1 && copied->UV()[0] == 5 && copied->YStride() == 2);
|
||||
source.size = 5; assert(!VideoPicture::RetainOrCopy(source, 4));
|
||||
source.width = 3; assert(!VideoPicture::RetainOrCopy(source, 4));
|
||||
|
||||
std::promise<void> started, release, finished;
|
||||
auto released = release.get_future();
|
||||
std::vector<int> rendered;
|
||||
LatestFrameWorker<std::unique_ptr<int>> worker([&](std::unique_ptr<int> value) {
|
||||
rendered.push_back(*value);
|
||||
if (*value == 1) { started.set_value(); released.wait(); }
|
||||
if (*value == 4) finished.set_value();
|
||||
});
|
||||
assert(worker.Submit(std::make_unique<int>(1)));
|
||||
assert(started.get_future().wait_for(2s) == std::future_status::ready);
|
||||
// A blocked Surface must not block frame submission; obsolete frames 2/3
|
||||
// must not be displayed after it recovers, even with move-only ownership.
|
||||
assert(worker.Submit(std::make_unique<int>(2)));
|
||||
assert(worker.Submit(std::make_unique<int>(3)));
|
||||
assert(worker.Submit(std::make_unique<int>(4)));
|
||||
release.set_value();
|
||||
assert(finished.get_future().wait_for(2s) == std::future_status::ready);
|
||||
worker.Stop();
|
||||
assert((rendered == std::vector<int>{1, 4}));
|
||||
assert(!worker.Submit(std::make_unique<int>(5)));
|
||||
worker.Stop();
|
||||
|
||||
std::promise<void> first_started, first_release;
|
||||
auto first_released = first_release.get_future();
|
||||
int count = 0;
|
||||
LatestFrameWorker<int> cleared([&](int value) {
|
||||
++count; assert(value == 1); first_started.set_value(); first_released.wait();
|
||||
});
|
||||
cleared.Submit(1);
|
||||
assert(first_started.get_future().wait_for(2s) == std::future_status::ready);
|
||||
cleared.Submit(2);
|
||||
cleared.Clear(); // Surface replacement/display switch discards pending pixels.
|
||||
first_release.set_value();
|
||||
cleared.Stop();
|
||||
assert(count == 1);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user