mirror of
https://github.com/kunkundi/crossdesk.git
synced 2026-10-15 16:30:50 +08:00
Compare commits
72
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
006526389a | ||
|
|
e76d2bf903 | ||
|
|
2cf0d79543 | ||
|
|
3043b5f110 | ||
|
|
5721222724 | ||
|
|
3ee0d42494 | ||
|
|
417ef7d58c | ||
|
|
0a6356085d | ||
|
|
61ff9b2787 | ||
|
|
4855b2d3b6 | ||
|
|
2ac197c2de | ||
|
|
b90359b08d | ||
|
|
5199b2df11 | ||
|
|
fd86dba212 | ||
|
|
2a9887ab8a | ||
|
|
435feb419c | ||
|
|
4e394ca650 | ||
|
|
4dfd8c3005 | ||
|
|
de16eb3b92 | ||
|
|
3bd0676672 | ||
|
|
73b4d0f645 | ||
|
|
54dbd04a8d | ||
|
|
c8907a00f9 | ||
|
|
c9e0078bfb | ||
|
|
e156ff5277 | ||
|
|
b44a203b19 | ||
|
|
852710f428 | ||
|
|
2d51936ca8 | ||
|
|
3baedac6df | ||
|
|
a667fe3b31 | ||
|
|
05f6d3d90a | ||
|
|
0e7d175631 | ||
|
|
52ca253980 | ||
|
|
1925e5ffcc | ||
|
|
3aa0470510 | ||
|
|
fbbb8c9e2c | ||
|
|
3750687e66 | ||
|
|
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 |
@@ -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,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()
|
||||
@@ -16,6 +16,8 @@ ARTIFACTS = {
|
||||
"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"),
|
||||
}
|
||||
|
||||
@@ -2,6 +2,12 @@ name: Build Android
|
||||
|
||||
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:
|
||||
@@ -9,9 +15,14 @@ on:
|
||||
required: false
|
||||
type: string
|
||||
default: ""
|
||||
patch:
|
||||
description: "Optional patch number from the main build workflow."
|
||||
required: false
|
||||
type: string
|
||||
default: "0"
|
||||
outputs:
|
||||
version:
|
||||
description: "Independent Android version and build date."
|
||||
description: "Android artifact version; combined releases match the desktop tag."
|
||||
value: ${{ jobs.build.outputs.version }}
|
||||
pull_request:
|
||||
paths:
|
||||
@@ -40,7 +51,8 @@ jobs:
|
||||
outputs:
|
||||
version: ${{ steps.package.outputs.version }}
|
||||
env:
|
||||
XMAKE_VERSION: "3.1.1"
|
||||
# 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:
|
||||
@@ -119,9 +131,9 @@ jobs:
|
||||
- name: Install xmake
|
||||
uses: xmake-io/github-action-setup-xmake@v1
|
||||
with:
|
||||
xmake-version: ${{ env.XMAKE_VERSION }}
|
||||
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_VERSION }}
|
||||
actions-cache-key: ${{ runner.os }}-${{ runner.arch }}-ubuntu24.04-android-xmake${{ env.XMAKE_MIN_VERSION }}
|
||||
|
||||
- name: Cache Xmake package repository
|
||||
uses: actions/cache@v5
|
||||
@@ -129,7 +141,7 @@ jobs:
|
||||
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
|
||||
# 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
|
||||
@@ -146,71 +158,85 @@ jobs:
|
||||
- name: Verify shared license catalog
|
||||
run: python3 -B apps/ios/scripts/generate_third_party_licenses.py
|
||||
|
||||
- name: Build APKs and run Lint
|
||||
working-directory: apps/android
|
||||
run: |
|
||||
./gradlew --no-daemon --stacktrace \
|
||||
:app:assembleDebug :app:assembleRelease :app:assembleDebugAndroidTest \
|
||||
:app:lintDebug :app:lintRelease
|
||||
|
||||
- name: Verify APKs and native protocol
|
||||
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
|
||||
python3 -B test/run_native.py
|
||||
"${ANDROID_HOME}/build-tools/36.0.0/apksigner" verify app/build/outputs/apk/debug/app-debug.apk
|
||||
"${ANDROID_HOME}/build-tools/36.0.0/apksigner" verify app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk
|
||||
|
||||
- name: Package APKs with the independent Android version
|
||||
id: package
|
||||
- name: Resolve Android version
|
||||
shell: python
|
||||
env:
|
||||
PATCH_NUMBER: ${{ inputs.patch || '0' }}
|
||||
run: |
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import runpy
|
||||
|
||||
resolver = Path("apps/android/scripts/release_version.py")
|
||||
if resolver.exists():
|
||||
runpy.run_path(str(resolver), run_name="__main__")
|
||||
else:
|
||||
# Older standalone releases predate the resolver and Gradle properties.
|
||||
# Keep their original package version when retrying an existing tag.
|
||||
tag = os.environ["CROSSDESK_SOURCE_TAG"]
|
||||
match = re.fullmatch(r"android-v([0-9]+\.[0-9]+\.[0-9]+)-([0-9]{8})", tag)
|
||||
config = Path("apps/android/app/build.gradle").read_text()
|
||||
name = re.search(r"versionName\s+'([^']+)'", config)
|
||||
code = re.search(r"versionCode\s+([0-9]+)", config)
|
||||
if not match or not name or not code or match[1] != name[1]:
|
||||
raise ValueError("Legacy Android sources require a matching standalone release tag")
|
||||
datetime.datetime.strptime(match[2], "%Y%m%d")
|
||||
with open(os.environ["GITHUB_ENV"], "a") as stream:
|
||||
stream.write(f"ANDROID_VERSION_NAME={name[1]}\nANDROID_VERSION_CODE={code[1]}\n"
|
||||
f"ANDROID_ARTIFACT_VERSION={tag.removeprefix('android-')}\n")
|
||||
|
||||
- name: Build APKs
|
||||
working-directory: apps/android
|
||||
run: |
|
||||
./gradlew --no-daemon --stacktrace \
|
||||
-PcrossdeskVersionName="${ANDROID_VERSION_NAME}" \
|
||||
-PcrossdeskVersionCode="${ANDROID_VERSION_CODE}" \
|
||||
:app:assembleDebug :app:assembleRelease
|
||||
|
||||
- name: Verify APKs
|
||||
working-directory: apps/android
|
||||
run: |
|
||||
for APK in app/build/outputs/apk/debug/app-debug.apk app/build/outputs/apk/release/app-release-unsigned.apk; do
|
||||
python3 -B test/verify_apk.py "${APK}" \
|
||||
--aapt2 "${ANDROID_HOME}/build-tools/36.0.0/aapt2" \
|
||||
--version-name "${ANDROID_VERSION_NAME}" --version-code "${ANDROID_VERSION_CODE}"
|
||||
done
|
||||
"${ANDROID_HOME}/build-tools/36.0.0/apksigner" verify app/build/outputs/apk/debug/app-debug.apk
|
||||
|
||||
- name: Package APKs with the resolved Android version
|
||||
id: package
|
||||
shell: python
|
||||
run: |
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
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}")
|
||||
version = os.environ["ANDROID_ARTIFACT_VERSION"]
|
||||
for variant in ("debug", "release"):
|
||||
metadata = json.loads((apk_dir / variant / "output-metadata.json").read_text())
|
||||
for element in metadata["elements"]:
|
||||
if (element["versionName"] != os.environ["ANDROID_VERSION_NAME"] or
|
||||
element["versionCode"] != int(os.environ["ANDROID_VERSION_CODE"])):
|
||||
raise ValueError(f"Unexpected Android {variant} version: {element}")
|
||||
output = Path(os.environ["RUNNER_TEMP"]) / "crossdesk-android"
|
||||
for variant, source in (
|
||||
("unsigned", "release/app-release-unsigned.apk"),
|
||||
("debug", "debug/app-debug.apk"),
|
||||
("debug", "androidTest/debug/app-debug-androidTest.apk"),
|
||||
):
|
||||
destination = output / variant
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
suffix = "-test" if "androidTest/" in source else ""
|
||||
shutil.copyfile(apk_dir / source, destination / f"crossdesk-android-arm64-{variant}-{version}{suffix}.apk")
|
||||
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"
|
||||
"Lint, native protocol/frame tests and APK checks passed. Device tests were compiled, not executed.\n")
|
||||
"Debug and Release APKs built and packaged; APK checks passed.\n")
|
||||
|
||||
- name: Upload unsigned Release APK
|
||||
uses: actions/upload-artifact@v6
|
||||
@@ -219,19 +245,10 @@ jobs:
|
||||
path: ${{ runner.temp }}/crossdesk-android/unsigned/*.apk
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload Debug and device test APKs
|
||||
- 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
|
||||
|
||||
- name: Upload Lint reports
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: crossdesk-android-reports
|
||||
path: apps/android/app/build/reports/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
||||
@@ -22,7 +22,7 @@ on:
|
||||
default: "0"
|
||||
outputs:
|
||||
version:
|
||||
description: "Independent iOS version and build date."
|
||||
description: "iOS artifact version; combined releases match the desktop tag."
|
||||
value: ${{ jobs.build.outputs.version }}
|
||||
pull_request:
|
||||
paths:
|
||||
@@ -51,7 +51,8 @@ jobs:
|
||||
CROSSDESK_SOURCE_TAG: ${{ inputs.source_tag || '' }}
|
||||
IOS_DEPLOYMENT_TARGET: "16.0"
|
||||
EXPECTED_IOS_SDK: "26.5"
|
||||
XMAKE_VERSION: "3.1.1"
|
||||
# Exercise the minimum supported version; local builds may use newer Xmake.
|
||||
XMAKE_MIN_VERSION: "3.1.1"
|
||||
XMAKE_REPO_REVISION: "121109352da272cd1a3d4ed52f2dcda34f839955"
|
||||
|
||||
steps:
|
||||
@@ -121,22 +122,29 @@ jobs:
|
||||
echo "CROSSDESK_RELEASE_BUILD=YES" >> "${GITHUB_ENV}"
|
||||
fi
|
||||
|
||||
- name: Read independent iOS version
|
||||
- name: Resolve iOS version
|
||||
id: ios_version
|
||||
shell: bash
|
||||
run: |
|
||||
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 }')"
|
||||
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
|
||||
VERSION_NUM="v${IOS_VERSION_BASE}-${VERSION_NUM##*-}"
|
||||
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
|
||||
@@ -152,9 +160,9 @@ jobs:
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: apps/ios/.xmake/packages
|
||||
key: "${{ runner.os }}-xmake${{ env.XMAKE_VERSION }}-deps-ios-arm64-source-v1-xcode26.6-xrepo1211093-min16-${{ github.run_id }}"
|
||||
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_VERSION }}-deps-ios-arm64-source-v1-xcode26.6-xrepo1211093-min16-
|
||||
${{ 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
|
||||
@@ -162,27 +170,19 @@ jobs:
|
||||
python-version: "3.13"
|
||||
|
||||
- name: Verify iOS license catalog
|
||||
run: |
|
||||
python3 -B -m unittest discover -s apps/ios/tests -p 'third_party_licenses_test.py' -v
|
||||
python3 -B apps/ios/scripts/generate_third_party_licenses.py
|
||||
|
||||
- name: Verify iOS privacy controls
|
||||
run: python3 -B -m unittest discover -s apps/ios/tests -p 'privacy_controls_test.py' -v
|
||||
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_VERSION }}"
|
||||
xmake-version: "${{ env.XMAKE_MIN_VERSION }}"
|
||||
|
||||
- name: Verify xmake version
|
||||
- name: Verify minimum xmake version
|
||||
shell: bash
|
||||
run: |
|
||||
XMAKE_VERSION_OUTPUT="$(xmake --version)"
|
||||
echo "${XMAKE_VERSION_OUTPUT}"
|
||||
if [[ "${XMAKE_VERSION_OUTPUT}" != *"xmake v${XMAKE_VERSION}"* ]]; then
|
||||
echo "Unexpected xmake version: expected ${XMAKE_VERSION}" >&2
|
||||
exit 1
|
||||
fi
|
||||
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
|
||||
@@ -207,6 +207,7 @@ jobs:
|
||||
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
|
||||
|
||||
|
||||
@@ -27,9 +27,9 @@ concurrency:
|
||||
|
||||
env:
|
||||
IMAGE_NAME: crossdesk/ubuntu20.04
|
||||
STACK_TAG: buildenv-cuda12.6.3-gcc10-cmake3.31.6-pipewire0.3.48-xmake3.0.9-rust1.92.0
|
||||
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.0.9
|
||||
XMAKE_VERSION: 3.1.1
|
||||
RUST_VERSION: 1.92.0
|
||||
RUSTUP_VERSION: 1.28.2
|
||||
|
||||
|
||||
+76
-41
@@ -27,6 +27,7 @@ permissions:
|
||||
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
XMAKE_MIN_VERSION: "3.1.1"
|
||||
|
||||
jobs:
|
||||
build-linux:
|
||||
@@ -37,6 +38,7 @@ jobs:
|
||||
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
|
||||
|
||||
@@ -108,8 +110,16 @@ jobs:
|
||||
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
|
||||
run: verify-crossdesk-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
|
||||
@@ -140,17 +150,6 @@ jobs:
|
||||
--cc=gcc-10 --cxx=g++-10 --root -y
|
||||
xmake b -vy --root crossdesk
|
||||
|
||||
- name: Verify repository and wire boundaries
|
||||
env:
|
||||
XMAKE_GLOBALDIR: /data
|
||||
run: |
|
||||
xmake b -vy --root repository_structure_test
|
||||
xmake b -vy --root crossdesk_wire_test
|
||||
xmake b -vy --root keyboard_state_wire_test
|
||||
xmake run --root repository_structure_test
|
||||
xmake run --root crossdesk_wire_test
|
||||
xmake run --root keyboard_state_wire_test
|
||||
|
||||
- name: Install Linux headless runtime dependencies
|
||||
run: |
|
||||
apt-get update
|
||||
@@ -163,23 +162,42 @@ jobs:
|
||||
|
||||
- name: Verify Ubuntu 20.04 package dependency resolution
|
||||
run: |
|
||||
PACKAGE_FILE="${GITHUB_WORKSPACE}/crossdesk-linux-${{ matrix.arch }}-${LEGAL_VERSION}.deb"
|
||||
apt-get update
|
||||
apt-get install --simulate "${PACKAGE_FILE}"
|
||||
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: |
|
||||
PACKAGE_FILE="${GITHUB_WORKSPACE}/crossdesk-linux-${{ matrix.arch }}-${LEGAL_VERSION}.deb"
|
||||
VERIFY_DIR="${RUNNER_TEMP}/crossdesk-glibc-${{ matrix.arch }}"
|
||||
install -d "${VERIFY_DIR}"
|
||||
dpkg-deb --extract "${PACKAGE_FILE}" "${VERIFY_DIR}"
|
||||
verify-crossdesk-glibc-baseline "${VERIFY_DIR}" 2.31
|
||||
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@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:
|
||||
@@ -264,18 +282,20 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-xmake-deps-${{ matrix.cache-key }}-
|
||||
|
||||
- name: Install xmake
|
||||
run: brew install xmake
|
||||
|
||||
- name: Update xmake repositories
|
||||
run: xmake repo -u
|
||||
|
||||
- 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: Update xmake repositories
|
||||
run: xmake repo -u
|
||||
|
||||
- name: Build CrossDesk
|
||||
run: |
|
||||
xmake f --target_minver=${MACOSX_DEPLOYMENT_TARGET} --CROSSDESK_VERSION=${VERSION_NUM} --USE_CUDA=false -vyD
|
||||
@@ -326,6 +346,8 @@ jobs:
|
||||
build-android:
|
||||
name: Build Android
|
||||
uses: ./.github/workflows/build-android.yml
|
||||
with:
|
||||
patch: ${{ inputs.patch || '0' }}
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -384,13 +406,23 @@ jobs:
|
||||
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"
|
||||
@@ -429,12 +461,6 @@ jobs:
|
||||
Write-Host "Copying $source to $target"
|
||||
Copy-Item $source $target -Force
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- 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"
|
||||
@@ -587,9 +613,6 @@ jobs:
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: Verify release manifest updates
|
||||
run: python3 -B -m unittest discover -s .github/scripts -p 'test_*.py' -v
|
||||
|
||||
- name: Extract version number
|
||||
id: version
|
||||
shell: bash
|
||||
@@ -647,6 +670,14 @@ jobs:
|
||||
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/).
|
||||
@@ -657,8 +688,12 @@ jobs:
|
||||
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
|
||||
|
||||
@@ -101,9 +101,6 @@ jobs:
|
||||
- name: Checkout publishing scripts
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Verify release manifest updates
|
||||
run: python3 -B -m unittest discover -s .github/scripts -p 'test_*.py' -v
|
||||
|
||||
- name: Verify release version
|
||||
shell: bash
|
||||
run: |
|
||||
|
||||
@@ -30,9 +30,6 @@ jobs:
|
||||
with:
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
|
||||
- name: Verify release manifest updates
|
||||
run: python3 -B -m unittest discover -s .github/scripts -p 'test_*.py' -v
|
||||
|
||||
- name: Download release information and assets
|
||||
shell: bash
|
||||
run: |
|
||||
|
||||
+8
-4
@@ -1,12 +1,12 @@
|
||||
# CrossDesk Privacy Policy
|
||||
|
||||
Last updated: October 2, 2026
|
||||
Last updated: October 10, 2026
|
||||
|
||||
[中文](#中文) | [English](#english)
|
||||
|
||||
## 中文
|
||||
|
||||
更新日期:2026 年 10 月 2 日
|
||||
更新日期:2026 年 10 月 10 日
|
||||
|
||||
CrossDesk 重视您的个人信息与隐私保护。本政策说明我们在提供远程桌面服务时如何处理相关信息,以及您可以如何管理授权、保存的内容和数据请求。请在使用前阅读并了解本政策。
|
||||
|
||||
@@ -60,7 +60,9 @@ Android 默认信令连接同样进行 TLS 证书校验。
|
||||
|
||||
**系统权限与会话功能。** iOS 客户端作为控制端接收远程电脑的画面与音频,不采集本机屏幕、摄像头或麦克风。局域网访问权限用于连接本地网络中的设备,您可在系统设置中管理。发送文件通过系统文件选择器选择,不要求开放整个文件库。当前 iOS 界面不读取或发送本机剪贴板文本;远端发送的剪贴板文本可在会话中写入本机剪贴板。
|
||||
|
||||
Android 客户端同样作为控制端接收远程画面与音频,不采集本机屏幕、摄像头或麦克风,当前不支持文件传输。剪贴板文本仅在您主动发送或复制远端文本时传输或写入本机,会话结束时清除应用内缓存的远端剪贴板文本。
|
||||
Android 客户端同样作为控制端接收远程画面与音频,不采集本机屏幕、摄像头或麦克风。发送及保存文件通过系统文件选择器完成,不要求开放整个文件库。剪贴板文本仅在您主动发送或复制远端文本时传输或写入本机,会话结束时清除应用内缓存的远端剪贴板文本。
|
||||
|
||||
Android 远程会话优先使用系统画中画在切换应用后继续显示画面。画中画不可用时,通过前台服务和连接通知保持您已建立的远程连接;后台暂停本地画面渲染和音频播放,不申请悬浮窗权限。通知权限用于提供返回及断开入口,CPU 唤醒锁用于会话后台期间维持连接,返回前台或会话结束时释放。您可以在应用或连接通知中断开,移除应用任务也会结束会话及保活服务。
|
||||
|
||||
应用及通信组件使用本地文件元数据、应用偏好和计时接口实现文件传输、设置保存及网络计时,不使用这些信息制作设备指纹或进行广告追踪。
|
||||
|
||||
@@ -138,7 +140,9 @@ Default signaling connections on Android also validate TLS certificates.
|
||||
|
||||
**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. It currently does not support file transfer. 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.
|
||||
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.
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<div align="center">
|
||||
<img src="apps/desktop/resources/linux/crossdesk_128x128.png" width="80" alt="CrossDesk 标志" />
|
||||
<h1>CrossDesk</h1>
|
||||
<p>轻量、跨平台的远程桌面,让电脑、浏览器和 iPhone / iPad 连接到同一张桌面。</p>
|
||||
<p>轻量、跨平台的远程桌面,支持电脑、浏览器和移动端连接,用桌面墙集中查看与操控多台设备。</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>
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
|
||||
</div>
|
||||
|
||||
CrossDesk 支持 Windows、macOS、Linux 之间的远程访问,也可从浏览器或原生 iOS / Android 客户端控制电脑。项目基于 [MiniRTC](https://github.com/kunkundi/minirtc),提供实时音视频传输、键鼠控制、文件传输与自托管能力,仍在持续开发中。
|
||||
CrossDesk 支持 Windows、macOS、Linux 之间的远程访问,也可从浏览器或原生 iOS / Android 客户端控制电脑。桌面端新增 **桌面墙(DeskHub)**,可在独立窗口中同时查看多台远程桌面,按分组管理设备,并进行批量操作与群控。项目基于 [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)
|
||||
[界面预览](#preview) · [下载与安装](#download) · [快速连接](#quick-start) · [桌面墙](#deskhub) · [会话操作](#session) · [设置](#settings) · [iOS](#ios) · [Android](#android) · [自托管](#self-hosting) · [源码构建](docs/BUILD.md) · [常见问题](docs/FAQ.md)
|
||||
|
||||
<a id="preview"></a>
|
||||
|
||||
@@ -27,10 +27,18 @@ CrossDesk 支持 Windows、macOS、Linux 之间的远程访问,也可从浏览
|
||||
|
||||
### 桌面客户端
|
||||
|
||||
主窗口集中展示本机 ID、连接密码、远程连接入口和近期连接记录。
|
||||
主窗口以“本桌面”和“远程桌面”两张卡片展示本机凭据与连接入口,下方是可按分组筛选的近期连接。左上角打开桌面墙,右上角菜单进入设置、消息与关于。
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-main-zh.png" width="800" alt="当前桌面客户端示例:已连接服务器,三台在线设备均显示页面缩略图" />
|
||||
<img src="docs/images/desktop-main-zh.png" width="800" alt="新版主窗口:桌面墙入口、本机凭据、远程连接卡片和近期连接分组筛选;数据为演示" />
|
||||
</p>
|
||||
|
||||
### 桌面墙(DeskHub)
|
||||
|
||||
在独立窗口中同时查看多台设备,支持分组、可调整大小的网格、精简模式、全屏与批量操作。点击画面可放大查看,再按需接管操控。
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-deskhub-zh.png" width="960" alt="桌面墙网格:六台演示设备、分组筛选、添加、选择、精简模式和网络状态入口" />
|
||||
</p>
|
||||
|
||||
### Web 客户端
|
||||
@@ -38,7 +46,7 @@ CrossDesk 支持 Windows、macOS、Linux 之间的远程访问,也可从浏览
|
||||
在浏览器中输入远程设备 ID 和密码,无需在控制端安装桌面客户端。
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/web-client.png" width="800" alt="CrossDesk Web 客户端当前连接首页" />
|
||||
<img src="docs/images/web-client.png" width="800" alt="CrossDesk Web 客户端连接首页(2026-09-25 截图)" />
|
||||
</p>
|
||||
|
||||
图片来源与更新方式见 [截图说明](docs/images/README.md)。
|
||||
@@ -49,7 +57,8 @@ CrossDesk 支持 Windows、macOS、Linux 之间的远程访问,也可从浏览
|
||||
| --- | --- |
|
||||
| 跨平台控制 | Windows / macOS / Linux 桌面互控;浏览器与原生 iOS / Android 作为控制端 |
|
||||
| 实时画面与声音 | H.264 / AV1、硬件编解码、远端声音播放;会话中可调整画质、30 / 60 fps 与画面偏好 |
|
||||
| 多设备与多显示器 | 近期连接、设备别名、会话标签与远端显示器切换 |
|
||||
| 多设备与多显示器 | 近期连接、设备别名与分组筛选、会话标签与远端显示器切换 |
|
||||
| 桌面墙(DeskHub) | 多桌面实时预览、分组与拖动排序、放大接管、群控、批量连接 / 断开 / 静音 / 文件分发;可配置分辨率、帧率与视频总带宽 |
|
||||
| 输入与协作 | 键鼠输入、远端光标同步、组合键、文本剪贴板同步、文件传输 |
|
||||
| 网络与部署 | P2P 直连、TURN 中继与强制中继、SRTP 媒体加密、自托管信令与中继服务 |
|
||||
| 隐私屏 | 被连接时自动开启,或在会话工具栏切换;可用性取决于被控端系统与采集方式 |
|
||||
@@ -68,17 +77,32 @@ CrossDesk 支持 Windows、macOS、Linux 之间的远程访问,也可从浏览
|
||||
| --- | --- | --- |
|
||||
| Windows | Windows 10+,x64 | `.exe` 安装包;便携构建也受支持 |
|
||||
| macOS | macOS 14.0+,Intel / Apple Silicon | 选择 x64 或 arm64 的 `.pkg` |
|
||||
| Linux | Ubuntu 20.04+,amd64 / arm64,glibc 2.31 基线 | `.deb` 安装包 |
|
||||
| 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 下载后,在下载目录中将文件名替换为实际安装包名称:
|
||||
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"
|
||||
```
|
||||
|
||||
如需虚拟桌面版,改为安装:
|
||||
|
||||
```bash
|
||||
sudo apt install "./crossdesk-virtual-desktop-xfce-linux-amd64-<version>.deb"
|
||||
```
|
||||
|
||||
两个包包含相同的完整程序,互相替换并保留用户配置;普通版自行补齐依赖后也能创建虚拟桌面。安装虚拟桌面版不会自动启动会话或切换默认桌面,启动方法见 [Linux 无头运行](docs/HEADLESS.md)。应用更新的下载按钮会选择已安装的包类型。已有版本升级后不会自动删除先前安装的 Xfce。
|
||||
|
||||
**macOS 首次运行:** 按应用提示,在“系统设置 → 隐私与安全性”中授予 CrossDesk **屏幕录制**(新系统可能显示为“屏幕与系统音频录制”)及 **辅助功能**权限,再按系统提示重新打开应用。前者用于捕获桌面,后者用于远程键鼠输入。
|
||||
|
||||
<a id="quick-start"></a>
|
||||
@@ -88,9 +112,9 @@ sudo apt install "./crossdesk-linux-amd64-<version>.deb"
|
||||
### 从另一台电脑连接
|
||||
|
||||
1. **准备被控电脑。** 安装并运行 CrossDesk,等待底部显示“已连接服务器”。在左侧“本桌面”查看 **本机 ID** 和 **密码**,提供给控制端。
|
||||
2. **输入对端 ID。** 在控制端右侧“远程桌面 → 对端 ID”输入被控电脑的 ID,点击 **→**。
|
||||
2. **输入对端 ID。** 在控制端右侧“远程桌面 → 对端 ID”输入被控电脑的 **9 位 ID**,点击 **连接**。
|
||||
3. **完成密码验证。** 按弹窗输入被控电脑当前的连接密码,确认后等待远程画面出现。需要保存密码时勾选“记住密码”。
|
||||
4. **再次连接。** 成功连接过的设备会出现在“近期连接”中,可通过卡片重连,也可编辑别名或删除记录。
|
||||
4. **再次连接。** 成功连接过的设备会出现在“近期连接”中,可通过卡片重连。悬停卡片可编辑别名、修改分组、删除记录或连接 / 断开;标题右侧可按分组筛选设备。
|
||||
|
||||
本机密码旁的眼睛按钮用于显示 / 隐藏密码,刷新按钮用于生成新的随机密码,铅笔按钮用于手动修改。密码统一为 **6 位数字或英文字母**。修改或刷新时需保持连接服务器;等待修改成功、客户端重新连接后,再复制当前密码。已保存旧密码的控制端需重新输入。
|
||||
|
||||
@@ -102,6 +126,27 @@ sudo apt install "./crossdesk-linux-amd64-<version>.deb"
|
||||
|
||||
如果使用自建服务器,需要让控制端与被控端接入同一服务;Web 部署配置见 [CrossDesk Web Client](https://github.com/kunkundi/crossdesk-web-client)。
|
||||
|
||||
<a id="deskhub"></a>
|
||||
|
||||
## 桌面墙:集中查看与操控多台设备
|
||||
|
||||
点击主窗口左上角 **桌面墙**,打开独立窗口;连接窗口仍可用于普通远程连接和全局设置。桌面墙会保存设备成员、分组、排序与窗口布局,重启后需要手动连接设备。
|
||||
|
||||
1. **添加设备。** 点击 **添加 → 通过设备 ID 添加**,填写 ID、密码及可选分组,点击“添加并连接”;只有勾选“记住密码”才保存凭据。也可选择 **从近期连接添加**,多选已有记录并导入;导入后用“选择 → 连接”发起连接。
|
||||
2. **查看与整理。** 从“全部设备”切换到指定分组;拖动网格分隔线统一调整画面大小,拖动设备到另一台设备上交换位置。精简模式隐藏名称和管理工具栏,全屏用于扩大查看区域;翻页保留连接。
|
||||
3. **放大与操控。** 点击设备画面进入只读放大视图,上方缩略图可切换设备,拖动中间分隔条可调整上下区域。点击 **接管操控** 后才发送键鼠;点击“释放操控”或按 **Ctrl / ⌘ + Shift + Esc** 释放。切换设备或窗口失焦也会释放操控。
|
||||
4. **批量操作。** 点击 **选择**,勾选设备或“全选”,执行连接、断开,或从“更多”中静音 / 取消静音、分发文件。“全选”覆盖当前分组的全部分页;切换分组会清空选择。
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-deskhub-focus-zh.png" width="960" alt="桌面墙放大视图:上方设备缩略图、下方主画面,以及只读预览、开启群控和接管操控入口;画面为演示" />
|
||||
</p>
|
||||
|
||||
**群控:** 在放大视图点击“开启群控”,将当前设备的键鼠操作同步到 **所有已连接设备**,包含其他分组、分页及未显示在墙内的连接;范围不受批量勾选限制。各设备接收相同坐标与按键,屏幕尺寸不同时不会另做比例适配。释放操控会同时结束群控。
|
||||
|
||||
桌面墙连接默认静音,需要声音时通过“选择 → 更多 → 取消静音”开启。底部 **网络状态** 可查看所有已连接设备的直连 / 中继、加密状态、收发速率、视频延时、丢包率、分辨率与帧率。需要显示器切换、隐私屏等完整单会话工具时,可在主窗口“近期连接”中点击已连接设备,打开独立会话窗口。
|
||||
|
||||
**关闭桌面墙会断开全部远程设备连接,并关闭共用连接的独立会话窗口;最小化不会断开。** 分组、分页和选择范围不会限制关闭时的断开范围。更多操作、预览策略与版本兼容性见 [桌面墙说明](docs/deskhub.md)。
|
||||
|
||||
<a id="session"></a>
|
||||
|
||||
## 会话中的常用操作
|
||||
@@ -121,7 +166,7 @@ sudo apt install "./crossdesk-linux-amd64-<version>.deb"
|
||||
| 全屏 | 进入 / 退出全屏 |
|
||||
| 断开连接 | 结束当前远程会话 |
|
||||
|
||||
桌面端可同步文本剪贴板。接收文件的位置可在“设置 → 文件保存路径”调整。关闭主窗口会隐藏窗口并保持程序运行;需要完全退出时使用系统托盘或菜单栏中的退出入口。
|
||||
桌面端可同步文本剪贴板。接收文件的位置可在“设置 → 常规 → 文件保存路径”调整。关闭主窗口会隐藏窗口并保持程序运行;需要完全退出时使用系统托盘或菜单栏中的退出入口。
|
||||
|
||||
### 在会话中调整画面
|
||||
|
||||
@@ -135,10 +180,10 @@ sudo apt install "./crossdesk-linux-amd64-<version>.deb"
|
||||
|
||||
## 客户端设置与更新
|
||||
|
||||
点击主窗口右上角 **☰ → 设置**,修改后点击“确认”保存。编码与连接选项建议在建立连接前调整;会话进行中部分选项不可修改。设置列表可向下滚动,查看自托管、启动方式与文件保存路径。画质、帧率和画面偏好在远程会话工具栏中调整。
|
||||
点击主窗口右上角 **☰ → 设置**,顶部切换 **常规 / 桌面墙**,修改后点击 **保存**。切换选项卡会保留未保存的修改,点击“取消”放弃修改。“常规”按界面、视频、网络连接等类别组织选项,可向下滚动查看其余设置。编码与连接选项建议在建立连接前调整;会话进行中部分选项不可修改。普通会话的画质、帧率和画面偏好在远程会话工具栏中调整。
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-settings-zh.png" width="720" alt="当前客户端设置:编码格式、硬件编解码、中继、强制中继与自动隐私屏" />
|
||||
<img src="docs/images/desktop-settings-zh.png" width="720" alt="新版常规设置:常规与桌面墙选项卡、语言、视频编码、硬件编解码及网络连接设置" />
|
||||
</p>
|
||||
|
||||
| 设置 | 说明 |
|
||||
@@ -154,9 +199,25 @@ sudo apt install "./crossdesk-linux-amd64-<version>.deb"
|
||||
| 开机自启 / 启用守护进程 | 调整启动与进程守护行为,按界面提示重启后生效 |
|
||||
| 文件保存路径 | 选择接收文件的目录 |
|
||||
|
||||
### 桌面墙画面传输
|
||||
|
||||
在 **设置 → 桌面墙** 中统一配置墙内设备,保存后立即应用到当前桌面墙会话,并用于后续连接;普通连接不受影响。
|
||||
|
||||
| 设置 | 说明 |
|
||||
| --- | --- |
|
||||
| 分辨率上限 | 自动、320 × 180、640 × 360、1280 × 720、1920 × 1080、2560 × 1440、3840 × 2160 或原始分辨率;自动模式按网格 / 放大视图调整,固定上限保持比例且不放大源画面 |
|
||||
| 帧率 | 跟随设备设置,或指定 15 / 30 / 60 FPS |
|
||||
| 视频总带宽 | 默认 20 Mbps,可选 2 / 5 / 10 / 20 / 50 / 100 Mbps;由支持该能力的桌面墙会话共享,放大画面优先分配,不包含音频、文件传输与普通连接,也不是瞬时流量的硬上限 |
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-settings-deskhub-zh.png" width="720" alt="桌面墙传输设置:自动分辨率、跟随设备帧率和 20 Mbps 视频总带宽" />
|
||||
</p>
|
||||
|
||||
支持预览订阅的设备在不可见时可暂停视频传输,重新可见时恢复;旧版被控端按其能力回退,不保证所有分辨率、帧率或带宽选项都生效。
|
||||
|
||||
### 检查更新
|
||||
|
||||
客户端启动后会在后台检查版本。发现新版本时,主窗口菜单入口会显示更新提示;打开 **☰ → 关于** 可查看版本,也可点击 **检查更新** 手动检查。发现更新后可查看更新说明并前往下载页面。
|
||||
客户端启动后会在后台检查版本,发现新版本时自动弹出更新提示,可查看更新说明并前往下载页面。关闭提示后,本次运行中的后台检查不会再次弹窗,主窗口菜单入口仍会显示更新提示;重新启动客户端后,如仍有新版本则再次提示。打开 **☰ → 关于** 可查看版本;有新版本时,点击版本信息下方的 **更新日志** 可再次打开更新提示,也可点击 **检查更新** 手动检查。
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-about-zh.png" width="720" alt="关于窗口与检查更新按钮,版本号和检查结果为演示数据" />
|
||||
@@ -191,7 +252,32 @@ sudo apt install "./crossdesk-linux-amd64-<version>.deb"
|
||||
|
||||
**CrossDesk Service**(服务名 `CrossDeskService`)提供锁屏、登录、凭据输入及安全桌面的状态上报、`Ctrl+Alt+Del` 发送和键鼠输入转发。
|
||||
|
||||
安装版会注册按需启动的服务,客户端启动时尝试启动它;本机没有 CrossDesk 客户端进程后服务会自动退出。便携版可在提示窗口或“设置 → 锁屏控制服务”中安装服务,需要管理员权限。该服务依赖客户端运行。
|
||||
安装版默认注册按需启动的服务,客户端启动时尝试启动它;未启用无人值守时,本机没有 CrossDesk 客户端进程后服务会自动退出。便携版可在提示窗口或“设置 → 锁屏控制服务”中安装服务,需要管理员权限。
|
||||
|
||||
Windows 的“开机自启”在当前用户登录后启动客户端。安装版使用以最高权限运行的登录计划任务,后续登录无需再次确认 UAC;便携版和 Debug 构建使用当前用户的普通启动项。升级安装版或手动启动新版时,会自动迁移指向该程序的旧启动项。关闭自启会删除相应注册。登录前远控需要另外启用下面的无人值守模式。
|
||||
|
||||
### 开机后尚未登录时远控
|
||||
|
||||
安装版支持独立的无人值守被控端。在完整安装目录中打开**管理员 PowerShell**,一次性启用:
|
||||
|
||||
```powershell
|
||||
.\CrossDesk.exe --unattended-enable
|
||||
# 等待联网注册后,查看独立设备 ID、密码和 online 状态
|
||||
.\CrossDesk.exe --unattended-status
|
||||
```
|
||||
|
||||
使用返回的 `device_id` 和 `password` 从另一台设备连接。首次启用时复制当前客户端的服务器和编码设置,单独生成无人值守凭据;它与普通客户端的设备 ID 不同,重启、注销和重新启用时保留。后续执行启用命令会复用机器配置,不会覆盖它。自建服务器的根证书需要安装到本地计算机的信任存储中。
|
||||
|
||||
启用后,`CrossDeskService` 改为系统启动时自动运行,无需 Windows 自动登录,也不需要保存 Windows 登录密码。服务以 SYSTEM 身份在当前控制台会话中启动无界面的被控进程,复用登录界面抓屏、键鼠及 `Ctrl+Alt+Del` 支持。用户登录、锁屏和关闭普通客户端不会停止它;注销、切换用户或进程崩溃后服务会重新拉起,期间连接可能中断,需要重新连接同一设备 ID。启动时网络尚未就绪会继续重试。
|
||||
|
||||
无人值守模式提供画面、键鼠、多屏切换和安全桌面控制;不提供声音、文件传输、剪贴板或隐私遮罩。便携版和 Debug 构建不能启用此模式。设置和凭据位于 `%ProgramData%\CrossDeskUnattended`,只允许 SYSTEM 和管理员访问;日志位于其 `logs` 子目录。
|
||||
|
||||
```powershell
|
||||
# 停止无人值守被控端,并恢复服务按需启动
|
||||
.\CrossDesk.exe --unattended-disable
|
||||
```
|
||||
|
||||
关闭普通“开机自启”不会关闭无人值守模式。禁用或卸载服务会取消无人值守启动,但保留受保护的机器配置;若需彻底清除凭据,在服务停止后由管理员删除该目录。
|
||||
|
||||
<details>
|
||||
<summary>手动部署与服务管理命令</summary>
|
||||
@@ -216,7 +302,7 @@ sudo apt install "./crossdesk-linux-amd64-<version>.deb"
|
||||
|
||||
## 自托管服务器
|
||||
|
||||
可自行部署信令服务与 TURN 中继,并在桌面客户端 **☰ → 设置 → 自托管配置** 中填写连接信息。控制端与被控端都需要启用同一套配置。
|
||||
可自行部署信令服务与 TURN 中继,并在桌面客户端 **☰ → 设置 → 常规 → 自托管配置** 中填写连接信息。控制端与被控端都需要启用同一套配置。
|
||||
|
||||
- [自托管指南](docs/SELF_HOSTING.md):当前 Compose 部署入口、客户端设置、证书信任与排查。
|
||||
- [CrossDesk Server](https://github.com/kunkundi/crossdesk-server):服务端源码与发布配置。
|
||||
|
||||
+103
-17
@@ -1,7 +1,7 @@
|
||||
<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 lightweight, cross-platform remote desktop for computers, browsers, and mobile devices, with DeskHub for viewing and controlling multiple desktops.</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>
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
|
||||
</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.
|
||||
CrossDesk connects Windows, macOS, and Linux desktops, with browser and native iOS / Android clients for controlling computers. The desktop client now includes **DeskHub**, a separate window for viewing multiple remote desktops, organizing devices into groups, and performing batch actions or synchronized control. 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)
|
||||
[Preview](#preview) · [Download](#download) · [Quick start](#quick-start) · [DeskHub](#deskhub) · [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>
|
||||
|
||||
@@ -27,10 +27,18 @@ CrossDesk connects Windows, macOS, and Linux desktops, with browser and native i
|
||||
|
||||
### Desktop client
|
||||
|
||||
The main window brings together your device ID, connection password, remote connection entry, and recent devices.
|
||||
The main window presents your credentials and connection controls in Local Desktop and Remote Desktop cards, with recent devices and a group filter below. Open DeskHub at the top left, or use the top-right menu for settings, messages, and About.
|
||||
|
||||
<p align="center">
|
||||
<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" />
|
||||
<img src="docs/images/desktop-main-en.png" width="800" alt="Updated main window with DeskHub access, local credentials, remote connection controls, and recent-device group filtering; data is illustrative" />
|
||||
</p>
|
||||
|
||||
### DeskHub
|
||||
|
||||
View multiple devices in a separate window with groups, a resizable grid, compact and fullscreen views, and batch actions. Click a preview to enlarge it, then take control when needed.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-deskhub-en.png" width="960" alt="DeskHub grid with six demonstration devices, group filtering, Add, Select, Compact, and Network controls" />
|
||||
</p>
|
||||
|
||||
### Web client
|
||||
@@ -38,7 +46,7 @@ The main window brings together your device ID, connection password, remote conn
|
||||
Enter a remote device ID and password in your browser without installing the desktop app on the controlling device.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/web-client.png" width="800" alt="Current CrossDesk Web Client connection page in Chinese" />
|
||||
<img src="docs/images/web-client.png" width="800" alt="CrossDesk Web Client connection page in Chinese, captured on 2026-09-25" />
|
||||
</p>
|
||||
|
||||
See the [screenshot notes](docs/images/README.md) for image sources and refresh instructions.
|
||||
@@ -49,7 +57,8 @@ See the [screenshot notes](docs/images/README.md) for image sources and refresh
|
||||
| --- | --- |
|
||||
| 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 |
|
||||
| Devices and displays | Recent connections, device aliases and group filtering, session tabs, and remote display switching |
|
||||
| DeskHub | Live multi-desktop previews, groups and drag reordering, enlarged views with control, synchronized input, and batch connection / disconnection / audio / file actions; configurable resolution, frame rate, and shared video budget |
|
||||
| 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 |
|
||||
@@ -68,17 +77,32 @@ Choose a package matching your OS and CPU architecture from [GitHub Releases](ht
|
||||
| --- | --- | --- |
|
||||
| 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 | `.deb` package |
|
||||
| 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/) |
|
||||
|
||||
On Linux, replace the example filename with the downloaded package name:
|
||||
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** |
|
||||
|
||||
To install the standard package, replace the example filename with your download (use arm64 for that architecture):
|
||||
|
||||
```bash
|
||||
sudo apt install "./crossdesk-linux-amd64-<version>.deb"
|
||||
```
|
||||
|
||||
For the virtual desktop package, install this file instead:
|
||||
|
||||
```bash
|
||||
sudo apt install "./crossdesk-virtual-desktop-xfce-linux-amd64-<version>.deb"
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
<a id="quick-start"></a>
|
||||
@@ -88,9 +112,9 @@ sudo apt install "./crossdesk-linux-amd64-<version>.deb"
|
||||
### Connect from another computer
|
||||
|
||||
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 **→**.
|
||||
2. **Enter the remote ID.** On the controlling computer, enter the host's **9-digit ID** in **Remote Desktop → Remote ID**, then click **Connect**.
|
||||
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.
|
||||
4. **Reconnect later.** Previously connected devices appear under **Recent Connections**. Reconnect from a card, or hover to rename it, edit its groups, remove its record, or connect / disconnect. Use the group filter beside the heading to narrow the list.
|
||||
|
||||
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.
|
||||
|
||||
@@ -102,6 +126,27 @@ The eye button shows or hides the local password, the refresh button generates a
|
||||
|
||||
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="deskhub"></a>
|
||||
|
||||
## DeskHub: view and control multiple devices
|
||||
|
||||
Click **DeskHub** at the top left of the main window to open a separate window. The connection window remains available for ordinary remote sessions and global settings. DeskHub saves its device membership, groups, order, and window layout; connections must be started manually after relaunching.
|
||||
|
||||
1. **Add devices.** Choose **Add → Add by device ID**, enter an ID, password, and optional group, then click **Add and connect**. Credentials are saved only when you select **Remember password**. Alternatively, choose **Add from recent** and import multiple records; use **Select → Connect** to connect after importing.
|
||||
2. **Arrange the view.** Switch from **All devices** to a group, drag grid dividers to resize all previews, or drag a device onto another to swap positions. **Compact** hides device names and management controls; fullscreen provides more viewing space. Changing pages keeps connections open.
|
||||
3. **Enlarge and control.** Click a preview to open a read-only enlarged view. Switch devices with the thumbnails above it, and drag the divider to resize the two areas. Click **Control** to send keyboard and mouse input. Click **Release** or press **Ctrl / ⌘ + Shift + Esc** to release; switching devices or losing window focus also releases control.
|
||||
4. **Apply batch actions.** Click **Select**, choose devices or **Select all**, and connect, disconnect with **Close**, or use **More** to mute / unmute or send a file. **Select all** includes every page in the current group; switching groups clears the selection.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-deskhub-focus-en.png" width="960" alt="DeskHub enlarged view with thumbnails above the main preview and View only status, Group control, and Control buttons; screens are illustrative" />
|
||||
</p>
|
||||
|
||||
**Group control:** click **Group control** in the enlarged view to mirror input from the current device to **all connected devices**, including other groups, pages, and connections not displayed in the wall. The scope is independent of the batch selection. Devices receive the same coordinates and keys without additional scaling for different screen sizes. Releasing control also ends group control.
|
||||
|
||||
DeskHub connections are muted by default. Enable sound with **Select → More → Unmute**. The bottom **Network** button shows direct / relay mode, encryption, receive/send rates, video latency, packet loss, resolution, and frame rate for all connected devices. For the full single-session toolbar, including display switching and privacy screens, click a connected device under **Recent Connections** in the main window to open its separate session window.
|
||||
|
||||
**Closing DeskHub disconnects all remote devices and closes session windows sharing those connections; minimizing it keeps connections open.** The disconnect scope includes all groups and pages, regardless of selection. See the [DeskHub guide](docs/deskhub.md) (Chinese) for further controls, preview behavior, and compatibility details.
|
||||
|
||||
<a id="session"></a>
|
||||
|
||||
## Session controls
|
||||
@@ -121,7 +166,7 @@ Switch devices using session tabs. Expand the control bar if it is collapsed, an
|
||||
| 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.
|
||||
Desktop clients synchronize text clipboard contents. Configure the receiving directory under **Settings → General → 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
|
||||
|
||||
@@ -135,10 +180,10 @@ After connecting, open **Video settings** (the sliders icon) in the toolbar. Cho
|
||||
|
||||
## 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.
|
||||
Open **☰ → Settings** in the top-right corner, choose **General / DeskHub**, and click **Save** to apply changes. Switching tabs preserves pending changes; **Cancel** discards them. General settings are grouped into interface, video, networking, and further sections available by scrolling. Configure codecs and connections before connecting; some settings are disabled during an active session. Adjust ordinary session quality, frame rate, and video preference from its 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" />
|
||||
<img src="docs/images/desktop-settings-en.png" width="720" alt="Updated General settings with General and DeskHub tabs, language, video codec, hardware codecs, and networking options" />
|
||||
</p>
|
||||
|
||||
| Setting | Purpose |
|
||||
@@ -154,9 +199,25 @@ Open **☰ → Settings** in the top-right corner and click **OK** to save. Conf
|
||||
| Auto Start / Enable Daemon | Configure startup and process supervision; restart as indicated by the UI |
|
||||
| File Save Path | Choose where received files are saved |
|
||||
|
||||
### DeskHub video transmission
|
||||
|
||||
Use **Settings → DeskHub** to configure wall sessions together. Saving applies changes immediately to current DeskHub sessions and future connections; ordinary connections are unaffected.
|
||||
|
||||
| Setting | Purpose |
|
||||
| --- | --- |
|
||||
| Resolution limit | Auto, 320 × 180, 640 × 360, 1280 × 720, 1920 × 1080, 2560 × 1440, 3840 × 2160, or Original resolution; Auto adapts to grid / enlarged views, while fixed limits preserve aspect ratio without upscaling the source |
|
||||
| Frame rate | Follow device settings, or choose 15 / 30 / 60 FPS |
|
||||
| Video budget | Defaults to 20 Mbps; choose 2 / 5 / 10 / 20 / 50 / 100 Mbps, shared by compatible DeskHub sessions with priority for enlarged views. Audio, file transfers, and ordinary connections are excluded; this is not a hard limit on instantaneous traffic |
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-settings-deskhub-en.png" width="720" alt="DeskHub video settings with Auto resolution, Follow device settings frame rate, and a 20 Mbps video budget" />
|
||||
</p>
|
||||
|
||||
Devices supporting preview subscriptions can pause video while their views are hidden and resume when visible. Older hosts fall back according to their capabilities, so not every resolution, frame-rate, or bandwidth setting will apply.
|
||||
|
||||
### Check for updates
|
||||
|
||||
The client checks for updates in the background after launch. A new version adds an update indicator to the main window menu. Open **☰ → About** to view the version or click **Check for updates** to check manually. When an update is available, you can view its release notes and open the download page.
|
||||
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" />
|
||||
@@ -183,7 +244,32 @@ Gestures include one-finger click, two-finger right-click, long-press drag, and
|
||||
|
||||
**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. CrossDesk tries to start it on launch, and 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. The service depends on a running client.
|
||||
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>
|
||||
@@ -208,7 +294,7 @@ If **Remote Windows service unavailable** appears, check installation and servic
|
||||
|
||||
## 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.
|
||||
Host your own signaling and TURN services, then enter their connection details under **☰ → Settings → General → 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.
|
||||
|
||||
+48
-17
@@ -1,10 +1,10 @@
|
||||
# CrossDesk Android
|
||||
|
||||
原生 Android 控制端,使用 Java 界面、JNI 和 MiniRTC,与桌面端使用相同的信令、ICE、SRTP 和输入协议。没有 WebView。当前版本为 1.6.0,支持 Android 8.0(API 26)及以上的 arm64 手机和平板。
|
||||
原生 Android 控制端,使用 Java 界面、JNI 和 MiniRTC,与桌面端使用相同的信令、ICE、SRTP 和输入协议。没有 WebView。当前版本为 1.6.1,支持 Android 8.0(API 26)及以上的 arm64 手机和平板。
|
||||
|
||||
## 当前功能
|
||||
|
||||
- 官方或自托管 WSS 信令服务器;授权后进入前台即自动注册或登录本机身份,首页实时显示连接、重连及失败状态。发起桌面连接时复用该身份;切换服务器会重新登录,撤回授权或进入后台会关闭连接。
|
||||
- 官方或自托管 WSS 信令服务器;授权后进入前台即自动注册或登录本机身份,首页实时显示连接、重连及失败状态。发起桌面连接时复用该身份;切换服务器会重新登录,撤回授权会关闭连接。已有远程会话优先通过系统画中画保持连接,画中画不可用时由带连接通知的前台服务兜底;首页空闲信令在后台关闭。
|
||||
- 优先使用 MediaCodec 硬件解码 H.264 / AV1,硬件缓冲区直接提交 Surface;设备无对应硬件、分辨率超限或运行失败时,按原编码格式回退到 OpenH264 / dav1d。软件输出由独立显示线程将 NV12 转 RGBA;只保留最新待显示帧。MiniRTC 原有的通用压缩帧解码队列保持不变。
|
||||
- 48 kHz 单声道 PCM 播放,支持静音,音频队列有容量限制。
|
||||
- 相对鼠标(触控板)和绝对位置模式;单指点击、绝对模式按住拖动、长按右键,以及外接键盘、鼠标。画面手势与 iOS 一致:双指捏合以触点为中心缩放(1–10 倍),放大后双指拖动画面,原始比例下双指上下滑动控制滚轮。
|
||||
@@ -12,8 +12,11 @@
|
||||
- 根据常见移动设备解码能力和屏幕尺寸设置起始参数:显示长边不超过 1280 像素时默认低画质(最高 720p)/30 fps,其余默认中画质(最高 1080p)/30 fps。用户保存的画面偏好不变,仍可手动选择高画质或 60 fps。
|
||||
- 网络状态按视频、音频、数据、合计展示收发速率和丢包率,并显示实际提交帧率、分辨率、画面延时、平滑 RTT、P2P/TURN 和实际 SRTP 状态。每秒刷新,过期或无效测量显示“—”。
|
||||
- 可拖动的悬浮控制球、三列控制菜单和浮动 ASCII / 电脑键盘、常用快捷键;通过剪贴板发送中文等文本,再手动执行远端粘贴。
|
||||
- 设备身份与选择保存的连接密码使用 Android Keystore / AES-GCM 加密;首次联网需同意,后台切换会结束会话。
|
||||
- 与 iOS 一致的首页卡片、顶部状态/公告/设置入口、密码底部弹层、两列最近连接及分组设置页;最近连接按服务器隔离,长按可删除记录及密码。
|
||||
- 悬浮菜单中的“虚拟鼠标”展开 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 共用信令协议,支持未读角标、分页、下拉刷新、更新推送、详情和网页链接;已读及删除状态按服务器、本机身份和公告版本保存在本机。
|
||||
@@ -21,7 +24,13 @@
|
||||
- 可选保存远程画面预览:默认关闭,经确认开启后,从下一次连接起保存一张 640×360 预览,用于最近连接卡片。支持清除预览,关闭选项或撤回授权会清除已有图片。
|
||||
- “关于 CrossDesk”对齐 iOS 的版本、软件许可、开源组件及源码与构建说明页面,包含 OpenFEC 告知、组件详情和可离线选择复制的完整许可;版本号读取当前 APK,构建时记录应用与 MiniRTC 的基础版本。
|
||||
|
||||
当前不包含安卓被控端、文件传输、隐私屏、Ctrl+Alt+Del 服务命令或 iOS 全部附加功能。相关入口保留 iOS 的布局并明确标注不可用。硬件能力取决于设备和编码格式,软件回退时高分辨率或高帧率可能增加功耗;可通过悬浮菜单的画面设置降低画质或采集帧率。暂只构建 `arm64-v8a`,不支持 x86 模拟器或 32 位设备。
|
||||
当前不包含安卓被控端、隐私屏或 iOS 全部附加功能。硬件能力取决于设备和编码格式,软件回退时高分辨率或高帧率可能增加功耗;可通过悬浮菜单的画面设置降低画质或采集帧率。暂只构建 `arm64-v8a`,不支持 x86 模拟器或 32 位设备。
|
||||
|
||||
## 本机更新提示
|
||||
|
||||
完成联网授权后,每次启动或从后台返回时检查一次公共版本文件,前台远程连接结束后再检查一次;同时触发时复用正在进行的请求。不进行周期性检查或自动重试,失败时保留已发现的新版本提示,等待下一次触发或手动检查;进入后台或撤回授权时取消请求并忽略过期回复。
|
||||
|
||||
本机只读取 `downloads.android-arm64`,复用 PC 端的版本号及补丁比较规则;仅构建日期变化不提示升级,平台版本字段缺失按检查失败处理。发现新版本后,首页设置按钮右上角显示红底白色感叹号角标,大小和位置与通知角标一致,设置页“关于”显示“新版本”文字和红点;“关于”展示新版本号、官网更新入口,并提供“检查更新”。该功能独立于被控电脑的版本升级提示。
|
||||
|
||||
## 构建
|
||||
|
||||
@@ -29,7 +38,7 @@
|
||||
|
||||
- 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 和主机编译工具。
|
||||
- Xmake **3.1.1 或更新版本**、Python 3.9+、Git、CMake 和主机编译工具。
|
||||
- Python 的 setuptools、wheel,用于构建依赖的宿主工具。
|
||||
|
||||
先在仓库根目录初始化子模块:
|
||||
@@ -43,8 +52,7 @@ 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 指定对应可执行文件。
|
||||
# 构建器也识别 ~/.cache/crossdesk/toolchains/xmake-3.1.1/xmake。
|
||||
# 使用 PATH 中的 Xmake(最低 3.1.1),或通过 XMAKE_BIN 指定其他可执行文件。
|
||||
cd apps/android
|
||||
./gradlew :app:assembleDebug
|
||||
```
|
||||
@@ -75,11 +83,11 @@ Release 构建使用 `./gradlew :app:assembleRelease`,默认输出未签名 AP
|
||||
|
||||
[`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` 标签,例如:
|
||||
单独发布使用 [`Release Mobile`](../../.github/workflows/release-mobile.yml)。先更新并提交 `gradle.properties` 中的 `crossdeskVersionName` 和递增的 `crossdeskVersionCode`,再为该提交创建 `android-v<versionName>-YYYYMMDD` 标签,例如:
|
||||
|
||||
```sh
|
||||
git tag android-v1.6.0-20261002
|
||||
git push origin android-v1.6.0-20261002
|
||||
git tag android-v1.6.1-20261010
|
||||
git push origin android-v1.6.1-20261010
|
||||
```
|
||||
|
||||
该标签只触发安卓构建,使用固定发布密钥签名并验证 Release APK 后,再发布到独立的 GitHub Release 和现有下载服务器。签名失败或缺少签名 Secrets 时停止发布,不回退到未签名 APK。标签版本必须与应用版本一致,日期必须有效。重试发布时,在 Actions 页面手动运行 `Release Mobile`,将已有标签填入 `source_tag`;即使从其他分支触发,也会检出该标签的源码。APK 的源码资料记录安卓标签及准确的应用、MiniRTC 提交。
|
||||
@@ -88,20 +96,19 @@ git push origin android-v1.6.0-20261002
|
||||
|
||||
已有 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。Gradle 使用工程内的 Wrapper,原生构建器固定 Xmake 包仓库版本。SDK/NDK 使用独立目录缓存,按宿主系统、架构和工具链版本区分;命中缓存时跳过 SDK 安装,未命中时在安装完成后立即保存,即使后续 APK 构建失败,下次也可复用。Xmake 可执行环境、固定版本的包仓库和 pip 下载也有各自的缓存;Ubuntu 系统工具只安装缺失项。
|
||||
工作流使用 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,执行 Debug / Release Lint、本机 C++ 协议与画面队列测试,并校验 APK 的 arm64 ABI、16 KB ELF / ZIP 对齐、完整许可证及 Debug 签名。Ubuntu x64 构建机上不运行 arm64 设备测试;使用下面的设备验证流程在 arm64 手机或模拟器上执行。Lint 报告在构建失败时也会保留。
|
||||
CI 仅构建和打包 Debug、Release APK,并校验 APK 的包名、`versionName` / `versionCode`、arm64 ABI、16 KB ELF / ZIP 对齐、完整许可证及 Debug 签名。单元测试、本机 C++ 协议与画面队列测试、Lint 和设备测试改为按需在本地执行;设备测试使用下面的设备验证流程在 arm64 手机或模拟器上执行。
|
||||
|
||||
产物使用 Android 工程自己的 `versionName`,例如 `v1.6.0-20261002`,不跟随桌面版本号。构建日期采用上海时区;带日期的版本标签沿用标签中的日期,与 iOS 一致。Actions 提供:
|
||||
统一 `v*` 发布从标签提取数字版本,通过 Gradle 属性写入 APK 的 `versionName`;App 内版本展示读取同一包信息。产物版本、日期及可选热修复编号与桌面端保持一致,例如 `v1.6.1-20261010` 或 `v1.6.1-2-20261010`。分支构建和独立 `android-v*` 发布使用 `gradle.properties` 中的版本,独立发布会检查标签与配置一致。构建日期采用上海时区;带日期的版本标签沿用标签中的日期,与 iOS 一致。Actions 提供:
|
||||
|
||||
- `crossdesk-android-arm64-<版本>.apk`:已签名 Release APK,独立安卓发布和全平台标签发布收集此 APK,可直接安装。
|
||||
- `crossdesk-android-arm64-unsigned-<版本>.apk`:构建工作流的中间产物,也可用于自行签名和验证修改后的构建。
|
||||
- `crossdesk-android-arm64-debug-<版本>.apk` 和对应的 `-test.apk`:可安装的调试应用和设备测试包,保留 14 天。
|
||||
- `crossdesk-android-reports`:Lint 报告,保留 14 天。
|
||||
- `crossdesk-android-arm64-debug-<版本>.apk`:可安装的调试应用,保留 14 天。
|
||||
|
||||
Debug APK 使用每次运行的临时调试证书,可能无法覆盖手机上已有的其他签名版本;卸载原应用会清除本机连接记录和密码。需要持续覆盖升级时,应使用同一私钥签名 Release APK,并在发布新版本时递增 `app/build.gradle` 中的 `versionCode`。未签名 APK 已完成对齐,可通过 SDK 的 `apksigner sign --ks <自己的密钥库> --out <已签名.apk> <未签名.apk>` 签名,再用 `apksigner verify` 检查。
|
||||
Debug APK 使用每次运行的临时调试证书,可能无法覆盖手机上已有的其他签名版本;卸载原应用会清除本机连接记录和密码。需要持续覆盖升级时,应使用同一私钥签名 Release APK,并在每次发布新版本(含统一发布及热修复)时递增 `gradle.properties` 中的 `crossdeskVersionCode`。该安装升级序号独立于显示版本,不从日期或 CI 运行编号推算。未签名 APK 已完成对齐,可通过 SDK 的 `apksigner sign --ks <自己的密钥库> --out <已签名.apk> <未签名.apk>` 签名,再用 `apksigner verify` 检查。
|
||||
|
||||
### Release 签名
|
||||
|
||||
@@ -146,6 +153,24 @@ gh secret set ANDROID_KEY_PASSWORD --repo kunkundi/crossdesk
|
||||
|
||||
会话中的“剪贴板”发送用户输入的文本;收到的远端文本先留在会话内,点击“复制远端文本”才写入手机剪贴板。退出会话后清除会话内容。每次发送最多 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 时清除旧帧,会话结束时先停止显示线程再销毁原生连接。
|
||||
@@ -197,6 +222,12 @@ python3 test/run_native.py
|
||||
|
||||
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 时仍可使用软件编解码。独立输出线程在画面停止更新后仍会取出最后一帧,空闲时休眠。
|
||||
|
||||
@@ -8,8 +8,8 @@ android {
|
||||
applicationId 'cn.crossdesk.mobile'
|
||||
minSdk 26
|
||||
targetSdk 36
|
||||
versionCode 2
|
||||
versionName '1.6.0'
|
||||
versionCode providers.gradleProperty('crossdeskVersionCode').get().toInteger()
|
||||
versionName providers.gradleProperty('crossdeskVersionName').get()
|
||||
ndk { abiFilters 'arm64-v8a' }
|
||||
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
|
||||
}
|
||||
|
||||
@@ -2,13 +2,25 @@
|
||||
<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:configChanges="orientation|screenSize|keyboardHidden"
|
||||
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" />
|
||||
|
||||
@@ -17,15 +17,22 @@ final class AboutPages {
|
||||
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){
|
||||
this.activity=activity;this.ui=ui;this.settings=settings;
|
||||
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 version=activity.section(content,"");value(version,"版本",applicationVersion());ui.gap(content,28);
|
||||
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);
|
||||
@@ -33,7 +40,22 @@ final class AboutPages {
|
||||
activity.footer(content,"许可与版权声明可离线查阅。");
|
||||
}
|
||||
private String applicationVersion(){
|
||||
try{return activity.getPackageManager().getPackageInfo(activity.getPackageName(),0).versionName;}catch(android.content.pm.PackageManager.NameNotFoundException error){return "—";}
|
||||
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);
|
||||
|
||||
@@ -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,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);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ 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;
|
||||
@@ -29,6 +30,9 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
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;
|
||||
@@ -43,6 +47,7 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
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());
|
||||
@@ -61,16 +66,28 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
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;
|
||||
@@ -84,6 +101,7 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
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);};
|
||||
@@ -107,10 +125,13 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
}
|
||||
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);
|
||||
root=column();canvas.addView(root,new FrameLayout.LayoutParams(-1,-1));
|
||||
root.setOnApplyWindowInsetsListener((view,insets)->{
|
||||
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);
|
||||
@@ -144,14 +165,24 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
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);}
|
||||
void link(LinearLayout parent,String title,String detail,Runnable action){
|
||||
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);
|
||||
}
|
||||
@android.annotation.SuppressLint("SourceLockedOrientationActivity") // Match the iOS portrait home; sessions support both orientations.
|
||||
private void home(String message){
|
||||
backAction=null;setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);installRoot("home",false);
|
||||
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->{
|
||||
@@ -159,11 +190,15 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
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 bell=(FrameLayout)ui.iconButton("bell","通知公告",this::announcements);bell.setClipChildren(false);toolbar.setClipChildren(false);
|
||||
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));bell.addView(announcementBadge,badgePosition);renderAnnouncements();
|
||||
toolbar.addView(bell,ui.size(40,40));View spacer=new View(this);toolbar.addView(spacer,ui.size(12,1));toolbar.addView(ui.iconButton("settings","设置",this::settings),ui.size(40,40));
|
||||
LinearLayout content=column();content.setPadding(dp(20),dp(24),dp(20),dp(12));content.setClipChildren(false);content.setClipToPadding(false);root.addView(content,new LinearLayout.LayoutParams(-1,0,1));
|
||||
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));
|
||||
@@ -181,10 +216,23 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
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);renderRecentConnections();
|
||||
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())new AlertDialog.Builder(this).setTitle("连接提示").setMessage(message).setPositiveButton("确定",null).show();
|
||||
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 ");}
|
||||
@@ -192,7 +240,7 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
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+=2){LinearLayout line=row();line.setGravity(Gravity.TOP);recentGrid.addView(line);for(int j=i;j<i+2;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.leftMargin=dp(12);line.addView(card,cell);}ui.gap(recentGrid,12);}
|
||||
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");
|
||||
@@ -223,7 +271,7 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
private void consent(Runnable accepted){
|
||||
if(privacyDialog!=null&&privacyDialog.isShowing())return;
|
||||
Dialog dialog=new PrivacyConsentDialog(this,ui,()->{
|
||||
preferences.edit().putBoolean("networkConsent",true).apply();renderSignaling();ensureSignaling();accepted.run();
|
||||
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();
|
||||
}
|
||||
@@ -239,10 +287,20 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
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));
|
||||
dialog.setContentView(sheet);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();if(window!=null){window.setLayout(-1,-2);window.setGravity(Gravity.BOTTOM);}password.requestFocus();if(!error.isEmpty())password.setError(error);
|
||||
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;
|
||||
@@ -260,27 +318,40 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
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.videoSettings(videoSettings);root.addView(controls,new LinearLayout.LayoutParams(-1,-1));getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
});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);home(reason);
|
||||
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);
|
||||
TextView detail=text(relative?"像触控板一样滑动光标,点击时操作当前光标位置。":"触摸位置直接对应远端屏幕位置,适合快速定位。",13,false);detail.setTextColor(SECONDARY);
|
||||
mouse.addView(segments(new String[]{"相对位置","绝对位置"},relative?0:1,true,index->{preferences.edit().putBoolean("relativeMouse",index==0).apply();detail.setText(index==0?"像触控板一样滑动光标,点击时操作当前光标位置。":"触摸位置直接对应远端屏幕位置,适合快速定位。");}));ui.gap(mouse,10);mouse.addView(detail);
|
||||
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)));TextView preferenceDetail=text(RemoteVideoSettings.DETAILS[preference],13,false);preferenceDetail.setTextColor(SECONDARY);
|
||||
picture.addView(segments(RemoteVideoSettings.PREFERENCES,preference,true,index->{preferences.edit().putInt("videoPreference",index).apply();preferenceDetail.setText(RemoteVideoSettings.DETAILS[index]);}));ui.gap(picture,10);picture.addView(preferenceDetail);ui.gap(content,28);
|
||||
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);
|
||||
@@ -294,7 +365,9 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
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();
|
||||
footer(content,"画面预览默认关闭。开启后,从下一次连接起保存一张远程画面到本机,显示在最近连接中,不上传且不纳入设备备份。关闭开关会清除已有预览;连接记录和密码不受影响。");LinearLayout about=section(content,"",MobileUi.SETTINGS_CARD_RADIUS);link(about,"关于","",this::about);
|
||||
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("保存远程画面预览?")
|
||||
@@ -362,15 +435,33 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
@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();previews.setEnabled(false);stopSignaling();announcementInbox.reset();privacyPage();}).show()));else content.addView(ui.primary("阅读并授权",()->consent(this::privacyPage)));
|
||||
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);aboutPages.show();
|
||||
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);}}
|
||||
@@ -378,6 +469,46 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
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);
|
||||
@@ -412,6 +543,7 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
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();
|
||||
@@ -447,6 +579,7 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
// 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();
|
||||
}
|
||||
@@ -463,7 +596,7 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
}
|
||||
private void cancelVideoSettingsTimeout(){if(videoSettingsTimeout!=null)mainHandler.removeCallbacks(videoSettingsTimeout);videoSettingsTimeout=null;}
|
||||
private void showRemoteUpdate(){
|
||||
if(!ready||session==null||!foreground||isFinishing()||!preferences.getBoolean("networkConsent",false))return;
|
||||
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);
|
||||
@@ -486,6 +619,7 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
}
|
||||
@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){
|
||||
@@ -497,20 +631,141 @@ public final class MainActivity extends Activity implements NativeSession.Listen
|
||||
if(foreground&&preferences.getBoolean("networkConsent",false))remoteVersionCheck.hostInfo(info);
|
||||
}
|
||||
}
|
||||
@Override public void videoSize(int width,int height){if(video!=null)video.videoSize(width,height);if(controls!=null)controls.videoSize(width,height);}
|
||||
@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&&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);
|
||||
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);if(controls!=null)controls.post(controls::constrainPanels);}
|
||||
@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 onStart(){super.onStart();foreground=true;if(!preferences.getBoolean("networkConsent",false))consent(this::renderSignaling);ensureSignaling();}
|
||||
@Override protected void onStop(){foreground=false;if(privacyDialog!=null)privacyDialog.dismiss();pageHost.finish();if(session!=null)end(isFinishing()?"":"应用已进入后台,会话已结束");stopSignaling();super.onStop();}
|
||||
@Override protected void onDestroy(){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(session!=null)session.close();stopSignaling();super.onDestroy();}
|
||||
@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();}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,16 @@ final class MobileUi {
|
||||
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);
|
||||
@@ -89,10 +99,19 @@ final class MobileUi {
|
||||
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":
|
||||
c.drawCircle(12,12,7,paint);c.drawCircle(12,12,3,paint);
|
||||
for(int i=0;i<8;i++){c.save();c.rotate(i*45,12,12);c.drawLine(12,2,12,5,paint);c.restore();}break;
|
||||
case "bell":
|
||||
path(c,5,17,6,14,6,9,7,6,10,4,14,4,17,6,18,9,18,14,19,17,5,17);c.drawArc(9,17,15,22,0,180,false,paint);c.drawLine(12,2,12,4,paint);break;
|
||||
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;
|
||||
|
||||
@@ -28,6 +28,8 @@ final class NativeSession implements AutoCloseable {
|
||||
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) { }
|
||||
@@ -38,7 +40,7 @@ final class NativeSession implements AutoCloseable {
|
||||
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 final Listener listener;
|
||||
private volatile Listener listener;
|
||||
private final SecretStore secrets;
|
||||
private final String host, scope;
|
||||
private volatile String remote;
|
||||
@@ -52,6 +54,11 @@ final class NativeSession implements AutoCloseable {
|
||||
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;
|
||||
@@ -67,6 +74,7 @@ final class NativeSession implements AutoCloseable {
|
||||
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;
|
||||
@@ -80,6 +88,7 @@ final class NativeSession implements AutoCloseable {
|
||||
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("安全存储或证书初始化失败,请重试或清除应用数据"); }
|
||||
});
|
||||
@@ -99,6 +108,9 @@ final class NativeSession implements AutoCloseable {
|
||||
});
|
||||
}
|
||||
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.
|
||||
@@ -169,7 +181,7 @@ final class NativeSession implements AutoCloseable {
|
||||
connected = true; main.removeCallbacks(timeout); nReady(handle);
|
||||
audio = new AudioPlayer();
|
||||
nControl(handle, 2, 1);
|
||||
ui(() -> { listener.connected(); if(!closed)statisticsTick.run(); });
|
||||
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 {
|
||||
@@ -186,6 +198,11 @@ final class NativeSession implements AutoCloseable {
|
||||
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("设备身份保存失败,请检查安全存储");
|
||||
@@ -232,19 +249,42 @@ final class NativeSession implements AutoCloseable {
|
||||
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);
|
||||
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);
|
||||
@@ -255,6 +295,10 @@ final class NativeSession implements AutoCloseable {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -12,11 +12,13 @@ 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);requestWindowFeature(Window.FEATURE_NO_TITLE);setCancelable(false);setCanceledOnTouchOutside(false);
|
||||
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);
|
||||
@@ -31,6 +33,15 @@ final class PrivacyConsentDialog extends Dialog {
|
||||
setContentView(sheet);Window window=getWindow();if(window!=null){window.setBackgroundDrawableResource(android.R.color.transparent);window.setDimAmount(.22f);}
|
||||
}
|
||||
@Override public void show(){
|
||||
super.show();Window window=getWindow();if(window!=null){window.setLayout(-1,Math.round(getContext().getResources().getDisplayMetrics().heightPixels*.9f));window.setGravity(Gravity.BOTTOM);}
|
||||
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,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,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,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();
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,7 @@ final class RemoteVersionCheck {
|
||||
request = null;
|
||||
}
|
||||
|
||||
private static final class ReleaseRequest implements Cancellation, Runnable {
|
||||
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;
|
||||
|
||||
@@ -23,16 +23,33 @@ final class RemoteVideoView extends FrameLayout implements SurfaceHolder.Callbac
|
||||
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;
|
||||
void setRelative(boolean value) { relative=value; }
|
||||
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));
|
||||
@@ -42,20 +59,23 @@ final class RemoteVideoView extends FrameLayout implements SurfaceHolder.Callbac
|
||||
gestures = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
|
||||
@Override public boolean onDown(MotionEvent e) { return point(e); }
|
||||
@Override public boolean onSingleTapUp(MotionEvent e) {
|
||||
if (!twoFinger && point(e)) cursor.performClick(); return true;
|
||||
if (!twoFinger && !suppressPointerGesture() && point(e)) cursor.performClick(); return true;
|
||||
}
|
||||
@Override public void onLongPress(MotionEvent e) { if (!twoFinger && !dragging && point(e)) click(3, 4); }
|
||||
@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) {
|
||||
if (!relative && !dragging && !suppressPointerGesture()) {
|
||||
if (!point(first)) return true;
|
||||
session.pointer(x, y, 1, 0); dragging = 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;
|
||||
@@ -87,7 +107,7 @@ final class RemoteVideoView extends FrameLayout implements SurfaceHolder.Callbac
|
||||
if (width <= 0 || height <= 0) return;
|
||||
frameWidth = width; frameHeight = height; fit();
|
||||
}
|
||||
void resetViewport() { viewport.reset(); applyViewport(); }
|
||||
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);
|
||||
@@ -106,14 +126,22 @@ final class RemoteVideoView extends FrameLayout implements SurfaceHolder.Callbac
|
||||
}
|
||||
private void fit() {
|
||||
if (getWidth() == 0 || getHeight() == 0) return;
|
||||
viewport.fit(getWidth(), getHeight(), frameWidth, frameHeight);
|
||||
video.setLayoutParams(new LayoutParams(viewport.baseWidth(),viewport.baseHeight(),android.view.Gravity.CENTER));
|
||||
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.
|
||||
video.setScaleX(viewport.scale()); video.setScaleY(viewport.scale());
|
||||
video.setTranslationX(viewport.offsetX()); video.setTranslationY(viewport.offsetY());
|
||||
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); }
|
||||
@@ -131,17 +159,19 @@ final class RemoteVideoView extends FrameLayout implements SurfaceHolder.Callbac
|
||||
y=viewport.normalizedY(py);
|
||||
}
|
||||
lastX=px;lastY=py;
|
||||
session.pointer(x,y,0,0); cursor.invalidate();
|
||||
mouseInput.move(x,y); cursor.invalidate();
|
||||
return true;
|
||||
}
|
||||
private void click(int down, int up) { session.pointer(x,y,down,0); session.pointer(x,y,up,0); }
|
||||
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) { session.pointer(x,y,2,0); dragging = false; }
|
||||
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);
|
||||
@@ -150,6 +180,7 @@ final class RemoteVideoView extends FrameLayout implements SurfaceHolder.Callbac
|
||||
}
|
||||
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;
|
||||
@@ -177,7 +208,7 @@ final class RemoteVideoView extends FrameLayout implements SurfaceHolder.Callbac
|
||||
twoFingerY = scrollY = focus(e,false,e.getActionIndex());
|
||||
}
|
||||
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
|
||||
if (dragging) session.pointer(x,y,2,0);
|
||||
if (dragging) mouseInput.gestureLeft(false);
|
||||
dragging = false;
|
||||
viewport.finishGesture(); applyViewport();
|
||||
viewportPanActive = false;
|
||||
@@ -195,7 +226,8 @@ final class RemoteVideoView extends FrameLayout implements SurfaceHolder.Callbac
|
||||
@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) { session.surface(null); }
|
||||
@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();
|
||||
|
||||
@@ -6,13 +6,14 @@ import android.view.*;
|
||||
import android.widget.*;
|
||||
import static cn.crossdesk.mobile.MobileUi.*;
|
||||
|
||||
/** Safe-area overlay: a draggable 54 dp orb, a three-column menu and a floating keyboard. */
|
||||
/** 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;
|
||||
@@ -20,7 +21,17 @@ final class SessionControls extends FrameLayout {
|
||||
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);
|
||||
@@ -43,13 +54,52 @@ final class SessionControls extends FrameLayout {
|
||||
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);}
|
||||
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();}
|
||||
private void closeMenu(){if(menu!=null){removeView(menu);menu=null;}if(shield!=null){removeView(shield);shield=null;}networkLabel=videoFeedback=null;trafficCells=null;trafficRows=null;networkDetails=null;encryptionLock=encryptionOpen=null;settingRows.clear();orb.setContentDescription("展开远程控制菜单");}
|
||||
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();
|
||||
@@ -57,19 +107,21 @@ final class SessionControls extends FrameLayout {
|
||||
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());menu.addView(scroll,new LinearLayout.LayoutParams(-1,0,1));LinearLayout body=ui.column();scroll.addView(body);
|
||||
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={"键盘","显示器","画面设置",muted?"静音":"声音",relative?"相对鼠标":"绝对鼠标","发送文件","网络状态","Ctrl+Alt+Del","剪贴板"};
|
||||
String[] icons={"keyboard","display","sliders","audio","mouse","folder","chart","lock","clipboard"};
|
||||
Runnable[] clicks={()->{closeMenu();toggleKeyboard();},actions::display,()->openMenu("video"),actions::mute,actions::mouse,()->{},()->openMenu("network"),()->{},actions::clipboard};
|
||||
for(int row=0;row<3;row++){LinearLayout line=ui.row();for(int col=0;col<3;col++){int index=row*3+col;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());
|
||||
if(index==5||index==7){control.setEnabled(false);control.setAlpha(.38f);control.setContentDescription(labels[index]+",暂不支持");}
|
||||
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<2)ui.gap(body,7);}
|
||||
}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{
|
||||
@@ -79,6 +131,7 @@ final class SessionControls extends FrameLayout {
|
||||
}
|
||||
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;
|
||||
@@ -133,17 +186,36 @@ final class SessionControls extends FrameLayout {
|
||||
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 panelWidth(int width){return Math.max(1,Math.min(width-ui.dp(16),Math.max(ui.dp(280),Math.min(ui.dp(340),width-ui.dp(160)))));}
|
||||
private int panelHeight(int height){return Math.min(ui.dp(310),Math.max(1,height-ui.dp(16)));}
|
||||
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 void closeKeyboard(){if(keyboard!=null){removeView(keyboard);keyboard=null;}}
|
||||
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();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));
|
||||
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);}keyboard.addView(line);ui.gap(keyboard,3);}
|
||||
int width=Math.min(ui.dp(computerKeyboard?520:440),Math.max(1,getWidth()-ui.dp(16)));addView(keyboard,new LayoutParams(width,-2));keyboard.post(()->{if(keyboard!=null){keyboard.setX(oldX<0?(getWidth()-keyboard.getWidth())/2f:oldX);keyboard.setY(oldY<0?getHeight()-keyboard.getHeight()-ui.dp(20):oldY);constrainPanels();}});
|
||||
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){
|
||||
@@ -166,8 +238,8 @@ final class SessionControls extends FrameLayout {
|
||||
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: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)));}return true;
|
||||
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;
|
||||
@@ -176,17 +248,28 @@ final class SessionControls extends FrameLayout {
|
||||
});
|
||||
}
|
||||
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)requestLayout();
|
||||
if(keyboard!=null){ViewGroup.LayoutParams p=keyboard.getLayoutParams();p.width=Math.min(ui.dp(computerKeyboard?520:440),Math.max(1,getWidth()-ui.dp(16)));keyboard.setLayoutParams(p);keyboard.setX(bound(keyboard.getX(),ui.dp(8),getWidth()-p.width-ui.dp(8)));keyboard.setY(bound(keyboard.getY(),ui.dp(8),getHeight()-keyboard.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());
|
||||
if(p.width!=width||p.height!=height){p.width=width;p.height=height;super.onMeasure(widthSpec,heightSpec);}
|
||||
// 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);
|
||||
@@ -194,7 +277,10 @@ final class SessionControls extends FrameLayout {
|
||||
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(); }
|
||||
}
|
||||
@@ -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>
|
||||
@@ -1,2 +1,4 @@
|
||||
org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8
|
||||
android.useAndroidX=true
|
||||
crossdeskVersionName=1.6.1
|
||||
crossdeskVersionCode=3
|
||||
|
||||
@@ -12,6 +12,12 @@
|
||||
#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{};
|
||||
@@ -32,4 +38,4 @@ inline nlohmann::json NetworkReport(const MiniRtcNetTrafficStats& stats, Travers
|
||||
}
|
||||
} // namespace crossdesk::android_controller
|
||||
|
||||
#endif
|
||||
#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
|
||||
@@ -18,6 +18,7 @@
|
||||
#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"
|
||||
@@ -76,6 +77,14 @@ struct Session {
|
||||
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;
|
||||
@@ -89,7 +98,7 @@ struct Session {
|
||||
if (scope.env->ExceptionCheck()) scope.env->ExceptionClear();
|
||||
}
|
||||
void Event(int type, const json& value) {
|
||||
const std::string data = value.dump(); Event(type, data.data(), data.size());
|
||||
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())
|
||||
@@ -136,6 +145,14 @@ struct Session {
|
||||
|
||||
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();
|
||||
@@ -172,6 +189,8 @@ void Data(const char* data, size_t size, const char*, size_t,
|
||||
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))) {
|
||||
@@ -290,6 +309,18 @@ extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nHasAppUpdate)(
|
||||
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) {
|
||||
@@ -332,15 +363,13 @@ extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nConnect)(
|
||||
AddAudioStream(s->controller, kAudioStream);
|
||||
AddDataStream(s->controller, kDataStream, false);
|
||||
for (const char* name : {kMouseStream, kKeyboardStream, kControlStream,
|
||||
kClipboardStream}) AddDataStream(s->controller, name, true);
|
||||
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;
|
||||
const std::string info = R"({"type":"client_info","version":"android-native","platform":"android"})";
|
||||
SendSignalMessage(s->controller, info.data(), info.size());
|
||||
auto action = MakeHostInformation("CrossDesk Android", {}, false, "1.6.0", HostPlatform::Android);
|
||||
s->Send(kControlStream, action.to_json()); FreeRemoteAction(action);
|
||||
}
|
||||
@@ -383,6 +412,30 @@ extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nVideoSettings)(
|
||||
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);
|
||||
@@ -424,6 +477,10 @@ extern "C" JNIEXPORT void JNICALL JNI_METHOD(nClipboard)(
|
||||
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 (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); }
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
set_project("crossdesk_android")
|
||||
set_xmakever("3.1.1")
|
||||
set_languages("c++17")
|
||||
add_rules("mode.release", "mode.debug")
|
||||
set_policy("package.precompiled", false)
|
||||
@@ -9,7 +10,7 @@ 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")
|
||||
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")
|
||||
|
||||
@@ -12,6 +12,19 @@ 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():
|
||||
@@ -20,13 +33,7 @@ def main():
|
||||
ndk = sdk / 'ndk/28.2.13676358'
|
||||
if not ndk.is_dir():
|
||||
raise SystemExit('Install Android NDK 28.2.13676358 using SDK Manager.')
|
||||
bundled = Path.home() / '.cache/crossdesk/toolchains/xmake-3.1.1/xmake'
|
||||
xmake = os.environ.get('XMAKE_BIN') or (str(bundled) if bundled.is_file() else shutil.which('xmake'))
|
||||
if not xmake:
|
||||
raise SystemExit('xmake is required; install it or set XMAKE_BIN.')
|
||||
version = subprocess.check_output([xmake, '--version'], text=True)
|
||||
if not re.search(r'xmake v3\.1\.1(?:\+|[,\s])', version):
|
||||
raise SystemExit('Use Xmake 3.1.1 (set XMAKE_BIN to its executable).')
|
||||
xmake = find_xmake()
|
||||
if not (SOURCE / 'xmake.lua').is_file():
|
||||
raise SystemExit('Initialize the MiniRTC submodule before building.')
|
||||
env = os.environ.copy()
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Resolve Android package and artifact versions before building the APKs."""
|
||||
|
||||
import datetime
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
|
||||
def resolve_version(version_name, version_code, tag="", patch="0", today=None):
|
||||
build_date = today or datetime.datetime.now(ZoneInfo("Asia/Shanghai")).strftime("%Y%m%d")
|
||||
patch = patch if re.fullmatch(r"[0-9]+", patch) else "0"
|
||||
if tag:
|
||||
independent = tag.startswith("android-v")
|
||||
source_version = tag.removeprefix("android-")
|
||||
base = r"(?P<base>[0-9]+\.[0-9]+\.[0-9]+)"
|
||||
for pattern in (
|
||||
rf"v{base}-(?P<patch>[0-9]+)-(?P<date>[0-9]{{8}})",
|
||||
rf"v{base}-(?P<date>[0-9]{{8}})(?:-(?P<patch>[0-9]+))?",
|
||||
rf"v{base}(?:-(?P<patch>[0-9]+))?",
|
||||
):
|
||||
match = re.fullmatch(pattern, source_version)
|
||||
if match:
|
||||
fields = match.groupdict()
|
||||
if independent and fields["base"] != version_name:
|
||||
raise ValueError(f"Android source tag does not match the app version: {tag} vs {version_name}")
|
||||
version_name = fields["base"]
|
||||
build_date = fields.get("date") or build_date
|
||||
patch = fields.get("patch") or patch
|
||||
break
|
||||
else:
|
||||
raise ValueError(f"Invalid Android release tag: {tag!r}")
|
||||
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version_name):
|
||||
raise ValueError(f"Invalid Android versionName: {version_name!r}")
|
||||
if not re.fullmatch(r"[0-9]+", version_code) or not 0 < int(version_code) <= 2100000000:
|
||||
raise ValueError(f"Invalid Android versionCode: {version_code!r}")
|
||||
datetime.datetime.strptime(build_date, "%Y%m%d")
|
||||
suffix = f"-{patch}" if patch != "0" else ""
|
||||
artifact_version = f"v{version_name}{suffix}-{build_date}"
|
||||
if tag.startswith("android-v") and tag.removeprefix("android-") != artifact_version:
|
||||
raise ValueError(f"Android source tag does not match the artifact version: {tag} vs {artifact_version}")
|
||||
return {"ANDROID_VERSION_NAME": version_name, "ANDROID_VERSION_CODE": str(int(version_code)),
|
||||
"ANDROID_ARTIFACT_VERSION": artifact_version}
|
||||
|
||||
|
||||
def main():
|
||||
properties = dict(line.split("=", 1) for line in
|
||||
(Path(__file__).resolve().parents[1] / "gradle.properties").read_text().splitlines()
|
||||
if "=" in line and not line.lstrip().startswith("#"))
|
||||
tag = os.environ.get("CROSSDESK_SOURCE_TAG", "")
|
||||
if not tag and os.environ.get("GITHUB_REF_TYPE") == "tag":
|
||||
ref_name = os.environ["GITHUB_REF_NAME"]
|
||||
# Moving aliases such as "latest" are builds, not versioned releases.
|
||||
if ref_name.startswith(("v", "android-v")):
|
||||
tag = ref_name
|
||||
values = resolve_version(properties["crossdeskVersionName"], properties["crossdeskVersionCode"],
|
||||
tag, os.environ.get("PATCH_NUMBER", "0"))
|
||||
text = "".join(f"{key}={value}\n" for key, value in values.items())
|
||||
if os.environ.get("GITHUB_ENV"):
|
||||
with open(os.environ["GITHUB_ENV"], "a") as stream:
|
||||
stream.write(text)
|
||||
print(text, end="")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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,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()
|
||||
@@ -1,13 +1,24 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check the shipped native ABI, ELF load alignment and APK zip alignment."""
|
||||
from pathlib import Path
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
import subprocess
|
||||
import zipfile
|
||||
|
||||
|
||||
def verify_package_version(badging, version_name, version_code):
|
||||
package = next((line for line in badging.splitlines() if line.startswith('package: ')), '')
|
||||
attributes = dict(re.findall(r"(\w+)='([^']*)'", package))
|
||||
expected = {'name': 'cn.crossdesk.mobile', 'versionName': version_name, 'versionCode': str(version_code)}
|
||||
for key, value in expected.items():
|
||||
if attributes.get(key) != value:
|
||||
raise ValueError(f'Unexpected APK {key}: expected {value!r}, got {attributes.get(key)!r}')
|
||||
|
||||
|
||||
def verify(path):
|
||||
with zipfile.ZipFile(path) as archive, open(path, 'rb') as raw:
|
||||
libraries = [i for i in archive.infolist() if i.filename.endswith('.so')]
|
||||
@@ -59,4 +70,16 @@ def verify(path):
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
verify(sys.argv[1])
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('apk', type=Path)
|
||||
parser.add_argument('--aapt2', type=Path)
|
||||
parser.add_argument('--version-name')
|
||||
parser.add_argument('--version-code', type=int)
|
||||
args = parser.parse_args()
|
||||
if any(value is not None for value in (args.aapt2, args.version_name, args.version_code)):
|
||||
if any(value is None for value in (args.aapt2, args.version_name, args.version_code)):
|
||||
parser.error('--aapt2, --version-name and --version-code must be supplied together')
|
||||
badging = subprocess.check_output([str(args.aapt2), 'dump', 'badging', str(args.apk)], text=True)
|
||||
verify_package_version(badging, args.version_name, args.version_code)
|
||||
print(f'PASS: {args.apk.name}: versionName={args.version_name}, versionCode={args.version_code}')
|
||||
verify(args.apk)
|
||||
|
||||
@@ -15,14 +15,15 @@ INPUT_VERSION="$3"
|
||||
EXTRA_RECOMMENDATION="${4:-}"
|
||||
|
||||
PKG_NAME="crossdesk"
|
||||
VIRTUAL_PACKAGE_NAME="crossdesk-virtual-desktop-xfce"
|
||||
APP_NAME="CrossDesk"
|
||||
MAINTAINER="Junkun Di <junkun.di@hotmail.com>"
|
||||
DESCRIPTION="A simple cross-platform remote desktop client."
|
||||
ALSA_RUNTIME_DEP="libasound2 | libasound2t64"
|
||||
PORTAL_RUNTIME_RECOMMENDS="xdg-desktop-portal, xdg-desktop-portal-gtk | xdg-desktop-portal-kde | xdg-desktop-portal-wlr"
|
||||
TRAY_RUNTIME_RECOMMENDS="libayatana-appindicator3-1 | libappindicator3-1"
|
||||
# Every published package includes the prerequisites for all Linux headless
|
||||
# paths, including a complete independent desktop. Older Ubuntu releases ship
|
||||
# Only the virtual desktop package installs a desktop environment. Both packages
|
||||
# contain the same application, including headless support. Older Ubuntu releases ship
|
||||
# dbus-run-session in dbus; newer releases split it into dbus-daemon.
|
||||
HEADLESS_RUNTIME_DEPS="xvfb, xfce4, dbus-daemon | dbus"
|
||||
|
||||
@@ -107,7 +108,6 @@ BIN_DIR="$DEB_DIR/usr/bin"
|
||||
PRIVATE_DIR="$DEB_DIR/usr/lib/$PKG_NAME"
|
||||
ICON_BASE_DIR="$DEB_DIR/usr/share/icons/hicolor"
|
||||
DESKTOP_DIR="$DEB_DIR/usr/share/applications"
|
||||
OUTPUT_FILE="$PROJECT_ROOT/${PKG_NAME}-linux-${DEBIAN_ARCH}-${APP_VERSION}.deb"
|
||||
|
||||
install -d "$DEBIAN_DIR" "$BIN_DIR" "$PRIVATE_DIR" "$DESKTOP_DIR"
|
||||
install -m 0755 "$BUILD_BINARY" "$PRIVATE_DIR/crossdesk-bin"
|
||||
@@ -161,23 +161,6 @@ if [[ -n "$EXTRA_RECOMMENDATION" ]]; then
|
||||
RECOMMENDS="$RECOMMENDS, $EXTRA_RECOMMENDATION"
|
||||
fi
|
||||
|
||||
cat > "$DEBIAN_DIR/control" <<EOF
|
||||
Package: $PKG_NAME
|
||||
Version: $DEB_VERSION
|
||||
Architecture: $DEBIAN_ARCH
|
||||
Maintainer: $MAINTAINER
|
||||
Description: $DESCRIPTION
|
||||
Depends: libc6 (>= 2.31), libstdc++6 (>= 10), libx11-6, libxext6,
|
||||
libxrender1, libxft2, libxrandr2, libxfixes3, libxcursor1, libxi6, libxcb1, libxcb-randr0,
|
||||
libxcb-xtest0, libxcb-xinerama0, libxcb-shape0, libxcb-xkb1,
|
||||
libxcb-xfixes0, libxv1, libxtst6, $ALSA_RUNTIME_DEP, libsndio7.0,
|
||||
libxcb-shm0, libpulse0, libdrm2, libdbus-1-3, libgl1,
|
||||
$HEADLESS_RUNTIME_DEPS
|
||||
Recommends: $RECOMMENDS
|
||||
Priority: optional
|
||||
Section: utils
|
||||
EOF
|
||||
|
||||
cat > "$DESKTOP_DIR/$PKG_NAME.desktop" <<EOF
|
||||
[Desktop Entry]
|
||||
Version=1.0
|
||||
@@ -191,15 +174,51 @@ Type=Application
|
||||
Categories=Utility;
|
||||
EOF
|
||||
|
||||
rm -f "$OUTPUT_FILE"
|
||||
dpkg-deb --root-owner-group --build "$DEB_DIR" "$OUTPUT_FILE"
|
||||
dpkg-deb --info "$OUTPUT_FILE" >/dev/null
|
||||
dpkg-deb --contents "$OUTPUT_FILE" > "$WORK_DIR/package-contents.txt"
|
||||
# Stage and strip the application once, then package it with two dependency sets.
|
||||
# Keep the executable, launcher and configuration paths identical when switching.
|
||||
for package_name in "$PKG_NAME" "$VIRTUAL_PACKAGE_NAME"; do
|
||||
extra_depends=""
|
||||
description="$DESCRIPTION"
|
||||
other_package="$VIRTUAL_PACKAGE_NAME"
|
||||
if [[ "$package_name" == "$VIRTUAL_PACKAGE_NAME" ]]; then
|
||||
extra_depends=", $HEADLESS_RUNTIME_DEPS"
|
||||
description="CrossDesk with Xfce and Xvfb for independent virtual desktops."
|
||||
other_package="$PKG_NAME"
|
||||
fi
|
||||
cat > "$DEBIAN_DIR/control" <<EOF
|
||||
Package: $package_name
|
||||
Version: $DEB_VERSION
|
||||
Architecture: $DEBIAN_ARCH
|
||||
Maintainer: $MAINTAINER
|
||||
Description: $description
|
||||
Depends: libc6 (>= 2.31), libstdc++6 (>= 10), libx11-6, libxext6,
|
||||
libxrender1, libxft2, libxrandr2, libxfixes3, libxcursor1, libxi6, libxcb1, libxcb-randr0,
|
||||
libxcb-xtest0, libxcb-xinerama0, libxcb-shape0, libxcb-xkb1,
|
||||
libxcb-xfixes0, libxv1, libxtst6, $ALSA_RUNTIME_DEP, libsndio7.0,
|
||||
libxcb-shm0, libpulse0, libdrm2, libdbus-1-3, libgl1$extra_depends
|
||||
Recommends: $RECOMMENDS
|
||||
Conflicts: $other_package
|
||||
Replaces: $other_package
|
||||
Priority: optional
|
||||
Section: utils
|
||||
EOF
|
||||
if [[ "$package_name" == "$VIRTUAL_PACKAGE_NAME" ]]; then
|
||||
echo "Provides: $PKG_NAME (= $DEB_VERSION)" >> "$DEBIAN_DIR/control"
|
||||
fi
|
||||
# Read beside the executable by the updater; never store this in user config.
|
||||
echo "$package_name" > "$PRIVATE_DIR/package-name"
|
||||
chmod 0644 "$PRIVATE_DIR/package-name"
|
||||
OUTPUT_FILE="$PROJECT_ROOT/${package_name}-linux-${DEBIAN_ARCH}-${APP_VERSION}.deb"
|
||||
rm -f "$OUTPUT_FILE"
|
||||
dpkg-deb --root-owner-group --build "$DEB_DIR" "$OUTPUT_FILE"
|
||||
dpkg-deb --info "$OUTPUT_FILE" >/dev/null
|
||||
dpkg-deb --contents "$OUTPUT_FILE" > "$WORK_DIR/package-contents.txt"
|
||||
|
||||
if [[ -n "$SLINT_NEEDED" ]] && \
|
||||
! grep -q "usr/lib/$PKG_NAME/$SLINT_NEEDED" "$WORK_DIR/package-contents.txt"; then
|
||||
echo "Packaged artifact is missing $SLINT_NEEDED" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ -n "$SLINT_NEEDED" ]] && \
|
||||
! grep -q "usr/lib/$PKG_NAME/$SLINT_NEEDED" "$WORK_DIR/package-contents.txt"; then
|
||||
echo "Packaged artifact is missing $SLINT_NEEDED" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Deb package created: $OUTPUT_FILE"
|
||||
echo "Deb package created: $OUTPUT_FILE"
|
||||
done
|
||||
|
||||
@@ -101,6 +101,15 @@ installApp:
|
||||
|
||||
Call RegisterInstalledService
|
||||
|
||||
; Replace an existing per-user Run entry only after the new binary is in
|
||||
; place. A fresh installation must not opt the user into auto-start.
|
||||
ClearErrors
|
||||
ExecWait '"$INSTDIR\CrossDesk.exe" --autostart-migrate' $0
|
||||
${If} ${Errors}
|
||||
${OrIf} $0 != 0
|
||||
MessageBox MB_ICONEXCLAMATION|MB_OK "Could not migrate CrossDesk auto-start. Open CrossDesk and enable Auto Start again."
|
||||
${EndIf}
|
||||
|
||||
; Write uninstall information
|
||||
WriteUninstaller "$INSTDIR\uninstall.exe"
|
||||
|
||||
@@ -147,6 +156,12 @@ cancelUninstall:
|
||||
Abort
|
||||
|
||||
uninstallApp:
|
||||
ClearErrors
|
||||
ExecWait '"$INSTDIR\CrossDesk.exe" --autostart-uninstall' $0
|
||||
${If} ${Errors}
|
||||
${OrIf} $0 != 0
|
||||
MessageBox MB_ICONEXCLAMATION|MB_OK "Could not remove CrossDesk auto-start. Remove any remaining CrossDesk Autostart tasks in Task Scheduler."
|
||||
${EndIf}
|
||||
Call un.UnregisterInstalledService
|
||||
Call un.RemoveUsbmmiddDriver
|
||||
|
||||
@@ -218,7 +233,18 @@ Function RegisterInstalledService
|
||||
Abort
|
||||
${EndIf}
|
||||
|
||||
DetailPrint "CrossDesk service registered for on-demand start"
|
||||
; Preserve an existing unattended opt-in and resume it after upgrades.
|
||||
; A fresh install still registers the ordinary on-demand lock-screen service.
|
||||
SetRegView 64
|
||||
ReadRegDWORD $1 HKLM "Software\CrossDesk\Unattended" "Enabled"
|
||||
SetRegView 32
|
||||
${If} $1 = 1
|
||||
ExecWait '"$INSTDIR\CrossDesk.exe" --service-start' $0
|
||||
${If} $0 != 0
|
||||
MessageBox MB_ICONEXCLAMATION|MB_OK "Could not restart the unattended host. Run CrossDesk.exe --service-start from an administrator terminal."
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
DetailPrint "CrossDesk service registered"
|
||||
|
||||
Return
|
||||
|
||||
@@ -228,6 +254,10 @@ missing_service_binary:
|
||||
FunctionEnd
|
||||
|
||||
Function un.UnregisterInstalledService
|
||||
; Also disarm unattended startup when removal must fall back to sc.exe.
|
||||
SetRegView 64
|
||||
DeleteRegKey HKLM "Software\CrossDesk\Unattended"
|
||||
SetRegView 32
|
||||
IfFileExists "$INSTDIR\CrossDesk.exe" 0 unregister_with_sc
|
||||
|
||||
DetailPrint "Stopping CrossDesk service"
|
||||
|
||||
@@ -16,8 +16,11 @@
|
||||
#ifdef _WIN32
|
||||
#include <cstdio>
|
||||
|
||||
#include "platform/windows/autostart_task.h"
|
||||
#include "platform/windows/gui/slint_backend.h"
|
||||
#include "service_host.h"
|
||||
#include "service_lifetime.h"
|
||||
#include "unattended_config.h"
|
||||
#endif
|
||||
|
||||
#include "config_center.h"
|
||||
@@ -70,6 +73,12 @@ void PrintServiceCliUsage() {
|
||||
<< " --service-ping Ping the service over named pipe IPC\n"
|
||||
<< " --service-status Query service runtime status\n"
|
||||
<< " --service-help Show this help\n";
|
||||
std::cout
|
||||
<< " --unattended-enable Enable a separate machine host before login\n"
|
||||
<< " --unattended-disable Stop the machine host and disable boot "
|
||||
"startup\n"
|
||||
<< " --unattended-status Show machine host status and connection "
|
||||
"credentials\n";
|
||||
}
|
||||
|
||||
std::wstring GetCurrentExecutablePathW() {
|
||||
@@ -97,6 +106,9 @@ bool IsServiceCliCommand(const char* arg) {
|
||||
}
|
||||
|
||||
return std::strcmp(arg, "--service-install") == 0 ||
|
||||
std::strcmp(arg, "--unattended-enable") == 0 ||
|
||||
std::strcmp(arg, "--unattended-disable") == 0 ||
|
||||
std::strcmp(arg, "--unattended-status") == 0 ||
|
||||
std::strcmp(arg, "--service-uninstall") == 0 ||
|
||||
std::strcmp(arg, "--service-start") == 0 ||
|
||||
std::strcmp(arg, "--service-stop") == 0 ||
|
||||
@@ -127,6 +139,97 @@ int HandleServiceCliCommand(const std::string& command) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (command.rfind("--unattended-", 0) == 0) {
|
||||
if (!crossdesk::IsAdministratorProcess()) {
|
||||
std::cerr << "Run this command from an administrator terminal.\n";
|
||||
return 1;
|
||||
}
|
||||
if (command == "--unattended-status") {
|
||||
std::cout << crossdesk::ReadUnattendedStatus() << '\n';
|
||||
return 0;
|
||||
}
|
||||
const auto service = GetSiblingServiceExecutablePath();
|
||||
if (service.empty() || !std::filesystem::exists(service)) {
|
||||
std::cerr << "Install CrossDesk with its Windows service first.\n";
|
||||
return 1;
|
||||
}
|
||||
if (command == "--unattended-disable") {
|
||||
// Disarm boot startup even if stopping the current process fails.
|
||||
const bool saved = crossdesk::SetUnattendedEnabled(false);
|
||||
const bool configured =
|
||||
saved && crossdesk::InstallCrossDeskService(service.wstring());
|
||||
const bool stopped = crossdesk::StopCrossDeskService(20000);
|
||||
std::cout << (configured && stopped
|
||||
? "Unattended host disabled.\n"
|
||||
: "Failed to disable unattended host.\n");
|
||||
return configured && stopped ? 0 : 1;
|
||||
}
|
||||
#if defined(CROSSDESK_DEBUG) || CROSSDESK_PORTABLE
|
||||
std::cerr << "Unattended mode requires the installed release build.\n";
|
||||
return 1;
|
||||
#else
|
||||
const bool was_enabled = crossdesk::IsUnattendedEnabled();
|
||||
if (!crossdesk::PrepareUnattendedDirectory(true)) {
|
||||
std::cerr
|
||||
<< "Cannot create a private machine profile. Existing permissive "
|
||||
"directories and links are rejected.\n";
|
||||
return 1;
|
||||
}
|
||||
if (crossdesk::IsCrossDeskServiceInstalled() &&
|
||||
!crossdesk::StopCrossDeskService(20000)) {
|
||||
std::cerr << "Could not stop the service to configure unattended mode.\n";
|
||||
return 1;
|
||||
}
|
||||
crossdesk::PathManager paths("CrossDesk");
|
||||
crossdesk::ConfigCenter source(
|
||||
(paths.GetCachePath() / "config.ini").string());
|
||||
const auto machine_config = crossdesk::UnattendedDataPath() / "config.ini";
|
||||
const auto staged_config =
|
||||
crossdesk::UnattendedDataPath() / "config.pending.ini";
|
||||
// Import only server/media preferences. Never share the GUI identity or
|
||||
// consume its file-transfer paths in the SYSTEM process.
|
||||
const auto host = source.IsSelfHosted() ? source.GetSignalServerHost()
|
||||
: source.GetDefaultServerHost();
|
||||
const int port = source.IsSelfHosted()
|
||||
? source.GetSignalServerPort()
|
||||
: source.GetDefaultSignalServerPort();
|
||||
bool configured = std::filesystem::exists(machine_config);
|
||||
if (!configured) {
|
||||
crossdesk::ConfigCenter destination(staged_config.string());
|
||||
configured =
|
||||
destination.SetServerHost(host) == 0 &&
|
||||
destination.SetServerPort(port) == 0 &&
|
||||
destination.SetSelfHosted(source.IsSelfHosted()) == 0 &&
|
||||
destination.SetTurnMode(source.GetTurnMode()) == 0 &&
|
||||
destination.SetVideoEncodeFormat(source.GetVideoEncodeFormat()) ==
|
||||
0 &&
|
||||
destination.SetHardwareVideoCodec(source.IsHardwareVideoCodec()) ==
|
||||
0 &&
|
||||
destination.SetScreenCaptureMethod(
|
||||
crossdesk::ScreenCaptureMethod::Auto) == 0 &&
|
||||
destination.SetPrivacyScreen(false) == 0 &&
|
||||
destination.SetSaveRemotePreviews(false) == 0;
|
||||
}
|
||||
if (configured && !std::filesystem::exists(machine_config)) {
|
||||
configured = MoveFileExW(staged_config.c_str(), machine_config.c_str(),
|
||||
MOVEFILE_WRITE_THROUGH) != FALSE;
|
||||
}
|
||||
if (!configured || !crossdesk::SetUnattendedEnabled(true) ||
|
||||
!crossdesk::InstallCrossDeskService(service.wstring()) ||
|
||||
!crossdesk::StartCrossDeskService()) {
|
||||
crossdesk::SetUnattendedEnabled(was_enabled);
|
||||
crossdesk::InstallCrossDeskService(service.wstring());
|
||||
if (was_enabled) crossdesk::StartCrossDeskService();
|
||||
std::cerr << "Failed to enable unattended host.\n";
|
||||
return 1;
|
||||
}
|
||||
std::cout << "Unattended host enabled for boot startup.\n"
|
||||
"After it connects, use --unattended-status to obtain its "
|
||||
"separate device ID and password.\n";
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
if (command == "--service-install") {
|
||||
std::filesystem::path service_path = GetSiblingServiceExecutablePath();
|
||||
if (service_path.empty()) {
|
||||
@@ -218,6 +321,10 @@ static int RunApplication(
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
if (!crossdesk::platform::MigrateLegacyAutostart("CrossDesk")) {
|
||||
crossdesk::get_logger()->warn(
|
||||
"Could not migrate the legacy Windows autostart entry");
|
||||
}
|
||||
TryStartManagedWindowsService();
|
||||
#endif
|
||||
|
||||
@@ -288,6 +395,41 @@ int main(int argc, char* argv[]) {
|
||||
}
|
||||
#endif
|
||||
#ifdef _WIN32
|
||||
if (argc > 1 && std::strcmp(argv[1], "--unattended-host") == 0) {
|
||||
// Internal service entry point: never elevate an ordinary invocation into
|
||||
// a SYSTEM host, and never open the GUI or the per-user daemon here.
|
||||
if (argc != 4 || !crossdesk::IsLocalSystemProcess() ||
|
||||
!crossdesk::IsUnattendedEnabled())
|
||||
return 1;
|
||||
const std::string name(argv[2]);
|
||||
if (name.rfind("Global\\CrossDeskUnattendedStop-", 0) != 0) return 1;
|
||||
const std::wstring wide_name(name.begin(), name.end());
|
||||
HANDLE stop = OpenEventW(SYNCHRONIZE, FALSE, wide_name.c_str());
|
||||
if (!stop) return 1;
|
||||
const std::string lifetime_name(argv[3]);
|
||||
crossdesk::ServiceLifetimeWatcher lifetime;
|
||||
if (!lifetime.Start(
|
||||
std::wstring(lifetime_name.begin(), lifetime_name.end()))) {
|
||||
CloseHandle(stop);
|
||||
return 1;
|
||||
}
|
||||
crossdesk::Render render;
|
||||
const int result = render.RunUnattended(stop);
|
||||
CloseHandle(stop);
|
||||
return result;
|
||||
}
|
||||
// Installer maintenance must not start the GUI or the process supervisor.
|
||||
if (argc == 2 && (std::strcmp(argv[1], "--autostart-migrate") == 0 ||
|
||||
std::strcmp(argv[1], "--autostart-uninstall") == 0)) {
|
||||
crossdesk::PathManager paths("CrossDesk");
|
||||
crossdesk::InitLogger(paths.GetLogPath().string(),
|
||||
"crossdesk-autostart-cli");
|
||||
const bool success =
|
||||
std::strcmp(argv[1], "--autostart-migrate") == 0
|
||||
? crossdesk::platform::MigrateLegacyAutostart("CrossDesk")
|
||||
: crossdesk::platform::RemoveInstalledAutostart("CrossDesk");
|
||||
return success ? 0 : 1;
|
||||
}
|
||||
if (argc == 2 &&
|
||||
std::strcmp(argv[1], crossdesk::kSlintRendererProbeArgument) == 0) {
|
||||
return crossdesk::RunSlintRendererProbe();
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#include "SimpleIni.h"
|
||||
#include "autostart.h"
|
||||
#include "rd_log.h"
|
||||
#include "signal_server_address.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
@@ -290,10 +291,23 @@ int ConfigCenter::SetTurn(bool enable_turn, bool force_relay) {
|
||||
}
|
||||
|
||||
int ConfigCenter::SetServerHost(const std::string& host) {
|
||||
if (host.empty() || host.size() > 253 || host.find_first_of("/\\@?#") != std::string::npos ||
|
||||
std::any_of(host.begin(), host.end(), [](unsigned char c) { return c <= 32 || c == 127; })) return -1;
|
||||
if (StoreValues({{"signal_server_host", host}}) != 0) return -1;
|
||||
signal_server_host_ = host;
|
||||
const auto address = minirtc::ParseSignalServerAddress(host);
|
||||
if (!address) return -1;
|
||||
if (address->port) return SetServerEndpoint(host, *address->port);
|
||||
if (StoreValues({{"signal_server_host", address->Address()}}) != 0) return -1;
|
||||
signal_server_host_ = address->Address();
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ConfigCenter::SetServerEndpoint(const std::string& host, int port) {
|
||||
const auto address = minirtc::ParseSignalServerAddress(host);
|
||||
if (!address) return -1;
|
||||
port = address->port.value_or(port);
|
||||
if (port < 1 || port > 65535) return -1;
|
||||
if (StoreValues({{"signal_server_host", address->Address()},
|
||||
{"signal_server_port", std::to_string(port)}}) != 0) return -1;
|
||||
signal_server_host_ = address->Address();
|
||||
signal_server_port_ = port;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -312,7 +326,16 @@ int ConfigCenter::SetSelfHosted(bool enabled) {
|
||||
|
||||
int ConfigCenter::SetAutostart(bool enabled) {
|
||||
const bool previous = IsAutostartEnabled("CrossDesk");
|
||||
if (enabled != previous && !(enabled ? EnableAutostart("CrossDesk") : DisableAutostart("CrossDesk"))) {
|
||||
// Refresh the executable path and remove legacy registrations even when the
|
||||
// boolean state is unchanged. In particular, a Run entry no longer counts
|
||||
// as enabled for an elevated Windows build, but still needs deleting.
|
||||
#ifdef _WIN32
|
||||
const bool update_registration = true;
|
||||
#else
|
||||
const bool update_registration = enabled != previous;
|
||||
#endif
|
||||
if (update_registration &&
|
||||
!(enabled ? EnableAutostart("CrossDesk") : DisableAutostart("CrossDesk"))) {
|
||||
LOG_ERROR("SetAutostart failed");
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ class ConfigCenter {
|
||||
int SetTurn(bool enable_turn, bool force_relay);
|
||||
int SetServerHost(const std::string& signal_server_host);
|
||||
int SetServerPort(int signal_server_port);
|
||||
int SetServerEndpoint(const std::string& address, int port);
|
||||
int SetSelfHosted(bool enable_self_hosted);
|
||||
int SetAutostart(bool enable_autostart);
|
||||
int SetDaemon(bool enable_daemon);
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-09
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _SIGNAL_SERVER_SETTINGS_H_
|
||||
#define _SIGNAL_SERVER_SETTINGS_H_
|
||||
|
||||
#include <tuple>
|
||||
|
||||
#include "config_center.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// Include the identity namespace as well as the effective endpoint. Editing
|
||||
// an inactive self-hosted endpoint must not disconnect the public server.
|
||||
inline auto GetSignalServerSettings(const ConfigCenter& config) {
|
||||
const bool self_hosted = config.IsSelfHosted();
|
||||
return std::make_tuple(
|
||||
self_hosted,
|
||||
self_hosted ? config.GetSignalServerHost() : config.GetDefaultServerHost(),
|
||||
self_hosted ? config.GetSignalServerPort()
|
||||
: config.GetDefaultSignalServerPort());
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -72,8 +72,6 @@ struct ServerWindowState {
|
||||
};
|
||||
|
||||
struct UiState {
|
||||
bool password_validating_ = false;
|
||||
uint32_t password_validating_time_ = 0;
|
||||
bool rejoin_ = false;
|
||||
bool show_password_ = true;
|
||||
bool show_connection_status_window_ = false;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -14,6 +14,7 @@
|
||||
|
||||
#include <remote_action.h>
|
||||
|
||||
#include "application/signal_connection_indicator.h"
|
||||
#include "runtime/cursor_state_provider.h"
|
||||
#include "runtime/gui_runtime.h"
|
||||
|
||||
@@ -29,6 +30,9 @@ public:
|
||||
~GuiApplication();
|
||||
|
||||
int Run();
|
||||
#ifdef _WIN32
|
||||
int RunUnattended(void* stop_event);
|
||||
#endif
|
||||
|
||||
private:
|
||||
struct SlintUi;
|
||||
@@ -46,7 +50,7 @@ private:
|
||||
void InitializeUi();
|
||||
void InitializeSystemTray();
|
||||
bool MinimizeMainWindowToTray();
|
||||
void BindMainCallbacks();
|
||||
void BindMainCallbacks(bool gallery_window = false);
|
||||
void BindStreamCallbacks();
|
||||
void BindServerCallbacks();
|
||||
void Tick();
|
||||
@@ -56,6 +60,25 @@ private:
|
||||
void HandlePasswordChangeResult();
|
||||
void HandleCredentialRecovery();
|
||||
void SyncMainWindow();
|
||||
void ShowGalleryWindow();
|
||||
void CloseGalleryWindow();
|
||||
void SyncWindowGeometry(bool gallery_window);
|
||||
void ToggleGalleryFullscreen();
|
||||
void RestoreWindowGeometry(bool before_show = false,
|
||||
bool gallery_window = false);
|
||||
void SyncGallery();
|
||||
void GalleryAction(const std::string& action, const std::string& value,
|
||||
bool gallery_window = true);
|
||||
bool AddGalleryDevice(const std::string& id, const std::string& password,
|
||||
const std::string& group, bool remember_password);
|
||||
bool ImportGalleryRecent(const std::string& group);
|
||||
void DeviceGroupAction(const std::string& action, const std::string& value,
|
||||
bool gallery_window);
|
||||
bool SaveDeviceGroups(const std::string& new_group, bool gallery_window);
|
||||
void ReleasePressedInput();
|
||||
void ReleaseControl();
|
||||
void SyncAudioPlayback();
|
||||
void SaveGalleryWindowState();
|
||||
void SyncAnnouncements();
|
||||
void SyncConnectionDialog();
|
||||
void SyncPlatformDialogs();
|
||||
@@ -66,12 +89,15 @@ private:
|
||||
void SyncStreamKeyboardFocus();
|
||||
void SetStreamKeyboardFocus(bool focused);
|
||||
void SyncServerWindow();
|
||||
void SetServerPanelExpanded(bool expanded);
|
||||
void PositionServerWindows();
|
||||
#if defined(__linux__) && !defined(__APPLE__)
|
||||
void SyncXWaylandWindowActivation();
|
||||
#endif
|
||||
void UpdateLocalization();
|
||||
void ResetSettingsUi();
|
||||
void SaveSettingsFromUi();
|
||||
void ResetSettingsUi(bool gallery_window = false);
|
||||
bool ValidateSelfHostedSettingsFromUi(bool gallery_window = false);
|
||||
bool SaveSettingsFromUi(bool gallery_window = false);
|
||||
void ApplySettingsFromConfig(bool reconnect);
|
||||
#if _WIN32 && CROSSDESK_PORTABLE
|
||||
void CheckPortableWindowsService();
|
||||
@@ -82,6 +108,7 @@ private:
|
||||
void SelectStreamTab(int index);
|
||||
void ReorderStreamTab(int from, float drop_x, float tab_width);
|
||||
void CloseStreamTab(const std::string &remote_id);
|
||||
void CloseRemoteClosedTabs();
|
||||
void SendPointerInput(int button, int kind, float x, float y);
|
||||
void SendScrollInput(float delta_x, float delta_y, float x, float y);
|
||||
void SendKeyInput(const std::string &text, bool pressed, bool control,
|
||||
@@ -99,6 +126,7 @@ private:
|
||||
cursor_delivery_states_;
|
||||
uint32_t cursor_state_sequence_ = 0;
|
||||
std::chrono::steady_clock::time_point next_video_frame_time_{};
|
||||
SignalConnectionIndicator signal_connection_indicator_;
|
||||
#if defined(__linux__) && !defined(__APPLE__)
|
||||
bool use_xwayland_gui_ = false;
|
||||
bool use_x11_custom_titlebar_ = false;
|
||||
|
||||
@@ -14,8 +14,47 @@
|
||||
|
||||
namespace crossdesk::server_window_state {
|
||||
|
||||
inline int ReconcileSelectedController(const std::vector<std::string>& ids,
|
||||
std::string* selected_id) {
|
||||
// All values use logical desktop coordinates (including negative monitor
|
||||
// origins). The bar's anchor is independent of the panel's changing height.
|
||||
struct Rect {
|
||||
float x, y, width, height;
|
||||
};
|
||||
|
||||
struct EdgeLayout {
|
||||
Rect bar;
|
||||
Rect panel;
|
||||
bool above;
|
||||
};
|
||||
|
||||
inline EdgeLayout PlacePanel(const Rect &screen, float position,
|
||||
float bar_width, float panel_height) {
|
||||
constexpr float bar_height = 36;
|
||||
constexpr float gap = 6;
|
||||
constexpr float margin = 8;
|
||||
const float travel = std::max(0.0f, screen.height - bar_height - 2 * margin);
|
||||
const float top =
|
||||
screen.y + margin + travel * std::clamp(position, 0.0f, 1.0f);
|
||||
const float above = std::max(0.0f, top - screen.y - margin - gap);
|
||||
const float below = std::max(0.0f, screen.y + screen.height - margin - top -
|
||||
bar_height - gap);
|
||||
const bool opens_above =
|
||||
below < panel_height && (above >= panel_height || above > below);
|
||||
const float height = std::min(panel_height, opens_above ? above : below);
|
||||
const float width = std::min(225.0f, screen.width);
|
||||
return {{screen.x + screen.width - bar_width, top, bar_width, bar_height},
|
||||
{screen.x + screen.width - width,
|
||||
opens_above ? top - gap - height : top + bar_height + gap, width,
|
||||
height},
|
||||
opens_above};
|
||||
}
|
||||
|
||||
inline bool Contains(const Rect &rect, float x, float y) {
|
||||
return x >= rect.x && y >= rect.y && x < rect.x + rect.width &&
|
||||
y < rect.y + rect.height;
|
||||
}
|
||||
|
||||
inline int ReconcileSelectedController(const std::vector<std::string> &ids,
|
||||
std::string *selected_id) {
|
||||
if (!selected_id) {
|
||||
return 0;
|
||||
}
|
||||
@@ -33,4 +72,4 @@ inline int ReconcileSelectedController(const std::vector<std::string>& ids,
|
||||
}
|
||||
} // namespace crossdesk::server_window_state
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
#ifndef CROSSDESK_SIGNAL_CONNECTION_INDICATOR_H_
|
||||
#define CROSSDESK_SIGNAL_CONNECTION_INDICATOR_H_
|
||||
|
||||
#include <chrono>
|
||||
#include <optional>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// Presentation state only. The actual connected flag remains authoritative
|
||||
// for actions and other UI consumers, including the announcement inbox.
|
||||
class SignalConnectionIndicator {
|
||||
public:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
bool Update(bool connected, Clock::time_point now = Clock::now()) {
|
||||
if (connected) {
|
||||
disconnected_at_.reset();
|
||||
} else if (was_connected_) {
|
||||
disconnected_at_ = now;
|
||||
}
|
||||
was_connected_ = connected;
|
||||
return disconnected_at_ &&
|
||||
now - *disconnected_at_ < std::chrono::seconds(10);
|
||||
}
|
||||
|
||||
void Reset() {
|
||||
was_connected_ = false;
|
||||
disconnected_at_.reset();
|
||||
}
|
||||
|
||||
private:
|
||||
bool was_connected_ = false;
|
||||
std::optional<Clock::time_point> disconnected_at_;
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate message_spacing.ttf with fontTools (only needed for regeneration).
|
||||
|
||||
Slint 1.17 pins line height to the requested font's ascent, descent and leading,
|
||||
but StyledText does not expose line-height. This metrics-only font supplies 1.5em
|
||||
line boxes without replacing any visible glyphs: Slint's normal system fallback
|
||||
fonts still render the text and links. Use this family for message and release-note
|
||||
bodies without changing the typography of other controls.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from fontTools.fontBuilder import FontBuilder
|
||||
from fontTools.pens.ttGlyphPen import TTGlyphPen
|
||||
|
||||
|
||||
def main():
|
||||
font = FontBuilder(1000, isTTF=True)
|
||||
glyphs = [".notdef", "zeroWidthSpace"]
|
||||
font.setupGlyphOrder(glyphs)
|
||||
font.setupCharacterMap({0x200B: "zeroWidthSpace"})
|
||||
font.setupGlyf({name: TTGlyphPen(None).glyph() for name in glyphs})
|
||||
font.setupHorizontalMetrics({name: (0, 0) for name in glyphs})
|
||||
font.setupHorizontalHeader(ascent=1000, descent=-250, lineGap=250)
|
||||
font.setupOS2(
|
||||
version=4,
|
||||
sTypoAscender=1000,
|
||||
sTypoDescender=-250,
|
||||
sTypoLineGap=250,
|
||||
usWinAscent=1000,
|
||||
usWinDescent=250,
|
||||
fsSelection=0xC0, # Regular, use typographic metrics.
|
||||
)
|
||||
font.setupNameTable({
|
||||
"familyName": "CrossDesk Message Spacing",
|
||||
"styleName": "Regular",
|
||||
"uniqueFontIdentifier": "CrossDesk-Message-Spacing-1.0",
|
||||
"fullName": "CrossDesk Message Spacing",
|
||||
"psName": "CrossDeskMessageSpacing-Regular",
|
||||
"version": "Version 1.0",
|
||||
"copyright": "Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.",
|
||||
})
|
||||
font.setupPost()
|
||||
# Fixed timestamps keep the generated asset reproducible.
|
||||
font.font["head"].created = font.font["head"].modified = 3874867200
|
||||
font.font.recalcTimestamp = False
|
||||
font.save(Path(__file__).with_name("message_spacing.ttf"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Binary file not shown.
@@ -23,10 +23,11 @@ struct TranslationRow {
|
||||
X(messages, u8"消息", "Messages", u8"Сообщения") \
|
||||
X(message_unread, u8"未读", "Unread", u8"Не прочитано") \
|
||||
X(message_read, u8"已读", "Read", u8"Прочитано") \
|
||||
X(message_read_all, u8"全部已读", "Mark all as read", u8"Отметить всё прочитанным") \
|
||||
X(message_empty, u8"暂无公告", "No announcements", u8"Нет объявлений") \
|
||||
X(message_select, u8"选择公告查看详情", "Select an announcement to read", u8"Выберите объявление") \
|
||||
X(message_loading, u8"正在加载…", "Loading…", u8"Загрузка…") \
|
||||
X(message_read_save_error, u8"无法保存本地阅读状态,请重新打开公告重试。", "Unable to save reading status locally. Open the announcement again to retry.", u8"Не удалось сохранить статус чтения. Откройте объявление снова.") \
|
||||
X(message_read_save_error, u8"无法保存本地阅读状态,请重试。", "Unable to save reading status locally. Please try again.", u8"Не удалось сохранить статус чтения. Повторите попытку.") \
|
||||
X(message_close, u8"关闭", "Close", u8"Закрыть") \
|
||||
X(message_delete, u8"删除", "Delete", u8"Удалить") \
|
||||
X(message_delete_title, u8"删除公告", "Delete announcement", u8"Удалить объявление") \
|
||||
@@ -240,6 +241,9 @@ struct TranslationRow {
|
||||
"Server Address:", u8"Адрес сервера:") \
|
||||
X(self_hosted_server_port, u8"信令服务端口:", \
|
||||
"Signal Service Port:", u8"Порт сигнального сервиса:") \
|
||||
X(self_hosted_address_invalid, u8"请输入有效的主机名、IP 或 HTTPS/WSS 信令地址,可包含路径。", "Enter a valid host, IP, or HTTPS/WSS signaling URL. Paths are supported.", u8"Введите имя хоста, IP или HTTPS/WSS-адрес сигнального сервиса. Путь допустим.") \
|
||||
X(self_hosted_port_invalid, u8"请输入 1–65535 范围内的信令端口。", "Enter a signaling port between 1 and 65535.", u8"Введите порт сигнального сервиса от 1 до 65535.") \
|
||||
X(self_hosted_save_failed, u8"配置保存失败,请检查配置目录是否可写后重试。", "Could not save settings. Check that the configuration directory is writable and retry.", u8"Не удалось сохранить настройки. Проверьте доступ на запись в каталог конфигурации.") \
|
||||
X(ok, u8"确认", "OK", u8"ОК") \
|
||||
X(cancel, u8"取消", "Cancel", u8"Отмена") \
|
||||
X(new_password, u8"请输入六位密码:", \
|
||||
@@ -255,6 +259,9 @@ struct TranslationRow {
|
||||
X(signal_connected, u8"已连接服务器", "Connected", u8"Подключено к серверу") \
|
||||
X(signal_disconnected, u8"未连接服务器", "Disconnected", \
|
||||
u8"Нет подключения к серверу") \
|
||||
X(signal_reconnect, u8"重新连接", "Reconnect", u8"Переподключиться") \
|
||||
X(signal_reconnecting, u8"正在重新连接...", "Reconnecting...", \
|
||||
u8"Переподключение...") \
|
||||
X(signal_tls_cert_error, u8"证书验证失败,请重新安装自托管根证书", \
|
||||
"Certificate verification failed. Reinstall the self-hosted root " \
|
||||
"certificate.", \
|
||||
@@ -269,6 +276,10 @@ struct TranslationRow {
|
||||
X(receiving_screen, u8"画面接收中...", "Receiving screen...", \
|
||||
u8"Получение изображения...") \
|
||||
X(p2p_failed, u8"对等连接失败", "P2P Failed", u8"Сбой P2P") \
|
||||
X(connection_auth_throttled, u8"验证尝试过于频繁,请稍后重试。", "Too many authentication attempts. Try again later.", u8"Слишком много попыток. Повторите позже.") \
|
||||
X(connection_service_busy, u8"认证服务繁忙,请稍后重试。", "Authentication service busy. Try again later.", u8"Сервис проверки занят. Повторите позже.") \
|
||||
X(connection_not_authenticated, u8"登录状态已失效,请重新连接。", "Signaling login expired. Please reconnect.", u8"Сеанс входа истёк. Подключитесь заново.") \
|
||||
X(connection_retry_after, u8"请在 %d 秒后重试。", "Retry in %d seconds.", u8"Повторите через %d сек.") \
|
||||
X(p2p_closed, u8"对等连接已关闭", "P2P closed", u8"P2P закрыто") \
|
||||
X(no_such_id, u8"无此ID", "No such ID", u8"ID не найден") \
|
||||
X(about, u8"关于", "About", u8"О программе") \
|
||||
@@ -286,6 +297,7 @@ struct TranslationRow {
|
||||
"Check failed. Please try again later.", \
|
||||
u8"Не удалось проверить обновления. Повторите позже.") \
|
||||
X(release_notes, u8"更新内容", "Release Notes", u8"Содержание обновления") \
|
||||
X(view_release_notes, u8"更新日志", "Release notes", u8"История изменений") \
|
||||
X(version, u8"版本", "Version", u8"Версия") \
|
||||
X(release_date, u8"发布日期: ", "Release Date: ", u8"Дата релиза: ") \
|
||||
X(access_website, u8"访问官网: ", \
|
||||
@@ -316,6 +328,13 @@ struct TranslationRow {
|
||||
X(completed, u8"已完成", "Completed", u8"Завершено") \
|
||||
X(failed, u8"失败", "Failed", u8"Ошибка") \
|
||||
X(controller, u8"控制端:", "Controller:", u8"Контроллер:") \
|
||||
X(server_controlled, u8"被控中", "Controlled", u8"Под управлением") \
|
||||
X(server_heading, u8"此设备被控中", "This device is controlled", u8"Устройство под управлением") \
|
||||
X(server_connected, u8"已连接", "Connected", u8"Подключено") \
|
||||
X(server_send_file, u8"发送文件", "Send file", u8"Отправить файл") \
|
||||
X(server_disconnect, u8"断开", "Disconnect", u8"Отключить") \
|
||||
X(server_disconnect_all, u8"全部断开", "Disconnect all", u8"Отключить всех") \
|
||||
X(server_confirm_disconnect, u8"断开所有控制端的连接?", "Disconnect all controllers?", u8"Отключить все контроллеры?") \
|
||||
X(file_transfer, u8"文件传输:", "File Transfer:", u8"Передача файлов:") \
|
||||
X(connection_status, u8"连接状态:", \
|
||||
"Connection Status:", u8"Состояние соединения:") \
|
||||
|
||||
@@ -46,7 +46,8 @@ void ClipboardController::Shutdown() {
|
||||
pending_remote_text_.reset();
|
||||
}
|
||||
|
||||
void ClipboardController::QueueRemoteText(const char *data, size_t size) {
|
||||
void ClipboardController::QueueRemoteText(const char* data, size_t size,
|
||||
const std::string& remote_id) {
|
||||
if (!events_enabled_.load(std::memory_order_acquire)) {
|
||||
return;
|
||||
}
|
||||
@@ -62,6 +63,11 @@ void ClipboardController::QueueRemoteText(const char *data, size_t size) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto session =
|
||||
remote_id.empty() ? nullptr : owner_.FindRemoteSession(remote_id);
|
||||
if (!remote_id.empty() && (!session || !session->clipboard_allowed_.load()))
|
||||
return;
|
||||
const auto generation = session ? session->input_generation_.load() : 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pending_mutex_);
|
||||
if (!events_enabled_.load(std::memory_order_relaxed)) {
|
||||
@@ -70,6 +76,9 @@ void ClipboardController::QueueRemoteText(const char *data, size_t size) {
|
||||
// Only the newest clipboard value matters. Replacing it also bounds the
|
||||
// amount of memory a busy or malicious peer can queue.
|
||||
pending_remote_text_ = std::string(data, size);
|
||||
pending_remote_id_ = remote_id;
|
||||
pending_session_ = session;
|
||||
pending_generation_ = generation;
|
||||
}
|
||||
|
||||
SDL_Event event{};
|
||||
@@ -87,9 +96,22 @@ void ClipboardController::ApplyPendingRemoteText() {
|
||||
}
|
||||
|
||||
std::optional<std::string> pending_text;
|
||||
std::string source_id;
|
||||
std::weak_ptr<gui_detail::RemoteSession> source_session;
|
||||
uint64_t generation = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pending_mutex_);
|
||||
pending_text.swap(pending_remote_text_);
|
||||
source_id.swap(pending_remote_id_);
|
||||
source_session.swap(pending_session_);
|
||||
generation = pending_generation_;
|
||||
}
|
||||
if (!source_id.empty()) {
|
||||
auto props = owner_.FindRemoteSession(source_id);
|
||||
if (!props || props != source_session.lock() ||
|
||||
!props->clipboard_allowed_.load() ||
|
||||
props->input_generation_.load() != generation)
|
||||
return;
|
||||
}
|
||||
if (!pending_text || *pending_text == last_text_) {
|
||||
return;
|
||||
@@ -145,7 +167,7 @@ int ClipboardController::SendToPeers(const std::string &text) {
|
||||
std::shared_lock lock(owner_.remote_sessions_mutex_);
|
||||
for (const auto &[remote_id, props] : owner_.remote_sessions_) {
|
||||
if (!props || !props->peer_ || !props->connection_established_ ||
|
||||
!props->enable_mouse_control_) {
|
||||
!props->clipboard_allowed_.load()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,10 +10,15 @@
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace crossdesk::gui_detail {
|
||||
struct RemoteSession;
|
||||
}
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
class GuiRuntime;
|
||||
@@ -29,7 +34,8 @@ public:
|
||||
|
||||
void Initialize();
|
||||
void Shutdown();
|
||||
void QueueRemoteText(const char *data, size_t size);
|
||||
void QueueRemoteText(const char* data, size_t size,
|
||||
const std::string& remote_id = {});
|
||||
void ApplyPendingRemoteText();
|
||||
void HandleLocalUpdate();
|
||||
|
||||
@@ -41,6 +47,9 @@ private:
|
||||
std::atomic<bool> events_enabled_{false};
|
||||
std::mutex pending_mutex_;
|
||||
std::optional<std::string> pending_remote_text_;
|
||||
std::string pending_remote_id_;
|
||||
std::weak_ptr<gui_detail::RemoteSession> pending_session_;
|
||||
uint64_t pending_generation_ = 0;
|
||||
std::string last_text_;
|
||||
};
|
||||
|
||||
|
||||
@@ -19,16 +19,20 @@
|
||||
#include "runtime/gui_runtime.h"
|
||||
#include "speaker_capturer_factory.h"
|
||||
#ifdef _WIN32
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "platform/windows/screen_capturer/screen_capturer_win.h"
|
||||
#include "platform/windows/input/mouse/mouse_controller.h"
|
||||
#include "service_host.h"
|
||||
#endif
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
|
||||
constexpr uint64_t kCaptureResumeKeyFrameGapMs = 500;
|
||||
constexpr size_t kMaxCapturedKeyboardInputs = 512;
|
||||
constexpr auto kFrameDeadlineTolerance = std::chrono::milliseconds(1);
|
||||
#ifdef _WIN32
|
||||
constexpr auto kKeyboardCaptureRetryDelay = std::chrono::seconds(1);
|
||||
#endif
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -45,7 +49,13 @@ SessionDeviceManager::SessionDeviceManager(GuiRuntime &owner)
|
||||
frame.data = reinterpret_cast<const char *>(data);
|
||||
frame.size = size;
|
||||
frame.captured_timestamp = GetSystemTimeMicros(owner_.peer_);
|
||||
SendAudioFrame(owner_.peer_, &frame, owner_.audio_label_.c_str());
|
||||
std::shared_lock lock(owner_.connection_status_mutex_);
|
||||
for (const auto& [id, status] : owner_.connection_status_) {
|
||||
if (status == ConnectionStatus::Connected)
|
||||
SendAudioFrameToPeer(owner_.peer_, &frame,
|
||||
owner_.audio_label_.c_str(), id.data(),
|
||||
id.size());
|
||||
}
|
||||
}) {}
|
||||
|
||||
SessionDeviceManager::~SessionDeviceManager() { speaker_capture_.Shutdown(); }
|
||||
@@ -115,7 +125,7 @@ void SessionDeviceManager::RecordCaptureCadence(
|
||||
}
|
||||
|
||||
void SessionDeviceManager::Initialize() {
|
||||
InitializeAudioOutput();
|
||||
if (!owner_.unattended_host_) InitializeAudioOutput();
|
||||
screen_capturer_factory_ = new ScreenCapturerFactory();
|
||||
device_controller_factory_ = new DeviceControllerFactory();
|
||||
keyboard_capturer_ =
|
||||
@@ -241,6 +251,8 @@ int SessionDeviceManager::InitializeScreenCapturer() {
|
||||
const auto send_started = std::chrono::steady_clock::now();
|
||||
uint64_t send_errors = 0;
|
||||
for (const std::string &remote_id : connected_remote_ids) {
|
||||
if (!owner_.preview_subscriptions_.ShouldSend(remote_id, now_time,
|
||||
stream_id)) continue;
|
||||
if (SendVideoFrameToPeer(owner_.peer_, &frame, stream_id.c_str(),
|
||||
remote_id.data(), remote_id.size()) != 0)
|
||||
++send_errors;
|
||||
@@ -325,10 +337,42 @@ int SessionDeviceManager::StopScreenCapturer() {
|
||||
void SessionDeviceManager::ReleaseRemoteMouseButtons() {
|
||||
if (auto mouse = dynamic_cast<PlatformMouseController*>(mouse_controller_))
|
||||
mouse->ReleasePressedButtons();
|
||||
std::lock_guard lock(service_mouse_mutex_);
|
||||
for (int button = 0; button < 3; ++button) {
|
||||
const unsigned bit = 1u << button;
|
||||
if (!(service_mouse_buttons_ & bit)) continue;
|
||||
const auto response = SendCrossDeskSecureDesktopMouseInput(
|
||||
service_mouse_x_, service_mouse_y_, 0, (button + 1) * 2, 1000);
|
||||
const auto json = nlohmann::json::parse(response, nullptr, false);
|
||||
if (json.is_object() && json.value("ok", false)) {
|
||||
service_mouse_buttons_ &= ~bit;
|
||||
} else {
|
||||
LOG_WARN("Service mouse button release failed: button={}, response={}",
|
||||
button, response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string SessionDeviceManager::SendServiceMouseCommand(int x, int y,
|
||||
int wheel, int flag) {
|
||||
std::lock_guard lock(service_mouse_mutex_);
|
||||
service_mouse_x_ = x;
|
||||
service_mouse_y_ = y;
|
||||
const unsigned bit = flag >= 1 && flag <= 6 ? 1u << ((flag - 1) / 2) : 0;
|
||||
// A timeout can follow successful injection. Keep downs for disconnect
|
||||
// cleanup even if the reply was lost; only clear a confirmed release.
|
||||
if (flag % 2 == 1) service_mouse_buttons_ |= bit;
|
||||
const auto response = SendCrossDeskSecureDesktopMouseInput(x, y, wheel, flag,
|
||||
1000);
|
||||
const auto json = nlohmann::json::parse(response, nullptr, false);
|
||||
if (flag % 2 == 0 && json.is_object() && json.value("ok", false))
|
||||
service_mouse_buttons_ &= ~bit;
|
||||
return response;
|
||||
}
|
||||
#endif
|
||||
|
||||
void SessionDeviceManager::StartSpeakerCapturer() {
|
||||
if (owner_.unattended_host_) return;
|
||||
speaker_capture_.SetEnabled(true);
|
||||
}
|
||||
|
||||
@@ -409,6 +453,9 @@ int SessionDeviceManager::StartMouseController() {
|
||||
}
|
||||
|
||||
int SessionDeviceManager::StopMouseController() {
|
||||
#ifdef _WIN32
|
||||
ReleaseRemoteMouseButtons();
|
||||
#endif
|
||||
if (mouse_controller_) {
|
||||
mouse_controller_->Destroy();
|
||||
delete mouse_controller_;
|
||||
@@ -418,8 +465,12 @@ int SessionDeviceManager::StopMouseController() {
|
||||
}
|
||||
|
||||
int SessionDeviceManager::StartKeyboardCapturer() {
|
||||
ClearCapturedKeyboardInput();
|
||||
captured_keyboard_inputs_.Clear();
|
||||
owner_.keyboard_capturer_uses_window_events_ = false;
|
||||
#ifdef _WIN32
|
||||
next_keyboard_capture_retry_ =
|
||||
std::chrono::steady_clock::now() + kKeyboardCaptureRetryDelay;
|
||||
#endif
|
||||
|
||||
#ifdef __APPLE__
|
||||
if (!owner_.EnsureMacAccessibilityPermission()) {
|
||||
@@ -448,8 +499,10 @@ int SessionDeviceManager::StartKeyboardCapturer() {
|
||||
void *user_ptr) {
|
||||
if (user_ptr) {
|
||||
auto *devices = static_cast<SessionDeviceManager *>(user_ptr);
|
||||
devices->QueueCapturedKeyboardInput(key_code, is_down, scan_code,
|
||||
extended);
|
||||
// Native hooks only enqueue; forwarding and logging stay off the
|
||||
// hook thread so they cannot trigger LowLevelHooksTimeout.
|
||||
devices->captured_keyboard_inputs_.Push(
|
||||
{key_code, is_down, scan_code, extended});
|
||||
}
|
||||
},
|
||||
this);
|
||||
@@ -467,7 +520,7 @@ int SessionDeviceManager::StartKeyboardCapturer() {
|
||||
int SessionDeviceManager::StopKeyboardCapturer() {
|
||||
owner_.keyboard_capturer_is_started_ = false;
|
||||
if (keyboard_capturer_) keyboard_capturer_->Unhook();
|
||||
ClearCapturedKeyboardInput();
|
||||
captured_keyboard_inputs_.Clear();
|
||||
if (owner_.keyboard_capturer_uses_window_events_) {
|
||||
owner_.keyboard_capturer_uses_window_events_ = false;
|
||||
LOG_INFO("Stop keyboard capturer with Slint keyboard backend");
|
||||
@@ -486,13 +539,13 @@ int SessionDeviceManager::InitializeAudioOutput() {
|
||||
desired_out.format = SDL_AUDIO_S16;
|
||||
desired_out.channels = 1;
|
||||
|
||||
auto open_stream = [&]() {
|
||||
output_stream_ = SDL_OpenAudioDeviceStream(
|
||||
SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &desired_out, nullptr, nullptr);
|
||||
return output_stream_ != nullptr;
|
||||
auto open_device = [&]() {
|
||||
output_device_ = SDL_OpenAudioDevice(
|
||||
SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &desired_out);
|
||||
return output_device_ != 0;
|
||||
};
|
||||
|
||||
if (!open_stream()) {
|
||||
if (!open_device()) {
|
||||
#if defined(__linux__) && !defined(__APPLE__)
|
||||
LOG_WARN("Failed to open output stream with driver [{}]: {}",
|
||||
getenv("SDL_AUDIODRIVER") ? getenv("SDL_AUDIODRIVER")
|
||||
@@ -506,7 +559,7 @@ int SessionDeviceManager::InitializeAudioOutput() {
|
||||
SDL_GetError());
|
||||
return -1;
|
||||
}
|
||||
if (!open_stream()) {
|
||||
if (!open_device()) {
|
||||
LOG_ERROR("Failed to open output stream with dummy driver: {}",
|
||||
SDL_GetError());
|
||||
return -1;
|
||||
@@ -518,27 +571,50 @@ int SessionDeviceManager::InitializeAudioOutput() {
|
||||
#endif
|
||||
}
|
||||
|
||||
SDL_ResumeAudioDevice(SDL_GetAudioStreamDevice(output_stream_));
|
||||
SDL_ResumeAudioDevice(output_device_);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int SessionDeviceManager::DestroyAudioOutput() {
|
||||
if (output_stream_) {
|
||||
SDL_CloseAudioDevice(SDL_GetAudioStreamDevice(output_stream_));
|
||||
SDL_DestroyAudioStream(output_stream_);
|
||||
output_stream_ = nullptr;
|
||||
for (const auto& [_, stream] : output_streams_)
|
||||
SDL_DestroyAudioStream(stream);
|
||||
output_streams_.clear();
|
||||
if (output_device_) {
|
||||
SDL_CloseAudioDevice(output_device_);
|
||||
output_device_ = 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void SessionDeviceManager::PushAudio(const char *data, size_t size) {
|
||||
if (!output_stream_) {
|
||||
return;
|
||||
void SessionDeviceManager::ClearAudio(const std::string& remote_id) {
|
||||
const auto found = output_streams_.find(remote_id);
|
||||
if (found == output_streams_.end()) return;
|
||||
SDL_DestroyAudioStream(found->second);
|
||||
output_streams_.erase(found);
|
||||
}
|
||||
|
||||
void SessionDeviceManager::PushAudio(const std::string& remote_id,
|
||||
const char *data, size_t size) {
|
||||
if (!output_device_) return;
|
||||
auto found = output_streams_.find(remote_id);
|
||||
if (found == output_streams_.end()) {
|
||||
SDL_AudioSpec spec{};
|
||||
spec.freq = 48000;
|
||||
spec.format = SDL_AUDIO_S16;
|
||||
spec.channels = 1;
|
||||
auto* stream = SDL_CreateAudioStream(&spec, &spec);
|
||||
if (!stream) {
|
||||
LOG_ERROR("Failed to create output stream: {}", SDL_GetError());
|
||||
return;
|
||||
}
|
||||
if (!SDL_BindAudioStream(output_device_, stream)) {
|
||||
LOG_ERROR("Failed to bind output stream: {}", SDL_GetError());
|
||||
SDL_DestroyAudioStream(stream);
|
||||
return;
|
||||
}
|
||||
found = output_streams_.emplace(remote_id, stream).first;
|
||||
}
|
||||
const int pushed = SDL_PutAudioStreamData(
|
||||
output_stream_, reinterpret_cast<const Uint8 *>(data),
|
||||
static_cast<int>(size));
|
||||
if (pushed < 0) {
|
||||
if (!SDL_PutAudioStreamData(found->second, data, static_cast<int>(size))) {
|
||||
LOG_ERROR("Failed to push audio data: {}", SDL_GetError());
|
||||
}
|
||||
}
|
||||
@@ -601,7 +677,18 @@ void SessionDeviceManager::UpdateInteractions() {
|
||||
#endif
|
||||
}
|
||||
|
||||
if (owner_.start_keyboard_capturer_ && owner_.focus_on_stream_window_) {
|
||||
if (owner_.start_keyboard_capturer_ && owner_.focus_on_stream_window_ &&
|
||||
!owner_.privacy_.Snapshot().input_blocked) {
|
||||
#ifdef _WIN32
|
||||
if (owner_.keyboard_capturer_is_started_ &&
|
||||
owner_.keyboard_capturer_uses_window_events_ && keyboard_capturer_ &&
|
||||
std::chrono::steady_clock::now() >= next_keyboard_capture_retry_) {
|
||||
// A transient installation failure or stalled hook must not leave
|
||||
// system shortcuts in the window-event fallback until focus changes.
|
||||
StopKeyboardCapturer();
|
||||
owner_.keyboard_.ForceReleasePressedKeys();
|
||||
}
|
||||
#endif
|
||||
if (!owner_.keyboard_capturer_is_started_ && StartKeyboardCapturer() == 0) {
|
||||
owner_.keyboard_capturer_is_started_ = true;
|
||||
}
|
||||
@@ -612,6 +699,10 @@ void SessionDeviceManager::UpdateInteractions() {
|
||||
owner_.keyboard_.ForceReleasePressedKeys();
|
||||
owner_.keyboard_capturer_uses_window_events_ = true;
|
||||
owner_.keyboard_capturer_is_started_ = true;
|
||||
#ifdef _WIN32
|
||||
next_keyboard_capture_retry_ =
|
||||
std::chrono::steady_clock::now() + kKeyboardCaptureRetryDelay;
|
||||
#endif
|
||||
LOG_WARN("Native keyboard capture stopped; using Slint keyboard events");
|
||||
}
|
||||
DrainCapturedKeyboardInput();
|
||||
@@ -620,43 +711,25 @@ void SessionDeviceManager::UpdateInteractions() {
|
||||
} else if (owner_.keyboard_capturer_is_started_) {
|
||||
owner_.keyboard_.ForceReleasePressedKeys();
|
||||
StopKeyboardCapturer();
|
||||
owner_.keyboard_capturer_is_started_ = false;
|
||||
}
|
||||
|
||||
owner_.keyboard_.CheckRemoteTimeouts();
|
||||
}
|
||||
|
||||
void SessionDeviceManager::QueueCapturedKeyboardInput(int key_code,
|
||||
bool is_down,
|
||||
uint32_t scan_code,
|
||||
bool extended) {
|
||||
std::lock_guard<std::mutex> lock(captured_keyboard_inputs_mutex_);
|
||||
if (captured_keyboard_inputs_.size() >= kMaxCapturedKeyboardInputs) {
|
||||
captured_keyboard_inputs_.pop_front();
|
||||
LOG_WARN("Captured keyboard input queue overflow, dropping oldest event");
|
||||
}
|
||||
captured_keyboard_inputs_.push_back(
|
||||
CapturedKeyboardInput{key_code, is_down, scan_code, extended});
|
||||
}
|
||||
|
||||
void SessionDeviceManager::DrainCapturedKeyboardInput() {
|
||||
std::deque<CapturedKeyboardInput> inputs;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(captured_keyboard_inputs_mutex_);
|
||||
inputs.swap(captured_keyboard_inputs_);
|
||||
}
|
||||
const auto inputs = captured_keyboard_inputs_.Drain();
|
||||
if (owner_.privacy_.Snapshot().input_blocked) return;
|
||||
for (const CapturedKeyboardInput &input : inputs) {
|
||||
if (inputs.resync) {
|
||||
LOG_WARN("Captured keyboard queue overflow; reconciling pressed keys");
|
||||
owner_.keyboard_.RecoverCapturedState(inputs.pressed);
|
||||
return;
|
||||
}
|
||||
for (const KeyboardInput &input : inputs.events) {
|
||||
owner_.keyboard_.SendKeyCommand(input.key_code, input.is_down,
|
||||
input.scan_code, input.extended);
|
||||
}
|
||||
}
|
||||
|
||||
void SessionDeviceManager::ClearCapturedKeyboardInput() {
|
||||
std::lock_guard<std::mutex> lock(captured_keyboard_inputs_mutex_);
|
||||
captured_keyboard_inputs_.clear();
|
||||
}
|
||||
|
||||
bool SessionDeviceManager::SendKeyboardCommand(int key_code, bool is_down,
|
||||
uint32_t scan_code,
|
||||
bool extended) {
|
||||
@@ -664,11 +737,12 @@ bool SessionDeviceManager::SendKeyboardCommand(int key_code, bool is_down,
|
||||
key_code, is_down, scan_code, extended) == 0;
|
||||
}
|
||||
|
||||
void SessionDeviceManager::SendMouseCommand(const RemoteAction &action,
|
||||
bool SessionDeviceManager::SendMouseCommand(const RemoteAction &action,
|
||||
int selected_display) {
|
||||
if (mouse_controller_) {
|
||||
mouse_controller_->SendMouseCommand(action, selected_display);
|
||||
return mouse_controller_->SendMouseCommand(action, selected_display) == 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
int SessionDeviceManager::SwitchDisplay(int display_id) {
|
||||
@@ -711,11 +785,7 @@ std::vector<HostDisplay> SessionDeviceManager::host_display_list() const {
|
||||
|
||||
void SessionDeviceManager::DestroyDevices() {
|
||||
speaker_capture_.Shutdown();
|
||||
if (mouse_controller_) {
|
||||
mouse_controller_->Destroy();
|
||||
delete mouse_controller_;
|
||||
mouse_controller_ = nullptr;
|
||||
}
|
||||
StopMouseController();
|
||||
if (screen_capturer_) {
|
||||
screen_capturer_->Destroy();
|
||||
delete screen_capturer_;
|
||||
|
||||
@@ -7,20 +7,20 @@
|
||||
#ifndef _SESSION_DEVICE_MANAGER_H_
|
||||
#define _SESSION_DEVICE_MANAGER_H_
|
||||
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include <remote_action.h>
|
||||
|
||||
#include "device_controller.h"
|
||||
#include "display_info.h"
|
||||
#include "features/input/captured_keyboard_queue.h"
|
||||
#include "speaker_capture_controller.h"
|
||||
|
||||
struct SDL_AudioStream;
|
||||
@@ -55,6 +55,7 @@ public:
|
||||
int StopScreenCapturer();
|
||||
#ifdef _WIN32
|
||||
void ReleaseRemoteMouseButtons();
|
||||
std::string SendServiceMouseCommand(int x, int y, int wheel, int flag);
|
||||
#endif
|
||||
// Requests are asynchronous; Stop drains/revokes audio delivery before
|
||||
// returning so the connection peer can be destroyed safely.
|
||||
@@ -67,11 +68,14 @@ public:
|
||||
|
||||
int InitializeAudioOutput();
|
||||
int DestroyAudioOutput();
|
||||
void PushAudio(const char *data, size_t size);
|
||||
// Serialized by GuiRuntime::audio_delivery_mutex_. Each peer has its own
|
||||
// stream so SDL mixes simultaneous playback and muting clears only that peer.
|
||||
void ClearAudio(const std::string& remote_id);
|
||||
void PushAudio(const std::string& remote_id, const char *data, size_t size);
|
||||
|
||||
bool SendKeyboardCommand(int key_code, bool is_down, uint32_t scan_code,
|
||||
bool extended);
|
||||
void SendMouseCommand(const RemoteAction &action, int selected_display);
|
||||
bool SendMouseCommand(const RemoteAction &action, int selected_display);
|
||||
int SwitchDisplay(int display_id);
|
||||
void ResetToInitialDisplay();
|
||||
|
||||
@@ -83,17 +87,7 @@ public:
|
||||
std::vector<HostDisplay> host_display_list() const;
|
||||
|
||||
private:
|
||||
struct CapturedKeyboardInput {
|
||||
int key_code = 0;
|
||||
bool is_down = false;
|
||||
uint32_t scan_code = 0;
|
||||
bool extended = false;
|
||||
};
|
||||
|
||||
void QueueCapturedKeyboardInput(int key_code, bool is_down,
|
||||
uint32_t scan_code, bool extended);
|
||||
void DrainCapturedKeyboardInput();
|
||||
void ClearCapturedKeyboardInput();
|
||||
bool ShouldSendCapturedFrame(std::chrono::steady_clock::time_point now,
|
||||
int fps);
|
||||
bool ShouldCaptureCursor() const;
|
||||
@@ -103,7 +97,8 @@ private:
|
||||
bool from_secure_desktop);
|
||||
|
||||
GuiRuntime &owner_;
|
||||
SDL_AudioStream *output_stream_ = nullptr;
|
||||
uint32_t output_device_ = 0;
|
||||
std::unordered_map<std::string, SDL_AudioStream*> output_streams_;
|
||||
ScreenCapturerFactory *screen_capturer_factory_ = nullptr;
|
||||
ScreenCapturer *screen_capturer_ = nullptr;
|
||||
std::atomic<bool> cursor_capture_dirty_{true};
|
||||
@@ -115,8 +110,13 @@ private:
|
||||
mutable std::mutex display_info_mutex_;
|
||||
std::vector<DisplayInfo> display_info_list_;
|
||||
size_t registered_display_stream_count_ = 0;
|
||||
std::deque<CapturedKeyboardInput> captured_keyboard_inputs_;
|
||||
std::mutex captured_keyboard_inputs_mutex_;
|
||||
CapturedKeyboardQueue captured_keyboard_inputs_;
|
||||
#ifdef _WIN32
|
||||
std::chrono::steady_clock::time_point next_keyboard_capture_retry_{};
|
||||
std::mutex service_mouse_mutex_;
|
||||
unsigned service_mouse_buttons_ = 0;
|
||||
int service_mouse_x_ = 0, service_mouse_y_ = 0;
|
||||
#endif
|
||||
std::chrono::steady_clock::time_point last_frame_time_{};
|
||||
std::chrono::steady_clock::time_point next_frame_deadline_{};
|
||||
std::mutex capture_metrics_mutex_;
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-12
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _GALLERY_FULLSCREEN_TRANSITION_H_
|
||||
#define _GALLERY_FULLSCREEN_TRANSITION_H_
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
|
||||
namespace crossdesk::gallery {
|
||||
|
||||
// Guard input while native geometry settles, without hiding the live content.
|
||||
// Driven by the existing UI tick; never pumps events or creates nested timers.
|
||||
class FullscreenTransition {
|
||||
public:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
enum class Action { Idle, Apply, Finished };
|
||||
|
||||
bool Begin(bool fullscreen, Clock::time_point now) {
|
||||
if (Active())
|
||||
return false;
|
||||
target_ = fullscreen;
|
||||
phase_ = Phase::Pending;
|
||||
phase_at_ = now;
|
||||
width_ = height_ = 0;
|
||||
scale_ = 0;
|
||||
geometry_changed_ = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
Action Advance(Clock::time_point now, uint32_t width, uint32_t height,
|
||||
float scale, bool fullscreen, bool restoring) {
|
||||
using namespace std::chrono_literals;
|
||||
if (phase_ == Phase::Pending) {
|
||||
if (restoring && now - phase_at_ >= 1500ms) {
|
||||
Cancel();
|
||||
return Action::Finished;
|
||||
}
|
||||
// Apply on the next UI tick as soon as window restoration is complete.
|
||||
if (restoring)
|
||||
return Action::Idle;
|
||||
phase_ = Phase::Settling;
|
||||
phase_at_ = stable_at_ = now;
|
||||
width_ = width;
|
||||
height_ = height;
|
||||
scale_ = scale;
|
||||
return Action::Apply;
|
||||
}
|
||||
if (phase_ == Phase::Settling) {
|
||||
const bool changed =
|
||||
width != width_ || height != height_ || scale != scale_;
|
||||
if (changed && width > 0 && height > 0)
|
||||
geometry_changed_ = true;
|
||||
if (changed || fullscreen != target_ || restoring) {
|
||||
width_ = width;
|
||||
height_ = height;
|
||||
scale_ = scale;
|
||||
stable_at_ = now;
|
||||
}
|
||||
// Some backends report the requested flag before delivering new bounds.
|
||||
// Also allow fullscreen modes whose client dimensions genuinely match.
|
||||
if ((width > 0 && height > 0 && fullscreen == target_ && !restoring &&
|
||||
(geometry_changed_ || now - phase_at_ >= 300ms) &&
|
||||
now - stable_at_ >= 32ms) ||
|
||||
now - phase_at_ >= 1500ms) {
|
||||
Cancel();
|
||||
return Action::Finished;
|
||||
}
|
||||
}
|
||||
return Action::Idle;
|
||||
}
|
||||
|
||||
void Cancel() { phase_ = Phase::Idle; }
|
||||
bool Active() const { return phase_ != Phase::Idle; }
|
||||
bool Target() const { return target_; }
|
||||
|
||||
private:
|
||||
enum class Phase { Idle, Pending, Settling };
|
||||
Phase phase_ = Phase::Idle;
|
||||
bool target_ = false;
|
||||
bool geometry_changed_ = false;
|
||||
uint32_t width_ = 0, height_ = 0;
|
||||
float scale_ = 0;
|
||||
Clock::time_point phase_at_{}, stable_at_{};
|
||||
};
|
||||
|
||||
} // namespace crossdesk::gallery
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,37 @@
|
||||
#include "gallery_storage.h"
|
||||
|
||||
#include <fstream>
|
||||
#ifdef _WIN32
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#endif
|
||||
namespace crossdesk::gallery {
|
||||
bool WriteAtomically(const std::filesystem::path &path,
|
||||
const std::string &text) {
|
||||
auto temporary = path;
|
||||
temporary += ".tmp";
|
||||
try {
|
||||
{
|
||||
std::ofstream output;
|
||||
output.exceptions(std::ios::failbit | std::ios::badbit);
|
||||
output.open(temporary, std::ios::binary | std::ios::trunc);
|
||||
output.write(text.data(), text.size());
|
||||
output.close();
|
||||
}
|
||||
#ifdef _WIN32
|
||||
if (MoveFileExW(temporary.c_str(), path.c_str(),
|
||||
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH))
|
||||
return true;
|
||||
#else
|
||||
std::filesystem::rename(temporary, path);
|
||||
return true;
|
||||
#endif
|
||||
} catch (...) {
|
||||
}
|
||||
std::error_code ignored;
|
||||
std::filesystem::remove(temporary, ignored);
|
||||
return false;
|
||||
}
|
||||
} // namespace crossdesk::gallery
|
||||
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-12
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _GALLERY_STORAGE_H_
|
||||
#define _GALLERY_STORAGE_H_
|
||||
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
|
||||
namespace crossdesk::gallery {
|
||||
bool WriteAtomically(const std::filesystem::path &path,
|
||||
const std::string &text);
|
||||
} // namespace crossdesk::gallery
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-12
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _GALLERY_STREAM_SETTINGS_H_
|
||||
#define _GALLERY_STREAM_SETTINGS_H_
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <optional>
|
||||
#include <preview_subscription.h>
|
||||
|
||||
#include "preview_resolution.h"
|
||||
|
||||
namespace crossdesk::gallery {
|
||||
struct StreamSettings {
|
||||
// Persisted preset order: automatic, fixed bounds, then original size.
|
||||
static constexpr std::array<PreviewResolution, 8> kResolutions{{
|
||||
{}, {320, 180}, {640, 360}, {1280, 720}, {1920, 1080},
|
||||
{2560, 1440}, {3840, 2160}, {}}};
|
||||
static constexpr std::array<int, 4> kFrameRates{0, 15, 30, 60};
|
||||
static constexpr std::array<int, 6> kBandwidthMbps{2, 5, 10, 20, 50, 100};
|
||||
int resolution = 0;
|
||||
int frame_rate = 0; // 0 follows the session's existing 30/60 FPS preference.
|
||||
int bandwidth_mbps = 20;
|
||||
|
||||
static std::optional<StreamSettings> FromIndices(int resolution, int fps,
|
||||
int bandwidth = 3) {
|
||||
if (resolution < 0 || resolution >= int(kResolutions.size()) ||
|
||||
fps < 0 || fps >= int(kFrameRates.size()) ||
|
||||
bandwidth < 0 || bandwidth >= int(kBandwidthMbps.size()))
|
||||
return {};
|
||||
return StreamSettings{resolution, kFrameRates[fps], kBandwidthMbps[bandwidth]};
|
||||
}
|
||||
int FrameRateIndex() const {
|
||||
return int(std::find(kFrameRates.begin(), kFrameRates.end(), frame_rate) -
|
||||
kFrameRates.begin());
|
||||
}
|
||||
int BandwidthIndex() const {
|
||||
return int(std::find(kBandwidthMbps.begin(), kBandwidthMbps.end(), bandwidth_mbps) -
|
||||
kBandwidthMbps.begin());
|
||||
}
|
||||
bool Valid() const {
|
||||
return resolution >= 0 && resolution < int(kResolutions.size()) &&
|
||||
FrameRateIndex() < int(kFrameRates.size()) &&
|
||||
BandwidthIndex() < int(kBandwidthMbps.size());
|
||||
}
|
||||
static StreamSettings FromJson(const nlohmann::json& json) {
|
||||
try {
|
||||
if (!json.at("resolution").is_number_integer() ||
|
||||
!json.at("frame_rate").is_number_integer()) return {};
|
||||
const auto resolution = json.at("resolution").get<int64_t>();
|
||||
const auto fps = json.at("frame_rate").get<int64_t>();
|
||||
if (resolution < 0 || resolution >= int(kResolutions.size()) ||
|
||||
fps < 0 || fps > 60) return {};
|
||||
// Retired sparse presets migrate to the lowest current setting.
|
||||
StreamSettings result{int(resolution), fps == 1 || fps == 8 ? 15 : int(fps)};
|
||||
if (json.contains("bandwidth_mbps") && json.at("bandwidth_mbps").is_number_integer()) {
|
||||
const auto bandwidth = json.at("bandwidth_mbps").get<int64_t>();
|
||||
if (std::find(kBandwidthMbps.begin(), kBandwidthMbps.end(), bandwidth) !=
|
||||
kBandwidthMbps.end()) result.bandwidth_mbps = int(bandwidth);
|
||||
}
|
||||
return result.Valid() ? result : StreamSettings{};
|
||||
} catch (...) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
nlohmann::json ToJson() const {
|
||||
return {{"resolution", resolution}, {"frame_rate", frame_rate},
|
||||
{"bandwidth_mbps", bandwidth_mbps}};
|
||||
}
|
||||
PreviewResolution Resolution(bool wall_managed, PreviewResolution wall_view,
|
||||
PreviewResolution stream_view) const {
|
||||
if (!wall_managed) return {};
|
||||
if (resolution != 0 && Valid()) return kResolutions[resolution];
|
||||
// Keep a bounded fallback until a rendered viewport is available.
|
||||
if (!wall_view.width && !stream_view.width) return {320, 320};
|
||||
return {std::max(wall_view.width, stream_view.width),
|
||||
std::max(wall_view.height, stream_view.height)};
|
||||
}
|
||||
void ApplyFrameRate(PreviewSubscription& demand, bool supports_fps15) const {
|
||||
if (!Valid() || !frame_rate) return;
|
||||
// Older peers reject fps=15. Keep their existing interactive wire format.
|
||||
demand.fps = frame_rate == 15 && supports_fps15 ? 15 : 60;
|
||||
demand.frame_rate = frame_rate <= 30 ? 30 : 60;
|
||||
}
|
||||
};
|
||||
} // namespace crossdesk::gallery
|
||||
#endif
|
||||
@@ -0,0 +1,178 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-12
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _GALLERY_WINDOW_STATE_H_
|
||||
#define _GALLERY_WINDOW_STATE_H_
|
||||
|
||||
#include <slint.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <optional>
|
||||
|
||||
namespace crossdesk::gallery {
|
||||
|
||||
struct WindowState {
|
||||
bool wall_fullscreen = false;
|
||||
bool wall_maximized = false;
|
||||
// Store client dimensions in logical pixels, independent of the display DPI.
|
||||
std::optional<slint::LogicalSize> wall_size;
|
||||
std::optional<slint::PhysicalPosition> wall_position, connection_position;
|
||||
|
||||
void Observe(bool wall, slint::PhysicalPosition position,
|
||||
slint::PhysicalSize size, float scale, bool fullscreen,
|
||||
bool maximized, float compact_height = 486,
|
||||
float compact_width = 640) {
|
||||
if (Restoring())
|
||||
return;
|
||||
if (!wall) {
|
||||
connection_position = position;
|
||||
return;
|
||||
}
|
||||
if (!fullscreen && !maximized &&
|
||||
IsUndersized(size, scale, compact_height, compact_width))
|
||||
return;
|
||||
scale = std::max(scale, 1.0f);
|
||||
wall_fullscreen = fullscreen;
|
||||
wall_maximized = !fullscreen && maximized;
|
||||
if (!fullscreen && !maximized) {
|
||||
wall_size = slint::LogicalSize(
|
||||
slint::Size<float>{size.width / scale, size.height / scale});
|
||||
wall_position = position;
|
||||
}
|
||||
}
|
||||
|
||||
bool RecoverUndersized(bool wall, slint::PhysicalPosition position,
|
||||
slint::PhysicalSize size, float scale, bool visible,
|
||||
bool minimized, bool fullscreen, bool maximized,
|
||||
float compact_height = 486,
|
||||
float compact_width = 640) {
|
||||
// Hidden/minimized/uninitialized windows can report temporary tiny bounds.
|
||||
// Leave those alone, and let an in-flight restoration retain its target.
|
||||
if (Restoring() || !visible || minimized || fullscreen || maximized ||
|
||||
size.width == 0 || size.height == 0 ||
|
||||
!IsUndersized(size, scale, compact_height, compact_width))
|
||||
return false;
|
||||
if (wall) {
|
||||
wall_position = position;
|
||||
wall_fullscreen = false;
|
||||
wall_maximized = false;
|
||||
} else {
|
||||
connection_position = position;
|
||||
}
|
||||
// Keep the last valid logical size; only the current anchor is captured.
|
||||
BeginRestore();
|
||||
return true;
|
||||
}
|
||||
|
||||
slint::PhysicalSize RestoreSize(bool wall, float scale,
|
||||
float compact_height = 486,
|
||||
float compact_width = 640) const {
|
||||
const float width =
|
||||
wall && wall_size ? std::max(compact_width, wall_size->width)
|
||||
: compact_width;
|
||||
const float height = wall && wall_size
|
||||
? std::max(compact_height, wall_size->height)
|
||||
: compact_height;
|
||||
scale = std::max(scale, 1.0f);
|
||||
return slint::PhysicalSize(
|
||||
slint::Size<uint32_t>{uint32_t(std::lround(width * scale)),
|
||||
uint32_t(std::lround(height * scale))});
|
||||
}
|
||||
|
||||
void BeginRestore() {
|
||||
phase_ = Phase::Normal;
|
||||
target_.reset();
|
||||
last_size_.reset();
|
||||
matches_ = 0;
|
||||
}
|
||||
|
||||
void PrepareForShow(slint::Window &window, bool wall,
|
||||
slint::PhysicalSize size,
|
||||
std::optional<slint::PhysicalPosition> position,
|
||||
float initial_y_offset = 0) {
|
||||
const float scale = std::max(window.scale_factor(), 1.0f);
|
||||
// The actual display scale is resolved when the native window is created.
|
||||
// Give the backend logical geometry so its first visible frame is correct.
|
||||
window.set_size(slint::LogicalSize(
|
||||
slint::Size<float>{size.width / scale, size.height / scale}));
|
||||
if (position) {
|
||||
(wall ? wall_position : connection_position) = position;
|
||||
window.set_position(slint::LogicalPosition(slint::Point<float>{
|
||||
position->x / scale, position->y / scale + initial_y_offset}));
|
||||
}
|
||||
}
|
||||
bool Restoring() const { return phase_ != Phase::Idle; }
|
||||
bool RestoringNormal() const { return phase_ == Phase::Normal; }
|
||||
|
||||
// A set_size request can complete asynchronously, after layout constraints
|
||||
// and the backing scale have changed. Acknowledge observations on later
|
||||
// ticks.
|
||||
bool NormalSizeRestored(slint::PhysicalSize actual,
|
||||
slint::PhysicalSize target) {
|
||||
if (!RestoringNormal())
|
||||
return false;
|
||||
if (target_ && SameSize(*target_, target) && SameSize(actual, target))
|
||||
++matches_;
|
||||
else
|
||||
matches_ = 0;
|
||||
target_ = target;
|
||||
if (matches_ < 2)
|
||||
return false;
|
||||
phase_ = Phase::Presentation;
|
||||
matches_ = 0;
|
||||
last_size_.reset();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FinishRestore(bool wall, slint::PhysicalSize actual, bool fullscreen,
|
||||
bool maximized) {
|
||||
if (phase_ != Phase::Presentation)
|
||||
return false;
|
||||
const bool want_fullscreen = wall && wall_fullscreen;
|
||||
const bool want_maximized = wall && !want_fullscreen && wall_maximized;
|
||||
const bool normal = !want_fullscreen && !want_maximized;
|
||||
if (normal && !fullscreen && !maximized && target_ &&
|
||||
!SameSize(actual, *target_)) {
|
||||
// A late constraint/DPI update can invalidate an earlier acknowledgement.
|
||||
// Reissue the normal size instead of getting stuck or saving that size.
|
||||
BeginRestore();
|
||||
return false;
|
||||
}
|
||||
const bool ready = fullscreen == want_fullscreen &&
|
||||
(want_fullscreen || maximized == want_maximized) &&
|
||||
(!normal || (target_ && SameSize(actual, *target_)));
|
||||
if (ready && last_size_ && SameSize(actual, *last_size_))
|
||||
++matches_;
|
||||
else
|
||||
matches_ = 0;
|
||||
last_size_ = actual;
|
||||
if (matches_ < 2)
|
||||
return false;
|
||||
phase_ = Phase::Idle;
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
enum class Phase { Idle, Normal, Presentation };
|
||||
Phase phase_ = Phase::Idle;
|
||||
std::optional<slint::PhysicalSize> target_, last_size_;
|
||||
int matches_ = 0;
|
||||
static bool IsUndersized(slint::PhysicalSize size, float scale,
|
||||
float compact_height, float compact_width) {
|
||||
scale = std::max(scale, 1.0f);
|
||||
return double(size.width) + 1 < compact_width * scale ||
|
||||
double(size.height) + 1 < compact_height * scale;
|
||||
}
|
||||
static bool SameSize(slint::PhysicalSize a, slint::PhysicalSize b) {
|
||||
return std::abs(double(a.width) - b.width) <= 1 &&
|
||||
std::abs(double(a.height) - b.height) <= 1;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace crossdesk::gallery
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,306 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-12
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _GALLERY_WORKSPACE_H_
|
||||
#define _GALLERY_WORKSPACE_H_
|
||||
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "gallery_storage.h"
|
||||
#include "gallery_stream_settings.h"
|
||||
|
||||
namespace crossdesk::gallery {
|
||||
struct Member {
|
||||
std::string id;
|
||||
std::string group;
|
||||
};
|
||||
|
||||
// Layout contains no credentials and never reconnects devices when loaded.
|
||||
struct Workspace {
|
||||
// Group assignments are shared by history and the wall. Wall enrollment is
|
||||
// independent, so assigning a group alone must never add a device to it.
|
||||
std::vector<Member> members;
|
||||
std::vector<std::string> groups;
|
||||
std::set<std::string> selected;
|
||||
int page = 0;
|
||||
int capacity = 6;
|
||||
StreamSettings stream_settings;
|
||||
|
||||
static std::string NormalizeId(const std::string &input) {
|
||||
std::string result;
|
||||
for (size_t i = 0; i < input.size();) {
|
||||
const auto ch = static_cast<unsigned char>(input[i]);
|
||||
if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n') {
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
if (i + 2 < input.size() && ch == 0xEF &&
|
||||
static_cast<unsigned char>(input[i + 1]) == 0xBC &&
|
||||
static_cast<unsigned char>(input[i + 2]) >= 0x90 &&
|
||||
static_cast<unsigned char>(input[i + 2]) <= 0x99) {
|
||||
result += char('0' + static_cast<unsigned char>(input[i + 2]) - 0x90);
|
||||
i += 3;
|
||||
} else if (input.compare(i, 3, "\xe3\x80\x80") == 0)
|
||||
i += 3;
|
||||
else
|
||||
result += input[i++];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
static bool ValidId(const std::string &id) {
|
||||
return id.size() == 9 &&
|
||||
std::all_of(id.begin(), id.end(),
|
||||
[](unsigned char c) { return c >= '0' && c <= '9'; });
|
||||
}
|
||||
bool Contains(const std::string &id) const {
|
||||
return wall_ids_.count(id) != 0;
|
||||
}
|
||||
bool Add(const std::string &id, const std::string &group = {}) {
|
||||
if (!ValidId(id))
|
||||
return false;
|
||||
const bool joined = wall_ids_.insert(id).second;
|
||||
// A device grouped earlier in history joins at the end when explicitly
|
||||
// added, while retaining its existing group assignments.
|
||||
if (joined)
|
||||
std::stable_partition(members.begin(), members.end(),
|
||||
[&](const auto &m) { return m.id != id; });
|
||||
if (group.empty() && HasAssignments(id))
|
||||
return joined;
|
||||
return AddAssignment(id, group) || joined;
|
||||
}
|
||||
std::vector<std::string> Ids(const std::string &group = {}) const {
|
||||
std::vector<std::string> ids;
|
||||
std::set<std::string> seen;
|
||||
for (const auto &m : members)
|
||||
if (wall_ids_.count(m.id) && (group.empty() || m.group == group) &&
|
||||
seen.insert(m.id).second)
|
||||
ids.push_back(m.id);
|
||||
return OrderIds(ids);
|
||||
}
|
||||
// Order is independent of membership, group assignments and live sessions.
|
||||
std::vector<std::string> OrderIds(const std::vector<std::string> &ids) const {
|
||||
if (device_order_.empty())
|
||||
return ids;
|
||||
std::set<std::string> remaining(ids.begin(), ids.end());
|
||||
std::vector<std::string> ordered;
|
||||
ordered.reserve(ids.size());
|
||||
for (const auto &id : device_order_)
|
||||
if (remaining.erase(id)) ordered.push_back(id);
|
||||
for (const auto &id : ids)
|
||||
if (remaining.erase(id)) ordered.push_back(id);
|
||||
return ordered;
|
||||
}
|
||||
bool SwapPositions(const std::string &source, const std::string &target,
|
||||
const std::vector<std::string> &visible_ids) {
|
||||
if (source == target || !ValidId(source) || !ValidId(target) ||
|
||||
std::find(visible_ids.begin(), visible_ids.end(), source) == visible_ids.end() ||
|
||||
std::find(visible_ids.begin(), visible_ids.end(), target) == visible_ids.end())
|
||||
return false;
|
||||
auto ordered = device_order_;
|
||||
std::set<std::string> known(ordered.begin(), ordered.end());
|
||||
// Include hidden groups before applying a swap in a filtered view.
|
||||
for (const auto &id : Ids())
|
||||
if (known.insert(id).second) ordered.push_back(id);
|
||||
// Active-only devices can be arranged without enrolling them in the wall.
|
||||
for (const auto &id : visible_ids)
|
||||
if (ValidId(id) && known.insert(id).second) ordered.push_back(id);
|
||||
std::iter_swap(std::find(ordered.begin(), ordered.end(), source),
|
||||
std::find(ordered.begin(), ordered.end(), target));
|
||||
device_order_ = std::move(ordered);
|
||||
return true;
|
||||
}
|
||||
// History filtering uses group assignments, independently of wall enrollment.
|
||||
// nullopt means all devices; an empty name means no named group.
|
||||
bool MatchesGroup(const std::string &id,
|
||||
const std::optional<std::string> &group) const {
|
||||
if (!group)
|
||||
return true;
|
||||
if (group->empty())
|
||||
return std::none_of(members.begin(), members.end(), [&](const auto &m) {
|
||||
return m.id == id && !m.group.empty();
|
||||
});
|
||||
return std::any_of(members.begin(), members.end(), [&](const auto &m) {
|
||||
return m.id == id && m.group == *group;
|
||||
});
|
||||
}
|
||||
size_t AddMany(const std::vector<std::string> &ids,
|
||||
const std::string &group = {}) {
|
||||
size_t added = 0;
|
||||
for (const auto &id : ids) {
|
||||
// Without a target group, an existing membership already puts the device
|
||||
// on the wall. An explicit group may reuse that same device/session.
|
||||
if (group.empty() && wall_ids_.count(id))
|
||||
continue;
|
||||
if (Add(id, group))
|
||||
++added;
|
||||
}
|
||||
return added;
|
||||
}
|
||||
// Both editors replace the same group assignments without changing wall
|
||||
// enrollment. Keep the position of devices already on the wall untouched.
|
||||
bool SetGroups(const std::string &id, const std::vector<std::string> &names) {
|
||||
if (!ValidId(id))
|
||||
return false;
|
||||
std::vector<Member> replacements;
|
||||
std::set<std::string> seen;
|
||||
for (const auto &name : names)
|
||||
if (!name.empty() && seen.insert(name).second)
|
||||
replacements.push_back({id, name});
|
||||
if (replacements.empty())
|
||||
replacements.push_back({id, ""});
|
||||
std::vector<Member> updated;
|
||||
bool inserted = false;
|
||||
for (const auto &member : members) {
|
||||
if (member.id != id) {
|
||||
updated.push_back(member);
|
||||
} else if (!inserted) {
|
||||
updated.insert(updated.end(), replacements.begin(), replacements.end());
|
||||
inserted = true;
|
||||
}
|
||||
}
|
||||
if (!inserted)
|
||||
updated.insert(updated.end(), replacements.begin(), replacements.end());
|
||||
members = std::move(updated);
|
||||
for (const auto &member : replacements)
|
||||
if (!member.group.empty() &&
|
||||
std::find(groups.begin(), groups.end(), member.group) == groups.end())
|
||||
groups.push_back(member.group);
|
||||
PruneGroups();
|
||||
return true;
|
||||
}
|
||||
void Remove(const std::string &id, const std::string &group = {}) {
|
||||
if (group.empty()) {
|
||||
// Removing from the wall leaves history's group assignments intact.
|
||||
wall_ids_.erase(id);
|
||||
std::erase(device_order_, id);
|
||||
} else if (MatchesGroup(id, group)) {
|
||||
// Removing the last named group leaves an ungrouped wall member.
|
||||
// Reuse the editor path so enrollment and card order stay unchanged.
|
||||
std::vector<std::string> remaining;
|
||||
for (const auto &member : members)
|
||||
if (member.id == id && member.group != group)
|
||||
remaining.push_back(member.group);
|
||||
SetGroups(id, remaining);
|
||||
}
|
||||
selected.erase(id);
|
||||
}
|
||||
void ResizePage(int new_capacity, int count) {
|
||||
const int first = page * capacity;
|
||||
capacity = std::max(1, new_capacity);
|
||||
page = std::clamp(first / capacity, 0, std::max(0, (count - 1) / capacity));
|
||||
}
|
||||
// The caller supplies every ID in the current filter, across all pages.
|
||||
void ToggleSelectAll(const std::vector<std::string> &ids) {
|
||||
std::set<std::string> targets(ids.begin(), ids.end());
|
||||
if (selected == targets)
|
||||
selected.clear();
|
||||
else
|
||||
selected = std::move(targets);
|
||||
}
|
||||
bool Load(const std::filesystem::path &path) {
|
||||
try {
|
||||
if (!std::filesystem::exists(path))
|
||||
return true;
|
||||
std::ifstream file(path);
|
||||
const auto doc = nlohmann::json::parse(file);
|
||||
const int version = doc.at("version").get<int>();
|
||||
if ((version != 1 && version != 2) || !doc.at("members").is_array())
|
||||
return false;
|
||||
if (version == 2 && !doc.at("wall_ids").is_array())
|
||||
return false;
|
||||
Workspace loaded;
|
||||
if (doc.contains("stream_settings"))
|
||||
loaded.stream_settings = StreamSettings::FromJson(doc["stream_settings"]);
|
||||
for (const auto &member : doc.at("members")) {
|
||||
const auto id = member.at("id").get<std::string>();
|
||||
loaded.AddAssignment(id, member.value("group", ""));
|
||||
// Every saved member in the old format was already on the wall.
|
||||
if (version == 1 && ValidId(id))
|
||||
loaded.wall_ids_.insert(id);
|
||||
}
|
||||
if (version == 2)
|
||||
for (const auto &value : doc.at("wall_ids")) {
|
||||
const auto id = value.get<std::string>();
|
||||
if (ValidId(id) && loaded.HasAssignments(id))
|
||||
loaded.wall_ids_.insert(id);
|
||||
}
|
||||
if (doc.contains("device_order") && doc["device_order"].is_array()) {
|
||||
std::set<std::string> seen;
|
||||
for (const auto &value : doc["device_order"]) {
|
||||
if (!value.is_string()) continue;
|
||||
const auto id = value.get<std::string>();
|
||||
if (ValidId(id) && seen.insert(id).second)
|
||||
loaded.device_order_.push_back(id);
|
||||
}
|
||||
}
|
||||
members = std::move(loaded.members);
|
||||
groups = std::move(loaded.groups);
|
||||
wall_ids_ = std::move(loaded.wall_ids_);
|
||||
device_order_ = std::move(loaded.device_order_);
|
||||
stream_settings = loaded.stream_settings;
|
||||
return true;
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
bool Save(const std::filesystem::path &path) const {
|
||||
try {
|
||||
nlohmann::json doc{{"version", 2},
|
||||
{"members", nlohmann::json::array()},
|
||||
{"wall_ids", wall_ids_},
|
||||
{"device_order", device_order_},
|
||||
{"stream_settings", stream_settings.ToJson()}};
|
||||
for (const auto &m : members)
|
||||
doc["members"].push_back({{"id", m.id}, {"group", m.group}});
|
||||
return WriteAtomically(path, doc.dump(2));
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::set<std::string> wall_ids_;
|
||||
std::vector<std::string> device_order_;
|
||||
|
||||
bool HasAssignments(const std::string &id) const {
|
||||
return std::any_of(members.begin(), members.end(),
|
||||
[&](const auto &m) { return m.id == id; });
|
||||
}
|
||||
bool AddAssignment(const std::string &id, const std::string &group) {
|
||||
if (!ValidId(id))
|
||||
return false;
|
||||
if (std::any_of(members.begin(), members.end(), [&](const auto &m) {
|
||||
return m.id == id && m.group == group;
|
||||
}))
|
||||
return false;
|
||||
if (!group.empty() &&
|
||||
std::find(groups.begin(), groups.end(), group) == groups.end())
|
||||
groups.push_back(group);
|
||||
members.push_back({id, group});
|
||||
return true;
|
||||
}
|
||||
void PruneGroups() {
|
||||
groups.erase(std::remove_if(groups.begin(), groups.end(),
|
||||
[&](const auto &name) {
|
||||
return std::none_of(members.begin(),
|
||||
members.end(),
|
||||
[&](const auto &m) {
|
||||
return m.group == name;
|
||||
});
|
||||
}),
|
||||
groups.end());
|
||||
}
|
||||
};
|
||||
} // namespace crossdesk::gallery
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-13
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PREVIEW_BANDWIDTH_H_
|
||||
#define _PREVIEW_BANDWIDTH_H_
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
namespace crossdesk::gallery {
|
||||
struct PreviewBandwidthDemand {
|
||||
int desired_bps = 0;
|
||||
bool foreground = false;
|
||||
|
||||
bool operator==(const PreviewBandwidthDemand& other) const {
|
||||
return desired_bps == other.desired_bps && foreground == other.foreground;
|
||||
}
|
||||
|
||||
static int Estimate(int width, int height, int fps) {
|
||||
// A demand ceiling, not a throughput measurement. Include room for video
|
||||
// repair traffic; the sender's congestion control may allocate less.
|
||||
const int64_t pixels = width > 0 && height > 0
|
||||
? int64_t(width) * height : 3840LL * 2160;
|
||||
const int64_t estimate = pixels * std::clamp(fps, 1, 60) * 15 / 100;
|
||||
return int(std::clamp<int64_t>((estimate + 49'999) / 50'000 * 50'000,
|
||||
150'000, 20'000'000));
|
||||
}
|
||||
};
|
||||
|
||||
inline std::vector<int> AllocatePreviewBandwidth(
|
||||
const std::vector<PreviewBandwidthDemand>& demands, int budget_bps) {
|
||||
std::vector<int> result(demands.size(), 0);
|
||||
int remaining = std::max(0, budget_bps);
|
||||
int active = 0;
|
||||
int64_t desired_total = 0;
|
||||
for (const auto& demand : demands) {
|
||||
active += demand.desired_bps > 0;
|
||||
desired_total += std::max(0, demand.desired_bps);
|
||||
}
|
||||
if (!active || !remaining) return result;
|
||||
if (desired_total <= remaining) {
|
||||
for (std::size_t i = 0; i < demands.size(); ++i)
|
||||
result[i] = std::max(0, demands[i].desired_bps);
|
||||
return result;
|
||||
}
|
||||
// First preserve a small fair share for every visible device, then perform
|
||||
// weighted max-min allocation. Satisfied devices return unused capacity.
|
||||
const int baseline = std::min(100'000, remaining / active);
|
||||
for (std::size_t i = 0; i < demands.size(); ++i) {
|
||||
result[i] = std::min(std::max(0, demands[i].desired_bps), baseline);
|
||||
remaining -= result[i];
|
||||
}
|
||||
while (remaining > 0) {
|
||||
int weights = 0;
|
||||
for (std::size_t i = 0; i < demands.size(); ++i)
|
||||
if (result[i] < demands[i].desired_bps)
|
||||
weights += demands[i].foreground ? 4 : 1;
|
||||
if (!weights) break;
|
||||
const int available = remaining;
|
||||
for (std::size_t i = 0; i < demands.size() && remaining > 0; ++i) {
|
||||
if (result[i] >= demands[i].desired_bps) continue;
|
||||
const int share = int(int64_t(available) *
|
||||
(demands[i].foreground ? 4 : 1) / weights);
|
||||
const int extra = std::min({remaining, demands[i].desired_bps - result[i],
|
||||
std::max(1, share)});
|
||||
result[i] += extra;
|
||||
remaining -= extra;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// UI refreshes much more often than video demand changes. Keep the previous
|
||||
// result while membership, dimensions, cadence, priority and budget are stable.
|
||||
class PreviewBandwidthAllocator {
|
||||
public:
|
||||
const std::vector<int>& Allocate(
|
||||
const std::vector<PreviewBandwidthDemand>& demands, int budget_bps) {
|
||||
if (budget_bps_ != budget_bps || demands_ != demands) {
|
||||
demands_ = demands;
|
||||
budget_bps_ = budget_bps;
|
||||
allocations_ = AllocatePreviewBandwidth(demands, budget_bps);
|
||||
}
|
||||
return allocations_;
|
||||
}
|
||||
|
||||
private:
|
||||
int budget_bps_ = -1;
|
||||
std::vector<PreviewBandwidthDemand> demands_;
|
||||
std::vector<int> allocations_;
|
||||
};
|
||||
} // namespace crossdesk::gallery
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-12
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PREVIEW_RESOLUTION_H_
|
||||
#define _PREVIEW_RESOLUTION_H_
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
|
||||
namespace crossdesk::gallery {
|
||||
struct PreviewResolution {
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
|
||||
bool operator==(const PreviewResolution& other) const {
|
||||
return width == other.width && height == other.height;
|
||||
}
|
||||
static PreviewResolution Viewport(float width, float height, float scale) {
|
||||
if (!std::isfinite(width) || !std::isfinite(height) ||
|
||||
!std::isfinite(scale) || width <= 0 || height <= 0 || scale <= 0)
|
||||
return {};
|
||||
return {int(std::clamp(std::ceil(double(width) * scale), 2.0, 16384.0)),
|
||||
int(std::clamp(std::ceil(double(height) * scale), 2.0, 16384.0))};
|
||||
}
|
||||
};
|
||||
|
||||
class PreviewResolutionDebouncer {
|
||||
public:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
PreviewResolution Update(PreviewResolution desired, Clock::time_point now,
|
||||
bool reset = false) {
|
||||
if (!initialized_ || reset) {
|
||||
initialized_ = true;
|
||||
applied_ = candidate_ = desired;
|
||||
changed_at_ = now;
|
||||
} else if (!(candidate_ == desired)) {
|
||||
candidate_ = desired;
|
||||
changed_at_ = now;
|
||||
} else if (now - changed_at_ >= std::chrono::milliseconds(200)) {
|
||||
applied_ = candidate_;
|
||||
}
|
||||
return applied_;
|
||||
}
|
||||
|
||||
private:
|
||||
bool initialized_ = false;
|
||||
PreviewResolution applied_, candidate_;
|
||||
Clock::time_point changed_at_{};
|
||||
};
|
||||
} // namespace crossdesk::gallery
|
||||
#endif
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-09
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _CAPTURED_KEYBOARD_QUEUE_H_
|
||||
#define _CAPTURED_KEYBOARD_QUEUE_H_
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
#include "keyboard_state.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
class CapturedKeyboardQueue {
|
||||
public:
|
||||
struct Batch {
|
||||
std::vector<KeyboardInput> events;
|
||||
bool resync = false;
|
||||
PressedKeys pressed;
|
||||
};
|
||||
|
||||
void Push(const KeyboardInput& input) {
|
||||
std::lock_guard lock(mutex_);
|
||||
if (input.is_down)
|
||||
pressed_[input.key_code] =
|
||||
{input.key_code, input.scan_code, input.extended};
|
||||
else
|
||||
pressed_.erase(input.key_code);
|
||||
|
||||
if (resync_) return;
|
||||
if (count_ == kCapacity) {
|
||||
// The event history is incomplete. Retain the authoritative state,
|
||||
// including releases, rather than dropping arbitrary key edges.
|
||||
count_ = 0;
|
||||
resync_ = true;
|
||||
return;
|
||||
}
|
||||
events_[count_++] = input;
|
||||
}
|
||||
|
||||
Batch Drain() {
|
||||
std::lock_guard lock(mutex_);
|
||||
Batch batch;
|
||||
batch.resync = resync_;
|
||||
if (resync_) batch.pressed = pressed_;
|
||||
else batch.events.assign(events_.begin(), events_.begin() + count_);
|
||||
count_ = 0;
|
||||
resync_ = false;
|
||||
return batch;
|
||||
}
|
||||
|
||||
void Clear() {
|
||||
std::lock_guard lock(mutex_);
|
||||
count_ = 0;
|
||||
resync_ = false;
|
||||
pressed_.clear();
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr size_t kCapacity = 512;
|
||||
std::mutex mutex_;
|
||||
std::array<KeyboardInput, kCapacity> events_{};
|
||||
size_t count_ = 0;
|
||||
bool resync_ = false;
|
||||
PressedKeys pressed_;
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -8,7 +8,7 @@
|
||||
#include <mutex>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "minirtc.h"
|
||||
@@ -16,8 +16,10 @@
|
||||
#include "runtime/gui_runtime.h"
|
||||
#include "windows_key_metadata.h"
|
||||
#if _WIN32
|
||||
#include "interactive_state.h"
|
||||
#include "desktop_transition_policy.h"
|
||||
#include "interactive_desktop.h"
|
||||
#include "service_host.h"
|
||||
#include "unattended_config.h"
|
||||
#endif
|
||||
|
||||
namespace crossdesk {
|
||||
@@ -25,6 +27,7 @@ namespace {
|
||||
|
||||
constexpr uint32_t kHeartbeatIntervalMs = 500;
|
||||
constexpr uint32_t kRemoteReleaseTimeoutMs = 2500;
|
||||
constexpr uint32_t kReleaseRetryIntervalMs = 250;
|
||||
|
||||
int NormalizeWindowsModifierVk(int key_code, uint32_t scan_code,
|
||||
bool extended) {
|
||||
@@ -82,12 +85,11 @@ void LogSecureDesktopInputBlocked(uint32_t* last_tick, const char* stage) {
|
||||
}
|
||||
|
||||
bool IsTransientSecureDesktopInputFailure(const nlohmann::json& response,
|
||||
const RemoteAction& action) {
|
||||
bool is_down) {
|
||||
return response.is_object() &&
|
||||
response.value("error", std::string()) == "send_input_failed" &&
|
||||
response.value("code", 0u) == ERROR_ACCESS_DENIED &&
|
||||
action.type == ControlType::keyboard &&
|
||||
action.k.flag == KeyFlag::key_up;
|
||||
!is_down;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -99,29 +101,38 @@ void KeyboardController::TrackPressedKey(int key_code, bool is_down,
|
||||
uint32_t scan_code, bool extended) {
|
||||
std::lock_guard<std::mutex> lock(pressed_keys_mutex_);
|
||||
if (is_down) {
|
||||
pressed_keys_[key_code] = PressedKey{key_code, scan_code, extended};
|
||||
pressed_keys_[key_code] = KeyboardKey{key_code, scan_code, extended};
|
||||
} else {
|
||||
pressed_keys_.erase(key_code);
|
||||
}
|
||||
}
|
||||
|
||||
void KeyboardController::ForceReleasePressedKeys() {
|
||||
std::vector<PressedKey> pressed_keys;
|
||||
PressedKeys pressed_keys;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pressed_keys_mutex_);
|
||||
pressed_keys.reserve(pressed_keys_.size());
|
||||
for (const auto& [_, key] : pressed_keys_) {
|
||||
pressed_keys.push_back(key);
|
||||
}
|
||||
pressed_keys_.clear();
|
||||
pressed_keys.swap(pressed_keys_);
|
||||
}
|
||||
|
||||
for (const PressedKey& key : pressed_keys) {
|
||||
for (const auto& [_, key] : pressed_keys) {
|
||||
SendKeyCommand(key.key_code, false, key.scan_code, key.extended);
|
||||
}
|
||||
SendHeartbeat(true);
|
||||
}
|
||||
|
||||
void KeyboardController::RecoverCapturedState(const PressedKeys& pressed) {
|
||||
std::vector<KeyboardInput> changes;
|
||||
{
|
||||
std::lock_guard lock(pressed_keys_mutex_);
|
||||
changes = ReconcileKeyboardState(pressed_keys_, pressed);
|
||||
}
|
||||
for (const auto& event : changes) {
|
||||
SendKeyCommand(event.key_code, event.is_down, event.scan_code,
|
||||
event.extended);
|
||||
}
|
||||
SendHeartbeat(true);
|
||||
}
|
||||
|
||||
void KeyboardController::SendHeartbeat(bool force) {
|
||||
const uint32_t now = static_cast<uint32_t>(SDL_GetTicks());
|
||||
if (!force && now - last_heartbeat_tick_ < kHeartbeatIntervalMs) {
|
||||
@@ -149,27 +160,7 @@ void KeyboardController::SendHeartbeat(bool force) {
|
||||
action.ks.pressed_count = index;
|
||||
}
|
||||
|
||||
const std::string target_id = owner_.controlled_remote_id_.empty()
|
||||
? owner_.focused_remote_id_
|
||||
: owner_.controlled_remote_id_;
|
||||
std::shared_lock sessions_lock(owner_.remote_sessions_mutex_);
|
||||
const auto props_it = owner_.remote_sessions_.find(target_id);
|
||||
if (target_id.empty() || props_it == owner_.remote_sessions_.end() ||
|
||||
props_it->second->connection_status_.load() !=
|
||||
ConnectionStatus::Connected ||
|
||||
!props_it->second->peer_) {
|
||||
last_heartbeat_tick_ = now;
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string message = action.to_json();
|
||||
const int result = SendReliableDataFrame(
|
||||
props_it->second->peer_, message.c_str(), message.size(),
|
||||
props_it->second->keyboard_label_.c_str());
|
||||
if (result != 0) {
|
||||
LOG_WARN("Send keyboard heartbeat failed, remote_id={}, ret={}", target_id,
|
||||
result);
|
||||
}
|
||||
owner_.SendRemoteInput(action);
|
||||
last_heartbeat_tick_ = now;
|
||||
}
|
||||
|
||||
@@ -189,24 +180,7 @@ int KeyboardController::SendKeyCommand(int key_code, bool is_down,
|
||||
action.k.scan_code = scan_code;
|
||||
action.k.extended = extended;
|
||||
|
||||
const std::string target_id = owner_.controlled_remote_id_.empty()
|
||||
? owner_.focused_remote_id_
|
||||
: owner_.controlled_remote_id_;
|
||||
std::shared_lock sessions_lock(owner_.remote_sessions_mutex_);
|
||||
const auto props_it = owner_.remote_sessions_.find(target_id);
|
||||
if (!target_id.empty() && props_it != owner_.remote_sessions_.end() &&
|
||||
props_it->second->connection_status_.load() ==
|
||||
ConnectionStatus::Connected &&
|
||||
props_it->second->peer_) {
|
||||
const std::string message = action.to_json();
|
||||
const int result = SendReliableDataFrame(
|
||||
props_it->second->peer_, message.c_str(), message.size(),
|
||||
props_it->second->keyboard_label_.c_str());
|
||||
if (result != 0) {
|
||||
LOG_WARN("Send keyboard command failed, remote_id={}, ret={}", target_id,
|
||||
result);
|
||||
}
|
||||
}
|
||||
owner_.SendRemoteInput(action);
|
||||
|
||||
TrackPressedKey(key_code, is_down, scan_code, extended);
|
||||
return 0;
|
||||
@@ -216,59 +190,79 @@ bool KeyboardController::InjectRemoteKey(int key_code, bool is_down,
|
||||
uint32_t scan_code, bool extended) {
|
||||
#if _WIN32
|
||||
if (owner_.privacy_.Engaged() && !IsWindowsPrivacyDesktopAvailable()) {
|
||||
owner_.privacy_.Fail("Secure desktop or locked session; privacy screen will turn off");
|
||||
owner_.privacy_.SuspendForDesktop();
|
||||
}
|
||||
if (owner_.local_service_status_received_ &&
|
||||
IsSecureDesktopInteractionRequired(owner_.local_interactive_stage_)) {
|
||||
const std::string response = SendCrossDeskSecureDesktopKeyInput(
|
||||
key_code, is_down, scan_code, extended, 1000);
|
||||
const auto json = nlohmann::json::parse(response, nullptr, false);
|
||||
if (json.is_discarded() || !json.value("ok", false)) {
|
||||
RemoteAction action{};
|
||||
action.type = ControlType::keyboard;
|
||||
action.k.key_value = static_cast<size_t>(key_code);
|
||||
action.k.scan_code = scan_code;
|
||||
action.k.extended = extended;
|
||||
action.k.flag = is_down ? KeyFlag::key_down : KeyFlag::key_up;
|
||||
if (!json.is_discarded() &&
|
||||
IsTransientSecureDesktopInputFailure(json, action)) {
|
||||
LOG_INFO(
|
||||
"Secure desktop keyboard injection transient failure, "
|
||||
"key_code={}, is_down={}, response={}",
|
||||
key_code, is_down, response);
|
||||
return true;
|
||||
}
|
||||
if (owner_.is_server_mode_ || !owner_.WindowsInputStage().empty()) {
|
||||
static const bool process_elevated = IsAdministratorProcess();
|
||||
return DispatchDesktopInput(
|
||||
[&] {
|
||||
return PreferUserDesktopInput(IsCurrentSessionUserDesktopActive(),
|
||||
owner_.windows_consent_ui_.load(),
|
||||
owner_.local_service_available_.load(),
|
||||
process_elevated);
|
||||
},
|
||||
[&] {
|
||||
SetLastError(ERROR_SUCCESS);
|
||||
const bool sent = owner_.devices_.SendKeyboardCommand(
|
||||
key_code, is_down, scan_code, extended);
|
||||
const DWORD error = GetLastError();
|
||||
const bool blocked =
|
||||
error == ERROR_ACCESS_DENIED || error == ERROR_GEN_FAILURE;
|
||||
return DesktopInputResult{
|
||||
sent, IsDesktopTransitionInputError(error) || blocked, blocked};
|
||||
},
|
||||
[&]() -> DesktopInputResult {
|
||||
const std::string response = SendCrossDeskSecureDesktopKeyInput(
|
||||
key_code, is_down, scan_code, extended, 1000);
|
||||
const auto json = nlohmann::json::parse(response, nullptr, false);
|
||||
if (!json.is_object() || !json.value("ok", false)) {
|
||||
const std::string error =
|
||||
json.is_object() ? json.value("error", "") : "";
|
||||
if (IsDesktopInputSetupPending(error)) {
|
||||
return {false, true};
|
||||
}
|
||||
if (IsTransientSecureDesktopInputFailure(json, is_down)) {
|
||||
LOG_INFO(
|
||||
"Secure desktop keyboard injection transient failure, "
|
||||
"key_code={}, is_down={}, response={}",
|
||||
key_code, is_down, response);
|
||||
// The release was not injected. Keep it tracked so cleanup can
|
||||
// retry on the ordinary desktop after the transition.
|
||||
return {false, false};
|
||||
}
|
||||
|
||||
LogSecureDesktopInputBlocked(
|
||||
&owner_.last_local_secure_input_block_log_tick_,
|
||||
owner_.local_interactive_stage_.c_str());
|
||||
LOG_WARN(
|
||||
"Secure desktop keyboard injection failed, key_code={}, is_down={}, "
|
||||
"response={}",
|
||||
key_code, is_down, response);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
LogSecureDesktopInputBlocked(
|
||||
&owner_.last_local_secure_input_block_log_tick_,
|
||||
owner_.WindowsInputStage().c_str());
|
||||
LOG_WARN(
|
||||
"Secure desktop keyboard injection failed, key_code={}, "
|
||||
"is_down={}, "
|
||||
"response={}",
|
||||
key_code, is_down, response);
|
||||
return {};
|
||||
}
|
||||
return {true, false};
|
||||
});
|
||||
}
|
||||
#endif
|
||||
// Recheck after the desktop query; key-up cleanup remains allowed while paused.
|
||||
return owner_.devices_.SendKeyboardCommand(key_code, is_down, scan_code,
|
||||
extended);
|
||||
}
|
||||
|
||||
void KeyboardController::ApplyRemoteEvent(const std::string& remote_id,
|
||||
const RemoteAction& action) {
|
||||
std::lock_guard input_lock(remote_input_mutex_);
|
||||
const int key_code = static_cast<int>(action.k.key_value);
|
||||
const bool is_down = action.k.flag == KeyFlag::key_down;
|
||||
const bool injected =
|
||||
InjectRemoteKey(key_code, is_down, action.k.scan_code, action.k.extended);
|
||||
if (injected) pending_key_releases_.erase(key_code);
|
||||
|
||||
std::lock_guard<std::mutex> lock(remote_states_mutex_);
|
||||
auto& state = remote_states_[remote_id];
|
||||
state.last_seen_tick = static_cast<uint32_t>(SDL_GetTicks());
|
||||
if (is_down && injected) {
|
||||
state.pressed_keys[key_code] =
|
||||
PressedKey{key_code, action.k.scan_code, action.k.extended};
|
||||
KeyboardKey{key_code, action.k.scan_code, action.k.extended};
|
||||
} else if (!is_down && injected) {
|
||||
state.pressed_keys.erase(key_code);
|
||||
}
|
||||
@@ -276,136 +270,117 @@ void KeyboardController::ApplyRemoteEvent(const std::string& remote_id,
|
||||
|
||||
void KeyboardController::ApplyRemoteState(const std::string& remote_id,
|
||||
const RemoteAction& action) {
|
||||
std::vector<PressedKey> keys_to_release;
|
||||
std::vector<PressedKey> keys_to_press;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(remote_states_mutex_);
|
||||
auto& state = remote_states_[remote_id];
|
||||
if (action.ks.seq != 0 && state.last_seq != 0 &&
|
||||
static_cast<int32_t>(action.ks.seq - state.last_seq) <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.last_seq = action.ks.seq;
|
||||
state.last_seen_tick = static_cast<uint32_t>(SDL_GetTicks());
|
||||
state.keyboard_state_seen = true;
|
||||
|
||||
std::unordered_map<int, PressedKey> desired_keys;
|
||||
const size_t count =
|
||||
(std::min)(action.ks.pressed_count, kMaxKeyboardStateKeys);
|
||||
for (size_t index = 0; index < count; ++index) {
|
||||
const auto& key = action.ks.pressed_keys[index];
|
||||
const int key_code = static_cast<int>(key.key_value);
|
||||
desired_keys[key_code] =
|
||||
PressedKey{key_code, key.scan_code, key.extended};
|
||||
}
|
||||
for (const auto& [key_code, key] : state.pressed_keys) {
|
||||
if (desired_keys.find(key_code) == desired_keys.end()) {
|
||||
keys_to_release.push_back(key);
|
||||
}
|
||||
}
|
||||
for (const auto& [key_code, key] : desired_keys) {
|
||||
if (state.pressed_keys.find(key_code) == state.pressed_keys.end()) {
|
||||
keys_to_press.push_back(key);
|
||||
}
|
||||
}
|
||||
std::lock_guard input_lock(remote_input_mutex_);
|
||||
auto& state = remote_states_[remote_id];
|
||||
if (action.ks.seq != 0 && state.last_seq != 0 &&
|
||||
static_cast<int32_t>(action.ks.seq - state.last_seq) <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const PressedKey& key : keys_to_release) {
|
||||
if (InjectRemoteKey(key.key_code, false, key.scan_code, key.extended)) {
|
||||
std::lock_guard<std::mutex> lock(remote_states_mutex_);
|
||||
const auto state_it = remote_states_.find(remote_id);
|
||||
if (state_it != remote_states_.end()) {
|
||||
state_it->second.pressed_keys.erase(key.key_code);
|
||||
}
|
||||
}
|
||||
state.last_seq = action.ks.seq;
|
||||
state.last_seen_tick = static_cast<uint32_t>(SDL_GetTicks());
|
||||
state.keyboard_state_seen = true;
|
||||
|
||||
PressedKeys desired_keys;
|
||||
const size_t count =
|
||||
(std::min)(action.ks.pressed_count, kMaxKeyboardStateKeys);
|
||||
for (size_t index = 0; index < count; ++index) {
|
||||
const auto& key = action.ks.pressed_keys[index];
|
||||
const int key_code = static_cast<int>(key.key_value);
|
||||
desired_keys[key_code] = {key_code, key.scan_code, key.extended};
|
||||
}
|
||||
for (const PressedKey& key : keys_to_press) {
|
||||
if (InjectRemoteKey(key.key_code, true, key.scan_code, key.extended)) {
|
||||
std::lock_guard<std::mutex> lock(remote_states_mutex_);
|
||||
remote_states_[remote_id].pressed_keys[key.key_code] = key;
|
||||
const auto changes = ReconcileKeyboardState(state.pressed_keys, desired_keys);
|
||||
bool can_press = true;
|
||||
for (const auto& key : changes) {
|
||||
if (key.is_down && !can_press) continue;
|
||||
if (!InjectRemoteKey(key.key_code, key.is_down, key.scan_code, key.extended)) {
|
||||
// Do not replay a shortcut with a stale/missing modifier. The next
|
||||
// heartbeat will retry from the state that was actually injected.
|
||||
can_press = false;
|
||||
continue;
|
||||
}
|
||||
pending_key_releases_.erase(key.key_code);
|
||||
if (key.is_down)
|
||||
state.pressed_keys[key.key_code] =
|
||||
{key.key_code, key.scan_code, key.extended};
|
||||
else
|
||||
state.pressed_keys.erase(key.key_code);
|
||||
}
|
||||
}
|
||||
|
||||
void KeyboardController::ReleaseRemotePressedKeys(const std::string& remote_id,
|
||||
const char* reason) {
|
||||
std::vector<PressedKey> keys_to_release;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(remote_states_mutex_);
|
||||
const auto state_it = remote_states_.find(remote_id);
|
||||
if (state_it == remote_states_.end()) {
|
||||
return;
|
||||
}
|
||||
for (const auto& [_, key] : state_it->second.pressed_keys) {
|
||||
keys_to_release.push_back(key);
|
||||
}
|
||||
remote_states_.erase(state_it);
|
||||
}
|
||||
std::lock_guard input_lock(remote_input_mutex_);
|
||||
ReleaseRemotePressedKeysLocked(remote_id, reason);
|
||||
}
|
||||
|
||||
void KeyboardController::ReleaseRemotePressedKeysLocked(
|
||||
std::string remote_id, const char* reason) {
|
||||
const auto state_it = remote_states_.find(remote_id);
|
||||
if (state_it == remote_states_.end()) return;
|
||||
auto keys_to_release = std::move(state_it->second.pressed_keys);
|
||||
remote_states_.erase(state_it);
|
||||
|
||||
if (!keys_to_release.empty()) {
|
||||
LOG_WARN("Releasing {} remote keyboard keys for remote_id={}, reason={}",
|
||||
keys_to_release.size(), remote_id, reason ? reason : "unknown");
|
||||
}
|
||||
for (const PressedKey& key : keys_to_release) {
|
||||
for (const auto& [code, key] : keys_to_release) {
|
||||
if (!InjectRemoteKey(key.key_code, false, key.scan_code, key.extended)) {
|
||||
#ifdef _WIN32
|
||||
if (owner_.privacy_.Engaged()) {
|
||||
std::lock_guard lock(remote_states_mutex_);
|
||||
pending_privacy_releases_[key.key_code] = key;
|
||||
}
|
||||
#endif
|
||||
pending_key_releases_[code] = key;
|
||||
} else {
|
||||
pending_key_releases_.erase(code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void KeyboardController::ReleaseAllRemotePressedKeys(const char* reason) {
|
||||
std::vector<std::string> remotes;
|
||||
{
|
||||
std::lock_guard lock(remote_states_mutex_);
|
||||
for (const auto& [id, state] : remote_states_) remotes.push_back(id);
|
||||
std::lock_guard input_lock(remote_input_mutex_);
|
||||
while (!remote_states_.empty())
|
||||
ReleaseRemotePressedKeysLocked(remote_states_.begin()->first, reason);
|
||||
}
|
||||
for (const auto& id : remotes) ReleaseRemotePressedKeys(id, reason);
|
||||
CheckRemoteTimeouts();
|
||||
}
|
||||
|
||||
void KeyboardController::CheckRemoteTimeouts() {
|
||||
#ifdef _WIN32
|
||||
bool pending = false;
|
||||
{
|
||||
std::lock_guard lock(remote_states_mutex_);
|
||||
pending = !pending_privacy_releases_.empty();
|
||||
}
|
||||
// A key-up rejected on the secure desktop is retained until the ordinary
|
||||
// desktop returns. Never route cleanup through the security UI helper.
|
||||
if (pending && IsWindowsPrivacyDesktopAvailable()) {
|
||||
std::unordered_map<int, PressedKey> releases;
|
||||
{
|
||||
std::lock_guard lock(remote_states_mutex_);
|
||||
releases.swap(pending_privacy_releases_);
|
||||
}
|
||||
for (const auto& [code, key] : releases) {
|
||||
if (!owner_.devices_.SendKeyboardCommand(code, false, key.scan_code, key.extended)) {
|
||||
std::lock_guard lock(remote_states_mutex_);
|
||||
pending_privacy_releases_[code] = key;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
// Do not stall the UI while a transport thread waits on desktop IPC.
|
||||
std::unique_lock input_lock(remote_input_mutex_, std::try_to_lock);
|
||||
if (!input_lock.owns_lock()) return;
|
||||
const uint32_t now = static_cast<uint32_t>(SDL_GetTicks());
|
||||
std::vector<std::string> timed_out_remotes;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(remote_states_mutex_);
|
||||
for (const auto& [remote_id, state] : remote_states_) {
|
||||
if (state.keyboard_state_seen && !state.pressed_keys.empty() &&
|
||||
state.last_seen_tick != 0 &&
|
||||
now - state.last_seen_tick > kRemoteReleaseTimeoutMs) {
|
||||
timed_out_remotes.push_back(remote_id);
|
||||
}
|
||||
// Retain failed releases in ordinary mode as well as privacy mode. Retry
|
||||
// only on the ordinary desktop, never through the security UI helper.
|
||||
if (!pending_key_releases_.empty() &&
|
||||
(last_release_retry_tick_ == 0 ||
|
||||
now - last_release_retry_tick_ >= kReleaseRetryIntervalMs)
|
||||
#ifdef _WIN32
|
||||
&& IsCurrentSessionUserDesktopActive()
|
||||
#endif
|
||||
) {
|
||||
last_release_retry_tick_ = now;
|
||||
for (auto it = pending_key_releases_.begin();
|
||||
it != pending_key_releases_.end();) {
|
||||
const auto& key = it->second;
|
||||
if (owner_.devices_.SendKeyboardCommand(
|
||||
key.key_code, false, key.scan_code, key.extended))
|
||||
it = pending_key_releases_.erase(it);
|
||||
else
|
||||
++it;
|
||||
}
|
||||
}
|
||||
for (const std::string& remote_id : timed_out_remotes) {
|
||||
ReleaseRemotePressedKeys(remote_id, "keyboard_heartbeat_timeout");
|
||||
|
||||
// Keep the timeout decision and release under the same lock, so a fresh
|
||||
// heartbeat cannot arrive between selecting a stale peer and clearing it.
|
||||
for (auto it = remote_states_.begin(); it != remote_states_.end();) {
|
||||
const auto& state = it->second;
|
||||
if (state.keyboard_state_seen && !state.pressed_keys.empty() &&
|
||||
state.last_seen_tick != 0 &&
|
||||
now - state.last_seen_tick > kRemoteReleaseTimeoutMs) {
|
||||
const auto expired = it++;
|
||||
ReleaseRemotePressedKeysLocked(expired->first, "keyboard_heartbeat_timeout");
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
#include <remote_action.h>
|
||||
|
||||
#include "device_controller.h"
|
||||
#include "keyboard_state.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
@@ -23,6 +23,7 @@ public:
|
||||
int SendKeyCommand(int key_code, bool is_down, uint32_t scan_code = 0,
|
||||
bool extended = false);
|
||||
void ForceReleasePressedKeys();
|
||||
void RecoverCapturedState(const PressedKeys& pressed);
|
||||
void SendHeartbeat(bool force);
|
||||
void ApplyRemoteEvent(const std::string &remote_id,
|
||||
const RemoteAction &remote_action);
|
||||
@@ -34,14 +35,8 @@ public:
|
||||
void CheckRemoteTimeouts();
|
||||
|
||||
private:
|
||||
struct PressedKey {
|
||||
int key_code = 0;
|
||||
uint32_t scan_code = 0;
|
||||
bool extended = false;
|
||||
};
|
||||
|
||||
struct RemoteState {
|
||||
std::unordered_map<int, PressedKey> pressed_keys;
|
||||
PressedKeys pressed_keys;
|
||||
uint32_t last_seq = 0;
|
||||
uint32_t last_seen_tick = 0;
|
||||
bool keyboard_state_seen = false;
|
||||
@@ -51,17 +46,20 @@ private:
|
||||
bool extended);
|
||||
bool InjectRemoteKey(int key_code, bool is_down, uint32_t scan_code,
|
||||
bool extended);
|
||||
// Caller holds remote_input_mutex_. Copy the id because this erases state.
|
||||
void ReleaseRemotePressedKeysLocked(std::string remote_id, const char* reason);
|
||||
|
||||
GuiRuntime &owner_;
|
||||
std::unordered_map<int, PressedKey> pressed_keys_;
|
||||
PressedKeys pressed_keys_;
|
||||
std::mutex pressed_keys_mutex_;
|
||||
uint32_t state_sequence_ = 0;
|
||||
uint32_t last_heartbeat_tick_ = 0;
|
||||
std::unordered_map<std::string, RemoteState> remote_states_;
|
||||
std::mutex remote_states_mutex_;
|
||||
#ifdef _WIN32
|
||||
std::unordered_map<int, PressedKey> pending_privacy_releases_;
|
||||
#endif
|
||||
// Guards all remote key state and serializes injection, cleanup and retries.
|
||||
std::mutex remote_input_mutex_;
|
||||
// Successful new input supersedes cleanup of an older press of that key.
|
||||
PressedKeys pending_key_releases_;
|
||||
uint32_t last_release_retry_tick_ = 0;
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
@@ -229,6 +229,13 @@ bool SettingsManager::ReadV2Locked() {
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string SettingsManager::ActiveIdentity() const {
|
||||
std::lock_guard<std::mutex> lock(cache_mutex_);
|
||||
return owner_.config_center_->IsSelfHosted()
|
||||
? cache_v2_.self_hosted_id
|
||||
: cache_v2_.client_id_with_password;
|
||||
}
|
||||
|
||||
int SettingsManager::Load() {
|
||||
std::unique_lock<std::mutex> lock(cache_mutex_);
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ public:
|
||||
|
||||
int Save();
|
||||
int Load();
|
||||
std::string ActiveIdentity() const;
|
||||
|
||||
int LoadRecentConnectionAliases();
|
||||
int SaveRecentConnectionAliases() const;
|
||||
|
||||
@@ -11,5 +11,10 @@ Render::Render() : application_(std::make_unique<GuiApplication>()) {}
|
||||
Render::~Render() = default;
|
||||
|
||||
int Render::Run() { return application_->Run(); }
|
||||
#ifdef _WIN32
|
||||
int Render::RunUnattended(void* stop_event) {
|
||||
return application_->RunUnattended(stop_event);
|
||||
}
|
||||
#endif
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
@@ -24,6 +24,9 @@ public:
|
||||
Render &operator=(const Render &) = delete;
|
||||
|
||||
int Run();
|
||||
#ifdef _WIN32
|
||||
int RunUnattended(void* stop_event);
|
||||
#endif
|
||||
|
||||
private:
|
||||
std::unique_ptr<GuiApplication> application_;
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
#ifndef _VIDEO_LATENCY_H_
|
||||
#define _VIDEO_LATENCY_H_
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
@@ -27,8 +29,20 @@ struct VideoLatencyFrame {
|
||||
uint64_t id = 0;
|
||||
Clock::time_point capture_time{};
|
||||
void MarkPresented(Clock::time_point now = Clock::now()) const;
|
||||
// GPU completion/submission are estimates: neither confirms screen display.
|
||||
void MarkEstimated(Clock::time_point now = Clock::now()) const;
|
||||
// Fallback for renderers which expose submission but no presentation time.
|
||||
void MarkSubmitted(Clock::time_point now = Clock::now()) const;
|
||||
// Translate a host-clock event, excluding any callback scheduling delay.
|
||||
static std::optional<Clock::time_point> FromHostTime(
|
||||
double event_time_s, double host_now_s,
|
||||
Clock::time_point now = Clock::now()) {
|
||||
const double age = host_now_s - event_time_s;
|
||||
if (event_time_s <= 0 || !std::isfinite(age) || age < 0 || age > 5)
|
||||
return std::nullopt;
|
||||
return now - std::chrono::duration_cast<Clock::duration>(
|
||||
std::chrono::duration<double>(age));
|
||||
}
|
||||
};
|
||||
|
||||
class VideoLatencyStats
|
||||
@@ -38,6 +52,7 @@ class VideoLatencyStats
|
||||
struct Snapshot {
|
||||
double average_ms;
|
||||
size_t samples;
|
||||
bool estimated;
|
||||
};
|
||||
|
||||
VideoLatencyFrame Frame(uint64_t captured_us, int64_t local_now_us,
|
||||
@@ -51,16 +66,28 @@ class VideoLatencyStats
|
||||
now - std::chrono::microseconds(local_now_us - captured_us)};
|
||||
}
|
||||
|
||||
void Record(const VideoLatencyFrame& frame, Clock::time_point now) {
|
||||
std::lock_guard lock(mutex_);
|
||||
// Redraws, cached snapshots and late completions must not count twice.
|
||||
if (frame.id <= last_id_) return;
|
||||
last_id_ = frame.id;
|
||||
void Record(const VideoLatencyFrame& frame, Clock::time_point now,
|
||||
bool estimated = false) {
|
||||
const double ms =
|
||||
std::chrono::duration<double, std::milli>(now - frame.capture_time)
|
||||
.count();
|
||||
if (ms < 0 || ms > 5000) return;
|
||||
samples_.push_back({now, ms});
|
||||
std::lock_guard lock(mutex_);
|
||||
if (frame.id <= last_id_) {
|
||||
// A presentation callback can arrive after GPU completion, including
|
||||
// callbacks for later frames. Upgrade its estimate without adding a
|
||||
// second sample. Never revive a pruned/reset frame or overwrite a real
|
||||
// presentation with a redraw or an estimate.
|
||||
if (estimated) return;
|
||||
auto sample = std::find_if(
|
||||
samples_.begin(), samples_.end(),
|
||||
[&](const Sample& value) { return value.id == frame.id; });
|
||||
if (sample == samples_.end() || !sample->estimated) return;
|
||||
*sample = {frame.id, now, ms, false};
|
||||
} else {
|
||||
last_id_ = frame.id;
|
||||
samples_.push_back({frame.id, now, ms, estimated});
|
||||
}
|
||||
Prune(now);
|
||||
}
|
||||
|
||||
@@ -68,11 +95,23 @@ class VideoLatencyStats
|
||||
std::lock_guard lock(mutex_);
|
||||
Prune(now);
|
||||
if (samples_.empty()) return std::nullopt;
|
||||
double sum = 0;
|
||||
double presented_sum = 0;
|
||||
double estimated_sum = 0;
|
||||
size_t presented_count = 0;
|
||||
for (const auto& sample : samples_) {
|
||||
sum += sample.ms;
|
||||
if (sample.estimated) {
|
||||
estimated_sum += sample.ms;
|
||||
} else {
|
||||
presented_sum += sample.ms;
|
||||
++presented_count;
|
||||
}
|
||||
}
|
||||
return Snapshot{sum / samples_.size(), samples_.size()};
|
||||
// Prefer actual presentations in the rolling window. Do not mix GPU and
|
||||
// screen endpoints, or let the newest not-yet-presented frame force an
|
||||
// otherwise precise measurement to be labelled approximate.
|
||||
if (presented_count != 0)
|
||||
return Snapshot{presented_sum / presented_count, presented_count, false};
|
||||
return Snapshot{estimated_sum / samples_.size(), samples_.size(), true};
|
||||
}
|
||||
|
||||
void Reset() {
|
||||
@@ -83,14 +122,20 @@ class VideoLatencyStats
|
||||
|
||||
private:
|
||||
void Prune(Clock::time_point now) {
|
||||
while (!samples_.empty() &&
|
||||
(now - samples_.front().time > std::chrono::seconds(1) ||
|
||||
samples_.size() > 240))
|
||||
samples_.pop_front();
|
||||
// Upgrades can change timestamps out of order.
|
||||
samples_.erase(std::remove_if(samples_.begin(), samples_.end(),
|
||||
[&](const Sample& sample) {
|
||||
return now - sample.time >
|
||||
std::chrono::seconds(1);
|
||||
}),
|
||||
samples_.end());
|
||||
while (samples_.size() > 240) samples_.pop_front();
|
||||
}
|
||||
struct Sample {
|
||||
uint64_t id;
|
||||
Clock::time_point time;
|
||||
double ms;
|
||||
bool estimated;
|
||||
};
|
||||
std::mutex mutex_;
|
||||
uint64_t issued_id_ = 0;
|
||||
@@ -99,7 +144,11 @@ class VideoLatencyStats
|
||||
};
|
||||
|
||||
inline void VideoLatencyFrame::MarkSubmitted(Clock::time_point now) const {
|
||||
MarkPresented(now);
|
||||
MarkEstimated(now);
|
||||
}
|
||||
|
||||
inline void VideoLatencyFrame::MarkEstimated(Clock::time_point now) const {
|
||||
if (stats) stats->Record(*this, now, true);
|
||||
}
|
||||
|
||||
inline void VideoLatencyFrame::MarkPresented(Clock::time_point now) const {
|
||||
@@ -107,4 +156,4 @@ inline void VideoLatencyFrame::MarkPresented(Clock::time_point now) const {
|
||||
}
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
#include <set>
|
||||
#include <system_error>
|
||||
|
||||
#include "signal_server_address.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#endif
|
||||
@@ -51,9 +53,12 @@ void AnnouncementInbox::Configure(std::string host, int port,
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (directory_.empty() || host.empty() || port <= 0 || device_id.empty())
|
||||
return;
|
||||
for (auto& ch : host)
|
||||
auto address = minirtc::ParseSignalServerAddress(host);
|
||||
if (!address) return;
|
||||
for (auto& ch : address->host)
|
||||
if (ch >= 'A' && ch <= 'Z') ch += 'a' - 'A';
|
||||
if (host.back() == '.') host.pop_back();
|
||||
if (address->host.back() == '.') address->host.pop_back();
|
||||
host = address->Address();
|
||||
const auto scope = json::array({host, port, device_id}).dump();
|
||||
if (scope_ == scope) return;
|
||||
scope_ = scope;
|
||||
@@ -149,6 +154,29 @@ bool AnnouncementInbox::Read(int64_t id, int64_t revision) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
bool AnnouncementInbox::ReadAll() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (catalog_revision_ < 0) return false;
|
||||
auto updated = reads_;
|
||||
// Use the complete catalog, including announcements whose bodies have not
|
||||
// been paged in. Persist once before changing any visible reading state.
|
||||
for (const auto& [id, revision] : catalog_) {
|
||||
if (!IsDismissed(id, revision)) updated[id] = revision;
|
||||
}
|
||||
if (updated == reads_) return true;
|
||||
if (!SaveLocalState(updated, dismissed_)) {
|
||||
state_.read_save_failed = true;
|
||||
++state_.version;
|
||||
return false;
|
||||
}
|
||||
reads_ = std::move(updated);
|
||||
state_.read_save_failed = false;
|
||||
state_.delete_failed = false;
|
||||
UpdateReadingState();
|
||||
++state_.version;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AnnouncementInbox::IsDismissed(int64_t id, int64_t revision) const {
|
||||
const auto found = dismissed_.find(id);
|
||||
return found != dismissed_.end() && found->second == revision;
|
||||
|
||||
@@ -38,6 +38,7 @@ class AnnouncementInbox {
|
||||
void Refresh();
|
||||
void LoadMore();
|
||||
bool Read(int64_t id, int64_t revision);
|
||||
bool ReadAll();
|
||||
bool Dismiss(int64_t id, int64_t revision);
|
||||
nlohmann::json TakePendingRequest(std::chrono::steady_clock::time_point now =
|
||||
std::chrono::steady_clock::now());
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
#ifndef CROSSDESK_CONNECTION_AUTH_STATE_H_
|
||||
#define CROSSDESK_CONNECTION_AUTH_STATE_H_
|
||||
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
#include <string_view>
|
||||
|
||||
#include "join_failure.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// One remote session's password prompt and server-requested retry delay.
|
||||
// Signaling callbacks and the UI access a single synchronized snapshot.
|
||||
class ConnectionAuthState {
|
||||
public:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
struct Snapshot {
|
||||
bool password_required = false;
|
||||
bool validating = false;
|
||||
bool incorrect_password = false;
|
||||
minirtc::JoinFailureKind error = minirtc::JoinFailureKind::Unknown;
|
||||
int retry_after = 0;
|
||||
};
|
||||
|
||||
bool Begin(std::string_view password, Clock::time_point now = Clock::now()) {
|
||||
std::lock_guard lock(mutex_);
|
||||
if (retry_at_ > now) return false;
|
||||
state_ = {};
|
||||
retry_at_ = {};
|
||||
state_.password_required = password.empty();
|
||||
state_.validating = !password.empty();
|
||||
return state_.validating;
|
||||
}
|
||||
|
||||
void Rejected(const nlohmann::json& reply,
|
||||
Clock::time_point now = Clock::now()) {
|
||||
const auto failure = minirtc::ParseJoinFailure(reply);
|
||||
std::lock_guard lock(mutex_);
|
||||
state_ = {};
|
||||
state_.error = failure.kind;
|
||||
state_.incorrect_password =
|
||||
failure.kind == minirtc::JoinFailureKind::AuthenticationFailed;
|
||||
state_.password_required =
|
||||
state_.incorrect_password ||
|
||||
failure.kind == minirtc::JoinFailureKind::PasswordRequired;
|
||||
retry_at_ = now + std::chrono::seconds(failure.retry_after);
|
||||
}
|
||||
|
||||
void Complete() {
|
||||
std::lock_guard lock(mutex_);
|
||||
state_.validating = false;
|
||||
}
|
||||
|
||||
Snapshot Get(Clock::time_point now = Clock::now()) const {
|
||||
std::lock_guard lock(mutex_);
|
||||
auto snapshot = state_;
|
||||
if (retry_at_ > now) {
|
||||
snapshot.retry_after = static_cast<int>(
|
||||
std::chrono::ceil<std::chrono::seconds>(retry_at_ - now).count());
|
||||
}
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
private:
|
||||
mutable std::mutex mutex_;
|
||||
Snapshot state_;
|
||||
Clock::time_point retry_at_{};
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -35,6 +35,30 @@ bool GuiRuntime::HasActiveSession() {
|
||||
});
|
||||
}
|
||||
|
||||
void GuiRuntime::MuteRemoteAudio(const std::shared_ptr<RemoteSession>& props) {
|
||||
if (!props) return;
|
||||
std::lock_guard delivery_lock(audio_delivery_mutex_);
|
||||
props->audio_capture_button_pressed_ = false;
|
||||
props->audio_allowed_ = false;
|
||||
devices_.ClearAudio(props->remote_id_);
|
||||
// Capable peers stop sending to this controller on the next subscription;
|
||||
// old peers remain muted by the local receive gate above.
|
||||
props->preview_needs_sync_ = true;
|
||||
}
|
||||
|
||||
void GuiRuntime::UnmuteRemoteAudio(const std::shared_ptr<RemoteSession>& props) {
|
||||
if (!props || props->closing_) return;
|
||||
props->audio_capture_button_pressed_ = true;
|
||||
props->preview_needs_sync_ = true;
|
||||
// Also resume capture on old peers, or after a legacy controller stopped it.
|
||||
RemoteAction action{};
|
||||
action.type = ControlType::audio_capture;
|
||||
action.a = true;
|
||||
const auto message = action.to_json();
|
||||
SendReliableDataFrame(props->peer_, message.data(), message.size(),
|
||||
props->control_data_label_.c_str());
|
||||
}
|
||||
|
||||
void GuiRuntime::HandleConnectionStatusChange() {
|
||||
if (!signal_connected_ || !peer_) {
|
||||
return;
|
||||
@@ -51,7 +75,8 @@ void GuiRuntime::HandleConnectionStatusChange() {
|
||||
}
|
||||
last_presence_request_attempt_at_ = now;
|
||||
const auto message =
|
||||
BuildDevicePresenceRequest(client_id_, recent_connection_ids_, true).dump();
|
||||
BuildDevicePresenceRequest(client_id_, recent_connection_ids_, true, {},
|
||||
gallery_presence_ids_).dump();
|
||||
if (SendSignalMessage(peer_, message.data(), message.size()) == 0) {
|
||||
next_presence_refresh_at_ = now + kPresenceRefreshInterval;
|
||||
} else {
|
||||
@@ -59,6 +84,39 @@ void GuiRuntime::HandleConnectionStatusChange() {
|
||||
}
|
||||
}
|
||||
|
||||
void GuiRuntime::HandlePendingRejoins() {
|
||||
need_to_rejoin_ = false;
|
||||
std::vector<std::shared_ptr<RemoteSession>> pending;
|
||||
{
|
||||
std::shared_lock lock(remote_sessions_mutex_);
|
||||
for (const auto& [_, props] : remote_sessions_) {
|
||||
if (props && props->rejoin_ && !props->closing_)
|
||||
pending.push_back(props);
|
||||
}
|
||||
}
|
||||
for (const auto& props : pending) {
|
||||
// Password submission already entered the validating state. Let Join
|
||||
// report its result even when this device is absent from the presence
|
||||
// cache (for example, a newly added DeskHub device). A failed presence
|
||||
// probe has no auth callback and would leave the prompt validating forever.
|
||||
ConnectTo(props->remote_id_, props->remote_password_,
|
||||
props->remember_password_, true, props->wall_managed_.load());
|
||||
}
|
||||
}
|
||||
|
||||
void GuiRuntime::CancelPendingConnection(const std::string& remote_id) {
|
||||
pending_reconnects_.erase(remote_id);
|
||||
if (auto props = FindRemoteSession(remote_id)) props->rejoin_ = false;
|
||||
std::lock_guard lock(pending_presence_probe_mutex_);
|
||||
if (pending_presence_remote_id_ != remote_id) return;
|
||||
pending_presence_probe_ = false;
|
||||
pending_presence_result_ready_ = false;
|
||||
pending_presence_online_ = false;
|
||||
pending_presence_remote_id_.clear();
|
||||
pending_presence_password_.clear();
|
||||
pending_presence_remember_password_ = false;
|
||||
}
|
||||
|
||||
void GuiRuntime::HandlePendingPresenceProbe() {
|
||||
bool has_action = false;
|
||||
bool should_connect = false;
|
||||
@@ -130,6 +188,7 @@ void GuiRuntime::HandlePresenceProbeTimeout() {
|
||||
|
||||
void GuiRuntime::HandleServerControllerDisconnected(
|
||||
const std::string& remote_id, const char* reason) {
|
||||
preview_subscriptions_.Remove(remote_id);
|
||||
keyboard_.ReleaseRemotePressedKeys(remote_id, reason);
|
||||
#ifdef _WIN32
|
||||
devices_.ReleaseRemoteMouseButtons();
|
||||
@@ -210,7 +269,8 @@ int GuiRuntime::RequestSingleDevicePresence(const std::string& remote_id,
|
||||
}
|
||||
|
||||
const auto s = BuildDevicePresenceRequest(
|
||||
client_id_, recent_connection_ids_, false, remote_id)
|
||||
client_id_, recent_connection_ids_, false, remote_id,
|
||||
gallery_presence_ids_)
|
||||
.dump();
|
||||
|
||||
int ret = SendSignalMessage(peer_, s.data(), s.size());
|
||||
@@ -227,8 +287,17 @@ int GuiRuntime::RequestSingleDevicePresence(const std::string& remote_id,
|
||||
return ret;
|
||||
}
|
||||
|
||||
int GuiRuntime::ForceSignalReconnect() {
|
||||
if (!peer_) {
|
||||
LOG_WARN("Signal reconnect requested with no connection peer");
|
||||
return -1;
|
||||
}
|
||||
return ReconnectSignal(peer_);
|
||||
}
|
||||
|
||||
void GuiRuntime::CloseRemoteSession(std::shared_ptr<RemoteSession> props) {
|
||||
if (!props || props->closing_.exchange(true)) return;
|
||||
MuteRemoteAudio(props);
|
||||
if (props->peer_events_) props->peer_events_->Deactivate();
|
||||
props->connection_established_ = false;
|
||||
props->streaming_ = false;
|
||||
@@ -308,7 +377,13 @@ void GuiRuntime::CloseServerController(const std::string& remote_id) {
|
||||
if (!peer_ || remote_id.empty() || controller_cleanup_tasks_.count(remote_id))
|
||||
return;
|
||||
controller_cleanup_tasks_[remote_id] = session_cleanup_queue_.PostTask(
|
||||
[peer = peer_, remote_id] { LeaveConnection(peer, remote_id.c_str()); });
|
||||
[peer = peer_, transmission_id = std::string(client_id_), remote_id] {
|
||||
if (DisconnectPeerConnection(peer, transmission_id.c_str(),
|
||||
remote_id.c_str()) != 0) {
|
||||
LOG_WARN("[{}] Could not queue controller disconnect notification",
|
||||
remote_id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void GuiRuntime::CloseConnectionPeer() {
|
||||
@@ -403,7 +478,8 @@ void GuiRuntime::HandleSessionCleanup() {
|
||||
recent_connection_image_save_time_ = 0;
|
||||
}
|
||||
for (const auto& [id, request] : reconnects) {
|
||||
ConnectTo(id, request.password.c_str(), request.remember_password);
|
||||
ConnectTo(id, request.password.c_str(), request.remember_password, false,
|
||||
request.background);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -433,6 +509,12 @@ void GuiRuntime::WaitForSessionCleanup() {
|
||||
void GuiRuntime::ResetRemoteSessionResources(
|
||||
std::shared_ptr<RemoteSession> props) {
|
||||
props->net_traffic_stats_.Reset();
|
||||
props->received_video_stats_.Reset();
|
||||
{
|
||||
std::lock_guard lock(props->gallery_frame_mutex_);
|
||||
props->gallery_video_latency_->Reset();
|
||||
props->gallery_frame_timing_ = {};
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(props->video_frame_mutex_);
|
||||
props->video_latency_->Reset();
|
||||
@@ -472,15 +554,28 @@ std::shared_ptr<GuiRuntime::RemoteSession> GuiRuntime::FindRemoteSession(
|
||||
}
|
||||
|
||||
int GuiRuntime::ConnectTo(const std::string& remote_id, const char* password,
|
||||
bool remember_password, bool bypass_presence_check) {
|
||||
bool remember_password, bool bypass_presence_check,
|
||||
bool background) {
|
||||
// Do not recreate a failed peer or send another probe during a server cooldown.
|
||||
if (const auto current = FindRemoteSession(remote_id);
|
||||
current && current->connection_auth_.Get().retry_after > 0) {
|
||||
if (!background) focused_remote_id_ = remote_id;
|
||||
if (!background) show_connection_status_window_ = true;
|
||||
current->rejoin_ = false;
|
||||
return 0;
|
||||
}
|
||||
if (session_cleanup_tasks_.count(remote_id)) {
|
||||
pending_reconnects_[remote_id] = {password ? password : "", remember_password};
|
||||
pending_reconnects_[remote_id] = {password ? password : "",
|
||||
remember_password, background};
|
||||
LOG_INFO("[{}] Reconnect queued until previous peer is destroyed", remote_id);
|
||||
return 0;
|
||||
}
|
||||
if (!bypass_presence_check && !device_presence_cache_.IsOnline(remote_id)) {
|
||||
int ret =
|
||||
RequestSingleDevicePresence(remote_id, password, remember_password);
|
||||
// Wall requests, including deferred reconnects, must not replace the single
|
||||
// interactive presence probe. Join reports availability for each session.
|
||||
if (!background && !bypass_presence_check &&
|
||||
!device_presence_cache_.IsOnline(remote_id)) {
|
||||
int ret = RequestSingleDevicePresence(remote_id, password,
|
||||
remember_password);
|
||||
if (ret != 0) {
|
||||
offline_warning_text_ =
|
||||
localization::device_offline[localization_language_index_];
|
||||
@@ -493,7 +588,7 @@ int GuiRuntime::ConnectTo(const std::string& remote_id, const char* password,
|
||||
}
|
||||
|
||||
LOG_INFO("Connect to [{}]", remote_id);
|
||||
focused_remote_id_ = remote_id;
|
||||
if (!background) focused_remote_id_ = remote_id;
|
||||
|
||||
auto stale = FindRemoteSession(remote_id);
|
||||
bool exists = stale != nullptr;
|
||||
@@ -523,7 +618,7 @@ int GuiRuntime::ConnectTo(const std::string& remote_id, const char* password,
|
||||
pending_reconnects_[remote_id] = {
|
||||
keep_stored_password ? std::string(stale->remote_password_)
|
||||
: std::string(password),
|
||||
remember_password};
|
||||
remember_password, background};
|
||||
CloseRemoteSession(stale);
|
||||
LOG_INFO("[{}] Reconnecting after terminal peer status {}", remote_id,
|
||||
static_cast<int>(status));
|
||||
@@ -543,6 +638,11 @@ int GuiRuntime::ConnectTo(const std::string& remote_id, const char* password,
|
||||
auto props = remote_sessions_[remote_id];
|
||||
props->local_id_ = "C-" + std::string(client_id_);
|
||||
props->remote_id_ = remote_id;
|
||||
props->wall_managed_ = background;
|
||||
props->tab_opened_ = !background;
|
||||
props->control_mouse_ = !background;
|
||||
props->enable_mouse_control_ = !background;
|
||||
props->audio_capture_button_pressed_ = !background;
|
||||
memcpy(&props->params_, ¶ms_, sizeof(Params));
|
||||
props->params_.user_id = props->local_id_.c_str();
|
||||
props->peer_events_ = std::make_shared<PeerEventHandler>(*this);
|
||||
@@ -550,7 +650,7 @@ int GuiRuntime::ConnectTo(const std::string& remote_id, const char* password,
|
||||
props->peer_ = CreatePeer(&props->params_);
|
||||
|
||||
props->connection_status_.store(ConnectionStatus::Connecting);
|
||||
show_connection_status_window_ = true;
|
||||
if (!background) show_connection_status_window_ = true;
|
||||
|
||||
if (!props->peer_) {
|
||||
LOG_INFO("Create peer [{}] instance failed", props->local_id_);
|
||||
@@ -588,19 +688,29 @@ int GuiRuntime::ConnectTo(const std::string& remote_id, const char* password,
|
||||
int ret = -1;
|
||||
auto props = FindRemoteSession(remote_id);
|
||||
if (!props || props->closing_) return -1;
|
||||
if (background) {
|
||||
// This also covers reusing a foreground connection that is awaiting auth.
|
||||
props->wall_managed_ = true;
|
||||
MuteRemoteAudio(props);
|
||||
}
|
||||
if (!props->connection_established_) {
|
||||
props->connection_status_.store(ConnectionStatus::Connecting);
|
||||
show_connection_status_window_ = true;
|
||||
if (!background) show_connection_status_window_ = true;
|
||||
|
||||
props->remember_password_ = remember_password;
|
||||
if (strcmp(password, "") != 0 &&
|
||||
if (password && *password &&
|
||||
strcmp(password, props->remote_password_) != 0) {
|
||||
strncpy(props->remote_password_, password,
|
||||
sizeof(props->remote_password_) - 1);
|
||||
props->remote_password_[sizeof(props->remote_password_) - 1] = '\0';
|
||||
}
|
||||
|
||||
std::string remote_id_with_pwd = remote_id + "@" + password;
|
||||
// Ask locally before Join; an empty-password round trip is no longer needed.
|
||||
if (!props->connection_auth_.Begin(props->remote_password_)) {
|
||||
props->rejoin_ = false;
|
||||
return 0;
|
||||
}
|
||||
props->connection_status_.store(ConnectionStatus::Connecting);
|
||||
std::string remote_id_with_pwd = remote_id + "@" + props->remote_password_;
|
||||
if (props->peer_) {
|
||||
ret = JoinConnection(props->peer_, remote_id_with_pwd.c_str());
|
||||
if (0 == ret) {
|
||||
|
||||
@@ -33,6 +33,15 @@ class CursorPresentation {
|
||||
const bool separate =
|
||||
state.render_mode == CursorRenderMode::separate ||
|
||||
(state.render_mode == CursorRenderMode::legacy && state.visible);
|
||||
system_hidden_ = state.render_mode == CursorRenderMode::hidden &&
|
||||
state.hidden_reason == CursorHiddenReason::system_hidden;
|
||||
if (separate) {
|
||||
mac_locator_allowed_ = state.shape != RemoteCursorShape::none;
|
||||
} else if (!system_hidden_) {
|
||||
// Embedded cursors and other hiding policies end the separate-cursor
|
||||
// history. A later system_hidden sample must not revive that overlay.
|
||||
mac_locator_allowed_ = false;
|
||||
}
|
||||
// Old senders cannot distinguish embedded from hidden. Only explicit
|
||||
// metadata from a new sender can establish the no-device compatibility
|
||||
// case.
|
||||
@@ -47,9 +56,21 @@ class CursorPresentation {
|
||||
|
||||
void NoteInput(uint64_t now) { last_input_ = now; }
|
||||
|
||||
RemoteCursorShape Resolve(uint64_t now) {
|
||||
RemoteCursorShape Resolve(uint64_t now, HostPlatform remote_platform) {
|
||||
if (!stale_at_) return RemoteCursorShape::default_cursor;
|
||||
|
||||
// macOS can keep its system cursor hidden after typing even while remote
|
||||
// mouse events move it. Keep a previously separate desktop locator across
|
||||
// those heartbeats; the video has no pointer to fall back to. On a new
|
||||
// connection, use an arrow until the first visible shape arrives. The
|
||||
// protocol cannot distinguish typing from other system_hidden cases;
|
||||
// restrict this policy to identified Mac hosts and stop on any explicit
|
||||
// embedded cursor or other hiding policy.
|
||||
if (remote_platform == HostPlatform::MacOS && system_hidden_ &&
|
||||
mac_locator_allowed_) {
|
||||
return last_visible_shape_;
|
||||
}
|
||||
|
||||
const bool recent_input =
|
||||
last_input_ && now - *last_input_ < kInputActivityMs;
|
||||
const bool can_recover =
|
||||
@@ -64,6 +85,8 @@ class CursorPresentation {
|
||||
|
||||
private:
|
||||
bool sample_unavailable_ = false;
|
||||
bool system_hidden_ = false;
|
||||
bool mac_locator_allowed_ = true;
|
||||
bool no_device_ = false;
|
||||
bool fallback_engaged_ = false;
|
||||
std::optional<uint64_t> stale_at_;
|
||||
@@ -74,4 +97,4 @@ class CursorPresentation {
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
@@ -33,12 +34,19 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
bool IsOnline(const std::string &device_id,
|
||||
Clock::time_point now = Clock::now()) const {
|
||||
std::optional<bool> GetOnline(const std::string &device_id,
|
||||
Clock::time_point now = Clock::now()) const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
const auto it = cache_.find(device_id);
|
||||
return signal_connected_ && it != cache_.end() && it->second.online &&
|
||||
now - it->second.updated_at < kMaxAge;
|
||||
if (!signal_connected_ || it == cache_.end() ||
|
||||
now - it->second.updated_at >= kMaxAge)
|
||||
return std::nullopt;
|
||||
return it->second.online;
|
||||
}
|
||||
|
||||
bool IsOnline(const std::string &device_id,
|
||||
Clock::time_point now = Clock::now()) const {
|
||||
return GetOnline(device_id, now).value_or(false);
|
||||
}
|
||||
|
||||
void Clear() {
|
||||
@@ -58,4 +66,4 @@ private:
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -16,22 +16,25 @@ namespace crossdesk {
|
||||
|
||||
inline nlohmann::json BuildDevicePresenceRequest(
|
||||
const std::string& client_id, const std::vector<std::string>& recent_ids,
|
||||
bool subscribe, const std::string& probe_id = {}) {
|
||||
bool subscribe, const std::string& probe_id = {},
|
||||
const std::vector<std::string>& additional_ids = {}) {
|
||||
std::vector<std::string> devices;
|
||||
for (const auto& id : recent_ids) {
|
||||
const auto append = [&](const std::string& id) {
|
||||
// Recent connection keys contain Y/N plus display settings after the ID.
|
||||
const std::string pure_id = id.substr(0, id.find_first_of("YN"));
|
||||
if (!pure_id.empty() &&
|
||||
std::find(devices.begin(), devices.end(), pure_id) == devices.end()) {
|
||||
devices.push_back(pure_id);
|
||||
}
|
||||
}
|
||||
};
|
||||
for (const auto& id : recent_ids) append(id);
|
||||
for (const auto& id : additional_ids) append(id);
|
||||
if (!probe_id.empty() &&
|
||||
std::find(devices.begin(), devices.end(), probe_id) == devices.end()) {
|
||||
devices.push_back(probe_id);
|
||||
}
|
||||
// Include recent devices even in a one-shot probe: older servers ignore
|
||||
// subscribe=false and replace their subscriptions with this device list.
|
||||
// Keep recent and wall devices even in a one-shot probe: older servers
|
||||
// ignore subscribe=false and replace subscriptions with this device list.
|
||||
return {{"type", "recent_connections_presence"},
|
||||
{"user_id", client_id},
|
||||
{"devices", devices},
|
||||
@@ -40,4 +43,4 @@ inline nlohmann::json BuildDevicePresenceRequest(
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -28,6 +28,49 @@ GuiRuntime::GuiRuntime()
|
||||
|
||||
GuiRuntime::~GuiRuntime() { WaitForSessionCleanup(); }
|
||||
|
||||
void GuiRuntime::SendRemoteInput(const RemoteAction& action) {
|
||||
const bool mouse = action.type == ControlType::mouse;
|
||||
if (!mouse && action.type != ControlType::keyboard &&
|
||||
action.type != ControlType::keyboard_state)
|
||||
return;
|
||||
const std::string& target_id = controlled_remote_id_.empty()
|
||||
? focused_remote_id_ : controlled_remote_id_;
|
||||
if (target_id.empty()) return;
|
||||
const bool group = gallery_group_control_id_ == target_id;
|
||||
const bool releasing = mouse
|
||||
? action.m.flag == MouseFlag::left_up ||
|
||||
action.m.flag == MouseFlag::right_up ||
|
||||
action.m.flag == MouseFlag::middle_up
|
||||
: action.type == ControlType::keyboard
|
||||
? action.k.flag == KeyFlag::key_up : action.ks.pressed_count == 0;
|
||||
const auto available = [](const auto& props) {
|
||||
return props && props->peer_ && !props->closing_ &&
|
||||
props->connection_status_ == ConnectionStatus::Connected;
|
||||
};
|
||||
std::shared_lock lock(remote_sessions_mutex_);
|
||||
const auto source = remote_sessions_.find(target_id);
|
||||
// A lost leader must stop new input, but its followers still need key/button
|
||||
// releases before group control is cleared by the UI.
|
||||
if (!releasing &&
|
||||
(source == remote_sessions_.end() || !available(source->second)))
|
||||
return;
|
||||
const auto message = action.to_json();
|
||||
for (const auto& [id, props] : remote_sessions_) {
|
||||
if ((!group && id != target_id) || !available(props)) continue;
|
||||
if (mouse) {
|
||||
std::lock_guard cursor_lock(props->remote_cursor_state_mutex_);
|
||||
props->cursor_presentation_.NoteInput(SDL_GetTicks());
|
||||
}
|
||||
// Reuse exactly the leader's mapped coordinates and key metadata. Neither
|
||||
// gallery filters nor the follower's preview dimensions affect input.
|
||||
const int result = SendReliableDataFrame(
|
||||
props->peer_, message.data(), message.size(),
|
||||
mouse ? props->mouse_label_.c_str() : props->keyboard_label_.c_str());
|
||||
if (result != 0)
|
||||
LOG_WARN("Send remote input failed, remote_id={}, ret={}", id, result);
|
||||
}
|
||||
}
|
||||
|
||||
int GuiRuntime::CreateConnectionPeer() {
|
||||
// Tick retries after the old peer's leave notification and socket shutdown.
|
||||
if (connection_peer_cleanup_.valid()) return 0;
|
||||
@@ -206,6 +249,35 @@ int GuiRuntime::CreateConnectionPeer() {
|
||||
}
|
||||
|
||||
void GuiRuntime::HandleRecentConnections() {
|
||||
if (thumbnail_ && session_cleanup_tasks_.empty()) {
|
||||
std::vector<std::shared_ptr<RemoteSession>> sessions;
|
||||
{
|
||||
std::shared_lock lock(remote_sessions_mutex_);
|
||||
for (const auto& [_, props] : remote_sessions_)
|
||||
if (props && !props->closing_ && props->was_connected_ &&
|
||||
props->recent_connection_dirty_.exchange(false))
|
||||
sessions.push_back(props);
|
||||
}
|
||||
for (const auto& props : sessions) {
|
||||
std::string host_name;
|
||||
HostPlatform platform;
|
||||
{
|
||||
std::lock_guard lock(props->remote_version_mutex_);
|
||||
host_name = props->remote_host_name_;
|
||||
platform = props->recent_platform_;
|
||||
}
|
||||
// Record a successful connection before a preview or host info arrives.
|
||||
// The close path still updates its final thumbnail. Remember password
|
||||
// controls only credential storage, not whether this device is listed.
|
||||
if (thumbnail_->SaveToThumbnail(
|
||||
nullptr, 0, 0, props->remote_id_, host_name,
|
||||
props->remember_password_ ? props->remote_password_ : "",
|
||||
platform) == 0)
|
||||
reload_recent_connections_ = true;
|
||||
else
|
||||
LOG_ERROR("[{}] Failed to save recent connection", props->remote_id_);
|
||||
}
|
||||
}
|
||||
if (session_cleanup_tasks_.empty() && reload_recent_connections_ && thumbnail_) {
|
||||
uint32_t now_time = SDL_GetTicks();
|
||||
if (now_time - recent_connection_image_save_time_ >= 50) {
|
||||
|
||||
@@ -51,12 +51,19 @@ class GuiRuntime : protected gui_detail::GuiState {
|
||||
|
||||
int CreateConnectionPeer();
|
||||
int ConnectTo(const std::string& remote_id, const char* password,
|
||||
bool remember_password, bool bypass_presence_check = false);
|
||||
bool remember_password, bool bypass_presence_check = false,
|
||||
bool background = false);
|
||||
// UI thread: mute this receiver without stopping audio for other controllers.
|
||||
void MuteRemoteAudio(const std::shared_ptr<RemoteSession>& props);
|
||||
void UnmuteRemoteAudio(const std::shared_ptr<RemoteSession>& props);
|
||||
int RequestSingleDevicePresence(const std::string& remote_id,
|
||||
const char* password, bool remember_password);
|
||||
int ForceSignalReconnect();
|
||||
|
||||
void HandleRecentConnections();
|
||||
void HandleConnectionStatusChange();
|
||||
void HandlePendingRejoins();
|
||||
void CancelPendingConnection(const std::string& remote_id);
|
||||
void HandlePendingPresenceProbe();
|
||||
void HandlePresenceProbeTimeout();
|
||||
bool HasActiveSession();
|
||||
@@ -80,6 +87,10 @@ class GuiRuntime : protected gui_detail::GuiState {
|
||||
void WaitForSessionCleanup();
|
||||
std::shared_ptr<RemoteSession> FindRemoteSession(
|
||||
const std::string& remote_id);
|
||||
// UI thread: send mapped mouse/keyboard input to the current control target,
|
||||
// or every connected session while that target leads DeskHub group control.
|
||||
void SendRemoteInput(const RemoteAction& action);
|
||||
std::string gallery_group_control_id_;
|
||||
|
||||
void ResetRemoteServiceStatus(RemoteSession& props);
|
||||
void ApplyRemoteServiceStatus(RemoteSession& props,
|
||||
@@ -87,6 +98,15 @@ class GuiRuntime : protected gui_detail::GuiState {
|
||||
RemoteUnlockState GetRemoteUnlockState(const RemoteSession& props) const;
|
||||
#if _WIN32
|
||||
void ResetLocalWindowsServiceState(bool clear_pending_sas);
|
||||
std::string WindowsInputStage() const {
|
||||
std::lock_guard lock(windows_input_stage_mutex_);
|
||||
return windows_input_stage_;
|
||||
}
|
||||
void PublishWindowsInputStage() {
|
||||
std::lock_guard lock(windows_input_stage_mutex_);
|
||||
windows_input_stage_ = local_service_status_received_
|
||||
? local_interactive_stage_ : std::string{};
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef __APPLE__
|
||||
@@ -100,6 +120,8 @@ class GuiRuntime : protected gui_detail::GuiState {
|
||||
#endif
|
||||
|
||||
PrivacyController privacy_;
|
||||
// Set before initializing callbacks; immutable for the process lifetime.
|
||||
bool unattended_host_ = false;
|
||||
AnnouncementInbox announcements_;
|
||||
PrivacySessionPolicy privacy_sessions_;
|
||||
std::mutex privacy_commands_mutex_;
|
||||
|
||||
@@ -24,6 +24,8 @@ class NetTrafficStatsCache {
|
||||
"Network statistics require lock-free scalar atomics");
|
||||
|
||||
public:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
void Store(const MiniRtcNetTrafficStats& stats) {
|
||||
video_inbound_stats_.Store(stats.video_inbound_stats);
|
||||
video_outbound_stats_.Store(stats.video_outbound_stats);
|
||||
@@ -36,6 +38,10 @@ class NetTrafficStatsCache {
|
||||
srtp_active_.store(stats.srtp_active, std::memory_order_relaxed);
|
||||
rtt_ms_.store(stats.rtt_ms, std::memory_order_relaxed);
|
||||
connection_latency_.Update(stats.rtt_ms);
|
||||
last_report_ms_.store(
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
Clock::now().time_since_epoch()).count(),
|
||||
std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
MiniRtcNetTrafficStats Load() const {
|
||||
@@ -65,9 +71,17 @@ class NetTrafficStatsCache {
|
||||
|
||||
void ResetLatency() { connection_latency_.Reset(); }
|
||||
|
||||
bool HasRecentReport(Clock::time_point now = Clock::now()) const {
|
||||
const auto last_report = last_report_ms_.load(std::memory_order_relaxed);
|
||||
const auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
now.time_since_epoch()).count();
|
||||
return last_report > 0 && now_ms - last_report < 3000;
|
||||
}
|
||||
|
||||
void Reset() {
|
||||
Store(MiniRtcNetTrafficStats{});
|
||||
ResetLatency();
|
||||
last_report_ms_.store(0, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -114,6 +128,7 @@ class NetTrafficStatsCache {
|
||||
OutboundStats total_outbound_stats_;
|
||||
std::atomic<bool> srtp_active_{false};
|
||||
std::atomic<double> rtt_ms_{-1};
|
||||
std::atomic<int64_t> last_report_ms_{0};
|
||||
ConnectionLatencyStats connection_latency_;
|
||||
};
|
||||
|
||||
|
||||
@@ -26,8 +26,10 @@
|
||||
#include "runtime/gui_runtime.h"
|
||||
|
||||
#if _WIN32
|
||||
#include "interactive_state.h"
|
||||
#include "desktop_transition_policy.h"
|
||||
#include "interactive_desktop.h"
|
||||
#include "service_host.h"
|
||||
#include "unattended_config.h"
|
||||
#endif
|
||||
|
||||
namespace crossdesk {
|
||||
@@ -91,6 +93,13 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
}
|
||||
|
||||
std::string source_id = std::string(src_id, src_id_size);
|
||||
// The service-owned host runs as SYSTEM. Do not expose filesystem or
|
||||
// clipboard operations in that security context.
|
||||
if (runtime->unattended_host_ &&
|
||||
(source_id == runtime->file_label_ ||
|
||||
source_id == runtime->file_feedback_label_ ||
|
||||
source_id == runtime->clipboard_label_))
|
||||
return;
|
||||
if (source_id == runtime->file_label_) {
|
||||
std::string remote_user_id = std::string(user_id, user_id_size);
|
||||
|
||||
@@ -130,11 +139,12 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
std::string remote_user_id(user_id, user_id_size);
|
||||
auto props =
|
||||
runtime->FindRemoteSession(remote_user_id);
|
||||
if (props && !props->enable_mouse_control_) {
|
||||
if (props && !props->clipboard_allowed_.load()) {
|
||||
return;
|
||||
}
|
||||
|
||||
runtime->clipboard_.QueueRemoteText(data, size);
|
||||
runtime->clipboard_.QueueRemoteText(
|
||||
data, size, props ? remote_user_id : std::string{});
|
||||
}
|
||||
return;
|
||||
} else if (source_id == runtime->file_feedback_label_) {
|
||||
@@ -142,14 +152,90 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string remote_id(user_id, user_id_size);
|
||||
std::string json_str(data, size);
|
||||
const auto preview_json =
|
||||
json_str.find("\"deskhub_preview") != std::string::npos
|
||||
? nlohmann::json::parse(json_str, nullptr, false)
|
||||
: nlohmann::json{};
|
||||
if (preview_json.is_object() &&
|
||||
preview_json.value("type", nlohmann::json{}) == "deskhub_preview") {
|
||||
if (source_id != runtime->control_data_label_ ||
|
||||
!runtime->IsAuthorizedController(remote_id))
|
||||
return;
|
||||
const auto subscription = PreviewSubscription::Parse(preview_json);
|
||||
if (!subscription) return;
|
||||
const auto previous = runtime->preview_subscriptions_.Get(remote_id);
|
||||
bool accepted = true;
|
||||
// Apply encoder quality to this controller only; other controllers retain
|
||||
// their own demand. MiniRTC owns per-peer video/audio pause state.
|
||||
if (!previous || subscription->IsNewerThan(*previous)) {
|
||||
if (subscription->fps > 0)
|
||||
accepted = UpdateVideoSettings(
|
||||
runtime->peer_, remote_id.data(), remote_id.size(),
|
||||
static_cast<VideoQuality>(subscription->quality),
|
||||
subscription->frame_rate,
|
||||
static_cast<VideoDegradationPreference>(
|
||||
subscription->EncoderPreference())) == 0;
|
||||
if (accepted && (!previous || previous->max_bitrate_bps.value_or(0) !=
|
||||
subscription->max_bitrate_bps.value_or(0)))
|
||||
accepted = UpdateVideoBitrateLimit(
|
||||
runtime->peer_, remote_id.data(), remote_id.size(),
|
||||
subscription->max_bitrate_bps.value_or(0)) == 0;
|
||||
// Rebalancing bandwidth alone must not force every device to send a
|
||||
// keyframe. The pause API requests its own keyframes on resume.
|
||||
if (accepted && (!previous || previous->width != subscription->width ||
|
||||
previous->height != subscription->height))
|
||||
accepted = UpdateVideoResolution(
|
||||
runtime->peer_, remote_id.data(), remote_id.size(),
|
||||
subscription->width, subscription->height) == 0;
|
||||
if (accepted)
|
||||
accepted = SetVideoSendPaused(runtime->peer_, remote_id.data(),
|
||||
remote_id.size(), subscription->fps == 0) == 0;
|
||||
if (accepted)
|
||||
accepted = SetAudioSendPaused(runtime->peer_, remote_id.data(),
|
||||
remote_id.size(), !subscription->audio) == 0;
|
||||
if (accepted && subscription->audio)
|
||||
runtime->devices_.StartSpeakerCapturer();
|
||||
}
|
||||
if (accepted) runtime->preview_subscriptions_.Set(remote_id, *subscription);
|
||||
const auto reply = nlohmann::json{
|
||||
{"type", "deskhub_preview_status"},
|
||||
{"version", subscription->version},
|
||||
{"request_id", subscription->request_id},
|
||||
{"accepted",
|
||||
accepted}}.dump();
|
||||
SendReliableDataFrameToPeer(runtime->peer_, reply.data(), reply.size(),
|
||||
runtime->control_data_label_.c_str(),
|
||||
remote_id.data(), remote_id.size());
|
||||
return;
|
||||
}
|
||||
if (preview_json.is_object() &&
|
||||
preview_json.value("type", nlohmann::json{}) ==
|
||||
"deskhub_preview_status") {
|
||||
if (auto props = runtime->FindRemoteSession(remote_id);
|
||||
props && source_id == props->control_data_label_) {
|
||||
try {
|
||||
if ((preview_json.at("version") == 1 ||
|
||||
preview_json.at("version") == 2) &&
|
||||
preview_json.at("request_id").is_number_unsigned() &&
|
||||
preview_json.at("request_id").get<uint64_t>() > 0 &&
|
||||
preview_json.at("request_id").get<uint64_t>() <= UINT32_MAX &&
|
||||
preview_json.at("accepted").is_boolean()) {
|
||||
props->preview_accepted_ = preview_json.at("accepted").get<bool>();
|
||||
props->preview_ack_ = preview_json.at("request_id").get<uint32_t>();
|
||||
}
|
||||
} catch (...) {
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
RemoteAction remote_action{};
|
||||
if (!remote_action.from_json(json_str)) {
|
||||
LOG_ERROR("Failed to parse RemoteAction JSON payload");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string remote_id(user_id, user_id_size);
|
||||
if (remote_action.type == ControlType::video_settings_status) {
|
||||
if (auto props = runtime->FindRemoteSession(remote_id)) {
|
||||
if (source_id != props->control_data_label_) return;
|
||||
@@ -209,6 +295,7 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
return;
|
||||
}
|
||||
if (remote_action.type == ControlType::privacy_command) {
|
||||
if (runtime->unattended_host_) return;
|
||||
if (source_id == runtime->control_data_label_)
|
||||
runtime->QueuePrivacyCommand(remote_id, remote_action.pc);
|
||||
return;
|
||||
@@ -227,7 +314,7 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
remote_action.type == ControlType::keyboard_state;
|
||||
if (!keyboard_input && runtime->privacy_.Engaged() &&
|
||||
!IsWindowsPrivacyDesktopAvailable()) {
|
||||
runtime->privacy_.Fail("Secure desktop or lock screen; privacy screen will turn off");
|
||||
runtime->privacy_.SuspendForDesktop();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -332,6 +419,12 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
if (props && source_id == props->control_data_label_) {
|
||||
std::lock_guard lock(props->video_settings_mutex_);
|
||||
const bool first_advertisement = !props->video_settings_supported_;
|
||||
props->preview_subscription_supported_ =
|
||||
remote_action.i.supports_deskhub_preview;
|
||||
props->preview_resolution_supported_ =
|
||||
remote_action.i.supports_deskhub_resolution;
|
||||
props->preview_fps15_supported_ = remote_action.i.supports_deskhub_fps15;
|
||||
props->preview_bandwidth_supported_ = remote_action.i.supports_deskhub_bandwidth;
|
||||
props->video_settings_supported_ =
|
||||
remote_action.i.supports_video_settings;
|
||||
if (first_advertisement && props->video_settings_supported_) {
|
||||
@@ -347,17 +440,21 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
}
|
||||
}
|
||||
// client mode
|
||||
if (props && props->remote_host_name_.empty()) {
|
||||
props->remote_host_name_ = std::string(remote_action.i.host_name,
|
||||
remote_action.i.host_name_size);
|
||||
LOG_INFO("Remote hostname: [{}]", props->remote_host_name_);
|
||||
if (props) {
|
||||
std::lock_guard lock(props->remote_version_mutex_);
|
||||
if (props->remote_host_name_.empty()) {
|
||||
props->remote_host_name_ = std::string(remote_action.i.host_name,
|
||||
remote_action.i.host_name_size);
|
||||
LOG_INFO("Remote hostname: [{}]", props->remote_host_name_);
|
||||
|
||||
for (int i = 0; i < remote_action.i.display_num; i++) {
|
||||
props->display_info_list_.push_back(
|
||||
DisplayInfo(remote_action.i.display_list[i],
|
||||
remote_action.i.left[i], remote_action.i.top[i],
|
||||
remote_action.i.right[i], remote_action.i.bottom[i]));
|
||||
for (int i = 0; i < remote_action.i.display_num; i++) {
|
||||
props->display_info_list_.push_back(
|
||||
DisplayInfo(remote_action.i.display_list[i],
|
||||
remote_action.i.left[i], remote_action.i.top[i],
|
||||
remote_action.i.right[i], remote_action.i.bottom[i]));
|
||||
}
|
||||
}
|
||||
props->recent_connection_dirty_ = true;
|
||||
}
|
||||
FreeRemoteAction(remote_action);
|
||||
} else {
|
||||
@@ -384,49 +481,77 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
std::chrono::steady_clock::now();
|
||||
}
|
||||
#if _WIN32
|
||||
if (runtime->local_service_status_received_ &&
|
||||
IsSecureDesktopInteractionRequired(runtime->local_interactive_stage_) &&
|
||||
remote_action.type != ControlType::keyboard &&
|
||||
remote_action.type != ControlType::keyboard_state) {
|
||||
if (remote_action.type == ControlType::mouse) {
|
||||
int absolute_x = 0;
|
||||
int absolute_y = 0;
|
||||
if (!BuildAbsoluteMousePosition(runtime->devices_.display_info_list(),
|
||||
runtime->selected_display_,
|
||||
remote_action.m.x, remote_action.m.y,
|
||||
&absolute_x, &absolute_y)) {
|
||||
LOG_WARN("Secure desktop mouse injection skipped, invalid display "
|
||||
"mapping: display_index={}, x={}, y={}",
|
||||
runtime->selected_display_, remote_action.m.x,
|
||||
remote_action.m.y);
|
||||
return;
|
||||
}
|
||||
if (runtime->is_server_mode_ && remote_action.type == ControlType::mouse) {
|
||||
static const bool process_elevated = IsAdministratorProcess();
|
||||
std::string response;
|
||||
const bool delivered = DispatchDesktopInput(
|
||||
[&] {
|
||||
return PreferUserDesktopInput(
|
||||
IsCurrentSessionUserDesktopActive(),
|
||||
runtime->windows_consent_ui_.load(),
|
||||
runtime->local_service_available_.load(), process_elevated);
|
||||
},
|
||||
[&] {
|
||||
SetLastError(ERROR_SUCCESS);
|
||||
const bool sent = runtime->devices_.SendMouseCommand(
|
||||
remote_action, runtime->selected_display_);
|
||||
const DWORD error = GetLastError();
|
||||
const bool blocked =
|
||||
error == ERROR_ACCESS_DENIED || error == ERROR_GEN_FAILURE;
|
||||
return DesktopInputResult{
|
||||
sent, IsDesktopTransitionInputError(error) || blocked, blocked};
|
||||
},
|
||||
[&]() -> DesktopInputResult {
|
||||
int absolute_x = 0;
|
||||
int absolute_y = 0;
|
||||
if (!BuildAbsoluteMousePosition(
|
||||
runtime->devices_.display_info_list(),
|
||||
runtime->selected_display_, remote_action.m.x,
|
||||
remote_action.m.y, &absolute_x, &absolute_y)) {
|
||||
LOG_WARN(
|
||||
"Secure desktop mouse injection skipped, invalid display "
|
||||
"mapping: display_index={}, x={}, y={}",
|
||||
runtime->selected_display_, remote_action.m.x,
|
||||
remote_action.m.y);
|
||||
return {};
|
||||
}
|
||||
|
||||
const std::string response = SendCrossDeskSecureDesktopMouseInput(
|
||||
absolute_x, absolute_y, remote_action.m.s,
|
||||
static_cast<int>(remote_action.m.flag), 1000);
|
||||
auto json = nlohmann::json::parse(response, nullptr, false);
|
||||
if (json.is_discarded() || !json.value("ok", false)) {
|
||||
LogSecureDesktopInputBlocked(
|
||||
&runtime->last_local_secure_input_block_log_tick_, "local",
|
||||
runtime->local_interactive_stage_.c_str());
|
||||
LOG_WARN(
|
||||
"Secure desktop mouse injection failed, x={}, y={}, wheel={}, "
|
||||
"flag={}, response={}",
|
||||
absolute_x, absolute_y, remote_action.m.s,
|
||||
static_cast<int>(remote_action.m.flag), response);
|
||||
}
|
||||
return;
|
||||
response = runtime->devices_.SendServiceMouseCommand(
|
||||
absolute_x, absolute_y, remote_action.m.s,
|
||||
static_cast<int>(remote_action.m.flag));
|
||||
auto json = nlohmann::json::parse(response, nullptr, false);
|
||||
const bool sent = json.is_object() && json.value("ok", false);
|
||||
const std::string error =
|
||||
json.is_object() ? json.value("error", "") : "";
|
||||
return {sent, IsDesktopInputSetupPending(error)};
|
||||
});
|
||||
if (!delivered && !response.empty()) {
|
||||
LogSecureDesktopInputBlocked(
|
||||
&runtime->last_local_secure_input_block_log_tick_, "local",
|
||||
runtime->WindowsInputStage().c_str());
|
||||
LOG_WARN(
|
||||
"Secure desktop mouse injection failed, x={}, y={}, wheel={}, "
|
||||
"flag={}, response={}",
|
||||
remote_action.m.x, remote_action.m.y, remote_action.m.s,
|
||||
static_cast<int>(remote_action.m.flag), response);
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (remote_action.type == ControlType::mouse) {
|
||||
runtime->devices_.SendMouseCommand(remote_action,
|
||||
runtime->selected_display_);
|
||||
runtime->selected_display_);
|
||||
} else if (remote_action.type == ControlType::audio_capture) {
|
||||
// A negotiated subscription remains authoritative if a legacy capture
|
||||
// command arrives after it (e.g. when unmuting an inactive window).
|
||||
const auto subscription = runtime->preview_subscriptions_.Get(remote_id);
|
||||
const bool paused = subscription ? !subscription->audio : !remote_action.a;
|
||||
const int ret = SetAudioSendPaused(runtime->peer_, remote_id.data(),
|
||||
remote_id.size(), paused);
|
||||
if (remote_action.a)
|
||||
runtime->devices_.StartSpeakerCapturer();
|
||||
else
|
||||
else if (ret != 0)
|
||||
// Legacy/web transports without the per-peer API retain their fallback.
|
||||
runtime->devices_.StopSpeakerCapturer();
|
||||
} else if (remote_action.type == ControlType::keyboard) {
|
||||
runtime->keyboard_.ApplyRemoteEvent(remote_id, remote_action);
|
||||
|
||||
@@ -79,7 +79,12 @@ void PeerEventHandler::OnSignalMessage(const char* message, size_t size,
|
||||
return;
|
||||
}
|
||||
std::string type = j["type"].get<std::string>();
|
||||
if (type == "announcements_changed") {
|
||||
if (type == "user_join_transmission" && j.contains("status") &&
|
||||
j["status"] == "failed" && j.contains("transmission_id") &&
|
||||
j["transmission_id"].is_string()) {
|
||||
const auto props = runtime->FindRemoteSession(j["transmission_id"].get<std::string>());
|
||||
if (props && !props->closing_) props->connection_auth_.Rejected(j);
|
||||
} else if (type == "announcements_changed") {
|
||||
runtime->announcements_.Refresh();
|
||||
} else if (type == "announcements") {
|
||||
runtime->announcements_.Receive(j);
|
||||
@@ -263,8 +268,10 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
|
||||
if (props) {
|
||||
runtime->is_client_mode_ = true;
|
||||
runtime->show_connection_status_window_ = true;
|
||||
if (!props->wall_managed_) runtime->show_connection_status_window_ = true;
|
||||
props->connection_status_.store(status);
|
||||
if (status != ConnectionStatus::Connecting && status != ConnectionStatus::Gathering)
|
||||
props->connection_auth_.Complete();
|
||||
|
||||
switch (status) {
|
||||
case ConnectionStatus::Connected: {
|
||||
@@ -278,9 +285,13 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
{
|
||||
RemoteAction remote_action = MakeHostInformation(
|
||||
GetHostName(), runtime->devices_.host_display_list(),
|
||||
/*supports_privacy_screen=*/true, CROSSDESK_VERSION,
|
||||
kClientPlatform);
|
||||
/*supports_privacy_screen=*/!runtime->unattended_host_,
|
||||
CROSSDESK_VERSION, kClientPlatform);
|
||||
remote_action.i.supports_video_settings = true;
|
||||
remote_action.i.supports_deskhub_preview = true;
|
||||
remote_action.i.supports_deskhub_resolution = true;
|
||||
remote_action.i.supports_deskhub_fps15 = true;
|
||||
remote_action.i.supports_deskhub_bandwidth = true;
|
||||
for (std::size_t i = 0; i < remote_action.i.display_num; i++) {
|
||||
LOG_INFO("Local display [{}:{}]", i + 1,
|
||||
remote_action.i.display_list[i]);
|
||||
@@ -296,12 +307,13 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
FreeRemoteAction(remote_action);
|
||||
}
|
||||
|
||||
if (!runtime->need_to_create_stream_window_) {
|
||||
if (!props->wall_managed_ && !runtime->need_to_create_stream_window_) {
|
||||
runtime->need_to_create_stream_window_ = true;
|
||||
}
|
||||
props->connection_established_ = true;
|
||||
props->was_connected_ = true;
|
||||
runtime->start_keyboard_capturer_ = true;
|
||||
props->recent_connection_dirty_ = true;
|
||||
if (!props->wall_managed_) runtime->start_keyboard_capturer_ = true;
|
||||
break;
|
||||
}
|
||||
case ConnectionStatus::Disconnected:
|
||||
@@ -318,7 +330,23 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
props->remote_update_dismissed_ = false;
|
||||
}
|
||||
props->net_traffic_stats_.Reset();
|
||||
props->received_video_stats_.Reset();
|
||||
{
|
||||
std::lock_guard lock(props->gallery_frame_mutex_);
|
||||
props->gallery_video_latency_->Reset();
|
||||
props->gallery_frame_timing_ = {};
|
||||
}
|
||||
props->traversal_mode_ = TraversalMode::UnknownMode;
|
||||
props->enable_mouse_control_ = false;
|
||||
props->preview_subscription_supported_ = false;
|
||||
props->preview_resolution_supported_ = false;
|
||||
props->preview_fps15_supported_ = false;
|
||||
props->preview_bandwidth_supported_ = false;
|
||||
props->preview_needs_sync_ = true;
|
||||
props->preview_ack_ = 0;
|
||||
props->preview_accepted_ = false;
|
||||
props->audio_allowed_ = false;
|
||||
props->clipboard_allowed_ = false;
|
||||
runtime->ResetRemoteServiceStatus(*props);
|
||||
{
|
||||
std::lock_guard lock(props->video_settings_mutex_);
|
||||
@@ -379,11 +407,10 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
|
||||
runtime->focus_on_stream_window_ = false;
|
||||
|
||||
break;
|
||||
}
|
||||
case ConnectionStatus::IncorrectPassword: {
|
||||
runtime->password_validating_ = false;
|
||||
runtime->password_validating_time_++;
|
||||
if (status == ConnectionStatus::Closed) {
|
||||
props->remote_close_pending_.store(true, std::memory_order_release);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
default:
|
||||
@@ -407,15 +434,20 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
|
||||
switch (status) {
|
||||
case ConnectionStatus::Connected: {
|
||||
runtime->preview_subscriptions_.Remove(remote_id);
|
||||
#if _WIN32
|
||||
runtime->last_windows_service_status_tick_ = 0;
|
||||
#endif
|
||||
{
|
||||
RemoteAction remote_action = MakeHostInformation(
|
||||
GetHostName(), runtime->devices_.host_display_list(),
|
||||
/*supports_privacy_screen=*/true, CROSSDESK_VERSION,
|
||||
kClientPlatform);
|
||||
/*supports_privacy_screen=*/!runtime->unattended_host_,
|
||||
CROSSDESK_VERSION, kClientPlatform);
|
||||
remote_action.i.supports_video_settings = true;
|
||||
remote_action.i.supports_deskhub_preview = true;
|
||||
remote_action.i.supports_deskhub_resolution = true;
|
||||
remote_action.i.supports_deskhub_fps15 = true;
|
||||
remote_action.i.supports_deskhub_bandwidth = true;
|
||||
for (std::size_t i = 0; i < remote_action.i.display_num; i++) {
|
||||
LOG_INFO("Local display [{}:{}]", i + 1,
|
||||
remote_action.i.display_list[i]);
|
||||
@@ -532,7 +564,7 @@ void PeerEventHandler::OnNetStatusReport(
|
||||
if (props->traversal_mode_ != mode) {
|
||||
props->net_traffic_stats_.ResetLatency();
|
||||
props->traversal_mode_ = mode;
|
||||
LOG_INFO("Net mode: [{}]", int(props->traversal_mode_));
|
||||
LOG_INFO("Net mode: [{}]", int(props->traversal_mode_.load()));
|
||||
}
|
||||
|
||||
if (!net_traffic_stats) {
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
#include <libyuv.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
@@ -5,6 +8,7 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "nv12_scaler.h"
|
||||
#include "platform/video_renderer.h"
|
||||
#include "runtime/gui_runtime.h"
|
||||
#include "runtime/peer_event_handler.h"
|
||||
@@ -46,9 +50,80 @@ void PeerEventHandler::OnReceiveVideoBuffer(
|
||||
|
||||
if (props->connection_established_) {
|
||||
const auto timing_now = VideoLatencyFrame::Clock::now();
|
||||
const auto timing = props->video_latency_->Frame(
|
||||
video_frame->captured_timestamp, GetSystemTimeMicros(props->peer_),
|
||||
// Pair the clocks before preview conversion so its cost is included.
|
||||
const auto local_now_us = GetSystemTimeMicros(props->peer_);
|
||||
const auto* received_native = GetNativeVideoFrame(video_frame);
|
||||
props->received_video_stats_.Record(
|
||||
received_native ? received_native->width : video_frame->width,
|
||||
received_native ? received_native->height : video_frame->height,
|
||||
timing_now);
|
||||
// Convert only visible thumbnails, off the UI thread. A session retains
|
||||
// one latest RGBA image, not an unbounded queue of frames.
|
||||
const int preview_width = props->gallery_preview_width_.load();
|
||||
// Multiple video streams may decode concurrently for the same session.
|
||||
// Serialize access to the shared conversion buffers. Visible previews
|
||||
// consume incoming frames at the negotiated interactive cadence.
|
||||
std::unique_lock conversion_lock(props->gallery_conversion_mutex_,
|
||||
std::defer_lock);
|
||||
if (preview_width > 0) conversion_lock.lock();
|
||||
if (conversion_lock.owns_lock()) {
|
||||
const auto gallery_timing = props->gallery_video_latency_->Frame(
|
||||
video_frame->captured_timestamp, local_now_us, timing_now);
|
||||
const auto* native = GetNativeVideoFrame(video_frame);
|
||||
const int w = native ? native->width : video_frame->width;
|
||||
const int h = native ? native->height : video_frame->height;
|
||||
if (w > 0 && h > 0 && w <= 16384 && h <= 16384 && !(w % 2) && !(h % 2)) {
|
||||
const size_t bytes = static_cast<size_t>(w) * h * 3 / 2;
|
||||
const uint8_t* data =
|
||||
reinterpret_cast<const uint8_t*>(video_frame->data);
|
||||
if (native) {
|
||||
props->gallery_nv12_.resize(bytes);
|
||||
data = native->copy_to_nv12(native->owner,
|
||||
props->gallery_nv12_.data(), bytes) == 0
|
||||
? props->gallery_nv12_.data()
|
||||
: nullptr;
|
||||
} else if (video_frame->size < bytes)
|
||||
data = nullptr;
|
||||
if (data) {
|
||||
const double scale = std::min(
|
||||
{1.0, double(preview_width) / w, double(preview_width) / h});
|
||||
const int dw = std::max(2, int(w * scale) & ~1);
|
||||
const int dh = std::max(2, int(h * scale) & ~1);
|
||||
auto& scaled = props->gallery_scaled_;
|
||||
scaled.resize(static_cast<size_t>(dw) * dh * 3 / 2);
|
||||
if (ScaleNv12ViaI420(data, w, data + w * h, w, w, h, scaled.data(),
|
||||
dw, scaled.data() + dw * dh, dw, dw, dh,
|
||||
libyuv::kFilterBilinear,
|
||||
&props->gallery_scratch_) == 0) {
|
||||
auto rgba = std::make_shared<std::vector<unsigned char>>(
|
||||
static_cast<size_t>(dw) * dh * 4);
|
||||
if (libyuv::NV12ToABGR(scaled.data(), dw, scaled.data() + dw * dh,
|
||||
dw, rgba->data(), dw * 4, dw, dh) == 0) {
|
||||
std::lock_guard lock(props->gallery_frame_mutex_);
|
||||
props->gallery_rgba_ = std::move(rgba);
|
||||
props->gallery_width_ = dw;
|
||||
props->gallery_height_ = dh;
|
||||
props->gallery_frame_at_ = timing_now;
|
||||
props->gallery_frame_timing_ = gallery_timing;
|
||||
++props->gallery_sequence_;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (conversion_lock.owns_lock()) conversion_lock.unlock();
|
||||
// A wall-only session does not need a second full-resolution CPU buffer.
|
||||
if (props->wall_managed_ && !props->tab_opened_) {
|
||||
{
|
||||
std::lock_guard lock(props->video_frame_mutex_);
|
||||
props->video_width_ = video_frame->width;
|
||||
props->video_height_ = video_frame->height;
|
||||
}
|
||||
props->streaming_ = true;
|
||||
return;
|
||||
}
|
||||
const auto timing = props->video_latency_->Frame(
|
||||
video_frame->captured_timestamp, local_now_us, timing_now);
|
||||
bool background_snapshot_only = false;
|
||||
auto* native_renderer = runtime->video_renderer_.get();
|
||||
if (native_renderer && native_renderer->IsActive()) {
|
||||
@@ -201,13 +276,17 @@ void PeerEventHandler::OnReceiveAudioBuffer(
|
||||
auto callback = handler->EnterCallback();
|
||||
if (!callback) return;
|
||||
GuiRuntime* runtime = handler ? &handler->owner_ : nullptr;
|
||||
if (!runtime) {
|
||||
if (!runtime || runtime->unattended_host_) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::lock_guard delivery_lock(runtime->audio_delivery_mutex_);
|
||||
const auto session =
|
||||
runtime->FindRemoteSession(std::string(user_id, user_id_size));
|
||||
if (!session || session->closing_ || !session->audio_allowed_.load()) return;
|
||||
runtime->audio_buffer_fresh_ = true;
|
||||
|
||||
runtime->devices_.PushAudio(data, size);
|
||||
runtime->devices_.PushAudio(session->remote_id_, data, size);
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-12
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PREVIEW_SUBSCRIPTIONS_H_
|
||||
#define _PREVIEW_SUBSCRIPTIONS_H_
|
||||
|
||||
#include <preview_subscription.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace crossdesk {
|
||||
// Accessed by the network callback and screen-capture callback. Legacy
|
||||
// controllers have no entry and continue receiving their normal stream.
|
||||
class PreviewSubscriptions {
|
||||
public:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
std::optional<PreviewSubscription> Get(const std::string &id) {
|
||||
std::lock_guard lock(mutex_);
|
||||
const auto found = states_.find(id);
|
||||
return found == states_.end() ? std::nullopt
|
||||
: std::optional(found->second.request);
|
||||
}
|
||||
bool Set(const std::string &id, const PreviewSubscription &request) {
|
||||
std::lock_guard lock(mutex_);
|
||||
const auto found = states_.find(id);
|
||||
if (found != states_.end() &&
|
||||
!request.IsNewerThan(found->second.request))
|
||||
return false;
|
||||
auto &state = states_[id];
|
||||
if (state.request.fps != request.fps) state.next.clear();
|
||||
state.request = request;
|
||||
return true;
|
||||
}
|
||||
bool ShouldSend(const std::string &id, Clock::time_point now = Clock::now(),
|
||||
const std::string &stream = {}) {
|
||||
std::lock_guard lock(mutex_);
|
||||
const auto found = states_.find(id);
|
||||
if (found == states_.end())
|
||||
return true;
|
||||
auto &state = found->second;
|
||||
// MiniRTC owns pause/resume. This gate only limits preview cadence, so
|
||||
// paused input reaches its cheap send gate without dividing by zero here.
|
||||
if (!state.request.fps)
|
||||
return true;
|
||||
// Interactive streams use the encoder's own 30/60 FPS cadence. A second
|
||||
// time gate here can drop valid frames because capture timing varies.
|
||||
if (state.request.fps == 60)
|
||||
return true;
|
||||
auto &next = state.next[stream];
|
||||
if (state.request.fps == 15) {
|
||||
// Keep a stable 15 FPS deadline across capture jitter. Rebasing every
|
||||
// frame can turn small timing errors into extra dropped capture frames.
|
||||
const auto interval = std::chrono::nanoseconds(1'000'000'000 / 15);
|
||||
if (now + std::chrono::milliseconds(1) < next) return false;
|
||||
next = next == Clock::time_point{} || now - next > interval
|
||||
? now + interval : next + interval;
|
||||
return true;
|
||||
}
|
||||
if (now < next)
|
||||
return false;
|
||||
next = now + std::chrono::milliseconds(1000 / state.request.fps);
|
||||
return true;
|
||||
}
|
||||
void Remove(const std::string &id) {
|
||||
std::lock_guard lock(mutex_);
|
||||
states_.erase(id);
|
||||
}
|
||||
|
||||
private:
|
||||
struct State {
|
||||
PreviewSubscription request;
|
||||
// One display must not consume another display's preview frame budget.
|
||||
std::unordered_map<std::string, Clock::time_point> next;
|
||||
};
|
||||
std::mutex mutex_;
|
||||
std::unordered_map<std::string, State> states_;
|
||||
};
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -46,7 +46,7 @@ void GuiRuntime::SetControllerPrivacySupport(const std::string& remote_id,
|
||||
|
||||
void GuiRuntime::ApplyPrivacyAdmission(bool automatic_enable) {
|
||||
if (!privacy_sessions_.CanEnable()) {
|
||||
if (privacy_.Engaged()) privacy_.Disable();
|
||||
privacy_.Disable();
|
||||
} else if (automatic_enable) {
|
||||
privacy_.EnableOnConnection();
|
||||
}
|
||||
@@ -93,6 +93,9 @@ void GuiRuntime::HandlePrivacy() {
|
||||
std::vector<std::string> controllers;
|
||||
{
|
||||
std::shared_lock lock(connection_status_mutex_);
|
||||
if (!privacy_sessions_.CanEnable() ||
|
||||
!config_center_->IsEnablePrivacyScreen())
|
||||
privacy_.CancelAutomaticResume();
|
||||
status = privacy_.Snapshot();
|
||||
for (const auto& [id, state] : connection_status_)
|
||||
if (state == ConnectionStatus::Connected &&
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-12
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _RECEIVED_VIDEO_STATS_H_
|
||||
#define _RECEIVED_VIDEO_STATS_H_
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
|
||||
namespace crossdesk::gui_detail {
|
||||
// Measured at decode delivery, including wall-only and background sessions.
|
||||
// Independent of the selected window's presentation cadence and FPS setting.
|
||||
class ReceivedVideoStats {
|
||||
public:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
struct Snapshot {
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
std::optional<int> fps;
|
||||
};
|
||||
|
||||
void Record(int width, int height, Clock::time_point now = Clock::now()) {
|
||||
if (width <= 0 || height <= 0) return;
|
||||
std::lock_guard lock(mutex_);
|
||||
const bool restart = snapshot_.width == 0 ||
|
||||
now - last_frame_ >= std::chrono::seconds(3);
|
||||
snapshot_.width = width;
|
||||
snapshot_.height = height;
|
||||
last_frame_ = now;
|
||||
if (restart) {
|
||||
started_ = now;
|
||||
frames_ = 0;
|
||||
snapshot_.fps.reset();
|
||||
return;
|
||||
}
|
||||
++frames_;
|
||||
const double elapsed = std::chrono::duration<double>(now - started_).count();
|
||||
if (elapsed >= 1.0) {
|
||||
snapshot_.fps = static_cast<int>(std::lround(frames_ / elapsed));
|
||||
frames_ = 0;
|
||||
started_ = now;
|
||||
}
|
||||
}
|
||||
|
||||
Snapshot Get(Clock::time_point now = Clock::now()) const {
|
||||
std::lock_guard lock(mutex_);
|
||||
auto result = snapshot_;
|
||||
if (result.width > 0 && now - last_frame_ >= std::chrono::seconds(1))
|
||||
result.fps = 0;
|
||||
return result;
|
||||
}
|
||||
|
||||
void Reset() {
|
||||
std::lock_guard lock(mutex_);
|
||||
snapshot_ = {};
|
||||
frames_ = 0;
|
||||
started_ = last_frame_ = {};
|
||||
}
|
||||
|
||||
private:
|
||||
mutable std::mutex mutex_;
|
||||
Snapshot snapshot_;
|
||||
unsigned frames_ = 0;
|
||||
Clock::time_point started_{}, last_frame_{};
|
||||
};
|
||||
} // namespace crossdesk::gui_detail
|
||||
#endif
|
||||
@@ -20,12 +20,16 @@
|
||||
#include <vector>
|
||||
|
||||
#include <remote_action.h>
|
||||
#include <preview_subscription.h>
|
||||
#include <stream_names.h>
|
||||
#include "display_info.h"
|
||||
#include "features/gallery/preview_resolution.h"
|
||||
#include "cursor_presentation.h"
|
||||
#include "minirtc.h"
|
||||
#include "rendering/video_latency.h"
|
||||
#include "runtime/net_traffic_stats_cache.h"
|
||||
#include "runtime/received_video_stats.h"
|
||||
#include "runtime/connection_auth_state.h"
|
||||
|
||||
namespace crossdesk { class PeerEventHandler; }
|
||||
|
||||
@@ -69,10 +73,41 @@ struct FileTransferState {
|
||||
// Runtime state for one connected or connecting remote endpoint. It groups the
|
||||
// connection, media, input, window and transfer data that share one lifetime.
|
||||
struct RemoteSession {
|
||||
// Wall membership, stream-window visibility and input ownership are separate.
|
||||
std::atomic<bool> wall_managed_{false};
|
||||
std::atomic<bool> preview_subscription_supported_{false};
|
||||
std::atomic<bool> preview_resolution_supported_{false};
|
||||
std::atomic<bool> preview_fps15_supported_{false};
|
||||
std::atomic<bool> preview_bandwidth_supported_{false};
|
||||
std::atomic<bool> preview_needs_sync_{true};
|
||||
std::atomic<uint32_t> preview_ack_{0};
|
||||
std::atomic<bool> preview_accepted_{false};
|
||||
uint32_t preview_request_ = 0;
|
||||
PreviewSubscription preview_requested_;
|
||||
gallery::PreviewResolutionDebouncer preview_resolution_;
|
||||
std::chrono::steady_clock::time_point preview_request_at_{};
|
||||
std::atomic<bool> clipboard_allowed_{false};
|
||||
std::atomic<uint64_t> input_generation_{0};
|
||||
std::atomic<bool> audio_allowed_{false};
|
||||
std::atomic<int> gallery_preview_width_{0};
|
||||
std::mutex gallery_frame_mutex_;
|
||||
std::shared_ptr<std::vector<unsigned char>> gallery_rgba_;
|
||||
int gallery_width_ = 0, gallery_height_ = 0;
|
||||
uint64_t gallery_sequence_ = 0;
|
||||
std::chrono::steady_clock::time_point gallery_frame_at_{};
|
||||
VideoLatencyFrame gallery_frame_timing_;
|
||||
// Keep preview submission estimates separate from stream presentation times.
|
||||
std::shared_ptr<VideoLatencyStats> gallery_video_latency_ =
|
||||
std::make_shared<VideoLatencyStats>();
|
||||
// Decoder-thread scratch memory, never shared with the UI.
|
||||
std::mutex gallery_conversion_mutex_;
|
||||
std::vector<unsigned char> gallery_nv12_, gallery_scaled_, gallery_scratch_;
|
||||
Params params_;
|
||||
PeerPtr* peer_ = nullptr;
|
||||
std::shared_ptr<PeerEventHandler> peer_events_;
|
||||
std::atomic<bool> closing_{false};
|
||||
// Transport callbacks request tab closure; only the UI thread destroys it.
|
||||
std::atomic<bool> remote_close_pending_{false};
|
||||
std::string audio_label_ = kAudioStream;
|
||||
std::string data_label_ = kDataStream;
|
||||
std::string mouse_label_ = kMouseStream;
|
||||
@@ -88,6 +123,8 @@ struct RemoteSession {
|
||||
SignalStatus signal_status_ = SignalStatus::SignalClosed;
|
||||
bool connection_established_ = false;
|
||||
std::atomic<bool> was_connected_{false};
|
||||
// Transport callbacks publish changes; the UI thread persists history.
|
||||
std::atomic<bool> recent_connection_dirty_{false};
|
||||
bool rejoin_ = false;
|
||||
bool net_traffic_stats_button_pressed_ = false;
|
||||
bool enable_mouse_control_ = true;
|
||||
@@ -98,6 +135,7 @@ struct RemoteSession {
|
||||
bool p2p_mode_ = true;
|
||||
bool remember_password_ = false;
|
||||
char remote_password_[7] = "";
|
||||
ConnectionAuthState connection_auth_;
|
||||
// Reused across frames by the decode callback thread when a CPU NV12
|
||||
// native frame has to be materialized for a renderer that rejects it.
|
||||
std::vector<unsigned char> native_cpu_fallback_;
|
||||
@@ -123,7 +161,7 @@ struct RemoteSession {
|
||||
std::shared_ptr<VideoLatencyStats> video_latency_ =
|
||||
std::make_shared<VideoLatencyStats>();
|
||||
bool tab_selected_ = false;
|
||||
bool tab_opened_ = true;
|
||||
std::atomic<bool> tab_opened_{true};
|
||||
std::string remote_host_name_;
|
||||
// Host metadata and dismissal state belong to this connection and are
|
||||
// protected by remote_version_mutex_.
|
||||
@@ -162,13 +200,14 @@ struct RemoteSession {
|
||||
CursorPresentation cursor_presentation_;
|
||||
// Shared by minirtc callbacks, Slint rendering and SDL audio callbacks.
|
||||
std::atomic<ConnectionStatus> connection_status_ = ConnectionStatus::Closed;
|
||||
TraversalMode traversal_mode_ = TraversalMode::UnknownMode;
|
||||
std::atomic<TraversalMode> traversal_mode_{TraversalMode::UnknownMode};
|
||||
int fps_ = 0;
|
||||
int frame_count_ = 0;
|
||||
std::chrono::steady_clock::time_point last_time_;
|
||||
// UI-thread snapshot refreshed with FPS once per second.
|
||||
std::optional<VideoLatencyStats::Snapshot> video_latency_snapshot_;
|
||||
NetTrafficStatsCache net_traffic_stats_;
|
||||
ReceivedVideoStats received_video_stats_;
|
||||
|
||||
using QueuedFile = FileTransferState::QueuedFile;
|
||||
using FileTransferStatus = FileTransferState::FileTransferStatus;
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
#ifndef _RUNTIME_STATE_H_
|
||||
#define _RUNTIME_STATE_H_
|
||||
|
||||
#include <stream_names.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
@@ -19,19 +21,24 @@
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include <stream_names.h>
|
||||
|
||||
#include "config_center.h"
|
||||
#include "common/task_queue_lock_free.h"
|
||||
#include "config_center.h"
|
||||
#include "path_manager.h"
|
||||
#include "runtime/device_presence_cache.h"
|
||||
#include "runtime/preview_subscriptions.h"
|
||||
#include "runtime/remote_session.h"
|
||||
#include "runtime/session_lifecycle.h"
|
||||
#include "thumbnail.h"
|
||||
|
||||
#if _WIN32
|
||||
#include "platform/windows/service/service_query_worker.h"
|
||||
#endif
|
||||
|
||||
namespace crossdesk::gui_detail {
|
||||
|
||||
struct InfrastructureState {
|
||||
PreviewSubscriptions preview_subscriptions_;
|
||||
std::mutex audio_delivery_mutex_;
|
||||
std::unique_ptr<ConfigCenter> config_center_;
|
||||
ConfigCenter::LANGUAGE localization_language_ =
|
||||
ConfigCenter::LANGUAGE::CHINESE;
|
||||
@@ -50,6 +57,7 @@ struct RecentConnectionsState {
|
||||
std::vector<std::pair<std::string, Thumbnail::RecentConnection>>
|
||||
recent_connections_;
|
||||
std::vector<std::string> recent_connection_ids_;
|
||||
std::vector<std::string> gallery_presence_ids_;
|
||||
int recent_connection_image_width_ = 160;
|
||||
int recent_connection_image_height_ = 90;
|
||||
uint32_t recent_connection_image_save_time_ = 0;
|
||||
@@ -76,16 +84,21 @@ struct PeerState {
|
||||
std::string file_label_ = kFileStream;
|
||||
std::string file_feedback_label_ = kFileFeedbackStream;
|
||||
std::string clipboard_label_ = kClipboardStream;
|
||||
Params params_;
|
||||
Params params_{};
|
||||
};
|
||||
|
||||
// OS-specific service and permission state is kept separate from transport
|
||||
// state so platform code does not appear to be part of the wire contract.
|
||||
struct PlatformIntegrationState {
|
||||
#if _WIN32
|
||||
std::unique_ptr<ServiceQueryWorker> windows_service_worker_;
|
||||
// Published by the UI, read by transport callbacks without sharing a mutable string.
|
||||
mutable std::mutex windows_input_stage_mutex_;
|
||||
std::string windows_input_stage_;
|
||||
std::atomic<bool> windows_consent_ui_{false};
|
||||
std::atomic<bool> pending_windows_service_sas_{false};
|
||||
bool local_service_status_received_ = false;
|
||||
bool local_service_available_ = false;
|
||||
std::atomic<bool> local_service_available_{false};
|
||||
std::string local_interactive_stage_;
|
||||
uint32_t last_local_secure_input_block_log_tick_ = 0;
|
||||
uint32_t last_windows_service_status_tick_ = 0;
|
||||
@@ -181,6 +194,7 @@ struct ConnectionState {
|
||||
struct PendingReconnect {
|
||||
std::string password;
|
||||
bool remember_password = false;
|
||||
bool background = false;
|
||||
};
|
||||
std::unordered_map<std::string, PendingReconnect> pending_reconnects_;
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { UiRadius } from "ui_radius.slint";
|
||||
// The legacy client uses ImGui::StyleColorsLight(). Keep the structural line
|
||||
// colors in one place so the Slint renderer produces the same visual weight.
|
||||
export global ImGuiLineStyle {
|
||||
@@ -7,6 +8,10 @@ export global ImGuiLineStyle {
|
||||
out property <color> control-separator: #b2b2b2;
|
||||
}
|
||||
|
||||
export global FloatingBarStyle {
|
||||
out property <length> corner-radius: UiRadius.menu;
|
||||
}
|
||||
|
||||
// ImGui loads a 32px font atlas and applies per-window font scales. These
|
||||
// logical sizes reproduce those visual tiers on Slint's HiDPI renderer.
|
||||
export global ImGuiFontStyle {
|
||||
@@ -45,6 +50,7 @@ export global FontAwesomeIcons {
|
||||
out property <string> signal: "\u{f012}";
|
||||
out property <string> shield-halved: "\u{f3ed}";
|
||||
out property <string> square-full: "\u{f45c}";
|
||||
out property <string> tags: "\u{f02c}";
|
||||
out property <string> trash-can: "\u{f2ed}";
|
||||
out property <string> user-secret: "\u{f21b}";
|
||||
out property <string> volume-high: "\u{f028}";
|
||||
@@ -55,6 +61,7 @@ export global FontAwesomeIcons {
|
||||
export component IconButton inherits Rectangle {
|
||||
in property <string> icon;
|
||||
in property <string> tooltip;
|
||||
in property <bool> tooltip-above: false;
|
||||
in property <bool> enabled: true;
|
||||
in property <bool> danger: false;
|
||||
in property <length> icon-size: 16px;
|
||||
@@ -70,7 +77,7 @@ export component IconButton inherits Rectangle {
|
||||
background: touch.pressed ? (danger ? #d92d20 : root.pressed-background)
|
||||
: touch.has-hover ? (danger ? #f04438 : root.hover-background)
|
||||
: root.normal-background;
|
||||
border-radius: 4px;
|
||||
border-radius: UiRadius.control;
|
||||
opacity: root.enabled ? 1 : 0.4;
|
||||
|
||||
Text {
|
||||
@@ -99,11 +106,11 @@ export component IconButton inherits Rectangle {
|
||||
|
||||
if touch.has-hover && root.tooltip != "": Rectangle {
|
||||
x: min(root.width - self.width, 0px);
|
||||
y: root.height + 3px;
|
||||
y: root.tooltip-above ? -self.height - 3px : root.height + 3px;
|
||||
width: tip.preferred-width + 12px;
|
||||
height: 24px;
|
||||
background: #22252be8;
|
||||
border-radius: 4px;
|
||||
border-radius: UiRadius.control;
|
||||
z: 20;
|
||||
tip := Text {
|
||||
text: root.tooltip;
|
||||
@@ -130,7 +137,7 @@ export component ImageButton inherits Rectangle {
|
||||
background: touch.pressed ? (danger ? #d92d20 : #d9dde5)
|
||||
: touch.has-hover ? (danger ? #f04438 : #edf0f5)
|
||||
: transparent;
|
||||
border-radius: 4px;
|
||||
border-radius: UiRadius.control;
|
||||
|
||||
Image {
|
||||
x: (parent.width - self.width) / 2;
|
||||
@@ -151,7 +158,7 @@ export component ImageButton inherits Rectangle {
|
||||
width: tip.preferred-width + 12px;
|
||||
height: 24px;
|
||||
background: #22252be8;
|
||||
border-radius: 4px;
|
||||
border-radius: UiRadius.control;
|
||||
z: 20;
|
||||
tip := Text {
|
||||
text: root.tooltip;
|
||||
@@ -167,6 +174,10 @@ export component CompactComboBox inherits Rectangle {
|
||||
in property <[string]> model;
|
||||
in-out property <int> current-index: 0;
|
||||
in property <bool> enabled: true;
|
||||
in property <bool> subtle: false;
|
||||
in property <bool> show-arrow: true;
|
||||
in property <color> normal-border-color: root.subtle ? #dfe6ef : #bfc2c7;
|
||||
in property <color> hover-border-color: root.normal-border-color;
|
||||
property <bool> popup-animation-enabled: false;
|
||||
property <float> popup-progress: 0.0;
|
||||
callback selected(int);
|
||||
@@ -179,29 +190,31 @@ export component CompactComboBox inherits Rectangle {
|
||||
|
||||
width: 73px;
|
||||
height: 24px;
|
||||
background: root.enabled ? white : #f1f1f1;
|
||||
background: root.enabled ? (root.subtle ? #f8fafc : white) : root.subtle ? #f1f3f6 : #f1f1f1;
|
||||
border-width: 1px;
|
||||
border-color: #bfc2c7;
|
||||
border-radius: 3px;
|
||||
border-color: root.enabled && combo-touch.has-hover ? root.hover-border-color : root.normal-border-color;
|
||||
border-radius: UiRadius.control;
|
||||
|
||||
Text {
|
||||
x: 5px;
|
||||
width: parent.width - 24px;
|
||||
x: root.subtle ? 10px : 5px;
|
||||
width: parent.width - (root.show-arrow ? (root.subtle ? 36px : 24px) : (root.subtle ? 20px : 10px));
|
||||
text: root.model[root.current-index];
|
||||
color: root.enabled ? #202124 : #8b8f95;
|
||||
font-size: ImGuiFontStyle.body;
|
||||
font-size: root.subtle ? 12px : ImGuiFontStyle.body;
|
||||
overflow: elide;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
Rectangle {
|
||||
x: parent.width - 21px;
|
||||
if root.show-arrow: Rectangle {
|
||||
x: parent.width - (root.subtle ? 27px : 21px);
|
||||
width: 20px;
|
||||
height: parent.height - 2px;
|
||||
y: 1px;
|
||||
background: root.enabled ? #9bc9f8 : #d7d9dc;
|
||||
background: root.subtle ? transparent : root.enabled ? #9bc9f8 : #d7d9dc;
|
||||
border-top-right-radius: UiRadius.control - 1px;
|
||||
border-bottom-right-radius: UiRadius.control - 1px;
|
||||
Text {
|
||||
text: FontAwesomeIcons.angle-down;
|
||||
color: #202124;
|
||||
color: root.subtle ? #79879a : #202124;
|
||||
font-family: "Font Awesome 6 Free";
|
||||
font-weight: 900;
|
||||
font-size: 10px;
|
||||
@@ -215,8 +228,8 @@ export component CompactComboBox inherits Rectangle {
|
||||
}
|
||||
}
|
||||
}
|
||||
TouchArea {
|
||||
enabled: root.enabled;
|
||||
combo-touch := TouchArea {
|
||||
enabled: root.enabled; mouse-cursor: pointer;
|
||||
clicked => {
|
||||
root.popup-animation-enabled = false;
|
||||
root.popup-progress = 0.0;
|
||||
@@ -255,15 +268,15 @@ export component CompactComboBox inherits Rectangle {
|
||||
opacity: root.popup-progress;
|
||||
background: white;
|
||||
border-width: 1px;
|
||||
border-color: #bfc2c7;
|
||||
border-radius: 3px;
|
||||
border-color: root.normal-border-color;
|
||||
border-radius: UiRadius.menu;
|
||||
clip: true;
|
||||
for choice[index] in root.model: Rectangle {
|
||||
y: index * 23px;
|
||||
width: parent.width;
|
||||
height: 23px;
|
||||
background: option-touch.has-hover ? #dbeafb : index == root.current-index ? #eef5fd : white;
|
||||
Text { x: 5px; width: parent.width - 10px; text: choice; color: #202124; font-size: ImGuiFontStyle.body; overflow: elide; vertical-alignment: center; }
|
||||
Text { x: 5px; width: parent.width - 10px; text: choice; color: #202124; font-size: root.subtle ? 12px : ImGuiFontStyle.body; overflow: elide; vertical-alignment: center; }
|
||||
option-touch := TouchArea {
|
||||
clicked => {
|
||||
popup-open-timer.running = false;
|
||||
@@ -280,8 +293,8 @@ export component CompactComboBox inherits Rectangle {
|
||||
height: parent.height;
|
||||
background: transparent;
|
||||
border-width: 1px;
|
||||
border-color: #bfc2c7;
|
||||
border-radius: 3px;
|
||||
border-color: root.normal-border-color;
|
||||
border-radius: UiRadius.menu;
|
||||
z: 2;
|
||||
}
|
||||
}
|
||||
@@ -341,18 +354,19 @@ export component CompactButton inherits Rectangle {
|
||||
in property <string> text;
|
||||
in property <length> text-size: ImGuiFontStyle.body;
|
||||
in property <bool> primary: false;
|
||||
in property <bool> quiet: false;
|
||||
in property <bool> enabled: true;
|
||||
callback clicked;
|
||||
|
||||
width: 34px;
|
||||
height: 24px;
|
||||
background: !root.enabled ? #eceef0
|
||||
background: !root.enabled ? (root.quiet ? transparent : #eceef0)
|
||||
: button-touch.pressed ? (root.primary ? #82b8f2 : #d8dadd)
|
||||
: button-touch.has-hover ? (root.primary ? #b8d9fb : #f0f1f2)
|
||||
: root.primary ? #a8d0fa : #e2e4e7;
|
||||
: root.primary ? #a8d0fa : root.quiet ? transparent : #e2e4e7;
|
||||
border-width: 1px;
|
||||
border-color: root.primary ? #9bc3ed : #c8cbd0;
|
||||
border-radius: 3px;
|
||||
border-color: root.primary ? #9bc3ed : root.quiet ? transparent : #c8cbd0;
|
||||
border-radius: UiRadius.control;
|
||||
Text {
|
||||
text: root.text;
|
||||
color: root.enabled ? #24272d : #8e9298;
|
||||
@@ -376,7 +390,7 @@ export component PrimaryButton inherits Rectangle {
|
||||
: touch.pressed ? #1849a9
|
||||
: touch.has-hover ? #2970d6
|
||||
: #2463c7;
|
||||
border-radius: 5px;
|
||||
border-radius: UiRadius.control;
|
||||
|
||||
Text {
|
||||
text: root.text;
|
||||
@@ -394,6 +408,7 @@ export component PrimaryButton inherits Rectangle {
|
||||
|
||||
export component SecondaryButton inherits Rectangle {
|
||||
in property <string> text;
|
||||
in property <length> text-size: ImGuiFontStyle.body;
|
||||
in property <bool> enabled: true;
|
||||
callback clicked;
|
||||
|
||||
@@ -404,13 +419,13 @@ export component SecondaryButton inherits Rectangle {
|
||||
: touch.has-hover ? #f3f4f6 : white;
|
||||
border-width: 1px;
|
||||
border-color: #c9ced7;
|
||||
border-radius: 5px;
|
||||
border-radius: UiRadius.control;
|
||||
clip: true;
|
||||
|
||||
Text {
|
||||
text: root.text;
|
||||
color: root.enabled ? #24272d : #949aa5;
|
||||
font-size: ImGuiFontStyle.body;
|
||||
font-size: root.text-size;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
@@ -461,5 +476,5 @@ export component DialogSurface inherits Rectangle {
|
||||
background: white;
|
||||
border-width: 1px;
|
||||
border-color: ImGuiLineStyle.border;
|
||||
border-radius: 8px;
|
||||
border-radius: UiRadius.surface;
|
||||
}
|
||||
|
||||
@@ -3,4 +3,9 @@
|
||||
export { AnnouncementItem, MessageStrings } from "message_panel.slint";
|
||||
export { MainWindow, RecentConnection, UpdateCheckStatus, UiStrings } from "main_window.slint";
|
||||
export { StreamWindow, StreamTab, FileTransferEntry, NetworkStatsRow, StreamStrings } from "stream_window.slint";
|
||||
export { ServerWindow, ControllerEntry } from "server_window.slint";
|
||||
export { ServerWindow, ServerStatusBar, ServerStrings, ControllerEntry } from "server_window.slint";
|
||||
|
||||
export { GalleryTile, GalleryRecentDevice, GalleryActionDevice } from "gallery_view.slint";
|
||||
export { GalleryStrings } from "device_strings.slint";
|
||||
export { GalleryNetworkDevice } from "gallery_network_dialog.slint";
|
||||
export { DeviceGroupOption } from "device_group_dialog.slint";
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { UiRadius } from "ui_radius.slint";
|
||||
import { IconButton, FontAwesomeIcons } from "common.slint";
|
||||
import { GalleryStrings } from "device_strings.slint";
|
||||
|
||||
export global DeviceCardStyle {
|
||||
out property <length> toolbar-width: 104px;
|
||||
out property <color> offline-preview: #626870;
|
||||
out property <color> offline-background: #e4e6e9;
|
||||
out property <color> offline-border: #c9cdd2;
|
||||
out property <color> offline-text: #68707a;
|
||||
out property <color> offline-placeholder: #eceef1;
|
||||
}
|
||||
|
||||
component CardAction inherits IconButton {
|
||||
width: 26px; height: 23px;
|
||||
border-radius: UiRadius.control;
|
||||
icon-size: 12px; icon-color: white;
|
||||
hover-background: #ffffff2e;
|
||||
pressed-background: #598cf273;
|
||||
tooltip-above: true;
|
||||
}
|
||||
|
||||
// Shared by recent connections and DeskHub; callers supply only behavior.
|
||||
export component DeviceCardActions inherits Rectangle {
|
||||
in property <string> remove-label;
|
||||
in property <bool> connected: false;
|
||||
callback edit-alias();
|
||||
callback edit-groups();
|
||||
callback remove-device();
|
||||
callback connect-device();
|
||||
callback disconnect-device();
|
||||
width: DeviceCardStyle.toolbar-width; height: 23px;
|
||||
background: #4a4e55dc; border-radius: UiRadius.control;
|
||||
HorizontalLayout {
|
||||
spacing: 0px;
|
||||
CardAction {
|
||||
icon: FontAwesomeIcons.pen;
|
||||
tooltip: GalleryStrings.tr("修改名称", "Rename", "Переименовать");
|
||||
clicked => { root.edit-alias(); }
|
||||
}
|
||||
CardAction {
|
||||
icon: FontAwesomeIcons.tags;
|
||||
tooltip: GalleryStrings.tr("修改分组", "Edit groups", "Изменить группы");
|
||||
clicked => { root.edit-groups(); }
|
||||
}
|
||||
CardAction {
|
||||
icon: FontAwesomeIcons.trash-can;
|
||||
tooltip: root.remove-label;
|
||||
clicked => { root.remove-device(); }
|
||||
}
|
||||
CardAction {
|
||||
icon: root.connected ? FontAwesomeIcons.xmark : FontAwesomeIcons.arrow-right-long;
|
||||
icon-size: 13px;
|
||||
tooltip: root.connected ? GalleryStrings.tr("断开", "Disconnect", "Отключить") : GalleryStrings.tr("连接", "Connect", "Подключить");
|
||||
clicked => {
|
||||
if root.connected { root.disconnect-device(); }
|
||||
else { root.connect-device(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { UiRadius } from "ui_radius.slint";
|
||||
import { ScrollView } from "std-widgets.slint";
|
||||
import { RoundedLineEdit } from "rounded_line_edit.slint";
|
||||
import { CompactButton, ImGuiCheckBox } from "common.slint";
|
||||
import { GalleryStrings } from "device_strings.slint";
|
||||
|
||||
export struct DeviceGroupOption {
|
||||
name: string,
|
||||
selected: bool,
|
||||
}
|
||||
|
||||
export component DeviceGroupDialog inherits Rectangle {
|
||||
in property <string> device-name;
|
||||
in property <string> device-id;
|
||||
in property <[DeviceGroupOption]> options;
|
||||
in property <string> error;
|
||||
in-out property <string> new-group;
|
||||
callback toggle-group(string);
|
||||
callback save(string);
|
||||
callback cancel();
|
||||
background: #00000040;
|
||||
TouchArea {}
|
||||
dialog := Rectangle {
|
||||
x: (parent.width - self.width) / 2;
|
||||
y: (parent.height - self.height) / 2;
|
||||
width: min(360px, parent.width - 40px);
|
||||
height: 208px + group-list.height + (root.error == "" ? 0px : 32px);
|
||||
background: white; border-radius: UiRadius.surface;
|
||||
border-width: 1px; border-color: #b2b2b2;
|
||||
TouchArea {}
|
||||
Text {
|
||||
x: 18px; y: 16px; height: 24px;
|
||||
text: GalleryStrings.tr("修改分组", "Edit groups", "Изменить группы");
|
||||
color: #24272d; font-size: 17px; font-weight: 600;
|
||||
}
|
||||
Text {
|
||||
x: 18px; y: 47px; width: parent.width - 36px; height: 18px;
|
||||
text: root.device-name; color: #30343b; font-size: 12px; overflow: elide;
|
||||
}
|
||||
Text {
|
||||
x: 18px; y: 67px; width: parent.width - 36px; height: 16px;
|
||||
text: "ID " + root.device-id; color: #858c97; font-size: 11px;
|
||||
}
|
||||
group-list := Rectangle {
|
||||
x: 18px; y: 95px; width: parent.width - 36px;
|
||||
height: min(5, max(1, root.options.length)) * 32px + 2px;
|
||||
background: #fbfcfd; border-width: 1px; border-color: #e1e5eb; border-radius: UiRadius.surface;
|
||||
clip: true;
|
||||
ScrollView {
|
||||
x: 1px; y: 1px; width: parent.width - 2px; height: parent.height - 2px;
|
||||
viewport-width: self.width;
|
||||
VerticalLayout {
|
||||
spacing: 0px;
|
||||
for option[index] in root.options: Rectangle {
|
||||
height: 32px;
|
||||
background: row-touch.has-hover ? #eef4fc : transparent;
|
||||
ImGuiCheckBox {
|
||||
x: 9px; y: 6px; width: 20px; height: 20px;
|
||||
checked: option.selected && (option.name != "" || root.new-group == "");
|
||||
}
|
||||
Text {
|
||||
x: 39px; width: parent.width - 48px; height: parent.height;
|
||||
text: option.name == "" ? GalleryStrings.tr("未分组", "Ungrouped", "Без группы") : option.name;
|
||||
color: #30343b; font-size: 12px; overflow: elide; vertical-alignment: center;
|
||||
}
|
||||
row-touch := TouchArea { clicked => { root.toggle-group(option.name); } }
|
||||
}
|
||||
}
|
||||
}
|
||||
// Keep row hover backgrounds inside the rounded list on every renderer.
|
||||
Rectangle {
|
||||
x: -UiRadius.surface; y: -UiRadius.surface;
|
||||
width: parent.width + 2 * UiRadius.surface;
|
||||
height: parent.height + 2 * UiRadius.surface;
|
||||
border-width: UiRadius.surface; border-radius: 2 * UiRadius.surface;
|
||||
border-color: white;
|
||||
}
|
||||
Rectangle {
|
||||
width: parent.width; height: parent.height;
|
||||
border-width: 1px; border-radius: UiRadius.surface;
|
||||
border-color: #e1e5eb;
|
||||
}
|
||||
}
|
||||
RoundedLineEdit {
|
||||
x: 18px; y: group-list.y + group-list.height + 12px;
|
||||
width: parent.width - 36px; height: 30px;
|
||||
text <=> root.new-group;
|
||||
placeholder-text: GalleryStrings.tr("新建分组(可选)", "New group (optional)", "Новая группа (необязательно)");
|
||||
}
|
||||
if root.error != "": Text {
|
||||
x: 18px; y: group-list.y + group-list.height + 48px;
|
||||
width: parent.width - 36px; height: 32px;
|
||||
text: root.error; color: #c53e3e; font-size: 11px; wrap: word-wrap;
|
||||
}
|
||||
HorizontalLayout {
|
||||
x: 18px; y: parent.height - 46px; width: parent.width - 36px; height: 28px;
|
||||
spacing: 10px;
|
||||
Rectangle { horizontal-stretch: 1; }
|
||||
CompactButton { width: 72px; height: 28px; text: GalleryStrings.tr("取消", "Cancel", "Отмена"); clicked => { root.cancel(); } }
|
||||
CompactButton { width: 88px; height: 28px; primary: true; text: GalleryStrings.tr("保存", "Save", "Сохранить"); clicked => { root.save(root.new-group); } }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export global GalleryStrings {
|
||||
in-out property <int> language: 0;
|
||||
public pure function tr(zh: string, en: string, ru: string) -> string {
|
||||
return self.language == 0 ? zh : self.language == 2 ? ru : en;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user