mirror of
https://github.com/kunkundi/crossdesk.git
synced 2026-10-16 17:10:20 +08:00
Compare commits
35
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
420e7a8cbb | ||
|
|
58ca67fa25 | ||
|
|
1f82bb39da | ||
|
|
587a1ef07b | ||
|
|
171de8b026 | ||
|
|
1dccbe42a3 | ||
|
|
be639eaf97 | ||
|
|
055d8424a6 | ||
|
|
5a7e816fb7 | ||
|
|
a06ed5806a | ||
|
|
d3ecbe2cc9 | ||
|
|
41aed0984f | ||
|
|
080b9760e3 | ||
|
|
4d65d12add | ||
|
|
dacdbc5c45 | ||
|
|
6d9230ff91 | ||
|
|
1d47256cbc | ||
|
|
9d613a5a13 | ||
|
|
06e23007ed | ||
|
|
3cfe7cbb80 | ||
|
|
5004c91a6c | ||
|
|
b0d6e8a520 | ||
|
|
abcdb214f2 | ||
|
|
f335f274ab | ||
|
|
5af7cc35e9 | ||
|
|
9550731681 | ||
|
|
ec6fe8ea98 | ||
|
|
ddefd14409 | ||
|
|
76eddc9f02 | ||
|
|
9489ede03c | ||
|
|
2f1c16c781 | ||
|
|
050394135a | ||
|
|
7f7b91851e | ||
|
|
b8f704abb9 | ||
|
|
115533cd62 |
@@ -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"),
|
||||
}
|
||||
|
||||
@@ -40,7 +40,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 +120,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 +130,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,21 +147,18 @@ jobs:
|
||||
- name: Verify shared license catalog
|
||||
run: python3 -B apps/ios/scripts/generate_third_party_licenses.py
|
||||
|
||||
- name: Build APKs and run Lint
|
||||
- name: Build APKs
|
||||
working-directory: apps/android
|
||||
run: |
|
||||
./gradlew --no-daemon --stacktrace \
|
||||
:app:assembleDebug :app:assembleRelease :app:assembleDebugAndroidTest \
|
||||
:app:lintDebug :app:lintRelease
|
||||
:app:assembleDebug :app:assembleRelease
|
||||
|
||||
- name: Verify APKs and native protocol
|
||||
- name: Verify APKs
|
||||
working-directory: apps/android
|
||||
run: |
|
||||
python3 -B test/verify_apk.py app/build/outputs/apk/debug/app-debug.apk
|
||||
python3 -B test/verify_apk.py app/build/outputs/apk/release/app-release-unsigned.apk
|
||||
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
|
||||
@@ -198,19 +196,17 @@ jobs:
|
||||
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 +215,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
|
||||
|
||||
|
||||
+74
-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
|
||||
@@ -384,13 +404,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 +459,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 +611,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 +668,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 +686,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.
|
||||
|
||||
|
||||
@@ -68,17 +68,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>
|
||||
@@ -156,7 +171,7 @@ sudo apt install "./crossdesk-linux-amd64-<version>.deb"
|
||||
|
||||
### 检查更新
|
||||
|
||||
客户端启动后会在后台检查版本。发现新版本时,主窗口菜单入口会显示更新提示;打开 **☰ → 关于** 可查看版本,也可点击 **检查更新** 手动检查。发现更新后可查看更新说明并前往下载页面。
|
||||
客户端启动后会在后台检查版本,发现新版本时自动弹出更新提示,可查看更新说明并前往下载页面。关闭提示后,本次运行中的后台检查不会再次弹窗,主窗口菜单入口仍会显示更新提示;重新启动客户端后,如仍有新版本则再次提示。打开 **☰ → 关于** 可查看版本;有新版本时,点击版本信息下方的 **更新日志** 可再次打开更新提示,也可点击 **检查更新** 手动检查。
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/desktop-about-zh.png" width="720" alt="关于窗口与检查更新按钮,版本号和检查结果为演示数据" />
|
||||
@@ -191,7 +206,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>
|
||||
|
||||
+44
-4
@@ -68,17 +68,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>
|
||||
@@ -156,7 +171,7 @@ Open **☰ → Settings** in the top-right corner and click **OK** to save. Conf
|
||||
|
||||
### 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 +198,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>
|
||||
|
||||
+42
-11
@@ -4,7 +4,7 @@
|
||||
|
||||
## 当前功能
|
||||
|
||||
- 官方或自托管 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
|
||||
```
|
||||
@@ -88,18 +96,17 @@ 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 的 arm64 ABI、16 KB ELF / ZIP 对齐、完整许可证及 Debug 签名。单元测试、本机 C++ 协议与画面队列测试、Lint 和设备测试改为按需在本地执行;设备测试使用下面的设备验证流程在 arm64 手机或模拟器上执行。
|
||||
|
||||
产物使用 Android 工程自己的 `versionName`,例如 `v1.6.0-20261002`,不跟随桌面版本号。构建日期采用上海时区;带日期的版本标签沿用标签中的日期,与 iOS 一致。Actions 提供:
|
||||
|
||||
- `crossdesk-android-arm64-<版本>.apk`:已签名 Release APK,独立安卓发布和全平台标签发布收集此 APK,可直接安装。
|
||||
- `crossdesk-android-arm64-unsigned-<版本>.apk`:构建工作流的中间产物,也可用于自行签名和验证修改后的构建。
|
||||
- `crossdesk-android-arm64-debug-<版本>.apk` 和对应的 `-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` 检查。
|
||||
|
||||
@@ -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 时仍可使用软件编解码。独立输出线程在画面停止更新后仍会取出最后一帧,空闲时休眠。
|
||||
|
||||
@@ -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>
|
||||
@@ -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,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()
|
||||
@@ -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
|
||||
@@ -62,6 +62,8 @@
|
||||
#endif
|
||||
#include "rd_log.h"
|
||||
#include "server_window_state.h"
|
||||
#include "signal_server_settings.h"
|
||||
#include "signal_server_address.h"
|
||||
#include "ui/announcement_text.h"
|
||||
#include "ui/ui_localization.h"
|
||||
#include "update_checker.h"
|
||||
@@ -665,7 +667,7 @@ struct WindowDragState {
|
||||
slint::Timer pointer_timer;
|
||||
#endif
|
||||
|
||||
bool ReadGlobalPointer(float* x, float* y) {
|
||||
bool ReadGlobalPointer(float* x, float* y, bool* left_pressed = nullptr) {
|
||||
#if defined(__linux__) && !defined(__APPLE__)
|
||||
const char* driver = SDL_GetCurrentVideoDriver();
|
||||
if (driver && std::strcmp(driver, "x11") == 0) {
|
||||
@@ -686,12 +688,14 @@ struct WindowDragState {
|
||||
&buttons)) {
|
||||
return false;
|
||||
}
|
||||
if (left_pressed) *left_pressed = (buttons & Button1Mask) != 0;
|
||||
*x = static_cast<float>(root_x);
|
||||
*y = static_cast<float>(root_y);
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
SDL_GetGlobalMouseState(x, y);
|
||||
const auto buttons = SDL_GetGlobalMouseState(x, y);
|
||||
if (left_pressed) *left_pressed = (buttons & SDL_BUTTON_LMASK) != 0;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
@@ -710,14 +714,6 @@ bool CanUseGlobalPointerPosition() {
|
||||
#endif
|
||||
}
|
||||
|
||||
float ServerWindowLogicalWidth(int language) {
|
||||
return language == 0 ? 250.0f : language == 1 ? 330.0f : 430.0f;
|
||||
}
|
||||
|
||||
float ServerWindowLogicalHeight(bool collapsed) {
|
||||
return collapsed ? 30.0f : 150.0f;
|
||||
}
|
||||
|
||||
constexpr float kStreamWindowLogicalWidth = 1280.0f;
|
||||
constexpr float kStreamWindowLogicalHeight = 720.0f;
|
||||
constexpr float kWaylandTitlebarLogicalHeight = 32.0f;
|
||||
@@ -798,57 +794,6 @@ bool PositionWindowAtCenter(slint::Window& window, const slint::Window& anchor,
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PositionWindowAtBottomRight(slint::Window& window, float logical_width,
|
||||
float logical_height) {
|
||||
if (!CanUseGlobalPointerPosition()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto position = window.position();
|
||||
const auto size = window.size();
|
||||
#if defined(__APPLE__)
|
||||
const float scale = std::max(window.scale_factor(), 0.01f);
|
||||
const SDL_Point center{
|
||||
static_cast<int>(
|
||||
std::lround(position.x / scale + size.width / (2.0f * scale))),
|
||||
static_cast<int>(
|
||||
std::lround(position.y / scale + size.height / (2.0f * scale)))};
|
||||
#else
|
||||
const SDL_Point center{
|
||||
position.x + static_cast<int>(size.width / 2),
|
||||
position.y + static_cast<int>(size.height / 2)};
|
||||
#endif
|
||||
SDL_DisplayID display = SDL_GetDisplayForPoint(¢er);
|
||||
if (display == 0) {
|
||||
display = SDL_GetPrimaryDisplay();
|
||||
}
|
||||
|
||||
SDL_Rect usable_bounds{};
|
||||
if (display == 0 || !SDL_GetDisplayUsableBounds(display, &usable_bounds)) {
|
||||
LOG_WARN("Unable to obtain usable display bounds for server window: {}",
|
||||
SDL_GetError());
|
||||
return false;
|
||||
}
|
||||
|
||||
#if defined(__APPLE__)
|
||||
const float target_x =
|
||||
static_cast<float>(usable_bounds.x) +
|
||||
std::max(0.0f, static_cast<float>(usable_bounds.w) - logical_width);
|
||||
const float target_y =
|
||||
static_cast<float>(usable_bounds.y) +
|
||||
std::max(0.0f, static_cast<float>(usable_bounds.h) - logical_height);
|
||||
window.set_position(
|
||||
slint::LogicalPosition(slint::Point<float>{target_x, target_y}));
|
||||
#else
|
||||
const auto target = window_geometry::BottomRightPosition(
|
||||
PhysicalDisplayBounds(usable_bounds),
|
||||
PhysicalWindowSize(window, logical_width, logical_height));
|
||||
window.set_position(slint::PhysicalPosition(
|
||||
slint::Point<int32_t>{target.x, target.y}));
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
#if _WIN32
|
||||
bool ConfigureWindowsServerWindow(slint::Window& window) {
|
||||
const HWND hwnd = window.win32_hwnd();
|
||||
@@ -977,6 +922,7 @@ struct GuiApplication::SlintUi {
|
||||
std::make_shared<slint::VectorModel<ui::ReleaseNoteBlock>>();
|
||||
std::optional<slint::ComponentHandle<ui::StreamWindow>> stream;
|
||||
std::optional<slint::ComponentHandle<ui::ServerWindow>> server;
|
||||
std::optional<slint::ComponentHandle<ui::ServerStatusBar>> server_bar;
|
||||
std::shared_ptr<slint::VectorModel<ui::RecentConnection>> recent_model =
|
||||
std::make_shared<slint::VectorModel<ui::RecentConnection>>();
|
||||
std::shared_ptr<slint::VectorModel<ui::StreamTab>> tab_model =
|
||||
@@ -989,26 +935,32 @@ struct GuiApplication::SlintUi {
|
||||
std::make_shared<slint::VectorModel<ui::NetworkStatsRow>>();
|
||||
std::shared_ptr<slint::VectorModel<ui::ControllerEntry>> controller_model =
|
||||
std::make_shared<slint::VectorModel<ui::ControllerEntry>>();
|
||||
std::shared_ptr<slint::VectorModel<slint::SharedString>>
|
||||
controller_name_model =
|
||||
std::make_shared<slint::VectorModel<slint::SharedString>>();
|
||||
std::unique_ptr<SlintVideoPresenter> video_presenter;
|
||||
std::vector<std::string> tab_order;
|
||||
std::vector<std::string> tab_ids;
|
||||
std::string tab_model_signature;
|
||||
std::vector<std::string> controller_ids;
|
||||
std::string controller_model_signature;
|
||||
std::string connection_dialog_remote_id;
|
||||
bool connection_password_initialized = false;
|
||||
bool portable_service_dialog_initialized = false;
|
||||
std::string recent_model_signature;
|
||||
slint::Timer timer;
|
||||
slint::Timer server_file_dialog_timer;
|
||||
WindowDragState main_drag;
|
||||
WindowDragState stream_drag;
|
||||
WindowDragState server_drag;
|
||||
int main_native_titlebar_attempts = 30;
|
||||
int stream_live_resize_configuration_attempts = 0;
|
||||
int stream_initial_position_attempts = 0;
|
||||
int server_initial_position_attempts = 0;
|
||||
SDL_DisplayID server_display = 0;
|
||||
float server_anchor = 0.3f;
|
||||
float server_drag_anchor = 0.3f;
|
||||
bool server_drag_moved = false;
|
||||
bool server_pointer_pressed = false;
|
||||
bool server_file_dialog_open = false;
|
||||
bool server_suspended_for_dialog = false;
|
||||
server_window_state::EdgeLayout server_layout{};
|
||||
#if _WIN32
|
||||
int server_native_window_attempts = 0;
|
||||
#endif
|
||||
@@ -1334,6 +1286,7 @@ void GuiApplication::ResetSettingsUi() {
|
||||
ui_->main->set_file_save_path(file_transfer_save_path_buf_);
|
||||
ui_->main->set_server_host(signal_server_ip_self_);
|
||||
ui_->main->set_server_port(signal_server_port_self_);
|
||||
ui_->main->set_self_host_settings_error("");
|
||||
}
|
||||
|
||||
void GuiApplication::BindMainCallbacks() {
|
||||
@@ -1468,29 +1421,14 @@ void GuiApplication::BindMainCallbacks() {
|
||||
ui_->main->set_file_save_path(folder);
|
||||
}
|
||||
});
|
||||
main->on_save_settings([this] { SaveSettingsFromUi(); });
|
||||
main->on_save_settings([this] { return SaveSettingsFromUi(); });
|
||||
main->on_cancel_settings([this] { ResetSettingsUi(); });
|
||||
main->on_save_self_hosted_settings([this] {
|
||||
const std::string host(ui_->main->get_server_host());
|
||||
const auto signal_port = ParsePort(ui_->main->get_server_port());
|
||||
if (!host.empty()) {
|
||||
config_center_->SetServerHost(host);
|
||||
std::memset(signal_server_ip_self_, 0, sizeof(signal_server_ip_self_));
|
||||
std::strncpy(signal_server_ip_self_, host.c_str(),
|
||||
sizeof(signal_server_ip_self_) - 1);
|
||||
std::memset(signal_server_ip_, 0, sizeof(signal_server_ip_));
|
||||
std::strncpy(signal_server_ip_, host.c_str(),
|
||||
sizeof(signal_server_ip_) - 1);
|
||||
}
|
||||
if (signal_port) {
|
||||
config_center_->SetServerPort(*signal_port);
|
||||
std::snprintf(signal_server_port_self_, sizeof(signal_server_port_self_),
|
||||
"%d", *signal_port);
|
||||
std::snprintf(signal_server_port_, sizeof(signal_server_port_), "%d",
|
||||
*signal_port);
|
||||
}
|
||||
// Stage the endpoint until the surrounding settings dialog is confirmed.
|
||||
return ValidateSelfHostedSettingsFromUi();
|
||||
});
|
||||
main->on_cancel_self_hosted_settings([this] {
|
||||
ui_->main->set_self_host_settings_error("");
|
||||
const std::string host = config_center_->GetSignalServerHost();
|
||||
ui_->main->set_server_host(UiText(host));
|
||||
const int signal_port = config_center_->GetSignalServerPort();
|
||||
@@ -1498,7 +1436,11 @@ void GuiApplication::BindMainCallbacks() {
|
||||
? UiText(std::to_string(signal_port))
|
||||
: slint::SharedString{});
|
||||
});
|
||||
main->on_open_download([this] { OpenUrl("https://crossdesk.cn"); });
|
||||
main->on_open_download([this] {
|
||||
const auto& latest = update_checker_->latest();
|
||||
OpenUrl(latest && !latest->download_url.empty() ? latest->download_url
|
||||
: "https://crossdesk.cn");
|
||||
});
|
||||
main->on_check_for_updates([this] {
|
||||
update_checker_->RequestCheck();
|
||||
SyncMainWindow();
|
||||
@@ -1855,18 +1797,37 @@ void GuiApplication::BindServerCallbacks() {
|
||||
return;
|
||||
}
|
||||
auto& server = *ui_->server;
|
||||
server->on_title_drag([this](int phase, float x, float y) {
|
||||
auto& bar = *ui_->server_bar;
|
||||
bar->on_title_drag([this](int phase, float, float) {
|
||||
auto& drag = ui_->server_drag;
|
||||
DragWindow(*ui_->server, phase, x, y, drag);
|
||||
if (phase == 1) {
|
||||
ui_->server_drag_moved = false;
|
||||
(*ui_->server_bar)->set_dragged(false);
|
||||
drag.active = CanUseGlobalPointerPosition() &&
|
||||
drag.ReadGlobalPointer(&drag.pointer_start_x, &drag.pointer_start_y);
|
||||
ui_->server_drag_anchor = ui_->server_anchor;
|
||||
} else if (phase == 0) {
|
||||
PositionServerWindows();
|
||||
drag.active = false;
|
||||
}
|
||||
});
|
||||
server->on_toggle_collapsed([this](bool collapsed) {
|
||||
server_window_collapsed_ = collapsed;
|
||||
const int language = (*ui_->server)->get_language_index();
|
||||
const float width = ServerWindowLogicalWidth(language);
|
||||
(*ui_->server)
|
||||
->window()
|
||||
.set_size(slint::LogicalSize(
|
||||
slint::Size<float>{width, ServerWindowLogicalHeight(collapsed)}));
|
||||
bar->on_toggle_panel([this] {
|
||||
SetServerPanelExpanded(server_window_collapsed_);
|
||||
});
|
||||
bar->on_move_anchor([this](float delta) {
|
||||
ui_->server_anchor = std::clamp(ui_->server_anchor + delta, 0.0f, 1.0f);
|
||||
PositionServerWindows();
|
||||
});
|
||||
const auto dismiss = [this] { SetServerPanelExpanded(false); };
|
||||
bar->on_dismiss_panel(dismiss);
|
||||
server->on_dismiss_panel(dismiss);
|
||||
server->window().on_close_requested([dismiss] {
|
||||
dismiss();
|
||||
return slint::CloseRequestResponse::KeepWindowShown;
|
||||
});
|
||||
bar->window().on_close_requested([dismiss] {
|
||||
dismiss();
|
||||
return slint::CloseRequestResponse::KeepWindowShown;
|
||||
});
|
||||
server->on_controller_selected([this](int index) {
|
||||
if (index < 0 || index >= static_cast<int>(ui_->controller_ids.size())) {
|
||||
@@ -1875,17 +1836,43 @@ void GuiApplication::BindServerCallbacks() {
|
||||
selected_server_remote_id_ = ui_->controller_ids[index];
|
||||
});
|
||||
server->on_select_file([this] {
|
||||
if (selected_server_remote_id_.empty()) {
|
||||
if (selected_server_remote_id_.empty() || ui_->server_file_dialog_open) {
|
||||
return;
|
||||
}
|
||||
transfers_.ProcessSelectedFile(
|
||||
OpenFileDialog(localization::select_file[localization_language_index_]),
|
||||
nullptr, file_label_, selected_server_remote_id_);
|
||||
// A native file picker runs a nested event loop. Keep the recipient stable
|
||||
// if another controller connects or leaves while it is open.
|
||||
const std::string recipient = selected_server_remote_id_;
|
||||
ui_->server_file_dialog_open = true;
|
||||
(*ui_->server)->window().request_redraw();
|
||||
// TouchArea clears pressed only after its clicked callback returns. Allow
|
||||
// that release and a repaint before entering the blocking native picker.
|
||||
ui_->server_file_dialog_timer.start(
|
||||
slint::TimerMode::SingleShot, std::chrono::milliseconds(32),
|
||||
[this, recipient] {
|
||||
const auto connected = [this, &recipient] {
|
||||
std::shared_lock lock(connection_status_mutex_);
|
||||
const auto found = connection_status_.find(recipient);
|
||||
return found != connection_status_.end() &&
|
||||
found->second == ConnectionStatus::Connected;
|
||||
};
|
||||
if (!connected()) {
|
||||
ui_->server_file_dialog_open = false;
|
||||
return;
|
||||
}
|
||||
const auto path = OpenFileDialog(
|
||||
localization::select_file[localization_language_index_]);
|
||||
ui_->server_file_dialog_open = false;
|
||||
if (connected() && !path.empty())
|
||||
transfers_.ProcessSelectedFile(path, nullptr, file_label_, recipient);
|
||||
});
|
||||
});
|
||||
server->on_disconnect_controller([this] {
|
||||
if (peer_ && !selected_server_remote_id_.empty()) {
|
||||
CloseServerController(selected_server_remote_id_);
|
||||
}
|
||||
server->on_disconnect_controller([this](slint::SharedString id) {
|
||||
CloseServerController(std::string(id));
|
||||
});
|
||||
server->on_disconnect_all([this] {
|
||||
// Work from the confirmed UI snapshot; a later arrival is a new session.
|
||||
const auto ids = ui_->controller_ids;
|
||||
for (const auto& id : ids) CloseServerController(id);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1972,6 +1959,7 @@ void GuiApplication::Tick() {
|
||||
devices_.UpdateInteractions();
|
||||
ShareLocalCursorState();
|
||||
|
||||
CloseRemoteClosedTabs();
|
||||
UpdateLocalization();
|
||||
SyncMainWindow();
|
||||
SyncConnectionDialog();
|
||||
@@ -2762,6 +2750,7 @@ void GuiApplication::SyncStreamWindow() {
|
||||
std::shared_lock lock(remote_sessions_mutex_);
|
||||
has_sessions = !remote_sessions_.empty();
|
||||
}
|
||||
if (!has_sessions) need_to_create_stream_window_ = false;
|
||||
if (need_to_create_stream_window_ && !ui_->stream) {
|
||||
ui_->stream.emplace(ui::StreamWindow::create());
|
||||
#if defined(__linux__)
|
||||
@@ -3249,6 +3238,96 @@ void GuiApplication::ScheduleNextVideoFrame() {
|
||||
[this] { ScheduleNextVideoFrame(); });
|
||||
}
|
||||
|
||||
void GuiApplication::SetServerPanelExpanded(bool expanded) {
|
||||
if (!ui_->server || !ui_->server_bar) return;
|
||||
server_window_collapsed_ = !expanded;
|
||||
(*ui_->server_bar)->set_expanded(expanded);
|
||||
if (expanded) {
|
||||
PositionServerWindows();
|
||||
(*ui_->server)->show();
|
||||
#if _WIN32
|
||||
ConfigureWindowsServerWindow((*ui_->server)->window());
|
||||
#endif
|
||||
PositionServerWindows();
|
||||
} else {
|
||||
(*ui_->server)->set_confirming_disconnect(false);
|
||||
(*ui_->server)->hide();
|
||||
}
|
||||
}
|
||||
|
||||
void GuiApplication::PositionServerWindows() {
|
||||
if (!ui_->server || !ui_->server_bar) return;
|
||||
auto& bar = *ui_->server_bar;
|
||||
auto& panel = *ui_->server;
|
||||
const float scale = std::max(bar->window().scale_factor(), 0.01f);
|
||||
SDL_Rect bounds{};
|
||||
if (!SDL_GetDisplayUsableBounds(ui_->server_display, &bounds)) {
|
||||
ui_->server_display = SDL_GetPrimaryDisplay();
|
||||
if (!SDL_GetDisplayUsableBounds(ui_->server_display, &bounds)) return;
|
||||
}
|
||||
// Cocoa/SDL uses points; Windows and X11 report desktop pixels.
|
||||
#if defined(__APPLE__)
|
||||
const float desktop_scale = 1;
|
||||
#else
|
||||
const float desktop_scale = scale;
|
||||
#endif
|
||||
const server_window_state::Rect screen{
|
||||
bounds.x / desktop_scale, bounds.y / desktop_scale,
|
||||
bounds.w / desktop_scale, bounds.h / desktop_scale};
|
||||
float pointer_x = 0, pointer_y = 0;
|
||||
bool pressed = false;
|
||||
const bool pointer_valid = CanUseGlobalPointerPosition() &&
|
||||
ui_->server_drag.ReadGlobalPointer(&pointer_x, &pointer_y, &pressed);
|
||||
if (pointer_valid && ui_->server_drag.active) {
|
||||
const float delta = (pointer_y - ui_->server_drag.pointer_start_y) / desktop_scale;
|
||||
if (std::abs(delta) >= 4) {
|
||||
ui_->server_drag_moved = true;
|
||||
bar->set_dragged(true);
|
||||
}
|
||||
if (ui_->server_drag_moved) {
|
||||
const float travel = std::max(1.0f, screen.height - 52.0f);
|
||||
ui_->server_anchor = std::clamp(ui_->server_drag_anchor + delta / travel, 0.0f, 1.0f);
|
||||
}
|
||||
if (!pressed) ui_->server_drag.active = false;
|
||||
}
|
||||
ui_->server_layout = server_window_state::PlacePanel(
|
||||
screen, ui_->server_anchor, bar->get_bar_width(), panel->get_content_height());
|
||||
const auto& layout = ui_->server_layout;
|
||||
bar->set_opens_above(layout.above);
|
||||
const auto apply = [scale](slint::Window& window, const server_window_state::Rect& rect) {
|
||||
const auto size = window.size();
|
||||
const float own_scale = std::max(window.scale_factor(), 0.01f);
|
||||
if (std::abs(size.width / own_scale - rect.width) > 0.5f ||
|
||||
std::abs(size.height / own_scale - rect.height) > 0.5f) {
|
||||
window.set_size(slint::LogicalSize(slint::Size<float>{rect.width, rect.height}));
|
||||
}
|
||||
if (!CanUseGlobalPointerPosition()) return;
|
||||
const auto position = window.position();
|
||||
if (std::abs(position.x / scale - rect.x) <= 0.5f &&
|
||||
std::abs(position.y / scale - rect.y) <= 0.5f) return;
|
||||
#if defined(__APPLE__)
|
||||
window.set_position(slint::LogicalPosition(slint::Point<float>{rect.x, rect.y}));
|
||||
#else
|
||||
window.set_position(slint::PhysicalPosition(slint::Point<int32_t>{
|
||||
static_cast<int32_t>(std::lround(rect.x * scale)),
|
||||
static_cast<int32_t>(std::lround(rect.y * scale))}));
|
||||
#endif
|
||||
};
|
||||
apply(bar->window(), layout.bar);
|
||||
apply(panel->window(), layout.panel);
|
||||
if (pointer_valid) {
|
||||
const float x = pointer_x / desktop_scale;
|
||||
const float y = pointer_y / desktop_scale;
|
||||
if (pressed && !ui_->server_pointer_pressed && !server_window_collapsed_ &&
|
||||
!ui_->server_file_dialog_open && !ui_->server_drag.active &&
|
||||
!server_window_state::Contains(layout.bar, x, y) &&
|
||||
!server_window_state::Contains(layout.panel, x, y)) {
|
||||
SetServerPanelExpanded(false);
|
||||
}
|
||||
ui_->server_pointer_pressed = pressed;
|
||||
}
|
||||
}
|
||||
|
||||
void GuiApplication::SyncServerWindow() {
|
||||
// The connection map is authoritative. Lifecycle flags record callback
|
||||
// intent, but callbacks for different controllers can cross each other, so
|
||||
@@ -3279,22 +3358,21 @@ void GuiApplication::SyncServerWindow() {
|
||||
#endif
|
||||
if (show_controller_window && !ui_->server) {
|
||||
ui_->server.emplace(ui::ServerWindow::create());
|
||||
ui_->server_bar.emplace(ui::ServerStatusBar::create());
|
||||
RegisterFontAwesome((*ui_->server)->window());
|
||||
RegisterFontAwesome((*ui_->server_bar)->window());
|
||||
(*ui_->server)->set_controllers(ui_->controller_model);
|
||||
(*ui_->server)->set_controller_names(ui_->controller_name_model);
|
||||
(*ui_->server)->set_language_index(localization_language_index_);
|
||||
server_window_collapsed_ = false;
|
||||
(*ui_->server)
|
||||
->window()
|
||||
.set_size(slint::LogicalSize(slint::Size<float>{
|
||||
ServerWindowLogicalWidth(localization_language_index_),
|
||||
ServerWindowLogicalHeight(false)}));
|
||||
server_window_collapsed_ = true;
|
||||
ui_->server_display = DisplayForSlintWindow(ui_->main->window());
|
||||
ui_->server_anchor = 0.3f;
|
||||
ui_->server_drag.active = false;
|
||||
ui_->server_drag_moved = false;
|
||||
ui_->server_pointer_pressed = false;
|
||||
ui_->server_suspended_for_dialog = false;
|
||||
BindServerCallbacks();
|
||||
(*ui_->server)->show();
|
||||
// Apply once immediately and once after the next layout pass. This keeps
|
||||
// the right and bottom edges correct when the backend resolves DPI and
|
||||
// language-dependent preferred width asynchronously on first show.
|
||||
ui_->server_initial_position_attempts = 2;
|
||||
ui_localization::ApplyServerStrings(*ui_->server, localization_language_index_);
|
||||
ui_localization::ApplyServerStrings(*ui_->server_bar, localization_language_index_);
|
||||
(*ui_->server_bar)->show();
|
||||
#if _WIN32
|
||||
ui_->server_native_window_attempts = 30;
|
||||
#endif
|
||||
@@ -3303,98 +3381,75 @@ void GuiApplication::SyncServerWindow() {
|
||||
}
|
||||
if (!show_controller_window && ui_->server) {
|
||||
(*ui_->server)->hide();
|
||||
(*ui_->server_bar)->hide();
|
||||
// Keep handles alive through a native file dialog's nested event loop.
|
||||
if (ui_->server_file_dialog_open) {
|
||||
server_window_collapsed_ = true;
|
||||
(*ui_->server_bar)->set_expanded(false);
|
||||
(*ui_->server)->set_confirming_disconnect(false);
|
||||
ui_->server_suspended_for_dialog = true;
|
||||
return;
|
||||
}
|
||||
ui_->server.reset();
|
||||
ui_->server_bar.reset();
|
||||
ui_->server_drag.active = false;
|
||||
server_window_created_ = false;
|
||||
server_window_inited_ = false;
|
||||
ui_->server_initial_position_attempts = 0;
|
||||
#if _WIN32
|
||||
ui_->server_native_window_attempts = 0;
|
||||
#endif
|
||||
}
|
||||
if (!ui_->server) {
|
||||
return;
|
||||
if (!ui_->server) return;
|
||||
if (ui_->server_suspended_for_dialog) {
|
||||
(*ui_->server_bar)->show();
|
||||
ui_->server_suspended_for_dialog = false;
|
||||
}
|
||||
|
||||
#if _WIN32
|
||||
ConfigureWindowsWindowIcons((*ui_->server)->window().win32_hwnd());
|
||||
#endif
|
||||
|
||||
std::vector<ui::ControllerEntry> controllers;
|
||||
std::vector<slint::SharedString> names;
|
||||
ui_->controller_ids.clear();
|
||||
{
|
||||
std::shared_lock lock(connection_status_mutex_);
|
||||
controllers.reserve(connection_status_.size());
|
||||
for (const auto& [id, _] : connection_status_) {
|
||||
for (const auto& [id, status] : connection_status_) {
|
||||
if (status != ConnectionStatus::Connected) continue;
|
||||
const auto host = connection_host_names_.find(id);
|
||||
const std::string name =
|
||||
host != connection_host_names_.end() && !host->second.empty()
|
||||
? host->second
|
||||
: id;
|
||||
ui::ControllerEntry entry;
|
||||
entry.remote_id = UiText(id);
|
||||
entry.display_name = UiText(name);
|
||||
controllers.push_back(entry);
|
||||
names.emplace_back(UiText(name));
|
||||
ui_->controller_ids.push_back(id);
|
||||
? host->second : id;
|
||||
controllers.push_back({UiText(id), UiText(name)});
|
||||
}
|
||||
}
|
||||
ui_->controller_model->set_vector(std::move(controllers));
|
||||
ui_->controller_name_model->set_vector(std::move(names));
|
||||
// Stable ordering and model identity preserve radio selection, hover and
|
||||
// scrolling while the 16 ms UI timer reconciles asynchronous peer events.
|
||||
std::sort(controllers.begin(), controllers.end(), [](const auto& a, const auto& b) {
|
||||
return std::string(a.remote_id) < std::string(b.remote_id);
|
||||
});
|
||||
std::vector<std::string> ids;
|
||||
std::string signature;
|
||||
for (const auto& controller : controllers) {
|
||||
ids.emplace_back(controller.remote_id);
|
||||
signature += std::string(controller.remote_id) + '\0' +
|
||||
std::string(controller.display_name) + '\0';
|
||||
}
|
||||
if (ids != ui_->controller_ids) (*ui_->server)->set_confirming_disconnect(false);
|
||||
ui_->controller_ids = std::move(ids);
|
||||
if (signature != ui_->controller_model_signature) {
|
||||
ui_->controller_model->set_vector(std::move(controllers));
|
||||
ui_->controller_model_signature = std::move(signature);
|
||||
}
|
||||
const int selected = server_window_state::ReconcileSelectedController(
|
||||
ui_->controller_ids, &selected_server_remote_id_);
|
||||
(*ui_->server)->set_selected_controller(selected);
|
||||
(*ui_->server)->set_language_index(localization_language_index_);
|
||||
(*ui_->server_bar)->set_controller_count(static_cast<int>(ui_->controller_ids.size()));
|
||||
ui_localization::ApplyServerStrings(*ui_->server, localization_language_index_);
|
||||
ui_localization::ApplyServerStrings(*ui_->server_bar, localization_language_index_);
|
||||
#if _WIN32
|
||||
if (ui_->server_native_window_attempts > 0) {
|
||||
if (ConfigureWindowsServerWindow((*ui_->server)->window())) {
|
||||
if (ConfigureWindowsServerWindow((*ui_->server_bar)->window()))
|
||||
ui_->server_native_window_attempts = 0;
|
||||
} else {
|
||||
else
|
||||
--ui_->server_native_window_attempts;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
if (ui_->server_initial_position_attempts > 0) {
|
||||
const float server_width =
|
||||
ServerWindowLogicalWidth(localization_language_index_);
|
||||
const float server_height =
|
||||
ServerWindowLogicalHeight(server_window_collapsed_);
|
||||
(*ui_->server)
|
||||
->window()
|
||||
.set_size(slint::LogicalSize(
|
||||
slint::Size<float>{server_width, server_height}));
|
||||
if (PositionWindowAtBottomRight((*ui_->server)->window(), server_width,
|
||||
server_height)) {
|
||||
--ui_->server_initial_position_attempts;
|
||||
} else {
|
||||
ui_->server_initial_position_attempts = 0;
|
||||
}
|
||||
}
|
||||
(*ui_->server)
|
||||
->set_controller_label(
|
||||
UiText(localization::controller[localization_language_index_]));
|
||||
(*ui_->server)
|
||||
->set_connection_label(UiText(
|
||||
localization::connection_status[localization_language_index_]));
|
||||
(*ui_->server)
|
||||
->set_file_transfer_label(
|
||||
UiText(localization::file_transfer[localization_language_index_]));
|
||||
(*ui_->server)
|
||||
->set_select_file_label(
|
||||
UiText(localization::select_file[localization_language_index_]));
|
||||
|
||||
ConnectionStatus status = ConnectionStatus::Closed;
|
||||
{
|
||||
std::shared_lock lock(connection_status_mutex_);
|
||||
if (const auto found = connection_status_.find(selected_server_remote_id_);
|
||||
found != connection_status_.end()) {
|
||||
status = found->second;
|
||||
}
|
||||
}
|
||||
(*ui_->server)
|
||||
->set_connection_status(
|
||||
UiText(ConnectionStatusText(status, localization_language_index_)));
|
||||
|
||||
auto& transfer = transfers_.global_state();
|
||||
const auto sent = transfer.file_sent_bytes_.load();
|
||||
const auto total = transfer.file_total_bytes_.load();
|
||||
@@ -3425,10 +3480,48 @@ void GuiApplication::SyncServerWindow() {
|
||||
->set_file_size_text(total == 0 ? slint::SharedString{}
|
||||
: UiText(FormatFileSize(sent) + " / " +
|
||||
FormatFileSize(total)));
|
||||
PositionServerWindows();
|
||||
}
|
||||
|
||||
void GuiApplication::SaveSettingsFromUi() {
|
||||
bool GuiApplication::ValidateSelfHostedSettingsFromUi() {
|
||||
auto& main = ui_->main;
|
||||
const auto address = minirtc::ParseSignalServerAddress(
|
||||
std::string(main->get_server_host()));
|
||||
if (!address) {
|
||||
main->set_self_host_settings_error(UiText(
|
||||
localization::self_hosted_address_invalid[localization_language_index_]));
|
||||
return false;
|
||||
}
|
||||
const auto port = address->port ? address->port : ParsePort(main->get_server_port());
|
||||
if (!port) {
|
||||
main->set_self_host_settings_error(UiText(
|
||||
localization::self_hosted_port_invalid[localization_language_index_]));
|
||||
return false;
|
||||
}
|
||||
main->set_server_host(UiText(address->Address()));
|
||||
main->set_server_port(UiText(std::to_string(*port)));
|
||||
main->set_self_host_settings_error("");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool GuiApplication::SaveSettingsFromUi() {
|
||||
const auto previous_server = GetSignalServerSettings(*config_center_);
|
||||
auto& main = ui_->main;
|
||||
const bool has_endpoint = main->get_self_hosted_enabled() ||
|
||||
!std::string(main->get_server_host()).empty() ||
|
||||
!std::string(main->get_server_port()).empty();
|
||||
if (has_endpoint && !ValidateSelfHostedSettingsFromUi()) {
|
||||
main->set_self_host_settings_open(true);
|
||||
return false;
|
||||
}
|
||||
if ((has_endpoint && config_center_->SetServerEndpoint(
|
||||
std::string(main->get_server_host()), *ParsePort(main->get_server_port())) != 0) ||
|
||||
config_center_->SetSelfHosted(main->get_self_hosted_enabled()) != 0) {
|
||||
main->set_self_host_settings_error(UiText(
|
||||
localization::self_hosted_save_failed[localization_language_index_]));
|
||||
main->set_self_host_settings_open(true);
|
||||
return false;
|
||||
}
|
||||
language_button_value_ =
|
||||
localization::detail::ClampLanguageIndex(main->get_language_index());
|
||||
video_encode_format_button_value_ = std::clamp(main->get_codec_index(), 0, 1);
|
||||
@@ -3462,10 +3555,18 @@ void GuiApplication::SaveSettingsFromUi() {
|
||||
reload_recent_connections_ = true;
|
||||
#ifdef _WIN32
|
||||
if (!HasActiveSession()) {
|
||||
const auto previous_capture_method = config_center_->GetScreenCaptureMethod();
|
||||
const auto capture_method = static_cast<ScreenCaptureMethod>(
|
||||
std::clamp(main->get_capture_method_index(), 0, 3));
|
||||
if (config_center_->SetScreenCaptureMethod(capture_method) != 0) {
|
||||
LOG_ERROR("Failed to save screen capture method");
|
||||
} else if (capture_method != previous_capture_method) {
|
||||
// Reconfigure only capture; its backend does not own signaling.
|
||||
devices_.StopScreenCapturer();
|
||||
screen_capturer_is_started_ = false;
|
||||
if (devices_.InitializeScreenCapturer() != 0) {
|
||||
LOG_ERROR("Failed to apply screen capture method");
|
||||
}
|
||||
}
|
||||
}
|
||||
main->set_capture_method_index(
|
||||
@@ -3486,16 +3587,9 @@ void GuiApplication::SaveSettingsFromUi() {
|
||||
sizeof(file_transfer_save_path_buf_) - 1);
|
||||
config_center_->SetFileTransferSavePath(path);
|
||||
|
||||
const std::string host(main->get_server_host());
|
||||
if (!host.empty()) {
|
||||
config_center_->SetServerHost(host);
|
||||
}
|
||||
if (const auto port = ParsePort(main->get_server_port())) {
|
||||
config_center_->SetServerPort(*port);
|
||||
}
|
||||
|
||||
config_center_->SetSelfHosted(enable_self_hosted_);
|
||||
ApplySettingsFromConfig(!HasActiveSession());
|
||||
ApplySettingsFromConfig(previous_server !=
|
||||
GetSignalServerSettings(*config_center_));
|
||||
return true;
|
||||
}
|
||||
|
||||
void GuiApplication::ApplySettingsFromConfig(bool reconnect) {
|
||||
@@ -3535,6 +3629,24 @@ void GuiApplication::ApplySettingsFromConfig(bool reconnect) {
|
||||
// Tick recreates the peer after asynchronous cleanup, using the committed
|
||||
// configuration. Keep the application and its console running throughout.
|
||||
CloseAllRemoteSessions();
|
||||
} else {
|
||||
const bool hardware = config_center_->IsHardwareVideoCodec();
|
||||
const bool av1 = config_center_->GetVideoEncodeFormat() ==
|
||||
ConfigCenter::VIDEO_ENCODE_FORMAT::AV1;
|
||||
const auto turn = static_cast<TurnMode>(config_center_->GetTurnMode());
|
||||
if (hardware != params_.hardware_acceleration || av1 != params_.av1_encoding ||
|
||||
turn != params_.turn_mode) {
|
||||
// Update the listening peer for incoming connections and the template
|
||||
// copied by ConnectTo for outgoing connections. Existing sessions retain
|
||||
// the codec/ICE snapshot with which they negotiated.
|
||||
if (!peer_ || UpdateConnectionSettings(peer_, hardware, av1, turn) == 0) {
|
||||
params_.hardware_acceleration = hardware;
|
||||
params_.av1_encoding = av1;
|
||||
params_.turn_mode = turn;
|
||||
} else {
|
||||
LOG_ERROR("Failed to apply connection settings without reconnecting");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3622,6 +3734,21 @@ void GuiApplication::ReorderStreamTab(int from, float drop_x, float tab_width) {
|
||||
SelectStreamTab(target);
|
||||
}
|
||||
|
||||
void GuiApplication::CloseRemoteClosedTabs() {
|
||||
std::vector<std::string> closed;
|
||||
{
|
||||
std::shared_lock lock(remote_sessions_mutex_);
|
||||
for (const auto& [id, props] : remote_sessions_) {
|
||||
if (props && props->remote_close_pending_.exchange(false)) {
|
||||
closed.push_back(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
// CloseRemoteSession drains transport callbacks and takes the session map
|
||||
// lock. Do this on the UI thread, outside both the callback and map lock.
|
||||
for (const auto& id : closed) CloseStreamTab(id);
|
||||
}
|
||||
|
||||
void GuiApplication::CloseStreamTab(const std::string& remote_id) {
|
||||
std::shared_ptr<RemoteSession> props;
|
||||
{
|
||||
@@ -3816,6 +3943,7 @@ void GuiApplication::Cleanup() {
|
||||
return;
|
||||
}
|
||||
ui_->timer.stop();
|
||||
ui_->server_file_dialog_timer.stop();
|
||||
ui_->video_timer.stop();
|
||||
#if _WIN32 && CROSSDESK_PORTABLE
|
||||
JoinPortableWindowsServiceInstallThread();
|
||||
@@ -3844,6 +3972,7 @@ void GuiApplication::Cleanup() {
|
||||
}
|
||||
if (ui_->server) {
|
||||
(*ui_->server)->hide();
|
||||
(*ui_->server_bar)->hide();
|
||||
}
|
||||
#if defined(_WIN32) || defined(__APPLE__) || defined(__linux__)
|
||||
if (ui_->tray) {
|
||||
|
||||
@@ -29,6 +29,9 @@ public:
|
||||
~GuiApplication();
|
||||
|
||||
int Run();
|
||||
#ifdef _WIN32
|
||||
int RunUnattended(void* stop_event);
|
||||
#endif
|
||||
|
||||
private:
|
||||
struct SlintUi;
|
||||
@@ -66,12 +69,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();
|
||||
bool ValidateSelfHostedSettingsFromUi();
|
||||
bool SaveSettingsFromUi();
|
||||
void ApplySettingsFromConfig(bool reconnect);
|
||||
#if _WIN32 && CROSSDESK_PORTABLE
|
||||
void CheckPortableWindowsService();
|
||||
@@ -82,6 +88,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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -240,6 +240,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"请输入六位密码:", \
|
||||
@@ -286,6 +289,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 +320,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"Состояние соединения:") \
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -115,7 +119,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_ =
|
||||
@@ -325,10 +329,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 +445,9 @@ int SessionDeviceManager::StartMouseController() {
|
||||
}
|
||||
|
||||
int SessionDeviceManager::StopMouseController() {
|
||||
#ifdef _WIN32
|
||||
ReleaseRemoteMouseButtons();
|
||||
#endif
|
||||
if (mouse_controller_) {
|
||||
mouse_controller_->Destroy();
|
||||
delete mouse_controller_;
|
||||
@@ -418,8 +457,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 +491,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 +512,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");
|
||||
@@ -601,7 +646,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 +668,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 +680,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 +706,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 +754,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,12 +7,10 @@
|
||||
#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 <vector>
|
||||
@@ -21,6 +19,7 @@
|
||||
|
||||
#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 +54,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.
|
||||
@@ -71,7 +71,7 @@ public:
|
||||
|
||||
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 +83,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;
|
||||
@@ -115,8 +105,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,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) {
|
||||
@@ -216,59 +227,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 +307,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;
|
||||
|
||||
@@ -308,7 +308,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() {
|
||||
|
||||
@@ -87,6 +87,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 +109,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_;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -209,6 +218,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 +237,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
|
||||
}
|
||||
@@ -384,45 +394,66 @@ 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) {
|
||||
if (remote_action.a)
|
||||
runtime->devices_.StartSpeakerCapturer();
|
||||
|
||||
@@ -278,8 +278,8 @@ 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;
|
||||
for (std::size_t i = 0; i < remote_action.i.display_num; i++) {
|
||||
LOG_INFO("Local display [{}:{}]", i + 1,
|
||||
@@ -379,6 +379,10 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
|
||||
runtime->focus_on_stream_window_ = false;
|
||||
|
||||
if (status == ConnectionStatus::Closed) {
|
||||
props->remote_close_pending_.store(true, std::memory_order_release);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case ConnectionStatus::IncorrectPassword: {
|
||||
@@ -413,8 +417,8 @@ 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;
|
||||
for (std::size_t i = 0; i < remote_action.i.display_num; i++) {
|
||||
LOG_INFO("Local display [{}:{}]", i + 1,
|
||||
|
||||
@@ -201,7 +201,7 @@ void PeerEventHandler::OnReceiveAudioBuffer(
|
||||
auto callback = handler->EnterCallback();
|
||||
if (!callback) return;
|
||||
GuiRuntime* runtime = handler ? &handler->owner_ : nullptr;
|
||||
if (!runtime) {
|
||||
if (!runtime || runtime->unattended_host_) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -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 &&
|
||||
|
||||
@@ -73,6 +73,8 @@ struct RemoteSession {
|
||||
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;
|
||||
|
||||
@@ -29,6 +29,10 @@
|
||||
#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 {
|
||||
@@ -76,16 +80,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;
|
||||
|
||||
@@ -7,6 +7,10 @@ export global ImGuiLineStyle {
|
||||
out property <color> control-separator: #b2b2b2;
|
||||
}
|
||||
|
||||
export global FloatingBarStyle {
|
||||
out property <length> corner-radius: 6px;
|
||||
}
|
||||
|
||||
// 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 {
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
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";
|
||||
|
||||
@@ -72,6 +72,7 @@ export global UiStrings {
|
||||
in-out property <string> up-to-date: "You’re up to date";
|
||||
in-out property <string> update-check-failed: "Check failed. Please try again later.";
|
||||
in-out property <string> release-notes: "Release notes";
|
||||
in-out property <string> view-release-notes: "Release notes";
|
||||
in-out property <string> later: "Later";
|
||||
in-out property <string> download: "Download";
|
||||
in-out property <string> input-password: "Input password";
|
||||
@@ -379,6 +380,7 @@ export component MainWindow inherits Window {
|
||||
in-out property <string> file-save-path: "";
|
||||
in-out property <string> server-host: "";
|
||||
in-out property <string> server-port: "";
|
||||
in-out property <string> self-host-settings-error: "";
|
||||
in property <bool> settings-session-active: false;
|
||||
// Keep the setting visible on every platform. Unsupported builds expose it
|
||||
// as disabled so the fixed settings layout never turns into a blank row.
|
||||
@@ -393,9 +395,9 @@ export component MainWindow inherits Window {
|
||||
callback recent-connect(string);
|
||||
callback recent-edit-alias(string, string);
|
||||
callback recent-delete(string);
|
||||
callback save-settings;
|
||||
callback save-settings() -> bool;
|
||||
callback cancel-settings;
|
||||
callback save-self-hosted-settings;
|
||||
callback save-self-hosted-settings() -> bool;
|
||||
callback cancel-self-hosted-settings;
|
||||
callback browse-save-path;
|
||||
callback open-download;
|
||||
@@ -418,8 +420,13 @@ export component MainWindow inherits Window {
|
||||
in-out property <bool> settings-open: false;
|
||||
private property <length> settings-scroll-y: 0px;
|
||||
in-out property <bool> self-host-settings-open: false;
|
||||
changed self-host-settings-open => {
|
||||
if !root.self-host-settings-open { root.self-host-settings-error = ""; }
|
||||
}
|
||||
in-out property <bool> about-open: false;
|
||||
in-out property <bool> update-open: false;
|
||||
// Follow the first available update. Dismissing the dialog replaces this
|
||||
// binding, so background checks do not reopen it during this launch.
|
||||
in-out property <bool> update-open: root.update-available;
|
||||
in-out property <bool> reset-password-open: false;
|
||||
in-out property <bool> reset-password-invalid: false;
|
||||
in-out property <string> new-password-input: "";
|
||||
@@ -1809,7 +1816,7 @@ export component MainWindow inherits Window {
|
||||
}
|
||||
|
||||
Rectangle { x: 7px; y: 286px; width: parent.width - 14px; height: 1px; background: ImGuiLineStyle.separator; }
|
||||
CompactButton { x: root.compact-language ? 63px : 89px; y: 297px; primary: true; text: UiStrings.ok; clicked => { root.save-settings(); root.settings-open = false; root.self-host-settings-open = false; } }
|
||||
CompactButton { x: root.compact-language ? 63px : 89px; y: 297px; primary: true; text: UiStrings.ok; clicked => { if root.save-settings() { root.settings-open = false; root.self-host-settings-open = false; } } }
|
||||
CompactButton { x: root.compact-language ? 104px : 130px; y: 297px; width: root.compact-language ? 34px : 56px; text: UiStrings.cancel; clicked => { root.cancel-settings(); root.settings-open = false; root.self-host-settings-open = false; } }
|
||||
}
|
||||
}
|
||||
@@ -1822,7 +1829,7 @@ export component MainWindow inherits Window {
|
||||
x: root.compact-language ? 190px : 140px;
|
||||
y: 105px;
|
||||
width: root.compact-language ? 260px : 360px;
|
||||
height: 138px;
|
||||
height: root.self-host-settings-error == "" ? 138px : 202px;
|
||||
border-radius: 7px;
|
||||
|
||||
Rectangle {
|
||||
@@ -1846,7 +1853,7 @@ export component MainWindow inherits Window {
|
||||
border-width: 1px;
|
||||
border-color: ImGuiLineStyle.border;
|
||||
border-radius: 4px;
|
||||
LineEdit { x: 1px; y: 1.5px; width: parent.width - 2px; height: parent.height - 2px; text <=> root.server-host; font-size: ImGuiFontStyle.body; }
|
||||
LineEdit { x: 1px; y: 1.5px; width: parent.width - 2px; height: parent.height - 2px; text <=> root.server-host; input-type: InputType.text; font-size: ImGuiFontStyle.body; }
|
||||
LineEditFocusUnderlineMask { x: 5px; y: parent.height - 3px; width: parent.width - 10px; }
|
||||
}
|
||||
Text { x: 8px; y: 61px; width: root.compact-language ? 88px : 165px; height: 24px; text: UiStrings.server-port; font-size: ImGuiFontStyle.body; overflow: elide; vertical-alignment: center; }
|
||||
@@ -1862,8 +1869,13 @@ export component MainWindow inherits Window {
|
||||
LineEdit { x: 1px; y: 1.5px; width: parent.width - 2px; height: parent.height - 2px; text <=> root.server-port; input-type: InputType.number; font-size: ImGuiFontStyle.body; }
|
||||
LineEditFocusUnderlineMask { x: 5px; y: parent.height - 3px; width: parent.width - 10px; }
|
||||
}
|
||||
CompactButton { x: root.compact-language ? 93px : 135px; y: 100px; primary: true; text: UiStrings.ok; clicked => { root.save-self-hosted-settings(); root.self-host-settings-open = false; } }
|
||||
CompactButton { x: root.compact-language ? 134px : 176px; y: 100px; width: root.compact-language ? 34px : 56px; text: UiStrings.cancel; clicked => { root.cancel-self-hosted-settings(); root.self-host-settings-open = false; } }
|
||||
if root.self-host-settings-error != "": Text {
|
||||
x: 8px; y: 89px; width: parent.width - 16px; height: 64px;
|
||||
text: root.self-host-settings-error; color: #b3261e;
|
||||
font-size: ImGuiFontStyle.body; wrap: word-wrap;
|
||||
}
|
||||
CompactButton { x: root.compact-language ? 93px : 135px; y: parent.height - 38px; primary: true; text: UiStrings.ok; clicked => { if root.save-self-hosted-settings() { root.self-host-settings-open = false; } } }
|
||||
CompactButton { x: root.compact-language ? 134px : 176px; y: parent.height - 38px; width: root.compact-language ? 34px : 56px; text: UiStrings.cancel; clicked => { root.cancel-self-hosted-settings(); root.self-host-settings-open = false; } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1876,7 +1888,7 @@ export component MainWindow inherits Window {
|
||||
x: (root.width - self.width) / 2;
|
||||
y: (root.height - self.height) / 2;
|
||||
width: 320px;
|
||||
height: 216px;
|
||||
height: max(216px, about-content.preferred-height);
|
||||
border-radius: 7px;
|
||||
|
||||
Rectangle {
|
||||
@@ -1890,8 +1902,8 @@ export component MainWindow inherits Window {
|
||||
Rectangle { y: parent.height - 7px; height: 7px; background: #d3d3d3; }
|
||||
Text { x: 6px; text: UiStrings.about; font-size: ImGuiFontStyle.base; font-weight: 600; color: #202124; vertical-alignment: center; }
|
||||
}
|
||||
// Keep the dialog/footer stable while visible text rows determine
|
||||
// each group's size and the layout redistributes the space between.
|
||||
// Grow for update actions and wrapped translations while keeping
|
||||
// the footer below the version and check result.
|
||||
about-content := VerticalLayout {
|
||||
padding: 16px;
|
||||
padding-top: 35px;
|
||||
@@ -1931,6 +1943,19 @@ export component MainWindow inherits Window {
|
||||
clicked => { root.about-open = false; root.update-open = true; }
|
||||
}
|
||||
}
|
||||
if root.update-available: HorizontalLayout {
|
||||
alignment: start;
|
||||
padding-top: 4px;
|
||||
CompactButton {
|
||||
width: max(76px, release-notes-button-metrics.preferred-width + 20px);
|
||||
text: UiStrings.view-release-notes;
|
||||
accessible-role: button;
|
||||
accessible-label: self.text;
|
||||
accessible-action-default => { self.clicked(); }
|
||||
clicked => { root.about-open = false; root.update-open = true; }
|
||||
release-notes-button-metrics := Text { visible: false; text: UiStrings.view-release-notes; font-size: ImGuiFontStyle.body; }
|
||||
}
|
||||
}
|
||||
if root.update-status-text != "": Text {
|
||||
text: root.update-status-text;
|
||||
color: root.update-check-status == UpdateCheckStatus.failed ? #b3261e : #61656c;
|
||||
|
||||
@@ -1,150 +1,281 @@
|
||||
import { CompactComboBox, FontAwesomeIcons, IconButton, SecondaryButton, ImGuiLineStyle, ImGuiFontStyle } from "common.slint";
|
||||
import { ScrollView } from "std-widgets.slint";
|
||||
import { FontAwesomeIcons, ImGuiLineStyle, FloatingBarStyle } from "common.slint";
|
||||
|
||||
export struct ControllerEntry {
|
||||
remote-id: string,
|
||||
display-name: string,
|
||||
}
|
||||
|
||||
export component ServerWindow inherits Window {
|
||||
export global ServerStrings {
|
||||
in property <string> controlled: "被控中";
|
||||
in property <string> heading: "此设备被控中";
|
||||
in property <string> connected: "已连接";
|
||||
in property <string> send-file: "发送文件";
|
||||
in property <string> disconnect: "断开";
|
||||
in property <string> disconnect-one: "断开连接";
|
||||
in property <string> disconnect-all: "全部断开";
|
||||
in property <string> confirm-disconnect: "断开所有控制端的连接?";
|
||||
in property <string> cancel: "取消";
|
||||
}
|
||||
|
||||
component SessionButton inherits Rectangle {
|
||||
in property <string> text;
|
||||
in property <bool> danger: false;
|
||||
in property <bool> enabled: true;
|
||||
private property <bool> keyboard-focus: false;
|
||||
private property <bool> pointer-feedback: true;
|
||||
callback clicked;
|
||||
width: label.preferred-width + 20px;
|
||||
height: 28px;
|
||||
border-radius: 5px;
|
||||
border-width: 1px;
|
||||
border-color: root.danger ? #d92d20 : #c9ced7;
|
||||
background: root.danger ? (root.pointer-feedback && touch.pressed ? #b42318 : root.pointer-feedback && touch.has-hover ? #f04438 : #d92d20)
|
||||
: (root.pointer-feedback && touch.pressed ? #dfe3e9 : root.pointer-feedback && touch.has-hover ? #f3f4f6 : white);
|
||||
opacity: root.enabled ? 1 : 0.5;
|
||||
accessible-role: button;
|
||||
accessible-label: root.text;
|
||||
accessible-action-default => { if root.enabled { root.pointer-feedback = false; root.clicked(); } }
|
||||
label := Text {
|
||||
text: root.text; color: root.danger ? white : #24272d;
|
||||
font-size: 12px; horizontal-alignment: center; vertical-alignment: center;
|
||||
}
|
||||
forward-focus: keyboard;
|
||||
keyboard := FocusScope {
|
||||
enabled: root.enabled;
|
||||
focus-gained(reason) => {
|
||||
if reason == FocusReason.tab-navigation {
|
||||
root.keyboard-focus = true;
|
||||
} else if reason == FocusReason.pointer-click {
|
||||
root.keyboard-focus = false;
|
||||
}
|
||||
// Preserve the input method when returning from the file picker.
|
||||
}
|
||||
key-pressed(event) => {
|
||||
root.keyboard-focus = true;
|
||||
if root.enabled && (event.text == Key.Return || event.text == " ") {
|
||||
root.pointer-feedback = false;
|
||||
root.clicked(); return accept;
|
||||
}
|
||||
return reject;
|
||||
}
|
||||
}
|
||||
touch := TouchArea {
|
||||
enabled: root.enabled;
|
||||
pointer-event(event) => {
|
||||
if event.kind == PointerEventKind.down || event.kind == PointerEventKind.move {
|
||||
root.pointer-feedback = true;
|
||||
}
|
||||
}
|
||||
// A native dialog may not deliver a pointer exit to the owner window.
|
||||
// Restore hover feedback only after a fresh pointer move or press.
|
||||
clicked => { root.pointer-feedback = false; root.keyboard-focus = false; keyboard.focus(); root.clicked(); }
|
||||
}
|
||||
if root.enabled && keyboard.has-focus && root.keyboard-focus: Rectangle {
|
||||
x: 2px; y: 2px; width: parent.width - 4px; height: parent.height - 4px;
|
||||
border-radius: 3px; border-width: 1px; border-color: root.danger ? white : #2463c7;
|
||||
}
|
||||
}
|
||||
|
||||
// A separate native window keeps the collapsed footprint as small as the bar.
|
||||
export component ServerStatusBar inherits Window {
|
||||
title: "CrossDesk";
|
||||
icon: @image-url("../../../resources/linux/crossdesk_256x256.png");
|
||||
preferred-width: root.language-index == 0 ? 250px : root.language-index == 1 ? 330px : 430px;
|
||||
preferred-height: 150px;
|
||||
min-width: root.language-index == 0 ? 250px : root.language-index == 1 ? 330px : 430px;
|
||||
max-width: root.language-index == 0 ? 250px : root.language-index == 1 ? 330px : 430px;
|
||||
no-frame: true;
|
||||
always-on-top: true;
|
||||
background: transparent;
|
||||
default-font-size: ImGuiFontStyle.base;
|
||||
in property <int> controller-count: 1;
|
||||
in property <bool> expanded: false;
|
||||
in property <bool> opens-above: false;
|
||||
in property <bool> dragged: false;
|
||||
out property <length> bar-width: label.preferred-width + 48px;
|
||||
preferred-width: root.bar-width;
|
||||
preferred-height: 36px;
|
||||
min-width: root.bar-width; max-width: root.bar-width;
|
||||
min-height: 36px; max-height: 36px;
|
||||
callback toggle-panel;
|
||||
callback dismiss-panel;
|
||||
callback title-drag(int, length, length);
|
||||
callback move-anchor(float);
|
||||
forward-focus: keyboard;
|
||||
keyboard := FocusScope {
|
||||
key-pressed(event) => {
|
||||
if event.text == Key.Return || event.text == " " { root.toggle-panel(); return accept; }
|
||||
if event.text == Key.Escape { root.dismiss-panel(); return accept; }
|
||||
if event.text == Key.UpArrow { root.move-anchor(-0.05); return accept; }
|
||||
if event.text == Key.DownArrow { root.move-anchor(0.05); return accept; }
|
||||
return reject;
|
||||
}
|
||||
}
|
||||
Rectangle {
|
||||
x: 0px; y: 0px; width: parent.width; height: parent.height;
|
||||
background: touch.pressed ? #dfe3e9 : touch.has-hover ? #f3f4f6 : white;
|
||||
border-width: 1px; border-color: ImGuiLineStyle.border;
|
||||
border-radius: FloatingBarStyle.corner-radius;
|
||||
border-top-right-radius: 0px;
|
||||
border-bottom-right-radius: 0px;
|
||||
}
|
||||
label := Text {
|
||||
x: 10px; width: root.width - 38px; height: root.height;
|
||||
text: ServerStrings.controlled + (root.controller-count > 1 ? " · " + root.controller-count : "");
|
||||
color: #24272d; font-size: 14px; vertical-alignment: center;
|
||||
}
|
||||
Text {
|
||||
x: root.width - 26px; width: 18px; height: root.height;
|
||||
text: root.opens-above != root.expanded ? FontAwesomeIcons.angle-up : FontAwesomeIcons.angle-down;
|
||||
color: #24272d; font-family: "Font Awesome 6 Free"; font-weight: 900;
|
||||
font-size: 12px; horizontal-alignment: center; vertical-alignment: center;
|
||||
}
|
||||
touch := TouchArea {
|
||||
property <int> phase: self.pressed ? 1 : 0;
|
||||
changed phase => { root.title-drag(self.phase, self.mouse-x, self.mouse-y); }
|
||||
moved => { if self.pressed { root.title-drag(2, self.mouse-x, self.mouse-y); } }
|
||||
clicked => { keyboard.focus(); if !root.dragged { root.toggle-panel(); } }
|
||||
}
|
||||
accessible-role: button;
|
||||
accessible-label: label.text;
|
||||
accessible-action-default => { root.toggle-panel(); }
|
||||
}
|
||||
|
||||
export component ServerWindow inherits Window {
|
||||
title: "CrossDesk";
|
||||
icon: @image-url("../../../resources/linux/crossdesk_256x256.png");
|
||||
preferred-width: 225px; min-width: 225px; max-width: 225px;
|
||||
preferred-height: root.content-height;
|
||||
no-frame: true;
|
||||
always-on-top: true;
|
||||
background: transparent;
|
||||
default-font-size: 12px;
|
||||
in property <[ControllerEntry]> controllers;
|
||||
in property <[string]> controller-names;
|
||||
in property <int> language-index: 0;
|
||||
in-out property <int> selected-controller: 0;
|
||||
in property <string> connection-label: "Connection status";
|
||||
in property <string> connection-status: "";
|
||||
in property <string> controller-label: "Controller";
|
||||
in property <string> file-transfer-label: "File transfer";
|
||||
in property <string> select-file-label: "Select file";
|
||||
in property <bool> sending-file: false;
|
||||
in property <bool> file-transfer-visible: false;
|
||||
in property <float> file-progress: 0;
|
||||
in property <string> file-progress-text: "";
|
||||
in property <string> current-file-name: "";
|
||||
in property <string> file-size-text: "";
|
||||
|
||||
callback title-drag(int, length, length);
|
||||
callback toggle-collapsed(bool);
|
||||
in property <string> file-progress-text;
|
||||
in property <string> current-file-name;
|
||||
in property <string> file-size-text;
|
||||
in-out property <bool> confirming-disconnect: false;
|
||||
private property <length> footer-height: send-file.width + disconnect-all.width + 6px > 205px ? 62px : 28px;
|
||||
private property <string> hovered-name;
|
||||
private property <length> tooltip-y;
|
||||
out property <length> content-height: 10px + 24px + (root.controllers.length > 1 ? min(root.controllers.length, 6) * 34px : 28px) + 8px + root.footer-height + 10px + (root.confirming-disconnect ? 36px : 0px) + (root.file-transfer-visible ? 58px : 0px);
|
||||
callback controller-selected(int);
|
||||
callback select-file;
|
||||
callback disconnect-controller;
|
||||
|
||||
private property <bool> collapsed: false;
|
||||
private property <bool> transfer-hovered: false;
|
||||
|
||||
Rectangle {
|
||||
width: root.width;
|
||||
height: root.height;
|
||||
background: white;
|
||||
border-width: 1px;
|
||||
border-color: ImGuiLineStyle.border;
|
||||
border-radius: 8px;
|
||||
clip: true;
|
||||
|
||||
Rectangle {
|
||||
x: 0px;
|
||||
y: 0px;
|
||||
width: parent.width;
|
||||
height: 30px;
|
||||
background: #f8f9fb;
|
||||
Rectangle { y: parent.height - 1px; height: 1px; background: ImGuiLineStyle.border; }
|
||||
IconButton {
|
||||
x: 0px;
|
||||
y: 0px;
|
||||
width: 30px; height: 30px;
|
||||
icon: root.collapsed ? FontAwesomeIcons.angle-down : FontAwesomeIcons.angle-up;
|
||||
icon-size: 12px;
|
||||
clicked => { root.collapsed = !root.collapsed; root.toggle-collapsed(root.collapsed); }
|
||||
}
|
||||
drag := TouchArea {
|
||||
x: 30px; width: parent.width - 30px;
|
||||
property <int> phase: self.pressed ? 1 : 0;
|
||||
changed phase => { root.title-drag(phase, self.mouse-x, self.mouse-y); }
|
||||
moved => { if (self.pressed) { root.title-drag(2, self.mouse-x, self.mouse-y); } }
|
||||
}
|
||||
callback disconnect-controller(string);
|
||||
callback disconnect-all;
|
||||
callback dismiss-panel;
|
||||
forward-focus: keyboard;
|
||||
keyboard := FocusScope {
|
||||
key-pressed(event) => {
|
||||
if event.text == Key.Escape { root.dismiss-panel(); return accept; }
|
||||
return reject;
|
||||
}
|
||||
|
||||
if !root.collapsed: Rectangle {
|
||||
x: 12px; y: 38px; width: parent.width - 52px; height: 101px;
|
||||
background: white; border-width: 1px; border-color: ImGuiLineStyle.border; border-radius: 5px;
|
||||
VerticalLayout {
|
||||
padding: 8px; spacing: 3px; alignment: start;
|
||||
HorizontalLayout {
|
||||
height: 24px; spacing: 5px;
|
||||
Text { width: root.language-index == 0 ? 69px : 110px; text: root.controller-label; color: #434953; font-size: ImGuiFontStyle.body; vertical-alignment: center; overflow: elide; }
|
||||
CompactComboBox {
|
||||
width: root.language-index == 0 ? 108px : root.language-index == 1 ? 147px : 247px;
|
||||
model: root.controller-names;
|
||||
current-index <=> root.selected-controller;
|
||||
selected(index) => { root.controller-selected(index); }
|
||||
}
|
||||
}
|
||||
Rectangle { height: 1px; background: ImGuiLineStyle.separator; }
|
||||
HorizontalLayout {
|
||||
height: 24px; spacing: 5px;
|
||||
Text { width: root.language-index == 0 ? 69px : 110px; text: root.connection-label; color: #434953; font-size: ImGuiFontStyle.body; vertical-alignment: center; overflow: elide; }
|
||||
Text { text: root.connection-status; color: #2463c7; font-size: ImGuiFontStyle.body; horizontal-alignment: left; vertical-alignment: center; overflow: elide; }
|
||||
}
|
||||
Rectangle { height: 1px; background: ImGuiLineStyle.separator; }
|
||||
Rectangle {
|
||||
height: 24px;
|
||||
HorizontalLayout {
|
||||
y: 0px;
|
||||
width: parent.width;
|
||||
height: 24px;
|
||||
spacing: 5px;
|
||||
Text { width: root.language-index == 0 ? 69px : 110px; text: root.file-transfer-label; color: #434953; font-size: ImGuiFontStyle.body; vertical-alignment: center; overflow: elide; }
|
||||
SecondaryButton { width: root.language-index == 0 ? 78px : root.language-index == 1 ? 140px : 205px; height: 24px; text: root.select-file-label; clicked => { root.select-file(); } }
|
||||
Rectangle {
|
||||
visible: root.file-transfer-visible;
|
||||
width: 35px;
|
||||
Text {
|
||||
text: root.sending-file ? "↑ " + round(root.file-progress * 100) + "%" : "✓";
|
||||
color: root.sending-file ? #2463c7 : #25874b;
|
||||
font-size: ImGuiFontStyle.small;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
transfer-touch := TouchArea {
|
||||
changed has-hover => { root.transfer-hovered = self.has-hover; }
|
||||
Rectangle {
|
||||
width: root.width; height: root.height;
|
||||
background: white; border-width: 1px; border-color: ImGuiLineStyle.border;
|
||||
border-radius: 8px;
|
||||
Text {
|
||||
x: 10px; y: 10px; width: parent.width - 20px; height: 24px;
|
||||
text: ServerStrings.heading + (root.controllers.length > 1 ? " · " + root.controllers.length : "");
|
||||
color: #24272d; font-size: 13px; font-weight: 500; vertical-alignment: center; overflow: elide;
|
||||
}
|
||||
list := ScrollView {
|
||||
x: 10px; y: 34px; width: parent.width - 20px;
|
||||
height: max(0px, root.height - 34px - root.footer-height - 18px - (root.confirming-disconnect ? 36px : 0px) - (root.file-transfer-visible ? 58px : 0px));
|
||||
viewport-width: self.visible-width;
|
||||
viewport-height: root.controllers.length * (root.controllers.length > 1 ? 34px : 28px);
|
||||
for controller[index] in root.controllers: row := Rectangle {
|
||||
x: 0px; y: index * (root.controllers.length > 1 ? 34px : 28px);
|
||||
width: list.visible-width; height: root.controllers.length > 1 ? 32px : 28px;
|
||||
select := Rectangle {
|
||||
x: 0px; y: 0px;
|
||||
width: parent.width - (root.controllers.length > 1 ? disconnect.width + 4px : status.preferred-width + 8px);
|
||||
height: parent.height; border-radius: 4px;
|
||||
background: root.controllers.length > 1 && index == root.selected-controller ? #eef5fd : select-touch.has-hover ? #f3f4f6 : transparent;
|
||||
if root.controllers.length > 1: Rectangle {
|
||||
x: 4px; y: (parent.height - 13px) / 2; width: 13px; height: 13px;
|
||||
border-radius: 7px; border-width: 1px; border-color: index == root.selected-controller ? #2463c7 : #8c939e;
|
||||
if index == root.selected-controller: Rectangle { x: 3px; y: 3px; width: 7px; height: 7px; border-radius: 4px; background: #2463c7; }
|
||||
}
|
||||
name := Text {
|
||||
x: root.controllers.length > 1 ? 23px : 0px; width: parent.width - self.x - 4px;
|
||||
height: parent.height; text: controller.display-name; color: #24272d;
|
||||
font-size: 13px; vertical-alignment: center; overflow: elide;
|
||||
}
|
||||
forward-focus: selection-keyboard;
|
||||
selection-keyboard := FocusScope {
|
||||
key-pressed(event) => {
|
||||
if event.text == Key.Return || event.text == " " {
|
||||
root.selected-controller = index; root.controller-selected(index); return accept;
|
||||
}
|
||||
if event.text == Key.UpArrow || event.text == Key.DownArrow {
|
||||
root.selected-controller = max(0, min(root.controllers.length - 1, root.selected-controller + (event.text == Key.UpArrow ? -1 : 1)));
|
||||
root.controller-selected(root.selected-controller); return accept;
|
||||
}
|
||||
return reject;
|
||||
}
|
||||
}
|
||||
select-touch := TouchArea {
|
||||
clicked => { selection-keyboard.focus(); root.selected-controller = index; root.controller-selected(index); }
|
||||
changed has-hover => {
|
||||
root.hovered-name = self.has-hover && name.preferred-width > name.width ? controller.display-name : "";
|
||||
root.tooltip-y = max(0px, min(root.height - 52px, list.y + row.y + list.viewport-y + row.height));
|
||||
}
|
||||
}
|
||||
accessible-role: radio-button;
|
||||
accessible-label: controller.display-name;
|
||||
accessible-checked: index == root.selected-controller;
|
||||
accessible-action-default => { root.selected-controller = index; root.controller-selected(index); }
|
||||
|
||||
}
|
||||
status := Text {
|
||||
visible: root.controllers.length == 1;
|
||||
x: parent.width - self.preferred-width; height: parent.height;
|
||||
text: ServerStrings.connected; color: #16a34a; font-size: 12px; vertical-alignment: center;
|
||||
}
|
||||
disconnect := SessionButton {
|
||||
visible: root.controllers.length > 1;
|
||||
x: parent.width - self.width; y: 2px;
|
||||
text: ServerStrings.disconnect; danger: true;
|
||||
clicked => { root.confirming-disconnect = false; root.disconnect-controller(controller.remote-id); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !root.collapsed: IconButton {
|
||||
x: parent.width - 34px; y: 38px; width: 24px; height: 101px;
|
||||
icon: FontAwesomeIcons.xmark;
|
||||
icon-size: 13px;
|
||||
icon-color: white;
|
||||
normal-background: #ef2b2d;
|
||||
hover-background: #d92d20;
|
||||
pressed-background: #b42318;
|
||||
border-radius: 5px;
|
||||
clicked => { root.disconnect-controller(); }
|
||||
}
|
||||
if root.file-transfer-visible && root.transfer-hovered: Rectangle {
|
||||
x: 15px; y: 67px; width: root.width - 30px; height: 70px;
|
||||
background: #22252bf2;
|
||||
border-radius: 5px;
|
||||
z: 20;
|
||||
VerticalLayout {
|
||||
padding: 8px; spacing: 3px;
|
||||
Text { text: root.current-file-name; color: white; font-size: ImGuiFontStyle.small; overflow: elide; }
|
||||
Text { text: root.file-size-text; color: #e1e4e8; font-size: ImGuiFontStyle.small; }
|
||||
Text { text: round(root.file-progress * 100) + "% " + root.file-progress-text; color: #e1e4e8; font-size: ImGuiFontStyle.small; }
|
||||
footer := Rectangle {
|
||||
x: 10px; y: list.y + list.height + 8px; width: parent.width - 20px; height: root.footer-height;
|
||||
send-file := SessionButton {
|
||||
x: root.footer-height > 28px ? parent.width - self.width : disconnect-all.x - self.width - 6px;
|
||||
y: 0px;
|
||||
text: root.confirming-disconnect ? ServerStrings.cancel : ServerStrings.send-file;
|
||||
enabled: root.confirming-disconnect || !root.sending-file;
|
||||
clicked => { if root.confirming-disconnect { root.confirming-disconnect = false; } else { root.select-file(); } }
|
||||
}
|
||||
disconnect-all := SessionButton {
|
||||
x: parent.width - self.width; y: root.footer-height - 28px;
|
||||
text: root.controllers.length > 1 ? ServerStrings.disconnect-all : ServerStrings.disconnect-one;
|
||||
danger: true;
|
||||
clicked => {
|
||||
if root.controllers.length == 1 { root.disconnect-controller(root.controllers[0].remote-id); }
|
||||
else if root.confirming-disconnect { root.confirming-disconnect = false; root.disconnect-all(); }
|
||||
else { root.confirming-disconnect = true; }
|
||||
}
|
||||
}
|
||||
}
|
||||
if root.confirming-disconnect: Text {
|
||||
x: 10px; y: footer.y + footer.height + 6px; width: parent.width - 20px; height: 30px;
|
||||
text: ServerStrings.confirm-disconnect; color: #d92d20; font-size: 12px; wrap: word-wrap;
|
||||
}
|
||||
if root.file-transfer-visible: VerticalLayout {
|
||||
x: 10px; y: root.height - 62px; width: parent.width - 20px; height: 52px; spacing: 2px;
|
||||
Text { text: root.current-file-name; color: #596575; font-size: 11px; overflow: elide; }
|
||||
Text { text: root.file-size-text; color: #596575; font-size: 11px; overflow: elide; }
|
||||
Text { text: round(root.file-progress * 100) + "% " + root.file-progress-text; color: #2463c7; font-size: 11px; overflow: elide; }
|
||||
}
|
||||
}
|
||||
// Draw outside the scrolling list so its last row can reveal its name.
|
||||
if root.hovered-name != "": Rectangle {
|
||||
x: 10px; y: root.tooltip-y; width: 205px; height: tip.preferred-height + 12px; z: 20;
|
||||
background: #24272d; border-radius: 5px;
|
||||
tip := Text { x: 6px; y: 6px; width: parent.width - 12px; text: root.hovered-name; color: white; font-size: 12px; wrap: word-wrap; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ComboBox, ScrollView } from "std-widgets.slint";
|
||||
import { FontAwesomeIcons, IconButton, PrimaryButton, DialogSurface, ImGuiLineStyle, ImGuiFontStyle } from "common.slint";
|
||||
import { FontAwesomeIcons, IconButton, PrimaryButton, DialogSurface, ImGuiLineStyle, ImGuiFontStyle, FloatingBarStyle } from "common.slint";
|
||||
|
||||
export struct StreamTab {
|
||||
remote-id: string,
|
||||
@@ -282,9 +282,21 @@ export component StreamWindow inherits Window {
|
||||
root.display-menu-open = false;
|
||||
root.shortcut-menu-open = false;
|
||||
}
|
||||
input-focus.focus();
|
||||
// Changed handlers may run while Winit/AccessKit is building the
|
||||
// accessibility tree. Changing focus there re-enters its borrowed
|
||||
// adapter and aborts the process; defer focus to the event loop.
|
||||
input-focus-timer.running = true;
|
||||
input-focus-timer.restart();
|
||||
root.keyboard-focus-changed(!root.remote-update-visible);
|
||||
}
|
||||
input-focus-timer := Timer {
|
||||
interval: 1ms;
|
||||
running: false;
|
||||
triggered => {
|
||||
self.running = false;
|
||||
input-focus.focus();
|
||||
}
|
||||
}
|
||||
private property <bool> control-tooltip-visible: false;
|
||||
private property <ControlBarTooltip> hovered-control: {
|
||||
if root.window-active && !root.control-dragging
|
||||
@@ -798,7 +810,7 @@ export component StreamWindow inherits Window {
|
||||
background: white;
|
||||
border-width: 1px;
|
||||
border-color: ImGuiLineStyle.border;
|
||||
border-radius: 6px;
|
||||
border-radius: FloatingBarStyle.corner-radius;
|
||||
z: 8;
|
||||
clip: true;
|
||||
// Keep width changes atomic. When docked right, animating both
|
||||
|
||||
@@ -20,6 +20,21 @@ inline slint::SharedString Text(const std::string& value) {
|
||||
return slint::SharedString(value);
|
||||
}
|
||||
|
||||
template <typename Component>
|
||||
void ApplyServerStrings(const Component& component, int language_index) {
|
||||
const int language = localization::detail::ClampLanguageIndex(language_index);
|
||||
auto& strings = component->template global<ui::ServerStrings>();
|
||||
strings.set_controlled(Text(localization::server_controlled[language]));
|
||||
strings.set_heading(Text(localization::server_heading[language]));
|
||||
strings.set_connected(Text(localization::server_connected[language]));
|
||||
strings.set_send_file(Text(localization::server_send_file[language]));
|
||||
strings.set_disconnect(Text(localization::server_disconnect[language]));
|
||||
strings.set_disconnect_one(Text(localization::disconnect[language]));
|
||||
strings.set_disconnect_all(Text(localization::server_disconnect_all[language]));
|
||||
strings.set_confirm_disconnect(Text(localization::server_confirm_disconnect[language]));
|
||||
strings.set_cancel(Text(localization::cancel[language]));
|
||||
}
|
||||
|
||||
inline int ApplyMainWindowStrings(
|
||||
const slint::ComponentHandle<ui::MainWindow>& window,
|
||||
int language_index) {
|
||||
@@ -105,6 +120,7 @@ inline int ApplyMainWindowStrings(
|
||||
strings.set_update_check_failed(
|
||||
Text(localization::update_check_failed[language]));
|
||||
strings.set_release_notes(Text(localization::release_notes[language]));
|
||||
strings.set_view_release_notes(Text(localization::view_release_notes[language]));
|
||||
strings.set_download(Text(localization::update[language]));
|
||||
strings.set_input_password(Text(localization::input_password[language]));
|
||||
strings.set_reinput_password(Text(localization::reinput_password[language]));
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-09
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _KEYBOARD_STATE_H_
|
||||
#define _KEYBOARD_STATE_H_
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
struct KeyboardKey {
|
||||
int key_code = 0;
|
||||
uint32_t scan_code = 0;
|
||||
bool extended = false;
|
||||
};
|
||||
|
||||
using PressedKeys = std::map<int, KeyboardKey>;
|
||||
|
||||
struct KeyboardInput {
|
||||
int key_code = 0;
|
||||
bool is_down = false;
|
||||
uint32_t scan_code = 0;
|
||||
bool extended = false;
|
||||
};
|
||||
|
||||
inline bool IsKeyboardModifier(int key_code) {
|
||||
return (key_code >= 0x10 && key_code <= 0x12) ||
|
||||
(key_code >= 0xA0 && key_code <= 0xA5) ||
|
||||
key_code == 0x5B || key_code == 0x5C;
|
||||
}
|
||||
|
||||
// Reconcile state after capture overflow without replaying discarded shortcuts.
|
||||
// Keep keys that are still held, release stale keys, then restore modifiers
|
||||
// before ordinary keys. Metadata matters for Enter/numpad Enter, etc.
|
||||
inline std::vector<KeyboardInput> ReconcileKeyboardState(
|
||||
const PressedKeys& current, const PressedKeys& desired) {
|
||||
const auto same_key = [](const KeyboardKey& a, const KeyboardKey& b) {
|
||||
return a.scan_code == b.scan_code && a.extended == b.extended;
|
||||
};
|
||||
std::vector<KeyboardInput> result;
|
||||
for (const auto& [code, key] : current) {
|
||||
const auto it = desired.find(code);
|
||||
if (it == desired.end() || !same_key(key, it->second))
|
||||
result.push_back({code, false, key.scan_code, key.extended});
|
||||
}
|
||||
// Release ordinary keys before modifiers as well.
|
||||
std::stable_partition(result.begin(), result.end(), [](const auto& key) {
|
||||
return !IsKeyboardModifier(key.key_code);
|
||||
});
|
||||
const auto releases = result.size();
|
||||
for (const auto& [code, key] : desired) {
|
||||
const auto it = current.find(code);
|
||||
if (it == current.end() || !same_key(key, it->second))
|
||||
result.push_back({code, true, key.scan_code, key.extended});
|
||||
}
|
||||
std::stable_partition(result.begin() + releases, result.end(),
|
||||
[](const auto& key) {
|
||||
return IsKeyboardModifier(key.key_code);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -524,7 +524,10 @@ int RunHeadless(const Options& options, const std::function<int()>& run) {
|
||||
const std::string xvfb = FindExecutable("Xvfb");
|
||||
if (xvfb.empty()) {
|
||||
Diagnostic() << "No usable display. Headless mode requires Xvfb; on Debian/Ubuntu "
|
||||
"install it with: sudo apt install xvfb\n";
|
||||
"install it with: sudo apt install xvfb\n"
|
||||
"For a complete independent desktop, install the "
|
||||
"crossdesk-virtual-desktop-xfce .deb and use "
|
||||
"--headless-session startxfce4.\n";
|
||||
return 1;
|
||||
}
|
||||
std::string session;
|
||||
@@ -532,9 +535,15 @@ int RunHeadless(const Options& options, const std::function<int()>& run) {
|
||||
if (!options.session.empty() && options.session != "none") {
|
||||
session = FindExecutable(options.session);
|
||||
dbus = FindExecutable("dbus-run-session");
|
||||
if (session.empty() || dbus.empty()) {
|
||||
Diagnostic() << "Headless desktop requires an executable --headless-session "
|
||||
"and dbus-run-session (Debian/Ubuntu: dbus-daemon)\n";
|
||||
if (session.empty()) {
|
||||
Diagnostic() << "Desktop session executable not found: " << options.session
|
||||
<< ". Install that desktop environment first; for Xfce use the "
|
||||
"crossdesk-virtual-desktop-xfce .deb.\n";
|
||||
return 1;
|
||||
}
|
||||
if (dbus.empty()) {
|
||||
Diagnostic() << "Headless desktop requires dbus-run-session. Install "
|
||||
"dbus-daemon (or dbus on older Debian/Ubuntu releases).\n";
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
#include <optional>
|
||||
|
||||
#include "config_center.h"
|
||||
#include "signal_server_address.h"
|
||||
#include "signal_server_settings.h"
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
@@ -82,9 +84,7 @@ SettingResult ApplyConsoleSetting(ConfigCenter& config, const std::string& key,
|
||||
canonical = value;
|
||||
save = [&config, mode] { return config.SetTurnMode(static_cast<ConfigCenter::TURN_MODE>(mode)); };
|
||||
} else if (key == "server_host") {
|
||||
if (input.empty() || input.size() > 253 ||
|
||||
input.find_first_of("/\\@?#") != std::string::npos ||
|
||||
std::any_of(input.begin(), input.end(), [](unsigned char c) { return c <= 32 || c == 127; })) return result;
|
||||
if (!minirtc::ParseSignalServerAddress(input)) return result;
|
||||
save = [&] { return config.SetServerHost(input); };
|
||||
} else if (key == "server_port") {
|
||||
int port = 0;
|
||||
@@ -142,11 +142,15 @@ SettingResult ApplyConsoleSetting(ConfigCenter& config, const std::string& key,
|
||||
return {true, SettingEffect::none, "console_settings_unchanged"};
|
||||
}
|
||||
}
|
||||
const auto previous_server = GetSignalServerSettings(config);
|
||||
status = save();
|
||||
if (status != 0) return {false, SettingEffect::none, "console_settings_save_failed"};
|
||||
if (network && ((key != "server_host" && key != "server_port") || config.IsSelfHosted())) {
|
||||
if (previous_server != GetSignalServerSettings(config)) {
|
||||
effect = SettingEffect::reconnect;
|
||||
message = "console_settings_reconnect";
|
||||
} else if (key == "codec" || key == "hardware" || key == "turn") {
|
||||
effect = SettingEffect::next_connection;
|
||||
message = "console_settings_next_connection";
|
||||
}
|
||||
return {true, effect, message};
|
||||
}
|
||||
|
||||
@@ -1259,12 +1259,32 @@ MacMetalVideoRenderer::RenderOutcome MacMetalVideoRenderer::RenderLatest(
|
||||
vertexCount:4];
|
||||
[encoder endEncoding];
|
||||
|
||||
NSWindow* window = impl_->video_view.window;
|
||||
const bool visible_at_submit = window != nil && window.isVisible &&
|
||||
!window.isMiniaturized && !impl_->video_view.isHiddenOrHasHiddenAncestor &&
|
||||
(window.occlusionState & NSWindowOcclusionStateVisible) != 0;
|
||||
std::shared_ptr<SharedFrameState> completion_frames = impl_->frames;
|
||||
[command_buffer addCompletedHandler:^(id<MTLCommandBuffer>) {
|
||||
std::lock_guard lock(completion_frames->mutex);
|
||||
auto& slot = completion_frames->slots[slot_index];
|
||||
if (slot.sequence == sequence && slot.use == SlotUse::in_flight) {
|
||||
slot.use = SlotUse::available;
|
||||
[command_buffer addCompletedHandler:^(id<MTLCommandBuffer> completed) {
|
||||
{
|
||||
std::lock_guard lock(completion_frames->mutex);
|
||||
auto& slot = completion_frames->slots[slot_index];
|
||||
if (slot.sequence == sequence && slot.use == SlotUse::in_flight) {
|
||||
slot.use = SlotUse::available;
|
||||
}
|
||||
}
|
||||
// Some macOS/display environments return zero for every presentedTime,
|
||||
// even while the video is visible. Keep a labelled GPU-end estimate so
|
||||
// that missing presentation feedback does not leave latency blank. A
|
||||
// real presentedTime takes precedence in VideoLatencyStats. Never use
|
||||
// callback arrival time, which can be delayed by seconds.
|
||||
const auto now = VideoLatencyFrame::Clock::now();
|
||||
const double gpu_end = completed.GPUEndTime;
|
||||
const auto rendered_at = VideoLatencyFrame::FromHostTime(
|
||||
gpu_end, CACurrentMediaTime(), now);
|
||||
const bool gpu_completed =
|
||||
completed.status == MTLCommandBufferStatusCompleted;
|
||||
if (gpu_completed && visible_at_submit && rendered_at) {
|
||||
timing.MarkEstimated(*rendered_at);
|
||||
}
|
||||
}];
|
||||
[drawable addPresentedHandler:^(id<MTLDrawable> presented) {
|
||||
@@ -1273,11 +1293,11 @@ MacMetalVideoRenderer::RenderOutcome MacMetalVideoRenderer::RenderLatest(
|
||||
// timing by value keeps this safe after a session/renderer is destroyed.
|
||||
const double presented_time = presented.presentedTime;
|
||||
const auto now = VideoLatencyFrame::Clock::now();
|
||||
const double age = CACurrentMediaTime() - presented_time;
|
||||
if (presented_time > 0 && std::isfinite(age) && age >= 0 && age <= 5) {
|
||||
timing.MarkPresented(
|
||||
now - std::chrono::duration_cast<VideoLatencyFrame::Clock::duration>(
|
||||
std::chrono::duration<double>(age)));
|
||||
const double host_now = CACurrentMediaTime();
|
||||
const auto presented_at = VideoLatencyFrame::FromHostTime(
|
||||
presented_time, host_now, now);
|
||||
if (presented_at) {
|
||||
timing.MarkPresented(*presented_at);
|
||||
}
|
||||
}];
|
||||
[command_buffer presentDrawable:drawable];
|
||||
|
||||
@@ -1,69 +1,322 @@
|
||||
#include "platform/autostart_backend.h"
|
||||
|
||||
#include <windows.h>
|
||||
#include <sddl.h>
|
||||
#include <taskschd.h>
|
||||
#include <wrl/client.h>
|
||||
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "autostart_task.h"
|
||||
#include "rd_log.h"
|
||||
|
||||
namespace crossdesk::platform {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kRunKey =
|
||||
"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
|
||||
using Microsoft::WRL::ComPtr;
|
||||
using Bstr = std::unique_ptr<OLECHAR, decltype(&SysFreeString)>;
|
||||
|
||||
constexpr wchar_t kRunKey[] =
|
||||
L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
|
||||
|
||||
Bstr MakeBstr(const std::wstring& value) {
|
||||
return Bstr(SysAllocString(value.c_str()), SysFreeString);
|
||||
}
|
||||
|
||||
std::wstring FromUtf8(const std::string& value) {
|
||||
if (value.empty()) return {};
|
||||
const int size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
|
||||
value.c_str(), -1, nullptr, 0);
|
||||
if (size <= 0) return {};
|
||||
std::wstring result(size, L'\0');
|
||||
if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value.c_str(), -1,
|
||||
result.data(), size))
|
||||
return {};
|
||||
result.pop_back();
|
||||
return result;
|
||||
}
|
||||
|
||||
std::wstring CurrentUserSid() {
|
||||
HANDLE token = nullptr;
|
||||
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return {};
|
||||
DWORD size = 0;
|
||||
GetTokenInformation(token, TokenUser, nullptr, 0, &size);
|
||||
std::vector<BYTE> data(size);
|
||||
const bool read =
|
||||
GetTokenInformation(token, TokenUser, data.data(), size, &size) != FALSE;
|
||||
CloseHandle(token);
|
||||
if (!read) return {};
|
||||
LPWSTR sid = nullptr;
|
||||
if (!ConvertSidToStringSidW(
|
||||
reinterpret_cast<TOKEN_USER*>(data.data())->User.Sid, &sid))
|
||||
return {};
|
||||
const std::wstring result(sid);
|
||||
LocalFree(sid);
|
||||
return result;
|
||||
}
|
||||
|
||||
bool Check(HRESULT result, const char* operation) {
|
||||
if (SUCCEEDED(result)) return true;
|
||||
LOG_ERROR("Windows autostart {} failed: HRESULT=0x{:08x}", operation,
|
||||
static_cast<unsigned long>(result));
|
||||
return false;
|
||||
}
|
||||
|
||||
class ComApartment {
|
||||
public:
|
||||
ComApartment() : result_(CoInitializeEx(nullptr, COINIT_MULTITHREADED)) {}
|
||||
~ComApartment() {
|
||||
if (SUCCEEDED(result_)) CoUninitialize();
|
||||
}
|
||||
bool ready() const {
|
||||
// Settings can run on a UI thread that already uses a different apartment.
|
||||
return result_ == RPC_E_CHANGED_MODE || Check(result_, "initialize COM");
|
||||
}
|
||||
|
||||
private:
|
||||
HRESULT result_;
|
||||
};
|
||||
|
||||
class TaskScheduler {
|
||||
private:
|
||||
// COM interfaces must be released before the apartment is uninitialized.
|
||||
ComApartment apartment_;
|
||||
ComPtr<ITaskService> service_;
|
||||
|
||||
public:
|
||||
ComPtr<ITaskFolder> folder;
|
||||
|
||||
bool Open() {
|
||||
if (!apartment_.ready()) return false;
|
||||
if (!Check(
|
||||
CoCreateInstance(CLSID_TaskScheduler, nullptr, CLSCTX_INPROC_SERVER,
|
||||
IID_PPV_ARGS(service_.GetAddressOf())),
|
||||
"create scheduler"))
|
||||
return false;
|
||||
const VARIANT empty{};
|
||||
if (!Check(service_->Connect(empty, empty, empty, empty), "connect"))
|
||||
return false;
|
||||
auto root = MakeBstr(L"\\");
|
||||
return root && Check(service_->GetFolder(root.get(), folder.GetAddressOf()),
|
||||
"open task folder");
|
||||
}
|
||||
};
|
||||
|
||||
LONG ReadRunEntry(const std::wstring& app_name, std::wstring* command) {
|
||||
DWORD size = 0;
|
||||
LONG result = RegGetValueW(HKEY_CURRENT_USER, kRunKey, app_name.c_str(),
|
||||
RRF_RT_REG_SZ, nullptr, nullptr, &size);
|
||||
if (result != ERROR_SUCCESS) return result;
|
||||
std::vector<wchar_t> buffer(size / sizeof(wchar_t) + 1, L'\0');
|
||||
result = RegGetValueW(HKEY_CURRENT_USER, kRunKey, app_name.c_str(),
|
||||
RRF_RT_REG_SZ, nullptr, buffer.data(), &size);
|
||||
if (result == ERROR_SUCCESS) *command = buffer.data();
|
||||
return result;
|
||||
}
|
||||
|
||||
bool RemoveRunEntry(const std::wstring& app_name) {
|
||||
const LONG result =
|
||||
RegDeleteKeyValueW(HKEY_CURRENT_USER, kRunKey, app_name.c_str());
|
||||
if (result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND ||
|
||||
result == ERROR_PATH_NOT_FOUND)
|
||||
return true;
|
||||
LOG_ERROR("Windows autostart remove Run entry failed: error={}", result);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool EnableRunEntry(const std::wstring& app_name,
|
||||
const std::wstring& executable) {
|
||||
HKEY key = nullptr;
|
||||
const LONG opened = RegCreateKeyExW(HKEY_CURRENT_USER, kRunKey, 0, nullptr, 0,
|
||||
KEY_SET_VALUE, nullptr, &key, nullptr);
|
||||
if (opened != ERROR_SUCCESS) {
|
||||
LOG_ERROR("Windows autostart open Run key failed: error={}", opened);
|
||||
return false;
|
||||
}
|
||||
const std::wstring command = L"\"" + executable + L"\"";
|
||||
const LONG result = RegSetValueExW(
|
||||
key, app_name.c_str(), 0, REG_SZ,
|
||||
reinterpret_cast<const BYTE*>(command.c_str()),
|
||||
static_cast<DWORD>((command.size() + 1) * sizeof(wchar_t)));
|
||||
RegCloseKey(key);
|
||||
if (result != ERROR_SUCCESS)
|
||||
LOG_ERROR("Windows autostart set Run entry failed: error={}", result);
|
||||
return result == ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
bool RegisterLogonTask(const std::wstring& app_name,
|
||||
const std::filesystem::path& executable) {
|
||||
const auto sid = CurrentUserSid();
|
||||
if (sid.empty()) return false;
|
||||
TaskScheduler scheduler;
|
||||
if (!scheduler.Open()) return false;
|
||||
auto name = MakeBstr(AutostartTaskName(app_name, sid));
|
||||
auto xml = MakeBstr(BuildAutostartTaskXml(
|
||||
sid, executable.wstring(), executable.parent_path().wstring()));
|
||||
auto user = MakeBstr(sid);
|
||||
if (!name || !xml || !user) return false;
|
||||
VARIANT user_id{};
|
||||
user_id.vt = VT_BSTR;
|
||||
user_id.bstrVal = user.get(); // Borrowed for this synchronous call.
|
||||
const VARIANT empty{};
|
||||
ComPtr<IRegisteredTask> task;
|
||||
return Check(scheduler.folder->RegisterTask(
|
||||
name.get(), xml.get(), TASK_CREATE_OR_UPDATE, user_id, empty,
|
||||
TASK_LOGON_INTERACTIVE_TOKEN, empty, task.GetAddressOf()),
|
||||
"register elevated logon task");
|
||||
}
|
||||
|
||||
bool RemoveLogonTask(const std::wstring& app_name) {
|
||||
const auto sid = CurrentUserSid();
|
||||
if (sid.empty()) return false;
|
||||
TaskScheduler scheduler;
|
||||
if (!scheduler.Open()) return false;
|
||||
auto name = MakeBstr(AutostartTaskName(app_name, sid));
|
||||
if (!name) return false;
|
||||
const HRESULT result = scheduler.folder->DeleteTask(name.get(), 0);
|
||||
return result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) ||
|
||||
result == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) ||
|
||||
Check(result, "delete logon task");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string GetAutostartExecutablePath() {
|
||||
char path[32768] = {};
|
||||
const DWORD length = GetModuleFileNameA(nullptr, path, sizeof(path));
|
||||
return length > 0 && length < sizeof(path) ? std::string(path, length)
|
||||
: std::string();
|
||||
std::vector<wchar_t> path(32768);
|
||||
const DWORD length =
|
||||
GetModuleFileNameW(nullptr, path.data(), static_cast<DWORD>(path.size()));
|
||||
if (length == 0 || length >= path.size()) return {};
|
||||
return std::filesystem::path(path.data(), path.data() + length).u8string();
|
||||
}
|
||||
|
||||
bool EnableAutostart(const std::string& app_name,
|
||||
const std::string& executable_path) {
|
||||
if (!std::filesystem::exists(executable_path)) return false;
|
||||
|
||||
HKEY key = nullptr;
|
||||
if (RegOpenKeyExA(HKEY_CURRENT_USER, kRunKey, 0, KEY_WRITE, &key) !=
|
||||
ERROR_SUCCESS) {
|
||||
const auto name = FromUtf8(app_name);
|
||||
const auto path = FromUtf8(executable_path);
|
||||
if (name.empty() || path.empty()) return false;
|
||||
const std::filesystem::path executable(path);
|
||||
std::error_code error;
|
||||
if (!executable.is_absolute() ||
|
||||
!std::filesystem::is_regular_file(executable, error))
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string value = executable_path;
|
||||
if (value.find(' ') != std::string::npos &&
|
||||
(value.front() != '"' || value.back() != '"')) {
|
||||
value = "\"" + value + "\"";
|
||||
}
|
||||
const LONG result = RegSetValueExA(
|
||||
key, app_name.c_str(), 0, REG_SZ,
|
||||
reinterpret_cast<const BYTE*>(value.c_str()),
|
||||
static_cast<DWORD>(value.size() + 1));
|
||||
RegCloseKey(key);
|
||||
return result == ERROR_SUCCESS;
|
||||
if (!kAutostartRequiresElevation) return EnableRunEntry(name, path);
|
||||
// Do not remove the old entry unless registering its replacement succeeded.
|
||||
if (!RegisterLogonTask(name, executable)) return false;
|
||||
RemoveRunEntry(name);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DisableAutostart(const std::string& app_name) {
|
||||
HKEY key = nullptr;
|
||||
if (RegOpenKeyExA(HKEY_CURRENT_USER, kRunKey, 0, KEY_WRITE, &key) !=
|
||||
ERROR_SUCCESS) {
|
||||
return false;
|
||||
}
|
||||
const LONG result = RegDeleteValueA(key, app_name.c_str());
|
||||
RegCloseKey(key);
|
||||
return result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND;
|
||||
const auto name = FromUtf8(app_name);
|
||||
if (name.empty()) return false;
|
||||
// Portable builds must not modify an installed build's elevated task.
|
||||
if (kAutostartRequiresElevation && !RemoveLogonTask(name)) return false;
|
||||
return RemoveRunEntry(name);
|
||||
}
|
||||
|
||||
bool IsAutostartEnabled(const std::string& app_name) {
|
||||
HKEY key = nullptr;
|
||||
if (RegOpenKeyExA(HKEY_CURRENT_USER, kRunKey, 0, KEY_READ, &key) !=
|
||||
ERROR_SUCCESS) {
|
||||
return false;
|
||||
const auto app = FromUtf8(app_name);
|
||||
if (app.empty()) return false;
|
||||
if (!kAutostartRequiresElevation) {
|
||||
std::wstring command;
|
||||
return ReadRunEntry(app, &command) == ERROR_SUCCESS;
|
||||
}
|
||||
const LONG result =
|
||||
RegQueryValueExA(key, app_name.c_str(), nullptr, nullptr, nullptr, nullptr);
|
||||
RegCloseKey(key);
|
||||
return result == ERROR_SUCCESS;
|
||||
const auto sid = CurrentUserSid();
|
||||
if (sid.empty()) return false;
|
||||
TaskScheduler scheduler;
|
||||
if (!scheduler.Open()) return false;
|
||||
auto name = MakeBstr(AutostartTaskName(app, sid));
|
||||
if (!name) return false;
|
||||
ComPtr<IRegisteredTask> task;
|
||||
if (FAILED(scheduler.folder->GetTask(name.get(), task.GetAddressOf())))
|
||||
return false;
|
||||
VARIANT_BOOL enabled = VARIANT_FALSE;
|
||||
return SUCCEEDED(task->get_Enabled(&enabled)) && enabled == VARIANT_TRUE;
|
||||
}
|
||||
|
||||
bool MigrateLegacyAutostart(const std::string& app_name) {
|
||||
if (!kAutostartRequiresElevation) return true;
|
||||
std::wstring command;
|
||||
const auto name = FromUtf8(app_name);
|
||||
if (name.empty()) return false;
|
||||
const LONG result = ReadRunEntry(name, &command);
|
||||
if (result == ERROR_FILE_NOT_FOUND || result == ERROR_PATH_NOT_FOUND)
|
||||
return true;
|
||||
if (result != ERROR_SUCCESS) return false;
|
||||
if (command.size() >= 2 && command.front() == L'"' && command.back() == L'"')
|
||||
command = command.substr(1, command.size() - 2);
|
||||
const auto executable = GetAutostartExecutablePath();
|
||||
if (executable.empty()) return false;
|
||||
if (_wcsicmp(command.c_str(), FromUtf8(executable).c_str()) != 0) return true;
|
||||
return EnableAutostart(app_name, executable);
|
||||
}
|
||||
|
||||
bool RemoveInstalledAutostart(const std::string& app_name) {
|
||||
const auto name = FromUtf8(app_name);
|
||||
const auto executable = FromUtf8(GetAutostartExecutablePath());
|
||||
if (name.empty() || executable.empty()) return false;
|
||||
TaskScheduler scheduler;
|
||||
if (!scheduler.Open()) return false;
|
||||
ComPtr<IRegisteredTaskCollection> tasks;
|
||||
if (!Check(scheduler.folder->GetTasks(TASK_ENUM_HIDDEN, tasks.GetAddressOf()),
|
||||
"enumerate logon tasks"))
|
||||
return false;
|
||||
LONG count = 0;
|
||||
if (!Check(tasks->get_Count(&count), "count logon tasks")) return false;
|
||||
const auto prefix = name + L" Autostart ";
|
||||
std::vector<std::wstring> remove;
|
||||
for (LONG index = 1; index <= count; ++index) {
|
||||
VARIANT item{};
|
||||
item.vt = VT_I4;
|
||||
item.lVal = index;
|
||||
ComPtr<IRegisteredTask> task;
|
||||
if (!Check(tasks->get_Item(item, task.GetAddressOf()), "read logon task"))
|
||||
return false;
|
||||
BSTR raw_name = nullptr;
|
||||
if (!Check(task->get_Name(&raw_name), "read task name")) return false;
|
||||
Bstr task_name(raw_name, SysFreeString);
|
||||
const std::wstring task_text(task_name.get() ? task_name.get() : L"");
|
||||
if (task_text.compare(0, prefix.size(), prefix) != 0) continue;
|
||||
ComPtr<ITaskDefinition> definition;
|
||||
ComPtr<IActionCollection> actions;
|
||||
ComPtr<IAction> action;
|
||||
ComPtr<IExecAction> exec;
|
||||
LONG action_count = 0;
|
||||
if (!Check(task->get_Definition(definition.GetAddressOf()),
|
||||
"read task definition") ||
|
||||
!Check(definition->get_Actions(actions.GetAddressOf()),
|
||||
"read task actions") ||
|
||||
!Check(actions->get_Count(&action_count), "count task actions"))
|
||||
return false;
|
||||
if (action_count != 1) continue;
|
||||
if (!Check(actions->get_Item(1, action.GetAddressOf()), "read task action"))
|
||||
return false;
|
||||
if (FAILED(action.As(&exec))) continue;
|
||||
BSTR raw_path = nullptr;
|
||||
if (!Check(exec->get_Path(&raw_path), "read task executable")) return false;
|
||||
Bstr path(raw_path, SysFreeString);
|
||||
if (path && _wcsicmp(path.get(), executable.c_str()) == 0)
|
||||
remove.push_back(task_text);
|
||||
}
|
||||
// Collect names first; deleting during enumeration can change its indices.
|
||||
for (const auto& task : remove) {
|
||||
auto task_name = MakeBstr(task);
|
||||
if (!task_name || !Check(scheduler.folder->DeleteTask(task_name.get(), 0),
|
||||
"remove installed logon task"))
|
||||
return false;
|
||||
}
|
||||
std::wstring command;
|
||||
const LONG result = ReadRunEntry(name, &command);
|
||||
if (result == ERROR_FILE_NOT_FOUND || result == ERROR_PATH_NOT_FOUND)
|
||||
return true;
|
||||
if (result != ERROR_SUCCESS) return false;
|
||||
if (command.size() >= 2 && command.front() == L'"' && command.back() == L'"')
|
||||
command = command.substr(1, command.size() - 2);
|
||||
return _wcsicmp(command.c_str(), executable.c_str()) != 0 ||
|
||||
RemoveRunEntry(name);
|
||||
}
|
||||
|
||||
} // namespace crossdesk::platform
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
#ifndef CROSSDESK_WINDOWS_AUTOSTART_TASK_H_
|
||||
#define CROSSDESK_WINDOWS_AUTOSTART_TASK_H_
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace crossdesk::platform {
|
||||
|
||||
// Keep this in sync with crossdesk.rc and crossdesk_portable.rc. Elevating a
|
||||
// portable build manually must not change its normal login startup policy.
|
||||
#if !defined(CROSSDESK_DEBUG) && \
|
||||
(!defined(CROSSDESK_PORTABLE) || !CROSSDESK_PORTABLE)
|
||||
inline constexpr bool kAutostartRequiresElevation = true;
|
||||
#else
|
||||
inline constexpr bool kAutostartRequiresElevation = false;
|
||||
#endif
|
||||
|
||||
inline std::wstring AutostartTaskName(const std::wstring& app_name,
|
||||
const std::wstring& user_sid) {
|
||||
return app_name + L" Autostart " + user_sid;
|
||||
}
|
||||
|
||||
inline std::wstring EscapeTaskXml(const std::wstring& value) {
|
||||
std::wstring escaped;
|
||||
for (const wchar_t character : value) {
|
||||
switch (character) {
|
||||
case L'&':
|
||||
escaped += L"&";
|
||||
break;
|
||||
case L'<':
|
||||
escaped += L"<";
|
||||
break;
|
||||
case L'>':
|
||||
escaped += L">";
|
||||
break;
|
||||
case L'"':
|
||||
escaped += L""";
|
||||
break;
|
||||
case L'\'':
|
||||
escaped += L"'";
|
||||
break;
|
||||
default:
|
||||
escaped += character;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return escaped;
|
||||
}
|
||||
|
||||
inline std::wstring BuildAutostartTaskXml(const std::wstring& user_sid,
|
||||
const std::wstring& executable,
|
||||
const std::wstring& directory) {
|
||||
const auto sid = EscapeTaskXml(user_sid);
|
||||
// InteractiveToken keeps the GUI in this user's logged-in desktop and does
|
||||
// not store a password. A remote desktop client must also survive battery
|
||||
// operation and the scheduler's default three-day execution time limit.
|
||||
return L"<Task version=\"1.3\" "
|
||||
L"xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">"
|
||||
L"<Triggers><LogonTrigger><Enabled>true</Enabled>"
|
||||
L"<ExecutionTimeLimit>PT0S</ExecutionTimeLimit><UserId>" +
|
||||
sid +
|
||||
L"</UserId></LogonTrigger></Triggers>"
|
||||
L"<Principals><Principal id=\"CurrentUser\"><UserId>" +
|
||||
sid +
|
||||
L"</UserId><LogonType>InteractiveToken</LogonType>"
|
||||
L"<RunLevel>HighestAvailable</RunLevel></Principal></Principals>"
|
||||
L"<Settings><MultipleInstancesPolicy>IgnoreNew</"
|
||||
L"MultipleInstancesPolicy>"
|
||||
L"<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>"
|
||||
L"<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>"
|
||||
L"<AllowHardTerminate>false</AllowHardTerminate>"
|
||||
L"<Enabled>true</Enabled><ExecutionTimeLimit>PT0S</ExecutionTimeLimit>"
|
||||
L"</Settings><Actions Context=\"CurrentUser\"><Exec><Command>" +
|
||||
EscapeTaskXml(executable) + L"</Command><WorkingDirectory>" +
|
||||
EscapeTaskXml(directory) +
|
||||
L"</WorkingDirectory></Exec></Actions></Task>";
|
||||
}
|
||||
|
||||
// Called at normal startup and by the installer after an upgrade. Only migrate
|
||||
// a legacy Run entry pointing to this executable, leaving other copies alone.
|
||||
bool MigrateLegacyAutostart(const std::string& app_name);
|
||||
|
||||
// Installer cleanup: remove tasks for this executable across users, preserving
|
||||
// registrations belonging to other installation/portable directories.
|
||||
bool RemoveInstalledAutostart(const std::string& app_name);
|
||||
|
||||
} // namespace crossdesk::platform
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,77 @@
|
||||
#include "application/gui_application.h"
|
||||
|
||||
#include <Windows.h>
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include "rd_log.h"
|
||||
#include "unattended_config.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
int GuiApplication::RunUnattended(void* stop_event) {
|
||||
if (!stop_event || !IsLocalSystemProcess() || !IsUnattendedEnabled() ||
|
||||
!PrepareUnattendedDirectory(false))
|
||||
return 1;
|
||||
unattended_host_ = true;
|
||||
DWORD session = 0;
|
||||
if (!ProcessIdToSessionId(GetCurrentProcessId(), &session) || session == 0)
|
||||
return 1;
|
||||
|
||||
path_manager_ = std::make_unique<PathManager>("CrossDesk");
|
||||
const auto root = UnattendedDataPath();
|
||||
cache_path_ = root.string();
|
||||
exec_log_path_ = (root / L"logs").string();
|
||||
dll_log_path_ = exec_log_path_;
|
||||
InitializeLogger();
|
||||
config_center_ = std::make_unique<ConfigCenter>(cache_path_ + "/config.ini");
|
||||
if (config_center_->SetPrivacyScreen(false) != 0 ||
|
||||
config_center_->SetSaveRemotePreviews(false) != 0)
|
||||
return 1;
|
||||
InitializeSettings();
|
||||
|
||||
// The transport and device controllers do not need a Slint window, an SDL
|
||||
// video driver, a tray icon, or a logged-in user's audio/clipboard session.
|
||||
if (!SDL_Init(SDL_INIT_EVENTS)) return 1;
|
||||
devices_.Initialize();
|
||||
ULONGLONG last_status = 0;
|
||||
ULONGLONG next_peer_attempt = 0;
|
||||
while (WaitForSingleObject(stop_event, 16) == WAIT_TIMEOUT) {
|
||||
HandleSessionCleanup();
|
||||
HandlePasswordChangeResult();
|
||||
HandleCredentialRecovery();
|
||||
const auto now = GetTickCount64();
|
||||
if (!peer_ && now >= next_peer_attempt) {
|
||||
next_peer_attempt = now + 3000;
|
||||
if (CreateConnectionPeer() != 0) CloseConnectionPeer();
|
||||
}
|
||||
HandleConnectionStatusChange();
|
||||
HandleWindowsServiceIntegration();
|
||||
devices_.UpdateInteractions();
|
||||
ShareLocalCursorState();
|
||||
if (now - last_status >= 1000) {
|
||||
last_status = now;
|
||||
if (!WriteUnattendedStatus(settings_.ActiveIdentity(),
|
||||
signal_connected_.load(), session)) {
|
||||
LOG_WARN("Could not publish unattended host status");
|
||||
}
|
||||
}
|
||||
// Pump native device messages without constructing an application window.
|
||||
MSG message{};
|
||||
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
}
|
||||
|
||||
// Quiesce network callbacks before destroying the controllers they use.
|
||||
CloseAllRemoteSessions();
|
||||
WaitForSessionCleanup();
|
||||
keyboard_.ReleaseAllRemotePressedKeys("unattended_host_exit");
|
||||
devices_.DestroyDevices();
|
||||
devices_.DestroyFactories();
|
||||
privacy_.Shutdown();
|
||||
WriteUnattendedStatus(settings_.ActiveIdentity(), false, session);
|
||||
SDL_Quit();
|
||||
return 0;
|
||||
}
|
||||
} // namespace crossdesk
|
||||
@@ -14,8 +14,10 @@
|
||||
|
||||
#if _WIN32
|
||||
#include "interactive_desktop.h"
|
||||
#include "desktop_transition_policy.h"
|
||||
#include "interactive_state.h"
|
||||
#include "service_host.h"
|
||||
#include "unattended_config.h"
|
||||
#endif
|
||||
|
||||
namespace crossdesk {
|
||||
@@ -25,12 +27,13 @@ struct WindowsServiceInteractiveStatus {
|
||||
bool available = false;
|
||||
bool session_mismatch = false;
|
||||
bool sas_secure_desktop_grace_active = false;
|
||||
bool consent_ui_visible = false;
|
||||
unsigned int error_code = 0;
|
||||
std::string interactive_stage;
|
||||
std::string error;
|
||||
};
|
||||
|
||||
constexpr uint32_t kWindowsServiceStatusIntervalMs = 1000;
|
||||
constexpr uint32_t kWindowsServiceStatusIntervalMs = 250;
|
||||
constexpr uint32_t kWindowsServiceSasSecureDesktopGraceMs = 2000;
|
||||
constexpr DWORD kWindowsServiceQueryTimeoutMs = 500;
|
||||
constexpr DWORD kWindowsServiceSasTimeoutMs = 500;
|
||||
@@ -51,15 +54,13 @@ BuildWindowsServiceStatusAction(const WindowsServiceInteractiveStatus &status) {
|
||||
return action;
|
||||
}
|
||||
|
||||
bool QueryWindowsServiceInteractiveStatus(
|
||||
bool ParseWindowsServiceInteractiveStatus(const std::string& response,
|
||||
WindowsServiceInteractiveStatus *status) {
|
||||
if (status == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
*status = WindowsServiceInteractiveStatus{};
|
||||
const std::string response =
|
||||
QueryCrossDeskService("status", kWindowsServiceQueryTimeoutMs);
|
||||
auto json = nlohmann::json::parse(response, nullptr, false);
|
||||
if (json.is_discarded() || !json.is_object()) {
|
||||
status->error = "invalid_service_status_json";
|
||||
@@ -84,6 +85,7 @@ bool QueryWindowsServiceInteractiveStatus(
|
||||
status->interactive_stage = json.value("interactive_stage", std::string());
|
||||
status->sas_secure_desktop_grace_active =
|
||||
json.value("sas_secure_desktop_grace_active", false);
|
||||
status->consent_ui_visible = json.value("consent_ui_visible", false);
|
||||
|
||||
if (ShouldNormalizeUnlockToUserDesktop(
|
||||
json.value("interactive_lock_screen_visible", false),
|
||||
@@ -125,13 +127,31 @@ void GuiRuntime::HandleWindowsServiceIntegration() {
|
||||
return;
|
||||
}
|
||||
|
||||
bool force_broadcast = false;
|
||||
if (!windows_service_worker_) {
|
||||
windows_service_worker_ = std::make_unique<ServiceQueryWorker>(
|
||||
[](const std::string& command) {
|
||||
ServiceQueryResult result;
|
||||
result.response = QueryCrossDeskService(
|
||||
command, command == "sas" ? kWindowsServiceSasTimeoutMs
|
||||
: kWindowsServiceQueryTimeoutMs);
|
||||
if (command == "status") {
|
||||
// A successful service reply can still carry a pre-unlock sample.
|
||||
result.user_desktop_recovered = IsCurrentSessionUserDesktopActive();
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
if (pending_windows_service_sas_.exchange(false, std::memory_order_relaxed)) {
|
||||
if (privacy_.Engaged()) {
|
||||
privacy_.Fail("Security shortcut requested; privacy screen will turn off");
|
||||
}
|
||||
const std::string response =
|
||||
QueryCrossDeskService("sas", kWindowsServiceSasTimeoutMs);
|
||||
windows_service_worker_->RequestSas();
|
||||
}
|
||||
|
||||
const uint32_t now = static_cast<uint32_t>(SDL_GetTicks());
|
||||
auto result = windows_service_worker_->Take();
|
||||
if (result && result->command == "sas") {
|
||||
const std::string& response = result->response;
|
||||
auto json = nlohmann::json::parse(response, nullptr, false);
|
||||
if (json.is_discarded() || !json.value("ok", false)) {
|
||||
LOG_WARN("Remote SAS request failed: {}", response);
|
||||
@@ -145,21 +165,33 @@ void GuiRuntime::HandleWindowsServiceIntegration() {
|
||||
local_interactive_stage_ = "secure-desktop";
|
||||
}
|
||||
last_windows_service_status_tick_ = 0;
|
||||
force_broadcast = true;
|
||||
PublishWindowsInputStage();
|
||||
if (local_service_status_received_) {
|
||||
WindowsServiceInteractiveStatus optimistic;
|
||||
optimistic.available = local_service_available_;
|
||||
optimistic.interactive_stage = local_interactive_stage_;
|
||||
const auto message = BuildWindowsServiceStatusAction(optimistic).to_json();
|
||||
SendReliableDataFrame(peer_, message.data(), message.size(),
|
||||
control_data_label_.c_str());
|
||||
}
|
||||
result.reset();
|
||||
}
|
||||
|
||||
const uint32_t now = static_cast<uint32_t>(SDL_GetTicks());
|
||||
if (!force_broadcast && last_windows_service_status_tick_ != 0 &&
|
||||
now - last_windows_service_status_tick_ <
|
||||
if (last_windows_service_status_tick_ == 0 ||
|
||||
now - last_windows_service_status_tick_ >=
|
||||
kWindowsServiceStatusIntervalMs) {
|
||||
return;
|
||||
windows_service_worker_->RequestStatus();
|
||||
last_windows_service_status_tick_ = now;
|
||||
}
|
||||
last_windows_service_status_tick_ = now;
|
||||
if (!result) return;
|
||||
|
||||
WindowsServiceInteractiveStatus status;
|
||||
const bool status_ok = QueryWindowsServiceInteractiveStatus(&status);
|
||||
const bool user_desktop_recovered =
|
||||
!status.available && IsCurrentSessionUserDesktopActive();
|
||||
const bool status_ok = ParseWindowsServiceInteractiveStatus(result->response, &status);
|
||||
const bool user_desktop_recovered = PreferUserDesktopInput(
|
||||
result->user_desktop_recovered, status.consent_ui_visible);
|
||||
if (status.available || status.session_mismatch) {
|
||||
windows_consent_ui_.store(status.available && status.consent_ui_visible);
|
||||
}
|
||||
if (user_desktop_recovered) status.interactive_stage = "user-desktop";
|
||||
WindowsServiceInteractiveStatus broadcast_status = status;
|
||||
const bool previous_secure_desktop_interaction =
|
||||
@@ -169,12 +201,17 @@ void GuiRuntime::HandleWindowsServiceIntegration() {
|
||||
static_cast<int32_t>(optimistic_windows_secure_desktop_until_tick_ -
|
||||
now) > 0;
|
||||
const bool keep_optimistic_secure_desktop =
|
||||
status_ok && status.available && optimistic_secure_desktop_active &&
|
||||
!user_desktop_recovered && status_ok && status.available && optimistic_secure_desktop_active &&
|
||||
status.sas_secure_desktop_grace_active &&
|
||||
status.interactive_stage == "user-desktop";
|
||||
local_service_status_received_ =
|
||||
status_ok || previous_secure_desktop_interaction;
|
||||
local_service_available_ = status.available;
|
||||
const bool service_was_available =
|
||||
local_service_available_.exchange(status.available);
|
||||
if (status.available && !service_was_available && !IsAdministratorProcess()) {
|
||||
LOG_INFO("Unelevated host input routed through Windows service, including "
|
||||
"elevated applications on the user desktop");
|
||||
}
|
||||
if (status.available) {
|
||||
if (keep_optimistic_secure_desktop) {
|
||||
local_interactive_stage_ = "secure-desktop";
|
||||
@@ -226,6 +263,7 @@ void GuiRuntime::HandleWindowsServiceIntegration() {
|
||||
last_logged_service_error_code = 0;
|
||||
}
|
||||
|
||||
PublishWindowsInputStage();
|
||||
RemoteAction remote_action =
|
||||
BuildWindowsServiceStatusAction(broadcast_status);
|
||||
std::string msg = remote_action.to_json();
|
||||
@@ -239,14 +277,17 @@ void GuiRuntime::HandleWindowsServiceIntegration() {
|
||||
|
||||
#if _WIN32
|
||||
void GuiRuntime::ResetLocalWindowsServiceState(bool clear_pending_sas) {
|
||||
if (windows_service_worker_) windows_service_worker_->Reset();
|
||||
last_windows_service_status_tick_ = 0;
|
||||
if (clear_pending_sas) {
|
||||
pending_windows_service_sas_.store(false, std::memory_order_relaxed);
|
||||
}
|
||||
local_service_status_received_ = false;
|
||||
local_service_available_ = false;
|
||||
windows_consent_ui_.store(false);
|
||||
local_interactive_stage_.clear();
|
||||
optimistic_windows_secure_desktop_until_tick_ = 0;
|
||||
PublishWindowsInputStage();
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
#include "keyboard_capturer.h"
|
||||
|
||||
#include <hidusage.h>
|
||||
|
||||
#include "rd_log.h"
|
||||
#include "windows_input_injector.h"
|
||||
#include "windows_input_marker.h"
|
||||
@@ -10,8 +8,8 @@
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
|
||||
constexpr wchar_t kRawInputWindowClassName[] =
|
||||
L"CrossDeskKeyboardRawInputWindow";
|
||||
constexpr UINT kHookRenewIntervalMs = 500;
|
||||
constexpr ULONGLONG kHookStallTimeoutMs = 2000;
|
||||
|
||||
bool PreferSideSpecificVkInjection(int key_code) {
|
||||
switch (key_code) {
|
||||
@@ -31,15 +29,32 @@ bool PreferSideSpecificVkInjection(int key_code) {
|
||||
|
||||
} // namespace
|
||||
|
||||
PlatformKeyboardCapturer::PlatformKeyboardCapturer() {}
|
||||
thread_local PlatformKeyboardCapturer*
|
||||
PlatformKeyboardCapturer::active_capturer_ = nullptr;
|
||||
|
||||
PlatformKeyboardCapturer::~PlatformKeyboardCapturer() { Unhook(); }
|
||||
|
||||
bool PlatformKeyboardCapturer::IsHookActive() const {
|
||||
if (!hook_active_.load()) return false;
|
||||
const auto last_pump_tick = last_hook_pump_tick_.load();
|
||||
return GetTickCount64() - last_pump_tick < kHookStallTimeoutMs;
|
||||
}
|
||||
|
||||
int PlatformKeyboardCapturer::Hook(OnKeyAction on_key_action, void* user_ptr) {
|
||||
if (capture_thread_.joinable()) {
|
||||
return 0;
|
||||
return IsHookActive() ? 0 : -1;
|
||||
}
|
||||
|
||||
// Hook() is called only while the stream has focus. Pin capture to that
|
||||
// window so a focus change cannot steal input before the UI stops capture.
|
||||
const HWND foreground_window = GetForegroundWindow();
|
||||
DWORD process_id = 0;
|
||||
GetWindowThreadProcessId(foreground_window, &process_id);
|
||||
if (!on_key_action || !foreground_window ||
|
||||
process_id != GetCurrentProcessId()) {
|
||||
return -1;
|
||||
}
|
||||
capture_window_ = foreground_window;
|
||||
on_key_action_ = on_key_action;
|
||||
user_ptr_ = user_ptr;
|
||||
{
|
||||
@@ -49,7 +64,7 @@ int PlatformKeyboardCapturer::Hook(OnKeyAction on_key_action, void* user_ptr) {
|
||||
capture_start_succeeded_ = false;
|
||||
}
|
||||
|
||||
capture_thread_ = std::thread(&PlatformKeyboardCapturer::RawInputThreadMain, this);
|
||||
capture_thread_ = std::thread(&PlatformKeyboardCapturer::CaptureThreadMain, this);
|
||||
|
||||
std::unique_lock<std::mutex> lock(capture_state_mutex_);
|
||||
capture_start_condition_.wait(
|
||||
@@ -69,6 +84,7 @@ int PlatformKeyboardCapturer::Hook(OnKeyAction on_key_action, void* user_ptr) {
|
||||
}
|
||||
|
||||
int PlatformKeyboardCapturer::Unhook() {
|
||||
hook_active_.store(false);
|
||||
DWORD capture_thread_id = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(capture_state_mutex_);
|
||||
@@ -76,7 +92,7 @@ int PlatformKeyboardCapturer::Unhook() {
|
||||
}
|
||||
if (capture_thread_id != 0 &&
|
||||
!PostThreadMessageW(capture_thread_id, WM_QUIT, 0, 0)) {
|
||||
LOG_WARN("Failed to stop keyboard raw input thread, thread_id={}, error={}",
|
||||
LOG_WARN("Failed to stop keyboard hook thread, thread_id={}, error={}",
|
||||
capture_thread_id, GetLastError());
|
||||
}
|
||||
if (capture_thread_.joinable()) {
|
||||
@@ -85,15 +101,130 @@ int PlatformKeyboardCapturer::Unhook() {
|
||||
|
||||
on_key_action_ = nullptr;
|
||||
user_ptr_ = nullptr;
|
||||
capture_window_ = nullptr;
|
||||
local_keys_down_.fill(false);
|
||||
captured_keys_.fill({});
|
||||
return 0;
|
||||
}
|
||||
|
||||
void PlatformKeyboardCapturer::RawInputThreadMain() {
|
||||
void PlatformKeyboardCapturer::SnapshotLocalKeys() {
|
||||
local_keys_down_.fill(false);
|
||||
for (int code = VK_BACK; code < 0xFF; ++code)
|
||||
local_keys_down_[code] = (GetAsyncKeyState(code) & 0x8000) != 0;
|
||||
ForwardLocalModifiers();
|
||||
}
|
||||
|
||||
void PlatformKeyboardCapturer::ForwardKey(int code, bool down,
|
||||
uint32_t scan_code, bool extended) {
|
||||
captured_keys_[code] = down ? KeyboardKey{code, scan_code, extended}
|
||||
: KeyboardKey{};
|
||||
on_key_action_(code, down, scan_code, extended, user_ptr_);
|
||||
}
|
||||
|
||||
void PlatformKeyboardCapturer::ForwardLocalModifiers() {
|
||||
// Windows already saw these presses before capture began. Forward held
|
||||
// modifiers now, but let their eventual physical releases reach Windows
|
||||
// too. Swallowing those releases would leave the controller's keys stuck.
|
||||
for (const int code : {VK_LSHIFT, VK_RSHIFT, VK_LCONTROL, VK_RCONTROL,
|
||||
VK_LMENU, VK_RMENU, VK_LWIN, VK_RWIN}) {
|
||||
if (!local_keys_down_[code] || captured_keys_[code].key_code != 0) continue;
|
||||
const UINT scan = MapVirtualKeyW(code, MAPVK_VK_TO_VSC_EX);
|
||||
ForwardKey(code, true, scan & 0xFF, (scan & 0xFF00) != 0);
|
||||
}
|
||||
}
|
||||
|
||||
void PlatformKeyboardCapturer::ReleaseCapturedKeys() {
|
||||
for (const bool modifiers : {false, true}) {
|
||||
for (const auto key : captured_keys_) {
|
||||
if (key.key_code != 0 && IsKeyboardModifier(key.key_code) == modifiers)
|
||||
ForwardKey(key.key_code, false, key.scan_code, key.extended);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool PlatformKeyboardCapturer::RenewKeyboardHook() {
|
||||
bool raw_keyboard_suspended = false;
|
||||
if (!raw_keyboard_guard_.Suspend(raw_keyboard_suspended)) {
|
||||
hook_active_.store(false);
|
||||
LOG_WARN("Failed to suspend raw keyboard registration, error={}",
|
||||
GetLastError());
|
||||
return false;
|
||||
}
|
||||
// Windows can silently remove a timed-out hook. Renew periodically instead
|
||||
// of relying on a bool set at startup. Install first to avoid an input gap.
|
||||
const HHOOK replacement = SetWindowsHookExW(
|
||||
WH_KEYBOARD_LL, &PlatformKeyboardCapturer::KeyboardHookProc,
|
||||
GetModuleHandleW(nullptr), 0);
|
||||
if (!replacement) {
|
||||
hook_active_.store(false);
|
||||
LOG_WARN("Failed to install keyboard hook, error={}", GetLastError());
|
||||
return false;
|
||||
}
|
||||
const HHOOK previous = keyboard_hook_;
|
||||
keyboard_hook_ = replacement;
|
||||
if (raw_keyboard_suspended && !previous)
|
||||
LOG_INFO("Suspended raw keyboard input for shortcut capture");
|
||||
bool reset_keys = previous && raw_keyboard_suspended;
|
||||
if (previous && !UnhookWindowsHookEx(previous)) {
|
||||
const DWORD error = GetLastError();
|
||||
if (error != ERROR_INVALID_HOOK_HANDLE) {
|
||||
// Do not keep capturing through two live hooks: a passed-through
|
||||
// inherited release could otherwise be handled twice and swallowed.
|
||||
// Renewal stops immediately, so only this one old hook needs cleanup.
|
||||
retired_hook_ = previous;
|
||||
hook_active_.store(false);
|
||||
LOG_WARN("Failed to retire keyboard hook, error={}", error);
|
||||
return false;
|
||||
}
|
||||
reset_keys = true;
|
||||
LOG_WARN("Recovered keyboard hook, error={}", error);
|
||||
}
|
||||
if (reset_keys) {
|
||||
// Events may have escaped while the hook was unavailable or a backend
|
||||
// re-enabled raw input. Cancel uncertain presses and adopt local state.
|
||||
ReleaseCapturedKeys();
|
||||
if (GetForegroundWindow() == capture_window_)
|
||||
SnapshotLocalKeys();
|
||||
else
|
||||
local_keys_down_.fill(false);
|
||||
LOG_WARN("Reset captured keys after keyboard capture recovery");
|
||||
}
|
||||
last_hook_pump_tick_.store(GetTickCount64());
|
||||
hook_active_.store(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
void PlatformKeyboardCapturer::RemoveKeyboardHook() {
|
||||
if (keyboard_hook_) UnhookWindowsHookEx(keyboard_hook_);
|
||||
keyboard_hook_ = nullptr;
|
||||
if (retired_hook_) UnhookWindowsHookEx(retired_hook_);
|
||||
retired_hook_ = nullptr;
|
||||
if (!raw_keyboard_guard_.Restore())
|
||||
LOG_WARN("Failed to restore raw keyboard registration, error={}",
|
||||
GetLastError());
|
||||
}
|
||||
|
||||
void PlatformKeyboardCapturer::CaptureThreadMain() {
|
||||
const DWORD thread_id = GetCurrentThreadId();
|
||||
|
||||
MSG message{};
|
||||
PeekMessageW(&message, nullptr, WM_USER, WM_USER, PM_NOREMOVE);
|
||||
const bool capture_started = CreateRawInputWindow();
|
||||
active_capturer_ = this;
|
||||
// Raw Input observes shortcuts but cannot prevent Alt+Tab, Win+D, etc.
|
||||
// from acting on the controller. Keep the hook off the UI/network thread:
|
||||
// its callback only queues events for SessionDeviceManager to forward.
|
||||
const bool installed = RenewKeyboardHook();
|
||||
const UINT_PTR timer = installed
|
||||
? SetTimer(nullptr, 0, kHookRenewIntervalMs, nullptr)
|
||||
: 0;
|
||||
const bool capture_started = installed && timer != 0;
|
||||
if (installed && !timer) {
|
||||
LOG_WARN("Failed to create keyboard hook renewal timer, error={}",
|
||||
GetLastError());
|
||||
}
|
||||
hook_active_.store(capture_started);
|
||||
if (capture_started && GetForegroundWindow() == capture_window_)
|
||||
SnapshotLocalKeys();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(capture_state_mutex_);
|
||||
capture_thread_id_ = thread_id;
|
||||
@@ -103,153 +234,78 @@ void PlatformKeyboardCapturer::RawInputThreadMain() {
|
||||
capture_start_condition_.notify_one();
|
||||
|
||||
if (!capture_started) {
|
||||
RemoveKeyboardHook();
|
||||
active_capturer_ = nullptr;
|
||||
std::lock_guard<std::mutex> lock(capture_state_mutex_);
|
||||
capture_thread_id_ = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_INFO("Keyboard raw input capture started, thread_id={}", thread_id);
|
||||
LOG_INFO("Keyboard hook capture started, thread_id={}", thread_id);
|
||||
while (true) {
|
||||
const BOOL get_message_result = GetMessageW(&message, nullptr, 0, 0);
|
||||
if (get_message_result <= 0) {
|
||||
if (get_message_result < 0) {
|
||||
LOG_WARN("Keyboard raw input message loop failed, thread_id={}, "
|
||||
LOG_WARN("Keyboard hook message loop failed, thread_id={}, "
|
||||
"error={}",
|
||||
thread_id, GetLastError());
|
||||
}
|
||||
break;
|
||||
}
|
||||
last_hook_pump_tick_.store(GetTickCount64());
|
||||
if (message.message == WM_TIMER && message.wParam == timer) {
|
||||
if (!RenewKeyboardHook()) break;
|
||||
continue;
|
||||
}
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
|
||||
DestroyRawInputWindow();
|
||||
hook_active_.store(false);
|
||||
KillTimer(nullptr, timer);
|
||||
RemoveKeyboardHook();
|
||||
active_capturer_ = nullptr;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(capture_state_mutex_);
|
||||
capture_thread_id_ = 0;
|
||||
}
|
||||
LOG_INFO("Keyboard raw input capture stopped, thread_id={}", thread_id);
|
||||
LOG_INFO("Keyboard hook capture stopped, thread_id={}", thread_id);
|
||||
}
|
||||
|
||||
bool PlatformKeyboardCapturer::CreateRawInputWindow() {
|
||||
const HINSTANCE instance = GetModuleHandleW(nullptr);
|
||||
WNDCLASSEXW window_class{};
|
||||
window_class.cbSize = sizeof(window_class);
|
||||
window_class.lpfnWndProc = &PlatformKeyboardCapturer::RawInputWindowProc;
|
||||
window_class.hInstance = instance;
|
||||
window_class.lpszClassName = kRawInputWindowClassName;
|
||||
|
||||
if (RegisterClassExW(&window_class) == 0) {
|
||||
const DWORD error = GetLastError();
|
||||
if (error != ERROR_CLASS_ALREADY_EXISTS) {
|
||||
LOG_WARN("Failed to register keyboard raw input window class, error={}",
|
||||
error);
|
||||
return false;
|
||||
}
|
||||
LRESULT CALLBACK PlatformKeyboardCapturer::KeyboardHookProc(
|
||||
int code, WPARAM message, LPARAM data) {
|
||||
if (code == HC_ACTION && active_capturer_ && data != 0 &&
|
||||
active_capturer_->HandleKeyboardInput(
|
||||
message, *reinterpret_cast<const KBDLLHOOKSTRUCT*>(data),
|
||||
GetForegroundWindow())) {
|
||||
return 1;
|
||||
}
|
||||
return CallNextHookEx(nullptr, code, message, data);
|
||||
}
|
||||
|
||||
raw_input_window_ = CreateWindowExW(
|
||||
0, kRawInputWindowClassName, L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr,
|
||||
instance, this);
|
||||
if (!raw_input_window_) {
|
||||
LOG_WARN("Failed to create keyboard raw input window, error={}",
|
||||
GetLastError());
|
||||
bool PlatformKeyboardCapturer::HandleKeyboardInput(
|
||||
WPARAM message, const KBDLLHOOKSTRUCT& keyboard, HWND foreground_window) {
|
||||
if (!hook_active_.load() || !on_key_action_ || !capture_window_ ||
|
||||
keyboard.vkCode < VK_BACK || keyboard.vkCode >= 0xFF ||
|
||||
keyboard.dwExtraInfo == kInjectedKeyboardInputMarker) {
|
||||
return false;
|
||||
}
|
||||
|
||||
RAWINPUTDEVICE keyboard_device{};
|
||||
keyboard_device.usUsagePage = HID_USAGE_PAGE_GENERIC;
|
||||
keyboard_device.usUsage = HID_USAGE_GENERIC_KEYBOARD;
|
||||
keyboard_device.dwFlags = RIDEV_DEVNOTIFY | RIDEV_INPUTSINK;
|
||||
keyboard_device.hwndTarget = raw_input_window_;
|
||||
if (!RegisterRawInputDevices(&keyboard_device, 1,
|
||||
sizeof(keyboard_device))) {
|
||||
LOG_WARN("Failed to register keyboard raw input, error={}", GetLastError());
|
||||
DestroyWindow(raw_input_window_);
|
||||
raw_input_window_ = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
raw_input_registered_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
void PlatformKeyboardCapturer::DestroyRawInputWindow() {
|
||||
if (raw_input_registered_) {
|
||||
RAWINPUTDEVICE keyboard_device{};
|
||||
keyboard_device.usUsagePage = HID_USAGE_PAGE_GENERIC;
|
||||
keyboard_device.usUsage = HID_USAGE_GENERIC_KEYBOARD;
|
||||
keyboard_device.dwFlags = RIDEV_REMOVE;
|
||||
keyboard_device.hwndTarget = nullptr;
|
||||
if (!RegisterRawInputDevices(&keyboard_device, 1,
|
||||
sizeof(keyboard_device))) {
|
||||
LOG_WARN("Failed to unregister keyboard raw input, error={}",
|
||||
GetLastError());
|
||||
}
|
||||
raw_input_registered_ = false;
|
||||
}
|
||||
if (raw_input_window_) {
|
||||
DestroyWindow(raw_input_window_);
|
||||
raw_input_window_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
LRESULT CALLBACK PlatformKeyboardCapturer::RawInputWindowProc(
|
||||
HWND window, UINT message, WPARAM w_param, LPARAM l_param) {
|
||||
PlatformKeyboardCapturer* capturer = reinterpret_cast<PlatformKeyboardCapturer*>(
|
||||
GetWindowLongPtrW(window, GWLP_USERDATA));
|
||||
if (message == WM_NCCREATE) {
|
||||
auto* create = reinterpret_cast<CREATESTRUCTW*>(l_param);
|
||||
capturer = static_cast<PlatformKeyboardCapturer*>(create->lpCreateParams);
|
||||
SetWindowLongPtrW(window, GWLP_USERDATA,
|
||||
reinterpret_cast<LONG_PTR>(capturer));
|
||||
} else if (message == WM_INPUT && capturer) {
|
||||
capturer->HandleRawInput(reinterpret_cast<HRAWINPUT>(l_param));
|
||||
} else if (message == WM_NCDESTROY) {
|
||||
SetWindowLongPtrW(window, GWLP_USERDATA, 0);
|
||||
}
|
||||
return DefWindowProcW(window, message, w_param, l_param);
|
||||
}
|
||||
|
||||
void PlatformKeyboardCapturer::HandleRawInput(HRAWINPUT raw_input_handle) {
|
||||
RAWINPUT input{};
|
||||
UINT input_size = sizeof(input);
|
||||
const UINT bytes_read =
|
||||
GetRawInputData(raw_input_handle, RID_INPUT, &input, &input_size,
|
||||
sizeof(RAWINPUTHEADER));
|
||||
if (bytes_read == static_cast<UINT>(-1) ||
|
||||
bytes_read < sizeof(RAWINPUTHEADER) ||
|
||||
input.header.dwType != RIM_TYPEKEYBOARD) {
|
||||
return;
|
||||
}
|
||||
|
||||
const RAWKEYBOARD& keyboard = input.data.keyboard;
|
||||
if (keyboard.VKey == 0xFF ||
|
||||
keyboard.ExtraInformation ==
|
||||
static_cast<ULONG>(kInjectedKeyboardInputMarker)) {
|
||||
return;
|
||||
}
|
||||
// Do not reject LLKHF_INJECTED wholesale: an upstream remote session or
|
||||
// accessibility tool can be the controller's keyboard source.
|
||||
|
||||
bool is_down = false;
|
||||
if (keyboard.Message == WM_KEYDOWN || keyboard.Message == WM_SYSKEYDOWN) {
|
||||
if (message == WM_KEYDOWN || message == WM_SYSKEYDOWN) {
|
||||
is_down = true;
|
||||
} else if (keyboard.Message != WM_KEYUP &&
|
||||
keyboard.Message != WM_SYSKEYUP) {
|
||||
return;
|
||||
} else if (message != WM_KEYUP && message != WM_SYSKEYUP) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool extended = (keyboard.Flags & (RI_KEY_E0 | RI_KEY_E1)) != 0;
|
||||
UINT mapped_scan_code = keyboard.MakeCode;
|
||||
if ((keyboard.Flags & RI_KEY_E0) != 0) {
|
||||
const bool extended = (keyboard.flags & LLKHF_EXTENDED) != 0;
|
||||
UINT mapped_scan_code = keyboard.scanCode & 0xFF;
|
||||
if (extended) {
|
||||
mapped_scan_code |= 0xE000;
|
||||
} else if ((keyboard.Flags & RI_KEY_E1) != 0) {
|
||||
mapped_scan_code |= 0xE100;
|
||||
}
|
||||
if (mapped_scan_code == 0xE11D || mapped_scan_code == 0xE02A) {
|
||||
return;
|
||||
}
|
||||
|
||||
int key_code = static_cast<int>(keyboard.VKey);
|
||||
int key_code = static_cast<int>(keyboard.vkCode);
|
||||
if (key_code == VK_SHIFT || key_code == VK_CONTROL || key_code == VK_MENU) {
|
||||
const UINT normalized =
|
||||
MapVirtualKeyW(mapped_scan_code, MAPVK_VSC_TO_VK_EX);
|
||||
@@ -258,9 +314,19 @@ void PlatformKeyboardCapturer::HandleRawInput(HRAWINPUT raw_input_handle) {
|
||||
}
|
||||
}
|
||||
|
||||
if (on_key_action_) {
|
||||
on_key_action_(key_code, is_down, keyboard.MakeCode, extended, user_ptr_);
|
||||
if (foreground_window != capture_window_) {
|
||||
// This event goes to Windows, even if focus changed before the UI thread
|
||||
// has noticed. Remember ownership in case focus returns before Unhook().
|
||||
local_keys_down_[key_code] = is_down;
|
||||
if (!is_down && captured_keys_[key_code].key_code != 0)
|
||||
ForwardKey(key_code, false, keyboard.scanCode, extended);
|
||||
return false;
|
||||
}
|
||||
ForwardLocalModifiers();
|
||||
const bool release_local = !is_down && local_keys_down_[key_code];
|
||||
if (!is_down) local_keys_down_[key_code] = false;
|
||||
ForwardKey(key_code, is_down, keyboard.scanCode, extended);
|
||||
return !release_local;
|
||||
}
|
||||
|
||||
// Apply remote keyboard commands to the local machine.
|
||||
@@ -313,8 +379,10 @@ int PlatformKeyboardCapturer::SendKeyboardCommand(int key_code, bool is_down,
|
||||
|
||||
const UINT sent = SendInputOnUserDesktop(input);
|
||||
if (sent != 1) {
|
||||
const DWORD error = GetLastError();
|
||||
LOG_WARN("SendInput failed for key_code={}, is_down={}, err={}", key_code,
|
||||
is_down, GetLastError());
|
||||
is_down, error);
|
||||
SetLastError(error);
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,39 +9,54 @@
|
||||
|
||||
#include <Windows.h>
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
#include "device_controller.h"
|
||||
#include "keyboard_state.h"
|
||||
#include "windows_raw_keyboard_guard.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
class PlatformKeyboardCapturer final : public KeyboardCapturer {
|
||||
public:
|
||||
PlatformKeyboardCapturer();
|
||||
virtual ~PlatformKeyboardCapturer();
|
||||
PlatformKeyboardCapturer() = default;
|
||||
~PlatformKeyboardCapturer() override;
|
||||
|
||||
public:
|
||||
virtual int Hook(OnKeyAction on_key_action, void* user_ptr);
|
||||
virtual int Unhook();
|
||||
virtual int SendKeyboardCommand(int key_code, bool is_down,
|
||||
uint32_t scan_code = 0,
|
||||
bool extended = false);
|
||||
int Hook(OnKeyAction on_key_action, void* user_ptr) override;
|
||||
int Unhook() override;
|
||||
bool IsHookActive() const override;
|
||||
int SendKeyboardCommand(int key_code, bool is_down, uint32_t scan_code = 0,
|
||||
bool extended = false) override;
|
||||
|
||||
private:
|
||||
static LRESULT CALLBACK RawInputWindowProc(HWND window, UINT message,
|
||||
WPARAM w_param, LPARAM l_param);
|
||||
static LRESULT CALLBACK KeyboardHookProc(int code, WPARAM message,
|
||||
LPARAM data);
|
||||
static thread_local PlatformKeyboardCapturer* active_capturer_;
|
||||
|
||||
void RawInputThreadMain();
|
||||
bool CreateRawInputWindow();
|
||||
void DestroyRawInputWindow();
|
||||
void HandleRawInput(HRAWINPUT raw_input_handle);
|
||||
void CaptureThreadMain();
|
||||
bool RenewKeyboardHook();
|
||||
void RemoveKeyboardHook();
|
||||
void SnapshotLocalKeys();
|
||||
void ForwardLocalModifiers();
|
||||
void ReleaseCapturedKeys();
|
||||
void ForwardKey(int code, bool down, uint32_t scan_code, bool extended);
|
||||
bool HandleKeyboardInput(WPARAM message, const KBDLLHOOKSTRUCT& keyboard,
|
||||
HWND foreground_window);
|
||||
|
||||
OnKeyAction on_key_action_ = nullptr;
|
||||
void* user_ptr_ = nullptr;
|
||||
HWND raw_input_window_ = nullptr;
|
||||
bool raw_input_registered_ = false;
|
||||
HWND capture_window_ = nullptr;
|
||||
std::atomic<bool> hook_active_{false};
|
||||
std::atomic<ULONGLONG> last_hook_pump_tick_{0};
|
||||
HHOOK keyboard_hook_ = nullptr;
|
||||
WindowsRawKeyboardGuard raw_keyboard_guard_;
|
||||
HHOOK retired_hook_ = nullptr;
|
||||
std::array<bool, 256> local_keys_down_{};
|
||||
std::array<KeyboardKey, 256> captured_keys_{};
|
||||
std::thread capture_thread_;
|
||||
DWORD capture_thread_id_ = 0;
|
||||
bool capture_start_complete_ = false;
|
||||
|
||||
@@ -144,9 +144,11 @@ int PlatformMouseController::SendMouseCommand(RemoteAction remote_action,
|
||||
ip.mi.dwExtraInfo = kInjectedMouseInputMarker;
|
||||
const UINT sent = SendInputOnUserDesktop(ip);
|
||||
if (sent != 1) {
|
||||
const DWORD error = GetLastError();
|
||||
LOG_WARN("SendInput failed for mouse x={}, y={}, wheel={}, flag={}, err={}",
|
||||
ip.mi.dx, ip.mi.dy, remote_action.m.s,
|
||||
static_cast<int>(remote_action.m.flag), GetLastError());
|
||||
static_cast<int>(remote_action.m.flag), error);
|
||||
SetLastError(error);
|
||||
return -1;
|
||||
}
|
||||
if (ip.mi.dwFlags & MOUSEEVENTF_LEFTDOWN) pressed_buttons_.fetch_or(1);
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-09
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _WINDOWS_RAW_KEYBOARD_GUARD_H_
|
||||
#define _WINDOWS_RAW_KEYBOARD_GUARD_H_
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// Winit registers raw keyboard input for the process. Windows bypasses this
|
||||
// process's WH_KEYBOARD_LL hook while that registration is active. Temporarily
|
||||
// suspend only the keyboard registration while forwarding remote input, then
|
||||
// restore the backend's latest registration on exit. Raw mouse input is kept.
|
||||
class WindowsRawKeyboardGuard {
|
||||
public:
|
||||
bool Suspend(bool& changed) {
|
||||
changed = false;
|
||||
std::optional<RAWINPUTDEVICE> current;
|
||||
if (!FindKeyboard(current)) return false;
|
||||
if (!current) return true;
|
||||
const RAWINPUTDEVICE removal{1, 6, RIDEV_REMOVE, nullptr};
|
||||
if (!RegisterRawInputDevices(&removal, 1, sizeof(removal))) return false;
|
||||
saved_ = current;
|
||||
// GetRegisteredRawInputDevices can omit DEVNOTIFY from its result.
|
||||
// Winit requests it for keyboard hotplug notifications, so retain it.
|
||||
saved_->dwFlags |= RIDEV_DEVNOTIFY;
|
||||
changed = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Restore() {
|
||||
if (!saved_) return true;
|
||||
std::optional<RAWINPUTDEVICE> current;
|
||||
if (!FindKeyboard(current)) return false;
|
||||
// A backend may have changed its registration or destroyed its target
|
||||
// since capture stopped. Never overwrite a newer registration.
|
||||
if (current || (saved_->hwndTarget && !IsWindow(saved_->hwndTarget))) {
|
||||
saved_.reset();
|
||||
return true;
|
||||
}
|
||||
if (!RegisterRawInputDevices(&*saved_, 1, sizeof(RAWINPUTDEVICE))) return false;
|
||||
saved_.reset();
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
static bool FindKeyboard(std::optional<RAWINPUTDEVICE>& result) {
|
||||
result.reset();
|
||||
for (int attempt = 0; attempt < 3; ++attempt) {
|
||||
UINT count = 0;
|
||||
const UINT status = GetRegisteredRawInputDevices(
|
||||
nullptr, &count, sizeof(RAWINPUTDEVICE));
|
||||
if (status == static_cast<UINT>(-1) &&
|
||||
GetLastError() != ERROR_INSUFFICIENT_BUFFER) return false;
|
||||
if (count == 0) return true;
|
||||
std::vector<RAWINPUTDEVICE> devices(count);
|
||||
const UINT read = GetRegisteredRawInputDevices(
|
||||
devices.data(), &count, sizeof(RAWINPUTDEVICE));
|
||||
if (read == static_cast<UINT>(-1)) {
|
||||
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) continue;
|
||||
return false;
|
||||
}
|
||||
for (UINT i = 0; i < read; ++i) {
|
||||
if (devices[i].usUsagePage == 1 && devices[i].usUsage == 6) {
|
||||
result = devices[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
SetLastError(ERROR_RETRY);
|
||||
return false;
|
||||
}
|
||||
|
||||
std::optional<RAWINPUTDEVICE> saved_;
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
#include "../screen_capturer/dxgi_cursor_state.h"
|
||||
#include "privacy_cursor_api.h"
|
||||
#include "privacy_cursor_process.h"
|
||||
#include "rd_log.h"
|
||||
|
||||
namespace crossdesk {
|
||||
@@ -85,15 +86,13 @@ bool PrivacyCursorGuard::Start(std::string& error) {
|
||||
startup.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
|
||||
inherited, sizeof(inherited), nullptr, nullptr) != FALSE;
|
||||
PROCESS_INFORMATION child{};
|
||||
bool used_job_fallback = false;
|
||||
if (ok) {
|
||||
std::wstring command = L"\"" + helper.wstring() + L"\"";
|
||||
for (HANDLE handle : inherited)
|
||||
command += L" " + std::to_wstring(reinterpret_cast<uintptr_t>(handle));
|
||||
ok =
|
||||
CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, TRUE,
|
||||
CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT |
|
||||
CREATE_BREAKAWAY_FROM_JOB,
|
||||
nullptr, nullptr, &startup.StartupInfo, &child) != FALSE;
|
||||
ok = CreatePrivacyCursorProcess(helper.c_str(), command, startup, child,
|
||||
used_job_fallback);
|
||||
}
|
||||
const DWORD start_error = GetLastError();
|
||||
DeleteProcThreadAttributeList(startup.lpAttributeList);
|
||||
@@ -102,6 +101,11 @@ bool PrivacyCursorGuard::Start(std::string& error) {
|
||||
return Failed("Start crossdesk_privacy_cursor_helper.exe", error,
|
||||
start_error);
|
||||
}
|
||||
if (used_job_fallback) {
|
||||
LOG_INFO("Privacy cursor: launcher denied job breakaway; helper process={} "
|
||||
"started without breakaway flag with parent-exit monitoring",
|
||||
child.dwProcessId);
|
||||
}
|
||||
CloseHandle(child.hThread);
|
||||
process_ = child.hProcess;
|
||||
stop_event_ = stop.value;
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-08
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PRIVACY_CURSOR_PROCESS_H_
|
||||
#define _PRIVACY_CURSOR_PROCESS_H_
|
||||
|
||||
#include <Windows.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// Prefer an independent lifetime, so closing the launcher's job cannot kill
|
||||
// the cursor helper before it restores the cursor. Some launchers (including
|
||||
// scheduled tasks) forbid breakaway. In that case retain the inherited parent
|
||||
// process handle/stop event and run in the job; parent-only exits still trigger
|
||||
// cleanup, although terminating the entire job also terminates the helper.
|
||||
inline bool CreatePrivacyCursorProcess(const wchar_t* executable,
|
||||
const std::wstring& command,
|
||||
STARTUPINFOEXW& startup,
|
||||
PROCESS_INFORMATION& child,
|
||||
bool& used_job_fallback) {
|
||||
used_job_fallback = false;
|
||||
const auto create = [&](DWORD flags) {
|
||||
// CreateProcessW may modify its command line, including on failure.
|
||||
auto mutable_command = command;
|
||||
return CreateProcessW(executable, mutable_command.data(), nullptr, nullptr,
|
||||
TRUE, CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT |
|
||||
flags,
|
||||
nullptr, nullptr, &startup.StartupInfo, &child) != FALSE;
|
||||
};
|
||||
if (create(CREATE_BREAKAWAY_FROM_JOB)) return true;
|
||||
const DWORD error = GetLastError();
|
||||
BOOL in_job = FALSE;
|
||||
if (error != ERROR_ACCESS_DENIED ||
|
||||
!IsProcessInJob(GetCurrentProcess(), nullptr, &in_job) || !in_job) {
|
||||
SetLastError(error);
|
||||
return false;
|
||||
}
|
||||
if (!create(0)) return false;
|
||||
used_job_fallback = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // _PRIVACY_CURSOR_PROCESS_H_
|
||||
@@ -408,6 +408,7 @@ SecureDesktopServiceStatus ReadSecureDesktopServiceStatus() {
|
||||
}
|
||||
|
||||
status.active_session_id = json.value("active_session_id", 0xFFFFFFFFu);
|
||||
status.consent_ui_visible = json.value("consent_ui_visible", false);
|
||||
status.helper_running = json.value("secure_input_helper_running", false);
|
||||
status.helper_process_id = json.value("secure_input_helper_pid", 0u);
|
||||
status.interactive_stage = json.value("interactive_stage", std::string());
|
||||
@@ -425,11 +426,7 @@ SecureDesktopServiceStatus ReadSecureDesktopServiceStatus() {
|
||||
|
||||
SecureDesktopServiceStatus QuerySecureDesktopServiceStatus() {
|
||||
auto status = ReadSecureDesktopServiceStatus();
|
||||
if (!status.service_available && IsCurrentSessionUserDesktopActive()) {
|
||||
status.desktop_state_known = true;
|
||||
status.capture_active = false;
|
||||
status.interactive_stage = "user-desktop";
|
||||
}
|
||||
if (IsCurrentSessionUserDesktopActive()) status.OnUserDesktopObserved();
|
||||
return status;
|
||||
}
|
||||
|
||||
@@ -445,10 +442,11 @@ bool QuerySecureDesktopHelperCommand(DWORD session_id,
|
||||
GetCrossDeskSecureInputHelperPipeName(session_id);
|
||||
std::string error;
|
||||
DWORD code = 0;
|
||||
// The legacy single-frame path includes a full GDI capture and a large
|
||||
// response. Give it a separate deadline from the small control messages.
|
||||
// Starting may have to join/release the old GPU producer first. Its reply
|
||||
// cannot use the short deadline intended for lightweight control messages.
|
||||
const DWORD timeout_ms =
|
||||
command.rfind(kCrossDeskSecureInputCaptureCommandPrefix, 0) == 0
|
||||
(command.rfind(kCrossDeskSecureInputCaptureCommandPrefix, 0) == 0 ||
|
||||
command.rfind(kCrossDeskSecureInputCaptureStartCommandPrefix, 0) == 0)
|
||||
? 1000
|
||||
: kSecureDesktopHelperPipeTimeoutMs;
|
||||
const bool ok = QueryNamedPipeWithDeadline(pipe_name, command, timeout_ms,
|
||||
@@ -579,8 +577,6 @@ int ScreenCapturerWin::Init(const int fps, cb_desktop_data cb) {
|
||||
0, std::memory_order_relaxed);
|
||||
const ULONGLONG elapsed_ms =
|
||||
start_tick == 0 ? 0 : GetTickCount64() - start_tick;
|
||||
post_secure_desktop_drop_logged_.store(false,
|
||||
std::memory_order_relaxed);
|
||||
LOG_INFO(
|
||||
"Windows capturer first normal frame after secure desktop: "
|
||||
"reported_stream='{}', mapped_stream='{}', size={}x{}, bytes={}, "
|
||||
@@ -804,7 +800,6 @@ void ScreenCapturerWin::ResetPostSecureDesktopState() {
|
||||
secure_desktop_capture_active_.store(false, std::memory_order_relaxed);
|
||||
post_secure_desktop_waiting_for_frame_.store(false,
|
||||
std::memory_order_relaxed);
|
||||
post_secure_desktop_drop_logged_.store(false, std::memory_order_relaxed);
|
||||
post_secure_desktop_started_tick_.store(0, std::memory_order_relaxed);
|
||||
SharedSecureDesktopCursorState().SetActive(false);
|
||||
}
|
||||
@@ -932,6 +927,9 @@ int ScreenCapturerWin::Stop() {
|
||||
// Drain management operations before stopping/replacing their backend.
|
||||
virtual_display_.RequestCancel();
|
||||
StopSecureCaptureThread();
|
||||
// A recovery already in progress can publish "running" while Stop waits.
|
||||
// Publish the final stopped state after that management thread has exited.
|
||||
NotifyPrivacyCapture(false);
|
||||
JoinVirtualDisplayThread();
|
||||
ResetPostSecureDesktopState();
|
||||
if (impl_) {
|
||||
@@ -1234,10 +1232,12 @@ bool ScreenCapturerWin::RestartCaptureBackendAfterSecureDesktop() {
|
||||
|
||||
LOG_INFO("Windows capturer: restarting capture backend after secure desktop");
|
||||
impl_->Stop();
|
||||
last_capture_progress_tick_.store(GetTickCount64(), std::memory_order_relaxed);
|
||||
int ret = impl_->Start(show_cursor);
|
||||
if (ret == 0) {
|
||||
applied_show_cursor_ = show_cursor;
|
||||
RestoreMonitor(current_monitor);
|
||||
NotifyPrivacyCapture(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1253,11 +1253,13 @@ bool ScreenCapturerWin::RestartCaptureBackendAfterSecureDesktop() {
|
||||
if (ret == 0) {
|
||||
applied_show_cursor_ = show_cursor;
|
||||
RestoreMonitor(current_monitor);
|
||||
NotifyPrivacyCapture(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (StartPreferredBackend(headless_compat_.load(std::memory_order_relaxed),
|
||||
current_monitor, usbmmidd)) {
|
||||
NotifyPrivacyCapture(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1397,7 +1399,7 @@ void ScreenCapturerWin::StopSecureDesktopSharedCapture(DWORD session_id) {
|
||||
target_session_id = secure_shared_session_id_;
|
||||
}
|
||||
|
||||
if (secure_shared_capture_started_ &&
|
||||
if ((secure_shared_capture_started_ || secure_shared_start_pending_) &&
|
||||
target_session_id != 0xFFFFFFFF) {
|
||||
std::vector<uint8_t> response;
|
||||
std::string error_message;
|
||||
@@ -1408,15 +1410,9 @@ void ScreenCapturerWin::StopSecureDesktopSharedCapture(DWORD session_id) {
|
||||
|
||||
CloseSecureDesktopSharedFrame();
|
||||
secure_shared_capture_started_ = false;
|
||||
secure_shared_start_pending_ = false;
|
||||
secure_shared_session_id_ = 0xFFFFFFFF;
|
||||
secure_shared_left_ = 0;
|
||||
secure_shared_top_ = 0;
|
||||
secure_shared_width_ = 0;
|
||||
secure_shared_height_ = 0;
|
||||
secure_shared_fps_ = 0;
|
||||
secure_shared_show_cursor_ = true;
|
||||
secure_shared_stage_.clear();
|
||||
secure_shared_desktop_.clear();
|
||||
secure_shared_configuration_ = {};
|
||||
}
|
||||
|
||||
bool ScreenCapturerWin::OpenSecureDesktopSharedFrame(DWORD session_id,
|
||||
@@ -1563,27 +1559,37 @@ bool ScreenCapturerWin::StartSecureDesktopSharedCapture(
|
||||
return false;
|
||||
}
|
||||
|
||||
const SharedCaptureConfiguration configuration{left, top, width, height,
|
||||
show_cursor, fps};
|
||||
if (secure_shared_capture_started_ &&
|
||||
secure_shared_session_id_ == session_id &&
|
||||
secure_shared_left_ == left && secure_shared_top_ == top &&
|
||||
secure_shared_width_ == width && secure_shared_height_ == height &&
|
||||
secure_shared_stage_ == stage && secure_shared_desktop_ == desktop &&
|
||||
secure_shared_show_cursor_ == show_cursor && secure_shared_fps_ == fps &&
|
||||
secure_shared_configuration_ == configuration &&
|
||||
OpenSecureDesktopSharedFrame(session_id, mapping_size, error_out)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
StopSecureDesktopSharedCapture(secure_shared_session_id_);
|
||||
if (secure_shared_session_id_ != session_id) {
|
||||
StopSecureDesktopSharedCapture(secure_shared_session_id_);
|
||||
} else {
|
||||
// capture-start performs the replacement atomically in the helper. Avoid
|
||||
// a separate stop round trip and keep retries idempotent after a timeout.
|
||||
CloseSecureDesktopSharedFrame();
|
||||
}
|
||||
secure_shared_capture_started_ = false;
|
||||
secure_shared_start_pending_ = true;
|
||||
secure_shared_session_id_ = session_id;
|
||||
|
||||
const std::string command =
|
||||
BuildSecureCaptureStartCommand(left, top, width, height, show_cursor, fps,
|
||||
stage, desktop);
|
||||
const std::string command = BuildSecureCaptureStartCommand(
|
||||
left, top, width, height, show_cursor, fps, stage, desktop);
|
||||
std::vector<uint8_t> response;
|
||||
if (!QuerySecureDesktopHelperCommand(session_id, command, &response,
|
||||
error_out)) {
|
||||
secure_shared_start_pending_ =
|
||||
error_out && IsPendingSecureCaptureStart(*error_out);
|
||||
return false;
|
||||
}
|
||||
|
||||
secure_shared_start_pending_ = false;
|
||||
Json json = Json::parse(response.begin(), response.end(), nullptr, false);
|
||||
if (json.is_discarded() || !json.value("ok", false)) {
|
||||
if (error_out != nullptr) {
|
||||
@@ -1594,14 +1600,7 @@ bool ScreenCapturerWin::StartSecureDesktopSharedCapture(
|
||||
|
||||
secure_shared_capture_started_ = true;
|
||||
secure_shared_session_id_ = session_id;
|
||||
secure_shared_left_ = left;
|
||||
secure_shared_top_ = top;
|
||||
secure_shared_width_ = width;
|
||||
secure_shared_height_ = height;
|
||||
secure_shared_show_cursor_ = show_cursor;
|
||||
secure_shared_fps_ = fps;
|
||||
secure_shared_stage_ = stage;
|
||||
secure_shared_desktop_ = desktop;
|
||||
secure_shared_configuration_ = configuration;
|
||||
|
||||
if (!OpenSecureDesktopSharedFrame(session_id, mapping_size, error_out)) {
|
||||
StopSecureDesktopSharedCapture(session_id);
|
||||
@@ -1621,6 +1620,8 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
ULONGLONG last_error_tick = 0;
|
||||
ULONGLONG capture_stage_started_tick = 0;
|
||||
bool post_secure_restart_pending = false;
|
||||
bool desktop_was_unavailable = false;
|
||||
bool normal_backend_suspended = false;
|
||||
ULONGLONG post_secure_restart_deadline_tick = 0;
|
||||
ULONGLONG last_post_secure_restart_tick = 0;
|
||||
ULONGLONG next_cursor_update_tick = 0;
|
||||
@@ -1663,11 +1664,12 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
};
|
||||
|
||||
while (running_.load(std::memory_order_relaxed)) {
|
||||
// Privacy covers belong to the ordinary desktop. Drop privacy on a
|
||||
// secure desktop, while continuing the normal helper capture path.
|
||||
if (privacy_ && privacy_->Engaged()) {
|
||||
if (!IsWindowsPrivacyDesktopAvailable())
|
||||
privacy_->Fail("Secure desktop or lock screen; privacy screen will turn off. Privacy cannot cover Windows security UI.");
|
||||
// Remember automatic privacy even if the connection started while locked
|
||||
// and its first enable attempt has already failed.
|
||||
const bool desktop_available = IsWindowsPrivacyDesktopAvailable();
|
||||
if (!desktop_available) {
|
||||
desktop_was_unavailable = true;
|
||||
if (privacy_) privacy_->SuspendForDesktop();
|
||||
}
|
||||
if (paused_.load(std::memory_order_relaxed)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
@@ -1677,9 +1679,14 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
const ULONGLONG now = GetTickCount64();
|
||||
const auto frame_started = std::chrono::steady_clock::now();
|
||||
report_stats(false);
|
||||
if (auto sample = status_poller.Take()) {
|
||||
const auto previous = std::exchange(status, std::move(sample->status));
|
||||
max_status_ms = (std::max)(max_status_ms, sample->query_ms);
|
||||
auto sample = status_poller.Take();
|
||||
if (sample || (desktop_available && status.capture_active)) {
|
||||
auto latest = sample ? std::move(sample->status) : status;
|
||||
// Recheck when applying a queued reply, not only when querying. A local
|
||||
// unlock must never be undone by a delayed secure-desktop snapshot.
|
||||
if (desktop_available) latest.OnUserDesktopObserved();
|
||||
const auto previous = std::exchange(status, std::move(latest));
|
||||
if (sample) max_status_ms = (std::max)(max_status_ms, sample->query_ms);
|
||||
if (status.service_available != previous.service_available ||
|
||||
status.error != previous.error) {
|
||||
if (status.service_available) {
|
||||
@@ -1710,8 +1717,12 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
report_stats(true);
|
||||
// A restarted helper can leave our mapping/event handles alive, but
|
||||
// their old producer is gone. Explicitly establish a fresh stream.
|
||||
StopSecureDesktopSharedCapture(secure_shared_session_id_);
|
||||
frame_schedule.Reset(now);
|
||||
if (status.capture_active != previous.capture_active ||
|
||||
status.active_session_id != previous.active_session_id ||
|
||||
status.helper_process_id != previous.helper_process_id) {
|
||||
StopSecureDesktopSharedCapture(secure_shared_session_id_);
|
||||
frame_schedule.Reset(now);
|
||||
}
|
||||
const bool secure_capture_started =
|
||||
!previous.capture_active && status.capture_active;
|
||||
const bool secure_capture_ended =
|
||||
@@ -1726,8 +1737,6 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
post_secure_restart_pending = false;
|
||||
post_secure_desktop_waiting_for_frame_.store(
|
||||
false, std::memory_order_relaxed);
|
||||
post_secure_desktop_drop_logged_.store(false,
|
||||
std::memory_order_relaxed);
|
||||
post_secure_desktop_started_tick_.store(0, std::memory_order_relaxed);
|
||||
} else if (secure_capture_ended) {
|
||||
post_secure_restart_pending = true;
|
||||
@@ -1736,34 +1745,69 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
last_post_secure_restart_tick = 0;
|
||||
post_secure_desktop_waiting_for_frame_.store(
|
||||
true, std::memory_order_relaxed);
|
||||
post_secure_desktop_drop_logged_.store(false,
|
||||
std::memory_order_relaxed);
|
||||
post_secure_desktop_started_tick_.store(now,
|
||||
std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A locked session can still report Default, and helper status can be
|
||||
// unavailable. Observe local unlocks independently so recovery publishes
|
||||
// a fresh capture-running notification in either case.
|
||||
if (desktop_available && desktop_was_unavailable) {
|
||||
desktop_was_unavailable = false;
|
||||
post_secure_restart_pending = true;
|
||||
post_secure_restart_deadline_tick =
|
||||
now + kPostSecureDesktopRestartTimeoutMs;
|
||||
last_post_secure_restart_tick = 0;
|
||||
}
|
||||
|
||||
if ((!desktop_available || status.capture_active) &&
|
||||
!normal_backend_suspended) {
|
||||
// LockApp may return to Default while the session remains locked. Merely
|
||||
// dropping callbacks leaves a second DXGI/GDI/WGC pipeline capturing and
|
||||
// converting the same desktop alongside the helper. Stop it once, also
|
||||
// when local lock detection precedes the service/helper startup.
|
||||
std::lock_guard<std::mutex> lock(impl_mutex_);
|
||||
if (impl_) {
|
||||
impl_->Stop();
|
||||
normal_backend_suspended = true;
|
||||
LOG_INFO("Windows capturer: normal backend suspended for secure desktop");
|
||||
}
|
||||
}
|
||||
|
||||
if (!status.capture_active || status.active_session_id == 0xFFFFFFFF) {
|
||||
StopSecureDesktopSharedCapture(secure_shared_session_id_);
|
||||
CheckDisplayPresence(now);
|
||||
MaybeAdoptVirtualDisplay();
|
||||
CheckCaptureProgress(now);
|
||||
if (post_secure_restart_pending) {
|
||||
// Normal capture was intentionally unavailable on the secure desktop.
|
||||
// Do not schedule a second topology/stall rebuild during its recovery.
|
||||
if (!post_secure_restart_pending && desktop_available &&
|
||||
!normal_backend_suspended) {
|
||||
CheckDisplayPresence(now);
|
||||
MaybeAdoptVirtualDisplay();
|
||||
CheckCaptureProgress(now);
|
||||
}
|
||||
if (post_secure_restart_pending && desktop_available) {
|
||||
if (now >= post_secure_restart_deadline_tick) {
|
||||
LOG_WARN(
|
||||
"Windows capturer: capture backend restart after secure desktop "
|
||||
"timed out");
|
||||
post_secure_restart_pending = false;
|
||||
"still unavailable; retrying");
|
||||
// The normal backend is stopped. Retain recovery ownership instead
|
||||
// of falling back to a stall probe on a thread that is not running.
|
||||
post_secure_restart_deadline_tick =
|
||||
now + kPostSecureDesktopRestartTimeoutMs;
|
||||
} else if (last_post_secure_restart_tick == 0 ||
|
||||
now - last_post_secure_restart_tick >=
|
||||
kPostSecureDesktopRestartRetryMs) {
|
||||
last_post_secure_restart_tick = now;
|
||||
post_secure_restart_pending =
|
||||
!RestartCaptureBackendAfterSecureDesktop();
|
||||
if (!post_secure_restart_pending) normal_backend_suspended = false;
|
||||
if (!post_secure_restart_pending && privacy_)
|
||||
privacy_->ResumeAfterDesktopRecovery();
|
||||
}
|
||||
}
|
||||
if (!post_secure_restart_pending && now >= next_cursor_update_tick) {
|
||||
if (!post_secure_restart_pending && !normal_backend_suspended &&
|
||||
now >= next_cursor_update_tick) {
|
||||
next_cursor_update_tick = now + 500;
|
||||
ApplyCursorCaptureSetting();
|
||||
}
|
||||
@@ -1814,7 +1858,7 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
status.interactive_stage, status.interactive_desktop, show_cursor,
|
||||
shared_fps, &error_message);
|
||||
if (!shared_ready) {
|
||||
report_shared_error("start", error_message);
|
||||
if (!secure_shared_start_pending_) report_shared_error("start", error_message);
|
||||
frame_schedule.OnStartFailure(GetTickCount64());
|
||||
} else if (!was_started) {
|
||||
frame_schedule.Reset(GetTickCount64());
|
||||
@@ -1830,8 +1874,8 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
frame_schedule.OnSharedFrame(GetTickCount64());
|
||||
}
|
||||
|
||||
const bool frame_pending = shared_ready && !frame_delivered &&
|
||||
IsPendingSecureDesktopFrame(error_message);
|
||||
const bool frame_pending = secure_shared_start_pending_ ||
|
||||
(shared_ready && !frame_delivered && IsPendingSecureDesktopFrame(error_message));
|
||||
if (frame_pending) ++shared_waits;
|
||||
if (shared_ready && !frame_delivered && !frame_pending) {
|
||||
report_shared_error("read", error_message);
|
||||
@@ -1884,6 +1928,10 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
}
|
||||
}
|
||||
|
||||
// The shared producer owns frame pacing. Waiting again here can miss the
|
||||
// next publication (and overwrite a pending frame) due to timer rounding.
|
||||
if (shared_ready && (frame_delivered || frame_pending)) continue;
|
||||
|
||||
const auto elapsed_ms =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now() - frame_started)
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
#include "privacy_controller.h"
|
||||
// Relative: platform include directories stay private to the capture target.
|
||||
#include "../virtual_display/virtual_display_provisioner.h"
|
||||
#include "../service/shared_capture_configuration.h"
|
||||
#include "headless_recovery.h"
|
||||
|
||||
namespace crossdesk {
|
||||
@@ -117,7 +118,6 @@ class ScreenCapturerWin : public ScreenCapturer {
|
||||
std::atomic<int> monitor_index_{0};
|
||||
std::atomic<bool> secure_desktop_capture_active_{false};
|
||||
std::atomic<bool> post_secure_desktop_waiting_for_frame_{false};
|
||||
std::atomic<bool> post_secure_desktop_drop_logged_{false};
|
||||
std::atomic<ULONGLONG> post_secure_desktop_started_tick_{0};
|
||||
std::thread secure_capture_thread_;
|
||||
HANDLE secure_frame_mapping_ = nullptr;
|
||||
@@ -125,15 +125,9 @@ class ScreenCapturerWin : public ScreenCapturer {
|
||||
uint8_t* secure_frame_view_ = nullptr;
|
||||
size_t secure_frame_view_size_ = 0;
|
||||
DWORD secure_shared_session_id_ = 0xFFFFFFFF;
|
||||
int secure_shared_left_ = 0;
|
||||
int secure_shared_top_ = 0;
|
||||
int secure_shared_width_ = 0;
|
||||
int secure_shared_height_ = 0;
|
||||
int secure_shared_fps_ = 0;
|
||||
bool secure_shared_show_cursor_ = true;
|
||||
std::string secure_shared_stage_;
|
||||
std::string secure_shared_desktop_;
|
||||
SharedCaptureConfiguration secure_shared_configuration_;
|
||||
bool secure_shared_capture_started_ = false;
|
||||
bool secure_shared_start_pending_ = false;
|
||||
std::shared_ptr<CapturedNv12FramePool> native_frame_pool_;
|
||||
|
||||
void BuildCanonicalFromImpl();
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-08
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _SECURE_DESKTOP_DXGI_CAPTURE_H_
|
||||
#define _SECURE_DESKTOP_DXGI_CAPTURE_H_
|
||||
|
||||
#include <Windows.h>
|
||||
#include <d3d11.h>
|
||||
#include <dxgi1_2.h>
|
||||
#include <libyuv.h>
|
||||
#include <wrl/client.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "secure_desktop_dxgi_cursor_state.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// Owned by the SYSTEM helper's capture thread, after binding its input desktop.
|
||||
// Destroy before switching desktops. The uncomposited pixels stay valid on a
|
||||
// timeout, so a static lock screen and a moving separate cursor keep their
|
||||
// requested cadence without another GPU readback or a GDI screenshot.
|
||||
class SecureDesktopDxgiCapture {
|
||||
public:
|
||||
HRESULT Initialize(int left, int top, int width, int height) {
|
||||
if (width <= 0 || height <= 0) return E_INVALIDARG;
|
||||
Microsoft::WRL::ComPtr<IDXGIFactory1> factory;
|
||||
HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(factory.GetAddressOf()));
|
||||
if (FAILED(hr)) return hr;
|
||||
Microsoft::WRL::ComPtr<IDXGIAdapter1> adapter;
|
||||
for (UINT a = 0; SUCCEEDED(factory->EnumAdapters1(
|
||||
a, adapter.ReleaseAndGetAddressOf())); ++a) {
|
||||
Microsoft::WRL::ComPtr<IDXGIOutput> output;
|
||||
for (UINT o = 0; SUCCEEDED(adapter->EnumOutputs(
|
||||
o, output.ReleaseAndGetAddressOf())); ++o) {
|
||||
DXGI_OUTPUT_DESC desc{};
|
||||
if (FAILED(output->GetDesc(&desc)) || !desc.AttachedToDesktop) continue;
|
||||
const RECT& bounds = desc.DesktopCoordinates;
|
||||
if (left < bounds.left || top < bounds.top ||
|
||||
static_cast<int64_t>(left) + width > bounds.right ||
|
||||
static_cast<int64_t>(top) + height > bounds.bottom) continue;
|
||||
|
||||
hr = D3D11CreateDevice(
|
||||
adapter.Get(), D3D_DRIVER_TYPE_UNKNOWN, nullptr,
|
||||
D3D11_CREATE_DEVICE_BGRA_SUPPORT, nullptr, 0, D3D11_SDK_VERSION,
|
||||
device_.GetAddressOf(), nullptr, context_.GetAddressOf());
|
||||
if (FAILED(hr)) return hr;
|
||||
Microsoft::WRL::ComPtr<IDXGIOutput1> output1;
|
||||
hr = output.As(&output1);
|
||||
if (FAILED(hr)) return hr;
|
||||
hr = output1->DuplicateOutput(device_.Get(), duplication_.GetAddressOf());
|
||||
if (FAILED(hr)) return hr;
|
||||
|
||||
output_desc_ = desc;
|
||||
offset_x_ = left - bounds.left;
|
||||
offset_y_ = top - bounds.top;
|
||||
DXGI_OUTDUPL_DESC duplication_desc{};
|
||||
duplication_->GetDesc(&duplication_desc);
|
||||
switch (duplication_desc.Rotation) {
|
||||
case DXGI_MODE_ROTATION_ROTATE90: rotation_ = libyuv::kRotate90; break;
|
||||
case DXGI_MODE_ROTATION_ROTATE180: rotation_ = libyuv::kRotate180; break;
|
||||
case DXGI_MODE_ROTATION_ROTATE270: rotation_ = libyuv::kRotate270; break;
|
||||
default: rotation_ = libyuv::kRotate0; break;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
}
|
||||
// Includes headless desktops and regions spanning more than one output.
|
||||
return DXGI_ERROR_NOT_FOUND;
|
||||
}
|
||||
|
||||
// S_FALSE means no first frame yet; the caller can use GDI until one arrives.
|
||||
// On any failure the caller must discard this instance, including its cache.
|
||||
HRESULT Capture() {
|
||||
updated_ = false;
|
||||
if (!duplication_) return E_UNEXPECTED;
|
||||
Microsoft::WRL::ComPtr<IDXGIResource> resource;
|
||||
DXGI_OUTDUPL_FRAME_INFO info{};
|
||||
const HRESULT hr = duplication_->AcquireNextFrame(0, &info, &resource);
|
||||
if (hr == DXGI_ERROR_WAIT_TIMEOUT) return pixels_.empty() ? S_FALSE : S_OK;
|
||||
if (FAILED(hr)) return hr;
|
||||
struct ReleaseFrame {
|
||||
IDXGIOutputDuplication* duplication;
|
||||
~ReleaseFrame() { duplication->ReleaseFrame(); }
|
||||
} release{duplication_.Get()};
|
||||
cursor_state_.Update(info.LastMouseUpdateTime.QuadPart,
|
||||
info.PointerPosition.Visible != FALSE);
|
||||
// Pointer-only updates leave the desktop image unchanged.
|
||||
if (info.LastPresentTime.QuadPart == 0 && !pixels_.empty()) return S_OK;
|
||||
|
||||
Microsoft::WRL::ComPtr<ID3D11Texture2D> texture;
|
||||
HRESULT result = resource.As(&texture);
|
||||
if (FAILED(result)) return result;
|
||||
D3D11_TEXTURE2D_DESC desc{};
|
||||
texture->GetDesc(&desc);
|
||||
const bool swap_axes = rotation_ == libyuv::kRotate90 ||
|
||||
rotation_ == libyuv::kRotate270;
|
||||
const UINT logical_width = swap_axes ? desc.Height : desc.Width;
|
||||
const UINT logical_height = swap_axes ? desc.Width : desc.Height;
|
||||
const RECT& bounds = output_desc_.DesktopCoordinates;
|
||||
if (desc.Format != DXGI_FORMAT_B8G8R8A8_UNORM ||
|
||||
logical_width != static_cast<UINT>(bounds.right - bounds.left) ||
|
||||
logical_height != static_cast<UINT>(bounds.bottom - bounds.top)) {
|
||||
return DXGI_ERROR_ACCESS_LOST;
|
||||
}
|
||||
if (!staging_) {
|
||||
desc.Usage = D3D11_USAGE_STAGING;
|
||||
desc.BindFlags = 0;
|
||||
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
|
||||
desc.MiscFlags = 0;
|
||||
result = device_->CreateTexture2D(&desc, nullptr, staging_.GetAddressOf());
|
||||
if (FAILED(result)) return result;
|
||||
}
|
||||
context_->CopyResource(staging_.Get(), texture.Get());
|
||||
D3D11_MAPPED_SUBRESOURCE mapped{};
|
||||
result = context_->Map(staging_.Get(), 0, D3D11_MAP_READ, 0, &mapped);
|
||||
if (FAILED(result)) return result;
|
||||
stride_ = static_cast<int>(logical_width) * 4;
|
||||
pixels_.resize(static_cast<size_t>(stride_) * logical_height);
|
||||
const int converted = libyuv::ARGBRotate(
|
||||
static_cast<const uint8_t*>(mapped.pData), static_cast<int>(mapped.RowPitch),
|
||||
pixels_.data(), stride_, static_cast<int>(desc.Width),
|
||||
static_cast<int>(desc.Height), rotation_);
|
||||
context_->Unmap(staging_.Get(), 0);
|
||||
updated_ = converted == 0;
|
||||
return converted == 0 ? S_OK : E_FAIL;
|
||||
}
|
||||
|
||||
const uint8_t* pixels() const {
|
||||
return pixels_.data() + static_cast<size_t>(offset_y_) * stride_ + offset_x_ * 4;
|
||||
}
|
||||
int stride() const { return stride_; }
|
||||
bool updated() const { return updated_; }
|
||||
bool CursorEmbedded(const CURSORINFO& cursor) const {
|
||||
return cursor_state_.IsEmbedded(
|
||||
(cursor.flags & CURSOR_SHOWING) != 0,
|
||||
MonitorFromPoint(cursor.ptScreenPos, MONITOR_DEFAULTTONULL) ==
|
||||
output_desc_.Monitor);
|
||||
}
|
||||
|
||||
private:
|
||||
Microsoft::WRL::ComPtr<ID3D11Device> device_;
|
||||
Microsoft::WRL::ComPtr<ID3D11DeviceContext> context_;
|
||||
Microsoft::WRL::ComPtr<IDXGIOutputDuplication> duplication_;
|
||||
Microsoft::WRL::ComPtr<ID3D11Texture2D> staging_;
|
||||
DXGI_OUTPUT_DESC output_desc_{};
|
||||
libyuv::RotationMode rotation_ = libyuv::kRotate0;
|
||||
int offset_x_ = 0, offset_y_ = 0, stride_ = 0;
|
||||
SecureDesktopDxgiCursorState cursor_state_;
|
||||
bool updated_ = false;
|
||||
std::vector<uint8_t> pixels_;
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // _SECURE_DESKTOP_DXGI_CAPTURE_H_
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-09
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _SECURE_DESKTOP_DXGI_CURSOR_STATE_H_
|
||||
#define _SECURE_DESKTOP_DXGI_CURSOR_STATE_H_
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// Owned by one secure-desktop duplication instance. Desktop-only frames and
|
||||
// timeouts retain the pointer mode; PointerPosition is undefined without a
|
||||
// mouse update.
|
||||
class SecureDesktopDxgiCursorState {
|
||||
public:
|
||||
void Update(int64_t last_mouse_update_time, bool separate_pointer_visible) {
|
||||
if (last_mouse_update_time != 0) {
|
||||
embedded_ = !separate_pointer_visible;
|
||||
}
|
||||
}
|
||||
|
||||
bool IsEmbedded(bool system_cursor_visible, bool cursor_on_output) const {
|
||||
return embedded_ && system_cursor_visible && cursor_on_output;
|
||||
}
|
||||
|
||||
private:
|
||||
// Secure desktops can composite the cursor without sending pointer-plane
|
||||
// updates, even on physical displays. Until DXGI explicitly reports a
|
||||
// separate pointer, do not add another cursor to the frame or controller.
|
||||
bool embedded_ = true;
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // _SECURE_DESKTOP_DXGI_CURSOR_STATE_H_
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-08
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _SECURE_DESKTOP_FRAME_PACER_H_
|
||||
#define _SECURE_DESKTOP_FRAME_PACER_H_
|
||||
|
||||
#include <Windows.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// Sleep's system-tick rounding can turn a 33ms frame into a 47ms frame.
|
||||
// Request precise waits only on this capture thread, without changing the
|
||||
// machine's timer resolution. Older Windows versions use a regular timer.
|
||||
class SecureDesktopFramePacer {
|
||||
public:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
explicit SecureDesktopFramePacer(int fps)
|
||||
: interval_(std::chrono::nanoseconds(
|
||||
1000000000LL / (std::clamp)(fps > 0 ? fps : 30, 1, 1000))) {
|
||||
constexpr DWORD kHighResolution = 0x00000002;
|
||||
timer_ = CreateWaitableTimerExW(nullptr, nullptr, kHighResolution,
|
||||
TIMER_MODIFY_STATE | SYNCHRONIZE);
|
||||
if (!timer_) timer_ = CreateWaitableTimerW(nullptr, FALSE, nullptr);
|
||||
}
|
||||
~SecureDesktopFramePacer() {
|
||||
if (timer_) CloseHandle(timer_);
|
||||
}
|
||||
SecureDesktopFramePacer(const SecureDesktopFramePacer&) = delete;
|
||||
SecureDesktopFramePacer& operator=(const SecureDesktopFramePacer&) = delete;
|
||||
|
||||
void Wait(Clock::time_point frame_started) {
|
||||
const auto now = Clock::now();
|
||||
// Keep fractional frame periods and compensate for small scheduler delays.
|
||||
// After a slow frame, resume now instead of issuing a burst of old frames.
|
||||
if (deadline_ == Clock::time_point{}) deadline_ = frame_started;
|
||||
deadline_ += interval_;
|
||||
if (deadline_ <= now) {
|
||||
deadline_ = now;
|
||||
return;
|
||||
}
|
||||
LARGE_INTEGER due{};
|
||||
const auto ticks = std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
deadline_ - now).count() / 100;
|
||||
due.QuadPart = -(ticks > 0 ? ticks : 1);
|
||||
if (timer_ && SetWaitableTimer(timer_, &due, 0, nullptr, nullptr, FALSE) &&
|
||||
WaitForSingleObject(timer_, INFINITE) == WAIT_OBJECT_0) return;
|
||||
std::this_thread::sleep_until(deadline_);
|
||||
}
|
||||
|
||||
private:
|
||||
HANDLE timer_ = nullptr;
|
||||
Clock::duration interval_;
|
||||
Clock::time_point deadline_{};
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // _SECURE_DESKTOP_FRAME_PACER_H_
|
||||
@@ -12,6 +12,12 @@
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
inline bool IsPendingSecureCaptureStart(const std::string& error) {
|
||||
// Once a command was written, a lost response does not mean startup failed.
|
||||
return error.rfind("pipe_read_failed:", 0) == 0 ||
|
||||
error.rfind("pipe_write_failed:", 0) == 0;
|
||||
}
|
||||
|
||||
inline bool IsPendingSecureDesktopFrame(const std::string& error) {
|
||||
return error == "frame_wait_timeout" ||
|
||||
error == "shared_frame_write_in_progress" ||
|
||||
@@ -47,4 +53,4 @@ class SecureDesktopFrameSchedule {
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-08
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _SECURE_DESKTOP_NV12_CACHE_H_
|
||||
#define _SECURE_DESKTOP_NV12_CACHE_H_
|
||||
|
||||
#include <libyuv.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// One cache per capture desktop/resource lifetime. DXGI can report a pointer
|
||||
// update or timeout without changing any pixels. Keep publishing those frames
|
||||
// (and fresh cursor metadata) without converting the entire desktop again.
|
||||
class SecureDesktopNv12Cache {
|
||||
public:
|
||||
bool Convert(const uint8_t* pixels, int stride, int width, int height,
|
||||
bool pixels_changed) {
|
||||
updated_ = false;
|
||||
if (!pixels || width <= 0 || height <= 0 || (width & 1) || (height & 1) ||
|
||||
stride < static_cast<int64_t>(width) * 4) {
|
||||
valid_ = false;
|
||||
return false;
|
||||
}
|
||||
if (valid_ && !pixels_changed && width == width_ && height == height_)
|
||||
return true;
|
||||
|
||||
valid_ = false;
|
||||
const size_t luma_size = static_cast<size_t>(width) * height;
|
||||
pixels_.resize(luma_size + luma_size / 2);
|
||||
if (libyuv::ARGBToNV12(pixels, stride, pixels_.data(), width,
|
||||
pixels_.data() + luma_size, width, width,
|
||||
height) != 0)
|
||||
return false;
|
||||
width_ = width;
|
||||
height_ = height;
|
||||
valid_ = updated_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool updated() const { return updated_; }
|
||||
const std::vector<uint8_t>& pixels() const { return pixels_; }
|
||||
|
||||
private:
|
||||
bool valid_ = false;
|
||||
bool updated_ = false;
|
||||
int width_ = 0, height_ = 0;
|
||||
std::vector<uint8_t> pixels_;
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // _SECURE_DESKTOP_NV12_CACHE_H_
|
||||
@@ -23,6 +23,7 @@ struct SecureDesktopServiceStatus {
|
||||
bool service_available = false;
|
||||
bool desktop_state_known = false;
|
||||
bool capture_active = false;
|
||||
bool consent_ui_visible = false;
|
||||
bool helper_running = false;
|
||||
uint32_t helper_process_id = 0;
|
||||
uint32_t active_session_id = 0xFFFFFFFF;
|
||||
@@ -31,6 +32,16 @@ struct SecureDesktopServiceStatus {
|
||||
std::string interactive_desktop;
|
||||
std::string error;
|
||||
|
||||
void OnUserDesktopObserved() {
|
||||
if (consent_ui_visible) return;
|
||||
desktop_state_known = true;
|
||||
capture_active = false;
|
||||
helper_running = false;
|
||||
helper_process_id = 0;
|
||||
interactive_stage = "user-desktop";
|
||||
interactive_desktop.clear();
|
||||
}
|
||||
|
||||
void UpdateFrom(SecureDesktopServiceStatus latest) {
|
||||
if (latest.service_available || latest.desktop_state_known) {
|
||||
*this = std::move(latest);
|
||||
@@ -108,4 +119,4 @@ class SecureDesktopStatusPoller {
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-10-08
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _DESKTOP_TRANSITION_POLICY_H_
|
||||
#define _DESKTOP_TRANSITION_POLICY_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
inline bool PreferUserDesktopInput(bool user_desktop_active,
|
||||
bool consent_ui_visible) {
|
||||
// Windows can display an elevated UAC dialog on Default when secure-desktop
|
||||
// prompting is disabled. Preserve its authorized SYSTEM input path.
|
||||
return user_desktop_active && !consent_ui_visible;
|
||||
}
|
||||
|
||||
inline bool PreferUserDesktopInput(bool user_desktop_active,
|
||||
bool consent_ui_visible,
|
||||
bool service_available,
|
||||
bool process_elevated) {
|
||||
// An elevated application still lives on Default. SendInput only reports
|
||||
// insertion into the input stream, not delivery to that application's UI.
|
||||
// Use the authorized service proactively for an unelevated host, including
|
||||
// clicks on an elevated window that has not become the foreground window.
|
||||
return PreferUserDesktopInput(user_desktop_active, consent_ui_visible) &&
|
||||
(process_elevated || !service_available);
|
||||
}
|
||||
|
||||
inline bool IsDesktopInputSetupPending(const std::string& error) {
|
||||
// These failures explicitly precede injection; timeouts remain ambiguous.
|
||||
return error == "secure_input_helper_not_ready" ||
|
||||
error == "secure_input_not_active";
|
||||
}
|
||||
|
||||
inline bool IsCurrentDesktopSample(uint64_t sample_started, uint64_t event_tick,
|
||||
bool lock_known, bool session_locked,
|
||||
bool sample_locked) {
|
||||
// A reply received after a notification can still contain a pre-event sample.
|
||||
return (event_tick == 0 || sample_started > event_tick) &&
|
||||
(!lock_known || session_locked == sample_locked);
|
||||
}
|
||||
|
||||
struct DesktopInputResult {
|
||||
bool delivered = false;
|
||||
// True only when the path explicitly refused the input before injection.
|
||||
// A pipe timeout may have happened after a click/key was applied: never
|
||||
// replay it.
|
||||
bool not_injected = false;
|
||||
// The ordinary desktop injector rejected its single input event (for
|
||||
// example UIPI). The authorized service can retry even on the same desktop.
|
||||
bool retry_with_service = false;
|
||||
};
|
||||
|
||||
template <typename ProbeUserDesktop, typename SendUser, typename SendSecure>
|
||||
bool DispatchDesktopInput(ProbeUserDesktop probe_user, SendUser send_user,
|
||||
SendSecure send_secure) {
|
||||
const bool user = probe_user();
|
||||
const auto result = user ? send_user() : send_secure();
|
||||
if (result.delivered) return true;
|
||||
if (!result.not_injected) return false;
|
||||
if (user && result.retry_with_service) {
|
||||
// Do not replay a failed/ambiguous service request through another path.
|
||||
return send_secure().delivered;
|
||||
}
|
||||
const bool current_user = probe_user();
|
||||
if (current_user == user) return false;
|
||||
// Handle a switch between the probe and injection exactly once. Ordering is
|
||||
// synchronous, so button/key releases cannot overtake their corresponding
|
||||
// downs.
|
||||
return (current_user ? send_user() : send_secure()).delivered;
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
#endif // _DESKTOP_TRANSITION_POLICY_H_
|
||||
@@ -14,6 +14,11 @@
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
inline bool IsDesktopTransitionInputError(DWORD error) {
|
||||
return error == ERROR_ACCESS_DENIED ||
|
||||
error == ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION;
|
||||
}
|
||||
|
||||
inline std::wstring GetDesktopNameW(HDESK desktop) {
|
||||
DWORD bytes_needed = 0;
|
||||
if (desktop == nullptr) {
|
||||
@@ -149,4 +154,4 @@ class ScopedInteractiveDesktop {
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -10,6 +10,7 @@
|
||||
#include <Windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
@@ -35,9 +36,14 @@ class CrossDeskServiceHost {
|
||||
void ShutdownRuntime();
|
||||
void RequestStop();
|
||||
void ClientProcessMonitorLoop();
|
||||
bool LaunchUnattendedHost(DWORD session_id);
|
||||
void StopUnattendedHost();
|
||||
void ReportServiceStatus(DWORD current_state, DWORD win32_exit_code,
|
||||
DWORD wait_hint);
|
||||
void IpcServerLoop();
|
||||
void SessionStateLoop();
|
||||
void RefreshInteractiveState();
|
||||
void WakeSessionState();
|
||||
void RefreshSessionState();
|
||||
void EnsureSessionHelper();
|
||||
void ReapSessionHelper();
|
||||
@@ -69,6 +75,14 @@ class CrossDeskServiceHost {
|
||||
DWORD client_session_id);
|
||||
std::string BuildStatusResponse(DWORD client_session_id);
|
||||
std::string SendSecureAttentionSequence(DWORD client_session_id);
|
||||
struct SecureInputTarget {
|
||||
DWORD session_id = 0xFFFFFFFF;
|
||||
std::string stage;
|
||||
std::string desktop;
|
||||
};
|
||||
// Returns an error response, or an empty string with a validated snapshot.
|
||||
std::string ResolveSecureInputTarget(DWORD client_session_id,
|
||||
SecureInputTarget& target);
|
||||
std::string SendSecureDesktopKeyboardInput(DWORD client_session_id,
|
||||
int key_code, bool is_down,
|
||||
uint32_t scan_code = 0,
|
||||
@@ -86,8 +100,20 @@ class CrossDeskServiceHost {
|
||||
SERVICE_STATUS service_status_{};
|
||||
HANDLE stop_event_ = nullptr;
|
||||
std::thread ipc_thread_;
|
||||
std::thread session_state_thread_;
|
||||
HANDLE session_state_event_ = nullptr;
|
||||
std::thread client_process_monitor_thread_;
|
||||
// Owned exclusively by the monitor, then drained after it joins.
|
||||
HANDLE unattended_process_ = nullptr;
|
||||
HANDLE unattended_stop_event_ = nullptr;
|
||||
DWORD unattended_session_ = 0xFFFFFFFF;
|
||||
std::atomic<uint64_t> unattended_logoff_generation_{0};
|
||||
std::mutex state_mutex_;
|
||||
uint64_t session_state_generation_ = 0;
|
||||
ULONGLONG last_session_transition_tick_ = 0;
|
||||
bool session_lock_state_known_ = false;
|
||||
HANDLE lifetime_mutex_ = nullptr;
|
||||
std::wstring lifetime_mutex_name_;
|
||||
DWORD active_session_id_ = 0xFFFFFFFF;
|
||||
DWORD process_session_id_ = 0xFFFFFFFF;
|
||||
DWORD input_desktop_error_code_ = 0;
|
||||
@@ -111,6 +137,9 @@ class CrossDeskServiceHost {
|
||||
ULONGLONG session_helper_report_state_age_ms_ = 0;
|
||||
ULONGLONG session_helper_report_uptime_ms_ = 0;
|
||||
ULONGLONG secure_input_helper_started_at_tick_ = 0;
|
||||
// Short idle grace after a validated user-desktop input request. This keeps
|
||||
// the SYSTEM helper available for elevated windows such as Task Manager.
|
||||
ULONGLONG user_desktop_input_until_tick_ = 0;
|
||||
ULONGLONG sas_secure_desktop_until_tick_ = 0;
|
||||
bool session_locked_ = false;
|
||||
bool logon_ui_visible_ = false;
|
||||
@@ -138,6 +167,7 @@ class CrossDeskServiceHost {
|
||||
HANDLE secure_input_helper_process_handle_ = nullptr;
|
||||
HANDLE secure_input_helper_stop_event_ = nullptr;
|
||||
std::string input_desktop_name_;
|
||||
std::string session_username_;
|
||||
std::string last_sas_error_;
|
||||
std::string session_helper_last_error_;
|
||||
std::string session_helper_status_error_;
|
||||
@@ -154,7 +184,7 @@ bool IsCrossDeskServiceInstalled();
|
||||
bool InstallCrossDeskService(const std::wstring& binary_path);
|
||||
bool UninstallCrossDeskService();
|
||||
bool StartCrossDeskService();
|
||||
bool StopCrossDeskService(DWORD timeout_ms = 5000);
|
||||
bool StopCrossDeskService(DWORD timeout_ms = 20000);
|
||||
std::string QueryCrossDeskService(const std::string& command,
|
||||
DWORD timeout_ms = 1000);
|
||||
std::string SendCrossDeskSecureDesktopKeyInput(int key_code, bool is_down,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user