Author SHA1 Message Date
bit9992 da1f867aee Offer actual Android call routes with distinct phone and speaker choices
android-ci / android-arm64 (push) Successful in 17m16s
2026-11-15 16:18:39 +03:00
bit9992 742120ebec Recreate Android playback when private test becomes a call
android-ci / android-arm64 (push) Successful in 14m49s
End private-test reservation before communication-mode activation.
Serialize mode and output startup; cover record/listen/call handoff and newer mute.
2026-11-15 15:09:18 +03:00
bit9992 7ff77ecb29 Include palette preview regressions in the existing CI test filter
android-ci / android-arm64 (push) Successful in 14m20s
2026-11-15 13:21:17 +03:00
bit9992 956b464df7 Synchronize Android Room navigation for programmatic callers
android-ci / android-arm64 (push) Successful in 14m52s
2026-11-15 12:54:19 +03:00
bit9992 87265a3e75 Implement Android Room UI and customizable palette
android-ci / android-arm64 (push) Successful in 17m10s
2026-11-15 12:32:59 +03:00
bit9992 057bfae87c Record interrupted verification and retry unchanged Android capture candidate
android-ci / android-arm64 (push) Successful in 14m2s
2026-11-15 00:19:27 +03:00
bit9992 a0a9b14207 Preserve Android capture tail continuity and condense mobile handoff
android-ci / android-arm64 (push) Failing after 21m24s
2026-11-14 23:46:25 +03:00
bit9992 8074343edc Acquire Android output hardware clock before playback publication
android-ci / android-arm64 (push) Successful in 16m53s
2026-11-14 22:21:21 +03:00
bit9992 e288553254 Keep fresh Android playback audible across downstream device latency
android-ci / android-arm64 (push) Successful in 14m59s
2026-11-14 21:13:27 +03:00
bit9992 4664be0818 Repair Android route settlement, failed recovery and AAudio startup contracts
android-ci / android-arm64 (push) Successful in 20m13s
2026-11-14 20:12:51 +03:00
bit9992 e619f66d59 Keep worker event consumers alive in Android route regression fixtures
android-ci / android-arm64 (push) Successful in 17m38s
2026-11-14 18:51:35 +03:00
bit9992 63861bec26 Honor manual Android endpoints and apply version-safe voice output attributes
android-ci / android-arm64 (push) Failing after 12m15s
2026-11-14 18:33:17 +03:00
bit9992 4ea413f589 Add bounded private Android route and audio pipeline diagnostics
android-ci / android-arm64 (push) Successful in 14m44s
2026-11-14 15:12:54 +03:00
bit9992 3b56013d0d Check disconnected capture by permit and activity rather than preferred owner
android-ci / android-arm64 (push) Successful in 16m37s
2026-11-14 14:02:29 +03:00
bit9992 61f748ce34 Retain route test startup observer until acknowledgement
android-ci / android-arm64 (push) Failing after 12m34s
2026-11-14 13:42:52 +03:00
bit9992 2565e5526a Join retired Android runtime and recover acknowledged headset routes
android-ci / android-arm64 (push) Failing after 12m25s
2026-11-14 13:25:16 +03:00
bit9992 505a784235 Complete isolated onboarding before terminal shutdown regression
android-ci / android-arm64 (push) Successful in 18m31s
2026-11-14 12:06:16 +03:00
bit9992 3fe8c82354 Preserve authorized Android background calls and stop on task removal
android-ci / android-arm64 (push) Failing after 3h5m22s
2026-11-14 10:53:49 +03:00
bit9992 f403dd5fcf Keep capture frame rejection separate from permit revocation
android-ci / android-arm64 (push) Successful in 15m1s
2026-11-14 09:45:55 +03:00
bit9992 8f74404729 Remove obsolete inactive private-stop error assertion
android-ci / android-arm64 (push) Successful in 16m59s
2026-11-13 23:01:04 +03:00
bit9992 2716aa54a1 Fix private resume state guard coercion
android-ci / android-arm64 (push) Failing after 11m25s
2026-11-13 22:42:28 +03:00
bit9992 691be5f783 Separate audio lifecycle ownership and repair audited voice state transitions
android-ci / android-arm64 (push) Failing after 14m6s
2026-11-13 22:23:23 +03:00
bit9992 6e5c831940 Request microphone permission on first visible Android entry
android-ci / android-arm64 (push) Successful in 17m30s
2026-11-13 20:36:23 +03:00
bit9992 fb2a38da27 Restore mute lifecycle ownership and publish capture before acknowledgements
android-ci / android-arm64 (push) Successful in 19m52s
2026-11-13 19:56:15 +03:00
bit9992 c7fdac5bae Fix AAudio capture first-frame timestamps and reject compressed gaps
android-ci / android-arm64 (push) Successful in 20m25s
2026-11-13 19:08:38 +03:00
bit9992 493f09aadf Wire Android endpoint classification into JNI enumeration
android-ci / android-arm64 (push) Successful in 16m54s
2026-11-13 18:27:37 +03:00
bit9992 5060f5ec3c Isolate microphone preview and classify Android capture endpoints 2026-11-13 18:26:27 +03:00
bit9992 e0f4d3b442 Specify Linux tray menu callback receiver types
android-ci / android-arm64 (push) Successful in 16m20s
2026-11-13 17:24:30 +03:00
bit9992 c5b35e50a2 Synchronize locked Linux tray dependency features
android-ci / android-arm64 (push) Failing after 9m40s
2026-11-13 16:57:49 +03:00
bit9992 c5a9cccd0b Align Linux tray async runtime with Slint host tests
android-ci / android-arm64 (push) Failing after 2m4s
2026-11-13 16:53:53 +03:00
bit9992 f47caf178a Fix shared audio timing and gate Android builds on native worker tests
android-ci / android-arm64 (push) Failing after 8m46s
2026-11-13 16:42:21 +03:00
bit9992 b58483ed62 Fix burst callback clock observations with reproducing audio regressions
android-ci / android-arm64 (push) Successful in 14m15s
2026-11-13 15:36:15 +03:00
bit9992 b4c363b99b Repair audio recovery contracts and retain first native fault evidence
android-ci / android-arm64 (push) Successful in 13m21s
2026-11-13 14:55:49 +03:00
bit9992 70ed120087 Complete audio configuration guard caller migration
android-ci / android-arm64 (push) Successful in 13m1s
2026-11-12 21:11:43 +03:00
bit9992 65707789a7 Serialize receive-only capture transitions and retain playback on command failure
android-ci / android-arm64 (push) Failing after 8m40s
2026-11-12 20:59:06 +03:00
bit9992 3c0593b3be Fix connected channel visibility and Android voice startup ownership
android-ci / android-arm64 (push) Successful in 15m17s
2026-11-12 19:56:20 +03:00
bit9992 5e2a82b1bb Adapt complete Android phone UI and fix idle audio and microphone test gates
android-ci / android-arm64 (push) Successful in 17m35s
2026-11-12 18:33:57 +03:00
bit9992 cec86d8e3d Use all available Android runner CPUs while preserving compatible caches
android-ci / android-arm64 (push) Successful in 12m28s
2026-11-12 17:37:02 +03:00
bit9992 e443f9aebc Record Android startup build and measure compatible warm CI cache
android-ci / android-arm64 (push) Successful in 11m17s
2026-11-12 17:20:33 +03:00
bit9992 5799fcb0d1 Complete Android bootstrap failure contracts, platform TLS and warm CI caches
android-ci / android-arm64 (push) Successful in 38m53s
2026-11-12 15:27:53 +03:00
bit9992 3cc9565fab Fix Android file lock portability and NativeActivity window insets
android-ci / android-arm64 (push) Successful in 18m47s
2026-11-12 14:03:35 +03:00
bit9992 fd41389d63 Fix Android sandbox onboarding and surface insets; checkpoint application cache
android-ci / android-arm64 (push) Successful in 18m47s
2026-11-12 13:25:41 +03:00
bit9992 52d2c22ec0 Align Android SDK preference paths for CI packaging
android-ci / android-arm64 (push) Successful in 17m51s
2026-11-12 12:04:25 +03:00
bit9992 6e69516f79 Restore normal Android release builds on migrated runner
android-ci / android-arm64 (push) Failing after 14m36s
2026-11-12 11:43:27 +03:00
bit9992 df2cce71df Use explicit low-memory Android native compilation in CI
android-ci / android-arm64 (push) Failing after 11m44s
2026-11-12 10:27:30 +03:00
bit9992 4f38a7e011 Preserve verified WebRTC object cache across gclient synchronization
android-ci / android-arm64 (push) Failing after 11m18s
2026-11-12 10:08:46 +03:00
bit9992 e676f2ad04 Resume Android CI after owner-requested pauses
android-ci / android-arm64 (push) Failing after 3m2s
2026-11-12 09:56:55 +03:00
bit9992 88276c09c7 Checkpoint Android dependencies and capture compiler memory evidence
android-ci / android-arm64 (push) Failing after 27m51s
2026-11-12 01:03:05 +03:00
bit9992 aecbacce4c Retry transient Skia source synchronization in Android CI
android-ci / android-arm64 (push) Failing after 52m23s
2026-11-12 00:00:40 +03:00
bit9992 2804788e9c Fix Gitea runner workspace default for Android CI
android-ci / android-arm64 (push) Failing after 2m16s
2026-11-11 23:53:28 +03:00
bit9992 3995f5c54f Retry Android CI after runner storage expansion
android-ci / android-arm64 (push) Failing after 5s
2026-11-11 23:41:48 +03:00
bit9992 8d25224816 Automate isolated Android APK builds and fix phone onboarding
android-ci / android-arm64 (push) Failing after 1m29s
2026-11-11 22:07:47 +03:00
153 changed files with 29897 additions and 8427 deletions

No files matched your search

+222
View File
@@ -0,0 +1,222 @@
#!/usr/bin/env python3
"""CI-only Cargo cache bookkeeping; never manufactures build/provenance receipts.
Cargo compares checkout source mtimes with cached dep-info/build-script timestamps.
A fresh checkout otherwise invalidates unchanged workspace and vendored crates.
Restore a recorded timestamp only for the same path, SHA-256, kind and mode; a
changed input keeps its real mtime. WebRTC is handled only AFTER xtask deps has
rebuilt/verified it, so identical republished headers/archives can retain their
original timestamps without trusting cached dependency provenance.
"""
import argparse
import hashlib
import json
import os
import pathlib
import stat
import subprocess
import time
import tomllib
ROOT = pathlib.Path.cwd().resolve()
STATE = ROOT / '.android-ci'
RECEIPT = STATE / 'application-cache-inputs.json'
PENDING = STATE / 'application-cache-pending.json'
def digest(path):
with path.open('rb') as source:
return hashlib.file_digest(source, 'sha256').hexdigest()
def tracked_paths():
return [os.fsdecode(name) for name in subprocess.check_output(
['git', 'ls-files', '-z']).split(b'\0') if name]
def compatibility():
# Content changes belong to Cargo's fingerprints and the input snapshot, not
# the restore prefix. Only configuration that changes the build contract is
# a compatibility boundary. In particular, dependency versions/features and
# source/dependency drivers are deliberately absent here.
target_dir = pathlib.Path(os.environ['CARGO_TARGET_DIR']).resolve()
if target_dir != STATE / 'cargo-target':
raise ValueError('Application cache requires the isolated .android-ci/cargo-target')
names = {'.gitea/android-ci-tools.json', 'rust-toolchain.toml',
'.gitea/setup-android-ci.sh', '.gitea/build-android-variant.sh',
'.gitea/android-rustc-low-memory.sh',
'platform/android/gradle/wrapper/gradle-wrapper.properties'}
profiles = {}
for name in tracked_paths():
path = pathlib.PurePosixPath(name)
if path.name in ('config', 'config.toml') and path.parent.name == '.cargo':
names.add(name)
if path.name == 'Cargo.toml':
profile = tomllib.loads((ROOT / name).read_text()).get('profile')
if profile:
profiles[name] = profile
environment = {
name: os.environ.get(name, '') for name in (
'TARGET', 'TEAMSPEACH_ANDROID_LOW_MEMORY', 'CARGO_TARGET_DIR',
'RUSTFLAGS', 'CARGO_ENCODED_RUSTFLAGS', 'RUSTC_WRAPPER',
'RUSTC_WORKSPACE_WRAPPER', 'RUSTUP_TOOLCHAIN', 'CARGO_HOME',
'RUSTUP_HOME', 'HOME', 'LLVM_HOME', 'LIBCLANG_PATH',
'ANDROID_SDK_ROOT', 'ANDROID_NDK_ROOT', 'ANDROID_API_LEVEL',
'SKIA_SOURCE_DIR', 'SKIA_GN_COMMAND', 'SKIA_NINJA_COMMAND',
'SKIA_FORCE_BUILD')}
environment.update({name: value for name, value in os.environ.items()
if name.startswith(('CARGO_PROFILE_', 'CARGO_TARGET_'))})
return {
'files': {name: digest(ROOT / name) for name in sorted(names)},
'profiles': profiles, 'environment': environment,
'rustc': subprocess.check_output(['rustc', '-vV'], text=True),
'cargo': subprocess.check_output(['cargo', '-V'], text=True),
'profile': 'release', 'variant': 'harness',
}
def identity(inputs):
fingerprint = hashlib.sha256(json.dumps(inputs, sort_keys=True).encode()).hexdigest()
environment = inputs['environment']
mode = 'low-memory' if environment['TEAMSPEACH_ANDROID_LOW_MEMORY'] == 'true' else 'normal'
return f"android-application-linux-x64-{environment['TARGET']}-release-{mode}-harness-v2-{fingerprint}"
def record(path):
info = path.lstat()
mode = stat.S_IMODE(info.st_mode)
if stat.S_ISREG(info.st_mode):
kind, value = 'file', digest(path)
elif stat.S_ISDIR(info.st_mode):
kind = 'directory'
value = hashlib.sha256(json.dumps(sorted(os.listdir(path))).encode()).hexdigest()
else:
# Never follow checkout/cache symlinks, including symlinked ancestors.
raise ValueError(f'Unsupported cache input: {path}')
return {'kind': kind, 'sha256': value, 'mode': mode, 'mtime_ns': info.st_mtime_ns}
def collect(names):
result = {}
for name in sorted(set(names)):
path = ROOT / name
if not path.exists():
continue
if not path.resolve().is_relative_to(ROOT) or any(parent.is_symlink() for parent in (path, *path.parents)):
raise ValueError(f'Unconfined cache input: {name}')
result[name] = record(path)
return result
def load(contract, path=RECEIPT):
if path == RECEIPT and not path.exists():
return {'inputs': {}, 'completed_ns': 0}
data = json.loads(path.read_text())
recorded = data.get('compatibility', {})
comparable = {**recorded, 'environment': dict(recorded.get('environment', {}))}
# Scheduling is not an artifact compatibility boundary. Accept the earlier
# explicit four-job receipt only after all actual tool/profile inputs match.
comparable['environment'].pop('CMAKE_BUILD_PARALLEL_LEVEL', None)
if (data['schema'] != 2 or comparable != contract
or data['identity'] != identity(recorded) or data['workspace'] != str(ROOT)):
# v1's opaque content identity cannot prove configuration compatibility
# after a manifest change. Start a new cache generation, never guess.
raise ValueError('Application cache compatibility/workspace mismatch (requires v2 receipt)')
return data
def cargo_timestamps():
# These are Cargo's real host/target build-start stamps, not target/ at the
# repository root (which contains the separately verified WebRTC tree).
target = STATE / 'cargo-target'
paths = [*target.glob('*/.fingerprint/*/invoked.timestamp'),
*target.glob('*/*/.fingerprint/*/invoked.timestamp')]
return {str(path.relative_to(ROOT)): path.stat().st_mtime_ns for path in paths}
def report_cargo_timestamps(previous):
current = cargo_timestamps()
recorded = previous.get('cargo_timestamps', {})
changed = sum(current.get(name) != stamp for name, stamp in recorded.items())
print(f'Cargo target: {STATE / "cargo-target"}; restored build-start stamps: '
f'{len(current)}; missing/retimed since snapshot: {changed}; '
f'cached completion ns: {previous["completed_ns"]}', flush=True)
if changed:
print('Cargo output timestamps changed during cache transport; Cargo may rebuild. '
'Build output timestamps are never rewritten.', flush=True)
def save(path, inputs, contract):
STATE.mkdir(exist_ok=True)
temporary = path.with_suffix('.tmp')
stamps = cargo_timestamps() if path == RECEIPT else {}
temporary.write_text(json.dumps({'schema': 2, 'identity': identity(contract),
'compatibility': contract,
'workspace': str(ROOT), 'inputs': inputs,
'completed_ns': time.time_ns(),
'cargo_timestamps': stamps}, sort_keys=True))
temporary.replace(path)
def restore(current, previous):
restored = 0
for name, item in current.items():
old = previous['inputs'].get(name)
if old is None or any(item[key] != old[key] for key in ('kind', 'sha256', 'mode')):
# Changed/new inputs must postdate the previous compilation. Reject
# clock regressions rather than making stale outputs appear fresh.
if previous['completed_ns'] and item['mtime_ns'] <= previous['completed_ns']:
raise ValueError(f'Changed input predates cached compilation: {name}; refuse stale Cargo reuse')
continue
if old['mtime_ns'] > item['mtime_ns']:
raise ValueError(f'Cached input timestamp is in the future: {name}')
path = ROOT / name
os.utime(path, ns=(path.stat().st_atime_ns, old['mtime_ns']), follow_symlinks=False)
item['mtime_ns'] = old['mtime_ns']
restored += 1
print(f'Restored {restored}/{len(current)} content-matched input timestamps', flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('key', 'sources', 'dependencies', 'snapshot'))
action = parser.parse_args().action
contract = compatibility()
if action == 'key':
with open(os.environ['GITHUB_OUTPUT'], 'a') as out:
out.write(f'key={identity(contract)}\n')
previous = {**contract, 'environment': {**contract['environment'], 'CMAKE_BUILD_PARALLEL_LEVEL': '4'}}
out.write(f'previous-parallelism-key={identity(previous)}\n')
return
previous = load(contract)
if action == 'sources':
report_cargo_timestamps(previous)
names = set(tracked_paths())
# Cargo's directory rerun rules also inspect directory mtimes. Preserve
# those only if their exact child-name inventory and mode still match.
for name in tuple(names):
names.update(str(parent) for parent in pathlib.Path(name).parents if parent != pathlib.Path('.'))
current = collect(names)
restore(current, previous)
save(PENDING, current, contract)
elif action == 'dependencies':
base = pathlib.Path('target/native-deps') / os.environ['TARGET'] / 'webrtc'
if not base.is_dir():
raise ValueError('Verified WebRTC artifact tree is missing')
current = collect([str(base), *(str(path) for path in base.rglob('*'))])
restore(current, previous)
pending = load(contract, PENDING)['inputs']
pending.update(current)
save(PENDING, pending, contract)
else:
pending = load(contract, PENDING)['inputs']
current = collect(pending)
# Only retain inputs whose bytes/mode/mtime stayed stable throughout the
# build. A generated or concurrently edited file is never backdated.
stable = {name: item for name, item in current.items() if item == pending[name]}
save(RECEIPT, stable, contract)
print(f'Recorded {len(stable)} stable application/dependency inputs', flush=True)
if __name__ == '__main__':
main()
+39
View File
@@ -0,0 +1,39 @@
{
"schema": 1,
"rust": {
"version": "1.96.0",
"target": "aarch64-linux-android",
"rustupVersion": "1.29.3",
"rustupUrl": "https://static.rust-lang.org/rustup/archive/1.29.3/x86_64-unknown-linux-gnu/rustup-init",
"rustupSha256": "b1c8cb14e30889e7e2999e6b69e62d9e9b9ffc0f4df8180564d306d9680e6c55",
"checksumSource": "https://static.rust-lang.org/rustup/archive/1.29.3/x86_64-unknown-linux-gnu/rustup-init.sha256"
},
"android": {
"commandLineToolsVersion": "15859902",
"commandLineToolsUrl": "https://dl.google.com/android/repository/commandlinetools-linux-15859902_latest.zip",
"commandLineToolsSha256": "4e4c464f145a7512b57d088ac6c278c03c9eea610886b35a5e0804e74eedf583",
"checksumSource": "https://developer.android.com/studio#command-line-tools-only",
"platform": "android-36",
"buildTools": "36.0.0",
"ndk": "28.2.13676358"
},
"gradle": {
"version": "8.14.3",
"pinSource": "platform/android/gradle/wrapper/gradle-wrapper.properties"
},
"skia": {
"revision": "m153-0.101.2",
"url": "https://codeload.github.com/rust-skia/skia/tar.gz/m153-0.101.2",
"sha256": "30c8b51a0a32fae63562c303bdc91605519a9598951422610e3fb8685b3c4f6f",
"metadataSource": "https://raw.githubusercontent.com/rust-skia/rust-skia/0.153.3/skia-bindings/Cargo.toml",
"urlSource": "https://raw.githubusercontent.com/rust-skia/rust-skia/0.153.3/skia-bindings/build_support/binary_cache/download.rs",
"gnRevision": "b2afae122eeb6ce09c52d63f67dc53fc517dbdc8",
"gnPinSource": "https://raw.githubusercontent.com/rust-skia/skia/m153-0.101.2/bin/fetch-gn"
},
"bundletool": {
"version": "1.18.3",
"url": "https://github.com/google/bundletool/releases/download/1.18.3/bundletool-all-1.18.3.jar",
"sha256": "a099cfa1543f55593bc2ed16a70a7c67fe54b1747bb7301f37fdfd6d91028e29",
"checksumSource": "https://api.github.com/repos/google/bundletool/releases/tags/1.18.3"
}
}
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# Read only resource counters; no environment, credentials, process arguments or kernel logs.
set -euo pipefail
printf 'RESOURCE_SNAPSHOT %s\n' "$(date -u +%FT%TZ)"
while read -r key value unit; do
case "$key" in MemTotal:|MemAvailable:|SwapTotal:|SwapFree:|CommitLimit:|Committed_AS:) printf '%s %s %s\n' "$key" "$value" "${unit:-}" ;; esac
done < /proc/meminfo
while IFS=: read -r hierarchy controllers relative; do
if [[ -z "$controllers" ]]; then
base=/sys/fs/cgroup
names=(memory.max memory.high memory.current memory.peak memory.events memory.events.local memory.swap.max memory.swap.current)
elif [[ ",$controllers," == *,memory,* ]]; then
base=/sys/fs/cgroup/memory
names=(memory.limit_in_bytes memory.usage_in_bytes memory.max_usage_in_bytes memory.failcnt memory.oom_control)
else
continue
fi
current="$(realpath -m "$base/${relative#/}")"
case "$current" in "$base"|"$base/"*) ;; *) current="$base" ;; esac
[[ -d "$current" ]] || current="$base"
while :; do
for name in "${names[@]}"; do
if [[ -r "$current/$name" ]]; then printf '%s\n' "$current/$name"; cat "$current/$name"; fi
done
[[ "$current" != "$base" ]] || break
current="${current%/*}"
done
done < /proc/self/cgroup
ulimit -a
df -Pk . /
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# Explicitly authorized Android CI optimization override, not a workspace release default.
set -euo pipefail
compiler="$1"
shift
crate= target= previous=
for argument in "$@"; do
case "$previous" in --crate-name) crate="$argument" ;; --target) target="$argument" ;; esac
previous="$argument"
done
if [[ "$crate" == teamspeach_native && "$target" == aarch64-linux-android ]]; then
exec "$compiler" "$@" -C codegen-units=256 -C lto=off
fi
exec "$compiler" "$@"
+10 -3
View File
@@ -8,11 +8,16 @@ case "$variant" in
*) echo "Expected harness or production" >&2; exit 2 ;;
esac
out="dist/android/$variant"
cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME" --skia-source "$SKIA_SOURCE_DIR" --test-harness "$harness"
if [[ "${TEAMSPEACH_ANDROID_LOW_MEMORY:-false}" == true ]]; then
[[ "$TARGET" == aarch64-linux-android ]] || { echo 'Low-memory CI mode is Android ARM64 only' >&2; exit 1; }
export RUSTC_WORKSPACE_WRAPPER="$PWD/.gitea/android-rustc-low-memory.sh"
fi
cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME" --skia-source "$SKIA_SOURCE_DIR" --test-harness "$harness" --jobs "${CARGO_BUILD_JOBS:-1}"
# Explicit online dependency resolution supports a fresh Gradle cache.
# Bootstrap still requires the local checksum-pinned zip; SDK downloads stay disabled.
cargo run --locked -p xtask -- package --target "$TARGET" --out "$out" --test-harness "$harness" --gradle-online true
cargo run --locked -p xtask -- verify-package --target "$TARGET" --out "$out" --test-harness "$harness"
# xtask package already verifies the completed APK/AAB before returning success.
# The receipt and artifact hashes below bind that verification to the uploaded bytes.
cp "$CARGO_TARGET_DIR/$TARGET/release/native-build.json" "$out/$TARGET/native-build.json"
cp native/native-deps.lock.json "$out/$TARGET/native-deps.lock.json"
cp "target/native-deps/$TARGET/provenance.json" "$out/$TARGET/dependency-provenance.json"
@@ -38,5 +43,7 @@ for path in files:
for chunk in iter(lambda: source.read(1024 * 1024), b''):
digest.update(chunk)
hashes[str(path.relative_to(out))] = digest.hexdigest()
(out / 'build-info.json').write_text(json.dumps({'schema': 1, 'revision': revision, 'run_id': os.environ['CI_RUN_ID'], 'target': target, 'testHarness': harness, 'gradleOnline': True, 'deviceAcceptance': 'not exercised', 'publicationAuthorized': False, 'sha256': hashes}, indent=2) + '\n')
low_memory = os.environ.get('TEAMSPEACH_ANDROID_LOW_MEMORY') == 'true'
optimization = {'scope': 'teamspeach_native/aarch64-linux-android', 'codegenUnits': 256, 'lto': 'off'} if low_memory else {'scope': 'workspace release defaults'}
(out / 'build-info.json').write_text(json.dumps({'schema': 1, 'revision': revision, 'run_id': os.environ['CI_RUN_ID'], 'target': target, 'testHarness': harness, 'gradleOnline': True, 'optimization': optimization, 'deviceAcceptance': 'not exercised', 'publicationAuthorized': False, 'sha256': hashes}, indent=2) + '\n')
PY
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""Undo only receipt-matched source patches before gclient reuses a CI checkpoint."""
import json
import pathlib
import subprocess
def unpatch(checkout, diffs):
checkout = checkout.resolve(strict=True)
pending = []
for relative, expected in diffs.items():
parts = pathlib.PurePosixPath(relative)
if parts.is_absolute() or '..' in parts.parts or not parts.parts or parts.parts[0] != 'src':
raise ValueError('Unconfined dependency receipt path')
directory = checkout.joinpath(*parts.parts).resolve(strict=True)
if not directory.is_relative_to(checkout):
raise ValueError('Dependency checkout escapes cache')
actual = subprocess.check_output(['git', '-C', str(directory), 'diff', '--binary', 'HEAD', '--'])
encoded = expected.encode('utf-8')
if actual != encoded:
raise ValueError(f'Cached changes differ from verified receipt: {relative}; refusing to reset')
if actual:
subprocess.run(['git', '-C', str(directory), 'apply', '--reverse', '--check', '-'], input=actual, check=True)
pending.append((directory, actual))
# Validate every repository before making any mutation. Untracked outputs are not touched.
for directory, patch in pending:
subprocess.run(['git', '-C', str(directory), 'apply', '--reverse', '-'], input=patch, check=True)
print(f'Removed {len(pending)} receipt-matched source patches; build objects retained', flush=True)
def main():
base = pathlib.Path('target/native-deps/aarch64-linux-android')
receipt_path = base / 'provenance.json'
if not receipt_path.exists():
print('No restored dependency receipt; fresh provisioning')
return
receipt = json.loads(receipt_path.read_text(encoding='utf-8'))
lock = json.loads(pathlib.Path('native/native-deps.lock.json').read_text(encoding='utf-8'))
if receipt['target'] != 'aarch64-linux-android':
raise ValueError('Wrong cached target')
for receipt_key, lock_key in [('webrtc_revision', 'webrtc'), ('sdk_revision', 'sdk'), ('depot_tools_revision', 'depot_tools')]:
if receipt[receipt_key] != lock[lock_key]['revision']:
raise ValueError('Cached source revision no longer matches policy')
unpatch(base / 'checkout', receipt['applied_source_diffs'])
if __name__ == '__main__':
main()
+235
View File
@@ -0,0 +1,235 @@
#!/usr/bin/env bash
# Only the explicitly authorized, disposable Android CI job container may install tools.
set -euo pipefail
umask 022
fail() { printf 'Android CI provisioning refused: %s\n' "$*" >&2; exit 1; }
[[ "$(uname -s)" == Linux && "$(uname -m)" == x86_64 ]] || fail 'Linux x86_64 is required'
[[ "${ANDROID_CI_PROVISION:-}" == container ]] || fail 'ANDROID_CI_PROVISION=container is required'
[[ "${GITHUB_ACTIONS:-}" == true || "${GITEA_ACTIONS:-}" == true ]] || fail 'an Actions job is required'
[[ -f /.dockerenv || -f /run/.containerenv ]] || fail 'no Docker/Podman container marker; host provisioning is forbidden'
: "${GITHUB_WORKSPACE:?Actions workspace is required}"
: "${GITHUB_ENV:?Actions environment output is required}"
: "${GITHUB_PATH:?Actions PATH output is required}"
if (( EUID == 0 )); then
elevate=()
else
command -v sudo >/dev/null || fail 'root or passwordless sudo is required inside the container'
sudo -n true || fail 'passwordless sudo is required inside the container'
elevate=(sudo -n)
fi
# No apt update, download, installation, or cache creation precedes this gate.
# MemAvailable alone can describe the host, so also respect every visible cgroup ancestor.
for filesystem in "$GITHUB_WORKSPACE" /; do
free="$(df --output=avail -B1 "$filesystem")"
free="${free##*$'\n'}"
[[ "$free" =~ ^[[:space:]]*[0-9]+[[:space:]]*$ ]] || fail 'cannot determine free disk'
printf 'RESOURCE disk=%s availableBytes=%s requiredBytes=%s\n' "$filesystem" "$free" "$((100 * 1024**3))"
(( free >= 100 * 1024**3 )) || fail 'resource gate needs at least 100 GiB free disk, including cache hits; no provisioning performed'
done
available=0
while read -r key value _; do
if [[ "$key" == MemAvailable: ]]; then available=$((value * 1024)); break; fi
done < /proc/meminfo
(( available > 0 )) || fail 'cannot determine available memory'
limit_count=0
while IFS=: read -r _ controllers relative; do
if [[ -z "$controllers" ]]; then
cgroup_root=/sys/fs/cgroup
limit_names=(memory.max memory.high)
usage_name=memory.current
elif [[ ",$controllers," == *,memory,* ]]; then
cgroup_root=/sys/fs/cgroup/memory
limit_names=(memory.limit_in_bytes)
usage_name=memory.usage_in_bytes
else
continue
fi
current="$(realpath -m "$cgroup_root/${relative#/}")"
case "$current" in "$cgroup_root"|"$cgroup_root/"*) ;; *) current="$cgroup_root" ;; esac
[[ -d "$current" ]] || current="$cgroup_root"
while :; do
for limit_name in "${limit_names[@]}"; do
if [[ -f "$current/$limit_name" && -f "$current/$usage_name" ]]; then
limit="$(<"$current/$limit_name")"
if [[ "$limit" != max ]]; then
[[ "$limit" =~ ^[0-9]+$ ]] || fail 'invalid cgroup memory limit'
usage="$(<"$current/$usage_name")"
[[ "$usage" =~ ^[0-9]+$ ]] || fail 'invalid cgroup memory usage'
remaining=$((limit > usage ? limit - usage : 0))
(( remaining >= available )) || available="$remaining"
limit_count=$((limit_count + 1))
fi
fi
done
[[ "$current" != "$cgroup_root" ]] || break
current="${current%/*}"
done
done < /proc/self/cgroup
printf 'RESOURCE effectiveAvailableMemoryBytes=%s requiredBytes=%s cgroupLimits=%s\n' "$available" "$((8 * 1024**3))" "$limit_count"
(( available >= 8 * 1024**3 )) || fail 'resource gate needs at least 8 GiB available memory; no provisioning performed'
# Stock noble packages provide matching LLVM/libclang18 and JDK21 without third-party apt setup.
# shellcheck disable=SC1091
source /etc/os-release
[[ "$ID" == ubuntu && "$VERSION_ID" == 24.04 ]] || fail 'the container image must use Ubuntu 24.04 (noble)'
workspace="$(realpath "$GITHUB_WORKSPACE")"
cd "$workspace"
[[ ! -L .android-ci && ! -L .android-ci/tools ]] || fail 'tool cache roots must not be symlinks'
tools="$workspace/.android-ci/tools"
mkdir -p "$tools"/{downloads,home,tmp,cache,config,data,apt/archives/partial,apt/lists/partial}
export HOME="$tools/home" TMPDIR="$tools/tmp"
export XDG_CACHE_HOME="$tools/cache" XDG_CONFIG_HOME="$tools/config" XDG_DATA_HOME="$tools/data"
export CARGO_HOME="$tools/cargo" RUSTUP_HOME="$tools/rustup" GRADLE_USER_HOME="$tools/gradle"
# New and legacy Android tools must resolve the same preferences directory.
export ANDROID_USER_HOME="$HOME/.android" ANDROID_EMULATOR_HOME="$HOME/.android/emulator"
export ANDROID_SDK_HOME="$HOME" JAVA_TOOL_OPTIONS="-Duser.home=$HOME"
export GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null GIT_TERMINAL_PROMPT=0
export PIP_CACHE_DIR="$tools/pip-cache" CIPD_CACHE_DIR="$tools/cipd-cache" VPYTHON_VIRTUALENV_ROOT="$tools/vpython-cache"
export DEPOT_TOOLS_METRICS=0 DEPOT_TOOLS_UPDATE=0
mkdir -p "$CARGO_HOME" "$RUSTUP_HOME" "$GRADLE_USER_HOME" "$ANDROID_USER_HOME"
# Apt archives/lists are workspace-local; installed packages exist only in this job container.
apt_options=(-o "Dir::Cache::archives=$tools/apt/archives" -o "Dir::State::lists=$tools/apt/lists" -o APT::Sandbox::User=root)
"${elevate[@]}" env DEBIAN_FRONTEND=noninteractive apt-get "${apt_options[@]}" update
"${elevate[@]}" env DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get "${apt_options[@]}" install -y --no-install-recommends \
ca-certificates openjdk-21-jdk-headless clang-18 llvm-18 lld-18 libclang-18-dev \
cmake ninja-build git python3 curl unzip zip pkg-config build-essential \
autoconf automake libtool bison flex gperf nasm binutils file patch rsync \
xz-utils bzip2 zstd gettext libxml2-utils locales time \
libc6-i386 lib32gcc-s1 lib32stdc++6 zlib1g-dev libbz2-dev liblzma-dev \
libssl-dev libffi-dev libelf-dev libcap-dev libudev-dev libglib2.0-dev \
libnss3-dev libnspr4-dev libdbus-1-dev libdrm-dev libgbm-dev \
libasound2-dev libpulse-dev libcups2-dev libatk1.0-dev libatspi2.0-dev \
libcairo2-dev libpango1.0-dev libgtk-3-dev libfontconfig1-dev libfreetype6-dev \
libx11-dev libx11-xcb-dev libxcb1-dev libxcomposite-dev libxcursor-dev libxdamage-dev \
libxext-dev libxfixes-dev libxi-dev libxrandr-dev libxrender-dev libxss-dev libxtst-dev \
libxkbcommon-dev libxshmfence-dev libwayland-dev libegl1-mesa-dev libgl1-mesa-dev
# Read checked-in pins; Gradle's URL and checksum have exactly one authority: its wrapper.
pins="$(python3 - <<'PY'
import json, pathlib, re, shlex, tomllib
p = json.loads(pathlib.Path('.gitea/android-ci-tools.json').read_text())
assert p['schema'] == 1
rust = tomllib.loads(pathlib.Path('rust-toolchain.toml').read_text())['toolchain']['channel']
assert rust == p['rust']['version'] == '1.96.0', 'toolchain pin mismatch'
props = dict(line.split('=', 1) for line in pathlib.Path(p['gradle']['pinSource']).read_text().splitlines() if '=' in line)
gradle_url = props['distributionUrl'].replace('\\:', ':')
assert gradle_url == 'https://services.gradle.org/distributions/gradle-8.14.3-bin.zip'
assert re.fullmatch(r'[0-9a-f]{64}', props['distributionSha256Sum'])
values = {
'rust_version': rust, 'rust_target': p['rust']['target'],
'rustup_url': p['rust']['rustupUrl'], 'rustup_sha': p['rust']['rustupSha256'],
'sdk_tools_version': p['android']['commandLineToolsVersion'],
'sdk_tools_url': p['android']['commandLineToolsUrl'], 'sdk_tools_sha': p['android']['commandLineToolsSha256'],
'sdk_platform': p['android']['platform'], 'build_tools': p['android']['buildTools'], 'ndk_version': p['android']['ndk'],
'gradle_url': gradle_url, 'gradle_sha': props['distributionSha256Sum'],
'skia_revision': p['skia']['revision'], 'skia_url': p['skia']['url'], 'skia_sha': p['skia']['sha256'],
'skia_gn_revision': p['skia']['gnRevision'],
'bundletool_version': p['bundletool']['version'], 'bundletool_url': p['bundletool']['url'], 'bundletool_sha': p['bundletool']['sha256'],
}
for key, value in values.items():
assert '\n' not in value and '\r' not in value
print(f'{key}={shlex.quote(value)}')
PY
)"
eval "$pins"
fetch() {
local url="$1" digest="$2" destination="$3"
if [[ -f "$destination" ]]; then
printf '%s %s\n' "$digest" "$destination" | sha256sum --check --status || fail "cached download checksum mismatch: $destination"
return
fi
curl --fail --location --show-error --silent --retry 3 --proto '=https' --tlsv1.2 "$url" -o "$destination.part"
printf '%s %s\n' "$digest" "$destination.part" | sha256sum --check --status || fail "download checksum mismatch: $url"
mv "$destination.part" "$destination"
}
export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64 LLVM_HOME=/usr/lib/llvm-18 LIBCLANG_PATH=/usr/lib/llvm-18/lib
export PATH="$CARGO_HOME/bin:$JAVA_HOME/bin:$LLVM_HOME/bin:$PATH"
fetch "$rustup_url" "$rustup_sha" "$tools/downloads/rustup-init"
chmod +x "$tools/downloads/rustup-init"
if [[ ! -x "$CARGO_HOME/bin/rustup" ]]; then
"$tools/downloads/rustup-init" -y --no-modify-path --profile minimal --default-toolchain none
fi
rustup toolchain install "$rust_version" --profile minimal --no-self-update
rustup target add --toolchain "$rust_version" "$rust_target"
export RUSTUP_TOOLCHAIN="$rust_version"
export ANDROID_HOME="$tools/android-sdk" ANDROID_SDK_ROOT="$tools/android-sdk"
fetch "$sdk_tools_url" "$sdk_tools_sha" "$tools/downloads/commandlinetools-linux-$sdk_tools_version.zip"
if [[ ! -x "$ANDROID_SDK_ROOT/cmdline-tools/$sdk_tools_version/bin/sdkmanager" ]]; then
stage="$(mktemp -d "$tools/tmp/sdk-tools.XXXXXXXX")"
unzip -q "$tools/downloads/commandlinetools-linux-$sdk_tools_version.zip" -d "$stage"
mkdir -p "$ANDROID_SDK_ROOT/cmdline-tools"
mv "$stage/cmdline-tools" "$ANDROID_SDK_ROOT/cmdline-tools/$sdk_tools_version"
rmdir "$stage"
fi
sdkmanager="$ANDROID_SDK_ROOT/cmdline-tools/$sdk_tools_version/bin/sdkmanager"
# The owner explicitly authorized SDK license acceptance in this isolated CI container.
# Ignore only yes(1)'s expected SIGPIPE; sdkmanager's own failure remains fatal.
set +e
yes | "$sdkmanager" --sdk_root="$ANDROID_SDK_ROOT" --licenses
license_status=("${PIPESTATUS[@]}")
set -e
[[ "${license_status[1]}" == 0 ]] || fail 'sdkmanager license acceptance failed'
"$sdkmanager" --sdk_root="$ANDROID_SDK_ROOT" --install "platforms;$sdk_platform" "build-tools;$build_tools" "ndk;$ndk_version" platform-tools
export ANDROID_NDK_ROOT="$ANDROID_SDK_ROOT/ndk/$ndk_version"
export ANDROID_NDK_HOME="$ANDROID_NDK_ROOT" ANDROID_NDK="$ANDROID_NDK_ROOT"
export ANDROID_JAR="$ANDROID_SDK_ROOT/platforms/$sdk_platform/android.jar"
export ANDROID_PLATFORM=android-26 ANDROID_API_LEVEL=26
export PATH="$ANDROID_SDK_ROOT/cmdline-tools/$sdk_tools_version/bin:$ANDROID_SDK_ROOT/build-tools/$build_tools:$ANDROID_SDK_ROOT/platform-tools:$PATH"
export TEAMSPEACH_GRADLE_DISTRIBUTION="$tools/downloads/gradle-8.14.3-bin.zip"
fetch "$gradle_url" "$gradle_sha" "$TEAMSPEACH_GRADLE_DISTRIBUTION"
export TEAMSPEACH_BUNDLETOOL="$tools/downloads/bundletool-all-$bundletool_version.jar"
fetch "$bundletool_url" "$bundletool_sha" "$TEAMSPEACH_BUNDLETOOL"
export SKIA_SOURCE_DIR="$tools/skia-$skia_revision"
fetch "$skia_url" "$skia_sha" "$tools/downloads/skia-$skia_revision.tar.gz"
if [[ ! -f "$SKIA_SOURCE_DIR/.android-ci-archive-sha256" ]]; then
[[ ! -e "$SKIA_SOURCE_DIR" ]] || fail 'incomplete Skia cache; remove only that CI cache entry before retrying'
stage="$(mktemp -d "$tools/tmp/skia.XXXXXXXX")"
tar -xzf "$tools/downloads/skia-$skia_revision.tar.gz" --strip-components=1 -C "$stage"
printf '%s\n' "$skia_sha" > "$stage/.android-ci-archive-sha256"
mv "$stage" "$SKIA_SOURCE_DIR"
fi
[[ "$(cat "$SKIA_SOURCE_DIR/.android-ci-archive-sha256")" == "$skia_sha" ]] || fail 'Skia cache pin mismatch'
# Android does not use emscripten. This skips only that unrelated toolchain, not native deps or GN.
# Some mirrors fail a connection while other pinned checkouts succeed. Retry the same
# immutable inputs only; revision verification below is still mandatory.
for attempt in 1 2 3; do
if GIT_SYNC_DEPS_SKIP_EMSDK=1 python3 "$SKIA_SOURCE_DIR/tools/git-sync-deps"; then break; fi
(( attempt < 3 )) || fail 'Skia source hosts remain unreachable after three attempts; check runner HTTPS egress to skia.googlesource.com/chromium.googlesource.com'
sleep "$((attempt * 10))"
done
python3 - "$SKIA_SOURCE_DIR" "$skia_gn_revision" <<'PY'
import pathlib, runpy, subprocess, sys
root = pathlib.Path(sys.argv[1])
assert (root / 'BUILD.gn').is_file()
assert sys.argv[2] in (root / 'bin/fetch-gn').read_text(), 'GN revision changed'
deps = runpy.run_path(str(root / 'tools/git-sync-deps'))['parse_file_to_dict'](str(root / 'DEPS'))['deps']
for relative, spec in deps.items():
if not isinstance(spec, str):
continue
expected = spec.rsplit('@', 1)[1]
actual = subprocess.check_output(['git', '-C', str(root / relative), 'rev-parse', 'HEAD'], text=True).strip()
assert actual == expected, f'Skia dependency mismatch: {relative}'
PY
export SKIA_GN_COMMAND="$SKIA_SOURCE_DIR/bin/gn" SKIA_NINJA_COMMAND="$(command -v ninja)" SKIA_FORCE_BUILD=1
[[ -x "$SKIA_GN_COMMAND" && -f "$ANDROID_JAR" && -x "$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin/clang" ]] || fail 'provisioned Android/Skia files are missing'
# Workflow steps are new shells. Publish the complete isolated tools/cache contract.
for name in HOME TMPDIR XDG_CACHE_HOME XDG_CONFIG_HOME XDG_DATA_HOME CARGO_HOME RUSTUP_HOME RUSTUP_TOOLCHAIN \
GRADLE_USER_HOME ANDROID_USER_HOME ANDROID_EMULATOR_HOME ANDROID_SDK_HOME JAVA_TOOL_OPTIONS \
GIT_CONFIG_NOSYSTEM GIT_CONFIG_GLOBAL GIT_TERMINAL_PROMPT PIP_CACHE_DIR CIPD_CACHE_DIR VPYTHON_VIRTUALENV_ROOT \
DEPOT_TOOLS_METRICS DEPOT_TOOLS_UPDATE JAVA_HOME LLVM_HOME LIBCLANG_PATH \
ANDROID_HOME ANDROID_SDK_ROOT ANDROID_NDK_ROOT ANDROID_NDK_HOME ANDROID_NDK ANDROID_JAR ANDROID_PLATFORM ANDROID_API_LEVEL \
TEAMSPEACH_GRADLE_DISTRIBUTION TEAMSPEACH_BUNDLETOOL SKIA_SOURCE_DIR SKIA_GN_COMMAND SKIA_NINJA_COMMAND SKIA_FORCE_BUILD; do
[[ "${!name}" != *$'\n'* && "${!name}" != *$'\r'* ]] || fail "invalid multiline environment value: $name"
printf '%s=%s\n' "$name" "${!name}" >> "$GITHUB_ENV"
done
printf '%s\n' "$CARGO_HOME/bin" "$JAVA_HOME/bin" "$LLVM_HOME/bin" \
"$ANDROID_SDK_ROOT/cmdline-tools/$sdk_tools_version/bin" "$ANDROID_SDK_ROOT/build-tools/$build_tools" "$ANDROID_SDK_ROOT/platform-tools" >> "$GITHUB_PATH"
printf 'Android CI tools provisioned in %s (no build, signing or publication performed by setup).\n' "$tools"
+345 -230
View File
@@ -1,230 +1,345 @@
# Trusted manual runs only. Inventory uses the existing generic runner;
# full builds require an administrator-provisioned Linux x64 Android runner.
# Neither mode installs host tools, publishes, or uses a device.
name: android-ci
on:
workflow_dispatch:
inputs:
mode:
description: Inventory only, or full Android build on the dedicated runner
required: true
default: inventory
type: choice
options:
- inventory
- build
permissions:
contents: read
defaults:
run:
shell: bash
working-directory: ${{ github.workspace }}/android-${{ github.run_id }}
jobs:
runner-inventory:
if: ${{ github.event.inputs.mode != 'build' }}
runs-on: ubuntu-latest
timeout-minutes: 5
defaults:
run:
working-directory: ${{ github.workspace }}
env:
CONFIG_ANDROID_SDK_ROOT: ${{ vars.ANDROID_SDK_ROOT }}
CONFIG_ANDROID_JAVA_HOME: ${{ vars.ANDROID_JAVA_HOME }}
CONFIG_NATIVE_LLVM_HOME: ${{ vars.NATIVE_LLVM_HOME }}
CONFIG_NATIVE_LIBCLANG_PATH: ${{ vars.NATIVE_LIBCLANG_PATH }}
CONFIG_NATIVE_SKIA_SOURCE_DIR: ${{ vars.NATIVE_SKIA_SOURCE_DIR }}
CONFIG_ANDROID_GRADLE_DISTRIBUTION: ${{ vars.ANDROID_GRADLE_DISTRIBUTION }}
CONFIG_ANDROID_BUNDLETOOL: ${{ vars.ANDROID_BUNDLETOOL }}
steps:
# No checkout, downloads, env dump, secret access, build or installation.
- name: Inspect available runner resources and Android prerequisites
run: |
set -euo pipefail
printf 'OS=%s ARCH=%s\n' "$(uname -s)" "$(uname -m)"
printf 'CPU_COUNT=%s\n' "$(getconf _NPROCESSORS_ONLN)"
df -Pk .
if [ -r /proc/meminfo ]; then
while IFS=: read -r key value; do
case "$key" in
MemTotal|MemAvailable|SwapTotal|SwapFree|CommitLimit|Committed_AS) printf '%s:%s\n' "$key" "$value" ;;
esac
done < /proc/meminfo
fi
for file in /sys/fs/cgroup/memory.max /sys/fs/cgroup/memory.current /sys/fs/cgroup/memory.swap.max /sys/fs/cgroup/cpu.max /sys/fs/cgroup/memory/memory.limit_in_bytes /sys/fs/cgroup/memory/memory.usage_in_bytes /sys/fs/cgroup/cpu/cpu.cfs_quota_us /sys/fs/cgroup/cpu/cpu.cfs_period_us; do
if [ -r "$file" ]; then printf '%s=' "$file"; cat "$file"; fi
done
for tool in cargo rustc rustup git cmake ninja python3 pkg-config clang clang++ ar llvm-strip llvm-readelf java javac jar keytool jarsigner sh zipalign aapt2 apksigner sdkmanager node; do
if command -v "$tool" >/dev/null 2>&1; then printf 'TOOL %s=present\n' "$tool"; else printf 'TOOL %s=missing-from-PATH\n' "$tool"; fi
done
for tool in java javac clang cmake ninja; do
if command -v "$tool" >/dev/null 2>&1; then
printf 'VERSION %s\n' "$tool"
case "$tool" in java|javac) flag=-version ;; *) flag=--version ;; esac
timeout 10s "$tool" "$flag" 2>&1 || printf 'VERSION %s=unavailable\n' "$tool"
fi
done
# Never invoke rustup proxies: even --version can auto-install a toolchain.
rust_home="${RUSTUP_HOME:-$HOME/.rustup}"
rust_found=false
for toolchain in "$rust_home"/toolchains/1.96.0-*; do
if [ -x "$toolchain/bin/rustc" ]; then
rust_found=true
printf 'RUST_1_96_0=present\n'
if [ -d "$toolchain/lib/rustlib/aarch64-linux-android/lib" ]; then printf 'RUST_ANDROID_TARGET=present\n'; else printf 'RUST_ANDROID_TARGET=missing\n'; fi
fi
done
if [ "$rust_found" = false ]; then printf 'RUST_1_96_0=not-found-in-rustup-home\n'; fi
for name in ANDROID_SDK_ROOT ANDROID_JAVA_HOME NATIVE_LLVM_HOME NATIVE_LIBCLANG_PATH NATIVE_SKIA_SOURCE_DIR ANDROID_GRADLE_DISTRIBUTION ANDROID_BUNDLETOOL; do
key="CONFIG_$name"
if [ -z "${!key:-}" ]; then
printf 'VARIABLE %s=unset\n' "$name"
elif [ -e "${!key}" ]; then
printf 'VARIABLE %s=set,path-exists\n' "$name"
else
printf 'VARIABLE %s=set,path-missing\n' "$name"
fi
done
# Inspect only explicitly configured or inherited tool roots, never home/profile contents.
for name in ANDROID_HOME ANDROID_SDK_ROOT ANDROID_NDK_ROOT JAVA_HOME LLVM_HOME LIBCLANG_PATH SKIA_SOURCE_DIR; do
if [ -n "${!name:-}" ]; then printf 'RUNNER_ENV %s=set\n' "$name"; else printf 'RUNNER_ENV %s=unset\n' "$name"; fi
done
sdk="${CONFIG_ANDROID_SDK_ROOT:-${ANDROID_SDK_ROOT:-${ANDROID_HOME:-}}}"
if [ -n "$sdk" ]; then
for relative in platforms/android-36/android.jar build-tools/36.0.0/aapt2 ndk/28.2.13676358/source.properties; do
if [ -f "$sdk/$relative" ]; then printf 'SDK %s=present\n' "$relative"; else printf 'SDK %s=missing\n' "$relative"; fi
done
else
printf 'SDK=unknown,no-configured-root\n'
fi
skia="${CONFIG_NATIVE_SKIA_SOURCE_DIR:-${SKIA_SOURCE_DIR:-}}"
if [ -n "$skia" ]; then
for relative in BUILD.gn bin/gn third_party/externals; do
if [ -e "$skia/$relative" ]; then printf 'SKIA %s=present\n' "$relative"; else printf 'SKIA %s=missing\n' "$relative"; fi
done
else
printf 'SKIA=unknown,no-configured-root\n'
fi
printf 'INVENTORY_ONLY: no build, installation, signing, publication or device access\n'
android-arm64:
if: ${{ github.event.inputs.mode == 'build' }}
runs-on: teamspeach-android-linux-x64
env:
CARGO_TERM_COLOR: never
TARGET: aarch64-linux-android
EXPECTED_REVISION: ${{ github.sha }}
CI_RUN_ID: ${{ github.run_id }}
CARGO_TARGET_DIR: ${{ github.workspace }}/android-${{ github.run_id }}/target
GRADLE_USER_HOME: ${{ github.workspace }}/android-${{ github.run_id }}/.gradle-ci
ANDROID_HOME: ${{ vars.ANDROID_SDK_ROOT }}
ANDROID_SDK_ROOT: ${{ vars.ANDROID_SDK_ROOT }}
JAVA_HOME: ${{ vars.ANDROID_JAVA_HOME }}
LLVM_HOME: ${{ vars.NATIVE_LLVM_HOME }}
LIBCLANG_PATH: ${{ vars.NATIVE_LIBCLANG_PATH }}
SKIA_SOURCE_DIR: ${{ vars.NATIVE_SKIA_SOURCE_DIR }}
TEAMSPEACH_GRADLE_DISTRIBUTION: ${{ vars.ANDROID_GRADLE_DISTRIBUTION }}
TEAMSPEACH_BUNDLETOOL: ${{ vars.ANDROID_BUNDLETOOL }}
steps:
- uses: actions/checkout@v4
with:
path: android-${{ github.run_id }}
clean: true
persist-credentials: false
- name: Require provisioned Linux Android tools (no host installation)
run: |
set -euo pipefail
test "$(uname -s)" = Linux
test "$(uname -m)" = x86_64
test "$(git rev-parse HEAD)" = "$EXPECTED_REVISION"
: "${ANDROID_SDK_ROOT:?set ANDROID_SDK_ROOT to installed SDK36 with build-tools/36.0.0 and NDK28.2.13676358}"
: "${JAVA_HOME:?set ANDROID_JAVA_HOME to installed JDK17+ (JDK21 is supported)}"
: "${LLVM_HOME:?set NATIVE_LLVM_HOME to installed LLVM}"
: "${LIBCLANG_PATH:?set NATIVE_LIBCLANG_PATH to the matching libclang directory}"
: "${SKIA_SOURCE_DIR:?set NATIVE_SKIA_SOURCE_DIR to a dependency-synchronized Skia checkout}"
: "${TEAMSPEACH_GRADLE_DISTRIBUTION:?set ANDROID_GRADLE_DISTRIBUTION to local gradle-8.14.3-bin.zip}"
: "${TEAMSPEACH_BUNDLETOOL:?set ANDROID_BUNDLETOOL to local bundletool.jar}"
export ANDROID_NDK_ROOT="$ANDROID_SDK_ROOT/ndk/28.2.13676358"
export ANDROID_NDK_HOME="$ANDROID_NDK_ROOT"
export PATH="$JAVA_HOME/bin:$LLVM_HOME/bin:$ANDROID_SDK_ROOT/build-tools/36.0.0:$PATH"
for tool in cargo rustc rustup git cmake ninja python3 pkg-config clang clang++ ar llvm-strip llvm-readelf java javac jar keytool jarsigner sh zipalign aapt2 apksigner; do
command -v "$tool"
done
test -f "$ANDROID_SDK_ROOT/platforms/android-36/android.jar"
test -f "$ANDROID_NDK_ROOT/source.properties"
test -x "$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android26-clang"
test -f "$SKIA_SOURCE_DIR/BUILD.gn"
test -x "$SKIA_SOURCE_DIR/bin/gn"
test -d "$SKIA_SOURCE_DIR/third_party/externals"
test -f "$TEAMSPEACH_BUNDLETOOL"
test -d "$(rustc --print target-libdir --target "$TARGET")"
# A clean checkout and run-specific Cargo/Gradle/output trees prevent stale
# packages or dependency receipts from another job/revision being selected.
test ! -e target
test ! -e dist/android
test ! -e .gradle-ci
python3 - <<'PY'
import hashlib, os, pathlib, re, subprocess
ndk = pathlib.Path(os.environ['ANDROID_NDK_ROOT'], 'source.properties').read_text()
assert re.search(r'^Pkg\.Revision\s*=\s*28\.2\.13676358\s*$', ndk, re.M), 'NDK must match Gradle ndkVersion'
java = subprocess.check_output(['java', '-version'], stderr=subprocess.STDOUT, text=True)
assert int(re.search(r'version "(\d+)', java)[1]) >= 17, 'JDK17+ is required'
assert list(pathlib.Path(os.environ['LIBCLANG_PATH']).glob('libclang.so*')), 'matching LLVM libclang.so is required'
properties = pathlib.Path('platform/android/gradle/wrapper/gradle-wrapper.properties').read_text()
expected = re.search(r'^distributionSha256Sum=(\w+)$', properties, re.M)[1]
with open(os.environ['TEAMSPEACH_GRADLE_DISTRIBUTION'], 'rb') as source:
digest = hashlib.sha256()
for chunk in iter(lambda: source.read(1024 * 1024), b''):
digest.update(chunk)
assert digest.hexdigest() == expected, 'local Gradle zip checksum mismatch'
# No signing configuration is consumed from a dedicated runner's environment.
for name in ('TEAMSPEACH_ANDROID_KEYSTORE', 'TEAMSPEACH_ANDROID_STORE_PASSWORD', 'TEAMSPEACH_ANDROID_KEY_ALIAS', 'TEAMSPEACH_ANDROID_KEY_PASSWORD'):
assert name not in os.environ, 'remove production signing environment from this unsigned runner'
PY
echo "ANDROID_NDK_ROOT=$ANDROID_NDK_ROOT" >> "$GITHUB_ENV"
echo "ANDROID_NDK_HOME=$ANDROID_NDK_HOME" >> "$GITHUB_ENV"
echo "$JAVA_HOME/bin" >> "$GITHUB_PATH"
echo "$LLVM_HOME/bin" >> "$GITHUB_PATH"
echo "$ANDROID_SDK_ROOT/build-tools/36.0.0" >> "$GITHUB_PATH"
echo "SKIA_GN_COMMAND=$SKIA_SOURCE_DIR/bin/gn" >> "$GITHUB_ENV"
echo "SKIA_NINJA_COMMAND=$(command -v ninja)" >> "$GITHUB_ENV"
- name: Check workspace version and packaging behavior
run: |
set -euo pipefail
cargo run --locked -p xtask -- check-version
cargo test --locked -p xtask
- name: Build pinned Android WebRTC from source on Linux
run: cargo run --locked -p xtask -- deps --target "$TARGET" --llvm-dir "$LLVM_HOME"
- name: Build and verify harness (full Skia + WebRTC)
run: bash .gitea/build-android-variant.sh harness
- name: Retain installable test-only ARM64 harness and exact receipts
uses: actions/upload-artifact@v3
with:
name: android-harness-arm64
path: |
android-${{ github.run_id }}/dist/android/harness/*-harness-test.apk
android-${{ github.run_id }}/dist/android/harness/build-info.json
android-${{ github.run_id }}/dist/android/harness/aarch64-linux-android/*.json
if-no-files-found: error
- name: Build and verify unsigned production (full Skia + WebRTC)
run: bash .gitea/build-android-variant.sh production
- name: Retain unsigned production ARM64 APK and store AAB (not installable)
uses: actions/upload-artifact@v3
with:
name: android-production-unsigned-arm64
path: |
android-${{ github.run_id }}/dist/android/production/*-unsigned.apk
android-${{ github.run_id }}/dist/android/production/*-unsigned.aab
android-${{ github.run_id }}/dist/android/production/build-info.json
android-${{ github.run_id }}/dist/android/production/aarch64-linux-android/*.json
if-no-files-found: error
# Trusted mobile-branch pushes only; never execute fork pull requests on the shared runner.
# Installs occur only inside the disposable Ubuntu container. No releases or phone actions.
name: android-ci
on:
push:
branches: [feature/mobile-port]
workflow_dispatch:
inputs:
mode:
description: Build the test APK, or inspect resources only
required: true
default: build
type: choice
options: [build, inventory]
permissions:
contents: read
defaults:
run:
shell: bash
jobs:
android-arm64:
runs-on: ubuntu-latest
container:
image: ubuntu:24.04
timeout-minutes: 360
env:
TARGET: aarch64-linux-android
EXPECTED_REVISION: ${{ github.sha }}
CI_RUN_ID: ${{ github.run_id }}
ANDROID_CI_PROVISION: container
CARGO_TERM_COLOR: never
TEAMSPEACH_ANDROID_LOW_MEMORY: "false"
CARGO_TARGET_DIR: ${{ github.workspace }}/.android-ci/cargo-target
steps:
- name: Resource gate before checkout, cache restore or tool installation
id: resources
run: |
set -euo pipefail
test "$(uname -s)" = Linux
test "$(uname -m)" = x86_64
test -f /.dockerenv
printf 'Architecture: '; uname -m
printf 'CPU count: '; getconf _NPROCESSORS_ONLN
df -Pk . /
while IFS=: read -r key value; do
case "$key" in MemTotal|MemAvailable) printf '%s:%s\n' "$key" "$value" ;; esac
done < /proc/meminfo
if [ '${{ github.event.inputs.mode }}' = inventory ]; then exit 0; fi
for path in . /; do
free=$(df --output=avail -B1 "$path")
free=${free##*$'\n'}
if ! [[ "$free" =~ ^[[:space:]]*[0-9]+[[:space:]]*$ ]] || (( free < 107374182400 )); then
echo "BLOCKED: Android cold source build requires 100 GiB free on workspace and container root; no tools installed. Ask runner administrator for build storage."
exit 1
fi
done
available=0
while read -r key value unit; do if [ "$key" = MemAvailable: ]; then available=$value; fi; done < /proc/meminfo
if (( available < 8388608 )); then echo 'BLOCKED: at least 8 GiB available RAM required'; exit 1; fi
jobs=$(nproc)
[[ "$jobs" =~ ^[1-9][0-9]*$ ]] || { echo 'Cannot determine available runner CPUs'; exit 1; }
printf 'Using all available runner CPUs: %s Cargo/Ninja/CMake jobs\n' "$jobs"
printf 'CARGO_BUILD_JOBS=%s\nCMAKE_BUILD_PARALLEL_LEVEL=%s\n' "$jobs" "$jobs" >> "$GITHUB_ENV"
- name: Bootstrap utilities inside the disposable job container
if: ${{ github.event.inputs.mode != 'inventory' }}
run: |
set -euo pipefail
test -f /.dockerenv
test "$(id -u)" = 0
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y --no-install-recommends ca-certificates git nodejs python3 zstd
- uses: actions/checkout@v4
if: ${{ github.event.inputs.mode != 'inventory' }}
with:
clean: true
persist-credentials: false
# Keep provisioned tools/registry sources separate from completed Cargo outputs.
- name: Restore isolated tool and Cargo source cache
if: ${{ github.event.inputs.mode != 'inventory' }}
id: cache
uses: actions/cache/restore@v3
with:
path: |
.android-ci/tools/downloads
.android-ci/tools/rustup
.android-ci/tools/cargo
.android-ci/tools/android-sdk
.android-ci/tools/skia-m153-0.101.2
.android-ci/tools/gradle
# Lock changes may need new registry sources, not a new SDK/toolchain.
# v3 starts one cold generation: v2 has no independently verifiable tool contract.
key: android-tools-linux-x64-arm64-v3-${{ hashFiles('.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh', 'rust-toolchain.toml', 'platform/android/gradle/wrapper/gradle-wrapper.properties') }}-${{ hashFiles('Cargo.lock') }}-${{ github.sha }}-${{ github.run_id }}
restore-keys: |
android-tools-linux-x64-arm64-v3-${{ hashFiles('.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh', 'rust-toolchain.toml', 'platform/android/gradle/wrapper/gradle-wrapper.properties') }}-${{ hashFiles('Cargo.lock') }}-
android-tools-linux-x64-arm64-v3-${{ hashFiles('.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh', 'rust-toolchain.toml', 'platform/android/gradle/wrapper/gradle-wrapper.properties') }}-
- name: Provision pinned Android tools in the job container
if: ${{ github.event.inputs.mode != 'inventory' }}
id: tools
run: bash .gitea/setup-android-ci.sh
# Setup publishes the pinned environment before compatibility is computed.
# Never cross the opaque v1 application identity: one cold v2 generation.
- name: Compute isolated application cache identity
if: ${{ github.event.inputs.mode != 'inventory' }}
id: application-key
run: python3 .gitea/android-application-cache.py key
- name: Restore completed application compilation
if: ${{ github.event.inputs.mode != 'inventory' }}
id: application-cache
uses: actions/cache/restore@v3
with:
path: |
.android-ci/cargo-target
.android-ci/application-cache-inputs.json
key: ${{ steps.application-key.outputs.key }}-${{ github.sha }}-${{ github.run_id }}
restore-keys: |
${{ steps.application-key.outputs.key }}-${{ github.sha }}-
${{ steps.application-key.outputs.key }}-
${{ steps.application-key.outputs.previous-parallelism-key }}-
- name: Restore timestamps only for content-matched Cargo source inputs
if: ${{ github.event.inputs.mode != 'inventory' }}
run: python3 .gitea/android-application-cache.py sources
- name: Require exact revision and no production signing
if: ${{ github.event.inputs.mode != 'inventory' }}
run: |
set -euo pipefail
test "$(git rev-parse HEAD)" = "$EXPECTED_REVISION"
test ! -e dist/android
for name in TEAMSPEACH_ANDROID_KEYSTORE TEAMSPEACH_ANDROID_STORE_PASSWORD TEAMSPEACH_ANDROID_KEY_ALIAS TEAMSPEACH_ANDROID_KEY_PASSWORD; do
if [[ -v "$name" ]]; then echo 'Production signing environment forbidden in test CI'; exit 1; fi
done
cargo run --locked -p xtask -- check-version
cargo test --locked -p xtask
- name: Compute source dependency cache identity
if: ${{ github.event.inputs.mode != 'inventory' }}
id: dependency-key
run: |
python3 - <<'PY'
import hashlib, json, os, pathlib
policy = json.loads(pathlib.Path('native/native-deps.lock.json').read_text())
policy.pop('builds', None)
digest = hashlib.sha256(json.dumps(policy, sort_keys=True, separators=(',', ':')).encode())
for name in ('.gitea/android-ci-tools.json', 'xtask/src/deps.rs', 'xtask/src/build_native.rs'):
digest.update(name.encode() + b'\0' + pathlib.Path(name).read_bytes())
with open(os.environ['GITHUB_OUTPUT'], 'a') as out:
out.write('key=android-webrtc-linux-arm64-v1-' + digest.hexdigest() + '\n')
PY
- name: Restore pinned WebRTC source and object checkpoint
if: ${{ github.event.inputs.mode != 'inventory' }}
id: webrtc-cache
uses: actions/cache/restore@v3
with:
path: target/native-deps/aarch64-linux-android
key: ${{ steps.dependency-key.outputs.key }}
# Source provenance is regenerated and verified, never trusted from an Actions cache.
- name: Build pinned WebRTC dependencies with bounded CI parallelism
if: ${{ github.event.inputs.mode != 'inventory' }}
id: dependencies
run: |
set -euo pipefail
python3 .gitea/prepare-android-dependency-cache.py
cargo run --locked -p xtask -- deps --target "$TARGET" --llvm-dir "$LLVM_HOME" --jobs "$CARGO_BUILD_JOBS"
python3 .gitea/android-application-cache.py dependencies
- name: Checkpoint verified WebRTC before application build
if: ${{ success() && github.event.inputs.mode != 'inventory' && steps.webrtc-cache.outputs.cache-hit != 'true' }}
uses: actions/cache/save@v3
with:
path: target/native-deps/aarch64-linux-android
key: ${{ steps.dependency-key.outputs.key }}
- name: Checkpoint provisioned tools before application build
if: ${{ success() && github.event.inputs.mode != 'inventory' && steps.cache.outputs.cache-hit != 'true' }}
uses: actions/cache/save@v3
with:
path: |
.android-ci/tools/downloads
.android-ci/tools/rustup
.android-ci/tools/cargo
.android-ci/tools/android-sdk
.android-ci/tools/skia-m153-0.101.2
.android-ci/tools/gradle
key: ${{ steps.cache.outputs.cache-primary-key }}-checkpoint
# Host tests use neither Android artifacts nor Skia/WebRTC. The APK below keeps all features.
- name: Install Linux host audio test prerequisites in container
if: ${{ github.event.inputs.mode != 'inventory' }}
run: |
set -euo pipefail
test -f /.dockerenv
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y --no-install-recommends libpipewire-0.3-dev libspa-0.2-dev libxkbcommon-x11-dev libxcb-shape0-dev libxcb-xfixes0-dev
- name: Restore isolated Linux audio test compilation
if: ${{ github.event.inputs.mode != 'inventory' }}
id: audio-test-cache
uses: actions/cache/restore@v3
with:
path: .android-ci/host-audio-target
key: host-audio-linux-x64-v1-${{ hashFiles('rust-toolchain.toml', 'Cargo.lock', '.cargo/config.toml', '.gitea/workflows/android.yml') }}-${{ github.sha }}-${{ github.run_id }}
restore-keys: |
host-audio-linux-x64-v1-${{ hashFiles('rust-toolchain.toml', 'Cargo.lock', '.cargo/config.toml', '.gitea/workflows/android.yml') }}-
- name: Run actual native audio worker and capture authorization regressions
if: ${{ github.event.inputs.mode != 'inventory' }}
id: audio-tests
env:
CARGO_TARGET_DIR: ${{ github.workspace }}/.android-ci/host-audio-target
CARGO_PROFILE_TEST_OPT_LEVEL: "1"
CARGO_PROFILE_TEST_DEBUG: "0"
run: |
set -euo pipefail
unset RUSTC_WORKSPACE_WRAPPER
mkdir -p .android-ci/audio-test-results
{
printf 'Revision: %s\nHost: x86_64-unknown-linux-gnu\nFeatures: no-default-features (test binary only)\n' "$EXPECTED_REVISION"
rustc --edition=2021 --test native/vendor/cpal-0.18.2/src/host/aaudio/device_catalog.rs -o .android-ci/audio-test-results/device-catalog-tests
.android-ci/audio-test-results/device-catalog-tests --test-threads=1
rustc --edition=2021 --test native/vendor/cpal-0.18.2/src/host/aaudio/capture_timing.rs -o .android-ci/audio-test-results/capture-timing-tests
.android-ci/audio-test-results/capture-timing-tests --test-threads=1
rustc --edition=2021 --test native/vendor/cpal-0.18.2/src/host/aaudio/output_usage.rs -o .android-ci/audio-test-results/output-usage-tests
.android-ci/audio-test-results/output-usage-tests --test-threads=1
rustc --edition=2021 --test native/vendor/cpal-0.18.2/src/host/aaudio/stream_start.rs -o .android-ci/audio-test-results/stream-start-tests
.android-ci/audio-test-results/stream-start-tests --test-threads=1
rustc --edition=2021 --test native/vendor/cpal-0.18.2/src/host/aaudio/output_clock.rs -o .android-ci/audio-test-results/output-clock-tests
.android-ci/audio-test-results/output-clock-tests --test-threads=1
mkdir -p .android-ci/audio-test-results/java
javac -d .android-ci/audio-test-results/java platform/android/src/main/java/dev/teamspeach/mobile/CommunicationRoutePolicy.java platform/android/src/test/java/dev/teamspeach/mobile/CommunicationRoutePolicyTest.java
java -cp .android-ci/audio-test-results/java dev.teamspeach.mobile.CommunicationRoutePolicyTest
cargo test --locked -p teamspeach-denoise --target x86_64-unknown-linux-gnu --lib capture::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib media::audio:: --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib capture_transition_tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib audit_lifecycle --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib android_call_authorization --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib only_explicit_output_device_actions_request_platform_routing --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib android_attachment_ --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib app::connections::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib ui::theme::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib services::prefs::tests::android_palette --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib ui::shell::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib ui::i18n::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib ui::settings::tests::communication_routes --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
cargo test --locked -p teamspeach-core --target x86_64-unknown-linux-gnu --lib audio::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
cargo test --locked -p teamspeach-core --target x86_64-unknown-linux-gnu --lib output::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
} 2>&1 | tee .android-ci/audio-test-results/tests.log
- name: Save successful Linux audio test compilation
if: ${{ success() && steps.audio-tests.outcome == 'success' && steps.audio-test-cache.outputs.cache-hit != 'true' }}
uses: actions/cache/save@v3
with:
path: .android-ci/host-audio-target
key: ${{ steps.audio-test-cache.outputs.cache-primary-key }}
- name: Retain actual host audio test results
if: ${{ always() && steps.audio-tests.outcome != 'skipped' && github.event.inputs.mode != 'inventory' }}
uses: actions/upload-artifact@v3
with:
name: native-audio-tests-linux-x64-${{ github.sha }}
path: .android-ci/audio-test-results/tests.log
if-no-files-found: warn
retention-days: 14
- name: Build and verify full-feature test APK
if: ${{ github.event.inputs.mode != 'inventory' }}
id: application-build
run: |
set -euo pipefail
unset RUSTC_WORKSPACE_WRAPPER
mkdir -p .android-ci/diagnostics
bash .gitea/android-memory-report.sh | tee .android-ci/diagnostics/before.txt
trap 'status=$?; trap - EXIT; bash .gitea/android-memory-report.sh | tee .android-ci/diagnostics/after.txt; exit "$status"' EXIT
/usr/bin/time -v -o .android-ci/diagnostics/build-time.txt bash .gitea/build-android-variant.sh harness
# Save immediately after compilation/package verification, not after uploads.
# always()+outcome also checkpoints a successful APK if later diagnostics fail.
- name: Record stable inputs of the completed application build
if: ${{ always() && steps.application-build.outcome == 'success' && github.event.inputs.mode != 'inventory' }}
id: application-snapshot
run: python3 .gitea/android-application-cache.py snapshot
- name: Save completed application compilation
if: ${{ always() && steps.application-snapshot.outcome == 'success' && steps.application-cache.outputs.cache-hit != 'true' && github.event.inputs.mode != 'inventory' }}
uses: actions/cache/save@v3
with:
path: |
.android-ci/cargo-target
.android-ci/application-cache-inputs.json
key: ${{ steps.application-cache.outputs.cache-primary-key }}
- name: Report container memory evidence on build failure
if: ${{ always() && steps.tools.outcome == 'success' && github.event.inputs.mode != 'inventory' }}
run: |
set -eu
if [ -f .android-ci/diagnostics/build-time.txt ]; then cat .android-ci/diagnostics/build-time.txt; fi
bash .gitea/android-memory-report.sh
- name: Retain native compiler resource diagnostics
if: ${{ always() && steps.tools.outcome == 'success' && github.event.inputs.mode != 'inventory' }}
uses: actions/upload-artifact@v3
with:
name: android-build-resources-${{ github.sha }}
path: .android-ci/diagnostics/*.txt
if-no-files-found: warn
retention-days: 7
- name: Upload installable Android test APK and provenance
if: ${{ github.event.inputs.mode != 'inventory' }}
uses: actions/upload-artifact@v3
with:
name: android-harness-arm64-${{ github.sha }}
path: |
dist/android/harness/*-harness-test.apk
dist/android/harness/build-info.json
dist/android/harness/aarch64-linux-android/*.json
if-no-files-found: error
retention-days: 14
- name: Save populated tool and Cargo source cache
if: ${{ always() && steps.application-build.outcome == 'success' && github.event.inputs.mode != 'inventory' && steps.cache.outputs.cache-hit != 'true' }}
uses: actions/cache/save@v3
with:
path: |
.android-ci/tools/downloads
.android-ci/tools/rustup
.android-ci/tools/cargo
.android-ci/tools/android-sdk
.android-ci/tools/skia-m153-0.101.2
.android-ci/tools/gradle
key: ${{ steps.cache.outputs.cache-primary-key }}
+1
View File
@@ -8,6 +8,7 @@ dist/
# Native Cargo artifacts
target/
core/target/
.android-ci/
# local runtime data, logs and identities
*.log
+8
View File
@@ -16,5 +16,13 @@
"xtask/src/package.rs"
],
"fingerprintBaselineCommit": "a761afaa43dddbdf78c70afb2546c79c3b1289e5",
"partialArchitectureUpdates": [{
"baseRevision": "6e5c831940dff96ca94b7ff76893558f162b20e3",
"workingTreeSnapshot": true,
"scope": "native audio lifecycle and authorization",
"files": ["native/src/media/audio/lifecycle.rs", "native/src/media/audio/engine.rs", "native/src/media/audio/devices.rs", "native/src/app/connections.rs", "native/src/app/runtime/context_helpers.rs"],
"navigation": "engine.rs::Worker::lifecycle services live PCM while lifecycle.rs owns CPAL construct/start/drop, DSP construction and notification preparation. devices.rs StreamOwner never leaves lifecycle thread. ConnectionManager publishes acknowledged capture_revision/configuration and current_capture_permit validates live core epoch. Runtime reconciles same-owner permit changes without blind retries.",
"graphWarning": "knowledge-graph.json remains the old full scan: engine single-worker ownership summaries and function line ranges are stale. This targeted navigation override does not mark the whole graph current; auto-update remains disabled."
}],
"note": "Граф актуализирован по незакоммиченному рабочему дереву. Штатный incremental save отказал из-за dirty tree; fingerprints/scan baseline оставлены прежними для следующего воспроизводимого обновления после коммита."
}
+520 -405
View File
@@ -1,405 +1,520 @@
# Changelog
## Unreleased
- Built the first full Skia/WebRTC Android ARM64 test APK in authorized WSL2. Verified APK v2 signing,
16-KiB alignment, native ISA/imports, resources and exported WebRTC JNI symbols; no device run claimed.
- Fixed Android build integration: use the complete NDK r28c rather than Chromium's sysroot-only subset,
copy the matching WebRTC jar to Cargo's actual output directory, retain JNI exports in the final cdylib,
pin Gradle launcher LF/build-tools36, and use the public AppOps permission-change observer.
Corrected the pinned Slint NonNull pointer conversion in Android accessibility.
- Implemented Android call-scoped audio recovery: focus/route changes revoke microphone authorization,
restore receive-only playback when permitted, and reject stale lease/revision callbacks. Communication
mode and Android 12+ communication-device notifications follow the active foreground call.
- Android network capability refreshes no longer masquerade as network handoffs. Added the missing
privacy-approved external-link adapter; SAF filename collisions offer a new destination, and identity
exports use private staging and the provider commit/partial-cleanup contract rather than direct writes.
- Adapted the Android phone shell: connection/tab actions, selected-target actions, compact detail
navigation and settings Back; bounded menus/forms, IME-aware chat/settings, and hold/cancel PTT.
Android APK, physical-device voice, Bluetooth/provider behavior and full parity remain unverified.
- Android Activity pause now releases touch PTT/long-press state without ending foreground screen/camera
capture. Pending playback recovery survives later microphone revocation; duplicate audio-focus gain
no longer revokes an explicitly enabled microphone.
- Android camera/projection consent remains visible until foreground handoff, pending Camera2 opens
drain before shutdown, and resize ignores obsolete ImageReader callbacks. Permission launch failures
complete requests; SAF grants validate access and close descriptors/capabilities on failed handoff.
- Added receiver instructions for building the exact mobile revision on another developer's WSL2
Linux machine, using the existing pinned-source recipe and returning the complete APK/receipt bundle.
- Fixed native Windows build environment capture for non-ASCII values by selecting UTF-8 in the
child MSVC activation shell; verified against real vcvarsall with a synthetic Cyrillic value.
- Pinned LF checkout for native dependency patches and recipe sources so Windows line-ending
conversion cannot invalidate exact patch checksums; expected lock hashes remain unchanged.
- Added a manual Android CI route producing separate full-feature ARM64 test-harness APK and unsigned
production APK/AAB bundles with source/build/dependency receipts. Windows developers do not need WSL.
Android packaging keeps offline Gradle by default; CI opts into dependency resolution explicitly and
isolates each package's Gradle outputs. CI runner provisioning and device acceptance remain unverified.
- Android CI now uploads the verified harness APK and receipts before starting production packaging,
so a later production failure does not prevent retaining the test APK. Both variants reuse one recipe.
- Android CI defaults to a bounded read-only runner inventory; full Android builds require explicit
manual selection and still use the dedicated Android runner label. Inventory never installs tools.
- Removed the Electron application, npm manifests and browser-only test/build tooling. Rust/Slint
is now the only application; native resources and versioning no longer depend on the removed tree.
Retained native profile migration and diagnostic core CLI. This cutover is not mobile runtime acceptance.
- Started the native implementation with one Cargo workspace and lockfile and pinned Rust 1.96.0.
Core/DSP dependency resolutions are preserved; the later native-only cutover removes the reference host.
- Added the native compatibility inventory; entries remain pending, not claims of feature completion.
Initial Slint software and Skia windows were exercised with a real pointer Close action;
this does not establish native voice, video, mobile support or whole-client migration completion.
- Extracted the protocol core into an embedded library with validated typed commands, joined session
lifetimes, generation-stamped events, bounded PCM and capture guards at the actual UDP-send boundary.
Diagnostic stdio remains independently usable for core inspection.
- Ported native profile import, local stores and session-bound file/icon/snapshot services. Imports retain
the original profile, preserve identity keys/UIDs and require bookmark passwords once again. Native
secret/preference pair commits recover interrupted writes; unknown staging directories are never discarded.
Windows isolated DPAPI and migration/restart smoke passed; other OS key stores and live mutations remain
separate verification gates. Snapshot format stays 0.0.1; native About labels legacy notices as historical.
- Added worker-owned CPAL audio, bounded timestamped callback queues, drift-aware Rubato conversion,
integrated Sonora AEC/NS/AGC and independent notification sinks. Capture/output revocation survives
queue congestion; source expiry remains attached through resampling to hardware presentation.
Controlled DSP/queue/permission and native worker smoke passed (generated PCM, no physical devices).
Official-peer voice, acoustic echo cancellation and mobile/Asahi hardware remain unverified.
- Added pinned source-built native WebRTC provisioning, checked desktop/mobile capture adapters and
generation-bound TS6 viewer/publisher state machines. Windows x64 CXX bridge compilation passed.
The production software decoder factory decoded synthetic H264 High, AV1, VP8 and VP9 fixtures;
all four 64×48 I420 outputs exactly matched independent FFmpeg decoding. Sustained native playback,
official TS6 peers, physical capture, hardware decode and other platforms remain separate gates.
- Proved a device-free native PeerConnection loopback through the real sender/decoder/display path
(13 decoded frames, 12 presented, terminal cleanup). Isolated WebRTC Opus symbols from the voice
core's existing codec without weakening linker checks or rewriting unrelated assembly objects.
- Rebuilt Privacy, Video, Notifications and About in the original section order. Unsupported account,
telemetry, Cisco/backend and content-report options are explicitly unavailable, never fake preferences.
Working Chromium decoder controls and installation/project details moved to linked subpages with
back-focus restoration. Report Issue uses the project's verified issue list through the external-link guard.
- Preserved native decoder-policy restart, notification overrides, trusted-site management and local
changelog/license navigation. Corrected narrow Russian update-row overlap without hiding status.
- Restored original selector wrapping, selected-preview radius clipping and whisper action tints.
Permission lists now reserve their source toolbar space and wrap badges without losing long-name
truncation; private-info descriptions and empty group states use the source sizing and spacing.
- Fixed channel right-click opening Whisper settings and silently staging a target. The normal channel
menu now leaves the current view and whisper state unchanged; only its explicit Add to Whisperlist
action stages the channel, behind the existing connection/session validity guard.
- Moved identity export and UID copy into the selected identity's context menu. Export keeps its
private-key confirmation. Disconnected nickname edits use identity Details; connected nickname
edits use the own-client information header. Removed the duplicate bookmark settings manager;
bookmarks remain editable in the sidebar.
- Language changes are saved for restart, with a cancelable restart confirmation. File-transfer
settings use the source defaults, shared rate limits and per-channel concurrency limits.
- Added generation-bound group deletion and explicit group/channel permission removal, plus the
channel icon picker. A refused icon after successful channel creation cannot create the channel
a second time; stale form/session responses do not apply to another view.
- About reports actual build metadata. Corrected identity slider layout, device-selector caption
overlap, broadcast tab/thumbnail geometry and transfer-row spacing. Migrated affected smoke scripts.
- Matched the detail header's source flex grouping, restored full-height administration panels and
bottom pagination, corrected client-list wrapping, group-badge spacing and server-info typography.
Audio device captions and broadcast title chips now use measured original text metrics.
- Whole-client pixel parity is not established; reference comparisons retain their original thresholds.
## 0.1.7 — 2026-11-02
- Matched light-theme toolbar/header/composer icon colors, header separators and chevron placement
to the installed reference. Corrected narrow chat width and input placeholder spacing.
All eight main-screen EN/RU, dark/light and wide/narrow fixture comparisons passed; this does not
establish whole-client parity or native-platform interoperability.
- Replaced the plain chat textarea with one local CodeMirror editor and the persisted Rich Text Editor
toggle. Hybrid preview uses the existing safe TS Markdown renderer; switching modes retains text,
selection and undo, while switching conversations isolates draft history. Toolbar/slash/emoji edits,
Enter/Shift+Enter, IME and refused-send preservation were exercised in the packaged offscreen app.
Constructed stylesheets keep the application CSP strict; no inline-style exception was added.
- Added the original editor's bold, italic, link, inline-code and code-block keyboard bindings.
Corrected the notification output selector's missing bottom margin using the original component rule.
- Matched list/quote authoring controls: Shift+Enter continuation, ordered/task item transitions,
Tab/Shift+Tab indentation, empty-item exit and Escape-then-Tab focus escape. Fenced code is not
mistaken for a list; quoted fences retain their quote prefix.
## 0.1.6 — 2026-11-02
Current development snapshot; full visual parity and native Asahi verification remain unfinished.
Version 0.1.5 was not published: CI rejected an empty changelog section.
- Added source-style advanced notification controls with independent persisted event choices,
confirmation before hiding advanced controls and single-event expansion.
- Corrected server-tree painting against paired hidden captures. Remaining light-theme,
narrow-layout and composer differences are not claimed fixed in this release.
- Rebuilt Identities around the original selector, inline creation/rename, selected-identity Details,
security-level controls and related bookmarks. Fixed default-profile UID leakage into selected Details,
selector popup initialization and the final improvement level briefly reverting during a list refresh.
Export and the explicit current-server nickname action remain available.
- Replaced raw File Transfer number fields with source-style keyboard/step controls that retain focus
and drafts through serialized saves. Native folder/copy restrictions, shared limits and safe defaults remain.
- Added notification category switches with real sound-policy gating, preserved per-event states and
independent event logs; concurrent state edits are serialized.
- Added nested bookmark folders with inline creation, rename, ordering, move/duplicate menus and
confirmed subtree deletion, using validated local preferences rather than a separate bookmark store.
- Extended bookmarks with a per-connection nickname, initial channel, session-bound channel drops,
startup connection and input-only startup mute. A nickname override never changes the stored identity.
- Bookmark passwords use OS-protected encryption, bound to address and server/channel purpose. Plaintext
is never persisted; Linux basic_text/unknown storage is refused. Stale metadata writes cannot overwrite
or resurrect a password, and native key-store interactions revalidate the window, bookmark and connection.
Explicit reveal, same-address duplication, address-change cleanup, restart and forgetting a password
after storage becomes unavailable were exercised with real Windows DPAPI. No live server join was performed.
- Startup bookmark enumeration is one-shot in main, so a renderer reload cannot start a second set of
connections. Automatic microphone mute is applied before connecting and never changes speaker mute.
- Added Privacy with trusted-site management and remembered confirmations; reset and concurrent
confirmation changes are serialized so an older save cannot overwrite a later reset.
- Removed the mistakenly added Remote Apps integration to honor the owner's explicit exclusion:
no listener, authorization IPC, settings page, remote-button capture or WebSocket production dependency.
- Added account-free local UID contacts and public badge artwork display. These are not myTeamSpeak
contacts, owned-badge management, cloud presence or offline messaging.
- Added server icon management bound to the listing's connection generation. Reconnecting invalidates
mutation grants; old icon/snapshot transfers cannot cancel a new session's reused transfer ID.
- Added the four-level noise-reduction control with persisted per-input settings. Processing remains
an independent implementation, not a claim of identity with TeamSpeak's private native DSP.
- Fixed key recording in the contents-layout settings host by checking the enclosing panel's visibility.
Packaged verification covers saving the binding and retaining it across an application restart.
- Isolated Mermaid rendering from the privileged application renderer; nested renderers cannot acquire
media/presentation permissions. Local diagram/math rendering and hostile-content rejection were exercised.
- Corrected smoke polling to await asynchronous IPC/import predicates instead of accepting a Promise
as a satisfied condition. Persistence checks now wait for actual saved state.
- Fixed full Changelog and Open Source Licenses pages rendering arrays as text instead of appending
their DOM nodes. Added a real offscreen navigation smoke covering document text and back-focus restoration.
- Whispers follow the original manager: Live Preview highlights the current list's clients and channels in
the server tree (resolved from the current snapshot only), "Switch to Server and Overlay" shows the list
next to the microphone's server, and the status bar Whisper History lists received whispers with Delete.
Replies and avatars use only entries whose client id and UID are still on the same server session.
- Key Bindings follow the original page: "Require exact key match" toggle, named profiles (inline
"New Profile Name" editor, rename, choose, Activate, delete of inactive profiles) and every official
hotkey action, each running the app's real operation. Push-to-mute stops sending without touching your
mute choice; global push-to-talk survives window focus loss while local keys still release on it. Go Live
opens the broadcast source chooser instead of guessing the focused application. Bindings can be in-window,
or global; with exact matching off, global keys also register their
extra-modifier combinations. keybinds.json moves to version 2; version 1 whisper bindings migrate unchanged
into one active profile and the original file is kept as `keybinds.v1-<time>.json`.
- Reworked the interface against the actual installed TeamSpeak frontend rather than the earlier
hand-reconstructed component sheet: original non-brand SVG artwork, Noto Sans 2.013, channel and
client chat layouts, membership event rows, sidebar actions, in-pane administration, settings
dropdowns/sliders and the two-stage broadcast dialog. Independent branding and account-free
behavior remain. Artwork provenance does not grant redistribution rights.
- Corrected sidebar group geometry and moved New Connection into its own account-free action slot;
bookmark add/search/disclosure retain their real persistence/navigation behavior. Language and sidebar
icon-mode selectors use original local artwork, content-based widths and restored keyboard focus.
Audio device captions use the observed system-default alias, not an inferred physical device.
- Matched device-field, VAD selector, slider, record-test and display-preview geometry to source values.
Fixed the chat spacer to use the composer's content-box height, removing a two-pixel full-history offset.
- Preserve a bottom-pinned chat on window reflow without forcing readers of older history to the end.
The regression reproduced a 119px gap after narrowing; the packaged fix retains a zero gap and
separately preserves the history reader's position. The paired harness retains this behavioral check.
- Match chat scrollbar safe-area width and system-event wrapping to the actual original renderer;
restore the localized empty-chat prompt with real draft/send-state visibility. Narrow composer tools
now overflow into working ordered menus rather than clipping. Settings categories occupy the original
narrow-sidebar position below Servers/New Connection, with source-sized previews and server columns.
- Correct empty-chat prompt geometry with the measured 22px glyph and the secondary-pane contrast
background. The focused dark/en wide-screen chat region passes; the whole screen still fails other regions.
- Use the original Russian bookmark-help wording (`Добавьте`), preserving the same save/connect behavior.
- Run both sides of visual QA with Electron's normal acceleration policy. Earlier reference captures
forced software rendering while the product did not; those comparisons remain historical evidence,
not directly comparable pixel baselines for the corrected capture policy.
- Actual whole-screen comparison still does not meet the 1:1 acceptance criterion. The refreshed 168-pair
run has no blocked captures but no fully passing screen pairs. Viewport-only timestamp comparison and
nested native-caption exclusions now avoid earlier harness false positives; thresholds are unchanged.
See `docs/evidence/official-parity/qa-parity-harness.md` for build-specific results and remaining differences.
- Initialize custom controls explicitly at renderer startup, not when audio/notification modules
import the slider helper. The Node suite and focused packaged chat/control smoke checks pass;
this does not establish complete visual or native platform parity.
- Added local TS6 theme extensions (Settings → Appearance → User Theme): the official `package.json`
schema, `<identifier>//<variant>` selection, stock fallback and a five-minute list cache with Reload.
Files load only through the restricted `tsext:` scheme (selected variant CSS, fonts, images, previews);
`@import`, remote URLs, links and path traversal are rejected and reads are bounded. Account-free; no
store or Remote Apps. Compatibility covers the package format and `--tsv-*` tokens, not official DOM
class hooks.
- Added account-free local identity management: additive import, selected-identity export, per-identity
names/nicknames, default and bookmark selection, guarded deletion, and resumable/cancellable bounded
security-level improvement. Active connections retain their chosen identity.
- Added simultaneous connection records with one isolated native core per server, explicit viewed/input
connection routing, connection-local chat, streams, recording and administrative operations.
- Added channel/server administration, local whisper lists and held targets, general legacy file browsing
and transfers, server snapshots, recording, notifications, and OS-specific local settings. Available
functionality and unverified native protocol branches are listed separately in the compatibility matrix.
- Migrated audio preferences to per-device capture/playback profiles and the official piecewise dB fader;
existing voice choices are converted on load. Automatic/hybrid/level activation, PTT release delay,
notification routing and independent processing are implemented without claiming native-DSP identity.
- Added connection/identity-scoped disk chat history, independent drafts/unread state, local rich text,
emoji/math/diagrams and server-file links. Remote images require explicit consent; account-only Matrix
editing, reactions and read receipts are not included. Local vendor assets carry redistribution notices.
- Recording finalization preserves dropped-tail timing and counts actual published bytes. Notification
event overrides and the event log are independent. Theme loading rejects directory escapes and remote
content; Small/Medium/Large and compact/detailed appearance settings use source-backed values.
- File Transfer settings apply app-wide directional concurrency and pacing limits across server tabs,
including snapshot transfers. The remembered destination is main-approved; no renderer-provided host
path is accepted and an unavailable folder never silently changes the destination.
- Unversioned legacy sidebar widths migrate lazily to the server-pane width for the three-pane layout.
Reading preferences does not rewrite the file; the next successful save records layout version 2,
while existing new-layout choices remain unchanged.
- Added a bounded ten-second in-memory microphone record/listen test using the selected output device.
It never sends test audio to a server; Finish, device/privacy changes and closing settings clear the clip.
- Bounded microphone MessagePort backlog to 200 ms using capture-context sample timestamps; renderer
stalls no longer replay older queued speech. Capture DSP preferences and channel bitrate mapping are
unchanged. Hidden 190-second speech/silence captures and a real Opus encode/decode matrix were measured;
natural-microphone and official-client subjective quality remain unproven.
- Saved servers now use an always-visible inline heading/chevron disclosure, with persisted collapsed
state; toggling the heading never connects or navigates. Removed the old detached bookmark toggle.
- Connection information now uses vertical labelled groups instead of one column per protocol field,
with locale-aware duration, byte, rate and loss units, long-value wrapping and expandable raw records.
Member menus use measured pointer/keyboard anchors, side flipping and viewport bounds, reposition on
resize and dismiss on background scrolling rather than retaining a stale sidebar offset.
- The flat application caption follows the official 44 px palette. Windows/Linux window-controls overlay
and macOS traffic lights remain OS-owned; offscreen fixtures do not claim native Snap, fullscreen,
picture-in-picture or focus behavior.
- Application chrome no longer selects text during clicks and drags; chat, inputs and useful content remain
selectable. Removed the redundant audio-muted banner and transmission-mode/key header hint without
changing mute/deafen or push-to-talk safety. The host banner now sits behind the server header card.
- Added separate channel-member collapse chevrons with compact avatar summaries and per-server persistence,
plus a bounded sidebar divider supporting pointer and keyboard resize/reset.
- Watched screen shares now have independent tiles, controls and native picture-in-picture windows. Full
screen and PiP preserve their media sessions; stopping one view leaves its siblings running. The upper
stream stage can be resized or collapsed independently of chat, with saved layout preferences.
- Stream players now put the picture first: large resizable video above chat, a small name overlay, and
controls over the picture on hover or keyboard focus instead of a permanent footer. Live statistics move
into an accessible EN/RU details disclosure. New profiles start with a larger stage; existing saved sizes,
independent streams and the broadcaster's separate local-preview controls are preserved.
- Added target-bound member context menus with server-derived capability hints, explicit unknown/denied
states, guarded confirmations for moderation and permission/group changes, native bounded avatar
selection, and visible backend errors. Menus reject stale identities and connection generations.
- Per-participant voice volume uses -200..+10 dB and an independent Mute control. Reset restores 0 dB and
unmutes. Explicit committed modifiers persist by UID; session mute remains connection-local.
- Added explicit source selection, private preview and Start/Stop P2P publishing, with a muted local tile,
quality targets, per-viewer admission and a transmission-scoped UID allowlist. Capture remains opt-in;
native OS/portal support and live official-client interoperability require separate platform evidence.
- Added selected-application audio adapters for Windows WASAPI process trees and Linux PulseAudio /
pipewire-pulse streams, with bounded IPC and outgoing per-app/master gain. macOS application-audio capture
remains unavailable. The native combined capture-to-WebRTC path is not claimed proven by UI fixtures.
- Disposable UI checks now run hidden and offscreen by default, with separate profiles, denied physical
capture/permission prompts and native dialogs disabled unless a test supplies a fixture answer. The
shared launcher asserts invisible/unfocused/nonfocusable offscreen state and mutes webContents.
Packaged tests verify bundled main-process bytes match the current offscreen-safe source before launch.
- Channel clicks now browse the channel without moving voice; double-click or the explicit Join channel
action moves voice. The header explains when the channel chat still belongs to the current voice channel.
- Available screen shares appear above chat with explicit Watch actions, including multiple announced
streams; the old member-row Watch buttons are replaced by stream indicators. Browsing never subscribes.
Unavailable discovery and denied joins remain visible errors rather than fabricated streams.
- Allowed HTML fullscreen requests from the app origin while retaining the existing camera/screen-capture
restrictions. The player uses native full screen, an exit control and native Escape, keeps the same media
session, and exits on stop/end/disconnect. Request/exit failures are reported, and teardown only exits
fullscreen owned by the stream player.
- Added an isolated Electron stream-UI/media smoke with EN/RU and light/dark captures. Synthetic directory
events and local real WebRTC media are explicitly distinguished from TS6 server interoperability.
- Fixed memory growth during microphone restart/test cycles: capture processors acknowledge shutdown,
release their ports and track listeners, and close their own capture context without interrupting the
persistent playback context. Partial audio initialization is rolled back and can be retried.
- The active chat DOM now follows the existing 500-message history limit, preserving message headers and
the visible scroll anchor. Reconnect history retains server labels instead of entire server snapshots.
- Server image caching releases obsolete avatars, banners and icons when the snapshot no longer refers
to them, including downloads that finish after removal; current resources are not arbitrarily evicted.
- Core startup failures now release child/log/readiness resources on process close, including failures
without an exit event. Core stderr applies lossless log-stream backpressure.
- Screenshare lifecycle: duplicate/unknown per-stream stop notifications no longer remove sibling shares;
cancellation stops queued ICE/offer work, releases closed peer connections, and avoids retaining stopped
sessions through empty translated-label callbacks. Added isolated generated-media pipeline/lifecycle
evidence; no codec, bitrate or throttling policy change, and no claimed FPS-cap fix.
- Added reproducible disposable-profile Electron memory workloads with generated/fake audio, native heap
and process memory evidence, and regression coverage for capture cancellation, chat and image ownership.
- Second lifecycle audit: obsolete pending image downloads no longer expose revoked URLs when a cache
key returns (A→B→A); reused client rows reload avatars when UID changes. Stream discovery ignores old
responses after newer announcements, client/channel changes or stream restarts while preserving current
failures and completing fresh discovery. Delayed output/fullscreen failures cannot report errors for
ended or replaced viewing sessions. Added disposable real-renderer interleaving and generated-WebRTC
callback regressions; the live 20 fps report remains unexplained, with no performance-policy change.
- Audio/core failure ownership: capture-processor errors stop the microphone; failed context closure
retains ownership until an explicit recovery succeeds. Explicit playback recovery settles failed
diagnostics and preserves applied volume/output selection. Core log-destination failures report an
error without crashing main or stalling stderr; exited cores reject new commands while final replies
and events drain before close.
## 0.1.4 — 2026-10-24
Version 0.1.3 was tagged but never released: a race in the transmit-mode handshake was found before
publication (an older answer could re-enable forwarding while a newer mode change was still pending). It is
fixed here.
- Added voice activation as a third transmission mode next to push to talk and the open microphone
(Settings → Audio → Voice transmission, sensitivity High / Normal / Low). The core decides locally with
the earshot voice detector (a small embedded neural network, no cloud service, no speech recognition) on
audio that has already passed the microphone processing (noise suppression, echo cancellation, gain
control). It sends from about 100 ms before a detected onset until about 400 ms after the last detected
speech. After connecting, unmuting or changing the mode the gate cannot open for 200 ms, but every frame
since then is kept (up to 300 ms) and sent with the first spurt, so the first word is complete; that first
spurt therefore starts up to 300 ms late (later spurts carry the normal 100 ms). Muting, deafening, disconnecting, a channel or codec change and
a server talk denial discard what the detector heard. Push to talk and the open microphone are unchanged;
stored settings keep their mode, and new profiles still start with push to talk.
- The transmission mode moved from Settings → Keyboard to Settings → Audio; the push-to-talk key stays in
Keyboard. The microphone test explains that it only shows the input level and never transmits.
- The renderer forwards microphone audio only after the core has confirmed the selected mode; only the
answer to the latest request counts (older answers, also from a restarted core, are ignored), and a failed
mode change is shown and nothing is sent until it is applied. Renderer diagnostics now count frames
forwarded to the core, not "sent" frames; whether voice is sent is the core's transmitting state.
- Fixed: a preference write failure no longer changes the in-memory value the app keeps using.
- ARM64 CI runs the core unit tests (voice detector, resampler, identity, codecs) under qemu-aarch64
(emulated, not native hardware).
## 0.1.2 — 2026-10-24
- Fixed: Settings → Audio listed only the system default device. Electron reports the app origin as
`app://teamspeach/` and the permission check compared it with `app://teamspeach`, so Chromium withheld
device ids and names. The audio-only permission policy now normalises origins (camera stays denied);
real inputs and outputs are listed without starting the microphone, and the default entry names the
device it points to.
- The default theme is now dark, independent of the OS; Light or System can be chosen in
Settings → Appearance and persists. A theme already saved by an earlier version is kept as is.
- Right-click (or Shift+F10 / Menu key) on the microphone and headphones buttons opens an input / output
device menu sharing the Settings selection; left click still mutes/deafens.
- Voice diagnostics: the local log records the capture device and track state; with
`TEAMSPEACH_LOG=debug` it also records push-to-talk presses with window focus and each transmission burst
(frames, peak level).
- The push-to-talk hint says when the window is not focused (the key is read only there).
- Fixed: ~1/256 newly created or imported identities could not be loaded again (private key with a leading
zero byte). Storage format unchanged.
- Replaced the application icon assets with an original peach silhouette on a transparent background,
including PNG assets and a seven-size Windows ICO. The reproducible Electron export now renders the
SVG directly to an alpha-enabled canvas instead of capturing a window, avoiding captured scrollbars.
The start, error and onboarding screens show the same icon asset instead of a separate inline drawing.
- Added an English-default interface with selectable Russian, backed by shared catalogs for the renderer
and native identity dialogs. Repository-authored documentation and technical diagnostics are English;
historical captures and server-provided content remain unchanged.
- Added update checks against published public Gitea releases, Preview and Stable channels, verified
downloads for Windows x64 NSIS and Linux x64/ARM64 AppImage installations, and manual-update guidance
for zip/tar.gz distributions. Installation requires confirmation; active sessions defer background
downloads. Version 0.1.1 and older require a first manual installation of an updater-capable version.
- Fixed capture cancellation during pending microphone acquisition and prevented device changes from
being applied when saving the selected device fails.
- A saved microphone that is no longer available is reported as unavailable; TeamsPeach no longer opens
a different microphone in its place. Choosing an available device restores capture while connected or
during the microphone test, and opens nothing otherwise. A failure while building the capture chain
releases the microphone.
- The microphone and headphones menus show a failed device enumeration instead of an earlier list.
- Windows installations started with a custom profile (`TEAMSPEACH_PROFILE_DIR`) only offer manual
updates, because the installer would restart TeamsPeach on the default profile.
## 0.1.1 — 2026-10-24
- Linux AppImages use the static AppImage runtime (electron-builder toolset `appimage` 1.0.3,
runtime 20251108). The 0.1.0 ARM64 AppImage used the legacy runtime, which needs an unversioned `libz.so`
(normally only in zlib development packages) and failed to start on stock systems.
- Release gate: every AppImage must start (`--appimage-version`) in a slim container without development
packages — natively for x64, under qemu for ARM64.
- No application changes.
## 0.1.0 — 2026-10-24 (pre-release, superseded by 0.1.1)
- Electron desktop shell (contextIsolation, sandbox, strict CSP, allowlisted IPC, `app://` protocol).
- First-run nickname with persistent P-256 identity, visible UID, rename without UID change,
identity export/import and restore-on-first-run through native dialogs.
- Connect to TeamSpeak 6 servers, channel tree, joining (incl. password channels), private/channel/server chat.
- Voice: AudioWorklet capture (48 kHz mono, 20 ms i16 frames) and bounded playback ring, push-to-talk,
open mic, mute, deafen, device selection, voice volume.
- TS6 screenshare viewing over P2P WebRTC with ICE buffering, realign/reconnect offers, filters,
cancellation, negotiated codec/decoder statistics, stream volume, output device, fullscreen.
- Server metadata in the tree: group name labels per `name_mode`, custom group icons, channel icons
and banners, country codes, recording flag.
- Packaging script with native-core architecture checks, fail-closed ELF page checker, Gitea CI and
release workflows (tag/version gate, draft-then-publish).
- Saved servers: quick access above the tree and management in settings; passwords are never stored.
- Settings redesigned as category navigation with titled cards; theme choice (system/dark/light);
hardware video decoding switch with launch state, engine status and live decoder details.
- Windows core links the C runtime statically (no VC++ redistributable needed).
# Changelog
## Unreleased
- End private microphone tests and retire pre-call playback before a new Android communication
lease changes audio mode. Hold the configuration lock through lease activation and call output
startup so the previous test sink cannot be reused across that transition; keep capture consent separate.
- On Android 12+, list the actual communication outputs for call playback, with distinct earpiece
and speakerphone labels. Keep independent notification media choices and saved unavailable routes
visible rather than silently substituting a device. Earlier Android and desktop lists are unchanged.
- Add rate-bounded Android audio-route/command diagnostics and active five-second RX/TX pipeline
summaries. Record only enums, booleans, format/count/timing fields and coarse signal buckets;
never PCM, endpoint identities, server addresses, chat or credentials. Callbacks increment counters
without logging; dropped output blocks and suppressed diagnostic events are counted separately.
- Join a terminated Android runtime before first re-entry instead of attaching to its frozen snapshot;
ordinary Activity recreation retains a live call and stale UI generations cannot stop the new owner.
- Keep Android capture and playback choices explicit: attaching a headset never selects it for the user,
exact built-in microphone selections are retained, and only explicit playback actions change the
communication route. Voice outputs use runtime-resolved AAudio voice/speech attributes on API28+;
API26/27 keep the link-safe legacy behavior. Independent notification output retains media policy.
- Preserve the concrete output stream fault when startup publication fails instead of replacing it
with a generic device error; failed streams remain unpublished and inactive.
- Wait for Android default-route settlement, retain a valid recovery continuation after failed manual
switches, and reject late startup acknowledgement after focus loss. Validate explicit Bluetooth
capture transport without automatically changing playback. Resolve default PCM capabilities before
opening and require AAudio to reach Started, retaining safe backend failure-stage diagnostics.
- Android playback expires stale PCM at the app-to-audio callback handoff, not at a predicted
Bluetooth presentation time. Keep queue-age, original source expiry, epoch and mute checks;
desktop presentation deadlines are unchanged. Count actual nonzero quantized callback frames
without logging PCM or attributing that count to acoustic output.
- Android output startup now waits for a real hardware timestamp before publishing playback;
startup silence does not seed a fabricated wall-time clock or historical xrun fault. Established
timestamp loss and new xruns remain explicit failures. Deferred output failures retain their
playback stage rather than being labelled as microphone activation failures. Mobile capture and
playback selectors are adjacent; desktop ordering is unchanged.
- Android capture retains bounded future-stamped callback tails in order until their original
timestamps are due, instead of dropping them and creating FramePositionGap. Future samples never
enter SRC/DSP/TX early; expiry, mute, epoch and real missing-frame checks remain. Exclude Android's
internal echo-reference endpoint from microphone choices without hiding unknown vendor devices.
- Keep already-authorized steady Android voice calls alive across Home, screen-off and UI recreation;
release momentary PTT/whisper controls, preserve permission/audio-focus revocation, and scope CPU wake
ownership to the foreground call. Removing the app from Recents ends its call and capture services.
- Distinguish stale/future capture-frame rejection from revoked stream authorization. Keep valid capture
running after a rejected frame, and retire an old worker input without revoking a newer manager permit.
Android aggregates ingress rejection counts in bounded diagnostic summaries.
- Separate slow CPAL/DSP/notification lifecycle ownership from live PCM servicing, preserving output
callbacks and reference draining while capture opens. Keep durable output authorization across reset
races; later stops still win. Reconcile acknowledged same-owner capture changes without retries.
- Preserve held PushToMute inhibitors, revoke mute before awaiting configuration, and prevent stale
lifecycle/private-test completion from stopping newer voice intent. Microphone controls reflect real
readiness; Android permission state is re-read after onboarding without granting capture consent.
- Ask for Android microphone permission on first visible app entry, without starting capture or voice
transmission. Already-granted access and prior denials do not trigger automatic repeat prompts;
explicit microphone actions retain the existing permission flow and offline smoke remains isolated.
- Publish acknowledged connection/capture snapshots before waking callers. Reset mute/deafen output
epochs and queued PCM in place instead of reopening every device; reject stale binding generations
and voice frames crossing playback boundaries.
- Restore authorized playback on undeafen without discarding retained microphone consent; explicit
microphone activation finishes private recording first. Fence permission replies against intervening
privacy changes, and route keybind mute/deafen through the same acknowledged workflow.
- Correct Android input timestamps to the first callback frame: AAudio frames-read already includes
the delivered buffer. Do not synthesize capture time when hardware timestamps are unavailable;
reject missing PCM spans rather than concatenating them into accelerated/choppy recordings.
- Bound private microphone preview peaks to -12 dBFS without boosting quiet recordings; taper preview
boundaries and replace live voice during preview instead of adding into it. Stop capture before
opening preview output; report processed recording RMS/peak separately from the pre-DSP meter.
- Android capture selection groups built-in/internal capture routes under system default, retains
real external source IDs with type labels, and rejects silent fallback from explicit endpoint IDs.
- Check audio queue residence after each pop using callback-local arrival time; retain strict capture
hardware age/epoch boundaries and diagnose negative ages separately from expired/invalid blocks.
Drain queued capture before applying timeout. Project converted PCM from actual SRC source phase
and current hardware observations so long-lived device drift cannot accumulate nominal-clock error.
- Fix callback clock observations being confused with their internal PCM subdivisions, which caused
false TimestampReversed shutdown on bursty Android playback. Preserve hardware-derived PCM timestamps,
expiry/privacy checks and reject genuine clock/sample-position discontinuities.
- Avoid running APK verification twice in Android CI; packaging already verifies final archive bytes.
- Retain sanitized first audio fault/callback counters across teardown; preserve operation-stage errors.
Keep connection playback epochs coherent across output replacement and distinguish first-device startup
time from live stream stalls. Voice-follow recovery retains logical route ownership without stale sink traps.
- Separate desired capture authorization from transient hardware activity during PTT/device refresh;
muted/deafened configurations complete without false target-change errors. Restore authorized output
before voice-follow notifications, and retire exact audio session scopes when closing/restarting tabs.
- Select explicitly opened server connections for the visible tree, show the acknowledged Android channel,
and keep audio recovery failures distinct from successful channel joins.
- Serialize Android voice output startup/recovery and notification routing; delayed observer events no
longer revoke newly authorized capture. Device faults still revoke at the audio owner boundary.
- Adapt Android shell, settings, chat and forms to phone-size navigation and keyboard-safe content;
expose New Connection directly and retain all target-bound actions in bounded menus and scroll bodies.
- Rebase idle audio deadlines without false device-stall errors, retaining active-device stale PCM
protection; permit private microphone testing before a server is connected.
- Android CI uses all CPUs available to the runner container for Cargo/Ninja/CMake; scheduling changes
retain compatible Cargo artifacts without changing optimization or local Windows resource limits.
- Bootstrap creation/recovery now shares validation and worker-owned persistence, preserves committed
identities on retry, acknowledges service initialization failures and publishes revisioned terminal
errors. UI queue rejection and background snapshots no longer strand or reset pending form state.
- Android profile creation now traverses search-only sandbox ancestors without reading them and uses
real descriptor-owned flock locks on Rust1.96; unsupported I/O is no longer reported as contention.
- Android TLS initializes the pinned platform verifier with the process Application/classloader before
networking; packages its matching JVM helper/Kotlin runtime and verifies helper definitions in DEX.
- Android insets follow the NativeActivity window rather than a nonexistent SurfaceView; IME updates
are sampled after layout commits. Import backup remains in Identities settings, not first-run onboarding.
- Android CI separates cached toolchain/profile compatibility from Cargo dependency/source changes,
retains content-verified input timestamps and saves completed Cargo artifacts before uploads.
- Android CI now runs on trusted feature/mobile-port pushes using an isolated Ubuntu24.04 container.
Added checksum-pinned SDK/NDK/Rust/Skia/Gradle provisioning, early disk/RAM gates, four-job CI compilation,
dependency checkpoints before native build, memory evidence and SHA-labelled test APK artifacts;
no automatic releases, production signing or device actions. Local Windows limits remain separate.
- Fixed restored Android WebRTC checkpoints: validate and reverse receipt-matched source patches
before gclient synchronization, then reapply pinned patches without deleting compiled objects.
- Added explicitly authorized Android CI low-memory native code generation (256 units, LTO off),
scoped to the ARM64 application crate and recorded in build-info; full Skia/WebRTC features retained.
- Android onboarding is now a full-screen page with a one-line 48dp nickname field, visible theme
choices, errors and Create/Cancel buttons; keyboard insets are handled before profile creation.
Cancel exits the matching Android Activity instead of reopening the same onboarding form.
- Fixed phone-reported identity creation refusal by canonicalizing only the OS-provided filesDir:
Android's app mount namespace can alias /data/user/0 to /data/data. Import/profile descendants
still reject symlinks; Android openat now uses target-correct libc O_NOFOLLOW/CLOEXEC/NONBLOCK flags.
- Built the first full Skia/WebRTC Android ARM64 test APK in authorized WSL2. Verified APK v2 signing,
16-KiB alignment, native ISA/imports, resources and exported WebRTC JNI symbols; no device run claimed.
- Fixed Android build integration: use the complete NDK r28c rather than Chromium's sysroot-only subset,
copy the matching WebRTC jar to Cargo's actual output directory, retain JNI exports in the final cdylib,
pin Gradle launcher LF/build-tools36, and use the public AppOps permission-change observer.
Corrected the pinned Slint NonNull pointer conversion in Android accessibility.
- Implemented Android call-scoped audio recovery: focus/route changes revoke microphone authorization,
restore receive-only playback when permitted, and reject stale lease/revision callbacks. Communication
mode and Android 12+ communication-device notifications follow the active foreground call.
- Android network capability refreshes no longer masquerade as network handoffs. Added the missing
privacy-approved external-link adapter; SAF filename collisions offer a new destination, and identity
exports use private staging and the provider commit/partial-cleanup contract rather than direct writes.
- Adapted the Android phone shell: connection/tab actions, selected-target actions, compact detail
navigation and settings Back; bounded menus/forms, IME-aware chat/settings, and hold/cancel PTT.
Android APK, physical-device voice, Bluetooth/provider behavior and full parity remain unverified.
- Android Activity pause now releases touch PTT/long-press state without ending foreground screen/camera
capture. Pending playback recovery survives later microphone revocation; duplicate audio-focus gain
no longer revokes an explicitly enabled microphone.
- Android camera/projection consent remains visible until foreground handoff, pending Camera2 opens
drain before shutdown, and resize ignores obsolete ImageReader callbacks. Permission launch failures
complete requests; SAF grants validate access and close descriptors/capabilities on failed handoff.
- Added receiver instructions for building the exact mobile revision on another developer's WSL2
Linux machine, using the existing pinned-source recipe and returning the complete APK/receipt bundle.
- Fixed native Windows build environment capture for non-ASCII values by selecting UTF-8 in the
child MSVC activation shell; verified against real vcvarsall with a synthetic Cyrillic value.
- Pinned LF checkout for native dependency patches and recipe sources so Windows line-ending
conversion cannot invalidate exact patch checksums; expected lock hashes remain unchanged.
- Added a manual Android CI route producing separate full-feature ARM64 test-harness APK and unsigned
production APK/AAB bundles with source/build/dependency receipts. Windows developers do not need WSL.
Android packaging keeps offline Gradle by default; CI opts into dependency resolution explicitly and
isolates each package's Gradle outputs. CI runner provisioning and device acceptance remain unverified.
- Android CI now uploads the verified harness APK and receipts before starting production packaging,
so a later production failure does not prevent retaining the test APK. Both variants reuse one recipe.
- Android CI defaults to a bounded read-only runner inventory; full Android builds require explicit
manual selection and still use the dedicated Android runner label. Inventory never installs tools.
- Removed the Electron application, npm manifests and browser-only test/build tooling. Rust/Slint
is now the only application; native resources and versioning no longer depend on the removed tree.
Retained native profile migration and diagnostic core CLI. This cutover is not mobile runtime acceptance.
- Started the native implementation with one Cargo workspace and lockfile and pinned Rust 1.96.0.
Core/DSP dependency resolutions are preserved; the later native-only cutover removes the reference host.
- Added the native compatibility inventory; entries remain pending, not claims of feature completion.
Initial Slint software and Skia windows were exercised with a real pointer Close action;
this does not establish native voice, video, mobile support or whole-client migration completion.
- Extracted the protocol core into an embedded library with validated typed commands, joined session
lifetimes, generation-stamped events, bounded PCM and capture guards at the actual UDP-send boundary.
Diagnostic stdio remains independently usable for core inspection.
- Ported native profile import, local stores and session-bound file/icon/snapshot services. Imports retain
the original profile, preserve identity keys/UIDs and require bookmark passwords once again. Native
secret/preference pair commits recover interrupted writes; unknown staging directories are never discarded.
Windows isolated DPAPI and migration/restart smoke passed; other OS key stores and live mutations remain
separate verification gates. Snapshot format stays 0.0.1; native About labels legacy notices as historical.
- Added worker-owned CPAL audio, bounded timestamped callback queues, drift-aware Rubato conversion,
integrated Sonora AEC/NS/AGC and independent notification sinks. Capture/output revocation survives
queue congestion; source expiry remains attached through resampling to hardware presentation.
Controlled DSP/queue/permission and native worker smoke passed (generated PCM, no physical devices).
Official-peer voice, acoustic echo cancellation and mobile/Asahi hardware remain unverified.
- Added pinned source-built native WebRTC provisioning, checked desktop/mobile capture adapters and
generation-bound TS6 viewer/publisher state machines. Windows x64 CXX bridge compilation passed.
The production software decoder factory decoded synthetic H264 High, AV1, VP8 and VP9 fixtures;
all four 64×48 I420 outputs exactly matched independent FFmpeg decoding. Sustained native playback,
official TS6 peers, physical capture, hardware decode and other platforms remain separate gates.
- Proved a device-free native PeerConnection loopback through the real sender/decoder/display path
(13 decoded frames, 12 presented, terminal cleanup). Isolated WebRTC Opus symbols from the voice
core's existing codec without weakening linker checks or rewriting unrelated assembly objects.
- Rebuilt Privacy, Video, Notifications and About in the original section order. Unsupported account,
telemetry, Cisco/backend and content-report options are explicitly unavailable, never fake preferences.
Working Chromium decoder controls and installation/project details moved to linked subpages with
back-focus restoration. Report Issue uses the project's verified issue list through the external-link guard.
- Preserved native decoder-policy restart, notification overrides, trusted-site management and local
changelog/license navigation. Corrected narrow Russian update-row overlap without hiding status.
- Restored original selector wrapping, selected-preview radius clipping and whisper action tints.
Permission lists now reserve their source toolbar space and wrap badges without losing long-name
truncation; private-info descriptions and empty group states use the source sizing and spacing.
- Fixed channel right-click opening Whisper settings and silently staging a target. The normal channel
menu now leaves the current view and whisper state unchanged; only its explicit Add to Whisperlist
action stages the channel, behind the existing connection/session validity guard.
- Moved identity export and UID copy into the selected identity's context menu. Export keeps its
private-key confirmation. Disconnected nickname edits use identity Details; connected nickname
edits use the own-client information header. Removed the duplicate bookmark settings manager;
bookmarks remain editable in the sidebar.
- Language changes are saved for restart, with a cancelable restart confirmation. File-transfer
settings use the source defaults, shared rate limits and per-channel concurrency limits.
- Added generation-bound group deletion and explicit group/channel permission removal, plus the
channel icon picker. A refused icon after successful channel creation cannot create the channel
a second time; stale form/session responses do not apply to another view.
- About reports actual build metadata. Corrected identity slider layout, device-selector caption
overlap, broadcast tab/thumbnail geometry and transfer-row spacing. Migrated affected smoke scripts.
- Matched the detail header's source flex grouping, restored full-height administration panels and
bottom pagination, corrected client-list wrapping, group-badge spacing and server-info typography.
Audio device captions and broadcast title chips now use measured original text metrics.
- Whole-client pixel parity is not established; reference comparisons retain their original thresholds.
## 0.1.7 — 2026-11-02
- Matched light-theme toolbar/header/composer icon colors, header separators and chevron placement
to the installed reference. Corrected narrow chat width and input placeholder spacing.
All eight main-screen EN/RU, dark/light and wide/narrow fixture comparisons passed; this does not
establish whole-client parity or native-platform interoperability.
- Replaced the plain chat textarea with one local CodeMirror editor and the persisted Rich Text Editor
toggle. Hybrid preview uses the existing safe TS Markdown renderer; switching modes retains text,
selection and undo, while switching conversations isolates draft history. Toolbar/slash/emoji edits,
Enter/Shift+Enter, IME and refused-send preservation were exercised in the packaged offscreen app.
Constructed stylesheets keep the application CSP strict; no inline-style exception was added.
- Added the original editor's bold, italic, link, inline-code and code-block keyboard bindings.
Corrected the notification output selector's missing bottom margin using the original component rule.
- Matched list/quote authoring controls: Shift+Enter continuation, ordered/task item transitions,
Tab/Shift+Tab indentation, empty-item exit and Escape-then-Tab focus escape. Fenced code is not
mistaken for a list; quoted fences retain their quote prefix.
## 0.1.6 — 2026-11-02
Current development snapshot; full visual parity and native Asahi verification remain unfinished.
Version 0.1.5 was not published: CI rejected an empty changelog section.
- Added source-style advanced notification controls with independent persisted event choices,
confirmation before hiding advanced controls and single-event expansion.
- Corrected server-tree painting against paired hidden captures. Remaining light-theme,
narrow-layout and composer differences are not claimed fixed in this release.
- Rebuilt Identities around the original selector, inline creation/rename, selected-identity Details,
security-level controls and related bookmarks. Fixed default-profile UID leakage into selected Details,
selector popup initialization and the final improvement level briefly reverting during a list refresh.
Export and the explicit current-server nickname action remain available.
- Replaced raw File Transfer number fields with source-style keyboard/step controls that retain focus
and drafts through serialized saves. Native folder/copy restrictions, shared limits and safe defaults remain.
- Added notification category switches with real sound-policy gating, preserved per-event states and
independent event logs; concurrent state edits are serialized.
- Added nested bookmark folders with inline creation, rename, ordering, move/duplicate menus and
confirmed subtree deletion, using validated local preferences rather than a separate bookmark store.
- Extended bookmarks with a per-connection nickname, initial channel, session-bound channel drops,
startup connection and input-only startup mute. A nickname override never changes the stored identity.
- Bookmark passwords use OS-protected encryption, bound to address and server/channel purpose. Plaintext
is never persisted; Linux basic_text/unknown storage is refused. Stale metadata writes cannot overwrite
or resurrect a password, and native key-store interactions revalidate the window, bookmark and connection.
Explicit reveal, same-address duplication, address-change cleanup, restart and forgetting a password
after storage becomes unavailable were exercised with real Windows DPAPI. No live server join was performed.
- Startup bookmark enumeration is one-shot in main, so a renderer reload cannot start a second set of
connections. Automatic microphone mute is applied before connecting and never changes speaker mute.
- Added Privacy with trusted-site management and remembered confirmations; reset and concurrent
confirmation changes are serialized so an older save cannot overwrite a later reset.
- Removed the mistakenly added Remote Apps integration to honor the owner's explicit exclusion:
no listener, authorization IPC, settings page, remote-button capture or WebSocket production dependency.
- Added account-free local UID contacts and public badge artwork display. These are not myTeamSpeak
contacts, owned-badge management, cloud presence or offline messaging.
- Added server icon management bound to the listing's connection generation. Reconnecting invalidates
mutation grants; old icon/snapshot transfers cannot cancel a new session's reused transfer ID.
- Added the four-level noise-reduction control with persisted per-input settings. Processing remains
an independent implementation, not a claim of identity with TeamSpeak's private native DSP.
- Fixed key recording in the contents-layout settings host by checking the enclosing panel's visibility.
Packaged verification covers saving the binding and retaining it across an application restart.
- Isolated Mermaid rendering from the privileged application renderer; nested renderers cannot acquire
media/presentation permissions. Local diagram/math rendering and hostile-content rejection were exercised.
- Corrected smoke polling to await asynchronous IPC/import predicates instead of accepting a Promise
as a satisfied condition. Persistence checks now wait for actual saved state.
- Fixed full Changelog and Open Source Licenses pages rendering arrays as text instead of appending
their DOM nodes. Added a real offscreen navigation smoke covering document text and back-focus restoration.
- Whispers follow the original manager: Live Preview highlights the current list's clients and channels in
the server tree (resolved from the current snapshot only), "Switch to Server and Overlay" shows the list
next to the microphone's server, and the status bar Whisper History lists received whispers with Delete.
Replies and avatars use only entries whose client id and UID are still on the same server session.
- Key Bindings follow the original page: "Require exact key match" toggle, named profiles (inline
"New Profile Name" editor, rename, choose, Activate, delete of inactive profiles) and every official
hotkey action, each running the app's real operation. Push-to-mute stops sending without touching your
mute choice; global push-to-talk survives window focus loss while local keys still release on it. Go Live
opens the broadcast source chooser instead of guessing the focused application. Bindings can be in-window,
or global; with exact matching off, global keys also register their
extra-modifier combinations. keybinds.json moves to version 2; version 1 whisper bindings migrate unchanged
into one active profile and the original file is kept as `keybinds.v1-<time>.json`.
- Reworked the interface against the actual installed TeamSpeak frontend rather than the earlier
hand-reconstructed component sheet: original non-brand SVG artwork, Noto Sans 2.013, channel and
client chat layouts, membership event rows, sidebar actions, in-pane administration, settings
dropdowns/sliders and the two-stage broadcast dialog. Independent branding and account-free
behavior remain. Artwork provenance does not grant redistribution rights.
- Corrected sidebar group geometry and moved New Connection into its own account-free action slot;
bookmark add/search/disclosure retain their real persistence/navigation behavior. Language and sidebar
icon-mode selectors use original local artwork, content-based widths and restored keyboard focus.
Audio device captions use the observed system-default alias, not an inferred physical device.
- Matched device-field, VAD selector, slider, record-test and display-preview geometry to source values.
Fixed the chat spacer to use the composer's content-box height, removing a two-pixel full-history offset.
- Preserve a bottom-pinned chat on window reflow without forcing readers of older history to the end.
The regression reproduced a 119px gap after narrowing; the packaged fix retains a zero gap and
separately preserves the history reader's position. The paired harness retains this behavioral check.
- Match chat scrollbar safe-area width and system-event wrapping to the actual original renderer;
restore the localized empty-chat prompt with real draft/send-state visibility. Narrow composer tools
now overflow into working ordered menus rather than clipping. Settings categories occupy the original
narrow-sidebar position below Servers/New Connection, with source-sized previews and server columns.
- Correct empty-chat prompt geometry with the measured 22px glyph and the secondary-pane contrast
background. The focused dark/en wide-screen chat region passes; the whole screen still fails other regions.
- Use the original Russian bookmark-help wording (`Добавьте`), preserving the same save/connect behavior.
- Run both sides of visual QA with Electron's normal acceleration policy. Earlier reference captures
forced software rendering while the product did not; those comparisons remain historical evidence,
not directly comparable pixel baselines for the corrected capture policy.
- Actual whole-screen comparison still does not meet the 1:1 acceptance criterion. The refreshed 168-pair
run has no blocked captures but no fully passing screen pairs. Viewport-only timestamp comparison and
nested native-caption exclusions now avoid earlier harness false positives; thresholds are unchanged.
See `docs/evidence/official-parity/qa-parity-harness.md` for build-specific results and remaining differences.
- Initialize custom controls explicitly at renderer startup, not when audio/notification modules
import the slider helper. The Node suite and focused packaged chat/control smoke checks pass;
this does not establish complete visual or native platform parity.
- Added local TS6 theme extensions (Settings → Appearance → User Theme): the official `package.json`
schema, `<identifier>//<variant>` selection, stock fallback and a five-minute list cache with Reload.
Files load only through the restricted `tsext:` scheme (selected variant CSS, fonts, images, previews);
`@import`, remote URLs, links and path traversal are rejected and reads are bounded. Account-free; no
store or Remote Apps. Compatibility covers the package format and `--tsv-*` tokens, not official DOM
class hooks.
- Added account-free local identity management: additive import, selected-identity export, per-identity
names/nicknames, default and bookmark selection, guarded deletion, and resumable/cancellable bounded
security-level improvement. Active connections retain their chosen identity.
- Added simultaneous connection records with one isolated native core per server, explicit viewed/input
connection routing, connection-local chat, streams, recording and administrative operations.
- Added channel/server administration, local whisper lists and held targets, general legacy file browsing
and transfers, server snapshots, recording, notifications, and OS-specific local settings. Available
functionality and unverified native protocol branches are listed separately in the compatibility matrix.
- Migrated audio preferences to per-device capture/playback profiles and the official piecewise dB fader;
existing voice choices are converted on load. Automatic/hybrid/level activation, PTT release delay,
notification routing and independent processing are implemented without claiming native-DSP identity.
- Added connection/identity-scoped disk chat history, independent drafts/unread state, local rich text,
emoji/math/diagrams and server-file links. Remote images require explicit consent; account-only Matrix
editing, reactions and read receipts are not included. Local vendor assets carry redistribution notices.
- Recording finalization preserves dropped-tail timing and counts actual published bytes. Notification
event overrides and the event log are independent. Theme loading rejects directory escapes and remote
content; Small/Medium/Large and compact/detailed appearance settings use source-backed values.
- File Transfer settings apply app-wide directional concurrency and pacing limits across server tabs,
including snapshot transfers. The remembered destination is main-approved; no renderer-provided host
path is accepted and an unavailable folder never silently changes the destination.
- Unversioned legacy sidebar widths migrate lazily to the server-pane width for the three-pane layout.
Reading preferences does not rewrite the file; the next successful save records layout version 2,
while existing new-layout choices remain unchanged.
- Added a bounded ten-second in-memory microphone record/listen test using the selected output device.
It never sends test audio to a server; Finish, device/privacy changes and closing settings clear the clip.
- Bounded microphone MessagePort backlog to 200 ms using capture-context sample timestamps; renderer
stalls no longer replay older queued speech. Capture DSP preferences and channel bitrate mapping are
unchanged. Hidden 190-second speech/silence captures and a real Opus encode/decode matrix were measured;
natural-microphone and official-client subjective quality remain unproven.
- Saved servers now use an always-visible inline heading/chevron disclosure, with persisted collapsed
state; toggling the heading never connects or navigates. Removed the old detached bookmark toggle.
- Connection information now uses vertical labelled groups instead of one column per protocol field,
with locale-aware duration, byte, rate and loss units, long-value wrapping and expandable raw records.
Member menus use measured pointer/keyboard anchors, side flipping and viewport bounds, reposition on
resize and dismiss on background scrolling rather than retaining a stale sidebar offset.
- The flat application caption follows the official 44 px palette. Windows/Linux window-controls overlay
and macOS traffic lights remain OS-owned; offscreen fixtures do not claim native Snap, fullscreen,
picture-in-picture or focus behavior.
- Application chrome no longer selects text during clicks and drags; chat, inputs and useful content remain
selectable. Removed the redundant audio-muted banner and transmission-mode/key header hint without
changing mute/deafen or push-to-talk safety. The host banner now sits behind the server header card.
- Added separate channel-member collapse chevrons with compact avatar summaries and per-server persistence,
plus a bounded sidebar divider supporting pointer and keyboard resize/reset.
- Watched screen shares now have independent tiles, controls and native picture-in-picture windows. Full
screen and PiP preserve their media sessions; stopping one view leaves its siblings running. The upper
stream stage can be resized or collapsed independently of chat, with saved layout preferences.
- Stream players now put the picture first: large resizable video above chat, a small name overlay, and
controls over the picture on hover or keyboard focus instead of a permanent footer. Live statistics move
into an accessible EN/RU details disclosure. New profiles start with a larger stage; existing saved sizes,
independent streams and the broadcaster's separate local-preview controls are preserved.
- Added target-bound member context menus with server-derived capability hints, explicit unknown/denied
states, guarded confirmations for moderation and permission/group changes, native bounded avatar
selection, and visible backend errors. Menus reject stale identities and connection generations.
- Per-participant voice volume uses -200..+10 dB and an independent Mute control. Reset restores 0 dB and
unmutes. Explicit committed modifiers persist by UID; session mute remains connection-local.
- Added explicit source selection, private preview and Start/Stop P2P publishing, with a muted local tile,
quality targets, per-viewer admission and a transmission-scoped UID allowlist. Capture remains opt-in;
native OS/portal support and live official-client interoperability require separate platform evidence.
- Added selected-application audio adapters for Windows WASAPI process trees and Linux PulseAudio /
pipewire-pulse streams, with bounded IPC and outgoing per-app/master gain. macOS application-audio capture
remains unavailable. The native combined capture-to-WebRTC path is not claimed proven by UI fixtures.
- Disposable UI checks now run hidden and offscreen by default, with separate profiles, denied physical
capture/permission prompts and native dialogs disabled unless a test supplies a fixture answer. The
shared launcher asserts invisible/unfocused/nonfocusable offscreen state and mutes webContents.
Packaged tests verify bundled main-process bytes match the current offscreen-safe source before launch.
- Channel clicks now browse the channel without moving voice; double-click or the explicit Join channel
action moves voice. The header explains when the channel chat still belongs to the current voice channel.
- Available screen shares appear above chat with explicit Watch actions, including multiple announced
streams; the old member-row Watch buttons are replaced by stream indicators. Browsing never subscribes.
Unavailable discovery and denied joins remain visible errors rather than fabricated streams.
- Allowed HTML fullscreen requests from the app origin while retaining the existing camera/screen-capture
restrictions. The player uses native full screen, an exit control and native Escape, keeps the same media
session, and exits on stop/end/disconnect. Request/exit failures are reported, and teardown only exits
fullscreen owned by the stream player.
- Added an isolated Electron stream-UI/media smoke with EN/RU and light/dark captures. Synthetic directory
events and local real WebRTC media are explicitly distinguished from TS6 server interoperability.
- Fixed memory growth during microphone restart/test cycles: capture processors acknowledge shutdown,
release their ports and track listeners, and close their own capture context without interrupting the
persistent playback context. Partial audio initialization is rolled back and can be retried.
- The active chat DOM now follows the existing 500-message history limit, preserving message headers and
the visible scroll anchor. Reconnect history retains server labels instead of entire server snapshots.
- Server image caching releases obsolete avatars, banners and icons when the snapshot no longer refers
to them, including downloads that finish after removal; current resources are not arbitrarily evicted.
- Core startup failures now release child/log/readiness resources on process close, including failures
without an exit event. Core stderr applies lossless log-stream backpressure.
- Screenshare lifecycle: duplicate/unknown per-stream stop notifications no longer remove sibling shares;
cancellation stops queued ICE/offer work, releases closed peer connections, and avoids retaining stopped
sessions through empty translated-label callbacks. Added isolated generated-media pipeline/lifecycle
evidence; no codec, bitrate or throttling policy change, and no claimed FPS-cap fix.
- Added reproducible disposable-profile Electron memory workloads with generated/fake audio, native heap
and process memory evidence, and regression coverage for capture cancellation, chat and image ownership.
- Second lifecycle audit: obsolete pending image downloads no longer expose revoked URLs when a cache
key returns (A→B→A); reused client rows reload avatars when UID changes. Stream discovery ignores old
responses after newer announcements, client/channel changes or stream restarts while preserving current
failures and completing fresh discovery. Delayed output/fullscreen failures cannot report errors for
ended or replaced viewing sessions. Added disposable real-renderer interleaving and generated-WebRTC
callback regressions; the live 20 fps report remains unexplained, with no performance-policy change.
- Audio/core failure ownership: capture-processor errors stop the microphone; failed context closure
retains ownership until an explicit recovery succeeds. Explicit playback recovery settles failed
diagnostics and preserves applied volume/output selection. Core log-destination failures report an
error without crashing main or stalling stderr; exited cores reject new commands while final replies
and events drain before close.
## 0.1.4 — 2026-10-24
Version 0.1.3 was tagged but never released: a race in the transmit-mode handshake was found before
publication (an older answer could re-enable forwarding while a newer mode change was still pending). It is
fixed here.
- Added voice activation as a third transmission mode next to push to talk and the open microphone
(Settings → Audio → Voice transmission, sensitivity High / Normal / Low). The core decides locally with
the earshot voice detector (a small embedded neural network, no cloud service, no speech recognition) on
audio that has already passed the microphone processing (noise suppression, echo cancellation, gain
control). It sends from about 100 ms before a detected onset until about 400 ms after the last detected
speech. After connecting, unmuting or changing the mode the gate cannot open for 200 ms, but every frame
since then is kept (up to 300 ms) and sent with the first spurt, so the first word is complete; that first
spurt therefore starts up to 300 ms late (later spurts carry the normal 100 ms). Muting, deafening, disconnecting, a channel or codec change and
a server talk denial discard what the detector heard. Push to talk and the open microphone are unchanged;
stored settings keep their mode, and new profiles still start with push to talk.
- The transmission mode moved from Settings → Keyboard to Settings → Audio; the push-to-talk key stays in
Keyboard. The microphone test explains that it only shows the input level and never transmits.
- The renderer forwards microphone audio only after the core has confirmed the selected mode; only the
answer to the latest request counts (older answers, also from a restarted core, are ignored), and a failed
mode change is shown and nothing is sent until it is applied. Renderer diagnostics now count frames
forwarded to the core, not "sent" frames; whether voice is sent is the core's transmitting state.
- Fixed: a preference write failure no longer changes the in-memory value the app keeps using.
- ARM64 CI runs the core unit tests (voice detector, resampler, identity, codecs) under qemu-aarch64
(emulated, not native hardware).
## 0.1.2 — 2026-10-24
- Fixed: Settings → Audio listed only the system default device. Electron reports the app origin as
`app://teamspeach/` and the permission check compared it with `app://teamspeach`, so Chromium withheld
device ids and names. The audio-only permission policy now normalises origins (camera stays denied);
real inputs and outputs are listed without starting the microphone, and the default entry names the
device it points to.
- The default theme is now dark, independent of the OS; Light or System can be chosen in
Settings → Appearance and persists. A theme already saved by an earlier version is kept as is.
- Right-click (or Shift+F10 / Menu key) on the microphone and headphones buttons opens an input / output
device menu sharing the Settings selection; left click still mutes/deafens.
- Voice diagnostics: the local log records the capture device and track state; with
`TEAMSPEACH_LOG=debug` it also records push-to-talk presses with window focus and each transmission burst
(frames, peak level).
- The push-to-talk hint says when the window is not focused (the key is read only there).
- Fixed: ~1/256 newly created or imported identities could not be loaded again (private key with a leading
zero byte). Storage format unchanged.
- Replaced the application icon assets with an original peach silhouette on a transparent background,
including PNG assets and a seven-size Windows ICO. The reproducible Electron export now renders the
SVG directly to an alpha-enabled canvas instead of capturing a window, avoiding captured scrollbars.
The start, error and onboarding screens show the same icon asset instead of a separate inline drawing.
- Added an English-default interface with selectable Russian, backed by shared catalogs for the renderer
and native identity dialogs. Repository-authored documentation and technical diagnostics are English;
historical captures and server-provided content remain unchanged.
- Added update checks against published public Gitea releases, Preview and Stable channels, verified
downloads for Windows x64 NSIS and Linux x64/ARM64 AppImage installations, and manual-update guidance
for zip/tar.gz distributions. Installation requires confirmation; active sessions defer background
downloads. Version 0.1.1 and older require a first manual installation of an updater-capable version.
- Fixed capture cancellation during pending microphone acquisition and prevented device changes from
being applied when saving the selected device fails.
- A saved microphone that is no longer available is reported as unavailable; TeamsPeach no longer opens
a different microphone in its place. Choosing an available device restores capture while connected or
during the microphone test, and opens nothing otherwise. A failure while building the capture chain
releases the microphone.
- The microphone and headphones menus show a failed device enumeration instead of an earlier list.
- Windows installations started with a custom profile (`TEAMSPEACH_PROFILE_DIR`) only offer manual
updates, because the installer would restart TeamsPeach on the default profile.
## 0.1.1 — 2026-10-24
- Linux AppImages use the static AppImage runtime (electron-builder toolset `appimage` 1.0.3,
runtime 20251108). The 0.1.0 ARM64 AppImage used the legacy runtime, which needs an unversioned `libz.so`
(normally only in zlib development packages) and failed to start on stock systems.
- Release gate: every AppImage must start (`--appimage-version`) in a slim container without development
packages — natively for x64, under qemu for ARM64.
- No application changes.
## 0.1.0 — 2026-10-24 (pre-release, superseded by 0.1.1)
- Electron desktop shell (contextIsolation, sandbox, strict CSP, allowlisted IPC, `app://` protocol).
- First-run nickname with persistent P-256 identity, visible UID, rename without UID change,
identity export/import and restore-on-first-run through native dialogs.
- Connect to TeamSpeak 6 servers, channel tree, joining (incl. password channels), private/channel/server chat.
- Voice: AudioWorklet capture (48 kHz mono, 20 ms i16 frames) and bounded playback ring, push-to-talk,
open mic, mute, deafen, device selection, voice volume.
- TS6 screenshare viewing over P2P WebRTC with ICE buffering, realign/reconnect offers, filters,
cancellation, negotiated codec/decoder statistics, stream volume, output device, fullscreen.
- Server metadata in the tree: group name labels per `name_mode`, custom group icons, channel icons
and banners, country codes, recording flag.
- Packaging script with native-core architecture checks, fail-closed ELF page checker, Gitea CI and
release workflows (tag/version gate, draft-then-publish).
- Saved servers: quick access above the tree and management in settings; passwords are never stored.
- Settings redesigned as category navigation with titled cards; theme choice (system/dark/light);
hardware video decoding switch with launch state, engine status and live decoder details.
- Windows core links the C runtime statically (no VC++ redistributable needed).
Generated
+15 -17
View File
@@ -387,7 +387,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parking_lot",
"percent-encoding",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
"wl-clipboard-rs",
"x11rb",
]
@@ -1926,7 +1926,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -2220,7 +2220,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -2713,7 +2713,7 @@ dependencies = [
"gobject-sys",
"libc",
"system-deps",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -4063,7 +4063,6 @@ dependencies = [
"pastey 0.2.3",
"serde",
"task-local",
"tokio",
"zbus",
]
@@ -4569,8 +4568,6 @@ dependencies = [
[[package]]
name = "ndk"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"
dependencies = [
"bitflags 2.13.2",
"jni-sys 0.3.1",
@@ -4663,7 +4660,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -5247,7 +5244,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.45.0",
]
[[package]]
@@ -5895,7 +5892,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -6489,7 +6486,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -6557,7 +6554,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -7475,6 +7472,7 @@ dependencies = [
"base64 0.22.1",
"dbus",
"earshot",
"fs2",
"futures",
"md-5",
"num-traits",
@@ -7528,6 +7526,7 @@ dependencies = [
"image",
"indexmap",
"jni 0.21.1",
"jni 0.22.4",
"katex-native",
"katex-rs",
"ksni",
@@ -7541,6 +7540,7 @@ dependencies = [
"ringbuf",
"roxmltree 0.21.2",
"rubato",
"rustls-platform-verifier",
"same-file",
"secret-service",
"security-framework",
@@ -7576,10 +7576,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"getrandom 0.3.4",
"once_cell",
"rustix 1.1.6",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -7786,7 +7786,6 @@ dependencies = [
"signal-hook-registry",
"socket2",
"tokio-macros",
"tracing",
"windows-sys 0.61.2",
]
@@ -8877,7 +8876,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -9446,7 +9445,6 @@ dependencies = [
"rustix 1.1.6",
"serde",
"serde_repr",
"tokio",
"tracing",
"uds_windows",
"uuid",
+2 -1
View File
@@ -1,7 +1,7 @@
[workspace]
resolver = "3"
members = ["core", "dsp", "native", "xtask"]
exclude = ["core/vendor/tsclientlib", "core/vendor/tsproto", "dsp/vendor/sonora", "dsp/vendor/sonora-agc2", "native/vendor/libwebrtc-0.4.0", "native/vendor/webrtc-sys-0.3.53", "native/vendor/katex-rs-0.3.0", "native/vendor/mermaid-rs-renderer-0.3.1", "native/vendor/cpal-0.18.2", "native/vendor/i-slint-backend-android-activity-1.18.1"]
exclude = ["core/vendor/tsclientlib", "core/vendor/tsproto", "dsp/vendor/sonora", "dsp/vendor/sonora-agc2", "native/vendor/libwebrtc-0.4.0", "native/vendor/webrtc-sys-0.3.53", "native/vendor/katex-rs-0.3.0", "native/vendor/mermaid-rs-renderer-0.3.1", "native/vendor/cpal-0.18.2", "native/vendor/i-slint-backend-android-activity-1.18.1", "native/vendor/ndk-0.9.0"]
[workspace.package]
version = "0.1.7"
@@ -39,6 +39,7 @@ katex-rs = { path = "native/vendor/katex-rs-0.3.0" }
mermaid-rs-renderer = { path = "native/vendor/mermaid-rs-renderer-0.3.1" }
cpal = { path = "native/vendor/cpal-0.18.2" }
i-slint-backend-android-activity = { path = "native/vendor/i-slint-backend-android-activity-1.18.1" }
ndk = { path = "native/vendor/ndk-0.9.0" }
[profile.release]
lto = "thin"
+20 -1
View File
@@ -97,7 +97,7 @@ components:
## Overview
**North Star: "The official TeamSpeak 6 client, value for value."**
**Desktop North Star: "The official TeamSpeak 6 client, value for value."**
The owner asked for the installed TeamSpeak 6 client's design, without reinterpretation. Two earlier
TeamsPeach worlds (flat warm-neutral, then the Liquid Glass approximation) are retired. The target values
@@ -115,6 +115,25 @@ and historical non-brand pictograms, have provenance/redistribution limitations
The official JavaScript application and removed browser implementation are historical references only,
not product runtime dependencies. Native cutover does not establish visual or functional acceptance.
### Android: Room (approved 2026-11-15)
The owner selected the entire **Room** direction from the interactive Android comparison, not a blend
of the alternatives. This is an Android-only exception to desktop source parity. The reference is the
Room variant in `target/tmp/android-ui-concepts/` and its captures in `target/tmp/android-ui-review/`;
these local design artifacts are not native-runtime acceptance evidence.
The current voice channel is the primary surface: centered channel/server context, a responsive grid
of participants, speaking emphasis from actual state, and a persistent rounded voice-control strip.
Channels, channel chat, and profile/settings have separate labelled navigation destinations. Secondary
server, contact, file and moderation operations remain reachable rather than being removed for visual
simplicity. Phone navigation changes to a rail/split arrangement at wider windows.
Start with the TS6 palette and bundled Noto Sans, but allow Android users to edit accent, background,
surface and text colors through a preview/save/cancel/reset workflow. Accent fill and readable accent
text are separate roles; user palettes must not make controls or status labels illegible. Insets,
IME, font scale, Back, focus and hold-release behavior constrain the layout. The installed Windows
baseline, its three-pane composition, and its preference behavior are unchanged.
## Colors
Dark is the default for new profiles; light follows the official light module. Native stock token data
+11
View File
@@ -26,3 +26,14 @@
`teamspeak-client-sounds-PROVENANCE.md`. They are not relicensed by TeamsPeach.
- TeamSpeak is a trademark of TeamSpeak Systems GmbH. TeamsPeach is an independent client and is not
affiliated with or endorsed by TeamSpeak Systems GmbH.
- Android uses Rust Mobile `ndk` 0.9.0 (MIT OR Apache-2.0; the MIT alternative is reproduced in
`native/vendor/ndk-0.9.0/LICENSE-MIT` from upstream revision
`49bbbba16c58ff63cb8a0ad0eca5a9fb7ecaec25`). The vendored archive is
`https://static.crates.io/crates/ndk/ndk-0.9.0.crate`, SHA-256
`c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4`.
Its only source patch exposes and documents the existing builder/stream `as_ptr` methods in
`src/audio.rs`; no struct layout, dependency, feature or Android API-level requirement changes.
The archive hash identifies the pristine upstream package, not the locally patched directory.
Cargo uses the root `[patch.crates-io]` path, so its lockfile path entry must not retain the
upstream registry `source`/`checksum`; no fabricated `.cargo-checksum.json` is added.
CPAL remains the single audio backend and resolves optional API28 attribute functions at runtime.
+85 -35
View File
@@ -84,37 +84,93 @@ Develop the existing Rust/Slint Android client on Windows; build/package on a se
Linux x64 machine. This can be the prepared Gitea workflow **or another developer's WSL2 Linux**.
WSL, Docker and an Android build SDK are **not required on this developer PC**. Tool installation and
resource limits belong to the chosen build machine; do not copy `mobile-build.local.md` or local
Windows compiler overrides to it. CI provisioning is currently deferred in favor of application work.
Windows compiler overrides to it. Gitea automatically builds the test APK on trusted mobile-branch pushes.
Pinned WebRTC's [official Android source-build documentation](https://github.com/webrtc-sdk/webrtc/blob/9c3a1386f07e4348c28cd85c066821cebc3b56e4/docs/native-code/android/README.md)
states “Android development is only supported on Linux.” This is a build-host requirement,
not a requirement to run Linux locally. A Windows WebRTC Android source build is not a supported
alternative. Keep the full **Skia + WebRTC** feature set and pinned-source/receipt checks.
#### CI administrator prerequisites
#### Automatic Gitea Android APK builds
The manual [`android-ci`](.gitea/workflows/android.yml) workflow is separate from the Linux desktop
workflows above. Before dispatch, an administrator must enable Gitea Actions and artifact support,
register a dedicated **Linux x64** runner labelled `teamspeach-android-linux-x64`, and provision its
toolchains and repository variables. Their presence is not established merely by committing the workflow.
[`android-ci`](.gitea/workflows/android.yml) runs on every push to **`feature/mobile-port`**.
It does not run on main, release tags or pull requests, and never publishes releases or uses a phone.
It selects the existing `ubuntu-latest` runner and an isolated official `ubuntu:24.04` job container.
The owner authorized Android SDK license acceptance and tool installation **inside that container only**.
No Android repository variables or preinstalled Android runner label are required.
| Repository variable | Required existing runner installation/input |
Before checkout, cache restore or package installation, the job requires a conservative **100 GiB free
disk** on workspace and container root, and **8 GiB available RAM**. Setup additionally accounts for
visible ancestor cgroup limits. This is a provisioning floor, not a measured maximum or a memory cap;
runner administrators must provide resource isolation/storage. The earlier runner had only about21GiB
free, so a job can stop at this gate until an administrator expands build storage. No automatic disk
expansion, host installation, privileged Docker socket or deletion of other jobs' files is performed.
`.gitea/setup-android-ci.sh` installs Ubuntu JDK21/LLVM18/libclang/CMake/Ninja prerequisites, then
checksummed pinned downloads listed in `.gitea/android-ci-tools.json`: Rust1.96.0, SDK36,
build-tools36.0.0, NDK28.2.13676358, Gradle8.14.3, synced Skia m153-0.101.2 and bundletool.
The output environment also supplies full NDK, ANDROID_JAR and Skia inputs needed by the real first build.
CI uses every CPU available to its container (`nproc`) for Cargo/Ninja/CMake, with a six-hour job deadline;
the developer PC's one-job memory policy and Windows-only optimization overrides do not apply here. `xtask deps`
regenerates dependency provenance; `build/package/verify-package` use the
existing full Skia+WebRTC path. Production signing environment is rejected.
Android CI uses normal workspace release optimization with runner-wide parallelism.
Only if a new build demonstrates memory exhaustion may the separately authorized low-memory
fallback be enabled: `TEAMSPEACH_ANDROID_LOW_MEMORY=true` selects codegen-units256/lto=off for only
`teamspeach_native/aarch64-linux-android` through `.gitea/android-rustc-low-memory.sh`. All features stay
enabled and `build-info.json` records the variant. Other targets and Windows settings remain unchanged.
Before APK compilation, CI runs actual native audio-worker, capture-transition and core-audio tests
on Linux x64 with `--no-default-features`. These offline test binaries use a separate
`.android-ci/host-audio-target` cache and test-only opt-level1/debug0 to exercise long SRC histories;
they do not alter Android release settings. Container-only host prerequisites include PipeWire/SPA
development libraries. A failed host test blocks packaging; logs are retained as
`native-audio-tests-linux-x64-<SHA>`. Host tests do not establish physical-device or voice acceptance.
Tools/downloads/SDK/Skia/Gradle/Cargo caches live under ignored `.android-ci/`. Tools-v3 keys
separate pinned tool/setup compatibility from Cargo.lock and source SHA: a changed lock first looks
for matching registry sources, then falls back within the same tool contract. Provisioning still
verifies the pinned tools and resolves any newly required sources. Tool/Cargo state is checkpointed
after successful dependency provisioning, before compiling the app; the final successful job saves
a newer checkpoint. Private signing keys and profiles are excluded.
A separate application-v2 cache keeps the actual `.android-ci/cargo-target` and a content snapshot.
Its compatibility identity is computed **after setup** from toolchain, target, optimization profiles,
Cargo config and the stable build environment, not Cargo.lock, dependency declarations or source
contents. Cargo fingerprints invalidate changed inputs. Only path/SHA-256/type/mode-matched inputs
regain their recorded mtimes; changed inputs are never backdated and fail closed if their timestamp
predates the cached compilation. Verified WebRTC inputs are considered only after the mandatory
`xtask deps` run. Cargo build-start timestamps are recorded/reported, never rewritten. Every hit
still runs revision checks, dependency provenance regeneration and full build/package verification.
The old tools-v2/application-v1 opaque hashes cannot prove this independent compatibility contract,
so this migration needs one cold cache generation; there is no unverified legacy fallback.
A separate exact-key cache keeps `target/native-deps/aarch64-linux-android`, including pinned Git
checkouts and Ninja objects. Its key excludes completed build receipts but includes source policy,
tool pins and dependency drivers; there is no cross-policy fallback. Every cache hit still runs
`xtask deps`: checkouts, patches, GN inputs and artifacts are checked and current provenance is
regenerated before use. The repository lock is never overwritten by a cached copy.
Before gclient sync, CI reverses only source diffs byte-identical to the restored provenance receipt;
unexpected modifications fail closed. Pinned patches are then reapplied by xtask. No reset/clean of
cached source or object outputs is used.
These potentially large checkpoints require runner cache storage/capacity; cache misses remain valid
cold builds. Before/after cgroup counters and `/usr/bin/time -v` data are retained as a separate
`android-build-resources-<SHA>` artifact even when native compilation fails, to diagnose SIGKILL
without assuming OOM. No host kernel logs, credentials or process argument dumps are collected.
The artifact is **`android-harness-arm64-<full commit SHA>`**, retained14days, containing the test APK
and revision/hash/build/dependency/package receipts. Unsigned production APK/AAB remain available via
the explicit local Linux helper, not built automatically on every push.
For a separately prepared Linux/WSL host, use these existing inputs instead of CI provisioning:
| Environment variable | Required existing input |
| --- | --- |
| `ANDROID_SDK_ROOT` | Android SDK with API 36, `build-tools/36.0.0` and `ndk/28.2.13676358` |
| `ANDROID_JAVA_HOME` | JDK 17+ including `keytool` (JDK 21 is acceptable) |
| `NATIVE_LLVM_HOME` | LLVM tool directory used by `xtask` |
| `NATIVE_LIBCLANG_PATH` | libclang library directory |
| `NATIVE_SKIA_SOURCE_DIR` | Dependency-synchronized Skia source checkout containing `bin/gn` |
| `ANDROID_GRADLE_DISTRIBUTION` | Local `gradle-8.14.3-bin.zip`; bootstrap verifies its committed SHA-256 |
| `ANDROID_BUNDLETOOL` | Local `bundletool.jar` for AAB inspection |
| `ANDROID_SDK_ROOT` | SDK API36, build-tools36.0.0, NDK28.2.13676358 |
| `JAVA_HOME` | JDK21 |
| `LLVM_HOME`, `LIBCLANG_PATH` | Matching Linux LLVM/libclang |
| `SKIA_SOURCE_DIR` | Dependency-synchronized Skia m153-0.101.2 with bin/gn |
| `TEAMSPEACH_GRADLE_DISTRIBUTION` | Local wrapper-checksummed Gradle8.14.3 ZIP |
| `TEAMSPEACH_BUNDLETOOL` | Local bundletool JAR |
Also provision the pinned Rust toolchain and `aarch64-linux-android` target, Python 3, Git, CMake,
Ninja and required Linux native-build dependencies. The workflow does not install system SDKs or
download a Gradle distribution. It source-builds pinned WebRTC via `xtask deps`, builds the ARM64
application, packages both variants and runs `verify-package`. Its explicit `--gradle-online true`
allows Gradle dependency resolution on CI; the ordinary packaging default remains offline.
Provision runner resources for the full native build; local developer-machine limits are not a CI policy.
No production signing credentials are needed or used by this unsigned-artifact workflow.
#### Handoff to another developer's WSL2 machine
@@ -180,20 +236,14 @@ does not establish phone UI, permissions, audio routes, foreground behavior or t
#### Dispatch, download and install from Windows
1. Deliver the source changes through the normal authorized repository process. In the repository's
**Actions** page select **android-ci** (`android.yml`) and choose the intended branch/ref.
The default **inventory** mode runs a read-only, five-minute resource/tool inventory on the existing
`ubuntu-latest` runner, without checkout, downloads, builds or installation. It reports configured
variable presence, not their values; an inventory pass does not mean Android build readiness.
Select **build** explicitly only after provisioning the dedicated Android runner and variables above.
This workflow has no automatic push/tag trigger and does not publish releases.
2. Only after an actual successful run, download and extract **`android-harness-arm64`** and
**`android-production-unsigned-arm64`**. Each bundle includes root `build-info.json` identifying
the exact revision, package manifests/hashes and `aarch64-linux-android` package-verification,
native-build and dependency JSON receipts. Match the run/ref and APK SHA-256 to that evidence
before installing; a bare APK is not provenance.
For version `0.1.7`, the harness APK is `TeamsPeach-0.1.7-android-arm64-harness-test.apk`; the
production bundle contains `TeamsPeach-0.1.7-android-arm64-unsigned.apk` and `.aab`.
1. Push the authorized source changes to `feature/mobile-port`; **android-ci** starts automatically.
For a manual run select the intended ref and **build** (default), or **inventory** to inspect only
basic resources without checkout/provisioning. Main and release publishing are separate routes.
2. After an actual successful build, download **`android-harness-arm64-<full commit SHA>`**.
The bundle includes root `build-info.json` identifying the exact revision and SHA256 hashes, plus
`aarch64-linux-android` package-verification, native-build and dependency receipts. Match run/ref
and APK SHA256 before installing; a bare APK is not provenance.
For version0.1.7 the harness is `TeamsPeach-0.1.7-android-arm64-harness-test.apk`.
Use the version actually recorded by the selected run, not a stale download.
3. Use a separate **ARM64 Android 8/API 26+ test device**, enable USB debugging and approve this
PC's debugging authorization. From the extracted harness APK directory in PowerShell, with
+3
View File
@@ -34,6 +34,9 @@ tokio = { version = "1", features = ["rt", "macros", "io-std", "io-util", "sync"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
[target.'cfg(target_os = "android")'.dependencies]
fs2 = "=0.4.3"
[target.'cfg(windows)'.dependencies]
windows-core = "0.62.2"
windows = { version = "0.62.2", features = [
+51
View File
@@ -0,0 +1,51 @@
//! Descriptor-owned advisory locks. Rust 1.96 std lacks Android flock support.
//! Other platforms keep std semantics; dropping the File releases the lock.
use std::{fs::{File, TryLockError}, io};
pub fn lock(file: &File, shared: bool) -> io::Result<()> {
#[cfg(target_os = "android")]
{ if shared { fs2::FileExt::lock_shared(file) } else { fs2::FileExt::lock_exclusive(file) } }
#[cfg(not(target_os = "android"))]
{ if shared { file.lock_shared() } else { file.lock() } }
}
pub fn try_lock(file: &File, shared: bool) -> Result<(), TryLockError> {
#[cfg(target_os = "android")]
{
let result = if shared { fs2::FileExt::try_lock_shared(file) } else { fs2::FileExt::try_lock_exclusive(file) };
result.map_err(|error| if error.kind() == io::ErrorKind::WouldBlock {
TryLockError::WouldBlock
} else { TryLockError::Error(error) })
}
#[cfg(not(target_os = "android"))]
{ if shared { file.try_lock_shared() } else { file.try_lock() } }
}
#[cfg(test)]
mod tests {
use super::*;
use std::{fs::{self, OpenOptions}, sync::atomic::{AtomicU64, Ordering}};
#[test]
fn owners_exclude_writers_share_readers_and_release_on_drop() {
static NEXT: AtomicU64 = AtomicU64::new(0);
let path = std::env::temp_dir().join(format!("teamspeach-lock-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let open = || OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&path).unwrap();
let writer = open();
try_lock(&writer, false).unwrap();
let contender = open();
assert!(matches!(try_lock(&contender, false), Err(TryLockError::WouldBlock)));
assert!(matches!(try_lock(&contender, true), Err(TryLockError::WouldBlock)));
drop(writer);
lock(&contender, true).unwrap();
let reader = open();
try_lock(&reader, true).unwrap();
let next_writer = open();
assert!(matches!(try_lock(&next_writer, false), Err(TryLockError::WouldBlock)));
drop(reader);
drop(contender);
try_lock(&next_writer, false).unwrap();
drop(next_writer);
fs::remove_file(path).unwrap();
}
}
+1
View File
@@ -3,6 +3,7 @@ pub mod admin;
pub mod app_audio;
pub mod audio;
mod events;
pub mod file_lock;
pub mod file_transfer;
pub mod hotkeys;
mod keyfmt;
+1 -1
View File
@@ -8,7 +8,7 @@ pub fn lock_dir(dir: &Path, shared: bool) -> Result<File, String> {
let path = dir.join("core.lock");
let file = OpenOptions::new().create(true).truncate(false).write(true).open(&path)
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
match if shared { file.try_lock_shared() } else { file.try_lock() } {
match crate::file_lock::try_lock(&file, shared) {
Ok(()) => Ok(file),
Err(TryLockError::WouldBlock) => Err(format!("data dir {} is in use by another teamspeach-core", dir.display())),
Err(TryLockError::Error(e)) => Err(format!("cannot lock {}: {e}", path.display())),
+4 -4
View File
@@ -561,7 +561,7 @@ impl Store {
.write(true)
.open(&path)
.map_err(io_err(format!("opening {}", path.display())))?;
file.lock().map_err(io_err(format!("locking {}", path.display())))?;
crate::file_lock::lock(&file, false).map_err(io_err(format!("locking {}", path.display())))?;
Ok(file)
}
@@ -584,7 +584,7 @@ impl Store {
/// True while a connection core holds the identity (informational; delete re-checks).
fn in_use(&self, uid: &str) -> bool {
let Ok(file) = fs::OpenOptions::new().write(true).open(self.use_path(uid)) else { return false };
match file.try_lock() {
match crate::file_lock::try_lock(&file, false) {
Ok(()) => false,
Err(TryLockError::WouldBlock) => true,
Err(TryLockError::Error(_)) => false,
@@ -674,7 +674,7 @@ impl Store {
};
let lock = self.open_use_file(&uid)?;
// Blocks only while a delete of this identity holds it exclusively (a few file operations).
lock.lock_shared().map_err(io_err(format!("locking {}", self.use_path(&uid).display())))?;
crate::file_lock::lock(&lock, true).map_err(io_err(format!("locking {}", self.use_path(&uid).display())))?;
// A delete that finished while we waited has removed it.
let vault = self.load_vault()?;
let e = vault.find(&uid).ok_or_else(|| StoreError::NotFound(uid.clone()))?;
@@ -833,7 +833,7 @@ impl Store {
return Err(StoreError::DeleteRefused("the default identity cannot be deleted; choose another default first".into()));
}
let guard = self.open_use_file(uid)?;
match guard.try_lock() {
match crate::file_lock::try_lock(&guard, false) {
Ok(()) => {}
Err(TryLockError::WouldBlock) => return Err(StoreError::InUse),
Err(TryLockError::Error(e)) => return Err(io_err(format!("locking {}", self.use_path(uid).display()))(e)),
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+124 -438
View File
@@ -1,468 +1,154 @@
# Оценка мобильного порта TeamsPeach: Android и iOS
# Мобильный порт: архитектура и ограничения
## Актуализация: native-only cutover, 2026-11-10
Актуально на **2026-11-15**. Device-база `8074343` / APK4955; TX-кандидат прошёл CI4959, но headset TX не принят.
Room UI `87265a3` прошёл CI4972; уточнения кандидата и device-проверки — в [handoff](mobile-port-progress.md).
Этот документ — карта действующей системы, не история расследований.
Предел: 200 строк / 16 KiB; обновлять разделы, а не дописывать каждый запуск CI.
По прямому решению владельца удаляется Electron-клиент, npm manifests и его browser-only tooling. Единственный application host — Rust/Slint в `native/`; core подключается как Rust-библиотека. Это архитектурное переключение, не утверждение о пройденной мобильной приёмке.
## 1. Архитектура
- Сохраняются `core::runtime`, нативный CPAL/Sonora/Opus аудиотракт, Slint UI, Android/iOS OS adapters и безопасный импорт прежних профилей.
- Ресурсы клиента переходят в `native/resources/`, версия и команды сборки — Cargo/xtask. Renderer-only WASM ABI и npm/Electron packaging больше не являются частью продукта.
- Текущие команды и build prerequisites см. в [README](../README.md), результаты последней проверки — в [передаче состояния](mobile-port-progress.md). Исследовательский запрет первой стадии не относится к отдельно разрешённому cutover.
- Прежние выводы о двух действующих hosts и выборе между ними ниже **исторические**. Rust/Slint теперь выбранная архитектура; Android/iOS runtime, interruption resume, Bluetooth и лицензионные вопросы по-прежнему требуют отдельных доказательств.
- Весь исходный разбор ниже сохранён как снимок `eb24965076599267687c8c4dd6f24f22953b15f6`; source citations закреплены за этой ревизией, включая удалённые файлы. Не использовать старые npm-команды и Electron passes для текущего дерева.
---
## Исторический первичный разбор
## 1. Ревизия, метод и границы доказательства
- **Дата исследования:** 2026-11-10 (UTC).
- **Репозиторий:** TeamsPeach/client; публичный адрес указан в [AboutService](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/services/about.rs#L10-L12).
- **Изученный HEAD:** `eb24965076599267687c8c4dd6f24f22953b15f6`, ветка `main`.
- **Исходное рабочее дерево:** чистое по `git status --porcelain=v1`; 2221 tracked-файл. Корень и разрешённые выходные каталоги проверены по метаданным; среди tracked-путей не обнаружено symlink/junction/reparse points.
- **Вопрос:** что реально можно переиспользовать для одинакового по функциям клиента Android/iOS, какие OS-адаптеры уже существуют и что нужно проверить до выбора окончательного UI и начала реализации.
- **Охват:** Electron reference-клиент, Rust `core/`, `dsp/`, `native/`, Android/iOS hosts, build/CI/test recipes; точечно — манифесты, provenance и значимые локальные изменения vendored-зависимостей. История коммитов и пользовательские профили не исследовались.
- **Исключено:** значения секретов, `.env*`, приватные ключи и identity-файлы, runtime-хранилища, бинарные ресурсы, массовое чтение стороннего vendor, запуск приложения, сборок, установочных скриптов и тестов. Наличие кода хранилища `secrets.rs` не означает чтение самого хранилища.
- **Метод:** первичное статическое картирование установленным Understand-Anything; затем отдельные трассировки Codebase Knowledge Builder. Существенные выводы основаны на исходниках, не на графе. Официальные документы зависимостей проверены отдельно, ссылки — в §8 и §9.
- **Обозначения:** **Факт** — непосредственно наблюдается в коде/конфигурации или официальной документации; **Вывод** — инженерная интерпретация с основанием; **Неизвестно** — нужен отсутствующий результат сборки, запуска, измерения или правовое разрешение; **План** — предлагаемая работа, не выполненная реализация.
- Ссылки `../path#Lx-Ly` относятся к указанному HEAD. Локальный Markdown viewer может не поддерживать line anchors; путь, символ и номера строк остаются координатами доказательства.
**Ни статический разбор, ни граф, ни наличие теста не доказывают работоспособность на телефоне. В этой сессии нет результатов Android/iOS-сборки, подключения к серверу или голосового обмена.**
## 2. Главный вывод
**Факт:** это уже не только Electron-приложение. В репозитории сосуществуют Electron reference-клиент и существенная Rust/Slint-реализация с Android/iOS-платформенными мостами. `native` зависит от `teamspeach-core` как Rust-библиотеки; Android использует `cdylib`/`android_main`, iOS — Rust executable и Winit/Skia. См. [workspace](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/Cargo.toml#L1-L41), [native manifest](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/Cargo.toml#L8-L30), [mobile target dependencies](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/Cargo.toml#L82-L100), [entry points](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/lib.rs#L115-L125), [iOS project](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/ios/project.yml#L50-L74).
**Вывод:** исходная стратегия — не переписывать клиент с нуля, а сначала проверить существующее embedded Rust-ядро и мобильную ветку. Наименьший объём новой архитектуры даёт продолжение Rust/Slint **при условии** прохождения сборочных, аудио-, accessibility- и лицензионных гейтов. Это рекомендация после установления границ ядра, а не заранее выбранный UI.
**Факт:** `native/compatibility.json` прямо обозначен как pending acceptance inventory, а не реестр работающих функций; 718 пунктов не являются 718 пройденными проверками. [Статус и ограничения](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/compatibility.json#L1-L36). README также называет native migration незавершённой: [README](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/README.md#L22-L26).
**Основные препятствия:**
1. Нет мобильного completed-build record в `native/native-deps.lock.json#/builds`: на момент чтения там только `x86_64-pc-windows-msvc`. Штатный `xtask build` откажет без per-target provenance: [deps::verify](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/deps.rs#L729-L747).
2. Штатный source-build требует Linux для Android и macOS для iOS; текущая Windows-среда не подходит для этих маршрутов: [Target::check_host](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/deps.rs#L28-L50).
3. В цепочке восстановления iOS аудиосессии найден незадействованный `CallLease::resume`; общий обработчик окончания interruption сам не восстанавливает output. Подробности и оговорки — §7.
4. Не подтверждены двусторонний голос, AEC, Bluetooth, фон, сетевой handoff и доступность интерфейса на физических телефонах.
5. Для распространения нет предоставленной open-source лицензии собственного кода; у заимствованных иконок и звуков не установлены права на redistribution: §9.
## 3. Архитектура и реальные границы повторного использования
```mermaid
flowchart LR
N1["Electron UI и AudioWorklet"] --> N2["preload и Electron main"]
N2 -->|"JSON-lines и PCM base64"| N3["core CLI stdio"]
N4["Общий Slint UI"] -->|"типизированные намерения"| N5["AppRuntime и ConnectionManager"]
N6["Android / iOS lifecycle"] --> N5
N5 -->|"CoreHandle / Command"| N7["Session и протокол TeamSpeak"]
N3 --> N7
N8["CPAL и Sonora DSP"] -->|"CapturedFrame"| N5
N7 -->|"decoded PCM"| N8
N7 <-->|"TeamSpeak UDP / Opus"| N9["Сервер TeamSpeak"]
N10["WebRTC peers трансляций"] -->|"декодированное аудио"| N8
```
Основания: [core embedded API](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/runtime.rs#L7-L26), [spawn](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/runtime.rs#L81-L138), [AppRuntime](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/lib.rs#L43-L110), [AudioSessionBinding](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/media_binding.rs#L18-L65), [Electron IPC](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/main/main.js#L498-L548), [отдельный WebRTC peer](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/stream/peer.rs#L45-L56).
| Компонент | Что подтверждено | Решение для мобильного клиента |
|---|---|---|
| `core::runtime::{CoreHandle,CoreEvents}` | `request(Command)`, `push_audio(CapturedFrame)`, control/playback receivers, управляемое shutdown; один worker/current-thread Tokio runtime на core. [API](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/runtime.rs#L44-L78), [spawn](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/runtime.rs#L81-L138) | **Переиспользовать.** Это существующая граница без UI и stdio; не нужно делать subprocess на телефоне. |
| `Session`, `protocol`, identity, channels, Opus/VAD | Общие для двух хостов; OS capture находится вне Session. [lib modules](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/lib.rs#L1-L28), [connect/join](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L505-L632) | **Переиспользовать с проверкой cross-build.** Сам crate не целиком platform-free: содержит desktop hotkeys/app-audio, файловую работу и нативный Opus. |
| `ConnectionManager` | До 8 соединений, отдельные `SessionKey`, выбранный input owner, capture permit после подтверждений core. [типы](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/connections.rs#L23-L108), [input acknowledgement](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/connections.rs#L503-L539) | **Переиспользовать.** Видимая вкладка не должна неявно менять получателя микрофона. |
| `native` app/services | Shared runtime, snapshots, intents; UI generation отделён от process runtime. [AppRuntime](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/lib.rs#L43-L103) | **Переиспользовать**, проверить storage/lifecycle/platform policy. Наличие ссылок на типы `ui::shell` означает, что app layer ещё не отдельный UI-neutral FFI SDK. |
| Sonora capture DSP, VAD, mixer, SRC | Rust-обработка отделена от device callback; 10/20-мс блоки, временные метки и epochs. §6 | **Переиспользовать**, но измерить CPU, drift, reference и акустическое качество на ARM64. |
| CPAL devices, Android/iOS audio session | Есть native device abstraction и OS callbacks. [hosts](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/devices.rs#L89-L110), [lifecycle](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/lifecycle.rs#L5-L32) | **Адаптеры уже есть; требуется доведение и проверка**, а не замена всего аудиоядра. |
| Slint UI | Общие `.slint` и Rust projections, platform-specific backend dependencies. [manifest](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/Cargo.toml#L82-L96), [binding](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/ui/application.rs#L31-L69) | **Первый кандидат на сохранение.** Функциональная и визуальная идентичность Android/iOS должна быть проверена сценарием, не выводится из общего исходника. |
| Electron main/preload/stdio transport | Зависит от Electron/Node, BrowserWindow, IPC, child process. [package](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/package.json#L5-L26), [CoreProcess](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/main/core-process.js#L169-L214) | **Заменить хост**, уже имеющимся native runtime. Не переносить Electron на Android/iOS. |
| HTML/CSS/JS reference UI | DOM и браузерные API; логика взаимодействия распределена по UI и main. [voice](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/voice.js#L129-L191), [capture](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/audio/engine.js#L279-L399) | Использовать как **reference поведения**, тексты/схемы — после проверки лицензии и эквивалентности. Не обещать прямой перенос DOM в Flutter/React Native. |
| Desktop OS-сервисы | rfd/arboard/open/tray отделены target cfg; Linux DBus/X11, Windows APIs и desktop capture. [dependencies](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/Cargo.toml#L65-L96), [platform modules](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/mod.rs#L1-L12), [core OS deps](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/Cargo.toml#L37-L61) | **Заменить OS-эквивалентами:** SAF/document picker, Keystore/Keychain, notification/service, touch PTT. Не имитировать tray/autostart/global hooks на мобильных. |
| WebRTC screenshare | Отдельные media peers, не транспорт основного TS-голоса; default native features включают `webrtc`. [features](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/Cargo.toml#L16-L20), [provenance](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/vendor/provenance.json#L170-L179) | Для полной версии сохранить отдельную проверочную очередь. Для первого voice proof **не реализовывать новый WebRTC-голос**; минимизация feature set возможна только как явно проверяемый эксперимент. |
### UI-решение после границы ядра
| Вариант | Что сохраняет | Что добавляет / риск | Условие выбора |
|---|---|---|---|
| Продолжить Rust/Slint | Core, app/services, PCM-тракт, большая часть UI, existing Android/iOS hosts | Зависимость от мобильной зрелости Slint, custom accessibility, лицензия и тяжёлая native сборка | **Рекомендуемый первый прототип**, если проверены реальные UI/audio/lifecycle сценарии. |
| Flutter или React Native поверх Rust | Core и DSP; часть app/services после отделения UI-типов | Новый FFI/async-event ABI, UI-переписывание, владение Rust runtime и платформенные плагины; DOM не становится переносимым автоматически | Только если установлен конкретный непреодолимый недостаток текущего UI, а не ради популярности стека. Поддержка конкретного bridge ещё **не исследована**. |
| Kotlin/Swift UI поверх Rust | Core/DSP и явные OS-интеграции | Два presentation слоя и риск расхождения UX; та же необходимость стабильного FFI | Если системная интеграция/accessibility перевешивает цену двух UI. Сейчас нет доказательства такой необходимости. |
**План паритета:** Android и iOS должны иметь общий каталог действий, ошибок, mute/PTT-состояний, экранов и EN/RU-текстов, общие серверные сценарии и одинаковую семантику подтверждений. System permission dialogs, маршрутизация и фон будут различаться по OS; «идентичная версия» не означает невозможное равенство системных окон. Никакие функции полной версии не исключаются молча: ограничения требуют явной записи и решения владельца.
## 4. Стек, входы, сборка и тесты
### Подтверждённый стек
- Cargo workspace: `core`, `dsp`, `native`, `xtask`; версия приложения `0.1.7`; Rust toolchain `1.96.0`, workspace edition 2024, core edition 2021. [workspace](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/Cargo.toml#L1-L24), [toolchain](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/rust-toolchain.toml#L1-L4), [core](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/Cargo.toml#L1-L18).
- Electron `44.9.3`, plain JavaScript/HTML/CSS, electron-builder `26.15.3`, Playwright tooling. [package.json](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/package.json#L5-L26).
- Slint `1.18.1`, CPAL `0.18.2`, Rubato `5.0.1`, Sonora `0.2.0`, libwebrtc `0.4.0`, webrtc-sys `0.3.53`; локальные patches перечислены в workspace. [pins](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/Cargo.toml#L17-L41). Core использует audiopus `0.3.0-rc.0`, earshot `1.2.2`, vendored tsclientlib с pinned upstream `ee3bc6…`. [core deps](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/Cargo.toml#L14-L35).
- Android: API 26+, compile/target 36, NDK `28.2.13676358`, Java 17, AGP `8.10.1`, ARM64 production и x86_64 emulator. [Gradle](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/build.gradle.kts#L5-L43).
- iOS/iPadOS: deployment target 16.0, ARM64 device и ARM64 simulator, XcodeGen host + ReplayKit extension. [project](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/ios/project.yml#L1-L26), [supported targets](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/deps.rs#L28-L43).
### Точки входа
| Путь / символ | Роль |
| Граница | Реализация и ответственность |
|---|---|
| [app/main/main.js](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/main/main.js#L498-L548), `package.json.main` | Electron composition root и проверяемый IPC. |
| [core/src/main.rs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/main.rs#L1-L40), [core/src/stdio.rs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/stdio.rs#L101-L114) | CLI/stdio host; не требование мобильного embedded runtime. |
| [core/src/runtime.rs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/runtime.rs#L81-L138), `spawn` | Типизированный embedded host с command/control/playback очередями. |
| [native/src/main.rs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/main.rs#L8-L29), `run` | Desktop/iOS executable; `AppRuntime::start(...).and_then(attach_ui)`. |
| [native/src/lib.rs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/lib.rs#L123-L125), `android_main` | Android library entry через Slint Android backend. |
| [native/build.rs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/build.rs#L1-L8) | Компиляция `.slint` и platform glue; **не запускался**. |
| [xtask/src/main.rs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/main.rs#L25-L68) | `deps`, `build`, `package`, `smoke`, `verify-package`; **не запускались**. |
| Клиент | Rust/Slint `native/`; UI отправляет typed intents, не выполняет device/network I/O |
| Протокол | Embedded `core::runtime`; TeamSpeak UDP/Opus для голоса |
| Трансляции | Отдельный libwebrtc тракт; не замена TeamSpeak-голосу |
| Сервисы | `native/src/app/runtime/`, `native/src/services/`: профиль, разрешения, соединения, настройки |
| Аудио | `native/src/media/audio/`: CPAL callback → bounded rings → worker/SRC/DSP |
| Android | `native/src/platform/android.rs` + `platform/android/.../mobile/` Java bridges; AAudio backend |
| iOS | Существующий платформенный адаптер; требует отдельной macOS/Xcode/signing/device проверки |
| Сборка | Cargo/`xtask`; Android workflow `.gitea/workflows/android.yml` |
### Сборочные ограничения
Electron/Node/npm удалены. Не возвращать второй host или параллельный стек.
Версия — Cargo workspace; ресурсы — `native/resources/`; toolchain/dependency pins —
`rust-toolchain.toml`, `.gitea/android-ci-tools.json`, `native/native-deps.lock.json`.
**Факт:** старый Electron recipe строит core и DSP WASM, затем запускает Electron: [README development](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/README.md#L12-L26). Он не создаёт APK/IPA.
## 2. Что действительно проверено
**Факт:** native recipe source-build-only: `xtask deps` provision-ит pinned WebRTC, `build` проверяет provenance и устанавливает `LK_CUSTOM_WEBRTC`; тихой загрузки случайного prebuilt нет. [deps policy](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/deps.rs#L1-L19), [verify](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/deps.rs#L729-L747), [build](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/build_native.rs#L238-L307). Для Android нужны SDK36/NDK r28+, JDK и Linux source-build host; для iOS — macOS/Xcode SDK. [prerequisites](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/build_native.rs#L170-L198). iOS на данной Windows-машине штатным маршрутом не собирается; Android также требует другого build host, хотя Android вообще не ограничен Linux вне этого recipe.
- Windows0.1.7: владелец принял connect, channel join и двусторонний голос. База — `main`,
`desktop-baseline-0.1.7-20261111`. Поздние мобильные изменения не равны новой Windows-приёмке.
- Android: реальные Linux CI builds, ARM64 APK, установка и запуск на TECNO KJ7.
- Обычный Android voice ранее принят на `f403dd5` / run4931; фон Home/screen-off принят отдельно.
- На **4955** владелец подтвердил **RX через G435**. TX при headset unmute ещё ломается;
успешные host fixtures не доказывают физический duplex.
- Два независимых мобильных input/output-селектора стоят рядом. Unified combination picker отменён.
- Полный функциональный parity, реальный Wi-Fi↔cellular handover, длительный endurance, iOS и
повторный вход после Recents не считать принятыми. Длительность — наблюдение обычного использования.
**Факт:** `.cargo/config.toml` принуждает static bundled Opus/CMake. WebRTC имеет свой Opus; `namespace_opus` специально разделяет символы, чтобы линкер не выбирал случайную реализацию. [Opus flags](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/.cargo/config.toml#L1-L9), [изоляция символов](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/deps.rs#L464-L468). Android также требует согласованный prefixed `libwebrtc.jar` и ARM64 ELF alignment 16 KiB. [Gradle input gates](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/build.gradle.kts#L61-L74), [binary gates](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/build_native.rs#L274-L322).
## 3. Аудиотракт и инварианты
**Неизвестно:** доступность SDK, source-build artifacts, signing, физического Android/iPhone и Mac/Linux host для следующего этапа. Секреты signing не читались, подключённые устройства не опрашивались. Единственный Windows record в lock — не гарантия наличия даже его локальных бинарников и тем более не доказательство мобильной сборки.
### Владение и данные
### Команды, найденные или выведенные из существующих test entry points
- Core voice boundary: mono `i16`,48kHz,960 samples/20ms. Native mixer/DSP работают блоками10ms.
- `engine.rs::Worker` обслуживает PCM; `lifecycle.rs` отдельно владеет CPAL construct/start/drop,
тяжёлой подготовкой DSP и уведомлений. `StreamOwner` не переносится между потоками.
- `devices.rs` callbacks используют готовые буферы и bounded rings, без I/O/выделений в нормальном пути.
- `resample.rs` выполняет SRC и отслеживание аппаратных часов. Hardware timestamps не заменять
временем worker; реальные пропуски/реверсы кадров не скрывать автосбросом.
- Sonora — владелец AEC/NS/AGC capture. Reference берётся из реально записанного выходного PCM;
не добавлять второй AEC поверх него без отдельного проектного решения.
Все команды ниже — **справка для следующего разрешённого этапа; не выполнены**.
### Разрешения и приватность
| Команда | Что проверяет / ограничение | Основание |
|---|---|---|
| `npm test` | Node tests `test/*.test.*`; часть desktop-path tests использует Electron/harness, не mobile proof | [package scripts](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/package.json#L10-L21), [CI](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/.gitea/workflows/ci.yml#L45-L71) |
| `cargo test --manifest-path core/Cargo.toml --locked` | Core unit/integration: protocol, identity, audio, embedded runtime | [CI](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/.gitea/workflows/ci.yml#L53-L63), [embedded](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/tests/embedded.rs#L16-L57), [runtime_failures](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/tests/runtime_failures.rs#L40-L111) |
| `cargo test --manifest-path dsp/Cargo.toml --locked` | DSP tests, не акустика реального speakerphone | [CI](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/.gitea/workflows/ci.yml#L45-L48), [capture tests](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/dsp/src/capture/tests.rs#L34-L145) |
| `cargo test -p teamspeach-native --test connections --locked` | Offline identity/session/generation ownership; требуется native build environment | [connections tests](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/tests/connections.rs#L37-L145) |
| `cargo test -p teamspeach-native --test audio_binding --locked` | Подтверждения input reset и корректное освобождение audio/manager | [audio_binding](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/tests/audio_binding.rs#L6-L36) |
| `cargo run -p xtask -- smoke --target <triple> --scenario offline-ui --device <explicit-id> --app <test-app> --out <fresh-dir>` | Имеющийся mobile smoke: Android выбранный APK/device; iOS выбранный simulator. Не живой голос | [CLI](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/main.rs#L35-L49), [Android/iOS smoke](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/smoke.rs#L61-L103) |
- Разрешение ОС само не включает запись. Нужны текущий владелец, acknowledged CapturePermit,
поколение/epoch, явное намерение и допустимое состояние focus/lifecycle.
- Более поздний mute, revocation, permission loss или завершение звонка всегда сильнее позднего ACK.
- Не перепривязывать старый PCM к новому epoch, не проигрывать старую очередь после восстановления.
- Удаление из Recents завершает call/capture; нет sticky restart. Home/screen-off сохраняют уже
разрешённый обычный звонок, но отпускают PTT/whisper holds.
- Точный выбор устройства не заменять default/другим устройством молча. Capability failure явный.
Штатный smoke требует `test-harness` build, запрещает network/OS actions/physical capture в отчёте; `media-loopback` не равен live TeamSpeak interoperability. [guards](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/smoke.rs#L13-L49). `codec-fixtures` CLI прямо не выполняется на Android/iOS: [mobile rejection](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/smoke.rs#L104-L106). CI в просмотренном workflow покрывает Linux x64 и GNU ARM64/qemu, **не Android и не iOS**: [jobs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/.gitea/workflows/ci.yml#L16-L20), [ARM job](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/.gitea/workflows/ci.yml#L81-L130).
### Принятый Android RX — сохранять
## 5. Подключение, авторизация, каналы и сеть
- Голосовой выход использует VOICE_COMMUNICATION/SPEECH на API28+; отдельные notification streams — MEDIA.
- API26 остаётся minimum: дополнительные AAudio symbols разрешаются динамически через vendored
`ndk0.9` borrowed-pointer accessors. На26/27 явно остаётся LegacyMediaDefault.
- AAudio `play()` требует Started и аппаратный output timestamp до публикации потока.
Во время получения timestamp — тишина; бюджет старта2s, без ложного перехода now→hardware time.
Startup xrun baseline отделён от новых live xruns; последующие faults не замалчиваются.
- Android проверяет исходную свежесть PCM при передаче в callback, не добавляя downstream Bluetooth
latency к сроку200ms. Epoch/mute/queue guards сохраняются; desktop presentation policy прежняя.
- Начало switch/CLEAR, OS callbacks и caller recovery согласуются по ревизиям; startup ACK не
возвращает отозванный focus. Ошибка playback не должна называться ошибкой микрофона.
### Нормальный путь — подтверждён по исходникам
## 4. Текущая проблема TX и неподтверждённая правка
1. **UI → host.** Electron `submitConnect/connectTo` → IPC allowlist → `ConnectionManager.request` → `CoreProcess.request`/stdin. Native Slint intent → AppRuntime worker → `connect_with_audio` → embedded `Command::Connect`. [Electron](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/app.js#L699-L766), [IPC](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/main/main.js#L498-L521), [native](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/runtime/local_actions/connections.rs#L42-L79).
2. **Identity вместо облачной учётной записи.** `Store::open_for_connect` выбирает identity/default и nickname, удерживает use-lock. Создание P-256 identity и security-level work — локальные операции; пароль сервера/канала не заменяет identity. [Store](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/profile.rs#L665-L708), [улучшение](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/profile.rs#L765-L783). Runtime-профили и приватные ключи не открывались.
3. **Session::connect** передаёт identity, nickname, mute state, пароли и initial channel в `Connection::build`; автоматическое unbounded повышение security level отключено. [connect](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L505-L581), [bounded task](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/identity_improve.rs#L26-L61).
4. **TeamSpeak transport.** Vendored библиотека разрешает адрес, создаёт UDP socket, делает tsproto handshake, отправляет `clientinit`, ждёт `initserver`. Это не WebSocket/REST и не WebRTC voice. [transport](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/vendor/tsclientlib/src/lib.rs#L461-L605). Resolver также имеет TS DNS/TCP и nickname lookup/HTTPS: [resolver](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/vendor/tsclientlib/src/resolver.rs#L72-L84), [DNS](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/vendor/tsclientlib/src/resolver.rs#L203-L217).
5. **Connected подтверждается событием**, затем `channelsubscribeall`, snapshot/audio/state и reply исходному request. [Session events](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L1105-L1144).
6. **Вход в канал:** `Session::join_channel` отправляет `client_move` с паролем и хранит pending request до server `MessageResult`; UI browsing не должен подменять voice join. [join](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L622-L632), [result](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L1187-L1206), [native password path](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/runtime/local_actions/connections.rs#L127-L143).
7. **Разрешение TX:** OS grant + mobile call lease + подтверждения `SetTransmit`/`SetAudio` → `CapturePermit { SessionKey, capture_epoch }`. [controller](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/runtime/controller.rs#L17-L29), [manager](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/connections.rs#L503-L539), [permit publication](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/connections.rs#L755-L769). Не смешивать viewed server с input owner.
### Наблюдения владельца и устройства
### Ошибки и границы
- На4955 headset RX слышен; `nonzero_frames` растёт, output активен без xruns/time discards.
- Headset microphone: несколько StartInput достигают Started/ok, затем появляется FramePositionGap.
- Отдельный выбранный телефонно-названный `Audio device`: Disconnected и затем Open Internal.
Текст продукта не доказывает физический builtin microphone; generation/session — только контекст.
- Первоначальные подробности gap уже отсутствуют в retained app log. Не выдавать кодовую модель
сбоя за доказанную полную последовательность конкретного аппаратного события.
- Неверный пароль, channel permissions и прочие TS failures сохраняют `ts_error`/`missing_permission`; недостаточный identity security level возвращается явно, а не запускает бесконтрольную нагрузку. [error mapping](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L56-L80).
- Connect не означает успешный subscribe-all: внутренняя ошибка подписки может стать отдельным error event. Проверять сервер с ограниченными правами: [pending results](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L1198-L1206).
- При временном разрыве core завершает pending/media, сбрасывает TX/RX, меняет generation и переходит в Connecting. Vendored tsclientlib содержит reconnect-путь; старый upstream README с фразой об отсутствии reconnect не описывает полностью локальную реализацию. [core transition](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L1059-L1080), [vendored reconnect](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/vendor/tsclientlib/src/lib.rs#L1166-L1183).
- **Неизвестно:** фактический Wi-Fi↔cellular handoff, NAT/IPv6/DNS и время восстановления. `NetworkChanged` сам не переподключает socket — он отзывает capture; reconnect принадлежит протокольной библиотеке. [handler](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/runtime/event_handlers.rs#L60-L63).
- **Факт / риск доверия:** рассматриваемый `ConnectArgs` не содержит ожидаемый server UID, а builder его не задаёт; в vendored библиотеке проверка предусмотрена только при заполненном `options.server`. Это не утверждение о найденной эксплуатации, но TOFU/pinning policy пока не установлена. [args](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/protocol.rs#L188-L208), [builder](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L514-L525), [UID check](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/vendor/tsclientlib/src/lib.rs#L523-L532).
### Исправления прошли CI4959; аппаратная TX-приёмка остаётся открытой
## 6. Полный аудиотракт
1. **Capture tail:** callback320 frames при16kHz делится на256+64. Если первая метка0ms, arrival10ms,
хвост имеет метку16ms. Раньше он выбрасывался; следующий callback начинался с позиции320,
создавая программный64-frame gap. Android теперь сохраняет порядок в bounded ring и держит
один будущий head block до наступления его исходного captured_at, прежде чем передавать в SRC/DSP/TX.
Expiry200ms, boundary, epoch, mute и настоящие missing-frame errors остаются; desktop не меняется.
2. **Каталог:** TYPE_ECHO_REFERENCE28 — внутренний AEC reference, не микрофон. В сохранённом
AudioPolicy он присутствует; отсутствовал в enum и мог выглядеть как generic Audio device.
Добавлены точная классификация и исключение из capture-кандидатов. Другие неизвестные vendor
sources не скрываются; сохранённый exact ID не подменяется автоматически.
### Общий формат и кодеки
Код: `native/src/media/audio/{devices,engine}.rs`, соответствующие tests;
`native/vendor/cpal-0.18.2/src/host/aaudio/device_catalog.rs`.
Приёмка: новые deterministic regressions → Linux CI/APK → согласованная проверка headset TX,
затем допустимой пары phone mic/headset output, при сохранённом RX. Никаких blind retries.
**Факт:** core boundary — mono `i16`, 48 кГц, 960 samples / 20 мс / 1920 bytes. TX-очередь ограничена 10 кадрами; максимальный возраст capture 200 мс. [protocol frame](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/protocol.rs#L1-L35), [queue](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/audio.rs#L20-L63).
## 5. Диагностика: что означает доказательство
**Факт:** TX поддерживает OpusVoice (mono/VoIP) и OpusMusic (stereo/Audio с дублированием mono); bitrate mapping проекта: 8–48 и 24–104 кбит/с для quality 0–10. Это не заявленная официальная таблица TeamSpeak. Speex Narrow/Wide/Ultra и CELT не реализованы как fallback. [TxCodec/TxEncoder](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/audio.rs#L204-L301). RX также отвергает неподдержанный codec: [Receiver](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/audio.rs#L403-L430).
### От микрофона до сети
| Этап | Electron reference — факт | Native/mobile — факт |
|---|---|---|
| Захват | `getUserMedia`, mono, Chromium AEC/AGC по профилю; browser NS выключен; отдельный capture AudioContext 48 кГц. [engine](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/audio/engine.js#L279-L349) | CPAL callback → mono `f32`, bounded блоки ≤256 samples, hardware timestamps; SRC в worker → 480 samples/10 мс при 48 кГц. [devices](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/devices.rs#L468-L501), [conversion](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/engine.rs#L300-L345) |
| Обработка | Typing attenuation; WASM Denoiser — NS по 480 samples, затем 960-sample `i16`; AEC/AGC остаются Chromium. [worklet](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/audio/capture-worklet.js#L111-L188) | Sonora AEC3 → NS → adaptive digital AGC2; независимые настройки; обработка на worker, не в callback. [CaptureProcessor](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/dsp/src/capture.rs#L85-L169) |
| Echo reference | Управляется Chromium; приложение не передаёт свой CPAL post-render reference | CPAL output callback публикует реально выданный устройству, уже квантованный сигнал; timestamps выравнивают reference и capture. [output callback](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/devices.rs#L546-L583), [timeline](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/engine.rs#L418-L449), [worker](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/engine.rs#L891-L943) |
| Сборка и guards | Worklet → renderer gate → IPC → base64/stdin. Renderer отбрасывает сообщения старше 200 мс; stdio назначает новый `Instant::now()`, исходный hardware timestamp не сохраняется сквозь IPC. [voice](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/voice.js#L230-L281), [stdio](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/stdio.rs#L101-L114) | Два 10-мс блока → `CapturedFrame`; сохраняются capture time, connection generation, privacy epoch. Передача через embedded handle без JSON/base64 PCM. [capture](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/capture.rs#L61-L80), [manager](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/connections.rs#L211-L226), [handle](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/runtime.rs#L55-L59) |
| Gate и кодирование | Общий core, выбранный input connection; PTT/mute/deafen до отправки | То же ядро плюс native capture permit; неверная session/epoch или старое PCM отклоняются |
**Общий TX:** direct либо VAD automatic/volume/hybrid; earshot анализирует downsampled 16-кГц окна 256 samples, поддерживаются onset/preroll/hangover. Whisper имеет отдельный route и обходит обычный VAD, но не epoch/permission checks. [VAD constants](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/vad.rs#L25-L58), [VAD implementation](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/vad.rs#L290-L389), [TX path](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L1405-L1564). Серверное `can_send_audio()` не обходится локальной кнопкой PTT. Кадр Opus становится TS voice/whisper packet; пустой packet завершает burst. [encoder](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/audio.rs#L277-L310).
**Факт:** локальный patch протокола сохраняет timestamps/epoch вплоть до deferred UDP send и повторяет guard при backpressure/retry. Нельзя заменить vendored tsclientlib vanilla-upstream без анализа этого контракта. [patch provenance](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/vendor/README.md#L14-L53), [AudioSendGuard](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/audio.rs#L190-L200).
### От сети до динамика
1. `StreamItem::Audio` → `Receiver::handle_packet` → tsclientlib `AudioHandler`: per-speaker jitter/decode. Output mute прекращает этот путь. [Session RX](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L958-L993).
2. Раз в 20 мс `mix_tapped` берёт decoded stereo float, применяет UID-громкость и отдельный playback AGC на говорящего, смешивает, downmix `(L+R)/2`, ограничивает и отдаёт mono `i16[960]`. [Receiver](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/audio.rs#L388-L490), [playback AGC](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/voice_dsp.rs#L217-L299).
3. Electron: base64 `audio` event → отдельный per-server playback ring (200 мс, prebuffer 40 мс, до 16 rings) → worklet mix → gain/ducking/sink. [serialization](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/audio.rs#L492-L510), [worklet](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/audio/playback-worklet.js#L1-L65), [playback](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/audio/playback-worklet.js#L139-L189).
4. Native: `CoreEvents.playback` → `AudioSessionBinding` проверяет session/output epoch → mixer разделяет 960 mono на два stereo 480-блока → output SRC/Rubato → CPAL. Voice, stream и notifications имеют отдельные маршруты. [binding](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/media_binding.rs#L18-L57), [mixer](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/mixer.rs#L323-L410), [output worker](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/engine.rs#L893-L979).
### Мобильные риски DSP
- Sonora требует **единственного владельца AEC/NS/AGC** и актуального post-gain reference; нельзя просто добавить OS VoiceProcessingIO поверх него. [контракт](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/dsp/src/capture.rs#L1-L8). iOS bridge намеренно выбирает `AVAudioSessionModeDefault`, а не voiceChat: [configureCall](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple/bridge.mm#L115-L120). Официальная документация Apple различает voiceChat mode и реально включённый voice processing — [voiceChat](https://developer.apple.com/documentation/avfaudio/avaudiosession/mode-swift.struct/voicechat).
- Раздельные input/output clocks и Rubato correction ±1000 ppm уже предусмотрены, но качество CPAL hardware timestamps на конкретных маршрутах **неизвестно**. [ClockTracker](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/resample.rs#L105-L196).
- **Неизвестно:** эффект Bluetooth HFP/LE, speakerphone double-talk, latency, battery/thermal load, реальная задержка OS DSP, reference при нескольких sinks. Pure Rust и NEON support — не акустическая приёмка.
- WebRTC stream audio — отдельная ветка; platform ADM recording/playout отключены, чтобы не становиться вторым владельцем микрофона/вывода. [peer](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/stream/peer.rs#L45-L56), [stream sink](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/stream/frames.rs#L323-L375).
## 7. Мобильные ограничения и фактический статус адаптеров
| Область | Android: наблюдается в коде | iOS: наблюдается в коде | Что остаётся проверить |
|---|---|---|---|
| Permission | `RECORD_AUDIO`, FGS declarations, prompt из видимой Activity, повторная проверка grant. [manifest](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/src/main/AndroidManifest.xml#L2-L24), [request](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/src/main/java/dev/teamspeach/mobile/TeamsPeachActivity.java#L128-L143) | Usage descriptions и `requestRecordPermission`; receive-only не требует mic grant. [plist](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/ios/Host/Info.plist#L34-L39), [bridge](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple/bridge.mm#L108-L127) | Deny, permanent deny, Settings revoke, one-time permissions; никакой передачи до разрешения. |
| Фон | `VoiceService`, notification, mediaPlayback/microphone types, START_NOT_STICKY. [service](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/src/main/java/dev/teamspeach/mobile/VoiceService.java#L19-L85) | `UIBackgroundModes=audio`, активная AVAudioSession и удержание runtime call lease. [plist](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/ios/Host/Info.plist#L39), [lease](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple.rs#L61-L83) | Lock screen, task recreation, OS termination, реальный фон; не обещать вечную жизнь процесса. |
| Interruption/focus | AudioFocusRequest; loss/gain → platform events, permanent loss останавливает service. [focus](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/src/main/java/dev/teamspeach/mobile/VoiceService.java#L61-L85) | Observer interruption, prior capture intent, shouldResume, native resume API. [observer](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple/bridge.mm#L74-L80), [resume](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple/bridge.mm#L130-L138) | Цепочка safe resume неполна, см. ниже. |
| Bluetooth/routes | AudioDeviceCallback есть; явного `setCommunicationDevice` в просмотренном `native/src`/Android source не найдено | AllowBluetooth/AllowBluetoothA2DP и route-change observer; explicit input-port selection не найдена в этих адаптерах | Реальный input и output headset, HFP/LE, unplug, speaker/receiver, confirmation route; CPAL enumeration не равна communication routing. |
| Network | `registerDefaultNetworkCallback`. [bridge](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/src/main/java/dev/teamspeach/mobile/PlatformBridge.java#L23-L29) | `nw_path_monitor`. [observer](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple/bridge.mm#L85) | Reconnect после Wi-Fi↔cellular, offline/recovery, IPv6/DNS, отсутствие replay старого capture. |
| UI lifecycle | Process-owned Application/runtime, новая UI generation; Activity destruction отменяет prompts. [Rust host](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/android.rs#L64-L116), [Activity](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/src/main/java/dev/teamspeach/mobile/TeamsPeachActivity.java#L61-L76) | HostLease/scene lifecycle, detach не тождественен завершению активного звонка. [binding](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/ui/application.rs#L53-L69), [bridge](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple/bridge.mm#L65-L105) | Rotation/recreation и scene reconnect без дублей core/audio worker и без автоматического PTT. |
| Touch/accessibility | Общие touch controls, SemanticView/TalkBack virtual nodes. [PTT](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/ui/shell.slint#L264-L275), [SemanticView](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/src/main/java/dev/teamspeach/mobile/SemanticView.java#L60-L95) | Safe-area/IME/VoiceOver traits передаются в Slint; эквивалент Android semantic overlay не установлен | Пройти Connect/Join/Mute/PTT/Disconnect TalkBack и VoiceOver; общий UI ещё не доказательство доступного дерева iOS. |
| Files/secrets | SAF, URI/grants/private staging; Android Keystore | Security-scoped documents; Keychain ThisDeviceOnly | Providers, cancellation, locked stores, reinstall/backup; не переносить Electron ciphertext. [platform selection](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/services/secrets/backend.rs#L1-L15), [mobile adaptations](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/compatibility.json#L28-L35) |
| Updates/capture | direct APK/store branches, MediaProjection/Camera2 | App Store channel, ReplayKit extension | Store review/signing/privacy, real capture capabilities; не обещать desktop capture на мобильных без OS consent. |
### Конкретный разрыв восстановления аудио
**Факт:** `event_handlers::platform` при начале interruption вызывает `StopInput` и `StopOutput`; при `should_resume` лишь выставляет строку статуса. Route/network change отзывает capture и вызывает `StopInput`. [handler](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/runtime/event_handlers.rs#L60-L63).
**Факт:** iOS `CallLease::resume(ResumeAuthorization,...)` существует, но текстовый поиск `ResumeAuthorization` и `.resume(` по `native/src` не обнаружил его вызова из runtime; найденные остальные `.resume()` принадлежат CPAL stream state. LSP в проекте не настроен, поэтому это результат ограниченного source search, не whole-program доказательство. [API](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple.rs#L71-L81).
**Факт:** `ensure_mobile_call` может вернуть успех для прежнего lease по cached флагу либо вызвать `set_capture_enabled`, а не `resume`; ObjC bridge запрещает включение capture при `!callActive`. [mobile_calls](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/runtime/mobile_calls.rs#L8-L25), [bridge guard](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple/bridge.mm#L140-L149).
**Вывод:** iOS safe resume — приоритетный blocker непрерывного voice сценария. На Android автоматическое восстановление выхода также отсутствует в общем handler, но отдельное действие пользователя идёт через `set_microphone_owner` → `sync_audio` и может открыть выход снова; **не следует утверждать, что звук невозможно восстановить вообще**. [explicit action](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/runtime/controller.rs#L17-L29). Проверить и оформить отдельно receive-only resume, capture resume и отказ OS. Не исправлять путём безусловного автозапуска микрофона.
### Официальные ограничения OS
- Android 14+: appropriate FGS type/permission; microphone FGS требует `RECORD_AUDIO` и подчинён while-in-use ограничениям. Старт из фона обычно запрещён без документированного исключения. [FGS types](https://developer.android.com/develop/background-work/services/fgs/service-types), [background restrictions](https://developer.android.com/develop/background-work/services/fgs/restrictions-bg-start).
- Target Android 15+: audio focus доступен top app либо foreground service. В service сначала вызывается foreground, затем requestAudioFocus — порядок соответствует этому требованию, но не подтверждает все runtime-переходы. [audio focus](https://developer.android.com/media/optimize/audio-focus).
- Android BLE Audio: официальный путь communication-device selection, callback фактической смены и очистка выбора; старый SCO-путь не заменяет BLE routing. [AudioManager guide](https://developer.android.com/develop/connectivity/bluetooth/ble-audio/audio-manager). Нельзя считать notification audio usage настройкой CPAL stream mode.
- iOS: microphone permission, корректная audio category, background audio capability, interruption и route-change handling. Background mode не отменяет прерывания/системное завершение. [interruptions](https://developer.apple.com/documentation/avfaudio/handling-audio-interruptions), [route changes](https://developer.apple.com/documentation/avfaudio/responding-to-audio-route-changes), [voice processing distinction](https://developer.apple.com/documentation/avfaudio/avaudiosession/mode-swift.struct/voicechat). Документы могут описывать будущие/newer SDK APIs: availability проверять относительно deployment target 16, не вводить новые API без guards.
## 8. Поддержка мобильных платформ ключевыми зависимостями
Проверено по официальным источникам 2026-11-10. «Поддерживается upstream» не означает «проверен этот fork, patch set и artifact». Для pure-Rust библиотек отсутствие отдельного mobile support statement не заменено догадкой.
| Зависимость | Официальное основание | Оценка для данного дерева |
|---|---|---|
| Rust | [Target tiers](https://doc.rust-lang.org/rustc/platform-support.html): Android ARM64 и iOS ARM64/device/simulator имеют std, Tier 2 | Toolchain target возможен; Tier 2 не гарантирует исполнение приложения/всех C-deps. |
| Electron 44.9.3 | [Versioned README](https://raw.githubusercontent.com/electron/electron/v44.9.3/README.md): binaries только Windows/macOS/Linux | Хост нельзя взять как Android/iOS shell. |
| Slint 1.18.1 | [Android guide source](https://github.com/slint-ui/slint/blob/v1.18.1/docs/astro/src/content/docs/guide/platforms/mobile/android.mdx): Rust/C++, android-activity, min API26. [iOS guide source](https://github.com/slint-ui/slint/blob/v1.18.1/docs/astro/src/content/docs/guide/platforms/mobile/ios.mdx): Rust, Winit/Skia, macOS/Xcode/XcodeGen | Соответствует текущему направлению native. [Mobile guide](https://github.com/slint-ui/slint/blob/v1.18.1/docs/astro/src/content/docs/guide/platforms/mobile/general.mdx) отдельно требует touch scrolling, safe area и IME. |
| CPAL 0.18.2 | [Published crate README](https://docs.rs/crate/cpal/0.18.2): Android AAudio API26+, iOS CoreAudio | Используется локальный patch; official support не покрывает автоматически изменения timing/route handling. |
| Sonora 0.2.0 | [Pinned upstream README](https://github.com/dignifiedquire/sonora/blob/a024d6ef8351add55be5e8b1d6cc35f555787660/README.md): Android architectures и iOS ARM64, NEON/scalar; [crate](https://docs.rs/crate/sonora/0.2.0) | Portable DSP реалистичен; локальные sonora/AGC2 patches и real-time workload нуждаются в проверке. |
| ReSpeak tsclientlib/tsproto | [Pinned upstream README](https://github.com/ReSpeak/tsclientlib/blob/ee3bc6f45a7137db7793ba5593a321df400d53e5/README.md) описывает TeamSpeak library, но не даёт mobile acceptance matrix | **Неизвестна официально подтверждённая Android/iOS-совместимость этой ревизии.** Проверить build/UDP/DNS/auth на обеих OS; patch set обязателен. |
| audiopus 0.3.0-rc.0 / audiopus_sys | [Published README](https://docs.rs/crate/audiopus/0.3.0-rc.0): CMake, bundled/preinstalled Opus, заявлены Windows/Linux/macOS; отдельной Android/iOS гарантии нет | **Cross-build gate**, а не доказанный mobile blocker и не гарантированная поддержка. Собирать target-native static Opus, не брать host library. |
| libwebrtc 0.4.0 / webrtc-sys 0.3.53 | [Pinned SDK README](https://github.com/livekit/rust-sdks/blob/88705b15086ecbe2c26ee91ede6203f974a0fc62/README.md) включает Android/iOS; [published crate](https://docs.rs/crate/libwebrtc/0.4.0) | Есть upstream mobile support, но локальная source-build-only интеграция, prefixed JNI и codec patches — отдельные гейты. Не требует LiveKit server для текущего standalone peer. |
| Tokio/Serde, earshot, Rubato | Использование и pins подтверждены манифестами; отдельный официальный mobile runtime certificate для данной комбинации не установлен | **Вывод:** кандидаты на reuse, не основания для обещания запуска. Основные проверки — compilation, timings, resampling/VAD и cancellation. |
| rfd/arboard/open, DBus/X11, Win32 | В манифесте исключены из мобильного target graph либо ограничены desktop cfg | Не тащить в мобильный UI; использовать существующие platform adapters. |
Публичные Slint web pages через static fetch отвечали timeout; использованы доступные **официальные versioned исходники документации** на GitHub и docs.rs, а не пересказ поисковой выдачи. Browser relay также дал timeout; проверка dashboard выполнена отдельным managed browser, без использования пользовательского аккаунта.
## 9. Лицензии и распространение
Это техническая инвентаризация рисков, **не юридическое заключение**.
| Объект | Подтверждённое ограничение | Действие до распространения |
|---|---|---|
| Собственный код TeamsPeach | `UNLICENSED`, rights reserved до выбора лицензии владельцем. [package](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/package.json#L7-L9), [NOTICE](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/LICENSES/NOTICE.md#L1-L4) | Получить документированное право на модификацию/распространение либо лицензию владельца. Публичный git сам по себе такого права не даёт. |
| Иконки TeamSpeak | Нет найденного redistribution grant; provenance не является лицензией. [icons](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/LICENSES/teamspeak-client-icons-PROVENANCE.md#L3-L12) | Заменить собственной/разрешённой графикой или получить права. |
| WAV notifications | Та же проблема с официальными sounds. [sounds](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/LICENSES/teamspeak-client-sounds-PROVENANCE.md#L3-L10) | Заменить/лицензировать, включая ресурсы в собранном mobile package. |
| Slint | [Royalty-free 2.0](https://github.com/slint-ui/slint/blob/v1.18.1/LICENSES/LicenseRef-Slint-Royalty-free-2.0.md) явно разрешает mobile при attribution; ограничения на standalone redistribution/API exposure; GPL/commercial — альтернативные условия | Зафиксировать выбранную лицензию; обеспечить доступный AboutSlint/badge и notices. [AboutWindow](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/ui/about.slint#L1-L24) содержит widget, но фактическую доступность в обоих mobile UI ещё надо проверить. |
| ReSpeak и Rust deps | MIT/Apache-2.0 и другие permissive licenses; earshot MIT/Apache, audiopus ISC; inventory не ограничен одной платформой. [vendor](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/vendor/README.md#L5-L12), [notices](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/THIRD_PARTY_NOTICES.md#L3-L15), [earshot](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/THIRD_PARTY_NOTICES.md#L52) | Сохранить copyright/license/NOTICE и условия модификаций, сверить именно финальный dependency graph. |
| Sonora | BSD-3-Clause; native использует больше pipeline, чем reference WASM. [notice](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/LICENSES/sonora-NOTICE.txt#L20-L49), [native DSP](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/dsp/Cargo.toml#L16-L21) | Старый WASM notice с «AEC/AGC never constructed» нельзя выдавать за описание native DSP; подготовить notices по фактической поставке. |
| Fonts | Noto Sans OFL-1.1, отдельные KaTeX font notices | Сохранить лицензии; проверить модификации/renaming rules и конечные assets. [NOTICE](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/LICENSES/NOTICE.md#L11-L13). |
| WebRTC/кодеки | Generated third-party licenses обязательны; software H264 patent/license review отмечен в dependency lock `/verification/licensing`; GN включает H264/FFmpeg и другие codecs. [GN](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/deps.rs#L199-L219), [iOS notice staging](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/ios/project.yml#L68-L74) | Проверить фактически слинкованные компоненты, license obligations и patent policy по регионам. Не объявлять пакет «весь MIT» и не выводить правомерность из успешного build. |
| Название/марки/магазины | Независимый клиент, TeamSpeak trademark; endorsement отсутствует. [NOTICE](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/LICENSES/NOTICE.md#L23-L24) | Проверить branding, privacy disclosures, microphone/background declarations и App Store/Play distribution policy перед релизом. |
**Вывод:** публичный mobile release сейчас юридически не обоснован имеющимися документами. Внутренний технический прототип не решает эти вопросы автоматически. Полная лицензия конечного APK/IPA неизвестна до фиксации разрешений и dependency/assets inventory.
## 10. Минимальный сквозной прототип — только план
### Цель и ограничения
**Цель:** физический Android и физический iPhone подключаются к разрешённому тестовому TeamSpeak-серверу, входят в один Opus-канал и обмениваются двусторонним голосом друг с другом и с контрольным desktop/официальным peer. Не заменять живую сеть synthetic signaling и не выдавать loopback за interoperability.
Минимальный UI: адрес/порт, nickname/identity, ввод пароля без записи в лог, список каналов/Join, статус соединения и актуального канала, receive-only, microphone permission, Mute/Deafen/PTT, Disconnect, ясные ошибки. Это ограничение **первого доказательного эксперимента**, а не отказ от остальных функций конечной идентичной версии.
### Порядок проверки технических препятствий
| Шаг | Что проверять | Наблюдаемый критерий успеха / остановки |
|---|---|---|
| 0. Условия эксперимента | Отдельное разрешение на build/install/run/network; Linux Android build host, Mac/Xcode для iOS; явные test devices и сервер/канал; disposable profiles; права на используемые assets | Задокументированы target triples, toolchain/SDK versions, test endpoints без секретов и разрешённые действия. Нет автоматического использования production identities. |
| 1. Реальный mobile build chain | Сначала Rust/core+static Opus на обоих targets; затем существующий native app/source-built WebRTC, matching JNI jar, iOS framework/link/signing, Android 16 KiB ELF | Получены воспроизводимые target artifacts, SHA/revision/recipe и новые per-target provenance. Package verifier подтверждает архитектуру; приложение действительно запускается. Никаких фиктивных completed records. |
| 2. Foreground audio boundary | CPAL enumerate/open input+output с разрешением, timestamps, SRC, full-duplex, один DSP owner. Сначала earphones, затем speakerphone | Receive-only работает без mic grant; deny/revoke не включает capture. Fresh PCM доходит через штатный DSP, нет stale-frame/repeated-init ошибок, выход не молчит после корректного start. |
| 3. Handshake и канал | Embedded `CoreHandle`, identity, password/no-password, security-level rejection, Join ACK, неподдержанный codec | Сервер и peer видят ожидаемого клиента/канал; UI отражает подтверждённое состояние. Неверный пароль/права отображаются как ошибки, не как connected/joined. |
| 4. Двусторонний голос | Android↔iOS, затем каждый ↔ desktop peer; OpusVoice, позже OpusMusic, PTT/mute/deafen | Два независимых слушателя/измерения подтверждают речь в обе стороны. Предлагаемый gate: 10 минут разговора без устойчивого одностороннего звука/зависания; зафиксировать loss/jitter, CPU и измеренную задержку. Предварительная цель mouth-to-ear p95 ≤250 мс в контролируемой LAN, метод и акустическую погрешность указать отдельно. Это цель, не текущий результат. |
| 5. Privacy и смена владения | Release PTT, mute, channel/input owner switch, disconnect/reconnect, permission revoke | После boundary не передаётся ранее захваченный PCM: проверить capture timestamps/epochs и получателя. Допуск сетевого хвоста измерять отдельно; не требовать физически мгновенного исчезновения уже доставленного звука. |
| 6. Lifecycle — устранить найденный разрыв | Safe interruption/resume, foreground service/session lease, receive-only восстановление; не только открыть микрофон заново | После звонка/потери focus разрешённое явное resume восстанавливает RX и TX на обеих OS; отказ OS остаётся видимым, mic не включается сам. iOS resume должен реально вызываться с актуальным SessionKey и авторизацией. |
| 7. Routing и сеть | Speaker↔wired↔Bluetooth HFP/LE, unplug; Wi-Fi↔cellular/offline; background/lock и UI recreation | Фактический mic/output соответствует выбору; нет старого PCM/двойных workers. Предварительный recovery gate: ≤30 с либо явное состояние ошибки с рабочим manual reconnect, без ложного connected. Фон: 10 минут активного разрешённого звонка с locked screen на каждой OS; ограничения OEM/OS записать. |
| 8. Доказать общий UX | Одинаковый сценарий/состояния на Android/iOS, safe area, IME, compact layout, TalkBack/VoiceOver | Все минимальные действия доступны touch и screen reader, release/cancel PTT безопасен. Скриншоты одинаковых app-состояний и отдельная фиксация ожидаемых OS-различий. |
**Решение после прототипа:** если ядро и OS-аудио работают, но Slint surface имеет доказанный blocker, сравнить замену presentation слоя, сохраняя `CoreHandle`, session ownership, DSP и callbacks. Если blocker находится в codec/capture/session, смена UI его не решит. Проверять iOS с первых шагов, не откладывать его до «готового Android».
### После минимального proof — план полной идентичной версии
1. Превратить existing compatibility inventory в исполняемый acceptance checklist, не наследуя historical passes; сравнивать актуальный Electron-контракт и native implementation.
2. Одна shared feature-модель для channels/admin/chat/files/whisper/recording/settings; для каждой фичи Android/iOS verdict, adapter и честный unsupported/error state.
3. Отдельно принять WebRTC screenshare/camera/notifications/file providers/secure storage/update channels на устройствах; не расширять первый voice proof до этих зависимых сценариев.
4. Проверить мобильный layout, performance/battery/thermal, accessibility, back navigation, recovery и migration без изменения identity/потери данных.
5. Закрыть лицензии, assets, signing/store privacy и конечный dependency inventory; только после этого обсуждать распространение.
## 11. Проверки, артефакты и неизвестное
### Реально выполнено в исследовательской сессии
- Metadata-only git preflight: HEAD/branch/status/tracked inventory; метаданные путей без чтения секретов.
- Статическое чтение перечисленных исходников, manifest/CI/test recipes и точечных vendor contracts; приложение не исполнялось.
- Установленные Understand scripts: ignore generation, scan, import extraction, semantic batching, structural extraction, merge, fingerprint baseline.
- Карта: **679 текстовых файлов**, **5233 узла**, **13204 связи**, **9 слоёв**, **9 шагов**. Scan/fingerprint inventory содержит 680 entries: один бинарный WAV без graph node. 872 resolved imports сохранены; штатный merge удалил 15 некорректных `tested_by` связей. Наличие ребра `tested_by` не означает test pass.
- `validateGraph` установленного core + проверка layer/tour references: success, без issues. Проверена фактическая загрузка и отрисовка русского графа в understand-dashboard; verification browser tabs закрыты.
- Официальные dependency/OS/license источники прочитаны; Slint timeout обойдён чтением официальных versioned docs sources.
- LSP status: **No language servers configured for this project**. Он не настраивался; Cargo/rust-analyzer checks не запускались.
- Финальная проверка: 179 ссылок на исходники в 82 файлах — пути и диапазоны строк корректны после исправления четырёх диапазонов; локальные ссылки документов разрешаются, code fences сбалансированы. Итоговый git status показывает только новые `.ua/`, `AGENTS.md`, `docs/mobile-port-assessment.md`, `docs/mobile-port-progress.md`; tracked и staged diff пусты. Исходники приложения не изменены. Промежуточные артефакты перемещены в стандартный `.ua/.trash-*`, scan inventory сохранён.
### Стандартные артефакты Understand-Anything
`.ua/knowledge-graph.json`, `.ua/meta.json`, `.ua/fingerprints.json`, `.ua/config.json`, `.ua/.understandignore`, `.ua/intermediate/scan-result.json`. `autoUpdate=false`, `outputLanguage=ru`. Граф — снимок исходников указанной ревизии; созданные вслед за ним `AGENTS.md` и документы исследования не являются архитектурными узлами этого первичного снимка. Dashboard может честно показывать working-tree changes из-за новых документов — это не нужно скрывать изменением commit metadata или запускать полный анализ повторно.
Для следующего просмотра: `/understand-dashboard C:/Dev/TeamsPeach`. В этой сессии использован уже установленный Vite dashboard без install/build; runtime access token в документы не сохраняется. Автообновление графа не включалось.
### Открытые вопросы
| Неизвестное | Как получить ответ |
| Сигнал | Что доказывает / чего не доказывает |
|---|---|
| Сборка и запуск данного patch set на Android/iOS | Разрешённые реальные source-build/package/start с per-target receipts. |
| Server/official peer interoperability | Изолированный live сервер и контрольный peer; тесты §10. |
| iOS safe resume и Android explicit recovery | Точечное исправление после разрешения, затем interruption scenario на устройствах. |
| Bluetooth/AAudio/CoreAudio timestamps, AEC, latency/battery | Полный duplex acoustic/device test, а не desktop loopback. |
| Full feature/visual/accessibility parity | Общая acceptance matrix и реальные Android/iOS UI checks. |
| Разрешение на распространение кода и TS assets | Решение правообладателей/лицензия или замена assets; проверка конечного пакета. |
| Compile/package SUCCESS | Сборка/упаковка, не работа на телефоне |
| Android route ACK | Выбор маршрута, не Started и не слышимость |
| voice_nonzero_blocks | Сигнал после микшера; не post-SRC/callback/hardware |
| submitted_frames | Кадры очереди, включая нули |
| nonzero_frames | Ненулевые квантованные кадры в CPAL buffer; не OS/HAL gain или слышимость |
| AudioFlinger latency `k` | Kernel/server estimate в ms, не акустическое измерение |
| Подтверждение владельца | Реальный результат только названного сценария/кандидата |
Краткая передача следующей сессии: [mobile-port-progress.md](mobile-port-progress.md). Порядок актуализации знаний: [AGENTS.md](../AGENTS.md).
Снимать ограниченные `audio_route`, `audio_command`, `audio_summary`, `audio_stream`,
`audio_backend`, `audio_first_fault` и app-owned system state. Не сохранять PCM, credentials,
identity/profile contents, device addresses или чужую активность. Первое fault-событие может
вытесниться из logcat; уже сохранённые файлы разбирать без повторного удержания телефона.
Последние локальные артефакты и APK/hash указаны в handoff.
---
## 6. Сборка и границы платформ
## Текущее решение: Android all-ci, 2026-11-10
- Android build/package — Linux CI, Windows — редактирование и согласованный adb install.
Команды, provisioning и caches: `.gitea/workflows/android.yml` и связанные helpers; не дублировать
их параметры в этом документе. Ресурсная политика рабочей станции — только `mobile-build.local.md`.
- Test signing одноразовый по решению владельца; production signing/release не разрешены.
- iOS требует macOS/Xcode/Apple SDK/signing и собственного runtime proof; Android CI ничего из этого
не подтверждает. Не обещать проверенные interruptions/routes/background до соответствующих тестов.
- `.ua/knowledge-graph.json` старый; использовать как навигацию, выводы проверять source. Без полного
перескана/автообновления и без перезапуска Understand на каждую небольшую правку.
Этот раздел дополняет, а не исправляет исторический снимок выше. Владелец выбрал маршрут
**Windows-разработка → ручной Gitea Actions → вся Android-сборка на Linux CI → скачивание
артефактов → установка тестового APK через Windows `adb`**. Точные workflow, runner label,
repository variables и имена артефактов указаны в [актуальном README](../README.md#android-development-windows-separate-linux-build-host).
Существующие Linux desktop workflows остаются отдельными: Linux desktop package не является Android APK.
## 7. Android Room UI — выбранное направление
### Где выполняется сборка
- Владелец выбрал Room целиком; Android-only исключение из desktop-паритета записано в `DESIGN.md`.
- `runtime/model.rs::Snapshot.room` проецирует всех участников своего канала, независимо от collapsed tree.
`ui/shell.rs` владеет Room-навигацией/Back и captured targets; `ui/shell.slint` — сеткой участников,
постоянным voice dock, каналами/чатом/профилем и доступом к прежним secondary-функциям.
- `services/prefs.rs` валидирует `androidPalette`; `runtime/settings_actions/themes.rs` владеет preview,
атомарным сохранением и отменой. `ui/theme.rs` отделяет контрастный текст акцента от цвета заливки.
Null сохраняет штатную/package-тему; desktop override не применяет. Preview не должен переживать уход из Settings.
- Каталог EN/RU общий; default **English**, Russian выбирается в Appearance, сохранённый язык сохраняется.
- Integrated Slint compile и реальные i18n tests3 прошли локально. Полный Rust/APK кандидата `87265a3`
прошёл CI4972; prefs-палитра2 и shell4 регрессии подтверждены журналом. Preview-tests были отфильтрованы
неверным именем модуля; имя исправлено для следующего CI. Новая device-проверка ещё не завершена.
- На Windows-ПК нужны исходники/редактор, браузер для Gitea и Android SDK Platform-Tools для
явно выбранного тестового устройства. WSL, Docker и локальный Linux для этого маршрута **не нужны**;
Android SDK/NDK, JDK и тяжёлые native source-build tools размещаются на CI runner, а не на ПК разработчика.
- Вся цепочка Android выполняется на выделенном Linux x64 runner: pinned source WebRTC,
Skia, Rust ARM64 application, Gradle APK/AAB и проверки пакетов/receipts. Полная конфигурация
`skia + webrtc` сохраняется; это не обход зависимости отключением функций или случайным prebuilt.
- Linux — требование pinned WebRTC Android source-build, а не требование к рабочему месту:
[официальный upstream README на используемой ревизии `9c3a1386f07e4348c28cd85c066821cebc3b56e4`](https://github.com/webrtc-sdk/webrtc/blob/9c3a1386f07e4348c28cd85c066821cebc3b56e4/docs/native-code/android/README.md)
прямо говорит: **“Android development is only supported on Linux.”** Windows source-build WebRTC
для Android не объявляется поддерживаемым маршрутом.
- До первого dispatch администратор должен включить нужные возможности Gitea Actions/artifacts,
предоставить runner с указанным label, установить SDK/toolchains и настроить repository variables.
Наличие workflow в дереве не означает, что эти prerequisites уже provisioned или что job успешно исполнен.
### Артефакты и установка с Windows
1. После доставки исходников обычным разрешённым процессом выбрать нужный ref в ручном Android
workflow через Gitea Actions. CI не публикует release и не подключается к физическому телефону.
2. После успешного завершения **фактического** run скачать test-harness и production bundles вместе
с manifests, hashes, build/dependency и package-verification receipts. Проверить соответствие ref/run
и SHA-256 выбранного APK данным bundle; наличие файла без receipts не заменяет provenance.
3. На отдельном ARM64 Android-телефоне включить USB debugging, подтвердить авторизацию ПК и
выбрать serial из `adb devices -l`. Установить только явно выбранный `*-harness-test.apk`:
`adb -s <serial> install -t -r <path-to-harness-test.apk>`. Флаг `-t` нужен для `testOnly` APK;
это debug/test signing, не production signing. Не удалять установленную production-версию или
пользовательские данные ради обхода несовпадения ключей; использовать отдельное тестовое устройство.
Debug key изолирован для каждой CI-упаковки: следующий run может дать другую подпись, и `-r`
тогда не обновит прежний harness. Удаление только прежней disposable test-установки возможно
лишь по отдельному явному решению пользователя: **uninstall удаляет данные приложения**,
включая локальные identities и настройки. Автоматически удалять приложение нельзя.
4. Unsigned production ARM64 APK **не устанавливается**, пока не выполнены production signing и
проверка подписи; AAB вообще не устанавливается напрямую через `adb install`. Production AAB
предназначен для отдельно разрешённого signing/store-процесса, а не является готовым APK.
**Граница доказательства:** конфигурация CI, receipts проверки пакета и даже успешная установка
test-only APK не доказывают полноценную Android-приёмку, живой голос с официальным клиентом,
Bluetooth, lifecycle/background, screenshare, доступность или право на распространение. Тестовый
host не подменяет проверку production build. **Уточнение read-only preflight 2026-11-11,
HEAD `82334f8`:** offline isolation включается при переданных smoke extras; без них
`smoke_request` возвращает `None` ([smoke.rs](../native/src/platform/android/smoke.rs):16–40),
а Android runtime разрешает network/OS actions ([android.rs](../native/src/platform/android.rs):61–85).
По исходникам обычный запуск harness APK может служить кандидатом для первого live voice proof
на отдельном согласованном тестовом устройстве с disposable app data; сам proof не выполнен.
Application ID `dev.teamspeach.mobile` общий с production ([Gradle](../platform/android/build.gradle.kts):20–35),
поэтому тестовый APK не следует устанавливать поверх реального профиля. Этот раздел
не заявляет успешного CI run, полученного APK/AAB, установки или работы на телефоне.
**iOS не переносится на Windows:** сборка и packaging по-прежнему требуют macOS с Xcode/Apple SDK
локально либо на отдельно provisioned macOS CI. Signing/provisioning и реальная приёмка iPhone/iPad
остаются отдельными prerequisites; Android Linux workflow не создаёт IPA и не доказывает iOS support.
## Android implementation update, 2026-11-11
Основание: рабочее дерево `feature/mobile-port` поверх `cb1d682`; пользователь явно перенёс Linux
build/test/CI и provisioning на потом и разрешил доработку самого Android-порта. iOS не изменялся.
Ниже — новые реализации, не mobile acceptance; исторические утверждения §7 относятся к прежнему снимку.
- **Audio lifecycle:** `VoiceService` ведёт focus и communication mode; Android 12+ сообщает фактическую
смену communication device, первоначальная регистрация списка устройств не считается переключением.
[CallAudioState](../native/src/platform/android/call_audio.rs) разделяет право на output и capture;
потеря focus/route/permission отзывает capture, gain не возвращает микрофон автоматически.
[Android bridge](../native/src/platform/android.rs) передаёт `SessionKey`, lease token и revision через
`AndroidCallAudio`; [runtime](../native/src/app/runtime/mobile_calls.rs) игнорирует устаревшие события,
останавливает захват и восстанавливает разрешённое прослушивание, отдельно выставляя input-muted.
Cached mobile lease повторно проверяется по реальному состоянию Android. Capture/transmission gates
в runtime учитывают эту авторизацию; non-Android ветви сохраняют прежние условия.
- **Routing boundary:** [VoiceService](../platform/android/src/main/java/dev/teamspeach/mobile/VoiceService.java)
использует `MODE_IN_COMMUNICATION`, освобождая mode при завершении. Добавлено обычное permission
`MODIFY_AUDIO_SETTINGS`. Это не доказательство фактического Bluetooth mic/output, AEC или OS device selection;
отдельного нового route-picker и обещания HFP/LE parity нет.
- **Network:** [PlatformBridge](../platform/android/src/main/java/dev/teamspeach/mobile/PlatformBridge.java)
отслеживает текущую default Network. Повторные capability callbacks больше не создают ложный
`NetworkChanged`; реальная потеря/смена сети сохраняет privacy boundary. Reconnect не объявлен проверенным.
- **SAF и identity:** typed `file_exists` проходит из [SafGrant](../platform/android/src/main/java/dev/teamspeach/mobile/SafGrant.java)
через [JNI](../native/src/platform/android/documents.rs); Android
[file workflow](../native/src/app/runtime/file_actions/io.rs) предлагает Save picker для другого имени,
а не подтверждение несуществующей atomic-replace возможности. Новый документ не получает ложный overwrite prompt.
[Identity export](../native/src/app/runtime/settings_actions/identities.rs) на Android пишет приватный staging,
затем `commit_document`; успешный commit удаляет staging, ошибка сохраняет защищённый источник.
Невозможность безопасно заменить существующий provider document остаётся явной ошибкой, не обходится.
- **External links:** добавлена отсутствовавшая `android::open_external_url`, уже вызываемая общим
`RuntimeServices::open_approved`. Разрешены http/https/mailto после privacy consent; Java выполняет
ACTION_VIEW только из видимой Activity и возвращает отказ, если обработчика нет.
- **Phone UI:** [shell](../native/src/ui/shell.rs) и [Slint shell](../native/ui/shell.slint) дают явные
действия connection tabs/selected targets, раскрывают результаты query без автоматического Join/Delete,
возвращаются по stack/settings Back. Android-specific ветви в dialogs/settings/chat ограничивают
высоту меню/форм, прокручивают focused fields при IME и сохраняют отдельные voice controls.
PTT освобождается при cancel/drag-out/focus loss и смене target; Android Enter в composer не отправляет
сообщение случайно. Реальная геометрия, TalkBack/IME и жесты остаются непроверенными.
- **Проверка:** 2 standalone regression tests реального `CallAudioState` прошли на Windows под локальным
memory guard, без Cargo/dependency/native build. Cached Slint1.18.1 compiler проверил полный
`app.slint` с material и fluent: parse/typecheck/codegen success. Ошибочный `Window.active` выявлен
этой проверкой и заменён Android lifecycle → UI callback. Rust parser проверил изменённые Rust files,
XML parser — manifest. Полный Rust/JNI/Java typecheck, native app runtime, APK/device, desktop runtime
regression и tests Linux не выполнялись. Compatibility inventory остаётся pending; CI больше не запускался.
### Завершение известных Android implementation gaps перед внешней сборкой
Рабочее дерево поверх `cb1d682`, без нового commit/push. Пользователь выбрал следующий маршрут:
доработка приложения здесь → передача committed revision другому разработчику → сборка у него
в WSL2 Linux x64. WSL/SDK на текущем Windows-ПК не устанавливаются; CI/provisioning отложены.
Команды и состав возвращаемого bundle — [README handoff](../README.md#handoff-to-another-developers-wsl2-machine).
- `CallAudioState` сохраняет pending output restart при более позднем отзыве capture; подтверждение
устаревшей revision не снимает этот restart. Runtime сериализует explicit Android authorization
с обработчиком recovery через существующий audio_configuration mutex. Повторный focus callback
не выключает разрешённый микрофон без смены focus.
- Activity pause приходит как `Visibility(false)`, не `Focus(false)`: теперь этот Android event
синхронно освобождает held input и сбрасывает UI long-press. Он не отзывает MediaProjection/Camera2
только из-за появления окна согласия или ухода Activity в фон.
- `CaptureConsentActivity` ждёт resumed перед запуском FGS и закрывается только после foreground
handoff из `CaptureService`. Ошибка permission-launch завершает pending native request.
`CaptureSession` оставляет handler живым до закрытия даже поздно открывшейся Camera2; старые
ImageReader callbacks после resize игнорируются. Изменения находятся в
[Android capture adapter](../platform/android/src/main/java/dev/teamspeach/mobile/capture/).
- `TeamsPeachActivity` не запрашивает write grant для чтения, различает отмену picker и некорректный
successful result, сообщает effective permission state и очищает pending request при исключении.
`SafGrant` проверяет возвращённые URI access flags и закрывает provider handle до detach дубликата fd;
JNI закрывает capability при ошибке преобразования, не оставляя persistable lease.
- **Реально проверено в продолжении:** 3 standalone Rust regression tests `CallAudioState` passed под
локальным Job Object/memory guard; parser-only проверка 6 изменённых Rust files; 26 Java native
declarations имеют соответствующие Rust export names; Bash syntax блока WSL2 handoff прошёл.
Проверка имён JNI не является проверкой типов/ABI. Java/Android compilation и runtime не запускались;
результаты прежней Slint material/fluent проверки остаются прежними, новой UI-разметки здесь нет.
- **Не выдавать за законченную платформенную приёмку:** физический routing/Bluetooth, IME/TalkBack,
background/OEM lifecycle, camera/screen/audio playback capture, file-provider behavior и двусторонний
voice остаются отдельными device gates. Полный Rust/Java/JNI build ещё не выполнен и может выявить
integration errors. Intentional product exclusions (SFU/MATRIXCHAT/HTTPFT/S3/legacy codecs/account
services) остаются exclusions, а не молча реализованными функциями. Existing-provider atomic replace
по-прежнему fail-closed; повторный выбор grants обязателен после restart, retained failed identity
staging не имеет отдельного UI восстановления. Compatibility inventory не повышен из pending.
## 8. Ссылки и архив
- [Handoff](mobile-port-progress.md) — текущий кандидат, открытая работа и правила продолжения.
- [Android AudioManager](https://developer.android.com/reference/android/media/AudioManager),
[AAudio](https://developer.android.com/ndk/guides/audio/aaudio/aaudio),
[latency](https://developer.android.com/ndk/guides/audio/audio-latency),
[device types](https://android.googlesource.com/platform/frameworks/base/+/refs/heads/main/media/java/android/media/AudioDeviceInfo.java).
- [Архив исследований](archive/2026-11-14-mobile-port-assessment.md),
[архив хронологии](archive/2026-11-14-mobile-port-progress.md).
**Не читать целиком по умолчанию.** Это неизменённые старые снимки; относительные ссылки исходно
относились к `docs/`, а исторические статусы/разрешения не заменяют текущий handoff.
+66 -168
View File
@@ -1,182 +1,80 @@
# Мобильный порт: передача состояния
# Мобильный порт: текущее состояние
Updated **2026-11-11**. Windows baseline remains `05e8d34bcf0e24a44f76e65220293c45b6821798`; active branch is `feature/mobile-port`. The owner explicitly authorized using existing WSL Ubuntu for Android builds (server1 container only as fallback), then committing/pushing fixes and publishing a separate Android APK tag/release. This supersedes the older no-local-WSL and no-release decisions below. Source base: `3d2e76eddd281e6801bb5fc591d2443a957568b7`, with the build fixes described here; the delivered build-info includes the exact source patch rather than claiming an unchanged base revision.
Обновлено: **2026-11-15**. Это handoff, не журнал работ.
**Не дописывать хронологию:** заменять устаревшее состояние. Предел: 100 строк / 8 KiB.
## First Android APK build
## База и правила
- Existing WSL Ubuntu24.04 x64, `/home/user/src/TeamsPeach`; full pinned Android WebRTC source build and Rust/Slint ARM64 release library succeeded. JDK21, Rust1.96, SDK36/build-tools36.0.0, full NDK28.2.13676358, LLVM18 and matching Skia m153-0.101.2 sources; one Cargo/Ninja job. No server1 container was needed.
- Fixed actual first-build failures: Chromium DEPS NDK is sysroot-only (Cargo needs complete NDK); Skia uses `ANDROID_NDK`, Slint Java compilation needs explicit SDK36 `ANDROID_JAR` despite native API26; vendored jar destination used the wrong target root; accessibility cast needs NonNull::as_ptr; Gradle launcher CRLF and implicit build-tools35; permission observer used non-public PackageManager API; WebRTC JNI linker arguments must be emitted by the final cdylib build script.
- `xtask package` and `verify-package` passed for `TeamsPeach-0.1.7-android-arm64-harness-test.apk`, 121385639 bytes, SHA256 `ab0c4119b4a8abfebbb31ed185459da8b1ef6c57c86324ad7862014aa1085d1b`. APK v2 test signature, ARM64, 16-KiB ZIP/ELF alignment and JNI exports verified. Android8/API26 minimum. Install with `adb install -t`; not a production signing identity.
- Delivery: `C:/Users/Admin/Desktop/TeamsPeach-Android-0.1.7/`, APK plus build-info, exact build-fixes.patch and dependency/build/package verification receipts. Private test keystore is not included. WSL caches retained for incremental builds. Phone runtime/UI/voice/background acceptance has NOT run; no device installed, microphone activated, server connected or Windows installation modified.
- Publication requested as a separate Android prerelease, not a `v*` desktop tag or desktop updater manifest. Record successful push/release only after remote acknowledgement; authorization failures are not publication.
- Единственный клиент — Rust/Slint `native/`, ядро — `core::runtime`. Без Electron/Node/npm.
- Ветка `feature/mobile-port`; Room-кандидат `956b464` прошёл CI4973; последняя принятая RX/device-база — APK4955.
- Windows0.1.7 принята владельцем; `main`/тег `desktop-baseline-0.1.7-20261111`, база `05e8d34`.
Desktop-поведение не менять; общие изменения проверять на регрессии.
- Android build/package — Linux CI. Локальные ограничения читать в **`mobile-build.local.md`**;
тяжёлые Windows-сборки без разрешения не запускать. Не удалять caches, не устанавливать WSL/Docker.
- Продолжение mobile commit/push/CI разрешено. Git — отдельное PowerShell-окно с ручной авторизацией;
не читать credentials, не считать GCM исправленным. Без merge main, release или новых секретов.
- Телефон: ранее выбран TECNO KJ7. Каждую установку/сброс согласовать; одноразовая TEST-подпись
обычно требует disposable reinstall. Стабильную TEST-подпись владелец отложил.
- Не включать микрофон/сервер самостоятельно, не читать профиль/identities/секреты и не сохранять PCM.
## Текущий этап: реализация Android, CI отложен
## Последние подтверждённые device-результаты
- По последнему указанию пользователя работа переключена с runner/provisioning на **сам Android-порт**.
Linux build/test/CI и iOS отложены; не возвращаться к настройке runner вместо реализации приложения.
Изменения реализации подготовлены поверх `cb1d682`; владелец явно разрешил commit и push только `feature/mobile-port` для передачи другому разработчику. Main, теги и релизы не входят в публикацию.
- Исправлены Android audio focus/route/permission transitions: receive-only recovery, новый call-scoped
event с SessionKey/token/revision, повторная проверка закэшированной capture authorization, stale callback
rejection. `VoiceService` управляет communication mode; Android12+ получает communication-device changes.
Микрофон после interruption/route revoke не включается без явного действия. Общие runtime файлы меняются
только Android-gated ветвями; core/DSP и iOS не менялись. Физический routing/Bluetooth/AEC не проверены.
- Исправлены ложные network-change events на capability refresh; отсутствовавший Android external-link
adapter; SAF collision → выбор нового имени; Android identity export → private staging/commit/cleanup.
Provider atomic replace не имитируется, существующие файлы не перезаписываются небезопасно.
- Доработан Android compact UI: overflow connection tabs, действия выбранных каналов/файлов, query detail,
settings Back, PTT cancel/focus/drag-out, IME-aware forms/chat/settings. Сохранён существующий Rust/Slint
клиент и desktop presentation; исходники UI и функциональные ветви, а не новый host или второй стек.
- Реально выполнены **2 standalone audio state tests: passed**, guarded one-job/below-normal execution,
без Cargo/full build. Пройдены **Slint1.18.1 material+fluent parse/typecheck/codegen** с готовыми rlib,
Rust syntax-only parsing и AndroidManifest XML parse. Первая Slint-проверка выявила `Window.active`;
исправлено через существующий Android lifecycle callback, повторная проверка успешна. LSP initialization
завершился code0, rustfmt/JDK не найдены; полная Java/Rust/JNI проверка не заявляется.
- Временные validation runners/generated sources удалены; готовые dependency caches не трогались.
Ни приложения, ни APK/телефон/микрофон/сервер не запускались. Нет новых screenshots или device evidence;
Windows baseline не переустанавливался, desktop runtime regression не выполнен. `compatibility.json`
остаётся pending. Подробные новые знания — последний раздел assessment; `.ua` остаётся прежним stale snapshot.
| Проверка | Результат |
|---|---|
| Linux CI4955, job5551, `8074343edc78a684764bbe07fc128532a645ca04` | SUCCESS; APK собран |
| Тесты | audio173, capture18, lifecycle14, authorization9; clock acquisition3; прочие suites прошли |
| Установка | APK-хеш совпал; cold launch успешен |
| Bluetooth RX | **Владелец подтвердил звук через G435**; callback пишет ненулевые сэмплы |
| Bluetooth TX | **Не принят:** при включении микрофона `FramePositionGap` |
| Телефонный источник | Выбранный `Audio device` получил Disconnected / Open Internal; не доказан builtin mic |
| UI | Два независимых селектора расположены рядом; проверено скрином |
| Фон | Ранее владелец подтвердил Home/screen-off; удаление из Recents завершает звонок |
| Повторный вход из Recents / iOS / полный parity | Не приняты; не подменять результатами CI |
### Продолжение перед передачей другому разработчику
APK4955 SHA256: `6092ff8801bf38cd6d91f666920fe21162737f51c5425899fd3f6a491a3b85a5`.
[CI4955](https://git.eeee.moe/TeamsPeach/client/actions/runs/4955).
- Закрыты дополнительные source-level дефекты: `Visibility(false)` освобождает Android touch PTT и
long-press; повторный audio-focus callback не выключает микрофон; pending output recovery сохраняется
при более позднем capture revoke; explicit authorization сериализована с audio recovery.
- Capture consent теперь остаётся видимым до FGS handoff; permission-launch failure завершает request.
Camera2 shutdown дожидается late-open/close callback, resize игнорирует старые ImageReader callbacks.
Pause host Activity не используется как blanket stop для foreground camera/projection capture.
- Android picker/permission callbacks различают отмену, отказ и некорректный результат; read-only open
не запрашивает write permission. SAF проверяет grant flags, освобождает capability при JNI error и
не теряет raw fd при ошибке закрытия provider handle. Desktop/iOS branches не менялись.
- **Проверено сейчас:** 3 actual standalone audio-state tests passed; Rust syntax-only parse 6 файлов;
26 Java native entrypoint names сопоставлены с Rust exports; Bash syntax инструкции передачи прошёл.
Compiler test выполнялся с 5GiB job cap/2GiB headroom/below-normal, без Cargo/full/native build.
Java/JNI typecheck, runtime UI/device и desktop regression остаются непроверенными; APK не создавался.
- [README handoff](../README.md#handoff-to-another-developers-wsl2-machine) содержит точный существующий
recipe и список receipts для другого ПК. Передавать нужно новый full SHA commit со **всеми** Android-изменениями;
старый `cb1d682` их не включает. Commit/push разрешены; успешность доставки устанавливается по remote SHA, не наличию этой записи.
Не передавать локальную ресурсную политику, credentials, signing keys, профили и Windows caches.
- Scope остаётся честным: известные подтверждённые пробелы доработаны, но «все 718 требований готовы»
не доказано. Перед первой Android-сборкой нельзя исключить Rust/Java/Gradle/JNI integration errors.
Остальные device gates и намеренные unsupported product features перечислены в последнем assessment.
## TX-кандидат: CI пройден, headset TX не принят
- `a0a9b14`: Android capture сохраняет будущий timestamp-хвост callback до SRC/DSP/TX;
возраст200ms, epoch/mute/boundary и desktop-путь сохранены (`native/src/media/audio/{devices,engine}.rs`).
- EchoReference28 исключён из микрофонов; неизвестные vendor-источники и exact selection не подменяются
(`native/vendor/cpal-0.18.2/src/host/aaudio/device_catalog.rs`).
- Повтор **CI4959 / `057bfae`: SUCCESS**, APK и тестовые артефакты готовы. Это не приёмка headset TX.
- Не откатывать кандидат и не трогать постороннее изменение `.ua/meta.json`.
## Принятая Windows-база и мобильная ветка
## Android UI — выбор направления
- Пользователь явно подтвердил в форме: **проверил подключение, вход в канал и голос в обе стороны, принимает установленную Windows 0.1.7 и разрешает baseline/push**. Desktop acceptance gate снят; это ручная приёмка владельца, не новый автоматический тест.
- До обновления стоял **0.1.4 Electron**; теперь принят **0.1.7 Rust/Slint**. `main` сохраняет проверенную базу, Android/iOS дорабатываются в `feature/mobile-port`; изменения desktop-поведения требуют отдельного запроса, общий core/DSP/services — desktop regression checks. Ниже сохранена хронология сборки; прежние запреты push относятся к этапу до приёмки.
- **Push main и desktop-baseline успешен**: пользователь ввёл credentials в отдельном обычном PowerShell, команда с отключённым для одного запуска credential helper завершилась exit0. `git ls-remote` подтвердил main и peeled tag на `05e8d34bcf0e24a44f76e65220293c45b6821798`. Прежний GCM auth/transport blocker обойдён, не объявлен исправленным; credentials ассистент не читал и команда их не сохраняла. По уточнению пользователя `feature/mobile-port` оставлена локально, на remote её нет; для CI по этой ветке позже потребуется отдельный push. Релиз/установщик не опубликован.
- До изменения установки сохранён побайтово проверенный rollback: `%LOCALAPPDATA%/Programs/TeamsPeach.rollback-20261110-223748`, 78 файлов. При установке native исходный каталог также целиком переименован в `TeamsPeach.pre-native-20261111-111816`. Пользовательские профили/identity/настройки вне installation directory не читались и не изменялись.
- Full native artifacts отсутствовали. Guarded serial `xtask deps` Windows x64 прошёл исправленную MSVC activation, pinned SDK/depot_tools/WebRTC checkout и gclient sync. OEM/UTF-8 ошибка устранена child `chcp 65001`; отдельный real-vcvarsall smoke сохранил синтетическую кириллицу. Следующий blocker — CRLF checkout checksum-pinned patches: добавлен `.gitattributes`, все три патча восстановлены как LF и точные SHA256 проверены без изменения lock. Повторный provisioning отказал до старта по локальному RAM guard (exit125); полный build/package/runtime **не выполнен**, установка 0.1.4 нетронута.
- После успешной сборки: isolated native smoke → production package/verify → установка с сохранённым rollback → ручная приёмка владельца. После подтверждения фиксировать desktop-baseline; mobile-specific изменения изолировать, shared core/services не менять без desktop regression проверки.
- Для продолжения нужен безопасный запас свободной RAM по локальной политике; не закрывать пользовательские приложения и не повышать предел автоматически. NSIS 3.13 установлен для будущего native packaging. Backup installation сохранён, профили не читались/не менялись, push после запроса desktop-приёмки не выполнялся.
- Пользователь попросил исходить из доступной RAM. Пересчитанный вниз локальный budget успешно выдержал **полный WebRTC source-build**: после timeout на 4010/4305 шагах build возобновлён с cache и завершился exit0; `xtask deps` выдал verified source dependency provenance и обновил реальный Windows record в `native/native-deps.lock.json`. SDK Debugging Tools установлен, dbghelp.dll присутствует. Это dependency compile/inspection pass, не UI/device acceptance. Следом запущен полный Rust/Slint `xtask build --test-harness true` под тем же guard; production install пока не изменён.
- Пользователь явно снял паузу («запускай… снимаю с паузы»). Full native harness build возобновлён под сохранённым локальным guard и одним заданием; WebRTC provenance уже готова. До успешных native smoke/package checks установленный 0.1.4 и профиль не менять. Push по-прежнему запрещён до пользовательской приёмки.
- Возобновлённая Rust/Slint build дошла до skia-bindings0.153.3: matching prebuilt URL вернул404, source extraction упала на Windows symlink privilege1314. Подготовлен отдельный Skia `m153-0.101.2` в `target/tools`, archive SHA256 `30c8b51a0a32fae63562c303bdc91605519a9598951422610e3fb8685b3c4f6f`; проверены archive paths/symlink target, только extraction выполнен elevated (exit0), global Developer Mode не менялся. Pinned git-sync-deps/GN выполнен serial под guard (exit0). Full build возобновлён с явным --skia-source и локальным Ninja wrapper -j1; установка/профиль не затронуты.
- Пользователь после обсуждения длительности явно разрешил продолжить первый Windows-native build («поехали дальше»). Возобновлён тот же cached full Rust/Slint build под локальным guard/-j1/below-normal; готовые WebRTC/Skia объекты не удаляются. Текущая установка и профиль до smoke/package pass не заменяются, push запрещён до desktop-приёмки.
- Full harness build **завершился exit0**; `target/x86_64-pc-windows-msvc/release/teamspeach.exe` получен с default Skia+WebRTC. До успешной попытки main rustc получил allocation failure/LLVM OOM под локальными пределами; согласованный пользователем локальный workaround записан только в `mobile-build.local.md`, общие optimization defaults не менялись.
- Реальный `xtask smoke --scenario offline-ui` **passed=true**, 8 checks, 28 screenshots: `target/desktop-acceptance/offline-ui/result.json`. Disposable profile, network/OS actions/physical capture выключены; Slint software offscreen. Проверены callback/runtime/settings, rich rendering, PTT focus, draft retention и profile restart; onboarding screenshot просмотрен. Это не GPU/on-device/двусторонний голос acceptance.
- Production build **без test-harness** и `xtask package` **exit0**; NSIS и ZIP прошли встроенный `verify-package`: `target/desktop-acceptance/production/x86_64-pc-windows-msvc/verification.json`, `passed=true`, `unsigned-local`, публикация не разрешена. Тот же локальный optimization override; не выдавать пакет за стандартный CI release.
- Native **0.1.7 установлен** в `%LOCALAPPDATA%/Programs/TeamsPeach`: NSIS exit0, SHA256 всех 76 payload files совпали, установленный `--version` вывел `TeamsPeach 0.1.7 (Rust + Slint)`, `--help` не содержит test-harness. Старый Electron uninstall key экспортирован в `target/desktop-acceptance/legacy-uninstall-registration.reg` и удалён после установки; исходный каталог сохранён, пользовательский профиль не тронут.
- Реальное окно установленного production exe проверено с новым временным `TEAMSPEACH_PROFILE_DIR` и закрыто штатно exit0; профиль удалён. Снимок: `target/desktop-acceptance/installed-native-window.png`. Подключение/голос затем проверил и принял владелец; миграция пользовательского профиля отдельно не подтверждена. Следующий этап — Android CI/device проверки в мобильной ветке. Baseline tag не является release tag `v*`; публикация установщика не выполняется.
- На ревизии `057bfae` владелец выбрал voice-first и разрешил собственный Android-стиль:
исходная палитра TS6, редактирование цветов в настройках. Windows остаётся без изменений.
- До реализации Slint запрошено HTML-сравнение пяти вариантов с одинаковыми сценариями.
Локальный прототип: `target/tmp/android-ui-concepts/index.html` (+ CSS, JS, bundled Noto Sans).
**Владелец выбрал «Комнату» целиком**, без смешивания вариантов; начат перенос в Android Slint.
- В Android Slint перенесены Room-навигация/участники/voice dock, чат и формы; реальные данные идут из
`Snapshot.room`, выбор канала/участника и команды остаются typed intents. DSP/media/platform не менялись.
- Добавлен `androidPalette`: preview/save/cancel/reset, hex/RGB, контрастные роли; desktop не применяет override.
По умолчанию **English**, Russian — через настройки; сохранённый язык не сбрасывается.
- Проверено локально: integrated Slint compile PASS; реальные `ui/i18n.rs` tests **3/3 PASS**.
- **CI4973 / `956b464`: SUCCESS**, поправка программной навигации включена; APK скачивается для UI-проверки.
Preview-tests исправлены под CI-фильтр (только имя тестового модуля); им предстоит отдельный подтверждённый запуск.
Android Room-исключение записано в DESIGN.md; desktop baseline сохраняется.
## Read-only Android CI preflight, 2026-11-11
## Следующее действие
- **Сверено:** `feature/mobile-port`, HEAD `82334f8a8bf25be6b594d013eb30f55f25c8c7bb`; исходное рабочее дерево чистое (staged/unstaged/untracked отсутствуют в `git status`). Локальные `main`, `origin/main` и peeled baseline tag — `05e8d34bcf0e24a44f76e65220293c45b6821798`; отличие HEAD от baseline — только этот handoff. `mobile-build.local.md` прочитан, исключение из Git подтверждено; локальные ограничения не перенесены в CI.
- **Live Gitea:** публичный [branches API](https://git.eeee.moe/api/v1/repos/TeamsPeach/client/branches) показывает только `main` на `05e8d34`; [Android Actions](https://git.eeee.moe/TeamsPeach/client/actions?workflow=android.yml&actor=0&status=0&branch=) показывает **0 workflow runs**. Workflow уже опубликован в baseline; мобильная ветка остаётся локальной. Actions UI доступен, но готовность artifact storage этим не доказана.
- **Точный блокер доступа:** GET `/api/v1/repos/TeamsPeach/client/actions/runners` и `/actions/variables` вернули HTTP 401. Попытка открыть Actions через подписанный браузер не состоялась: relay connection timeout 30 s. `ssh://` сообщает, что настроенных hosts нет. Runner `teamspeach-android-linux-x64`, его online/labels/resources, установленные SDK/NDK/JDK/LLVM/Skia и наличие семи variables из README **неизвестны**; ни одна variable не объявлена отсутствующей без доступа. Credentials/tokens/profile не читались; Git auth не проверялся и не объявлен исправленным.
- **Статически готово:** ручной ARM64 workflow с full Skia+WebRTC, source dependency provisioning, отдельными harness APK и unsigned production APK/AAB, package verification, revision/SHA256 receipts ([workflow](../.gitea/workflows/android.yml), job `android-arm64`; [variant recipe](../.gitea/build-android-variant.sh)). SDK API36/build-tools36.0.0/NDK28.2.13676358, JDK17+, LLVM/libclang, synced Skia+GN, local Gradle8.14.3 ZIP и bundletool должны существовать на runner до build dispatch; Rust1.96.0 и Android target также обязательны. Список variables — [README](../README.md):101–117. В dependency lock по-прежнему только Windows record; Android receipt должен появиться от реального `xtask deps`, не вручную.
- **Дополнительные prerequisites:** runner execution environment должен поддерживать checkout@v4/upload-artifact@v3 и исходящие загрузки pinned WebRTC/depot_tools/CIPD, Cargo и Gradle dependencies. `xtask deps` использует отдельный upstream Gradle wrapper для prefixed JNI jar ([deps.rs](../xtask/src/deps.rs):605–615); локальный Gradle ZIP приложения не делает всю цепочку offline. Rust Android build выбирает DEPS-pinned NDK из WebRTC checkout ([build_native.rs](../xtask/src/build_native.rs):275–290), а установленный NDK28.2 проверяется workflow/Gradle. CI capacity и сетевой доступ не измерены; run-specific checkout/target/Gradle trees означают, что межзапусковой object-cache reuse этим workflow не настроен.
- **Риск получения первого APK найден и затем исправлен локально:** исходный workflow загружал harness после полного цикла harness+production. В разрешённом продолжении порядок изменён на harness build/verify → harness upload → production build/verify → production upload ([workflow](../.gitea/workflows/android.yml), job `android-arm64`). Общий прежний recipe вынесен в `.gitea/build-android-variant.sh`; failure gates и receipts сохранены. Реальный CI upload ещё не проверен.
- **Уточнение harness:** без smoke extras `smoke_request` возвращает `None`, а Android host выставляет `network_enabled=true` и `allow_os_actions=true` ([smoke.rs](../native/src/platform/android/smoke.rs):16–40; [android.rs](../native/src/platform/android.rs):61–85). Offline isolation относится к smoke-запуску, не ко всем запускам harness APK. Обычный запуск test APK — кандидат для первого разрешённого live voice proof на отдельном тестовом телефоне; это статический вывод, не phone/production acceptance. Application ID общий с production — не устанавливать поверх реального профиля.
- **Граф:** `.ua/meta.json` и project metadata остаются working-tree snapshot от `5ce12714`, не текущий HEAD; прочитаны только нужные метаданные/узлы/связи. Архитектура не менялась, граф и auto-update не тронуты.
- **Следующий порядок:** восстановить read-only доступ к runner/variables и получить фактический tool/resource inventory → согласовать только обнаруженное provisioning и точечные CI-изменения → отдельное разрешение на push `feature/mobile-port` и manual dispatch → проверить скачанный harness APK, revision/SHA256 и receipts → отдельно согласовать ARM64 API26+ телефон, disposable app data, сервер/канал и ПК-peer, затем install/launch/mic/Join ACK/двусторонний голос. iOS/macOS/Xcode/signing — отдельный незакрытый маршрут.
- **Проверки этой сессии:** Git metadata, targeted source/docs/graph reads и публичные HTTP GET. Не запускались Cargo/Gradle/tests/build/package/CI/device/app, ничего не устанавливалось и не отправлялось. Изменены только handoff и точное уточнение harness в assessment; исходники, desktop, caches и локальная политика нетронуты. Исторические записи ниже о незакоммиченном CI относятся к прежнему этапу, не к состоянию этого preflight.
- Проверить хеши APK4973 и UI на TECNO KJ7; отдельно дождаться CI тестового переименования.
- **Владелец разрешил установку без удаления данных и offline UI-проверку.** При несовпадении TEST-подписи
остановиться и отдельно согласовать переустановку; не подключаться к серверу/микрофону самостоятельно.
- Принимать headset TX отдельно от принятого RX. Затем остаются reconnect, Recents first-reopen и
совместимые input/output-пары. Сначала использовать сохранённую диагностику, не переписывать RX.
### Разрешённое продолжение: доступ к CI и точечная правка
## Навигация и доказательства
- Пользователь разрешил браузерный вход и продолжение подготовки, повторно подтвердив, что Android LLVM/SDK/build должны находиться на удалённом CI, не на его Windows-ПК. Локальная политика, WSL, память и compiler settings не менялись.
- Браузерный вход состоялся через уже установленный Chrome, без установки инструментов/расширений и без чтения пароля/cookies/tokens. Авторизованная страница repository Actions runners показала **ровно один доступный runner**: `monkeyRunner`, ID9, v0.2.13, глобальный, «Простаивает»; labels `ubuntu-latest`, `ubuntu-22.04`, `ubuntu-20.04`. **Нужного label `teamspeach-android-linux-x64` нет.** Repository variables page показала пустой список; семь требуемых переменных на уровне репозитория не настроены. Наследуемые organization variables и установленный host toolchain не проверены.
- Авторизованный доступ к Gitea settings больше не блокер; **блокер запуска — отсутствие matching runner label и repository configuration**, а фактические SDK/NDK/JDK/LLVM/Skia, RAM/disk/network на host остаются неизвестны. Нельзя просто заменить runs-on на `ubuntu-latest`: это направит тяжёлую сборку в неподтверждённую среду. Нужен согласованный удалённый Linux execution environment и его inventory; Git auth отдельно не проверен.
- Повторные обращения к браузеру давали detached Frame и открывали новые окна. Пользователь потребовал прекратить открывать Chrome, затем **уточнил разрешение: невидимый браузер допустим, видимые окна запрещены**. Продолжение выполнено с `headed:false`, вкладка закрыта после чтения. Пароли/cookies/tokens и пользовательский профиль приложения не читались.
- Локальная CI-правка завершена: helper `bash -n`, syntax всех workflow run blocks, YAML parse, compile обоих embedded Python scripts и статический порядок стадий прошли. Python subprocess сначала не нашёл Bash в PATH; проверка выполнена через имеющийся shell tool, без установки. Это syntax/structure checks, **не Android build или CI/device proof**. Обновлён CHANGELOG; исходники приложения и desktop-поведение нетронуты, граф не обновлялся.
- Пользователь подтвердил **Android-only на ближайшем этапе**: разработка на Windows, APK на удалённом Linux; WSL не возвращать. После проверки вариантов явно разрешены **push только `feature/mobile-port` и один диагностический CI run до 5 минут на существующем runner**, без установки, компиляции и чтения секретов. Main/релизы/телефон и тяжёлый build не входят в это разрешение.
- В `android.yml` добавлен безопасный default `mode=inventory`: job `runner-inventory` на `ubuntu-latest`, без checkout/action downloads, только OS/CPU/RAM/disk/cgroup/tool/config inventory; значения variables не печатаются, Rust proxies не вызываются. `mode=build` — единственный путь к прежней тяжёлой job на выделенном Android label. YAML/Bash syntax и статические mode/timeout/job gates проверены; фактический remote run ещё предстоит. Runner resources и inherited organization variables пока неизвестны.
### Реальный runner inventory: run 4828, 2026-11-11
- **Push выполнен:** отдельный PowerShell с ручным вводом credentials, credential helper отключён только для команды; exit0. Публичный branches API подтвердил `feature/mobile-port=cb1d682dfb307ec41d73434ab40de5de0b30410e`, `main=05e8d34bcf0e24a44f76e65220293c45b6821798`. Credentials не читались, GCM не объявлен исправленным. Коммит включает диагностический режим, раннее сохранение harness и документы; запись фактического результата ниже добавлена локально после push.
- **Единственный разрешённый dispatch выполнен:** [android-ci run 4828 / #62](https://git.eeee.moe/TeamsPeach/client/actions/runs/4828), [job runner-inventory 5423](https://git.eeee.moe/TeamsPeach/client/actions/runs/4828/jobs/5423) — **success, 1 s**; `android-arm64` — **skipped**. Выбрана `feature/mobile-port`; форма Gitea на default branch ещё не показывала input `mode`, поэтому сработал безопасный fallback inventory при отсутствии `mode=build`. Новых dispatch/re-run не выполнялось.
- **Execution environment подтверждён setup log:** `monkeyRunner` v0.2.13 запускает job в контейнере `docker.gitea.com/runner-images:ubuntu-latest`. Docker pull проверил существующий image как up-to-date; это инфраструктура удалённого CI, не Docker/WSL на Windows. Диагностический step не скачивал SDK/dependencies и не устанавливал инструменты. Наличие инструментов на физическом host из этих данных не следует: измерено окружение job.
- **Ресурсы, видимые job:** Linux x86_64, 32 CPU; `/proc/meminfo`: MemTotal 129429464 KiB, MemAvailable 30306932 KiB (≈28,9 GiB); workspace Available 21965056 KiB (≈20,95 GiB) из 64 GiB. Cgroup v2 `memory.max=max`, `memory.swap.max=max`, `cpu.max=max 100000` в видимом scope; это не гарантия отсутствия ancestor/shared-host limits. Linux Committed_AS превышал CommitLimit; не трактовать эти Linux показатели как Windows Job Object guard или обещание безопасной build capacity. Достаточность свободного диска для холодного WebRTC+Skia build не подтверждена.
- **Фактические tools:** git/python3/pkg-config/ar/sh/node найдены в PATH. cargo/rustc/rustup, cmake/ninja, clang/clang++, llvm-strip/llvm-readelf, java/javac/jar/keytool/jarsigner, zipalign/aapt2/apksigner/sdkmanager — **missing-from-PATH**, не утверждение об отсутствии на всём host. Rust1.96.0 не найден в обычном rustup-home. SDK/Skia roots не настроены, поэтому их установки остаются неизвестными, а не просканированными как отсутствующие.
- **Все семь variables действительно unset в CI-контексте:** `ANDROID_SDK_ROOT`, `ANDROID_JAVA_HOME`, `NATIVE_LLVM_HOME`, `NATIVE_LIBCLANG_PATH`, `NATIVE_SKIA_SOURCE_DIR`, `ANDROID_GRADLE_DISTRIBUTION`, `ANDROID_BUNDLETOOL`. Унаследованные runner env roots Android/JAVA/LLVM/libclang/Skia тоже unset. Пустой repository UI больше не единственное основание этого вывода.
- **Точный следующий blocker:** общий runner работает, но его job image не предоставляет Android toolchain/configuration; matching Android label по-прежнему отсутствует. Нужна отдельно разрешённая подготовка Android execution image и build/cache storage на существующем удалённом runner, затем фактические paths/variables и dedicated label. Нельзя подменять этим изменением общий image других проектов или просто запускать heavy build на generic `ubuntu-latest`. Host access/административное provisioning не предоставлены; текущая авторизация покрывала только push и один inventory, не установку/сборку.
- **Граница доказательства:** реальный read-only Linux CI pass, не Android compile/package/APK/device/voice acceptance. Windows acceptance/base, desktop-код, локальные compiler settings, caches, pagefile и WSL не менялись. Все последующие browser calls использовали `headed:false`; вкладки закрыты. iOS на этом этапе не исследовался и не собирался.
## Текущий маршрут: Android в CI, Windows без WSL
- После пользовательского входа в Git Credential Manager push **успешен**: `origin/main` обновлён с `eb24965` до `5ce1271` (включая cutover, handoff и граф). Указанный ниже прежний auth blocker снят. Секреты не читались и в документы не записывались.
- По отдельному разрешению установлен rustup и toolchain `1.96.0-x86_64-pc-windows-msvc` (`minimal`). Реально выполнены `rustc --version` и `cargo --version`: обе версии 1.96.0. Инструменты находятся в `%USERPROFILE%/.cargo/bin`; уже запущенной оболочке может понадобиться обновление PATH.
- По выбору пользователя **весь Android APK/AAB build/package выполняется на Linux CI**; Windows используется для разработки и установки test APK через Platform-Tools. Локальные WSL/Docker/Linux и виртуализация для этого маршрута не нужны. Pinned WebRTC Android source-build официально Linux-only — это требование CI, а не компьютера разработчика. iOS по-прежнему требует macOS/Xcode локально или на CI.
- Пользователь возобновил работу после паузы. LLVM 23.1.5 установлен, `clang --version` и `rustc --version` после перезагрузки успешны; CMake/Ninja найдены в Visual Studio Build Tools. `cargo test --locked -p xtask -p teamspeach-core -p teamspeach-denoise` завершился успешно: **246 passed, 1 ignored, 0 failed** (core unit 207; bridge 5; embedded 3; runtime failures 4; DSP 18; xtask 9). Это Windows-проверки core/DSP/упаковщика, не full native UI/WebRTC или device acceptance.
- Visual Studio Build Tools **2022 17.14.44** установлен повторной попыткой (официальный актуальный bootstrapper с проверенной подписью Microsoft, exit 0). `vswhere -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64` подтвердил C++ workload, `isComplete=true`, `isLaunchable=true`, `isRebootRequired=false`. Путь: `C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools`. Первая попытка winget завершилась 5008; её результат не считать итоговым.
- WSL удалён штатными Appx/MSI uninstall (exit0); проверено AppxPackages=0, MsiPackages=0, DistroCount=0. Удалены его runtime directory, пустое хранилище неудавшейся Ubuntu, `.wslconfig` и пустой WSL installer cache. Windows optional features `VirtualMachinePlatform` и `Microsoft-Windows-Subsystem-Linux` отключены (CIM InstallState=2). Измеренный удалённый runtime payload — около 828 MiB; Windows system launcher/общие Installer caches вручную не удалялись.
- Локальные ограничения памяти остаются только в `mobile-build.local.md` и `.git/info/exclude`; не переносить их в общие настройки/граф. Не устанавливать WSL снова для мобильной цели без нового запроса.
- Добавлен ручной `.gitea/workflows/android.yml`: ARM64 harness APK и отдельные unsigned production APK/AAB, default Skia+WebRTC, pinned dependencies, receipts и `build-info.json` с revision/SHA256. Для чистого CI Gradle cache добавлен явный Android-package-only `--gradle-online true`; default offline сохранён, SDK downloads выключены, build/project caches изолированы по package.
- Проверено после изменения: `cargo test --locked -p xtask` **10 passed, 0 failed**, фактический CLI `--help`, YAML manual trigger, syntax четырёх bash steps и двух Python scripts, локальные ссылки docs. Реальный Android CI/Gradle/APK/device запуск **не выполнен**: нужен provisioned `teamspeach-android-linux-x64` runner и переменные из README. Неавторизованный read-only Actions API вернул HTTP401; наличие/готовность runner неизвестны. Credentials не извлекались.
- Изменения текущего CI-маршрута не закоммичены/не отправлены. Граф обновлён по рабочему дереву: **3702 узла, 9131 связей, 7 native-слоёв**, добавлены Android CI, `parse_options`, `android_gradle_command` и текущий маршрут без WSL. Штатный incremental updater отказал из-за dirty tree; использованы установленные scan/import/structure scripts и targeted reconciliation без commit/stash. `meta.json` явно помечен `workingTreeSnapshot=true`; прежние fingerprints/scan baseline не выданы за clean HEAD. Schema/refs проверены, actual dashboard на :5173 отрисовал native+Android CI без Electron-слоёв. Предупреждение working-tree changes остаётся корректным до коммита. Автообновление выключено.
## Native-only cutover
- Выбранная архитектура: Rust/Slint `native/` + embedded `core::runtime`; Electron/Node application host, `app/`, browser-only `test/`, `scripts/`, npm manifests удалены. Профильный import и защитные проверки устаревшего ciphertext сохранены — это пользовательская совместимость данных, не Electron runtime.
- Native icon и 54 WAV перенесены в `native/resources/`; перед удалением старого дерева SHA-256 каждой пары проверен на точное совпадение. Native DSP больше не экспортирует renderer-only WASM ABI; Cargo `denoise` profile удалён.
- Build/CI/release переключены на Cargo/xtask и явно подготовленные native Linux x64/ARM64 runners; версия приложения/core/xtask берётся из Cargo workspace. Публикация отдельной командой: проверка artifacts → draft → upload/readback hashes → publish. Историческое исследование в assessment сохранено с immutable ссылками на базовую ревизию.
- **Ограничение проверки:** `cargo`, `rustc`, `rustup`, `cl`, `clang`, `cmake`, `ninja` отсутствуют в PATH; стандартные пользовательские каталоги Rust также отсутствуют, CARGO_HOME/RUSTUP_HOME не заданы. Сборочный toolchain автоматически не устанавливался. Нельзя выдавать static checks за native build или device proof.
- Мобильные blockers из первоначального исследования не исправляются удалением Electron. Не считать interruption/Bluetooth/background/official-peer сценарии пройденными.
- Выполнены 4 Python-теста release transport с mocked HTTP (OK), parse 8 TOML/lock и 3 YAML, проверка 718 сохранённых pending acceptance cases, отсутствие удалённых деревьев и разрешение 21 literal embedded-resource path. Rust unit/build/UI/device checks не выполнены: toolchain отсутствует; `wsl --list --quiet` подтвердил, что WSL не установлен. Новые runner labels/configurations ещё не проверены реальным CI запуском.
- Source cutover закоммичен: `220852f8cb7ccb4b912f988f603c23267808626d` (`Remove Electron and make Rust Slint the sole native client`). `git push origin main` завершился ошибкой авторизации: `could not read Username ... terminal prompts disabled`; удалённая ветка этой попыткой не изменена. Авторизовать Git через credential manager/обычный терминал, не передавать токены в чат.
- Следующий проверочный шаг для текущей архитектуры: предоставить Rust 1.96.0 и native C/C++/SDK source-build prerequisites, выполнить Cargo/native smoke из README, затем мобильный voice prototype. Старый read-only этап ниже сохранён только как история.
- Understand update preflight выбрал `FULL_UPDATE` (314 удалённых граф-файлов, 38 файлов для нового анализа). Итоговая native-only карта: 371 текстовый файл, 3699 узлов, 9120 связей, 7 слоёв, 9 шагов на русском; один binary WAV из 372 scan entries исключён. Schema/path/layer/tour validation прошла без issues, 263 resolved imports сохранены; merger удалил 45 некорректных tested_by связей. Electron runtime/framework/layers отсутствуют, `autoUpdate=false`. Application source — `220852f8`; `meta.json` фиксирует конкретный snapshot после передачи состояния.
## Историческое исследование до cutover
## Решения и основания
- Не начинать переписывание на Flutter/React Native/двух native UI: сначала проверить уже существующие `core::runtime::{CoreHandle,CoreEvents}`, Rust app/services и Android/iOS-адаптеры. Rust/Slint — первый кандидат для прототипа **после** установления этой границы, не безусловный окончательный выбор.
- Основной голос — TeamSpeak UDP/Opus; WebRTC используется отдельно для трансляций. Не подменять серверный протокол WebRTC-голосом.
- Android и iOS проверять с первого сквозного эксперимента. Общий UI не доказывает одинаковый UX, accessibility или background behaviour.
- Не переносить subprocess/stdio/PCM-base64 Electron в мобильный runtime: embedded API уже существует. Сохранять SessionKey, capture epochs, timestamps и единственного владельца микрофона.
- Никаких исходников приложения не менять на исследовательском этапе; build/install/test/run/network-to-test-server требуют отдельного разрешения.
## Выполнено
- Создан [подробный разбор](mobile-port-assessment.md): стек/входы/build/tests, connect/auth/channels, оба аудиотракта, переносимость, OS-ограничения, официальные dependency references, лицензии и последовательность прототипа с наблюдаемыми критериями.
- Однократно проведён первичный Understand-Anything: `.ua/knowledge-graph.json`, `meta.json`, `fingerprints.json`, config и scan inventory. 679 текстовых файлов, 5233 узла, 13204 связи, 9 слоёв и 9 шагов на русском. Scan/fingerprints: 680 entries; один бинарный WAV исключён из графа. `autoUpdate=false`.
- Создан корневой [AGENTS.md](../AGENTS.md) с порядком чтения/актуализации переносимой памяти. До сессии корневого файла не было; вложенные инструкции не изменены.
## Реально проведённые проверки
- Git metadata/inventory: HEAD, branch, initial porcelain status, 2221 tracked-файл; метаданные путей проверены на reparse links. Пользовательские профили и секреты не открывались.
- Статическое чтение исходников и test/build recipes; официальные Slint/CPAL/Sonora/Rust/Electron/LiveKit/Android/Apple/license документы.
- Штатные installed Understand scanner/import/batching/structure/merge/fingerprint scripts. `validateGraph` и layer/tour integrity — success, issues отсутствуют; все 872 resolved imports сохранены. Merge удалил 15 некорректных `tested_by` связей.
- Проверена фактическая загрузка и отрисовка русского графа в installed understand-dashboard через managed browser; tabs закрыты. Dashboard service запущен на loopback в текущей сессии; для следующей использовать `/understand-dashboard C:/Dev/TeamsPeach`, не сохранять access token.
- Проверка путей/диапазонов цитат обнаружила четыре выходивших за EOF диапазона; они сверены с исходниками и исправлены.
- Финальная проверка: все 179 source citations к 82 файлам имеют существующие пути и допустимые диапазоны; локальные ссылки документов корректны, code fences сбалансированы. Финальный git status содержит только новые `.ua/`, `AGENTS.md` и два разрешённых документа; tracked/staged diff пуст. Промежуточные файлы Understand перемещены в стандартный `.ua/.trash-*`, scan inventory сохранён.
- **Не выполнялись:** сборка/установка/запуск приложения, Node/Cargo tests, мобильный smoke, подключение к серверу, измерение звука, проверка телефона, signing/publishing. Нельзя записывать эти проверки как пройденные.
- LSP не настроен (`No language servers configured for this project`). Static Slint site fetch и browser relay дали timeout; официальные versioned docs прочитаны через GitHub, dashboard — через отдельный managed browser. Навыки доступны и реально использованы.
## Блокеры и риски
1. **Сборки:** в `native/native-deps.lock.json#/builds` только Windows x64 record. Native recipe требует Linux source-build host для Android и macOS/Xcode для iOS; наличия этих hosts, SDK, signing и test devices не установлено. Не создавать fake provenance.
2. **iOS interruption resume:** API `CallLease::resume` есть, вызова из runtime в просмотренном дереве не найдено; common handler останавливает input/output, окончание лишь сообщает статус. Cached mobile lease не равен активной AVAudioSession. Android explicit microphone action может восстановить output через `sync_audio`, но автоматический handler этого не делает. См. assessment §7, не упрощать до «resume нигде невозможен».
3. **Реальный audio/runtime:** неизвестны speakerphone AEC, Bluetooth mic/output, timestamps/drift, фон, permission revoke, Wi-Fi↔cellular и VoiceOver parity. Upstream support не доказывает эту сборку.
4. **Распространение:** код `UNLICENSED`; разрешение на redistribution заимствованных TeamSpeak icons/sounds не установлено. Slint attribution и полный native dependency/codec notices inventory требуют проверки конечного пакета.
5. **Паритет:** `native/compatibility.json` — pending inventory, не доказательство 718 работающих функций; legacy Speex/CELT и перечисленные unsupported services не считать реализованными.
## Следующий шаг
После отдельного разрешения на исполнение — подготовить **изолированные** Android/Linux и iOS/macOS build/test среды и пройти assessment §10 по порядку: native dependency/core build → foreground capture/playback → реальный connect и Join ACK → двусторонний голос Android↔iOS↔контрольный desktop peer → privacy/lifecycle/routes/network. Минимальный proof не сокращает требования к полной версии; остальные функции получают отдельную parity-приёмку.
В новой сессии сначала сопоставить HEAD и uncommitted изменения с этой записью. Перепроверять только затронутые выводы. Новые docs/AGENTS созданы после первичного scan и могут давать честный working-tree warning в dashboard; исходники приложения в этой сессии не менялись. Не перезапускать полный Understand ради новых документов; обновлять граф при архитектурных изменениях, предпочитая incremental.
- [Текущая архитектура и ограничения](mobile-port-assessment.md) — читать только нужный раздел.
- Последняя диагностика: `target/tmp/android-4955-audio-only.log`,
`android-4955-headset-system-summary.json`, `android-4955-rx-working-mic-gap-now.png`.
Это локальные артефакты; не считать гарантированно доступными в другом checkout.
- `.ua/knowledge-graph.json` — старый snapshot, только навигация. Не пересканировать весь проект;
auto-update выключен. Существенные выводы проверять исходниками.
- [Архив хронологии](archive/2026-11-14-mobile-port-progress.md) и
[архив исследований](archive/2026-11-14-mobile-port-assessment.md) — **не читать при старте**.
Открывать нужный участок только по конкретному вопросу; старые ссылки/статусы исторические.
+5 -1
View File
@@ -3,6 +3,9 @@
//! Sonora owns the split/filter/synthesis path. Never put another noise suppressor
//! or OS/WebRTC AEC in front of this processor. The caller supplies the actual
//! post-gain playout mix, aligned to the capture clock, before capture processing.
//! Both public PCM boundaries are normalized `f32` in [-1, 1], not FloatS16.
//! Sonora's AudioBuffer performs the internal FloatS16 conversion for AEC/NS/AGC;
//! scaling by 32768 here would double-convert and saturate ordinary microphone PCM.
//!
//! Sonora's integrated NS also enables its split-band high-pass filter. The test-only
//! noise-only reference does not; waveform equivalence to that wrapper is not promised.
@@ -24,6 +27,7 @@ pub struct CaptureSettings {
/// `None` disables NS; `Some(0..=3)` means Low / Moderate / High / Very High.
pub noise_suppression: Option<u8>,
/// Enables adaptive digital AGC2, not hardware microphone-volume control.
/// Uses Sonora's speech/noise-aware gain and limiter; does not add fixed pre-gain.
pub automatic_gain_control: bool,
}
@@ -145,7 +149,7 @@ impl CaptureProcessor {
})
}
/// Analyze the actual post-gain playout mix; this never modifies the supplied PCM.
/// Analyze normalized, actual post-gain playout PCM; never modify the supplied frame.
///
/// `delay_ms` includes hardware delay, queued samples and resampler latency. Reject
/// out-of-range delay rather than silently continuing with Sonora's clamped estimate.
+155
View File
@@ -274,3 +274,158 @@ fn invalid_settings_never_construct_a_processor() {
}), Err(CaptureError::InvalidNoiseSuppressionLevel(actual)) if actual == level));
}
}
#[test]
fn normalized_float_matches_integer_sonora_at_every_enabled_stage_boundary() {
// The independent i16 entry point consumes FloatS16 units without the float
// API's normalization conversion. This catches both missing and double scaling,
// including reverse/AEC scaling, rather than comparing two float wrappers.
for echo_cancellation in [false, true] {
for noise_suppression in [None, Some(0), Some(1), Some(2), Some(3)] {
for automatic_gain_control in [false, true] {
let settings = CaptureSettings { echo_cancellation, noise_suppression, automatic_gain_control };
let mut processor = CaptureProcessor::new(settings).unwrap();
let stream = StreamConfig::new(48_000, 1);
let mut integer = AudioProcessing::builder()
.config(configuration(settings).unwrap())
.capture_config(stream)
.render_config(stream)
.build();
let mut seed = 0x71ab_2309;
let mut render_output = [0_i16; FRAME_SAMPLES];
let mut expected = [0_i16; FRAME_SAMPLES];
let mut output_energy = 0.0;
for frame in 0..120 {
let render = noise(&mut seed, 0.15).map(|sample| (sample * 32768.0).round() as i16);
let input: [i16; FRAME_SAMPLES] = match frame {
0..=9 | 90..=119 => [0; FRAME_SAMPLES],
10..=39 => harmonic(frame, 0.002).map(|sample| (sample * 32768.0).round() as i16),
40..=69 => harmonic(frame, 0.08).map(|sample| (sample * 32768.0).round() as i16),
70..=79 => std::array::from_fn(|index| if index % 2 == 0 { i16::MAX } else { i16::MIN }),
_ => [512; FRAME_SAMPLES],
};
let normalized_render = render.map(|sample| f32::from(sample) / 32768.0);
let mut actual = input.map(|sample| f32::from(sample) / 32768.0);
processor.process_render(&normalized_render, 20).unwrap();
integer.set_stream_delay_ms(20).unwrap();
integer.process_render_i16(&render, &mut render_output).unwrap();
processor.process_capture(&mut actual).unwrap();
integer.process_capture_i16(&input, &mut expected).unwrap();
assert_normalized(&actual);
for (&actual, &expected) in actual.iter().zip(&expected) {
assert!((actual * 32768.0 - f32::from(expected)).abs() <= 1.5,
"float/i16 scale mismatch: {settings:?}, frame {frame}");
}
output_energy += energy(&actual);
}
assert!(output_energy > 0.001, "pipeline discarded the entire probe: {settings:?}");
}
}
}
}
#[test]
fn startup_and_sustained_silence_do_not_generate_audio_in_any_stage_combination() {
for echo_cancellation in [false, true] {
for noise_suppression in [None, Some(0), Some(1), Some(2), Some(3)] {
for automatic_gain_control in [false, true] {
let settings = CaptureSettings { echo_cancellation, noise_suppression, automatic_gain_control };
let mut processor = CaptureProcessor::new(settings).unwrap();
// Cross the AGC VAD's 1.5 s reset period as well as startup.
for frame in 0..200 {
processor.process_render(&[0.0; FRAME_SAMPLES], 0).unwrap();
let mut silence = [0.0; FRAME_SAMPLES];
processor.process_capture(&mut silence).unwrap();
assert_eq!(silence, [0.0; FRAME_SAMPLES], "generated audio: {settings:?}, frame {frame}");
}
}
}
}
}
#[test]
fn agc_does_not_wind_up_in_silence_and_quiet_onset_does_not_clip() {
let settings = CaptureSettings { automatic_gain_control: true, ..BYPASS };
for silent_frames in [0, 1200] {
let mut processor = CaptureProcessor::new(settings).unwrap();
for _ in 0..silent_frames {
let mut silence = [0.0; FRAME_SAMPLES];
processor.process_capture(&mut silence).unwrap();
assert_eq!(silence, [0.0; FRAME_SAMPLES]);
}
let mut input_energy = 0.0;
let mut output_energy = 0.0;
let mut peak = 0.0_f32;
for frame in 0..30 {
let mut samples = harmonic(frame, 0.002);
input_energy += energy(&samples);
processor.process_capture(&mut samples).unwrap();
assert_normalized(&samples);
peak = samples.iter().fold(peak, |peak, sample| peak.max(sample.abs()));
output_energy += energy(&samples);
}
let gain_db = 10.0 * (output_energy / input_energy).log10();
// Default initial gain is 15 dB, at most 6 dB/s adaptation. Silence
// must not turn a -50 dBFS onset into a near-full-scale burst.
assert!((6.0..18.0).contains(&gain_db), "{silent_frames} silent frames: {gain_db:.2} dB");
assert!(peak < 0.05, "quiet onset became loud after {silent_frames} silent frames: {peak}");
}
}
#[test]
fn full_scale_impulses_and_polarity_steps_remain_bounded_and_decay_to_silence() {
for settings in [
CaptureSettings { automatic_gain_control: true, ..BYPASS },
CaptureSettings { noise_suppression: Some(1), ..BYPASS },
CaptureSettings::default(),
] {
let mut processor = CaptureProcessor::new(settings).unwrap();
let mut tail_energy = 0.0;
for frame in 0..400 {
let mut samples = match frame {
0 | 100 => std::array::from_fn(|index| if index == 0 { if frame == 0 { 1.0 } else { -1.0 } } else { 0.0 }),
1..=9 => [1.0; FRAME_SAMPLES],
10..=19 => [-1.0; FRAME_SAMPLES],
20..=29 => std::array::from_fn(|index| if index % 2 == 0 { 1.0 } else { -1.0 }),
_ => [0.0; FRAME_SAMPLES],
};
processor.process_render(&[0.0; FRAME_SAMPLES], 0).unwrap();
processor.process_capture(&mut samples).unwrap();
assert_normalized(&samples);
// A full-scale onset can legitimately engage Sonora's hard limiter;
// do not mistake finite bounded output for proof of no hard clipping.
if frame >= 300 {
tail_energy += energy(&samples);
}
}
assert!(tail_energy < 1e-6, "transient persisted in silence: {settings:?}, energy {tail_energy}");
}
}
#[test]
fn integrated_noise_suppression_attenuates_dc_without_rail_clipping() {
for level in 0..=3 {
let settings = CaptureSettings { noise_suppression: Some(level), ..BYPASS };
let mut processor = CaptureProcessor::new(settings).unwrap();
let mut tail_energy = 0.0;
let mut input_energy = 0.0;
for frame in 0..200 {
let mut samples = [0.1; FRAME_SAMPLES];
if frame >= 150 {
input_energy += energy(&samples);
}
processor.process_capture(&mut samples).unwrap();
assert_normalized(&samples);
assert!(samples.iter().all(|sample| sample.abs() < 1.0), "DC clipped: level {level}, frame {frame}");
if frame >= 150 {
tail_energy += energy(&samples);
}
}
// The split-band HPF has finite DC rejection, not exact DC zeros (see
// its biquad numerators). Use the upstream HPF's 47.3 dB DC rejection
// criterion rather than an absolute sum that scales with probe length.
let attenuation_db = 10.0 * (input_energy / tail_energy).log10();
assert!(attenuation_db >= 47.3,
"insufficient integrated HPF/NS DC rejection at level {level}: {attenuation_db:.2} dB");
}
}
+4 -1
View File
@@ -76,7 +76,7 @@ cpal = { workspace = true, features = ["pipewire", "pulseaudio"] }
secret-service = { version = "=5.1.0", default-features = false, features = ["rt-async-io-crypto-rust"] }
libwebrtc = { workspace = true, optional = true, features = ["glib-main-loop"] }
zbus = { version = "=5.19.0", features = ["blocking-api"] }
ksni = { version = "=0.3.7", features = ["blocking"] }
ksni = { version = "=0.3.7", default-features = false, features = ["blocking", "async-io"] }
directories = "=6.0.0"
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
@@ -93,6 +93,9 @@ slint = { workspace = true, features = ["backend-winit", "renderer-skia"] }
[target.'cfg(target_os = "android")'.dependencies]
slint = { workspace = true, features = ["backend-android-activity-06"] }
jni = "=0.21.1"
# rustls-platform-verifier uses JNI 0.22; keep the app/WebRTC JNI 0.21 ABI unchanged.
jni-verifier = { package = "jni", version = "=0.22.4", default-features = false }
rustls-platform-verifier = "=0.7.1"
i-slint-backend-android-activity = { version = "=1.18.1", default-features = false, features = ["aa-06", "native-activity"] }
[build-dependencies]
+2359 -2305
View File
File diff suppressed because it is too large. Load diff
+2373 -2319
View File
File diff suppressed because it is too large. Load diff
+61 -13
View File
@@ -118,6 +118,10 @@ pub struct ConnectionsSnapshot {
pub viewed_id: Option<String>,
pub input_id: Option<String>,
pub capture: Option<CapturePermit>,
/// Current invalidation identity; changes even when owner/session are unchanged.
pub capture_revision: u64,
/// Only successfully acknowledged configuration, never the in-flight request.
pub capture_configuration: Option<InputConfiguration>,
}
impl ConnectionsSnapshot {
pub fn get(&self, id: &str) -> Option<&ConnectionSnapshot> {
@@ -133,7 +137,9 @@ pub enum ConnectionEvent {
Playback { key: SessionKey, frame: PlaybackFrame },
/// The media owner must clear held PTT/whisper and its capture buffers here.
InputReset,
Failure { key: Option<SessionKey>, error: ConnectionError },
Failure { key: Option<SessionKey>, error: ConnectionError, terminal: bool },
/// Manager-owned teardown, delivered with the old key before its worker is removed.
Closed { key: SessionKey },
}
pub trait ConnectionSink: Send + Sync + 'static {
fn on_event(&self, event: ConnectionEvent);
@@ -143,11 +149,29 @@ impl<F: Fn(ConnectionEvent) + Send + Sync + 'static> ConnectionSink for F {
}
struct AudioRoute { permit: CapturePermit, core: Arc<CoreHandle> }
/// A frame can expire without revoking its stream. Do not turn a media drop
/// into a manager-wide privacy invalidation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CaptureIngress { Accepted, FrameRejected, PermitRevoked }
impl AudioRoute {
fn push(&self, key: &SessionKey, frame: CapturedFrame) -> CaptureIngress {
let current = || self.core.connection_generation() == self.permit.key.generation
&& self.core.audio_epoch() == self.permit.capture_epoch;
if self.permit.key != *key || frame.capture_epoch != self.permit.capture_epoch
|| frame.connection_generation != key.generation || !current() {
return CaptureIngress::PermitRevoked;
}
if self.core.push_audio(frame) { CaptureIngress::Accepted }
else if current() { CaptureIngress::FrameRejected }
else { CaptureIngress::PermitRevoked }
}
}
#[derive(Default)]
struct CaptureState { revision: u64, route: Option<AudioRoute> }
struct CaptureState { revision: u64, route: Option<AudioRoute>, acknowledged: Option<InputConfiguration> }
impl CaptureState {
fn revoke(&mut self) -> u64 {
self.revision = self.revision.checked_add(1).expect("capture revision exhausted");
self.acknowledged = None;
if let Some(route) = self.route.take() {
route.core.invalidate_audio();
route.core.end_audio();
@@ -211,13 +235,20 @@ impl ConnectionManager {
pub async fn set_input(&self, key: Option<&SessionKey>, config: InputConfiguration) -> Result<Option<CapturePermit>, ConnectionError> {
self.call(|reply| Operation::SetInput(key.cloned(), config, reply)).await
}
/// Invoke from the DSP/service worker, not a device callback. No per-frame allocation.
pub fn push_audio(&self, key: &SessionKey, frame: CapturedFrame) -> bool {
/// Read the live authorization boundary, not the asynchronously published UI view.
pub fn current_capture_permit(&self) -> Option<CapturePermit> {
let capture = self.capture.lock().expect("capture route poisoned");
capture.route.as_ref().is_some_and(|route| {
route.permit.key == *key && frame.capture_epoch == route.permit.capture_epoch
&& frame.connection_generation == key.generation && route.core.push_audio(frame)
})
capture.route.as_ref().filter(|route| route.core.connection_generation() == route.permit.key.generation
&& route.core.audio_epoch() == route.permit.capture_epoch).map(|route| route.permit.clone())
}
#[cfg(test)]
pub(crate) async fn fixture_control(&self, key: &SessionKey, value: Value) -> Result<(), ConnectionError> {
self.call(|reply| Operation::FixtureControl(key.clone(), value, reply)).await
}
/// Invoke from the DSP/service worker, not a device callback. No per-frame allocation.
pub fn push_audio(&self, key: &SessionKey, frame: CapturedFrame) -> CaptureIngress {
let capture = self.capture.lock().expect("capture route poisoned");
capture.route.as_ref().map_or(CaptureIngress::PermitRevoked, |route| route.push(key, frame))
}
/// Synchronous privacy boundary for device loss, held-key release and capture changes.
/// The caller must obtain a new acknowledged permit before forwarding more PCM.
@@ -274,6 +305,8 @@ enum Operation {
Request(SessionKey, Command, Option<u64>, Reply<Value>),
Close(SessionKey, Reply<()>),
Restart(SessionKey, Reply<SessionKey>),
#[cfg(test)]
FixtureControl(SessionKey, Value, Reply<()>),
}
struct Worker {
core: Arc<CoreHandle>,
@@ -395,11 +428,12 @@ impl Actor {
}).collect(),
viewed_id: self.viewed.clone(), input_id: self.input.clone(),
capture: capture.route.as_ref().map(|route| route.permit.clone()),
capture_revision: capture.revision, capture_configuration: capture.acknowledged,
};
self.snapshots.send_replace(Arc::new(snapshot));
}
fn failure(&self, key: Option<SessionKey>, error: ConnectionError) {
self.sink.on_event(ConnectionEvent::Failure { key, error });
self.sink.on_event(ConnectionEvent::Failure { key, error, terminal: false });
}
fn revoke(&mut self) -> u64 {
let revision = self.capture.lock().expect("capture route poisoned").revoke();
@@ -540,6 +574,11 @@ impl Actor {
}
fn operation(&mut self, operation: Operation) {
match operation {
#[cfg(test)]
Operation::FixtureControl(key, value, reply) => {
let result = self.checked(&key).map(|index| self.control(index, value));
self.publish(); let _ = reply.send(result);
}
Operation::Create(reply) => { let result = self.create(); self.publish(); let _ = reply.send(result); }
Operation::Key(id, reply) => { let _ = reply.send(self.index(&id).map(|index| self.entries[index].key())); }
Operation::Workflow(settings, reply) => { self.workflow = settings; let _ = reply.send(Ok(())); }
@@ -572,11 +611,11 @@ impl Actor {
self.choose_input(key.as_ref().map(|key| key.connection_id.clone()));
if let (Some(index), Some(key)) = (index, key) {
if self.entries[index].worker.as_ref().expect("checked live worker").requests.len() >= COMMAND_CAPACITY {
let _ = reply.send(Err(ConnectionError::Busy)); self.publish(); return;
self.publish(); let _ = reply.send(Err(ConnectionError::Busy)); return;
}
self.entries[index].config = Some(config);
self.configure_input(index, key, Some(reply));
} else { let _ = reply.send(Ok(None)); }
} else { self.publish(); let _ = reply.send(Ok(None)); return; }
self.publish();
}
Operation::Request(key, command, expected_channel, reply) => {
@@ -643,6 +682,7 @@ impl Actor {
}
}
fn stop(&mut self, entry: &mut Entry, purpose: StopPurpose) {
if entry.worker.is_some() { self.sink.on_event(ConnectionEvent::Closed { key: entry.key() }); }
entry.reset_session();
entry.snapshot.state = ConnectionState::Disconnected;
entry.snapshot.status = CoreStatus::Stopping;
@@ -713,6 +753,7 @@ impl Actor {
if let Some(worker) = &entry.worker {
*worker.playback_key.lock().expect("playback key poisoned") = entry.snapshot.is_connected().then(|| entry.key());
}
self.publish();
self.sink.on_event(ConnectionEvent::Control { key: self.entries[index].key(), value });
}
fn complete(&mut self, index: usize, completion: Completion) {
@@ -739,6 +780,7 @@ impl Actor {
let mut capture = self.capture.lock().expect("capture route poisoned");
if capture.revision == revision && self.input.as_ref() == Some(&completion.key.connection_id) {
if completion.result.is_err() && changes_config { entry.config = None; }
if completion.result.is_ok() && changes_config { capture.acknowledged = entry.config; }
if completion.result.is_ok() && entry.snapshot.is_connected()
&& entry.config.is_some_and(|config| !config.input_muted && !config.output_muted) {
let core = entry.worker.as_ref().expect("valid live worker").core.clone();
@@ -748,6 +790,9 @@ impl Actor {
}
}
}
// The application runs on another executor: waking its caller
// before publishing lets it observe the pre-ACK capture snapshot.
self.publish();
let _ = reply.send(if valid { completion.result } else { Err(ConnectionError::TargetChanged) });
}
CompletionKind::Input { revision, config, reply } => {
@@ -760,12 +805,14 @@ impl Actor {
if capture.revision != revision || self.input.as_ref() != Some(&completion.key.connection_id) {
return Err(ConnectionError::TargetChanged);
}
capture.acknowledged = Some(config);
let core = entry.worker.as_ref().expect("valid live worker").core.clone();
if !entry.snapshot.is_connected() || config.input_muted || config.output_muted { return Ok(None); }
let permit = CapturePermit { key: entry.key(), capture_epoch: core.audio_epoch() };
capture.route = Some(AudioRoute { permit: permit.clone(), core });
Ok(Some(permit))
});
self.publish();
if let Some(reply) = reply { let _ = reply.send(result); }
else if let Err(error) = result {
if !matches!(error, ConnectionError::TargetChanged) { self.failure(Some(completion.key), error); }
@@ -773,6 +820,7 @@ impl Actor {
}
CompletionKind::ReleaseWhisper => {
if valid { if let Err(error) = completion.result { self.failure(Some(completion.key), error); } }
self.publish();
}
}
}
@@ -785,11 +833,11 @@ impl Actor {
if self.entries[index].incarnation != incarnation || self.entries[index].worker.is_none() { return; }
match message {
Internal::Control { value, .. } => self.control(index, value),
Internal::Complete { completion, .. } => self.complete(index, completion),
Internal::Complete { completion, .. } => { self.complete(index, completion); return; }
Internal::Ended { .. } => {
let key = self.entries[index].key();
if self.input.as_ref() == Some(&key.connection_id) { self.revoke(); self.restore_input(); }
self.failure(Some(key), ConnectionError::Worker("core event stream ended".into()));
self.sink.on_event(ConnectionEvent::Failure { key: Some(key), error: ConnectionError::Worker("core event stream ended".into()), terminal: true });
let mut entry = self.entries.remove(index);
self.stop(&mut entry, StopPurpose::Failed);
self.entries.insert(index, entry);
+76
View File
@@ -152,3 +152,79 @@ async fn directory_slot_is_reserved_until_the_old_core_is_joined() {
assert!(actor.entries[actor.index(&replacement.connection_id).unwrap()].snapshot.server.is_none());
stop(actor).await;
}
#[tokio::test(flavor = "current_thread")]
async fn closing_sessions_releases_all_audio_scopes_before_slot_reuse() {
let profile = Profile::new();
let (publish, _) = watch::channel(Arc::new(ConnectionsSnapshot::default()));
let registry = Arc::new(Mutex::new(crate::media::audio::mixer::PlaybackMixer::new()));
let observed = registry.clone();
let sink = Arc::new(move |event| match event {
ConnectionEvent::Closed { key } => { observed.lock().unwrap().remove_connection(&key); },
_ => {},
});
let mut actor = Actor::new(profile.0.clone(), sink, Arc::new(Mutex::new(CaptureState::default())), publish);
actor.create().unwrap();
for _ in 0..MAX_CONNECTIONS + 2 {
let key = actor.create().unwrap();
registry.lock().unwrap().activate_connection(key.clone(), 1).unwrap();
let (reply, closed) = oneshot::channel();
actor.operation(Operation::Close(key.clone(), reply));
assert!(!registry.lock().unwrap().remove_connection(&key), "closed session must already have released its audio scope");
let stopped = tokio::time::timeout(Duration::from_secs(10), actor.stopping.join_next()).await.unwrap().unwrap().unwrap();
actor.stopped(stopped, false).unwrap();
closed.await.unwrap().unwrap();
}
stop(actor).await;
}
struct CaptureAckProbe {
snapshot: watch::Receiver<Arc<ConnectionsSnapshot>>,
observed: Mutex<Option<bool>>,
}
impl std::task::Wake for CaptureAckProbe {
fn wake(self: Arc<Self>) { self.wake_by_ref(); }
fn wake_by_ref(self: &Arc<Self>) {
*self.observed.lock().unwrap() = Some(self.snapshot.borrow().capture.is_some());
}
}
#[tokio::test(flavor = "current_thread")]
async fn acknowledged_capture_is_published_before_the_waiting_consumer_wakes() {
use std::{future::Future, pin::Pin, task::{Context, Poll, Waker}};
let profile = Profile::new();
let (mut actor, snapshots, _) = actor(&profile);
let key = actor.create().unwrap();
// Reducer fixture only: no server. Both SetTransmit/SetAudio acknowledgments
// below come from the real embedded core's supported disconnected commands.
actor.control(0, snapshot(1, &[1]));
let (reply, mut response) = oneshot::channel();
actor.operation(Operation::SetInput(Some(key.clone()), InputConfiguration::default(), reply));
let probe = Arc::new(CaptureAckProbe { snapshot: snapshots.clone(), observed: Mutex::new(None) });
let waker = Waker::from(probe.clone());
assert!(matches!(Pin::new(&mut response).poll(&mut Context::from_waker(&waker)), Poll::Pending));
tokio::time::timeout(Duration::from_secs(10), async {
loop {
let event = actor.events.recv().await.unwrap();
let complete = matches!(&event, Internal::Complete { completion: Completion { kind: CompletionKind::Input { reply: Some(_), .. }, .. }, .. });
actor.internal(event);
if complete { break; }
}
}).await.unwrap();
let permit = response.await.unwrap().unwrap().unwrap();
assert_eq!(*probe.observed.lock().unwrap(), Some(true), "ACK must not wake a reader with a pre-permit snapshot");
assert_eq!(snapshots.borrow().capture.as_ref(), Some(&permit));
assert_eq!(snapshots.borrow().capture_configuration,Some(InputConfiguration::default()));
let acknowledged_revision=snapshots.borrow().capture_revision;
let (reply, mut response) = oneshot::channel();
let released = Arc::new(CaptureAckProbe { snapshot: snapshots.clone(), observed: Mutex::new(None) });
let waker = Waker::from(released.clone());
assert!(matches!(Pin::new(&mut response).poll(&mut Context::from_waker(&waker)), Poll::Pending));
actor.operation(Operation::SetInput(None, InputConfiguration::default(), reply));
assert!(response.await.unwrap().unwrap().is_none());
assert_eq!(*released.observed.lock().unwrap(), Some(false), "release ACK must not expose an obsolete permit");
assert!(snapshots.borrow().capture_configuration.is_none());
assert!(snapshots.borrow().capture_revision>acknowledged_revision);
stop(actor).await;
}
+24 -5
View File
@@ -21,13 +21,17 @@ impl ConnectionSink for AudioSessionBinding {
match event{
ConnectionEvent::InputReset=>{audio.revoke_local_capture();},
ConnectionEvent::Playback{key,frame}=>{
audio.record_binding_received();
let routes=self.routes.lock().expect("playback routes poisoned");
if let Some(route)=routes.get(&key.connection_id).filter(|r|r.key==key&&r.enabled){
self.report(audio.push_voice(key,route.epoch,frame.pcm,frame.emitted_at));
}
}else{audio.record_binding_route_drop();}
},
ConnectionEvent::Control{key,value}=>{
let mut routes=self.routes.lock().expect("playback routes poisoned");
// Delayed control from a replaced core must not remove or
// overwrite the newer connection's playback/privacy route.
if routes.get(&key.connection_id).is_some_and(|route|(key.session,key.generation)<(route.key.session,route.key.generation)){return;}
if value["event"]=="state"&&value["state"]!="connected"{
if let Some(old)=routes.remove(&key.connection_id){self.report(audio.send(AudioCommand::RemoveConnection{key:old.key}));}
self.report(audio.send(AudioCommand::SetTransmitting(routes.values().any(|route|route.transmitting))));
@@ -56,13 +60,28 @@ impl ConnectionSink for AudioSessionBinding {
self.report(audio.send(AudioCommand::SetTransmitting(routes.values().any(|route|route.transmitting))));
}
},
ConnectionEvent::Failure{key:Some(key),error}=>{
ConnectionEvent::Closed{key}=>{
let mut routes=self.routes.lock().expect("playback routes poisoned");
if let Some(old)=routes.remove(&key.connection_id){self.report(audio.send(AudioCommand::RemoveConnection{key:old.key}));}
self.report(audio.send(AudioCommand::SetTransmitting(routes.values().any(|route|route.transmitting))));
if routes.get(&key.connection_id).is_some_and(|route|route.key==key){
routes.remove(&key.connection_id);
self.report(audio.send(AudioCommand::RemoveConnection{key}));
self.report(audio.send(AudioCommand::SetTransmitting(routes.values().any(|route|route.transmitting))));
}
},
ConnectionEvent::Failure{key,error,terminal}=>{
// A rejected command does not end the session or invalidate its playback epoch.
// Only the manager's terminal notification may remove the matching route.
if terminal{
if let Some(key)=key{
let mut routes=self.routes.lock().expect("playback routes poisoned");
if routes.get(&key.connection_id).is_some_and(|route|route.key==key){
if let Some(old)=routes.remove(&key.connection_id){self.report(audio.send(AudioCommand::RemoveConnection{key:old.key}));}
self.report(audio.send(AudioCommand::SetTransmitting(routes.values().any(|route|route.transmitting))));
}
}
}
(self.errors)(ServiceError::new("connection_failed",error.to_string()));
},
ConnectionEvent::Failure{key:None,error}=>(self.errors)(ServiceError::new("connection_failed",error.to_string())),
}
}
}
+19 -4
View File
@@ -2,6 +2,7 @@
use std::path::PathBuf;
use crate::{AppConfig,services::{Result,ServiceError,profile::ProfileServices,profile_import as import},ui::{shell::*,i18n::Catalog}};
use super::model::{AppState,BootstrapState};
#[derive(Clone)]
pub struct Bootstrap {pub root:PathBuf,pub candidates:Vec<PathBuf>,pub selected:Option<PathBuf>,pub interrupted:bool}
impl Bootstrap {
pub async fn inspect(config:&AppConfig)->Result<(Self,Option<ProfileServices>)>{
@@ -17,6 +18,8 @@ impl Bootstrap {
state.snapshot.root=Some(self.root.clone());state.snapshot.loading=false;
if let Some(profile)=profile{if !profile.identities.list()?.identities.is_empty(){state.snapshot.bootstrap=BootstrapState::Ready;state.snapshot.profile_form=None;return Ok(())}}
let catalog=Catalog::default();let mut form=crate::ui::shell::forms::form("onboarding",Operation::CreateProfile,Target::application(),&catalog).ok_or_else(||error("profile_form","Username form is unavailable"))?;
#[cfg(target_os="android")]
form.actions.retain(|action|!matches!(action.operation,Operation::ChooseLegacyProfile|Operation::ImportIdentity));
state.snapshot.bootstrap=if self.interrupted{BootstrapState::RecoverImport}else if !self.candidates.is_empty(){BootstrapState::ChooseProfile}else{BootstrapState::Username};
if self.interrupted{form.description="An incomplete import was found. Retry the import, or explicitly discard its staging directory before creating a new identity. The source profile is unchanged.".into();form.actions.push(Action{form:None,..Action::new("discard-import",Operation::ConfirmOverwrite,Target::application(),&catalog)});}
for(index,path)in self.candidates.iter().enumerate(){let target=Target{entity:Entity::LegacyProfile(index.to_string()),name:path.to_string_lossy().into_owned(),..Target::application()};let mut action=Action::new(format!("legacy-{index}"),Operation::ImportLegacyProfile,target,&catalog);action.form=None;form.actions.push(action);}
@@ -39,10 +42,7 @@ impl Bootstrap {
let root=self.root.clone();tokio::task::spawn_blocking(move||import::discard_interrupted_import(&root,true)).await.map_err(|_|error("profile_worker","Import recovery worker stopped"))??;self.interrupted=false;Ok(None)
},
Operation::CreateProfile=>{
let nickname=text(values,"nickname")?;let theme=text(values,"theme")?;if nickname.trim().chars().count()<3||nickname.trim().chars().count()>30{return Err(error("invalid_nickname","Choose a nickname with 3–30 characters"))}
if !matches!(theme.as_str(),"dark"|"light"|"system"){return Err(error("bad_request","Choose dark, light or system appearance"))}
if self.interrupted{return Err(error("import_interrupted","Discard or retry the incomplete import before creating a profile"))}
let root=self.root.clone();tokio::task::spawn_blocking(move||{import::initialize_native_root(&root)?;let mut profile=ProfileServices::open(&root)?;profile.identities.onboard(nickname.trim())?;profile.prefs.set(serde_json::json!({"theme":theme}))?;Ok(Some(profile))}).await.map_err(|_|error("profile_worker","Profile creation worker stopped"))?
self.create(values.clone(),None).await.map(Some)
},
Operation::ImportLegacyProfile=>{
config_policy(config).check()?;
@@ -58,6 +58,21 @@ impl Bootstrap {
},_=>Err(error("profile_required","Finish profile creation or import before using server services"))
}
}
/// A retry may find a committed identity after a later preference/service failure. Reuse it;
/// never replace the vault or roll back an already committed identity.
pub async fn create(&self,values:Values,existing:Option<ProfileServices>)->Result<ProfileServices>{
let root=self.root.clone();let interrupted=self.interrupted;
tokio::task::spawn_blocking(move||{
let nickname=text(&values,"nickname")?;let theme=text(&values,"theme")?;
if !(3..=30).contains(&nickname.trim().chars().count()){return Err(error("invalid_nickname","Choose a nickname with 3–30 characters"))}
if !matches!(theme.as_str(),"dark"|"light"|"system"){return Err(error("bad_request","Choose dark, light or system appearance"))}
if interrupted{return Err(error("import_interrupted","Discard or retry the incomplete import before creating a profile"))}
let mut profile=match existing{Some(profile)=>profile,None=>{import::initialize_native_root(&root)?;ProfileServices::open(&root)?}};
if profile.identities.list()?.identities.is_empty(){profile.identities.onboard(nickname.trim())?;}
profile.prefs.set(serde_json::json!({"theme":theme}))?;
Ok(profile)
}).await.map_err(|error|ServiceError::new("profile_worker",format!("Profile creation worker stopped: {error}")))?
}
pub fn confirmation_form(&self,target:Target,operation:Operation)->Result<Form>{
let mut form=crate::ui::shell::forms::form("bootstrap-confirmation",operation,target.clone(),&Catalog::default()).ok_or_else(||error("confirmation_required","Confirmation form is unavailable"))?;
form.confirmation=Some(target.name.clone());form.destructive=operation==Operation::ConfirmOverwrite;
+121
View File
@@ -0,0 +1,121 @@
//! Consumer-level bootstrap regressions: real profile storage, actor snapshots and captured effects.
use super::*;
use crate::services::{identities::IdentityService,profile_import};
fn values(nickname:&str,theme:&str)->Values{
Values::from([("nickname".into(),FieldValue::Text(nickname.into())),("theme".into(),FieldValue::Choice(theme.into()))])
}
fn submit(runtime:&AppRuntime,id:&str,nickname:&str,theme:&str){
runtime.dispatch_shell(ShellAction::Submit{editor_id:id.into(),target:Target::application(),operation:Operation::CreateProfile,values:values(nickname,theme),confirmation:String::new()}).unwrap();
}
async fn snapshot_when(runtime:&AppRuntime,predicate:impl Fn(&model::Snapshot)->bool)->Arc<model::Snapshot>{
let mut snapshots=runtime.subscribe();
tokio::time::timeout(Duration::from_secs(20),async{
loop{let snapshot=snapshots.borrow_and_update().clone();if predicate(&snapshot){return snapshot}snapshots.changed().await.expect("runtime snapshot publisher stopped");}
}).await.expect("bootstrap did not publish the expected consumer state")
}
async fn acknowledgement(runtime:&AppRuntime,id:&str)->Result<()>{
tokio::time::timeout(Duration::from_secs(20),async{
let mut effects=runtime.effects.lock().unwrap();
loop{match effects.recv().await.expect("runtime effects ended without a form acknowledgement"){
UiEffect::FormComplete{id:captured,target,result}=>{assert_eq!(captured,id);assert_eq!(target,Target::application());return result},_=>{}
}}
}).await.expect("bootstrap did not acknowledge the captured submission")
}
async fn shutdown(runtime:&AppRuntime)->Result<()>{
tokio::time::timeout(Duration::from_secs(20),runtime.shutdown()).await.expect("bootstrap did not release its workers")
}
#[tokio::test(flavor="current_thread")]
async fn bootstrap_contract_initialized_empty_validation_and_saved_profile_failure_are_distinct(){
let directory=tempfile::tempdir().unwrap();let root=directory.path().join("native");profile_import::initialize_native_root(&root).unwrap();
let mut config=AppConfig::isolated(root.clone());config.build_version="invalid-version";
let runtime=AppRuntime::start(config.clone()).unwrap();
snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Username).await;
submit(&runtime,"invalid-nickname","ab","dark");
assert_eq!(acknowledgement(&runtime,"invalid-nickname").await.unwrap_err().code,"invalid_nickname");
let rejected=snapshot_when(&runtime,|snapshot|!snapshot.error.is_empty()).await;
assert_eq!(rejected.bootstrap,BootstrapState::Username);assert!(rejected.profile_form.is_some());
assert!(IdentityService::open(&root).unwrap().list().unwrap().identities.is_empty());
submit(&runtime,"invalid-theme","Valid User","unsupported");
assert_eq!(acknowledgement(&runtime,"invalid-theme").await.unwrap_err().code,"bad_request");
submit(&runtime,"saved-profile","Native User","light");
let error=acknowledgement(&runtime,"saved-profile").await.unwrap_err();
assert_eq!(error.code,"services_initialization_failed");assert!(error.message.contains("profile is saved"));
let terminal=snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Failed).await;
assert_ne!(terminal.revision,rejected.revision,"revision-gated consumers must receive terminal failure");
assert!(terminal.ready);assert!(!terminal.loading);assert!(terminal.profile_form.is_none());assert!(terminal.dialog.is_none());
assert_eq!(terminal.error,error.message);assert_eq!(terminal.last_error.as_ref().unwrap().code,error.code);
assert_eq!(shutdown(&runtime).await.unwrap_err().code,error.code);drop(runtime);
let saved=ProfileServices::open(&root).unwrap();let identities=saved.identities.list().unwrap();
assert_eq!(identities.identities.len(),1);assert_eq!(saved.prefs.get()["theme"],"light");let uid=identities.default_id;drop(saved);
// Cold-start failure must expose the same truthful outcome, without repeating onboarding.
let runtime=AppRuntime::start(config).unwrap();
let terminal=snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Failed).await;
assert!(terminal.revision>0);assert!(terminal.profile_form.is_none());assert!(terminal.error.contains("profile is saved"));
assert_eq!(shutdown(&runtime).await.unwrap_err().code,"services_initialization_failed");drop(runtime);
assert_eq!(ProfileServices::open(&root).unwrap().identities.list().unwrap().default_id,uid);
}
#[tokio::test(flavor="current_thread")]
async fn bootstrap_contract_late_construction_failure_joins_workers_before_restart(){
let directory=tempfile::tempdir().unwrap();let root=directory.path().join("native");profile_import::initialize_native_root(&root).unwrap();
// Theme scanning fails only after the real connection and audio owners have started.
std::fs::write(root.join("extensions"),b"not a directory").unwrap();
let config=AppConfig::isolated(root.clone());let runtime=AppRuntime::start(config.clone()).unwrap();
snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Username).await;
submit(&runtime,"late-failure","Native User","system");
assert_eq!(acknowledgement(&runtime,"late-failure").await.unwrap_err().code,"services_initialization_failed");
snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Failed).await;
assert_eq!(shutdown(&runtime).await.unwrap_err().code,"services_initialization_failed");drop(runtime);
let profile=ProfileServices::open(&root).unwrap();let uid=profile.identities.list().unwrap().default_id;assert_eq!(profile.prefs.get()["theme"],"system");drop(profile);
std::fs::remove_file(root.join("extensions")).unwrap();
let runtime=AppRuntime::start(config).unwrap();
let resumed=snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Ready&&snapshot.settings.loaded).await;
assert!(resumed.profile_form.is_none());assert!(!resumed.loading);
shutdown(&runtime).await.unwrap();drop(runtime);
assert_eq!(ProfileServices::open(&root).unwrap().identities.list().unwrap().default_id,uid);
}
#[tokio::test(flavor="current_thread")]
async fn bootstrap_contract_fresh_create_acknowledges_only_after_services_start(){
let directory=tempfile::tempdir().unwrap();let root=directory.path().join("native");
let runtime=AppRuntime::start(AppConfig::isolated(root.clone())).unwrap();
snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Username).await;
submit(&runtime,"fresh-create","Native User","light");acknowledgement(&runtime,"fresh-create").await.unwrap();
let ready=snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Ready&&snapshot.settings.loaded).await;
assert!(ready.profile_form.is_none());assert_eq!(ready.settings.prefs["theme"],"light");
shutdown(&runtime).await.unwrap();drop(runtime);
let profile=ProfileServices::open(&root).unwrap();assert_eq!(profile.identities.list().unwrap().identities.len(),1);assert_eq!(profile.prefs.get()["theme"],"light");
}
#[tokio::test(flavor="current_thread")]
async fn bootstrap_contract_preference_failure_retry_preserves_committed_identity(){
let directory=tempfile::tempdir().unwrap();let root=directory.path().join("native");profile_import::initialize_native_root(&root).unwrap();
let mut existing=ProfileServices::open(&root).unwrap();existing.prefs.set(serde_json::json!({"theme":"dark"})).unwrap();
std::fs::remove_file(root.join("prefs.json")).unwrap();std::fs::create_dir(root.join("prefs.json")).unwrap();
let bootstrap=bootstrap::Bootstrap{root:root.clone(),candidates:vec![],selected:None,interrupted:false};
assert!(bootstrap.create(values("Original User","light"),Some(existing)).await.is_err());
let committed=IdentityService::open(&root).unwrap().list().unwrap();assert_eq!(committed.identities.len(),1);
std::fs::remove_dir(root.join("prefs.json")).unwrap();
let recovered=bootstrap.create(values("Different User","system"),None).await.unwrap();
assert_eq!(recovered.identities.list().unwrap(),committed,"recovery must not regenerate or rename the committed identity");
assert_eq!(recovered.prefs.get()["theme"],"system");drop(recovered);
let reopened=ProfileServices::open(&root).unwrap();assert_eq!(reopened.identities.list().unwrap(),committed);assert_eq!(reopened.prefs.get()["theme"],"system");
}
#[tokio::test(flavor="current_thread")]
async fn bootstrap_contract_quit_is_consumed_while_storage_commit_is_blocked(){
let directory=tempfile::tempdir().unwrap();let root=directory.path().join("native");profile_import::initialize_native_root(&root).unwrap();
let runtime=AppRuntime::start(AppConfig::isolated(root.clone())).unwrap();
snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Username).await;
let lock=std::fs::OpenOptions::new().write(true).create(true).truncate(false).open(root.join("core/profile.lock")).unwrap();
teamspeach_core::file_lock::try_lock(&lock,false).unwrap();
let mut cancelled=runtime.cancel.subscribe();
submit(&runtime,"blocked-create","Native User","light");runtime.platform_event(crate::platform::lifecycle::PlatformEvent::Quit);
let responsive=tokio::time::timeout(Duration::from_secs(5),async{while !*cancelled.borrow_and_update(){cancelled.changed().await.unwrap();}}).await;
drop(lock); // allow the already-started atomic storage operation to finish, not roll back
shutdown(&runtime).await.unwrap();drop(runtime);
assert!(responsive.is_ok(),"the current-thread actor must consume lifecycle events during profile work");
let profile=ProfileServices::open(&root).unwrap();assert_eq!(profile.identities.list().unwrap().identities.len(),1);assert_eq!(profile.prefs.get()["theme"],"light");
}
+25 -1
View File
@@ -26,6 +26,30 @@ pub struct TransmissionState {
pub deactivated:HashSet<String>,
pub whisper:crate::services::whisper::WhisperHold,
pub configured:Option<crate::app::connections::InputConfiguration>,
/// Exact manager identity attempted by reconciliation; unchanged failures are not retried.
pub observed_capture:Option<(u64,Option<crate::app::connections::CapturePermit>,Option<crate::app::connections::InputConfiguration>)>,
/// Permit successfully bound by the audio consumer, never inferred from the owner key.
pub bound_permit:Option<crate::app::connections::CapturePermit>,
pub output_intent_revision:u64,
pub output_desired:bool,
/// Logical PTT/push-to-mute closure is not a physical-device failure.
pub gate_inhibited:bool,
/// Explicit authorization to resume capture; hardware events are observations only.
pub capture_desired:bool,
/// Fences queued local momentary-control starts after UI focus/visibility loss.
pub ui_controls_suspended:bool,
}
#[derive(Clone)]
pub struct MicrophoneTestResume {
pub owner:Option<SessionKey>,
pub input:bool,
pub output:bool,
pub output_revision:u64,
}
impl MicrophoneTestResume {
pub(super) fn activities(&self,state:&TransmissionState)->(bool,bool){
(self.input&&state.capture_desired,if state.output_intent_revision==self.output_revision{self.output}else{state.output_desired})
}
}
pub struct RuntimeServices {
pub root:PathBuf,
@@ -60,7 +84,7 @@ pub struct RuntimeServices {
pub audio_output_active:AtomicBool,
pub applied_audio_selections:Mutex<Option<(String,String)>>,
pub audio_configuration:tokio::sync::Mutex<()>,
pub microphone_test_resume:Mutex<Option<(Option<SessionKey>,bool,bool)>>,
pub microphone_test_resume:Mutex<Option<MicrophoneTestResume>>,
pub transmission:Mutex<TransmissionState>,
pub notification_clock:Instant,
pub system_scheme:Mutex<Option<crate::services::themes::ColorScheme>>,
+703 -214
View File
@@ -1,214 +1,703 @@
//! Runtime helpers bridge captured service intents to native capabilities.
use std::{path::PathBuf,sync::{Arc,Mutex,MutexGuard,atomic::{AtomicBool,Ordering}},time::{Duration,Instant}};
use serde_json::Value;
use super::{context::{RuntimeServices,changed,closed,connection_error},events::{UiEffect,WorkflowResult}};
use crate::{app::connections::{InputConfiguration,SessionKey},media::audio::{engine::AudioCommand,devices::StartPermission},platform::resources::{DirectoryGrant,DocumentGrant},services::{Result,ServiceError,keybinds::{Action,ActionEvent,Phase,Scope},themes::ColorScheme},ui::{shell::{Detail,InfoRow,Target,Entity},settings::{Capability,OsView}}};
fn lock<T>(value:&Mutex<T>)->Result<MutexGuard<'_,T>>{value.lock().map_err(|_|ServiceError::new("service_unavailable","Runtime service state is unavailable"))}
fn worker()->ServiceError{ServiceError::new("os_worker","The native operation worker stopped")}
fn unavailable(message:&str)->ServiceError{ServiceError::new("desktop_only",message)}
struct CommitCancellation(Arc<AtomicBool>);
impl Drop for CommitCancellation{fn drop(&mut self){self.0.store(true,Ordering::Release);}}
impl RuntimeServices {
pub fn color_scheme(&self)->ColorScheme {self.system_scheme.lock().ok().and_then(|scheme|*scheme).unwrap_or(ColorScheme::Dark)}
pub async fn sync_notifications(&self)->Result<()>{super::settings_actions::sync_notifications(self).await}
pub fn notification_now_ms(&self)->u64 {self.notification_clock.elapsed().as_millis().min(u128::from(u64::MAX)) as u64}
pub fn current_ui_generation(&self)->Result<u64>{let runtime=self.runtime.upgrade().ok_or_else(closed)?;let generation=runtime.ui_generation();if !runtime.is_ui_current(generation){return Err(ServiceError::new("ui_destroyed","The initiating UI is no longer attached"))}Ok(generation)}
pub fn require_ui_generation(&self,generation:u64)->Result<()>{if self.runtime.upgrade().is_some_and(|runtime|runtime.is_ui_current(generation)){Ok(())}else{Err(ServiceError::new("ui_destroyed","The initiating UI was replaced"))}}
/// Retain the grant and runtime until the adapter reaches its atomic publication point.
/// Cancellation is checked by the adapter throughout copying and immediately before commit.
pub async fn commit_document(self:&Arc<Self>,document:Arc<dyn DocumentGrant>,source:PathBuf,key:Option<SessionKey>)->Result<()> {
self.policy.check()?;
if let Some(key)=&key{self.require_key(key,false)?;}
if *self.cancelled.borrow(){return Err(closed())}
let owner=self.clone();
let cancellation=CommitCancellation(Arc::new(AtomicBool::new(false)));
let abandoned=cancellation.0.clone();
tokio::task::spawn_blocking(move||{
let cancelled=||abandoned.load(Ordering::Acquire)||*owner.cancelled.borrow()||key.as_ref().is_some_and(|key|owner.require_key(key,false).is_err());
if cancelled(){return Err(key.as_ref().filter(|key|owner.require_key(key,false).is_err()).map_or_else(closed,|_|changed()))}
let result=document.commit_from(&source,&cancelled);
if result.as_ref().is_err_and(|error|error.code=="cancelled")&&key.as_ref().is_some_and(|key|owner.require_key(key,false).is_err()){return Err(changed())}
result
}).await.map_err(|_|worker())?
}
pub async fn restore_directory(&self,path:PathBuf)->Result<Arc<dyn DirectoryGrant>>{
self.policy.check()?;
#[cfg(not(any(target_os="android",target_os="ios")))]
{tokio::task::spawn_blocking(move||crate::platform::desktop::documents::restore_directory(&path)).await.map_err(|_|worker())?}
#[cfg(any(target_os="android",target_os="ios"))]
{let _=path;Err(ServiceError::new("directory_grant_required","Choose the directory again using the system document picker"))}
}
pub async fn open_local_directory(&self,path:PathBuf)->Result<()> {
let grant=self.restore_directory(path).await?;
self.open_directory(grant).await
}
pub async fn open_directory(&self,grant:Arc<dyn DirectoryGrant>)->Result<()> {
self.policy.check()?;
#[cfg(not(any(target_os="android",target_os="ios")))]
{crate::platform::desktop::open_directory(grant,self.policy).await}
#[cfg(any(target_os="android",target_os="ios"))]
{let _=grant;Err(unavailable("This operating system opens individual documents through its share sheet; it has no desktop directory reveal operation"))}
}
pub async fn open_document(&self,document:Arc<dyn DocumentGrant>,reveal:bool)->Result<()> {
self.policy.check()?;
#[cfg(not(any(target_os="android",target_os="ios")))]
{if reveal{crate::platform::desktop::reveal_document(document,self.policy).await}else{crate::platform::desktop::open_document(document,self.policy).await}}
#[cfg(target_os="android")]
{let _=reveal;crate::platform::android::share_document(document,"application/octet-stream",self.policy).await}
#[cfg(target_os="ios")]
{let _=reveal;if crate::platform::apple::share_document(document,self.policy).await?{Ok(())}else{Err(ServiceError::new("cancelled","Document sharing was cancelled"))}}
}
pub async fn open_logs(&self)->Result<()> {
self.policy.check()?;
// Only the opened profile supplies this path; do not retain a profile MutexGuard across await.
let path={self.profile()?.root.join("logs")};
self.open_local_directory(path).await
}
pub async fn request_microphone_permission(&self)->Result<()> {
self.policy.check()?;
let generation=self.current_ui_generation()?;
#[cfg(target_os="android")]
let granted=crate::platform::android::request_permission(crate::platform::lifecycle::Permission::Microphone,self.policy).await?;
#[cfg(target_os="ios")]
let granted=crate::platform::apple::request_permission(crate::platform::lifecycle::Permission::Microphone,self.policy).await?;
// Desktop CPAL opens the explicitly selected input and reports privacy/TCC/device failures.
#[cfg(not(any(target_os="android",target_os="ios")))]
let granted=true;
self.require_ui_generation(generation)?;
self.microphone_granted.store(granted,Ordering::Release);
if !granted {self.audio.set_transmission_enabled(false);self.audio.revoke_capture();return Err(ServiceError::new("microphone_permission_denied","The operating system denied microphone access"))}
Ok(())
}
pub fn capture_configuration(&self,key:&SessionKey,prefs:&Value)->Result<InputConfiguration>{
self.require_key(key,true)?;
let snapshot=self.connected.connections.snapshot();let session=snapshot.get(&key.connection_id).filter(|entry|entry.key==*key).ok_or_else(changed)?;
let vad=super::settings_actions::capture_gate(prefs);
// PTT and push-to-mute are independent forwarding gates, never the user's mute flags.
Ok(InputConfiguration{vad,input_muted:session.audio.input_muted,output_muted:session.audio.output_muted})
}
pub fn refresh_transmission_gate(&self,key:&SessionKey,prefs:&Value)->Result<()> {
let snapshot=self.connected.connections.snapshot();
let session=snapshot.get(&key.connection_id).filter(|entry|entry.key==*key&&entry.is_connected()).ok_or_else(changed)?;
let state=lock(&self.transmission)?;
let whisper=state.whisper.held();
let ptt= !state.ptt_holders.is_empty()||state.release_at.is_some_and(|at|at>Instant::now());
let channel_allowed=session.server.as_deref().is_some_and(|server|{
let own=server["own_channel_id"].as_u64();
let channel=server["channels"].as_array().and_then(|channels|channels.iter().find(|channel|channel["id"].as_u64()==own));
channel.is_none_or(|channel|channel["codec"].is_null()||matches!(channel["codec"].as_str(),Some("opus_voice"|"opus_music")))
});
let allowed={let profile=self.profile()?;profile.prefs.capture_allowed(profile.migration.is_some())};
let enabled= !*self.cancelled.borrow()&&allowed&&self.microphone_granted.load(Ordering::Acquire)&&self.audio_input_active.load(Ordering::Acquire)
&& snapshot.input_id.as_deref()==Some(key.connection_id.as_str())&&snapshot.capture.as_ref().is_some_and(|permit|permit.key==*key)
&&state.deactivated.is_empty()&&!session.audio.input_muted&&!session.audio.output_muted&&channel_allowed
&&lock(&self.microphone_test_resume)?.is_none()
&& if whisper{state.whisper.epoch(key).is_some()}else{prefs["pttEnabled"]!=true||ptt};
#[cfg(target_os="android")]
let enabled=enabled&&crate::platform::android::voice_audio_allowed(key,true);
self.audio.set_transmission_enabled(enabled);Ok(())
}
/// A closed forwarding gate invalidates the old permit; obtain fresh real acknowledgements before opening.
pub async fn refresh_capture(self:&Arc<Self>)->Result<()> {
let _configuration=self.audio_configuration.lock().await;
if lock(&self.microphone_test_resume)?.is_some(){return Ok(())}
let snapshot=self.connected.connections.snapshot();
let key=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).filter(|entry|entry.is_connected()).map(|entry|entry.key.clone());
let Some(key)=key else{self.audio.set_transmission_enabled(false);self.audio.revoke_capture();return Ok(())};
#[cfg(target_os="android")]
if !crate::platform::android::voice_audio_allowed(&key,true){self.audio_input_active.store(false,Ordering::Release);self.audio.request(AudioCommand::StopInput).await?;return Ok(())}
let (prefs,allowed)={let profile=self.profile()?;(profile.prefs.get(),profile.prefs.capture_allowed(profile.migration.is_some()))};
let (revision,whisper)={let mut state=lock(&self.transmission)?;if state.key.as_ref()!=Some(&key){state.key=Some(key.clone());state.ptt_holders.clear();state.deactivated.clear();state.release_at=None;state.whisper.release(None);state.revision=state.revision.wrapping_add(1);}(state.revision,state.whisper.held())};
if whisper{return self.refresh_transmission_gate(&key,&prefs)}
let config=self.capture_configuration(&key,&prefs)?;
self.audio.revoke_capture();
let permit=self.connected.connections.set_input(Some(&key),config).await.map_err(connection_error)?;
self.require_key(&key,true)?;
if self.connected.connections.snapshot().input_id.as_deref()!=Some(key.connection_id.as_str())||lock(&self.transmission)?.revision!=revision{return Err(changed())}
let Some(permit)=permit else{return Err(changed())};
let settings=super::settings_actions::capture_settings(&prefs);
self.audio.request(AudioCommand::BindPermit{permit,settings}).await?;
self.require_key(&key,true)?;
if lock(&self.transmission)?.revision!=revision{self.audio.revoke_capture();return Err(changed())}
lock(&self.transmission)?.configured=Some(config);
if allowed&&self.microphone_granted.load(Ordering::Acquire)&&self.audio_input_active.load(Ordering::Acquire){self.audio.request(AudioCommand::StartInput(StartPermission::Granted)).await?;}
self.refresh_transmission_gate(&key,&prefs)
}
pub async fn apply_key_events(self:&Arc<Self>,events:Vec<ActionEvent>)->Result<()> {
let prefs=self.profile()?.prefs.get();let mut forwarded=Vec::new();let mut refresh=false;
for event in events {
if event.phase==Phase::End&&matches!(event.binding.action,Action::ReplyWhisper|Action::QuickWhisper|Action::WhisperList){
self.audio.set_transmission_enabled(false);
self.audio.revoke_capture();
let stop={let mut state=lock(&self.transmission)?;let stop=state.whisper.release(Some(&event.binding.id));state.revision=state.revision.wrapping_add(1);stop};
if let Some(stop)=stop{
let runtime=self.runtime.upgrade().ok_or_else(closed)?;
if runtime.commands.try_send(super::RuntimeCommand::WhisperStop(stop)).is_err(){runtime.cancel.send_replace(true);return Err(closed())}
}
}
if !matches!(event.binding.action,Action::PushToTalk|Action::PushToMute){forwarded.push(event);continue}
let holder=format!("keybind:{}:{}",event.binding.id,if event.scope==Scope::Global{"global"}else{"local"});
let snapshot=self.connected.connections.snapshot();
let owner=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).filter(|session|session.is_connected()).map(|session|session.key.clone());
{let mut state=lock(&self.transmission)?;
if state.key!=owner{state.key=owner;state.ptt_holders.clear();state.deactivated.clear();state.release_at=None;state.whisper.release(None);}
if event.binding.action==Action::PushToMute {if event.phase==Phase::Start{state.deactivated.insert(holder);}else{state.deactivated.remove(&holder);}}
else if event.phase==Phase::Start{state.ptt_holders.insert(holder);state.release_at=None;}
else{state.ptt_holders.remove(&holder);if state.ptt_holders.is_empty(){let delay=if prefs["pttReleaseDelay"]["active"]==true{prefs["pttReleaseDelay"]["ms"].as_u64().unwrap_or(300)}else{0};state.release_at=(delay>0).then(||Instant::now()+Duration::from_millis(delay));}}
state.revision=state.revision.wrapping_add(1);
}
let snapshot=self.connected.connections.snapshot();if let Some(key)=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).map(|session|&session.key){self.refresh_transmission_gate(key,&prefs)?;}
refresh=true;
}
#[cfg(not(any(target_os="android",target_os="ios")))]
if self.policy.allow_os_actions{let capturing=self.keys.lock().await.capture.is_some();if let Some(handle)=self.runtime.upgrade().and_then(|runtime|runtime.desktop_handle()){handle.capture_physical_keys(capturing)?;}}
if refresh {self.refresh_capture().await?;}
if !forwarded.is_empty(){self.effect(UiEffect::KeyEvents(forwarded)).await?;}
self.changed().await
}
pub async fn tick_transmission(self:&Arc<Self>)->Result<()> {
let expired={let mut state=lock(&self.transmission)?;if state.release_at.is_some_and(|at|Instant::now()>=at){state.release_at=None;state.revision=state.revision.wrapping_add(1);true}else{false}};
if expired{let prefs=self.profile()?.prefs.get();let snapshot=self.connected.connections.snapshot();if let Some(session)=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)){self.refresh_transmission_gate(&session.key,&prefs)?;}self.changed().await?;}
Ok(())
}
pub async fn refresh_os_settings(&self)->Result<()> {
if let Err(error)=self.policy.check(){
let unavailable=Capability{reason:error.message,..Default::default()};
lock(&self.settings_status)?.os=OsView{autostart:unavailable.clone(),taskbar:unavailable.clone(),flash:unavailable.clone(),lock_mute:unavailable.clone(),global_hotkeys:unavailable};
return self.changed().await;
}
let prefs=self.profile()?.prefs.get();
#[cfg(not(any(target_os="android",target_os="ios")))]
let os={
let autostart=if self.installed{match crate::platform::desktop::autostart_enabled(self.policy).await{Ok(enabled)=>Capability{supported:true,enabled,reason:String::new()},Err(error)=>Capability{reason:error.message,..Default::default()}}}else{Capability{reason:"Autostart requires an installed native application".into(),..Default::default()}};
let mut lock_mute=Capability{supported:true,enabled:prefs["osMuteWhenLocked"]==true,reason:String::new()};
if let Some(handle)=self.runtime.upgrade().and_then(|runtime|runtime.desktop_handle()){if let Err(error)=handle.action(crate::platform::desktop::WindowAction::LockObserver(lock_mute.enabled)).await{lock_mute.supported=false;lock_mute.reason=error.message;}}
else{lock_mute.supported=false;lock_mute.reason="The desktop window is not attached".into();}
let keys=self.keys.lock().await;let global_hotkeys=match &keys.global{Some(global)=>{let status=global.status();Capability{supported:status.is_some_and(|value|value["global"]==true||value["backend"]=="macos_carbon_registerhotkey"||value["results"].as_array().is_some_and(|results|results.iter().any(|row|row["ok"]==true))),enabled:status.is_some_and(|value|value["event"]!="error"),reason:status.map(Value::to_string).unwrap_or_else(||"The global shortcut backend has not acknowledged registration".into())}},None=>Capability{reason:"Global shortcuts are not registered".into(),..Default::default()}};
OsView{autostart,taskbar:Capability{supported:true,enabled:prefs["osHideInTaskbar"]==true,reason:String::new()},flash:Capability{supported:true,enabled:prefs["osFlashOnMessage"]==true||prefs["osFlashOnPoke"]==true,reason:String::new()},lock_mute,global_hotkeys}
};
#[cfg(any(target_os="android",target_os="ios"))]
let os={let _=prefs;let desktop=Capability{reason:"Desktop-only operating system integration".into(),..Default::default()};OsView{autostart:desktop.clone(),taskbar:desktop.clone(),flash:desktop.clone(),lock_mute:desktop.clone(),global_hotkeys:desktop}};
lock(&self.settings_status)?.os=os;self.changed().await
}
pub async fn set_autostart(&self,enabled:bool)->Result<()> {
self.policy.check()?;
#[cfg(not(any(target_os="android",target_os="ios")))]
{let acknowledged=crate::platform::desktop::autostart(enabled,self.installed,self.policy).await?;lock(&self.settings_status)?.os.autostart=Capability{supported:true,enabled:acknowledged,reason:String::new()};self.changed().await}
#[cfg(any(target_os="android",target_os="ios"))]
{let _=enabled;Err(unavailable("Mobile applications cannot register desktop login autostart"))}
}
pub async fn apply_update_effect(&self,effect:crate::services::updates::UpdateEffect)->Result<()> {self.policy.check()?;self.effect(UiEffect::Update(effect)).await}
pub async fn relaunch(&self)->Result<()> {self.policy.check()?;self.effect(UiEffect::Relaunch).await}
pub async fn show_whisper_overlay(&self,key:SessionKey)->Result<WorkflowResult>{
self.require_key(&key,true)?;
let (targets,pending)={let status=lock(&self.settings_status)?;(status.whisper_targets.clone(),status.pending_whisper.clone())};
let prefs=self.profile()?.prefs.get();let catalog=crate::ui::i18n::Catalog::new(crate::ui::i18n::Language::from_code(prefs["language"].as_str().unwrap_or("en")));
let mut rows=targets.into_iter().map(|(label,value)|InfoRow{label,value}).collect::<Vec<_>>();
if let Some((pending_key,entry))=pending.filter(|(pending_key,_)|pending_key==&key){self.require_key(&pending_key,true)?;rows.push(InfoRow{label:catalog.text("clientMenu.whisper"),value:entry.name});}
let detail=Detail{title:catalog.text("settings.whisper.live_preview"),rows,..Detail::default()};
Ok(WorkflowResult::effect(UiEffect::Detail{target:Target{session:Some(key),entity:Entity::Connection,name:String::new(),own_channel_id:None},detail}))
}
}
//! Runtime helpers bridge captured service intents to native capabilities.
use std::{path::PathBuf,sync::{Arc,Mutex,MutexGuard,atomic::{AtomicBool,Ordering}},time::{Duration,Instant}};
use serde_json::Value;
use super::{context::{RuntimeServices,changed,closed,connection_error},events::{UiEffect,WorkflowResult}};
use crate::{app::connections::{InputConfiguration,SessionKey},media::audio::{engine::AudioCommand,devices::StartPermission},platform::resources::{DirectoryGrant,DocumentGrant},services::{Result,ServiceError,keybinds::{Action,ActionEvent,Phase,Scope},themes::ColorScheme},ui::{shell::{Detail,InfoRow,Target,Entity},settings::{Capability,OsView}}};
fn lock<T>(value:&Mutex<T>)->Result<MutexGuard<'_,T>>{value.lock().map_err(|_|ServiceError::new("service_unavailable","Runtime service state is unavailable"))}
fn worker()->ServiceError{ServiceError::new("os_worker","The native operation worker stopped")}
fn unavailable(message:&str)->ServiceError{ServiceError::new("desktop_only",message)}
struct CommitCancellation(Arc<AtomicBool>);
impl Drop for CommitCancellation{fn drop(&mut self){self.0.store(true,Ordering::Release);}}
impl super::context::TransmissionState {
/// Observe receive-only owners too: authorization is separate from owner identity.
pub(super) fn observe_owner(&mut self,key:Option<SessionKey>)->bool {
if self.key==key{return false}
self.key=key;self.ptt_holders.clear();self.deactivated.clear();self.release_at=None;self.whisper.release(None);self.configured=None;self.observed_capture=None;self.bound_permit=None;self.gate_inhibited=false;self.capture_desired=false;
self.revision=self.revision.wrapping_add(1);true
}
/// A refresh may retain intent, but cannot survive a newer owner or privacy boundary.
pub(super) fn capture_intent(&self,key:&SessionKey,revision:u64)->Result<bool>{
if self.key.as_ref()!=Some(key)||self.revision!=revision{return Err(changed())}
Ok(self.capture_desired)
}
pub(super) fn acknowledge_capture_configuration(&mut self,key:&SessionKey,revision:u64,config:InputConfiguration,has_permit:bool)->Result<()>{
self.capture_intent(key,revision)?;
self.configured=Some(config);
// Output mute removes the permit temporarily, not explicit microphone intent.
// Input mute (including permission/policy loss) remains a privacy boundary.
if !has_permit&&config.input_muted{self.capture_desired=false;}
Ok(())
}
}
/// Activation diagnostics contain only a fixed stage, error code and session counters.
pub(super) fn capture_stage<T>(result:Result<T>,stage:&'static str,key:&SessionKey)->Result<T>{
result.map_err(|error|ServiceError::new(&error.code,format!("Microphone activation failed at {stage} ({}; generation={}; session={})",error.code,key.generation,key.session)))
}
impl RuntimeServices {
pub fn color_scheme(&self)->ColorScheme {self.system_scheme.lock().ok().and_then(|scheme|*scheme).unwrap_or(ColorScheme::Dark)}
pub async fn sync_notifications(&self)->Result<()>{super::settings_actions::sync_notifications(self).await}
pub fn notification_now_ms(&self)->u64 {self.notification_clock.elapsed().as_millis().min(u128::from(u64::MAX)) as u64}
pub fn current_ui_generation(&self)->Result<u64>{let runtime=self.runtime.upgrade().ok_or_else(closed)?;let generation=runtime.ui_generation();if !runtime.is_ui_current(generation){return Err(ServiceError::new("ui_destroyed","The initiating UI is no longer attached"))}Ok(generation)}
pub fn require_ui_generation(&self,generation:u64)->Result<()>{if self.runtime.upgrade().is_some_and(|runtime|runtime.is_ui_current(generation)){Ok(())}else{Err(ServiceError::new("ui_destroyed","The initiating UI was replaced"))}}
/// Retain the grant and runtime until the adapter reaches its atomic publication point.
/// Cancellation is checked by the adapter throughout copying and immediately before commit.
pub async fn commit_document(self:&Arc<Self>,document:Arc<dyn DocumentGrant>,source:PathBuf,key:Option<SessionKey>)->Result<()> {
self.policy.check()?;
if let Some(key)=&key{self.require_key(key,false)?;}
if *self.cancelled.borrow(){return Err(closed())}
let owner=self.clone();
let cancellation=CommitCancellation(Arc::new(AtomicBool::new(false)));
let abandoned=cancellation.0.clone();
tokio::task::spawn_blocking(move||{
let cancelled=||abandoned.load(Ordering::Acquire)||*owner.cancelled.borrow()||key.as_ref().is_some_and(|key|owner.require_key(key,false).is_err());
if cancelled(){return Err(key.as_ref().filter(|key|owner.require_key(key,false).is_err()).map_or_else(closed,|_|changed()))}
let result=document.commit_from(&source,&cancelled);
if result.as_ref().is_err_and(|error|error.code=="cancelled")&&key.as_ref().is_some_and(|key|owner.require_key(key,false).is_err()){return Err(changed())}
result
}).await.map_err(|_|worker())?
}
pub async fn restore_directory(&self,path:PathBuf)->Result<Arc<dyn DirectoryGrant>>{
self.policy.check()?;
#[cfg(not(any(target_os="android",target_os="ios")))]
{tokio::task::spawn_blocking(move||crate::platform::desktop::documents::restore_directory(&path)).await.map_err(|_|worker())?}
#[cfg(any(target_os="android",target_os="ios"))]
{let _=path;Err(ServiceError::new("directory_grant_required","Choose the directory again using the system document picker"))}
}
pub async fn open_local_directory(&self,path:PathBuf)->Result<()> {
let grant=self.restore_directory(path).await?;
self.open_directory(grant).await
}
pub async fn open_directory(&self,grant:Arc<dyn DirectoryGrant>)->Result<()> {
self.policy.check()?;
#[cfg(not(any(target_os="android",target_os="ios")))]
{crate::platform::desktop::open_directory(grant,self.policy).await}
#[cfg(any(target_os="android",target_os="ios"))]
{let _=grant;Err(unavailable("This operating system opens individual documents through its share sheet; it has no desktop directory reveal operation"))}
}
pub async fn open_document(&self,document:Arc<dyn DocumentGrant>,reveal:bool)->Result<()> {
self.policy.check()?;
#[cfg(not(any(target_os="android",target_os="ios")))]
{if reveal{crate::platform::desktop::reveal_document(document,self.policy).await}else{crate::platform::desktop::open_document(document,self.policy).await}}
#[cfg(target_os="android")]
{let _=reveal;crate::platform::android::share_document(document,"application/octet-stream",self.policy).await}
#[cfg(target_os="ios")]
{let _=reveal;if crate::platform::apple::share_document(document,self.policy).await?{Ok(())}else{Err(ServiceError::new("cancelled","Document sharing was cancelled"))}}
}
pub async fn open_logs(&self)->Result<()> {
self.policy.check()?;
// Only the opened profile supplies this path; do not retain a profile MutexGuard across await.
let path={self.profile()?.root.join("logs")};
self.open_local_directory(path).await
}
pub async fn request_microphone_permission(&self)->Result<()> {
self.policy.check()?;
let revision=lock(&self.transmission)?.revision;
let generation=self.current_ui_generation()?;
#[cfg(target_os="android")]
let granted=crate::platform::android::request_permission(crate::platform::lifecycle::Permission::Microphone,self.policy).await?;
#[cfg(target_os="ios")]
let granted=crate::platform::apple::request_permission(crate::platform::lifecycle::Permission::Microphone,self.policy).await?;
// Desktop CPAL opens the explicitly selected input and reports privacy/TCC/device failures.
#[cfg(not(any(target_os="android",target_os="ios")))]
let granted=true;
// A denial always wins, including a result for a detached UI. A delayed
// grant may not overwrite a newer stop/privacy revision.
if !granted{return self.acknowledge_microphone_permission(revision,false)}
self.require_ui_generation(generation)?;
self.acknowledge_microphone_permission(revision,true)
}
fn acknowledge_microphone_permission(&self,revision:u64,granted:bool)->Result<()> {
if !granted{self.microphone_granted.store(false,Ordering::Release);super::controller::release_immediate(self);return Err(ServiceError::new("microphone_permission_denied","The operating system denied microphone access"))}
let state=lock(&self.transmission)?;
if state.revision!=revision{return Err(ServiceError::new("audio_activation_revoked","Microphone authorization ended during the permission request"))}
self.microphone_granted.store(true,Ordering::Release);drop(state);Ok(())
}
pub(super) async fn finish_private_microphone_test(&self,_configuration:&tokio::sync::MutexGuard<'_,()>)->Result<()> {
if lock(&self.microphone_test_resume)?.is_some(){
self.audio.revoke_capture();self.audio.set_transmission_enabled(false);
self.audio.request(AudioCommand::FinishMicrophoneTest).await?;
lock(&self.microphone_test_resume)?.take();
self.audio_input_active.store(self.audio.input_active(),Ordering::Release);
}Ok(())
}
/// Explicit undeafen repairs the output owner; a routing event alone cannot
/// reopen hardware after StopOutput removed its owners.
pub(super) async fn restore_voice_output(&self,key:&SessionKey)->Result<()> {
self.require_key(key,true)?;
if !self.output_granted.load(Ordering::Acquire){return Ok(())}
#[cfg(target_os="android")]
if !crate::platform::android::voice_audio_allowed(key,false){return Err(ServiceError::new("audio_focus_unavailable","Android has not authorized call playback"))}
{let mut state=lock(&self.transmission)?;state.output_desired=true;state.output_intent_revision=state.output_intent_revision.wrapping_add(1);}
self.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await?;
self.require_key(key,true)?;
#[cfg(target_os="android")]
if !crate::platform::android::voice_audio_allowed(key,false){self.audio.request(AudioCommand::StopOutput).await?;return Err(ServiceError::new("audio_focus_unavailable","Android revoked call playback during startup"))}
self.audio_output_active.store(self.audio.output_active(),Ordering::Release);
Ok(())
}
pub fn capture_configuration(&self,key:&SessionKey,prefs:&Value)->Result<InputConfiguration>{
self.require_key(key,true)?;
let snapshot=self.connected.connections.snapshot();let session=snapshot.get(&key.connection_id).filter(|entry|entry.key==*key).ok_or_else(changed)?;
let vad=super::settings_actions::capture_gate(prefs);
// PTT and push-to-mute are independent forwarding gates, never the user's mute flags.
Ok(InputConfiguration{vad,input_muted:session.audio.input_muted,output_muted:session.audio.output_muted})
}
/// Deliberate deafen/PTT inhibition retains consent; unexpected stopped capture
/// projects unavailable so the microphone button offers activation, not another mute.
pub fn microphone_enabled(&self,key:&SessionKey)->bool {
let snapshot=self.connected.connections.snapshot();
if snapshot.input_id.as_deref()!=Some(key.connection_id.as_str())||!self.microphone_granted.load(Ordering::Acquire){return false}
let Some(session)=snapshot.get(&key.connection_id).filter(|session|session.key==*key&&session.is_connected()&&!session.audio.input_muted) else{return false};
let Ok(state)=self.transmission.lock() else{return false};
if state.key.as_ref()!=Some(key)||!state.capture_desired{return false}
session.audio.output_muted||state.gate_inhibited
||(self.audio.input_active()&&state.bound_permit.as_ref().is_some_and(|permit|permit.key==*key&&self.connected.connections.current_capture_permit().as_ref()==Some(permit)))
}
pub fn refresh_transmission_gate(&self,key:&SessionKey,prefs:&Value)->Result<()> {
let snapshot=self.connected.connections.snapshot();
let session=snapshot.get(&key.connection_id).filter(|entry|entry.key==*key&&entry.is_connected()).ok_or_else(changed)?;
let mut state=lock(&self.transmission)?;
let whisper=state.whisper.held();
let ptt= !state.ptt_holders.is_empty()||state.release_at.is_some_and(|at|at>Instant::now());
state.gate_inhibited= !state.deactivated.is_empty()||(!whisper&&prefs["pttEnabled"]==true&&!ptt);
let channel_allowed=session.server.as_deref().is_some_and(|server|{
let own=server["own_channel_id"].as_u64();
let channel=server["channels"].as_array().and_then(|channels|channels.iter().find(|channel|channel["id"].as_u64()==own));
channel.is_none_or(|channel|channel["codec"].is_null()||matches!(channel["codec"].as_str(),Some("opus_voice"|"opus_music")))
});
let allowed={let profile=self.profile()?;profile.prefs.capture_allowed(profile.migration.is_some())};
let enabled= !*self.cancelled.borrow()&&allowed&&self.microphone_granted.load(Ordering::Acquire)&&self.audio_input_active.load(Ordering::Acquire)
&& snapshot.input_id.as_deref()==Some(key.connection_id.as_str())&&state.bound_permit.as_ref().is_some_and(|permit|permit.key==*key&&self.connected.connections.current_capture_permit().as_ref()==Some(permit))
&&state.capture_desired&&!state.gate_inhibited&&!session.audio.input_muted&&!session.audio.output_muted&&channel_allowed
&&lock(&self.microphone_test_resume)?.is_none()
&&(!whisper||state.whisper.epoch(key).is_some());
#[cfg(target_os="android")]
let enabled=enabled&&crate::platform::android::voice_audio_allowed(key,true);
self.audio.set_transmission_enabled(enabled);Ok(())
}
/// A closed forwarding gate invalidates the old permit; obtain fresh real acknowledgements before opening.
pub async fn refresh_capture(self:&Arc<Self>)->Result<()> {
let configuration=self.audio_configuration.lock().await;
self.refresh_capture_locked(&configuration,false).await.map(|_|())
}
/// The ticker must compare the owner under the same lock as the eventual refresh.
/// A queued or completed explicit activation must not be revoked by an old observation.
pub async fn refresh_capture_owner_changed(self:&Arc<Self>)->Result<bool> {
let Ok(configuration)=self.audio_configuration.try_lock() else{return Ok(false)};
self.refresh_capture_locked(&configuration,true).await
}
pub(super) async fn refresh_capture_locked(self:&Arc<Self>,_configuration:&tokio::sync::MutexGuard<'_,()>,owner_changed_only:bool)->Result<bool> {
if lock(&self.microphone_test_resume)?.is_some(){return Ok(false)}
let snapshot=self.connected.connections.snapshot();
let key=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).filter(|entry|entry.is_connected()).map(|entry|entry.key.clone());
let live_permit=self.connected.connections.current_capture_permit();
let identity=(snapshot.capture_revision,live_permit.clone(),snapshot.capture_configuration);
let (revision,whisper,resume)={
let mut state=lock(&self.transmission)?;
if owner_changed_only&&state.key==key&&state.observed_capture.as_ref()==Some(&identity){return Ok(false)}
state.observe_owner(key.clone());state.observed_capture=Some(identity);
(state.revision,state.whisper.held(),state.capture_desired)
};
let Some(key)=key else{self.audio.set_transmission_enabled(false);self.audio.request(AudioCommand::StopInput).await?;self.audio_input_active.store(self.audio.input_active(),Ordering::Release);return Ok(true)};
#[cfg(target_os="android")]
if !crate::platform::android::voice_audio_allowed(&key,true){super::controller::release_immediate(self);self.audio.request(AudioCommand::StopInput).await?;self.audio_input_active.store(self.audio.input_active(),Ordering::Release);return Ok(true)}
let (prefs,allowed)={let profile=self.profile()?;(profile.prefs.get(),profile.prefs.capture_allowed(profile.migration.is_some()))};
if whisper{return self.refresh_transmission_gate(&key,&prefs).map(|_|true)}
let mut config=self.capture_configuration(&key,&prefs)?;
config.input_muted|=!allowed||!self.microphone_granted.load(Ordering::Acquire)||!resume;
// Binding a replacement must not invalidate its real manager ACK. A late Join
// snapshot may schedule that ACK after the Join command has already returned.
self.audio.revoke_local_capture();lock(&self.transmission)?.bound_permit=None;
// Observations may consume an existing ACK, never manufacture a retry after
// a physical failure or supersede an in-flight manager configuration.
if owner_changed_only&&(snapshot.capture_configuration!=Some(config)||snapshot.capture.as_ref()!=live_permit.as_ref()){
self.audio_input_active.store(self.audio.input_active(),Ordering::Release);return Ok(true)
}
let permit=if owner_changed_only{live_permit}
else if snapshot.capture_configuration==Some(config)
&&snapshot.capture.as_ref()==self.connected.connections.current_capture_permit().as_ref(){snapshot.capture.clone()}
else{
let result=self.connected.connections.set_input(Some(&key),config).await.map_err(connection_error);
let current=self.connected.connections.snapshot();
lock(&self.transmission)?.observed_capture=Some((current.capture_revision,self.connected.connections.current_capture_permit(),current.capture_configuration));
capture_stage(result,"refresh_configuration",&key)?
};
self.require_key(&key,true)?;
if self.connected.connections.snapshot().input_id.as_deref()!=Some(key.connection_id.as_str()){return Err(changed())}
lock(&self.transmission)?.capture_intent(&key,revision)?;
let Some(permit)=permit else{
lock(&self.transmission)?.acknowledge_capture_configuration(&key,revision,config,false)?;
self.audio.set_transmission_enabled(false);capture_stage(self.audio.request(AudioCommand::StopInput).await,"stop_input",&key)?;
self.audio_input_active.store(self.audio.input_active(),Ordering::Release);return Ok(true)
};
if self.connected.connections.current_capture_permit().as_ref()!=Some(&permit){return Err(changed())}
let settings=super::settings_actions::capture_settings(&prefs);
capture_stage(self.audio.request(AudioCommand::BindPermit{permit:permit.clone(),settings}).await,"bind_permit",&key)?;
self.require_key(&key,true)?;
if self.connected.connections.current_capture_permit().as_ref()!=Some(&permit){self.audio.revoke_local_capture();return Err(changed())}
{let mut state=lock(&self.transmission)?;if let Err(error)=state.acknowledge_capture_configuration(&key,revision,config,true){self.audio.revoke_capture();return Err(error)}state.bound_permit=Some(permit.clone());}
if resume&&allowed&&self.microphone_granted.load(Ordering::Acquire){
#[cfg(target_os="android")]
{
let (input,output)=lock(&self.applied_audio_selections)?.clone().unwrap_or_else(||(
prefs["inputDeviceId"].as_str().unwrap_or_default().to_owned(),
prefs["outputDeviceId"].as_str().unwrap_or_default().to_owned()));
capture_stage(crate::platform::android::validate_voice_capture_pair(&input,&output,true),"validate_capture_route",&key)?;
}
capture_stage(self.audio.request(AudioCommand::StartInput(StartPermission::Granted)).await,"start_input",&key)?;
}
if self.connected.connections.current_capture_permit().as_ref()!=Some(&permit){self.audio.revoke_local_capture();lock(&self.transmission)?.bound_permit=None;return Err(changed())}
if let Err(error)=lock(&self.transmission)?.capture_intent(&key,revision){self.audio.revoke_capture();return Err(error)}
self.audio_input_active.store(self.audio.input_active(),Ordering::Release);
self.refresh_transmission_gate(&key,&prefs).map(|_|true)
}
pub async fn apply_key_events(self:&Arc<Self>,events:Vec<ActionEvent>)->Result<()> {
let prefs=self.profile()?.prefs.get();let mut forwarded=Vec::new();let mut refresh=false;
for event in events {
if event.phase==Phase::Start&&event.scope==Scope::Local&&matches!(event.binding.action,Action::PushToTalk|Action::PushToMute|Action::ReplyWhisper|Action::QuickWhisper|Action::WhisperList)&&lock(&self.transmission)?.ui_controls_suspended{continue}
if event.phase==Phase::End&&matches!(event.binding.action,Action::ReplyWhisper|Action::QuickWhisper|Action::WhisperList){
self.audio.set_transmission_enabled(false);
self.audio.revoke_capture();
let stop={let mut state=lock(&self.transmission)?;let stop=state.whisper.release(Some(&event.binding.id));state.revision=state.revision.wrapping_add(1);stop};
if let Some(stop)=stop{
let runtime=self.runtime.upgrade().ok_or_else(closed)?;
if runtime.commands.try_send(super::RuntimeCommand::WhisperStop(stop)).is_err(){runtime.cancel.send_replace(true);return Err(closed())}
}
}
if !matches!(event.binding.action,Action::PushToTalk|Action::PushToMute){forwarded.push(event);continue}
let holder=format!("keybind:{}:{}",event.binding.id,if event.scope==Scope::Global{"global"}else{"local"});
let snapshot=self.connected.connections.snapshot();
let owner=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).filter(|session|session.is_connected()).map(|session|session.key.clone());
{let mut state=lock(&self.transmission)?;
state.observe_owner(owner);
if event.binding.action==Action::PushToMute {if event.phase==Phase::Start{state.deactivated.insert(holder);}else{state.deactivated.remove(&holder);}}
else if event.phase==Phase::Start{state.ptt_holders.insert(holder);state.release_at=None;}
else{state.ptt_holders.remove(&holder);if state.ptt_holders.is_empty(){let delay=if prefs["pttReleaseDelay"]["active"]==true{prefs["pttReleaseDelay"]["ms"].as_u64().unwrap_or(300)}else{0};state.release_at=(delay>0).then(||Instant::now()+Duration::from_millis(delay));}}
state.revision=state.revision.wrapping_add(1);
}
let snapshot=self.connected.connections.snapshot();if let Some(key)=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).map(|session|&session.key){self.refresh_transmission_gate(key,&prefs)?;}
refresh=true;
}
#[cfg(not(any(target_os="android",target_os="ios")))]
if self.policy.allow_os_actions{let capturing=self.keys.lock().await.capture.is_some();if let Some(handle)=self.runtime.upgrade().and_then(|runtime|runtime.desktop_handle()){handle.capture_physical_keys(capturing)?;}}
if refresh {self.refresh_capture().await?;}
if !forwarded.is_empty(){self.effect(UiEffect::KeyEvents(forwarded)).await?;}
self.changed().await
}
pub async fn tick_transmission(self:&Arc<Self>)->Result<()> {
let expired={let mut state=lock(&self.transmission)?;if state.release_at.is_some_and(|at|Instant::now()>=at){state.release_at=None;state.revision=state.revision.wrapping_add(1);true}else{false}};
if expired{let prefs=self.profile()?.prefs.get();let snapshot=self.connected.connections.snapshot();if let Some(session)=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)){self.refresh_transmission_gate(&session.key,&prefs)?;}self.changed().await?;}
Ok(())
}
pub async fn refresh_os_settings(&self)->Result<()> {
if let Err(error)=self.policy.check(){
let unavailable=Capability{reason:error.message,..Default::default()};
lock(&self.settings_status)?.os=OsView{autostart:unavailable.clone(),taskbar:unavailable.clone(),flash:unavailable.clone(),lock_mute:unavailable.clone(),global_hotkeys:unavailable};
return self.changed().await;
}
let prefs=self.profile()?.prefs.get();
#[cfg(not(any(target_os="android",target_os="ios")))]
let os={
let autostart=if self.installed{match crate::platform::desktop::autostart_enabled(self.policy).await{Ok(enabled)=>Capability{supported:true,enabled,reason:String::new()},Err(error)=>Capability{reason:error.message,..Default::default()}}}else{Capability{reason:"Autostart requires an installed native application".into(),..Default::default()}};
let mut lock_mute=Capability{supported:true,enabled:prefs["osMuteWhenLocked"]==true,reason:String::new()};
if let Some(handle)=self.runtime.upgrade().and_then(|runtime|runtime.desktop_handle()){if let Err(error)=handle.action(crate::platform::desktop::WindowAction::LockObserver(lock_mute.enabled)).await{lock_mute.supported=false;lock_mute.reason=error.message;}}
else{lock_mute.supported=false;lock_mute.reason="The desktop window is not attached".into();}
let keys=self.keys.lock().await;let global_hotkeys=match &keys.global{Some(global)=>{let status=global.status();Capability{supported:status.is_some_and(|value|value["global"]==true||value["backend"]=="macos_carbon_registerhotkey"||value["results"].as_array().is_some_and(|results|results.iter().any(|row|row["ok"]==true))),enabled:status.is_some_and(|value|value["event"]!="error"),reason:status.map(Value::to_string).unwrap_or_else(||"The global shortcut backend has not acknowledged registration".into())}},None=>Capability{reason:"Global shortcuts are not registered".into(),..Default::default()}};
OsView{autostart,taskbar:Capability{supported:true,enabled:prefs["osHideInTaskbar"]==true,reason:String::new()},flash:Capability{supported:true,enabled:prefs["osFlashOnMessage"]==true||prefs["osFlashOnPoke"]==true,reason:String::new()},lock_mute,global_hotkeys}
};
#[cfg(any(target_os="android",target_os="ios"))]
let os={let _=prefs;let desktop=Capability{reason:"Desktop-only operating system integration".into(),..Default::default()};OsView{autostart:desktop.clone(),taskbar:desktop.clone(),flash:desktop.clone(),lock_mute:desktop.clone(),global_hotkeys:desktop}};
lock(&self.settings_status)?.os=os;self.changed().await
}
pub async fn set_autostart(&self,enabled:bool)->Result<()> {
self.policy.check()?;
#[cfg(not(any(target_os="android",target_os="ios")))]
{let acknowledged=crate::platform::desktop::autostart(enabled,self.installed,self.policy).await?;lock(&self.settings_status)?.os.autostart=Capability{supported:true,enabled:acknowledged,reason:String::new()};self.changed().await}
#[cfg(any(target_os="android",target_os="ios"))]
{let _=enabled;Err(unavailable("Mobile applications cannot register desktop login autostart"))}
}
pub async fn apply_update_effect(&self,effect:crate::services::updates::UpdateEffect)->Result<()> {self.policy.check()?;self.effect(UiEffect::Update(effect)).await}
pub async fn relaunch(&self)->Result<()> {self.policy.check()?;self.effect(UiEffect::Relaunch).await}
pub async fn show_whisper_overlay(&self,key:SessionKey)->Result<WorkflowResult>{
self.require_key(&key,true)?;
let (targets,pending)={let status=lock(&self.settings_status)?;(status.whisper_targets.clone(),status.pending_whisper.clone())};
let prefs=self.profile()?.prefs.get();let catalog=crate::ui::i18n::Catalog::new(crate::ui::i18n::Language::from_code(prefs["language"].as_str().unwrap_or("en")));
let mut rows=targets.into_iter().map(|(label,value)|InfoRow{label,value}).collect::<Vec<_>>();
if let Some((pending_key,entry))=pending.filter(|(pending_key,_)|pending_key==&key){self.require_key(&pending_key,true)?;rows.push(InfoRow{label:catalog.text("clientMenu.whisper"),value:entry.name});}
let detail=Detail{title:catalog.text("settings.whisper.live_preview"),rows,..Detail::default()};
Ok(WorkflowResult::effect(UiEffect::Detail{target:Target{session:Some(key),entity:Entity::Connection,name:String::new(),own_channel_id:None},detail}))
}
}
#[cfg(test)]
mod capture_transition_tests {
use super::*;
use super::super::context::TransmissionState;
use std::future::Future;
fn key(session:u64)->SessionKey{SessionKey{connection_id:"private-connection".into(),session,generation:7}}
async fn offline_runtime()->(tempfile::TempDir,super::super::Owner,tokio::sync::mpsc::Receiver<super::super::events::ServiceEvent>,tokio::sync::mpsc::Receiver<crate::app::connections::ConnectionEvent>){
let directory=tempfile::tempdir().unwrap();let root=directory.path().join("native");
crate::services::profile_import::initialize_native_root(&root).unwrap();
let profile=crate::services::profile::ProfileServices::open(&root).unwrap();
let config=crate::AppConfig::isolated(root);
let (events,received)=tokio::sync::mpsc::channel(1024);let (controls,observed)=tokio::sync::mpsc::channel(1024);
let (_cancel,cancelled)=tokio::sync::watch::channel(false);
let owner=super::super::construct(&config,profile,std::sync::Weak::new(),events,cancelled,controls).await.unwrap();
(directory,owner,received,observed)
}
async fn shutdown_offline(owner:super::super::Owner){
owner.ctx.phishing.stop();owner.ctx.badges.stop();owner.ctx.updates.stop();
owner.settings_worker.abort();let _=owner.settings_worker.await;
owner.ctx.streams.shutdown();owner.ctx.connected.shutdown().await.unwrap();owner.audio.shutdown().await.unwrap();
owner.ctx.profile().unwrap().identities.close().unwrap();
}
#[tokio::test(flavor="current_thread")]
async fn runtime_output_only_flags_preserve_consent_but_microphone_mute_revokes_it(){
let (_directory,owner,_events,_controls)=offline_runtime().await;let ctx=&owner.ctx;
let snapshot=ctx.connected.connections.snapshot();let key=snapshot.connections[0].key.clone();
{let mut state=ctx.transmission.lock().unwrap();state.observe_owner(Some(key.clone()));state.capture_desired=true;}
for output in [true,false]{
super::super::controller::set_audio_flags(ctx,&key,None,Some(output)).await.unwrap();
assert_eq!(ctx.connected.connections.snapshot().get(&key.connection_id).unwrap().audio.output_muted,output,"real core acknowledgment must be published before orchestration returns");
assert!(ctx.transmission.lock().unwrap().capture_desired);
assert!(!ctx.audio.input_active());assert!(!ctx.audio.output_active(),"disconnected flags must not open hardware");
}
super::super::controller::set_audio_flags(ctx,&key,Some(true),None).await.unwrap();
assert!(ctx.connected.connections.snapshot().get(&key.connection_id).unwrap().audio.input_muted);
assert!(!ctx.transmission.lock().unwrap().capture_desired);
super::super::controller::set_audio_flags(ctx,&key,None,Some(false)).await.unwrap();
assert!(!ctx.transmission.lock().unwrap().capture_desired);
shutdown_offline(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn runtime_explicit_private_test_exit_discards_resume_without_engine_reservation(){
let (_directory,owner,_events,_controls)=offline_runtime().await;let ctx=&owner.ctx;
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
// Runtime-only stale bookkeeping must not fabricate an engine reservation,
// emit Finished, or open any device while being discarded.
*ctx.microphone_test_resume.lock().unwrap()=Some(super::super::context::MicrophoneTestResume{owner:Some(key),input:true,output:true,output_revision:0});
super::super::controller::release_immediate(ctx);
let configuration=ctx.audio_configuration.lock().await;
ctx.finish_private_microphone_test(&configuration).await.unwrap();drop(configuration);
assert!(ctx.microphone_test_resume.lock().unwrap().is_none());
assert!(!ctx.transmission.lock().unwrap().capture_desired);
assert!(!ctx.audio.input_active());assert!(!ctx.audio.output_active());
assert!(!owner.audio_events.try_iter().any(|event|matches!(event,crate::media::audio::engine::AudioEvent::MicrophoneTest{state:crate::media::audio::engine::MicrophoneTestState::Finished,..})));
shutdown_offline(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn runtime_android_call_takeover_finishes_private_capture_without_restoring_consent(){
use crate::media::audio::engine::{AudioCommand,AudioEvent,MicrophoneTestState};
let (_directory,mut owner,_events,_controls)=offline_runtime().await;
let ctx=owner.ctx.clone();
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
let (_entered,release)=capture_start_barrier(&mut owner);release.send(()).unwrap();
let settings=teamspeach_denoise::CaptureSettings{echo_cancellation:false,noise_suppression:None,automatic_gain_control:false};
ctx.audio.request(AudioCommand::BeginMicrophoneTest{permission:StartPermission::Granted,settings}).await.unwrap();
assert!(ctx.audio.input_active());
// Old test resume flags must not become call consent, including after a
// later explicit mute. The actual engine owns a real test reservation.
*ctx.microphone_test_resume.lock().unwrap()=Some(super::super::context::MicrophoneTestResume{owner:Some(key),input:true,output:true,output_revision:0});
super::super::controller::release_immediate(&ctx);
let configuration=ctx.audio_configuration.lock().await;
ctx.prepare_android_call_locked(&configuration).await.unwrap();
assert!(ctx.microphone_test_resume.lock().unwrap().is_none());
assert!(!ctx.audio.input_active());assert!(!ctx.audio.output_active());
assert!(!ctx.audio.output_authorized());
assert!(!ctx.transmission.lock().unwrap().capture_desired);
assert!(owner.audio_events.try_iter().any(|event|matches!(event,AudioEvent::MicrophoneTest{state:MicrophoneTestState::Finished,samples:0})));
assert_eq!(ctx.audio.request(AudioCommand::ListenMicrophoneTest).await.unwrap_err().code,"microphone_test_inactive");
drop(configuration);shutdown_offline(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn runtime_permission_loss_wins_over_late_grant_and_retained_output_intent(){
let (_directory,owner,_events,_controls)=offline_runtime().await;let ctx=&owner.ctx;
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
let revision={let mut state=ctx.transmission.lock().unwrap();state.observe_owner(Some(key.clone()));state.capture_desired=true;state.revision};
ctx.acknowledge_microphone_permission(revision,true).unwrap();
assert!(ctx.microphone_granted.load(Ordering::Acquire));
assert_eq!(ctx.acknowledge_microphone_permission(revision,false).unwrap_err().code,"microphone_permission_denied");
assert_eq!(ctx.acknowledge_microphone_permission(revision,true).unwrap_err().code,"audio_activation_revoked");
assert!(!ctx.microphone_granted.load(Ordering::Acquire));assert!(!ctx.transmission.lock().unwrap().capture_desired);
super::super::controller::set_audio_flags(ctx,&key,None,Some(false)).await.unwrap();
assert!(!ctx.microphone_granted.load(Ordering::Acquire));assert!(!ctx.transmission.lock().unwrap().capture_desired);
shutdown_offline(owner).await;
}
async fn pending_once<F:Future>(future:std::pin::Pin<&mut F>){
let mut future=future;
std::future::poll_fn(|cx|{assert!(future.as_mut().poll(cx).is_pending(),"operation must be blocked at the controlled configuration barrier");std::task::Poll::Ready(())}).await
}
fn moved_snapshot(key:&SessionKey,channel:u64)->Value{
serde_json::json!({"event":"snapshot","generation":key.generation,"own_channel_id":channel,"channels":[{"id":1,"codec":"opus_voice"},{"id":2,"codec":"opus_voice"}],"clients":[]})
}
async fn reducer_capture_fixture(ctx:&Arc<RuntimeServices>)->SessionKey{
// Only connected presentation is a reducer fixture. SetTransmit/SetAudio ACKs,
// permit publication and all audio commands use the real command/event consumers.
// No test here asserts a network handshake or physical-device success.
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
ctx.profile().unwrap().prefs.set(serde_json::json!({"pttEnabled":false})).unwrap();
ctx.connected.connections.fixture_control(&key,moved_snapshot(&key,1)).await.unwrap();
let prefs=ctx.profile().unwrap().prefs.get();
let config=InputConfiguration{vad:super::super::settings_actions::capture_gate(&prefs),input_muted:false,output_muted:false};
let permit=ctx.connected.connections.set_input(Some(&key),config).await.unwrap().unwrap();
assert_eq!(ctx.connected.connections.current_capture_permit(),Some(permit));
{let mut state=ctx.transmission.lock().unwrap();state.observe_owner(Some(key.clone()));state.capture_desired=true;}
ctx.microphone_granted.store(true,Ordering::Release);key
}
fn capture_start_barrier(owner:&mut super::super::Owner)->(std::sync::mpsc::Receiver<()>,std::sync::mpsc::SyncSender<()>){
let (entered,observed)=std::sync::mpsc::sync_channel(1);let (release,released)=std::sync::mpsc::sync_channel(1);
owner.audio.set_test_capture_start(entered,released);(observed,release)
}
#[tokio::test(flavor="current_thread")]
async fn runtime_consumer_mute_fences_an_inflight_capture_start(){
let (_directory,mut owner,_events,_controls)=offline_runtime().await;
let key=reducer_capture_fixture(&owner.ctx).await;
let (entered,release)=capture_start_barrier(&mut owner);
let ctx=owner.ctx.clone();let refresh=tokio::spawn({let ctx=ctx.clone();async move{ctx.refresh_capture().await}});
tokio::task::spawn_blocking(move||entered.recv_timeout(Duration::from_secs(10))).await.unwrap().unwrap();
assert!(ctx.audio_configuration.try_lock().is_err(),"real startup consumer retains the configuration lease");
let mut mute=Box::pin(super::super::controller::set_audio_flags(&ctx,&key,Some(true),None));
pending_once(mute.as_mut()).await;
assert!(!ctx.transmission.lock().unwrap().capture_desired);
assert!(ctx.connected.connections.current_capture_permit().is_none(),"mute must fence the live manager before startup can acknowledge");
release.send(()).unwrap();assert!(refresh.await.unwrap().is_err());mute.await.unwrap();
assert!(!ctx.audio.input_active());assert!(ctx.connected.connections.current_capture_permit().is_none());
assert!(ctx.connected.connections.snapshot().get(&key.connection_id).unwrap().audio.input_muted);
shutdown_offline(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn runtime_consumer_late_same_owner_move_binds_fresh_ack_once(){
let (_directory,mut owner,_events,_controls)=offline_runtime().await;
let key=reducer_capture_fixture(&owner.ctx).await;
let (_entered,release)=capture_start_barrier(&mut owner);release.send(()).unwrap();
owner.ctx.refresh_capture().await.unwrap();
let old=owner.ctx.connected.connections.current_capture_permit().unwrap();assert!(owner.ctx.audio.input_active());
let configuration=owner.ctx.audio_configuration.lock().await;
let mut observed=owner.ctx.connected.connections.subscribe();
// The moved-channel observation is deliberately delivered after the first
// successful binding. The manager itself obtains the replacement core ACK.
owner.ctx.connected.connections.fixture_control(&key,moved_snapshot(&key,2)).await.unwrap();
let fresh=tokio::time::timeout(Duration::from_secs(10),async{
loop{let snapshot=observed.borrow_and_update().clone();if let Some(permit)=snapshot.capture.clone().filter(|permit|permit!=&old){assert!(snapshot.capture_configuration.is_some());break permit}observed.changed().await.unwrap();}
}).await.unwrap();
assert!(!owner.ctx.refresh_capture_owner_changed().await.unwrap(),"a queued observer cannot cross another configuration lease");
let acknowledged_revision=owner.ctx.connected.connections.snapshot().capture_revision;
drop(configuration);
let (_entered,release)=capture_start_barrier(&mut owner);release.send(()).unwrap();
assert!(owner.ctx.refresh_capture_owner_changed().await.unwrap());
assert_eq!(owner.ctx.transmission.lock().unwrap().bound_permit.as_ref(),Some(&fresh));
assert_eq!(owner.ctx.connected.connections.current_capture_permit().as_ref(),Some(&fresh));assert!(owner.ctx.audio.input_active());
assert_eq!(owner.ctx.connected.connections.snapshot().capture_revision,acknowledged_revision,"binding an acknowledged replacement must not configure/revoke it again");
for _ in 0..3{assert!(!owner.ctx.refresh_capture_owner_changed().await.unwrap());}
assert_eq!(owner.ctx.connected.connections.current_capture_permit(),Some(fresh));
shutdown_offline(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn runtime_consumer_nonowner_output_change_reconciles_actual_microphone_owner(){
let (_directory,mut owner,_events,_controls)=offline_runtime().await;
let microphone=reducer_capture_fixture(&owner.ctx).await;
let (_entered,release)=capture_start_barrier(&mut owner);release.send(()).unwrap();owner.ctx.refresh_capture().await.unwrap();
let other=owner.ctx.connected.connections.create().await.unwrap();
owner.ctx.connected.connections.fixture_control(&other,moved_snapshot(&other,1)).await.unwrap();
let (_entered,release)=capture_start_barrier(&mut owner);release.send(()).unwrap();
super::super::controller::set_audio_flags(&owner.ctx,&other,None,Some(true)).await.unwrap();
let snapshot=owner.ctx.connected.connections.snapshot();
assert_eq!(snapshot.input_id.as_deref(),Some(microphone.connection_id.as_str()));
assert!(snapshot.get(&other.connection_id).unwrap().audio.output_muted);assert!(!snapshot.get(&microphone.connection_id).unwrap().audio.output_muted);
let permit=owner.ctx.connected.connections.current_capture_permit().unwrap();
assert_eq!(permit.key,microphone);assert_eq!(owner.ctx.transmission.lock().unwrap().bound_permit.as_ref(),Some(&permit));
assert!(owner.ctx.audio.input_active(),"a nonowner playback boundary must not strand the actual input owner");
assert!(!owner.ctx.refresh_capture_owner_changed().await.unwrap());
shutdown_offline(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn runtime_consumer_microphone_readiness_distinguishes_stop_from_logical_inhibition(){
let (_directory,mut owner,_events,_controls)=offline_runtime().await;
let key=reducer_capture_fixture(&owner.ctx).await;
let (_entered,release)=capture_start_barrier(&mut owner);release.send(()).unwrap();owner.ctx.refresh_capture().await.unwrap();
assert!(owner.ctx.microphone_enabled(&key));
owner.ctx.audio.request(AudioCommand::StopInput).await.unwrap();
assert!(!owner.ctx.microphone_enabled(&key),"unexpected stopped capture must offer one-click activation");
assert!(owner.ctx.transmission.lock().unwrap().capture_desired,"device observations do not revoke durable consent");
let (unexpected_start,release)=capture_start_barrier(&mut owner);release.send(()).unwrap();
for _ in 0..3{owner.ctx.refresh_capture_owner_changed().await.unwrap();}
assert!(owner.ctx.connected.connections.current_capture_permit().is_none());assert!(!owner.ctx.audio.input_active());
assert_eq!(unexpected_start.try_recv(),Err(std::sync::mpsc::TryRecvError::Empty),"ticker observations may not retry stopped hardware");
let mut prefs=owner.ctx.profile().unwrap().prefs.get();prefs["pttEnabled"]=serde_json::json!(true);
owner.ctx.refresh_transmission_gate(&key,&prefs).unwrap();
assert!(owner.ctx.microphone_enabled(&key),"idle PTT retains the on-screen hold control even though forwarding is fenced");
owner.ctx.transmission.lock().unwrap().ptt_holders.insert("screen".into());
owner.ctx.refresh_transmission_gate(&key,&prefs).unwrap();
assert!(!owner.ctx.microphone_enabled(&key),"held PTT cannot hide unavailable capture");
owner.ctx.request(&key,teamspeach_core::protocol::Command::SetAudio{input_muted:None,output_muted:Some(true)}).await.unwrap();
assert!(owner.ctx.microphone_enabled(&key),"deafen retains microphone consent without claiming physical readiness");
owner.ctx.request(&key,teamspeach_core::protocol::Command::SetAudio{input_muted:None,output_muted:Some(false)}).await.unwrap();
assert!(!owner.ctx.microphone_enabled(&key));
let (_entered,release)=capture_start_barrier(&mut owner);release.send(()).unwrap();owner.ctx.refresh_capture().await.unwrap();
assert!(owner.ctx.microphone_enabled(&key));shutdown_offline(owner).await;
}
#[test]
fn private_resume_uses_newer_output_intent_and_never_restores_revoked_capture(){
let resume=super::super::context::MicrophoneTestResume{owner:Some(key(1)),input:true,output:false,output_revision:8};
let mut state=TransmissionState::default();state.capture_desired=true;state.output_intent_revision=8;
assert_eq!(resume.activities(&state),(true,false));
state.output_intent_revision=9;state.output_desired=true;
assert_eq!(resume.activities(&state),(true,true),"a newer undeafen supersedes the saved inactive output");
state.capture_desired=false;
assert_eq!(resume.activities(&state),(false,true),"Clear is not fresh microphone consent");
state.output_intent_revision=10;state.output_desired=false;
assert_eq!(resume.activities(&state),(false,false));
}
#[tokio::test(flavor="current_thread")]
async fn runtime_mute_revokes_before_waiting_for_configuration(){
let (_directory,owner,_events,_controls)=offline_runtime().await;let ctx=&owner.ctx;
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
let revision={let mut state=ctx.transmission.lock().unwrap();state.observe_owner(Some(key.clone()));state.capture_desired=true;state.revision};
ctx.microphone_granted.store(true,Ordering::Release);
let configuration=ctx.audio_configuration.lock().await;
let mut mute=Box::pin(super::super::controller::set_audio_flags(ctx,&key,Some(true),None));
pending_once(mute.as_mut()).await;
assert!(!ctx.transmission.lock().unwrap().capture_desired);
assert_eq!(ctx.acknowledge_microphone_permission(revision,true).unwrap_err().code,"audio_activation_revoked");
drop(configuration);mute.await.unwrap();
assert!(ctx.connected.connections.snapshot().get(&key.connection_id).unwrap().audio.input_muted,"real command consumer must acknowledge mute");
assert!(!ctx.audio.input_active());shutdown_offline(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn runtime_retained_suspend_keeps_held_negative_inhibitors(){
let (_directory,owner,_events,_controls)=offline_runtime().await;let ctx=&owner.ctx;
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
{let mut state=ctx.transmission.lock().unwrap();state.observe_owner(Some(key.clone()));state.capture_desired=true;state.deactivated.insert("still-held".into());state.ptt_holders.insert("positive".into());}
for output in [true,false]{super::super::controller::set_audio_flags(ctx,&key,None,Some(output)).await.unwrap();let state=ctx.transmission.lock().unwrap();assert!(state.capture_desired);assert!(state.deactivated.contains("still-held"));assert!(state.ptt_holders.is_empty());}
shutdown_offline(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn runtime_queued_clear_without_reservation_does_not_touch_new_intent(){
let (_directory,mut owner,_events,_controls)=offline_runtime().await;let ctx=owner.ctx.clone();
let key=reducer_capture_fixture(&ctx).await;
let (_entered,release)=capture_start_barrier(&mut owner);release.send(()).unwrap();
*ctx.microphone_test_resume.lock().unwrap()=Some(super::super::context::MicrophoneTestResume{owner:Some(key.clone()),input:false,output:false,output_revision:0});
let configuration=ctx.audio_configuration.lock().await;
let mut clear=Box::pin(super::super::settings_actions::handle(ctx.clone(),crate::ui::settings::SettingsAction::Invoke(crate::ui::settings::Operation::AudioTest(crate::ui::settings::AudioTest::Clear))));
pending_once(clear.as_mut()).await;
ctx.finish_private_microphone_test(&configuration).await.unwrap();
let revision={let mut state=ctx.transmission.lock().unwrap();state.capture_desired=true;state.output_desired=true;state.output_intent_revision=1;state.revision};
ctx.refresh_capture_locked(&configuration,false).await.unwrap();
let permit=ctx.connected.connections.current_capture_permit().unwrap();assert!(ctx.audio.input_active());
drop(configuration);clear.await.unwrap();
let state=ctx.transmission.lock().unwrap();assert_eq!(state.revision,revision);assert!(state.capture_desired);assert!(state.output_desired);drop(state);
assert!(ctx.microphone_test_resume.lock().unwrap().is_none());
assert!(ctx.audio.input_active(),"a Clear queued before activation cannot stop the newer real input consumer");
assert_eq!(ctx.connected.connections.current_capture_permit(),Some(permit));
assert!(!owner.audio_events.try_iter().any(|event|matches!(event,crate::media::audio::engine::AudioEvent::MicrophoneTest{state:crate::media::audio::engine::MicrophoneTestState::Finished,..})));
shutdown_offline(owner).await;
}
#[test]
fn receive_only_owner_is_observed_once_without_authorizing_capture(){
let mut state=TransmissionState::default();let owner=key(1);
assert!(state.observe_owner(Some(owner.clone())));
let revision=state.revision;
// The receive-only early return has no permit/configuration, but the next
// ticker observation must not request another StopInput/revoke cycle.
assert!(state.configured.is_none());
for _ in 0..1000{assert!(!state.observe_owner(Some(owner.clone())));}
assert_eq!(state.revision,revision);assert_eq!(state.key,Some(owner));
assert!(state.configured.is_none());
}
#[test]
fn owner_changes_clear_old_forwarding_state_and_configuration(){
let mut state=TransmissionState::default();state.observe_owner(Some(key(1)));
state.ptt_holders.insert("held".into());state.deactivated.insert("muted".into());
state.release_at=Some(Instant::now());state.configured=Some(InputConfiguration::default());state.capture_desired=true;
assert!(state.observe_owner(Some(key(2))));
assert!(state.ptt_holders.is_empty());assert!(state.deactivated.is_empty());
assert!(state.release_at.is_none());assert!(state.configured.is_none());
assert!(!state.capture_desired);
assert!(state.observe_owner(None));assert!(!state.observe_owner(None));
assert!(state.key.is_none());
}
#[tokio::test(flavor="current_thread")]
async fn capture_intent_survives_delayed_stops_and_consecutive_refreshes(){
let mut state=TransmissionState::default();let owner=key(1);
state.observe_owner(Some(owner.clone()));state.capture_desired=true;
let activity=AtomicBool::new(true);
for _ in 0..2{
let revision=state.revision;
let resume=state.capture_intent(&owner,revision).unwrap();
// Configuration closes hardware. The event actor can observe that stop
// while the owner awaits acknowledgments, or before the next refresh.
tokio::task::yield_now().await;activity.store(false,Ordering::Release);
state.acknowledge_capture_configuration(&owner,revision,InputConfiguration::default(),true).unwrap();
assert!(!activity.load(Ordering::Acquire));assert!(resume);
assert!(state.capture_intent(&owner,revision).unwrap());
}
}
#[test]
fn no_permit_preserves_only_output_muted_capture_intent(){
for config in [InputConfiguration{input_muted:true,..InputConfiguration::default()},InputConfiguration{output_muted:true,..InputConfiguration::default()}]{
let mut state=TransmissionState::default();let owner=key(1);
state.observe_owner(Some(owner.clone()));state.capture_desired=true;let revision=state.revision;
state.acknowledge_capture_configuration(&owner,revision,config,false).unwrap();
assert_eq!(state.configured,Some(config));assert_eq!(state.capture_intent(&owner,revision).unwrap(),!config.input_muted);
state.acknowledge_capture_configuration(&owner,revision,InputConfiguration::default(),true).unwrap();
assert_eq!(state.capture_intent(&owner,revision).unwrap(),!config.input_muted);
}
}
#[test]
fn no_capture_acknowledgment_does_not_hide_owner_or_revision_mismatch(){
let mut state=TransmissionState::default();let owner=key(1);
state.observe_owner(Some(owner.clone()));state.capture_desired=true;let revision=state.revision;
let config=InputConfiguration{input_muted:true,..InputConfiguration::default()};
assert_eq!(state.acknowledge_capture_configuration(&key(2),revision,config,false).unwrap_err().code,"target_changed");
state.revision=state.revision.wrapping_add(1);state.capture_desired=false;
assert_eq!(state.acknowledge_capture_configuration(&owner,revision,config,false).unwrap_err().code,"target_changed");
assert!(state.configured.is_none());assert!(!state.capture_desired);
}
#[test]
fn newer_authorization_does_not_validate_an_old_refresh(){
let mut state=TransmissionState::default();let owner=key(1);
state.observe_owner(Some(owner.clone()));state.capture_desired=true;let revision=state.revision;
state.revision=state.revision.wrapping_add(1);state.capture_desired=false;
assert_eq!(state.capture_intent(&owner,revision).unwrap_err().code,"target_changed");
state.revision=state.revision.wrapping_add(1);state.capture_desired=true;
assert_eq!(state.capture_intent(&owner,revision).unwrap_err().code,"target_changed");
assert!(state.capture_intent(&owner,state.revision).unwrap());
}
#[test]
fn activation_failure_exposes_stage_and_counters_without_private_details(){
let owner=key(42);
let error=capture_stage::<()>(Err(ServiceError::new("target_changed","private server response")),"bind_permit",&owner).unwrap_err();
assert_eq!(error.code,"target_changed");
assert!(error.message.contains("bind_permit"));assert!(error.message.contains("generation=7"));assert!(error.message.contains("session=42"));
assert!(!error.message.contains(&owner.connection_id));assert!(!error.message.contains("private server response"));
assert_eq!(capture_stage(Ok(13),"start_input",&owner).unwrap(),13);
}
}
+84 -25
View File
@@ -2,39 +2,92 @@
use std::sync::{Arc,atomic::Ordering};
use crate::{app::{connections::SessionKey,server_actions},services::{Result,ServiceError},ui::shell::*};
use super::{context::{RuntimeServices,changed,connection_error},events::{UiEffect,WorkflowResult}};
use crate::media::audio::{engine::AudioCommand,devices::StartPermission};
pub fn release_immediate(ctx:&RuntimeServices){
use crate::media::audio::engine::AudioCommand;
use super::context_helpers::capture_stage;
fn suspend_immediate(ctx:&RuntimeServices,retain_capture:bool){
ctx.audio.revoke_capture();ctx.audio.set_transmission_enabled(false);
if let Ok(mut tx)=ctx.transmission.lock(){tx.revision=tx.revision.wrapping_add(1);tx.ptt_holders.clear();tx.release_at=None;tx.deactivated.clear();}
if let Ok(mut tx)=ctx.transmission.lock(){if !retain_capture{tx.capture_desired=false;tx.deactivated.clear();}tx.revision=tx.revision.wrapping_add(1);tx.ptt_holders.clear();tx.release_at=None;tx.bound_permit=None;}
}
pub async fn release_voice(ctx:&Arc<RuntimeServices>,key:&SessionKey)->Result<()>{
pub fn release_immediate(ctx:&RuntimeServices){suspend_immediate(ctx,false);}
/// Fence old PCM immediately; only already-granted steady capture may migrate.
#[cfg(any(target_os="android",test))]
pub fn suspend_route_immediate(ctx:&RuntimeServices,key:&SessionKey,authorized:bool)->Option<crate::services::whisper::RoutedCommand>{
ctx.audio.revoke_capture();ctx.audio.set_transmission_enabled(false);
let mut tx=ctx.transmission.lock().ok()?;
let preserve=authorized&&ctx.microphone_granted.load(Ordering::Acquire)&&tx.key.as_ref()==Some(key)
&&tx.capture_desired&&tx.ptt_holders.is_empty()&&tx.release_at.is_none()&&tx.deactivated.is_empty()&&!tx.whisper.held();
if !preserve{tx.capture_desired=false;tx.deactivated.clear();}
tx.revision=tx.revision.wrapping_add(1);tx.ptt_holders.clear();tx.release_at=None;tx.bound_permit=None;
tx.whisper.release(None)
}
/// A foreground call owns steady-state capture; momentary controls remain UI-owned.
pub fn release_ui_immediate(ctx:&RuntimeServices,background_capture:bool)->Option<crate::services::whisper::RoutedCommand>{
if let Ok(mut tx)=ctx.transmission.lock(){tx.ui_controls_suspended=true;}
let preserve=ctx.transmission.lock().map(|tx|background_capture&&tx.capture_desired&&tx.ptt_holders.is_empty()&&tx.release_at.is_none()&&tx.deactivated.is_empty()&&!tx.whisper.held()).unwrap_or(false);
if !preserve{release_immediate(ctx);}
ctx.transmission.lock().ok().and_then(|mut tx|tx.whisper.release(None))
}
pub async fn release_voice(ctx:&Arc<RuntimeServices>,key:&SessionKey)->Result<()>{suspend_voice_to(ctx,key,false).await}
/// A user-selected receive/channel transition closes forwarding, not microphone consent.
pub(super) async fn suspend_voice(ctx:&Arc<RuntimeServices>,key:&SessionKey)->Result<()>{suspend_voice_to(ctx,key,true).await}
async fn suspend_voice_to(ctx:&Arc<RuntimeServices>,key:&SessionKey,retain_capture:bool)->Result<()>{
ctx.require_key(key,false)?;let snapshot=ctx.connected.connections.snapshot();if snapshot.input_id.as_deref().is_some_and(|id|id!=key.connection_id){return Ok(())}
release_immediate(ctx);let stop={ctx.transmission.lock().map_err(|_|changed())?.whisper.release(None)};
suspend_immediate(ctx,retain_capture);let stop={ctx.transmission.lock().map_err(|_|changed())?.whisper.release(None)};
ctx.audio.request(AudioCommand::Whisper{epoch:None,acknowledged:false}).await?;
if let Some(stop)=stop{if ctx.require_key(&stop.key,true).is_ok(){ctx.request(&stop.key,stop.command).await?;}}
ctx.require_key(key,false)
}
pub async fn set_microphone_owner(ctx:&Arc<RuntimeServices>,key:&SessionKey)->Result<()>{
ctx.require_key(key,true)?;ctx.policy.check()?;let snapshots=ctx.connected.connections.snapshot();if let Some(previous)=snapshots.input_id.as_deref().and_then(|id|snapshots.get(id)){release_voice(ctx,&previous.key).await?;}else{release_immediate(ctx);}
ctx.request_microphone_permission().await?;ctx.require_key(key,true)?;
ctx.require_key(key,true)?;ctx.policy.check()?;let generation=ctx.current_ui_generation()?;
let requested_revision=ctx.transmission.lock().map_err(|_|changed())?.revision;
let configuration=ctx.audio_configuration.lock().await;
if ctx.transmission.lock().map_err(|_|changed())?.revision!=requested_revision{return Err(ServiceError::new("audio_activation_revoked","Microphone authorization ended before activation"))}
capture_stage(ctx.require_key(key,true),"validate_owner",key)?;ctx.require_ui_generation(generation)?;
// Only our own release may advance this revision; a later stop wins even while
// release/permission/core acknowledgments are pending.
let activation_revision=ctx.transmission.lock().map_err(|_|changed())?.revision.wrapping_add(1);
let snapshots=ctx.connected.connections.snapshot();if let Some(previous)=snapshots.input_id.as_deref().and_then(|id|snapshots.get(id)){capture_stage(release_voice(ctx,&previous.key).await,"release",key)?;}else{release_immediate(ctx);}
// Explicit microphone consent replaces private capture; never bind real TX while
// the test reserves the input, and never replay its remembered resume flags.
ctx.finish_private_microphone_test(&configuration).await?;
ctx.audio_input_active.store(ctx.audio.input_active(),Ordering::Release);
capture_stage(ctx.request_microphone_permission().await,"permission",key)?;capture_stage(ctx.require_key(key,true),"permission_owner",key)?;ctx.require_ui_generation(generation)?;
#[cfg(any(target_os="android",target_os="ios"))]
ctx.ensure_mobile_call(key,true).await?;
capture_stage(ctx.ensure_mobile_call_locked(key,true,&configuration).await,"mobile_call",key)?;
let allowed={let profile=ctx.profile()?;profile.prefs.capture_allowed(profile.migration.is_some())};
if !allowed{return Err(ServiceError::new("device_mapping_required","Confirm the imported microphone device before capture"))}
let configuration=ctx.audio_configuration.lock().await;
let prefs=ctx.profile()?.prefs.get();let mut config=ctx.capture_configuration(key,&prefs)?;config.input_muted=false;
ctx.connected.connections.set_input(Some(key),config).await.map_err(connection_error)?;
ctx.require_key(key,true)?;ctx.audio_input_active.store(true,Ordering::Release);ctx.output_granted.store(true,Ordering::Release);ctx.audio_output_active.store(true,Ordering::Release);
{let mut transmission=ctx.transmission.lock().map_err(|_|changed())?;transmission.key=Some(key.clone());transmission.revision=transmission.revision.wrapping_add(1);}
drop(configuration);super::settings_actions::sync_audio(ctx.clone()).await?;ctx.changed().await
let prefs=ctx.profile()?.prefs.get();let mut config=capture_stage(ctx.capture_configuration(key,&prefs),"owner_configuration",key)?;config.input_muted=false;
capture_stage(ctx.connected.connections.set_input(Some(key),config).await.map_err(connection_error),"select_owner",key)?;
capture_stage(ctx.require_key(key,true),"selected_owner",key)?;ctx.require_ui_generation(generation)?;ctx.output_granted.store(true,Ordering::Release);
{let mut transmission=ctx.transmission.lock().map_err(|_|changed())?;if transmission.revision!=activation_revision||!ctx.microphone_granted.load(Ordering::Acquire){return capture_stage(Err(ServiceError::new("audio_activation_revoked","Microphone authorization ended during activation")),"authorization_current",key)}transmission.key=Some(key.clone());transmission.capture_desired=true;transmission.configured=None;transmission.revision=transmission.revision.wrapping_add(1);}
super::settings_actions::activate_microphone(ctx.clone(),key,&configuration).await?;
drop(configuration);ctx.changed().await
}
pub async fn set_audio_flags(ctx:&Arc<RuntimeServices>,key:&SessionKey,input:Option<bool>,output:Option<bool>)->Result<()>{
set_audio_flags_to(ctx,key,input,output,true).await
}
async fn set_audio_flags_to(ctx:&Arc<RuntimeServices>,key:&SessionKey,input:Option<bool>,output:Option<bool>,reconcile:bool)->Result<()>{
use teamspeach_core::protocol::Command;
ctx.require_key(key,false)?;release_voice(ctx,key).await?;
if input==Some(false){ctx.policy.check()?;ctx.request_microphone_permission().await?;ctx.require_key(key,true)?;}
if let Some(muted)=input{ctx.request(key,Command::SetAudio{input_muted:Some(muted),output_muted:None}).await?;ctx.require_key(key,false)?;}
if let Some(muted)=output{ctx.request(key,Command::SetAudio{input_muted:None,output_muted:Some(muted)}).await?;ctx.require_key(key,false)?;}
if ctx.connected.connections.snapshot().get(&key.connection_id).is_some_and(|c|c.is_connected()){if input==Some(false){set_microphone_owner(ctx,key).await?;}else{ctx.refresh_capture().await?;}}ctx.changed().await
ctx.require_key(key,false)?;
// Owner configuration already sends the unmuted state with its fresh permit.
// Sending SetAudio first races that acknowledgement and asks permission twice.
let activate=input==Some(false);
if activate&&output.is_none(){return set_microphone_owner(ctx,key).await}
let input=if activate{None}else{input};
// Fence the owner synchronously, before waiting behind any older activation.
let snapshot=ctx.connected.connections.snapshot();
if snapshot.input_id.as_deref().is_none_or(|id|id==key.connection_id){suspend_immediate(ctx,input!=Some(true));}
if output.is_some(){let mut state=ctx.transmission.lock().map_err(|_|changed())?;state.output_intent_revision=state.output_intent_revision.wrapping_add(1);}
let configuration=ctx.audio_configuration.lock().await;
if input==Some(true){release_voice(ctx,key).await?;}else{suspend_voice(ctx,key).await?;}
ctx.request(key,Command::SetAudio{input_muted:input,output_muted:output}).await?;ctx.require_key(key,false)?;
if output.is_some(){let snapshot=ctx.connected.connections.snapshot();ctx.transmission.lock().map_err(|_|changed())?.output_desired=snapshot.connections.iter().any(|session|session.is_connected()&&!session.audio.output_muted);}
if reconcile&&ctx.connected.connections.snapshot().get(&key.connection_id).is_some_and(|c|c.is_connected())&&output==Some(false){ctx.restore_voice_output(key).await?;}
// Playback lifecycle commands affect the global input even when this tab is not its owner.
let snapshot=ctx.connected.connections.snapshot();
if reconcile&&snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).is_some_and(|session|session.is_connected()){ctx.refresh_capture_locked(&configuration,false).await?;}
ctx.changed().await?;drop(configuration);
if activate{set_microphone_owner(ctx,key).await}else{Ok(())}
}
pub async fn dispatch(ctx:Arc<RuntimeServices>,target:Target,operation:Operation,values:Values)->Result<WorkflowResult>{
if let Some(key)=&target.session{ctx.require_key(key,false)?;}
@@ -71,12 +124,13 @@ async fn server_form(ctx:&Arc<RuntimeServices>,target:&Target,operation:Operatio
}
pub async fn ptt(ctx:Arc<RuntimeServices>,target:Target,held:bool)->Result<()> {
let key=target.session.ok_or_else(changed)?;ctx.require_key(&key,true)?;
{let mut state=ctx.transmission.lock().map_err(|_|changed())?;if state.key.as_ref()!=Some(&key){return Err(changed())}if held{state.ptt_holders.insert("screen".into());state.release_at=None;}else{state.ptt_holders.remove("screen");}state.revision=state.revision.wrapping_add(1);}
ctx.refresh_capture().await
{let mut state=ctx.transmission.lock().map_err(|_|changed())?;if held&&state.ui_controls_suspended{return Err(ServiceError::new("ui_not_focused","Push-to-talk requires the active UI"))}if state.key.as_ref()!=Some(&key){return Err(changed())}if held{state.ptt_holders.insert("screen".into());state.release_at=None;}else{state.ptt_holders.remove("screen");}state.revision=state.revision.wrapping_add(1);}
let prefs=ctx.profile()?.prefs.get();ctx.refresh_transmission_gate(&key,&prefs)?;ctx.refresh_capture().await
}
pub async fn key_events(ctx:Arc<RuntimeServices>,events:Vec<crate::services::keybinds::ActionEvent>)->Result<()> {
use crate::services::keybinds::{Action as A,Phase};
for event in events {
if event.phase==Phase::Start&&event.scope==crate::services::keybinds::Scope::Local&&matches!(event.binding.action,A::PushToTalk|A::PushToMute|A::ReplyWhisper|A::QuickWhisper|A::WhisperList)&&ctx.transmission.lock().map_err(|_|changed())?.ui_controls_suspended{continue}
let sessions=ctx.connected.connections.snapshot();
if !sessions.connections.iter().any(|session|session.is_connected())&&event.phase!=Phase::End&&matches!(event.binding.action,A::MicrophoneToggle|A::MicrophoneMute|A::MicrophoneUnmute|A::SpeakerToggle|A::SpeakerMute|A::SpeakerUnmute){let mut defaults=ctx.audio_defaults.lock().map_err(|_|changed())?;match event.binding.action{A::MicrophoneToggle=>defaults.0=!defaults.0,A::MicrophoneMute=>defaults.0=true,A::MicrophoneUnmute=>defaults.0=false,A::SpeakerToggle=>defaults.1=!defaults.1,A::SpeakerMute=>defaults.1=true,A::SpeakerUnmute=>defaults.1=false,_=>{}}continue}
let snapshots=ctx.connected.connections.snapshot();let preferred=if matches!(event.binding.action,A::RecordingStart|A::RecordingStop|A::RecordingTogglePause){snapshots.viewed_id.as_ref().or(snapshots.input_id.as_ref())}else{snapshots.input_id.as_ref().or(snapshots.viewed_id.as_ref())};let Some(connection)=preferred.and_then(|id|snapshots.get(id)).filter(|c|c.is_connected())else{continue};
@@ -95,15 +149,20 @@ pub async fn key_events(ctx:Arc<RuntimeServices>,events:Vec<crate::services::key
let succeeded=match ctx.request(&key,teamspeach_core::protocol::Command::Whisper(teamspeach_core::whisper::WhisperCommand::Start{epoch:token.epoch,target:spec})).await{Ok(_)=>true,Err(error)=>{ctx.effect(UiEffect::Error(error)).await?;false}};
ctx.require_key(&key,true)?;let accepted={ctx.transmission.lock().map_err(|_|changed())?.whisper.acknowledge(&token,&key,succeeded)};
ctx.audio.request(AudioCommand::Whisper{epoch:Some(token.epoch),acknowledged:accepted}).await?;
if accepted{let prefs=ctx.profile()?.prefs.get();if let Some(permit)=ctx.connected.connections.snapshot().capture.clone().filter(|p|p.key==key){ctx.audio.request(AudioCommand::BindPermit{permit,settings:super::settings_actions::capture_settings(&prefs)}).await?;ctx.refresh_transmission_gate(&key,&prefs)?;}}continue
if accepted{let prefs=ctx.profile()?.prefs.get();if let Some(permit)=ctx.connected.connections.current_capture_permit().filter(|p|p.key==key){ctx.audio.request(AudioCommand::BindPermit{permit:permit.clone(),settings:super::settings_actions::capture_settings(&prefs)}).await?;ctx.transmission.lock().map_err(|_|changed())?.bound_permit=Some(permit);ctx.refresh_transmission_gate(&key,&prefs)?;}}continue
}
if event.phase==Phase::End{continue}
if matches!(event.binding.action,A::MicrophoneToggle|A::MicrophoneMute|A::MicrophoneUnmute|A::SpeakerToggle|A::SpeakerMute|A::SpeakerUnmute){
let mut defaults=*ctx.audio_defaults.lock().map_err(|_|changed())?;let microphone=matches!(event.binding.action,A::MicrophoneToggle|A::MicrophoneMute|A::MicrophoneUnmute);
let muted=match event.binding.action{A::MicrophoneToggle=>!defaults.0,A::SpeakerToggle=>!defaults.1,A::MicrophoneMute|A::SpeakerMute=>true,_=>false};
release_voice(&ctx,&key).await?;if !muted{ctx.policy.check()?;if microphone{ctx.request_microphone_permission().await?;}}
for session in snapshots.connections.iter().filter(|session|session.is_connected()){ctx.request(&session.key,teamspeach_core::protocol::Command::SetAudio{input_muted:microphone.then_some(muted),output_muted:(!microphone).then_some(muted)}).await?;ctx.require_key(&session.key,true)?;}
if microphone{defaults.0=muted;if !muted{set_microphone_owner(&ctx,&key).await?;}}else{defaults.1=muted;if !muted{ctx.output_granted.store(true,Ordering::Release);ctx.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await?;}}
if !muted{ctx.policy.check()?;}
if microphone&&muted{release_immediate(&ctx);}else if !microphone{suspend_immediate(&ctx,true);}
for session in snapshots.connections.iter().filter(|session|session.is_connected()){
if microphone&&!muted&&session.key!=key{ctx.request(&session.key,teamspeach_core::protocol::Command::SetAudio{input_muted:Some(false),output_muted:None}).await?;ctx.require_key(&session.key,true)?;}
else{set_audio_flags_to(&ctx,&session.key,microphone.then_some(muted),(!microphone).then_some(muted),false).await?;}
}
if !microphone||muted{let configuration=ctx.audio_configuration.lock().await;if !microphone&&!muted{ctx.restore_voice_output(&key).await?;}ctx.refresh_capture_locked(&configuration,false).await?;}
if microphone{defaults.0=muted;}else{defaults.1=muted;}
*ctx.audio_defaults.lock().map_err(|_|changed())?=defaults;ctx.changed().await?;continue
}
let operation=match event.binding.action {
+134 -86
View File
@@ -1,86 +1,134 @@
async fn control(ctx:&Arc<RuntimeServices>,event:ConnectionEvent)->Result<()> {
match event {
ConnectionEvent::Control{key,value}=>{
if ctx.require_key(&key,false).is_err(){return Ok(())}
ctx.streams.on_control(key.clone(),&value);
stream_actions::on_control(ctx.clone(),&key,&value).await?;
local_actions::on_control(ctx,&key,&value)?;
notification_actions::on_control(ctx,&key,&value).await?;
chat_actions::on_control(ctx.clone(),key.clone(),(*value).clone()).await?;
match value["event"].as_str(){
Some("state") if value["state"]=="connected"=>{
let receive=ctx.profile()?.whispers.receive_command();ctx.request(&key,receive).await?;
let volumes=ctx.profile()?.volumes.replace_command()?;ctx.request(&key,volumes).await?;
},
Some("state") if value["state"]!="connected"=>{
let snapshot=ctx.connected.connections.snapshot();if snapshot.input_id.as_deref().is_none_or(|id|id==key.connection_id){ctx.audio.revoke_capture();}let mut transmission=ctx.transmission.lock().map_err(|_|context::changed())?;if transmission.key.as_ref()==Some(&key){transmission.whisper.release(None);transmission.ptt_holders.clear();transmission.release_at=None;transmission.revision=transmission.revision.wrapping_add(1);}drop(transmission);
local_actions::on_closed(ctx,&key)?;chat_actions::on_closed(ctx.clone(),&key).await?;stream_actions::on_closed(ctx.clone(),&key).await?;file_actions::on_closed(ctx.clone(),&key).await?;
ctx.end_mobile_call(&key).await?;
#[cfg(target_os="android")] if ctx.policy.allow_os_actions{crate::platform::android::invalidate_session(&key);}
},
Some("file_transfer")=>file_actions::on_transfer(ctx.clone(),&key,&value).await?,
Some("recording"|"recording_finalized"|"recording_state")=>file_actions::on_recording(ctx.clone(),&key,&value).await?,_=>{}
}
ctx.changed().await?;
},
ConnectionEvent::Failure{key,error}=>{if let Some(key)=key{ctx.streams.disconnect(&key,"connection_failure");local_actions::on_closed(ctx,&key)?;chat_actions::on_closed(ctx.clone(),&key).await?;stream_actions::on_closed(ctx.clone(),&key).await?;file_actions::on_closed(ctx.clone(),&key).await?;}ctx.effect(UiEffect::Error(context::connection_error(error))).await?;},
ConnectionEvent::InputReset=>{ctx.audio.revoke_local_capture();},
ConnectionEvent::Playback{..}=>{},
}Ok(())
}
fn audio_event(ctx:&RuntimeServices,state:&mut AppState,event:AudioEvent){
use crate::media::audio::devices::Direction;
if let Ok(mut status)=ctx.settings_status.lock(){match event{
AudioEvent::Devices(catalog)=>{
status.audio.inputs=catalog.inputs.into_iter().map(|d|crate::ui::settings::DeviceView{id:d.id,name:d.description.name().to_owned(),available:d.configuration_error.is_none()}).collect();
status.audio.outputs=catalog.outputs.into_iter().map(|d|crate::ui::settings::DeviceView{id:d.id,name:d.description.name().to_owned(),available:d.configuration_error.is_none()}).collect();status.audio.status=format!("Audio backend: {}",catalog.host_id);
},
AudioEvent::Started{direction,device_id}=>{match direction{Direction::Input=>{state.snapshot.audio_input_active=true;state.snapshot.audio_input_starts=state.snapshot.audio_input_starts.saturating_add(1);ctx.audio_input_active.store(true,Ordering::Release)},Direction::Output=>{state.snapshot.audio_output_active=true;state.snapshot.audio_output_starts=state.snapshot.audio_output_starts.saturating_add(1);ctx.audio_output_active.store(true,Ordering::Release)}}status.audio.status=format!("{direction:?}: {device_id}");},
AudioEvent::Stopped(direction)=>match direction{Direction::Input=>{state.snapshot.audio_input_active=false;ctx.audio_input_active.store(false,Ordering::Release)},Direction::Output=>{state.snapshot.audio_output_active=false;ctx.audio_output_active.store(false,Ordering::Release)}},
AudioEvent::CaptureRevoked=>{ctx.audio.set_transmission_enabled(false);},
AudioEvent::PermissionRequired(direction)=>{status.audio.status=format!("{direction:?} permission is required");},
AudioEvent::Error(error)=>{status.audio.status=error.message.clone();status.error=error.message.clone();state.snapshot.error=error.message;ctx.audio.set_transmission_enabled(false);},
AudioEvent::MicrophoneTest{state:test,samples}=>{use crate::media::audio::engine::MicrophoneTestState::*;status.audio.recording=test==Recording;status.audio.playing=test==Listening;status.audio.has_sample=samples>0;status.audio.test_status=format!("{test:?}");},
AudioEvent::NotificationRoute{revision,..}=>{if let Ok(mut notifications)=ctx.notifications.lock(){notifications.acknowledge_output_revision(revision);}},_=>{}
}}
}
async fn platform(ctx:&Arc<RuntimeServices>,runtime:&Weak<AppRuntime>,state:&mut AppState,event:crate::platform::lifecycle::PlatformEvent)->Result<bool>{
use crate::platform::lifecycle::{PlatformEvent::*,Permission,NotificationAction};
let current=|generation|runtime.upgrade().is_some_and(|r|r.is_ui_current(generation));
#[cfg(feature="webrtc")]
if let PictureInPicture{key,stream_id,active,playing}=&event{stream_actions::on_pip(ctx.clone(),key,stream_id,*active,*playing).await?;}
match &event{
UiDestroyed{ui_generation}=>{if let Some(runtime)=runtime.upgrade(){runtime.release_ui(*ui_generation);}settings_actions::focus_lost(ctx.clone()).await?;},
Insets{ui_generation,value}=>{if !current(*ui_generation){return Ok(false)}state.snapshot.insets=*value;},
Accessibility{ui_generation,text_scale,reduce_motion,high_contrast,..}=>{if !current(*ui_generation){return Ok(false)}if text_scale.is_finite(){state.snapshot.text_scale=text_scale.clamp(0.5,4.);}state.snapshot.reduced_motion=*reduce_motion;state.snapshot.high_contrast=*high_contrast;},
DesktopTheme{ui_generation,dark}=>{if !current(*ui_generation){return Ok(false)}*ctx.system_scheme.lock().map_err(|_|failed("System theme unavailable"))?=Some(if *dark{crate::services::themes::ColorScheme::Dark}else{crate::services::themes::ColorScheme::Light});let scheme=theme_actions::scheme(ctx)?;let theme=ctx.themes.lock().map_err(|_|failed("Theme state unavailable"))?.resolve(scheme)?;ctx.effect(UiEffect::Theme(theme)).await?;},
Focus{ui_generation,focused}=>{if !current(*ui_generation){return Ok(false)}if !focused{settings_actions::focus_lost(ctx.clone()).await?;}ctx.notifications.lock().map_err(|_|failed("Notifications unavailable"))?.set_presentation(crate::services::notifications::Presentation{focused:*focused,prohibit_os_effects:!ctx.policy.allow_os_actions});},
PhysicalKey{ui_generation,code,mask,down,repeat,text_input}=>{if !current(*ui_generation){return Ok(false)}settings_actions::physical_key(ctx.clone(),code.clone(),*mask,*down,*repeat,*text_input).await?;},
PermissionChanged{permission:Permission::Microphone,granted}=>{ctx.microphone_granted.store(*granted,Ordering::Release);if !granted{controller::release_immediate(ctx);ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;}},
#[cfg(target_os="android")]
AndroidCallAudio{key,token,revision,restart_output}=>{
if !crate::platform::android::voice_audio_current(key,*token,*revision){return Ok(false)}
ctx.android_audio_changed(key,*token,*revision,*restart_output).await?;
state.snapshot.status=if crate::platform::android::voice_audio_allowed(key,false){"Listening resumed. Enable the microphone explicitly."}else{"Audio paused by Android. Waiting for audio focus."}.into();
},
AudioInterruption{began,should_resume}=>{if *began{controller::release_immediate(ctx);ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;ctx.audio.request(crate::media::audio::engine::AudioCommand::StopOutput).await?;}else if *should_resume{state.snapshot.status="Audio interruption ended. Resume the call with an explicit microphone action.".into();}},
AudioRouteChanged|NetworkChanged=>{controller::release_immediate(ctx);ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;state.snapshot.status="Audio/network route changed; stale capture was discarded. Resume microphone explicitly.".into();},
CallLeaseEnded{key}=>{if ctx.require_key(key,false).is_ok(){controller::release_voice(ctx,key).await?;ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;ctx.request(key,teamspeach_core::protocol::Command::Disconnect{message:None}).await?;}},
Notification{key,action}=>{ctx.require_key(key,true)?;let target=Target{session:Some(key.clone()),entity:Entity::Connection,name:key.connection_id.clone(),own_channel_id:None};match action{NotificationAction::Show=>{#[cfg(not(any(target_os="android",target_os="ios")))]if let Some(handle)=runtime.upgrade().and_then(|r|r.desktop_handle()){handle.action(crate::platform::desktop::WindowAction::Show).await?;}},NotificationAction::Mute=>controller::set_audio_flags(ctx,key,Some(true),None).await?,NotificationAction::Deafen=>controller::set_audio_flags(ctx,key,None,Some(true)).await?,NotificationAction::Disconnect=>{controller::dispatch(ctx.clone(),target,Operation::Disconnect,Values::new()).await?;},NotificationAction::Conversation{client_id,uid,..}=>{let target=if let(Some(id),Some(uid))=(client_id,uid){Target{entity:Entity::Client{id:*id,uid:uid.clone(),channel_id:0},..target}}else{target};let operation=if client_id.is_some(){Operation::ClientPrivateChat}else{Operation::ServerChat};if let Some(result)=chat_actions::open(ctx.clone(),target,operation).await?{for effect in result.effects{ctx.effect(effect).await?;}}}}},
ScreenLocked(locked)=>{if *locked&&ctx.profile()?.prefs.get()["osMuteWhenLocked"]==true{controller::release_immediate(ctx);let snapshots=ctx.connected.connections.snapshot();if let Some(key)=snapshots.input_id.as_deref().and_then(|id|snapshots.get(id)).map(|s|s.key.clone()){controller::set_audio_flags(ctx,&key,Some(true),None).await?;}}},
Visibility{ui_generation,visible}=>{if !current(*ui_generation){return Ok(false)}if !visible{settings_actions::focus_lost(ctx.clone()).await?;}},
DesktopWindow{ui_generation,x,y,width,height,maximized}=>{if !current(*ui_generation){return Ok(false)}desktop_actions::save_placement(ctx,*x,*y,*width,*height,*maximized).await?;},
Quit=>return Ok(true),MemoryPressure=>{state.snapshot.status="Memory pressure: unused media caches can be reloaded on demand.".into();},_=>{}
}ctx.effect(UiEffect::Platform(event)).await?;Ok(false)
}
fn target_triple()->String{
if let Some(target)=option_env!("TEAMSPEACH_BUILD_TARGET"){return target.into()}
let arch=std::env::consts::ARCH;
if cfg!(target_os="windows"){format!("{arch}-pc-windows-msvc")}
else if cfg!(target_os="linux"){format!("{arch}-unknown-linux-gnu")}
else if cfg!(target_os="android"){format!("{arch}-linux-android")}
else if cfg!(all(target_os="ios",target_abi="sim")){"aarch64-apple-ios-sim".into()}
else if cfg!(target_os="ios"){"aarch64-apple-ios".into()}
else{format!("{arch}-apple-darwin")}
}
fn current_state_observation(ctx:&RuntimeServices,key:&crate::app::connections::SessionKey,value:&serde_json::Value)->bool {
if value["event"]!="state" { return true; }
let snapshot=ctx.connected.connections.snapshot();
let Some(entry)=snapshot.get(&key.connection_id).filter(|entry|entry.key==*key) else{return false};
use crate::app::connections::ConnectionState::*;
matches!((value["state"].as_str(),entry.state),
(Some("connecting"),Connecting)|(Some("connected"),Connected)|
(Some("disconnecting"),Disconnecting)|(Some("disconnected"),Disconnected))
}
async fn control(ctx:&Arc<RuntimeServices>,event:ConnectionEvent)->Result<()> {
match event {
ConnectionEvent::Control{key,value}=>{
if ctx.require_key(&key,false).is_err(){return Ok(())}
if !current_state_observation(ctx,&key,&value){return Ok(())}
ctx.streams.on_control(key.clone(),&value);
stream_actions::on_control(ctx.clone(),&key,&value).await?;
local_actions::on_control(ctx,&key,&value)?;
notification_actions::on_control(ctx,&key,&value).await?;
chat_actions::on_control(ctx.clone(),key.clone(),(*value).clone()).await?;
// Event consumers above await. A newer manager state may already be
// published even though this observer retains the same session key.
if !current_state_observation(ctx,&key,&value){return Ok(())}
match value["event"].as_str(){
Some("state") if value["state"]=="connected"=>{
let receive=ctx.profile()?.whispers.receive_command();ctx.request(&key,receive).await?;
let volumes=ctx.profile()?.volumes.replace_command()?;ctx.request(&key,volumes).await?;
},
Some("state") if value["state"]!="connected"=>{
let snapshot=ctx.connected.connections.snapshot();if snapshot.input_id.as_deref().is_none_or(|id|id==key.connection_id){ctx.audio.revoke_capture();}let mut transmission=ctx.transmission.lock().map_err(|_|context::changed())?;if transmission.key.as_ref()==Some(&key){transmission.capture_desired=false;transmission.whisper.release(None);transmission.ptt_holders.clear();transmission.release_at=None;transmission.revision=transmission.revision.wrapping_add(1);}drop(transmission);
local_actions::on_closed(ctx,&key)?;chat_actions::on_closed(ctx.clone(),&key).await?;stream_actions::on_closed(ctx.clone(),&key).await?;file_actions::on_closed(ctx.clone(),&key).await?;
ctx.end_mobile_call(&key).await?;
#[cfg(target_os="android")] if ctx.policy.allow_os_actions{crate::platform::android::invalidate_session(&key);}
},
Some("file_transfer")=>file_actions::on_transfer(ctx.clone(),&key,&value).await?,
Some("recording"|"recording_finalized"|"recording_state")=>file_actions::on_recording(ctx.clone(),&key,&value).await?,_=>{}
}
ctx.changed().await?;
},
ConnectionEvent::Closed{key}=>{
{let mut tx=ctx.transmission.lock().map_err(|_|context::changed())?;if tx.key.as_ref()==Some(&key){tx.capture_desired=false;tx.key=None;tx.configured=None;tx.whisper.release(None);tx.ptt_holders.clear();tx.release_at=None;tx.revision=tx.revision.wrapping_add(1);}}
ctx.streams.disconnect(&key,"connection_closed");
local_actions::on_closed(ctx,&key)?;chat_actions::on_closed(ctx.clone(),&key).await?;stream_actions::on_closed(ctx.clone(),&key).await?;file_actions::on_closed(ctx.clone(),&key).await?;
ctx.end_mobile_call(&key).await?;
#[cfg(target_os="android")] if ctx.policy.allow_os_actions{crate::platform::android::invalidate_session(&key);}
ctx.changed().await?;
},
ConnectionEvent::Failure{key,error,terminal}=>{
// Configuration/command rejection is visible without closing live session workflows.
if terminal{if let Some(key)=key{ctx.streams.disconnect(&key,"connection_failure");local_actions::on_closed(ctx,&key)?;chat_actions::on_closed(ctx.clone(),&key).await?;stream_actions::on_closed(ctx.clone(),&key).await?;file_actions::on_closed(ctx.clone(),&key).await?;}}
ctx.effect(UiEffect::Error(context::connection_error(error))).await?;
},
// Runtime's composite sink invokes AudioSessionBinding synchronously before
// queueing this observation. Revoking again can invalidate a newer permit.
ConnectionEvent::InputReset=>{},
ConnectionEvent::Playback{..}=>{},
}Ok(())
}
fn audio_event(ctx:&RuntimeServices,state:&mut AppState,event:AudioEvent){
use crate::media::audio::devices::Direction;
if let Ok(mut status)=ctx.settings_status.lock(){match event{
AudioEvent::Devices(catalog)=>{
status.audio.inputs=catalog.inputs.into_iter().map(|d|crate::ui::settings::DeviceView{id:d.id,name:d.description.name().to_owned(),available:d.configuration_error.is_none()}).collect();
status.audio.outputs=catalog.outputs.into_iter().map(|d|crate::ui::settings::DeviceView{id:d.id,name:d.description.name().to_owned(),available:d.configuration_error.is_none()}).collect();status.audio.status=format!("Audio backend: {}",catalog.host_id);
#[cfg(target_os="android")]
if ctx.policy.allow_os_actions {
match crate::platform::android::communication_outputs(){
Ok(routes)=>status.audio.communication_outputs=routes,
Err(error)=>{status.audio.communication_outputs=Some(Vec::new());status.audio.status=error.message;}
}
}
},
// Hardware observations never change TransmissionState::capture_desired, even
// when a delayed stop is delivered during or after an authorized PTT refresh.
AudioEvent::Started{direction,device_id}=>{match direction{Direction::Input=>{state.snapshot.audio_input_active=ctx.audio.input_active();state.snapshot.audio_input_starts=state.snapshot.audio_input_starts.saturating_add(1);ctx.audio_input_active.store(state.snapshot.audio_input_active,Ordering::Release)},Direction::Output=>{state.snapshot.audio_output_active=ctx.audio.output_active();state.snapshot.audio_output_starts=state.snapshot.audio_output_starts.saturating_add(1);ctx.audio_output_active.store(state.snapshot.audio_output_active,Ordering::Release)}}status.audio.status=format!("{direction:?}: {device_id}");},
AudioEvent::Stopped(direction)=>match direction{Direction::Input=>{state.snapshot.audio_input_active=ctx.audio.input_active();ctx.audio_input_active.store(state.snapshot.audio_input_active,Ordering::Release)},Direction::Output=>{state.snapshot.audio_output_active=ctx.audio.output_active();ctx.audio_output_active.store(state.snapshot.audio_output_active,Ordering::Release)}},
// Revocation already closed the engine gate synchronously. A queued event
// must not revoke a newer explicit activation after its real acknowledgment.
AudioEvent::CaptureRevoked=>{},
AudioEvent::PermissionRequired(direction)=>{status.audio.status=format!("{direction:?} permission is required");},
// Command errors (including notification routing) remain visible, but are
// not capture faults. Device/capture failure paths revoke on the audio owner.
AudioEvent::Error(error)=>{status.audio.status=error.message.clone();status.error=error.message.clone();state.snapshot.error=error.message;},
AudioEvent::MicrophoneTest{state:test,samples}=>{use crate::media::audio::engine::MicrophoneTestState::*;status.audio.recording=test==Recording;status.audio.playing=test==Listening;status.audio.has_sample=samples>0;status.audio.test_status=format!("{test:?} · {:.2} s",samples as f64/48_000.0);},
AudioEvent::MicrophoneTestLevels{rms_dbfs,peak_dbfs}=>{status.audio.test_status=format!("{} · recorded RMS {rms_dbfs:.1} dBFS · peak {peak_dbfs:.1} dBFS · preview peak ≤ −12 dBFS",status.audio.test_status);},
AudioEvent::NotificationRoute{revision,..}=>{if let Ok(mut notifications)=ctx.notifications.lock(){notifications.acknowledge_output_revision(revision);}},_=>{}
}}
}
async fn platform(ctx:&Arc<RuntimeServices>,runtime:&Weak<AppRuntime>,state:&mut AppState,event:crate::platform::lifecycle::PlatformEvent)->Result<bool>{
use crate::platform::lifecycle::{PlatformEvent::*,Permission,NotificationAction};
let current=|generation|runtime.upgrade().is_some_and(|r|r.is_ui_current(generation));
#[cfg(feature="webrtc")]
if let PictureInPicture{key,stream_id,active,playing}=&event{stream_actions::on_pip(ctx.clone(),key,stream_id,*active,*playing).await?;}
match &event{
UiDestroyed{ui_generation}=>{if let Some(runtime)=runtime.upgrade(){runtime.release_ui(*ui_generation);}settings_actions::focus_lost(ctx.clone()).await?;},
Insets{ui_generation,value}=>{if !current(*ui_generation){return Ok(false)}state.snapshot.insets=*value;},
Accessibility{ui_generation,text_scale,reduce_motion,high_contrast,..}=>{if !current(*ui_generation){return Ok(false)}if text_scale.is_finite(){state.snapshot.text_scale=text_scale.clamp(0.5,4.);}state.snapshot.reduced_motion=*reduce_motion;state.snapshot.high_contrast=*high_contrast;},
DesktopTheme{ui_generation,dark}=>{if !current(*ui_generation){return Ok(false)}*ctx.system_scheme.lock().map_err(|_|failed("System theme unavailable"))?=Some(if *dark{crate::services::themes::ColorScheme::Dark}else{crate::services::themes::ColorScheme::Light});let scheme=theme_actions::scheme(ctx)?;let theme=ctx.themes.lock().map_err(|_|failed("Theme state unavailable"))?.resolve(scheme)?;ctx.effect(UiEffect::Theme(theme)).await?;},
Focus{ui_generation,focused}=>{if !current(*ui_generation){return Ok(false)}if !focused{settings_actions::focus_lost(ctx.clone()).await?;}ctx.notifications.lock().map_err(|_|failed("Notifications unavailable"))?.set_presentation(crate::services::notifications::Presentation{focused:*focused,prohibit_os_effects:!ctx.policy.allow_os_actions});},
PhysicalKey{ui_generation,code,mask,down,repeat,text_input}=>{if !current(*ui_generation){return Ok(false)}settings_actions::physical_key(ctx.clone(),code.clone(),*mask,*down,*repeat,*text_input).await?;},
PermissionChanged{permission:Permission::Microphone,granted}=>{
#[cfg(target_os="android")]
let granted=if ctx.policy.allow_os_actions{crate::platform::android::microphone_permission_granted(ctx.policy)?}else{*granted};
#[cfg(not(target_os="android"))]
let granted=*granted;
ctx.microphone_granted.store(granted,Ordering::Release);
if !granted{controller::release_immediate(ctx);ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;}
},
#[cfg(target_os="android")]
AndroidCallAudio{key,token,revision,restart_output}=>{
if !crate::platform::android::voice_audio_current(key,*token,*revision){return Ok(false)}
ctx.android_audio_changed(key,*token,*revision,*restart_output).await?;
state.snapshot.status=if crate::platform::android::voice_audio_allowed(key,true)&&ctx.audio.input_active(){"Microphone active."}else if crate::platform::android::voice_audio_allowed(key,false)&&ctx.audio.output_active(){"Listening active. Microphone inactive."}else{"Audio inactive. Check device selection and Android audio focus."}.into();
},
AudioInterruption{began,should_resume}=>{if *began{controller::release_immediate(ctx);ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;ctx.audio.request(crate::media::audio::engine::AudioCommand::StopOutput).await?;}else if *should_resume{state.snapshot.status="Audio interruption ended. Resume the call with an explicit microphone action.".into();}},
AudioRouteChanged|NetworkChanged=>{controller::release_immediate(ctx);ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;state.snapshot.status="Audio/network route changed; stale capture was discarded. Resume microphone explicitly.".into();},
CallLeaseEnded{key}=>{if ctx.require_key(key,false).is_ok(){controller::release_voice(ctx,key).await?;ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;ctx.request(key,teamspeach_core::protocol::Command::Disconnect{message:None}).await?;}},
Notification{key,action}=>{ctx.require_key(key,true)?;let target=Target{session:Some(key.clone()),entity:Entity::Connection,name:key.connection_id.clone(),own_channel_id:None};match action{NotificationAction::Show=>{#[cfg(not(any(target_os="android",target_os="ios")))]if let Some(handle)=runtime.upgrade().and_then(|r|r.desktop_handle()){handle.action(crate::platform::desktop::WindowAction::Show).await?;}},NotificationAction::Mute=>controller::set_audio_flags(ctx,key,Some(true),None).await?,NotificationAction::Deafen=>controller::set_audio_flags(ctx,key,None,Some(true)).await?,NotificationAction::Disconnect=>{controller::dispatch(ctx.clone(),target,Operation::Disconnect,Values::new()).await?;},NotificationAction::Conversation{client_id,uid,..}=>{let target=if let(Some(id),Some(uid))=(client_id,uid){Target{entity:Entity::Client{id:*id,uid:uid.clone(),channel_id:0},..target}}else{target};let operation=if client_id.is_some(){Operation::ClientPrivateChat}else{Operation::ServerChat};if let Some(result)=chat_actions::open(ctx.clone(),target,operation).await?{for effect in result.effects{ctx.effect(effect).await?;}}}}},
ScreenLocked(locked)=>{if *locked&&ctx.profile()?.prefs.get()["osMuteWhenLocked"]==true{controller::release_immediate(ctx);let snapshots=ctx.connected.connections.snapshot();if let Some(key)=snapshots.input_id.as_deref().and_then(|id|snapshots.get(id)).map(|s|s.key.clone()){controller::set_audio_flags(ctx,&key,Some(true),None).await?;}}},
Visibility{ui_generation,visible}=>{if !current(*ui_generation){return Ok(false)}if !visible{settings_actions::focus_lost(ctx.clone()).await?;}},
DesktopWindow{ui_generation,x,y,width,height,maximized}=>{if !current(*ui_generation){return Ok(false)}desktop_actions::save_placement(ctx,*x,*y,*width,*height,*maximized).await?;},
Quit=>return Ok(true),MemoryPressure=>{state.snapshot.status="Memory pressure: unused media caches can be reloaded on demand.".into();},_=>{}
}ctx.effect(UiEffect::Platform(event)).await?;Ok(false)
}
fn target_triple()->String{
if let Some(target)=option_env!("TEAMSPEACH_BUILD_TARGET"){return target.into()}
let arch=std::env::consts::ARCH;
if cfg!(target_os="windows"){format!("{arch}-pc-windows-msvc")}
else if cfg!(target_os="linux"){format!("{arch}-unknown-linux-gnu")}
else if cfg!(target_os="android"){format!("{arch}-linux-android")}
else if cfg!(all(target_os="ios",target_abi="sim")){"aarch64-apple-ios-sim".into()}
else if cfg!(target_os="ios"){"aarch64-apple-ios".into()}
else{format!("{arch}-apple-darwin")}
}
+369
View File
@@ -0,0 +1,369 @@
//! Runtime observer regressions use the real actor/core/engine with an isolated profile.
use super::*;
use serde_json::json;
#[path="../../platform/android/call_audio.rs"]
mod android_call_authorization;
async fn fixture() -> (tempfile::TempDir, Owner, mpsc::Receiver<ServiceEvent>, mpsc::Receiver<ConnectionEvent>) {
let directory=tempfile::tempdir().unwrap();
let root=directory.path().join("native");
crate::services::profile_import::initialize_native_root(&root).unwrap();
let profile=ProfileServices::open(&root).unwrap();
let config=AppConfig::isolated(root);
let(events,received)=mpsc::channel(1024);let(controls,observed)=mpsc::channel(1024);
let(_cancel,cancelled)=watch::channel(false);
let owner=construct(&config,profile,Weak::new(),events,cancelled,controls).await.unwrap();
(directory,owner,received,observed)
}
async fn cleanup(owner:Owner) {
owner.ctx.phishing.stop();owner.ctx.badges.stop();owner.ctx.updates.stop();
owner.settings_worker.abort();let _=owner.settings_worker.await;
owner.ctx.streams.shutdown();owner.ctx.connected.shutdown().await.unwrap();owner.audio.shutdown().await.unwrap();
owner.ctx.profile().unwrap().identities.close().unwrap();
}
#[tokio::test(flavor="current_thread")]
async fn audit_lifecycle_late_connecting_observer_cannot_close_newly_connected_call() {
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
// Only server bookkeeping is a reducer fixture; permissions/observer/owner state
// are production paths. No server connection or device-open success is fabricated.
ctx.connected.connections.fixture_control(&key,json!({"event":"state","state":"connecting","generation":0})).await.unwrap();
let queued=ConnectionEvent::Control{key:key.clone(),value:Arc::new(json!({"event":"state","state":"connecting","generation":0}))};
ctx.connected.connections.fixture_control(&key,json!({"event":"snapshot","generation":0,"own_channel_id":1,"channels":[{"id":1}],"clients":[]})).await.unwrap();
*ctx.mobile_call.lock().await=Some((key.clone(),false));
let revision={let mut tx=ctx.transmission.lock().unwrap();tx.observe_owner(Some(key.clone()));tx.capture_desired=true;tx.revision};
control(ctx,queued).await.unwrap();
assert_eq!(*ctx.mobile_call.lock().await,Some((key.clone(),false)),"obsolete observer must not retire connected call lease");
assert!(ctx.transmission.lock().unwrap().capture_desired);
assert_eq!(ctx.transmission.lock().unwrap().revision,revision);
assert!(ctx.connected.connections.snapshot().get(&key.connection_id).unwrap().is_connected());
cleanup(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn audit_lifecycle_permission_grant_alone_does_not_present_enabled_microphone() {
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
ctx.connected.connections.fixture_control(&key,json!({"event":"snapshot","generation":0,"own_channel_id":1,"server":{"name":"Fixture"},"channels":[],"clients":[]})).await.unwrap();
ctx.microphone_granted.store(true,Ordering::Release);
assert!(!ctx.connected.connections.snapshot().get(&key.connection_id).unwrap().audio.input_muted);
assert!(!ctx.microphone_enabled(&key),"permission is not capture intent");
let mut state=AppState::default();
state.project(ctx).await.unwrap();
let voice=state.snapshot.voice.as_ref().unwrap();
assert!(voice.muted);assert!(!voice.transmitting);assert!(!voice.ptt_enabled);
assert!(!ctx.audio.input_active());
cleanup(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn audit_lifecycle_background_call_preserves_only_existing_steady_capture_intent() {
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
{let mut tx=ctx.transmission.lock().unwrap();tx.observe_owner(Some(key));tx.capture_desired=true;}
let revision=ctx.transmission.lock().unwrap().revision;
// The bool is the OS-lease decision, not a fabricated device/manager ACK.
// Repeated Focus/Visibility/UiDestroyed notifications must be idempotent.
for _ in 0..3{assert!(controller::release_ui_immediate(ctx,true).is_none());}
{let tx=ctx.transmission.lock().unwrap();assert!(tx.capture_desired);assert!(tx.ui_controls_suspended);assert_eq!(tx.revision,revision);}
assert!(!ctx.audio.input_active(),"retained intent alone cannot open hardware");
controller::release_ui_immediate(ctx,false);
assert!(!ctx.transmission.lock().unwrap().capture_desired,"no lease retains no capture authorization");
controller::release_ui_immediate(ctx,true);
assert!(!ctx.transmission.lock().unwrap().capture_desired,"background observation must never regrant consent");
cleanup(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn audit_lifecycle_background_releases_ptt_delay_and_whisper_without_late_ack() {
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
for delayed in [false,true]{
{let mut tx=ctx.transmission.lock().unwrap();tx.capture_desired=true;if delayed{tx.release_at=Some(Instant::now()+Duration::from_secs(30));}else{tx.ptt_holders.insert("screen".into());}}
controller::release_ui_immediate(ctx,true);
let tx=ctx.transmission.lock().unwrap();assert!(tx.ptt_holders.is_empty());assert!(tx.release_at.is_none());assert!(!tx.capture_desired);
}
let token={let mut tx=ctx.transmission.lock().unwrap();tx.capture_desired=true;tx.whisper.prepare("held-whisper",key.clone()).0};
let stop=controller::release_ui_immediate(ctx,true).expect("held whisper requires an ordered stop");
assert_eq!(stop.key,key);
{let mut tx=ctx.transmission.lock().unwrap();assert!(!tx.whisper.held());assert!(!tx.whisper.acknowledge(&token,&key,true),"late start ACK cannot resurrect a released whisper");assert!(!tx.capture_desired);}
cleanup(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn audit_lifecycle_background_rejects_queued_local_momentary_starts() {
use crate::services::keybinds::{Action,ActionEvent,Phase,Scope};
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
ctx.connected.connections.fixture_control(&key,json!({"event":"snapshot","generation":0,"own_channel_id":1,"channels":[{"id":1}],"clients":[]})).await.unwrap();
{let mut tx=ctx.transmission.lock().unwrap();tx.observe_owner(Some(key.clone()));tx.capture_desired=true;}
controller::release_ui_immediate(ctx,true);
let target=Target{session:Some(key.clone()),entity:Entity::Connection,name:String::new(),own_channel_id:None};
assert_eq!(controller::ptt(ctx.clone(),target,true).await.unwrap_err().code,"ui_not_focused");
for action in [Action::PushToTalk,Action::PushToMute,Action::QuickWhisper,Action::ReplyWhisper,Action::WhisperList]{
let binding=serde_json::from_value(json!({"id":"queued","action":action,"code":"Space","global":false})).unwrap();
ctx.apply_key_events(vec![ActionEvent{binding,scope:Scope::Local,phase:Phase::Start}]).await.unwrap();
}
{let tx=ctx.transmission.lock().unwrap();assert!(tx.capture_desired);assert!(tx.ptt_holders.is_empty());assert!(tx.deactivated.is_empty());assert!(!tx.whisper.held());}
assert!(!ctx.audio.input_active());cleanup(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn audit_lifecycle_background_permission_and_os_focus_loss_still_revoke() {
use crate::platform::lifecycle::{PlatformEvent,Permission};
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
let mut state=AppState::default();
ctx.transmission.lock().unwrap().capture_desired=true;
platform(ctx,&Weak::new(),&mut state,PlatformEvent::PermissionChanged{permission:Permission::Microphone,granted:false}).await.unwrap();
assert!(!ctx.transmission.lock().unwrap().capture_desired);
platform(ctx,&Weak::new(),&mut state,PlatformEvent::PermissionChanged{permission:Permission::Microphone,granted:true}).await.unwrap();
assert!(!ctx.transmission.lock().unwrap().capture_desired,"permission grant does not restore capture intent");
ctx.transmission.lock().unwrap().capture_desired=true;
platform(ctx,&Weak::new(),&mut state,PlatformEvent::AudioInterruption{began:true,should_resume:false}).await.unwrap();
assert!(!ctx.transmission.lock().unwrap().capture_desired);
platform(ctx,&Weak::new(),&mut state,PlatformEvent::AudioInterruption{began:false,should_resume:true}).await.unwrap();
assert!(!ctx.transmission.lock().unwrap().capture_desired);assert!(!ctx.audio.input_active());
cleanup(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn audit_lifecycle_background_screen_lock_honors_explicit_mute_policy() {
use crate::platform::lifecycle::PlatformEvent;
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
let mut state=AppState::default();
ctx.profile().unwrap().prefs.set(json!({"osMuteWhenLocked":false})).unwrap();
ctx.transmission.lock().unwrap().capture_desired=true;
platform(ctx,&Weak::new(),&mut state,PlatformEvent::ScreenLocked(true)).await.unwrap();
assert!(ctx.transmission.lock().unwrap().capture_desired,"screen off alone must not revoke an authorized call");
ctx.profile().unwrap().prefs.set(json!({"osMuteWhenLocked":true})).unwrap();
platform(ctx,&Weak::new(),&mut state,PlatformEvent::ScreenLocked(true)).await.unwrap();
assert!(!ctx.transmission.lock().unwrap().capture_desired);
platform(ctx,&Weak::new(),&mut state,PlatformEvent::ScreenLocked(false)).await.unwrap();
assert!(!ctx.transmission.lock().unwrap().capture_desired,"unlock is not microphone consent");
cleanup(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn audit_lifecycle_background_terminal_shutdown_fences_capture_before_cleanup() {
let directory=tempfile::tempdir().unwrap();let root=directory.path().join("native");
crate::services::profile_import::initialize_native_root(&root).unwrap();
let runtime=AppRuntime::start(AppConfig::isolated(root)).unwrap();
let mut snapshots=runtime.subscribe();
let ctx=tokio::time::timeout(Duration::from_secs(20),async {
loop {
if snapshots.borrow_and_update().bootstrap==BootstrapState::Username { break; }
snapshots.changed().await.unwrap();
}
runtime.dispatch_shell(ShellAction::Submit{editor_id:"shutdown-fixture".into(),target:Target::application(),
operation:Operation::CreateProfile,values:Values::from([
("nickname".into(),FieldValue::Text("Shutdown test".into())),
("theme".into(),FieldValue::Choice("dark".into()))]),confirmation:String::new()}).unwrap();
loop {
if let Some(ctx)=runtime.services.lock().unwrap().upgrade(){break ctx}
snapshots.changed().await.unwrap();
}
}).await.expect("isolated onboarding must finish before shutdown test");
ctx.transmission.lock().unwrap().capture_desired=true;
runtime.request_shutdown();
assert!(*runtime.cancel.borrow());
assert!(!ctx.transmission.lock().unwrap().capture_desired,"terminal OS event must fence capture synchronously");
tokio::time::timeout(Duration::from_secs(20),runtime.shutdown()).await.unwrap().unwrap();
assert!(!ctx.audio.input_active());assert!(!ctx.audio.output_active());
}
#[tokio::test(flavor="current_thread")]
async fn audit_lifecycle_network_change_fences_old_capture_without_automatic_resume() {
use crate::platform::lifecycle::PlatformEvent;
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
ctx.connected.connections.fixture_control(&key,json!({"event":"snapshot","generation":0,
"own_channel_id":1,"channels":[{"id":1}],"clients":[]})).await.unwrap();
let permit=ctx.connected.connections.set_input(Some(&key),crate::app::connections::InputConfiguration::default()).await.unwrap().unwrap();
{let mut tx=ctx.transmission.lock().unwrap();tx.observe_owner(Some(key.clone()));tx.capture_desired=true;tx.bound_permit=Some(permit.clone());}
ctx.microphone_granted.store(true,Ordering::Release);
let mut state=AppState::default();
platform(ctx,&Weak::new(),&mut state,PlatformEvent::NetworkChanged).await.unwrap();
assert!(!ctx.transmission.lock().unwrap().capture_desired);
assert!(ctx.connected.connections.current_capture_permit().is_none());
let old=teamspeach_core::audio::CapturedFrame{pcm:[1;960],captured_at:Instant::now(),
connection_generation:key.generation,capture_epoch:permit.capture_epoch,whisper:None};
assert_eq!(ctx.connected.connections.push_audio(&key,old),crate::app::connections::CaptureIngress::PermitRevoked);
platform(ctx,&Weak::new(),&mut state,PlatformEvent::NetworkChanged).await.unwrap();
assert!(!ctx.audio.input_active());assert!(!ctx.transmission.lock().unwrap().capture_desired);
cleanup(owner).await;
}
async fn route_capture_fixture(owner:&Owner)->crate::app::connections::SessionKey {
let ctx=&owner.ctx;let key=ctx.connected.connections.snapshot().connections[0].key.clone();
// Only connected server presentation is reduced locally. Configuration,
// permits, BindPermit, ingress rejection and startup use production consumers.
ctx.profile().unwrap().prefs.set(json!({"pttEnabled":false})).unwrap();
ctx.connected.connections.fixture_control(&key,json!({"event":"snapshot","generation":key.generation,"own_channel_id":1,"channels":[{"id":1,"codec":"opus_voice"}],"clients":[]})).await.unwrap();
let prefs=ctx.profile().unwrap().prefs.get();
let config=crate::app::connections::InputConfiguration{vad:settings_actions::capture_gate(&prefs),input_muted:false,output_muted:false};
ctx.connected.connections.set_input(Some(&key),config).await.unwrap().unwrap();
{let mut tx=ctx.transmission.lock().unwrap();tx.observe_owner(Some(key.clone()));tx.capture_desired=true;}
ctx.microphone_granted.store(true,Ordering::Release);key
}
fn route_capture_barrier(owner:&mut Owner)->(std::sync::mpsc::Receiver<()>,std::sync::mpsc::SyncSender<()>) {
let(entered,observed)=std::sync::mpsc::sync_channel(1);let(release,released)=std::sync::mpsc::sync_channel(1);
owner.audio.set_test_capture_start(entered,released);(observed,release)
}
#[tokio::test(flavor="current_thread")]
async fn audit_lifecycle_route_ack_replaces_revoked_capture_once_and_reverses() {
let(_directory,mut owner,_events,_controls)=fixture().await;
let key=route_capture_fixture(&owner).await;let ctx=owner.ctx.clone();
let(_initial_entered,release)=route_capture_barrier(&mut owner);release.send(()).unwrap();ctx.refresh_capture().await.unwrap();
for route in ["headset acknowledged","phone return acknowledged"] {
let old=ctx.connected.connections.current_capture_permit().unwrap();
assert!(controller::suspend_route_immediate(&ctx,&key,true).is_none());
assert!(!ctx.audio.input_active(),"{route}: PCM must be fenced before any worker await");
assert!(ctx.transmission.lock().unwrap().capture_desired);
assert!(ctx.connected.connections.current_capture_permit().is_none());
let stale=teamspeach_core::audio::CapturedFrame{pcm:[1;960],captured_at:Instant::now(),connection_generation:key.generation,capture_epoch:old.capture_epoch,whisper:None};
assert_eq!(ctx.connected.connections.push_audio(&key,stale),crate::app::connections::CaptureIngress::PermitRevoked);
let revision=ctx.transmission.lock().unwrap().revision;
ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await.unwrap();
let(entered,release)=route_capture_barrier(&mut owner);
// This is the production post-OS-ACK capture continuation, not a fabricated
// physical headset or network success. The synthetic device owns its barrier.
let recovery=tokio::spawn({let ctx=ctx.clone();let key=key.clone();async move{
let configuration=ctx.audio_configuration.lock().await;
ctx.resume_mobile_route_capture_locked(&key,revision,&configuration).await
}});
tokio::task::spawn_blocking(move||entered.recv_timeout(Duration::from_secs(10))).await.unwrap().unwrap();
let fresh=ctx.connected.connections.current_capture_permit().unwrap();assert_ne!(old,fresh);
assert_eq!(ctx.transmission.lock().unwrap().bound_permit.as_ref(),Some(&fresh),"fresh manager + BindPermit ACK must precede StartInput");
assert!(!ctx.audio.input_active(),"startup must not acknowledge before its backend barrier");
release.send(()).unwrap();assert!(recovery.await.unwrap().unwrap());assert!(ctx.audio.input_active());
let manager_revision=ctx.connected.connections.snapshot().capture_revision;
assert!(!ctx.refresh_capture_owner_changed().await.unwrap(),"queued old observations must not replace the acknowledged route again");
assert_eq!(manager_revision,ctx.connected.connections.snapshot().capture_revision);
}
controller::suspend_route_immediate(&ctx,&key,true);let stale=ctx.transmission.lock().unwrap().revision;
controller::suspend_route_immediate(&ctx,&key,true);
let configuration=ctx.audio_configuration.lock().await;
assert!(!ctx.resume_mobile_route_capture_locked(&key,stale,&configuration).await.unwrap(),"superseded route ACK cannot start capture");
drop(configuration);cleanup(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn audit_lifecycle_newer_mute_supersedes_pending_route_start() {
let(_directory,mut owner,_events,_controls)=fixture().await;
let key=route_capture_fixture(&owner).await;let ctx=owner.ctx.clone();
controller::suspend_route_immediate(&ctx,&key,true);let revision=ctx.transmission.lock().unwrap().revision;
let(entered,release)=route_capture_barrier(&mut owner);
let recovery=tokio::spawn({let ctx=ctx.clone();let key=key.clone();async move{
let configuration=ctx.audio_configuration.lock().await;
ctx.resume_mobile_route_capture_locked(&key,revision,&configuration).await
}});
tokio::task::spawn_blocking(move||entered.recv_timeout(Duration::from_secs(10))).await.unwrap().unwrap();
let mut mute=Box::pin(controller::set_audio_flags(&ctx,&key,Some(true),None));
std::future::poll_fn(|cx|{assert!(Future::poll(mute.as_mut(),cx).is_pending());std::task::Poll::Ready(())}).await;
assert!(!ctx.transmission.lock().unwrap().capture_desired);assert!(ctx.connected.connections.current_capture_permit().is_none());
release.send(()).unwrap();assert!(recovery.await.unwrap().is_err());mute.await.unwrap();
assert!(!ctx.audio.input_active());assert!(ctx.connected.connections.current_capture_permit().is_none());
let configuration=ctx.audio_configuration.lock().await;
assert!(!ctx.resume_mobile_route_capture_locked(&key,revision,&configuration).await.unwrap(),"late route completion is not a microphone regrant");
drop(configuration);cleanup(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn audit_lifecycle_route_fence_never_promotes_receive_only_or_momentary_capture() {
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
let key=route_capture_fixture(&owner).await;
for boundary in ["receive only","permission denied","held PTT","PTT release delay","held whisper"] {
ctx.microphone_granted.store(boundary!="permission denied",Ordering::Release);
{let mut tx=ctx.transmission.lock().unwrap();tx.capture_desired=boundary!="receive only";
if boundary=="held PTT"{tx.ptt_holders.insert("screen".into());}
if boundary=="PTT release delay"{tx.release_at=Some(Instant::now()+Duration::from_secs(30));}
if boundary=="held whisper"{tx.whisper.prepare("route-whisper",key.clone());}
}
controller::suspend_route_immediate(ctx,&key,boundary!="receive only");
let tx=ctx.transmission.lock().unwrap();assert!(!tx.capture_desired,"{boundary} is not migratable steady capture");assert!(tx.ptt_holders.is_empty());assert!(tx.release_at.is_none());assert!(!tx.whisper.held());
}
controller::suspend_route_immediate(ctx,&key,true);
assert!(!ctx.transmission.lock().unwrap().capture_desired,"another route observation is never a new grant");
assert!(!ctx.audio.input_active());cleanup(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn audit_lifecycle_manual_phone_capture_keeps_playback_selection_and_later_mute_wins() {
use crate::media::audio::{devices::{DeviceSelection,Direction},engine::{AudioCommand,AudioEvent}};
let(_directory,mut owner,_events,_controls)=fixture().await;let ctx=owner.ctx.clone();
// Selection command consumption is real; no Android route or hardware-open
// success is claimed by these inert IDs and the synthetic capture boundary.
ctx.audio.request(AudioCommand::SelectOutput(DeviceSelection::Exact("aaudio:80".into()))).await.unwrap();
let key=route_capture_fixture(&owner).await;
let(_entered,release)=route_capture_barrier(&mut owner);release.send(()).unwrap();ctx.refresh_capture().await.unwrap();
let old=ctx.connected.connections.current_capture_permit().unwrap();
owner.audio_events.try_iter().for_each(drop);
let output_revision=ctx.audio.notification_revision();
let phone=DeviceSelection::Exact("aaudio:11".into());
ctx.audio.request(AudioCommand::SelectInput(phone.clone())).await.unwrap();
let selections:Vec<_>=owner.audio_events.try_iter().filter_map(|event|match event{AudioEvent::Selected{direction,selection}=>Some((direction,selection)),_=>None}).collect();
assert_eq!(selections,vec![(Direction::Input,phone)],"manual phone capture must neither alias to default nor select a playback endpoint");
assert_eq!(ctx.audio.notification_revision(),output_revision,"capture selection cannot redirect the voice-follow output");
assert!(!ctx.audio.input_active(),"selecting an endpoint is not capture authorization or a StartInput ACK");
controller::suspend_route_immediate(&ctx,&key,true);
let pending=ctx.transmission.lock().unwrap().revision;
let stale=teamspeach_core::audio::CapturedFrame{pcm:[1;960],captured_at:Instant::now(),connection_generation:key.generation,capture_epoch:old.capture_epoch,whisper:None};
assert_eq!(ctx.connected.connections.push_audio(&key,stale),crate::app::connections::CaptureIngress::PermitRevoked);
controller::release_immediate(&ctx);
let configuration=ctx.audio_configuration.lock().await;
assert!(!ctx.resume_mobile_route_capture_locked(&key,pending,&configuration).await.unwrap(),"a late manual playback/OS route ACK cannot override a newer mute");
assert!(!ctx.audio.input_active());assert!(!ctx.transmission.lock().unwrap().capture_desired);
drop(configuration);cleanup(owner).await;
}
#[tokio::test(flavor="current_thread")]
async fn audit_lifecycle_failed_manual_ack_retains_applied_pair_and_saved_intent_until_newer_mute() {
use crate::media::audio::{devices::DeviceSelection,engine::{AudioCommand,AudioEvent}};
use android_call_authorization::CallAudioState;
let(_directory,mut owner,_events,_controls)=fixture().await;
let key=route_capture_fixture(&owner).await;let ctx=owner.ctx.clone();
let old_pair=("aaudio:11".to_string(),"aaudio:80".to_string());
ctx.audio.request(AudioCommand::SelectInput(DeviceSelection::Exact(old_pair.0.clone()))).await.unwrap();
ctx.audio.request(AudioCommand::SelectOutput(DeviceSelection::Exact(old_pair.1.clone()))).await.unwrap();
*ctx.applied_audio_selections.lock().unwrap()=Some(old_pair.clone());
let(_entered,release)=route_capture_barrier(&mut owner);release.send(()).unwrap();ctx.refresh_capture().await.unwrap();
let authorization=Arc::new(std::sync::Mutex::new(CallAudioState::default()));
assert!(authorization.lock().unwrap().start(true));
// These remain desired settings after a platform failure, NOT selected
// endpoints and NOT fabricated hardware acceptance.
ctx.profile().unwrap().prefs.set(json!({"inputDeviceId":"aaudio:99","outputDeviceId":"aaudio:100"})).unwrap();
for newer_mute in [false,true] {
owner.audio_events.try_iter().for_each(drop);
authorization.lock().unwrap().begin_route();
controller::suspend_route_immediate(&ctx,&key,true);
let intent=ctx.transmission.lock().unwrap().revision;
let(event,received)=tokio::sync::oneshot::channel();
let(entered,release)=route_capture_barrier(&mut owner);
let recovery=tokio::spawn({let ctx=ctx.clone();let key=key.clone();let authorization=authorization.clone();async move {
let revision=received.await.unwrap();
assert!(authorization.lock().unwrap().is_current(revision),"failed ACK must not invalidate its own queued continuation");
let configuration=ctx.audio_configuration.lock().await;
ctx.resume_mobile_route_capture_locked(&key,intent,&configuration).await
}});
// Same state transition used by the JNI completion chooses event ownership
// and finalizes revision before the receiver is allowed to run.
let(revision,recover)=authorization.lock().unwrap().finish_manual_route(false);
assert!(recover);event.send(revision).unwrap();
tokio::task::spawn_blocking(move||entered.recv_timeout(Duration::from_secs(10))).await.unwrap().unwrap();
assert!(!ctx.audio.input_active(),"real StartInput ACK is still behind the backend barrier");
if newer_mute {
let mut mute=Box::pin(controller::set_audio_flags(&ctx,&key,Some(true),None));
std::future::poll_fn(|cx|{assert!(Future::poll(mute.as_mut(),cx).is_pending());std::task::Poll::Ready(())}).await;
authorization.lock().unwrap().revoke_capture();
release.send(()).unwrap();assert!(recovery.await.unwrap().is_err());mute.await.unwrap();
assert!(!ctx.audio.input_active());assert!(!ctx.transmission.lock().unwrap().capture_desired);
}else{release.send(()).unwrap();assert!(recovery.await.unwrap().unwrap());assert!(ctx.audio.input_active());}
assert_eq!(ctx.applied_audio_selections.lock().unwrap().as_ref(),Some(&old_pair));
let prefs=ctx.profile().unwrap().prefs.get();
assert_eq!(prefs["inputDeviceId"],"aaudio:99");assert_eq!(prefs["outputDeviceId"],"aaudio:100");
assert!(!owner.audio_events.try_iter().any(|event|matches!(event,AudioEvent::Selected{..})),"failed recovery preserves the existing worker pair, not saved unavailable choices or a default fallback");
}
cleanup(owner).await;
}
@@ -1,143 +1,151 @@
use super::*;
use crate::{app::connections::ConnectionState,services::secrets::{SecretString,SecretBinding,SecretPurpose,ExplicitSecretAccess}};
use teamspeach_core::protocol::{Command,ConnectArgs};
pub(super) async fn handle(ctx:Arc<RuntimeServices>,target:Target,operation:Operation,values:Values)->Result<WorkflowResult>{
use Operation::*;
match operation{
Connect|NewConnection=>{
let mut editor=form(&ctx,&target,operation)?;
if let Some(key)=&target.session{ctx.require_key(key,false)?;let state=ctx.connected.connections.snapshot();if let Some(entry)=state.get(&key.connection_id){set(&mut editor,"address",FieldValue::Text(entry.address.clone()));identities(&ctx,&mut editor,entry.identity_id.clone()).await?;}}
else{let address=ctx.profile()?.prefs.get()["lastAddress"].as_str().unwrap_or_default().to_owned();set(&mut editor,"address",FieldValue::Text(address));identities(&ctx,&mut editor,None).await?;}
// A disconnected tab is a valid connect target, but service prompts require
// connected session targets. Keep the exact key locally and revalidate it below.
editor.target.session=None;
let values=input(&ctx,editor,values).await?;
if !ctx.network_enabled{return Err(ServiceError::new("network_disabled","Network connections are disabled in this isolated runtime"))}
let args=ConnectArgs{address:text(&values,"address")?.trim().into(),identity_id:identity(text(&values,"identity_id")?),nickname:optional(text(&values,"nickname")?),server_password:password_value(&values,"password")?,channel:None,channel_password:None};
let args=validate_connect(&ctx,args).await?;
if let Some(key)=&target.session{ctx.require_key(key,false)?;}
let key=if operation==NewConnection||target.session.is_none(){ctx.connected.connections.create().await.map_err(connection_error)?}else{key(&target)?};
connect(&ctx,&key,args).await?;
},
Disconnect|CloseConnection|RestartCore=>{
let key=key(&target)?;ctx.require_key(&key,false)?;
super::super::controller::release_voice(&ctx,&key).await?;
match operation{Disconnect=>{ctx.request(&key,Command::Disconnect{message:None}).await?;},CloseConnection=>ctx.connected.close(&key).await?,RestartCore=>{ctx.connected.connections.restart(&key).await.map_err(connection_error)?;},_=>unreachable!()}
},
UseMicrophone=>{let key=key(&target)?;super::super::controller::set_microphone_owner(&ctx,&key).await?;},
ToggleMicrophone|ToggleDeafen=>{
let key=key(&target)?;ctx.require_key(&key,false)?;
let audio=ctx.connected.connections.snapshot().get(&key.connection_id).ok_or_else(changed)?.audio;
super::super::controller::set_audio_flags(&ctx,&key,(operation==ToggleMicrophone).then_some(!audio.input_muted),(operation==ToggleDeafen).then_some(!audio.output_muted)).await?;
},
SetAway=>{let key=key(&target)?;ctx.require_key(&key,true)?;let values=input(&ctx,form(&ctx,&target,operation)?,values).await?;ctx.require_key(&key,true)?;let away=boolean(&values,"away")?;ctx.request(&key,Command::Admin(teamspeach_core::admin::AdminCommand::SetAway{away,message:if away{optional(text(&values,"message")?)}else{None}})).await?;},
SetNickname=>{let key=key(&target)?;ctx.require_key(&key,true)?;let values=input(&ctx,form(&ctx,&target,operation)?,values).await?;ctx.require_key(&key,true)?;ctx.request(&key,Command::Rename{nickname:text(&values,"name")?.trim().into()}).await?;},
OpenLogs=>ctx.open_logs().await?,
JoinChannel=>join(&ctx,target,values).await?,
_=>return Err(bad("Invalid connection workflow")),
}ctx.changed().await?;Ok(done())
}
fn password_value(values:&Values,id:&str)->Result<Option<String>>{let value=text(values,id)?;if value.is_empty(){Ok(None)}else{let secret=SecretString::new(value)?;Ok(Some(secret.expose(ExplicitSecretAccess::ConnectByUser).to_owned()))}}
pub(super) async fn validate_connect(ctx:&Arc<RuntimeServices>,args:ConnectArgs)->Result<ConnectArgs>{
teamspeach_core::protocol::validate_command(Command::Connect(args.clone())).map_err(|e|bad(e.message))?;
let identities=ctx.profile()?.identities.clone();let uid=args.identity_id.clone();
tokio::task::spawn_blocking(move||identities.profile(uid.as_deref())).await.map_err(|_|bad("Identity worker stopped"))??;
Ok(args)
}
pub(super) async fn connect(ctx:&Arc<RuntimeServices>,key:&SessionKey,args:ConnectArgs)->Result<()>{
connect_with_audio(ctx,key,args,None,None).await
}
async fn connect_with_audio(ctx:&Arc<RuntimeServices>,key:&SessionKey,args:ConnectArgs,input_override:Option<bool>,bookmark:Option<&Value>)->Result<()>{
let ui_generation=ctx.current_ui_generation()?;
ctx.policy.check()?;
ctx.require_key(key,false)?;
if ctx.connected.connections.snapshot().get(&key.connection_id).ok_or_else(changed)?.state!=ConnectionState::Disconnected{return Err(ServiceError::new("already_connected","The server tab is already connected"))}
let address=args.address.clone();
let (input_muted,output_muted)=*ctx.audio_defaults.lock().map_err(|_|bad("Audio defaults are unavailable"))?;
ctx.request(key,Command::SetAudio{input_muted:Some(input_override.unwrap_or(input_muted)),output_muted:Some(output_muted)}).await?;
ctx.require_ui_generation(ui_generation)?;
ctx.require_key(key,false)?;
if let Some(bookmark)=bookmark{check_bookmark(&*ctx.profile()?,bookmark)?;}
ctx.request(key,Command::Connect(args)).await?;
ctx.require_ui_generation(ui_generation)?;
// Connect intentionally advances the network generation, but not the tab's
// session incarnation. Never grant output to a reconnect/recycled tab.
let connected=ctx.connected.connections.key(&key.connection_id).await.map_err(connection_error)?;
if connected.session!=key.session||Some(connected.generation)!=key.generation.checked_add(1){return Err(changed())}
ctx.require_key(&connected,true)?;
ctx.require_ui_generation(ui_generation)?;
#[cfg(any(target_os="android",target_os="ios"))]
ctx.ensure_mobile_call(&connected,false).await?;
ctx.require_ui_generation(ui_generation)?;
ctx.require_key(&connected,true)?;
ctx.output_granted.store(true,std::sync::atomic::Ordering::Release);
if !ctx.audio_output_active.load(std::sync::atomic::Ordering::Acquire){
ctx.audio.request(crate::media::audio::engine::AudioCommand::StartOutput(crate::media::audio::devices::StartPermission::Granted)).await?;
ctx.audio_output_active.store(true,std::sync::atomic::Ordering::Release);
}
ctx.require_ui_generation(ui_generation)?;
ctx.require_key(&connected,true)?;
ctx.mutate(move|p|{p.prefs.set(json!({"lastAddress":address}))?;Ok(())}).await?;
Ok(())
}
pub async fn bookmark(ctx:&Arc<RuntimeServices>,target:&Target,startup:bool)->Result<WorkflowResult>{
if !ctx.network_enabled{return Err(ServiceError::new("network_disabled","Network connections are disabled in this isolated runtime"))}
let generation=ctx.current_ui_generation()?;
let id=bookmark_id(target)?;let original=saved_bookmark(&*ctx.profile()?,&id)?;
if startup&&original["auto_connect"]!=true{return Err(bad("The bookmark no longer connects at startup"))}
let key=if let Some(key)=&target.session{ctx.require_key(key,false)?;key.clone()}else{
let snapshot=ctx.connected.connections.snapshot();
if let Some(entry)=snapshot.viewed_id.as_deref().and_then(|id|snapshot.get(id)).filter(|entry|entry.state==ConnectionState::Disconnected){entry.key.clone()}
else{ctx.connected.connections.create().await.map_err(connection_error)?}
};
let mut prompt_target=target.clone();prompt_target.session=None;
let server=password(ctx,&prompt_target,&key,&original,SecretPurpose::Server).await?;
let channel=password(ctx,&prompt_target,&key,&original,SecretPurpose::Channel).await?;
ctx.require_ui_generation(generation)?;check_bookmark(&*ctx.profile()?,&original)?;ctx.require_key(&key,false)?;
let args=validate_connect(ctx,ConnectArgs{address:original["address"].as_str().unwrap_or_default().trim().into(),identity_id:original["identity_id"].as_str().map(str::to_owned),nickname:original["nickname"].as_str().map(str::to_owned),channel:original["channel"].as_str().map(str::to_owned),server_password:server,channel_password:channel}).await?;
ctx.require_ui_generation(generation)?;check_bookmark(&*ctx.profile()?,&original)?;ctx.require_key(&key,false)?;
ctx.connected.connections.view(&key).await.map_err(connection_error)?;
ctx.require_ui_generation(generation)?;check_bookmark(&*ctx.profile()?,&original)?;
connect_with_audio(ctx,&key,args,(startup&&original["auto_connect_muted"]==true).then_some(true),Some(&original)).await?;Ok(done())
}
async fn password(ctx:&Arc<RuntimeServices>,target:&Target,key:&SessionKey,original:&Value,purpose:SecretPurpose)->Result<Option<String>>{
let binding=SecretBinding::new(original["id"].as_str().ok_or_else(||bad("Invalid bookmark"))?,purpose,original["address"].as_str().ok_or_else(||bad("Invalid bookmark address"))?)?;
let owner=ctx.clone();let expected=original.clone();let captured=binding.clone();
let found=tokio::task::spawn_blocking(move||{
let profile=owner.profile()?;check_bookmark(&profile,&expected)?;
let secrets=profile.secrets.lock().map_err(|_|bad("Password service unavailable"))?;
let state=secrets.password_state(&captured)?;
if state.address_changed{return Err(ServiceError::new("password_mismatch","The saved password belongs to a different bookmark address"))}
if state.required{return Ok((true,None))}
if !state.saved{return Ok((false,None))}
match secrets.reveal(&captured,ExplicitSecretAccess::ConnectByUser){Ok(secret)=>Ok((false,Some(secret))),Err(error)if matches!(error.code.as_str(),"storage_unavailable"|"password_unreadable")=>Ok((true,None)),Err(error)=>Err(error)}
}).await.map_err(|_|bad("Password worker stopped"))??;
ctx.require_key(key,false)?;check_bookmark(&*ctx.profile()?,original)?;
if let Some(secret)=found.1{return Ok(Some(secret.expose(ExplicitSecretAccess::ConnectByUser).to_owned()))}
if !found.0{return Ok(None)}
let mut editor=form(ctx,target,Operation::ConfirmPassword)?;editor.title=format!("{} — {}",target.name,if purpose==SecretPurpose::Server{"Server password"}else{"Channel password"});
let answer=input(ctx,editor,Values::new()).await?;
ctx.require_key(key,false)?;check_bookmark(&*ctx.profile()?,original)?;
let secret=SecretString::new(text(&answer,"password")?)?;
let password=secret.expose(ExplicitSecretAccess::ConnectByUser).to_owned();
if boolean(&answer,"save")?{let expected=original.clone();ctx.mutate(move|p|{check_bookmark(p,&expected)?;p.secrets.lock().map_err(|_|bad("Password service unavailable"))?.save(&binding,secret)?;p.migration=crate::services::profile_import::load_migration(&p.root)?;Ok(())}).await?;}
ctx.require_key(key,false)?;check_bookmark(&*ctx.profile()?,original)?;Ok(Some(password))
}
async fn join(ctx:&Arc<RuntimeServices>,target:Target,values:Values)->Result<()>{
ctx.require_target(&target)?;let key=key(&target)?;let Entity::Channel{id}=target.entity else{return Err(bad("A channel is required"))};
let mut password=password_value(&values,"password")?;
if password.is_none(){let snapshot=ctx.connected.connections.snapshot();let protected=snapshot.get(&key.connection_id).and_then(|entry|entry.server.as_deref()).and_then(|s|s["channels"].as_array()).and_then(|channels|channels.iter().find(|c|c["id"].as_u64()==Some(id))).is_some_and(|c|c["has_password"]==true);if protected{password=Some(channel_password(ctx,&target).await?);}}
super::super::controller::release_voice(ctx,&key).await?;ctx.require_target(&target)?;
let joined=async{
match ctx.request(&key,Command::JoinChannel{channel_id:id,password}).await{
Err(error)if error.code=="channel_password_invalid"=>{let password=channel_password(ctx,&target).await?;ctx.require_target(&target)?;ctx.request(&key,Command::JoinChannel{channel_id:id,password:Some(password)}).await?;},
result=>{result?;},
}Ok::<(),ServiceError>(())
}.await;
// Even an unsuccessful join crossed a capture boundary. Restore only the
// same still-current microphone owner with a freshly acknowledged permit.
let restored=if ctx.require_key(&key,true).is_ok()&&ctx.connected.connections.snapshot().input_id.as_deref()==Some(key.connection_id.as_str()){ctx.refresh_capture().await}else{Ok(())};
joined?;restored?;Ok(())
}
async fn channel_password(ctx:&RuntimeServices,target:&Target)->Result<String>{let mut editor=form(ctx,target,Operation::ConfirmPassword)?;editor.fields.retain(|field|field.id=="password");let values=input(ctx,editor,Values::new()).await?;let secret=SecretString::new(text(&values,"password")?)?;Ok(secret.expose(ExplicitSecretAccess::ConnectByUser).to_owned())}
use super::*;
use crate::{app::connections::ConnectionState,services::secrets::{SecretString,SecretBinding,SecretPurpose,ExplicitSecretAccess}};
use teamspeach_core::protocol::{Command,ConnectArgs};
pub(super) async fn handle(ctx:Arc<RuntimeServices>,target:Target,operation:Operation,values:Values)->Result<WorkflowResult>{
use Operation::*;
match operation{
Connect|NewConnection=>{
let mut editor=form(&ctx,&target,operation)?;
if let Some(key)=&target.session{ctx.require_key(key,false)?;let state=ctx.connected.connections.snapshot();if let Some(entry)=state.get(&key.connection_id){set(&mut editor,"address",FieldValue::Text(entry.address.clone()));identities(&ctx,&mut editor,entry.identity_id.clone()).await?;}}
else{let address=ctx.profile()?.prefs.get()["lastAddress"].as_str().unwrap_or_default().to_owned();set(&mut editor,"address",FieldValue::Text(address));identities(&ctx,&mut editor,None).await?;}
// A disconnected tab is a valid connect target, but service prompts require
// connected session targets. Keep the exact key locally and revalidate it below.
editor.target.session=None;
let values=input(&ctx,editor,values).await?;
if !ctx.network_enabled{return Err(ServiceError::new("network_disabled","Network connections are disabled in this isolated runtime"))}
let args=ConnectArgs{address:text(&values,"address")?.trim().into(),identity_id:identity(text(&values,"identity_id")?),nickname:optional(text(&values,"nickname")?),server_password:password_value(&values,"password")?,channel:None,channel_password:None};
let args=validate_connect(&ctx,args).await?;
if let Some(key)=&target.session{ctx.require_key(key,false)?;}
let key=if operation==NewConnection||target.session.is_none(){ctx.connected.connections.create().await.map_err(connection_error)?}else{key(&target)?};
// A user-opened connection must own the visible tree even if handshake
// fails. Input ownership is independent and is not a view selection.
ctx.connected.connections.view(&key).await.map_err(connection_error)?;
connect(&ctx,&key,args).await?;
},
Disconnect|CloseConnection|RestartCore=>{
let key=key(&target)?;ctx.require_key(&key,false)?;
super::super::controller::release_voice(&ctx,&key).await?;
match operation{Disconnect=>{ctx.request(&key,Command::Disconnect{message:None}).await?;},CloseConnection=>ctx.connected.close(&key).await?,RestartCore=>{ctx.connected.connections.restart(&key).await.map_err(connection_error)?;},_=>unreachable!()}
},
UseMicrophone=>{let key=key(&target)?;super::super::controller::set_microphone_owner(&ctx,&key).await?;},
ToggleMicrophone|ToggleDeafen=>{
let key=key(&target)?;ctx.require_key(&key,false)?;
let audio=ctx.connected.connections.snapshot().get(&key.connection_id).ok_or_else(changed)?.audio;
super::super::controller::set_audio_flags(&ctx,&key,(operation==ToggleMicrophone).then(||ctx.microphone_enabled(&key)),(operation==ToggleDeafen).then_some(!audio.output_muted)).await?;
},
SetAway=>{let key=key(&target)?;ctx.require_key(&key,true)?;let values=input(&ctx,form(&ctx,&target,operation)?,values).await?;ctx.require_key(&key,true)?;let away=boolean(&values,"away")?;ctx.request(&key,Command::Admin(teamspeach_core::admin::AdminCommand::SetAway{away,message:if away{optional(text(&values,"message")?)}else{None}})).await?;},
SetNickname=>{let key=key(&target)?;ctx.require_key(&key,true)?;let values=input(&ctx,form(&ctx,&target,operation)?,values).await?;ctx.require_key(&key,true)?;ctx.request(&key,Command::Rename{nickname:text(&values,"name")?.trim().into()}).await?;},
OpenLogs=>ctx.open_logs().await?,
JoinChannel=>join(&ctx,target,values).await?,
_=>return Err(bad("Invalid connection workflow")),
}ctx.changed().await?;Ok(done())
}
fn password_value(values:&Values,id:&str)->Result<Option<String>>{let value=text(values,id)?;if value.is_empty(){Ok(None)}else{let secret=SecretString::new(value)?;Ok(Some(secret.expose(ExplicitSecretAccess::ConnectByUser).to_owned()))}}
pub(super) async fn validate_connect(ctx:&Arc<RuntimeServices>,args:ConnectArgs)->Result<ConnectArgs>{
teamspeach_core::protocol::validate_command(Command::Connect(args.clone())).map_err(|e|bad(e.message))?;
let identities=ctx.profile()?.identities.clone();let uid=args.identity_id.clone();
tokio::task::spawn_blocking(move||identities.profile(uid.as_deref())).await.map_err(|_|bad("Identity worker stopped"))??;
Ok(args)
}
pub(super) async fn connect(ctx:&Arc<RuntimeServices>,key:&SessionKey,args:ConnectArgs)->Result<()>{
connect_with_audio(ctx,key,args,None,None).await
}
async fn connect_with_audio(ctx:&Arc<RuntimeServices>,key:&SessionKey,args:ConnectArgs,input_override:Option<bool>,bookmark:Option<&Value>)->Result<()>{
let ui_generation=ctx.current_ui_generation()?;
ctx.policy.check()?;
ctx.require_key(key,false)?;
if ctx.connected.connections.snapshot().get(&key.connection_id).ok_or_else(changed)?.state!=ConnectionState::Disconnected{return Err(ServiceError::new("already_connected","The server tab is already connected"))}
let address=args.address.clone();
let (input_muted,output_muted)=*ctx.audio_defaults.lock().map_err(|_|bad("Audio defaults are unavailable"))?;
ctx.request(key,Command::SetAudio{input_muted:Some(input_override.unwrap_or(input_muted)),output_muted:Some(output_muted)}).await?;
ctx.require_ui_generation(ui_generation)?;
ctx.require_key(key,false)?;
if let Some(bookmark)=bookmark{check_bookmark(&*ctx.profile()?,bookmark)?;}
ctx.request(key,Command::Connect(args)).await?;
ctx.require_ui_generation(ui_generation)?;
// Connect intentionally advances the network generation, but not the tab's
// session incarnation. Never grant output to a reconnect/recycled tab.
let connected=ctx.connected.connections.key(&key.connection_id).await.map_err(connection_error)?;
if connected.session!=key.session||Some(connected.generation)!=key.generation.checked_add(1){return Err(changed())}
ctx.require_key(&connected,true)?;
ctx.require_ui_generation(ui_generation)?;
let configuration=ctx.audio_configuration.lock().await;
#[cfg(any(target_os="android",target_os="ios"))]
ctx.ensure_mobile_call_locked(&connected,false,&configuration).await?;
ctx.require_ui_generation(ui_generation)?;
ctx.require_key(&connected,true)?;
#[cfg(target_os="android")]
if !crate::platform::android::voice_audio_allowed(&connected,false){return Err(ServiceError::new("audio_focus_unavailable","Android has not authorized call playback"))}
// Authorization is not an active-device acknowledgment. Always ask the audio
// owner: a previous device failure or delayed Stopped event can stale the UI flag.
ctx.output_granted.store(true,std::sync::atomic::Ordering::Release);
ctx.restore_voice_output(&connected).await?;
ctx.sync_notifications().await?;
ctx.audio_output_active.store(ctx.audio.output_active(),std::sync::atomic::Ordering::Release);
drop(configuration);
ctx.require_ui_generation(ui_generation)?;
ctx.require_key(&connected,true)?;
ctx.mutate(move|p|{p.prefs.set(json!({"lastAddress":address}))?;Ok(())}).await?;
Ok(())
}
pub async fn bookmark(ctx:&Arc<RuntimeServices>,target:&Target,startup:bool)->Result<WorkflowResult>{
if !ctx.network_enabled{return Err(ServiceError::new("network_disabled","Network connections are disabled in this isolated runtime"))}
let generation=ctx.current_ui_generation()?;
let id=bookmark_id(target)?;let original=saved_bookmark(&*ctx.profile()?,&id)?;
if startup&&original["auto_connect"]!=true{return Err(bad("The bookmark no longer connects at startup"))}
let key=if let Some(key)=&target.session{ctx.require_key(key,false)?;key.clone()}else{
let snapshot=ctx.connected.connections.snapshot();
if let Some(entry)=snapshot.viewed_id.as_deref().and_then(|id|snapshot.get(id)).filter(|entry|entry.state==ConnectionState::Disconnected){entry.key.clone()}
else{ctx.connected.connections.create().await.map_err(connection_error)?}
};
let mut prompt_target=target.clone();prompt_target.session=None;
let server=password(ctx,&prompt_target,&key,&original,SecretPurpose::Server).await?;
let channel=password(ctx,&prompt_target,&key,&original,SecretPurpose::Channel).await?;
ctx.require_ui_generation(generation)?;check_bookmark(&*ctx.profile()?,&original)?;ctx.require_key(&key,false)?;
let args=validate_connect(ctx,ConnectArgs{address:original["address"].as_str().unwrap_or_default().trim().into(),identity_id:original["identity_id"].as_str().map(str::to_owned),nickname:original["nickname"].as_str().map(str::to_owned),channel:original["channel"].as_str().map(str::to_owned),server_password:server,channel_password:channel}).await?;
ctx.require_ui_generation(generation)?;check_bookmark(&*ctx.profile()?,&original)?;ctx.require_key(&key,false)?;
ctx.connected.connections.view(&key).await.map_err(connection_error)?;
ctx.require_ui_generation(generation)?;check_bookmark(&*ctx.profile()?,&original)?;
connect_with_audio(ctx,&key,args,(startup&&original["auto_connect_muted"]==true).then_some(true),Some(&original)).await?;Ok(done())
}
async fn password(ctx:&Arc<RuntimeServices>,target:&Target,key:&SessionKey,original:&Value,purpose:SecretPurpose)->Result<Option<String>>{
let binding=SecretBinding::new(original["id"].as_str().ok_or_else(||bad("Invalid bookmark"))?,purpose,original["address"].as_str().ok_or_else(||bad("Invalid bookmark address"))?)?;
let owner=ctx.clone();let expected=original.clone();let captured=binding.clone();
let found=tokio::task::spawn_blocking(move||{
let profile=owner.profile()?;check_bookmark(&profile,&expected)?;
let secrets=profile.secrets.lock().map_err(|_|bad("Password service unavailable"))?;
let state=secrets.password_state(&captured)?;
if state.address_changed{return Err(ServiceError::new("password_mismatch","The saved password belongs to a different bookmark address"))}
if state.required{return Ok((true,None))}
if !state.saved{return Ok((false,None))}
match secrets.reveal(&captured,ExplicitSecretAccess::ConnectByUser){Ok(secret)=>Ok((false,Some(secret))),Err(error)if matches!(error.code.as_str(),"storage_unavailable"|"password_unreadable")=>Ok((true,None)),Err(error)=>Err(error)}
}).await.map_err(|_|bad("Password worker stopped"))??;
ctx.require_key(key,false)?;check_bookmark(&*ctx.profile()?,original)?;
if let Some(secret)=found.1{return Ok(Some(secret.expose(ExplicitSecretAccess::ConnectByUser).to_owned()))}
if !found.0{return Ok(None)}
let mut editor=form(ctx,target,Operation::ConfirmPassword)?;editor.title=format!("{} — {}",target.name,if purpose==SecretPurpose::Server{"Server password"}else{"Channel password"});
let answer=input(ctx,editor,Values::new()).await?;
ctx.require_key(key,false)?;check_bookmark(&*ctx.profile()?,original)?;
let secret=SecretString::new(text(&answer,"password")?)?;
let password=secret.expose(ExplicitSecretAccess::ConnectByUser).to_owned();
if boolean(&answer,"save")?{let expected=original.clone();ctx.mutate(move|p|{check_bookmark(p,&expected)?;p.secrets.lock().map_err(|_|bad("Password service unavailable"))?.save(&binding,secret)?;p.migration=crate::services::profile_import::load_migration(&p.root)?;Ok(())}).await?;}
ctx.require_key(key,false)?;check_bookmark(&*ctx.profile()?,original)?;Ok(Some(password))
}
async fn join(ctx:&Arc<RuntimeServices>,target:Target,values:Values)->Result<()>{
ctx.require_target(&target)?;let key=key(&target)?;let Entity::Channel{id}=target.entity else{return Err(bad("A channel is required"))};
let mut password=password_value(&values,"password")?;
if password.is_none(){let snapshot=ctx.connected.connections.snapshot();let protected=snapshot.get(&key.connection_id).and_then(|entry|entry.server.as_deref()).and_then(|s|s["channels"].as_array()).and_then(|channels|channels.iter().find(|c|c["id"].as_u64()==Some(id))).is_some_and(|c|c["has_password"]==true);if protected{password=Some(channel_password(ctx,&target).await?);}}
super::super::controller::suspend_voice(ctx,&key).await?;ctx.require_target(&target)?;
let joined=async{
match ctx.request(&key,Command::JoinChannel{channel_id:id,password}).await{
Err(error)if error.code=="channel_password_invalid"=>{let password=channel_password(ctx,&target).await?;ctx.require_target(&target)?;ctx.request(&key,Command::JoinChannel{channel_id:id,password:Some(password)}).await?;},
result=>{result?;},
}Ok::<(),ServiceError>(())
}.await;
// Even an unsuccessful join crossed a forwarding boundary. Retain explicit
// consent only for this still-current owner, with fresh real acknowledgments.
let restored=if ctx.require_key(&key,true).is_ok()&&ctx.connected.connections.snapshot().input_id.as_deref()==Some(key.connection_id.as_str()){ctx.refresh_capture().await}else{Ok(())};
joined?;restored.map_err(|error|ServiceError::new(error.code,format!("Channel join was acknowledged, but audio recovery failed: {}",error.message)))?;Ok(())
}
async fn channel_password(ctx:&RuntimeServices,target:&Target)->Result<String>{let mut editor=form(ctx,target,Operation::ConfirmPassword)?;editor.fields.retain(|field|field.id=="password");let values=input(ctx,editor,Values::new()).await?;let secret=SecretString::new(text(&values,"password")?)?;Ok(secret.expose(ExplicitSecretAccess::ConnectByUser).to_owned())}
+180 -64
View File
@@ -1,64 +1,180 @@
use std::sync::Arc;
use super::context::RuntimeServices;
#[cfg(any(target_os="android",target_os="ios"))]
use super::context::closed;
use crate::{app::connections::SessionKey,services::Result};
impl RuntimeServices {
/// Created only by a current foreground Connect/microphone action, never profile load or resume.
pub async fn ensure_mobile_call(self:&Arc<Self>,key:&SessionKey,microphone:bool)->Result<()> {
self.policy.check()?;self.require_key(key,true)?;let generation=self.current_ui_generation()?;
let mut call=self.mobile_call.lock().await;
#[cfg(target_os="android")]
let _configuration=self.audio_configuration.lock().await;
let cached=call.as_ref().is_some_and(|(current,enabled)|current==key&&(*enabled||!microphone));
#[cfg(target_os="android")]
let cached=cached&&crate::platform::android::voice_audio_allowed(key,microphone);
if cached{return Ok(())}
#[cfg(target_os="android")]
{
if let Some((current,_))=call.as_ref(){if current!=key{crate::platform::android::stop_voice(current)?;*call=None;}}
if call.is_none(){let runtime=self.runtime.upgrade().ok_or_else(closed)?;crate::platform::android::start_voice(runtime,key.clone(),microphone,self.policy).await?;}
else{crate::platform::android::set_voice_capture(key,microphone,self.policy).await?;}
}
#[cfg(target_os="ios")]
{
let mut lease=self.apple_call.lock().await;
if lease.as_ref().is_some_and(|lease|lease.key()!=key){lease.take();}
if let Some(lease)=lease.as_ref(){lease.set_capture_enabled(microphone,self.policy).await?;}
else{*lease=Some(crate::platform::apple::begin_call(key.clone(),self.runtime.upgrade().ok_or_else(closed)?,microphone,self.policy).await?);}
}
self.require_key(key,true)?;self.require_ui_generation(generation)?;*call=Some((key.clone(),microphone));Ok(())
}
#[cfg(target_os="android")]
pub async fn android_audio_changed(self:&Arc<Self>,key:&SessionKey,token:u64,revision:u64,restart_output:bool)->Result<()> {
use crate::media::audio::{engine::AudioCommand,devices::StartPermission};
use std::sync::atomic::Ordering;
let current=||self.require_key(key,true).is_ok()&&crate::platform::android::voice_audio_current(key,token,revision);
if !current(){return Ok(())}
let _configuration=self.audio_configuration.lock().await;
if !current(){return Ok(())}
super::controller::release_immediate(self);
self.audio_input_active.store(false,Ordering::Release);
self.audio.request(AudioCommand::StopInput).await?;
if restart_output {
self.audio_output_active.store(false,Ordering::Release);
self.audio.request(AudioCommand::StopOutput).await?;
if current()&&self.output_granted.load(Ordering::Acquire)&&crate::platform::android::voice_audio_allowed(key,false) {
self.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await?;
if !current()||!crate::platform::android::voice_audio_allowed(key,false){self.audio.request(AudioCommand::StopOutput).await?;}
}
if current(){crate::platform::android::acknowledge_voice_output(key,token,revision);}
}
if current()&&self.connected.connections.snapshot().input_id.as_deref()==Some(key.connection_id.as_str()) {
self.request(key,teamspeach_core::protocol::Command::SetAudio{input_muted:Some(true),output_muted:None}).await?;
}
Ok(())
}
pub async fn end_mobile_call(&self,key:&SessionKey)->Result<()> {
let mut call=self.mobile_call.lock().await;
if call.as_ref().is_none_or(|(current,_)|current!=key){return Ok(())}
#[cfg(target_os="android")]if self.policy.allow_os_actions{crate::platform::android::stop_voice(key)?;}
#[cfg(target_os="ios")]self.apple_call.lock().await.take();
*call=None;Ok(())
}
}
use std::sync::Arc;
use super::context::RuntimeServices;
#[cfg(any(target_os="android",target_os="ios"))]
use super::context::closed;
use crate::{app::connections::SessionKey,services::Result};
impl RuntimeServices {
/// Observation only: cannot create a lease or grant/re-enable capture.
pub fn background_capture_authorized(&self)->bool {
#[cfg(target_os="android")]
{
if !self.policy.allow_os_actions||!self.microphone_granted.load(std::sync::atomic::Ordering::Acquire){return false}
let snapshot=self.connected.connections.snapshot();
return snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).is_some_and(|session|session.is_connected()&&crate::platform::android::voice_capture_retained(&session.key));
}
#[cfg(not(target_os="android"))]
false
}
/// A newly acquired Android communication lease changes the meaning of the
/// default endpoint. Retire private/pre-call streams before changing OS mode;
/// never replay the private test's remembered capture/output consent.
#[cfg(any(target_os="android",test))]
pub(super) async fn prepare_android_call_locked(&self,configuration:&tokio::sync::MutexGuard<'_,()>)->Result<()> {
use crate::media::audio::engine::AudioCommand;
use std::sync::atomic::Ordering;
self.finish_private_microphone_test(configuration).await?;
self.audio.request(AudioCommand::StopOutput).await?;
self.audio_input_active.store(self.audio.input_active(),Ordering::Release);
self.audio_output_active.store(self.audio.output_active(),Ordering::Release);
Ok(())
}
/// Callers retain this guard through capture permit binding and hardware startup.
pub async fn ensure_mobile_call_locked(self:&Arc<Self>,key:&SessionKey,microphone:bool,_configuration:&tokio::sync::MutexGuard<'_,()>)->Result<()> {
self.policy.check()?;self.require_key(key,true)?;let generation=self.current_ui_generation()?;
let mut call=self.mobile_call.lock().await;
#[cfg(target_os="android")]
if microphone {
let prefs=self.profile()?.prefs.get();
crate::platform::android::validate_voice_capture_pair(prefs["inputDeviceId"].as_str().unwrap_or_default(),prefs["outputDeviceId"].as_str().unwrap_or_default(),call.is_some())?;
}
let cached=call.as_ref().is_some_and(|(current,enabled)|current==key&&(*enabled||!microphone));
#[cfg(target_os="android")]
let cached=cached&&crate::platform::android::voice_audio_allowed(key,microphone);
if cached{return Ok(())}
#[cfg(target_os="android")]
{
if let Some((current,_))=call.as_ref(){if current!=key{crate::platform::android::stop_voice(current)?;*call=None;}}
if call.is_none(){
let runtime=self.runtime.upgrade().ok_or_else(closed)?;
self.prepare_android_call_locked(_configuration).await?;
self.require_key(key,true)?;self.require_ui_generation(generation)?;
let prefs=self.profile()?.prefs.get();
crate::platform::android::start_voice(runtime,key.clone(),microphone,prefs["outputDeviceId"].as_str().unwrap_or_default(),self.policy).await?;
}
else{crate::platform::android::set_voice_capture(key,microphone,self.policy).await?;}
}
#[cfg(target_os="ios")]
{
let mut lease=self.apple_call.lock().await;
if lease.as_ref().is_some_and(|lease|lease.key()!=key){lease.take();}
if let Some(lease)=lease.as_ref(){lease.set_capture_enabled(microphone,self.policy).await?;}
else{*lease=Some(crate::platform::apple::begin_call(key.clone(),self.runtime.upgrade().ok_or_else(closed)?,microphone,self.policy).await?);}
}
self.require_key(key,true)?;self.require_ui_generation(generation)?;
#[cfg(target_os="android")]
{
if !crate::platform::android::voice_audio_allowed(key,microphone){return Err(crate::services::ServiceError::new("audio_focus_unavailable","Android revoked call audio authorization during startup"))}
if microphone {let prefs=self.profile()?.prefs.get();crate::platform::android::validate_voice_capture_pair(prefs["inputDeviceId"].as_str().unwrap_or_default(),prefs["outputDeviceId"].as_str().unwrap_or_default(),true)?;}
}
*call=Some((key.clone(),microphone));
Ok(())
}
/// Complete only the steady intent captured by the synchronous route fence.
/// Shared with host consumer regressions; hardware/core ACKs remain real.
#[cfg(any(target_os="android",test))]
pub(super) async fn resume_mobile_route_capture_locked(self:&Arc<Self>,key:&SessionKey,intent_revision:u64,configuration:&tokio::sync::MutexGuard<'_,()>)->Result<bool>{
self.require_key(key,true)?;
if self.transmission.lock().map_err(|_|super::context::changed())?.capture_intent(key,intent_revision).is_err(){return Ok(false)}
self.refresh_capture_locked(configuration,false).await
}
#[cfg(target_os="android")]
pub async fn android_audio_changed(self:&Arc<Self>,key:&SessionKey,token:u64,revision:u64,restart_output:bool)->Result<()> {
use crate::media::audio::{engine::AudioCommand,devices::StartPermission};
use std::sync::atomic::Ordering;
use crate::platform::android::{VoiceRoutePhase as Phase,VoiceRouteReason as Reason,log_voice_route};
let started=std::time::Instant::now();
let mut phase=Phase::Validate;
let mut reason=Reason::Completed;
let current=||{
if self.require_key(key,true).is_err(){Err(Reason::OwnerChanged)}
else if !crate::platform::android::voice_audio_current(key,token,revision){Err(Reason::AudioRevisionChanged)}
else{Ok(())}
};
let result:Result<()>=async {
if let Err(changed)=current(){reason=changed;return Ok(())}
phase=Phase::Configuration;
let configuration=self.audio_configuration.lock().await;
if let Err(changed)=current(){reason=changed;return Ok(())}
let migrate=crate::platform::android::voice_audio_allowed(key,true);
// The callback already fenced PCM and dropped momentary controls. Do not
// revoke retained steady consent a second time on the queued worker.
if !migrate{super::controller::release_immediate(self);}
let intent_revision=self.transmission.lock().map_err(|_|super::context::changed())?.revision;
phase=Phase::StopInput;
self.audio.request(AudioCommand::StopInput).await?;
self.audio_input_active.store(self.audio.input_active(),Ordering::Release);
if let Err(changed)=current(){reason=changed;return Ok(())}
let prefs=self.profile()?.prefs.get();
// Observation never requests or ranks a communication output device.
let failed_request=crate::platform::android::voice_playback_failed(key,token,revision);
let applied=self.applied_audio_selections.lock().map_err(|_|super::context::changed())?.clone();
let pair=if failed_request {
// Recover only the last acknowledged worker selections after a
// FAILED request. Never rewrite desired preferences or choose a sink.
applied.ok_or_else(||crate::services::ServiceError::new("audio_route_unapplied","The saved playback choice was not applied and no previous acknowledged pair is available"))?
}else{(prefs["inputDeviceId"].as_str().unwrap_or_default().into(),prefs["outputDeviceId"].as_str().unwrap_or_default().into())};
phase=Phase::SelectInput;
if !failed_request{self.audio.request(AudioCommand::SelectInput(crate::platform::android::voice_device_selection(&pair.0)?)).await?;}
if let Err(changed)=current(){reason=changed;return Ok(())}
phase=Phase::SelectOutput;
if !failed_request{self.audio.request(AudioCommand::SelectOutput(crate::platform::android::voice_device_selection(&pair.1)?)).await?;}
if let Err(changed)=current(){reason=changed;return Ok(())}
let mut playback_error=None;
// A failed selection must not tear down still-live permitted RX merely
// to reopen its exact old endpoint. No arbitrary fallback is attempted.
let keep_live=failed_request&&self.audio.output_active()&&self.output_granted.load(Ordering::Acquire)&&crate::platform::android::voice_audio_allowed(key,false);
if restart_output&&!keep_live {
phase=Phase::StopOutput;
self.audio.request(AudioCommand::StopOutput).await?;
self.audio_output_active.store(self.audio.output_active(),Ordering::Release);
if current().is_ok()&&self.output_granted.load(Ordering::Acquire)&&crate::platform::android::voice_audio_allowed(key,false) {
phase=Phase::StartOutput;
playback_error=self.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await.err();
if current().is_err()||!crate::platform::android::voice_audio_allowed(key,false){
reason=current().err().unwrap_or(Reason::PlaybackRevoked);
phase=Phase::StopOutput;
self.audio.request(AudioCommand::StopOutput).await?;return Ok(())
}
self.audio_output_active.store(self.audio.output_active(),Ordering::Release);
}else if !self.output_granted.load(Ordering::Acquire){reason=Reason::OutputNotGranted;}
else{reason=Reason::PlaybackRevoked;}
}
if restart_output {
phase=Phase::OutputAck;
if current().is_ok(){crate::platform::android::acknowledge_voice_output(key,token,revision,self.audio.output_active());}
log_voice_route(key,phase,reason,started.elapsed(),restart_output,self.audio.output_active(),self.audio.input_active());
}
if let Err(changed)=current(){reason=changed;return Ok(())}
// Permission/mute/owner changes that arrived while hardware was replaced
// supersede this migration. Never infer consent from an old route event.
phase=Phase::CaptureIntent;
if self.transmission.lock().map_err(|_|super::context::changed())?.revision!=intent_revision{reason=Reason::CaptureIntentChanged;return Ok(())}
if migrate&&self.microphone_granted.load(Ordering::Acquire){
crate::platform::android::validate_voice_capture_pair(&pair.0,&pair.1,true)?;
phase=Phase::ResumeCapture;
if !self.resume_mobile_route_capture_locked(key,intent_revision,&configuration).await?{reason=Reason::CaptureIntentChanged;}
}else if self.connected.connections.snapshot().input_id.as_deref()==Some(key.connection_id.as_str()) {
phase=Phase::MuteCapture;
self.request(key,teamspeach_core::protocol::Command::SetAudio{input_muted:Some(true),output_muted:None}).await?;
}
phase=Phase::Enumerate;
if current().is_ok(){self.audio.request(AudioCommand::Enumerate).await?;}
else if let Err(changed)=current(){reason=changed;return Ok(())}
phase=Phase::Complete;
if let Some(error)=playback_error{return Err(error)}
Ok(())
}.await;
if result.is_err(){reason=Reason::Failed;}
self.audio_input_active.store(self.audio.input_active(),Ordering::Release);
self.audio_output_active.store(self.audio.output_active(),Ordering::Release);
log_voice_route(key,phase,reason,started.elapsed(),restart_output,self.audio.output_active(),self.audio.input_active());
result
}
pub async fn end_mobile_call(&self,key:&SessionKey)->Result<()> {
let mut call=self.mobile_call.lock().await;
if call.as_ref().is_none_or(|(current,_)|current!=key){return Ok(())}
#[cfg(target_os="android")]if self.policy.allow_os_actions{crate::platform::android::stop_voice(key)?;}
#[cfg(target_os="ios")]self.apple_call.lock().await.take();
*call=None;Ok(())
}
}
+113 -23
View File
@@ -32,32 +32,58 @@ pub fn start(config:AppConfig)->std::result::Result<Arc<AppRuntime>,AppError>{
let(snapshots_tx,snapshots)=watch::channel(Arc::new(model::Snapshot::default()));let(effects_tx,effects)=mpsc::channel(128);let(finished_tx,finished)=watch::channel(None);
let runtime=Arc::new(AppRuntime{config:config.clone(),commands,cancel,snapshots,effects:Mutex::new(effects),services:Mutex::new(Weak::new()),wake:Mutex::new(None),pending_wake:AtomicBool::new(false),active_ui:AtomicU64::new(0),finished,worker:Mutex::new(None),#[cfg(not(any(target_os="android",target_os="ios")))]desktop:Mutex::new(None)});
let weak=Arc::downgrade(&runtime);
#[cfg(target_os="android")]
let bootstrap_platform=if config.allow_os_actions{
let sink=weak.clone();Some(crate::platform::lifecycle::subscribe(Arc::new(move|event|{if let Some(runtime)=sink.upgrade(){runtime.platform_event(event);}}))?)
}else{None};
let worker=std::thread::Builder::new().name("teamspeach-app".into()).spawn(move||{
#[cfg(target_os="android")]
let _platform=bootstrap_platform;
let observed=snapshots_tx.clone();let wake=weak.clone();
let result=executor.block_on(run(config,weak,incoming,cancelled,snapshots_tx,effects_tx));
if let Err(error)=&result{let mut snapshot=(**observed.borrow()).clone();snapshot.error=error.message.clone();snapshot.loading=false;snapshot.ready=true;snapshot.bootstrap=BootstrapState::Failed;observed.send_replace(Arc::new(snapshot));if let Some(runtime)=wake.upgrade(){runtime.notify_ui();}}
if let Err(error)=&result{publish_failure(&wake,&observed,error);}
drop(executor);finished_tx.send_replace(Some(result));
})?;*runtime.worker.lock().expect("runtime worker")=Some(worker);Ok(runtime)
}
fn publish_failure(runtime:&Weak<AppRuntime>,sender:&watch::Sender<Arc<model::Snapshot>>,error:&ServiceError){
let mut snapshot=(**sender.borrow()).clone();
snapshot.revision=snapshot.revision.wrapping_add(1);snapshot.error=error.message.clone();snapshot.last_error=Some(error.clone());
snapshot.loading=false;snapshot.ready=true;snapshot.bootstrap=BootstrapState::Failed;snapshot.profile_form=None;snapshot.dialog=None;
sender.send_replace(Arc::new(snapshot));if let Some(runtime)=runtime.upgrade(){runtime.notify_ui();}
}
fn failed(message:impl Into<String>)->ServiceError{ServiceError::new("runtime_failed",message)}
struct Owner {ctx:Arc<RuntimeServices>,audio:AudioEngine,audio_events:std::sync::mpsc::Receiver<AudioEvent>,settings:mpsc::Sender<settings_queue::Request>,settings_worker:tokio::task::JoinHandle<()>,_platform:Option<crate::platform::lifecycle::Subscription>}
async fn construct(config:&AppConfig,profile:ProfileServices,runtime:Weak<AppRuntime>,events:mpsc::Sender<ServiceEvent>,cancelled:watch::Receiver<bool>,controls:mpsc::Sender<ConnectionEvent>)->Result<Owner>{
let root=profile.root.clone();let prefs=profile.prefs.get();
let policy=crate::platform::resources::ActionPolicy{allow_os_actions:config.allow_os_actions};
// Startup permission may have completed during onboarding, before this owner
// existed. Read OS state; never infer consent or open capture from the grant.
#[cfg(target_os="android")]
let microphone_granted=if policy.allow_os_actions{crate::platform::android::microphone_permission_granted(policy)?}else{false};
#[cfg(not(target_os="android"))]
let microphone_granted=false;
let (installation,installed)=distribution::detect(config)?;
let updates=crate::services::updates::UpdateService::new(installation,root.join("update-cache"),if prefs["updateChannel"]=="preview"{crate::services::updates::Channel::Preview}else{crate::services::updates::Channel::Stable},Instant::now(),policy).map_err(|e|ServiceError::new(e.code,e.detail))?;
let phishing=crate::services::privacy::PhishingList::new(&root,config.network_enabled)?;let badges=Arc::new(crate::services::badges::BadgeCatalog::new(&root,config.network_enabled)?);
let notifications=crate::services::notifications::Notifications::new(serde_json::from_value(prefs.clone())?)?;
#[cfg(not(target_os="android"))]
let subscription={let weak=runtime.clone();if config.allow_os_actions{Some(crate::platform::lifecycle::subscribe(Arc::new(move|event|{if let Some(runtime)=weak.upgrade(){runtime.platform_event(event);}}))?)}else{None}};
#[cfg(target_os="android")]
let subscription=None;
let reports=events.clone();let error_runtime=runtime.clone();let errors=Arc::new(move|error|{if reports.try_send(ServiceEvent::Effect(UiEffect::Error(error))).is_err(){if let Some(runtime)=error_runtime.upgrade(){runtime.cancel.send_replace(true);}}});
let binding=Arc::new(AudioSessionBinding::new(errors));let binding_sink=binding.clone();let overflow_runtime=runtime.clone();
let consumer:Arc<dyn ConnectionSink>=Arc::new(move|event:ConnectionEvent|{
if matches!(&event,ConnectionEvent::Playback{..}){binding_sink.on_event(event);return}
match &event{ConnectionEvent::Control{key,value}=>binding_sink.on_event(ConnectionEvent::Control{key:key.clone(),value:value.clone()}),ConnectionEvent::Playback{..}=>unreachable!(),ConnectionEvent::InputReset=>binding_sink.on_event(ConnectionEvent::InputReset),ConnectionEvent::Failure{key,error}=>binding_sink.on_event(ConnectionEvent::Failure{key:key.clone(),error:error.clone()})}
match &event{ConnectionEvent::Control{key,value}=>binding_sink.on_event(ConnectionEvent::Control{key:key.clone(),value:value.clone()}),ConnectionEvent::Closed{key}=>binding_sink.on_event(ConnectionEvent::Closed{key:key.clone()}),ConnectionEvent::Playback{..}=>unreachable!(),ConnectionEvent::InputReset=>binding_sink.on_event(ConnectionEvent::InputReset),ConnectionEvent::Failure{key,error,terminal}=>binding_sink.on_event(ConnectionEvent::Failure{key:key.clone(),error:error.clone(),terminal:*terminal})}
if controls.try_send(event).is_err(){if let Some(runtime)=overflow_runtime.upgrade(){runtime.release_held();runtime.cancel.send_replace(true);}}
});
let connected=Arc::new(crate::services::connected::ConnectedServices::start(root.clone(),profile.files.clone(),config.network_enabled,consumer)?);
let(engine,audio_events)=AudioEngine::start(connected.connections.clone(),teamspeach_denoise::CaptureSettings::default())?;let audio=engine.handle();binding.bind(audio.clone())?;
let(engine,audio_events)=match AudioEngine::start(connected.connections.clone(),teamspeach_denoise::CaptureSettings::default()){
Ok(value)=>value,Err(mut error)=>{if let Err(cleanup)=connected.shutdown().await{error.message.push_str(&format!("; cleanup failed: {cleanup}"));}return Err(error)}
};
let audio=engine.handle();if let Err(error)=binding.bind(audio.clone()){return Err(stop_construction(&connected,engine,error).await)}
let signal=Arc::new(CoreSignal::new(connected.connections.clone()));let failures=events.clone();
let streams=StreamHub::new(signal,tokio::runtime::Handle::current(),Arc::new(move|_key,error|{let _=failures.try_send(ServiceEvent::Effect(UiEffect::Error(ServiceError::new(error.code,error.message))));}));
let policy=crate::platform::resources::ActionPolicy{allow_os_actions:config.allow_os_actions};
let (installation,installed)=distribution::detect(config)?;
let updates=crate::services::updates::UpdateService::new(installation,root.join("update-cache"),if prefs["updateChannel"]=="preview"{crate::services::updates::Channel::Preview}else{crate::services::updates::Channel::Stable},Instant::now(),policy).map_err(|e|ServiceError::new(e.code,e.detail))?;
let phishing=crate::services::privacy::PhishingList::new(&root,config.network_enabled)?;let badges=Arc::new(crate::services::badges::BadgeCatalog::new(&root,config.network_enabled)?);
let ctx=Arc::new(RuntimeServices{
mobile_call:Default::default(),
#[cfg(target_os="ios")]apple_call:Default::default(),
@@ -65,7 +91,7 @@ async fn construct(config:&AppConfig,profile:ProfileServices,runtime:Weak<AppRun
root:root.clone(),profile:Mutex::new(profile),connected,audio,streams,
themes:Mutex::new(crate::services::themes::ThemeService::new(root.join("extensions"),prefs["userStyle"].as_str().map(str::to_owned))),
phishing,badges,
notifications:Mutex::new(crate::services::notifications::Notifications::new(serde_json::from_value(prefs.clone())?)?),
notifications:Mutex::new(notifications),
updates,keys:Default::default(),settings_drafts:Default::default(),settings_status:Default::default(),
audio_defaults:Mutex::new((false,false)),
improvements:Mutex::new(HashMap::new()),progress:Mutex::new(HashMap::new()),
@@ -74,40 +100,61 @@ async fn construct(config:&AppConfig,profile:ProfileServices,runtime:Weak<AppRun
audio_input_active:AtomicBool::new(false),audio_output_active:AtomicBool::new(false),
applied_audio_selections:Mutex::new(None),audio_configuration:Default::default(),microphone_test_resume:Mutex::new(None),
transmission:Default::default(),notification_clock:Instant::now(),system_scheme:Mutex::new(None),installed,
microphone_granted:AtomicBool::new(false),output_granted:AtomicBool::new(false),policy,
microphone_granted:AtomicBool::new(microphone_granted),output_granted:AtomicBool::new(false),policy,
network_enabled:config.network_enabled,version:config.build_version,runtime:runtime.clone(),
revision:AtomicU64::new(0),events,cancelled,dialogs:Semaphore::new(8),prompt_counter:AtomicU64::new(1)
});
let initialized:Result<()>=async{
ctx.notifications.lock().map_err(|_|failed("Notifications unavailable"))?.set_presentation(crate::services::notifications::Presentation{focused:true,prohibit_os_effects:!config.allow_os_actions});
ctx.connected.connections.create().await.map_err(context::connection_error)?;
let scheme=theme_actions::scheme(&ctx)?;let theme=ctx.themes.lock().map_err(|_|failed("Theme service unavailable"))?.resolve(scheme)?;ctx.effect(UiEffect::Theme(theme)).await?;
// Restoring configuration doesn't grant or open hardware, even for autostart/resume.
if let Err(error)=settings_actions::sync_keys(ctx.clone()).await{ctx.settings_status.lock().map_err(|_|failed("Shortcut state unavailable"))?.key_status=error.message;}
Ok(())
}.await;
if let Err(error)=initialized{ctx.streams.shutdown();return Err(stop_construction(&ctx.connected,engine,error).await)}
ctx.phishing.start();
if let Some(runtime)=runtime.upgrade(){*runtime.services.lock().expect("runtime services")=Arc::downgrade(&ctx);}
let weak=runtime.clone();let subscription=if config.allow_os_actions{Some(crate::platform::lifecycle::subscribe(Arc::new(move|event|{if let Some(runtime)=weak.upgrade(){runtime.platform_event(event);}}))?)}else{None};
ctx.notifications.lock().map_err(|_|failed("Notifications unavailable"))?.set_presentation(crate::services::notifications::Presentation{focused:true,prohibit_os_effects:!config.allow_os_actions});
ctx.phishing.start();ctx.connected.connections.create().await.map_err(context::connection_error)?;
// Restoring configuration doesn't grant or open hardware, even for autostart/resume.
if let Err(error)=settings_actions::sync_keys(ctx.clone()).await{ctx.settings_status.lock().map_err(|_|failed("Shortcut state unavailable"))?.key_status=error.message;}
let scheme=theme_actions::scheme(&ctx)?;let theme=ctx.themes.lock().map_err(|_|failed("Theme service unavailable"))?.resolve(scheme)?;ctx.effect(UiEffect::Theme(theme)).await?;
let(settings,settings_worker)=settings_queue::start(ctx.clone());
Ok(Owner{ctx,audio:engine,audio_events,settings,settings_worker,_platform:subscription})
}
async fn stop_construction(connected:&crate::services::connected::ConnectedServices,engine:AudioEngine,mut error:ServiceError)->ServiceError{
for result in [connected.shutdown().await,engine.shutdown().await]{if let Err(cleanup)=result{error.message.push_str(&format!("; cleanup failed: {cleanup}"));}}
error
}
fn services_failed(error:ServiceError)->ServiceError{ServiceError::new("services_initialization_failed",format!("Your profile is saved, but application services could not start: {}. Restart the app to resume the saved profile.",error.message))}
async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiver<RuntimeCommand>,mut cancelled:watch::Receiver<bool>,snapshots:watch::Sender<Arc<model::Snapshot>>,effects:mpsc::Sender<UiEffect>)->Result<()> {
let(events,mut service_events)=mpsc::channel(1024);let(controls,mut control_events)=mpsc::channel(1024);let mut state=AppState::default();let mut prompts:std::collections::VecDeque<Prompt>=Default::default();let mut jobs=tokio::task::JoinSet::new();let mut owner=None;
let inspected=bootstrap::Bootstrap::inspect(&config).await;let(mut bootstrap,mut profile)=match inspected{Ok(value)=>value,Err(error)=>{state.snapshot.bootstrap=BootstrapState::Failed;state.snapshot.error=error.message;state.snapshot.loading=false;publish(&runtime,&snapshots,&mut state);wait_failed(commands,cancelled).await?;return send_effect(&runtime,&effects,UiEffect::Quit).await;}};
bootstrap.present(&mut state,profile.as_ref())?;
if state.snapshot.bootstrap==BootstrapState::Ready{owner=Some(construct(&config,profile.take().unwrap(),runtime.clone(),events.clone(),cancelled.clone(),controls.clone()).await?);}
if state.snapshot.bootstrap==BootstrapState::Ready{owner=Some(construct(&config,profile.take().unwrap(),runtime.clone(),events.clone(),cancelled.clone(),controls.clone()).await.map_err(services_failed)?);}
publish(&runtime,&snapshots,&mut state);let mut tick=tokio::time::interval(Duration::from_millis(20));let mut dirty=true;let mut last_update=Instant::now();let mut update_gate=None;let mut relaunch=false;
let mut desktop_state=desktop_actions::DesktopState::default();let mut startup_done=false;
let mut settings_serial=0u64;
let mut onboarding:Option<tokio::task::JoinHandle<(bootstrap::Bootstrap,Result<Option<ProfileServices>>)>>=None;
let mut submission:Option<(String,Target)>=None;
loop {
tokio::select! {
_=cancelled.changed()=>{if *cancelled.borrow(){break}},
command=commands.recv()=>{let Some(command)=command else{break};if jobs.len()>=64&&matches!(&command,RuntimeCommand::Settings(_)|RuntimeCommand::Chat(_)|RuntimeCommand::Shell(ShellAction::Invoke{..})){state.snapshot.error="Too many pending application actions; complete or cancel the current dialog first".into();dirty=true;continue}match command {
RuntimeCommand::Shell(ShellAction::Cancel{editor_id,..})=>{if prompts.front().is_some_and(|p|p.form.id==editor_id){if let Some(prompt)=prompts.pop_front(){let _=prompt.answer.send(Err(ServiceError::new("cancelled","Dialog cancelled")));}state.snapshot.dialog=prompts.front().map(|p|p.form.clone());}else if owner.is_none(){state.snapshot.dialog=None;}dirty=true;},
RuntimeCommand::Shell(ShellAction::Cancel{editor_id,target})=>{
#[cfg(target_os="android")]
if owner.is_none()&&state.snapshot.profile_form.as_ref().is_some_and(|form|form.id==editor_id&&form.target==target)&&state.snapshot.dialog.is_none(){break}
if prompts.front().is_some_and(|p|p.form.id==editor_id){if let Some(prompt)=prompts.pop_front(){let _=prompt.answer.send(Err(ServiceError::new("cancelled","Dialog cancelled")));}state.snapshot.dialog=prompts.front().map(|p|p.form.clone());}else if owner.is_none(){state.snapshot.dialog=None;}dirty=true;
},
RuntimeCommand::Shell(ShellAction::Submit{editor_id,target,operation,values,confirmation})=>{
if prompts.front().is_some_and(|p|p.form.id==editor_id){let prompt=prompts.pop_front().unwrap();let answer=if prompt.form.target!=target||prompt.form.confirmation.as_ref().is_some_and(|c|c!=&confirmation){Err(context::changed())}else{Ok(values)};let result=answer.as_ref().map(|_|()).map_err(Clone::clone);let _=prompt.answer.send(answer);send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result}).await?;state.snapshot.dialog=prompts.front().map(|p|p.form.clone());dirty=true;continue}
if let Some(owner)=&owner{let ctx=owner.ctx.clone();let sender=events.clone();jobs.spawn(async move{let result=controller::dispatch(ctx,target.clone(),operation,values).await;let ack=result.as_ref().map(|_|()).map_err(Clone::clone);let _=sender.send(ServiceEvent::Effect(UiEffect::FormComplete{id:editor_id,target,result:ack})).await;let _=sender.send(ServiceEvent::Workflow(result)).await;});}
else{
let result=if let Some(existing)=profile.as_mut(){if operation==Operation::CreateProfile{let nickname=values.get("nickname").and_then(|v|if let FieldValue::Text(v)=v{Some(v.clone())}else{None}).unwrap_or_default();existing.identities.onboard(nickname.trim()).map(|_|None)}else{Err(ServiceError::new("profile_exists","Continue onboarding the initialized profile"))}}else{bootstrap.handle(&config,&target,operation,&values,confirmation==target.name).await};
if result.is_ok(){state.snapshot.dialog=None;}
match result{Ok(created)=>{if created.is_some(){profile=created}bootstrap.present(&mut state,profile.as_ref())?;if state.snapshot.bootstrap==BootstrapState::Ready{owner=Some(construct(&config,profile.take().unwrap(),runtime.clone(),events.clone(),cancelled.clone(),controls.clone()).await?);}send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result:Ok(())}).await?;},Err(error)=>{state.snapshot.error=error.message.clone();send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result:Err(error)}).await?;}}dirty=true;
if onboarding.is_some(){send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result:Err(ServiceError::new("profile_busy","Profile initialization is already running"))}).await?;continue}
let mut pending=bootstrap.clone();let config=config.clone();let existing=profile.take();let captured=target.clone();
submission=Some((editor_id,target));
onboarding=Some(tokio::spawn(async move{
let result=if operation==Operation::CreateProfile{pending.create(values,existing).await.map(Some)}
else if existing.is_some(){Err(ServiceError::new("profile_exists","Continue onboarding the initialized profile"))}
else{pending.handle(&config,&captured,operation,&values,confirmation==captured.name).await};
(pending,result)
}));
}
},
RuntimeCommand::Shell(action)=>{
@@ -122,8 +169,9 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
ShellAction::Page{target,offset}=>{state.query.offset=offset.min(u32::MAX as usize) as u32;if let Some(operation)=state.detail_operation{spawn_query(&mut jobs,events.clone(),ctx,target,operation,state.query.clone());}},
ShellAction::PaneWidths{sidebar,server}=>{let sender=events.clone();jobs.spawn(async move{let result=ctx.mutate(move|p|{p.prefs.set(serde_json::json!({"sidebarWidth":sidebar.round(),"serverPaneWidth":server.round()}))?;Ok(())}).await.map(|_|events::WorkflowResult::default());let _=sender.send(ServiceEvent::Workflow(result)).await;});},_=>{}
}}else if let ShellAction::Invoke{target,operation}=action{
if onboarding.is_some(){state.snapshot.error="Profile initialization is already running".into();dirty=true;continue}
if matches!(operation,Operation::ImportIdentity|Operation::ImportLegacyProfile|Operation::ConfirmOverwrite){state.snapshot.dialog=Some(bootstrap.confirmation_form(target,operation)?);}
else{match bootstrap.handle(&config,&target,operation,&Values::new(),false).await{Ok(created)=>{if created.is_some(){profile=created}bootstrap.present(&mut state,profile.as_ref())?;if state.snapshot.bootstrap==BootstrapState::Ready{owner=Some(construct(&config,profile.take().unwrap(),runtime.clone(),events.clone(),cancelled.clone(),controls.clone()).await?);}},Err(error)=>state.snapshot.error=error.message}}dirty=true;
else{match bootstrap.handle(&config,&target,operation,&Values::new(),false).await{Ok(created)=>{if created.is_some(){profile=created}bootstrap.present(&mut state,profile.as_ref())?;if state.snapshot.bootstrap==BootstrapState::Ready{owner=Some(construct(&config,profile.take().unwrap(),runtime.clone(),events.clone(),cancelled.clone(),controls.clone()).await.map_err(services_failed)?);}},Err(error)=>state.snapshot.error=error.message}}dirty=true;
}
},
RuntimeCommand::Settings(action)=>{if let Some(owner)=&owner{settings_serial=settings_serial.checked_add(1).ok_or_else(||failed("Settings request IDs exhausted"))?;state.snapshot.error.clear();state.snapshot.last_error=None;let pending=settings_queue::pending(&action,&state.snapshot);let request=settings_queue::Request{action,pending,serial:settings_serial};if let Err(error)=settings_queue::enqueue(&owner.ctx,&owner.settings,request){state.snapshot.settings_completed=settings_serial;state.snapshot.last_error=Some(error.clone());state.snapshot.error=error.message;}dirty=true;}},
@@ -132,8 +180,42 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
RuntimeCommand::Detached(_)=>{if let Some(owner)=&owner{if let Ok(mut notifications)=owner.ctx.notifications.lock(){let _=notifications.view_chat(None);}if let Err(error)=settings_actions::focus_lost(owner.ctx.clone()).await{state.snapshot.error=error.message;}dirty=true;}},
RuntimeCommand::WhisperStop(stop)=>{if let Some(owner)=&owner{let ctx=owner.ctx.clone();let sender=events.clone();jobs.spawn(async move{let result=ctx.request(&stop.key,stop.command).await.map(|_|events::WorkflowResult::default());let _=sender.send(ServiceEvent::Workflow(result)).await;});}},
RuntimeCommand::Platform(crate::platform::lifecycle::PlatformEvent::Quit)=>break,
#[cfg(target_os="android")]
RuntimeCommand::Platform(crate::platform::lifecycle::PlatformEvent::Insets{ui_generation,value}) if owner.is_none()=>{
if runtime.upgrade().is_some_and(|r|r.is_ui_current(ui_generation)){state.snapshot.insets=value;dirty=true;}
},
#[cfg(target_os="android")]
RuntimeCommand::Platform(crate::platform::lifecycle::PlatformEvent::Accessibility{ui_generation,text_scale,reduce_motion,high_contrast,..}) if owner.is_none()=>{
if runtime.upgrade().is_some_and(|r|r.is_ui_current(ui_generation))&&text_scale.is_finite(){state.snapshot.text_scale=text_scale.clamp(0.5,4.);state.snapshot.reduced_motion=reduce_motion;state.snapshot.high_contrast=high_contrast;dirty=true;}
},
RuntimeCommand::Platform(event)=>{if let Some(owner)=&owner{match platform(&owner.ctx,&runtime,&mut state,event).await{Ok(true)=>break,Ok(false)=>{},Err(error)=>state.snapshot.error=error.message}dirty=true;}},
}},
completed=async{onboarding.as_mut().expect("pending onboarding").await},if onboarding.is_some()=>{
onboarding=None;let(editor_id,target)=submission.take().expect("onboarding submission");
let result=match completed{Ok((updated,result))=>{bootstrap=updated;result},Err(error)=>Err(ServiceError::new("profile_worker",format!("Profile initialization worker stopped: {error}")))};
let result=match result{
Ok(created)=>{
if created.is_some(){profile=created}
match bootstrap.present(&mut state,profile.as_ref()){
Ok(()) if state.snapshot.bootstrap==BootstrapState::Ready=>{
match construct(&config,profile.take().expect("ready profile"),runtime.clone(),events.clone(),cancelled.clone(),controls.clone()).await{
Ok(created)=>{owner=Some(created);Ok(())},
Err(error)=>{
let error=services_failed(error);
send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result:Err(error.clone())}).await?;
return Err(error)
}
}
},
result=>result,
}
},
Err(error)=>Err(error),
};
if let Err(error)=&result{state.snapshot.error=error.message.clone();state.snapshot.last_error=Some(error.clone());}
else{state.snapshot.dialog=None;state.snapshot.error.clear();state.snapshot.last_error=None;}
send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result}).await?;dirty=true;
},
event=control_events.recv()=>{if let(Some(owner),Some(event))=(&owner,event){if let Err(error)=control(&owner.ctx,event).await{state.snapshot.error=error.message;}dirty=true;}},
event=service_events.recv()=>{if let Some(event)=event{match event{
ServiceEvent::Changed=>dirty=true,
@@ -159,8 +241,7 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
if let Some(owner)=&owner{
while let Ok(event)=owner.audio_events.try_recv(){audio_event(&owner.ctx,&mut state,event);dirty=true;}
if let Err(error)=owner.ctx.tick_transmission().await{state.snapshot.error=error.message;dirty=true;}
let snapshot=owner.ctx.connected.connections.snapshot();let current=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).filter(|entry|entry.is_connected()).map(|entry|entry.key.clone());let configured=owner.ctx.transmission.lock().map_err(|_|failed("Transmission state unavailable"))?.key.clone();
if current!=configured&&owner.ctx.audio_configuration.try_lock().is_ok(){if current.is_some(){if let Err(error)=owner.ctx.refresh_capture().await{state.snapshot.error=error.message;}}else{controller::release_immediate(&owner.ctx);owner.ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;owner.ctx.transmission.lock().map_err(|_|failed("Transmission state unavailable"))?.key=None;}dirty=true;}
match owner.ctx.refresh_capture_owner_changed().await{Ok(changed)=>dirty|=changed,Err(error)=>{state.snapshot.error=error.message;dirty=true;}}
#[cfg(not(any(target_os="android",target_os="ios")))]
{let key_events={let mut keys=owner.ctx.keys.lock().await;let mut events=vec![];let context::KeyState{runtime,global,..}=&mut *keys;if let Some(global)=global{if let Err(error)=global.dispatch(runtime,|event|events.push(event)){state.snapshot.error=error.message;}}events};if !key_events.is_empty(){owner.ctx.apply_key_events(key_events).await?;}}
if !startup_done&&config.allow_os_actions&&runtime.upgrade().and_then(|r|r.current_ui_generation()).is_some(){
@@ -180,6 +261,9 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
}
if let Some(runtime)=runtime.upgrade(){runtime.cancel.send_replace(true);runtime.release_held();}
for prompt in prompts{let _=prompt.answer.send(Err(context::closed()));}
// A blocking storage commit cannot be cancelled safely. Join it before releasing the runtime
// so a restart cannot race its profile lease or replace a just-committed identity.
if let Some(onboarding)=onboarding{onboarding.await.map_err(|error|ServiceError::new("profile_worker",format!("Profile initialization worker stopped: {error}")))?;}
if let Some(owner)=owner{
owner.ctx.phishing.stop();owner.ctx.badges.stop();owner.ctx.updates.stop();for cancel in owner.ctx.improvements.lock().map_err(|_|failed("Identity jobs unavailable"))?.values(){cancel.store(true,Ordering::Release);}
jobs.abort_all();while jobs.join_next().await.is_some(){}
@@ -215,3 +299,9 @@ async fn isolated_settings(ctx:Arc<RuntimeServices>,action:crate::ui::settings::
SettingsAction::Invoke(O::Reload(Category::Audio))=>return Err(ServiceError::new("os_actions_disabled","Physical audio enumeration is disabled in this isolated runtime")),_=>{}
}}settings_actions::handle(ctx,action).await
}
#[cfg(test)]
mod bootstrap_tests;
#[cfg(test)]
mod lifecycle_tests;
+46 -2
View File
@@ -11,6 +11,7 @@ pub struct Snapshot {
pub audio_input_starts:u64,pub audio_output_starts:u64,
pub connections:Arc<ConnectionsSnapshot>,pub tabs:Vec<Tab>,pub tree:Vec<Entry>,pub bookmarks:Vec<Entry>,pub contacts:Vec<Entry>,
pub detail:Detail,pub actions:Vec<Action>,pub voice:Option<Voice>,pub profile_form:Option<Form>,pub dialog:Option<Form>,
pub room:Room,
pub last_error:Option<crate::services::ServiceError>,pub settings_completed:u64,
pub status:String,pub error:String,pub loading:bool,pub destination:Destination,
pub settings:SettingsSnapshot,pub settings_view:ViewState,pub chat:ChatPresentation,
@@ -22,7 +23,7 @@ pub struct Snapshot {
pub insets:crate::platform::lifecycle::Insets,pub text_scale:f32,pub reduced_motion:bool,pub high_contrast:bool,
}
impl Default for Snapshot {
fn default()->Self{Self{revision:0,ready:false,last_error:None,settings_completed:0,audio_input_active:false,audio_output_active:false,audio_input_starts:0,audio_output_starts:0,bootstrap:BootstrapState::Loading,root:None,catalog:Catalog::default(),connections:Arc::default(),tabs:vec![],tree:vec![],bookmarks:vec![],contacts:vec![],detail:Detail::default(),actions:vec![],voice:None,profile_form:None,dialog:None,status:String::new(),error:String::new(),loading:true,destination:Destination::Servers,settings:SettingsSnapshot::default(),settings_view:ViewState::default(),chat:ChatPresentation::default(),streams:vec![],#[cfg(feature="webrtc")]frames:vec![],theme:None,theme_revision:0,theme_fonts:vec![],insets:Default::default(),text_scale:1.,reduced_motion:false,high_contrast:false}}
fn default()->Self{Self{revision:0,ready:false,last_error:None,settings_completed:0,audio_input_active:false,audio_output_active:false,audio_input_starts:0,audio_output_starts:0,bootstrap:BootstrapState::Loading,root:None,catalog:Catalog::default(),connections:Arc::default(),tabs:vec![],tree:vec![],bookmarks:vec![],contacts:vec![],detail:Detail::default(),actions:vec![],voice:None,room:Room::default(),profile_form:None,dialog:None,status:String::new(),error:String::new(),loading:true,destination:Destination::Servers,settings:SettingsSnapshot::default(),settings_view:ViewState::default(),chat:ChatPresentation::default(),streams:vec![],#[cfg(feature="webrtc")]frames:vec![],theme:None,theme_revision:0,theme_fonts:vec![],insets:Default::default(),text_scale:1.,reduced_motion:false,high_contrast:false}}
}
pub struct AppState {
pub snapshot:Snapshot,pub selected:Option<Target>,pub expanded:HashSet<(String,u64)>,pub folder:Option<String>,
@@ -54,7 +55,20 @@ impl AppState {
let mut entry=entry(target.clone(),"server".into(),0);entry.expandable=true;entry.expanded=true;entry.actions=actions(&target,&[Operation::ServerInfo,Operation::ServerEdit,Operation::ServerChat,Operation::ServerPermissions,Operation::ServerBans,Operation::ServerKeys,Operation::ServerPasswords,Operation::ServerIcons,Operation::ServerClients,Operation::ServerLog,Operation::ChannelCreate,Operation::SubscribeAll,Operation::UnsubscribeAll,Operation::TransferList,Operation::RecordingOpen,Operation::SnapshotExport,Operation::SnapshotChoose,Operation::KeyUse,Operation::TalkQueue,Operation::CaptureChoose],&c);self.snapshot.tree.push(entry);
let mut visited=HashSet::new();self.channel_children(ctx,&connection.key,server,0,1,&mut visited,&c);
}}
self.snapshot.voice=connections.input_id.as_deref().and_then(|id|connections.get(id)).filter(|s|s.is_connected()).map(|s|Voice{target:Target{session:Some(s.key.clone()),entity:Entity::Connection,name:s.address.clone(),own_channel_id:s.server.as_ref().and_then(|v|v["own_channel_id"].as_u64())},title:s.server.as_ref().and_then(|v|v["server"]["name"].as_str()).unwrap_or(&s.address).into(),muted:s.audio.input_muted,deafened:s.audio.output_muted,transmitting:s.audio.transmitting,ptt_enabled:prefs["pttEnabled"]==true&&!s.audio.input_muted,status:format!("{:?}",s.state)});
self.snapshot.voice=connections.input_id.as_deref().and_then(|id|connections.get(id)).filter(|s|s.is_connected()).map(|s|{
let enabled=ctx.microphone_enabled(&s.key);
Voice{target:Target{session:Some(s.key.clone()),entity:Entity::Connection,name:s.address.clone(),own_channel_id:s.server.as_ref().and_then(|v|v["own_channel_id"].as_u64())},title:s.server.as_ref().and_then(|v|v["server"]["name"].as_str()).unwrap_or(&s.address).into(),muted:!enabled,deafened:s.audio.output_muted,transmitting:enabled&&s.audio.transmitting,ptt_enabled:prefs["pttEnabled"]==true&&enabled,status:format!("{:?}",s.state)}
});
#[cfg(target_os="android")]
if let Some(voice)=&mut self.snapshot.voice {
if let Some(channel)=voice.target.session.as_ref().and_then(|key|connections.get(&key.connection_id))
.and_then(|connection|connection.server.as_ref())
.and_then(|server|server["channels"].as_array().and_then(|channels|channels.iter().find(|channel|channel["id"].as_u64()==server["own_channel_id"].as_u64())))
.and_then(|channel|channel["name"].as_str()) {
voice.title=channel.into();
voice.status=c.text(if voice.transmitting{"native.room.speaking"}else if voice.deafened{"native.room.sound_off"}else if voice.muted{"native.room.listening"}else{"native.room.microphone_on"});
}
}
self.snapshot.actions=actions(&Target::application(),&[Operation::NewConnection,Operation::BookmarkCreate,Operation::BookmarkFolderCreate,Operation::ContactAdd,Operation::OpenLogs],&c);
self.snapshot.bookmarks.clear();
for folder in prefs["bookmarkFolders"].as_array().into_iter().flatten(){if folder["parent"].as_str()!=self.folder.as_deref(){continue}if let Some(id)=folder["id"].as_str(){let target=Target{entity:Entity::BookmarkFolder(id.into()),name:folder["name"].as_str().unwrap_or_default().into(),..Target::application()};let mut e=entry(target.clone(),format!("folder:{id}"),0);e.actions=actions(&target,&[Operation::BookmarkFolderOpen,Operation::BookmarkFolderRename,Operation::BookmarkFolderDelete],&c);self.snapshot.bookmarks.push(e);}}
@@ -62,8 +76,38 @@ impl AppState {
for bookmark in prefs["savedServers"].as_array().into_iter().flatten(){if bookmark["folder"].as_str()!=self.folder.as_deref(){continue}if let Some(id)=bookmark["id"].as_str(){let target=Target{entity:Entity::Bookmark(id.into()),name:bookmark["name"].as_str().unwrap_or_default().into(),..Target::application()};let mut e=entry(target.clone(),format!("bookmark:{id}"),0);e.subtitle=bookmark["address"].as_str().unwrap_or_default().into();e.actions=actions(&target,&[Operation::BookmarkConnect,Operation::BookmarkEdit,Operation::BookmarkRename,Operation::BookmarkDuplicate,Operation::BookmarkMove,Operation::BookmarkPasswordSet,Operation::BookmarkPasswordReveal,Operation::BookmarkPasswordClear,Operation::BookmarkDelete],&c);self.snapshot.bookmarks.push(e);}}
self.snapshot.contacts.clear();for contact in prefs["contacts"].as_array().into_iter().flatten(){if let Some(uid)=contact["uid"].as_str(){let target=Target{entity:Entity::Contact(uid.into()),name:contact["alias"].as_str().filter(|s|!s.is_empty()).or_else(||contact["name"].as_str()).unwrap_or(uid).into(),..Target::application()};let mut e=entry(target.clone(),format!("contact:{uid}"),0);e.subtitle=uid.into();e.actions=actions(&target,&[Operation::ContactChat,Operation::ContactRename,Operation::ContactIgnore,Operation::ContactUnignore,Operation::ContactRemove],&c);self.snapshot.contacts.push(e);}}
if self.detail_target.as_ref().is_some_and(|t|ctx.require_target(t).is_err()){self.detail_target=None;self.snapshot.detail=Detail::default();}
#[cfg(target_os="android")]
if self.snapshot.destination!=Destination::Settings {
super::settings_actions::cancel_palette_preview(ctx)?;
if self.snapshot.settings_view.page()==crate::ui::settings::Page::Palette {self.snapshot.settings_view.pages.clear();}
}
self.snapshot.settings=super::settings_actions::project(ctx,&self.snapshot.settings_view)?;
self.snapshot.chat=super::chat_actions::project(ctx).await?;
#[cfg(target_os="android")]
{
self.snapshot.room=Room::default();
if let Some(connection)=viewed.filter(|connection|connection.is_connected()) {
if let Some(server)=connection.server.as_ref() {
if let Some(channel_id)=server["own_channel_id"].as_u64().filter(|id|*id>0) {
let room=&mut self.snapshot.room;
room.server=server["server"]["name"].as_str().unwrap_or(&connection.address).into();
room.title=server["channels"].as_array().into_iter().flatten().find(|channel|channel["id"].as_u64()==Some(channel_id)).and_then(|channel|channel["name"].as_str()).unwrap_or_default().into();
room.target=Some(Target{session:Some(connection.key.clone()),entity:Entity::Channel{id:channel_id},name:room.title.clone(),own_channel_id:Some(channel_id)});
for client in server["clients"].as_array().into_iter().flatten().filter(|client|client["channel_id"].as_u64()==Some(channel_id)) {
let (Some(id),Some(uid))=(client["id"].as_u64().and_then(|id|u16::try_from(id).ok()),client["uid"].as_str()) else {continue};
let target=Target{session:Some(connection.key.clone()),entity:Entity::Client{id,uid:uid.into(),channel_id},name:client["nickname"].as_str().unwrap_or_default().into(),own_channel_id:Some(channel_id)};
let mut participant=entry(target.clone(),format!("client:{id}:{uid}"),0);
participant.muted=client["input_muted"]==true;
participant.talking=if client["id"]==server["own_client_id"] {connection.audio.transmitting && ctx.microphone_enabled(&connection.key)} else {connection.talking.contains(&id)};
participant.subtitle=c.text(if participant.talking{"native.room.speaking"}else if participant.muted{"native.room.microphone_off"}else{"native.room.listening"});
participant.actions=actions(&target,&[Operation::ClientVolume,Operation::ClientPrivateChat,Operation::ClientInfo,Operation::ClientConnectionInfo,Operation::ClientPoke,Operation::ClientWhisperAdd,Operation::ClientMove,Operation::ClientKickChannel,Operation::ClientKickServer,Operation::ClientBan,Operation::ClientCommander,Operation::ClientServerGroupAdd,Operation::ClientServerGroupRemove,Operation::ClientChannelGroupSet,Operation::ClientPermissions,Operation::ClientChannelPermissionSet,Operation::ClientChannelPermissionRemove,Operation::ClientAvatarChoose,Operation::ClientAvatarDelete,Operation::TalkGrant,Operation::TalkRevoke,Operation::ContactAdd],&c);
room.participants.push(participant);
}
room.chat_id=self.snapshot.chat.tabs.iter().find(|tab|tab.target.session==connection.key && matches!(tab.target.target,crate::ui::chat::ChatTarget::Channel(id) if id==channel_id)).map(|tab|format!("{}\u{1f}{}\u{1f}{:?}\u{1f}{}",tab.target.scope.base.identity,tab.target.scope.base.server,tab.target.scope.kind,tab.target.scope.key)).unwrap_or_default();
}
}
}
}
self.snapshot.streams=super::stream_actions::project(ctx).await?;
#[cfg(feature="webrtc")] {self.snapshot.frames=super::stream_actions::frame_sources(ctx).await;}
self.snapshot.connections=connections;self.snapshot.loading=false;self.snapshot.bootstrap=BootstrapState::Ready;Ok(())
+13 -1
View File
@@ -26,7 +26,19 @@ pub async fn on_control(ctx:&RuntimeServices,key:&SessionKey,value:&Value)->Resu
}
pub async fn execute(ctx:Arc<RuntimeServices>,effect:NotificationEffect)->Result<()> {
match effect {
NotificationEffect::Sound{session,sound,output_revision,..}=>{if ctx.policy.allow_os_actions&&ctx.output_granted.load(std::sync::atomic::Ordering::Acquire){ctx.require_key(&session,true)?;ctx.audio.request(crate::media::audio::engine::AudioCommand::Notify{key:session,name:sound.file.into(),revision:output_revision}).await?;}},
NotificationEffect::Sound{session,sound,output_revision,..}=>{
let _configuration=ctx.audio_configuration.lock().await;
if ctx.policy.allow_os_actions&&ctx.output_granted.load(std::sync::atomic::Ordering::Acquire){
ctx.require_key(&session,true)?;
#[cfg(target_os="android")]
if !crate::platform::android::voice_audio_allowed(&session,false){return Ok(())}
// A voice-follow sound may use an acknowledged voice route, never
// open one itself during Connect, Android interruption, or failure.
let voice=ctx.profile()?.prefs.get()["notificationDeviceId"]=="voice";
if voice&&!ctx.audio.output_active(){return Ok(())}
ctx.audio.request(crate::media::audio::engine::AudioCommand::Notify{key:session,name:sound.file.into(),revision:output_revision}).await?;
}
},
NotificationEffect::System{session,title_key,name,body,..}=>{ctx.require_key(&session,true)?;ctx.policy.check()?;let catalog=super::controller::catalog(&ctx)?;let title=catalog.format(title_key,&[("name",&name)]).chars().take(200).collect::<String>();
#[cfg(not(any(target_os="android",target_os="ios")))]crate::platform::desktop::notify(crate::platform::desktop::Notification{key:session,action:NotificationAction::Show,title,body},ctx.policy).await?;
#[cfg(target_os="android")] {let lease=crate::platform::android::notify(session,&title,&body,ctx.policy)?;let mut retained=ctx.android_notifications.lock().map_err(|_|ServiceError::new("notification_owner","Notification lease owner stopped"))?;while retained.len()>=32{retained.pop_front();}retained.push_back(lease);}
+9 -3
View File
@@ -11,9 +11,11 @@ mod themes;
mod projection;
mod whisper_preview;
pub use audio::sync_audio;
pub(crate) use audio::{sync_notifications,capture_settings,gate as capture_gate};
pub(crate) use audio::{activate_microphone,sync_notifications,capture_settings,gate as capture_gate};
pub use keys::{sync_keys,physical_key,focus_lost};
pub use projection::project;
/// Called by the shell projection on Android whenever the destination leaves Settings.
pub fn cancel_palette_preview(ctx:&RuntimeServices)->Result<()> {themes::cancel_palette(ctx)}
fn bad(message:impl Into<String>)->ServiceError{ServiceError::new("bad_request",message)}
fn lock<T>(value:&std::sync::Mutex<T>)->Result<MutexGuard<'_,T>>{value.lock().map_err(|_|ServiceError::new("settings_unavailable","Settings state is unavailable"))}
@@ -48,10 +50,14 @@ pub async fn handle(ctx:Arc<RuntimeServices>,action:SettingsAction)->Result<Work
async fn invoke(ctx:Arc<RuntimeServices>,op:Operation)->Result<WorkflowResult>{
use Operation::*;
match op {
Navigate(nav)=>{match &nav{Navigation::Category(Category::About)|Navigation::Page(Page::Changelog|Page::Licenses|Page::Diagnostics)=>projection::reload_about(&ctx).await?,Navigation::Category(Category::Appearance)|Navigation::Page(Page::Themes)=>themes::reload(&ctx,false).await?,Navigation::Category(Category::Audio|Category::Notifications)=>ctx.audio.send(crate::media::audio::engine::AudioCommand::Enumerate)?,Navigation::Category(Category::OsSpecific)=>ctx.refresh_os_settings().await?,_=>{}}Ok(WorkflowResult::effect(UiEffect::SettingsNavigate(nav)))},
Navigate(nav)=>{
if cfg!(target_os="android") {if matches!(&nav,Navigation::Page(Page::Palette)){themes::begin_palette(&ctx)?;}else if matches!(&nav,Navigation::Back|Navigation::Category(_)|Navigation::Page(_)){themes::cancel_palette(&ctx)?;}}
match &nav{Navigation::Category(Category::About)|Navigation::Page(Page::Changelog|Page::Licenses|Page::Diagnostics)=>projection::reload_about(&ctx).await?,Navigation::Category(Category::Appearance)|Navigation::Page(Page::Themes)=>themes::reload(&ctx,false).await?,Navigation::Category(Category::Audio|Category::Notifications)=>ctx.audio.send(crate::media::audio::engine::AudioCommand::Enumerate)?,Navigation::Category(Category::OsSpecific)=>ctx.refresh_os_settings().await?,_=>{}}
Ok(WorkflowResult::effect(UiEffect::SettingsNavigate(nav)))
},
Reload(category)=>{match category{Category::Audio=>ctx.audio.send(crate::media::audio::engine::AudioCommand::Enumerate)?,Category::Appearance=>themes::reload(&ctx,true).await?,Category::About=>projection::reload_about(&ctx).await?,Category::OsSpecific=>ctx.refresh_os_settings().await?,_=>{}}ctx.changed().await?;done()},
IdentityCreate|IdentityDefault(_)|IdentityDelete(_)|IdentityImport|IdentityExport(_)|IdentityCopyUid(_)|IdentityImprove(_)|IdentityCancelImprove(_)=>identities::invoke(ctx,op).await,
ThemeSelect(_)|ThemePreview(_)|ThemeReload|ThemeInstall|ThemeOpenDirectory(_)|ThemeLink{..}=>themes::invoke(ctx,op).await,
ThemeSelect(_)|ThemePreview(_)|ThemeReload|ThemeInstall|ThemeOpenDirectory(_)|ThemeLink{..}|PalettePreset(_)|PaletteSave|PaletteCancel=>themes::invoke(ctx,op).await,
SelectDevice{..}|MapDevice{..}|NewDevice{..}|CopyDspToTemplate{..}|ApplyDspTemplate{..}|AudioTest(_)|PreviewNotification(_)=>audio::invoke(ctx,op).await,
CapturePtt|KeyProfileCreate|KeyProfileActivate(_)|KeyProfileDelete(_)|KeyCapture{..}|KeyCaptureDone|KeyCaptureCancel|KeyRemove{..}=>keys::invoke(ctx,op).await,
WhisperCreate|WhisperDelete(_)|WhisperRemoveEntry{..}|WhisperAddEntry{..}|WhisperPickServer{..}|WhisperPickGroup{..}|WhisperOverlay(_)=>preferences::whisper(ctx,op).await,
+171 -27
View File
@@ -4,45 +4,138 @@ use teamspeach_denoise::CaptureSettings;
pub(super) fn dsp_key(kind:DeviceKind)->Result<&'static str>{match kind{DeviceKind::Input=>Ok("inputDsp"),DeviceKind::Output=>Ok("outputDsp"),DeviceKind::Notification=>Err(bad("Notification devices have no voice DSP profile"))}}
fn selection_key(kind:DeviceKind)->&'static str{match kind{DeviceKind::Input=>"inputDeviceId",DeviceKind::Output=>"outputDeviceId",DeviceKind::Notification=>"notificationDeviceId"}}
fn selection(id:&str)->DeviceSelection{if id.is_empty(){DeviceSelection::SystemDefault}else{DeviceSelection::Exact(id.into())}}
fn selection(id:&str)->Result<DeviceSelection>{
#[cfg(target_os="android")]
{return crate::platform::android::voice_device_selection(id)}
#[cfg(not(target_os="android"))]
Ok(if id.is_empty(){DeviceSelection::SystemDefault}else{DeviceSelection::Exact(id.into())})
}
pub(super) fn profile<'a>(prefs:&'a Value,kind:DeviceKind)->&'a Value{let key=if kind==DeviceKind::Input{"inputDsp"}else{"outputDsp"};let id=prefs[selection_key(kind)].as_str().filter(|s|!s.is_empty()).unwrap_or("default");prefs[key]["devices"].get(id).unwrap_or(&prefs[key]["template"])}
pub(crate) fn capture_settings(prefs:&Value)->CaptureSettings{let input=profile(prefs,DeviceKind::Input);let output=profile(prefs,DeviceKind::Output);CaptureSettings{echo_cancellation:output["aec"]==true,noise_suppression:if input["denoise"]==true{Some(input["denoiseLevel"].as_u64().unwrap_or(1) as u8)}else{None},automatic_gain_control:input["agc"]==true}}
pub(crate) fn gate(prefs:&Value)->Option<teamspeach_core::vad::GateMode>{use teamspeach_core::vad::{GateMode,Sensitivity};let input=profile(prefs,DeviceKind::Input);if input["vad"]!=true{return None}let sensitivity=match input["vadSensitivity"].as_str(){Some("high")=>Sensitivity::High,Some("low")=>Sensitivity::Low,_=>Sensitivity::Normal};let level_db=input["vadLevel"].as_f64().unwrap_or(-30.) as f32;Some(match input["vadMode"].as_str(){Some("volume_gate")=>GateMode::VolumeGate{level_db},Some("hybrid")=>GateMode::Hybrid{sensitivity,level_db},_=>GateMode::Automatic(sensitivity)})}
/// Loading preferences never opens hardware. Reconfiguration only resumes previously active, granted routes.
/// Loading preferences never opens hardware. Reconfiguration resumes only retained, granted intent.
pub async fn sync_audio(ctx:Arc<RuntimeServices>)->Result<()> {
if lock(&ctx.microphone_test_resume)?.is_some(){return Err(ServiceError::new("microphone_test_active","Finish the private microphone test before applying voice settings"))}
let active=(ctx.audio_input_active.load(Ordering::Acquire),ctx.audio_output_active.load(Ordering::Acquire));
sync_audio_to(ctx,active).await
let configuration=ctx.audio_configuration.lock().await;
sync_audio_to(&ctx,None,None,&configuration).await
}
async fn sync_audio_to(ctx:Arc<RuntimeServices>,active:(bool,bool))->Result<()> {
let _configuration=ctx.audio_configuration.lock().await;
/// Explicit activation carries resume intent separately from acknowledged hardware state.
pub(crate) async fn activate_microphone(ctx:Arc<RuntimeServices>,key:&crate::app::connections::SessionKey,configuration:&tokio::sync::MutexGuard<'_,()>)->Result<()> {
sync_audio_to(&ctx,Some((true,true)),Some(key),configuration).await
}
async fn sync_audio_to(ctx:&Arc<RuntimeServices>,resume:Option<(bool,bool)>,expected_owner:Option<&crate::app::connections::SessionKey>,_configuration:&tokio::sync::MutexGuard<'_,()>)->Result<()> {
#[cfg(target_os="android")]
let route_started=std::time::Instant::now();
let mut stage="validate_activation";
let mut stage_key=expected_owner.cloned();
let result:Result<()>=async {
if lock(&ctx.microphone_test_resume)?.is_some(){return Err(ServiceError::new("microphone_test_active","Finish the private microphone test before applying voice settings"))}
let (prefs,allowed)={let p=ctx.profile()?;(p.prefs.get(),p.prefs.capture_allowed(p.migration.is_some()))};
let snapshot=ctx.connected.connections.snapshot();let owner=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).filter(|s|s.is_connected()).map(|s|s.key.clone());
if let Some(expected)=expected_owner{ctx.require_key(expected,true)?;if owner.as_ref()!=Some(expected){return Err(super::super::context::changed())}}
if stage_key.is_none(){stage_key=owner.clone();}
let (revision,desired)={let mut state=lock(&ctx.transmission)?;state.observe_owner(owner.clone());(state.revision,state.capture_desired)};
let active=resume.map(|(input,output)|(input&&desired,output)).unwrap_or_else(||(desired,ctx.audio_output_active.load(Ordering::Acquire)));
#[cfg(target_os="android")]
let active=(active.0&&owner.as_ref().is_some_and(|key|crate::platform::android::voice_audio_allowed(key,true)),active.1&&snapshot.connections.iter().any(|session|crate::platform::android::voice_audio_allowed(&session.key,false)));
if expected_owner.is_some()&&(!active.0||!allowed||!ctx.microphone_granted.load(Ordering::Acquire)){return Err(ServiceError::new("audio_activation_revoked","Microphone authorization ended before audio startup; enable it explicitly"))}
// Validate before any capture open, but still restore permitted RX when the
// desired capture transport is incompatible. Preferences remain exact intent.
#[cfg(target_os="android")]
let capture_pair=if active.0 {crate::platform::android::validate_voice_capture_pair(prefs["inputDeviceId"].as_str().unwrap_or_default(),prefs["outputDeviceId"].as_str().unwrap_or_default(),true)}else{Ok(())};
ctx.audio.revoke_capture();
stage="configure_workflow";
ctx.connected.connections.configure_workflow(WorkflowSettings{auto_enable_microphone:prefs["autoEnableMicrophone"]==true,auto_reactivate_previous:prefs["autoReactivateMicOnPreviousTarget"]==true}).await.map_err(super::super::context::connection_error)?;
let selected=(prefs["inputDeviceId"].as_str().unwrap_or_default().to_owned(),prefs["outputDeviceId"].as_str().unwrap_or_default().to_owned());
let selected=(selection(prefs["inputDeviceId"].as_str().unwrap_or_default())?,selection(prefs["outputDeviceId"].as_str().unwrap_or_default())?);
let selected_id=|selection:&DeviceSelection|match selection{DeviceSelection::SystemDefault=>String::new(),DeviceSelection::Exact(id)=>id.clone()};
// Cache the exact applied selections; phone endpoints are not default aliases.
let applied=(selected_id(&selected.0),selected_id(&selected.1));
let previous=lock(&ctx.applied_audio_selections)?.clone();
if previous.as_ref().is_none_or(|p|p.0!=selected.0){ctx.audio.request(AudioCommand::SelectInput(selection(&selected.0))).await?;}
if previous.as_ref().is_none_or(|p|p.1!=selected.1){ctx.audio.request(AudioCommand::SelectOutput(selection(&selected.1))).await?;}
*lock(&ctx.applied_audio_selections)?=Some(selected);
if previous.as_ref().is_none_or(|p|p.0!=applied.0){stage="select_input";ctx.audio.request(AudioCommand::SelectInput(selected.0)).await?;}
if previous.as_ref().is_none_or(|p|p.1!=applied.1){stage="select_output";ctx.audio.request(AudioCommand::SelectOutput(selected.1)).await?;}
*lock(&ctx.applied_audio_selections)?=Some(applied);
let output=profile(&prefs,DeviceKind::Output);
stage="playback_settings";
ctx.audio.request(AudioCommand::SetPlaybackDsp(PlaybackDsp{comfort_noise:output["comfortNoise"]==true,comfort_noise_level_db:output["comfortNoiseLevel"].as_f64().unwrap_or(-60.) as f32,echo_reduction_db:output["echoReduction"].as_f64().unwrap_or(0.) as f32})).await?;
stage="voice_gain";
let level=prefs["outputLevelDb"].as_f64().unwrap_or(0.);ctx.audio.request(AudioCommand::SetVoiceGain(if level<=-200.{0.}else{10f32.powf(level as f32/20.)})).await?;
stage="typing_settings";
ctx.audio.request(AudioCommand::TypingEnabled(profile(&prefs,DeviceKind::Input)["typing"]==true)).await?;
sync_notifications(&ctx).await?;
if active.1&&ctx.output_granted.load(Ordering::Acquire){ctx.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await?;}
// Resolve/open authorized voice output before configuring voice-follow notifications.
// Otherwise a retained Explicit sink can reject recovery before StartOutput repairs it.
#[cfg(target_os="android")]
let mut playback_error=None;
if active.1&&ctx.output_granted.load(Ordering::Acquire){
stage="start_output";
let playback=ctx.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await;
#[cfg(target_os="android")]
{playback_error=playback.err().map(|error|("start_output",error));}
#[cfg(not(target_os="android"))]
playback?;
ctx.audio_output_active.store(ctx.audio.output_active(),Ordering::Release);
}
stage="notification_route";
let notifications=sync_notifications(&ctx).await;
#[cfg(target_os="android")]
if let Err(error)=notifications{if playback_error.is_none(){playback_error=Some(("notification_route",error));}}
#[cfg(not(target_os="android"))]
notifications?;
stage="server_playback_dsp";
for session in snapshot.connections.iter().filter(|s|s.is_connected()) {ctx.request(&session.key,teamspeach_core::protocol::Command::SetPlaybackDsp{agc:output["agc"]==true}).await?;ctx.require_key(&session.key,true)?;}
#[cfg(target_os="android")]
{stage="capture_transport";capture_pair?;}
if let Some(key)=owner {
stage="configure_capture";
ctx.require_key(&key,true)?;
if ctx.connected.connections.snapshot().input_id.as_deref()!=Some(key.connection_id.as_str()){return Err(super::super::context::changed())}
let mut config=ctx.capture_configuration(&key,&prefs)?;config.vad=gate(&prefs);config.input_muted|=!allowed||!ctx.microphone_granted.load(Ordering::Acquire);
lock(&ctx.transmission)?.capture_intent(&key,revision)?;
let mut config=ctx.capture_configuration(&key,&prefs)?;config.vad=gate(&prefs);config.input_muted|=!active.0||!allowed||!ctx.microphone_granted.load(Ordering::Acquire);
let permit=ctx.connected.connections.set_input(Some(&key),config).await.map_err(super::super::context::connection_error)?;
let current=ctx.connected.connections.snapshot();lock(&ctx.transmission)?.observed_capture=Some((current.capture_revision,ctx.connected.connections.current_capture_permit(),current.capture_configuration));
ctx.require_key(&key,true)?;
if let Some(permit)=permit{ctx.audio.request(AudioCommand::BindPermit{permit,settings:capture_settings(&prefs)}).await?;ctx.require_key(&key,true)?;if active.0&&allowed&&ctx.microphone_granted.load(Ordering::Acquire){ctx.audio.request(AudioCommand::StartInput(StartPermission::Granted)).await?;ctx.audio_input_active.store(true,Ordering::Release);ctx.refresh_transmission_gate(&key,&prefs)?;}}
if ctx.connected.connections.snapshot().input_id.as_deref()!=Some(key.connection_id.as_str()){return Err(super::super::context::changed())}
lock(&ctx.transmission)?.capture_intent(&key,revision)?;
if let Some(permit)=permit{
if ctx.connected.connections.current_capture_permit().as_ref()!=Some(&permit){return Err(super::super::context::changed())}
stage="bind_permit";ctx.audio.request(AudioCommand::BindPermit{permit:permit.clone(),settings:capture_settings(&prefs)}).await?;ctx.require_key(&key,true)?;
if ctx.connected.connections.current_capture_permit().as_ref()!=Some(&permit){ctx.audio.revoke_local_capture();return Err(super::super::context::changed())}
{let mut state=lock(&ctx.transmission)?;if let Err(error)=state.acknowledge_capture_configuration(&key,revision,config,true){ctx.audio.revoke_capture();return Err(error)}state.bound_permit=Some(permit.clone());}
if active.0&&allowed&&ctx.microphone_granted.load(Ordering::Acquire){
stage="start_input";ctx.audio.request(AudioCommand::StartInput(StartPermission::Granted)).await?;
if ctx.connected.connections.current_capture_permit().as_ref()!=Some(&permit){ctx.audio.revoke_local_capture();lock(&ctx.transmission)?.bound_permit=None;return Err(super::super::context::changed())}
if let Err(error)=lock(&ctx.transmission)?.capture_intent(&key,revision){ctx.audio.revoke_capture();return Err(error)}
ctx.audio_input_active.store(ctx.audio.input_active(),Ordering::Release);
stage="transmission_gate";ctx.refresh_transmission_gate(&key,&prefs)?;
}
}else{
// A muted or deafened configuration is a successful no-capture outcome.
lock(&ctx.transmission)?.acknowledge_capture_configuration(&key,revision,config,false)?;
lock(&ctx.transmission)?.bound_permit=None;
stage="stop_input";ctx.audio.set_transmission_enabled(false);ctx.audio.request(AudioCommand::StopInput).await?;
ctx.audio_input_active.store(ctx.audio.input_active(),Ordering::Release);
}
}
#[cfg(target_os="android")]
if let Some((failed_stage,error))=playback_error{stage=failed_stage;return Err(error)}
Ok(())
}.await;
#[cfg(target_os="android")]
{
// Failed commands need not produce Started events. Never leave a previous
// selection marked active after an unsuccessful Android reconstruction.
ctx.audio_input_active.store(ctx.audio.input_active(),Ordering::Release);
ctx.audio_output_active.store(ctx.audio.output_active(),Ordering::Release);
}
#[cfg(target_os="android")]
if let Some(key)=stage_key.as_ref(){
use crate::platform::android::{VoiceRoutePhase as Phase,VoiceRouteReason as Reason,log_voice_route};
let phase=match stage{"select_input"=>Phase::SelectInput,"select_output"=>Phase::SelectOutput,"start_output"=>Phase::StartOutput,"start_input"=>Phase::ResumeCapture,"stop_input"=>Phase::StopInput,_=>Phase::Settings};
log_voice_route(key,phase,if result.is_ok(){Reason::Completed}else{Reason::Failed},route_started.elapsed(),false,ctx.audio.output_active(),ctx.audio.input_active());
}
if let Some(key)=stage_key.as_ref(){
if cfg!(target_os="android")&&matches!(stage,"start_output"|"notification_route") {
result.map_err(|error|ServiceError::new(&error.code,format!("Playback activation failed at {stage} ({}; generation={}; session={})",error.code,key.generation,key.session)))
}else{super::super::context_helpers::capture_stage(result,stage,key)}
}else{result}
}
pub(crate) async fn sync_notifications(ctx:&RuntimeServices)->Result<()> {
let prefs=ctx.profile()?.prefs.get();let settings:crate::services::notifications::NotificationPrefs=serde_json::from_value(prefs.clone())?;
@@ -50,14 +143,20 @@ pub(crate) async fn sync_notifications(ctx:&RuntimeServices)->Result<()> {
ctx.audio.request(AudioCommand::ConfigureNotifications{device:settings.device(),level_db:settings.notification_level_db,revision,permission:if ctx.output_granted.load(Ordering::Acquire){StartPermission::Granted}else{StartPermission::NotRequested}}).await
}
pub(super) async fn update_notifications(ctx:&Arc<RuntimeServices>)->Result<()> {
let active=(ctx.audio_input_active.load(Ordering::Acquire),ctx.audio_output_active.load(Ordering::Acquire));
sync_notifications(ctx).await?;
if active.0&&lock(&ctx.microphone_test_resume)?.is_none(){sync_audio_to(ctx.clone(),active).await?;}
let configuration=ctx.audio_configuration.lock().await;
let active=(lock(&ctx.transmission)?.capture_desired,ctx.audio_output_active.load(Ordering::Acquire));
if lock(&ctx.microphone_test_resume)?.is_none(){sync_audio_to(ctx,Some(active),None,&configuration).await?;}else{sync_notifications(ctx).await?;}
Ok(())
}
#[cfg(any(target_os="android",test))]
fn requests_playback_route(op:&Operation)->bool {
matches!(op,Operation::SelectDevice{kind:DeviceKind::Output,..}|Operation::MapDevice{kind:DeviceKind::Output,..}|Operation::NewDevice{kind:DeviceKind::Output,..})
}
pub(super) async fn invoke(ctx:Arc<RuntimeServices>,op:Operation)->Result<WorkflowResult>{
let notification_only=matches!(&op,Operation::SelectDevice{kind:DeviceKind::Notification,..}|Operation::MapDevice{kind:DeviceKind::Notification,..}|Operation::NewDevice{kind:DeviceKind::Notification,..});
if !notification_only&&!matches!(&op,Operation::AudioTest(_)|Operation::PreviewNotification(_))&&lock(&ctx.microphone_test_resume)?.is_some(){return Err(ServiceError::new("microphone_test_active","Finish the private microphone test before changing devices"))}
#[cfg(target_os="android")]
let playback_selection=requests_playback_route(&op);
match op {
Operation::SelectDevice{kind,id}=>{patch(&ctx,selection_key(kind),json!(id)).await?;},
Operation::MapDevice{kind,legacy,native}=>{ctx.mutate(move|p|{p.prefs.map_legacy_device(kind,&legacy,&native)?;Ok(())}).await?;},
@@ -65,37 +164,82 @@ pub(super) async fn invoke(ctx:Arc<RuntimeServices>,op:Operation)->Result<Workfl
Operation::CopyDspToTemplate{kind,device}=>{ctx.mutate(move|p|{let key=dsp_key(kind)?;let mut dsp=p.prefs.get()[key].clone();dsp["template"]=dsp["devices"].get(&device).cloned().ok_or_else(||bad("Device profile no longer exists"))?;p.prefs.set(json!({key:dsp}))?;Ok(())}).await?;},
Operation::ApplyDspTemplate{kind,device}=>{ctx.mutate(move|p|{let key=dsp_key(kind)?;let mut dsp=p.prefs.get()[key].clone();if dsp["devices"].get(&device).is_none(){return Err(bad("Device profile no longer exists"))}dsp["devices"][&device]=dsp["template"].clone();p.prefs.set(json!({key:dsp}))?;Ok(())}).await?;},
Operation::AudioTest(action)=>{
let configuration=ctx.audio_configuration.lock().await;
match action {
AudioTest::Record=>{ctx.policy.check()?;let allowed={let p=ctx.profile()?;p.prefs.capture_allowed(p.migration.is_some())};if !allowed{return Err(ServiceError::new("device_mapping_required","Confirm the imported microphone device first"))}
let snapshot=ctx.connected.connections.snapshot();let key=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).map(|s|s.key.clone());
let resume=(key.clone(),ctx.audio_input_active.load(Ordering::Acquire),ctx.audio_output_active.load(Ordering::Acquire));
ctx.request_microphone_permission().await?;if let Some(key)=key{ctx.require_key(&key,true)?;}
let (revision,desired)={let state=lock(&ctx.transmission)?;(state.revision,state.capture_desired)};
let resume={let state=lock(&ctx.transmission)?;super::super::context::MicrophoneTestResume{owner:key.clone(),input:desired,output:ctx.audio.output_authorized(),output_revision:state.output_intent_revision}};
// The private microphone test needs a current slot, not a live server.
// Still reject ownership changes while the OS permission prompt was open.
ctx.request_microphone_permission().await?;if let Some(key)=key{ctx.require_key(&key,false)?;}
if lock(&ctx.transmission)?.revision!=revision{return Err(ServiceError::new("audio_activation_revoked","Microphone authorization ended during the permission request"))}
let settings=capture_settings(&ctx.profile()?.prefs.get());
{let mut previous=lock(&ctx.microphone_test_resume)?;if previous.is_none(){*previous=Some(resume);}}
if let Err(error)=ctx.audio.request(AudioCommand::BeginMicrophoneTest{permission:StartPermission::Granted,settings}).await{lock(&ctx.microphone_test_resume)?.take();return Err(error)}},
if let Err(error)=ctx.audio.request(AudioCommand::BeginMicrophoneTest{permission:StartPermission::Granted,settings}).await{lock(&ctx.microphone_test_resume)?.take();return Err(error)}
if lock(&ctx.transmission)?.revision!=revision{
// Keep the private reservation until the owner confirms cleanup.
// A failed Finish must not expose real TX to private capture.
ctx.finish_private_microphone_test(&configuration).await?;
return Err(ServiceError::new("audio_activation_revoked","Microphone authorization ended during private capture startup"))
}
},
AudioTest::Stop=>ctx.audio.request(AudioCommand::StopMicrophoneTest).await?,
AudioTest::Play=>{ctx.policy.check()?;ctx.output_granted.store(true,Ordering::Release);ctx.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await?;ctx.audio.request(AudioCommand::ListenMicrophoneTest).await?;},
AudioTest::Clear=>{ctx.audio.request(AudioCommand::FinishMicrophoneTest).await?;let resume=lock(&ctx.microphone_test_resume)?.take();if let Some((owner,input,output))=resume{let snapshot=ctx.connected.connections.snapshot();let current=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).map(|s|s.key.clone());if current!=owner{return Err(super::super::context::changed())}if !output{ctx.audio.request(AudioCommand::StopOutput).await?;}sync_audio_to(ctx.clone(),(input,output)).await?;}},
AudioTest::Play=>{ctx.policy.check()?;ctx.audio.request(AudioCommand::StopMicrophoneTest).await?;ctx.output_granted.store(true,Ordering::Release);ctx.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await?;ctx.audio.request(AudioCommand::ListenMicrophoneTest).await?;},
AudioTest::Clear=>{
let Some(resume)=lock(&ctx.microphone_test_resume)?.clone() else{return done()};
// The configuration lease and reservation check precede Finish: a queued
// Clear after explicit microphone activation must never stop its new input.
ctx.finish_private_microphone_test(&configuration).await?;
let snapshot=ctx.connected.connections.snapshot();let current=snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).map(|s|s.key.clone());
if current!=resume.owner{return Err(super::super::context::changed())}
let (input,output)={let state=lock(&ctx.transmission)?;resume.activities(&state)};
if !output{ctx.audio.request(AudioCommand::StopOutput).await?;}
sync_audio_to(&ctx,Some((input,output)),None,&configuration).await?;
},
}return done()
},
Operation::PreviewNotification(name)=>{
ctx.policy.check()?;if !crate::services::notifications::SOUNDS.iter().any(|s|s.key==name){return Err(bad("Unknown notification sound"))}
let snapshot=ctx.connected.connections.snapshot();let key=snapshot.viewed_id.as_deref().and_then(|id|snapshot.get(id)).map(|entry|entry.key.clone()).ok_or_else(||bad("No server session for notification preview"))?;
let active=(ctx.audio_input_active.load(Ordering::Acquire),ctx.audio_output_active.load(Ordering::Acquire));
ctx.require_key(&key,false)?;ctx.output_granted.store(true,Ordering::Release);sync_notifications(&ctx).await?;
let configuration=ctx.audio_configuration.lock().await;
let active=(lock(&ctx.transmission)?.capture_desired,ctx.audio_output_active.load(Ordering::Acquire));
ctx.require_key(&key,false)?;ctx.output_granted.store(true,Ordering::Release);
let voice=ctx.profile()?.prefs.get()["notificationDeviceId"]=="voice";
if voice{ctx.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await?;}
sync_notifications(&ctx).await?;
ctx.require_key(&key,false)?;
let (setting,event)=crate::services::notifications::GROUPS.iter().flat_map(|g|g.settings).find_map(|s|if s.preview==name{Some((s.id,None))}else{s.events.iter().find(|e|e.sound==Some(name.as_str())).map(|e|(s.id,Some(e.id)))}).ok_or_else(||bad("Sound has no notification preview mapping"))?;
let effects={let mut notifications=lock(&ctx.notifications)?;notifications.acknowledge_output_revision(ctx.audio.notification_revision());notifications.preview(&key,setting,event,ctx.notification_now_ms())?};
for effect in effects{if let crate::services::notifications::NotificationEffect::Sound{session,sound,output_revision,..}=effect{ctx.require_key(&session,false)?;ctx.audio.request(AudioCommand::Notify{key:session,name:sound.file.into(),revision:output_revision}).await?;}}
if active.0&&lock(&ctx.microphone_test_resume)?.is_none(){sync_audio_to(ctx.clone(),(true,active.1||voice)).await?;}return done()
if active.0&&lock(&ctx.microphone_test_resume)?.is_none(){sync_audio_to(&ctx,Some((true,active.1||voice)),None,&configuration).await?;}return done()
},
_=>return Err(bad("Invalid audio operation")),
}if notification_only{update_notifications(&ctx).await?;}else{sync_audio(ctx).await?;}done()
}
#[cfg(target_os="android")]
if playback_selection {
let configuration=ctx.audio_configuration.lock().await;
let prefs=ctx.profile()?.prefs.get();
let route=crate::platform::android::select_voice_playback(prefs["outputDeviceId"].as_str().unwrap_or_default()).await?;
let result=sync_audio_to(&ctx,None,None,&configuration).await;
if let Some((token,revision))=route{crate::platform::android::acknowledge_voice_playback(token,revision,ctx.audio.output_active());}
result?;
return done()
}
if notification_only{update_notifications(&ctx).await?;}else{sync_audio(ctx).await?;}done()
}
#[cfg(test)]mod tests {
use super::*;
#[test]fn only_explicit_output_device_actions_request_platform_routing(){
for kind in [DeviceKind::Input,DeviceKind::Notification,DeviceKind::Output] {
let expected=matches!(kind,DeviceKind::Output);
assert_eq!(requests_playback_route(&Operation::SelectDevice{kind,id:"aaudio:11".into()}),expected);
assert_eq!(requests_playback_route(&Operation::MapDevice{kind,legacy:"old".into(),native:"aaudio:11".into()}),expected);
assert_eq!(requests_playback_route(&Operation::NewDevice{kind,native:"aaudio:11".into()}),expected);
assert!(!requests_playback_route(&Operation::CopyDspToTemplate{kind,device:"aaudio:11".into()}));
assert!(!requests_playback_route(&Operation::ApplyDspTemplate{kind,device:"aaudio:11".into()}));
}
}
#[test]fn ptt_forwarding_never_rewrites_selected_device_vad_policy(){
let mut prefs=crate::services::prefs::defaults();prefs["pttEnabled"]=json!(true);prefs["inputDeviceId"]=json!("native-input");
let mut device=crate::services::prefs::input_default();device["vadMode"]=json!("volume_gate");device["vadLevel"]=json!(-17);prefs["inputDsp"]["devices"]["native-input"]=device;
@@ -3,11 +3,12 @@ use crate::services::{whisper::{WhisperList,ReceiveMode},file_settings::FileSett
pub(super) async fn edit(ctx:Arc<RuntimeServices>,field:Field,value:SettingValue)->Result<WorkflowResult>{
match field {
Field::Palette(field)=>return themes::edit_palette(ctx,field,value).await,
Field::Preference(pref)=>{
let hardware=matches!(pref,Preference::HardwareVideoDecode);let update=matches!(pref,Preference::UpdateChannel);
let audio=matches!(pref,Preference::PttEnabled|Preference::OutputLevelDb|Preference::AutoEnableMicrophone|Preference::AutoReactivateMicOnPreviousTarget);
let value=if matches!(pref,Preference::RecordingMode){json!(choice_number(value,1,3)?)}else{value.json()};
patch(&ctx,pref.key(),value).await?;
if cfg!(target_os="android")&&matches!(pref,Preference::Theme){ctx.mutate(move|p|{p.prefs.set(json!({pref.key():value,"androidPalette":null}))?;Ok(())}).await?;}else{patch(&ctx,pref.key(),value).await?;}
if hardware{lock(&ctx.settings_status)?.video.restart_required=true;}
if update{let channel=serde_json::from_value(ctx.profile()?.prefs.get()["updateChannel"].clone())?;ctx.updates.set_channel(channel,std::time::Instant::now());}
if audio{sync_audio(ctx.clone()).await?;}
@@ -14,10 +14,37 @@ pub(super) async fn reload(ctx:&Arc<RuntimeServices>,force:bool)->Result<()> {
let resolved=themes.resolve(scheme(&owner,&profile.prefs.get()))?;publish(&owner,listing,&resolved,None)?;Ok::<_,ServiceError>(resolved)
}).await.map_err(|_|bad("Theme worker stopped"))??;ctx.effect(UiEffect::Theme(resolved)).await
}
/// Clear ephemeral edits when the shell leaves settings; never touches persisted preferences.
pub(super) fn cancel_palette(ctx:&RuntimeServices)->Result<()> {lock(&ctx.settings_status)?.palette_draft=None;Ok(())}
pub(super) fn begin_palette(ctx:&RuntimeServices)->Result<()> {
if !cfg!(target_os="android"){return Err(bad("Palette editing is available on Android"))}
let saved=ctx.profile()?.prefs.get()["androidPalette"].clone();let saved=if crate::services::prefs::valid_android_palette(&saved){saved}else{crate::services::prefs::android_palette_default()};lock(&ctx.settings_status)?.palette_draft=Some(saved);Ok(())
}
pub(super) async fn edit_palette(ctx:Arc<RuntimeServices>,field:PaletteColor,value:SettingValue)->Result<WorkflowResult> {
if !cfg!(target_os="android"){return Err(bad("Palette editing is available on Android"))}
let value=text(value)?;if value.len()>32{return Err(bad("Color must use #RRGGBB"))}
{let mut status=lock(&ctx.settings_status)?;let draft=status.palette_draft.as_mut().ok_or_else(||bad("Open the palette editor before changing colors"))?;draft[field.key()]=json!(value);}
ctx.changed().await?;done()
}
async fn palette(ctx:Arc<RuntimeServices>,op:Operation)->Result<WorkflowResult> {
if !cfg!(target_os="android"){return Err(bad("Palette editing is available on Android"))}
match op {
Operation::PalettePreset(preset)=>{let value=crate::services::prefs::android_palette_preset(preset.key()).ok_or_else(||bad("Unknown palette"))?;let mut status=lock(&ctx.settings_status)?;if status.palette_draft.is_none(){return Err(bad("Open the palette editor before choosing a preset"))}status.palette_draft=Some(value);},
Operation::PaletteSave=>{
let value=lock(&ctx.settings_status)?.palette_draft.clone().ok_or_else(||bad("Open the palette editor before saving"))?;
if !crate::services::prefs::valid_android_palette(&value){return Err(bad("Use #RRGGBB colors with text contrast of at least 4.5:1"))}
patch(&ctx,"androidPalette",value).await?;cancel_palette(&ctx)?;
return Ok(WorkflowResult::effect(UiEffect::SettingsNavigate(Navigation::Back)))
},
Operation::PaletteCancel=>{cancel_palette(&ctx)?;return Ok(WorkflowResult::effect(UiEffect::SettingsNavigate(Navigation::Back)))},
_=>return Err(bad("Invalid palette operation")),
}ctx.changed().await?;done()
}
pub(super) async fn invoke(ctx:Arc<RuntimeServices>,op:Operation)->Result<WorkflowResult>{
match op {
Operation::PalettePreset(_)|Operation::PaletteSave|Operation::PaletteCancel=>return palette(ctx,op).await,
Operation::ThemeReload=>reload(&ctx,true).await?,
Operation::ThemeSelect(selection)=>{let owner=ctx.clone();tokio::task::spawn_blocking(move||{let mut profile=owner.profile()?;lock(&owner.themes)?.select(selection.as_deref(),|value|{profile.prefs.set(json!({"userStyle":value}))?;Ok(())})}).await.map_err(|_|bad("Theme worker stopped"))??;reload(&ctx,false).await?;},
Operation::ThemeSelect(selection)=>{let owner=ctx.clone();tokio::task::spawn_blocking(move||{let mut profile=owner.profile()?;lock(&owner.themes)?.select(selection.as_deref(),|value|{let patch=if cfg!(target_os="android"){json!({"userStyle":value,"androidPalette":null})}else{json!({"userStyle":value})};profile.prefs.set(patch)?;Ok(())})}).await.map_err(|_|bad("Theme worker stopped"))??;reload(&ctx,false).await?;},
Operation::ThemePreview(selection)=>{let owner=ctx.clone();let resolved=tokio::task::spawn_blocking(move||{let mut profile=owner.profile()?;let mut themes=lock(&owner.themes)?;let listing=themes.list(false,|value|{profile.prefs.set(json!({"userStyle":value}))?;Ok(())})?;let resolved=themes.preview(&selection,scheme(&owner,&profile.prefs.get()))?;publish(&owner,listing,&resolved,Some(selection))?;Ok::<_,ServiceError>(resolved)}).await.map_err(|_|bad("Theme worker stopped"))??;ctx.effect(UiEffect::Theme(resolved)).await?;},
Operation::ThemeOpenDirectory(identifier)=>{let owner=ctx.clone();let path=tokio::task::spawn_blocking(move||lock(&owner.themes)?.directory_for(identifier.as_deref())).await.map_err(|_|bad("Theme worker stopped"))??;ctx.open_local_directory(path).await?;},
Operation::ThemeLink{identifier,kind}=>{let owner=ctx.clone();let url=tokio::task::spawn_blocking(move||lock(&owner.themes)?.package_link(&identifier,&kind)).await.map_err(|_|bad("Theme worker stopped"))??;let url=url.ok_or_else(||bad("Theme has no such link"))?;open_link(&ctx,&url).await?;},
+43 -7
View File
@@ -13,6 +13,9 @@ pub mod platform;
pub mod ui;
#[cfg(feature="test-harness")]
pub mod smoke;
#[cfg(any(target_os="android",test))]
#[path="platform/android/runtime_attachment.rs"]
mod runtime_attachment;
slint::include_modules!();
#[derive(Clone,Debug)]
@@ -64,7 +67,7 @@ impl AppRuntime {
pub fn build_description(&self)->String{format!("Version {}\nRust + Slint 1.18.1\n{} / {}",self.config.build_version,std::env::consts::OS,std::env::consts::ARCH)}
pub fn policy(&self)->platform::resources::ActionPolicy{platform::resources::ActionPolicy{allow_os_actions:self.config.allow_os_actions}}
pub fn next_ui_generation(&self)->u64 {
self.release_held();
self.release_ui_holds();
let generation=NEXT_UI_GENERATION.fetch_update(Ordering::AcqRel,Ordering::Acquire,|g|g.checked_add(1)).expect("UI generation exhausted")+1;
self.active_ui.store(generation,Ordering::Release);generation
}
@@ -73,12 +76,30 @@ impl AppRuntime {
pub fn is_ui_current(&self,generation:u64)->bool{generation!=0&&self.ui_generation()==generation}
pub fn release_ui(&self,generation:u64){
if self.active_ui.compare_exchange(generation,0,Ordering::AcqRel,Ordering::Acquire).is_ok(){
self.release_held();self.wake.lock().expect("UI wake").take();
self.release_ui_holds();self.wake.lock().expect("UI wake").take();
#[cfg(not(any(target_os="android",target_os="ios")))] self.desktop.lock().expect("desktop handle").take();
let _=self.commands.try_send(app::runtime::RuntimeCommand::Detached(generation));
}
}
pub fn release_held(&self){if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){app::runtime::controller::release_immediate(&ctx);let stop=ctx.transmission.lock().ok().and_then(|mut tx|tx.whisper.release(None));if let Some(stop)=stop{if self.commands.try_send(app::runtime::RuntimeCommand::WhisperStop(stop)).is_err(){self.cancel.send_replace(true);}}}}
/// UI loss releases momentary controls, not an already-authorized Android call.
pub fn release_ui_holds(&self){if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){let stop=app::runtime::controller::release_ui_immediate(&ctx,ctx.background_capture_authorized());if let Some(stop)=stop{if self.commands.try_send(app::runtime::RuntimeCommand::WhisperStop(stop)).is_err(){self.cancel.send_replace(true);}}}}
/// Runs on the OS callback before the route request or any worker await.
#[cfg(target_os="android")]
pub(crate) fn fence_android_audio_route(&self,key:&app::connections::SessionKey,authorized:bool){
if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){
if let Some(stop)=app::runtime::controller::suspend_route_immediate(&ctx,key,authorized){
if self.commands.try_send(app::runtime::RuntimeCommand::WhisperStop(stop)).is_err(){self.cancel.send_replace(true);}
}
}
}
/// Nonblocking OS shutdown: synchronous capture fence followed by worker cleanup.
pub(crate) fn request_shutdown(&self){self.release_held();self.cancel.send_replace(true);}
/// Lifecycle truth comes from the worker, not its last presentation snapshot.
#[cfg(any(target_os="android",test))]
pub(crate) fn accepts_ui_attachment(&self)->bool{
!*self.cancel.borrow()&&self.finished.borrow().is_none()&&!self.commands.is_closed()
}
fn release_screen(&self,target:&ui::shell::Target){if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){
let delay=ctx.profile().ok().map(|profile|profile.prefs.get()["pttReleaseDelay"].clone());
let revoke=if let Ok(mut tx)=ctx.transmission.lock(){if tx.key.as_ref()!=target.session.as_ref(){return}let removed=tx.ptt_holders.remove("screen");if removed{tx.revision=tx.revision.wrapping_add(1);if tx.ptt_holders.is_empty(){tx.release_at=delay.filter(|d|d["active"]==true).and_then(|d|d["ms"].as_u64()).map(|ms|std::time::Instant::now()+std::time::Duration::from_millis(ms));}}removed&&!tx.whisper.held()}else{true};
@@ -94,14 +115,17 @@ impl AppRuntime {
use platform::lifecycle::PlatformEvent::*;
let generation=match &event{Visibility{ui_generation,..}|UiDestroyed{ui_generation}|Insets{ui_generation,..}|Accessibility{ui_generation,..}|DesktopTheme{ui_generation,..}|DesktopWindow{ui_generation,..}|PhysicalKey{ui_generation,..}|Focus{ui_generation,..}=>Some(*ui_generation),_=>None};
if generation.is_some_and(|generation|!self.is_ui_current(generation)){return}
if matches!(&event,Focus{focused:true,..})||(!cfg!(target_os="android")&&matches!(&event,Visibility{visible:true,..})){if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){if let Ok(mut tx)=ctx.transmission.lock(){tx.ui_controls_suspended=false;}}}
#[cfg(target_os="android")]
if let AndroidCallAudio{key,token,revision,..}=&event {
if !platform::android::voice_audio_current(key,*token,*revision){return}
self.release_held();
if platform::android::voice_audio_allowed(key,true){self.fence_android_audio_route(key,true);}else{self.release_held();}
}
if matches!(&event,Focus{focused:false,..}|UiDestroyed{..}){self.release_ui_holds();}
#[cfg(target_os="android")]
if matches!(&event,Visibility{visible:false,..}){self.release_held();}
if matches!(&event,Focus{focused:false,..}|UiDestroyed{..}|AudioInterruption{began:true,..}|AudioRouteChanged|NetworkChanged|PermissionChanged{permission:platform::lifecycle::Permission::Microphone,granted:false}|CallLeaseEnded{..}|Quit){self.release_held();}
if matches!(&event,Visibility{visible:false,..}){self.release_ui_holds();}
if matches!(&event,AudioInterruption{began:true,..}|AudioRouteChanged|NetworkChanged|PermissionChanged{permission:platform::lifecycle::Permission::Microphone,granted:false}|CallLeaseEnded{..}|Notification{action:platform::lifecycle::NotificationAction::Mute|platform::lifecycle::NotificationAction::Disconnect,..}|Quit){self.release_held();}
if matches!(&event,ScreenLocked(true))&&self.services.lock().expect("runtime services").upgrade().is_some_and(|ctx|ctx.profile().is_ok_and(|profile|profile.prefs.get()["osMuteWhenLocked"]==true)){self.release_held();}
if self.enqueue(app::runtime::RuntimeCommand::Platform(event)).is_err(){self.cancel.send_replace(true);}
}
fn enqueue(&self,command:app::runtime::RuntimeCommand)->services::Result<()>{self.commands.try_send(command).map_err(|_|services::ServiceError::new("runtime_busy","Application action queue is full or stopped; retry the action"))}
@@ -110,9 +134,21 @@ impl AppRuntime {
pub(crate) fn drain_effects(&self)->Vec<app::runtime::events::UiEffect>{self.pending_wake.store(false,Ordering::Release);let mut effects=self.effects.lock().expect("UI effects");let mut batch=Vec::new();while let Ok(effect)=effects.try_recv(){batch.push(effect)}batch}
#[cfg(not(any(target_os="android",target_os="ios")))]
pub fn desktop_handle(&self)->Option<platform::desktop::DesktopHandle>{self.desktop.lock().expect("desktop handle").clone()}
async fn finished_result(&self)->services::Result<()> {
let mut done=self.finished.clone();
loop{if let Some(result)=done.borrow_and_update().clone(){return result}done.changed().await.map_err(|_|services::ServiceError::new("worker_stopped","Application worker ended without a shutdown result"))?;}
}
/// Android's new native Activity thread must join the retired owner before reopening storage.
/// No runtime/attachment mutex is held while waiting for the dedicated worker.
#[cfg(any(target_os="android",test))]
pub(crate) fn join_shutdown(&self)->services::Result<()> {
self.request_shutdown();
let worker=self.worker.lock().expect("runtime worker").take();
if let Some(worker)=worker{worker.join().map_err(|_|services::ServiceError::new("worker_panicked","Application worker panicked"))?;}
futures::executor::block_on(self.finished_result())
}
pub async fn shutdown(&self)->services::Result<()> {
self.release_held();self.cancel.send_replace(true);let mut done=self.finished.clone();
let result=loop{if let Some(result)=done.borrow_and_update().clone(){break result}done.changed().await.map_err(|_|services::ServiceError::new("worker_stopped","Application worker ended without a shutdown result"))?;};
self.request_shutdown();let result=self.finished_result().await;
let worker=self.worker.lock().expect("runtime worker").take();
if let Some(worker)=worker{tokio::task::spawn_blocking(move||worker.join()).await.map_err(|_|services::ServiceError::new("worker_join","Application worker join failed"))?.map_err(|_|services::ServiceError::new("worker_panicked","Application worker panicked"))?;}result
}
+3
View File
@@ -49,6 +49,8 @@ impl CapturePipeline {
self.dsp.reset(settings).map_err(|e|ServiceError::new("capture_dsp",e.to_string()))?;
self.settings=settings;Ok(())
}
/// Return the same normalized DSP output used by TX, without i16 conversion or
/// playback amplification. On failure the entire block is silent and TX is revoked.
pub fn process_private(&mut self,samples:&mut[f32;BLOCK])->Result<()> {
if self.typing{for value in samples.iter_mut(){
if self.typing_remaining>0{self.typing_gain=(self.typing_gain-(1.-TYPING_GAIN)/96.).max(TYPING_GAIN);self.typing_remaining-=1;}
@@ -65,6 +67,7 @@ impl CapturePipeline {
}
self.process_private(&mut samples)?;
if self.position==0{self.first_capture=Some(captured_at);}
// Quantize only at the TeamSpeak boundary; private recording stays normalized.
for sample in samples{
let sample=sample.clamp(-1.,1.);
let scaled=sample*if sample<0.{32768.}else{32767.};
+75
View File
@@ -318,3 +318,78 @@ fn real_sonora_chain_processes_signal_and_requires_fresh_reference_after_reset()
assert_eq!(silence.pcm, [0; 960], "reset must remove previous DSP signal history");
assert_tags(&silence, reset_at, EPOCH + 2, 33, None);
}
#[test]
fn private_recording_stays_normalized_and_matches_transmitted_dsp_before_quantization() {
let settings = CaptureSettings::default();
let mut private = bound();
let start = Instant::now();
// Entering private capture revokes TX and discards a pending non-private half.
assert!(push(&mut private, -0.75, start, EPOCH).is_none());
private.reset_private(settings).unwrap();
assert!(private.permit().is_none());
let mut transmit = CapturePipeline::new(settings).unwrap();
transmit.bind(permit(EPOCH + 1, 32), settings).unwrap();
let mut expected = [0_i16; 960];
let mut private_energy = 0.0;
for block in 0..100_u64 {
let amplitude = match block {
0..=9 | 70..=99 => 0.0,
10..=39 => 0.002,
_ => 0.04,
};
let input = std::array::from_fn(|index| {
let time = (block as usize * BLOCK + index) as f32 / 48_000.0;
amplitude * (std::f32::consts::TAU * 220.0 * time).sin()
});
let mut processed = input;
private.render_reference(&[0.0; BLOCK], 0).unwrap();
transmit.render_reference(&[0.0; BLOCK], 0).unwrap();
private.process_private(&mut processed).unwrap();
for (index, &sample) in processed.iter().enumerate() {
assert!(sample.is_finite() && sample.abs() < 1.0, "private PCM clipped or changed units at block {block}");
if block < 10 {
assert_eq!(sample, 0.0, "private startup silence generated audio");
}
private_energy += f64::from(sample).powi(2);
expected[(block as usize % 2) * BLOCK + index] =
(sample * if sample < 0.0 { 32768.0 } else { 32767.0 } + 0.5).floor() as i16;
}
let stamp = start + Duration::from_millis(block * 10);
let frame = transmit.process(input, stamp, EPOCH + 1, stamp).unwrap();
if block % 2 == 1 {
assert_eq!(frame.unwrap().pcm, expected, "private/TX DSP diverged at block {block}");
} else {
assert!(frame.is_none());
}
assert!(private.process(input, stamp, EPOCH, stamp).unwrap().is_none(), "private capture restored TX");
assert!(private.permit().is_none());
}
assert!(private_energy > 0.0, "actual private DSP discarded the entire synthetic signal");
}
#[test]
fn private_capture_errors_return_only_silence_and_discard_pending_transmit_pcm() {
let now = Instant::now();
for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
let mut pipeline = bound();
assert!(push(&mut pipeline, -0.75, now, EPOCH).is_none());
let mut samples = [0.25; BLOCK];
samples[BLOCK / 2] = invalid;
let error = pipeline.process_private(&mut samples).unwrap_err();
assert_eq!(error.code, "capture_dsp");
assert_eq!(samples, [0.0; BLOCK], "rejected private frame retained audible PCM");
assert!(pipeline.permit().is_none());
assert!(push(&mut pipeline, 0.5, now, EPOCH).is_none());
pipeline.bind(permit(EPOCH + 1, 32), bypass()).unwrap();
assert!(push(&mut pipeline, 0.25, now, EPOCH + 1).is_none());
assert_eq!(push(&mut pipeline, 0.25, now, EPOCH + 1).unwrap().pcm, [8192; 960]);
}
let mut pipeline = bound();
pipeline.reset_private(CaptureSettings::default()).unwrap();
let mut samples = [0.25; BLOCK];
assert_eq!(pipeline.process_private(&mut samples).unwrap_err().code, "capture_dsp");
assert_eq!(samples, [0.0; BLOCK], "missing AEC reference must never return bypass audio");
assert!(pipeline.permit().is_none());
}
+287 -39
View File
@@ -2,9 +2,9 @@
//!
//! Enumeration never builds a stream. ALSA capability probes open PCM handles,
//! so their configurations are deliberately deferred until a permitted start.
//! An engine worker owns every StreamOwner; callbacks only convert samples and
//! exchange fixed-size blocks. Resampling, DSP, routing and permission prompts
//! belong to the worker/platform layers, not this module.
//! A dedicated lifecycle owner constructs, starts and destroys every StreamOwner;
//! callbacks only convert samples and exchange fixed-size blocks. The live PCM
//! worker independently services resampling, DSP and routing.
use std::{
marker::PhantomData,
rc::Rc,
@@ -17,7 +17,7 @@ use cpal::{
StreamInstant, SupportedBufferSize, SupportedStreamConfigRange,
};
use crate::services::{Result, ServiceError};
use super::ring::{self, Consumer, Producer};
use super::{resample::ClockObservation, ring::{self, Consumer, Producer}};
pub const BLOCK_FRAMES: usize = 256;
pub const MAX_AUDIO_AGE: Duration = Duration::from_millis(200);
@@ -84,6 +84,29 @@ pub struct SelectedDevice {
pub direction: Direction,
pub format: DeviceFormat,
device: cpal::Device,
#[cfg(target_os = "android")]
requested: Option<DeviceFormat>,
}
impl SelectedDevice {
/// Resolve the output role to an exact Android endpoint when available.
/// Unresolved defaults are reconciled serially by the engine, never guessed.
pub fn prepare_output(&mut self, _voice: bool) -> Result<bool> {
#[cfg(target_os = "android")]
{
let resolved = if let cpal::platform::DeviceInner::AAudio(device) = self.device.as_inner_mut() {
device.prepare_output(_voice).map_err(audio_error)?
} else { true };
let id = self.device.id().map_err(audio_error)?.to_string();
let format = resolved_output_format(self.format, self.requested, self.id != id,
|| configurations(&self.device, Direction::Output).map_err(audio_error))?;
self.format = format;
self.id = id;
Ok(resolved)
}
#[cfg(not(target_os = "android"))]
{ Ok(true) }
}
}
/// Host choice is made once. Refresh, selection and stream failure never pick
@@ -184,7 +207,10 @@ impl DeviceHost {
}.ok_or_else(|| ServiceError::new("audio_device_missing", "The selected audio device is unavailable; its selection was preserved"))?;
let ranges = configurations(&device, direction).map_err(audio_error)?;
let format = select_format(&ranges, direction, requested)?;
Ok(SelectedDevice { id: device.id().map_err(audio_error)?.to_string(), direction, format, device })
Ok(SelectedDevice { id: device.id().map_err(audio_error)?.to_string(), direction, format, device,
#[cfg(target_os = "android")]
requested,
})
}
}
@@ -252,6 +278,15 @@ fn select_format(ranges: &[SupportedStreamConfigRange], direction: Direction, re
}
Err(ServiceError::new("audio_configuration_unsupported", "The selected device does not support the requested PCM configuration"))
}
/// Re-query the physical endpoint after Android resolves a synthetic default.
/// Exact endpoints and unresolved roles retain their already validated format.
#[cfg(any(target_os = "android", test))]
fn resolved_output_format(current: DeviceFormat, requested: Option<DeviceFormat>, endpoint_changed: bool,
ranges: impl FnOnce() -> Result<Vec<SupportedStreamConfigRange>>) -> Result<DeviceFormat> {
if !endpoint_changed { return Ok(current); }
select_format(&ranges()?, Direction::Output, requested)
}
fn audio_error(error: cpal::Error) -> ServiceError {
let code = match error.kind() {
cpal::ErrorKind::PermissionDenied => "audio_permission_denied",
@@ -259,6 +294,9 @@ fn audio_error(error: cpal::Error) -> ServiceError {
cpal::ErrorKind::DeviceBusy => "audio_device_busy",
cpal::ErrorKind::HostUnavailable => "audio_host_unavailable",
cpal::ErrorKind::UnsupportedConfig | cpal::ErrorKind::UnsupportedOperation => "audio_configuration_unsupported",
cpal::ErrorKind::DeviceChanged => "audio_route_changed",
cpal::ErrorKind::StreamInvalidated => "audio_stream_invalidated",
cpal::ErrorKind::Xrun => "audio_clock_discontinuity",
_ => "audio_device_error",
};
ServiceError::new(code, error.kind().to_string())
@@ -272,7 +310,12 @@ pub struct CaptureBlock {
pub epoch: u64,
pub captured_at: Instant,
pub callback_at: Instant,
/// Local callback entry time, independent of the calibrated backend clock.
pub arrived_at: Instant,
pub calibration_uncertainty: Duration,
pub frame_position: u64,
/// Unsubdivided callback clock observation; shared by all blocks from that callback.
pub clock: ClockObservation,
}
#[derive(Clone, Copy, Debug)]
pub struct PlaybackBlock {
@@ -301,7 +344,11 @@ pub struct RenderBlock {
/// CPAL's hardware-clock playback estimate, not a measured acoustic time.
pub playback_at: Instant,
pub callback_at: Instant,
/// Queue residence uses local callback entry, not the mapped backend estimate.
pub arrived_at: Instant,
pub calibration_uncertainty: Duration,
pub frame_position: u64,
pub clock: ClockObservation,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -336,6 +383,14 @@ pub struct StreamState {
dropped_blocks: AtomicU64,
underrun_frames: AtomicU64,
realtime_denied: AtomicBool,
callbacks: AtomicU64,
frames: AtomicU64,
xruns: AtomicU64,
submitted_frames: AtomicU64,
discarded_route_blocks: AtomicU64,
discarded_time_blocks: AtomicU64,
#[cfg(any(target_os = "android", test))]
nonzero_frames: AtomicU64,
}
#[derive(Clone, Copy, Debug)]
pub struct StreamStats {
@@ -345,10 +400,26 @@ pub struct StreamStats {
pub dropped_blocks: u64,
pub underrun_frames: u64,
pub realtime_denied: bool,
pub callbacks: u64,
pub frames: u64,
/// Number of CPAL Xrun error notifications, not a backend-specific cumulative count.
pub xruns: u64,
/// Device-rate frames successfully enqueued by the worker, including mixed silence.
pub submitted_frames: u64,
/// Unconsumed blocks discarded by callback generation/format/enable gates.
pub discarded_route_blocks: u64,
/// Unconsumed blocks discarded by queue age or hardware presentation deadlines.
pub discarded_time_blocks: u64,
/// Quantized output frames with a nonzero sample handed to CPAL, not proof of audibility.
#[cfg(any(target_os = "android", test))]
pub nonzero_frames: u64,
}
impl StreamState {
fn new(epoch: u64, origin: Instant) -> Self {
Self { origin, epoch: AtomicU64::new(epoch), boundary_ns: AtomicU64::new(0), enabled: AtomicBool::new(false), fault: AtomicU8::new(0), dropped_blocks: AtomicU64::new(0), underrun_frames: AtomicU64::new(0), realtime_denied: AtomicBool::new(false) }
pub(super) fn new(epoch: u64, origin: Instant) -> Self {
Self { origin, epoch: AtomicU64::new(epoch), boundary_ns: AtomicU64::new(0), enabled: AtomicBool::new(false), fault: AtomicU8::new(0), dropped_blocks: AtomicU64::new(0), underrun_frames: AtomicU64::new(0), realtime_denied: AtomicBool::new(false), callbacks: AtomicU64::new(0), frames: AtomicU64::new(0), xruns: AtomicU64::new(0),
submitted_frames: AtomicU64::new(0), discarded_route_blocks: AtomicU64::new(0), discarded_time_blocks: AtomicU64::new(0),
#[cfg(any(target_os = "android", test))]
nonzero_frames: AtomicU64::new(0) }
}
pub fn epoch(&self) -> u64 { self.epoch.load(Ordering::Acquire) }
/// Call before an acknowledged capture-boundary cutover. Samples physically
@@ -376,20 +447,29 @@ impl StreamState {
}
}
pub fn stats(&self) -> StreamStats {
StreamStats { epoch: self.epoch(), enabled: self.enabled.load(Ordering::Acquire), fault: self.fault(), dropped_blocks: self.dropped_blocks.load(Ordering::Relaxed), underrun_frames: self.underrun_frames.load(Ordering::Relaxed), realtime_denied: self.realtime_denied.load(Ordering::Relaxed) }
StreamStats { epoch: self.epoch(), enabled: self.enabled.load(Ordering::Acquire), fault: self.fault(), dropped_blocks: self.dropped_blocks.load(Ordering::Relaxed), underrun_frames: self.underrun_frames.load(Ordering::Relaxed), realtime_denied: self.realtime_denied.load(Ordering::Relaxed), callbacks: self.callbacks.load(Ordering::Relaxed), frames: self.frames.load(Ordering::Relaxed), xruns: self.xruns.load(Ordering::Relaxed),
submitted_frames: self.submitted_frames.load(Ordering::Relaxed), discarded_route_blocks: self.discarded_route_blocks.load(Ordering::Relaxed), discarded_time_blocks: self.discarded_time_blocks.load(Ordering::Relaxed),
#[cfg(any(target_os = "android", test))]
nonzero_frames: self.nonzero_frames.load(Ordering::Relaxed) }
}
pub(super) fn record_submission(&self, frames: usize) { self.submitted_frames.fetch_add(frames as u64, Ordering::Relaxed); }
#[cfg(target_os = "android")]
pub(super) fn enabled(&self) -> bool { self.enabled.load(Ordering::Acquire) }
fn active(&self, epoch: u64) -> bool {
self.enabled.load(Ordering::Acquire) && self.epoch() == epoch && self.fault.load(Ordering::Acquire) == 0
}
fn accepts_capture(&self, epoch: u64, at: Instant, now: Instant) -> bool {
fn accepts_capture<const HOLD_FUTURE: bool>(&self, epoch: u64, at: Instant, now: Instant) -> bool {
self.active(epoch) && at >= self.origin
&& nanos(at.duration_since(self.origin)) >= self.boundary_ns.load(Ordering::Acquire)
&& now.checked_duration_since(at).is_some_and(|age| age <= MAX_AUDIO_AGE)
&& if at <= now { now.duration_since(at) <= MAX_AUDIO_AGE }
else { HOLD_FUTURE && at.duration_since(now) <= MAX_AUDIO_AGE }
}
fn fail(&self, fault: StreamFault) {
let _ = self.fault.compare_exchange(0, fault as u8, Ordering::AcqRel, Ordering::Acquire);
self.suspend();
}
#[cfg(test)]
pub(super) fn test_backend_error(&self, error: cpal::Error) { self.on_error(error); }
fn on_error(&self, error: cpal::Error) {
let fault = match error.kind() {
cpal::ErrorKind::RealtimeDenied => { self.realtime_denied.store(true, Ordering::Relaxed); return; }
@@ -397,7 +477,7 @@ impl StreamState {
cpal::ErrorKind::PermissionDenied => StreamFault::PermissionDenied,
cpal::ErrorKind::DeviceChanged => StreamFault::RouteChanged,
cpal::ErrorKind::StreamInvalidated => StreamFault::Invalidated,
cpal::ErrorKind::Xrun => StreamFault::ClockDiscontinuity,
cpal::ErrorKind::Xrun => { self.xruns.fetch_add(1, Ordering::Relaxed); StreamFault::ClockDiscontinuity }
_ => StreamFault::Backend,
};
self.fail(fault);
@@ -408,7 +488,7 @@ pub struct CapturePort { pub samples: Consumer<CaptureBlock>, pub state: Arc<Str
pub struct PlaybackPort { pub samples: Producer<PlaybackBlock>, pub rendered: Consumer<RenderBlock>, pub state: Arc<StreamState> }
/// !Send/!Sync by design: CPAL construction, pause and destruction stay on the
/// engine owner thread, never on the UI or device callback thread.
/// lifecycle owner thread, never on the live PCM, UI or device callback thread.
pub struct StreamOwner {
stream: Option<cpal::Stream>,
pub state: Arc<StreamState>,
@@ -417,10 +497,7 @@ pub struct StreamOwner {
_owner_thread: PhantomData<Rc<()>>,
}
impl StreamOwner {
/// Pausing closes the OS stream on its owner. Resume is a fresh permitted
/// start, so backends without hardware pause cannot silently keep recording.
pub fn pause(&mut self) { self.stop(); }
pub fn stop(&mut self) {
fn stop(&mut self) {
self.state.suspend();
if let Some(stream) = self.stream.take() {
let _ = stream.pause();
@@ -433,15 +510,21 @@ impl Drop for StreamOwner { fn drop(&mut self) { self.stop(); } }
/// Common monotonic mapping calibrated on the owner before play. Each stream
/// has its own CPAL origin, so CPAL timestamps from different sinks are never
/// subtracted directly. Calibration does not use callback arrival cadence.
struct ClockAnchor { origin: Instant, device_ns: AtomicU64, local_ns: AtomicU64 }
struct ClockAnchor { origin: Instant, device_ns: AtomicU64, local_ns: AtomicU64, uncertainty_ns: AtomicU64 }
impl ClockAnchor {
fn new(origin: Instant) -> Self { Self { origin, device_ns: AtomicU64::new(0), local_ns: AtomicU64::new(0) } }
fn new(origin: Instant) -> Self { Self { origin, device_ns: AtomicU64::new(0), local_ns: AtomicU64::new(0), uncertainty_ns: AtomicU64::new(0) } }
fn calibrate(&self, stream: &cpal::Stream) {
let before = Instant::now();
let device = stream.now();
let after = Instant::now();
let midpoint = before + after.duration_since(before) / 2;
self.set_calibration(before, device, after);
}
fn set_calibration(&self, before: Instant, device: StreamInstant, after: Instant) {
let bracket = after.duration_since(before);
let midpoint = before + bracket / 2;
self.device_ns.store(device.as_nanos().min(u64::MAX as u128) as u64, Ordering::Relaxed);
// Round up: an odd-nanosecond bracket must not understate uncertainty.
self.uncertainty_ns.store(nanos(bracket).div_ceil(2), Ordering::Relaxed);
self.local_ns.store(nanos(midpoint.duration_since(self.origin)), Ordering::Release);
}
fn map(&self, timestamp: StreamInstant) -> Option<Instant> {
@@ -451,6 +534,7 @@ impl ClockAnchor {
if mapped >= 0 { self.origin.checked_add(Duration::from_nanos(u64::try_from(mapped).ok()?)) }
else { self.origin.checked_sub(Duration::from_nanos(u64::try_from(-mapped).ok()?)) }
}
fn uncertainty(&self) -> Duration { Duration::from_nanos(self.uncertainty_ns.load(Ordering::Relaxed)) }
}
fn nanos(duration: Duration) -> u64 { duration.as_nanos().min(u64::MAX as u128) as u64 }
fn frames_duration(frames: u64, rate: u32) -> Duration {
@@ -468,9 +552,15 @@ struct CaptureCallback {
impl CaptureCallback {
fn process<T>(&mut self, data: &[T], timestamp: cpal::InputStreamTimestamp, now: Instant)
where T: cpal::SizedSample, f32: cpal::FromSample<T> {
self.process_with_future_hold::<T, { cfg!(target_os = "android") }>(data, timestamp, now);
}
fn process_with_future_hold<T, const HOLD_FUTURE: bool>(&mut self, data: &[T], timestamp: cpal::InputStreamTimestamp, now: Instant)
where T: cpal::SizedSample, f32: cpal::FromSample<T> {
self.state.callbacks.fetch_add(1, Ordering::Relaxed);
let channels = self.format.channels as usize;
if data.len() % channels != 0 { self.state.fail(StreamFault::InvalidBuffer); return; }
let frames = data.len() / channels;
self.state.frames.fetch_add(frames as u64, Ordering::Relaxed);
let position = self.frame_position;
self.frame_position = self.frame_position.saturating_add(frames as u64);
let (Some(captured_at), Some(callback_at)) = (self.clock.map(timestamp.capture), self.clock.map(timestamp.callback)) else {
@@ -483,14 +573,17 @@ impl CaptureCallback {
for offset in (0..frames).step_by(BLOCK_FRAMES) {
let count = BLOCK_FRAMES.min(frames - offset);
let Some(at) = captured_at.checked_add(frames_duration(offset as u64, self.format.sample_rate)) else { self.state.fail(StreamFault::ClockDiscontinuity); return; };
if !self.state.accepts_capture(epoch, at, now) { continue; }
let mut block = CaptureBlock { samples: [0.0; BLOCK_FRAMES], frames: count, sample_rate: self.format.sample_rate, epoch, captured_at: at, callback_at, frame_position: position + offset as u64 };
// Android may deliver a callback whose estimated tail is still ahead
// of the local clock. Queue it in order; the worker quarantines it
// until due. Dropping just that tail creates a false FramePositionGap.
if !self.state.accepts_capture::<HOLD_FUTURE>(epoch, at, now) { continue; }
let mut block = CaptureBlock { samples: [0.0; BLOCK_FRAMES], frames: count, sample_rate: self.format.sample_rate, epoch, captured_at: at, callback_at, arrived_at: now, calibration_uncertainty: self.clock.uncertainty(), frame_position: position + offset as u64, clock: ClockObservation { at: captured_at, position } };
for (output, input) in block.samples[..count].iter_mut().zip(data[offset * channels..(offset + count) * channels].chunks_exact(channels)) {
let mut mono = 0.0;
for &sample in input { mono += finite_sample(<f32 as cpal::Sample>::from_sample(sample)); }
*output = mono / channels as f32;
}
if !self.state.accepts_capture(epoch, at, now) { continue; }
if !self.state.accepts_capture::<HOLD_FUTURE>(epoch, at, now) { continue; }
if self.producer.try_push(block).is_err() {
self.state.dropped_blocks.fetch_add(1, Ordering::Relaxed);
self.state.fail(StreamFault::CaptureOverflow);
@@ -499,6 +592,58 @@ impl CaptureCallback {
}
}
}
/// Synthetic hardware boundary for lifecycle/runtime tests; uses the production
/// callback adapter and its exact epoch, timestamp, capacity and overflow checks.
#[cfg(test)]
pub(super) fn test_capture_port(state: Arc<StreamState>, format: DeviceFormat, retired: Arc<AtomicBool>) -> CapturePort {
let (producer, samples) = ring::channel(queue_capacity(format.sample_rate));
let port = CapturePort { samples, state: state.clone() };
std::thread::spawn(move || {
let clock = Arc::new(ClockAnchor::new(state.origin));
let mut callback = CaptureCallback { producer, state, clock, format, frame_position: 0, expected_at: None };
while !retired.load(Ordering::Acquire) {
std::thread::sleep(Duration::from_millis(10));
let now = Instant::now();
let elapsed = now.duration_since(callback.state.origin);
let timestamp = cpal::InputStreamTimestamp {
capture: StreamInstant::from_nanos(nanos(elapsed.saturating_sub(Duration::from_millis(10)))),
callback: StreamInstant::from_nanos(nanos(elapsed)),
};
callback.process(&[0.125_f32; 480], timestamp, now);
}
});
port
}
/// Hardware-free render callback producer for full Worker::run tests. It owns
/// both callback ends exactly as CPAL does; tests never manually drain references.
#[cfg(test)]
pub(super) fn test_playback_port(state: Arc<StreamState>, format: DeviceFormat, retired: Arc<AtomicBool>) -> (PlaybackPort, Arc<AtomicU64>) {
let capacity = queue_capacity(format.sample_rate);
let (samples, consumer) = ring::channel(capacity);
let (references, rendered) = ring::channel(capacity);
let audible = Arc::new(AtomicU64::new(0));
let observed = audible.clone();
let port = PlaybackPort { samples, rendered, state: state.clone() };
std::thread::spawn(move || {
let clock = Arc::new(ClockAnchor::new(state.origin));
let mut callback = PlaybackCallback { consumer, references, state, clock, format,
current: None, current_offset: 0, frame_position: 0, expected_at: None };
let mut output = [0_f32; BLOCK_FRAMES];
let mut next = Instant::now();
while !retired.load(Ordering::Acquire) {
next += frames_duration(BLOCK_FRAMES as u64, format.sample_rate);
std::thread::sleep(next.saturating_duration_since(Instant::now()));
let now = Instant::now();
let timestamp = cpal::OutputStreamTimestamp {
callback: StreamInstant::from_nanos(nanos(now.duration_since(callback.state.origin))),
playback: StreamInstant::from_nanos(nanos(frames_duration(callback.frame_position, format.sample_rate) + Duration::from_millis(20))),
};
callback.process(&mut output, timestamp, now);
observed.fetch_add(output.iter().filter(|sample| sample.abs() > 0.01).count() as u64, Ordering::Relaxed);
}
});
(port, audible)
}
fn clock_contiguous(expected: Option<Instant>, actual: Instant) -> bool {
expected.is_none_or(|expected| if actual >= expected { actual.duration_since(expected) <= MAX_AUDIO_AGE } else { expected.duration_since(actual) <= MAX_AUDIO_AGE })
}
@@ -508,22 +653,28 @@ struct PlaybackCallback {
format: DeviceFormat, current: Option<PlaybackBlock>, current_offset: usize, frame_position: u64, expected_at: Option<Instant>,
}
impl PlaybackCallback {
fn next_frame(&mut self, epoch: u64, now: Instant, playback_at: Instant, output_offset: usize, deadline_checked: &mut bool, scan_budget: &mut usize) -> Option<[f32; 2]> {
if !self.state.active(epoch) { self.current = None; return None; }
fn next_frame<const PRESENTATION_DEADLINE: bool>(&mut self, epoch: u64, now: Instant, playback_at: Instant, output_offset: usize, deadline_checked: &mut bool, scan_budget: &mut usize) -> Option<[f32; 2]> {
if !self.state.active(epoch) {
if self.current.as_ref().is_some_and(|block| self.current_offset < block.frames) {
self.state.discarded_route_blocks.fetch_add(1, Ordering::Relaxed);
}
self.current = None; return None;
}
loop {
if let Some(block) = self.current.as_ref() {
if block.epoch == epoch && block.sample_rate == self.format.sample_rate && block.frames <= BLOCK_FRAMES
&& now.checked_duration_since(block.produced_at).is_some_and(|age| age <= MAX_AUDIO_AGE)
&& now < block.expires_at
&& self.current_offset < block.frames {
if !*deadline_checked {
// Check the entire remaining block at its proposed
// hardware presentation time, including its last frame.
// Recheck partial blocks on every hardware callback.
if PRESENTATION_DEADLINE && !*deadline_checked {
// Preserve the desktop presentation deadline. Android expires
// PCM at handoff above: downstream device latency is not stale
// application queue residence. Epoch and mute gates still apply.
let last_offset = output_offset + block.frames - self.current_offset - 1;
let timely = playback_at.checked_add(frames_duration(last_offset as u64, self.format.sample_rate))
.is_some_and(|last_at| last_at < block.expires_at);
if !timely {
self.state.discarded_time_blocks.fetch_add(1, Ordering::Relaxed);
self.current = None;
continue;
}
@@ -533,6 +684,13 @@ impl PlaybackCallback {
self.current_offset += 1;
return Some(sample);
}
if self.current_offset < block.frames {
if block.epoch != epoch || block.sample_rate != self.format.sample_rate || block.frames > BLOCK_FRAMES {
self.state.discarded_route_blocks.fetch_add(1, Ordering::Relaxed);
} else {
self.state.discarded_time_blocks.fetch_add(1, Ordering::Relaxed);
}
}
self.current = None;
}
if *scan_budget == 0 { return None; }
@@ -545,10 +703,16 @@ impl PlaybackCallback {
}
fn process<T>(&mut self, data: &mut [T], timestamp: cpal::OutputStreamTimestamp, now: Instant)
where T: cpal::SizedSample + cpal::FromSample<f32>, f32: cpal::FromSample<T> {
self.process_with_deadline::<T, { !cfg!(target_os = "android") }>(data, timestamp, now);
}
fn process_with_deadline<T, const PRESENTATION_DEADLINE: bool>(&mut self, data: &mut [T], timestamp: cpal::OutputStreamTimestamp, now: Instant)
where T: cpal::SizedSample + cpal::FromSample<f32>, f32: cpal::FromSample<T> {
self.state.callbacks.fetch_add(1, Ordering::Relaxed);
let channels = self.format.channels as usize;
data.fill(T::EQUILIBRIUM);
if data.len() % channels != 0 { self.state.fail(StreamFault::InvalidBuffer); return; }
let frames = data.len() / channels;
self.state.frames.fetch_add(frames as u64, Ordering::Relaxed);
let position = self.frame_position;
self.frame_position = self.frame_position.saturating_add(frames as u64);
let (Some(playback_at), Some(callback_at)) = (self.clock.map(timestamp.playback), self.clock.map(timestamp.callback)) else { self.state.fail(StreamFault::ClockDiscontinuity); return; };
@@ -557,13 +721,15 @@ impl PlaybackCallback {
let epoch = self.state.epoch();
let mut budget = self.consumer.capacity();
let mut underrun = 0;
#[cfg(any(target_os = "android", test))]
let mut nonzero_frames = 0;
let mut deadline_checked = false;
for offset in (0..frames).step_by(BLOCK_FRAMES) {
let count = BLOCK_FRAMES.min(frames - offset);
let Some(at) = playback_at.checked_add(frames_duration(offset as u64, self.format.sample_rate)) else { self.state.fail(StreamFault::ClockDiscontinuity); return; };
let mut rendered = RenderBlock { samples: [0.0; BLOCK_FRAMES], frames: count, sample_rate: self.format.sample_rate, epoch, playback_at: at, callback_at, frame_position: position + offset as u64 };
let mut rendered = RenderBlock { samples: [0.0; BLOCK_FRAMES], frames: count, sample_rate: self.format.sample_rate, epoch, playback_at: at, callback_at, arrived_at: now, calibration_uncertainty: self.clock.uncertainty(), frame_position: position + offset as u64, clock: ClockObservation { at: playback_at, position } };
for (index, frame) in data[offset * channels..(offset + count) * channels].chunks_exact_mut(channels).enumerate() {
let stereo = match self.next_frame(epoch, now, playback_at, offset + index, &mut deadline_checked, &mut budget) {
let stereo = match self.next_frame::<PRESENTATION_DEADLINE>(epoch, now, playback_at, offset + index, &mut deadline_checked, &mut budget) {
Some(stereo) => [finite_sample(stereo[0]), finite_sample(stereo[1])],
None => { underrun += 1; [0.0; 2] }
};
@@ -576,6 +742,8 @@ impl PlaybackCallback {
frame[1] = T::from_sample(stereo[1]);
rendered.samples[index] = (<f32 as cpal::Sample>::from_sample(frame[0]) + <f32 as cpal::Sample>::from_sample(frame[1])) * 0.5;
}
#[cfg(any(target_os = "android", test))]
if frame[0] != T::EQUILIBRIUM || (channels > 1 && frame[1] != T::EQUILIBRIUM) { nonzero_frames += 1; }
}
if self.references.try_push(rendered).is_err() {
self.state.dropped_blocks.fetch_add(1, Ordering::Relaxed);
@@ -584,6 +752,8 @@ impl PlaybackCallback {
}
}
self.state.underrun_frames.fetch_add(underrun, Ordering::Relaxed);
#[cfg(any(target_os = "android", test))]
self.state.nonzero_frames.fetch_add(nonzero_frames, Ordering::Relaxed);
}
}
@@ -615,19 +785,28 @@ where T: cpal::SizedSample + cpal::FromSample<f32>, f32: cpal::FromSample<T> {
device.build_output_stream(callback.format.stream_config(), move |data: &mut [T], info| callback.process(data, info.timestamp(), Instant::now()), move |error| errors.on_error(error), Some(STREAM_START_TIMEOUT)).map_err(audio_error)
}
pub fn start_capture(selected: SelectedDevice, permission: StartPermission, epoch: u64) -> Result<(StreamOwner, CapturePort)> {
/// Preserve a callback fault even when backend start fails before engine publication.
pub struct StreamStartFailure { pub error: ServiceError, pub stats: Option<StreamStats> }
impl From<ServiceError> for StreamStartFailure {
fn from(error: ServiceError) -> Self { Self { error, stats: None } }
}
impl StreamStartFailure {
fn observed(error: ServiceError, state: &StreamState) -> Self { Self { error, stats: Some(state.stats()) } }
}
pub fn start_capture(selected: SelectedDevice, permission: StartPermission, epoch: u64) -> std::result::Result<(StreamOwner, CapturePort), StreamStartFailure> {
permission.require()?;
if selected.direction != Direction::Input { return Err(ServiceError::new("audio_direction_mismatch", "An input device is required for capture")); }
if selected.direction != Direction::Input { return Err(ServiceError::new("audio_direction_mismatch", "An input device is required for capture").into()); }
selected.format.validate()?;
let origin = Instant::now();
let state = Arc::new(StreamState::new(epoch, origin));
let clock = Arc::new(ClockAnchor::new(origin));
let (producer, samples) = ring::channel(queue_capacity(selected.format.sample_rate));
let callback = CaptureCallback { producer, state: state.clone(), clock: clock.clone(), format: selected.format, frame_position: 0, expected_at: None };
let stream = dispatch_pcm!(selected.format.sample_format, build_capture, &selected.device, callback, state.clone())?;
let stream = dispatch_pcm!(selected.format.sample_format, build_capture, &selected.device, callback, state.clone()).map_err(|error| StreamStartFailure::observed(error, &state))?;
clock.calibrate(&stream);
// Capture remains gated until the parent explicitly resumes after its ack.
stream.play().map_err(audio_error)?;
stream.play().map_err(audio_error).map_err(|error| StreamStartFailure::observed(error, &state))?;
let owner = StreamOwner { stream: Some(stream), state: state.clone(), device_id: selected.id, format: selected.format, _owner_thread: PhantomData };
Ok((owner, CapturePort { samples, state }))
}
@@ -635,9 +814,9 @@ pub fn start_capture(selected: SelectedDevice, permission: StartPermission, epoc
/// Starts the OS callback with PCM forwarding disabled. The engine must publish
/// the state under its privacy-generation fence before explicitly calling
/// `state.resume()`. Until then the callback submits silence only.
pub fn start_playback(selected: SelectedDevice, permission: StartPermission, epoch: u64) -> Result<(StreamOwner, PlaybackPort)> {
pub fn start_playback(selected: SelectedDevice, permission: StartPermission, epoch: u64) -> std::result::Result<(StreamOwner, PlaybackPort), StreamStartFailure> {
permission.require()?;
if selected.direction != Direction::Output { return Err(ServiceError::new("audio_direction_mismatch", "An output device is required for playback")); }
if selected.direction != Direction::Output { return Err(ServiceError::new("audio_direction_mismatch", "An output device is required for playback").into()); }
selected.format.validate()?;
let origin = Instant::now();
let state = Arc::new(StreamState::new(epoch, origin));
@@ -646,14 +825,83 @@ pub fn start_playback(selected: SelectedDevice, permission: StartPermission, epo
let (samples, consumer) = ring::channel(capacity);
let (references, rendered) = ring::channel(capacity);
let callback = PlaybackCallback { consumer, references, state: state.clone(), clock: clock.clone(), format: selected.format, current: None, current_offset: 0, frame_position: 0, expected_at: None };
let stream = dispatch_pcm!(selected.format.sample_format, build_playback, &selected.device, callback, state.clone())?;
let stream = dispatch_pcm!(selected.format.sample_format, build_playback, &selected.device, callback, state.clone()).map_err(|error| StreamStartFailure::observed(error, &state))?;
#[cfg(target_os = "android")]
let device_id = if let cpal::platform::StreamInner::AAudio(aaudio) = stream.as_inner() {
aaudio.device_id().map_err(audio_error).map_err(|error| StreamStartFailure::observed(error, &state))?.to_string()
} else { selected.id };
#[cfg(not(target_os = "android"))]
let device_id = selected.id;
clock.calibrate(&stream);
// The engine, not backend construction, grants the playback generation.
stream.play().map_err(audio_error)?;
let owner = StreamOwner { stream: Some(stream), state: state.clone(), device_id: selected.id, format: selected.format, _owner_thread: PhantomData };
stream.play().map_err(audio_error).map_err(|error| StreamStartFailure::observed(error, &state))?;
let owner = StreamOwner { stream: Some(stream), state: state.clone(), device_id, format: selected.format, _owner_thread: PhantomData };
Ok((owner, PlaybackPort { samples, rendered, state }))
}
#[cfg(test)]
#[path = "devices_tests.rs"]
mod tests;
#[cfg(test)]
mod playback_diagnostics_tests {
use super::*;
fn fixture(now: Instant) -> (PlaybackCallback, Producer<PlaybackBlock>) {
let format = DeviceFormat { sample_rate: 48_000, channels: 2, sample_format: SampleFormat::F32, buffer_size: BufferSize::Default };
let state = Arc::new(StreamState::new(7, now));
assert!(state.resume());
let (producer, consumer) = ring::channel(8);
let (references, _rendered) = ring::channel(8);
(PlaybackCallback { consumer, references, state, clock: Arc::new(ClockAnchor::new(now)),
format, current: None, current_offset: 0, frame_position: 0, expected_at: None }, producer)
}
fn block(now: Instant) -> PlaybackBlock {
let mut block = PlaybackBlock::silence(48_000, 7, now);
block.frames = 1;
block.samples[0] = [0.25; 2];
block
}
#[test]
fn expired_and_old_epoch_blocks_are_counted_once_without_changing_scan_behavior() {
let now = Instant::now();
let (mut callback, mut producer) = fixture(now);
let mut old = block(now);
old.epoch = 6;
producer.try_push(old).unwrap();
let mut expired = block(now);
expired.expires_at = now;
producer.try_push(expired).unwrap();
producer.try_push(block(now)).unwrap();
let mut budget = 8;
let mut checked = false;
assert_eq!(callback.next_frame::<true>(7, now, now, 0, &mut checked, &mut budget), Some([0.25; 2]));
assert_eq!(callback.next_frame::<true>(7, now, now, 1, &mut checked, &mut budget), None);
let stats = callback.state.stats();
assert_eq!((stats.discarded_route_blocks, stats.discarded_time_blocks), (1, 1));
assert_eq!(stats.fault, StreamFault::None);
}
#[test]
fn hardware_deadline_and_suspended_partial_block_have_distinct_discard_counters() {
let now = Instant::now();
let (mut callback, mut producer) = fixture(now);
let mut late = block(now);
late.expires_at = now + Duration::from_millis(1);
producer.try_push(late).unwrap();
let mut budget = 8;
let mut checked = false;
assert_eq!(callback.next_frame::<true>(7, now, now + Duration::from_millis(1), 0, &mut checked, &mut budget), None);
let mut partial = block(now);
partial.frames = 2;
callback.current = Some(partial);
callback.current_offset = 1;
callback.state.suspend();
assert_eq!(callback.next_frame::<true>(7, now, now, 0, &mut checked, &mut budget), None);
assert_eq!(callback.next_frame::<true>(7, now, now, 0, &mut checked, &mut budget), None);
let stats = callback.state.stats();
assert_eq!((stats.discarded_route_blocks, stats.discarded_time_blocks), (1, 1));
}
}
+336 -7
View File
@@ -90,6 +90,31 @@ fn explicit_unsupported_configuration_never_silently_changes_rate() {
assert!(select_format(&[range(2, 48_000, 48_000, SampleFormat::DsdU8)], Direction::Output, None).is_err());
}
#[test]
fn resolved_default_uses_physical_mono_16k_i16_before_stream_preparation() {
let generic = select_format(&[range(2, 48_000, 48_000, SampleFormat::F32)], Direction::Output, None).unwrap();
let physical = || Ok(vec![range(1, 16_000, 16_000, SampleFormat::I16)]);
let resolved = resolved_output_format(generic, None, true, physical).unwrap();
assert_eq!((resolved.channels, resolved.sample_rate, resolved.sample_format), (1, 16_000, SampleFormat::I16));
assert_eq!(resolved.stream_config().channels, 1);
assert_eq!(resolved.stream_config().sample_rate, 16_000);
assert_eq!(resolved.buffer_size, BufferSize::Fixed(160));
// An explicit PCM request is still exact: resolving default must not grant
// permission to replace an unsupported requested shape.
assert_eq!(resolved_output_format(generic, Some(generic), true, physical).unwrap_err().code,
"audio_configuration_unsupported");
assert_eq!(resolved_output_format(generic, Some(resolved), true, physical).unwrap(), resolved);
}
#[test]
fn exact_and_unresolved_output_keep_format_without_another_capability_probe() {
let current = format(48_000, 2);
assert_eq!(resolved_output_format(current, None, false, || panic!("unchanged endpoint must not be probed")).unwrap(), current);
let failure = resolved_output_format(current, None, true,
|| Err(ServiceError::new("audio_device_missing", "Physical endpoint disappeared"))).unwrap_err();
assert_eq!(failure.code, "audio_device_missing");
}
#[test]
fn capture_splits_variable_callback_and_preserves_hardware_clock() {
let (mut callback, mut samples, origin) = capture_fixture(48_000, 2, 4);
@@ -101,6 +126,8 @@ fn capture_splits_variable_callback_and_preserves_hardware_clock() {
assert_eq!(block.frame_position, position);
assert_eq!(block.captured_at, origin + frames_duration(position, 48_000));
assert_eq!(block.callback_at, origin + Duration::from_millis(15));
assert_eq!(block.arrived_at, origin + Duration::from_millis(15));
assert_eq!(block.calibration_uncertainty, Duration::ZERO);
assert_eq!(block.epoch, 7);
assert!(block.samples[..frames].iter().all(|&sample| sample == 0.5));
}
@@ -166,6 +193,38 @@ fn clock_mapping_aligns_independent_stream_origins_without_callback_jitter() {
assert_eq!(a.map(StreamInstant::from_millis(9990)), origin.checked_sub(Duration::from_millis(8)));
}
#[test]
fn calibrated_bracket_is_retained_without_replacing_hardware_capture_time() {
let (mut callback, mut samples, origin) = capture_fixture(48_000, 1, 2);
callback.clock.set_calibration(origin, StreamInstant::from_millis(0), origin + Duration::from_millis(10));
callback.process(&[0.5_f32; 48], input_time(0, 20), origin + Duration::from_millis(6));
let block = samples.try_pop().unwrap();
assert_eq!(block.captured_at, origin + Duration::from_millis(5));
assert_eq!(block.callback_at, origin + Duration::from_millis(25));
assert_eq!(block.arrived_at, origin + Duration::from_millis(6));
assert_eq!(block.calibration_uncertainty, Duration::from_millis(5));
}
#[test]
fn calibration_uncertainty_does_not_authorize_future_hardware_capture() {
let (mut callback, mut samples, origin) = capture_fixture(48_000, 1, 2);
callback.clock.set_calibration(origin, StreamInstant::from_millis(0), origin + Duration::from_millis(10));
callback.process(&[0.5_f32; 48], input_time(0, 1), origin + Duration::from_millis(4));
assert!(samples.try_pop().is_none(), "mapped capture remains future even within the calibration bracket");
}
#[test]
fn render_queue_arrival_is_not_the_mapped_backend_callback() {
let (mut callback, _samples, mut rendered, origin) = playback_fixture(48_000, 1, 2);
callback.clock.set_calibration(origin, StreamInstant::from_millis(0), origin + Duration::from_nanos(3));
callback.process(&mut [0.0_f32; 48], output_time(20, 30), origin + Duration::from_millis(1));
let block = rendered.try_pop().unwrap();
assert_eq!(block.arrived_at, origin + Duration::from_millis(1));
assert_eq!(block.callback_at, origin + Duration::from_millis(20) + Duration::from_nanos(1));
assert_eq!(block.playback_at, origin + Duration::from_millis(30) + Duration::from_nanos(1));
assert_eq!(block.calibration_uncertainty, Duration::from_nanos(2));
}
#[test]
fn device_clock_discontinuity_disables_capture() {
let (mut callback, mut samples, origin) = capture_fixture(48_000, 1, 2);
@@ -176,6 +235,71 @@ fn device_clock_discontinuity_disables_capture() {
assert!(samples.try_pop().is_none());
}
#[test]
fn overlapping_bursty_playback_estimates_keep_raw_callback_observations() {
for rate in [44_100, 48_000] {
let (mut callback, _samples, mut rendered, origin) = playback_fixture(rate, 1, 32);
let mut tracker = super::super::resample::ClockTracker::new(rate).unwrap();
let mut previous_block_at = None;
let mut saw_chunk_overlap = false;
// The observed Android failure had five callbacks / 4100 frames, no
// dropped PCM and no CPAL xrun. Callback estimates may repeat or arrive
// in a burst, even though every callback contains multiple 256 blocks.
for (index, millis) in [0, 0, 1, 2, 3].into_iter().enumerate() {
callback.process(&mut [0.0_f32; 820], output_time(millis, millis + 10), origin + Duration::from_millis(millis));
for offset in (0..820).step_by(BLOCK_FRAMES) {
let block = rendered.try_pop().unwrap();
assert_eq!(block.clock, ClockObservation { at: origin + Duration::from_millis(millis + 10), position: index as u64 * 820 });
assert_eq!(block.playback_at, block.clock.at + frames_duration(offset as u64, rate));
assert_eq!(block.frame_position, block.clock.position + offset as u64);
if previous_block_at.is_some_and(|previous| block.playback_at < previous) { saw_chunk_overlap = true; }
previous_block_at = Some(block.playback_at);
assert_eq!(tracker.observe(block.clock.at, block.clock.position), Ok(None));
}
}
assert!(saw_chunk_overlap, "regression must exercise the actual split-block reversal");
let stats = callback.state.stats();
assert_eq!(stats.callbacks, 5);
assert_eq!(stats.frames, 4100);
assert_eq!(stats.xruns, 0);
assert_eq!(stats.dropped_blocks, 0);
assert_eq!(stats.fault, StreamFault::None);
}
}
#[test]
fn exact_1024_frame_callback_split_with_five_ms_next_estimate_does_not_fault() {
for rate in [44_100, 48_000] {
let (mut callback, _samples, mut rendered, origin) = playback_fixture(rate, 1, 8);
let mut tracker = super::super::resample::ClockTracker::new(rate).unwrap();
for millis in [0, 5] {
callback.process(&mut [0.0_f32; 1024], output_time(millis, millis), origin + Duration::from_millis(millis));
for _ in 0..4 {
let block = rendered.try_pop().unwrap();
assert_eq!(tracker.observe(block.clock.at, block.clock.position), Ok(None));
}
}
assert_eq!(callback.state.fault(), StreamFault::None);
assert_eq!(callback.state.stats().xruns, 0);
}
}
#[test]
fn desktop_overlapping_playback_estimates_do_not_refresh_source_expiry() {
let (mut callback, mut samples, mut rendered, origin) = playback_fixture(48_000, 1, 8);
callback.process(&mut [0.0_f32; 1024], output_time(0, 0), origin);
rendered.discard_pending();
let mut expiring = block(origin, 256, [0.75; 2]);
expiring.expires_at = origin + Duration::from_millis(9);
samples.try_push(expiring).unwrap();
let mut output = [1.0_f32; 256];
// The next callback's raw estimate overlaps the previous callback's last
// subblock. Its proposed last frame is still after the source deadline.
callback.process_with_deadline::<_, true>(&mut output, output_time(5, 5), origin + Duration::from_millis(5));
assert_eq!(output, [0.0; 256]);
assert_eq!(callback.state.fault(), StreamFault::None);
}
#[test]
fn playback_preserves_stereo_and_reports_submitted_quantized_reference() {
let (mut callback, mut samples, mut rendered, origin) = playback_fixture(48_000, 2, 4);
@@ -191,6 +315,7 @@ fn playback_preserves_stereo_and_reports_submitted_quantized_reference() {
assert_eq!(reference.playback_at, origin + Duration::from_millis(10));
assert_eq!(reference.frame_position, 0);
assert_eq!(callback.state.stats().underrun_frames, 2);
assert_eq!(callback.state.stats().nonzero_frames, 2);
}
#[test]
@@ -320,20 +445,20 @@ fn ring_capacity_is_bounded_by_200ms_at_device_rate() {
}
#[test]
fn fresh_worker_block_does_not_refresh_old_source_expiry() {
fn desktop_fresh_worker_block_does_not_refresh_old_source_expiry() {
let (mut callback, mut samples, mut references, origin) = playback_fixture(48_000, 1, 4);
let now = origin + Duration::from_millis(190);
let mut old_source = block(now, 2, [0.8; 2]);
old_source.expires_at = origin + Duration::from_millis(200);
samples.try_push(old_source).unwrap();
let mut output = [1.0_f32; 2];
callback.process(&mut output, output_time(190, 205), now);
callback.process_with_deadline::<_, true>(&mut output, output_time(190, 205), now);
assert_eq!(output, [0.0; 2]);
assert_eq!(references.try_pop().unwrap().samples[..2], [0.0; 2]);
}
#[test]
fn entire_playback_block_must_finish_before_source_expiry() {
fn desktop_entire_playback_block_must_finish_before_source_expiry() {
let (mut callback, mut samples, _, origin) = playback_fixture(48_000, 1, 4);
let now = origin + Duration::from_millis(190);
let mut crossing_deadline = block(now, 256, [0.8; 2]);
@@ -341,7 +466,7 @@ fn entire_playback_block_must_finish_before_source_expiry() {
samples.try_push(crossing_deadline).unwrap();
let mut output = [1.0_f32; 256];
// First sample is timely, last would be presented after 200 ms.
callback.process(&mut output, output_time(190, 195), now);
callback.process_with_deadline::<_, true>(&mut output, output_time(190, 195), now);
assert_eq!(output, [0.0; 256]);
}
@@ -359,16 +484,16 @@ fn exact_expiry_is_rejected_but_fresh_following_block_can_play() {
}
#[test]
fn partial_block_expiry_is_rechecked_after_hardware_schedule_change() {
fn desktop_partial_block_expiry_is_rechecked_after_hardware_schedule_change() {
let (mut callback, mut samples, mut references, origin) = playback_fixture(48_000, 1, 4);
let mut pending = block(origin, 48, [0.5; 2]);
pending.expires_at = origin + Duration::from_millis(20);
samples.try_push(pending).unwrap();
let mut output = [0.0_f32; 24];
callback.process(&mut output, output_time(0, 10), origin);
callback.process_with_deadline::<_, true>(&mut output, output_time(0, 10), origin);
assert_eq!(output, [0.5; 24]);
references.discard_pending();
callback.process(&mut output, output_time(15, 20), origin + Duration::from_millis(15));
callback.process_with_deadline::<_, true>(&mut output, output_time(15, 20), origin + Duration::from_millis(15));
assert_eq!(output, [0.0; 24]);
assert_eq!(references.try_pop().unwrap().samples[..24], [0.0; 24]);
}
@@ -388,3 +513,207 @@ fn unpublished_playback_state_emits_only_silence_until_explicit_resume() {
assert_eq!(output, [0.5; 2]);
assert_eq!(references.try_pop().unwrap().samples[..2], [0.5; 2]);
}
#[test]
fn callback_frame_xrun_counters_survive_fault_and_suspension() {
let (mut callback, _, mut references, origin) = playback_fixture(48_000, 1, 4);
let mut data = [1.0_f32; 48];
callback.process(&mut data, output_time(0, 10), origin);
references.discard_pending();
callback.process(&mut data, output_time(1, 11), origin + Duration::from_millis(1));
callback.state.on_error(cpal::Error::new(cpal::ErrorKind::Xrun));
callback.state.on_error(cpal::Error::new(cpal::ErrorKind::DeviceNotAvailable));
callback.state.suspend();
let stats = callback.state.stats();
assert_eq!(stats.callbacks, 2);
assert_eq!(stats.frames, 96);
assert_eq!(stats.underrun_frames, 96);
assert_eq!(stats.xruns, 1);
assert_eq!(stats.epoch, 7);
assert_eq!(stats.fault, StreamFault::ClockDiscontinuity);
assert!(!stats.enabled);
// A failed backend start retains the same evidence before its owner is dropped.
let failure = StreamStartFailure::observed(ServiceError::new("audio_device_error", "not retained in diagnostics"), &callback.state);
assert_eq!(failure.stats.unwrap().xruns, 1);
}
#[test]
fn synchronous_start_errors_keep_the_known_backend_cause_code() {
assert_eq!(audio_error(cpal::Error::new(cpal::ErrorKind::Xrun)).code, "audio_clock_discontinuity");
assert_eq!(audio_error(cpal::Error::new(cpal::ErrorKind::DeviceChanged)).code, "audio_route_changed");
assert_eq!(audio_error(cpal::Error::new(cpal::ErrorKind::StreamInvalidated)).code, "audio_stream_invalidated");
}
#[path = "../../../vendor/cpal-0.18.2/src/host/aaudio/capture_timing.rs"]
mod android_capture_timing;
#[cfg(not(target_os = "android"))]
#[path = "../../../vendor/cpal-0.18.2/src/host/aaudio/output_usage.rs"]
mod android_output_usage;
#[cfg(not(target_os = "android"))]
#[path = "../../../vendor/cpal-0.18.2/src/host/aaudio/stream_start.rs"]
mod android_stream_start;
#[test]
fn android_end_counter_projects_complete_capture_buffers_without_time_compression() {
for rate in [44_100_u32, 48_000] {
let (mut callback, mut consumer, origin) = capture_fixture(rate, 1, 8);
let mut received = 0_u64;
for packet in 0..100_u64 {
let first = packet * 480;
let stamp = android_capture_timing::input_capture_nanos(0, 1_000_000_000,
(first + 480) as i64, 480, rate).unwrap();
let arrived_ns = 1_000_000_000 + ((first + 480) * 1_000_000_000 / u64::from(rate)) + 1_000_000;
callback.process(&[0.125_f32;480], cpal::InputStreamTimestamp {
capture: StreamInstant::from_nanos(stamp),
callback: StreamInstant::from_nanos(arrived_ns),
}, origin + Duration::from_nanos(arrived_ns));
while let Some(block) = consumer.try_pop() {
assert_eq!(block.frame_position, received);
assert_eq!(&block.samples[..block.frames], &[0.125;256][..block.frames]);
received += block.frames as u64;
}
assert_eq!(received, first + 480, "rate={rate}, packet={packet}: no chopped callback suffix");
}
assert_eq!(received, 48_000);
assert_eq!(callback.state.fault(), StreamFault::None);
}
}
#[test]
fn android_handoff_preserves_fresh_pcm_despite_long_device_latency() {
for latency_ms in [0, 100, 300, 800] {
let (mut callback, mut samples, mut references, origin) = playback_fixture(16_000, 1, 4);
let mut pcm = block(origin, 160, [0.25; 2]);
pcm.sample_rate = 16_000;
samples.try_push(pcm).unwrap();
let mut output = [0_i16; 160];
callback.process_with_deadline::<_, false>(&mut output, output_time(50, 50 + latency_ms), origin + Duration::from_millis(50));
assert_eq!(output, [8192; 160]);
let rendered = references.try_pop().unwrap();
assert_eq!(rendered.samples[..160], [0.25; 160]);
assert_eq!(rendered.playback_at, origin + Duration::from_millis(50 + latency_ms));
let stats = callback.state.stats();
assert_eq!((stats.nonzero_frames, stats.underrun_frames, stats.discarded_time_blocks), (160, 0, 0));
}
}
#[test]
fn android_handoff_still_rejects_expired_future_old_epoch_and_muted_pcm() {
for rejected in ["expired", "future", "old epoch", "muted"] {
let (mut callback, mut samples, _, origin) = playback_fixture(16_000, 1, 4);
let now = origin + Duration::from_millis(100);
let mut pcm = block(origin, 160, [0.5; 2]);
pcm.sample_rate = 16_000;
match rejected {
"expired" => pcm.expires_at = now,
"future" => pcm.produced_at = now + Duration::from_nanos(1),
"old epoch" => pcm.epoch = 6,
"muted" => callback.state.suspend(),
_ => unreachable!(),
}
samples.try_push(pcm).unwrap();
let mut output = [123_i16; 160];
callback.process_with_deadline::<_, false>(&mut output, output_time(100, 500), now);
assert_eq!(output, [0; 160], "{rejected}");
assert_eq!(callback.state.stats().nonzero_frames, 0);
assert_eq!(callback.state.stats().underrun_frames, 160);
}
}
#[test]
fn android_handoff_partial_block_expires_without_extending_original_source_deadline() {
let (mut callback, mut samples, mut references, origin) = playback_fixture(16_000, 1, 4);
let mut pcm = block(origin, 160, [0.25; 2]);
pcm.sample_rate = 16_000;
pcm.expires_at = origin + Duration::from_millis(20);
samples.try_push(pcm).unwrap();
let mut output = [0_i16; 80];
callback.process_with_deadline::<_, false>(&mut output, output_time(15, 415), origin + Duration::from_millis(15));
assert_eq!(output, [8192; 80]);
references.discard_pending();
callback.process_with_deadline::<_, false>(&mut output, output_time(20, 420), origin + Duration::from_millis(20));
assert_eq!(output, [0; 80]);
assert_eq!((callback.state.stats().nonzero_frames, callback.state.stats().discarded_time_blocks), (80, 1));
}
#[test]
fn android_resampled_voice_reaches_mono_i16_callback_with_transport_latency() {
use super::super::resample::AudioResampler;
for rate in [8_000, 16_000, 48_000] {
let mut resampler = AudioResampler::new_playback(rate, 2).unwrap();
let mut converted = vec![0.0; resampler.output_frames_max() * 2];
let (mut callback, mut samples, mut references, origin) = playback_fixture(rate, 1, 8);
callback.format.sample_format = SampleFormat::I16;
let mut written_nonzero = 0;
for tick in 0..60 {
let millis = tick * 10;
let now = origin + Duration::from_millis(millis);
let count = resampler.process_interleaved(&[0.25; 960], &mut converted).unwrap();
assert_eq!(count.consumed, 480);
for chunk in converted[..count.produced * 2].chunks(BLOCK_FRAMES * 2) {
let mut pcm = PlaybackBlock::silence(rate, 7, now);
pcm.frames = chunk.len() / 2;
for (destination, source) in pcm.samples.iter_mut().zip(chunk.chunks_exact(2)) { *destination = [source[0], source[1]]; }
samples.try_push(pcm).unwrap();
}
let mut output = vec![0_i16; count.produced];
callback.process_with_deadline::<_, false>(&mut output, output_time(millis, millis + 400), now);
if tick >= 10 {
assert!(output.iter().all(|sample| (i32::from(*sample) - 8192).abs() <= 32), "steady mono amplitude at {rate} Hz");
}
written_nonzero += output.iter().filter(|&&sample| sample != 0).count() as u64;
for reference in std::iter::from_fn(|| references.try_pop()) {
assert_eq!(reference.sample_rate, rate);
assert_eq!(reference.epoch, 7);
}
}
let stats = callback.state.stats();
assert_eq!(stats.nonzero_frames, written_nonzero);
assert!(stats.nonzero_frames > u64::from(rate) / 3, "more than 333 ms of nonzero quantized voice must reach the callback");
assert!((stats.frames as i64 - i64::from(rate) * 60 / 100).abs() < i64::from(rate) / 10, "device-rate duration must match the 600 ms source within SRC startup delay");
assert_eq!(stats.discarded_time_blocks, 0);
assert_eq!(stats.underrun_frames, 0);
assert_eq!(stats.fault, StreamFault::None);
}
}
#[test]
fn android_capture_queues_future_tail_instead_of_creating_frame_position_gap() {
let (mut callback, mut samples, origin) = capture_fixture(16_000, 1, 8);
for start_ms in [0, 20] {
callback.process_with_future_hold::<_, true>(&[8192_i16; 320], input_time(start_ms, start_ms + 10), origin + Duration::from_millis(start_ms + 10));
}
let mut next_position = 0;
for (frames, capture_ms, arrived_ms) in [(256, 0, 10), (64, 16, 10), (256, 20, 30), (64, 36, 30)] {
let packet = samples.try_pop().unwrap();
assert_eq!(packet.frame_position, next_position);
assert_eq!(packet.frames, frames);
assert_eq!(packet.captured_at, origin + Duration::from_millis(capture_ms));
assert_eq!(packet.arrived_at, origin + Duration::from_millis(arrived_ms));
assert!(packet.samples[..frames].iter().all(|&sample| sample == 0.25));
next_position += frames as u64;
}
assert_eq!(next_position, 640);
assert!(samples.try_pop().is_none());
assert_eq!(callback.state.fault(), StreamFault::None);
}
#[test]
fn android_capture_quarantine_keeps_boundary_mute_and_clock_bounds() {
let (mut callback, mut samples, origin) = capture_fixture(16_000, 1, 8);
callback.state.set_epoch(8, origin + Duration::from_millis(15));
assert!(callback.state.resume());
callback.process_with_future_hold::<_, true>(&[8192_i16; 320], input_time(0, 10), origin + Duration::from_millis(10));
let admitted = samples.try_pop().unwrap();
assert_eq!((admitted.epoch, admitted.frame_position, admitted.frames), (8, 256, 64));
assert_eq!(admitted.captured_at, origin + Duration::from_millis(16));
assert!(samples.try_pop().is_none(), "pre-boundary microphone samples remain rejected");
callback.state.suspend();
callback.process_with_future_hold::<_, true>(&[8192_i16; 320], input_time(20, 30), origin + Duration::from_millis(30));
assert!(samples.try_pop().is_none(), "mute still prevents queue admission");
let (mut future, mut samples, origin) = capture_fixture(16_000, 1, 8);
future.process_with_future_hold::<_, true>(&[8192_i16; 320], input_time(201, 0), origin);
assert!(samples.try_pop().is_none(), "far-future timestamps cannot acquire extra freshness");
}
+99
View File
@@ -0,0 +1,99 @@
//! Sanitized counters and fixed-capacity log gates; never retain media or route identities.
#![cfg_attr(not(any(target_os = "android", test)), allow(dead_code))]
use std::time::{Duration, Instant};
#[cfg(any(target_os = "android", test))]
use std::sync::atomic::{AtomicU64, Ordering};
pub(super) const REPORT_INTERVAL: Duration = Duration::from_secs(5);
#[derive(Default)]
pub(super) struct Counter {
#[cfg(any(target_os = "android", test))]
value: AtomicU64,
}
impl Counter {
pub fn increment(&self) {
#[cfg(any(target_os = "android", test))]
self.value.fetch_add(1, Ordering::Relaxed);
}
pub fn load(&self) -> u64 {
#[cfg(any(target_os = "android", test))]
{ self.value.load(Ordering::Relaxed) }
#[cfg(not(any(target_os = "android", test)))]
{ 0 }
}
pub fn record_max(&self, value: u64) {
#[cfg(any(target_os = "android", test))]
self.value.fetch_max(value, Ordering::Relaxed);
#[cfg(not(any(target_os = "android", test)))]
let _ = value;
}
}
macro_rules! counters {
($($name:ident),+ $(,)?) => {
#[derive(Default)]
pub(super) struct Counters { $(pub $name: Counter),+ }
#[allow(dead_code)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Totals { $(pub $name: u64),+ }
impl Counters {
pub fn totals(&self) -> Totals { Totals { $($name: self.$name.load()),+ } }
}
};
}
counters!(binding_received, binding_route_drop, rx_offered, rx_enqueued, rx_queue_drop,
rx_accepted, rx_route_drop, rx_time_drop, rx_mixer_drop,
tx_accepted, tx_frame_drop, tx_permit_revoked, command_logs_suppressed,
voice_nonzero_blocks, voice_peak_bucket_max);
impl Counters {
/// Coarse aggregate only; no sample, exact magnitude, timing or media is retained.
pub fn observe_voice(&self, pcm: &[[f32; 2]]) {
#[cfg(any(target_os = "android", test))]
{
let peak = pcm.iter().flatten().fold(0_f32, |peak, sample| peak.max(sample.abs()));
let bucket = if peak == 0. { 0 } else if peak < 0.001 { 1 }
else if peak < 0.01 { 2 } else if peak < 0.1 { 3 } else { 4 };
if bucket != 0 { self.voice_nonzero_blocks.increment(); }
self.voice_peak_bucket_max.record_max(bucket);
}
#[cfg(not(any(target_os = "android", test)))]
let _ = pcm;
}
}
/// Activation starts a new window; idle time never causes an immediate report.
#[allow(dead_code)]
#[derive(Default)]
pub(super) struct SummaryGate { since: Option<Instant> }
#[allow(dead_code)]
impl SummaryGate {
pub fn due(&mut self, now: Instant, active: bool) -> bool {
if !active { self.since = None; return false; }
let Some(since) = self.since else { self.since = Some(now); return false; };
if now.saturating_duration_since(since) < REPORT_INTERVAL { return false; }
self.since = Some(now);
true
}
}
/// One begin/end pair per command kind per window, including per-frame commands.
/// Fixed labels only, and fixed storage: no strings from commands are retained.
#[allow(dead_code)]
#[derive(Default)]
pub(super) struct CommandGate { last: [Option<Instant>; 26] }
#[allow(dead_code)]
impl CommandGate {
pub fn admit(&mut self, name: &'static str, now: Instant) -> bool {
const NAMES: [&str; 26] = ["enumerate", "pin_host", "select_input", "select_output",
"start_input", "start_output", "stop_input", "stop_output", "bind_permit",
"activate_connection", "connection_enabled", "remove_connection", "stream_gain",
"remove_stream", "playback_dsp", "voice_gain", "transmitting", "typing_enabled",
"typing_hit", "whisper", "configure_notifications", "notify", "begin_microphone_test",
"listen_microphone_test", "stop_microphone_test", "finish_microphone_test"];
let Some(index) = NAMES.iter().position(|candidate| *candidate == name) else { return false; };
if self.last[index].is_some_and(|last| now.saturating_duration_since(last) < REPORT_INTERVAL) { return false; }
self.last[index] = Some(now);
true
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+109
View File
@@ -0,0 +1,109 @@
//! Slow device and DSP lifecycle work has a separate owner from live PCM servicing.
//! CPAL values never cross this thread boundary; only callback ports and inert leases do.
use super::*;
type Job = Box<dyn FnOnce(&mut DeviceOwner) + Send>;
pub(super) struct Lifecycle {
jobs: Option<SyncSender<Job>>,
thread: Option<JoinHandle<()>>,
}
impl Lifecycle {
pub(super) fn new() -> Result<Self> {
let (jobs, receive) = mpsc::sync_channel::<Job>(1);
let thread = thread::Builder::new().name("teamspeach-audio-lifecycle".into()).spawn(move || {
let mut owner = DeviceOwner { host: None, streams: Vec::with_capacity(3), notifications: NotificationOutput::new() };
loop {
// Retirement may block in a backend. The live PCM worker remains runnable.
let next = receive.recv_timeout(Duration::from_millis(1));
owner.streams.retain(|(_, retired)| !retired.load(Ordering::Acquire));
match next {
Ok(job) => job(&mut owner),
Err(mpsc::RecvTimeoutError::Timeout) => (),
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
}
owner.streams.clear(); // Destroy streams before their backend host.
}).map_err(|error| ServiceError::new("audio_worker", error.to_string()))?;
Ok(Self { jobs: Some(jobs), thread: Some(thread) })
}
pub(super) fn submit<T: Send + 'static>(&self, work: impl FnOnce(&mut DeviceOwner) -> T + Send + 'static) -> Result<Receiver<T>> {
let (complete, result) = mpsc::sync_channel(1);
self.jobs.as_ref().ok_or_else(closed)?.try_send(Box::new(move |owner| {
let _ = complete.send(work(owner));
})).map_err(queue_error)?;
Ok(result)
}
}
impl Drop for Lifecycle {
fn drop(&mut self) {
self.jobs.take();
if let Some(thread) = self.thread.take() { let _ = thread.join(); }
}
}
pub(super) struct DeviceOwner {
host: Option<DeviceHost>,
streams: Vec<(StreamOwner, Arc<AtomicBool>)>,
pub(super) notifications: NotificationOutput,
}
impl DeviceOwner {
#[cfg(test)]
pub(super) fn host_initialized(&self) -> bool { self.host.is_some() }
pub(super) fn host(&mut self) -> Result<&DeviceHost> {
if self.host.is_none() { self.host = Some(DeviceHost::initial()?); }
Ok(self.host.as_ref().expect("host initialized"))
}
pub(super) fn pin(&mut self, id: &str) -> Result<()> {
if self.host.as_ref().is_some_and(|host| host.id() != id) {
return Err(ServiceError::new("audio_host_changed", "Restart the audio engine to change its pinned host"));
}
if self.host.is_none() { self.host = Some(DeviceHost::pinned(id)?); }
Ok(())
}
pub(super) fn lease(&mut self, owner: StreamOwner) -> DeviceLease {
let retired = Arc::new(AtomicBool::new(false));
let lease = DeviceLease { state: owner.state.clone(), device_id: owner.device_id.clone(), format: owner.format,
retired: retired.clone() };
self.streams.push((owner, retired));
lease
}
}
pub(super) struct DeviceLease {
pub(super) state: Arc<StreamState>,
pub(super) device_id: String,
pub(super) format: devices::DeviceFormat,
retired: Arc<AtomicBool>,
}
impl DeviceLease {
#[cfg(test)]
pub(super) fn test(format: devices::DeviceFormat, epoch: u64, origin: Instant) -> Self {
let state = Arc::new(StreamState::new(epoch, origin));
assert!(state.resume());
Self { state, device_id: "test-only".into(), format, retired: Arc::new(AtomicBool::new(false)) }
}
#[cfg(test)]
pub(super) fn capture_test(epoch: u64) -> Result<(Self, CapturePort, MonoConversion)> {
let format = devices::DeviceFormat { sample_rate: 48_000, channels: 1,
sample_format: cpal::SampleFormat::F32, buffer_size: cpal::BufferSize::Default };
let lease = Self::test(format, epoch, Instant::now());
lease.state.suspend();
let port = devices::test_capture_port(lease.state.clone(), format, lease.retired.clone());
Ok((lease, port, MonoConversion::new(format.sample_rate)?))
}
#[cfg(test)]
pub(super) fn playback_test(epoch: u64) -> (Self, PlaybackPort, Arc<AtomicU64>) {
let format = devices::DeviceFormat { sample_rate: 48_000, channels: 1,
sample_format: cpal::SampleFormat::F32, buffer_size: cpal::BufferSize::Default };
let lease = Self::test(format, epoch, Instant::now());
let (port, audible) = devices::test_playback_port(lease.state.clone(), format, lease.retired.clone());
(lease, port, audible)
}
}
impl Drop for DeviceLease {
fn drop(&mut self) {
self.state.suspend();
self.retired.store(true, Ordering::Release);
}
}
+80
View File
@@ -0,0 +1,80 @@
//! Mixer deadlines only describe live device work, not time spent suspended while idle.
use std::time::{Duration, Instant};
pub(super) const TICK: Duration = Duration::from_millis(10);
pub(super) const MAX_AGE: Duration = Duration::from_millis(200);
/// Rebase after a scheduling gap before processing queued commands/PCM. Report a
/// stall only if devices were already open; a newly requested stream gets a fresh clock.
pub(super) fn resume(next: &mut Instant, now: Instant, devices_active: bool) -> bool {
if now.saturating_duration_since(*next) > MAX_AGE {
*next = now;
devices_active
} else {
false
}
}
/// A first device has no live scheduling obligation during its backend/converter
/// construction. Do not rebase when an already-live stream waited for this command.
pub(super) fn after_command(next: &mut Instant, now: Instant, was_active: bool, is_active: bool) {
if !was_active && is_active { *next = now; }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn idle_suspend_does_not_fail_a_newly_requested_device() {
let origin = Instant::now();
let mut next = origin;
let resumed = origin + Duration::from_secs(60);
assert!(!resume(&mut next, resumed, false));
// A start command processed after resume must not inherit the old deadline.
assert!(!resume(&mut next, resumed + TICK, true));
assert_eq!(next, resumed);
}
#[test]
fn live_device_gap_fails_once_and_rebases_before_queued_work() {
let origin = Instant::now();
let mut next = origin;
let resumed = origin + MAX_AGE + Duration::from_nanos(1);
assert!(resume(&mut next, resumed, true));
assert_eq!(next, resumed);
assert!(!resume(&mut next, resumed, false));
}
#[test]
fn ordinary_jitter_keeps_the_hardware_cadence() {
let origin = Instant::now();
let mut next = origin;
assert!(!resume(&mut next, origin + TICK, true));
assert_eq!(next, origin);
assert!(!resume(&mut next, origin + MAX_AGE, true));
assert_eq!(next, origin);
assert!(!resume(&mut next, origin - TICK, false));
assert_eq!(next, origin);
}
#[test]
fn slow_first_device_creation_starts_a_fresh_live_deadline() {
let origin = Instant::now();
let mut next = origin;
let ready = origin + Duration::from_secs(2);
after_command(&mut next, ready, false, true);
assert!(!resume(&mut next, ready, true));
assert_eq!(next, ready);
assert!(resume(&mut next, ready + MAX_AGE + TICK, true));
}
#[test]
fn opening_another_device_cannot_hide_an_existing_live_stall() {
let origin = Instant::now();
let mut next = origin;
let ready = origin + Duration::from_secs(2);
after_command(&mut next, ready, true, true);
assert!(resume(&mut next, ready, true));
}
}
+6 -4
View File
@@ -70,7 +70,7 @@ pub struct NotificationOutput {
sink: Option<OutputSink>,
open_sink: Option<OutputSink>,
revision: u64,
configured: bool,
source: Option<NotificationDevice>,
gain: f32,
idle_since: Option<Instant>,
}
@@ -80,7 +80,7 @@ impl NotificationOutput {
pub fn new() -> Self {
Self { cache: VecDeque::with_capacity(BUNDLED_SOUND_NAMES.len()), cached_bytes: 0,
sessions: Vec::with_capacity(8), active: std::array::from_fn(|_| None), sink: Some(OutputSink::SystemDefault),
open_sink: None, revision: 0, configured: false, gain: 10.0_f32.powf(-23.0 / 20.0), idle_since: None }
open_sink: None, revision: 0, source: None, gain: 10.0_f32.powf(-23.0 / 20.0), idle_since: None }
}
/// Returns a retired logical sink. The engine closes it only if voice/another route does
@@ -99,7 +99,9 @@ impl NotificationOutput {
}
let sink = resolve_sink(&device, &voice_sink);
let route_changed = self.sink != sink;
if revision < self.revision || (self.configured && revision == self.revision && route_changed) {
// A voice role can resolve to a new physical endpoint after teardown without
// changing preferences. Fence logical preference changes, not that resolution.
if revision < self.revision || (revision == self.revision && self.source.as_ref().is_some_and(|source| source != &device)) {
return Err(changed());
}
if route_changed || revision != self.revision || level_db <= -200.0 { self.stop(now); }
@@ -107,7 +109,7 @@ impl NotificationOutput {
self.sink = sink;
self.revision = revision;
self.gain = if level_db <= -200.0 { 0.0 } else { 10.0_f64.powf(level_db / 20.0) as f32 };
self.configured = true;
self.source = Some(device);
Ok(retired)
}
@@ -205,3 +205,29 @@ fn preflight_rejects_silence_capacity_and_stale_requests_without_preparing() {
assert!(output.can_play(&session, 1).unwrap());
assert_eq!(output.cached_bytes(), 0);
}
#[test]
fn voice_resolution_recovers_at_same_revision_after_teardown() {
let (mut output, key, now) = output(NotificationDevice::Voice);
let old_sink = OutputSink::Explicit("voice-device".into());
assert!(output.play(prepared(1, 1), &key, 0, &old_sink, now).unwrap());
output.stop(now);
// No voice owner after StopOutput/failure: the same logical Voice preference
// temporarily resolves to default, then to the explicitly reopened endpoint.
assert_eq!(output.configure(NotificationDevice::Voice, OutputSink::SystemDefault, 0.0, 0, now).unwrap(), Some(old_sink.clone()));
assert_eq!(output.revision(), 0);
assert!(output.play(prepared(1, 1), &key, 0, &old_sink, now).is_err());
let reopened = OutputSink::Explicit("reopened-voice".into());
output.configure(NotificationDevice::Voice, reopened.clone(), 0.0, 0, now).unwrap();
assert!(output.play(prepared(1, 1), &key, 0, &reopened, now).unwrap());
assert_eq!(output.revision(), 0);
}
#[test]
fn same_physical_sink_does_not_hide_a_changed_logical_preference() {
let (mut output, _, now) = output(NotificationDevice::Voice);
let voice = OutputSink::Explicit("voice-device".into());
assert_eq!(output.configure(NotificationDevice::Explicit("voice-device".into()), voice.clone(), 0.0, 0, now).unwrap_err().code, "target_changed");
output.configure(NotificationDevice::Explicit("voice-device".into()), voice, 0.0, 1, now).unwrap();
assert_eq!(output.revision(), 1);
}
+119 -25
View File
@@ -13,6 +13,8 @@ pub const BLOCK_FRAMES: usize = 480;
pub const MAX_DRIFT_PPM: f64 = 1_000.0;
const CLOCK_WINDOW: Duration = Duration::from_secs(1);
const MAX_CLOCK_DISCONTINUITY: f64 = 0.2;
const CLOCK_SAMPLE_SPACING: Duration = Duration::from_millis(50);
const CLOCK_SAMPLES: usize = 32;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Direction { Capture, Playback }
@@ -26,6 +28,8 @@ pub struct AudioResampler {
device_rate: u32,
channels: usize,
history_tail_output_frames: usize,
source_position: f64,
last_output_source_position: f64,
}
impl AudioResampler {
@@ -59,7 +63,8 @@ impl AudioResampler {
let retained_input = 2 * parameters.sinc_len.next_multiple_of(8) + 4;
let history_tail_output_frames = (retained_input as f64 * ratio * max_relative_ratio).ceil() as usize
+ inner.output_frames_max();
Ok(Self { inner, direction, device_rate, channels, history_tail_output_frames })
Ok(Self { inner, direction, device_rate, channels, history_tail_output_frames,
source_position: 0.0, last_output_source_position: 0.0 })
}
pub fn channels(&self) -> usize { self.channels }
@@ -85,6 +90,11 @@ impl AudioResampler {
}
pub fn ratio(&self) -> f64 { self.inner.resample_ratio() }
/// Source coordinate of the FIRST frame of the most recently produced block,
/// relative to the first input frame, before subtracting sinc group delay.
/// This follows rubato's actual ramp, not nominal output-frame wall time.
pub fn last_output_source_position(&self) -> f64 { self.last_output_source_position }
/// Buffers are interleaved (a mono slice is also interleaved). Allocate their maximum
/// sizes once on the worker. Only the returned frame counts were consumed/produced.
pub fn process_interleaved(&mut self, input: &[f32], output: &mut [f32]) -> Result<ProcessedFrames> {
@@ -97,8 +107,14 @@ impl AudioResampler {
.map_err(|error| ServiceError::new("audio_buffer", error.to_string()))?;
let mut destination = InterleavedSlice::new_mut(&mut output[..output_frames * self.channels], self.channels, output_frames)
.map_err(|error| ServiceError::new("audio_buffer", error.to_string()))?;
let before = self.inner.resample_ratio().recip();
let (consumed, produced) = self.inner.process_into_buffer(&source, &mut destination, None)
.map_err(|error| ServiceError::new("audio_resampler", error.to_string()))?;
let after = self.inner.resample_ratio().recip();
self.last_output_source_position = self.source_position;
// rubato 5.0.1 advances its input index BEFORE each output frame, with
// a linear reciprocal-ratio ramp; sum exactly that arithmetic series.
self.source_position += produced as f64 * 0.5 * (before + after) + 0.5 * (after - before);
Ok(ProcessedFrames { consumed, produced })
}
@@ -118,11 +134,18 @@ impl AudioResampler {
/// Call only as part of a route/epoch boundary, after dropping queued old PCM.
pub fn reset(&mut self) -> Result<()> {
self.inner.reset();
self.source_position = 0.0;
self.last_output_source_position = 0.0;
self.inner.set_resample_ratio_relative(1.0, false)
.map_err(|error| ServiceError::new("audio_resampler", error.to_string()))
}
}
/// A backend estimate of the first frame in an entire hardware callback. Splitting
/// PCM into worker blocks does not create additional hardware clock observations.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ClockObservation { pub at: Instant, pub position: u64 }
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ClockDiscontinuity {
TimestampReversed,
@@ -131,15 +154,20 @@ pub enum ClockDiscontinuity {
DriftOutOfRange,
}
/// Estimates hardware drift from hardware first-frame timestamps, not worker wake times.
/// The device adapter maps each device clock to `Instant` before calling this. A complete
/// one-second window feeds a one-second exponential smoothing filter. On any error the
/// caller must invalidate capture/output epochs, flush PCM, reset DSP and rebuffer.
/// Tracks raw callback observations independently of PCM subdivisions. The
/// discontinuity budget is NOT timestamp precision: drift acquisition instead
/// uses a short rolling fit and its explicitly measured residual interval.
/// Timestamps project source coordinates from the latest raw callback, so even
/// an unresolved rate estimate cannot accumulate unbounded wall-clock phase.
pub struct ClockTracker {
sample_rate: u32,
anchor: Option<(Instant, u64)>,
previous: Option<(Instant, u64)>,
anchor: Option<ClockObservation>,
previous: Option<ClockObservation>,
samples: [Option<ClockObservation>; CLOCK_SAMPLES],
sample_count: usize,
sample_next: usize,
smoothed_ppm: f64,
measured_jitter: Duration,
}
impl ClockTracker {
@@ -147,16 +175,35 @@ impl ClockTracker {
if !(8_000..=384_000).contains(&sample_rate) {
return Err(ServiceError::new("audio_format", "Audio clock sample rate is outside 8–384 kHz"));
}
Ok(Self { sample_rate, anchor: None, previous: None, smoothed_ppm: 0.0 })
Ok(Self { sample_rate, anchor: None, previous: None, samples: [None; CLOCK_SAMPLES],
sample_count: 0, sample_next: 0, smoothed_ppm: 0.0, measured_jitter: Duration::ZERO })
}
pub fn reset(&mut self) {
self.anchor = None;
self.previous = None;
self.samples.fill(None);
self.sample_count = 0;
self.sample_next = 0;
self.smoothed_ppm = 0.0;
self.measured_jitter = Duration::ZERO;
}
pub fn drift_ppm(&self) -> f64 { self.smoothed_ppm }
pub fn measured_jitter(&self) -> Duration { self.measured_jitter }
/// Hardware-domain projection, never a worker wake-time replacement. The
/// caller supplies actual SRC source phase and separately subtracts delay.
/// Its error depends on distance from this callback, not stream duration.
pub fn timestamp(&self, frame_position: f64) -> Option<Instant> {
if !frame_position.is_finite() { return None; }
let observation = self.previous?;
let seconds = (frame_position - observation.position as f64)
/ (f64::from(self.sample_rate) * (1.0 + self.smoothed_ppm / 1_000_000.0));
let duration = Duration::try_from_secs_f64(seconds.abs()).ok()?;
if seconds < 0.0 { observation.at.checked_sub(duration) }
else { observation.at.checked_add(duration) }
}
pub fn observe(&mut self, hardware_at: Instant, frame_position: u64)
-> std::result::Result<Option<f64>, ClockDiscontinuity>
@@ -169,31 +216,78 @@ impl ClockTracker {
fn observe_inner(&mut self, hardware_at: Instant, frame_position: u64)
-> std::result::Result<Option<f64>, ClockDiscontinuity>
{
if let Some((previous_at, previous_position)) = self.previous {
let elapsed = hardware_at.checked_duration_since(previous_at)
if let Some(previous) = self.previous {
let elapsed = hardware_at.checked_duration_since(previous.at)
.ok_or(ClockDiscontinuity::TimestampReversed)?;
let frames = frame_position.checked_sub(previous_position)
let frames = frame_position.checked_sub(previous.position)
.ok_or(ClockDiscontinuity::FramePositionReversed)?;
if elapsed.is_zero() && frames == 0 { return Ok(None); }
if (elapsed.as_secs_f64() - frames as f64 / f64::from(self.sample_rate)).abs() > MAX_CLOCK_DISCONTINUITY {
return Err(ClockDiscontinuity::TimestampJump);
}
if elapsed.is_zero() && frames > 0 { return Err(ClockDiscontinuity::TimestampJump); }
}
self.previous = Some((hardware_at, frame_position));
let Some((anchor_at, anchor_position)) = self.anchor else {
self.anchor = self.previous;
let observation = ClockObservation { at: hardware_at, position: frame_position };
self.previous = Some(observation);
let anchor = *self.anchor.get_or_insert(observation);
let seconds = hardware_at.duration_since(anchor.at).as_secs_f64();
let nominal = (frame_position - anchor.position) as f64 / f64::from(self.sample_rate);
// Keep an epoch-wide bound: a rolling fit must not hide a frozen clock
// or a succession of individually small jumps. Legitimate drift gets
// its own rate allowance, not another 200 ms per observation/window.
if (seconds - nominal).abs() > MAX_CLOCK_DISCONTINUITY + nominal * MAX_DRIFT_PPM / 1_000_000.0 {
return Err(if seconds < CLOCK_WINDOW.as_secs_f64() { ClockDiscontinuity::TimestampJump }
else { ClockDiscontinuity::DriftOutOfRange });
}
if self.sample_count > 0 {
let last = self.samples[(self.sample_next + CLOCK_SAMPLES - 1) % CLOCK_SAMPLES].unwrap();
if hardware_at.duration_since(last.at) < CLOCK_SAMPLE_SPACING { return Ok(None); }
}
self.samples[self.sample_next] = Some(observation);
self.sample_next = (self.sample_next + 1) % CLOCK_SAMPLES;
self.sample_count = (self.sample_count + 1).min(CLOCK_SAMPLES);
let oldest = self.samples[if self.sample_count == CLOCK_SAMPLES { self.sample_next } else { 0 }].unwrap();
if hardware_at.duration_since(oldest.at) < CLOCK_WINDOW { return Ok(None); }
// Least-squares elapsed time against nominal source time. Residual
// peak-to-peak is an observed jitter interval, NOT a precision promise.
let mut sum_x = 0.0;
let mut sum_y = 0.0;
for sample in self.samples.iter().flatten() {
sum_x += (sample.position - oldest.position) as f64 / f64::from(self.sample_rate);
sum_y += sample.at.duration_since(oldest.at).as_secs_f64();
}
let mean_x = sum_x / self.sample_count as f64;
let mean_y = sum_y / self.sample_count as f64;
let mut covariance = 0.0;
let mut variance = 0.0;
for sample in self.samples.iter().flatten() {
let x = (sample.position - oldest.position) as f64 / f64::from(self.sample_rate) - mean_x;
let y = sample.at.duration_since(oldest.at).as_secs_f64() - mean_y;
covariance += x * y;
variance += x * x;
}
if variance == 0.0 { return Ok(None); }
let slope = covariance / variance;
let mut low = f64::INFINITY;
let mut high = f64::NEG_INFINITY;
for sample in self.samples.iter().flatten() {
let x = (sample.position - oldest.position) as f64 / f64::from(self.sample_rate) - mean_x;
let y = sample.at.duration_since(oldest.at).as_secs_f64() - mean_y;
let residual = y - slope * x;
low = low.min(residual);
high = high.max(residual);
}
let jitter = (high - low).max(0.000_000_002);
self.measured_jitter = Duration::from_secs_f64(jitter);
let span = (frame_position - oldest.position) as f64 / f64::from(self.sample_rate);
if slope <= 0.0 || span <= 0.0 { return Ok(None); }
let uncertainty = 2.0 * jitter / span;
if slope <= uncertainty { return Ok(None); }
let lower_ppm = ((slope + uncertainty).recip() - 1.0) * 1_000_000.0;
let upper_ppm = ((slope - uncertainty).recip() - 1.0) * 1_000_000.0;
if lower_ppm < -MAX_DRIFT_PPM || upper_ppm > MAX_DRIFT_PPM || lower_ppm <= 0.0 && upper_ppm >= 0.0 {
return Ok(None);
};
let elapsed = hardware_at.duration_since(anchor_at);
if elapsed < CLOCK_WINDOW { return Ok(None); }
let frames = frame_position - anchor_position;
let ppm = (frames as f64 / (f64::from(self.sample_rate) * elapsed.as_secs_f64()) - 1.0) * 1_000_000.0;
if !ppm.is_finite() || ppm.abs() > MAX_DRIFT_PPM {
return Err(ClockDiscontinuity::DriftOutOfRange);
}
let weight = 1.0 - (-elapsed.as_secs_f64()).exp();
self.smoothed_ppm += weight * (ppm - self.smoothed_ppm);
self.anchor = self.previous;
self.smoothed_ppm = (slope.recip() - 1.0) * 1_000_000.0;
Ok(Some(self.smoothed_ppm))
}
}
+149 -13
View File
@@ -82,26 +82,40 @@ fn drift_correction_is_reciprocal_for_capture_and_direct_for_output() {
}
#[test]
fn clock_uses_hardware_time_and_one_second_smoothing() {
let start = Instant::now();
let mut clock = ClockTracker::new(48_000).unwrap();
assert_eq!(clock.observe(start, 0), Ok(None));
assert_eq!(clock.observe(start + Duration::from_millis(500), 24_012), Ok(None));
let first = clock.observe(start + Duration::from_secs(1), 48_024).unwrap().unwrap();
assert!((300.0..330.0).contains(&first));
for seconds in 2..=10 {
let ppm = clock.observe(start + Duration::from_secs(seconds), seconds * 48_024).unwrap().unwrap();
assert!((first..=500.000_001).contains(&ppm));
fn stable_callback_clock_acquires_drift_without_spending_the_age_budget() {
for rate in [44_100, 48_000] {
for ppm in [-500.0, 500.0] {
let start = Instant::now();
let mut clock = ClockTracker::new(rate).unwrap();
let physical_rate = f64::from(rate) * (1.0 + ppm / 1_000_000.0);
let mut acquired = false;
for callback in 0..=300_u64 {
let position = callback * u64::from(rate) / 100;
let at = start + Duration::from_secs_f64(position as f64 / physical_rate);
if let Some(estimate) = clock.observe(at, position).unwrap() {
assert!((estimate - ppm).abs() < 0.01);
acquired = true;
}
}
assert!(acquired, "rate={rate}, ppm={ppm}");
assert!(clock.measured_jitter() <= Duration::from_nanos(3));
}
}
assert!((clock.drift_ppm() - 500.0).abs() < 0.1);
}
#[test]
fn clock_fault_clears_estimate_instead_of_hiding_excess_drift() {
let start = Instant::now();
let mut clock = ClockTracker::new(48_000).unwrap();
clock.observe(start, 100).unwrap();
assert_eq!(clock.observe(start + Duration::from_secs(1), 48_196), Err(ClockDiscontinuity::DriftOutOfRange));
clock.observe(start, 0).unwrap();
let mut fault = None;
for seconds in 1..=201 {
if let Err(error) = clock.observe(start + Duration::from_secs(seconds), seconds * 48_096) {
fault = Some(error);
break;
}
}
assert_eq!(fault, Some(ClockDiscontinuity::DriftOutOfRange));
assert_eq!(clock.drift_ppm(), 0.0);
assert_eq!(clock.observe(start, 0), Ok(None));
assert_eq!(clock.observe(start - Duration::from_millis(1), 480), Err(ClockDiscontinuity::TimestampReversed));
@@ -111,6 +125,128 @@ fn clock_fault_clears_estimate_instead_of_hiding_excess_drift() {
assert_eq!(clock.observe(start + Duration::from_secs(1), 480), Err(ClockDiscontinuity::TimestampJump));
}
#[test]
fn clock_accepts_repeated_callback_estimates_but_bounds_cumulative_uncertainty() {
for rate in [44_100, 48_000] {
let start = Instant::now();
let mut clock = ClockTracker::new(rate).unwrap();
assert_eq!(clock.observe(start, 0), Ok(None));
assert_eq!(clock.observe(start, 0), Ok(None)); // another subblock, not a clock tick
for callback in 1..=9 {
assert_eq!(clock.observe(start, u64::from(rate) * callback / 50), Ok(None));
}
// Each individual callback advances only 20 ms; the aggregate must still
// fail rather than turn an indefinitely clamped clock into valid timing.
assert_eq!(clock.observe(start, u64::from(rate) * 11 / 50), Err(ClockDiscontinuity::TimestampJump));
clock.observe(start, 0).unwrap();
assert_eq!(clock.observe(start + Duration::from_millis(211), u64::from(rate) / 100), Err(ClockDiscontinuity::TimestampJump));
}
}
#[test]
fn burst_offset_is_not_misreported_as_hardware_drift_after_one_second() {
for rate in [44_100, 48_000] {
let start = Instant::now();
let mut clock = ClockTracker::new(rate).unwrap();
clock.observe(start, 0).unwrap();
for callback in 1..=500 {
let position = u64::from(rate) * callback / 100;
let at = start + Duration::from_millis((callback * 10).saturating_sub(30));
assert_eq!(clock.observe(at, position), Ok(None));
}
assert_eq!(clock.drift_ppm(), 0.0);
}
}
#[test]
fn callback_projection_bounds_two_hour_phase_even_when_jitter_prevents_drift_acquisition() {
for rate in [44_100, 48_000] {
for ppm in [-500.0, 500.0] {
let start = Instant::now();
let mut clock = ClockTracker::new(rate).unwrap();
let physical_rate = f64::from(rate) * (1.0 + ppm / 1_000_000.0);
// Deterministic callback timestamp jitter exceeds the 500 ppm signal
// inside the short fit. Projection must still stay bounded in phase.
for callback in 0..=720_000_u64 {
let position = callback * u64::from(rate) / 100;
let jitter = if (callback / 20) % 2 == 0 { 0.000_6 } else { 0.0 };
let at = start + Duration::from_secs_f64(position as f64 / physical_rate + jitter);
clock.observe(at, position).unwrap();
if callback == 0 { continue; }
let source = position as f64 - f64::from(rate) * 0.02 + 0.25;
let projected = clock.timestamp(source).unwrap();
let truth = start + Duration::from_secs_f64(source.max(0.0) / physical_rate);
let now = at + Duration::from_millis(10);
assert!(projected <= now);
assert!(now.duration_since(projected) < Duration::from_millis(32));
if source >= 0.0 {
let error = projected.max(truth).duration_since(projected.min(truth));
assert!(error < Duration::from_micros(650), "rate={rate}, ppm={ppm}, callback={callback}, error={error:?}");
}
}
assert!(clock.measured_jitter() >= Duration::from_micros(500));
}
}
}
#[test]
fn emitted_src_timestamps_follow_actual_ramped_source_phase() {
for rate in [44_100, 48_000] {
for ppm in [-500.0, 500.0] {
let start = Instant::now();
let mut clock = ClockTracker::new(rate).unwrap();
let mut converter = AudioResampler::new_capture(rate, 1).unwrap();
let input = vec![0.25; converter.input_frames_max()];
let mut output = vec![0.0; converter.output_frames_max()];
let physical_rate = f64::from(rate) * (1.0 + ppm / 1_000_000.0);
let mut consumed = 0_u64;
let mut phase = 0.0;
for block in 0..400 {
let at = start + Duration::from_secs_f64(consumed as f64 / physical_rate);
if let Some(estimate) = clock.observe(at, consumed).unwrap() {
converter.set_device_drift_ppm(estimate).unwrap();
}
let before = converter.ratio().recip();
let counts = converter.process_interleaved(&input, &mut output).unwrap();
let after = converter.ratio().recip();
assert!((converter.last_output_source_position() - phase).abs() < 1e-7);
let projected = clock.timestamp(converter.last_output_source_position()).unwrap();
let emitted = projected.checked_sub(converter.output_delay()).unwrap();
let now = start + Duration::from_secs_f64((consumed + counts.consumed as u64) as f64 / physical_rate);
assert!(emitted <= now, "rate={rate}, ppm={ppm}, block={block}");
assert!(now.duration_since(emitted) < Duration::from_millis(40));
phase += counts.produced as f64 * (before + after) * 0.5 + (after - before) * 0.5;
consumed += counts.consumed as u64;
}
assert!((clock.drift_ppm() - ppm).abs() < 0.01);
// Buffer consumption includes bounded sinc lookahead; the sample
// phase must not accidentally use that lookahead as source time.
assert!(consumed as f64 - phase > 1.0);
assert!(consumed as f64 - phase < f64::from(rate) * 0.02);
converter.reset().unwrap();
converter.process_interleaved(&input, &mut output).unwrap();
assert_eq!(converter.last_output_source_position(), 0.0);
}
}
}
#[test]
fn rolling_clock_fit_does_not_erase_cumulative_small_discontinuities() {
let start = Instant::now();
let mut clock = ClockTracker::new(48_000).unwrap();
let mut fault = None;
for callback in 0..=250_u64 {
let at = start + Duration::from_millis(callback * 11);
if let Err(error) = clock.observe(at, callback * 480) {
fault = Some(error);
break;
}
}
assert_eq!(fault, Some(ClockDiscontinuity::DriftOutOfRange));
assert!(clock.timestamp(0.0).is_none());
assert_eq!(clock.drift_ppm(), 0.0);
}
#[test]
fn unsupported_format_is_explicit() {
assert!(AudioResampler::new_capture(0, 1).is_err());
+580 -387
View File
@@ -1,387 +1,580 @@
//! Android owns OS capabilities, never a second UI or server model.
use std::{collections::HashMap, ffi::c_void, path::PathBuf, sync::{Arc, LazyLock, Mutex, OnceLock, Weak, atomic::{AtomicBool, AtomicU64, Ordering}}};
use jni::{JNIEnv, JavaVM, objects::{GlobalRef, JClass, JObject, JString, JValue}, sys::{jboolean, jfloat, jint, jlong}};
use tokio::sync::oneshot;
use crate::{AppConfig, AppRuntime, app::connections::SessionKey, services::{Result, ServiceError}};
use super::{lifecycle::{self, Insets, NotificationAction, Permission, PlatformEvent}, resources::{ActionPolicy, PickRequest, Selection}};
mod documents;
mod smoke;
mod call_audio;
pub use smoke::{AndroidSmokeRequest, smoke_request};
pub mod accessibility;
pub use accessibility::{attach_accessibility, AccessibilityLease};
struct Binding { vm: JavaVM, application: GlobalRef, class: GlobalRef, files: PathBuf }
static BINDING: OnceLock<Binding> = OnceLock::new();
static RUNTIME: LazyLock<Mutex<Weak<AppRuntime>>> = LazyLock::new(|| Mutex::new(Weak::new()));
static UI: AtomicU64 = AtomicU64::new(0);
static SCREEN_READER: AtomicBool = AtomicBool::new(false);
static NEXT: AtomicU64 = AtomicU64::new(1);
static REQUESTS: LazyLock<Mutex<HashMap<u64, oneshot::Sender<Result<Response>>>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
struct Voice { token: u64, key: SessionKey, microphone: bool, capture_revision: u64, capture_change: Option<u64>, audio: call_audio::CallAudioState, _runtime: Arc<AppRuntime> }
static VOICE: LazyLock<Mutex<Option<Voice>>> = LazyLock::new(|| Mutex::new(None));
#[derive(Clone)]
struct Action { key: SessionKey, stream: Option<String> }
static ACTIONS: LazyLock<Mutex<HashMap<u64, Action>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
enum Response { Selection(Option<Selection>), Permission(bool), Text(String), Voice }
fn error(code: &'static str, message: impl Into<String>) -> ServiceError { ServiceError::new(code, message) }
fn java<T>(value: jni::errors::Result<T>) -> Result<T> { value.map_err(|_| error("android_os_error", "Android rejected the requested OS operation")) }
fn binding() -> Result<&'static Binding> { BINDING.get().ok_or_else(|| error("android_not_initialized", "Android Application context has not been initialized")) }
fn with_env<T>(operation: impl FnOnce(&mut JNIEnv<'_>, &JClass<'_>) -> Result<T>) -> Result<T> {
let binding = binding()?;
let mut env = java(binding.vm.attach_current_thread())?;
java(env.push_local_frame(48))?;
let result = operation(&mut env, binding.class.as_obj().into());
if env.exception_check().unwrap_or(true) { let _ = env.exception_clear(); }
let _ = unsafe { env.pop_local_frame(&JObject::null()) };
result
}
fn next_id() -> Result<u64> { NEXT.fetch_update(Ordering::AcqRel, Ordering::Acquire, |id| (id < i64::MAX as u64).then_some(id + 1)).map_err(|_| error("generation_exhausted", "Android action identity exhausted")) }
fn call_void(name: &str, signature: &str, args: &[JValue<'_, '_>]) -> Result<()> { with_env(|env, class| { java(env.call_static_method(class, name, signature, args))?; Ok(()) }) }
fn complete(id: u64, response: Result<Response>) { if let Some(sender) = REQUESTS.lock().expect("Android requests").remove(&id) { let _ = sender.send(response); } }
struct Request { id: u64, receiver: Option<oneshot::Receiver<Result<Response>>> }
impl Request {
fn new() -> Result<Self> {
let mut pending = REQUESTS.lock().expect("Android requests");
if pending.len() >= 32 { return Err(error("os_busy", "Too many pending Android OS operations")); }
let id = next_id()?; let (sender, receiver) = oneshot::channel(); pending.insert(id, sender);
Ok(Self { id, receiver: Some(receiver) })
}
async fn receive(mut self) -> Result<Response> { self.receiver.take().expect("single Android receiver").await.map_err(|_| error("operation_cancelled", "Android operation was cancelled"))? }
}
impl Drop for Request { fn drop(&mut self) { if REQUESTS.lock().expect("Android requests").remove(&self.id).is_some() { let _ = call_void("cancel", "(J)V", &[JValue::Long(self.id as i64)]); } } }
fn accepted(value: bool) -> Result<()> { if value { Ok(()) } else { Err(error("os_busy", "Android OS callback queue is full or the action was denied")) } }
fn permission_id(permission: Permission) -> i32 { match permission { Permission::Microphone => 0, Permission::Camera => 1, Permission::Notifications => 2 } }
/// Process-owned context for CPAL/WebRTC; the GlobalRef is never an Activity.
pub fn application_context() -> Result<(*mut c_void, *mut c_void)> { let b = binding()?; Ok((b.vm.get_java_vm_pointer().cast(), b.application.as_obj().as_raw().cast())) }
pub fn build_channel()->Result<crate::services::updates::BuildChannel>{with_env(|env,_|{let harness=java(env.get_static_field("dev/teamspeach/mobile/BuildConfig","TEST_HARNESS","Z"))?.z().map_err(|_|error("build_channel","Android build metadata is invalid"))?;let direct=java(env.get_static_field("dev/teamspeach/mobile/BuildConfig","DIRECT_UPDATES","Z"))?.z().map_err(|_|error("build_channel","Android update metadata is invalid"))?;Ok(if harness{crate::services::updates::BuildChannel::Development}else if direct{crate::services::updates::BuildChannel::Direct}else{crate::services::updates::BuildChannel::GooglePlay})})}
/// Called by the root `android_main`, with the re-exported android-activity 0.6 type.
pub fn run(app: slint::android::AndroidApp) {
let result = (|| -> std::result::Result<(), Box<dyn std::error::Error>> {
let smoke = smoke_request(&app)?;
#[cfg(feature="test-harness")]
let prepared = if let Some(request) = &smoke {
if RUNTIME.lock().expect("Android runtime").upgrade().is_some() {
return Err(error("smoke_runtime_active", "Restart the isolated test process before launching a smoke scenario").into());
}
Some(crate::smoke::prepare(&request.scenario, request.profile.clone(), request.output.clone())?)
} else { None };
let runtime = {
let mut weak = RUNTIME.lock().expect("Android runtime");
if let Some(runtime) = weak.upgrade() {
if smoke.is_some() { return Err(error("smoke_runtime_active", "Restart the isolated test process before launching a smoke scenario").into()); }
runtime
} else {
let config = AppConfig {
mobile_container: Some(binding()?.files.clone()),
profile_dir: smoke.as_ref().map(|request|request.profile.clone()),
allow_os_actions: smoke.is_none(),
network_enabled: smoke.is_none(),
..AppConfig::default()
};
let runtime = AppRuntime::start(config)?; *weak = Arc::downgrade(&runtime); runtime
}
};
i_slint_backend_android_activity::set_clipboard_enabled(smoke.is_none());
let generation = runtime.next_ui_generation(); UI.store(generation, Ordering::Release);
struct AttachmentGeneration(u64);
impl Drop for AttachmentGeneration {fn drop(&mut self){destroy_ui(self.0);}}
let _attachment = AttachmentGeneration(generation);
slint::android::init_with_event_listener(app.clone(), move |event| {
use slint::android::android_activity::{MainEvent, PollEvent};
if matches!(event, PollEvent::Main(MainEvent::Destroy)) { destroy_ui(generation); }
})?;
with_env(|env, class| {
// Borrow only during this UI attachment call; no worker receives an Activity reference.
let activity = unsafe { JObject::from_raw(app.activity_as_ptr().cast()) };
accepted(java(env.call_static_method(class,"attached","(Landroid/app/Activity;J)Z",&[JValue::Object(&activity),JValue::Long(generation as i64)]))?.z().unwrap_or(false))
})?;
#[cfg(feature="test-harness")]
let result = if let Some(prepared) = prepared {
crate::smoke::run_prepared(runtime, generation, prepared)
} else {
crate::attach_ui_with_generation(runtime, generation)
};
#[cfg(not(feature="test-harness"))]
let result = crate::attach_ui_with_generation(runtime, generation);
destroy_ui(generation);
result?;
Ok(())
})();
if let Err(error) = result { eprintln!("Android native startup: {error}"); }
}
fn destroy_ui(generation: u64) {
if UI.compare_exchange(generation, 0, Ordering::AcqRel, Ordering::Acquire).is_ok() {
lifecycle::emit(PlatformEvent::UiDestroyed { ui_generation: generation });
accessibility::detach(generation);
}
}
pub async fn pick(request: PickRequest, policy: ActionPolicy) -> Result<Option<Selection>> {
policy.check()?; let pending = Request::new()?;
let (kind, name, mime, types) = match request {
PickRequest::Open { mime_types } => (0, String::new(), "*/*".to_owned(), mime_types),
PickRequest::Save { suggested_name, mime_type } => { super::resources::require_component(&suggested_name)?; (1, suggested_name, mime_type, Vec::new()) },
PickRequest::Directory => (2, String::new(), "*/*".to_owned(), Vec::new()),
};
if types.len() > 64 || types.iter().chain(std::iter::once(&mime)).any(|s| s.len() > 128 || s.contains('\0')) { return Err(error("invalid_mime", "Invalid document MIME filter")); }
with_env(|env, class| {
let name = java(env.new_string(name))?; let mime = java(env.new_string(mime))?;
let array = java(env.new_object_array(types.len() as i32, "java/lang/String", JObject::null()))?;
for (index, value) in types.iter().enumerate() { let value = java(env.new_string(value))?; java(env.set_object_array_element(&array, index as i32, &value))?; java(env.delete_local_ref(value))?; }
accepted(java(env.call_static_method(class, "pick", "(JILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;)Z", &[JValue::Long(pending.id as i64), JValue::Int(kind), JValue::Object(&name), JValue::Object(&mime), JValue::Object(&array)]))?.z().map_err(|_| error("android_os_error", "Invalid picker response"))?)
})?;
match pending.receive().await? { Response::Selection(value) => Ok(value), _ => Err(error("android_os_error", "Unexpected picker completion")) }
}
pub async fn request_permission(permission: Permission, policy: ActionPolicy) -> Result<bool> {
policy.check()?; let pending = Request::new()?;
with_env(|env, class| accepted(java(env.call_static_method(class, "permission", "(JI)Z", &[JValue::Long(pending.id as i64), JValue::Int(permission_id(permission))]))?.z().unwrap_or(false)))?;
match pending.receive().await? { Response::Permission(value) => Ok(value), _ => Err(error("android_os_error", "Unexpected permission completion")) }
}
/// Caller revalidates `key` and active-call intent before this explicit foreground action.
pub async fn start_voice(runtime: Arc<AppRuntime>, key: SessionKey, microphone: bool, policy: ActionPolicy) -> Result<()> {
policy.check()?; let request = Request::new()?; let token = request.id;
{ let mut voice = VOICE.lock().expect("Android voice"); if voice.is_some() { return Err(error("call_lease_exists", "An Android foreground call already owns the audio session")); } *voice = Some(Voice { token, key: key.clone(), microphone: false, capture_revision: 0, capture_change: None, audio: Default::default(), _runtime: runtime }); }
struct PendingVoice(u64, bool);
impl Drop for PendingVoice { fn drop(&mut self) { if !self.1 { end_voice(self.0); let _ = call_void("stopVoice", "(J)V", &[JValue::Long(self.0 as i64)]); } } }
let mut pending = PendingVoice(token, false);
with_env(|env, class| accepted(java(env.call_static_method(class, "startVoice", "(JZ)Z", &[JValue::Long(token as i64), JValue::Bool(microphone as u8)]))?.z().unwrap_or(false)))?;
match tokio::time::timeout(std::time::Duration::from_secs(15), request.receive()).await {
Ok(Ok(Response::Voice)) if VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|voice.token==token && voice.microphone==microphone) => { pending.1 = true; Ok(()) },
Ok(Err(error)) => Err(error),
_ => Err(error("call_start_failed", "Android did not grant a foreground voice session")),
}
}
/// Stop/invalidate CPAL capture before disabling. Enable CPAL only after this OS acknowledgment
/// and revalidation of the captured SessionKey. Enabling always requires a visible user action.
pub async fn set_voice_capture(key: &SessionKey, enabled: bool, policy: ActionPolicy) -> Result<()> {
policy.check()?;
let request=Request::new()?;let id=request.id;
let token={let mut slot=VOICE.lock().expect("Android voice");let voice=slot.as_mut().filter(|voice|&voice.key==key).ok_or_else(||error("target_changed","The Android call lease changed"))?;
if voice.capture_change.is_some(){return Err(error("call_capture_busy","An Android microphone transition is pending"));}
voice.capture_revision=id;voice.capture_change=Some(id);voice.token};
struct CaptureChange {token:u64,id:u64,committed:bool}
impl Drop for CaptureChange {fn drop(&mut self){if !self.committed {
let cancel={let mut slot=VOICE.lock().expect("Android voice");if let Some(voice)=slot.as_mut().filter(|voice|voice.token==self.token&&voice.capture_revision==self.id){voice.microphone=false;voice.audio.revoke_capture();voice.capture_change=None;true}else{false}};
if cancel{let _=call_void("cancelVoiceCapture","(JJ)V",&[JValue::Long(self.token as i64),JValue::Long(self.id as i64)]);}
}}}
let mut change=CaptureChange{token,id,committed:false};
with_env(|env,class|accepted(java(env.call_static_method(class,"setVoiceCapture","(JJZ)Z",&[JValue::Long(token as i64),JValue::Long(id as i64),JValue::Bool(enabled as u8)]))?.z().unwrap_or(false)))?;
match tokio::time::timeout(std::time::Duration::from_secs(15),request.receive()).await {
Ok(Ok(Response::Voice)) if VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|voice.token==token&&voice.capture_revision==id&&voice.microphone==enabled)=>{change.committed=true;Ok(())},
Ok(Err(error))=>Err(error),
_=>Err(error("call_capture_failed","Android did not acknowledge the microphone service transition")),
}
}
fn voice_audio_changed(token:u64, focused:Option<bool>, restart_output:bool) {
let changed={let mut slot=VOICE.lock().expect("Android voice");slot.as_mut().filter(|voice|voice.token==token).map(|voice|{
voice.microphone=false;voice.capture_revision=0;
let revision=match focused{Some(focused)=>voice.audio.interrupt(focused),None if restart_output=>voice.audio.route_changed(),None=>voice.audio.revoke_capture()};
(voice.key.clone(),revision,voice.capture_change.take(),voice.audio.restart_output())
})};
if let Some((key,revision,pending,restart_output))=changed {
if let Some(id)=pending{complete(id,Err(error("call_capture_revoked","Microphone authorization ended; resume explicitly")));}
lifecycle::emit(PlatformEvent::AndroidCallAudio{key,token,revision,restart_output});
}
}
pub(crate) fn voice_audio_allowed(key:&SessionKey,microphone:bool)->bool {
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|&voice.key==key&&voice.audio.allows(microphone))
}
pub(crate) fn voice_audio_current(key:&SessionKey,token:u64,revision:u64)->bool {
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|&voice.key==key&&voice.token==token&&voice.audio.is_current(revision))
}
pub(crate) fn acknowledge_voice_output(key:&SessionKey,token:u64,revision:u64) {
if let Some(voice)=VOICE.lock().expect("Android voice").as_mut().filter(|voice|&voice.key==key&&voice.token==token){voice.audio.acknowledge_output(revision);}
}
fn end_voice(token: u64) -> bool {
let voice = { let mut voice = VOICE.lock().expect("Android voice"); if voice.as_ref().is_some_and(|voice| voice.token == token) { voice.take() } else { None } };
if let Some(voice) = voice { lifecycle::emit(PlatformEvent::CallLeaseEnded { key: voice.key.clone() }); complete(token, Err(error("call_lease_ended", "Android foreground call ended"))); if let Some(id)=voice.capture_change{complete(id,Err(error("call_lease_ended","Android foreground call ended")));} true } else { false }
}
pub fn stop_voice(key: &SessionKey) -> Result<()> {
let token = VOICE.lock().expect("Android voice").as_ref().filter(|voice| &voice.key == key).map(|voice| voice.token);
if let Some(token) = token { end_voice(token); call_void("stopVoice", "(J)V", &[JValue::Long(token as i64)])?; }
Ok(())
}
pub fn invalidate_session(key: &SessionKey) {
let _ = stop_voice(key);
let tokens: Vec<_> = { let mut actions = ACTIONS.lock().expect("Android actions"); let tokens = actions.iter().filter(|(_, action)| &action.key == key).map(|(token, _)| *token).collect::<Vec<_>>(); for token in &tokens { actions.remove(token); } tokens };
for token in tokens { let _ = call_void("cancelNotification", "(J)V", &[JValue::Long(token as i64)]); let _ = call_void("closePip", "(J)V", &[JValue::Long(token as i64)]); }
}
fn register_action(key: SessionKey, stream: Option<String>) -> Result<u64> {
let mut actions = ACTIONS.lock().expect("Android actions");
if actions.len() >= 64 { return Err(error("notification_limit", "Dismiss existing OS notifications before adding more")); }
let token = next_id()?; actions.insert(token, Action { key, stream }); Ok(token)
}
pub struct NotificationLease(u64);
impl Drop for NotificationLease { fn drop(&mut self) { ACTIONS.lock().expect("Android actions").remove(&self.0); let _ = call_void("cancelNotification", "(J)V", &[JValue::Long(self.0 as i64)]); } }
pub fn notify(key: SessionKey, title: &str, body: &str, policy: ActionPolicy) -> Result<NotificationLease> {
policy.check()?; if title.len()>1024 || body.len()>8192 { return Err(error("notification_size", "Notification text is too large")); }
let lease = NotificationLease(register_action(key, None)?);
with_env(|env, class| { let title = java(env.new_string(title))?; let body = java(env.new_string(body))?; accepted(java(env.call_static_method(class,"notify","(JLjava/lang/String;Ljava/lang/String;)Z", &[JValue::Long(lease.0 as i64),JValue::Object(&title),JValue::Object(&body)]))?.z().unwrap_or(false)) })?;
Ok(lease)
}
pub struct PictureInPictureLease(u64);
impl Drop for PictureInPictureLease { fn drop(&mut self) { let action = ACTIONS.lock().expect("Android actions").remove(&self.0); if let Some(action) = action { if let Some(stream_id) = action.stream { lifecycle::emit(PlatformEvent::PictureInPicture { key: action.key, stream_id, active:false, playing:true }); } } let _ = call_void("closePip", "(J)V", &[JValue::Long(self.0 as i64)]); } }
/// The caller presents the existing viewer tile before entering PiP. No peer or volume is changed here.
pub async fn enter_picture_in_picture(key: SessionKey, stream_id: String, width: u32, height: u32, policy: ActionPolicy) -> Result<PictureInPictureLease> {
policy.check()?; if stream_id.is_empty() || stream_id.len()>256 || width==0 || height==0 || !(0.418..=2.39).contains(&(width as f64/height as f64)) { return Err(error("pip_aspect_ratio", "Android PiP needs an existing viewer and aspect ratio between 1:2.39 and 2.39:1")); }
with_env(|env, class| { let reason = java(env.call_static_method(class,"pipUnavailable","()Ljava/lang/String;",&[]))?.l().map_err(|_|error("pip_unavailable","Android PiP capability query failed"))?; if reason.is_null() {Ok(())} else {let reason=JString::from(reason);Err(error("pip_unavailable",String::from(java(env.get_string(&reason))?)))}})?;
let lease = PictureInPictureLease(register_action(key, Some(stream_id))?);
let request=Request::new()?;
with_env(|env, class| accepted(java(env.call_static_method(class,"pip","(JJII)Z", &[JValue::Long(request.id as i64),JValue::Long(lease.0 as i64),JValue::Int(width as i32),JValue::Int(height as i32)]))?.z().unwrap_or(false)))?;
match request.receive().await? {Response::Text(_)=>Ok(lease),_=>Err(error("pip_unavailable","Android did not acknowledge picture-in-picture"))}
}
pub async fn clipboard_read(policy: ActionPolicy) -> Result<String> { clipboard(None, policy).await }
pub async fn clipboard_write(text: &str, policy: ActionPolicy) -> Result<()> { clipboard(Some(text), policy).await.map(|_| ()) }
async fn clipboard(text: Option<&str>, policy: ActionPolicy) -> Result<String> {
policy.check()?; if text.is_some_and(|value|value.len()>1024*1024) { return Err(error("clipboard_size", "Clipboard text exceeds 1 MiB")); }
let request = Request::new()?;
with_env(|env,class| { let value=java(env.new_string(text.unwrap_or_default()))?; accepted(java(env.call_static_method(class,"clipboard","(JLjava/lang/String;Z)Z",&[JValue::Long(request.id as i64),JValue::Object(&value),JValue::Bool(text.is_some() as u8)]))?.z().unwrap_or(false)) })?;
match request.receive().await? { Response::Text(value)=>Ok(value), _=>Err(error("android_os_error","Unexpected clipboard completion")) }
}
pub async fn share_text(text: &str, policy: ActionPolicy) -> Result<()> {
policy.check()?; if text.len()>1024*1024 { return Err(error("share_size", "Shared text exceeds 1 MiB")); }
let request=Request::new()?;
with_env(|env,class| { let text=java(env.new_string(text))?; let mime=java(env.new_string("text/plain"))?; accepted(java(env.call_static_method(class,"share","(JLjava/lang/String;Ldev/teamspeach/mobile/SafGrant;Ljava/lang/String;)Z",&[JValue::Long(request.id as i64),JValue::Object(&text),JValue::Object(&JObject::null()),JValue::Object(&mime)]))?.z().unwrap_or(false)) })?;
match request.receive().await? { Response::Text(_)=>Ok(()), _=>Err(error("android_os_error","Unexpected share completion")) }
}
/// Shares only a document capability returned by this platform's SAF picker.
pub async fn share_document(document: Arc<dyn super::resources::DocumentGrant>, mime_type: &str, policy: ActionPolicy) -> Result<()> {
policy.check()?;
if mime_type.is_empty() || mime_type.len()>128 || mime_type.contains('\0') {return Err(error("invalid_mime","Invalid share MIME type"));}
let native = document.as_any().downcast_ref::<documents::Document>().ok_or_else(||error("document_grant","Android share requires an Android document capability"))?;
let request=Request::new()?;
with_env(|env,class| {let text=java(env.new_string(""))?;let mime=java(env.new_string(mime_type))?;accepted(java(env.call_static_method(class,"share","(JLjava/lang/String;Ldev/teamspeach/mobile/SafGrant;Ljava/lang/String;)Z",&[JValue::Long(request.id as i64),JValue::Object(&text),JValue::Object(native.object()),JValue::Object(&mime)]))?.z().unwrap_or(false))})?;
match request.receive().await? {Response::Text(_)=>Ok(()),_=>Err(error("android_os_error","Unexpected share completion"))}
}
#[derive(Clone,Copy,Debug,PartialEq,Eq)]
pub enum InstallOutcome { Installed, Cancelled }
/// Only an explicit updater effect can supply this verified capability. The OS still asks for consent.
pub async fn install_apk(apk: crate::services::updates::VerifiedApk, policy: ActionPolicy) -> Result<InstallOutcome> {
use std::os::fd::AsRawFd;
policy.check()?;
let (_apk, descriptor)=tokio::task::spawn_blocking(move||apk.open_for_install().map(|file|(apk,file))).await.map_err(|_|error("installer_worker","Verified APK worker stopped"))?.map_err(|failure|ServiceError::new(failure.code,failure.detail))?;
let request=Request::new()?;
with_env(|env,class|accepted(java(env.call_static_method(class,"installApk","(JI)Z",&[JValue::Long(request.id as i64),JValue::Int(descriptor.as_raw_fd())]))?.z().unwrap_or(false)))?;
// Java duplicated the verified read-only descriptor synchronously before posting the UI work.
drop(descriptor);
match request.receive().await? {Response::Text(value) if value=="installed"=>Ok(InstallOutcome::Installed),Response::Text(value) if value=="cancelled"=>Ok(InstallOutcome::Cancelled),_=>Err(error("installer_result","Android returned an invalid installer result"))}
}
pub async fn open_store(policy: ActionPolicy) -> Result<()> {
policy.check()?;let request=Request::new()?;
with_env(|env,class|accepted(java(env.call_static_method(class,"openStore","(J)Z",&[JValue::Long(request.id as i64)]))?.z().unwrap_or(false)))?;
match request.receive().await? {Response::Text(_)=>Ok(()),_=>Err(error("store_result","Android returned an invalid store response"))}
}
/// Called only after the privacy service has obtained consent for this URL.
pub async fn open_external_url(url:&str,policy:ActionPolicy)->Result<()> {
policy.check()?;
let parsed=reqwest::Url::parse(url).map_err(|_|error("invalid_url","Invalid external URL"))?;
if !matches!(parsed.scheme(),"https"|"http"|"mailto"){return Err(error("invalid_url","This external URL scheme is not allowed"))}
let request=Request::new()?;
with_env(|env,class|{
let value=java(env.new_string(parsed.as_str()))?;
accepted(java(env.call_static_method(class,"openExternalUrl","(JLjava/lang/String;)Z",&[JValue::Long(request.id as i64),JValue::Object(&value)]))?.z().unwrap_or(false))
})?;
match request.receive().await?{Response::Text(_)=>Ok(()),_=>Err(error("link_result","Android returned an invalid link response"))}
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeInstall(mut env: JNIEnv, class: JClass, application: JObject, files: JString) -> jboolean {
let result=(|| -> Result<()> {
if BINDING.get().is_some() { return Ok(()); }
if !java(env.is_instance_of(&application,"android/app/Application"))? { return Err(error("android_context", "Application context required")); }
let vm=java(env.get_java_vm())?;
#[cfg(feature="webrtc")]
if !libwebrtc::android::initialize_android_context(&vm,&application) { return Err(error("android_webrtc", "Matching prefixed WebRTC JNI jar/context initialization failed")); }
#[cfg(feature="webrtc")]
{
let capture_application = java(env.new_local_ref(&application))?;
super::mobile_capture::install(&mut env, capture_application).map_err(|e|error("android_capture",e.message))?;
}
let files: String=java(env.get_string(&files))?.into();
// Old immutable PendingIntents must not alias a new process's first call.
let mut nonce=[0u8;8];getrandom::fill(&mut nonce).map_err(|_|error("android_nonce","Unable to create process action identities"))?;
NEXT.store((u64::from_le_bytes(nonce)&0x3fff_ffff_ffff_ffff)|1,Ordering::Release);
let binding=Binding { vm, application:java(env.new_global_ref(application))?, class:java(env.new_global_ref(class))?, files:PathBuf::from(files) };
BINDING.set(binding).map_err(|_|error("android_context","Concurrent Application initialization"))?;
let (vm,application)=application_context()?;
if !unsafe { cpal::android_context::set_process_android_context(vm,application) } { return Err(error("android_context","CPAL process context conflict")); }
Ok(())
})();
if env.exception_check().unwrap_or(true) { let _=env.exception_clear(); }
result.is_ok() as u8
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeEvent(_env:JNIEnv,_class:JClass,generation:jlong,event:jint,value:jboolean) {
let value=value!=0; let generation=generation as u64;
let event=match event {
0 if generation!=0 && UI.load(Ordering::Acquire)==generation=>PlatformEvent::Visibility{ui_generation:generation,visible:value},
1=>{destroy_ui(generation);return;}, 2=>PlatformEvent::AudioInterruption{began:value,should_resume:!value},
3=>PlatformEvent::AudioRouteChanged,4=>PlatformEvent::NetworkChanged,5=>PlatformEvent::ScreenLocked(value),6=>PlatformEvent::MemoryPressure,_=>return,
}; lifecycle::emit(event);
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativePermission(_env:JNIEnv,_class:JClass,id:jlong,permission:jint,granted:jboolean) {
let permission=match permission {0=>Permission::Microphone,1=>Permission::Camera,2=>Permission::Notifications,_=>return};
lifecycle::emit(PlatformEvent::PermissionChanged{permission,granted:granted!=0});
if id!=0 {complete(id as u64,Ok(Response::Permission(granted!=0)));}
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativePick(mut env:JNIEnv,_class:JClass,id:jlong,grant:JObject,message:JString) {
let result=if !message.is_null() {Err(error("document_picker",java(env.get_string(&message)).map(String::from).unwrap_or_else(|_|"Document picker failed".into())))} else if grant.is_null() {Ok(Response::Selection(None))} else {documents::selection(&mut env,grant).map(|value|Response::Selection(Some(value)))};
complete(id as u64,result);
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeText(mut env:JNIEnv,_class:JClass,id:jlong,value:JString,message:JString) {
let result=if !message.is_null() {Err(error("android_os_error",java(env.get_string(&message)).map(String::from).unwrap_or_else(|_|"Android operation failed".into())))} else {java(env.get_string(&value)).map(String::from).and_then(|s|if s.len()<=1024*1024 {Ok(Response::Text(s))}else{Err(error("clipboard_size","Clipboard text exceeds 1 MiB"))})}; complete(id as u64,result);
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceValid(_env:JNIEnv,_class:JClass,token:jlong)->jboolean {VOICE.lock().expect("Android voice").as_ref().is_some_and(|v|v.token==token as u64) as u8}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceStarted(_env:JNIEnv,_class:JClass,token:jlong,microphone:jboolean){
let active={let mut slot=VOICE.lock().expect("Android voice");if let Some(voice)=slot.as_mut().filter(|voice|voice.token==token as u64){voice.microphone=microphone!=0;voice.audio.start(microphone!=0);true}else{false}};
if active{complete(token as u64,Ok(Response::Voice));}
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceStopped(_env:JNIEnv,_class:JClass,token:jlong)->jboolean{end_voice(token as u64) as u8}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceEvent(_env:JNIEnv,_class:JClass,token:jlong,event:jint,value:jboolean){
match event{2=>voice_audio_changed(token as u64,Some(value==0),true),3=>voice_audio_changed(token as u64,None,true),_=>{}}
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceCaptureValid(_env:JNIEnv,_class:JClass,token:jlong,id:jlong)->jboolean{
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|voice.token==token as u64&&voice.capture_revision==id as u64&&voice.capture_change==Some(id as u64)) as u8
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceCaptureCurrent(_env:JNIEnv,_class:JClass,token:jlong,id:jlong)->jboolean{
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|voice.token==token as u64&&voice.capture_revision==id as u64) as u8
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceCaptureChanged(_env:JNIEnv,_class:JClass,token:jlong,id:jlong,enabled:jboolean)->jboolean{
let active={let mut slot=VOICE.lock().expect("Android voice");if let Some(voice)=slot.as_mut().filter(|voice|voice.token==token as u64&&voice.capture_revision==id as u64&&voice.capture_change==Some(id as u64)){if !voice.audio.change_capture(enabled!=0){false}else{voice.microphone=enabled!=0;voice.capture_change=None;true}}else{false}};
if active{complete(id as u64,Ok(Response::Voice));}active as u8
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceCaptureRevoked(_env:JNIEnv,_class:JClass,token:jlong){voice_audio_changed(token as u64,None,false);}
fn action(token:u64)->Option<Action>{VOICE.lock().expect("Android voice").as_ref().filter(|v|v.token==token).map(|v|Action{key:v.key.clone(),stream:None}).or_else(||ACTIONS.lock().expect("Android actions").get(&token).cloned())}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeNotificationValid(_env:JNIEnv,_class:JClass,token:jlong)->jboolean {action(token as u64).is_some() as u8}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeAction(mut env:JNIEnv,_class:JClass,token:jlong,name:JString){
let Some(action)=action(token as u64) else{return};let Ok(name)=env.get_string(&name)else{return};let name:String=name.into();
if let Some(stream_id)=action.stream {if matches!(name.as_str(),"pip-play"|"pip-pause"){lifecycle::emit(PlatformEvent::PictureInPicture{key:action.key,stream_id,active:true,playing:name=="pip-play"});}return;}
let event=match name.as_str(){"show"=>NotificationAction::Show,"mute"=>NotificationAction::Mute,"disconnect"=>NotificationAction::Disconnect,_=>return};lifecycle::emit(PlatformEvent::Notification{key:action.key,action:event});
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeInsets(_env:JNIEnv,_class:JClass,generation:jlong,top:jfloat,right:jfloat,bottom:jfloat,left:jfloat,keyboard:jfloat){if UI.load(Ordering::Acquire)==generation as u64 && [top,right,bottom,left,keyboard].iter().all(|v|v.is_finite()&&*v>=0.0){lifecycle::emit(PlatformEvent::Insets{ui_generation:generation as u64,value:Insets{top,right,bottom,left,keyboard}});}}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeAccessibility(_env:JNIEnv,_class:JClass,generation:jlong,scale:jfloat,reduced:jboolean,contrast:jboolean,reader:jboolean){if generation>0&&UI.load(Ordering::Acquire)==generation as u64&&scale.is_finite()&&scale>0.0{SCREEN_READER.store(reader!=0,Ordering::Release);lifecycle::emit(PlatformEvent::Accessibility{ui_generation:generation as u64,text_scale:scale,reduce_motion:reduced!=0,high_contrast:contrast!=0,screen_reader:reader!=0});}}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativePip(_env:JNIEnv,_class:JClass,token:jlong,active:jboolean,playing:jboolean){if let Some(Action{key,stream:Some(stream_id)})=action(token as u64){lifecycle::emit(PlatformEvent::PictureInPicture{key,stream_id,active:active!=0,playing:playing!=0});}}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeHarnessEnabled(_env:JNIEnv,_class:JClass)->jboolean{cfg!(feature="test-harness") as u8}
//! Android owns OS capabilities, never a second UI or server model.
use std::{collections::HashMap, ffi::c_void, path::PathBuf, sync::{Arc, LazyLock, Mutex, OnceLock, atomic::{AtomicBool, AtomicU64, Ordering}}};
use jni::{JNIEnv, JavaVM, objects::{GlobalRef, JClass, JObject, JString, JValue}, sys::{jboolean, jfloat, jint, jlong}};
use tokio::sync::oneshot;
use crate::{AppConfig, AppRuntime, app::connections::SessionKey, services::{Result, ServiceError}};
use super::{lifecycle::{self, Insets, NotificationAction, Permission, PlatformEvent}, resources::{ActionPolicy, PickRequest, Selection}};
mod documents;
mod smoke;
mod call_audio;
mod private_container;
mod tls;
pub use smoke::{AndroidSmokeRequest, smoke_request};
pub mod accessibility;
pub use accessibility::{attach_accessibility, AccessibilityLease};
struct Binding { vm: JavaVM, application: GlobalRef, class: GlobalRef, files: PathBuf }
static BINDING: OnceLock<Binding> = OnceLock::new();
// Retain the join owner until a new Activity has retired it, even after its last UI/call lease drops.
static RUNTIME: LazyLock<Mutex<Option<Arc<AppRuntime>>>> = LazyLock::new(|| Mutex::new(None));
static UI: AtomicU64 = AtomicU64::new(0);
static SCREEN_READER: AtomicBool = AtomicBool::new(false);
static NEXT: AtomicU64 = AtomicU64::new(1);
static REQUESTS: LazyLock<Mutex<HashMap<u64, oneshot::Sender<Result<Response>>>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
struct Voice { token: u64, key: SessionKey, microphone: bool, capture_revision: u64, capture_change: Option<u64>, failed_playback_revision: Option<u64>, audio: call_audio::CallAudioState, _runtime: Arc<AppRuntime> }
static VOICE: LazyLock<Mutex<Option<Voice>>> = LazyLock::new(|| Mutex::new(None));
static ROUTE_LOG_BUDGET: LazyLock<Mutex<call_audio::RouteLogBudget>> = LazyLock::new(|| Mutex::new(Default::default()));
#[derive(Clone, Copy, Debug)]
pub(crate) enum VoiceRoutePhase { CallStart, CaptureChange, Authorization, Fence, Selection, Settings, Validate, Configuration, StopInput, SelectInput, SelectOutput, StopOutput, StartOutput, OutputAck, CaptureIntent, ResumeCapture, MuteCapture, Enumerate, Complete }
#[derive(Clone, Copy, Debug)]
pub(crate) enum VoiceRouteReason { Queued, Timeout, RouteChanged, FocusGained, FocusLost, CaptureRevoked, Pending, Completed, Failed, OwnerChanged, AudioRevisionChanged, CaptureIntentChanged, PlaybackRevoked, OutputNotGranted, DefaultSelection, ExactSelection }
// Called only by service/control workers, never a PCM callback. No identity-bearing
// keys, endpoint IDs, device descriptions or arbitrary platform error strings.
fn route_log_permit() -> Option<u64> { ROUTE_LOG_BUDGET.lock().expect("Android route log budget").take(std::time::Instant::now()) }
fn log_voice_authorization(token:u64,phase:VoiceRoutePhase,reason:VoiceRouteReason) {
let Some(suppressed)=route_log_permit() else{return};
let state={let slot=VOICE.lock().expect("Android voice");slot.as_ref().filter(|voice|voice.token==token).map(|voice|(voice.audio.allows(false),voice.audio.allows(true),voice.audio.retains_capture(),voice.audio.restart_output(),voice.capture_change.is_some()))};
eprintln!("audio_route platform=native phase={phase:?} reason={reason:?} lease_current={} output_allowed={} capture_allowed={} capture_retained={} restart_pending={} capture_change_pending={} suppressed={suppressed}",state.is_some(),state.is_some_and(|s|s.0),state.is_some_and(|s|s.1),state.is_some_and(|s|s.2),state.is_some_and(|s|s.3),state.is_some_and(|s|s.4));
}
pub(crate) fn log_voice_route(key:&SessionKey,phase:VoiceRoutePhase,reason:VoiceRouteReason,elapsed:std::time::Duration,restart_output:bool,output_active:bool,input_active:bool) {
let Some(suppressed)=route_log_permit() else{return};
let state={let slot=VOICE.lock().expect("Android voice");slot.as_ref().filter(|voice|&voice.key==key).map(|voice|(voice.audio.allows(false),voice.audio.allows(true),voice.audio.retains_capture(),voice.audio.restart_output()))};
eprintln!("audio_route platform=runtime phase={phase:?} reason={reason:?} elapsed_ms={} lease_current={} restart_output={restart_output} output_allowed={} output_active={output_active} capture_allowed={} input_active={input_active} capture_retained={} restart_pending={} suppressed={suppressed}",elapsed.as_millis(),state.is_some(),state.is_some_and(|s|s.0),state.is_some_and(|s|s.1),state.is_some_and(|s|s.2),state.is_some_and(|s|s.3));
}
fn log_voice_selection(reason:VoiceRouteReason) {
if let Some(suppressed)=route_log_permit(){eprintln!("audio_route platform=native phase={:?} reason={reason:?} suppressed={suppressed}",VoiceRoutePhase::Selection);}
}
fn log_voice_request(phase:VoiceRoutePhase,reason:VoiceRouteReason,started:std::time::Instant,capture:bool) {
if let Some(suppressed)=route_log_permit(){eprintln!("audio_route platform=native phase={phase:?} reason={reason:?} elapsed_ms={} capture_requested={capture} suppressed={suppressed}",started.elapsed().as_millis());}
}
#[derive(Clone)]
struct Action { key: SessionKey, stream: Option<String> }
static ACTIONS: LazyLock<Mutex<HashMap<u64, Action>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
enum Response { Selection(Option<Selection>), Permission(bool), Text(String), Voice }
fn error(code: &'static str, message: impl Into<String>) -> ServiceError { ServiceError::new(code, message) }
fn java<T>(value: jni::errors::Result<T>) -> Result<T> { value.map_err(|_| error("android_os_error", "Android rejected the requested OS operation")) }
fn binding() -> Result<&'static Binding> { BINDING.get().ok_or_else(|| error("android_not_initialized", "Android Application context has not been initialized")) }
fn with_env<T>(operation: impl FnOnce(&mut JNIEnv<'_>, &JClass<'_>) -> Result<T>) -> Result<T> {
let binding = binding()?;
let mut env = java(binding.vm.attach_current_thread())?;
java(env.push_local_frame(48))?;
let result = operation(&mut env, binding.class.as_obj().into());
if env.exception_check().unwrap_or(true) { let _ = env.exception_clear(); }
let _ = unsafe { env.pop_local_frame(&JObject::null()) };
result
}
fn next_id() -> Result<u64> { NEXT.fetch_update(Ordering::AcqRel, Ordering::Acquire, |id| (id < i64::MAX as u64).then_some(id + 1)).map_err(|_| error("generation_exhausted", "Android action identity exhausted")) }
fn call_void(name: &str, signature: &str, args: &[JValue<'_, '_>]) -> Result<()> { with_env(|env, class| { java(env.call_static_method(class, name, signature, args))?; Ok(()) }) }
pub(crate) fn finish_activity(generation: u64) -> Result<()> { call_void("finishActivity", "(J)V", &[JValue::Long(generation as i64)]) }
fn complete(id: u64, response: Result<Response>) { if let Some(sender) = REQUESTS.lock().expect("Android requests").remove(&id) { let _ = sender.send(response); } }
struct Request { id: u64, receiver: Option<oneshot::Receiver<Result<Response>>> }
impl Request {
fn new() -> Result<Self> {
let mut pending = REQUESTS.lock().expect("Android requests");
if pending.len() >= 32 { return Err(error("os_busy", "Too many pending Android OS operations")); }
let id = next_id()?; let (sender, receiver) = oneshot::channel(); pending.insert(id, sender);
Ok(Self { id, receiver: Some(receiver) })
}
async fn receive(mut self) -> Result<Response> { self.receiver.take().expect("single Android receiver").await.map_err(|_| error("operation_cancelled", "Android operation was cancelled"))? }
}
impl Drop for Request { fn drop(&mut self) { if REQUESTS.lock().expect("Android requests").remove(&self.id).is_some() { let _ = call_void("cancel", "(J)V", &[JValue::Long(self.id as i64)]); } } }
fn accepted(value: bool) -> Result<()> { if value { Ok(()) } else { Err(error("os_busy", "Android OS callback queue is full or the action was denied")) } }
fn permission_id(permission: Permission) -> i32 { match permission { Permission::Microphone => 0, Permission::Camera => 1, Permission::Notifications => 2 } }
/// Process-owned context for CPAL/WebRTC; the GlobalRef is never an Activity.
pub fn application_context() -> Result<(*mut c_void, *mut c_void)> { let b = binding()?; Ok((b.vm.get_java_vm_pointer().cast(), b.application.as_obj().as_raw().cast())) }
pub fn build_channel()->Result<crate::services::updates::BuildChannel>{with_env(|env,_|{let harness=java(env.get_static_field("dev/teamspeach/mobile/BuildConfig","TEST_HARNESS","Z"))?.z().map_err(|_|error("build_channel","Android build metadata is invalid"))?;let direct=java(env.get_static_field("dev/teamspeach/mobile/BuildConfig","DIRECT_UPDATES","Z"))?.z().map_err(|_|error("build_channel","Android update metadata is invalid"))?;Ok(if harness{crate::services::updates::BuildChannel::Development}else if direct{crate::services::updates::BuildChannel::Direct}else{crate::services::updates::BuildChannel::GooglePlay})})}
/// Called by the root `android_main`, with the re-exported android-activity 0.6 type.
pub fn run(app: slint::android::AndroidApp) {
let result = (|| -> std::result::Result<(), Box<dyn std::error::Error>> {
let smoke = smoke_request(&app)?;
#[cfg(feature="test-harness")]
let prepared = if let Some(request) = &smoke {
if RUNTIME.lock().expect("Android runtime").is_some() {
return Err(error("smoke_runtime_active", "Restart the isolated test process before launching a smoke scenario").into());
}
Some(crate::smoke::prepare(&request.scenario, request.profile.clone(), request.output.clone())?)
} else { None };
let previous = RUNTIME.lock().expect("Android runtime").clone();
if smoke.is_some() && previous.is_some() { return Err(error("smoke_runtime_active", "Restart the isolated test process before launching a smoke scenario").into()); }
// The process mutex is released before joining the old actor or starting its replacement.
let runtime = crate::runtime_attachment::runtime_for_attachment(previous, || Ok(AppConfig {
mobile_container: Some(binding()?.files.clone()),
profile_dir: smoke.as_ref().map(|request|request.profile.clone()),
allow_os_actions: smoke.is_none(),
network_enabled: smoke.is_none(),
..AppConfig::default()
}))?;
*RUNTIME.lock().expect("Android runtime") = Some(runtime.clone());
i_slint_backend_android_activity::set_clipboard_enabled(smoke.is_none());
let generation = runtime.next_ui_generation(); UI.store(generation, Ordering::Release);
struct AttachmentGeneration(u64);
impl Drop for AttachmentGeneration {fn drop(&mut self){destroy_ui(self.0);}}
let _attachment = AttachmentGeneration(generation);
slint::android::init_with_event_listener(app.clone(), move |event| {
use slint::android::android_activity::{MainEvent, PollEvent};
if matches!(event, PollEvent::Main(MainEvent::Destroy)) { destroy_ui(generation); }
})?;
with_env(|env, class| {
// Borrow only during this UI attachment call; no worker receives an Activity reference.
let activity = unsafe { JObject::from_raw(app.activity_as_ptr().cast()) };
accepted(java(env.call_static_method(class,"attached","(Landroid/app/Activity;J)Z",&[JValue::Object(&activity),JValue::Long(generation as i64)]))?.z().unwrap_or(false))
})?;
#[cfg(feature="test-harness")]
let result = if let Some(prepared) = prepared {
crate::smoke::run_prepared(runtime, generation, prepared)
} else {
crate::attach_ui_with_generation(runtime, generation)
};
#[cfg(not(feature="test-harness"))]
let result = crate::attach_ui_with_generation(runtime, generation);
destroy_ui(generation);
result?;
Ok(())
})();
if let Err(error) = result { eprintln!("Android native startup: {error}"); }
}
fn destroy_ui(generation: u64) {
if UI.compare_exchange(generation, 0, Ordering::AcqRel, Ordering::Acquire).is_ok() {
lifecycle::emit(PlatformEvent::UiDestroyed { ui_generation: generation });
accessibility::detach(generation);
}
}
pub async fn pick(request: PickRequest, policy: ActionPolicy) -> Result<Option<Selection>> {
policy.check()?; let pending = Request::new()?;
let (kind, name, mime, types) = match request {
PickRequest::Open { mime_types } => (0, String::new(), "*/*".to_owned(), mime_types),
PickRequest::Save { suggested_name, mime_type } => { super::resources::require_component(&suggested_name)?; (1, suggested_name, mime_type, Vec::new()) },
PickRequest::Directory => (2, String::new(), "*/*".to_owned(), Vec::new()),
};
if types.len() > 64 || types.iter().chain(std::iter::once(&mime)).any(|s| s.len() > 128 || s.contains('\0')) { return Err(error("invalid_mime", "Invalid document MIME filter")); }
with_env(|env, class| {
let name = java(env.new_string(name))?; let mime = java(env.new_string(mime))?;
let array = java(env.new_object_array(types.len() as i32, "java/lang/String", JObject::null()))?;
for (index, value) in types.iter().enumerate() { let value = java(env.new_string(value))?; java(env.set_object_array_element(&array, index as i32, &value))?; java(env.delete_local_ref(value))?; }
accepted(java(env.call_static_method(class, "pick", "(JILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;)Z", &[JValue::Long(pending.id as i64), JValue::Int(kind), JValue::Object(&name), JValue::Object(&mime), JValue::Object(&array)]))?.z().map_err(|_| error("android_os_error", "Invalid picker response"))?)
})?;
match pending.receive().await? { Response::Selection(value) => Ok(value), _ => Err(error("android_os_error", "Unexpected picker completion")) }
}
/// Read current OS permission without prompting or activating a microphone.
pub(crate) fn microphone_permission_granted(policy: ActionPolicy) -> Result<bool> {
policy.check()?;
with_env(|env,class| java(env.call_static_method(class,"granted","(I)Z",&[JValue::Int(0)]))?
.z().map_err(|_|error("android_os_error","Invalid microphone permission state")))
}
pub async fn request_permission(permission: Permission, policy: ActionPolicy) -> Result<bool> {
policy.check()?; let pending = Request::new()?;
with_env(|env, class| accepted(java(env.call_static_method(class, "permission", "(JI)Z", &[JValue::Long(pending.id as i64), JValue::Int(permission_id(permission))]))?.z().unwrap_or(false)))?;
match pending.receive().await? { Response::Permission(value) => Ok(value), _ => Err(error("android_os_error", "Unexpected permission completion")) }
}
/// Caller revalidates `key` and active-call intent before this explicit foreground action.
pub async fn start_voice(runtime: Arc<AppRuntime>, key: SessionKey, microphone: bool, playback:&str, policy: ActionPolicy) -> Result<()> {
policy.check()?; let endpoint=voice_endpoint(playback)?;let request = Request::new()?; let token = request.id;
{ let mut voice = VOICE.lock().expect("Android voice"); if voice.is_some() { return Err(error("call_lease_exists", "An Android foreground call already owns the audio session")); } *voice = Some(Voice { token, key: key.clone(), microphone: false, capture_revision: 0, capture_change: None, failed_playback_revision: None, audio: Default::default(), _runtime: runtime }); }
struct PendingVoice(u64, bool);
impl Drop for PendingVoice { fn drop(&mut self) { if !self.1 { end_voice(self.0); let _ = call_void("stopVoice", "(J)V", &[JValue::Long(self.0 as i64)]); } } }
let mut pending = PendingVoice(token, false);
let started=std::time::Instant::now();
if let Err(error)=with_env(|env, class| accepted(java(env.call_static_method(class, "startVoice", "(JZI)Z", &[JValue::Long(token as i64), JValue::Bool(microphone as u8),JValue::Int(endpoint)]))?.z().unwrap_or(false))){
log_voice_request(VoiceRoutePhase::CallStart,VoiceRouteReason::Failed,started,microphone);return Err(error)
}
log_voice_request(VoiceRoutePhase::CallStart,VoiceRouteReason::Queued,started,microphone);
let (result,reason)=match tokio::time::timeout(std::time::Duration::from_secs(15), request.receive()).await {
Ok(Ok(Response::Voice)) if VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|voice.token==token && voice.microphone==microphone && voice.audio.allows(microphone)) => { pending.1 = true; (Ok(()),VoiceRouteReason::Completed) },
Ok(Err(error)) => (Err(error),VoiceRouteReason::Failed),
Err(_) => (Err(error("call_start_failed", "Android did not grant a foreground voice session")),VoiceRouteReason::Timeout),
_ => (Err(error("call_start_failed", "Android did not grant a foreground voice session")),VoiceRouteReason::AudioRevisionChanged),
};
log_voice_request(VoiceRoutePhase::CallStart,reason,started,microphone);
result
}
/// Stop/invalidate CPAL capture before disabling. Enable CPAL only after this OS acknowledgment
/// and revalidation of the captured SessionKey. Enabling always requires a visible user action.
pub async fn set_voice_capture(key: &SessionKey, enabled: bool, policy: ActionPolicy) -> Result<()> {
policy.check()?;
let request=Request::new()?;let id=request.id;
let token={let mut slot=VOICE.lock().expect("Android voice");let voice=slot.as_mut().filter(|voice|&voice.key==key).ok_or_else(||error("target_changed","The Android call lease changed"))?;
if voice.capture_change.is_some(){return Err(error("call_capture_busy","An Android microphone transition is pending"));}
voice.capture_revision=id;voice.capture_change=Some(id);voice.token};
struct CaptureChange {token:u64,id:u64,committed:bool}
impl Drop for CaptureChange {fn drop(&mut self){if !self.committed {
let cancel={let mut slot=VOICE.lock().expect("Android voice");if let Some(voice)=slot.as_mut().filter(|voice|voice.token==self.token&&voice.capture_revision==self.id){voice.microphone=false;voice.audio.revoke_capture();voice.capture_change=None;true}else{false}};
if cancel{let _=call_void("cancelVoiceCapture","(JJ)V",&[JValue::Long(self.token as i64),JValue::Long(self.id as i64)]);}
}}}
let mut change=CaptureChange{token,id,committed:false};
let started=std::time::Instant::now();
if let Err(error)=with_env(|env,class|accepted(java(env.call_static_method(class,"setVoiceCapture","(JJZ)Z",&[JValue::Long(token as i64),JValue::Long(id as i64),JValue::Bool(enabled as u8)]))?.z().unwrap_or(false))){
log_voice_request(VoiceRoutePhase::CaptureChange,VoiceRouteReason::Failed,started,enabled);return Err(error)
}
log_voice_request(VoiceRoutePhase::CaptureChange,VoiceRouteReason::Queued,started,enabled);
let (result,reason)=match tokio::time::timeout(std::time::Duration::from_secs(15),request.receive()).await {
Ok(Ok(Response::Voice)) if VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|voice.token==token&&voice.capture_revision==id&&voice.microphone==enabled)=>{change.committed=true;(Ok(()),VoiceRouteReason::Completed)},
Ok(Err(error))=>(Err(error),VoiceRouteReason::Failed),
Err(_)=>(Err(error("call_capture_failed","Android did not acknowledge the microphone service transition")),VoiceRouteReason::Timeout),
_=>(Err(error("call_capture_failed","Android did not acknowledge the microphone service transition")),VoiceRouteReason::AudioRevisionChanged),
};
log_voice_request(VoiceRoutePhase::CaptureChange,reason,started,enabled);
result
}
fn voice_audio_changed(token:u64, focused:Option<bool>, restart_output:bool) {
let reason=match focused{Some(true)=>VoiceRouteReason::FocusGained,Some(false)=>VoiceRouteReason::FocusLost,None if restart_output=>VoiceRouteReason::RouteChanged,None=>VoiceRouteReason::CaptureRevoked};
let changed={let mut slot=VOICE.lock().expect("Android voice");slot.as_mut().filter(|voice|voice.token==token).map(|voice|{
let route=focused.is_none()&&restart_output;
// Only completed consent can survive endpoint replacement. A route may
// cancel a pending activation, but can never acknowledge it on its behalf.
if !route||voice.capture_change.is_some(){voice.microphone=false;voice.capture_revision=0;}
let revision=match focused{Some(focused)=>voice.audio.interrupt(focused),None if route=>{
if !voice.microphone{voice.audio.revoke_capture();}voice.audio.route_changed()
},None=>voice.audio.revoke_capture()};
(voice.key.clone(),revision,voice.capture_change.take(),voice.audio.restart_output())
})};
if let Some((key,revision,pending,restart_output))=changed {
if let Some(id)=pending{complete(id,Err(error("call_capture_revoked","Microphone transition was superseded by an Android audio change")));}
lifecycle::emit(PlatformEvent::AndroidCallAudio{key,token,revision,restart_output});
log_voice_authorization(token,VoiceRoutePhase::Authorization,reason);
}
}
/// Capture and playback retain exact endpoint identity, including the phone mic.
pub(crate) fn voice_device_selection(raw:&str)->Result<crate::media::audio::devices::DeviceSelection>{
use crate::media::audio::devices::DeviceSelection;
if raw.is_empty(){log_voice_selection(VoiceRouteReason::DefaultSelection);Ok(DeviceSelection::SystemDefault)}
else{log_voice_selection(VoiceRouteReason::ExactSelection);Ok(DeviceSelection::Exact(raw.into()))}
}
/// Communication-route inventory uses the same platform API as explicit selection.
/// None keeps the existing pre-API31 enumeration behavior; errors never fabricate routes.
pub(crate) fn communication_outputs()->Result<Option<Vec<(String,i32)>>> {
with_env(|env,class|{
let sdk=java(env.get_static_field("android/os/Build$VERSION","SDK_INT","I"))?.i().map_err(|_|error("android_os_error","Android API level unavailable"))?;
if sdk<31{return Ok(None)}
let value=java(env.call_static_method(class,"communicationOutputs","()[I",&[]))?.l().map_err(|_|error("android_os_error","Communication output inventory unavailable"))?;
let array=jni::objects::JIntArray::from(value);
let length=java(env.get_array_length(&array))?;
if length<0||length%2!=0{return Err(error("android_os_error","Invalid communication output inventory"))}
let mut raw=vec![0;length as usize];java(env.get_int_array_region(&array,0,&mut raw))?;
Ok(Some(raw.chunks_exact(2).filter(|pair|pair[0]>0).map(|pair|(format!("aaudio:{}",pair[0]),pair[1])).collect()))
})
}
fn voice_endpoint(raw:&str)->Result<i32> {
if raw.is_empty(){return Ok(0)}
let id=raw.parse::<cpal::DeviceId>().map_err(|_|error("device_unavailable","Invalid exact Android audio endpoint"))?;
if id.host()!=cpal::HostId::AAudio{return Err(error("device_unavailable","The exact endpoint is not an Android audio device"))}
match id.id().parse::<i32>(){Ok(-1)=>Ok(0),Ok(id) if id>0=>Ok(id),_=>Err(error("device_unavailable","The exact Android audio endpoint is unavailable"))}
}
/// Validate the user's exact pair using platform types/addresses, never names or
/// a guessed input->output remapping. Read-only: does not activate any transport.
pub(crate) fn validate_voice_capture_pair(input:&str,output:&str,settled:bool)->Result<()> {
let input=voice_endpoint(input)?;
if input==0{return Ok(())}
let output=voice_endpoint(output)?;
let result=with_env(|env,class|{
// Use the installed application class loader, not FindClass on a native
// Tokio thread (whose bootstrap loader cannot resolve app classes).
let loader=java(env.call_method(class,"getClassLoader","()Ljava/lang/ClassLoader;",&[]))?.l().map_err(|_|error("android_os_error","Android class loader unavailable"))?;
let name=java(env.new_string("dev.teamspeach.mobile.VoiceService"))?;
let service=java(env.call_method(&loader,"loadClass","(Ljava/lang/String;)Ljava/lang/Class;",&[JValue::Object(name.as_ref())]))?.l().map_err(|_|error("android_os_error","Android route validator unavailable"))?;
let service=JClass::from(service);
java(env.call_static_method(&service,"validateCapturePair","(IIZ)I",&[JValue::Int(input),JValue::Int(output),JValue::Bool(settled as u8)]))?.i().map_err(|_|error("android_os_error","Invalid Android route validation response"))
})?;
match result {
0=>Ok(()),
1=>Err(error("device_unavailable","The exact capture endpoint is no longer available; the saved choice has not changed")),
2=>Err(error("audio_route_incompatible","The exact Bluetooth capture endpoint requires a matching active communication playback transport. Choose a compatible Capture/Playback pair explicitly; neither saved choice was changed")),
3=>Err(error("audio_route_incompatible","The chosen playback communication route is not active for the exact Bluetooth capture endpoint; explicitly select a compatible playback route")),
_=>Err(error("android_os_error","Invalid Android route validation response")),
}
}
/// Only an explicit playback action requests a communication-device override.
/// Its caller owns configuration and recovery; capture/DSP refresh never calls it.
pub(crate) async fn select_voice_playback(raw:&str)->Result<Option<(u64,u64)>> {
let token=match VOICE.lock().expect("Android voice").as_ref(){Some(voice)=>voice.token,None=>return Ok(None)};
let endpoint=voice_endpoint(raw)?;
let request=Request::new()?;let id=request.id;
struct PlaybackChange {token:u64,id:u64,completed:bool}
impl Drop for PlaybackChange {fn drop(&mut self){if !self.completed{let _=call_void("cancelVoicePlayback","(JJ)V",&[JValue::Long(self.token as i64),JValue::Long(self.id as i64)]);}}}
let mut change=PlaybackChange{token,id,completed:false};
with_env(|env,class|accepted(java(env.call_static_method(class,"setVoicePlayback","(JJI)Z",&[JValue::Long(token as i64),JValue::Long(id as i64),JValue::Int(endpoint)]))?.z().unwrap_or(false)))?;
match tokio::time::timeout(std::time::Duration::from_secs(15),request.receive()).await {
Ok(Ok(Response::Text(_)))=>{
let slot=VOICE.lock().expect("Android voice");
let voice=slot.as_ref().filter(|voice|voice.token==token).ok_or_else(||error("target_changed","The Android call changed during playback selection"))?;
change.completed=true;Ok(Some((token,voice.audio.revision())))
},
Ok(Err(error))=>Err(error),
Err(_)=>Err(error("audio_route_timeout","Android did not acknowledge the exact playback communication route")),
_=>Err(error("target_changed","The Android call changed during playback selection")),
}
}
pub(crate) fn acknowledge_voice_playback(token:u64,revision:u64,active:bool) {
if let Some(voice)=VOICE.lock().expect("Android voice").as_mut().filter(|voice|voice.token==token){voice.audio.acknowledge_output(revision,active);}
}
pub(crate) fn voice_audio_allowed(key:&SessionKey,microphone:bool)->bool {
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|&voice.key==key&&voice.audio.allows(microphone))
}
pub(crate) fn voice_capture_retained(key:&SessionKey)->bool {
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|&voice.key==key&&voice.audio.retains_capture())
}
pub(crate) fn voice_audio_current(key:&SessionKey,token:u64,revision:u64)->bool {
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|&voice.key==key&&voice.token==token&&voice.audio.is_current(revision))
}
pub(crate) fn voice_playback_failed(key:&SessionKey,token:u64,revision:u64)->bool {
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|&voice.key==key&&voice.token==token&&voice.audio.is_current(revision)&&voice.failed_playback_revision==Some(revision))
}
pub(crate) fn acknowledge_voice_output(key:&SessionKey,token:u64,revision:u64,active:bool) {
let acknowledged={let mut slot=VOICE.lock().expect("Android voice");if let Some(voice)=slot.as_mut().filter(|voice|&voice.key==key&&voice.token==token){let current=voice.audio.is_current(revision);voice.audio.acknowledge_output(revision,active);current}else{false}};
log_voice_authorization(token,VoiceRoutePhase::OutputAck,if acknowledged{VoiceRouteReason::Completed}else{VoiceRouteReason::AudioRevisionChanged});
}
fn end_voice(token: u64) -> bool {
end_voice_with_shutdown(token,false)
}
/// Task dismissal is terminal only for the exact lease that owns this callback.
fn end_voice_with_shutdown(token:u64,shutdown:bool)->bool {
let voice = { let mut voice = VOICE.lock().expect("Android voice"); if voice.as_ref().is_some_and(|voice| voice.token == token) { voice.take() } else { None } };
if let Some(voice) = voice {
if shutdown{voice._runtime.request_shutdown();}
lifecycle::emit(PlatformEvent::CallLeaseEnded { key: voice.key.clone() }); complete(token, Err(error("call_lease_ended", "Android foreground call ended"))); if let Some(id)=voice.capture_change{complete(id,Err(error("call_lease_ended","Android foreground call ended")));} true
} else { false }
}
pub fn stop_voice(key: &SessionKey) -> Result<()> {
let token = VOICE.lock().expect("Android voice").as_ref().filter(|voice| &voice.key == key).map(|voice| voice.token);
if let Some(token) = token { end_voice(token); call_void("stopVoice", "(J)V", &[JValue::Long(token as i64)])?; }
Ok(())
}
pub fn invalidate_session(key: &SessionKey) {
let _ = stop_voice(key);
let tokens: Vec<_> = { let mut actions = ACTIONS.lock().expect("Android actions"); let tokens = actions.iter().filter(|(_, action)| &action.key == key).map(|(token, _)| *token).collect::<Vec<_>>(); for token in &tokens { actions.remove(token); } tokens };
for token in tokens { let _ = call_void("cancelNotification", "(J)V", &[JValue::Long(token as i64)]); let _ = call_void("closePip", "(J)V", &[JValue::Long(token as i64)]); }
}
fn register_action(key: SessionKey, stream: Option<String>) -> Result<u64> {
let mut actions = ACTIONS.lock().expect("Android actions");
if actions.len() >= 64 { return Err(error("notification_limit", "Dismiss existing OS notifications before adding more")); }
let token = next_id()?; actions.insert(token, Action { key, stream }); Ok(token)
}
pub struct NotificationLease(u64);
impl Drop for NotificationLease { fn drop(&mut self) { ACTIONS.lock().expect("Android actions").remove(&self.0); let _ = call_void("cancelNotification", "(J)V", &[JValue::Long(self.0 as i64)]); } }
pub fn notify(key: SessionKey, title: &str, body: &str, policy: ActionPolicy) -> Result<NotificationLease> {
policy.check()?; if title.len()>1024 || body.len()>8192 { return Err(error("notification_size", "Notification text is too large")); }
let lease = NotificationLease(register_action(key, None)?);
with_env(|env, class| { let title = java(env.new_string(title))?; let body = java(env.new_string(body))?; accepted(java(env.call_static_method(class,"notify","(JLjava/lang/String;Ljava/lang/String;)Z", &[JValue::Long(lease.0 as i64),JValue::Object(&title),JValue::Object(&body)]))?.z().unwrap_or(false)) })?;
Ok(lease)
}
pub struct PictureInPictureLease(u64);
impl Drop for PictureInPictureLease { fn drop(&mut self) { let action = ACTIONS.lock().expect("Android actions").remove(&self.0); if let Some(action) = action { if let Some(stream_id) = action.stream { lifecycle::emit(PlatformEvent::PictureInPicture { key: action.key, stream_id, active:false, playing:true }); } } let _ = call_void("closePip", "(J)V", &[JValue::Long(self.0 as i64)]); } }
/// The caller presents the existing viewer tile before entering PiP. No peer or volume is changed here.
pub async fn enter_picture_in_picture(key: SessionKey, stream_id: String, width: u32, height: u32, policy: ActionPolicy) -> Result<PictureInPictureLease> {
policy.check()?; if stream_id.is_empty() || stream_id.len()>256 || width==0 || height==0 || !(0.418..=2.39).contains(&(width as f64/height as f64)) { return Err(error("pip_aspect_ratio", "Android PiP needs an existing viewer and aspect ratio between 1:2.39 and 2.39:1")); }
with_env(|env, class| { let reason = java(env.call_static_method(class,"pipUnavailable","()Ljava/lang/String;",&[]))?.l().map_err(|_|error("pip_unavailable","Android PiP capability query failed"))?; if reason.is_null() {Ok(())} else {let reason=JString::from(reason);Err(error("pip_unavailable",String::from(java(env.get_string(&reason))?)))}})?;
let lease = PictureInPictureLease(register_action(key, Some(stream_id))?);
let request=Request::new()?;
with_env(|env, class| accepted(java(env.call_static_method(class,"pip","(JJII)Z", &[JValue::Long(request.id as i64),JValue::Long(lease.0 as i64),JValue::Int(width as i32),JValue::Int(height as i32)]))?.z().unwrap_or(false)))?;
match request.receive().await? {Response::Text(_)=>Ok(lease),_=>Err(error("pip_unavailable","Android did not acknowledge picture-in-picture"))}
}
pub async fn clipboard_read(policy: ActionPolicy) -> Result<String> { clipboard(None, policy).await }
pub async fn clipboard_write(text: &str, policy: ActionPolicy) -> Result<()> { clipboard(Some(text), policy).await.map(|_| ()) }
async fn clipboard(text: Option<&str>, policy: ActionPolicy) -> Result<String> {
policy.check()?; if text.is_some_and(|value|value.len()>1024*1024) { return Err(error("clipboard_size", "Clipboard text exceeds 1 MiB")); }
let request = Request::new()?;
with_env(|env,class| { let value=java(env.new_string(text.unwrap_or_default()))?; accepted(java(env.call_static_method(class,"clipboard","(JLjava/lang/String;Z)Z",&[JValue::Long(request.id as i64),JValue::Object(&value),JValue::Bool(text.is_some() as u8)]))?.z().unwrap_or(false)) })?;
match request.receive().await? { Response::Text(value)=>Ok(value), _=>Err(error("android_os_error","Unexpected clipboard completion")) }
}
pub async fn share_text(text: &str, policy: ActionPolicy) -> Result<()> {
policy.check()?; if text.len()>1024*1024 { return Err(error("share_size", "Shared text exceeds 1 MiB")); }
let request=Request::new()?;
with_env(|env,class| { let text=java(env.new_string(text))?; let mime=java(env.new_string("text/plain"))?; accepted(java(env.call_static_method(class,"share","(JLjava/lang/String;Ldev/teamspeach/mobile/SafGrant;Ljava/lang/String;)Z",&[JValue::Long(request.id as i64),JValue::Object(&text),JValue::Object(&JObject::null()),JValue::Object(&mime)]))?.z().unwrap_or(false)) })?;
match request.receive().await? { Response::Text(_)=>Ok(()), _=>Err(error("android_os_error","Unexpected share completion")) }
}
/// Shares only a document capability returned by this platform's SAF picker.
pub async fn share_document(document: Arc<dyn super::resources::DocumentGrant>, mime_type: &str, policy: ActionPolicy) -> Result<()> {
policy.check()?;
if mime_type.is_empty() || mime_type.len()>128 || mime_type.contains('\0') {return Err(error("invalid_mime","Invalid share MIME type"));}
let native = document.as_any().downcast_ref::<documents::Document>().ok_or_else(||error("document_grant","Android share requires an Android document capability"))?;
let request=Request::new()?;
with_env(|env,class| {let text=java(env.new_string(""))?;let mime=java(env.new_string(mime_type))?;accepted(java(env.call_static_method(class,"share","(JLjava/lang/String;Ldev/teamspeach/mobile/SafGrant;Ljava/lang/String;)Z",&[JValue::Long(request.id as i64),JValue::Object(&text),JValue::Object(native.object()),JValue::Object(&mime)]))?.z().unwrap_or(false))})?;
match request.receive().await? {Response::Text(_)=>Ok(()),_=>Err(error("android_os_error","Unexpected share completion"))}
}
#[derive(Clone,Copy,Debug,PartialEq,Eq)]
pub enum InstallOutcome { Installed, Cancelled }
/// Only an explicit updater effect can supply this verified capability. The OS still asks for consent.
pub async fn install_apk(apk: crate::services::updates::VerifiedApk, policy: ActionPolicy) -> Result<InstallOutcome> {
use std::os::fd::AsRawFd;
policy.check()?;
let (_apk, descriptor)=tokio::task::spawn_blocking(move||apk.open_for_install().map(|file|(apk,file))).await.map_err(|_|error("installer_worker","Verified APK worker stopped"))?.map_err(|failure|ServiceError::new(failure.code,failure.detail))?;
let request=Request::new()?;
with_env(|env,class|accepted(java(env.call_static_method(class,"installApk","(JI)Z",&[JValue::Long(request.id as i64),JValue::Int(descriptor.as_raw_fd())]))?.z().unwrap_or(false)))?;
// Java duplicated the verified read-only descriptor synchronously before posting the UI work.
drop(descriptor);
match request.receive().await? {Response::Text(value) if value=="installed"=>Ok(InstallOutcome::Installed),Response::Text(value) if value=="cancelled"=>Ok(InstallOutcome::Cancelled),_=>Err(error("installer_result","Android returned an invalid installer result"))}
}
pub async fn open_store(policy: ActionPolicy) -> Result<()> {
policy.check()?;let request=Request::new()?;
with_env(|env,class|accepted(java(env.call_static_method(class,"openStore","(J)Z",&[JValue::Long(request.id as i64)]))?.z().unwrap_or(false)))?;
match request.receive().await? {Response::Text(_)=>Ok(()),_=>Err(error("store_result","Android returned an invalid store response"))}
}
/// Called only after the privacy service has obtained consent for this URL.
pub async fn open_external_url(url:&str,policy:ActionPolicy)->Result<()> {
policy.check()?;
let parsed=reqwest::Url::parse(url).map_err(|_|error("invalid_url","Invalid external URL"))?;
if !matches!(parsed.scheme(),"https"|"http"|"mailto"){return Err(error("invalid_url","This external URL scheme is not allowed"))}
let request=Request::new()?;
with_env(|env,class|{
let value=java(env.new_string(parsed.as_str()))?;
accepted(java(env.call_static_method(class,"openExternalUrl","(JLjava/lang/String;)Z",&[JValue::Long(request.id as i64),JValue::Object(&value)]))?.z().unwrap_or(false))
})?;
match request.receive().await?{Response::Text(_)=>Ok(()),_=>Err(error("link_result","Android returned an invalid link response"))}
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeInstall(mut env: JNIEnv, class: JClass, application: JObject, files: JString) -> jboolean {
let result=(|| -> Result<()> {
if BINDING.get().is_some() { return Ok(()); }
if !java(env.is_instance_of(&application,"android/app/Application"))? { return Err(error("android_context", "Application context required")); }
// Install the process Application/classloader before publishing BINDING or starting workers.
tls::initialize(&mut env, &application)?;
let vm=java(env.get_java_vm())?;
#[cfg(feature="webrtc")]
if !libwebrtc::android::initialize_android_context(&vm,&application) { return Err(error("android_webrtc", "Matching prefixed WebRTC JNI jar/context initialization failed")); }
#[cfg(feature="webrtc")]
{
let capture_application = java(env.new_local_ref(&application))?;
super::mobile_capture::install(&mut env, capture_application).map_err(|e|error("android_capture",e.message))?;
}
let files: String=java(env.get_string(&files))?.into();
let files = private_container::normalize_files_dir(std::path::Path::new(&files))?;
// Old immutable PendingIntents must not alias a new process's first call.
let mut nonce=[0u8;8];getrandom::fill(&mut nonce).map_err(|_|error("android_nonce","Unable to create process action identities"))?;
NEXT.store((u64::from_le_bytes(nonce)&0x3fff_ffff_ffff_ffff)|1,Ordering::Release);
let binding=Binding { vm, application:java(env.new_global_ref(application))?, class:java(env.new_global_ref(class))?, files };
BINDING.set(binding).map_err(|_|error("android_context","Concurrent Application initialization"))?;
let (vm,application)=application_context()?;
if !unsafe { cpal::android_context::set_process_android_context(vm,application) } { return Err(error("android_context","CPAL process context conflict")); }
Ok(())
})();
match result {
Ok(()) => 1,
Err(error) => {
// Preserve the original JVM exception (including missing helper classes), otherwise
// surface the native initialization failure instead of the bridge's generic boolean error.
if !env.exception_check().unwrap_or(true) {
let _ = env.throw_new("java/lang/IllegalStateException", format!("{}: {}", error.code, error.message));
}
0
}
}
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeEvent(_env:JNIEnv,_class:JClass,generation:jlong,event:jint,value:jboolean) {
let value=value!=0; let generation=generation as u64;
let event=match event {
0 if generation!=0 && UI.load(Ordering::Acquire)==generation=>PlatformEvent::Visibility{ui_generation:generation,visible:value},
8 if generation!=0&&UI.load(Ordering::Acquire)==generation=>PlatformEvent::Focus{ui_generation:generation,focused:value},
1=>{destroy_ui(generation);return;}, 2=>PlatformEvent::AudioInterruption{began:value,should_resume:!value},
7 if generation!=0&&UI.load(Ordering::Acquire)==generation=>{
let runtime=RUNTIME.lock().expect("Android runtime").clone();
if let Some(runtime)=runtime{crate::runtime_attachment::request_shutdown_for_ui(&runtime,generation);}
return;
},
3=>PlatformEvent::AudioRouteChanged,4=>PlatformEvent::NetworkChanged,5=>PlatformEvent::ScreenLocked(value),6=>PlatformEvent::MemoryPressure,_=>return,
}; lifecycle::emit(event);
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativePermission(_env:JNIEnv,_class:JClass,id:jlong,permission:jint,granted:jboolean) {
let permission=match permission {0=>Permission::Microphone,1=>Permission::Camera,2=>Permission::Notifications,_=>return};
lifecycle::emit(PlatformEvent::PermissionChanged{permission,granted:granted!=0});
if id!=0 {complete(id as u64,Ok(Response::Permission(granted!=0)));}
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativePick(mut env:JNIEnv,_class:JClass,id:jlong,grant:JObject,message:JString) {
let result=if !message.is_null() {Err(error("document_picker",java(env.get_string(&message)).map(String::from).unwrap_or_else(|_|"Document picker failed".into())))} else if grant.is_null() {Ok(Response::Selection(None))} else {documents::selection(&mut env,grant).map(|value|Response::Selection(Some(value)))};
complete(id as u64,result);
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeText(mut env:JNIEnv,_class:JClass,id:jlong,value:JString,message:JString) {
let result=if !message.is_null() {Err(error("android_os_error",java(env.get_string(&message)).map(String::from).unwrap_or_else(|_|"Android operation failed".into())))} else {java(env.get_string(&value)).map(String::from).and_then(|s|if s.len()<=1024*1024 {Ok(Response::Text(s))}else{Err(error("clipboard_size","Clipboard text exceeds 1 MiB"))})}; complete(id as u64,result);
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceValid(_env:JNIEnv,_class:JClass,token:jlong)->jboolean {VOICE.lock().expect("Android voice").as_ref().is_some_and(|v|v.token==token as u64) as u8}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceStarted(_env:JNIEnv,_class:JClass,token:jlong,microphone:jboolean){
let active={let mut slot=VOICE.lock().expect("Android voice");if let Some(voice)=slot.as_mut().filter(|voice|voice.token==token as u64){
if voice.audio.start(microphone!=0){voice.microphone=microphone!=0;true}else{false}
}else{false}};
if active{log_voice_authorization(token as u64,VoiceRoutePhase::Authorization,VoiceRouteReason::Completed);complete(token as u64,Ok(Response::Voice));}
else{complete(token as u64,Err(error("audio_activation_revoked","Android focus or microphone consent changed before startup was acknowledged")));}
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceStopped(_env:JNIEnv,_class:JClass,token:jlong)->jboolean{end_voice(token as u64) as u8}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceEvent(_env:JNIEnv,_class:JClass,token:jlong,event:jint,value:jboolean){
match event{
2=>voice_audio_changed(token as u64,Some(value==0),true),
3=>voice_audio_changed(token as u64,None,true),
// Fence before explicit playback requests or after an observed OS route
// change; only the acknowledged/observed continuation may recover PCM.
8=>{
let owner={let mut slot=VOICE.lock().expect("Android voice");slot.as_mut().filter(|voice|voice.token==token as u64).map(|voice|{
let pending=voice.capture_change.take();
if pending.is_some(){voice.microphone=false;voice.capture_revision=0;voice.audio.revoke_capture();}
let authorized=voice.audio.retains_capture();voice.failed_playback_revision=None;voice.audio.begin_route();
(voice._runtime.clone(),voice.key.clone(),authorized,pending)
})};
if let Some((runtime,key,authorized,pending))=owner{
runtime.fence_android_audio_route(&key,authorized);
log_voice_authorization(token as u64,VoiceRoutePhase::Fence,VoiceRouteReason::Pending);
if let Some(id)=pending{complete(id,Err(error("call_capture_revoked","Microphone transition was superseded by a route change")));}
}
},
7=>{end_voice_with_shutdown(token as u64,true);},_=>{}
}
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceCaptureValid(_env:JNIEnv,_class:JClass,token:jlong,id:jlong)->jboolean{
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|voice.token==token as u64&&voice.capture_revision==id as u64&&voice.capture_change==Some(id as u64)) as u8
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceCaptureCurrent(_env:JNIEnv,_class:JClass,token:jlong,id:jlong)->jboolean{
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|voice.token==token as u64&&voice.capture_revision==id as u64) as u8
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoicePlaybackValid(_env:JNIEnv,_class:JClass,token:jlong,id:jlong)->jboolean{
(VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|voice.token==token as u64)&&REQUESTS.lock().expect("Android requests").contains_key(&(id as u64))) as u8
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoicePlaybackFinished(_env:JNIEnv,_class:JClass,token:jlong,_id:jlong,accepted:jboolean){
// Success returns ownership to the settings caller. Failure/cancellation
// finalizes and chooses the sole recovery revision under one authorization lock.
let changed={let mut slot=VOICE.lock().expect("Android voice");slot.as_mut().filter(|voice|voice.token==token as u64).and_then(|voice|{
let (revision,recover)=voice.audio.finish_manual_route(accepted!=0);
voice.failed_playback_revision=recover.then_some(revision);
recover.then(||(voice.key.clone(),revision,voice.audio.restart_output()))
})};
if let Some((key,revision,restart_output))=changed{lifecycle::emit(PlatformEvent::AndroidCallAudio{key,token:token as u64,revision,restart_output});}
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceCaptureChanged(_env:JNIEnv,_class:JClass,token:jlong,id:jlong,enabled:jboolean)->jboolean{
let active={let mut slot=VOICE.lock().expect("Android voice");if let Some(voice)=slot.as_mut().filter(|voice|voice.token==token as u64&&voice.capture_revision==id as u64&&voice.capture_change==Some(id as u64)){if !voice.audio.change_capture(enabled!=0){false}else{voice.microphone=enabled!=0;voice.capture_change=None;true}}else{false}};
log_voice_authorization(token as u64,VoiceRoutePhase::Authorization,if active{VoiceRouteReason::Completed}else{VoiceRouteReason::AudioRevisionChanged});
if active{complete(id as u64,Ok(Response::Voice));}active as u8
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceCaptureRevoked(_env:JNIEnv,_class:JClass,token:jlong){voice_audio_changed(token as u64,None,false);}
fn action(token:u64)->Option<Action>{VOICE.lock().expect("Android voice").as_ref().filter(|v|v.token==token).map(|v|Action{key:v.key.clone(),stream:None}).or_else(||ACTIONS.lock().expect("Android actions").get(&token).cloned())}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeNotificationValid(_env:JNIEnv,_class:JClass,token:jlong)->jboolean {action(token as u64).is_some() as u8}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeAction(mut env:JNIEnv,_class:JClass,token:jlong,name:JString){
let Some(action)=action(token as u64) else{return};let Ok(name)=env.get_string(&name)else{return};let name:String=name.into();
if let Some(stream_id)=action.stream {if matches!(name.as_str(),"pip-play"|"pip-pause"){lifecycle::emit(PlatformEvent::PictureInPicture{key:action.key,stream_id,active:true,playing:name=="pip-play"});}return;}
let event=match name.as_str(){"show"=>NotificationAction::Show,"mute"=>NotificationAction::Mute,"disconnect"=>NotificationAction::Disconnect,_=>return};lifecycle::emit(PlatformEvent::Notification{key:action.key,action:event});
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeInsets(_env:JNIEnv,_class:JClass,generation:jlong,top:jfloat,right:jfloat,bottom:jfloat,left:jfloat,keyboard:jfloat){if UI.load(Ordering::Acquire)==generation as u64 && [top,right,bottom,left,keyboard].iter().all(|v|v.is_finite()&&*v>=0.0){lifecycle::emit(PlatformEvent::Insets{ui_generation:generation as u64,value:Insets{top,right,bottom,left,keyboard}});}}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeAccessibility(_env:JNIEnv,_class:JClass,generation:jlong,scale:jfloat,reduced:jboolean,contrast:jboolean,reader:jboolean){if generation>0&&UI.load(Ordering::Acquire)==generation as u64&&scale.is_finite()&&scale>0.0{SCREEN_READER.store(reader!=0,Ordering::Release);lifecycle::emit(PlatformEvent::Accessibility{ui_generation:generation as u64,text_scale:scale,reduce_motion:reduced!=0,high_contrast:contrast!=0,screen_reader:reader!=0});}}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativePip(_env:JNIEnv,_class:JClass,token:jlong,active:jboolean,playing:jboolean){if let Some(Action{key,stream:Some(stream_id)})=action(token as u64){lifecycle::emit(PlatformEvent::PictureInPicture{key,stream_id,active:active!=0,playing:playing!=0});}}
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeHarnessEnabled(_env:JNIEnv,_class:JClass)->jboolean{cfg!(feature="test-harness") as u8}
+140 -11
View File
@@ -1,15 +1,23 @@
//! Android call authorization; focus/route changes never restore microphone consent.
//! Android call authorization; route replacement retains consent, interruptions revoke it.
#[derive(Default)]
pub(super) struct CallAudioState {
revision: u64,
focused: bool,
capture: bool,
restart_output: bool,
route_pending: bool,
}
impl CallAudioState {
pub fn start(&mut self, capture: bool) { self.focused = true; self.capture = capture; }
pub fn revision(&self) -> u64 { self.revision }
pub fn start(&mut self, capture: bool) -> bool {
// A delayed startup ACK cannot overwrite any intervening focus/privacy
// event, even a loss followed by gain. Only a fresh user action may retry.
if self.revision != 0 { return false; }
self.focused = true; self.capture = capture; self.route_pending = false;
true
}
pub fn change_capture(&mut self, enabled: bool) -> bool {
if enabled && !self.focused { return false; }
if enabled && (!self.focused || self.route_pending) { return false; }
self.capture = enabled;
self.revision = self.revision.checked_add(1).expect("Android audio revision exhausted");
true
@@ -24,22 +32,72 @@ impl CallAudioState {
self.revision = self.revision.checked_add(1).expect("Android audio revision exhausted");
self.revision
}
pub fn route_changed(&mut self) -> u64 {
pub fn begin_route(&mut self) -> u64 {
self.route_pending = true;
self.restart_output = true;
self.revoke_capture()
self.revision = self.revision.checked_add(1).expect("Android audio revision exhausted");
self.revision
}
pub fn route_changed(&mut self) -> u64 {
self.route_pending = false;
self.restart_output = true;
// A replacement endpoint is not a new microphone activation. Focus loss,
// permission denial and explicit mute still call revoke_capture instead.
self.revision = self.revision.checked_add(1).expect("Android audio revision exhausted");
self.revision
}
/// The result is the sole continuation owner: success belongs to the settings
/// caller; failure publishes recovery with this already-finalized revision.
pub fn finish_manual_route(&mut self,accepted:bool)->(u64,bool) {
(self.route_changed(),!accepted)
}
pub fn restart_output(&self) -> bool { self.restart_output }
pub fn acknowledge_output(&mut self, revision: u64) {
if self.is_current(revision) { self.restart_output = false; }
pub fn acknowledge_output(&mut self, revision: u64, active: bool) {
// A focused call whose output has not started still owes recovery. Muting
// capture or receiving an early route callback is not a playback ack.
if self.is_current(revision) && (!self.focused || active) { self.restart_output = false; }
}
pub fn allows(&self, microphone: bool) -> bool { self.focused && (!microphone || self.capture) }
pub fn retains_capture(&self) -> bool { self.focused && self.capture }
pub fn allows(&self, microphone: bool) -> bool { !self.route_pending && self.focused && (!microphone || self.capture) }
pub fn is_current(&self, revision: u64) -> bool { self.revision == revision }
}
/// Control-thread log budget; callback storms cannot flood retained diagnostics.
#[derive(Default)]
pub(super) struct RouteLogBudget {
window: Option<std::time::Instant>,
emitted: u8,
suppressed: u64,
}
impl RouteLogBudget {
pub fn take(&mut self, now: std::time::Instant) -> Option<u64> {
if self.window.is_none_or(|window| now.saturating_duration_since(window) >= std::time::Duration::from_secs(10)) {
self.window = Some(now);
self.emitted = 0;
}
if self.emitted >= 16 {
self.suppressed = self.suppressed.saturating_add(1);
return None;
}
self.emitted += 1;
Some(std::mem::take(&mut self.suppressed))
}
}
#[cfg(test)]
mod tests {
use super::CallAudioState;
#[test]
fn route_logs_are_bounded_and_report_suppression_in_next_window() {
let mut budget = super::RouteLogBudget::default();
let now = std::time::Instant::now();
for _ in 0..16 { assert_eq!(budget.take(now), Some(0)); }
assert_eq!(budget.take(now), None);
assert_eq!(budget.take(now + std::time::Duration::from_secs(9)), None);
assert_eq!(budget.take(now + std::time::Duration::from_secs(10)), Some(2));
assert_eq!(budget.take(now + std::time::Duration::from_secs(10)), Some(0));
}
#[test]
fn focus_gain_restores_only_receive_authorization() {
let mut state = CallAudioState::default();
assert!(!state.allows(false));
@@ -57,7 +115,7 @@ mod tests {
assert!(!state.is_current(gained), "queued recovery must not mute a newer explicit activation");
}
#[test]
fn route_or_permission_revocation_keeps_receive_only() {
fn permission_revocation_keeps_receive_only() {
let mut state = CallAudioState::default();
state.start(true);
let route = state.revoke_capture();
@@ -77,11 +135,82 @@ mod tests {
let permission = state.revoke_capture();
assert!(!state.is_current(route));
assert!(state.restart_output());
state.acknowledge_output(route);
state.acknowledge_output(route, true);
assert!(state.restart_output());
state.acknowledge_output(permission);
state.acknowledge_output(permission, true);
assert!(!state.restart_output());
assert!(state.allows(false));
assert!(!state.allows(true));
}
#[test]
fn focused_output_recovery_is_not_acknowledged_before_device_start() {
let mut state = CallAudioState::default();
state.start(false);
let route = state.route_changed();
state.acknowledge_output(route, false);
assert!(state.restart_output(), "foreground authorization alone is not a device acknowledgment");
let capture = state.revoke_capture();
state.acknowledge_output(route, true);
assert!(state.restart_output(), "stale completion cannot satisfy a newer recovery");
state.acknowledge_output(capture, true);
assert!(!state.restart_output());
assert!(!state.allows(true), "receive recovery must not restore capture consent");
let lost = state.interrupt(false);
state.acknowledge_output(lost, false);
assert!(!state.restart_output(), "a focus loss is acknowledged by stopping output");
}
#[test]
fn acknowledged_route_reversal_preserves_only_completed_consent() {
let mut state=CallAudioState::default();state.start(true);
let plugging=state.begin_route();
assert!(state.retains_capture());assert!(!state.allows(true));assert!(!state.allows(false));
assert!(!state.change_capture(true),"a pending route is not an activation acknowledgement");
let plugged=state.route_changed();assert!(!state.is_current(plugging));assert!(state.allows(true));
let unplugging=state.begin_route();assert!(!state.is_current(plugged));assert!(!state.allows(true));
let unplugged=state.route_changed();assert!(!state.is_current(unplugging));assert!(state.is_current(unplugged));assert!(state.allows(true));
}
#[test]
fn newer_privacy_or_focus_loss_wins_pending_route() {
for focus_loss in [false,true]{
let mut state=CallAudioState::default();state.start(true);let pending=state.begin_route();
if focus_loss{state.interrupt(false);}else{state.revoke_capture();}
state.route_changed();assert!(!state.is_current(pending));assert!(!state.retains_capture());assert!(!state.allows(true));
}
let mut state=CallAudioState::default();state.start(false);state.begin_route();state.route_changed();assert!(!state.allows(true));
}
#[tokio::test(flavor="current_thread")]
async fn delayed_startup_ack_cannot_overwrite_interruption_or_revocation() {
for interruption in [0,1,2] {
let state=std::sync::Arc::new(std::sync::Mutex::new(CallAudioState::default()));
let (ack,received)=tokio::sync::oneshot::channel();
let startup=tokio::spawn({let state=state.clone();async move {
received.await.unwrap();state.lock().unwrap().start(true)
}});
tokio::task::yield_now().await;
if interruption==2{state.lock().unwrap().revoke_capture();}
else{state.lock().unwrap().interrupt(false);}
if interruption==1 {state.lock().unwrap().interrupt(true);}
ack.send(()).unwrap();
assert!(!startup.await.unwrap());
let state=state.lock().unwrap();
assert!(!state.allows(true));assert_eq!(state.allows(false),interruption==1);
}
}
#[tokio::test(flavor="current_thread")]
async fn failed_manual_ack_publishes_only_final_revision_and_keeps_consent() {
let state=std::sync::Arc::new(std::sync::Mutex::new(CallAudioState::default()));
assert!(state.lock().unwrap().start(true));
let pending=state.lock().unwrap().begin_route();
let (event,received)=tokio::sync::oneshot::channel();
let recovery=tokio::spawn({let state=state.clone();async move {
let revision=received.await.unwrap();
let state=state.lock().unwrap();
assert!(state.is_current(revision));assert!(state.allows(false));assert!(state.allows(true));
}});
tokio::task::yield_now().await;
let (final_revision,recover)=state.lock().unwrap().finish_manual_route(false);
assert!(recover);
assert_ne!(pending,final_revision);
event.send(final_revision).unwrap();recovery.await.unwrap();
}
}
@@ -0,0 +1,51 @@
//! Resolve aliases only in Android's OS-provided private container, before adding profile paths.
use std::{fs, io, path::{Path, PathBuf}};
/// This must only receive Application.getFilesDir(), never a selected/import path or a profile root.
/// Android may expose the private container through a system-managed symlink. Resolve that trusted
/// prefix once; profile-v1, staging directories and every imported descendant retain no-follow checks.
pub(super) fn normalize_files_dir(files: &Path) -> io::Result<PathBuf> {
if !files.is_absolute() {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Android filesDir must be absolute"));
}
let files = fs::canonicalize(files)?;
if !fs::metadata(&files)?.is_dir() {
return Err(io::Error::new(io::ErrorKind::NotADirectory, "Android filesDir must be a directory"));
}
Ok(files)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_relative_missing_and_non_directory_containers() {
assert_eq!(normalize_files_dir(Path::new("relative")).unwrap_err().kind(), io::ErrorKind::InvalidInput);
let fixture = tempfile::tempdir().unwrap();
assert_eq!(normalize_files_dir(&fixture.path().join("missing")).unwrap_err().kind(), io::ErrorKind::NotFound);
let file = fixture.path().join("file");
fs::write(&file, b"").unwrap();
assert_eq!(normalize_files_dir(&file).unwrap_err().kind(), io::ErrorKind::NotADirectory);
}
#[cfg(unix)]
#[test]
fn resolves_os_container_alias_without_resolving_profile_descendants() {
use std::os::unix::fs::symlink;
let fixture = tempfile::tempdir().unwrap();
let real = fixture.path().join("real");
fs::create_dir_all(real.join("files")).unwrap();
let alias = fixture.path().join("os-alias");
symlink(&real, &alias).unwrap();
let outside = fixture.path().join("outside");
fs::create_dir(&outside).unwrap();
symlink(&outside, real.join("files/profile-v1")).unwrap();
let files = normalize_files_dir(&alias.join("files")).unwrap();
assert_eq!(crate::services::profile_import::initialize_native_root(&files.join("profile-v1")).unwrap_err().code, "profile_symlink");
assert_eq!(files, fs::canonicalize(real.join("files")).unwrap());
assert!(fs::symlink_metadata(files.join("profile-v1")).unwrap().file_type().is_symlink());
assert_eq!(fs::read_dir(outside).unwrap().count(), 0);
}
}
@@ -0,0 +1,145 @@
//! Select Android's process service owner before creating an Activity-bound Slint backend.
use std::sync::Arc;
use crate::{AppConfig, AppError, AppRuntime};
/// The caller clones the process lease and releases its mutex before entering here.
/// A terminal owner's immutable snapshot may still look connected; never use it as lifecycle truth.
pub(crate) fn runtime_for_attachment(previous: Option<Arc<AppRuntime>>, config: impl FnOnce() -> Result<AppConfig, AppError>) -> Result<Arc<AppRuntime>, AppError> {
if let Some(runtime) = previous {
if runtime.accepts_ui_attachment() { return Ok(runtime); }
// Join even when asynchronous callbacks still retain this Arc. This releases the original
// profile/core/audio workers before the new owner opens the same persistent profile.
if let Err(error) = runtime.join_shutdown() { eprintln!("Android retired runtime: {error}"); }
}
AppRuntime::start(config()?)
}
/// Revalidate against the captured owner after reading the process slot: a stale Activity must not
/// shut down a replacement whose generation was published between the JNI callback's checks.
pub(crate) fn request_shutdown_for_ui(runtime: &AppRuntime, generation: u64) -> bool {
if !runtime.is_ui_current(generation) { return false; }
runtime.request_shutdown();
true
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
use crate::{app::{connections::ConnectionState, runtime::model::{BootstrapState, Snapshot}}, ui::shell::{FieldValue, Operation, ShellAction, Target, Values}};
async fn snapshot_when(runtime: &AppRuntime, predicate: impl Fn(&Snapshot) -> bool) -> Arc<Snapshot> {
let mut snapshots = runtime.subscribe();
tokio::time::timeout(Duration::from_secs(20), async {
loop {
let snapshot = snapshots.borrow_and_update().clone();
if predicate(&snapshot) { return snapshot; }
snapshots.changed().await.expect("real runtime snapshot publisher stopped");
}
}).await.expect("real runtime did not publish its expected state")
}
async fn fixture() -> (tempfile::TempDir, AppConfig, Arc<AppRuntime>) {
let directory = tempfile::tempdir().unwrap();
let root = directory.path().join("native");
crate::services::profile_import::initialize_native_root(&root).unwrap();
let config = AppConfig::isolated(root);
let runtime = AppRuntime::start(config.clone()).unwrap();
snapshot_when(&runtime, |snapshot| snapshot.bootstrap == BootstrapState::Username).await;
runtime.dispatch_shell(ShellAction::Submit {
editor_id: "attachment-profile".into(),
target: Target::application(),
operation: Operation::CreateProfile,
values: Values::from([
("nickname".into(), FieldValue::Text("Attachment test".into())),
("theme".into(), FieldValue::Choice("light".into())),
]),
confirmation: String::new(),
}).unwrap();
snapshot_when(&runtime, |snapshot| snapshot.bootstrap == BootstrapState::Ready && snapshot.settings.loaded).await;
(directory, config, runtime)
}
async fn stop(runtime: &AppRuntime) {
tokio::time::timeout(Duration::from_secs(20), runtime.shutdown()).await.unwrap().unwrap();
}
async fn attach(previous: Arc<AppRuntime>, config: AppConfig) -> Arc<AppRuntime> {
tokio::time::timeout(Duration::from_secs(20), tokio::task::spawn_blocking(move || runtime_for_attachment(Some(previous), || Ok(config))))
.await.expect("retired worker did not join").unwrap().unwrap()
}
fn assert_disconnected(snapshot: &Snapshot) {
assert_eq!(snapshot.connections.connections.len(), 1);
assert!(snapshot.connections.connections.iter().all(|connection| connection.state == ConnectionState::Disconnected && connection.server.is_none()));
assert!(snapshot.connections.capture.is_none());
assert!(snapshot.voice.is_none());
assert!(!snapshot.audio_input_active && !snapshot.audio_output_active);
assert!(snapshot.tree.is_empty());
}
#[tokio::test(flavor="current_thread")]
async fn android_attachment_reuses_live_actor_across_home_and_activity_recreation() {
let (_directory, _config, runtime) = fixture().await;
let old_generation = runtime.next_ui_generation();
runtime.platform_event(crate::platform::lifecycle::PlatformEvent::Visibility { ui_generation: old_generation, visible: false });
runtime.release_ui(old_generation);
assert!(runtime.accepts_ui_attachment());
let reused = runtime_for_attachment(Some(runtime.clone()), || panic!("live Activity recreation must not rebuild runtime configuration")).unwrap();
assert!(runtime.worker.lock().unwrap().is_some(), "nonterminal UI loss must not join the live worker");
let new_generation = reused.next_ui_generation();
assert_ne!(old_generation, new_generation);
runtime.release_ui(old_generation);
assert!(reused.is_ui_current(new_generation));
assert!(!request_shutdown_for_ui(&reused, old_generation));
assert!(reused.accepts_ui_attachment());
stop(&reused).await;
}
#[tokio::test(flavor="current_thread")]
async fn android_attachment_joins_terminal_actor_with_retained_arc_before_same_profile_restart() {
let (_directory, config, runtime) = fixture().await;
let uid = runtime.services.lock().unwrap().upgrade().unwrap().profile().unwrap().identities.list().unwrap().default_id;
let old_generation = runtime.next_ui_generation();
assert!(request_shutdown_for_ui(&runtime, old_generation));
assert!(!runtime.accepts_ui_attachment(), "shutdown is terminal before its worker finishes");
// The old Arc deliberately remains alive, just like a delayed OS/async callback.
let fresh = attach(runtime.clone(), config.clone()).await;
assert!(!Arc::ptr_eq(&runtime, &fresh));
assert!(runtime.worker.lock().unwrap().is_none(), "the old worker must be joined, not just cancelled");
assert!(runtime.finished.borrow().is_some());
let snapshot = snapshot_when(&fresh, |snapshot| snapshot.bootstrap == BootstrapState::Ready && snapshot.settings.loaded).await;
assert_disconnected(&snapshot);
assert_eq!(snapshot.root.as_ref(), config.profile_dir.as_ref());
assert_eq!(snapshot.settings.prefs["theme"], "light");
let generation = fresh.next_ui_generation();
assert!(!request_shutdown_for_ui(&fresh, old_generation));
runtime.release_ui(old_generation);
assert!(fresh.is_ui_current(generation));
assert!(fresh.accepts_ui_attachment());
stop(&fresh).await;
let saved = crate::services::profile::ProfileServices::open(config.profile_dir.as_ref().unwrap()).unwrap();
assert_eq!(saved.identities.list().unwrap().default_id, uid);
assert_eq!(saved.identities.list().unwrap().identities.len(), 1);
}
#[tokio::test(flavor="current_thread")]
async fn android_attachment_restarts_worker_that_finished_without_shutdown_request() {
let (_directory, config, runtime) = fixture().await;
stop(&runtime).await;
let mut failing = config.clone();
failing.build_version = "invalid-version";
let failed = AppRuntime::start(failing).unwrap();
let error = tokio::time::timeout(Duration::from_secs(20), failed.finished_result()).await.unwrap().unwrap_err();
assert_eq!(error.code, "services_initialization_failed");
assert!(!*failed.cancel.borrow(), "this must exercise worker completion, not a fabricated shutdown flag");
assert_eq!(failed.snapshot().bootstrap, BootstrapState::Failed);
assert!(!failed.accepts_ui_attachment());
let fresh = attach(failed.clone(), config).await;
assert!(!Arc::ptr_eq(&failed, &fresh));
assert!(failed.worker.lock().unwrap().is_none());
let snapshot = snapshot_when(&fresh, |snapshot| snapshot.bootstrap == BootstrapState::Ready && snapshot.settings.loaded).await;
assert_disconnected(&snapshot);
stop(&fresh).await;
}
}
+47
View File
@@ -0,0 +1,47 @@
//! JNI-version boundary for the process-owned Android platform trust verifier.
use jni::{JNIEnv, objects::{JObject, JValue}};
use jni_verifier::{EnvUnowned, Outcome};
use super::{error, java};
use crate::services::Result;
pub(super) fn initialize(env: &mut JNIEnv<'_>, application: &JObject<'_>) -> Result<()> {
// Use the same Application classloader the verifier retains, not FindClass on a
// native worker (whose default loader cannot see application dependencies).
let loader = env.call_method(application, "getClassLoader", "()Ljava/lang/ClassLoader;", &[])
.and_then(|value| value.l())
.map_err(|cause| error("android_tls", format!("Android TLS Application classloader unavailable: {cause}")))?;
if loader.is_null() {
return Err(error("android_tls", "Android TLS Application classloader is null"));
}
for class in ["org.rustls.platformverifier.CertificateVerifier", "org.rustls.platformverifier.VerificationResult", "org.rustls.platformverifier.StatusCode"] {
let name = java(env.new_string(class))?;
// Initialize as well as load, so absent Kotlin runtime/linkage fails during install.
let loaded = env.call_static_method("java/lang/Class", "forName", "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;", &[JValue::Object(name.as_ref()), JValue::Bool(1), JValue::Object(&loader)])
.and_then(|value| value.l())
.map_err(|cause| error("android_tls", format!("Android TLS helper {class} is unavailable; package org.rustls:rustls-platform-verifier:0.2.0 and retain its JNI classes: {cause}")))?;
if loaded.is_null() {
return Err(error("android_tls", format!("Android TLS helper classloader returned null for {class}")));
}
}
// JNI 0.21 remains the app/WebRTC API. Borrow its current-thread environment
// only inside this call; JNI 0.22 never receives a transmuted Rust wrapper.
// Give 0.22 its own local reference so there are no competing owning wrappers.
let context = java(env.new_local_ref(application))?.into_raw();
// SAFETY: nativeInstall supplied a valid current-thread JNI environment. The
// adapter cannot escape this call or detach the JVM-owned native stack frame.
let mut verifier_env = unsafe { EnvUnowned::from_raw(env.get_raw().cast()) };
let outcome = verifier_env.with_env(|env| {
// SAFETY: context is the transferred local above, belongs to this thread/
// native frame, and has no remaining JNI 0.21 owner. The verifier retains
// its own global Application/classloader references, never an Activity.
let context = unsafe { jni_verifier::objects::JObject::from_raw(env, context.cast()) };
rustls_platform_verifier::android::init_with_env(env, context)
}).into_outcome();
match outcome {
Outcome::Ok(()) => Ok(()),
Outcome::Err(cause) => Err(error("android_tls", format!("Android platform TLS verifier initialization failed: {cause}"))),
Outcome::Panic(_) => Err(error("android_tls", "Android platform TLS verifier initialization panicked")),
}
}
+1 -1
View File
@@ -56,7 +56,7 @@ impl ksni::Tray for Item {
fn title(&self)->String{"TeamsPeach".into()}
fn icon_pixmap(&self)->Vec<ksni::Icon>{let mut argb=self.icon.rgba.clone();for pixel in argb.chunks_exact_mut(4){pixel.rotate_right(1);}vec![ksni::Icon{width:self.icon.width as i32,height:self.icon.height as i32,data:argb}]}
fn activate(&mut self,_:i32,_:i32){(self.callback)(false)}
fn menu(&self)->Vec<ksni::MenuItem<Self>>{vec![ksni::menu::StandardItem{label:self.show.clone(),activate:Box::new(|s|(s.callback)(false)),..Default::default()}.into(),ksni::menu::StandardItem{label:self.quit.clone(),activate:Box::new(|s|(s.callback)(true)),..Default::default()}.into()]}
fn menu(&self)->Vec<ksni::MenuItem<Self>>{vec![ksni::menu::StandardItem{label:self.show.clone(),activate:Box::new(|s: &mut Self|(s.callback)(false)),..Default::default()}.into(),ksni::menu::StandardItem{label:self.quit.clone(),activate:Box::new(|s: &mut Self|(s.callback)(true)),..Default::default()}.into()]}
fn watcher_offline(&self,_:ksni::OfflineReason)->bool{(self.callback)(false);false}
}
pub struct Tray(ksni::blocking::Handle<Item>);
+3 -3
View File
@@ -30,7 +30,7 @@ impl ConnectedServices {
let routed = Arc::new(move |event: ConnectionEvent| {
let packet = match &event {
ConnectionEvent::Control {key,value} if value["event"] == "file_transfer" => Some(FileEvent::Control(key.clone(),value.clone())),
ConnectionEvent::Failure {key:Some(key),..} => Some(FileEvent::Closed(key.clone())),
ConnectionEvent::Closed {key} | ConnectionEvent::Failure {key:Some(key),terminal:true,..} => Some(FileEvent::Closed(key.clone())),
_ => None,
};
if packet.is_some_and(|packet| sender.try_send(packet).is_err()) {
@@ -54,12 +54,12 @@ impl ConnectedServices {
event = incoming.recv() => match event {
Some(FileEvent::Control(key,value)) => {
if let Err(error) = files.lock().await.on_event(owner.as_ref(), &key, &value).await {
observer.on_event(ConnectionEvent::Failure { key: Some(key), error: crate::app::connections::ConnectionError::Worker(error.to_string()) });
observer.on_event(ConnectionEvent::Failure { key: Some(key), error: crate::app::connections::ConnectionError::Worker(error.to_string()), terminal: false });
}
},
Some(FileEvent::Closed(key)) => {
if let Err(error) = files.lock().await.on_closed(owner.as_ref(), &key).await {
observer.on_event(ConnectionEvent::Failure { key: Some(key), error: crate::app::connections::ConnectionError::Worker(error.to_string()) });
observer.on_event(ConnectionEvent::Failure { key: Some(key), error: crate::app::connections::ConnectionError::Worker(error.to_string()), terminal: false });
}
},
None => break,
+1 -1
View File
@@ -17,7 +17,7 @@ fn connection(id: &str, generation: u64, away: bool) -> ConnectionSnapshot {
}
fn connections() -> ConnectionsSnapshot {
ConnectionsSnapshot { connections: vec![connection("c1", 7, true), connection("c2", 8, false)],
viewed_id: Some("c2".into()), input_id: None, capture: None }
viewed_id: Some("c2".into()), input_id: None, capture: None, ..Default::default() }
}
fn prefs() -> Value {
json!({"contacts":[{"uid":"Friend=","alias":"","name":"Remembered"},
+1 -1
View File
@@ -38,7 +38,7 @@ impl ConnectionSink for ServiceEvents {
_ => {},
}
self.icon_transfers.on_control(key, value.clone());
} else if let ConnectionEvent::Failure { key: Some(key), .. } = &event {
} else if let ConnectionEvent::Closed { key } | ConnectionEvent::Failure { key: Some(key), terminal: true, .. } = &event {
self.close(key);
}
self.consumer.on_event(event);
+17 -1
View File
@@ -13,6 +13,17 @@ fn choice(v:&Value,options:&[&str])->bool {v.as_str().is_some_and(|s|options.con
fn exact(v:&Value,keys:&[&str])->bool {v.as_object().is_some_and(|o|o.len()==keys.len()&&keys.iter().all(|k|o.contains_key(*k)))}
pub fn input_default()->Value {json!({"agc":true,"denoise":true,"denoiseLevel":1,"typing":false,"vad":true,"vadMode":"automatic","vadLevel":-30,"vadSensitivity":"normal"})}
pub fn output_default()->Value {json!({"aec":false,"agc":true,"comfortNoise":false,"comfortNoiseLevel":-60,"echoReduction":0})}
/// Android-only presentation palette. Desktop keeps its stock/package theme semantics.
/// A null androidPalette delegates to the existing stock/package theme; saving a palette object installs an override.
pub fn android_palette_default()->Value {android_palette_preset("ts6").unwrap()}
pub fn android_palette_preset(name:&str)->Option<Value> {let (accent,bg,surface,fg)=match name{"ts6"=>("#1588FA","#222A3C","#2B3346","#F4F6FB"),"graphite"=>("#D2B989","#242626","#323535","#F4F1E9"),"light"=>("#24694F","#F1F4EF","#E2E9DF","#25362D"),_=>return None};Some(json!({"version":1,"accent":accent,"background":bg,"surface":surface,"foreground":fg}))}
pub fn palette_rgb(value:&str)->Option<[u8;3]> {if value.len()!=7||!value.starts_with('#')||!value.as_bytes()[1..].iter().all(u8::is_ascii_hexdigit){return None}Some([u8::from_str_radix(&value[1..3],16).ok()?,u8::from_str_radix(&value[3..5],16).ok()?,u8::from_str_radix(&value[5..7],16).ok()?])}
pub fn palette_mix(a:[u8;3],b:[u8;3],amount:f64)->[u8;3] {std::array::from_fn(|i|(f64::from(a[i])*(1.-amount)+f64::from(b[i])*amount).round() as u8)}
pub fn palette_luminance(rgb:[u8;3])->f64 {let v=rgb.map(|v|{let v=f64::from(v)/255.;if v<=0.04045{v/12.92}else{((v+0.055)/1.055).powf(2.4)}});v[0]*0.2126+v[1]*0.7152+v[2]*0.0722}
pub fn palette_contrast(a:[u8;3],b:[u8;3])->f64 {let a=palette_luminance(a);let b=palette_luminance(b);(a.max(b)+0.05)/(a.min(b)+0.05)}
pub fn palette_surfaces(bg:[u8;3],surface:[u8;3])->[[u8;3];4] {let end=if palette_luminance(bg)>0.5{[255;3]}else{[0;3]};[bg,surface,palette_mix(bg,end,0.17),palette_mix(bg,end,0.4)]}
pub fn android_palette_contrast(v:&Value)->Option<f64> {let bg=palette_rgb(v["background"].as_str()?)?;let surface=palette_rgb(v["surface"].as_str()?)?;let fg=palette_rgb(v["foreground"].as_str()?)?;Some(palette_surfaces(bg,surface).iter().map(|bg|palette_contrast(fg,*bg)).fold(f64::INFINITY,f64::min))}
pub fn valid_android_palette(v:&Value)->bool {exact(v,&["version","accent","background","surface","foreground"])&&v["version"]==1&&["accent","background","surface","foreground"].iter().all(|key|v[key].as_str().and_then(palette_rgb).is_some())&&android_palette_contrast(v).is_some_and(|ratio|ratio>=4.5)}
pub fn defaults()->Value {
let entries = [
("lastAddress", json!("")),
@@ -38,6 +49,7 @@ pub fn defaults()->Value {
("collapsedChannels", json!([])),
("savedServersCollapsed", json!(false)),
("theme", json!("dark")),
("androidPalette", Value::Null),
("displaySize", json!("medium")),
("treeStyle", json!("detailed")),
("chatStyle", json!("detailed")),
@@ -96,6 +108,7 @@ fn collapsed(v:&Value)->bool {let Some(a)=v.as_array() else{return false};let mu
fn style(v:&Value)->bool {if v.is_null(){return true}let Some(s)=v.as_str() else{return false};if bookmarks::units(s)>200||bookmarks::control(s){return false}let Some((id,name))=s.split_once("//") else{return false};let parts:Vec<_>=id.split('.').collect();id.len()<=64&&parts.len()>=3&&parts.iter().enumerate().all(|(i,p)|p.len()>=(if i==0{2}else{3})&&p.bytes().all(|c|c.is_ascii_lowercase()))&&(4..=30).contains(&name.chars().count())}
pub fn validate_value(key:&str,v:&Value)->bool {match key {
"lastAddress"=>string(v,255,false)&&v.as_str().is_some_and(|s|!s.chars().any(|c|c<='\u{1f}')),
"androidPalette"=>v.is_null()||valid_android_palette(v),
"inputDsp"=>dsp(v,true),"outputDsp"=>dsp(v,false),
"pttReleaseDelay"=>exact(v,&["active","ms"])&&v["active"].is_boolean()&&[100.0,300.0,500.0].iter().any(|n|v["ms"].as_f64()==Some(*n)),
"outputLevelDb"|"notificationLevelDb"=>v.as_f64().is_some_and(|n|n.is_finite()&&(-200.0..=10.0).contains(&n)&&(n*2.0).fract()==0.0),
@@ -154,7 +167,10 @@ impl Prefs {
let path=path.as_ref().to_path_buf();let parent=path.parent().filter(|p|!p.as_os_str().is_empty()).ok_or_else(||err("invalid_path","Preference path needs a parent directory"))?;
secure_fs::ensure_private_dir(parent)?;
let lock=path.with_extension("json.lock");let owner=OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&lock)?;
owner.try_lock().map_err(|_|err("profile_busy","Preferences are already owned by another service"))?;
teamspeach_core::file_lock::try_lock(&owner, false).map_err(|error| match error {
std::fs::TryLockError::WouldBlock => err("profile_busy", "Preferences are already owned by another service"),
std::fs::TryLockError::Error(error) => error.into(),
})?;
#[cfg(windows)] secure_fs::win::set_owner_only(&lock)?;
#[cfg(unix)] {use std::os::unix::fs::PermissionsExt;fs::set_permissions(&lock,fs::Permissions::from_mode(0o600))?;}
require_recovered_bookmark_transaction(&path)?;
+22
View File
@@ -105,3 +105,25 @@ fn repeated_mapping_reconfirms_selected_native_input_without_replacing_dsp(){
p.map_legacy_device(DeviceKind::Input,"legacy-a","native-a").unwrap();assert!(!p.capture_allowed(true));assert_eq!(p.get()["inputDeviceId"],"unresolved");assert_eq!(p.get()["inputDsp"],dsp);
assert!(p.map_legacy_device(DeviceKind::Input,"legacy-a","unresolved").is_err());assert!(p.confirm_new_device(DeviceKind::Input,"unresolved").is_err());assert!(!p.capture_allowed(true));
}
#[test]
fn android_palette_schema_rejects_unsafe_colors_and_contrast_without_rewriting_load() {
for name in ["ts6","graphite","light"]{let palette=android_palette_preset(name).unwrap();assert!(valid_android_palette(&palette),"{name}");}
for invalid in ["#fff","#11223344","112233","#GG0000","#12é45","transparent",""] {
let mut palette=android_palette_default();palette["accent"]=json!(invalid);assert!(!validate_value("androidPalette",&palette),"{invalid}");
}
let mut palette=android_palette_default();palette["foreground"]=palette["surface"].clone();assert!(!valid_android_palette(&palette));
palette=android_palette_default();palette["version"]=json!(2);assert!(!valid_android_palette(&palette));
palette=android_palette_default();palette["unknown"]=json!(true);assert!(!valid_android_palette(&palette));
let f=Fixture::new();let raw=json!({"androidPalette":palette});let bytes=serde_json::to_vec(&raw).unwrap();fs::write(f.path(),&bytes).unwrap();let p=Prefs::open(f.path()).unwrap();assert_eq!(p.get()["androidPalette"],Value::Null);assert_eq!(fs::read(f.path()).unwrap(),bytes);
}
#[test]
fn android_palette_save_restore_reset_and_failed_persistence_are_atomic() {
let f=Fixture::new();let mut prefs=Prefs::open(f.path()).unwrap();let graphite=android_palette_preset("graphite").unwrap();
prefs.set(json!({"androidPalette":graphite})).unwrap();drop(prefs);
let mut prefs=Prefs::open(f.path()).unwrap();assert_eq!(prefs.get()["androidPalette"],graphite);
let mut invalid=graphite.clone();invalid["foreground"]=json!("#242626");assert!(prefs.set(json!({"androidPalette":invalid})).is_err());assert_eq!(prefs.get()["androidPalette"],graphite);
let bytes=fs::read(f.path()).unwrap();fs::create_dir(f.0.join("prefs.json.tmp")).unwrap();assert!(prefs.set(json!({"androidPalette":android_palette_default()})).is_err());assert_eq!(prefs.get()["androidPalette"],graphite);assert_eq!(fs::read(f.path()).unwrap(),bytes);
fs::remove_dir(f.0.join("prefs.json.tmp")).unwrap();prefs.set(json!({"androidPalette":android_palette_default()})).unwrap();drop(prefs);assert_eq!(Prefs::open(f.path()).unwrap().get()["androidPalette"],android_palette_default());
}
+4 -1
View File
@@ -27,7 +27,10 @@ impl ProfileServices {
}
let path = root.join("native-owner.lock");
let owner = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&path)?;
owner.try_lock().map_err(|_| ServiceError::new("profile_busy", "The native profile is already open"))?;
teamspeach_core::file_lock::try_lock(&owner, false).map_err(|error| match error {
std::fs::TryLockError::WouldBlock => ServiceError::new("profile_busy", "The native profile is already open"),
std::fs::TryLockError::Error(error) => error.into(),
})?;
#[cfg(windows)] teamspeach_core::secure_fs::win::set_owner_only(&path)?;
#[cfg(unix)] {
use std::os::unix::fs::PermissionsExt;
+26 -7
View File
@@ -204,7 +204,7 @@ pub fn save_migration(root: &Path, state: &MigrationState) -> Result<()> {
/// Caller persists the OS secret first. Failure leaves the re-entry requirement in place.
pub fn clear_required_password(root: &Path, bookmark_id: &str, purpose: &str, address: &str) -> Result<()> {
let file = OpenOptions::new().write(true).create(true).truncate(false).open(root.join("migration.lock"))?;
file.lock()?;
teamspeach_core::file_lock::lock(&file, false)?;
if let Some(mut state) = load_migration(root)? {
let before = state.required_passwords.len();
state.required_passwords.retain(|m| !(m.bookmark_id == bookmark_id && m.purpose == purpose && m.address == address.trim()));
@@ -420,7 +420,10 @@ impl ConfinedSource {
let relative = Path::new(name);
if self.metadata(relative)?.is_none() { continue; }
let file = self.open_file(relative)?;
file.try_lock().map_err(|_| err("profile_occupied", "Close the legacy client before importing its profile"))?;
teamspeach_core::file_lock::try_lock(&file, false).map_err(|error| match error {
std::fs::TryLockError::WouldBlock => err("profile_occupied", "Close the legacy client before importing its profile"),
std::fs::TryLockError::Error(error) => error.into(),
})?;
locks.push(file);
}
Ok(locks)
@@ -428,6 +431,13 @@ impl ConfinedSource {
}
#[cfg(unix)]
fn open_unix_absolute(path: &Path) -> Result<File> {
// Android grants search, not directory-read access, above the app sandbox.
#[cfg(target_os = "android")]
let root = {
use std::os::unix::fs::OpenOptionsExt;
OpenOptions::new().read(true).custom_flags(libc::O_PATH | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC).open("/")?
};
#[cfg(not(target_os = "android"))]
let root = File::open("/")?;
open_unix_relative(&root, path.strip_prefix("/").map_err(|_| err("invalid_profile_path", "Invalid absolute path"))?)
}
@@ -435,17 +445,26 @@ fn open_unix_absolute(path: &Path) -> Result<File> {
fn open_unix_relative(root: &File, path: &Path) -> Result<File> {
use std::{ffi::CString, os::{fd::{AsRawFd, FromRawFd}, unix::ffi::OsStrExt}};
unsafe extern "C" { fn openat(fd: i32, path: *const std::ffi::c_char, flags: i32, ...) -> i32; }
// Android arm64 assigns O_NOFOLLOW a different bit than desktop Linux.
#[cfg(target_os = "android")]
use libc::{O_NOFOLLOW as NOFOLLOW, O_CLOEXEC as CLOEXEC, O_NONBLOCK as NONBLOCK};
#[cfg(any(target_os = "macos", target_os = "ios"))] const NOFOLLOW: i32 = 0x100;
#[cfg(not(any(target_os = "macos", target_os = "ios")))] const NOFOLLOW: i32 = 0x20000;
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))] const NOFOLLOW: i32 = 0x20000;
#[cfg(any(target_os = "macos", target_os = "ios"))] const CLOEXEC: i32 = 0x1000000;
#[cfg(not(any(target_os = "macos", target_os = "ios")))] const CLOEXEC: i32 = 0x80000;
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))] const CLOEXEC: i32 = 0x80000;
#[cfg(any(target_os = "macos", target_os = "ios"))] const NONBLOCK: i32 = 4;
#[cfg(not(any(target_os = "macos", target_os = "ios")))] const NONBLOCK: i32 = 0x800;
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))] const NONBLOCK: i32 = 0x800;
let mut file = root.try_clone()?;
for component in path.components() {
let mut components = path.components().peekable();
while let Some(component) = components.next() {
let Component::Normal(name) = component else { return Err(err("invalid_profile_path", "Invalid path component")) };
let name = CString::new(name.as_bytes()).map_err(|_| err("invalid_profile_path", "Invalid path byte"))?;
let fd = unsafe { openat(file.as_raw_fd(), name.as_ptr(), NOFOLLOW | CLOEXEC | NONBLOCK) }; // nonblocking prevents FIFO hangs; regular files unaffected
let flags = NOFOLLOW | CLOEXEC | NONBLOCK;
// Pin ancestors without requesting read/list permission. The final entry
// still needs normal read access; O_DIRECTORY + NOFOLLOW reject links.
#[cfg(target_os = "android")]
let flags = if components.peek().is_some() { flags | libc::O_PATH | libc::O_DIRECTORY } else { flags };
let fd = unsafe { openat(file.as_raw_fd(), name.as_ptr(), flags) }; // nonblocking prevents FIFO hangs; regular files unaffected
if fd < 0 { return Err(std::io::Error::last_os_error().into()); }
file = unsafe { File::from_raw_fd(fd) };
deny_link(&file.metadata()?)?;
@@ -189,6 +189,42 @@ fn symbolic_links_are_not_followed_even_inside_allowed_trees() {
assert!(import_profile(&source, &fixture.destination()).is_err()); assert!(!fixture.destination().exists());
}
#[cfg(unix)]
#[test]
fn descriptor_relative_opens_reject_directory_and_file_links() {
let fixture = Fixture::new();
let directory = fixture.0.join("real"); fs::create_dir(&directory).unwrap();
fs::write(directory.join("file"), b"sentinel").unwrap();
std::os::unix::fs::symlink(&directory, fixture.0.join("directory-link")).unwrap();
std::os::unix::fs::symlink(directory.join("file"), fixture.0.join("file-link")).unwrap();
let root = File::open(&fixture.0).unwrap();
assert!(open_unix_relative(&root, Path::new("real/file")).unwrap().metadata().unwrap().is_file());
// Exercise openat directly: ConfinedSource's earlier lstat must not mask wrong flag bits.
assert!(open_unix_relative(&root, Path::new("directory-link/file")).is_err());
assert!(open_unix_relative(&root, Path::new("file-link")).is_err());
}
#[cfg(target_os = "android")]
#[test]
fn onboarding_traverses_search_only_ancestors_without_following_links() {
use std::os::unix::fs::{PermissionsExt, symlink};
let fixture = Fixture::new();
let ancestor = fixture.0.join("search-only");
let container = ancestor.join("files");
fs::create_dir_all(&container).unwrap();
let destination = container.join("profile-v1");
symlink(&container, ancestor.join("linked-files")).unwrap();
fs::set_permissions(&ancestor, fs::Permissions::from_mode(0o100)).unwrap();
let created = initialize_native_root(&destination);
let inspected = inspect_native_root(&destination);
let escaped = open_unix_absolute(&ancestor.join("linked-files/profile-v1"));
// Restore directory access before assertions so Fixture always cleans up.
fs::set_permissions(&ancestor, fs::Permissions::from_mode(0o700)).unwrap();
created.unwrap();
assert_eq!(inspected.unwrap(), ProfileRootState::Native);
assert!(escaped.is_err());
}
#[test]
fn legacy_discovery_returns_all_real_candidates_without_opening_keys() {
let fixture = Fixture::new();
+1 -1
View File
@@ -126,7 +126,7 @@ pub(super) fn recover(root: &Path) -> Result<()> {
#[cfg(unix)]
{ use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); }
let owner = options.open(&lock_path).map_err(|_| recovery_error())?;
owner.try_lock().map_err(|_| recovery_error())?;
teamspeach_core::file_lock::try_lock(&owner, false).map_err(|_| recovery_error())?;
#[cfg(windows)]
secure_fs::win::set_owner_only(&lock_path).map_err(|_| recovery_error())?;
let bytes = read_bounded(&root.join(JOURNAL), JOURNAL_LIMIT)?.ok_or_else(recovery_error)?;
+44 -8
View File
@@ -2,11 +2,17 @@
use std::{cell::RefCell,collections::HashMap,rc::Rc,sync::Arc,time::Duration};
use slint::ComponentHandle;
use crate::{AppRuntime,AppWindow,AppError,Theme,ShellBridge,app::runtime::{events::UiEffect,model::Snapshot},ui::{shell,settings,chat}};
struct DispatchFeedback{form:Option<(String,shell::Target)>,result:crate::services::Result<()>}
fn dispatch_shell(runtime:&AppRuntime,action:shell::ShellAction)->DispatchFeedback{
let form=match &action{shell::ShellAction::Submit{editor_id,target,..}=>Some((editor_id.clone(),target.clone())),_=>None};
DispatchFeedback{form,result:runtime.dispatch_shell(action)}
}
struct Bindings {
shell:shell::ShellBinding,settings:settings::Binding,chat:chat::ChatBinding,
revision:u64,destination:shell::Destination,
fonts:super::theme::Fonts,
panes:Option<(i32,i32)>,
feedback:std::sync::mpsc::Receiver<DispatchFeedback>,dispatch_error:Option<String>,
#[cfg(feature="webrtc")]
frames:HashMap<String,(Arc<crate::media::stream::frames::VideoFrames>,crate::media::stream::frames::PresentedFrame)>,
}
@@ -32,10 +38,13 @@ pub fn bind(runtime:Arc<AppRuntime>,generation:u64)->Result<UiAttachment,AppErro
let generation=if generation==0{runtime.next_ui_generation()}else{generation};
if !runtime.is_ui_current(generation){return Err(crate::services::ServiceError::new("ui_destroyed","The UI attachment was replaced").into())}
let window=AppWindow::new()?;
let weak=Arc::downgrade(&runtime);let shell=shell::bind(&window,Arc::new(move|action|{if let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)){if let Err(error)=runtime.dispatch_shell(action){report(&runtime,error);}}}));
let weak=Arc::downgrade(&runtime);let settings=settings::bind(&window,Arc::new(move|action|{if let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)){if let Err(error)=runtime.dispatch_settings(action){report(&runtime,error);}}}));
let weak=Arc::downgrade(&runtime);let chat=chat::bind(&window,Arc::new(move|action|{if let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)){if let Err(error)=runtime.dispatch_chat(action){report(&runtime,error);}}}));
let bindings=Rc::new(RefCell::new(Bindings{shell,settings,chat,revision:u64::MAX,destination:shell::Destination::Servers,fonts:Default::default(),panes:None,#[cfg(feature="webrtc")]frames:HashMap::new()}));
// Dispatch can fail before RuntimeServices exists (or after it stops). Return captured failures
// through the attachment, deferred until the callback releases the shell editor borrow.
let(feedback_tx,feedback)=std::sync::mpsc::channel();
let weak=Arc::downgrade(&runtime);let sender=feedback_tx.clone();let shell=shell::bind(&window,Arc::new(move|action|{if let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)){let _=sender.send(dispatch_shell(&runtime,action));}}));
let weak=Arc::downgrade(&runtime);let sender=feedback_tx.clone();let settings=settings::bind(&window,Arc::new(move|action|{if let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)){let _=sender.send(DispatchFeedback{form:None,result:runtime.dispatch_settings(action)});}}));
let weak=Arc::downgrade(&runtime);let chat=chat::bind(&window,Arc::new(move|action|{if let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)){let _=feedback_tx.send(DispatchFeedback{form:None,result:runtime.dispatch_chat(action)});}}));
let bindings=Rc::new(RefCell::new(Bindings{shell,settings,chat,feedback,dispatch_error:None,revision:u64::MAX,destination:shell::Destination::Servers,fonts:Default::default(),panes:None,#[cfg(feature="webrtc")]frames:HashMap::new()}));
{let runtime=runtime.clone();window.window().on_close_requested(move||{runtime.release_held();runtime.platform_event(crate::platform::lifecycle::PlatformEvent::Quit);slint::CloseRequestResponse::KeepWindowShown});}
window.show()?;
let startup_error=Rc::new(RefCell::new(None));
@@ -68,10 +77,15 @@ pub fn bind(runtime:Arc<AppRuntime>,generation:u64)->Result<UiAttachment,AppErro
let timer=slint::Timer::default();let tick=update.clone();timer.start(slint::TimerMode::Repeated,Duration::from_millis(16),move||tick());update();
Ok(UiAttachment{window,runtime,generation,_bindings:bindings,_timer:timer,startup_error,#[cfg(not(any(target_os="android",target_os="ios")))]_desktop:desktop,#[cfg(not(any(target_os="android",target_os="ios")))]desktop_task,#[cfg(target_os="ios")]_apple:apple,#[cfg(target_os="android")]_accessibility:accessibility})
}
fn report(runtime:&AppRuntime,error:crate::services::ServiceError){if let Some(ctx)=runtime.services.lock().expect("runtime services").upgrade(){let _=ctx.events.try_send(crate::app::runtime::events::ServiceEvent::Effect(UiEffect::Error(error)));}}
fn update(ui:&AppWindow,runtime:&AppRuntime,bindings:&mut Bindings){
let mut feedback_changed=false;
while let Ok(feedback)=bindings.feedback.try_recv(){
feedback_changed=true;
bindings.dispatch_error=feedback.result.as_ref().err().map(|error|error.message.clone());
if let(Some((id,target)),Err(error))=(feedback.form,feedback.result){bindings.shell.complete(ui,&id,&target,Err(error.message));}
}
let snapshot=runtime.snapshot();let changed=bindings.revision!=snapshot.revision;
if changed{if let Err(error)=bindings.fonts.synchronize(&snapshot){report(runtime,error);}apply_theme(ui,&snapshot);let panes=(snapshot.settings.prefs["sidebarWidth"].as_i64().filter(|n|*n>0).unwrap_or(270) as i32,snapshot.settings.prefs["serverPaneWidth"].as_i64().filter(|n|*n>0).unwrap_or(500) as i32);if bindings.panes!=Some(panes){ui.global::<ShellBridge>().set_sidebar_width(panes.0 as f32);ui.global::<ShellBridge>().set_server_width(panes.1 as f32);bindings.panes=Some(panes);}bindings.revision=snapshot.revision;}
if changed{if let Err(error)=bindings.fonts.synchronize(&snapshot){bindings.dispatch_error=Some(error.message);}apply_theme(ui,&snapshot);let panes=(snapshot.settings.prefs["sidebarWidth"].as_i64().filter(|n|*n>0).unwrap_or(270) as i32,snapshot.settings.prefs["serverPaneWidth"].as_i64().filter(|n|*n>0).unwrap_or(500) as i32);if bindings.panes!=Some(panes){ui.global::<ShellBridge>().set_sidebar_width(panes.0 as f32);ui.global::<ShellBridge>().set_server_width(panes.1 as f32);bindings.panes=Some(panes);}bindings.revision=snapshot.revision;}
let mut new_frames=Vec::new();
#[cfg(feature="webrtc")]
{
@@ -80,7 +94,7 @@ fn update(ui:&AppWindow,runtime:&AppRuntime,bindings:&mut Bindings){
for(id,source)in &snapshot.frames{match source.take_image(width,height){Ok(Some(frame))=>{new_frames.push((id.clone(),frame.image.clone()));if let Some((old_source,old))=bindings.frames.insert(id.clone(),(source.clone(),frame)){let crate::media::stream::frames::PresentedFrame{image,pixels,..}=old;drop(image);old_source.recycle(pixels);}},Ok(None)=>{},Err(error)=>ui.global::<ShellBridge>().set_error(error.message.into())}}
}
if changed {
let mut shell=shell::ShellPresentation{catalog:snapshot.catalog,tabs:snapshot.tabs.clone(),tree:snapshot.tree.clone(),bookmarks:snapshot.bookmarks.clone(),contacts:snapshot.contacts.clone(),detail:snapshot.detail.clone(),actions:snapshot.actions.clone(),streams:vec![],voice:snapshot.voice.clone(),profile_form:snapshot.profile_form.clone(),dialog:snapshot.dialog.clone(),status:snapshot.status.clone(),error:snapshot.error.clone(),loading:snapshot.loading};
let mut shell=shell::ShellPresentation{catalog:snapshot.catalog,tabs:snapshot.tabs.clone(),tree:snapshot.tree.clone(),bookmarks:snapshot.bookmarks.clone(),contacts:snapshot.contacts.clone(),room:snapshot.room.clone(),detail:snapshot.detail.clone(),actions:snapshot.actions.clone(),streams:vec![],voice:snapshot.voice.clone(),profile_form:snapshot.profile_form.clone(),dialog:snapshot.dialog.clone(),status:snapshot.status.clone(),error:snapshot.error.clone(),loading:snapshot.loading};
for stream in &snapshot.streams{
#[cfg(feature="webrtc")]let image=bindings.frames.get(&stream.id).map(|(_,frame)|frame.image.clone());
#[cfg(not(feature="webrtc"))]let image:Option<slint::Image>=None;
@@ -90,6 +104,8 @@ fn update(ui:&AppWindow,runtime:&AppRuntime,bindings:&mut Bindings){
if snapshot.destination!=bindings.destination{bindings.shell.navigate(ui,snapshot.destination);bindings.destination=snapshot.destination;}
if changed{settings::present(ui,&bindings.settings,settings::build(&snapshot.settings,&snapshot.settings_view,&snapshot.catalog));chat::present(ui,&bindings.chat,snapshot.chat.clone());}
}
if changed&&snapshot.bootstrap==crate::app::runtime::model::BootstrapState::Failed{bindings.dispatch_error=None;bindings.shell.failed(ui);}
if feedback_changed||bindings.dispatch_error.is_some(){ui.global::<ShellBridge>().set_error(bindings.dispatch_error.as_deref().unwrap_or(&snapshot.error).into());}
if !changed&&!new_frames.is_empty(){bindings.shell.update_frames(ui,&new_frames);}
{let shell=ui.global::<ShellBridge>();let theme=ui.global::<Theme>();let compact=ui.window().size().width as f32/ui.window().scale_factor()-theme.get_safe_left()-theme.get_safe_right()<600.;let visible=(shell.get_destination()==1||shell.get_destination()==0&&shell.get_stage()==1&&(!compact||shell.get_depth()>0))&&!ui.global::<crate::MarkupBridge>().get_visible();chat::set_visibility(&bindings.chat,visible);}
for effect in runtime.drain_effects(){match effect{
@@ -108,12 +124,17 @@ fn update(ui:&AppWindow,runtime:&AppRuntime,bindings:&mut Bindings){
#[cfg(any(target_os="android",target_os="ios"))]{let size=ui.window().size();let scale=f64::from(ui.window().scale_factor());let _=runtime.commands.try_send(crate::app::runtime::RuntimeCommand::Pip{target,rect:[0.,0.,f64::from(size.width)/scale,f64::from(size.height)/scale]});}
},
UiEffect::StreamClose{target}=>{let _=bindings.shell.stream_effect(ui,&target,false,true);},
UiEffect::Quit=>{let _=ui.hide();let _=slint::quit_event_loop();},
UiEffect::Quit=>{
#[cfg(target_os="android")]
if let Err(error)=crate::platform::android::finish_activity(runtime.ui_generation()){ui.global::<ShellBridge>().set_error(error.message.into());}
let _=ui.hide();let _=slint::quit_event_loop();
},
UiEffect::Theme(theme)=>{let mut current=(*snapshot).clone();current.theme=Some(theme);apply_theme(ui,&current);},
#[cfg(target_os="android")]
UiEffect::Platform(crate::platform::lifecycle::PlatformEvent::Focus{focused:false,..}|crate::platform::lifecycle::PlatformEvent::Visibility{visible:false,..}|crate::platform::lifecycle::PlatformEvent::AndroidCallAudio{..})=>ui.invoke_focus_lost(),
_=>{}
}}
if (changed||feedback_changed)&&snapshot.bootstrap==crate::app::runtime::model::BootstrapState::Failed{ui.global::<ShellBridge>().set_error(snapshot.error.clone().into());}
}
fn apply_theme(ui:&AppWindow,snapshot:&Snapshot){
use crate::services::themes::TokenValue;
@@ -129,4 +150,19 @@ fn apply_theme(ui:&AppWindow,snapshot:&Snapshot){
if let Some(TokenValue::FontFamily(fonts))=resolved.values.get("--tsv-font-family"){if let Some(font)=fonts.first(){let family=snapshot.theme_fonts.iter().find(|prepared|prepared.family==*font).map_or(font.as_str(),|prepared|prepared.alias.as_str());theme.set_font_family(family.into());}}
let base=match resolved.values.get("--tsv-font-size"){Some(TokenValue::LengthPx(size))=>*size,_=>15.};let size=match prefs["displaySize"].as_str(){Some("small")=>13./15.,Some("large")=>17./15.,_=>1.};theme.set_font_size(base*snapshot.text_scale*size);
}
#[cfg(target_os="android")]
{
if snapshot.theme.is_none() {
let color=|dark_rgb:[u8;3],light_rgb:[u8;3]|{let rgb=if dark{dark_rgb}else{light_rgb};slint::Color::from_rgb_u8(rgb[0],rgb[1],rgb[2])};
theme.set_bg(color([43,51,70],[245,245,245]));theme.set_shaded(color([34,42,60],[235,235,235]));
theme.set_header(color([28,37,57],[226,229,235]));theme.set_contrast(color([12,19,38],[201,217,229]));theme.set_deviant(color([30,37,56],[211,213,222]));
theme.set_tint(color([21,136,250],[34,101,143]));theme.set_fg(color([255;3],[26;3]));
}
super::theme::apply_android_palette(&theme,super::theme::android_palette(snapshot),snapshot.high_contrast);
if snapshot.theme.is_none(){let size=match prefs["displaySize"].as_str(){Some("small")=>13.,Some("large")=>17.,_=>15.};theme.set_font_size(size*snapshot.text_scale);}
}
}
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))]
#[path="application_tests.rs"]
mod tests;
+43
View File
@@ -0,0 +1,43 @@
use super::*;
use crate::{DialogBridge,app::runtime::{RuntimeCommand,model::BootstrapState}};
use slint::{Model,platform::{Platform,WindowAdapter,software_renderer::{MinimalSoftwareWindow,RepaintBufferType}}};
use std::sync::{Mutex,Weak,atomic::{AtomicBool,AtomicU64}};
struct TestPlatform;
impl Platform for TestPlatform{
fn create_window_adapter(&self)->Result<Rc<dyn WindowAdapter>,slint::PlatformError>{
let window=MinimalSoftwareWindow::new(RepaintBufferType::NewBuffer);window.set_size(slint::PhysicalSize::new(360,760));Ok(window)
}
}
#[test]
fn bootstrap_contract_ui_dispatch_rejection_and_terminal_failure_are_visible_without_services(){
slint::platform::set_platform(Box::new(TestPlatform)).unwrap();
let(commands,mut incoming)=tokio::sync::mpsc::channel(1);
assert!(commands.try_send(RuntimeCommand::Detached(0)).is_ok()); // real bounded queue, deliberately full
let(cancel,_cancelled)=tokio::sync::watch::channel(false);
let mut snapshot=Snapshot::default();snapshot.revision=1;snapshot.bootstrap=BootstrapState::Username;snapshot.loading=false;snapshot.ready=true;
snapshot.profile_form=Some(shell::forms::form("onboarding",shell::Operation::CreateProfile,shell::Target::application(),&snapshot.catalog).unwrap());
let(snapshots_tx,snapshots)=tokio::sync::watch::channel(Arc::new(snapshot));
let(_effects_tx,effects)=tokio::sync::mpsc::channel(1);let(_finished_tx,finished)=tokio::sync::watch::channel(None);
let directory=tempfile::tempdir().unwrap();
let runtime=Arc::new(AppRuntime{config:crate::AppConfig::isolated(directory.path().join("native")),commands,cancel,snapshots,effects:Mutex::new(effects),services:Mutex::new(Weak::new()),wake:Mutex::new(None),pending_wake:AtomicBool::new(false),active_ui:AtomicU64::new(0),finished,worker:Mutex::new(None),desktop:Mutex::new(None)});
let attachment=bind(runtime.clone(),0).unwrap();let ui=attachment.window();let dialog=ui.global::<DialogBridge>();
assert!(runtime.services.lock().unwrap().upgrade().is_none());assert!(dialog.get_visible());
dialog.invoke_edit("nickname".into(),"Native User".into());dialog.invoke_submit();assert!(dialog.get_busy());
update(ui,&runtime,&mut attachment._bindings.borrow_mut());
assert!(!dialog.get_busy());assert!(dialog.get_error().contains("queue is full or stopped"));assert!(dialog.get_visible());
let mut unrelated=(*runtime.snapshot()).clone();unrelated.revision+=1;unrelated.status="Unrelated lifecycle update".into();snapshots_tx.send_replace(Arc::new(unrelated));
update(ui,&runtime,&mut attachment._bindings.borrow_mut());
assert!(!dialog.get_busy());assert!(dialog.get_error().contains("queue is full or stopped"));
assert!(dialog.get_fields().iter().any(|field|field.id=="nickname"&&field.value=="Native User"));
incoming.try_recv().unwrap();dialog.invoke_submit();assert!(dialog.get_busy());
update(ui,&runtime,&mut attachment._bindings.borrow_mut());assert!(dialog.get_busy(),"accepted enqueue is not completion");
let mut unrelated=(*runtime.snapshot()).clone();unrelated.revision+=1;snapshots_tx.send_replace(Arc::new(unrelated));
update(ui,&runtime,&mut attachment._bindings.borrow_mut());assert!(dialog.get_busy(),"snapshots cannot acknowledge submission");
// Exercise the revision-gated consumer when the actor cannot deliver a final form effect.
let mut terminal=(*runtime.snapshot()).clone();terminal.revision+=1;terminal.bootstrap=BootstrapState::Failed;terminal.profile_form=None;terminal.dialog=None;terminal.error="Your profile is saved, but application services could not start".into();
snapshots_tx.send_replace(Arc::new(terminal));update(ui,&runtime,&mut attachment._bindings.borrow_mut());
assert!(!dialog.get_busy());assert!(!dialog.get_visible(),"a terminal actor cannot accept another create submission");
assert!(ui.global::<ShellBridge>().get_error().contains("profile is saved"));
}
+12 -5
View File
@@ -151,6 +151,7 @@ pub fn present(ui:&AppWindow,binding:&ChatBinding,presentation:ChatPresentation)
let old_target=state.presentation.conversation.as_ref().map(|c|c.target.clone());let new_target=presentation.conversation.as_ref().map(|c|c.target.clone());
let changed=old_target!=new_target;
if changed {(state.emit)(ChatAction::CancelAssets{generation:state.generation});state.generation=next_render_generation();state.assets.clear();state.requested.clear();state.revealed.clear();state.selection=Selection::default();ui.global::<ChatBridge>().set_selected_text(SharedString::default());ui.global::<ChatBridge>().set_bottom_pinned(true);ui.global::<ChatBridge>().set_log_position(0.);}
if changed && cfg!(target_os="android"){ui.global::<ChatBridge>().set_mobile_overlay(false);}
if changed {state.scenes.clear();state.avatars.clear();}
if language_changed {let bridge=ui.global::<ChatBridge>();bridge.set_language_revision(bridge.get_language_revision().wrapping_add(1));}
if let Some(c)=&presentation.conversation{let key=c.target.draft_key();if !state.editors.contains_key(&key){let mut editor=editor::Editor::new(c.draft.clone());editor.revision=c.draft_revision;state.editors.insert(key,editor);(state.emit)(ChatAction::DraftChanged{target:c.target.clone(),text:c.draft.clone(),revision:c.draft_revision});}}
@@ -258,8 +259,13 @@ impl State {
let empty=PreparedDocument::default();
let mut scene=render::prepared_document(if hide_text{&empty}else{&message.document},&id,render::Options{width:self.width,font_scale:scale,preview:false,revealed:&self.revealed,assets:&metadata,auto_images:self.presentation.auto_download_images,auto_diagrams:self.presentation.auto_diagrams},&mut|text,style|measure(ui,text,style));
for (index,file) in message.document.files.iter().cloned().enumerate(){
let action=format!("{id}/attachment/{index}");let allowed=!file.is_directory&&file.server_uid.as_deref()==Some(target.scope.base.server.as_str());let text=file.name.clone();let style=render::Style{size:14.*scale,underline:allowed,..render::Style::default()};let(width,height)=measure(ui,&text,style);let len=text.len();
scene.rows.push(render::Visual{id:action.clone(),height:height.max(44.)+8.,plain:text.clone(),kind:12,runs:vec![render::Run{x:8.,y:4.,width:width.min(self.width-16.),height:height.max(44.),text,style,action:if allowed{action.clone()}else{String::new()},asset:String::new(),text_range:0..len,concealed:false}],..render::Visual::default()});
let action=format!("{id}/attachment/{index}");let allowed=!file.is_directory&&file.server_uid.as_deref()==Some(target.scope.base.server.as_str());
if cfg!(target_os="android") {
scene.rows.push(render::attachment(&action,&file.name,if allowed{&action}else{""},render::Options{width:self.width,font_scale:scale,preview:false,revealed:&self.revealed,assets:&metadata,auto_images:false,auto_diagrams:false},&mut|text,style|measure(ui,text,style)));
} else {
let text=file.name.clone();let style=render::Style{size:14.*scale,underline:allowed,..render::Style::default()};let(width,height)=measure(ui,&text,style);let len=text.len();
scene.rows.push(render::Visual{id:action.clone(),height:height.max(44.)+8.,plain:text.clone(),kind:12,runs:vec![render::Run{x:8.,y:4.,width:width.min(self.width-16.),height:height.max(44.),text,style,action:if allowed{action.clone()}else{String::new()},asset:String::new(),text_range:0..len,concealed:false}],..render::Visual::default()});
}
if allowed{scene.actions.insert(action,render::Interaction::Link(policy::Link::ServerFile(file)));}
}
self.scenes.insert(cache_key,scene.clone());scene
@@ -281,7 +287,7 @@ impl State {
if self.programmatic{return}let bridge=ui.global::<ChatBridge>();let Some(key)=self.current_key()else{bridge.set_editor_text(SharedString::default());bridge.set_before(model(vec![]));bridge.set_after(model(vec![]));bridge.set_can_send(false);return};
let hybrid=self.presentation.hybrid;let Some(editor)=self.editors.get_mut(&key)else{return};if editor.composing{return}let old_active=editor.active.clone();let(before,after)=editor.hybrid_blocks(hybrid);let active=editor.active.clone();let text=editor.text()[active.clone()].to_owned();let selection=editor.selection().clone();let can_undo=editor.can_undo();let can_redo=editor.can_redo();let draft_revision=editor.revision;let can_send=!editor.text().trim().is_empty()&&editor.text().trim_end().len()<=8192&&!self.pending.contains_key(&key)&&self.presentation.conversation.as_ref().is_some_and(|c|c.can_send);self.completions=editor.completions();self.completion_index=0;
let metadata=self.metadata();let target=self.presentation.conversation.as_ref().map(|c|c.target.clone());let mut automatic=vec![];self.actions.retain(|k,_|!k.starts_with("draft/"));
let mut render_preview=|blocks:Vec<editor::PreviewBlock>|{let mut result=vec![];for block in blocks{let id=format!("draft/{key}/{draft_revision}/{}",block.range.start);let scene=render::prepared_document(&block.document,&id,render::Options{width:self.editor_width,font_scale:14./16.,preview:true,revealed:&self.revealed,assets:&metadata,auto_images:false,auto_diagrams:self.presentation.auto_diagrams},&mut|text,style|measure(ui,text,style));for (id,interaction)in scene.actions{if let Some(target)=&target{self.actions.insert(id,BoundInteraction{target:target.clone(),interaction});}}automatic.extend(scene.automatic);for row in scene.rows{result.push(convert_visual(&row,"",&self.assets,block.range.start as i32,false,true));}}result};
let mut render_preview=|blocks:Vec<editor::PreviewBlock>|{let mut result=vec![];for block in blocks{let id=format!("draft/{key}/{draft_revision}/{}",block.range.start);let scene=render::prepared_document(&block.document,&id,render::Options{width:self.editor_width,font_scale:14./16.*if cfg!(target_os="android"){(ui.global::<Theme>().get_font_size()/15.).max(0.5)}else{1.},preview:true,revealed:&self.revealed,assets:&metadata,auto_images:false,auto_diagrams:self.presentation.auto_diagrams},&mut|text,style|measure(ui,text,style));for (id,interaction)in scene.actions{if let Some(target)=&target{self.actions.insert(id,BoundInteraction{target:target.clone(),interaction});}}automatic.extend(scene.automatic);for row in scene.rows{result.push(convert_visual(&row,"",&self.assets,block.range.start as i32,false,true));}}result};
let before=render_preview(before);let after=render_preview(after);
bridge.set_editor_width(before.iter().chain(after.iter()).map(|row|row.content_width).fold(self.editor_width,f32::max));
self.programmatic=true;bridge.set_before(model(before));bridge.set_after(model(after));bridge.set_can_send(can_send);bridge.set_can_undo(can_undo);bridge.set_can_redo(can_redo);
@@ -292,6 +298,7 @@ impl State {
}
fn publish_completions(&self,ui:&AppWindow){let bridge=ui.global::<ChatBridge>();bridge.set_completions(model(self.completions.iter().map(|c|ChatCompletion{id:c.id.clone().into(),label:if c.emoji{c.label.clone()}else{format!("{} — {}",c.label,tr(&self.presentation.language,&format!("chat.snippet.{}",c.id)))}.into()}).collect()));bridge.set_completion_index(self.completion_index as i32);}
fn command(&mut self,ui:&AppWindow,command:&str)->bool{
if command=="clear-selection"{self.selection=Selection::default();self.publish_selection(ui);return true}
if command=="completion-next"||command=="completion-previous"{if self.completions.is_empty(){return false}self.completion_index=(self.completion_index+if command=="completion-next"{1}else{self.completions.len()-1})%self.completions.len();self.publish_completions(ui);return true}
if command=="dismiss-completion"{self.completions.clear();self.publish_completions(ui);return true}
let Some(editor)=self.editor_mut()else{return false};if editor.composing{return false}let changed=match command{
@@ -308,7 +315,7 @@ impl State {
render::Interaction::Link(policy::Link::ServerFile(file))=>{if !file.is_directory&&file.server_uid.as_deref()==Some(bound.target.scope.base.server.as_str()){(self.emit)(ChatAction::DownloadFile{target:bound.target,file});}return},
render::Interaction::Image(file)=>AssetKind::ServerImage(file),
render::Interaction::Spoiler(key)|render::Interaction::Details(key)=>{if !self.revealed.remove(&key){self.revealed.insert(key);}self.scenes.clear();self.refresh_log(ui);return},
render::Interaction::Footnote(label)=>{let mut offset=0.;for row in &self.log{if row.id==label{ui.global::<ChatBridge>().set_bottom_pinned(false);ui.global::<ChatBridge>().set_log_position(-offset);break}offset+=row.height;if matches!(row.kind,6|7){offset+=ui.global::<Theme>().get_touch_target();}}return},
render::Interaction::Footnote(label)=>{let mut offset=0.;for row in &self.log{if row.id==label{ui.global::<ChatBridge>().set_bottom_pinned(false);ui.global::<ChatBridge>().set_log_position(-offset);break}offset+=row.height;if matches!(row.kind,6|7){offset+=ui.global::<Theme>().get_touch_target();}if cfg!(target_os="android")&&row.runs.iter().any(|run|run.x+run.width+8.>self.width){offset+=24.;}}return},
render::Interaction::Math{source,display}=>{let color=ui.global::<Theme>().get_fg();AssetKind::Math{source:source.into(),display,font_size_px:if display{18.}else{16.},color:[color.red(),color.green(),color.blue(),color.alpha()],width_px:f64::from(self.width)}},
render::Interaction::Diagram{source,retry}=>AssetKind::Diagram{source:source.into(),manual:!automatic,retry},
};
@@ -344,7 +351,7 @@ pub fn preview_with_assets(ui:&AppWindow,source:&str,document:&PreparedDocument,
use std::hash::{Hash,Hasher};let mut hash=std::collections::hash_map::DefaultHasher::new();source.hash(&mut hash);width.to_bits().hash(&mut hash);let theme=ui.global::<Theme>();let color=theme.get_fg();[color.red(),color.green(),color.blue(),color.alpha()].hash(&mut hash);theme.get_font_family().as_str().hash(&mut hash);theme.get_font_size().to_bits().hash(&mut hash);let prefix=format!("help/{}",hash.finish());
let mut assets=HashMap::new();for(id,result)in results{let loaded=result.clone().and_then(load_image);let stored=match loaded{Ok((image,width,height))=>StoredAsset{metadata:render::Asset{width,height,ready:true,error:None},image},Err(error)=>StoredAsset{metadata:render::Asset{width:0.,height:0.,ready:false,error:Some(error)},image:slint::Image::default()}};assets.insert(id.clone(),stored);}
let metadata=assets.iter().map(|(id,a)|(id.clone(),a.metadata.clone())).collect();
let scene=render::prepared_document(document,&prefix,render::Options{width,font_scale:1.,preview:true,revealed:&HashSet::new(),assets:&metadata,auto_images:false,auto_diagrams:false},&mut|text,style|measure(ui,text,style));
let scene=render::prepared_document(document,&prefix,render::Options{width,font_scale:if cfg!(target_os="android"){(theme.get_font_size()/15.).max(0.5)}else{1.},preview:true,revealed:&HashSet::new(),assets:&metadata,auto_images:false,auto_diagrams:false},&mut|text,style|measure(ui,text,style));
let requests=scene.actions.into_iter().filter_map(|(id,interaction)|{let kind=match interaction{
render::Interaction::Math{source,display}=>AssetKind::Math{source:source.into(),display,font_size_px:16.,color:[color.red(),color.green(),color.blue(),color.alpha()],width_px:f64::from(width)},
render::Interaction::Diagram{source,retry}=>AssetKind::Diagram{source:source.into(),manual:true,retry},_=>return None};Some((id,kind))}).collect();
+3 -1
View File
@@ -280,5 +280,7 @@
"native.chat.redo": "Redo",
"native.chat.cut": "Cut",
"native.chat.paste": "Paste",
"native.chat.selectAll": "Select All"
"native.chat.selectAll": "Select All",
"native.chat.conversations": "Conversations",
"native.chat.copySelection": "Copy selected message text"
}
+23 -8
View File
@@ -35,6 +35,16 @@ pub fn prepared_document(doc:&PreparedDocument,id:&str,options:Options<'_>,measu
pub fn document(doc:&crate::services::chat::parse::Document,id:&str,options:Options<'_>,measure:&mut dyn FnMut(&str,Style)->(f32,f32))->Scene{
prepared_document(&PreparedDocument::from_document(doc.clone()),id,options,measure)
}
/// Server-file names are literal text, not markup. Reuse shaping/wrapping while
/// retaining the caller's already validated target-bound download action.
pub fn attachment(id:&str,text:&str,action:&str,options:Options<'_>,measure:&mut dyn FnMut(&str,Style)->(f32,f32))->Visual {
let policies=PreparedDocument::default();
let mut renderer=Renderer{options,scene:Scene::default(),measure,root_id:id.to_owned(),policies:&policies};
let atom=Atom{text:text.to_owned(),style:Style{size:14.,underline:!action.is_empty(),..Style::default()},action:action.to_owned(),asset:String::new(),width:None,height:None,concealed:false};
renderer.flow(id.to_owned(),vec![atom],8.,12,String::new(),Align::Left);
let mut row=renderer.scene.rows.pop().unwrap_or_default();row.height=row.height.max(56.);row
}
struct Renderer<'a,'b>{options:Options<'a>,scene:Scene,measure:&'b mut dyn FnMut(&str,Style)->(f32,f32),root_id:String,policies:&'a PreparedDocument}
impl Renderer<'_,'_>{
fn atom(&self,text:String,style:Style)->Atom{Atom{text,style,action:String::new(),asset:String::new(),width:None,height:None,concealed:false}}
@@ -61,7 +71,7 @@ impl Renderer<'_,'_>{
if let Some(asset)=self.options.assets.get(key){if asset.ready {return Atom{text:source.into(),style,action,asset:key.into(),width:Some(asset.width),height:Some(asset.height),concealed:false}}let text=asset.error.as_ref().map_or_else(||source.to_owned(),|error|format!("{source}\n{error}"));return Atom{action,..self.atom(text,Style{mono:true,..style})}}
Atom{action,..self.atom(source.to_owned(),Style{mono:true,..style})}
}
fn blocks(&mut self,blocks:&[Block],path:&str,indent:f32,style:Style,align:Align){for (i,block) in blocks.iter().enumerate(){let key=format!("{path}/b{i}");match &block.kind{
fn blocks(&mut self,blocks:&[Block],path:&str,indent:f32,style:Style,align:Align){let indent=if cfg!(target_os="android"){indent.min((self.options.width-56.).max(0.))}else{indent};for (i,block) in blocks.iter().enumerate(){let key=format!("{path}/b{i}");match &block.kind{
BlockKind::Paragraph(nodes)=>{if let [Inline::BbAlign{align:a,children}]=nodes.as_slice(){let a_nodes=self.inline(children,&key,style);self.flow(key,a_nodes,indent,0,String::new(),Align::parse(a));}else{let a=self.inline(nodes,&key,style);self.flow(key,a,indent,0,String::new(),align);}},
BlockKind::Heading{level,children}=>{let factor=match level{1=>1.8,2=>1.55,3=>1.3,4=>1.15,_=>1.};let a=self.inline(children,&key,Style{size:style.size*factor,weight:700,..style});self.flow(key,a,indent,1,String::new(),align);},
BlockKind::Hr=>self.scene.rows.push(Visual{id:key,height:12.,kind:2,indent,..Visual::default()}),
@@ -70,7 +80,7 @@ impl Renderer<'_,'_>{
BlockKind::Blockquote{callout,children}=>{if let Some(callout)=callout{let a=vec![self.atom(callout.title.clone(),Style{weight:700,..style})];self.flow(format!("{key}/title"),a,indent,4,callout.kind.clone(),align);}let start=self.scene.rows.len();self.blocks(children,&key,indent+12.,style,align);for row in &mut self.scene.rows[start..]{if matches!(row.kind,0|1){row.kind=4;row.label=callout.as_ref().map_or(String::new(),|c|c.kind.clone());}}},
BlockKind::List(list)=>self.list(list,&key,indent,style),
BlockKind::Table{align:columns,header,rows}=>{
let count=header.len().max(rows.iter().map(Vec::len).max().unwrap_or(0)).max(1);let width=((self.options.width-indent)/count as f32).max(40.);let old_width=self.options.width;
let count=header.len().max(rows.iter().map(Vec::len).max().unwrap_or(0)).max(1);let width=((self.options.width-indent)/count as f32).max(if cfg!(target_os="android"){120.}else{40.});let old_width=self.options.width;
for (row_index,cells) in std::iter::once(header).chain(rows.iter()).enumerate(){let mut joined=Visual{id:format!("{key}/r{row_index}"),kind:8,indent,..Visual::default()};let mut max_height=0f32;
for (column,cell) in cells.iter().enumerate(){self.options.width=width-12.;let atoms=self.inline(cell,&format!("{key}/r{row_index}/c{column}"),Style{weight:if row_index==0{700}else{style.weight},..style});self.flow(format!("{key}/cell"),atoms,0.,8,String::new(),columns.get(column).and_then(|s|s.as_deref()).map_or(Align::Left,Align::parse));let mut visual=self.scene.rows.pop().unwrap_or_default();let offset=joined.plain.len();if column>0{joined.plain.push('\t');}let offset=offset+usize::from(column>0);for run in &mut visual.runs{run.x+=indent+column as f32*width+6.;run.text_range.start+=offset;run.text_range.end+=offset;}joined.plain.push_str(&visual.plain);joined.runs.extend(visual.runs);max_height=max_height.max(visual.height);}
joined.height=max_height+8.;self.scene.rows.push(joined);
@@ -82,11 +92,16 @@ impl Renderer<'_,'_>{
}}}
fn list(&mut self,list:&List,path:&str,indent:f32,style:Style){for(i,item)in list.items.iter().enumerate(){let key=format!("{path}/l{i}");let marker=if let Some(checked)=item.task{if checked{"[x] ".into()}else{"[ ] ".into()}}else if list.ordered{format!("{}. ",u64::from(list.start)+i as u64)}else{"• ".into()};let mut a=vec![self.atom(marker,style)];a.extend(self.inline(&item.children,&key,style));self.flow(key.clone(),a,indent,0,String::new(),Align::Left);if let Some(sub)=&item.sub{self.list(sub,&key,indent+20.,style)}}}
fn flow(&mut self,id:String,atoms:Vec<Atom>,indent:f32,kind:i32,label:String,align:Align){
// Keep deeply nested quotes/lists on screen. Tables retain readable columns
// and use the UI's row-local horizontal viewport rather than widening chat.
let indent=if cfg!(target_os="android"){indent.min((self.options.width-56.).max(0.))}else{indent};
let available=(self.options.width-indent-8.).max(16.);let mut row=Visual{id,kind,indent,label,..Visual::default()};let mut x=0.;let mut y=if kind==1{8.}else{4.};let mut line_height=20.*self.options.font_scale;let mut line_start=0;
for atom in atoms {let style=Style{size:atom.style.size*self.options.font_scale,shift:atom.style.shift*self.options.font_scale,..atom.style};
if !atom.asset.is_empty(){let width=atom.width.unwrap_or(available).min(available).max(16.);let height=atom.height.unwrap_or(50.)*(width/atom.width.unwrap_or(width).max(1.));if x>0.&&x+width>available{align_line(&mut row.runs[line_start..],x,available,align);y+=line_height;x=0.;line_height=20.;line_start=row.runs.len();}let from=row.plain.len();row.plain.push_str(&atom.text);row.runs.push(Run{x:x+indent,y,width,height,text:atom.text,style,action:atom.action,asset:atom.asset,text_range:from..row.plain.len(),concealed:atom.concealed});x+=width;line_height=line_height.max(height);continue}
for token in split_tokens(&atom.text){if token=="\n"{align_line(&mut row.runs[line_start..],x,available,align);row.plain.push('\n');y+=line_height;x=0.;line_height=20.*self.options.font_scale;line_start=row.runs.len();continue}
let(width,height)=(self.measure)(token,style);if width>available {
for atom in atoms {let style=Style{size:atom.style.size*self.options.font_scale,shift:atom.style.shift*self.options.font_scale,..atom.style};let touch=cfg!(target_os="android")&&!atom.action.is_empty();
if !atom.asset.is_empty(){let mut width=atom.width.unwrap_or(available).min(available).max(16.);let mut height=atom.height.unwrap_or(50.)*(width/atom.width.unwrap_or(width).max(1.));if cfg!(target_os="android"){let scale=(available*1.25/height.max(1.)).min(1.);width*=scale;height*=scale;}if touch{width=width.max(48.);height=height.max(48.);}if x>0.&&x+width>available{align_line(&mut row.runs[line_start..],x,available,align);y+=line_height;x=0.;line_height=20.;line_start=row.runs.len();}let from=row.plain.len();row.plain.push_str(&atom.text);row.runs.push(Run{x:x+indent,y,width,height,text:atom.text,style,action:atom.action,asset:atom.asset,text_range:from..row.plain.len(),concealed:atom.concealed});x+=width;line_height=line_height.max(height);continue}
// Keep a link's words together so a 48dp target does not introduce
// artificial spacing between each word or steal adjacent text taps.
for token in split_tokens(&atom.text,touch){if token=="\n"{align_line(&mut row.runs[line_start..],x,available,align);row.plain.push('\n');y+=line_height;x=0.;line_height=20.*self.options.font_scale;line_start=row.runs.len();continue}
let(mut width,mut height)=(self.measure)(token,style);if touch{width=width.max(48.);height=height.max(48.);}if width>available {
// Shape complete native strings. Splitting glyph-by-glyph breaks Arabic shaping,
// ligatures and emoji ZWJ sequences; choose a fitting UTF-8 chunk instead.
let mut remaining=token;
@@ -95,7 +110,7 @@ impl Renderer<'_,'_>{
let boundaries:Vec<_>=remaining.grapheme_indices(true).map(|(i,_)|i).filter(|i|*i>0).chain(std::iter::once(remaining.len())).collect();
let(mut lo,mut hi)=(0,boundaries.len());
while lo<hi{let mid=(lo+hi)/2;let w=(self.measure)(&remaining[..boundaries[mid]],style).0;if w<=available{lo=mid+1}else{hi=mid}}
let end=boundaries[lo.saturating_sub(1)];let chunk=&remaining[..end];let(w,h)=(self.measure)(chunk,style);
let end=boundaries[lo.saturating_sub(1)];let chunk=&remaining[..end];let(mut w,mut h)=(self.measure)(chunk,style);if touch{w=w.max(48.);h=h.max(48.);}
push_run(&mut row,&atom,chunk.into(),style,x+indent,y,w,h);x=w;line_height=line_height.max(h+style.shift.abs());remaining=&remaining[end..];
}continue
}
@@ -107,7 +122,7 @@ impl Renderer<'_,'_>{
}
}
fn push_run(row:&mut Visual,atom:&Atom,text:String,style:Style,x:f32,y:f32,width:f32,height:f32){let start=row.plain.len();row.plain.push_str(&text);row.runs.push(Run{x,y:y+style.shift,width,height,text,style,action:atom.action.clone(),asset:String::new(),text_range:start..row.plain.len(),concealed:atom.concealed});}
fn split_tokens(text:&str)->Vec<&str>{let mut parts=vec![];let mut start=0;let mut whitespace=None;for(i,c)in text.char_indices(){if c=='\n'{if start<i{parts.push(&text[start..i]);}parts.push(&text[i..i+1]);start=i+1;whitespace=None;continue}let ws=c.is_whitespace();if whitespace.is_some_and(|prev|prev!=ws){parts.push(&text[start..i]);start=i;}whitespace=Some(ws);}if start<text.len(){parts.push(&text[start..]);}parts}
fn split_tokens(text:&str,whole_lines:bool)->Vec<&str>{let mut parts=vec![];let mut start=0;let mut whitespace=None;for(i,c)in text.char_indices(){if c=='\n'{if start<i{parts.push(&text[start..i]);}parts.push(&text[i..i+1]);start=i+1;whitespace=None;continue}let ws=c.is_whitespace();if !whole_lines&&whitespace.is_some_and(|prev|prev!=ws){parts.push(&text[start..i]);start=i;}whitespace=Some(ws);}if start<text.len(){parts.push(&text[start..]);}parts}
fn align_line(runs:&mut[Run],used:f32,width:f32,align:Align){let spare=(width-used).max(0.);let offset=match align{Align::Center=>spare/2.,Align::Right=>spare,_=>0.};let gaps=runs.iter().filter(|r|r.text.chars().all(char::is_whitespace)).count();let mut extra=0.;for run in runs{run.x+=offset+extra;if matches!(align,Align::Justify)&&gaps>0&&run.text.chars().all(char::is_whitespace){let step=spare/gaps as f32;run.width+=step;extra+=step;}}}
fn font_size(size:&str,base:f32)->f32{base*match size{"xx-small"=>0.6,"x-small"=>0.75,"small"=>0.9,"large"=>1.2,"x-large"=>1.5,"xx-large"=>2.,"xxx-large"=>3.,_=>1.}}
fn parse_color(value:&str)->Option<[u8;4]>{let mut parser=cssparser::Parser::new(value);let color=cssparser_color::Color::parse(&mut parser).ok()?;parser.expect_exhausted().ok()?;match color{cssparser_color::Color::Rgba(c)=>Some([c.red,c.green,c.blue,(c.alpha*255.).round()as u8]),_=>None}}
+3 -1
View File
@@ -280,5 +280,7 @@
"native.chat.redo": "Повторить",
"native.chat.cut": "Вырезать",
"native.chat.paste": "Вставить",
"native.chat.selectAll": "Выделить всё"
"native.chat.selectAll": "Выделить всё",
"native.chat.conversations": "Разговоры",
"native.chat.copySelection": "Копировать выделенный текст сообщения"
}
+29
View File
@@ -61,3 +61,32 @@ fn selection_paste_and_completion_keep_unrelated_source(){
let mut editor=Editor::new("/bo".into());let completion=editor.completions().remove(0);editor.complete(&completion);assert_eq!(editor.text(),"****");assert_eq!(editor.selection().range(),2..2);
assert!(!super::editor::emoji_search("smile",0..0,80).is_empty());
}
#[cfg(target_os="android")]
#[test]
fn phone_actions_have_non_overlapping_touch_geometry(){
let rendered=scene("before [a short link](https://example.com) after ||hidden||",&HashSet::new(),&HashMap::new());
let actions:Vec<_>=rendered.rows.iter().flat_map(|row|row.runs.iter()).filter(|run|!run.action.is_empty()).collect();
assert!(!actions.is_empty());
for run in &actions{assert!(run.width>=48.&&run.height>=48.);assert!(run.x+run.width<=360.);}
for (i,a) in actions.iter().enumerate(){for b in actions.iter().skip(i+1){assert!(a.x+a.width<=b.x||b.x+b.width<=a.x||a.y+a.height<=b.y||b.y+b.height<=a.y);}}
}
#[cfg(target_os="android")]
#[test]
fn phone_attachment_wraps_literal_unicode_without_losing_its_action(){
let name="報告👩‍💻[not markup]<plain>very-long-file-name".repeat(8);
let row=render::attachment("file",&name,"file/download",render::Options{width:160.,font_scale:1.,preview:false,revealed:&HashSet::new(),assets:&HashMap::new(),auto_images:false,auto_diagrams:false},&mut|text,style|(text.chars().count()as f32*style.size/2.,style.size+4.));
assert_eq!(row.plain,name);assert!(row.runs.len()>1);
for run in row.runs{assert_eq!(run.action,"file/download");assert!(run.width>=48.&&run.height>=48.);assert!(run.x+run.width<=160.);}
}
#[cfg(target_os="android")]
#[test]
fn phone_tall_rendered_media_stays_bounded_and_tables_keep_readable_columns(){
let first=scene("$$\nx^2\n$$",&HashSet::new(),&HashMap::new());let id=first.automatic[0].clone();
let rendered=scene("$$\nx^2\n$$",&HashSet::new(),&HashMap::from([(id,render::Asset{width:80.,height:10000.,ready:true,error:None})]));
for run in rendered.rows.iter().flat_map(|row|&row.runs){assert!(run.width<=360.&&run.height<=450.);}
let table=scene("| first | second | third | fourth |\n| --- | --- | --- | --- |\n| a | b | c | d |",&HashSet::new(),&HashMap::new());
assert!(table.rows.iter().any(|row|row.runs.iter().any(|run|run.x>360.)));
}
+14 -3
View File
@@ -77,7 +77,7 @@ pub fn bind(ui:&AppWindow,emit:Arc<dyn Fn(SettingsAction)+Send+Sync>)->Binding{
Intent::Edit(field)=>{if let Control::Choice{options,..}=&r.control{if let Some((value,_))=options.get(index){if let Some(value)=choice_value(field,value){emit_edit(&emit,&r,value);}}}},_=>{}
}
});}
{let state=state.clone();bridge.on_draft(move |token,text|{if let Some(r)=row(&state,token.as_str()){if matches!(r.control,Control::Text(_)|Control::Number{..}){state.borrow_mut().drafts.insert(r.id,text.to_string());}}});}
{let state=state.clone();let emit=emit.clone();bridge.on_draft(move |token,text|{if let Some(r)=row(&state,token.as_str()){if matches!(r.control,Control::Color(_)){emit_edit(&emit,&r,SettingValue::Text(text.to_string()));}else if matches!(r.control,Control::Text(_)|Control::Number{..}){state.borrow_mut().drafts.insert(r.id,text.to_string());}}});}
{let state=state.clone();let emit=emit.clone();bridge.on_commit(move |token,text|commit(&state,&emit,token.as_str(),text.as_str()));}
{let state=state.clone();let emit=emit.clone();bridge.on_step(move |token,direction|{
let Some(r)=row(&state,token.as_str())else{return;};
@@ -87,6 +87,12 @@ pub fn bind(ui:&AppWindow,emit:Arc<dyn Fn(SettingsAction)+Send+Sync>)->Binding{
}
});}
{let emit=emit.clone();bridge.on_capture_lost(move ||emit(SettingsAction::CaptureFocusLost));}
{let state=state.clone();let emit=emit.clone();bridge.on_color_channel(move |token,channel,value|{
let Some(r)=row(&state,token.as_str())else{return};let Control::Color(current)=&r.control else{return};
let Ok(channel)=usize::try_from(channel)else{return};if channel>2||!value.is_finite(){return}
let mut rgb=crate::services::prefs::palette_rgb(current).unwrap_or([0;3]);rgb[channel]=value.round().clamp(0.,255.) as u8;
emit_edit(&emit,&r,SettingValue::Text(format!("#{:02X}{:02X}{:02X}",rgb[0],rgb[1],rgb[2])));
});}
Binding{state}
}
@@ -97,7 +103,9 @@ pub fn present(ui:&AppWindow,binding:&Binding,p:Presentation){
let mut state=binding.state.borrow_mut();
state.generation=state.generation.checked_add(1).expect("settings presentation generation exhausted");
state.rows.clear();
let context=(p.category,p.subpage);if state.context.as_ref()!=Some(&context){state.drafts.clear();state.context=Some(context);}
// Android navigation retains unfinished non-secret edits. Target-specific row IDs
// keep drafts on their original identity/profile; secrets never enter this map.
let context=(p.category,p.subpage);if state.context.as_ref()!=Some(&context){if !cfg!(target_os="android"){state.drafts.clear();}state.context=Some(context);}
let mut rows=Vec::with_capacity(p.rows.len());
for r in p.rows{
let token=format!("{}:{}",state.generation,r.id);
@@ -106,12 +114,14 @@ pub fn present(ui:&AppWindow,binding:&Binding,p:Presentation){
Control::Toggle(v)=>(2,*v,String::new(),Vec::new(),0,0.0),
Control::Choice{options,selected}=>(3,false,String::new(),options.iter().map(|(_,s)|SharedString::from(s)).collect(),*selected as i32,0.0),
Control::Text(v)=>(4,false,v.clone(),Vec::new(),0,0.0),Control::Number{value,..}=>(5,false,value.to_string(),Vec::new(),0,0.0),
Control::Color(v)=>(10,false,v.clone(),Vec::new(),0,0.0),
Control::Action=>(6,false,String::new(),Vec::new(),0,0.0),Control::Meter(v)=>(7,false,String::new(),Vec::new(),0,*v),Control::Secret=>(8,false,String::new(),Vec::new(),0,0.0),Control::Rich{..}=>(9,false,String::new(),Vec::new(),0,0.0),
};
if state.drafts.get(&r.id)==Some(&value){state.drafts.remove(&r.id);}
let value=state.drafts.get(&r.id).cloned().unwrap_or(value);
let rich=if let Control::Rich{source,document}=&r.control{crate::ui::chat::preview_document(ui,source,document,ui.window().size().width as f32/ui.window().scale_factor()).into_iter().collect()}else{Vec::new()};
rows.push(SettingsRow{token:token.clone().into(),stable_id:r.id.clone().into(),title:r.title.clone().into(),subtitle:r.subtitle.clone().into(),kind,checked,value:value.into(),options:model(options),selected,enabled:r.enabled,destructive:r.destructive,inset:r.inset,error:r.error.clone().into(),meter,decrease:p.decrease_template.replace("{name}",&r.title).into(),increase:p.increase_template.replace("{name}",&r.title).into(),rich:model(rich)});
let parsed_rgb=crate::services::prefs::palette_rgb(&value);let rgb=parsed_rgb.unwrap_or([0;3]);
rows.push(SettingsRow{token:token.clone().into(),stable_id:r.id.clone().into(),title:r.title.clone().into(),subtitle:r.subtitle.clone().into(),kind,checked,value:value.into(),options:model(options),selected,enabled:r.enabled,destructive:r.destructive,inset:r.inset,error:r.error.clone().into(),meter,decrease:p.decrease_template.replace("{name}",&r.title).into(),increase:p.increase_template.replace("{name}",&r.title).into(),rich:model(rich),swatch:parsed_rgb.map(|rgb|slint::Color::from_rgb_u8(rgb[0],rgb[1],rgb[2])).unwrap_or_else(||slint::Color::from_argb_u8(0,0,0,0)),red:f32::from(rgb[0]),green:f32::from(rgb[1]),blue:f32::from(rgb[2])});
state.rows.insert(token,r);
}
// Retain the model object for unchanged identities. Only an actual navigation/reorder replaces it.
@@ -120,6 +130,7 @@ pub fn present(ui:&AppWindow,binding:&Binding,p:Presentation){
let bridge=ui.global::<SettingsBridge>();bridge.set_rows(state.model.clone().into());
bridge.set_categories(model(p.categories.into_iter().map(SharedString::from).collect()));
bridge.set_category_groups(model(p.category_groups.into_iter().map(SharedString::from).collect()));
bridge.set_category_subtitles(model(p.category_subtitles.into_iter().map(SharedString::from).collect()));bridge.set_profile_name(p.profile_name.into());bridge.set_profile_label(p.profile_label.into());
bridge.set_category(Category::ALL.iter().position(|c|*c==p.category).unwrap_or(0) as i32);
bridge.set_title(p.title.into());bridge.set_status(p.status.into());bridge.set_error(p.error.into());
bridge.set_panel_open(p.panel_open);bridge.set_subpage(p.subpage);bridge.set_show_slint(p.show_slint);
+153 -119
View File
@@ -1,119 +1,153 @@
use super::{pages::Builder,types::*};
use crate::services::{prefs::DeviceKind,notifications::{GROUPS,NotificationPrefs}};
impl Builder<'_> {
fn device(&mut self,kind:DeviceKind) {
let (key,label,devices)=match kind{DeviceKind::Input=>("inputDeviceId","settings.audio.capture_device",&self.s.audio.inputs),DeviceKind::Output=>("outputDeviceId","settings.audio.playback_device",&self.s.audio.outputs),DeviceKind::Notification=>("notificationDeviceId","settings.notifications.output_device",&self.s.audio.outputs)};
let current=self.s.prefs[key].as_str().unwrap_or_default();
let op=|id:String|Operation::SelectDevice{kind,id};
let mut choices=vec![(String::new(),self.text("ui.system.default.device"),op(String::new()))];
if kind==DeviceKind::Notification{choices.insert(0,("voice".into(),self.text("audio.use_playback_device"),op("voice".into())));choices.push(("none".into(),self.text("universal.none"),op("none".into())));}
choices.extend(devices.iter().map(|d|(d.id.clone(),d.name.clone(),op(d.id.clone()))));
if !choices.iter().any(|(id,_,_)|id==current){choices.push((current.into(),current.into(),op(current.into())));}
self.select(key,label,current,choices);
}
fn dsp(&self,kind:DeviceKind,field:DspField)->(String,Field,serde_json::Value){
let (key,selection,shown)=if kind==DeviceKind::Input{("inputDsp","inputDeviceId",&self.v.input_profile)}else{("outputDsp","outputDeviceId",&self.v.output_profile)};
let selected=self.s.prefs[selection].as_str().filter(|s|!s.is_empty()).unwrap_or("default");
let id=if self.v.page()==Page::AudioProfiles{shown.as_deref().unwrap_or(selected)}else{selected};
let target=if id=="template"{DspTarget::Template}else{DspTarget::Device(id.into())};
let profile=if id=="template"{&self.s.prefs[key]["template"]}else{self.s.prefs[key]["devices"].get(id).unwrap_or(&self.s.prefs[key]["template"])};
(format!("{key}:{id}:{}",field.key()),Field::Dsp{kind,target,field},profile[field.key()].clone())
}
fn dsp_toggle(&mut self,kind:DeviceKind,field:DspField,key:&str,info:&str){let(id,field,v)=self.dsp(kind,field);self.toggle(id,key,info,v.as_bool().unwrap_or(false),field);}
fn dsp_number(&mut self,kind:DeviceKind,field:DspField,key:&str,min:f64,max:f64){let(id,field,v)=self.dsp(kind,field);self.number(id,key,v.as_f64().unwrap_or(min),min,max,1.0,field);}
fn dsp_choice(&mut self,kind:DeviceKind,field:DspField,key:&str,options:&[(&str,&str)]){let(id,field,v)=self.dsp(kind,field);let current=v.as_str().map(str::to_owned).unwrap_or_else(||v.to_string());self.choice(id,key,&current,options,field);}
pub(super) fn audio(&mut self){
use DeviceKind::{Input,Output};
if self.v.page()==Page::DeviceMigration{self.migration();return;}
if self.v.page()==Page::AudioProfiles{
self.heading("native.audio.profiles");
for(kind,key,selection,shown)in[(Input,"inputDsp","inputDeviceId",&self.v.input_profile),(Output,"outputDsp","outputDeviceId",&self.v.output_profile)]{
let selected=shown.as_deref().unwrap_or_else(||self.s.prefs[selection].as_str().filter(|v|!v.is_empty()).unwrap_or("default"));
let mut choices=vec![("template".into(),self.text("native.audio.template"),Operation::Navigate(Navigation::DspProfile{kind,id:"template".into()}))];
if let Some(profiles)=self.s.prefs[key]["devices"].as_object(){choices.extend(profiles.keys().map(|id|(id.clone(),id.clone(),Operation::Navigate(Navigation::DspProfile{kind,id:id.clone()}))));}
if !choices.iter().any(|(id,_,_)|id==selected){choices.push((selected.into(),if selected=="default"{self.text("ui.system.default.device")}else{selected.into()},Operation::Navigate(Navigation::DspProfile{kind,id:selected.into()})));}
self.select(key,if kind==Input{"settings.audio.capture_device"}else{"settings.audio.playback_device"},selected,choices);
if selected!="template"{self.action(format!("{key}:copy-template"),"native.audio.copy_template",Operation::CopyDspToTemplate{kind,device:selected.into()});self.action(format!("{key}:apply-template"),"native.audio.apply_template",Operation::ApplyDspTemplate{kind,device:selected.into()});}
}
}
self.heading("ui.microphone");self.device(Input);
self.note("audio-status","",self.s.audio.status.clone());
self.pref_toggle(Preference::PttEnabled,"settings.audio.ptt","settings.audio.ptt.info");
if self.s.prefs["pttEnabled"]==true{
self.row("ptt-key","audio.pttKey",self.s.prefs["pttCode"].as_str().unwrap_or_default().into(),Control::Action,Intent::Invoke(Operation::CapturePtt));
let release=&self.s.prefs["pttReleaseDelay"];let value=if release["active"]==true{release["ms"].to_string()}else{"0".into()};
self.choice("ptt-release","settings.audio.release_delay",&value,&[("0","audio.off"),("100","100 ms"),("300","300 ms"),("500","500 ms")],Field::PttReleaseDelay);
}
self.dsp_toggle(Input,DspField::Vad,"settings.audio.vad.title","settings.audio.vad.disabled.info");
let vad=self.dsp(Input,DspField::Vad).2==true;let mode=self.dsp(Input,DspField::VadMode).2;
if vad{self.dsp_choice(Input,DspField::VadMode,"settings.audio.vad.mode",&[("automatic","audio.automatic"),("hybrid","audio.hybrid"),("volume_gate","audio.volume_gate")]);if mode!="automatic"{self.dsp_number(Input,DspField::VadLevel,"audio.vadLevel",-50.0,50.0);}}
self.pref_toggle(Preference::AutoEnableMicrophone,"ui.connections.autoEnableMic","");self.pref_toggle(Preference::AutoReactivateMicOnPreviousTarget,"ui.connections.reactivateMic","");
self.heading("settings.audio.speakers_headphones");self.device(Output);
self.number("outputLevelDb","settings.audio.output_volume",self.s.prefs["outputLevelDb"].as_f64().unwrap_or_default(),-200.0,10.0,0.5,Field::Preference(Preference::OutputLevelDb));
self.heading("settings.audio.processing.title");
self.action("audio-test-record",if self.s.audio.recording{"ui.stop.test"}else{"audio.test.record"},Operation::AudioTest(if self.s.audio.recording{AudioTest::Stop}else{AudioTest::Record}));
self.action("audio-test-play","audio.test.listen",Operation::AudioTest(AudioTest::Play));self.rows.last_mut().unwrap().enabled &=self.s.audio.has_sample&&!self.s.audio.recording&&!self.s.audio.playing;
self.action("audio-test-clear","audio.test.finish",Operation::AudioTest(AudioTest::Clear));
self.note("audio-test-status","settings.audio.test.info",self.s.audio.test_status.clone());
self.row("audio-meter","ui.microphone",String::new(),Control::Meter(self.s.audio.input_level),Intent::None);
self.dsp_toggle(Input,DspField::Denoise,"settings.audio.noise_reduction","settings.audio.noise_reduction.info");
self.dsp_choice(Input,DspField::DenoiseLevel,"settings.audio.noise_reduction.level",&[("0","settings.audio.noise_reduction.level.0"),("1","settings.audio.noise_reduction.level.1"),("2","settings.audio.noise_reduction.level.2"),("3","settings.audio.noise_reduction.level.3")]);
let denoise=self.dsp(Input,DspField::Denoise).2==true;self.rows.last_mut().unwrap().enabled&=denoise;
self.dsp_toggle(Output,DspField::Agc,"settings.audio.gain","settings.audio.gain.info");self.dsp_toggle(Output,DspField::Aec,"settings.audio.echo_cancellation","settings.audio.echo_cancellation.info");
self.dsp_number(Output,DspField::EchoReduction,"settings.audio.ducking",-40.0,0.0);self.dsp_toggle(Input,DspField::Typing,"settings.audio.typing","settings.audio.typing.info");
self.dsp_toggle(Output,DspField::ComfortNoise,"settings.audio.comfort_noise","settings.audio.comfort_noise.info");self.dsp_number(Output,DspField::ComfortNoiseLevel,"audio.comfortNoiseLevel",-97.0,-23.0);
self.heading("settings.additional");self.dsp_toggle(Input,DspField::Agc,"audio.captureAgc","settings.audio.capture_agc.info");
if vad&&mode!="volume_gate"{self.dsp_choice(Input,DspField::VadSensitivity,"audio.sensitivity",&[("high","audio.high"),("normal","audio.normal"),("low","audio.low")]);}
self.note("audio-per-device","audio.perDevice",self.text("audio.independentDsp"));
if self.v.page()!=Page::AudioProfiles{self.nav("native.audio.profiles",Page::AudioProfiles);}
self.nav("native.audio.mapping",Page::DeviceMigration);
self.heading("notify.group.local_recording");
let mode=self.s.prefs["recordingMode"].to_string();self.choice("recordingMode","recording.card.subtitle.modes",&mode,&[("1","recording.mode.multitrack"),("2","recording.mode.master"),("3","recording.mode.multitrack_and_master")],Field::Preference(Preference::RecordingMode));
self.note("recording-location","recording.output_folder",self.s.recording_location.clone());self.action("recording-choose","recording.folder.select",Operation::ChooseRecordingDirectory);
}
fn migration(&mut self){
self.heading("native.audio.mapping");
for item in &self.s.audio.migration{
self.note(&format!("migration:{:?}:{}",item.kind,item.legacy),"",item.legacy.clone());
let devices=if item.kind==DeviceKind::Input{&self.s.audio.inputs}else{&self.s.audio.outputs};
for d in devices{
self.row(format!("map:{:?}:{}:{}",item.kind,item.legacy,d.id),"native.audio.same_device",d.name.clone(),Control::Action,Intent::Invoke(Operation::MapDevice{kind:item.kind,legacy:item.legacy.clone(),native:d.id.clone()}));
}
}
for(kind,devices)in[(DeviceKind::Input,&self.s.audio.inputs),(DeviceKind::Output,&self.s.audio.outputs),(DeviceKind::Notification,&self.s.audio.outputs)]{
self.heading(match kind{DeviceKind::Input=>"settings.audio.capture_device",DeviceKind::Output=>"settings.audio.playback_device",DeviceKind::Notification=>"settings.notifications.output_device"});
self.row(format!("new-device:{kind:?}:default"),"native.audio.new_device",self.text("ui.system.default.device"),Control::Action,Intent::Invoke(Operation::NewDevice{kind,native:String::new()}));
for d in devices{self.row(format!("new-device:{kind:?}:{}",d.id),"native.audio.new_device",d.name.clone(),Control::Action,Intent::Invoke(Operation::NewDevice{kind,native:d.id.clone()}));}
}
}
pub(super) fn notifications(&mut self){
let prefs:NotificationPrefs=serde_json::from_value(self.s.prefs.clone()).unwrap_or_default();
self.heading("notify.system.title");
for key in ["notify.system.global_private","notify.system.global_group"]{self.unavailable(key,key,"settings.notifications.account.unavailable");}
self.pref_toggle(Preference::SystemNotifyServerPrivate,"notify.system.server_private","");self.pref_toggle(Preference::SystemNotifyChannelChat,"notify.system.channel_chat","");
self.heading("notify.title");self.device(DeviceKind::Notification);
self.number("notificationLevelDb","ui.volume",prefs.notification_level_db,-200.0,10.0,0.5,Field::Preference(Preference::NotificationLevelDb));
let choices=[("0","notify.state.disabled"),("1","notify.state.enabled"),("2","notify.state.important")];
for group in GROUPS{
let group_key=format!("notify.group.{}",group.id);self.heading(&group_key);
let flag=format!("group_{}",group.id);let enabled=prefs.notification_states.get(&flag).copied().unwrap_or(1)!=0;
self.toggle(format!("notification:{flag}"),&group_key,"",enabled,Field::NotificationGroup(group.id.into()));
for setting in group.settings{
let key=format!("notify.setting.{}",setting.id);let advanced=prefs.is_advanced(setting.id);
if !advanced{
self.choice(format!("notification:{}",setting.id),&key,&prefs.setting_state(setting.id).to_string(),&choices,Field::NotificationState(setting.id.into()));
self.action(format!("notify-preview:{}",setting.id),"universal.listen",Operation::PreviewNotification(setting.preview.into()));
}
self.toggle(format!("notification:advanced:{}",setting.id),if advanced{"universal.hide_advanced"}else{"universal.show.advanced"},if advanced{"settings.notifications.advanced.editing.info"}else{""},advanced,Field::NotificationAdvanced(setting.id.into()));
if advanced{for event in setting.events{
let event_key=if setting.events.len()==1{key.clone()}else{format!("notify.event.{}",event.id)};
let id=format!("event_{}_{}",setting.id,event.id);
self.choice(format!("notification:{id}"),&event_key,&prefs.event_state(setting.id,event.id).to_string(),&choices,Field::NotificationState(id));self.rows.last_mut().unwrap().inset=true;
if let Some(sound)=event.sound{self.action(format!("notify-preview:{}:{}",setting.id,event.id),"universal.listen",Operation::PreviewNotification(sound.into()));self.rows.last_mut().unwrap().inset=true;}
}}
}
if group.id=="stream"{self.heading("notify.group.call");for key in ["notify.setting.call_incoming","notify.setting.call_outgoing"]{self.unavailable(key,key,"settings.notifications.account.unavailable");}}
}
}
}
use super::{pages::Builder,types::*};
use crate::services::{prefs::DeviceKind,notifications::{GROUPS,NotificationPrefs}};
#[cfg(any(target_os="android",test))]
fn communication_choices(audio:&AudioView,c:&crate::ui::i18n::Catalog)->Option<Vec<(String,String,Operation)>> {
let routes=audio.communication_outputs.as_ref()?;
Some(routes.iter().map(|(id,kind)|{
let label=match kind {
1=>c.text("native.audio.route.earpiece"),
2|24=>c.text("native.audio.route.speaker"),
_=>audio.outputs.iter().find(|device|device.id==*id).map(|device|device.name.clone())
.unwrap_or_else(||c.text("native.audio.route.headset")),
};
(id.clone(),label,Operation::SelectDevice{kind:DeviceKind::Output,id:id.clone()})
}).collect())
}
impl Builder<'_> {
fn device(&mut self,kind:DeviceKind) {
let (key,label,devices)=match kind{DeviceKind::Input=>("inputDeviceId","settings.audio.capture_device",&self.s.audio.inputs),DeviceKind::Output=>("outputDeviceId","settings.audio.playback_device",&self.s.audio.outputs),DeviceKind::Notification=>("notificationDeviceId","settings.notifications.output_device",&self.s.audio.outputs)};
let current=self.s.prefs[key].as_str().unwrap_or_default();
let op=|id:String|Operation::SelectDevice{kind,id};
let default_id=if cfg!(target_os="android")&&current=="aaudio:-1"{current}else{""};
let mut choices=vec![(default_id.into(),self.text("ui.system.default.device"),op(default_id.into()))];
if kind==DeviceKind::Notification{choices.insert(0,("voice".into(),self.text("audio.use_playback_device"),op("voice".into())));choices.push(("none".into(),self.text("universal.none"),op("none".into())));}
#[cfg(any(target_os="android",test))]
let routes=if kind==DeviceKind::Output{communication_choices(&self.s.audio,self.c)}else{None};
#[cfg(not(any(target_os="android",test)))]
let routes:Option<Vec<(String,String,Operation)>>=None;
let communication=routes.is_some();
if let Some(routes)=routes{choices.extend(routes);}else{
choices.extend(devices.iter().filter(|d|!cfg!(target_os="android")||d.id!="aaudio:-1").map(|d|(d.id.clone(),d.name.clone(),op(d.id.clone()))));
}
if !choices.iter().any(|(id,_,_)|id==current){
let name=devices.iter().find(|device|device.id==current).map_or(current,|device|device.name.as_str());
let label=if communication{format!("{name} — {}",self.text("native.audio.route.unavailable"))}else{current.into()};
choices.push((current.into(),label,op(current.into())));
}
self.select(key,label,current,choices);
if communication{self.note("communication-output-info","",self.text("native.audio.route.info"));}
}
fn dsp(&self,kind:DeviceKind,field:DspField)->(String,Field,serde_json::Value){
let (key,selection,shown)=if kind==DeviceKind::Input{("inputDsp","inputDeviceId",&self.v.input_profile)}else{("outputDsp","outputDeviceId",&self.v.output_profile)};
let selected=self.s.prefs[selection].as_str().filter(|s|!s.is_empty()).unwrap_or("default");
let id=if self.v.page()==Page::AudioProfiles{shown.as_deref().unwrap_or(selected)}else{selected};
let target=if id=="template"{DspTarget::Template}else{DspTarget::Device(id.into())};
let profile=if id=="template"{&self.s.prefs[key]["template"]}else{self.s.prefs[key]["devices"].get(id).unwrap_or(&self.s.prefs[key]["template"])};
(format!("{key}:{id}:{}",field.key()),Field::Dsp{kind,target,field},profile[field.key()].clone())
}
fn dsp_toggle(&mut self,kind:DeviceKind,field:DspField,key:&str,info:&str){let(id,field,v)=self.dsp(kind,field);self.toggle(id,key,info,v.as_bool().unwrap_or(false),field);}
fn dsp_number(&mut self,kind:DeviceKind,field:DspField,key:&str,min:f64,max:f64){let(id,field,v)=self.dsp(kind,field);self.number(id,key,v.as_f64().unwrap_or(min),min,max,1.0,field);}
fn dsp_choice(&mut self,kind:DeviceKind,field:DspField,key:&str,options:&[(&str,&str)]){let(id,field,v)=self.dsp(kind,field);let current=v.as_str().map(str::to_owned).unwrap_or_else(||v.to_string());self.choice(id,key,&current,options,field);}
pub(super) fn audio(&mut self){
use DeviceKind::{Input,Output};
if self.v.page()==Page::DeviceMigration{self.migration();return;}
if self.v.page()==Page::AudioProfiles{
self.heading("native.audio.profiles");
for(kind,key,selection,shown)in[(Input,"inputDsp","inputDeviceId",&self.v.input_profile),(Output,"outputDsp","outputDeviceId",&self.v.output_profile)]{
let selected=shown.as_deref().unwrap_or_else(||self.s.prefs[selection].as_str().filter(|v|!v.is_empty()).unwrap_or("default"));
let mut choices=vec![("template".into(),self.text("native.audio.template"),Operation::Navigate(Navigation::DspProfile{kind,id:"template".into()}))];
if let Some(profiles)=self.s.prefs[key]["devices"].as_object(){choices.extend(profiles.keys().map(|id|(id.clone(),id.clone(),Operation::Navigate(Navigation::DspProfile{kind,id:id.clone()}))));}
if !choices.iter().any(|(id,_,_)|id==selected){choices.push((selected.into(),if selected=="default"{self.text("ui.system.default.device")}else{selected.into()},Operation::Navigate(Navigation::DspProfile{kind,id:selected.into()})));}
self.select(key,if kind==Input{"settings.audio.capture_device"}else{"settings.audio.playback_device"},selected,choices);
if selected!="template"{self.action(format!("{key}:copy-template"),"native.audio.copy_template",Operation::CopyDspToTemplate{kind,device:selected.into()});self.action(format!("{key}:apply-template"),"native.audio.apply_template",Operation::ApplyDspTemplate{kind,device:selected.into()});}
}
}
let mobile=cfg!(any(target_os="android",target_os="ios"));
if mobile {
self.heading("ui.audio");self.device(Input);self.device(Output);
self.note("audio-status","",self.s.audio.status.clone());
self.heading("ui.microphone");
}else{
self.heading("ui.microphone");self.device(Input);
self.note("audio-status","",self.s.audio.status.clone());
}
self.pref_toggle(Preference::PttEnabled,"settings.audio.ptt","settings.audio.ptt.info");
if self.s.prefs["pttEnabled"]==true{
self.row("ptt-key","audio.pttKey",self.s.prefs["pttCode"].as_str().unwrap_or_default().into(),Control::Action,Intent::Invoke(Operation::CapturePtt));
let release=&self.s.prefs["pttReleaseDelay"];let value=if release["active"]==true{release["ms"].to_string()}else{"0".into()};
self.choice("ptt-release","settings.audio.release_delay",&value,&[("0","audio.off"),("100","100 ms"),("300","300 ms"),("500","500 ms")],Field::PttReleaseDelay);
}
self.dsp_toggle(Input,DspField::Vad,"settings.audio.vad.title","settings.audio.vad.disabled.info");
let vad=self.dsp(Input,DspField::Vad).2==true;let mode=self.dsp(Input,DspField::VadMode).2;
if vad{self.dsp_choice(Input,DspField::VadMode,"settings.audio.vad.mode",&[("automatic","audio.automatic"),("hybrid","audio.hybrid"),("volume_gate","audio.volume_gate")]);if mode!="automatic"{self.dsp_number(Input,DspField::VadLevel,"audio.vadLevel",-50.0,50.0);}}
self.pref_toggle(Preference::AutoEnableMicrophone,"ui.connections.autoEnableMic","");self.pref_toggle(Preference::AutoReactivateMicOnPreviousTarget,"ui.connections.reactivateMic","");
self.heading("settings.audio.speakers_headphones");if !mobile{self.device(Output);}
self.number("outputLevelDb","settings.audio.output_volume",self.s.prefs["outputLevelDb"].as_f64().unwrap_or_default(),-200.0,10.0,0.5,Field::Preference(Preference::OutputLevelDb));
self.heading("settings.audio.processing.title");
self.action("audio-test-record",if self.s.audio.recording{"ui.stop.test"}else{"audio.test.record"},Operation::AudioTest(if self.s.audio.recording{AudioTest::Stop}else{AudioTest::Record}));
self.action("audio-test-play","audio.test.listen",Operation::AudioTest(AudioTest::Play));self.rows.last_mut().unwrap().enabled &=self.s.audio.has_sample&&!self.s.audio.recording&&!self.s.audio.playing;
self.action("audio-test-clear","audio.test.finish",Operation::AudioTest(AudioTest::Clear));
self.note("audio-test-status","settings.audio.test.info",self.s.audio.test_status.clone());
self.row("audio-meter","ui.microphone",String::new(),Control::Meter(self.s.audio.input_level),Intent::None);
self.dsp_toggle(Input,DspField::Denoise,"settings.audio.noise_reduction","settings.audio.noise_reduction.info");
self.dsp_choice(Input,DspField::DenoiseLevel,"settings.audio.noise_reduction.level",&[("0","settings.audio.noise_reduction.level.0"),("1","settings.audio.noise_reduction.level.1"),("2","settings.audio.noise_reduction.level.2"),("3","settings.audio.noise_reduction.level.3")]);
let denoise=self.dsp(Input,DspField::Denoise).2==true;self.rows.last_mut().unwrap().enabled&=denoise;
self.dsp_toggle(Output,DspField::Agc,"settings.audio.gain","settings.audio.gain.info");self.dsp_toggle(Output,DspField::Aec,"settings.audio.echo_cancellation","settings.audio.echo_cancellation.info");
self.dsp_number(Output,DspField::EchoReduction,"settings.audio.ducking",-40.0,0.0);self.dsp_toggle(Input,DspField::Typing,"settings.audio.typing","settings.audio.typing.info");
self.dsp_toggle(Output,DspField::ComfortNoise,"settings.audio.comfort_noise","settings.audio.comfort_noise.info");self.dsp_number(Output,DspField::ComfortNoiseLevel,"audio.comfortNoiseLevel",-97.0,-23.0);
self.heading("settings.additional");self.dsp_toggle(Input,DspField::Agc,"audio.captureAgc","settings.audio.capture_agc.info");
if vad&&mode!="volume_gate"{self.dsp_choice(Input,DspField::VadSensitivity,"audio.sensitivity",&[("high","audio.high"),("normal","audio.normal"),("low","audio.low")]);}
self.note("audio-per-device","audio.perDevice",self.text("audio.independentDsp"));
if self.v.page()!=Page::AudioProfiles{self.nav("native.audio.profiles",Page::AudioProfiles);}
self.nav("native.audio.mapping",Page::DeviceMigration);
self.heading("notify.group.local_recording");
let mode=self.s.prefs["recordingMode"].to_string();self.choice("recordingMode","recording.card.subtitle.modes",&mode,&[("1","recording.mode.multitrack"),("2","recording.mode.master"),("3","recording.mode.multitrack_and_master")],Field::Preference(Preference::RecordingMode));
self.note("recording-location","recording.output_folder",self.s.recording_location.clone());self.action("recording-choose","recording.folder.select",Operation::ChooseRecordingDirectory);
}
fn migration(&mut self){
self.heading("native.audio.mapping");
for item in &self.s.audio.migration{
self.note(&format!("migration:{:?}:{}",item.kind,item.legacy),"",item.legacy.clone());
let devices=if item.kind==DeviceKind::Input{&self.s.audio.inputs}else{&self.s.audio.outputs};
for d in devices{
self.row(format!("map:{:?}:{}:{}",item.kind,item.legacy,d.id),"native.audio.same_device",d.name.clone(),Control::Action,Intent::Invoke(Operation::MapDevice{kind:item.kind,legacy:item.legacy.clone(),native:d.id.clone()}));
}
}
for(kind,devices)in[(DeviceKind::Input,&self.s.audio.inputs),(DeviceKind::Output,&self.s.audio.outputs),(DeviceKind::Notification,&self.s.audio.outputs)]{
self.heading(match kind{DeviceKind::Input=>"settings.audio.capture_device",DeviceKind::Output=>"settings.audio.playback_device",DeviceKind::Notification=>"settings.notifications.output_device"});
self.row(format!("new-device:{kind:?}:default"),"native.audio.new_device",self.text("ui.system.default.device"),Control::Action,Intent::Invoke(Operation::NewDevice{kind,native:String::new()}));
for d in devices{self.row(format!("new-device:{kind:?}:{}",d.id),"native.audio.new_device",d.name.clone(),Control::Action,Intent::Invoke(Operation::NewDevice{kind,native:d.id.clone()}));}
}
}
pub(super) fn notifications(&mut self){
let prefs:NotificationPrefs=serde_json::from_value(self.s.prefs.clone()).unwrap_or_default();
self.heading("notify.system.title");
for key in ["notify.system.global_private","notify.system.global_group"]{self.unavailable(key,key,"settings.notifications.account.unavailable");}
self.pref_toggle(Preference::SystemNotifyServerPrivate,"notify.system.server_private","");self.pref_toggle(Preference::SystemNotifyChannelChat,"notify.system.channel_chat","");
self.heading("notify.title");self.device(DeviceKind::Notification);
self.number("notificationLevelDb","ui.volume",prefs.notification_level_db,-200.0,10.0,0.5,Field::Preference(Preference::NotificationLevelDb));
let choices=[("0","notify.state.disabled"),("1","notify.state.enabled"),("2","notify.state.important")];
for group in GROUPS{
let group_key=format!("notify.group.{}",group.id);self.heading(&group_key);
let flag=format!("group_{}",group.id);let enabled=prefs.notification_states.get(&flag).copied().unwrap_or(1)!=0;
self.toggle(format!("notification:{flag}"),&group_key,"",enabled,Field::NotificationGroup(group.id.into()));
for setting in group.settings{
let key=format!("notify.setting.{}",setting.id);let advanced=prefs.is_advanced(setting.id);
if !advanced{
self.choice(format!("notification:{}",setting.id),&key,&prefs.setting_state(setting.id).to_string(),&choices,Field::NotificationState(setting.id.into()));
self.action(format!("notify-preview:{}",setting.id),"universal.listen",Operation::PreviewNotification(setting.preview.into()));
}
self.toggle(format!("notification:advanced:{}",setting.id),if advanced{"universal.hide_advanced"}else{"universal.show.advanced"},if advanced{"settings.notifications.advanced.editing.info"}else{""},advanced,Field::NotificationAdvanced(setting.id.into()));
if advanced{for event in setting.events{
let event_key=if setting.events.len()==1{key.clone()}else{format!("notify.event.{}",event.id)};
let id=format!("event_{}_{}",setting.id,event.id);
self.choice(format!("notification:{id}"),&event_key,&prefs.event_state(setting.id,event.id).to_string(),&choices,Field::NotificationState(id));self.rows.last_mut().unwrap().inset=true;
if let Some(sound)=event.sound{self.action(format!("notify-preview:{}:{}",setting.id,event.id),"universal.listen",Operation::PreviewNotification(sound.into()));self.rows.last_mut().unwrap().inset=true;}
}}
}
if group.id=="stream"{self.heading("notify.group.call");for key in ["notify.setting.call_incoming","notify.setting.call_outgoing"]{self.unavailable(key,key,"settings.notifications.account.unavailable");}}
}
}
}
+25 -3
View File
@@ -32,11 +32,13 @@ impl<'a> Builder<'a> {
pub fn identities(&mut self) {
self.heading("settings.nav.identities");
let selected_uid=self.s.identities.iter().find(|i|Some(i.uid.as_str())==self.v.identity.as_deref()).or_else(||self.s.identities.iter().find(|i|i.is_default)).or(self.s.identities.first()).map(|i|i.uid.as_str()).unwrap_or("");
self.select("identity-select","settings.identity.choose",selected_uid,self.s.identities.iter().map(|i|(i.uid.clone(),i.name.clone(),Operation::Navigate(Navigation::Identity(i.uid.clone())))).collect());
let identity_default=self.text("identity.default");
self.select("identity-select","settings.identity.choose",selected_uid,self.s.identities.iter().map(|i|(i.uid.clone(),i.display_name(&identity_default).to_owned(),Operation::Navigate(Navigation::Identity(i.uid.clone())))).collect());
if cfg!(target_os="android"){self.action("identity-import","settings.identity.action.import",Operation::IdentityImport);}
self.note("identity-info","settings.identity.info",String::new());
self.input("identity-new-name","settings.identity.new.placeholder","",Field::NewIdentityName);
self.action("identity-create","settings.identity.add",Operation::IdentityCreate);
self.action("identity-import","settings.identity.action.import",Operation::IdentityImport);
if !cfg!(target_os="android"){self.action("identity-import","settings.identity.action.import",Operation::IdentityImport);}
let selected=self.s.identities.iter().find(|i|Some(i.uid.as_str())==self.v.identity.as_deref()).or_else(||self.s.identities.iter().find(|i|i.is_default)).or(self.s.identities.first());
if let Some(i)=selected {
self.input(format!("identity-name:{}",i.uid),"universal.rename",&i.name,Field::IdentityName(i.uid.clone()));
@@ -80,6 +82,7 @@ impl<'a> Builder<'a> {
}
pub fn appearance(&mut self) {
if self.v.page()==Page::Themes {self.themes();return;}
if cfg!(target_os="android") {if self.v.page()==Page::Palette{self.palette();return;}self.nav("native.palette.title",Page::Palette);}
self.heading("settings.general");
self.pref_choice(Preference::Theme,"settings.theme.stock",&[("dark","ui.dark"),("light","ui.light"),("system","ui.system")]);
self.nav("themes.user",Page::Themes);
@@ -92,6 +95,23 @@ impl<'a> Builder<'a> {
self.pref_choice(Preference::TreeStyle,"appearance.treeStyle",&[("compact","appearance.compact"),("detailed","appearance.detailed")]);
self.heading("ui.chats");self.pref_choice(Preference::ChatStyle,"settings.chat_style",&[("compact","appearance.compact"),("detailed","appearance.detailed")]);
}
fn palette(&mut self) {
use crate::services::prefs;
let value=self.s.palette_draft.as_ref().unwrap_or(&self.s.prefs["androidPalette"]);
self.note("palette-preview","native.palette.preview",self.text("native.palette.preview.info"));
self.select("palette-presets","native.palette.presets","",[(PalettePreset::Ts6,"native.palette.ts6"),(PalettePreset::Graphite,"native.palette.graphite"),(PalettePreset::Light,"native.palette.light")].into_iter().map(|(preset,key)|(preset.key().into(),self.text(key),Operation::PalettePreset(preset))).collect());
for color in PaletteColor::ALL {
let text=value[color.key()].as_str().unwrap_or_default();
self.row(format!("palette:{}",color.key()),&format!("native.palette.{}",color.key()),String::new(),Control::Color(text.into()),Intent::Edit(Field::Palette(color)));
// Ephemeral color edits remain focusable while their ordered acknowledgement is pending.
self.rows.last_mut().unwrap().enabled=true;
}
let valid=prefs::valid_android_palette(value);
self.note("palette-contrast",if valid{"native.palette.contrast.ok"}else{"native.palette.contrast.error"},self.text("native.palette.contrast.info"));
self.action("palette-reset","native.palette.reset",Operation::PalettePreset(PalettePreset::Ts6));
self.action("palette-cancel","ui.cancel",Operation::PaletteCancel);
self.action("palette-save","ui.save",Operation::PaletteSave);self.rows.last_mut().unwrap().enabled&=valid;
}
fn themes(&mut self) {
self.heading("themes.user");
self.action("theme-stock","themes.user.disabled",Operation::ThemeSelect(None));
@@ -169,5 +189,7 @@ pub fn build(s:&SettingsSnapshot,v:&ViewState,c:&Catalog)->Presentation {
if s.loaded{match v.category{Category::Identities=>b.identities(),Category::Privacy=>b.privacy(),Category::Appearance=>b.appearance(),Category::Audio=>b.audio(),Category::Video=>b.video(),Category::KeyBindings=>b.keys(),Category::Chats=>b.chats(),Category::Whispers=>b.whispers(),Category::Notifications=>b.notifications(),Category::FileTransfer=>b.files(),Category::OsSpecific=>b.os(),Category::About=>b.about()}}
let readonly=(v.category==Category::KeyBindings&&s.key_read_only)||(v.category==Category::Whispers&&s.whispers.as_ref().is_some_and(|w|w.read_only));
if readonly{for row in &mut b.rows{let navigation=match &row.intent{Intent::None=>true,Intent::Invoke(Operation::Navigate(_)|Operation::WhisperOverlay(_))=>true,Intent::Select(ops)=>ops.iter().all(|op|matches!(op,Operation::Navigate(_))),_=>false};row.enabled&=navigation;}}
Presentation{category:v.category,title:c.text(v.category.key()),categories:Category::ALL.iter().map(|x|c.text(x.key())).collect(),category_groups:["ui.user","ui.application","ui.information"].into_iter().map(|k|c.text(k)).collect(),rows:b.rows,panel_open:v.panel_open,subpage:!v.pages.is_empty(),show_slint:v.category==Category::About && v.page()==Page::Root,status:if !s.loaded&&s.status.is_empty(){c.text("files.loading")}else{s.status.clone()},error:s.error.clone(),back:c.text("clientMenu.back"),apply:c.text("ui.save"),cancel:c.text("ui.cancel"),loading:!s.loaded,capturing:s.capture.active,decrease_template:c.text("files.settings.decrease"),increase_template:c.text("files.settings.increase")}
let category_subtitles=Category::ALL.iter().map(|category|c.text(&format!("native.room.settings.{}",match category{Category::Identities=>"identity",Category::Privacy=>"privacy",Category::Appearance=>"appearance",Category::Audio=>"audio",Category::Video=>"video",Category::KeyBindings=>"keys",Category::Chats=>"chats",Category::Whispers=>"whispers",Category::Notifications=>"notifications",Category::FileTransfer=>"files",Category::OsSpecific=>"system",Category::About=>"about"}))).collect();
let profile_label=c.text("native.room.settings.profile");let profile_name=s.identities.iter().find(|i|i.is_default).or(s.identities.first()).map(|i|i.display_name(&profile_label).to_owned()).unwrap_or_else(||c.text("native.room.settings.profile.empty"));
Presentation{category:v.category,title:c.text(if cfg!(target_os="android")&&v.page()==Page::Palette{"native.palette.title"}else{v.category.key()}),categories:Category::ALL.iter().map(|x|c.text(x.key())).collect(),category_subtitles,profile_name,profile_label,category_groups:if cfg!(target_os="android"){["native.room.settings.conversation","native.room.settings.personal","native.room.settings.application"].into_iter().map(|k|c.text(k)).collect()}else{["ui.user","ui.application","ui.information"].into_iter().map(|k|c.text(k)).collect()},rows:b.rows,panel_open:v.panel_open,subpage:!v.pages.is_empty(),show_slint:v.category==Category::About && v.page()==Page::Root,status:if !s.loaded&&s.status.is_empty(){c.text("files.loading")}else{s.status.clone()},error:s.error.clone(),back:c.text("clientMenu.back"),apply:c.text("ui.save"),cancel:c.text("ui.cancel"),loading:!s.loaded,capturing:s.capture.active,decrease_template:c.text("files.settings.decrease"),increase_template:c.text("files.settings.increase")}
}
+120 -58
View File
@@ -1,58 +1,120 @@
use super::*;
use crate::ui::i18n::{Catalog,Language};
fn loaded()->SettingsSnapshot {SettingsSnapshot{loaded:true,prefs:crate::services::prefs::defaults(),..Default::default()}}
fn presentation(category:Category,s:&SettingsSnapshot)->Presentation {build(s,&ViewState{category,panel_open:true,..Default::default()},&Catalog::new(Language::En))}
#[test]
fn navigation_back_never_emits_service_mutation(){
let mut view=ViewState::default();
assert!(view.navigate(&Navigation::Category(Category::Privacy)));
assert!(view.navigate(&Navigation::Page(Page::TrustedHosts)));
assert!(view.navigate(&Navigation::Back));assert_eq!(view.page(),Page::Root);
assert!(view.navigate(&Navigation::Back));assert!(!view.panel_open);
assert!(!view.navigate(&Navigation::Back));
}
#[test]
fn every_advanced_notification_retains_its_exact_preference_key(){
let mut snapshot=loaded();let mut count=0;
for group in crate::services::notifications::GROUPS{for setting in group.settings{
snapshot.prefs["notificationStates"][format!("advanced_{}",setting.id)]=1.into();
for event in setting.events{snapshot.prefs["notificationStates"][format!("event_{}_{}",setting.id,event.id)]=2.into();count+=1;}
}}
let p=presentation(Category::Notifications,&snapshot);
let rows:Vec<_>=p.rows.iter().filter(|r|matches!(&r.intent,Intent::Edit(Field::NotificationState(key)) if key.starts_with("event_"))).collect();
assert_eq!(rows.len(),count);
for r in rows{assert!(matches!(r.control,Control::Choice{selected:2,..}));}
}
#[test]
fn imported_device_mapping_never_becomes_a_generic_preference_edit(){
let mut s=loaded();s.audio.inputs.push(DeviceView{id:"native-in".into(),name:"Input".into(),available:true});
s.audio.migration.push(MigrationDevice{kind:crate::services::prefs::DeviceKind::Input,legacy:"chromium-in".into()});
let p=build(&s,&ViewState{category:Category::Audio,pages:vec![Page::DeviceMigration],..Default::default()},&Catalog::new(Language::En));
assert!(p.rows.iter().any(|r|matches!(&r.intent,Intent::Invoke(Operation::MapDevice{legacy,native,..}) if legacy=="chromium-in"&&native=="native-in")));
assert!(!p.rows.iter().any(|r|matches!(&r.intent,Intent::Edit(Field::Preference(_)))));
}
#[test]
fn download_destination_is_only_a_chooser_intent(){
let mut s=loaded();s.files=Some(crate::services::file_settings::FileSettingsValue::default());s.download_location="retained grant display".into();
let p=presentation(Category::FileTransfer,&s);
assert!(p.rows.iter().any(|r|matches!(r.intent,Intent::Invoke(Operation::ChooseDownloadDirectory))));
assert!(!p.rows.iter().any(|r|matches!(r.control,Control::Text(_)|Control::Secret)));
}
#[test]
fn stale_presentation_token_cannot_resolve_new_target(){
let mut p=presentation(Category::Identities,&loaded());
let target=p.rows.iter_mut().find(|r|r.id=="identity-create").unwrap();
let state=Rc::new(RefCell::new(State{generation:1,rows:HashMap::from([("1:identity-create".into(),target.clone())]),drafts:HashMap::new(),model:Rc::new(VecModel::default()),context:None}));
assert!(row(&state,"1:identity-create").is_some());
state.borrow_mut().rows=HashMap::from([("2:identity-create".into(),target.clone())]);
assert!(row(&state,"1:identity-create").is_none());
assert!(row(&state,"2:identity-create").is_some());
}
#[test]
fn unsupported_os_action_has_reported_reason_not_fake_success(){
let mut s=loaded();s.os.autostart.reason="reported platform restriction".into();
let p=presentation(Category::OsSpecific,&s);let r=p.rows.iter().find(|r|r.id=="os:autostart").unwrap();
assert!(!r.enabled);assert_eq!(r.subtitle,"reported platform restriction");
}
use super::*;
use crate::ui::i18n::{Catalog,Language};
fn loaded()->SettingsSnapshot {SettingsSnapshot{loaded:true,prefs:crate::services::prefs::defaults(),..Default::default()}}
fn presentation(category:Category,s:&SettingsSnapshot)->Presentation {build(s,&ViewState{category,panel_open:true,..Default::default()},&Catalog::new(Language::En))}
#[test]
fn navigation_back_never_emits_service_mutation(){
let mut view=ViewState::default();
assert!(view.navigate(&Navigation::Category(Category::Privacy)));
assert!(view.navigate(&Navigation::Page(Page::TrustedHosts)));
assert!(view.navigate(&Navigation::Back));assert_eq!(view.page(),Page::Root);
assert!(view.navigate(&Navigation::Back));assert!(!view.panel_open);
assert!(!view.navigate(&Navigation::Back));
}
#[test]
fn every_advanced_notification_retains_its_exact_preference_key(){
let mut snapshot=loaded();let mut count=0;
for group in crate::services::notifications::GROUPS{for setting in group.settings{
snapshot.prefs["notificationStates"][format!("advanced_{}",setting.id)]=1.into();
for event in setting.events{snapshot.prefs["notificationStates"][format!("event_{}_{}",setting.id,event.id)]=2.into();count+=1;}
}}
let p=presentation(Category::Notifications,&snapshot);
let rows:Vec<_>=p.rows.iter().filter(|r|matches!(&r.intent,Intent::Edit(Field::NotificationState(key)) if key.starts_with("event_"))).collect();
assert_eq!(rows.len(),count);
for r in rows{assert!(matches!(r.control,Control::Choice{selected:2,..}));}
}
#[test]
fn imported_device_mapping_never_becomes_a_generic_preference_edit(){
let mut s=loaded();s.audio.inputs.push(DeviceView{id:"native-in".into(),name:"Input".into(),available:true});
s.audio.migration.push(MigrationDevice{kind:crate::services::prefs::DeviceKind::Input,legacy:"chromium-in".into()});
let p=build(&s,&ViewState{category:Category::Audio,pages:vec![Page::DeviceMigration],..Default::default()},&Catalog::new(Language::En));
assert!(p.rows.iter().any(|r|matches!(&r.intent,Intent::Invoke(Operation::MapDevice{legacy,native,..}) if legacy=="chromium-in"&&native=="native-in")));
assert!(!p.rows.iter().any(|r|matches!(&r.intent,Intent::Edit(Field::Preference(_)))));
}
#[test]
fn download_destination_is_only_a_chooser_intent(){
let mut s=loaded();s.files=Some(crate::services::file_settings::FileSettingsValue::default());s.download_location="retained grant display".into();
let p=presentation(Category::FileTransfer,&s);
assert!(p.rows.iter().any(|r|matches!(r.intent,Intent::Invoke(Operation::ChooseDownloadDirectory))));
assert!(!p.rows.iter().any(|r|matches!(r.control,Control::Text(_)|Control::Secret)));
}
#[test]
fn stale_presentation_token_cannot_resolve_new_target(){
let mut p=presentation(Category::Identities,&loaded());
let target=p.rows.iter_mut().find(|r|r.id=="identity-create").unwrap();
let state=Rc::new(RefCell::new(State{generation:1,rows:HashMap::from([("1:identity-create".into(),target.clone())]),drafts:HashMap::new(),model:Rc::new(VecModel::default()),context:None}));
assert!(row(&state,"1:identity-create").is_some());
state.borrow_mut().rows=HashMap::from([("2:identity-create".into(),target.clone())]);
assert!(row(&state,"1:identity-create").is_none());
assert!(row(&state,"2:identity-create").is_some());
}
#[test]
fn unsupported_os_action_has_reported_reason_not_fake_success(){
let mut s=loaded();s.os.autostart.reason="reported platform restriction".into();
let p=presentation(Category::OsSpecific,&s);let r=p.rows.iter().find(|r|r.id=="os:autostart").unwrap();
assert!(!r.enabled);assert_eq!(r.subtitle,"reported platform restriction");
}
#[cfg(target_os="android")]
#[test]
fn palette_has_real_color_intents_and_blocks_invalid_saves() {
let mut snapshot=loaded();let mut invalid=crate::services::prefs::android_palette_default();invalid["foreground"]=invalid["background"].clone();snapshot.palette_draft=Some(invalid);
let view=ViewState{category:Category::Appearance,pages:vec![Page::Palette],panel_open:true,..Default::default()};
let p=build(&snapshot,&view,&Catalog::new(Language::En));
assert_eq!(p.rows.iter().filter(|row|matches!(row.intent,Intent::Edit(Field::Palette(_)))).count(),4);
assert!(!p.rows.iter().find(|row|row.id=="palette-save").unwrap().enabled);
let cancel=p.rows.iter().position(|row|row.id=="palette-cancel").unwrap();assert_eq!(p.rows[cancel+1].id,"palette-save");
assert!(matches!(p.rows.iter().find(|row|row.id=="palette-reset").unwrap().intent,Intent::Invoke(Operation::PalettePreset(PalettePreset::Ts6))));
snapshot.palette_draft=Some(crate::services::prefs::android_palette_default());snapshot.pending.push("palette:accent".into());
let p=build(&snapshot,&view,&Catalog::new(Language::En));assert!(p.rows.iter().find(|row|row.id=="palette-save").unwrap().enabled);assert!(p.rows.iter().find(|row|row.id=="palette:accent").unwrap().enabled);
}
#[test]
fn communication_routes_expose_earpiece_speaker_and_headset_but_not_media_only_output(){
use crate::services::prefs::DeviceKind;
let mut s=loaded();
s.audio.outputs=vec![
DeviceView{id:"aaudio:1".into(),name:"Phone model".into(),available:true},
DeviceView{id:"aaudio:2".into(),name:"Phone model".into(),available:true},
DeviceView{id:"aaudio:7".into(),name:"G435 (Bluetooth headset)".into(),available:true},
DeviceView{id:"aaudio:8".into(),name:"G435 (Bluetooth audio)".into(),available:true},
];
s.audio.communication_outputs=Some(vec![("aaudio:1".into(),1),("aaudio:2".into(),2),("aaudio:7".into(),7)]);
let p=presentation(Category::Audio,&s);
let row=p.rows.iter().find(|row|row.id=="outputDeviceId").unwrap();
let Control::Choice{options,..}=&row.control else{panic!("output choice missing")};
assert_eq!(options.iter().map(|(id,_)|id.as_str()).collect::<Vec<_>>(),["","aaudio:1","aaudio:2","aaudio:7"]);
assert_eq!(options[1].1,"Phone earpiece");assert_eq!(options[2].1,"Speakerphone");
let Intent::Select(actions)=&row.intent else{panic!("selection actions missing")};
assert!(matches!(&actions[1],Operation::SelectDevice{kind:DeviceKind::Output,id} if id=="aaudio:1"));
assert!(matches!(&actions[2],Operation::SelectDevice{kind:DeviceKind::Output,id} if id=="aaudio:2"));
// Notifications retain the broader media output list; call route filtering
// must not silently remove an independently valid notification sink.
let notifications=presentation(Category::Notifications,&s);
let notification=notifications.rows.iter().find(|row|row.id=="notificationDeviceId").unwrap();
assert!(matches!(&notification.control,Control::Choice{options,..} if options.iter().any(|(id,_)|id=="aaudio:8")));
// Keep a saved unavailable choice visible and identified as unavailable,
// not silently rewritten to speaker/default when the platform list changes.
s.prefs["outputDeviceId"]="aaudio:8".into();
let p=presentation(Category::Audio,&s);
let row=p.rows.iter().find(|row|row.id=="outputDeviceId").unwrap();
let Control::Choice{selected,options}=&row.control else{panic!("output choice missing")};
assert_eq!(options[*selected].0,"aaudio:8");
assert!(options[*selected].1.contains("Unavailable for calls"));
}
#[test]
fn communication_routes_absence_keeps_desktop_and_legacy_choices(){
let mut s=loaded();
s.audio.outputs.push(DeviceView{id:"native-output".into(),name:"Existing output".into(),available:true});
let p=presentation(Category::Audio,&s);
let row=p.rows.iter().find(|row|row.id=="outputDeviceId").unwrap();
assert!(matches!(&row.control,Control::Choice{options,..} if options.iter().any(|(id,name)|id=="native-output"&&name=="Existing output")));
assert!(!p.rows.iter().any(|row|row.id=="communication-output-info"));
s.audio.communication_outputs=Some(Vec::new());
let p=presentation(Category::Audio,&s);
let row=p.rows.iter().find(|row|row.id=="outputDeviceId").unwrap();
assert!(matches!(&row.control,Control::Choice{options,..} if options.iter().all(|(id,_)|id.is_empty())));
}
+174 -155
View File
@@ -1,155 +1,174 @@
//! Typed settings intents. All mutations are requests; only service acknowledgements change snapshots.
use crate::app::connections::SessionKey;
use crate::services::{file_settings::FileSettingsValue, keybinds::{Action as KeyAction, KeybindState}, prefs::DeviceKind, secrets::{SecretBinding, SecretString}, whisper::{WhisperEntry, WhisperState}};
use serde_json::Value;
use std::collections::{BTreeMap, HashMap};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Category { #[default] Identities, Privacy, Appearance, Audio, Video, KeyBindings, Chats, Whispers, Notifications, FileTransfer, OsSpecific, About }
impl Category {
pub const ALL: [Self; 12] = [Self::Identities,Self::Privacy,Self::Appearance,Self::Audio,Self::Video,Self::KeyBindings,Self::Chats,Self::Whispers,Self::Notifications,Self::FileTransfer,Self::OsSpecific,Self::About];
pub fn key(self)->&'static str {match self {Self::Identities=>"settings.nav.identities",Self::Privacy=>"settings.privacy.title",Self::Appearance=>"ui.appearance",Self::Audio=>"ui.audio",Self::Video=>"ui.video",Self::KeyBindings=>"settings.nav.keybinds",Self::Chats=>"ui.chats",Self::Whispers=>"settings.nav.whispers",Self::Notifications=>"ui.layout.notifications",Self::FileTransfer=>"files.title",Self::OsSpecific=>"os.title",Self::About=>"settings.nav.about"}}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum Page { #[default] Root, TrustedHosts, PrivacyDetails, Themes, AudioProfiles, DeviceMigration, VideoDetails, MarkdownHelp, Changelog, Licenses, License(String), Diagnostics }
#[derive(Clone, Debug)]
pub struct ViewState {
pub category: Category, pub pages: Vec<Page>, pub panel_open: bool,
pub identity: Option<String>, pub key_profile: Option<String>, pub whisper_list: Option<String>,
pub input_profile: Option<String>, pub output_profile: Option<String>,
pub preview_theme: Option<String>, pub whisper_preview: bool,
}
impl Default for ViewState {
fn default()->Self {Self{category:Category::Identities,pages:Vec::new(),panel_open:false,identity:None,key_profile:None,whisper_list:None,input_profile:None,output_profile:None,preview_theme:None,whisper_preview:true}}
}
impl ViewState {
pub fn page(&self)->Page {self.pages.last().cloned().unwrap_or_default()}
/// Navigation is presentation-only. Returning false means the shell should close settings.
pub fn navigate(&mut self, navigation:&Navigation)->bool {
match navigation {
Navigation::Category(c)=>{self.category=*c;self.pages.clear();self.panel_open=true;},
Navigation::Page(p)=>{self.pages.push(p.clone());self.panel_open=true;},
Navigation::Back=>{if self.pages.pop().is_none(){if self.panel_open {self.panel_open=false;}else{return false;}}},
Navigation::Identity(id)=>self.identity=Some(id.clone()),
Navigation::KeyProfile(id)=>self.key_profile=Some(id.clone()),
Navigation::WhisperList(id)=>self.whisper_list=Some(id.clone()),
Navigation::DspProfile{kind,id}=>match kind{DeviceKind::Input=>self.input_profile=Some(id.clone()),DeviceKind::Output=>self.output_profile=Some(id.clone()),DeviceKind::Notification=>{}},
Navigation::WhisperPreview(v)=>self.whisper_preview=*v,
} true
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Navigation { Category(Category), Page(Page), Back, Identity(String), KeyProfile(String), WhisperList(String), DspProfile{kind:DeviceKind,id:String}, WhisperPreview(bool) }
macro_rules! preferences {($($variant:ident => $key:literal),+ $(,)?)=>{
#[derive(Clone,Copy,Debug,PartialEq,Eq,Hash)] pub enum Preference {$($variant),+}
impl Preference {pub fn key(self)->&'static str {match self {$(Self::$variant=>$key),+}}}
};}
preferences! {
Theme=>"theme", DisplaySize=>"displaySize", TreeStyle=>"treeStyle", ChatStyle=>"chatStyle", SidebarIconMode=>"sidebarIconMode", Language=>"language",
ShowBadges=>"showBadges", ShowCountryFlags=>"showCountryFlags", HighlightContacts=>"highlightContacts", ShowClientsBeforeChannels=>"showClientsBeforeChannels", ShowChannelBanners=>"showChannelBanners", ShowChannelBackground=>"showChannelBackground", ChannelCommanderAsLamp=>"channelCommanderAsLamp",
AllowWhitelistMalicious=>"allowWhitelistMalicious", PttEnabled=>"pttEnabled", OutputLevelDb=>"outputLevelDb", AutoEnableMicrophone=>"autoEnableMicrophone", AutoReactivateMicOnPreviousTarget=>"autoReactivateMicOnPreviousTarget", HardwareVideoDecode=>"hardwareVideoDecode",
ChatRichTextEditor=>"chatRichTextEditor", ChatToolbarVisibility=>"chatToolbarVisibility", ChatMermaidAutoload=>"chatMermaidAutoload", ChatOpenIncoming=>"chatOpenIncoming", ChatShowModerationEvents=>"chatShowModerationEvents", ChatUse24hTime=>"chatUse24hTime", AutoDownloadImages=>"autoDownloadImages",
ContactsSortAlphabetically=>"contactsSortAlphabetically", ContactsShowOffline=>"contactsShowOffline", ContactsGroupOffline=>"contactsGroupOffline",
NotificationLevelDb=>"notificationLevelDb", SystemNotifyServerPrivate=>"systemNotifyServerPrivate", SystemNotifyChannelChat=>"systemNotifyChannelChat",
OsFlashOnMessage=>"osFlashOnMessage", OsFlashOnPoke=>"osFlashOnPoke", OsHideInTaskbar=>"osHideInTaskbar", OsMuteWhenLocked=>"osMuteWhenLocked", UpdateChannel=>"updateChannel", RecordingMode=>"recordingMode"
}
#[derive(Clone,Debug,PartialEq)]
pub enum SettingValue { Bool(bool), Number(f64), Text(String) }
impl SettingValue {
pub fn json(&self)->Value {match self {Self::Bool(v)=>(*v).into(),Self::Number(v)=>serde_json::json!(v),Self::Text(v)=>v.clone().into()}}
pub fn text(&self)->String {match self {Self::Bool(v)=>v.to_string(),Self::Number(v)=>v.to_string(),Self::Text(v)=>v.clone()}}
}
#[derive(Clone,Copy,Debug,PartialEq,Eq)]
pub enum DspField { Agc, Denoise, DenoiseLevel, Typing, Vad, VadMode, VadLevel, VadSensitivity, Aec, ComfortNoise, ComfortNoiseLevel, EchoReduction }
impl DspField {pub fn key(self)->&'static str {match self{Self::Agc=>"agc",Self::Denoise=>"denoise",Self::DenoiseLevel=>"denoiseLevel",Self::Typing=>"typing",Self::Vad=>"vad",Self::VadMode=>"vadMode",Self::VadLevel=>"vadLevel",Self::VadSensitivity=>"vadSensitivity",Self::Aec=>"aec",Self::ComfortNoise=>"comfortNoise",Self::ComfortNoiseLevel=>"comfortNoiseLevel",Self::EchoReduction=>"echoReduction"}}}
#[derive(Clone,Debug,PartialEq)]
pub enum DspTarget { Template, Device(String) }
#[derive(Clone,Copy,Debug,PartialEq)]
pub enum FileField { AlwaysAsk, LimitUpload, LimitDownload, UploadMiB, DownloadMiB, UploadSlots, DownloadSlots }
#[derive(Clone,Copy,Debug,PartialEq)]
pub enum WhisperField { Name, Kind, GroupType, GroupTargetMode, ServerUid, GroupId }
#[derive(Clone,Debug,PartialEq)]
pub enum Field {
Preference(Preference), Device(DeviceKind), PttReleaseDelay,
Dsp {kind:DeviceKind,target:DspTarget,field:DspField},
IdentityName(String), IdentityNickname(String), IdentityTarget(String), NewIdentityName,
KeyExact, KeyProfileName(String), NewKeyProfileName,
KeyBindingAction{profile:String,binding:String}, KeyBindingTarget{profile:String,binding:String}, KeyBindingGlobal{profile:String,binding:String},
WhisperReceive, Whisper {list:String,field:WhisperField}, NewWhisperName,
NotificationState(String), NotificationGroup(String), NotificationAdvanced(String),
File(FileField), Autostart,
}
#[derive(Clone,Copy,Debug,PartialEq)]
pub enum AudioTest { Record, Stop, Play, Clear }
#[derive(Clone,Copy,Debug,PartialEq)]
pub enum UpdateAction { Check, Download, Install, Cancel, OpenRelease }
#[derive(Clone,Debug,PartialEq)]
pub enum Operation {
Navigate(Navigation), Reload(Category),
IdentityCreate, IdentityDefault(String), IdentityDelete(String), IdentityImport, IdentityExport(String), IdentityCopyUid(String), IdentityImprove(String), IdentityCancelImprove(String),
RemoveTrustedHost(String), ClearTrustedHosts, ResetConfirmations,
ThemeSelect(Option<String>), ThemePreview(String), ThemeReload, ThemeInstall, ThemeOpenDirectory(Option<String>), ThemeLink{identifier:String,kind:String},
SelectDevice{kind:DeviceKind,id:String}, MapDevice{kind:DeviceKind,legacy:String,native:String}, NewDevice{kind:DeviceKind,native:String},
CopyDspToTemplate{kind:DeviceKind,device:String}, ApplyDspTemplate{kind:DeviceKind,device:String},
AudioTest(AudioTest), CapturePtt,
KeyProfileCreate, KeyProfileActivate(String), KeyProfileDelete(String),
KeyCapture{profile:String,binding:Option<String>,action:KeyAction,target:String}, KeyCaptureDone, KeyCaptureCancel, KeyRemove{profile:String,binding:String},
WhisperCreate, WhisperDelete(String), WhisperRemoveEntry{list:String,entry:WhisperEntry}, WhisperAddEntry{list:String,key:SessionKey,entry:WhisperEntry},
WhisperPickServer{list:String,key:SessionKey,uid:String,name:String}, WhisperPickGroup{list:String,key:SessionKey,id:String,name:String}, WhisperOverlay(SessionKey),
RemoveIgnoredUser(String), PreviewNotification(String),
ChooseDownloadDirectory, CopyDownloadDirectory, ChooseRecordingDirectory,
CopyText(String), PreviewMarkup(String),
Update(UpdateAction), OpenLogs, OpenProject, OpenIssues, Relaunch,
}
#[derive(Debug)]
pub enum SettingsAction {
Edit{field:Field,value:SettingValue}, Invoke(Operation),
SaveSecret{binding:SecretBinding,secret:SecretString},
/// Platform physical key bridge owns the recorder; text input is never treated as a physical keycode.
CaptureFocusLost,
}
#[derive(Clone,Debug)]
pub struct IdentityView {pub uid:String,pub name:String,pub nickname:String,pub security_level:u8,pub is_default:bool,pub bookmarks:Vec<String>,pub progress:String,pub improving:bool}
#[derive(Clone,Debug)]
pub struct DeviceView {pub id:String,pub name:String,pub available:bool}
#[derive(Clone,Debug)]
pub struct MigrationDevice {pub kind:DeviceKind,pub legacy:String}
#[derive(Clone,Debug,Default)]
pub struct AudioView {pub inputs:Vec<DeviceView>,pub outputs:Vec<DeviceView>,pub migration:Vec<MigrationDevice>,pub status:String,pub test_status:String,pub recording:bool,pub playing:bool,pub has_sample:bool,pub input_level:f32}
#[derive(Clone,Debug,Default)]
pub struct VideoView {pub policy:String,pub backend:String,pub reception:String,pub codecs:Vec<String>,pub restart_required:bool}
#[derive(Clone,Debug)]
pub struct ThemeView {pub selection:String,pub identifier:String,pub name:String,pub description:String,pub warnings:Vec<String>,pub links:Vec<String>}
#[derive(Clone,Debug)]
pub struct GroupView {pub id:String,pub name:String}
#[derive(Clone,Debug)]
pub struct WhisperServer {pub key:SessionKey,pub uid:String,pub name:String,pub server_groups:Vec<GroupView>,pub channel_groups:Vec<GroupView>}
#[derive(Clone,Debug,Default)]
pub struct CaptureView {pub active:bool,pub chord:String,pub error:String}
#[derive(Clone,Debug,Default)]
pub struct Capability {pub supported:bool,pub enabled:bool,pub reason:String}
#[derive(Clone,Debug,Default)]
pub struct OsView {pub autostart:Capability,pub taskbar:Capability,pub flash:Capability,pub lock_mute:Capability,pub global_hotkeys:Capability}
#[derive(Clone,Debug,Default)]
pub struct AboutView {pub version:String,pub build:Vec<(String,String)>,pub update_status:String,pub update_actions:Vec<UpdateAction>,pub changelog:Vec<(String,String)>,pub licenses:Vec<(String,String)>,pub license_text:Option<(String,String)>,pub diagnostics:Vec<(String,String)>}
#[derive(Clone,Debug,Default)]
pub struct SettingsSnapshot {
pub loaded:bool, pub prefs:Value, pub identities:Vec<IdentityView>,pub audio:AudioView,pub video:VideoView,
pub keybinds:Option<KeybindState>,pub key_read_only:bool,pub key_conflicts:HashMap<String,String>,pub key_status:String,pub capture:CaptureView,
pub whispers:Option<WhisperState>,pub servers:Vec<WhisperServer>,pub input_session:Option<SessionKey>,pub pending_whisper:Option<(SessionKey,WhisperEntry)>,pub whisper_targets:Vec<(String,String)>,
pub files:Option<FileSettingsValue>,pub download_location:String,pub recording_location:String,
pub themes:Vec<ThemeView>,pub theme_warnings:Vec<String>,pub theme_preview:Option<String>,
pub os:OsView,pub about:AboutView,pub status:String,pub error:String,
/// Exact stable row IDs currently being persisted; errors and previous values remain visible.
pub pending:Vec<String>, pub row_errors:BTreeMap<String,String>,
pub rich_documents:std::sync::Arc<HashMap<String,std::sync::Arc<crate::ui::chat::prepared::PreparedDocument>>>,
}
#[derive(Clone,Debug)]
pub enum Intent { None, Edit(Field), Invoke(Operation), Select(Vec<Operation>), Secret(SecretBinding) }
#[derive(Clone,Debug)]
pub enum Control { Heading, Note, Toggle(bool), Choice{options:Vec<(String,String)>,selected:usize}, Text(String), Number{value:f64,min:f64,max:f64,step:f64}, Action, Meter(f32), Secret, Rich{source:String,document:std::sync::Arc<crate::ui::chat::prepared::PreparedDocument>} }
#[derive(Clone,Debug)]
pub struct Row {pub id:String,pub title:String,pub subtitle:String,pub control:Control,pub intent:Intent,pub enabled:bool,pub destructive:bool,pub inset:bool,pub error:String}
#[derive(Clone,Debug)]
pub struct Presentation {pub category:Category,pub title:String,pub categories:Vec<String>,pub category_groups:Vec<String>,pub rows:Vec<Row>,pub panel_open:bool,pub subpage:bool,pub show_slint:bool,pub status:String,pub error:String,pub back:String,pub apply:String,pub cancel:String,pub loading:bool,pub capturing:bool,pub decrease_template:String,pub increase_template:String}
//! Typed settings intents. All mutations are requests; only service acknowledgements change snapshots.
use crate::app::connections::SessionKey;
use crate::services::{file_settings::FileSettingsValue, keybinds::{Action as KeyAction, KeybindState}, prefs::DeviceKind, secrets::{SecretBinding, SecretString}, whisper::{WhisperEntry, WhisperState}};
use serde_json::Value;
use std::collections::{BTreeMap, HashMap};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Category { #[default] Identities, Privacy, Appearance, Audio, Video, KeyBindings, Chats, Whispers, Notifications, FileTransfer, OsSpecific, About }
impl Category {
pub const ALL: [Self; 12] = [Self::Identities,Self::Privacy,Self::Appearance,Self::Audio,Self::Video,Self::KeyBindings,Self::Chats,Self::Whispers,Self::Notifications,Self::FileTransfer,Self::OsSpecific,Self::About];
pub fn key(self)->&'static str {match self {Self::Identities=>"settings.nav.identities",Self::Privacy=>"settings.privacy.title",Self::Appearance=>"ui.appearance",Self::Audio=>"ui.audio",Self::Video=>"ui.video",Self::KeyBindings=>"settings.nav.keybinds",Self::Chats=>"ui.chats",Self::Whispers=>"settings.nav.whispers",Self::Notifications=>"ui.layout.notifications",Self::FileTransfer=>"files.title",Self::OsSpecific=>"os.title",Self::About=>"settings.nav.about"}}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum Page { #[default] Root, TrustedHosts, PrivacyDetails, Themes, Palette, AudioProfiles, DeviceMigration, VideoDetails, MarkdownHelp, Changelog, Licenses, License(String), Diagnostics }
#[derive(Clone, Debug)]
pub struct ViewState {
pub category: Category, pub pages: Vec<Page>, pub panel_open: bool,
pub identity: Option<String>, pub key_profile: Option<String>, pub whisper_list: Option<String>,
pub input_profile: Option<String>, pub output_profile: Option<String>,
pub preview_theme: Option<String>, pub whisper_preview: bool,
}
impl Default for ViewState {
fn default()->Self {Self{category:Category::Identities,pages:Vec::new(),panel_open:false,identity:None,key_profile:None,whisper_list:None,input_profile:None,output_profile:None,preview_theme:None,whisper_preview:true}}
}
impl ViewState {
pub fn page(&self)->Page {self.pages.last().cloned().unwrap_or_default()}
/// Navigation is presentation-only. Returning false means the shell should close settings.
pub fn navigate(&mut self, navigation:&Navigation)->bool {
match navigation {
Navigation::Category(c)=>{self.category=*c;self.pages.clear();self.panel_open=true;},
Navigation::Page(p)=>{self.pages.push(p.clone());self.panel_open=true;},
Navigation::Back=>{if self.pages.pop().is_none(){if self.panel_open {self.panel_open=false;}else{return false;}}},
Navigation::Identity(id)=>self.identity=Some(id.clone()),
Navigation::KeyProfile(id)=>self.key_profile=Some(id.clone()),
Navigation::WhisperList(id)=>self.whisper_list=Some(id.clone()),
Navigation::DspProfile{kind,id}=>match kind{DeviceKind::Input=>self.input_profile=Some(id.clone()),DeviceKind::Output=>self.output_profile=Some(id.clone()),DeviceKind::Notification=>{}},
Navigation::WhisperPreview(v)=>self.whisper_preview=*v,
} true
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Navigation { Category(Category), Page(Page), Back, Identity(String), KeyProfile(String), WhisperList(String), DspProfile{kind:DeviceKind,id:String}, WhisperPreview(bool) }
macro_rules! preferences {($($variant:ident => $key:literal),+ $(,)?)=>{
#[derive(Clone,Copy,Debug,PartialEq,Eq,Hash)] pub enum Preference {$($variant),+}
impl Preference {pub fn key(self)->&'static str {match self {$(Self::$variant=>$key),+}}}
};}
preferences! {
Theme=>"theme", DisplaySize=>"displaySize", TreeStyle=>"treeStyle", ChatStyle=>"chatStyle", SidebarIconMode=>"sidebarIconMode", Language=>"language",
ShowBadges=>"showBadges", ShowCountryFlags=>"showCountryFlags", HighlightContacts=>"highlightContacts", ShowClientsBeforeChannels=>"showClientsBeforeChannels", ShowChannelBanners=>"showChannelBanners", ShowChannelBackground=>"showChannelBackground", ChannelCommanderAsLamp=>"channelCommanderAsLamp",
AllowWhitelistMalicious=>"allowWhitelistMalicious", PttEnabled=>"pttEnabled", OutputLevelDb=>"outputLevelDb", AutoEnableMicrophone=>"autoEnableMicrophone", AutoReactivateMicOnPreviousTarget=>"autoReactivateMicOnPreviousTarget", HardwareVideoDecode=>"hardwareVideoDecode",
ChatRichTextEditor=>"chatRichTextEditor", ChatToolbarVisibility=>"chatToolbarVisibility", ChatMermaidAutoload=>"chatMermaidAutoload", ChatOpenIncoming=>"chatOpenIncoming", ChatShowModerationEvents=>"chatShowModerationEvents", ChatUse24hTime=>"chatUse24hTime", AutoDownloadImages=>"autoDownloadImages",
ContactsSortAlphabetically=>"contactsSortAlphabetically", ContactsShowOffline=>"contactsShowOffline", ContactsGroupOffline=>"contactsGroupOffline",
NotificationLevelDb=>"notificationLevelDb", SystemNotifyServerPrivate=>"systemNotifyServerPrivate", SystemNotifyChannelChat=>"systemNotifyChannelChat",
OsFlashOnMessage=>"osFlashOnMessage", OsFlashOnPoke=>"osFlashOnPoke", OsHideInTaskbar=>"osHideInTaskbar", OsMuteWhenLocked=>"osMuteWhenLocked", UpdateChannel=>"updateChannel", RecordingMode=>"recordingMode"
}
#[derive(Clone,Debug,PartialEq)]
pub enum SettingValue { Bool(bool), Number(f64), Text(String) }
impl SettingValue {
pub fn json(&self)->Value {match self {Self::Bool(v)=>(*v).into(),Self::Number(v)=>serde_json::json!(v),Self::Text(v)=>v.clone().into()}}
pub fn text(&self)->String {match self {Self::Bool(v)=>v.to_string(),Self::Number(v)=>v.to_string(),Self::Text(v)=>v.clone()}}
}
#[derive(Clone,Copy,Debug,PartialEq,Eq)]
pub enum DspField { Agc, Denoise, DenoiseLevel, Typing, Vad, VadMode, VadLevel, VadSensitivity, Aec, ComfortNoise, ComfortNoiseLevel, EchoReduction }
impl DspField {pub fn key(self)->&'static str {match self{Self::Agc=>"agc",Self::Denoise=>"denoise",Self::DenoiseLevel=>"denoiseLevel",Self::Typing=>"typing",Self::Vad=>"vad",Self::VadMode=>"vadMode",Self::VadLevel=>"vadLevel",Self::VadSensitivity=>"vadSensitivity",Self::Aec=>"aec",Self::ComfortNoise=>"comfortNoise",Self::ComfortNoiseLevel=>"comfortNoiseLevel",Self::EchoReduction=>"echoReduction"}}}
#[derive(Clone,Debug,PartialEq)]
pub enum DspTarget { Template, Device(String) }
#[derive(Clone,Copy,Debug,PartialEq)]
pub enum FileField { AlwaysAsk, LimitUpload, LimitDownload, UploadMiB, DownloadMiB, UploadSlots, DownloadSlots }
#[derive(Clone,Copy,Debug,PartialEq)]
pub enum WhisperField { Name, Kind, GroupType, GroupTargetMode, ServerUid, GroupId }
#[derive(Clone,Debug,PartialEq)]
pub enum PaletteColor { Accent, Background, Surface, Foreground }
impl PaletteColor {pub const ALL:[Self;4]=[Self::Accent,Self::Background,Self::Surface,Self::Foreground];pub fn key(&self)->&'static str {match self{Self::Accent=>"accent",Self::Background=>"background",Self::Surface=>"surface",Self::Foreground=>"foreground"}}}
#[derive(Clone,Copy,Debug,PartialEq)]
pub enum PalettePreset { Ts6, Graphite, Light }
impl PalettePreset {pub fn key(self)->&'static str {match self{Self::Ts6=>"ts6",Self::Graphite=>"graphite",Self::Light=>"light"}}}
#[derive(Clone,Debug,PartialEq)]
pub enum Field {
Preference(Preference), Device(DeviceKind), PttReleaseDelay,
Palette(PaletteColor),
Dsp {kind:DeviceKind,target:DspTarget,field:DspField},
IdentityName(String), IdentityNickname(String), IdentityTarget(String), NewIdentityName,
KeyExact, KeyProfileName(String), NewKeyProfileName,
KeyBindingAction{profile:String,binding:String}, KeyBindingTarget{profile:String,binding:String}, KeyBindingGlobal{profile:String,binding:String},
WhisperReceive, Whisper {list:String,field:WhisperField}, NewWhisperName,
NotificationState(String), NotificationGroup(String), NotificationAdvanced(String),
File(FileField), Autostart,
}
#[derive(Clone,Copy,Debug,PartialEq)]
pub enum AudioTest { Record, Stop, Play, Clear }
#[derive(Clone,Copy,Debug,PartialEq)]
pub enum UpdateAction { Check, Download, Install, Cancel, OpenRelease }
#[derive(Clone,Debug,PartialEq)]
pub enum Operation {
Navigate(Navigation), Reload(Category),
IdentityCreate, IdentityDefault(String), IdentityDelete(String), IdentityImport, IdentityExport(String), IdentityCopyUid(String), IdentityImprove(String), IdentityCancelImprove(String),
RemoveTrustedHost(String), ClearTrustedHosts, ResetConfirmations,
ThemeSelect(Option<String>), ThemePreview(String), ThemeReload, ThemeInstall, ThemeOpenDirectory(Option<String>), ThemeLink{identifier:String,kind:String},
PalettePreset(PalettePreset), PaletteSave, PaletteCancel,
SelectDevice{kind:DeviceKind,id:String}, MapDevice{kind:DeviceKind,legacy:String,native:String}, NewDevice{kind:DeviceKind,native:String},
CopyDspToTemplate{kind:DeviceKind,device:String}, ApplyDspTemplate{kind:DeviceKind,device:String},
AudioTest(AudioTest), CapturePtt,
KeyProfileCreate, KeyProfileActivate(String), KeyProfileDelete(String),
KeyCapture{profile:String,binding:Option<String>,action:KeyAction,target:String}, KeyCaptureDone, KeyCaptureCancel, KeyRemove{profile:String,binding:String},
WhisperCreate, WhisperDelete(String), WhisperRemoveEntry{list:String,entry:WhisperEntry}, WhisperAddEntry{list:String,key:SessionKey,entry:WhisperEntry},
WhisperPickServer{list:String,key:SessionKey,uid:String,name:String}, WhisperPickGroup{list:String,key:SessionKey,id:String,name:String}, WhisperOverlay(SessionKey),
RemoveIgnoredUser(String), PreviewNotification(String),
ChooseDownloadDirectory, CopyDownloadDirectory, ChooseRecordingDirectory,
CopyText(String), PreviewMarkup(String),
Update(UpdateAction), OpenLogs, OpenProject, OpenIssues, Relaunch,
}
#[derive(Debug)]
pub enum SettingsAction {
Edit{field:Field,value:SettingValue}, Invoke(Operation),
SaveSecret{binding:SecretBinding,secret:SecretString},
/// Platform physical key bridge owns the recorder; text input is never treated as a physical keycode.
CaptureFocusLost,
}
#[derive(Clone,Debug)]
pub struct IdentityView {pub uid:String,pub name:String,pub nickname:String,pub security_level:u8,pub is_default:bool,pub bookmarks:Vec<String>,pub progress:String,pub improving:bool}
impl IdentityView {
/// Onboarded/legacy identities can have a nickname but no separate display name.
/// This fallback never rewrites the stored identity name or key.
pub fn display_name<'a>(&'a self, fallback:&'a str)->&'a str {
[self.name.as_str(),self.nickname.as_str()].into_iter().map(str::trim).find(|name|!name.is_empty()).unwrap_or(fallback)
}
}
#[derive(Clone,Debug)]
pub struct DeviceView {pub id:String,pub name:String,pub available:bool}
#[derive(Clone,Debug)]
pub struct MigrationDevice {pub kind:DeviceKind,pub legacy:String}
#[derive(Clone,Debug,Default)]
pub struct AudioView {pub inputs:Vec<DeviceView>,pub outputs:Vec<DeviceView>,pub migration:Vec<MigrationDevice>,pub status:String,pub test_status:String,pub recording:bool,pub playing:bool,pub has_sample:bool,pub input_level:f32,
#[cfg(any(target_os="android",test))]
pub communication_outputs:Option<Vec<(String,i32)>>,
}
#[derive(Clone,Debug,Default)]
pub struct VideoView {pub policy:String,pub backend:String,pub reception:String,pub codecs:Vec<String>,pub restart_required:bool}
#[derive(Clone,Debug)]
pub struct ThemeView {pub selection:String,pub identifier:String,pub name:String,pub description:String,pub warnings:Vec<String>,pub links:Vec<String>}
#[derive(Clone,Debug)]
pub struct GroupView {pub id:String,pub name:String}
#[derive(Clone,Debug)]
pub struct WhisperServer {pub key:SessionKey,pub uid:String,pub name:String,pub server_groups:Vec<GroupView>,pub channel_groups:Vec<GroupView>}
#[derive(Clone,Debug,Default)]
pub struct CaptureView {pub active:bool,pub chord:String,pub error:String}
#[derive(Clone,Debug,Default)]
pub struct Capability {pub supported:bool,pub enabled:bool,pub reason:String}
#[derive(Clone,Debug,Default)]
pub struct OsView {pub autostart:Capability,pub taskbar:Capability,pub flash:Capability,pub lock_mute:Capability,pub global_hotkeys:Capability}
#[derive(Clone,Debug,Default)]
pub struct AboutView {pub version:String,pub build:Vec<(String,String)>,pub update_status:String,pub update_actions:Vec<UpdateAction>,pub changelog:Vec<(String,String)>,pub licenses:Vec<(String,String)>,pub license_text:Option<(String,String)>,pub diagnostics:Vec<(String,String)>}
#[derive(Clone,Debug,Default)]
pub struct SettingsSnapshot {
pub loaded:bool, pub prefs:Value, pub identities:Vec<IdentityView>,pub audio:AudioView,pub video:VideoView,
pub keybinds:Option<KeybindState>,pub key_read_only:bool,pub key_conflicts:HashMap<String,String>,pub key_status:String,pub capture:CaptureView,
pub whispers:Option<WhisperState>,pub servers:Vec<WhisperServer>,pub input_session:Option<SessionKey>,pub pending_whisper:Option<(SessionKey,WhisperEntry)>,pub whisper_targets:Vec<(String,String)>,
pub files:Option<FileSettingsValue>,pub download_location:String,pub recording_location:String,
pub themes:Vec<ThemeView>,pub theme_warnings:Vec<String>,pub theme_preview:Option<String>,
pub palette_draft:Option<Value>,
pub os:OsView,pub about:AboutView,pub status:String,pub error:String,
/// Exact stable row IDs currently being persisted; errors and previous values remain visible.
pub pending:Vec<String>, pub row_errors:BTreeMap<String,String>,
pub rich_documents:std::sync::Arc<HashMap<String,std::sync::Arc<crate::ui::chat::prepared::PreparedDocument>>>,
}
#[derive(Clone,Debug)]
pub enum Intent { None, Edit(Field), Invoke(Operation), Select(Vec<Operation>), Secret(SecretBinding) }
#[derive(Clone,Debug)]
pub enum Control { Heading, Note, Toggle(bool), Choice{options:Vec<(String,String)>,selected:usize}, Text(String), Color(String), Number{value:f64,min:f64,max:f64,step:f64}, Action, Meter(f32), Secret, Rich{source:String,document:std::sync::Arc<crate::ui::chat::prepared::PreparedDocument>} }
#[derive(Clone,Debug)]
pub struct Row {pub id:String,pub title:String,pub subtitle:String,pub control:Control,pub intent:Intent,pub enabled:bool,pub destructive:bool,pub inset:bool,pub error:String}
#[derive(Clone,Debug)]
pub struct Presentation {pub category:Category,pub title:String,pub categories:Vec<String>,pub category_subtitles:Vec<String>,pub profile_name:String,pub profile_label:String,pub category_groups:Vec<String>,pub rows:Vec<Row>,pub panel_open:bool,pub subpage:bool,pub show_slint:bool,pub status:String,pub error:String,pub back:String,pub apply:String,pub cancel:String,pub loading:bool,pub capturing:bool,pub decrease_template:String,pub increase_template:String}
+93 -26
View File
@@ -9,24 +9,33 @@ use std::{cell::RefCell, collections::BTreeMap, rc::Rc, sync::Arc};
struct Editor { form: Form, raw: BTreeMap<String,String>, dirty: BTreeMap<String,bool>, confirmation: String }
impl Editor {
fn new(form:Form)->Self { let raw=form.fields.iter().map(|f|(f.id.clone(),forms::value_text(&f.value))).collect(); Self {form,raw,dirty:BTreeMap::new(),confirmation:String::new()} }
fn merge(&mut self, form:Form) {
fn merge(&mut self, mut form:Form) {
if self.form.id!=form.id || self.form.target!=form.target || self.form.acknowledged_revision!=form.acknowledged_revision { *self=Self::new(form); return; }
for field in &form.fields { if !self.dirty.contains_key(&field.id) { self.raw.insert(field.id.clone(),forms::value_text(&field.value)); } }
// Presentation snapshots are not submission acknowledgements. Only complete() (or an
// explicit acknowledged revision) ends local busy/error state for this captured editor.
form.busy|=self.form.busy;
if form.error.is_empty(){form.error=self.form.error.clone();}
self.form=form;
}
fn complete(&mut self,result:Result<(),String>)->bool{
match result{Ok(())=>true,Err(error)=>{self.form.busy=false;self.form.error=error;false}}
}
}
struct State {
presentation:ShellPresentation,
targets:BTreeMap<String,Target>, actions:BTreeMap<String,Action>, contexts:BTreeMap<String,Vec<Action>>,
editor:Option<Editor>, stack:Vec<Target>, destination:Destination,
room_page:i32, room_history:Vec<i32>,
fields:Rc<VecModel<ShellField>>, tree:Rc<VecModel<ShellRow>>, bookmarks:Rc<VecModel<ShellRow>>, contacts:Rc<VecModel<ShellRow>>, entries:Rc<VecModel<ShellRow>>,
participants:Rc<VecModel<ShellRow>>,
held_target:Option<Target>, menu_target:Option<Target>,
press_epoch:u64, pressed_row:Option<String>, suppress_click:Option<String>,
selection_actions:bool,
popouts:BTreeMap<String,(Target,crate::StreamWindow)>,
}
impl Default for State {
fn default()->Self { Self {presentation:ShellPresentation::default(),targets:BTreeMap::new(),actions:BTreeMap::new(),contexts:BTreeMap::new(),editor:None,stack:vec![],destination:Destination::Servers,fields:Rc::new(VecModel::default()),tree:Rc::new(VecModel::default()),bookmarks:Rc::new(VecModel::default()),contacts:Rc::new(VecModel::default()),entries:Rc::new(VecModel::default()),held_target:None,menu_target:None,press_epoch:0,pressed_row:None,suppress_click:None,selection_actions:false,popouts:BTreeMap::new()} }
fn default()->Self { Self {presentation:ShellPresentation::default(),targets:BTreeMap::new(),actions:BTreeMap::new(),contexts:BTreeMap::new(),editor:None,stack:vec![],destination:Destination::Servers,room_page:0,room_history:vec![],participants:Rc::new(VecModel::default()),fields:Rc::new(VecModel::default()),tree:Rc::new(VecModel::default()),bookmarks:Rc::new(VecModel::default()),contacts:Rc::new(VecModel::default()),entries:Rc::new(VecModel::default()),held_target:None,menu_target:None,press_epoch:0,pressed_row:None,suppress_click:None,selection_actions:false,popouts:BTreeMap::new()} }
}
pub struct ShellBinding { state:Rc<RefCell<State>>, emit:Arc<dyn Fn(ShellAction)+Send+Sync> }
fn strings(values:impl IntoIterator<Item=String>)->ModelRc<SharedString> { ModelRc::new(VecModel::from(values.into_iter().map(Into::into).collect::<Vec<_>>())) }
@@ -35,10 +44,10 @@ fn command(action:&Action,id:String)->ShellCommand { ShellCommand{id:id.into(),l
fn commands(state:&mut State, scope:&str, actions:&[Action])->ModelRc<ShellCommand> {
model(actions.iter().enumerate().map(|(index,a)|{let id=format!("{scope}/{index}/{}",a.id);state.actions.insert(id.clone(),a.clone());command(a,id)}).collect())
}
fn rows(state:&mut State, scope:&str, entries:&[Entry])->Vec<ShellRow> {
fn rows(state:&mut State, scope:&str, entries:&[Entry], catalog:super::i18n::Catalog)->Vec<ShellRow> {
entries.iter().map(|entry| {
let id=format!("{scope}/{}",entry.id); state.targets.insert(id.clone(),entry.target.clone()); state.contexts.insert(id.clone(),entry.actions.clone());
ShellRow{id:id.into(),title:entry.title.clone().into(),subtitle:entry.subtitle.clone().into(),depth:entry.depth.min(24) as i32,selected:entry.selected,expanded:entry.expanded,expandable:entry.expandable,talking:entry.talking,muted:entry.muted,unread:if entry.unread==0 {"".into()}else{entry.unread.to_string().into()}}
ShellRow{id:id.into(),title:entry.title.clone().into(),subtitle:entry.subtitle.clone().into(),depth:entry.depth.min(24) as i32,selected:entry.selected,expanded:entry.expanded,expandable:entry.expandable,talking:entry.talking,muted:entry.muted,unread:if entry.unread==0 {"".into()}else{entry.unread.to_string().into()},disclosure:if cfg!(target_os="android") && entry.expandable{catalog.format(if entry.expanded{"message.collapse.channel.members"}else{"message.expand.channel.members"},&[("p0",entry.title.as_str())]).into()}else{SharedString::default()}}
}).collect()
}
/// Preserve model identity and update only changed rows, including insert/remove positions.
@@ -58,9 +67,11 @@ fn projected_field(field:&Field,raw:&str)->ShellField {
}
fn project_editor(ui:&AppWindow,state:&mut State) {
let bridge=ui.global::<DialogBridge>();
let Some(editor)=&state.editor else {bridge.set_visible(false);return};
let Some(editor)=&state.editor else {bridge.set_visible(false);bridge.set_busy(false);bridge.set_has_advanced(false);return};
let c=state.presentation.catalog;
bridge.set_visible(true);bridge.set_title(editor.form.title.clone().into());bridge.set_description(editor.form.description.clone().into());
bridge.set_onboarding(editor.form.operation==Operation::CreateProfile);
bridge.set_has_advanced(editor.form.fields.iter().any(|field|field.advanced));
bridge.set_error(editor.form.error.clone().into());bridge.set_busy(editor.form.busy);bridge.set_destructive(editor.form.destructive);
bridge.set_submit_label(editor.form.submit_label.clone().into());bridge.set_cancel_label(c.text("native.action.cancel").into());bridge.set_advanced_label(c.text("native.form.advanced").into());bridge.set_loading_label(c.text("native.status.loading").into());
bridge.set_confirmation_label(editor.form.confirmation.as_ref().map(|target|c.format("native.form.confirm",&[("target",target)])).unwrap_or_default().into());
@@ -85,18 +96,42 @@ fn opens_detail(operation:Operation)->bool {
matches!(operation,Operation::ServerInfo|Operation::ServerClients|Operation::ServerLog|Operation::ServerBans|Operation::ServerKeys|Operation::ServerPasswords|Operation::ServerPermissions|Operation::TalkQueue|Operation::ChannelInfo|Operation::ClientInfo|Operation::ClientConnectionInfo|Operation::ClientPermissions|Operation::GroupPermissions|Operation::FileBrowse|Operation::FileRefresh|Operation::TransferList|Operation::RecordingOpen|Operation::ServerIcons|Operation::WhisperHistory)
}
fn room_destination(page:i32)->Destination { match page {2=>Destination::Chats,3=>Destination::Settings,4=>Destination::Contacts,_=>Destination::Servers} }
fn room_navigate(ui:&AppWindow,state:&mut State,emit:&Arc<dyn Fn(ShellAction)+Send+Sync>,page:i32) {
if !(0..=6).contains(&page){return}
release_hold(state,emit);
if page>=4 {state.room_history.push(state.room_page);}else{state.room_history.clear();}
state.room_page=page;state.destination=room_destination(page);state.stack.clear();state.selection_actions=false;
let bridge=ui.global::<ShellBridge>();bridge.set_room_page(page);bridge.set_destination(destination_index(state.destination));bridge.set_depth(0);bridge.set_stage(0);bridge.set_menu_visible(false);
if page==2 && !state.presentation.room.chat_id.is_empty(){ui.global::<crate::ChatBridge>().invoke_choose_tab(state.presentation.room.chat_id.clone().into());}
emit(ShellAction::Back);emit(ShellAction::Navigate(state.destination));
if matches!(page,0|2){if let Some(target)=&state.presentation.room.target{emit(ShellAction::Select(target.clone()));}}
}
pub fn bind(ui:&AppWindow,emit:Arc<dyn Fn(ShellAction)+Send+Sync>)->ShellBinding {
let state=Rc::new(RefCell::new(State::default()));
{
let s=state.borrow();let b=ui.global::<ShellBridge>();
b.set_tree(s.tree.clone().into());b.set_bookmarks(s.bookmarks.clone().into());b.set_contacts(s.contacts.clone().into());b.set_entries(s.entries.clone().into());ui.global::<DialogBridge>().set_fields(s.fields.clone().into());
b.set_participants(s.participants.clone().into());
}
let b=ui.global::<ShellBridge>();
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_navigate(move|index|{let destination=match index{1=>Destination::Chats,2=>Destination::Contacts,3=>Destination::Settings,_=>Destination::Servers};let mut s=s.borrow_mut();release_hold(&mut s,&e);s.destination=destination;s.stack.clear();if let Some(ui)=weak.upgrade(){ui.global::<ShellBridge>().set_destination(destination_index(destination));ui.global::<ShellBridge>().set_depth(0);}e(ShellAction::Navigate(destination));});}
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_room_navigate(move|page|{if let Some(ui)=weak.upgrade(){room_navigate(&ui,&mut s.borrow_mut(),&e,page);}});}
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_navigate(move|index|{
let mut s=s.borrow_mut();
if cfg!(target_os="android") {
if let Some(ui)=weak.upgrade(){room_navigate(&ui,&mut s,&e,match index{1=>2,2=>4,3=>3,_=>0});}
return;
}
let destination=match index{1=>Destination::Chats,2=>Destination::Contacts,3=>Destination::Settings,_=>Destination::Servers};
release_hold(&mut s,&e);s.destination=destination;s.stack.clear();
if let Some(ui)=weak.upgrade(){ui.global::<ShellBridge>().set_destination(destination_index(destination));ui.global::<ShellBridge>().set_depth(0);}
e(ShellAction::Navigate(destination));
});}
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_back(move||{if let Some(ui)=weak.upgrade(){back(&ui,&mut s.borrow_mut(),&e);}});}
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();ui.on_back_requested(move||{if let Some(ui)=weak.upgrade(){back(&ui,&mut s.borrow_mut(),&e);}});}
{let s=state.clone();let e=emit.clone();ui.on_focus_lost(move||{let mut s=s.borrow_mut();release_hold(&mut s,&e);if cfg!(target_os="android"){s.press_epoch=s.press_epoch.wrapping_add(1);s.pressed_row=None;}});}
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_select(move|id|{let mut s=s.borrow_mut();if s.suppress_click.take().as_deref()==Some(id.as_str()){return}if let Some(target)=s.targets.get(id.as_str()).cloned(){if matches!(target.entity,Entity::Connection){s.stack.clear();s.selection_actions=false;}else{if !cfg!(target_os="android") || s.stack.last()!=Some(&target){s.stack.push(target.clone());}s.selection_actions=cfg!(target_os="android");}if let Some(ui)=weak.upgrade(){let b=ui.global::<ShellBridge>();b.set_depth(s.stack.len() as i32);if cfg!(target_os="android"){b.set_stage(0);}}e(ShellAction::Select(target));}});}
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_select(move|id|{let mut s=s.borrow_mut();if s.suppress_click.take().as_deref()==Some(id.as_str()){return}if cfg!(target_os="android"){release_hold(&mut s,&e);}if let Some(target)=s.targets.get(id.as_str()).cloned(){if matches!(target.entity,Entity::Connection){s.stack.clear();s.selection_actions=false;}else{if !cfg!(target_os="android") || s.stack.last()!=Some(&target){s.stack.push(target.clone());}s.selection_actions=cfg!(target_os="android");}if let Some(ui)=weak.upgrade(){let b=ui.global::<ShellBridge>();b.set_depth(s.stack.len() as i32);if cfg!(target_os="android"){b.set_stage(0);}}e(ShellAction::Select(target));}});}
{let s=state.clone();let e=emit.clone();b.on_expand(move|id|{if let Some(target)=s.borrow().targets.get(id.as_str()).cloned(){e(ShellAction::Expand(target));}});}
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_context(move|id|{let mut s=s.borrow_mut();let Some(target)=s.targets.get(id.as_str()).cloned()else{return};if cfg!(target_os="android"){release_hold(&mut s,&e);}let actions=s.contexts.get(id.as_str()).cloned().unwrap_or_default();s.menu_target=Some(target.clone());if let Some(ui)=weak.upgrade(){let b=ui.global::<ShellBridge>();b.set_menu_title(target.name.clone().into());b.set_menu_actions(commands(&mut s,"context",&actions));b.set_menu_visible(true);}e(ShellAction::Context(target));});}
{
@@ -141,7 +176,7 @@ pub fn bind(ui:&AppWindow,emit:Arc<dyn Fn(ShellAction)+Send+Sync>)->ShellBinding
}
}
});}
{let s=state.clone();let e=emit.clone();b.on_voice(move|kind|{if let Some(v)=&s.borrow().presentation.voice{e(ShellAction::Invoke{target:v.target.clone(),operation:if kind==0{Operation::ToggleMicrophone}else{Operation::ToggleDeafen}});}});}
{let s=state.clone();let e=emit.clone();b.on_voice(move|kind|{let mut state=s.borrow_mut();if cfg!(target_os="android"){release_hold(&mut state,&e);}if let Some(v)=&state.presentation.voice{e(ShellAction::Invoke{target:v.target.clone(),operation:if kind==0{Operation::ToggleMicrophone}else{Operation::ToggleDeafen}});}});}
{let s=state.clone();let e=emit.clone();b.on_held(move|held|{let mut s=s.borrow_mut();if !held{release_hold(&mut s,&e);}else if s.held_target.is_none(){if let Some(v)=s.presentation.voice.as_ref().filter(|v|v.ptt_enabled){let target=v.target.clone();s.held_target=Some(target.clone());e(ShellAction::PushToTalk{target,held:true});}}});}
{let s=state.clone();let e=emit.clone();b.on_search_edited(move|query|{if let Some(target)=&s.borrow().presentation.detail.search_target{e(ShellAction::Search{target:target.clone(),query:query.to_string()});}});}
{let s=state.clone();let e=emit.clone();b.on_page(move|next|{let s=s.borrow();let d=&s.presentation.detail;if let Some(target)=&d.search_target{e(ShellAction::Page{target:target.clone(),offset:if next{d.page_offset.saturating_add(d.page_size)}else{d.page_offset.saturating_sub(d.page_size)}});}});}
@@ -160,19 +195,28 @@ fn back(ui:&AppWindow,state:&mut State,emit:&Arc<dyn Fn(ShellAction)+Send+Sync>)
if ui.global::<ShellBridge>().get_menu_visible(){ui.global::<ShellBridge>().set_menu_visible(false);return}
if !ui.global::<ShellBridge>().get_fullscreen_stream().is_empty(){ui.global::<ShellBridge>().set_fullscreen_stream("".into());return}
if let Some(editor)=state.editor.take(){emit(ShellAction::Cancel{editor_id:editor.form.id,target:editor.form.target});project_editor(ui,state);return}
if cfg!(target_os="android") && ui.global::<crate::ChatBridge>().get_mobile_overlay(){ui.global::<crate::ChatBridge>().set_mobile_overlay(false);return}
if cfg!(target_os="android") && state.destination==Destination::Settings{
let settings=ui.global::<crate::SettingsBridge>();
if settings.get_capturing(){settings.invoke_capture_lost();return}
if settings.get_panel_open() || settings.get_subpage(){settings.invoke_back();return}
}
let previous=state.destination;
state.stack.pop();if state.stack.is_empty(){state.destination=Destination::Servers;}
if cfg!(target_os="android"){state.selection_actions=!state.stack.is_empty();}
ui.global::<ShellBridge>().set_depth(state.stack.len() as i32);ui.global::<ShellBridge>().set_destination(destination_index(state.destination));emit(ShellAction::Back);
if cfg!(target_os="android"){
if previous!=state.destination{emit(ShellAction::Navigate(state.destination));}
if let Some(target)=state.stack.last(){emit(ShellAction::Select(target.clone()));}
if cfg!(target_os="android") && state.stack.is_empty() {
if let Some(page)=state.room_history.pop(){state.room_page=page;}else if state.room_page!=0{state.room_page=0;}else{emit(ShellAction::Back);return}
state.destination=room_destination(state.room_page);
let bridge=ui.global::<ShellBridge>();bridge.set_room_page(state.room_page);bridge.set_destination(destination_index(state.destination));bridge.set_stage(0);
emit(ShellAction::Back);emit(ShellAction::Navigate(state.destination));return
}
state.stack.pop();
if cfg!(target_os="android") {
state.selection_actions=!state.stack.is_empty();
ui.global::<ShellBridge>().set_depth(state.stack.len() as i32);
emit(ShellAction::Back);
if let Some(target)=state.stack.last(){emit(ShellAction::Select(target.clone()));}
return
}
if state.stack.is_empty(){state.destination=Destination::Servers;}
ui.global::<ShellBridge>().set_depth(state.stack.len() as i32);ui.global::<ShellBridge>().set_destination(destination_index(state.destination));emit(ShellAction::Back);
}
fn destination_index(d:Destination)->i32{match d{Destination::Servers=>0,Destination::Chats=>1,Destination::Contacts=>2,Destination::Settings=>3}}
fn submit(ui:&AppWindow,state:&mut State,emit:&Arc<dyn Fn(ShellAction)+Send+Sync>){
@@ -195,8 +239,8 @@ fn submit(ui:&AppWindow,state:&mut State,emit:&Arc<dyn Fn(ShellAction)+Send+Sync
project_editor(ui,state);
}
impl ShellBinding {
pub fn navigate(&self,ui:&AppWindow,destination:Destination){let mut state=self.state.borrow_mut();state.destination=destination;state.stack.clear();ui.global::<ShellBridge>().set_destination(destination_index(destination));ui.global::<ShellBridge>().set_depth(0);}
pub fn stream_effect(&self,ui:&AppWindow,target:&Target,popout:bool,close:bool)->Result<(),String>{let mut state=self.state.borrow_mut();let Some(stream)=state.presentation.streams.iter().find(|stream|&stream.target==target).cloned()else{return Ok(())};if close{if let Some((_,window))=state.popouts.remove(&stream.id){window.hide().map_err(|e|e.to_string())?;}if ui.global::<ShellBridge>().get_fullscreen_stream()==stream.id{ui.global::<ShellBridge>().set_fullscreen_stream("".into());}return Ok(())}if popout{open_popout(ui,&mut state,&stream)}else{ui.global::<ShellBridge>().set_fullscreen_stream(stream.id.into());Ok(())}}
pub fn navigate(&self,ui:&AppWindow,destination:Destination){let mut state=self.state.borrow_mut();if cfg!(target_os="android"){release_hold(&mut state,&self.emit);if state.destination!=destination{state.room_page=match destination{Destination::Servers=>0,Destination::Chats=>2,Destination::Contacts=>4,Destination::Settings=>3};state.room_history.clear();ui.global::<ShellBridge>().set_room_page(state.room_page);}}state.destination=destination;state.stack.clear();ui.global::<ShellBridge>().set_destination(destination_index(destination));ui.global::<ShellBridge>().set_depth(0);}
pub fn stream_effect(&self,ui:&AppWindow,target:&Target,popout:bool,close:bool)->Result<(),String>{let mut state=self.state.borrow_mut();if cfg!(target_os="android"){release_hold(&mut state,&self.emit);}let Some(stream)=state.presentation.streams.iter().find(|stream|&stream.target==target).cloned()else{return Ok(())};if close{if let Some((_,window))=state.popouts.remove(&stream.id){window.hide().map_err(|e|e.to_string())?;}if ui.global::<ShellBridge>().get_fullscreen_stream()==stream.id{ui.global::<ShellBridge>().set_fullscreen_stream("".into());}return Ok(())}if popout{open_popout(ui,&mut state,&stream)}else{ui.global::<ShellBridge>().set_fullscreen_stream(stream.id.into());Ok(())}}
pub fn update_frames(&self,ui:&AppWindow,frames:&[(String,slint::Image)]){let mut state=self.state.borrow_mut();let model=ui.global::<ShellBridge>().get_streams();for(id,image)in frames{if let Some(stream)=state.presentation.streams.iter_mut().find(|stream|stream.id==*id){stream.frame=image.clone();stream.has_frame=true;}for row in 0..model.row_count(){if let Some(mut stream)=model.row_data(row){if stream.id.as_str()==id{stream.frame=image.clone();stream.has_frame=true;model.set_row_data(row,stream.clone());if let Some((_,window))=state.popouts.get(id){window.set_item(stream);}break}}}}}
/// Call on the Slint event loop after runtime has coalesced a snapshot.
pub fn present(&self,ui:&AppWindow,p:ShellPresentation){
@@ -206,19 +250,31 @@ impl ShellBinding {
let b=ui.global::<ShellBridge>();let c=p.catalog;
let selected_detail=if cfg!(target_os="android") && s.selection_actions{
s.stack.last().map(|target|{
let actions=p.tree.iter().chain(&p.bookmarks).chain(&p.contacts).chain(&p.detail.entries).find(|entry|&entry.target==target).map(|entry|entry.actions.clone()).unwrap_or_default();
let actions=p.room.participants.iter().chain(&p.tree).chain(&p.bookmarks).chain(&p.contacts).chain(&p.detail.entries).find(|entry|&entry.target==target).map(|entry|entry.actions.clone()).unwrap_or_default();
Detail{title:target.name.clone(),actions,..Detail::default()}
})
}else{None};
let detail=selected_detail.as_ref().unwrap_or(&p.detail);
let tree=rows(&mut s,"tree",&p.tree);reconcile(&s.tree,tree);
let bookmarks=rows(&mut s,"bookmark",&p.bookmarks);reconcile(&s.bookmarks,bookmarks);
let contacts=rows(&mut s,"contact",&p.contacts);reconcile(&s.contacts,contacts);
let entries=rows(&mut s,"entry",&detail.entries);reconcile(&s.entries,entries);
let tree=rows(&mut s,"tree",&p.tree,c);reconcile(&s.tree,tree);
if cfg!(target_os="android") {let participants=rows(&mut s,"room",&p.room.participants,c);reconcile(&s.participants,participants);b.set_room_title(p.room.title.clone().into());b.set_room_server(p.room.server.clone().into());b.set_room_caption(c.format("native.room.members",&[("count",p.room.participants.len().to_string().as_str())]).into());b.set_room_destinations(strings(["native.room.room","native.room.channels","native.room.chat","native.room.profile"].map(|key|c.text(key))));b.set_room_labels(strings(["native.room.switch","native.room.open_chat","native.room.listening","native.room.speaking","native.room.microphone_on","native.room.microphone_off","native.room.sound_on","native.room.sound_off","native.room.disconnect","native.room.empty","native.room.streams","native.room.profile_settings"].map(|key|c.text(key))));}
let bookmarks=rows(&mut s,"bookmark",&p.bookmarks,c);reconcile(&s.bookmarks,bookmarks);
let contacts=rows(&mut s,"contact",&p.contacts,c);reconcile(&s.contacts,contacts);
let entries=rows(&mut s,"entry",&detail.entries,c);reconcile(&s.entries,entries);
let tabs=p.tabs.iter().enumerate().map(|(index,tab)|{let id=format!("tab/{index}");s.targets.insert(id.clone(),tab.target.clone());s.contexts.insert(id.clone(),tab.actions.clone());ShellTab{id:id.into(),title:tab.title.clone().into(),selected:tab.selected,microphone_owner:tab.microphone_owner,connected:tab.connected,unread:if tab.unread==0{"".into()}else{tab.unread.to_string().into()}}}).collect();b.set_tabs(model(tabs));
b.set_actions(commands(&mut s,"global",&p.actions));b.set_detail_actions(commands(&mut s,"detail",&detail.actions));
if cfg!(target_os="android") {
b.set_connection_names(strings(p.tabs.iter().map(|tab|tab.title.clone())));
b.set_selected_connection(p.tabs.iter().position(|tab|tab.selected).map_or(-1,|index|index as i32));
}
let global_commands=commands(&mut s,"global",&p.actions);
if cfg!(target_os="android") {
let primary=p.actions.iter().position(|action|action.operation==Operation::NewConnection).and_then(|index|global_commands.row_data(index)).unwrap_or_default();
b.set_primary_action(primary);
}
if cfg!(target_os="android") {let disconnect=p.voice.as_ref().and_then(|voice|p.tabs.iter().find(|tab|tab.target.session==voice.target.session)).and_then(|tab|tab.actions.iter().find(|action|action.operation==Operation::Disconnect)).cloned();b.set_room_disconnect(disconnect.map(|action|{s.actions.insert("room-disconnect".into(),action.clone());command(&action,"room-disconnect".into())}).unwrap_or_default());}
b.set_actions(global_commands);b.set_detail_actions(commands(&mut s,"detail",&detail.actions));
b.set_info(model(detail.rows.iter().map(|r|ShellInfo{label:r.label.clone().into(),value:r.value.clone().into()}).collect()));
let streams:Vec<ShellStream>=p.streams.iter().map(|v|ShellStream{id:v.id.clone().into(),title:v.title.clone().into(),status:v.status.clone().into(),frame:v.frame.clone(),has_frame:v.has_frame,volume:v.volume,actions:commands(&mut s,&format!("stream/{}",v.id),&v.actions)}).collect();
let streams:Vec<ShellStream>=p.streams.iter().map(|v|ShellStream{id:v.id.clone().into(),title:v.title.clone().into(),status:v.status.clone().into(),frame:v.frame.clone(),has_frame:v.has_frame,has_volume:v.actions.iter().any(|action|action.operation==Operation::StreamVolume && action.enabled),volume:v.volume,actions:commands(&mut s,&format!("stream/{}",v.id),&v.actions)}).collect();
if cfg!(target_os="android") {b.set_room_connected(p.room.target.is_some());b.set_room_streams(model(p.streams.iter().zip(&streams).filter(|(stream,_)|p.room.target.as_ref().is_some_and(|room|stream.target.session==room.session && stream.target.own_channel_id==room.own_channel_id)).map(|(_,stream)|stream.clone()).collect()));}
s.popouts.retain(|id,(target,window)|{if p.streams.iter().any(|v|v.id==*id&&v.target==*target){if let Some(stream)=streams.iter().find(|v|v.id.as_str()==id){window.set_item(stream.clone());}true}else{let _=window.hide();false}});
if !streams.iter().any(|stream|stream.id==b.get_fullscreen_stream()){b.set_fullscreen_stream("".into());}
b.set_streams(model(streams));
@@ -242,7 +298,9 @@ impl ShellBinding {
s.presentation=p;project_editor(ui,&mut s);
}
/// Explicit result for a captured submission, not a background snapshot. Failure retains edits.
pub fn complete(&self,ui:&AppWindow,id:&str,target:&Target,result:Result<(),String>){let mut s=self.state.borrow_mut();if let Some(editor)=&mut s.editor{if editor.form.id!=id||&editor.form.target!=target{return}match result{Ok(())=>s.editor=None,Err(error)=>{editor.form.busy=false;editor.form.error=error;}}}project_editor(ui,&mut s);}
pub fn complete(&self,ui:&AppWindow,id:&str,target:&Target,result:Result<(),String>){let mut s=self.state.borrow_mut();if let Some(editor)=&mut s.editor{if editor.form.id!=id||&editor.form.target!=target{return}if editor.complete(result){s.editor=None;}}project_editor(ui,&mut s);}
/// A terminal runtime failure is authoritative even when no form effect could be delivered.
pub(crate) fn failed(&self,ui:&AppWindow){let mut s=self.state.borrow_mut();s.editor=None;project_editor(ui,&mut s);}
pub fn release_holds(&self){release_hold(&mut self.state.borrow_mut(),&self.emit);}
}
impl Drop for ShellBinding{fn drop(&mut self){self.release_holds();}}
@@ -250,7 +308,7 @@ impl Drop for ShellBinding{fn drop(&mut self){self.release_holds();}}
fn open_popout(ui:&AppWindow,state:&mut State,stream:&Stream)->Result<(),String>{
if let Some((_,window))=state.popouts.get(&stream.id){return window.show().map_err(|error|error.to_string())}
let window=crate::StreamWindow::new().map_err(|error|error.to_string())?;
let item=ShellStream{id:stream.id.clone().into(),title:stream.title.clone().into(),status:stream.status.clone().into(),frame:stream.frame.clone(),has_frame:stream.has_frame,volume:stream.volume,actions:commands(state,&format!("stream/{}",stream.id),&stream.actions)};
let item=ShellStream{id:stream.id.clone().into(),title:stream.title.clone().into(),status:stream.status.clone().into(),frame:stream.frame.clone(),has_frame:stream.has_frame,has_volume:stream.actions.iter().any(|action|action.operation==Operation::StreamVolume && action.enabled),volume:stream.volume,actions:commands(state,&format!("stream/{}",stream.id),&stream.actions)};
window.set_item(item);
let bridge=window.global::<ShellBridge>();
bridge.set_label_stream_waiting(state.presentation.catalog.text("native.stream.waiting").into());
@@ -282,6 +340,15 @@ mod tests {
assert_eq!(editor.raw.get("name").map(String::as_str),Some(""));assert!(editor.dirty.is_empty());
}
#[test]
fn bootstrap_contract_pending_submission_and_failed_ack_survive_snapshots(){
let form=forms::form("onboarding",Operation::CreateProfile,Target::application(),&super::super::i18n::Catalog::default()).unwrap();
let mut editor=Editor::new(form.clone());editor.raw.insert("nickname".into(),"Retained User".into());editor.dirty.insert("nickname".into(),true);
editor.form.busy=true;editor.merge(form.clone());assert!(editor.form.busy,"a snapshot must not permit duplicate creation");
assert!(!editor.complete(Err("Profile saved; services failed".into())));
editor.merge(form);assert!(!editor.form.busy);assert_eq!(editor.form.error,"Profile saved; services failed");
assert_eq!(editor.raw["nickname"],"Retained User");
}
#[test]
fn compact_detail_navigation_only_reveals_read_views() {
for operation in [Operation::FileBrowse,Operation::FileRefresh,Operation::ChannelInfo,Operation::TransferList,Operation::ServerIcons] {
assert!(opens_detail(operation));
+7 -1
View File
@@ -118,12 +118,18 @@ pub struct Voice {
pub target: Target, pub title: String, pub muted: bool, pub deafened: bool,
pub transmitting: bool, pub ptt_enabled: bool, pub status: String,
}
/// Android's current room is independent of the tree's disclosure/selection state.
#[derive(Clone, Debug, Default)]
pub struct Room {
pub title: String, pub server: String, pub participants: Vec<Entry>, pub chat_id: String, pub target: Option<Target>,
}
#[derive(Clone, Debug)]
pub struct ShellPresentation {
pub catalog: Catalog, pub tabs: Vec<Tab>, pub tree: Vec<Entry>, pub bookmarks: Vec<Entry>, pub contacts: Vec<Entry>,
pub detail: Detail, pub actions: Vec<Action>, pub streams: Vec<Stream>, pub voice: Option<Voice>,
pub room: Room,
pub profile_form: Option<Form>, pub dialog: Option<Form>, pub status: String, pub error: String, pub loading: bool,
}
impl Default for ShellPresentation {
fn default() -> Self { Self { catalog: Catalog::default(), tabs: vec![], tree: vec![], bookmarks: vec![], contacts: vec![], detail: Detail::default(), actions: vec![], streams: vec![], voice: None, profile_form: None, dialog: None, status: String::new(), error: String::new(), loading: false } }
fn default() -> Self { Self { catalog: Catalog::default(), tabs: vec![], tree: vec![], bookmarks: vec![], contacts: vec![], detail: Detail::default(), actions: vec![], streams: vec![], voice: None, room: Room::default(), profile_form: None, dialog: None, status: String::new(), error: String::new(), loading: false } }
}
+50
View File
@@ -50,3 +50,53 @@ pub fn color(value:&cssparser_color::Color)->Option<slint::Color>{
if rgb.iter().any(|v|!v.is_finite())||!alpha.is_finite(){return None}
Some(slint::Color::from_argb_u8((alpha.clamp(0.,1.)*255.).round() as u8,(rgb[0].clamp(0.,1.)*255.).round() as u8,(rgb[1].clamp(0.,1.)*255.).round() as u8,(rgb[2].clamp(0.,1.)*255.).round() as u8))
}
/// Only the active Android settings editor may supply ephemeral colors to the renderer.
pub fn android_palette(snapshot:&Snapshot)->&serde_json::Value {
let saved=&snapshot.settings.prefs["androidPalette"];
// Package previews remain usable even when a custom Android palette has been saved.
let preview=snapshot.destination==crate::ui::shell::Destination::Settings&&snapshot.settings_view.panel_open&&snapshot.settings_view.page()==crate::ui::settings::Page::Palette;
if preview {snapshot.settings.palette_draft.as_ref().filter(|value|crate::services::prefs::valid_android_palette(value)).unwrap_or(saved)}else if snapshot.settings.theme_preview.is_some(){&serde_json::Value::Null}else{saved}
}
/// Derive readable semantic roles without changing the user's chosen accent fill.
#[cfg(target_os="android")]
pub fn apply_android_palette(theme:&crate::Theme,value:&serde_json::Value,high_contrast:bool) {
use crate::services::prefs::*;
let custom=valid_android_palette(value);
let existing=|color:slint::Color|[color.red(),color.green(),color.blue()];
let (bg,surface,fg,accent,surfaces)=if custom {
let rgb=|key:&str|palette_rgb(value[key].as_str().unwrap()).unwrap();let bg=rgb("background");let surface=rgb("surface");(bg,surface,rgb("foreground"),rgb("accent"),palette_surfaces(bg,surface))
}else{let bg=existing(theme.get_shaded());let surface=existing(theme.get_bg());(bg,surface,existing(theme.get_fg()),existing(theme.get_tint()),[bg,surface,existing(theme.get_header()),existing(theme.get_contrast())])};
let ink=|seed:[u8;3]|{(0..=100).map(|step|palette_mix(seed,fg,f64::from(step)/100.)).find(|candidate|surfaces.iter().all(|bg|palette_contrast(*candidate,*bg)>=4.5)).unwrap_or(fg)};
let color=|v:[u8;3]|slint::Color::from_rgb_u8(v[0],v[1],v[2]);
let on=if palette_contrast(accent,[255;3])>=palette_contrast(accent,[0;3]){[255;3]}else{[0;3]};
if custom {theme.set_dark(palette_luminance(bg)<=0.5);theme.set_bg(color(surface));theme.set_shaded(color(bg));theme.set_header(color(surfaces[2]));theme.set_contrast(color(surfaces[3]));theme.set_deviant(color(surface));}
theme.set_fg(color(fg));theme.set_tint(color(accent));theme.set_tint_text(color(ink(accent)));theme.set_on_tint(color(on));
theme.set_muted(color(if high_contrast{fg}else{ink(palette_mix(fg,surface,0.24))}));theme.set_outline(color(if high_contrast{fg}else{palette_mix(fg,surface,0.65)}));
theme.set_success(color(ink([122,221,181])));theme.set_error(color(ink([255,155,155])));theme.set_warning(color(ink([255,180,80])));
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{services::prefs,ui::{settings::{Category,Page},shell::Destination}};
#[test]
fn preview_never_persists_or_leaks_into_other_destinations() {
let mut snapshot=Snapshot::default();snapshot.settings.prefs=prefs::defaults();
let saved=snapshot.settings.prefs["androidPalette"].clone();let draft=prefs::android_palette_preset("graphite").unwrap();
snapshot.settings.palette_draft=Some(draft.clone());snapshot.settings_view.category=Category::Appearance;snapshot.settings_view.pages=vec![Page::Palette];snapshot.settings_view.panel_open=true;snapshot.destination=Destination::Settings;
assert_eq!(android_palette(&snapshot),&draft);assert_eq!(snapshot.settings.prefs["androidPalette"],saved);
snapshot.destination=Destination::Servers;assert_eq!(android_palette(&snapshot),&saved);
snapshot.destination=Destination::Settings;snapshot.settings.palette_draft=None;assert_eq!(android_palette(&snapshot),&saved);
snapshot.settings.palette_draft=Some(draft);snapshot.settings_view.panel_open=false;assert_eq!(android_palette(&snapshot),&saved);
}
#[test]
fn malformed_or_low_contrast_preview_keeps_saved_readable_colors() {
let mut snapshot=Snapshot::default();snapshot.settings.prefs=prefs::defaults();snapshot.destination=Destination::Settings;snapshot.settings_view.panel_open=true;snapshot.settings_view.pages=vec![Page::Palette];
let saved=snapshot.settings.prefs["androidPalette"].clone();let mut draft=saved.clone();
draft["accent"]="#12".into();snapshot.settings.palette_draft=Some(draft.clone());assert_eq!(android_palette(&snapshot),&saved);
draft=saved.clone();draft["foreground"]=draft["background"].clone();snapshot.settings.palette_draft=Some(draft);assert_eq!(android_palette(&snapshot),&saved);
snapshot.settings.palette_draft=Some(prefs::android_palette_preset("light").unwrap());snapshot.settings_view.pages.clear();assert_eq!(android_palette(&snapshot),&saved);
}
}
+2 -2
View File
@@ -138,8 +138,8 @@ async fn offline_input_waits_for_real_validation_and_never_grants_capture() {
assert!(manager.snapshot().capture.is_none());
assert!(manager.set_input(Some(&key), InputConfiguration::default()).await.unwrap().is_none());
assert!(events.lock().unwrap().callback_threads.len() > 0);
assert!(!manager.push_audio(&key, CapturedFrame { pcm: [1; 960], captured_at: std::time::Instant::now(),
connection_generation: key.generation, capture_epoch: 1, whisper: None }));
assert_eq!(manager.push_audio(&key, CapturedFrame { pcm: [1; 960], captured_at: std::time::Instant::now(),
connection_generation: key.generation, capture_epoch: 1, whisper: None }), teamspeach_native::app::connections::CaptureIngress::PermitRevoked);
manager.invalidate_audio();
manager.shutdown().await.unwrap();
}
+3 -1
View File
@@ -16,7 +16,7 @@ export component AppWindow inherits Window {
preferred-width: 1280px;
preferred-height: 800px;
min-width: 320px;
min-height: 360px;
min-height: Theme.android ? 0px : 360px;
default-font-family: Theme.font-family;
default-font-size: Theme.font-size;
background: Theme.shaded;
@@ -32,6 +32,8 @@ export component AppWindow inherits Window {
}
measure := Text { visible: false; accessible-role: none; }
keyboard := FocusScope {
// Android reports only the overlap remaining inside the rendering surface.
// Bars and IME overlap at the bottom: reserve their maximum, not their sum.
x: Theme.safe-left; y: Theme.safe-top;
width: max(0px, parent.width - Theme.safe-left - Theme.safe-right);
height: max(0px, parent.height - Theme.safe-top - max(Theme.safe-bottom, Theme.ime-inset));
+216 -50
View File
@@ -1,6 +1,6 @@
import { ListView, ScrollView } from "std-widgets.slint";
import { Theme } from "theme.slint";
import { ActionButton, TextField, Toggle } from "controls.slint";
import { ActionButton, TextField, Toggle, RoomIconButton } from "controls.slint";
export struct ChatMeasure { width: float, height: float }
export struct ChatRun {
@@ -53,6 +53,8 @@ export global ChatBridge {
in-out property <bool> toolbar-dynamic;
in-out property <bool> composing;
in-out property <bool> focus-request;
// Android transient panels participate in the shell's Back dispatch.
in-out property <bool> mobile-overlay;
in-out property <bool> bottom-pinned: true;
in-out property <float> log-position;
in-out property <float> content-width;
@@ -98,30 +100,40 @@ component ChatSelectionArea inherits TouchArea {
in property <string> action;
in property <float> offset-x;
in property <float> offset-y;
in property <float> row-height;
callback begun();
mouse-cursor: root.action != "" ? pointer : text;
clicked => { if root.action != "" && ChatBridge.selected-text == "" { ChatBridge.activate(root.action); } }
clicked => {
if Theme.android {
if root.action != "" { ChatBridge.activate(root.action); }
else {
ChatBridge.select-text(root.row-id, 0, 0, false);
ChatBridge.select-text(root.row-id, 100000, max(0, root.row-height - 1), true);
}
} else if root.action != "" && ChatBridge.selected-text == "" { ChatBridge.activate(root.action); }
}
pointer-event(event) => {
if event.button == PointerEventButton.left && event.kind == PointerEventKind.down {
if !Theme.android && event.button == PointerEventButton.left && event.kind == PointerEventKind.down {
root.begun();
ChatBridge.select-text(root.row-id, root.offset-x + self.mouse-x / 1px, root.offset-y + self.mouse-y / 1px, false);
}
}
moved => { if self.pressed { ChatBridge.select-text(root.row-id, root.offset-x + self.mouse-x / 1px, root.offset-y + self.mouse-y / 1px, true); } }
// A phone drag belongs to the enclosing flickable, not text selection.
moved => { if !Theme.android && self.pressed { ChatBridge.select-text(root.row-id, root.offset-x + self.mouse-x / 1px, root.offset-y + self.mouse-y / 1px, true); } }
}
component RichRow inherits Rectangle {
component RichRowContent inherits Rectangle {
in property <ChatVisual> visual;
in property <bool> inert;
in property <length> viewport-width;
callback render-request(string);
render-request(id) => { ChatBridge.activate(id); }
height: root.visual.height * 1px + ((root.visual.kind == 6 || root.visual.kind == 7) ? Theme.touch-target : 0px);
height: max(root.visual.height * 1px + ((root.visual.kind == 6 || root.visual.kind == 7) ? Theme.touch-target : 0px), Theme.android && root.inert && root.visual.preview-position >= 0 ? 48px : 0px);
width: max(root.viewport-width, root.visual.content-width * 1px);
background: root.visual.kind == 3 || root.visual.kind == 7 ? Theme.header
: root.visual.kind == 4 ? Theme.deviant : root.visual.kind == 8 ? Theme.bg
: root.visual.kind == 11 ? Theme.header : !root.visual.compact && !root.visual.header && !root.inert ? (root.visual.own ? Theme.contrast : Theme.muted) : transparent;
border-radius: root.visual.kind == 11 ? 10px : 4px;
: root.visual.kind == 11 ? Theme.header : !root.visual.compact && !root.visual.header && !root.inert ? (Theme.android ? (root.visual.own ? Theme.bg : transparent) : (root.visual.own ? Theme.contrast : Theme.muted)) : transparent;
border-radius: Theme.android ? 12px : root.visual.kind == 11 ? 10px : 4px;
row-focus := FocusScope {
accessible-role: text;
accessible-label: root.visual.plain;
@@ -145,7 +157,7 @@ component RichRow inherits Rectangle {
Rectangle { x: 12px; y: 6px; width: 10px; height: 10px; border-radius: 5px; background: Theme.muted; }
Rectangle { x: 6px; y: 18px; width: 22px; height: 12px; border-radius: 8px; background: Theme.muted; }
}
Text { text: root.visual.author; color: Theme.high-contrast ? Theme.fg : root.visual.author-color; font-family: Theme.font-family; font-size: 13px; font-weight: 700; overflow: elide; vertical-alignment: center; }
Text { text: root.visual.author; color: Theme.high-contrast || Theme.android ? Theme.fg : root.visual.author-color; font-family: Theme.font-family; font-size: 13px; font-weight: 700; overflow: elide; vertical-alignment: center; }
if !root.visual.compact: Text { text: root.visual.time; color: Theme.muted; font-family: Theme.font-family; font-size: 13px; vertical-alignment: center; horizontal-alignment: right; horizontal-stretch: 1; }
}
for run in root.visual.runs: Rectangle {
@@ -155,7 +167,7 @@ component RichRow inherits Rectangle {
if run.image-ready && !run.concealed: Image { source: run.asset; image-fit: contain; }
if !run.image-ready && !run.concealed: Text {
text: run.text;
color: run.use-color && !Theme.high-contrast ? run.foreground : run.action != "" && !root.inert ? Theme.tint : Theme.fg;
color: run.use-color && !Theme.high-contrast ? run.foreground : run.action != "" && !root.inert ? (Theme.android ? Theme.tint-text : Theme.tint) : Theme.fg;
font-family: run.mono ? "monospace" : Theme.font-family;
font-size: run.font-size * 1px; font-weight: run.font-weight; font-italic: run.italic;
vertical-alignment: top;
@@ -173,14 +185,37 @@ component RichRow inherits Rectangle {
return reject;
}
Rectangle { border-width: action-focus.has-focus ? 1px : 0px; border-color: Theme.tint; background: transparent; }
ChatSelectionArea { row-id: root.visual.id; action: run.action; offset-x: run.x; offset-y: run.y; begun => { action-focus.focus(); } }
ChatSelectionArea { row-id: root.visual.id; row-height: root.visual.height; action: run.action; offset-x: run.x; offset-y: run.y; begun => { action-focus.focus(); } }
}
if !root.inert && run.action == "": ChatSelectionArea { row-id: root.visual.id; offset-x: run.x; offset-y: run.y; begun => { row-focus.focus(); } }
if !root.inert && run.action == "": ChatSelectionArea { row-id: root.visual.id; row-height: root.visual.height; offset-x: run.x; offset-y: run.y; begun => { row-focus.focus(); } }
}
if root.inert && root.visual.preview-position >= 0: TouchArea { clicked => { ChatBridge.preview-edit(root.visual.preview-position); } }
if root.visual.kind == 6 || root.visual.kind == 7: HorizontalLayout {
y: root.visual.height * 1px; height: Theme.touch-target;
for run in root.visual.runs: ActionButton { text: ChatBridge.action-label(run.action) != "" ? ChatBridge.action-label(run.action) : root.visual.kind == 7 ? ChatBridge.tr("chat.message.mermaid.placeholder.load") : ChatBridge.tr("chat.snippet.math"); visible: run.action != "" && !run.image-ready; clicked => { root.render-request(run.action); } }
if !Theme.android: HorizontalLayout { for run in root.visual.runs: ActionButton { text: ChatBridge.action-label(run.action) != "" ? ChatBridge.action-label(run.action) : root.visual.kind == 7 ? ChatBridge.tr("chat.message.mermaid.placeholder.load") : ChatBridge.tr("chat.snippet.math"); visible: run.action != "" && !run.image-ready; clicked => { root.render-request(run.action); } } }
if Theme.android && root.visual.runs.length > 0 && root.visual.runs[0].action != "" && !root.visual.runs[0].image-ready: ActionButton { text: root.visual.kind == 7 ? ChatBridge.tr("chat.message.mermaid.placeholder.load") : ChatBridge.tr("chat.snippet.math"); clicked => { root.render-request(root.visual.runs[0].action); } }
}
}
// Wide tables and code scroll within their row, never the phone's whole page.
component RichRow inherits Rectangle {
in property <ChatVisual> visual;
in property <bool> inert;
in property <length> viewport-width;
callback render-request(string);
render-request(id) => { ChatBridge.activate(id); }
private property <length> body-height: max(root.visual.height * 1px + ((root.visual.kind == 6 || root.visual.kind == 7) ? Theme.touch-target : 0px), Theme.android && root.inert && root.visual.preview-position >= 0 ? 48px : 0px);
private property <bool> wide: root.visual.content-width * 1px > root.viewport-width;
min-width: 0px; horizontal-stretch: 1;
preferred-width: Theme.android ? 0px : root.visual.content-width * 1px;
height: root.body-height + (Theme.android && root.wide ? 24px : 0px);
if !Theme.android || !root.wide: RichRowContent { visual: root.visual; viewport-width: root.viewport-width; inert: root.inert; render-request(id) => { root.render-request(id); } }
if Theme.android && root.wide: ScrollView {
width: root.width; height: root.height;
content-width: max(self.visible-width, root.visual.content-width * 1px);
content-height: root.body-height;
vertical-scrollbar-policy: always-off;
RichRowContent { visual: root.visual; viewport-width: parent.width; inert: root.inert; render-request(id) => { root.render-request(id); } }
}
}
@@ -192,45 +227,59 @@ export component RichDocument inherits Rectangle {
callback render-request(string);
render-request(id) => { ChatBridge.activate(id); }
height: contents.preferred-height;
contents := VerticalLayout { spacing: 0px; for row in root.rows: RichRow { visual: row; viewport-width: root.width; inert: root.inert; render-request(id) => { root.render-request(id); } } }
contents := VerticalLayout { min-width: 0px; preferred-width: 0px; spacing: 0px; for row in root.rows: RichRow { visual: row; viewport-width: root.width; inert: root.inert; render-request(id) => { root.render-request(id); } } }
}
export component MarkupPanel inherits Rectangle {
background: Theme.bg;
changed width => { MarkupBridge.layout(max(32, (self.width - 32px) / 1px)); }
changed width => { if !Theme.android { MarkupBridge.layout(max(32, (self.width - 32px) / 1px)); } }
init => { focus.focus(); }
TouchArea { }
focus := FocusScope {
VerticalLayout {
padding: 16px; spacing: 8px;
padding: Theme.android ? 8px : 16px; spacing: 8px;
HorizontalLayout {
min-height: Theme.touch-target;
Text { text: MarkupBridge.title; color: Theme.fg; font-family: Theme.font-family; font-size: Theme.font-size; font-weight: 600; vertical-alignment: center; accessible-role: text; accessible-label: self.text; }
if !Theme.android: Text { text: MarkupBridge.title; color: Theme.fg; font-family: Theme.font-family; font-size: Theme.font-size; font-weight: 600; vertical-alignment: center; accessible-role: text; accessible-label: self.text; }
if Theme.android: Text { min-width: 0px; text: MarkupBridge.title; color: Theme.fg; font-family: Theme.font-family; font-size: Theme.font-size; font-weight: 600; vertical-alignment: center; overflow: elide; accessible-role: text; accessible-label: self.text; }
ActionButton { text: MarkupBridge.close-label; clicked => { MarkupBridge.close(); } }
}
ScrollView {
RichDocument { rows: MarkupBridge.rows; inert: true; render-request(id) => { MarkupBridge.render-request(id); } }
document-scroll := ScrollView {
min-width: 0px; min-height: 0px;
horizontal-scrollbar-policy: Theme.android ? always-off : as-needed;
if !Theme.android: RichDocument { rows: MarkupBridge.rows; inert: true; render-request(id) => { MarkupBridge.render-request(id); } }
if Theme.android: RichDocument { width: document-scroll.visible-width; rows: MarkupBridge.rows; inert: true; changed width => { MarkupBridge.layout(max(32, self.width / 1px)); } render-request(id) => { MarkupBridge.render-request(id); } }
}
}
}
}
export component ChatScreen inherits Rectangle {
background: Theme.shaded;
background: Theme.android ? Theme.header : Theme.shaded;
min-width: 0px; min-height: 0px;
preferred-width: 100%; preferred-height: 100%;
private property <bool> show-tools;
init => { if Theme.android { ChatBridge.mobile-overlay = false; } }
private property <bool> show-emoji;
private property <bool> show-search;
private property <bool> show-conversations;
private property <bool> mobile-overlay: ChatBridge.mobile-overlay;
changed mobile-overlay => {
if Theme.android && !root.mobile-overlay {
if root.show-emoji { ChatBridge.command("dismiss-completion"); }
root.show-tools = false; root.show-emoji = false; root.show-search = false; root.show-conversations = false;
}
}
private property <bool> typing: Theme.android && Theme.ime-inset > 0px;
private property <length> caret-y;
// Measure the allocated viewport; composer constraints must not size their own parent.
private property <length> allocated-height;
private property <length> allocated-width;
changed height => { allocated-height = self.height; }
changed width => { ChatBridge.layout(max(16, (root.width - 32px) / 1px), max(16, (root.width - 40px) / 1px)); }
changed width => { allocated-width = self.width; if !Theme.android { ChatBridge.layout(max(16, (root.width - 32px) / 1px), max(16, (root.width - 40px) / 1px)); } }
VerticalLayout {
spacing: 0px;
if ChatBridge.tabs.length > 0 && !root.typing: ScrollView {
if !Theme.android && ChatBridge.tabs.length > 0: ScrollView {
height: Theme.touch-target; vertical-stretch: 0;
HorizontalLayout {
spacing: 4px;
@@ -241,27 +290,40 @@ export component ChatScreen inherits Rectangle {
}
}
}
if !root.typing: HorizontalLayout {
if !Theme.android: HorizontalLayout {
padding: 8px; spacing: 8px; height: 52px;
Text { text: ChatBridge.title; color: Theme.fg; font-family: Theme.font-family; font-size: 18px; font-weight: 700; overflow: elide; vertical-alignment: center; horizontal-stretch: 1; }
if ChatBridge.can-info: ActionButton { text: ChatBridge.tr("admin.info"); clicked => { ChatBridge.client-info(); } }
ActionButton { text: ChatBridge.tr("admin.search"); clicked => { root.show-search = !root.show-search; } }
}
if root.show-search: HorizontalLayout {
if Theme.android && !root.typing && root.allocated-height > 220px: HorizontalLayout {
min-height: 48px; vertical-stretch: 0; padding-left: 8px; padding-right: 8px; spacing: 8px;
ActionButton {
min-width: 48px; horizontal-stretch: 1; text: "";
accessible-label: ChatBridge.tr("native.chat.conversations") + ": " + ChatBridge.title; enabled: ChatBridge.tabs.length > 0;
Text { x: 12px; width: max(0px, parent.width - 44px); text: ChatBridge.title; overflow: elide; color: Theme.fg; font-family: Theme.font-family; font-size: Theme.font-size; vertical-alignment: center; accessible-role: none; }
Path { x: parent.width - 24px; y: (parent.height - 6px) / 2; width: 10px; height: 6px; commands: "M 0 0 L 5 5 L 10 0"; stroke: Theme.fg; stroke-width: 1.5px; }
clicked => { root.show-conversations = true; ChatBridge.mobile-overlay = true; }
}
RoomIconButton { icon: "search"; label: ChatBridge.tr("admin.search"); clicked => { root.show-search = true; ChatBridge.mobile-overlay = true; } }
}
if !Theme.android && root.show-search: HorizontalLayout {
padding-left: 12px; padding-right: 12px; spacing: 8px;
TextField { text <=> ChatBridge.search; placeholder: ChatBridge.tr("admin.search"); accepted => { ChatBridge.search-history(ChatBridge.search); } }
ActionButton { text: ChatBridge.tr("admin.search"); clicked => { ChatBridge.search-history(ChatBridge.search); } }
}
if !root.typing && (ChatBridge.has-older || ChatBridge.older-page || ChatBridge.loading): HorizontalLayout {
if !Theme.android && (ChatBridge.has-older || ChatBridge.older-page || ChatBridge.loading): HorizontalLayout {
padding-left: 12px; padding-right: 12px; spacing: 8px;
if ChatBridge.has-older: ActionButton { text: ChatBridge.tr("chat.history.older"); enabled: !ChatBridge.loading; clicked => { ChatBridge.history(false); } }
if ChatBridge.older-page: ActionButton { text: ChatBridge.tr("chat.history.latest"); enabled: !ChatBridge.loading; clicked => { ChatBridge.history(true); } }
if ChatBridge.loading: Text { text: ChatBridge.tr("admin.loading"); color: Theme.muted; vertical-alignment: center; }
}
Rectangle {
vertical-stretch: 1;
min-width: 0px; min-height: 0px; vertical-stretch: 1; clip: Theme.android;
log := ListView {
content-width: max(self.visible-width, ChatBridge.content-width * 1px);
content-width: Theme.android ? self.visible-width : max(self.visible-width, ChatBridge.content-width * 1px);
horizontal-scrollbar-policy: Theme.android ? always-off : as-needed;
changed visible-width => { if Theme.android { ChatBridge.layout(max(32, self.visible-width / 1px), max(32, editor-scroll.visible-width / 1px)); } }
width: parent.width; height: parent.height;
content-y: ChatBridge.log-position * 1px;
changed content-y => {
@@ -269,45 +331,62 @@ export component ChatScreen inherits Rectangle {
ChatBridge.bottom-pinned = self.content-height + self.content-y - self.height < 80px;
}
changed content-height => { if ChatBridge.bottom-pinned && !ChatBridge.older-page { self.content-y = min(0px, self.height - self.content-height); } }
changed visible-height => { if Theme.android && ChatBridge.bottom-pinned && !ChatBridge.older-page { self.content-y = min(0px, self.height - self.content-height); } }
for row in ChatBridge.rows: RichRow { visual: row; viewport-width: log.visible-width; inert: false; }
}
if ChatBridge.rows.length == 0 && !ChatBridge.loading: Text { width: parent.width; text: ChatBridge.tr("chat.history.empty"); color: Theme.muted; font-family: Theme.font-family; font-size: Theme.font-size; horizontal-alignment: center; }
}
if ChatBridge.selected-text != "": HorizontalLayout {
if !Theme.android && ChatBridge.selected-text != "": HorizontalLayout {
padding-left: 12px; spacing: 8px;
ActionButton { text: ChatBridge.tr("ui.copy"); clicked => { ChatBridge.copy-selection(); } }
Text { text: ChatBridge.selected-text; color: Theme.muted; overflow: elide; vertical-alignment: center; }
}
if ChatBridge.status != "": Text { text: ChatBridge.status; color: Theme.muted; wrap: word-wrap; font-family: Theme.font-family; font-size: 13px; }
if ChatBridge.error != "": Text { text: ChatBridge.error; color: Theme.error; wrap: word-wrap; font-family: Theme.font-family; font-size: 13px; accessible-role: text; }
if !Theme.android && ChatBridge.status != "": Text { text: ChatBridge.status; color: Theme.muted; wrap: word-wrap; font-family: Theme.font-family; font-size: 13px; }
if !Theme.android && ChatBridge.error != "": Text { text: ChatBridge.error; color: Theme.error; wrap: word-wrap; font-family: Theme.font-family; font-size: 13px; accessible-role: text; }
if Theme.android && ChatBridge.error != "" && !root.typing: error-scroll := ScrollView {
min-height: 0px; max-height: 48px; preferred-height: error-text.preferred-height;
horizontal-scrollbar-policy: always-off;
error-text := Text { width: error-scroll.visible-width; text: ChatBridge.error; color: Theme.error; wrap: word-wrap; font-family: Theme.font-family; font-size: 13px; accessible-role: text; }
}
composer := Rectangle {
background: Theme.bg; border-radius: 8px; border-width: 1px; border-color: input.has-focus ? Theme.tint : Theme.outline;
min-height: 92px; max-height: Theme.android ? max(120px, root.allocated-height) : max(120px, root.allocated-height * 0.55); vertical-stretch: 0;
background: Theme.bg; border-radius: Theme.android ? 12px : 8px; border-width: Theme.android ? 0px : 1px; border-color: input.has-focus ? Theme.tint : Theme.outline;
min-width: 0px; min-height: Theme.android ? 64px : 92px;
max-height: Theme.android ? max(64px, root.allocated-height * 0.5) : max(120px, root.allocated-height * 0.55); vertical-stretch: 0;
VerticalLayout {
min-width: 0px; preferred-width: 0px;
padding: 8px; spacing: 4px;
if ChatBridge.toolbar-visible && (!ChatBridge.toolbar-dynamic || input.has-focus || root.show-tools || root.show-emoji): HorizontalLayout {
spacing: 4px;
if !Theme.android && ChatBridge.toolbar-visible && (!ChatBridge.toolbar-dynamic || input.has-focus || root.show-tools || root.show-emoji): HorizontalLayout {
min-width: 0px; preferred-width: 0px; spacing: 4px;
ActionButton { text: "B"; accessible-label: ChatBridge.tr("chat.snippet.bold"); enabled: ChatBridge.enabled && !ChatBridge.composing; clicked => { ChatBridge.format("bold"); } }
ActionButton { text: "I"; accessible-label: ChatBridge.tr("chat.snippet.italic"); enabled: ChatBridge.enabled && !ChatBridge.composing; clicked => { ChatBridge.format("italic"); } }
if root.width > 420px: ActionButton { text: ChatBridge.tr("chat.snippet.link"); enabled: ChatBridge.enabled && !ChatBridge.composing; clicked => { ChatBridge.format("link"); } }
if root.allocated-width > 420px: ActionButton { text: ChatBridge.tr("chat.snippet.link"); enabled: ChatBridge.enabled && !ChatBridge.composing; clicked => { ChatBridge.format("link"); } }
ActionButton { text: ChatBridge.tr("chat.toolbar.more"); enabled: ChatBridge.enabled; clicked => { root.show-tools = !root.show-tools; root.show-emoji = false; } }
}
HorizontalLayout {
if !Theme.android: HorizontalLayout {
Text { text: ChatBridge.tr("settings.chat.text_edit.rich_text"); color: Theme.muted; font-family: Theme.font-family; font-size: 13px; vertical-alignment: center; horizontal-stretch: 1; }
Toggle { label: ChatBridge.tr("settings.chat.text_edit.rich_text"); checked <=> ChatBridge.hybrid; enabled: !ChatBridge.composing; toggled(value) => { ChatBridge.set-hybrid(value); } }
}
if root.show-tools: ListView {
height: Theme.android ? clamp(root.allocated-height - 240px, 48px, 160px) : 160px;
if !Theme.android && root.show-tools: ListView {
height: 160px;
for tool in ChatBridge.tools: ActionButton { text: tool.label; enabled: ChatBridge.enabled && !ChatBridge.composing; clicked => { ChatBridge.format(tool.id); root.show-tools = false; } }
}
if root.show-emoji: TextField { text <=> ChatBridge.emoji-search; placeholder: ChatBridge.tr("chat.emoji.search"); edited(value) => { ChatBridge.emoji(value); } }
if ChatBridge.completions.length > 0: ListView {
height: min(Theme.android ? clamp(root.allocated-height - 240px, 48px, 160px) : 160px, ChatBridge.completions.length * Theme.touch-target);
if !Theme.android && root.show-emoji: TextField { text <=> ChatBridge.emoji-search; placeholder: ChatBridge.tr("chat.emoji.search"); edited(value) => { ChatBridge.emoji(value); } }
if !Theme.android && ChatBridge.completions.length > 0: ListView {
height: min(160px, ChatBridge.completions.length * Theme.touch-target);
for item[index] in ChatBridge.completions: ActionButton { text: item.label; primary: index == ChatBridge.completion-index; clicked => { ChatBridge.complete(index); root.show-emoji = false; } }
}
HorizontalLayout {
spacing: Theme.android ? 8px : 0px; min-width: 0px;
if Theme.android: RoomIconButton {
icon: "plus"; label: ChatBridge.tr("chat.toolbar.more");
clicked => { root.show-tools = true; ChatBridge.mobile-overlay = true; }
}
editor-scroll := ScrollView {
content-width: max(self.visible-width, ChatBridge.editor-width * 1px);
min-height: 48px; preferred-height: min(240px, editor-content.height); vertical-stretch: 1;
content-width: Theme.android ? self.visible-width : max(self.visible-width, ChatBridge.editor-width * 1px);
horizontal-scrollbar-policy: Theme.android ? always-off : as-needed;
min-width: 0px; min-height: 48px;
preferred-height: Theme.android ? min(max(48px, root.allocated-height * 0.25), editor-content.height) : min(240px, editor-content.height); vertical-stretch: 1;
changed visible-width => { if Theme.android { ChatBridge.layout(max(32, log.visible-width / 1px), max(32, self.visible-width / 1px)); } }
changed visible-height => {
if Theme.android && input.has-focus {
if root.caret-y + self.content-y < 0px { self.content-y = -root.caret-y; }
@@ -317,13 +396,13 @@ export component ChatScreen inherits Rectangle {
VerticalLayout {
spacing: 0px;
editor-content := Rectangle {
width: ChatBridge.editor-width * 1px;
height: before-doc.height + max(36px, input.preferred-height) + after-doc.height;
width: Theme.android ? editor-scroll.visible-width : ChatBridge.editor-width * 1px;
height: before-doc.height + max(Theme.android ? 48px : 36px, input.preferred-height) + after-doc.height;
before-doc := RichDocument { rows: ChatBridge.before; width: parent.width; }
input := TextInput {
y: before-doc.height; width: parent.width; height: max(36px, self.preferred-height);
y: before-doc.height; width: parent.width; height: max(Theme.android ? 48px : 36px, self.preferred-height);
text <=> ChatBridge.editor-text; enabled: ChatBridge.enabled;
single-line: false; wrap: word-wrap; font-family: Theme.font-family; font-size: 14px;
single-line: false; wrap: word-wrap; font-family: Theme.font-family; font-size: Theme.android ? Theme.font-size * 14 / 15 : 14px;
color: Theme.fg; selection-foreground-color: Theme.fg; selection-background-color: Theme.tint;
accessible-label: ChatBridge.tr("ui.message"); accessible-placeholder-text: ChatBridge.placeholder;
page-height: editor-scroll.visible-height;
@@ -347,7 +426,7 @@ export component ChatScreen inherits Rectangle {
if event.text == "c" && event.modifiers.alt { ChatBridge.format("codeblock"); return accept; }
if event.text == "a" { ChatBridge.command("select-all"); return accept; }
}
if ChatBridge.completions.length > 0 {
if ChatBridge.completions.length > 0 && !(Theme.android && event.text == Key.Return && !event.modifiers.control && !event.modifiers.meta) {
if event.text == Key.DownArrow { ChatBridge.command("completion-next"); return accept; }
if event.text == Key.UpArrow { ChatBridge.command("completion-previous"); return accept; }
if event.text == Key.Return || event.text == Key.Tab { ChatBridge.complete(ChatBridge.completion-index); return accept; }
@@ -379,12 +458,18 @@ export component ChatScreen inherits Rectangle {
MenuItem { title: ChatBridge.tr("native.chat.selectAll"); activated => { ChatBridge.command("select-all"); } }
}
}
if input.text == "" && input.preedit-text == "": Text { y: input.y; text: ChatBridge.placeholder; color: Theme.muted; font-family: Theme.font-family; font-size: 14px; }
if input.text == "" && input.preedit-text == "": Text { y: input.y; width: parent.width; text: ChatBridge.placeholder; color: Theme.muted; font-family: Theme.font-family; font-size: Theme.android ? Theme.font-size * 14 / 15 : 14px; wrap: Theme.android ? word-wrap : no-wrap; }
after-doc := RichDocument { y: input.y + input.height; rows: ChatBridge.after; width: parent.width; }
}
}
}
HorizontalLayout {
if Theme.android: RoomIconButton {
icon: "send"; label: ChatBridge.tr("ui.send"); primary: true;
enabled: ChatBridge.can-send && !ChatBridge.composing;
clicked => { ChatBridge.send(); }
}
}
if !Theme.android: HorizontalLayout {
spacing: 4px;
ActionButton { text: ChatBridge.tr("chat.emoji.label"); enabled: ChatBridge.enabled && !ChatBridge.composing; clicked => { root.show-emoji = !root.show-emoji; root.show-tools = false; ChatBridge.emoji(""); } }
if ChatBridge.can-attach: ActionButton { text: ChatBridge.tr("chat.attachment.label"); enabled: ChatBridge.enabled; clicked => { ChatBridge.attach(); } }
@@ -394,4 +479,85 @@ export component ChatScreen inherits Rectangle {
}
}
}
if Theme.android && ChatBridge.selected-text != "" && ChatBridge.completions.length == 0 && !ChatBridge.mobile-overlay && composer.y >= 48px: Rectangle {
y: max(0px, composer.y - 48px); height: 48px; background: Theme.header;
HorizontalLayout {
spacing: 8px;
ActionButton { text: ChatBridge.tr("ui.copy"); clicked => { ChatBridge.copy-selection(); ChatBridge.command("clear-selection"); } }
Text { min-width: 0px; text: ChatBridge.selected-text; color: Theme.muted; font-family: Theme.font-family; font-size: 13px; overflow: elide; vertical-alignment: center; horizontal-stretch: 1; }
ActionButton { text: ChatBridge.tr("ui.close"); clicked => { ChatBridge.command("clear-selection"); } }
}
}
// Completion suggestions float over the log instead of increasing the minimum
// composer height while Android's IME owns most of the landscape viewport.
if Theme.android && !ChatBridge.mobile-overlay && ChatBridge.completions.length > 0 && composer.y >= 48px: Rectangle {
width: root.width; height: min(144px, max(48px, composer.y));
y: max(0px, composer.y - self.height); background: Theme.header;
ListView {
for item[index] in ChatBridge.completions: ActionButton { text: item.label; primary: index == ChatBridge.completion-index; clicked => { ChatBridge.complete(index); } }
}
}
if Theme.android && ChatBridge.mobile-overlay: Rectangle {
background: Theme.header;
TouchArea { }
VerticalLayout {
padding: 8px; spacing: 8px;
HorizontalLayout {
spacing: 8px;
if root.show-emoji: TextField { text <=> ChatBridge.emoji-search; placeholder: ChatBridge.tr("chat.emoji.search"); edited(value) => { ChatBridge.emoji(value); } }
if !root.show-emoji: Text { min-width: 0px; text: root.show-search ? ChatBridge.tr("admin.search") : root.show-conversations ? ChatBridge.tr("native.chat.conversations") : ChatBridge.tr("chat.toolbar.more"); color: Theme.fg; font-family: Theme.font-family; font-size: Theme.font-size; font-weight: 600; overflow: elide; vertical-alignment: center; horizontal-stretch: 1; }
ActionButton { text: ChatBridge.tr("ui.close"); clicked => { ChatBridge.mobile-overlay = false; } }
}
if root.show-conversations: ListView {
min-width: 0px; min-height: 0px;
for tab in ChatBridge.tabs: HorizontalLayout {
spacing: 8px;
ActionButton { horizontal-stretch: 1; text: tab.label + (tab.unread != "" ? " " + tab.unread : ""); primary: tab.active; clicked => { ChatBridge.choose-tab(tab.id); ChatBridge.mobile-overlay = false; } }
if tab.closable: ActionButton { text: ChatBridge.tr("ui.close"); accessible-label: ChatBridge.tr("ui.close.private.chat") + " " + tab.label; clicked => { ChatBridge.close-tab(tab.id); } }
}
}
if root.show-emoji: ListView {
min-width: 0px; min-height: 0px;
for item[index] in ChatBridge.completions: ActionButton { text: item.label; primary: index == ChatBridge.completion-index; clicked => { ChatBridge.complete(index); ChatBridge.mobile-overlay = false; } }
}
if root.show-search: ScrollView {
min-width: 0px; min-height: 0px;
VerticalLayout {
spacing: 8px;
TextField { text <=> ChatBridge.search; placeholder: ChatBridge.tr("admin.search"); accepted => { ChatBridge.search-history(ChatBridge.search); ChatBridge.mobile-overlay = false; } }
ActionButton { text: ChatBridge.tr("admin.search"); clicked => { ChatBridge.search-history(ChatBridge.search); ChatBridge.mobile-overlay = false; } }
}
}
if root.show-tools: ScrollView {
min-width: 0px; min-height: 0px; horizontal-scrollbar-policy: always-off;
VerticalLayout {
spacing: 8px;
ActionButton { text: ChatBridge.tr("chat.emoji.label"); enabled: ChatBridge.enabled && !ChatBridge.composing; clicked => { root.show-tools = false; root.show-emoji = true; ChatBridge.emoji(""); } }
if ChatBridge.can-attach: ActionButton { text: ChatBridge.tr("chat.attachment.label"); enabled: ChatBridge.enabled && !ChatBridge.composing; clicked => { ChatBridge.mobile-overlay = false; ChatBridge.attach(); } }
for item[index] in ChatBridge.completions: ActionButton { text: item.label; primary: index == ChatBridge.completion-index; clicked => { ChatBridge.complete(index); ChatBridge.mobile-overlay = false; } }
ActionButton { text: ChatBridge.tr("native.chat.conversations"); enabled: ChatBridge.tabs.length > 0; clicked => { root.show-tools = false; root.show-conversations = true; } }
ActionButton { text: ChatBridge.tr("admin.search"); clicked => { root.show-tools = false; root.show-search = true; } }
if ChatBridge.can-info: ActionButton { text: ChatBridge.tr("admin.info"); clicked => { ChatBridge.mobile-overlay = false; ChatBridge.client-info(); } }
if ChatBridge.has-older: ActionButton { text: ChatBridge.tr("chat.history.older"); enabled: !ChatBridge.loading; clicked => { ChatBridge.history(false); ChatBridge.mobile-overlay = false; } }
if ChatBridge.older-page: ActionButton { text: ChatBridge.tr("chat.history.latest"); enabled: !ChatBridge.loading; clicked => { ChatBridge.history(true); ChatBridge.mobile-overlay = false; } }
if ChatBridge.loading: Text { text: ChatBridge.tr("admin.loading"); color: Theme.muted; wrap: word-wrap; }
if ChatBridge.selected-text != "": ActionButton { text: ChatBridge.tr("native.chat.copySelection"); clicked => { ChatBridge.copy-selection(); ChatBridge.command("clear-selection"); ChatBridge.mobile-overlay = false; } }
if ChatBridge.status != "": Text { text: ChatBridge.status; color: Theme.muted; font-family: Theme.font-family; font-size: 13px; wrap: word-wrap; }
if ChatBridge.error != "": Text { text: ChatBridge.error; color: Theme.error; font-family: Theme.font-family; font-size: 13px; wrap: word-wrap; }
HorizontalLayout {
spacing: 8px;
Text { min-width: 0px; text: ChatBridge.tr("settings.chat.text_edit.rich_text"); color: Theme.fg; font-family: Theme.font-family; font-size: 13px; wrap: word-wrap; vertical-alignment: center; horizontal-stretch: 1; }
Toggle { label: ChatBridge.tr("settings.chat.text_edit.rich_text"); checked <=> ChatBridge.hybrid; enabled: !ChatBridge.composing; toggled(value) => { ChatBridge.set-hybrid(value); ChatBridge.mobile-overlay = false; } }
}
ActionButton { text: ChatBridge.tr("native.chat.undo"); enabled: ChatBridge.can-undo && !ChatBridge.composing; clicked => { ChatBridge.command("undo"); ChatBridge.mobile-overlay = false; } }
ActionButton { text: ChatBridge.tr("native.chat.redo"); enabled: ChatBridge.can-redo && !ChatBridge.composing; clicked => { ChatBridge.command("redo"); ChatBridge.mobile-overlay = false; } }
ActionButton { text: ChatBridge.tr("native.chat.cut"); enabled: ChatBridge.enabled && !ChatBridge.composing; clicked => { input.cut(); ChatBridge.mobile-overlay = false; } }
ActionButton { text: ChatBridge.tr("ui.copy"); clicked => { input.copy(); ChatBridge.mobile-overlay = false; } }
ActionButton { text: ChatBridge.tr("native.chat.paste"); enabled: ChatBridge.enabled && !ChatBridge.composing; clicked => { input.paste(); ChatBridge.mobile-overlay = false; } }
ActionButton { text: ChatBridge.tr("native.chat.selectAll"); enabled: ChatBridge.enabled && !ChatBridge.composing; clicked => { ChatBridge.command("select-all"); ChatBridge.mobile-overlay = false; } }
for tool in ChatBridge.tools: ActionButton { text: tool.label; enabled: ChatBridge.enabled && !ChatBridge.composing; clicked => { ChatBridge.format(tool.id); ChatBridge.mobile-overlay = false; } }
}
}
}
}
}
+92 -10
View File
@@ -1,4 +1,4 @@
import { ComboBox } from "std-widgets.slint";
import { ComboBox, ScrollView } from "std-widgets.slint";
import { Theme } from "theme.slint";
export component ActionButton inherits Rectangle {
@@ -7,11 +7,12 @@ export component ActionButton inherits Rectangle {
in property <bool> primary: false;
in property <bool> destructive: false;
callback clicked();
min-height: Theme.touch-target;
min-width: max(Theme.android ? 48px : 44px, label.preferred-width + 24px);
preferred-height: Theme.touch-target;
border-radius: primary ? self.height / 2 : 4px;
background: primary ? (destructive ? Theme.error : Theme.tint) : (touch.has-hover || focus.has-focus ? Theme.bg : transparent);
min-height: Theme.android ? max(Theme.touch-target, label.preferred-height + 16px) : Theme.touch-target;
min-width: Theme.android ? 48px : max(44px, label.preferred-width + 24px);
preferred-height: Theme.android ? max(Theme.touch-target, label.preferred-height + 16px) : Theme.touch-target;
vertical-stretch: Theme.android ? 0 : 1;
border-radius: Theme.android || primary ? self.height / 2 : 4px;
background: primary ? (destructive ? Theme.error : Theme.tint) : (Theme.android || touch.has-hover || focus.has-focus ? Theme.bg : transparent);
border-width: focus.has-focus || Theme.high-contrast ? 2px : 0px;
border-color: Theme.outline;
opacity: enabled ? 1 : 0.45;
@@ -19,7 +20,7 @@ export component ActionButton inherits Rectangle {
accessible-label: text;
accessible-enabled: enabled;
accessible-action-default => { if root.enabled { root.clicked(); } }
label := Text { text: root.text; color: root.primary ? (Theme.dark ? Theme.contrast : #fff) : (root.destructive ? Theme.error : Theme.fg); font-family: Theme.font-family; font-size: Theme.font-size; horizontal-alignment: center; vertical-alignment: center; overflow: elide; }
label := Text { x: Theme.android ? 12px : 0px; width: parent.width - (Theme.android ? 24px : 0px); text: root.text; color: root.primary ? (Theme.android ? Theme.on-tint : (Theme.dark ? Theme.contrast : #fff)) : (root.destructive ? Theme.error : Theme.fg); font-family: Theme.font-family; font-size: Theme.font-size; horizontal-alignment: center; vertical-alignment: center; wrap: Theme.android ? word-wrap : no-wrap; overflow: elide; }
focus := FocusScope {
enabled: root.enabled;
key-pressed(event) => { if event.text == "\n" || event.text == " " { root.clicked(); return accept; } return reject; }
@@ -30,6 +31,7 @@ export component ActionButton inherits Rectangle {
export component TextField inherits Rectangle {
in-out property <string> text;
in property <string> placeholder;
in property <string> label: placeholder;
in property <bool> secret: false;
in property <bool> enabled: true;
out property <bool> has-focus: input.has-focus;
@@ -37,6 +39,7 @@ export component TextField inherits Rectangle {
callback accepted();
min-height: Theme.touch-target;
preferred-height: Theme.touch-target;
vertical-stretch: Theme.android ? 0 : 1;
background: Theme.bg;
border-radius: 4px;
forward-focus: input;
@@ -57,7 +60,7 @@ export component TextField inherits Rectangle {
selection-foreground-color: Theme.contrast;
edited => { root.edited(self.text); }
accepted => { root.accepted(); }
accessible-label: root.placeholder;
accessible-label: root.label;
}
}
@@ -87,18 +90,97 @@ export component Choice inherits Rectangle {
in property <bool> enabled: true;
in property <string> label;
callback selected(int);
min-height: Theme.touch-target;
preferred-height: Theme.touch-target;
min-width: Theme.android ? 48px : 0px;
min-height: Theme.android ? mobile.preferred-height : Theme.touch-target;
preferred-height: Theme.android ? mobile.preferred-height : Theme.touch-target;
vertical-stretch: Theme.android ? 0 : 1;
forward-focus: input;
// ComboBox normalizes its local model/index internally. Never let those writes sever
// the caller's authoritative selected-index binding during a snapshot/model update.
changed current-index => { input.current-index = root.current-index; }
changed values => { input.current-index = root.current-index; }
input := ComboBox {
visible: !Theme.android;
width: parent.width; height: parent.height;
model: root.values;
current-index: root.current-index;
enabled: root.enabled;
accessible-label: root.label;
selected(value) => { root.selected(self.current-index); }
}
mobile := ActionButton {
visible: Theme.android;
width: parent.width; height: parent.height;
text: root.current-index >= 0 && root.current-index < root.values.length ? root.values[root.current-index] : root.label;
enabled: root.enabled && root.values.length > 0;
background: Theme.bg; border-width: 1px; border-color: Theme.outline;
accessible-label: root.label + ": " + self.text;
clicked => { options.show(); }
}
options := PopupWindow {
x: 0px; y: root.height;
width: root.width; height: min(240px, root.values.length * Theme.touch-target + 16px);
Rectangle {
background: Theme.contrast; border-width: 1px; border-color: Theme.outline;
ScrollView {
width: parent.width; height: parent.height;
VerticalLayout {
padding: 8px; spacing: 4px; alignment: start;
for value[index] in root.values: ActionButton {
text: value; primary: root.current-index == index;
clicked => { root.current-index = index; root.selected(index); options.close(); }
}
}
}
}
}
}
// Android Room controls share one stroke vocabulary and labelled 48dp hit targets.
export component RoomIcon inherits Path {
in property <string> name;
in property <color> ink: Theme.fg;
width: 24px; height: 24px;
fill: transparent; stroke: ink; stroke-width: 1.8px;
commands: name == "back" ? "M19 12H5 M12 5L5 12L12 19"
: name == "more" ? "M5 11V13 M12 11V13 M19 11V13"
: name == "close" ? "M6 6L18 18 M6 18L18 6"
: name == "mic" ? "M9 5A3 3 0 0 1 15 5V12A3 3 0 0 1 9 12Z M5 10V12A7 7 0 0 0 19 12V10 M12 19V22 M9 22H15"
: name == "mic-off" ? "M3 3L21 21 M9 9V12A3 3 0 0 0 14 14 M9 5A3 3 0 0 1 15 5V11 M5 10V12A7 7 0 0 0 17 17 M19 12V10 M12 19V22 M9 22H15"
: name == "headphones" ? "M4 13V12A8 8 0 0 1 20 12V13 M4 12H3V20H7V12Z M20 12H21V20H17V12Z"
: name == "sound-off" ? "M4 9H8L13 5V19L8 15H4Z M17 10L22 15 M17 15L22 10"
: name == "chat" ? "M4 4H20V16H9L4 20Z M8 8H16 M8 12H13"
: name == "users" ? "M9 12A4 4 0 1 0 9 4A4 4 0 0 0 9 12 M2 21V19A6 6 0 0 1 14 19V21 M17 4A4 4 0 0 1 17 12 M19 15A5 5 0 0 1 22 19V21"
: name == "user" ? "M12 12A4 4 0 1 0 12 4A4 4 0 0 0 12 12 M5 21V19A7 7 0 0 1 19 19V21"
: name == "settings" ? "M9 3L8 6L5 7L3 10L5 12L4 15L6 18L9 17L12 19L15 17L18 18L20 15L19 12L21 10L19 7L16 6L15 3Z M12 9A3 3 0 1 0 12 15A3 3 0 0 0 12 9"
: name == "server" ? "M4 3H20V10H4Z M4 14H20V21H4Z M7 6V7 M7 17V18 M11 6H17 M11 17H17"
: name == "screen" ? "M3 4H21V17H3Z M12 17V21 M8 21H16"
: name == "down" ? "M6 9L12 15L18 9"
: name == "chevron" ? "M9 5L16 12L9 19"
: name == "leave" ? "M9 4H4V20H9 M13 7L18 12L13 17 M8 12H21"
: name == "send" ? "M3 3L22 12L3 21L7 12Z M7 12H22"
: name == "plus" ? "M12 5V19 M5 12H19"
: name == "search" ? "M10 17A7 7 0 1 0 10 3A7 7 0 0 0 10 17 M15 15L21 21"
: name == "palette" ? "M12 3A9 9 0 1 0 12 21H14A2 2 0 0 0 15 17A2 2 0 0 1 16 13H18A3 3 0 0 0 21 10A9 9 0 0 0 12 3 M7 7V9 M12 5V7 M17 7V9 M6 12V14"
: name == "shield" ? "M12 3L20 6V12C20 17 12 21 12 21C12 21 4 17 4 12V6Z"
: name == "bell" ? "M5 16H19L17 13V9A5 5 0 0 0 7 9V13Z M10 20H14"
: "M12 3A9 9 0 1 0 12 21A9 9 0 0 0 12 3 M12 10V16 M12 6V8";
}
export component RoomIconButton inherits Rectangle {
in property <string> icon;
in property <string> label;
in property <bool> enabled: true;
in property <bool> primary: false;
callback clicked();
width: 48px; min-height: 48px; preferred-height: 48px; vertical-stretch: 0;
border-radius: 12px;
background: primary ? Theme.tint : (touch.has-hover || focus.has-focus ? Theme.bg : transparent);
border-width: focus.has-focus || Theme.high-contrast ? 2px : 0px;
border-color: Theme.outline; opacity: enabled ? 1 : 0.45;
accessible-role: button; accessible-label: label; accessible-enabled: enabled;
accessible-action-default => { if root.enabled { root.clicked(); } }
RoomIcon { name: root.icon; ink: root.primary ? Theme.on-tint : Theme.fg; x: (parent.width - self.width)/2; y: (parent.height - self.height)/2; }
focus := FocusScope { enabled: root.enabled; key-pressed(e) => { if e.text == " " || e.text == Key.Return { root.clicked(); return accept; } return reject; } }
touch := TouchArea { enabled: root.enabled; clicked => { focus.focus(); root.clicked(); } }
}
+219 -18
View File
@@ -1,4 +1,4 @@
import { ScrollView, TextEdit } from "std-widgets.slint";
import { ScrollView, TextEdit, Slider } from "std-widgets.slint";
import { Theme } from "theme.slint";
import { ActionButton, TextField, Choice, Toggle } from "controls.slint";
import { ShellBridge, ShellCommand } from "shell.slint";
@@ -19,6 +19,7 @@ export global DialogBridge {
in-out property <string> submit-label;
in-out property <string> cancel-label;
in-out property <string> advanced-label;
in-out property <bool> has-advanced;
in-out property <string> loading-label;
callback edit(string, string);
callback choose(string, int);
@@ -27,11 +28,221 @@ export global DialogBridge {
callback cancel();
}
// Android forms share a bounded viewport: context and decisions stay on screen while
// every field, auxiliary action and confirmation remains scrollable above the IME.
component AndroidDialog inherits Rectangle {
background: Theme.bg;
border-radius: DialogBridge.onboarding || Theme.ime-inset > 0px ? 0px : 20px;
accessible-role: form;
accessible-label: DialogBridge.title;
property <bool> advanced: false;
property <length> focused-y: -1px;
property <string> focused-field;
property <bool> short: root.height < 400px;
property <bool> stack-actions: root.width < 360px && Theme.font-size > 17px && !root.short;
VerticalLayout {
padding: 20px; spacing: 12px;
if !DialogBridge.onboarding && !root.short && Theme.ime-inset == 0px: HorizontalLayout {
alignment: center; vertical-stretch: 0;
Rectangle { width: 32px; height: 3px; border-radius: 2px; background: Theme.muted; }
}
Text {
text: DialogBridge.title; color: Theme.fg;
font-family: Theme.font-family; font-size: Theme.font-size * 1.25; font-weight: 700;
wrap: word-wrap; vertical-stretch: 0;
accessible-role: text; accessible-label: self.text;
}
body := ScrollView {
min-height: 0px; min-width: 0px; vertical-stretch: 1;
changed visible-height => {
if root.focused-y >= 0px { self.content-y = clamp(-root.focused-y, min(0px, self.visible-height - self.content-height), 0px); }
}
VerticalLayout {
spacing: 12px; alignment: start;
if DialogBridge.description != "": Text {
text: DialogBridge.description; color: Theme.muted; wrap: word-wrap;
font-family: Theme.font-family; font-size: Theme.font-size;
}
for field in DialogBridge.fields: field-row := Rectangle {
visible: !field.advanced || root.advanced;
height: self.visible ? row.preferred-height : 0px;
vertical-stretch: 0; min-width: 0px;
changed y => {
if root.focused-field == field.id {
root.focused-y = self.y;
body.content-y = clamp(-self.y, min(0px, body.visible-height - body.content-height), 0px);
}
}
row := VerticalLayout {
spacing: 4px;
if field.kind != 5: Text {
text: field.label; color: Theme.fg; wrap: word-wrap;
font-family: Theme.font-family; font-size: Theme.font-size;
}
if field.kind == 0 || field.kind == 1 || field.kind == 3 || (field.kind == 4 && field.id != "db" && field.id != "volume"): TextField {
text: field.value; placeholder: field.label; secret: field.kind == 1;
enabled: field.enabled && !DialogBridge.busy; min-width: 0px;
edited(value) => { DialogBridge.edit(field.id, value); }
accepted => { if DialogBridge.onboarding { DialogBridge.submit(); } }
changed has-focus => {
if self.has-focus {
root.focused-field = field.id;
root.focused-y = field-row.y;
body.content-y = clamp(-field-row.y, min(0px, body.visible-height - body.content-height), 0px);
} else if root.focused-field == field.id {
root.focused-field = "";
root.focused-y = -1px;
}
}
}
if field.kind == 4 && (field.id == "db" || field.id == "volume"): VerticalLayout {
spacing: 8px;
Text {
text: field.id == "db" ? "\{round(field.value.to-float() * 10) / 10} dB" : "\{round(field.value.to-float() * 100)}%";
color: Theme.tint-text; font-family: Theme.font-family; font-size: Theme.font-size;
horizontal-alignment: right;
}
Slider {
min-height: 48px; minimum: field.id == "db" ? -200 : 0;
maximum: field.id == "db" ? 10 : 2; value: field.value.to-float();
enabled: field.enabled && !DialogBridge.busy;
accessible-label: field.label;
changed(value) => { DialogBridge.edit(field.id, "\{round(value * 100) / 100}"); }
}
}
if field.kind == 2: TextEdit {
text: field.value; enabled: field.enabled && !DialogBridge.busy; wrap: word-wrap;
height: max(96px, Theme.font-size * 4); min-width: 0px;
font-family: Theme.font-family; font-size: Theme.font-size;
accessible-label: field.label;
edited => { DialogBridge.edit(field.id, self.text); }
changed has-focus => {
if self.has-focus {
root.focused-field = field.id;
root.focused-y = field-row.y;
body.content-y = clamp(-field-row.y, min(0px, body.visible-height - body.content-height), 0px);
} else if root.focused-field == field.id {
root.focused-field = "";
root.focused-y = -1px;
}
}
}
if field.kind == 5: HorizontalLayout {
spacing: 8px;
Text {
text: field.label; color: Theme.fg; wrap: word-wrap; vertical-alignment: center;
font-family: Theme.font-family; font-size: Theme.font-size;
horizontal-stretch: 1; min-width: 0px;
}
Toggle {
width: max(48px, Theme.touch-target); horizontal-stretch: 0;
checked: field.checked; label: field.label; enabled: field.enabled && !DialogBridge.busy;
toggled(value) => { DialogBridge.edit(field.id, value ? "true" : "false"); }
}
}
if field.kind == 6: Choice {
values: field.choices; current-index: field.choice-index; label: field.label;
enabled: field.enabled && !DialogBridge.busy; min-width: 0px;
selected(index) => { DialogBridge.choose(field.id, index); }
}
if field.hint != "": Text {
text: field.hint; color: Theme.muted; wrap: word-wrap;
font-family: Theme.font-family; font-size: Theme.font-size;
}
if field.error != "": Text {
text: field.error; color: Theme.error; wrap: word-wrap;
font-family: Theme.font-family; font-size: Theme.font-size;
accessible-role: text; accessible-live-region: assertive;
}
}
}
for action in DialogBridge.actions: ActionButton {
text: action.label; enabled: action.enabled && !DialogBridge.busy;
destructive: action.destructive; min-width: 0px;
clicked => { ShellBridge.invoke(action.id); }
}
if !DialogBridge.onboarding && DialogBridge.has-advanced: ActionButton {
text: DialogBridge.advanced-label; min-width: 0px;
clicked => { root.advanced = !root.advanced; }
}
if DialogBridge.confirmation-label != "": confirmation-row := VerticalLayout {
spacing: 4px; vertical-stretch: 0;
changed y => {
if root.focused-field == "__confirmation" {
root.focused-y = self.y;
body.content-y = clamp(-self.y, min(0px, body.visible-height - body.content-height), 0px);
}
}
Text {
text: DialogBridge.confirmation-label; color: Theme.warning; wrap: word-wrap;
font-family: Theme.font-family; font-size: Theme.font-size;
}
TextField {
text: DialogBridge.confirmation; placeholder: DialogBridge.confirmation-label;
enabled: !DialogBridge.busy; min-width: 0px;
edited(value) => { DialogBridge.confirm(value); }
changed has-focus => {
if self.has-focus {
root.focused-field = "__confirmation";
root.focused-y = confirmation-row.y;
body.content-y = clamp(-confirmation-row.y, min(0px, body.visible-height - body.content-height), 0px);
} else if root.focused-field == "__confirmation" {
root.focused-field = "";
root.focused-y = -1px;
}
}
}
}
if DialogBridge.error != "": Text {
text: DialogBridge.error; color: Theme.error; wrap: word-wrap;
font-family: Theme.font-family; font-size: Theme.font-size;
accessible-live-region: assertive;
}
if DialogBridge.busy: Text {
text: DialogBridge.loading-label; color: Theme.muted; wrap: word-wrap;
font-family: Theme.font-family; font-size: Theme.font-size;
}
}
}
if root.stack-actions: VerticalLayout {
spacing: 8px; vertical-stretch: 0;
ActionButton {
text: DialogBridge.submit-label; primary: true; destructive: DialogBridge.destructive;
enabled: !DialogBridge.busy; min-width: 0px;
clicked => { DialogBridge.submit(); }
}
ActionButton {
text: DialogBridge.cancel-label; enabled: !DialogBridge.onboarding || !DialogBridge.busy; min-width: 0px;
clicked => { DialogBridge.cancel(); }
}
}
if !root.stack-actions: HorizontalLayout {
spacing: 8px; vertical-stretch: 0;
ActionButton {
text: DialogBridge.cancel-label; enabled: !DialogBridge.onboarding || !DialogBridge.busy;
min-width: 0px; horizontal-stretch: 1;
clicked => { DialogBridge.cancel(); }
}
ActionButton {
text: DialogBridge.submit-label; primary: true; destructive: DialogBridge.destructive;
enabled: !DialogBridge.busy; min-width: 0px; horizontal-stretch: 1;
clicked => { DialogBridge.submit(); }
}
}
}
}
export component ShellDialog inherits Rectangle {
background: Theme.contrast.with-alpha(0.75);
property <bool> phone: Theme.android;
// An overlay blocks background pointer input without turning Cancel into a submit.
TouchArea { }
dialog := Rectangle {
if root.phone: AndroidDialog {
width: min(root.width, 640px); x: (root.width - self.width) / 2;
height: DialogBridge.onboarding || Theme.ime-inset > 0px || root.height < 480px ? root.height : min(root.height - 24px, 660px);
y: root.height - self.height;
}
if !root.phone: dialog := Rectangle {
width: min(parent.width - 24px, 640px);
height: min(parent.height - 24px, layout.preferred-height);
x: (parent.width - self.width)/2;
@@ -46,15 +257,12 @@ export component ShellDialog inherits Rectangle {
property <length> focused-y: 0px;
layout := VerticalLayout {
padding: 20px; spacing: 12px;
if !Theme.android: Text { text: DialogBridge.title; font-size: Theme.font-size * 1.6; font-weight: 700; color: Theme.fg; wrap: word-wrap; }
if !Theme.android && DialogBridge.description != "": Text { text: DialogBridge.description; color: Theme.muted; wrap: word-wrap; }
Text { text: DialogBridge.title; font-size: Theme.font-size * 1.6; font-weight: 700; color: Theme.fg; wrap: word-wrap; }
if DialogBridge.description != "": Text { text: DialogBridge.description; color: Theme.muted; wrap: word-wrap; }
form-scroll := ScrollView {
min-height: Theme.android ? min(80px, max(0px, root.height - 112px)) : 80px; max-height: 600px;
changed visible-height => { if Theme.android { self.content-y = clamp(-dialog.focused-y, min(0px, self.visible-height - self.content-height), 0px); } }
min-height: 80px; max-height: 600px;
VerticalLayout {
spacing: 12px;
if Theme.android: Text { text: DialogBridge.title; font-size: Theme.font-size * 1.6; font-weight: 700; color: Theme.fg; wrap: word-wrap; }
if Theme.android && DialogBridge.description != "": Text { text: DialogBridge.description; color: Theme.muted; wrap: word-wrap; }
for field in DialogBridge.fields: field-row := Rectangle {
visible: !field.advanced || dialog.advanced;
height: self.visible ? row.preferred-height : 0px;
@@ -82,22 +290,15 @@ export component ShellDialog inherits Rectangle {
ActionButton { text: DialogBridge.advanced-label; clicked => { dialog.advanced = !dialog.advanced; } }
if DialogBridge.confirmation-label != "": Text { text: DialogBridge.confirmation-label; color: Theme.warning; wrap: word-wrap; }
if DialogBridge.confirmation-label != "": TextField { text: DialogBridge.confirmation; placeholder: DialogBridge.confirmation-label; enabled: !DialogBridge.busy; edited(value) => { DialogBridge.confirm(value); } }
if Theme.android && DialogBridge.error != "": Text { text: DialogBridge.error; color: Theme.error; wrap: word-wrap; accessible-live-region: assertive; }
if Theme.android && DialogBridge.busy: Text { text: DialogBridge.loading-label; color: Theme.muted; }
}
}
if !Theme.android && DialogBridge.error != "": Text { text: DialogBridge.error; color: Theme.error; wrap: word-wrap; accessible-live-region: assertive; }
if !Theme.android && DialogBridge.busy: Text { text: DialogBridge.loading-label; color: Theme.muted; }
if !Theme.android: HorizontalLayout {
if DialogBridge.error != "": Text { text: DialogBridge.error; color: Theme.error; wrap: word-wrap; accessible-live-region: assertive; }
if DialogBridge.busy: Text { text: DialogBridge.loading-label; color: Theme.muted; }
HorizontalLayout {
alignment: end; spacing: 8px;
ActionButton { text: DialogBridge.cancel-label; clicked => { DialogBridge.cancel(); } }
ActionButton { text: DialogBridge.submit-label; primary: true; destructive: DialogBridge.destructive; enabled: !DialogBridge.busy; clicked => { DialogBridge.submit(); } }
}
if Theme.android: HorizontalLayout {
spacing: 8px;
ActionButton { min-width: 48px; horizontal-stretch: 1; text: DialogBridge.cancel-label; clicked => { DialogBridge.cancel(); } }
ActionButton { min-width: 48px; horizontal-stretch: 1; text: DialogBridge.submit-label; primary: true; destructive: DialogBridge.destructive; enabled: !DialogBridge.busy; clicked => { DialogBridge.submit(); } }
}
}
}
}
+215 -24
View File
@@ -1,6 +1,6 @@
import { ScrollView, ListView, AboutSlint } from "std-widgets.slint";
import { ScrollView, ListView, AboutSlint, Slider } from "std-widgets.slint";
import { Theme } from "theme.slint";
import { ActionButton, TextField, Toggle, Choice } from "controls.slint";
import { ActionButton, TextField, Toggle, Choice, RoomIcon, RoomIconButton } from "controls.slint";
import { RichDocument, ChatVisual } from "chat.slint";
export struct SettingsRow {
@@ -8,10 +8,14 @@ export struct SettingsRow {
checked: bool, value: string, options: [string], selected: int,
enabled: bool, destructive: bool, inset: bool, error: string,
meter: float, decrease: string, increase: string, rich: [ChatVisual],
swatch: color, red: float, green: float, blue: float,
}
export global SettingsBridge {
in-out property <[string]> categories;
in-out property <[string]> category-groups;
in-out property <[string]> category-subtitles;
in-out property <string> profile-name;
in-out property <string> profile-label;
in-out property <[SettingsRow]> rows;
in-out property <int> category;
in-out property <string> title;
@@ -33,49 +37,87 @@ export global SettingsBridge {
callback commit(string, string);
callback step(string, int);
callback capture-lost();
callback color-channel(string, int, float);
}
component SettingCell inherits Rectangle {
in property <SettingsRow> setting;
in property <bool> compact;
callback field-focused();
background: setting.kind == 0 ? transparent : Theme.header;
min-height: setting.kind == 0 ? 48px : content.preferred-height + 16px;
private property <string> secret-draft;
private property <bool> color-expanded;
private property <string> secret-owner: setting.stable-id;
changed secret-owner => { root.secret-draft = ""; }
callback field-focused(bool);
background: Theme.android || setting.kind == 0 ? transparent : Theme.header;
min-height: Theme.android ? content.preferred-height : (setting.kind == 0 ? 48px : content.preferred-height + 16px);
preferred-height: self.min-height;
vertical-stretch: Theme.android ? 0 : 1;
VerticalLayout { padding: 0px;
content := VerticalLayout {
padding-top: root.setting.kind == 0 ? 14px : 8px;
padding-top: root.setting.kind == 0 ? (Theme.android ? 12px : 14px) : 8px;
padding-bottom: 8px;
padding-left: root.setting.inset ? 36px : 20px;
padding-right: 20px;
spacing: 8px;
Text { text: root.setting.title; color: Theme.fg; font-family: Theme.font-family;
padding-left: Theme.android ? (root.setting.inset ? 24px : 12px) : (root.setting.inset ? 36px : 20px);
padding-right: Theme.android ? 12px : 20px;
spacing: Theme.android ? 6px : 8px;
if !Theme.android || (root.setting.title != "" && root.setting.kind != 6 && root.setting.kind != 2): Text { text: root.setting.title; color: Theme.fg; font-family: Theme.font-family;
font-size: Theme.font-size; font-weight: root.setting.kind == 0 ? 700 : 450;
wrap: word-wrap; accessible-role: text; accessible-label: self.text;
}
if root.setting.subtitle != "": Text { text: root.setting.subtitle; color: Theme.muted;
if root.setting.subtitle != "" && (!Theme.android || root.setting.kind != 2): Text { text: root.setting.subtitle; color: Theme.muted;
font-family: Theme.font-family; font-size: Theme.font-size - 1px; wrap: word-wrap;
accessible-role: text; accessible-label: self.text;
}
if root.setting.kind == 2: Toggle {
if root.setting.kind == 2 && !Theme.android: Toggle {
checked: root.setting.checked; enabled: root.setting.enabled; label: root.setting.title;
min-height: max(48px, Theme.touch-target);
toggled(value) => { self.checked = root.setting.checked; SettingsBridge.toggle-value(root.setting.token, value); }
}
if root.setting.kind == 3: Choice {
if root.setting.kind == 2 && Theme.android: HorizontalLayout {
spacing: 8px;
Text { text: root.setting.title; color: Theme.fg; font-family: Theme.font-family;
font-size: Theme.font-size; wrap: word-wrap; vertical-alignment: center;
horizontal-stretch: 1; min-width: 0px;
}
Toggle {
width: max(48px, Theme.touch-target); horizontal-stretch: 0;
checked: root.setting.checked; enabled: root.setting.enabled; label: root.setting.title;
toggled(value) => { self.checked = root.setting.checked; SettingsBridge.toggle-value(root.setting.token, value); }
}
}
if Theme.android && root.setting.kind == 2 && root.setting.subtitle != "": Text {
text: root.setting.subtitle; color: Theme.muted; wrap: word-wrap;
font-family: Theme.font-family; font-size: Theme.font-size - 1px;
accessible-role: text; accessible-label: self.text;
}
if root.setting.kind == 3 && root.setting.stable-id != "palette-presets": Choice {
values: root.setting.options; current-index: root.setting.selected;
enabled: root.setting.enabled; label: root.setting.title;
min-height: max(48px, Theme.touch-target);
selected(index) => { self.current-index = root.setting.selected; SettingsBridge.choice-value(root.setting.token, index); }
}
if root.setting.kind == 3 && root.setting.stable-id == "palette-presets": HorizontalLayout {
spacing: 8px;
for preset[index] in root.setting.options: ActionButton {
text: preset; min-width: 0px; enabled: root.setting.enabled;
clicked => { SettingsBridge.choice-value(root.setting.token, index); }
}
}
if root.setting.kind == 4 || root.setting.kind == 5 || root.setting.kind == 8: VerticalLayout {
spacing: 4px;
field := TextField {
text: root.setting.value; placeholder: root.setting.title; secret: root.setting.kind == 8;
text: Theme.android && root.setting.kind == 8 ? root.secret-draft : root.setting.value;
placeholder: root.setting.title; secret: root.setting.kind == 8;
enabled: root.setting.enabled; min-height: max(48px, Theme.touch-target);
changed has-focus => { if self.has-focus { root.field-focused(); } }
edited(value) => { SettingsBridge.draft(root.setting.token, value); }
accepted() => { SettingsBridge.commit(root.setting.token, self.text); }
min-width: 0px;
changed has-focus => { root.field-focused(self.has-focus); }
edited(value) => {
if Theme.android && root.setting.kind == 8 { root.secret-draft = value; }
else { SettingsBridge.draft(root.setting.token, value); }
}
accepted() => {
SettingsBridge.commit(root.setting.token, self.text);
if root.setting.kind == 8 { root.secret-draft = ""; }
}
}
HorizontalLayout { spacing: 4px;
if root.setting.kind == 5: ActionButton { text: "-"; accessible-label: root.setting.decrease; enabled: root.setting.enabled;
@@ -88,12 +130,49 @@ component SettingCell inherits Rectangle {
}
ActionButton { text: SettingsBridge.apply-label; enabled: root.setting.enabled;
min-height: max(48px, Theme.touch-target);
clicked => { SettingsBridge.commit(root.setting.token, field.text); }
clicked => {
SettingsBridge.commit(root.setting.token, field.text);
if root.setting.kind == 8 { root.secret-draft = ""; }
}
}
}
}
if root.setting.kind == 10: VerticalLayout {
spacing: 8px;
HorizontalLayout {
spacing: 8px;
TextField {
text: root.setting.value; placeholder: "#RRGGBB"; label: root.setting.title + " · #RRGGBB";
enabled: root.setting.enabled; min-width: 0px; horizontal-stretch: 1;
changed has-focus => { root.field-focused(self.has-focus); }
edited(value) => { SettingsBridge.draft(root.setting.token, value); }
accepted => { SettingsBridge.commit(root.setting.token, self.text); }
}
Rectangle {
width: 48px; height: 48px; background: root.setting.swatch; border-radius: 8px;
border-width: 1px; border-color: Theme.outline;
RoomIconButton { icon: "palette"; label: root.setting.title; enabled: root.setting.enabled;
accessible-expandable: true; accessible-expanded: root.color-expanded;
clicked => { root.color-expanded = !root.color-expanded; }
}
}
}
if root.color-expanded: VerticalLayout {
spacing: 8px;
for channel[index] in [root.setting.red, root.setting.green, root.setting.blue]: HorizontalLayout {
spacing: 8px;
Text { text: index == 0 ? "R" : index == 1 ? "G" : "B"; color: Theme.fg;
font-family: Theme.font-family; font-size: Theme.font-size; width: 24px; vertical-alignment: center; }
Slider { minimum: 0; maximum: 255; value: channel; enabled: root.setting.enabled; min-height: 48px;
accessible-label: root.setting.title + (index == 0 ? " · R" : index == 1 ? " · G" : " · B");
changed(value) => { SettingsBridge.color-channel(root.setting.token, index, value); }
}
Text { text: "\{round(channel)}"; color: Theme.fg; font-family: Theme.font-family; font-size: Theme.font-size; width: 36px; vertical-alignment: center; }
}
}
}
if root.setting.kind == 6: ActionButton {
text: root.setting.title; enabled: root.setting.enabled; destructive: root.setting.destructive;
text: root.setting.title; enabled: root.setting.enabled; destructive: root.setting.destructive; primary: Theme.android && root.setting.stable-id == "palette-save";
min-height: max(48px, Theme.touch-target);
clicked => { SettingsBridge.invoke(root.setting.token); }
}
@@ -109,23 +188,50 @@ component SettingCell inherits Rectangle {
}
}
component RoomSettingsRow inherits Rectangle {
in property <int> category;
min-height: max(72px, row-content.preferred-height); vertical-stretch: 0;
background: row-touch.pressed ? Theme.bg : transparent;
accessible-role: button;
accessible-label: SettingsBridge.categories[category] + ". " + SettingsBridge.category-subtitles[category];
accessible-action-default => { SettingsBridge.category-chosen(root.category); }
border-width: row-focus.has-focus ? 2px : 0px; border-color: Theme.tint-text;
row-content := HorizontalLayout {
padding-left: 0px; padding-right: 0px; padding-top: 12px; padding-bottom: 12px; spacing: 16px;
RoomIcon { name: root.category == 3 ? "headphones" : root.category == 8 ? "bell" : root.category == 2 ? "palette" : root.category == 0 ? "user" : root.category == 1 ? "shield" : root.category == 4 ? "screen" : root.category == 6 ? "chat" : root.category == 7 ? "users" : root.category == 11 ? "info" : "settings"; ink: Theme.muted; width: 20px; height: 24px; }
VerticalLayout { spacing: 4px; alignment: center;
Text { text: SettingsBridge.categories[root.category]; color: Theme.fg; font-family: Theme.font-family; font-size: Theme.font-size; font-weight: 600; wrap: word-wrap; }
Text { text: SettingsBridge.category-subtitles[root.category]; color: Theme.muted; font-family: Theme.font-family; font-size: Theme.font-size * 0.85; wrap: word-wrap; }
}
RoomIcon { name: "chevron"; ink: Theme.muted; width: 20px; height: 24px; }
}
Rectangle { y: parent.height - 1px; height: 1px; width: parent.width; background: Theme.outline; }
row-focus := FocusScope { key-pressed(event) => {
if event.text == Key.Return || event.text == " " { SettingsBridge.category-chosen(root.category); return accept; }return reject;
} }
row-touch := TouchArea { clicked => { row-focus.focus(); SettingsBridge.category-chosen(root.category); } }
}
export component SettingsScreen inherits Rectangle {
background: Theme.shaded;
min-width: 0px; min-height: 0px;
preferred-width: 100%; preferred-height: 100%;
private property <bool> compact: self.width < 600px;
private property <length> focused-row-y;
private property <length> focused-row-y: -1px;
private property <string> focused-row;
private property <string> content-title: SettingsBridge.title;
changed content-title => { root.focused-row = ""; root.focused-row-y = -1px; }
forward-focus: keyboard;
keyboard := FocusScope {
key-pressed(event) => {
if event.text == Key.Escape && !SettingsBridge.capturing { SettingsBridge.back(); return accept; }
if !Theme.android && event.text == Key.Escape && !SettingsBridge.capturing { SettingsBridge.back(); return accept; }
if !SettingsBridge.panel-open && event.text == Key.DownArrow { SettingsBridge.category-chosen(SettingsBridge.category < 11 ? SettingsBridge.category + 1 : 0); return accept; }
if !SettingsBridge.panel-open && event.text == Key.UpArrow { SettingsBridge.category-chosen(SettingsBridge.category > 0 ? SettingsBridge.category - 1 : 11); return accept; }
if !SettingsBridge.panel-open && event.text == Key.Home { SettingsBridge.category-chosen(0); return accept; }
if !SettingsBridge.panel-open && event.text == Key.End { SettingsBridge.category-chosen(11); return accept; }
return reject;
}
HorizontalLayout {
if !Theme.android: HorizontalLayout {
spacing: 0px;
if !root.compact || !SettingsBridge.panel-open: Rectangle {
width: root.compact ? parent.width : min(280px, root.width * 0.34);
@@ -170,14 +276,99 @@ export component SettingsScreen inherits Rectangle {
if SettingsBridge.error != "": Text { text: SettingsBridge.error; color: Theme.error; wrap: word-wrap; accessible-role: text; accessible-label: self.text; }
if SettingsBridge.status != "": Text { text: SettingsBridge.status; color: Theme.muted; wrap: word-wrap; accessible-role: text; accessible-label: self.text; }
settings-list := ListView {
changed visible-height => { if Theme.android { self.content-y = clamp(-root.focused-row-y, min(0px, self.visible-height - self.content-height), 0px); } }
for row in SettingsBridge.rows: cell := SettingCell {
setting: row; compact: root.compact;
field-focused => { if Theme.android { root.focused-row-y = cell.y; settings-list.content-y = clamp(-cell.y, min(0px, settings-list.visible-height - settings-list.content-height), 0px); } }
}
}
if SettingsBridge.show-slint: AboutSlint { }
}
}
if Theme.android: VerticalLayout {
padding: 20px; spacing: 0px; min-width: 0px;
if !SettingsBridge.panel-open: ScrollView {
min-height: 0px; min-width: 0px; vertical-stretch: 1;
VerticalLayout {
spacing: 0px; alignment: start; min-width: 0px; preferred-width: 0px;
Rectangle {
min-height: max(104px, profile-content.preferred-height); vertical-stretch: 0;
accessible-role: button; accessible-label: SettingsBridge.profile-label + ". " + SettingsBridge.profile-name;
accessible-action-default => { SettingsBridge.category-chosen(0); }
border-width: profile-focus.has-focus ? 2px : 0px; border-color: Theme.tint-text;
profile-content := HorizontalLayout { spacing: 14px; padding-top: 12px; padding-bottom: 12px;
Rectangle { width: 64px; height: 64px; background: Theme.bg; border-radius: 32px;
RoomIcon { name: "user"; ink: Theme.tint-text; x: 16px; y: 16px; width: 32px; height: 32px; }
}
VerticalLayout { spacing: 4px; alignment: center;
Text { text: SettingsBridge.profile-name; color: Theme.fg; font-family: Theme.font-family; font-size: Theme.font-size * 1.25; font-weight: 700; wrap: word-wrap; }
Text { text: SettingsBridge.profile-label; color: Theme.muted; font-family: Theme.font-family; font-size: Theme.font-size * 0.85; wrap: word-wrap; }
}
}
profile-focus := FocusScope { key-pressed(event) => { if event.text == Key.Return || event.text == " " { SettingsBridge.category-chosen(0); return accept; }return reject; } }
TouchArea { clicked => { profile-focus.focus(); SettingsBridge.category-chosen(0); } }
}
for category[index] in [3, 8, 2, 0, 1, 4, 5, 6, 7, 9, 10, 11]: VerticalLayout {
spacing: 0px; vertical-stretch: 0; min-width: 0px; preferred-width: 0px;
if index == 0 || index == 2 || index == 5: Text {
text: SettingsBridge.category-groups[index == 0 ? 0 : index == 2 ? 1 : 2];
color: Theme.muted; font-family: Theme.font-family; font-size: Theme.font-size * 0.85;
font-weight: 600; min-height: 48px; vertical-alignment: center; wrap: word-wrap;
}
RoomSettingsRow { category: category; min-width: 0px; }
}
}
}
if SettingsBridge.panel-open: phone-list := ScrollView {
min-height: 0px; min-width: 0px; vertical-stretch: 1;
changed visible-height => {
if root.focused-row-y >= 0px { self.content-y = clamp(-root.focused-row-y, min(0px, self.visible-height - self.content-height), 0px); }
}
VerticalLayout {
spacing: 4px; alignment: start; min-width: 0px; preferred-width: 0px;
if SettingsBridge.error != "": Text {
text: SettingsBridge.error; color: Theme.error; wrap: word-wrap;
font-family: Theme.font-family; font-size: Theme.font-size;
accessible-role: text; accessible-label: self.text; accessible-live-region: assertive;
}
if SettingsBridge.status != "": Text {
text: SettingsBridge.status; color: Theme.muted; wrap: word-wrap;
font-family: Theme.font-family; font-size: Theme.font-size;
accessible-role: text; accessible-label: self.text;
}
for row[index] in SettingsBridge.rows: phone-row := VerticalLayout {
spacing: 0px; vertical-stretch: 0; min-width: 0px; preferred-width: 0px;
changed y => {
if root.focused-row == row.stable-id {
root.focused-row-y = self.y;
phone-list.content-y = clamp(-self.y, min(0px, phone-list.visible-height - phone-list.content-height), 0px);
}
}
if row.stable-id == "palette-cancel": HorizontalLayout {
spacing: 8px;
ActionButton { text: row.title; enabled: row.enabled;
clicked => { SettingsBridge.invoke(row.token); }
}
ActionButton { text: SettingsBridge.rows[index + 1].title; primary: true; enabled: SettingsBridge.rows[index + 1].enabled;
clicked => { SettingsBridge.invoke(SettingsBridge.rows[index + 1].token); }
}
}
if (row.kind != 0 || row.title != SettingsBridge.title) && row.stable-id != "palette-cancel" && row.stable-id != "palette-save": SettingCell {
setting: row; compact: true;
min-width: 0px; preferred-width: 0px; vertical-stretch: 0;
field-focused(focused) => {
if focused {
root.focused-row = row.stable-id;
root.focused-row-y = phone-row.y;
phone-list.content-y = clamp(-phone-row.y, min(0px, phone-list.visible-height - phone-list.content-height), 0px);
} else if root.focused-row == row.stable-id {
root.focused-row = "";
root.focused-row-y = -1px;
}
}
}
}
if SettingsBridge.show-slint: AboutSlint { }
}
}
}
}
}
+353 -48
View File
@@ -1,14 +1,14 @@
import { ScrollView, ListView, Slider } from "std-widgets.slint";
import { Theme } from "theme.slint";
import { ActionButton, TextField } from "controls.slint";
import { ActionButton, TextField, Choice, RoomIcon, RoomIconButton } from "controls.slint";
import { ChatScreen } from "chat.slint";
import { SettingsScreen } from "settings.slint";
import { SettingsScreen, SettingsBridge } from "settings.slint";
export struct ShellRow { id: string, title: string, subtitle: string, depth: int, selected: bool, expanded: bool, expandable: bool, talking: bool, muted: bool, unread: string }
export struct ShellRow { id: string, title: string, subtitle: string, depth: int, selected: bool, expanded: bool, expandable: bool, talking: bool, muted: bool, unread: string, disclosure: string }
export struct ShellTab { id: string, title: string, selected: bool, microphone-owner: bool, connected: bool, unread: string }
export struct ShellCommand { id: string, label: string, enabled: bool, reason: string, destructive: bool }
export struct ShellInfo { label: string, value: string }
export struct ShellStream { id: string, title: string, status: string, frame: image, has-frame: bool, volume: float, actions: [ShellCommand] }
export struct ShellStream { id: string, title: string, status: string, frame: image, has-frame: bool, has-volume: bool, volume: float, actions: [ShellCommand] }
export global ShellBridge {
in-out property <[ShellTab]> tabs;
in-out property <[ShellRow]> tree;
@@ -21,6 +21,9 @@ export global ShellBridge {
in-out property <[ShellCommand]> menu-actions;
in-out property <[ShellStream]> streams;
in-out property <[string]> destinations;
in-out property <[string]> connection-names;
in-out property <int> selected-connection: -1;
in-out property <ShellCommand> primary-action;
in-out property <int> destination;
in-out property <int> depth;
in-out property <int> stage;
@@ -65,6 +68,17 @@ export global ShellBridge {
in-out property <[string]> stages;
in-out property <length> sidebar-width: 270px;
in-out property <length> server-width: 500px;
in-out property <[ShellRow]> participants;
in-out property <[ShellStream]> room-streams;
in-out property <bool> room-connected;
in-out property <int> room-page;
in-out property <string> room-title;
in-out property <string> room-server;
in-out property <string> room-caption;
in-out property <[string]> room-destinations;
in-out property <[string]> room-labels;
in-out property <ShellCommand> room-disconnect;
callback room-navigate(int);
callback navigate(int);
callback back();
callback select(string);
@@ -128,7 +142,7 @@ component EntryRow inherits Rectangle {
component CommandList inherits VerticalLayout {
in property <[ShellCommand]> commands;
spacing: 4px;
spacing: Theme.android ? 8px : 4px;
for command in root.commands: VerticalLayout {
ActionButton { text: command.label; enabled: command.enabled; destructive: command.destructive; clicked => { ShellBridge.invoke(command.id); } }
if command.reason != "": Text { text: command.reason; color: Theme.muted; wrap: word-wrap; }
@@ -137,25 +151,307 @@ component CommandList inherits VerticalLayout {
component StreamTile inherits Rectangle {
in property <ShellStream> item;
min-height: 230px;
min-height: Theme.android ? stream-content.preferred-height : 230px;
vertical-stretch: Theme.android ? 0 : 1;
background: Theme.contrast;
border-radius: 8px;
border-width: 2px;
border-color: Theme.bg;
VerticalLayout {
stream-content := VerticalLayout {
padding: 8px; spacing: 4px;
Text { text: root.item.title; color: Theme.fg; overflow: elide; }
Rectangle {
min-height: 150px;
Text { text: root.item.title; color: Theme.fg; overflow: Theme.android ? clip : elide; wrap: Theme.android ? word-wrap : no-wrap; }
if !Theme.android || root.item.has-frame || root.item.has-volume: Rectangle {
min-height: Theme.android ? max(100px,root.width * 0.5625) : 150px;
if root.item.has-frame: Image { source: root.item.frame; image-fit: contain; }
if !root.item.has-frame: Text { text: root.item.status != "" ? root.item.status : ShellBridge.label-stream-waiting; color: Theme.muted; horizontal-alignment: center; vertical-alignment: center; wrap: word-wrap; }
}
Text { text: root.item.status; color: Theme.muted; overflow: elide; }
Slider { minimum: 0; maximum: 2; value: root.item.volume; accessible-label: ShellBridge.label-volume; changed(value) => { ShellBridge.stream-volume(root.item.id,value); } }
Text { text: root.item.status; color: Theme.muted; overflow: Theme.android ? clip : elide; wrap: Theme.android ? word-wrap : no-wrap; }
if !Theme.android || root.item.has-volume: Slider { min-height: Theme.android ? 48px : 0px; minimum: 0; maximum: 2; value: root.item.volume; accessible-label: ShellBridge.label-volume; changed(value) => { ShellBridge.stream-volume(root.item.id,value); } }
CommandList { commands: root.item.actions; }
}
}
// Touch navigation is structurally separate from the desktop's three fixed slots.
component PhoneIconAction inherits Rectangle {
in property <int> kind;
in property <string> label;
in property <bool> enabled: true;
callback clicked();
width: 48px; min-height: 48px; vertical-stretch: 0;
background: icon-touch.has-hover || icon-focus.has-focus ? Theme.bg : transparent;
border-radius: 8px; border-width: icon-focus.has-focus ? 2px : 0px; border-color: Theme.outline;
opacity: enabled ? 1 : 0.45;
accessible-role: button; accessible-label: label; accessible-enabled: enabled;
accessible-action-default => { if root.enabled { root.clicked(); } }
if root.kind == 0: HorizontalLayout { padding: 15px; spacing: 3px; for dot in 3: Rectangle { width: 4px; height: 4px; border-radius: 2px; background: Theme.fg; } }
if root.kind == 1: Path { x: 12px; y: (parent.height - 24px)/2; width: 24px; height: 24px; commands: "M 15 4 L 7 12 L 15 20 M 7 12 L 22 12"; fill: transparent; stroke: Theme.fg; stroke-width: 2px; }
if root.kind == 2: Path { x: 12px; y: (parent.height - 24px)/2; width: 24px; height: 24px; commands: "M 8 4 L 16 12 L 8 20"; fill: transparent; stroke: Theme.fg; stroke-width: 2px; }
if root.kind == 3: Path { x: 12px; y: (parent.height - 24px)/2; width: 24px; height: 24px; commands: "M 4 8 L 12 16 L 20 8"; fill: transparent; stroke: Theme.fg; stroke-width: 2px; }
icon-focus := FocusScope { enabled: root.enabled; key-pressed(e) => { if e.text == "\n" || e.text == " " { root.clicked(); return accept; } return reject; } }
icon-touch := TouchArea { enabled: root.enabled; clicked => { icon-focus.focus(); root.clicked(); } }
}
component PhoneEntryRow inherits Rectangle {
in property <ShellRow> item;
min-width: 0px;
property <length> indent: min(item.depth * 12px, 48px);
min-height: max(48px, row-content.preferred-height); preferred-height: self.min-height; vertical-stretch: 0;
background: item.selected ? Theme.contrast : transparent;
border-radius: 9px; border-width: item.selected || row-focus.has-focus ? 1.5px : 0px; border-color: Theme.tint;
accessible-role: list-item; accessible-label: item.title + ". " + item.subtitle;
accessible-item-selectable: true; accessible-item-selected: item.selected;
accessible-expandable: item.expandable; accessible-expanded: item.expanded;
accessible-action-default => { ShellBridge.select(root.item.id); }
accessible-action-expand => { if root.item.expandable { ShellBridge.expand(root.item.id); } }
row-content := HorizontalLayout { padding-left: root.indent; spacing: 8px;
if root.item.expandable: PhoneIconAction { kind: root.item.expanded ? 3 : 2; label: root.item.disclosure; clicked => { ShellBridge.expand(root.item.id); } }
Rectangle { width: 6px; height: 6px; border-radius: 3px; background: root.item.talking ? Theme.success : (root.item.muted ? Theme.error : Theme.muted); }
VerticalLayout { padding-top: 8px; padding-bottom: 8px; spacing: 2px; alignment: center; horizontal-stretch: 1;
Text { min-width: 0px; text: root.item.title; color: Theme.fg; font-size: Theme.font-size; wrap: word-wrap; }
if root.item.subtitle != "": Text { min-width: 0px; text: root.item.subtitle; color: Theme.muted; font-size: Theme.font-size * 0.86; wrap: word-wrap; }
}
if root.item.unread != "": Text { text: root.item.unread; color: Theme.tint; vertical-alignment: center; }
PhoneIconAction { kind: 0; label: ShellBridge.label-more + ": " + root.item.title; clicked => { ShellBridge.context(root.item.id); } }
}
row-focus := FocusScope { key-pressed(e) => { if e.text == "\n" { ShellBridge.select(root.item.id); return accept; } if e.text == Key.F10 && e.modifiers.shift { ShellBridge.context(root.item.id); return accept; } return reject; } }
TouchArea {
x: root.indent + (root.item.expandable ? 56px : 0px); width: max(0px,parent.width - self.x - 56px);
clicked => { row-focus.focus(); ShellBridge.select(root.item.id); }
pointer-event(e) => {
if e.button == PointerEventButton.right && e.kind == PointerEventKind.down { ShellBridge.context(root.item.id); }
if e.button == PointerEventButton.left && e.kind == PointerEventKind.down { ShellBridge.row-press(root.item.id,true); }
if e.kind == PointerEventKind.up || e.kind == PointerEventKind.cancel { ShellBridge.row-press(root.item.id,false); }
if e.kind == PointerEventKind.move && (abs((self.mouse-x - self.pressed-x)/1px)>8 || abs((self.mouse-y - self.pressed-y)/1px)>8) { ShellBridge.row-press(root.item.id,false); }
}
}
}
component PhoneServerList inherits Rectangle {
background: Theme.bg; min-width: 0px; min-height: 0px;
VerticalLayout { spacing: 8px; padding: 8px;
if ShellBridge.primary-action.id != "": ActionButton { text: ShellBridge.primary-action.label; primary: true; enabled: ShellBridge.primary-action.enabled; clicked => { ShellBridge.invoke(ShellBridge.primary-action.id); } }
if ShellBridge.tabs.length > 0: HorizontalLayout { spacing: 8px; vertical-stretch: 0;
Choice { horizontal-stretch: 1; values: ShellBridge.connection-names; current-index: ShellBridge.selected-connection; label: ShellBridge.destinations[0]; selected(index) => { if index >= 0 && index < ShellBridge.tabs.length { ShellBridge.select(ShellBridge.tabs[index].id); } } }
PhoneIconAction { kind: 0; label: ShellBridge.label-more; enabled: ShellBridge.selected-connection >= 0; clicked => { ShellBridge.context(ShellBridge.tabs[ShellBridge.selected-connection].id); } }
}
if ShellBridge.bookmarks.length > 0 && ShellBridge.room-page != 6: ActionButton { text: ShellBridge.label-bookmarks; clicked => { ShellBridge.room-navigate(6); } }
if ShellBridge.tree.length > 0 && ShellBridge.room-page != 6: ListView { min-height: 0px; vertical-stretch: 1; for item in ShellBridge.tree: PhoneEntryRow { item: item; } }
if ShellBridge.tree.length == 0 || ShellBridge.room-page == 6: ScrollView { min-height: 0px; vertical-stretch: 1;
VerticalLayout { spacing: 8px;
if ShellBridge.tree.length == 0: Text { text: ShellBridge.label-tree-empty; color: Theme.muted; wrap: word-wrap; }
if ShellBridge.bookmarks.length > 0: Text { text: ShellBridge.label-bookmarks; color: Theme.fg; font-weight: 600; wrap: word-wrap; }
for item in ShellBridge.bookmarks: PhoneEntryRow { item: item; }
}
}
}
}
component PhoneDetail inherits Rectangle {
in property <bool> typing;
preferred-width: 0px; horizontal-stretch: 1;
min-width: 0px; min-height: 0px; background: Theme.shaded;
VerticalLayout { spacing: 4px;
if ShellBridge.destination == 1: ChatScreen { min-height: 0px; }
if ShellBridge.room-page == 5 && ShellBridge.destination != 1: ScrollView { min-height: 0px; vertical-stretch: 1;
VerticalLayout { padding: 8px; spacing: 12px;
if ShellBridge.streams.length == 0: Text { text: ShellBridge.label-stream-empty; color: Theme.muted; wrap: word-wrap; }
for stream in ShellBridge.streams: StreamTile { item: stream; }
CommandList { commands: ShellBridge.detail-actions; }
}
}
if ShellBridge.room-page != 5 && ShellBridge.destination != 1: VerticalLayout { spacing: 8px;
if ShellBridge.searchable: TextField { text: ShellBridge.search; placeholder: ShellBridge.label-search; edited(value) => { ShellBridge.search-edited(value); } }
ScrollView { min-height: 0px; vertical-stretch: 1;
VerticalLayout { padding: 8px; spacing: 12px;
if ShellBridge.detail-loading: Text { text: ShellBridge.label-loading; color: Theme.muted; wrap: word-wrap; }
if ShellBridge.detail-error != "": Text { text: ShellBridge.detail-error; color: Theme.error; wrap: word-wrap; }
if ShellBridge.subtitle != "": Text { text: ShellBridge.subtitle; color: Theme.muted; wrap: word-wrap; }
if ShellBridge.description != "": Text { text: ShellBridge.description; color: Theme.fg; wrap: word-wrap; }
for row in ShellBridge.info: VerticalLayout { spacing: 4px; Text { text: row.label; color: Theme.muted; wrap: word-wrap; } Text { text: row.value; color: Theme.fg; wrap: word-wrap; } }
CommandList { commands: ShellBridge.detail-actions; }
for item in ShellBridge.entries: PhoneEntryRow { item: item; }
if ShellBridge.has-previous || ShellBridge.has-next: HorizontalLayout { spacing: 8px;
ActionButton { min-width: 48px; horizontal-stretch: 1; text: ShellBridge.label-previous; enabled: ShellBridge.has-previous; clicked => { ShellBridge.page(false); } }
ActionButton { min-width: 48px; horizontal-stretch: 1; text: ShellBridge.label-next; enabled: ShellBridge.has-next; clicked => { ShellBridge.page(true); } }
}
}
}
}
}
}
component RoomNavigation inherits Rectangle {
in property <int> index;
property <bool> selected: ShellBridge.room-page == index || (index == 0 && ShellBridge.room-page == 5) || (index == 1 && ShellBridge.room-page == 6) || (index == 3 && ShellBridge.room-page == 4);
min-width: 48px; min-height: max(64px, nav-content.preferred-height); vertical-stretch: 0;
background: transparent;
accessible-role: tab; accessible-label: ShellBridge.room-destinations[index]; accessible-item-selected: selected;
accessible-action-default => { ShellBridge.room-navigate(root.index); }
nav-content := VerticalLayout { padding: 8px; spacing: 4px; alignment: center;
Rectangle { width: 56px; height: 28px; border-radius: 14px; background: root.selected ? Theme.contrast : transparent;
RoomIcon { x: (parent.width - self.width)/2; y: 2px; name: root.index == 0 ? "headphones" : root.index == 1 ? "server" : root.index == 2 ? "chat" : "user"; ink: root.selected ? Theme.tint-text : Theme.muted; }
}
Text { text: ShellBridge.room-destinations[root.index]; color: root.selected ? Theme.tint-text : Theme.fg; font-size: Theme.font-size * 0.86; font-weight: root.selected ? 700 : 400; horizontal-alignment: center; wrap: word-wrap; }
}
border-width: nav-focus.has-focus ? 2px : 0px; border-color: Theme.outline; border-radius: 12px;
nav-focus := FocusScope { key-pressed(e) => { if e.text == "\n" || e.text == " " { ShellBridge.room-navigate(root.index); return accept; } return reject; } }
TouchArea { clicked => { nav-focus.focus(); ShellBridge.room-navigate(root.index); } }
}
component RoomParticipant inherits Rectangle {
in property <ShellRow> item;
min-width: 0px; min-height: max(136px, person-content.preferred-height); preferred-height: self.min-height; vertical-stretch: 0;
background: transparent; border-radius: 12px; border-width: person-focus.has-focus ? 2px : 0px; border-color: Theme.outline;
accessible-role: button; accessible-label: item.title + ". " + item.subtitle + ". " + ShellBridge.label-more;
accessible-action-default => { ShellBridge.context(root.item.id); }
person-content := VerticalLayout { padding: 8px; spacing: 8px; alignment: start;
Rectangle { width: 68px; height: 68px; border-radius: 34px;
background: root.item.talking ? Theme.success.with-alpha(0.14) : Theme.bg;
border-width: root.item.talking ? 2px : 0px; border-color: Theme.success;
RoomIcon { x: 18px; y: 18px; width: 32px; height: 32px; name: root.item.muted ? "mic-off" : "user"; ink: root.item.talking ? Theme.success : (root.item.muted ? Theme.error : Theme.fg); }
}
Text { min-width: 0px; text: root.item.title; color: Theme.fg; font-size: Theme.font-size; font-weight: 600; horizontal-alignment: center; wrap: word-wrap; }
Text { min-width: 0px; text: root.item.subtitle; color: root.item.talking ? Theme.success : Theme.muted; font-size: Theme.font-size * 0.86; horizontal-alignment: center; wrap: word-wrap; }
}
person-focus := FocusScope { key-pressed(e) => { if e.text == "\n" || e.text == " " { ShellBridge.context(root.item.id); return accept; } return reject; } }
TouchArea { clicked => { person-focus.focus(); ShellBridge.context(root.item.id); } }
}
component RoomView inherits Rectangle {
min-width: 0px; min-height: 0px; background: Theme.shaded;
property <int> columns: self.width < 360px || Theme.font-size > 18px ? 2 : 3;
ScrollView { min-height: 0px;
VerticalLayout { padding: 16px; spacing: 24px;
VerticalLayout { padding-top: 24px; padding-bottom: 8px; spacing: 8px;
if ShellBridge.room-server != "": Text { text: ShellBridge.room-server; color: Theme.muted; horizontal-alignment: center; wrap: word-wrap; }
Text { text: ShellBridge.room-title != "" ? ShellBridge.room-title : ShellBridge.room-destinations[0]; color: Theme.fg; font-size: Theme.font-size * 2; font-weight: 700; horizontal-alignment: center; wrap: word-wrap; }
Text { text: ShellBridge.room-connected ? ShellBridge.room-caption : ShellBridge.room-labels[9]; color: Theme.muted; horizontal-alignment: center; wrap: word-wrap; }
HorizontalLayout { alignment: center; ActionButton { text: ShellBridge.room-labels[0]; clicked => { ShellBridge.room-navigate(1); } } }
}
VerticalLayout { spacing: 16px;
for row in ceil(ShellBridge.participants.length / root.columns): HorizontalLayout { spacing: 8px;
for column in root.columns: Rectangle { min-width: 0px; horizontal-stretch: 1; min-height: person.preferred-height;
person := RoomParticipant { visible: row * root.columns + column < ShellBridge.participants.length; item: ShellBridge.participants[row * root.columns + column]; }
}
}
}
for stream in ShellBridge.room-streams: Rectangle { min-height: max(64px,invite.preferred-height); preferred-height: self.min-height; vertical-stretch: 0; border-radius: 16px; background: Theme.bg;
invite := HorizontalLayout { padding: 12px; spacing: 12px;
RoomIcon { name: "screen"; ink: Theme.tint-text; }
VerticalLayout { horizontal-stretch: 1; spacing: 4px;
Text { text: stream.title; color: Theme.fg; font-weight: 600; wrap: word-wrap; }
Text { text: stream.status; color: Theme.muted; wrap: word-wrap; }
}
RoomIconButton { icon: "chevron"; label: ShellBridge.room-labels[10] + ": " + stream.title; clicked => { ShellBridge.room-navigate(5); } }
}
}
ActionButton { text: ShellBridge.room-labels[1]; clicked => { ShellBridge.room-navigate(2); } }
}
}
}
component RoomVoiceToggle inherits Rectangle {
in property <int> kind;
property <bool> active: kind == 0 ? !ShellBridge.muted : !ShellBridge.deafened;
property <string> label: kind == 0 ? (active ? ShellBridge.room-labels[4] : ShellBridge.room-labels[5]) : (active ? ShellBridge.room-labels[6] : ShellBridge.room-labels[7]);
min-width: 48px; min-height: max(48px, toggle-content.preferred-height); preferred-height: self.min-height; vertical-stretch: 0;
background: active ? Theme.bg : Theme.error.with-alpha(0.14); border-radius: 24px;
accessible-role: button; accessible-label: label; accessible-action-default => { ShellBridge.voice(root.kind); }
toggle-content := HorizontalLayout { padding: 12px; spacing: 8px;
RoomIcon { name: root.kind == 0 ? (root.active ? "mic" : "mic-off") : (root.active ? "headphones" : "sound-off"); ink: root.active ? Theme.success : Theme.error; }
Text { min-width: 0px; text: root.label; color: root.active ? Theme.success : Theme.error; font-size: Theme.font-size * 0.86; font-weight: 600; wrap: word-wrap; vertical-alignment: center; }
}
border-width: toggle-focus.has-focus ? 2px : 0px; border-color: Theme.outline;
toggle-focus := FocusScope { key-pressed(e) => { if e.text == "\n" || e.text == " " { ShellBridge.voice(root.kind); return accept; } return reject; } }
TouchArea { clicked => { toggle-focus.focus(); ShellBridge.voice(root.kind); } }
}
component PhoneVoice inherits Rectangle {
in property <bool> typing;
background: Theme.contrast; border-radius: 16px;
min-height: voice-content.preferred-height; preferred-height: self.min-height; vertical-stretch: 0;
voice-content := VerticalLayout { padding: 12px; spacing: 8px;
if !root.typing: HorizontalLayout { spacing: 8px;
RoomIcon { name: "headphones"; ink: ShellBridge.deafened ? Theme.error : Theme.success; }
VerticalLayout { horizontal-stretch: 1; spacing: 2px;
Text { text: ShellBridge.voice-title; color: Theme.fg; font-size: Theme.font-size * 0.86; font-weight: 600; wrap: word-wrap; }
Text { text: ShellBridge.voice-status; color: ShellBridge.transmitting ? Theme.success : Theme.muted; font-size: Theme.font-size * 0.86; wrap: word-wrap; }
}
if ShellBridge.room-disconnect.id != "": RoomIconButton { icon: "leave"; label: ShellBridge.room-labels[8] + ": " + ShellBridge.voice-title; enabled: ShellBridge.room-disconnect.enabled; clicked => { ShellBridge.invoke(ShellBridge.room-disconnect.id); } }
}
HorizontalLayout { spacing: 8px;
if !ShellBridge.ptt-enabled: RoomVoiceToggle { horizontal-stretch: 1; kind: 0; }
if ShellBridge.ptt-enabled: Rectangle {
min-width: 48px; horizontal-stretch: 1; min-height: max(48px,hold-label.preferred-height + 16px); background: ShellBridge.transmitting ? Theme.tint : Theme.bg; border-radius: 24px;
accessible-role: button; accessible-label: ShellBridge.label-ptt;
border-width: hold-focus.has-focus ? 2px : 0px; border-color: Theme.outline;
hold-label := Text { text: ShellBridge.label-ptt; color: ShellBridge.transmitting ? Theme.on-tint : Theme.fg; vertical-alignment: center; horizontal-alignment: center; wrap: word-wrap; }
hold-focus := FocusScope {
changed has-focus => { if !self.has-focus { ShellBridge.held(false); } }
key-pressed(e) => { if e.text == " " || e.text == Key.Return { ShellBridge.held(true); return accept; } return reject; }
key-released(e) => { if e.text == " " || e.text == Key.Return { ShellBridge.held(false); return accept; } return reject; }
}
hold := TouchArea {
pointer-event(e) => { if e.button == PointerEventButton.left && e.kind == PointerEventKind.down { hold-focus.focus(); ShellBridge.held(true); } else if e.kind == PointerEventKind.up || e.kind == PointerEventKind.cancel { ShellBridge.held(false); } }
moved => { if self.pressed && (self.mouse-x < 0px || self.mouse-y < 0px || self.mouse-x > self.width || self.mouse-y > self.height) { ShellBridge.held(false); } }
}
}
RoomVoiceToggle { horizontal-stretch: 1; kind: 1; }
}
}
}
component AndroidShell inherits Rectangle {
property <bool> compact: self.width < 600px;
property <bool> split: self.width >= 840px && !typing;
property <bool> typing: Theme.ime-inset > 0px;
property <length> content-width: max(0px, self.width - (!compact && !typing ? 104px : 0px));
property <string> header: ShellBridge.depth > 0 ? ShellBridge.title : ShellBridge.room-page == 0 ? "TeamsPeach" : ShellBridge.room-page == 1 ? ShellBridge.room-destinations[1] : ShellBridge.room-page == 2 ? ShellBridge.room-title : ShellBridge.room-page == 3 ? (SettingsBridge.panel-open ? SettingsBridge.title : ShellBridge.room-labels[11]) : ShellBridge.room-page == 4 ? ShellBridge.destinations[2] : ShellBridge.room-page == 5 ? ShellBridge.room-labels[10] : ShellBridge.label-bookmarks;
VerticalLayout { spacing: 0px;
if !root.typing: Rectangle { background: Theme.shaded; min-height: app-bar.preferred-height; preferred-height: self.min-height; vertical-stretch: 0;
app-bar := HorizontalLayout { padding: 8px; spacing: 8px;
if ShellBridge.depth > 0 || ShellBridge.room-page != 0: RoomIconButton { icon: "back"; label: ShellBridge.label-back; clicked => { ShellBridge.back(); } }
Text { min-width: 0px; text: root.header; color: Theme.fg; font-size: Theme.font-size * 1.2; font-weight: 700; overflow: elide; horizontal-stretch: 1; vertical-alignment: center; }
RoomIconButton { icon: "more"; label: ShellBridge.label-more; clicked => { ShellBridge.menu(); } }
}
}
if ShellBridge.error != "": Text { text: ShellBridge.error; color: Theme.error; wrap: word-wrap; }
if ShellBridge.loading: Text { text: ShellBridge.label-loading; color: Theme.muted; }
HorizontalLayout { spacing: 0px; min-height: 0px; vertical-stretch: 1;
if !root.compact && !root.typing: Rectangle { width: 104px; background: Theme.header;
ScrollView { VerticalLayout { padding: 8px; spacing: 8px; for index in 4: RoomNavigation { index: index; } } }
}
if ShellBridge.room-page == 3: SettingsScreen { min-width: 0px; min-height: 0px; }
if ShellBridge.room-page == 4 && (root.split || ShellBridge.depth == 0): ScrollView { min-height: 0px; width: root.split ? root.content-width * 0.35 : root.content-width;
VerticalLayout { padding: 16px; spacing: 8px;
if ShellBridge.contacts.length == 0: Text { text: ShellBridge.label-empty; color: Theme.muted; wrap: word-wrap; }
for item in ShellBridge.contacts: PhoneEntryRow { item: item; }
}
}
if ShellBridge.room-page == 4 && ShellBridge.depth > 0: PhoneDetail { typing: root.typing; }
if ShellBridge.room-page == 2: ChatScreen { min-width: 0px; min-height: 0px; }
if ShellBridge.room-page == 5: PhoneDetail { typing: root.typing; }
if ShellBridge.room-page == 0: HorizontalLayout { min-width: 0px; spacing: 0px;
if root.split: PhoneServerList { width: root.content-width * 0.35; }
if ShellBridge.depth == 0: RoomView { horizontal-stretch: 1; }
if ShellBridge.depth > 0: PhoneDetail { typing: root.typing; }
}
if ShellBridge.room-page == 1 || ShellBridge.room-page == 6: HorizontalLayout { spacing: 0px; min-width: 0px;
if !root.typing && (root.split || ShellBridge.depth == 0): PhoneServerList { width: root.split ? root.content-width * 0.4 : root.content-width; }
if root.split: Rectangle { width: 1px; background: Theme.outline; }
if ShellBridge.depth > 0 || root.typing: PhoneDetail { typing: root.typing; }
if root.split && ShellBridge.depth == 0: RoomView { horizontal-stretch: 1; }
}
}
if ShellBridge.has-voice: Rectangle { min-height: dock.preferred-height + 16px; preferred-height: self.min-height; vertical-stretch: 0;
dock := PhoneVoice { x: 12px; y: 8px; width: max(0px,parent.width - 24px); typing: root.typing; }
}
if root.compact && !root.typing: Rectangle { min-height: bottom-nav.preferred-height; preferred-height: self.min-height; vertical-stretch: 0; background: Theme.header;
bottom-nav := HorizontalLayout { spacing: 8px; padding: 4px; for index in 4: RoomNavigation { horizontal-stretch: 1; index: index; } }
}
}
}
export component ShellScreen inherits Rectangle {
background: Theme.shaded;
min-width: 0px; min-height: 0px;
@@ -169,7 +465,7 @@ export component ShellScreen inherits Rectangle {
property <length> actual-server: desktop ? min(server-width,max(220px,self.width - actual-sidebar - 295px)) : min(300px,self.width * 0.4);
property <length> main-width: max(0px, self.width - actual-sidebar - (desktop ? 4px : 0px));
property <length> detail-width: max(0px, main-width - (ShellBridge.destination == 0 && !compact ? actual-server + (desktop ? 4px : 0px) : 0px));
VerticalLayout {
if !Theme.android: VerticalLayout {
spacing: 0px;
Rectangle {
height: max(44px, Theme.touch-target); background: Theme.header;
@@ -216,18 +512,13 @@ export component ShellScreen inherits Rectangle {
background: Theme.bg;
VerticalLayout {
spacing: 0px;
if !Theme.android: ScrollView { height: Theme.touch-target; HorizontalLayout { for tab in ShellBridge.tabs: ActionButton {
ScrollView { height: Theme.touch-target; HorizontalLayout { for tab in ShellBridge.tabs: ActionButton {
text: tab.title + (tab.microphone-owner ? " · " + ShellBridge.label-mute : "") + (tab.unread != "" ? " (" + tab.unread + ")" : ""); primary: tab.selected; clicked => { ShellBridge.select(tab.id); }
} } }
if Theme.android: ScrollView { height: Theme.touch-target; HorizontalLayout { for tab in ShellBridge.tabs: HorizontalLayout {
ActionButton { text: tab.title + (tab.microphone-owner ? " · " + ShellBridge.label-mute : "") + (tab.unread != "" ? " (" + tab.unread + ")" : ""); primary: tab.selected; clicked => { ShellBridge.select(tab.id); } }
ActionButton { text: ShellBridge.label-more; clicked => { ShellBridge.context(tab.id); } }
} } }
if root.compact && (ShellBridge.tabs.length == 0 || Theme.android) && ShellBridge.bookmarks.length > 0: ListView { max-height: Theme.android && ShellBridge.tabs.length > 0 ? root.height * 0.25 : root.height; for item in ShellBridge.bookmarks: EntryRow { item: item; } }
if root.compact && ShellBridge.tabs.length == 0 && ShellBridge.bookmarks.length > 0: ListView { max-height: root.height; for item in ShellBridge.bookmarks: EntryRow { item: item; } }
ListView { for item in ShellBridge.tree: EntryRow { item: item; } }
if ShellBridge.tree.length == 0: Text { text: ShellBridge.label-tree-empty; color: Theme.muted; wrap: word-wrap; }
if !root.desktop && !Theme.android: CommandList { commands: ShellBridge.actions; }
if !root.desktop && Theme.android: ScrollView { height: min(Theme.touch-target * 2, root.height * 0.22); CommandList { commands: ShellBridge.actions; } }
if !root.desktop: CommandList { commands: ShellBridge.actions; }
}
}
if root.desktop && ShellBridge.destination == 0: Rectangle {
@@ -239,11 +530,10 @@ export component ShellScreen inherits Rectangle {
background: Theme.shaded;
VerticalLayout {
spacing: 4px;
if !Theme.android || !root.compact || (ShellBridge.stage != 1 && ShellBridge.destination != 1): Rectangle { min-height: 71px; background: Theme.shaded;
Rectangle { min-height: 71px; background: Theme.shaded;
VerticalLayout { padding: 12px; Text { text: ShellBridge.title; color: Theme.fg; font-size: Theme.font-size * 1.6; font-weight: 700; overflow: elide; } Text { text: ShellBridge.subtitle; color: Theme.muted; overflow: elide; } }
}
if !Theme.android: HorizontalLayout { for name[index] in ShellBridge.stages: ActionButton { text: name; primary: ShellBridge.stage == index; clicked => { ShellBridge.stage = index; } } }
if Theme.android && !root.typing: ScrollView { height: Theme.touch-target; vertical-stretch: 0; HorizontalLayout { for name[index] in ShellBridge.stages: ActionButton { text: name; primary: ShellBridge.stage == index; clicked => { ShellBridge.stage = index; } } } }
HorizontalLayout { for name[index] in ShellBridge.stages: ActionButton { text: name; primary: ShellBridge.stage == index; clicked => { ShellBridge.stage = index; } } }
if ShellBridge.stage == 1 || ShellBridge.destination == 1: ChatScreen { width: root.detail-width; }
if ShellBridge.stage == 2 && ShellBridge.destination != 1: ScrollView {
VerticalLayout { padding: 10px; spacing: 10px;
@@ -261,7 +551,7 @@ export component ShellScreen inherits Rectangle {
for row in ShellBridge.info: VerticalLayout { Text { text: row.label; color: Theme.muted; } Text { text: row.value; color: Theme.fg; wrap: word-wrap; } }
CommandList { commands: ShellBridge.detail-actions; }
} }
if !Theme.android || ShellBridge.entries.length > 0: ListView { for item in ShellBridge.entries: EntryRow { item: item; } }
ListView { for item in ShellBridge.entries: EntryRow { item: item; } }
if ShellBridge.has-previous || ShellBridge.has-next: HorizontalLayout {
ActionButton { text: ShellBridge.label-previous; enabled: ShellBridge.has-previous; clicked => { ShellBridge.page(false); } }
ActionButton { text: ShellBridge.label-next; enabled: ShellBridge.has-next; clicked => { ShellBridge.page(true); } }
@@ -277,49 +567,64 @@ export component ShellScreen inherits Rectangle {
if !root.typing: Text { text: ShellBridge.voice-title + " · " + ShellBridge.voice-status; color: ShellBridge.transmitting ? Theme.success : Theme.fg; overflow: elide; }
HorizontalLayout {
spacing: 4px;
ActionButton { min-width: Theme.android ? 48px : 0px; horizontal-stretch: 1; text: ShellBridge.label-mute; primary: Theme.android && ShellBridge.muted; destructive: ShellBridge.muted; clicked => { ShellBridge.voice(0); } }
ActionButton { min-width: Theme.android ? 48px : 0px; horizontal-stretch: 1; text: ShellBridge.label-deafen; primary: Theme.android && ShellBridge.deafened; destructive: ShellBridge.deafened; clicked => { ShellBridge.voice(1); } }
if !Theme.android: Rectangle { min-height: Theme.touch-target; background: desktop-ptt.pressed ? Theme.tint : Theme.bg; border-radius: 4px; accessible-role: button; accessible-label: ShellBridge.label-ptt;
ActionButton { min-width: 0px; horizontal-stretch: 1; text: ShellBridge.label-mute; destructive: ShellBridge.muted; clicked => { ShellBridge.voice(0); } }
ActionButton { min-width: 0px; horizontal-stretch: 1; text: ShellBridge.label-deafen; destructive: ShellBridge.deafened; clicked => { ShellBridge.voice(1); } }
Rectangle { min-height: Theme.touch-target; background: desktop-ptt.pressed ? Theme.tint : Theme.bg; border-radius: 4px; accessible-role: button; accessible-label: ShellBridge.label-ptt;
Text { text: ShellBridge.label-ptt; color: Theme.fg; vertical-alignment: center; horizontal-alignment: center; wrap: word-wrap; }
desktop-ptt := TouchArea { enabled: ShellBridge.ptt-enabled; pointer-event(e) => { if e.kind == PointerEventKind.down { ShellBridge.held(true); } else if e.kind == PointerEventKind.up || e.kind == PointerEventKind.cancel { ShellBridge.held(false); } } }
}
if Theme.android: Rectangle { min-width: 48px; horizontal-stretch: 1; min-height: Theme.touch-target; background: ptt.pressed ? Theme.tint : Theme.bg; border-radius: 4px; opacity: ShellBridge.ptt-enabled ? 1 : 0.45;
accessible-role: button; accessible-label: ShellBridge.label-ptt; accessible-enabled: ShellBridge.ptt-enabled;
border-width: ptt-focus.has-focus ? 2px : 0px; border-color: Theme.outline;
Text { text: ShellBridge.label-ptt; color: Theme.fg; vertical-alignment: center; horizontal-alignment: center; wrap: word-wrap; }
ptt-focus := FocusScope {
enabled: ShellBridge.ptt-enabled;
changed has-focus => { if !self.has-focus { ShellBridge.held(false); } }
key-pressed(e) => { if e.text == " " || e.text == Key.Return { ShellBridge.held(true); return accept; } return reject; }
key-released(e) => { if e.text == " " || e.text == Key.Return { ShellBridge.held(false); return accept; } return reject; }
}
ptt := TouchArea {
enabled: ShellBridge.ptt-enabled;
pointer-event(e) => { if e.button == PointerEventButton.left && e.kind == PointerEventKind.down { ptt-focus.focus(); ShellBridge.held(true); } else if e.kind == PointerEventKind.up || e.kind == PointerEventKind.cancel { ShellBridge.held(false); } }
moved => { if self.pressed && (self.mouse-x < 0px || self.mouse-y < 0px || self.mouse-x > self.width || self.mouse-y > self.height) { ShellBridge.held(false); } }
}
}
}
}
}
if ShellBridge.status != "": Text { text: ShellBridge.status; color: Theme.muted; overflow: elide; }
if root.compact && !root.typing: HorizontalLayout { for label[index] in ShellBridge.destinations: ActionButton { min-width: Theme.android ? 48px : 0px; horizontal-stretch: 1; text: label; primary: ShellBridge.destination == index; clicked => { ShellBridge.navigate(index); } } }
if root.compact: HorizontalLayout { for label[index] in ShellBridge.destinations: ActionButton { min-width: 0px; horizontal-stretch: 1; text: label; primary: ShellBridge.destination == index; clicked => { ShellBridge.navigate(index); } } }
}
if ShellBridge.fullscreen-stream != "": Rectangle {
if Theme.android: AndroidShell { }
if !Theme.android && ShellBridge.fullscreen-stream != "": Rectangle {
background: Theme.contrast;
VerticalLayout {
ActionButton { text: ShellBridge.label-close; clicked => { ShellBridge.fullscreen-stream = ""; } }
for stream in ShellBridge.streams: StreamTile { visible: stream.id == ShellBridge.fullscreen-stream; height: self.visible ? parent.height - Theme.touch-target : 0px; item: stream; }
}
}
if ShellBridge.menu-visible: Rectangle {
if !Theme.android && ShellBridge.menu-visible: Rectangle {
background: Theme.contrast.with-alpha(0.7);
TouchArea { clicked => { ShellBridge.close-menu(); } }
Rectangle {
width: min(parent.width - 24px,360px); height: min(parent.height - 24px, menu.preferred-height);
x: parent.width - self.width - 12px; y: root.compact ? parent.height - self.height - 12px : 12px;
background: Theme.header; border-radius: 8px; border-width: 1px; border-color: Theme.outline;
menu := VerticalLayout { padding: 12px; spacing: 8px; Text { text: ShellBridge.menu-title; color: Theme.fg; font-weight: 600; wrap: word-wrap; } ScrollView { min-height: Theme.android ? min(Theme.touch-target * 3, max(0px, root.height - 160px)) : 0px; CommandList { commands: ShellBridge.menu-actions; } } ActionButton { text: ShellBridge.label-close; clicked => { ShellBridge.close-menu(); } } }
menu := VerticalLayout { padding: 12px; spacing: 8px; Text { text: ShellBridge.menu-title; color: Theme.fg; font-weight: 600; wrap: word-wrap; } ScrollView { min-height: 0px; CommandList { commands: ShellBridge.menu-actions; } } ActionButton { text: ShellBridge.label-close; clicked => { ShellBridge.close-menu(); } } }
}
}
if Theme.android && ShellBridge.fullscreen-stream != "": Rectangle {
background: Theme.contrast;
VerticalLayout {
ActionButton { text: ShellBridge.label-close; clicked => { ShellBridge.fullscreen-stream = ""; } }
ScrollView { min-height: 0px; vertical-stretch: 1;
VerticalLayout { padding: 8px; for stream in ShellBridge.streams: VerticalLayout { if stream.id == ShellBridge.fullscreen-stream: StreamTile { item: stream; } } }
}
}
}
if Theme.android && ShellBridge.menu-visible: Rectangle {
background: Theme.contrast.with-alpha(0.7);
TouchArea { clicked => { ShellBridge.close-menu(); } }
Rectangle {
width: min(parent.width - 16px,480px); height: min(parent.height - 16px,phone-menu.preferred-height);
x: (parent.width - self.width)/2; y: parent.height - self.height - 8px;
background: Theme.header; border-radius: 8px; border-width: 1px; border-color: Theme.outline;
phone-menu := VerticalLayout { padding: 12px; spacing: 8px;
menu-title := Text { text: ShellBridge.menu-title; color: Theme.fg; font-weight: 600; wrap: word-wrap; max-height: root.height * 0.2; overflow: elide; }
ScrollView { height: min(phone-commands.preferred-height,max(0px,root.height - menu-title.preferred-height - menu-close.preferred-height - 64px));
phone-commands := VerticalLayout { spacing: 8px;
CommandList { commands: ShellBridge.menu-actions; }
ActionButton { text: ShellBridge.destinations[2]; clicked => { ShellBridge.room-navigate(4); } }
ActionButton { text: ShellBridge.label-bookmarks; clicked => { ShellBridge.room-navigate(6); } }
ActionButton { text: ShellBridge.room-labels[10]; clicked => { ShellBridge.room-navigate(5); } }
}
}
menu-close := ActionButton { text: ShellBridge.label-close; clicked => { ShellBridge.close-menu(); } }
}
}
}
}
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff. Show more