Complete Android lifecycle and phone UI fixes for external build handoff
This commit is contained in:
1 parent
cb1d682dfb
commit
3d2e76eddd
31 files changed
+790
-129
No files matched your search
@@ -2,6 +2,24 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- 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
|
||||
|
||||
@@ -78,18 +78,18 @@ it refuses to overwrite an existing release. Manual dispatch builds/verifies wit
|
||||
The Python tests mock HTTP and never publish. Native compilation, UI smoke and device acceptance
|
||||
remain separate checks; removing the Electron updater harness does not establish native update E2E.
|
||||
|
||||
### Android development (Windows, Linux CI)
|
||||
### Android development (Windows, separate Linux build host)
|
||||
|
||||
The selected Android route is **develop on Windows → manually dispatch Gitea Actions → build and
|
||||
package entirely on Linux CI → download artifacts → install the test-only APK with Windows `adb`**.
|
||||
WSL, Docker and a local Linux installation are **not required on the developer PC**. Windows needs
|
||||
the editor/source checkout, a browser for Gitea and Android SDK Platform-Tools for device installation;
|
||||
the Android SDK/NDK, Java and heavy native build tools belong on the CI runner for this route.
|
||||
Develop the existing Rust/Slint Android client on Windows; build/package on a separately authorized
|
||||
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.
|
||||
|
||||
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 for CI,
|
||||
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. CI keeps the full **Skia + WebRTC** feature set and pinned-source/receipt checks.
|
||||
alternative. Keep the full **Skia + WebRTC** feature set and pinned-source/receipt checks.
|
||||
|
||||
#### CI administrator prerequisites
|
||||
|
||||
@@ -116,6 +116,66 @@ allows Gradle dependency resolution on CI; the ordinary packaging default remain
|
||||
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
|
||||
|
||||
Use Linux x64 inside WSL2, with the source and caches in its Linux filesystem (for example
|
||||
`~/src/TeamsPeach`), not a shared Windows `target/`. No Android emulator is required to build an APK.
|
||||
The receiving developer must approve tool installation, storage and resource limits on **their** PC.
|
||||
This is the same Linux source-build route, not a separately tested WSL product configuration.
|
||||
|
||||
1. Receive a **committed and pushed** `feature/mobile-port` revision containing the Android changes.
|
||||
The sender supplies its full SHA; the receiver checks `git rev-parse HEAD` against it and begins
|
||||
from a clean worktree. `cb1d682` is only the earlier CI-inventory baseline, not the completed port.
|
||||
Do not build `main` or assume uncommitted sender changes were transferred. Build fixes need their
|
||||
own commits and a new recorded SHA, not an APK with undocumented source modifications.
|
||||
2. Provision the versions/tools in the table above, plus Rust 1.96.0 and its
|
||||
`aarch64-linux-android` standard library. Use matching Linux LLVM/libclang and dependency-synchronized
|
||||
Skia sources, not Windows caches. Cargo/WebRTC/CIPD/Gradle dependency resolution needs network access.
|
||||
The Android dependency receipt must be generated by `xtask deps`, never copied from Windows or forged.
|
||||
3. Set these variables to **existing absolute Linux paths**: `ANDROID_SDK_ROOT`, `JAVA_HOME`,
|
||||
`LLVM_HOME`, `LIBCLANG_PATH`, `SKIA_SOURCE_DIR`, `TEAMSPEACH_GRADLE_DISTRIBUTION`, and
|
||||
`TEAMSPEACH_BUNDLETOOL` (the same inputs as the CI table, mapped to the names consumed by tools).
|
||||
Do not provide production signing credentials for the test-only build. From the repository root:
|
||||
|
||||
```bash
|
||||
set -euo pipefail
|
||||
: "${ANDROID_SDK_ROOT:?}" "${JAVA_HOME:?}" "${LLVM_HOME:?}" "${LIBCLANG_PATH:?}"
|
||||
: "${SKIA_SOURCE_DIR:?}" "${TEAMSPEACH_GRADLE_DISTRIBUTION:?}" "${TEAMSPEACH_BUNDLETOOL:?}"
|
||||
export TARGET=aarch64-linux-android
|
||||
export EXPECTED_REVISION="$(git rev-parse HEAD)"
|
||||
export CI_RUN_ID="wsl2-$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
export CARGO_BUILD_JOBS=1
|
||||
export CARGO_TARGET_DIR="$PWD/target"
|
||||
export GRADLE_USER_HOME="$PWD/target/android-gradle-cache"
|
||||
export ANDROID_HOME="$ANDROID_SDK_ROOT"
|
||||
export ANDROID_NDK_ROOT="$ANDROID_SDK_ROOT/ndk/28.2.13676358"
|
||||
export ANDROID_NDK_HOME="$ANDROID_NDK_ROOT"
|
||||
export SKIA_GN_COMMAND="$SKIA_SOURCE_DIR/bin/gn"
|
||||
export SKIA_NINJA_COMMAND="$(command -v ninja)"
|
||||
export PATH="$JAVA_HOME/bin:$LLVM_HOME/bin:$ANDROID_SDK_ROOT/build-tools/36.0.0:$PATH"
|
||||
cargo run --locked -p xtask -- check-version
|
||||
cargo run --locked -p xtask -- deps --target "$TARGET" --llvm-dir "$LLVM_HOME" --jobs 1
|
||||
bash .gitea/build-android-variant.sh harness
|
||||
```
|
||||
|
||||
The helper uses the existing `xtask build`, `package` and `verify-package` commands and writes
|
||||
`dist/android/harness/build-info.json`. Its `CI_RUN_ID` is a local provenance label here, not a claim
|
||||
that Gitea ran the build. Package directories must be fresh; preserve failed results/caches and
|
||||
explicitly move aside an old `dist/android/harness` before retrying. Do not run `cargo clean`.
|
||||
One Cargo job is only build parallelism, not a complete memory guard; choose WSL/host memory limits
|
||||
with that PC's owner before starting heavy compilation.
|
||||
4. Return the **whole `dist/android/harness` bundle**, including `*-harness-test.apk`,
|
||||
`build-info.json`, `package-report.json`, `verification.json`, `native-build.json`,
|
||||
`native-deps.lock.json` and `dependency-provenance.json`. Return the exact source SHA and
|
||||
build errors/fixes separately; omit credentials, private signing material and app/user profiles.
|
||||
Verify `passed=true`, ARM64, test-only signing and APK SHA256 before delivery.
|
||||
5. Optional production build is a separate decision: the same helper with `production` creates
|
||||
unsigned APK/AAB, not an installable release. Do not publish, sign for production, install on a
|
||||
phone, access a microphone or connect to a server without the relevant owner's explicit approval.
|
||||
|
||||
The receiver's first build still needs to establish Rust/Java/JNI/Gradle integration. A build pass
|
||||
does not establish phone UI, permissions, audio routes, foreground behavior or two-way voice.
|
||||
|
||||
#### Dispatch, download and install from Windows
|
||||
|
||||
1. Deliver the source changes through the normal authorized repository process. In the repository's
|
||||
@@ -155,10 +215,11 @@ No production signing credentials are needed or used by this unsigned-artifact w
|
||||
The **unsigned production APK is not installable** until separately authorized production signing
|
||||
and signature verification are completed. **An AAB is not directly installable with `adb install`**;
|
||||
it requires the separate signing/store or APK-generation process. These bundles are not a release.
|
||||
The harness is for test-only/offline smoke scenarios, not production feature/device acceptance.
|
||||
Neither this workflow configuration nor installing a harness proves live voice, official-client
|
||||
interoperability, Bluetooth/background behavior or full mobile parity. No successful CI run, generated
|
||||
APK/AAB, device install or mobile acceptance is claimed here.
|
||||
The harness supports isolated offline smoke; a normal launch without smoke extras uses the ordinary
|
||||
runtime and must be confined to an authorized disposable test installation. It is not production
|
||||
feature/device acceptance. Neither configuration nor installation proves live voice, official-client
|
||||
interoperability, Bluetooth/background behavior or full mobile parity. The read-only runner inventory
|
||||
passed; no successful Android build, generated APK/AAB, device install or mobile acceptance is claimed.
|
||||
|
||||
**iOS still requires macOS and Xcode/Apple SDKs**, either locally or on separately provisioned macOS
|
||||
CI, plus appropriate signing/provisioning for devices. Windows editing does not make iOS buildable
|
||||
|
||||
@@ -329,7 +329,7 @@ flowchart LR
|
||||
Этот раздел дополняет, а не исправляет исторический снимок выше. Владелец выбрал маршрут
|
||||
**Windows-разработка → ручной Gitea Actions → вся Android-сборка на Linux CI → скачивание
|
||||
артефактов → установка тестового APK через Windows `adb`**. Точные workflow, runner label,
|
||||
repository variables и имена артефактов указаны в [актуальном README](../README.md#android-development-windows-linux-ci).
|
||||
repository variables и имена артефактов указаны в [актуальном README](../README.md#android-development-windows-separate-linux-build-host).
|
||||
Существующие Linux desktop workflows остаются отдельными: Linux desktop package не является Android APK.
|
||||
|
||||
### Где выполняется сборка
|
||||
@@ -384,3 +384,85 @@ Application ID `dev.teamspeach.mobile` общий с production ([Gradle](../pla
|
||||
**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.
|
||||
|
||||
@@ -1,6 +1,56 @@
|
||||
# Мобильный порт: передача состояния
|
||||
|
||||
Обновлено: **2026-11-11**. Принятая Windows-база **`05e8d34bcf0e24a44f76e65220293c45b6821798`** опубликована в `origin/main` с тегом **`desktop-baseline-0.1.7-20261111`**. Дальнейшая мобильная разработка — локальная активная `feature/mobile-port` от этой базы. Единственный application host — Rust/Slint; результаты ниже отделены от первоначального read-only исследования.
|
||||
Обновлено: **2026-11-11**. Принятая Windows-база **`05e8d34bcf0e24a44f76e65220293c45b6821798`** опубликована в `origin/main` с тегом **`desktop-baseline-0.1.7-20261111`**. Активная мобильная ветка — **`feature/mobile-port`**; Android implementation подготовлена поверх `cb1d682dfb307ec41d73434ab40de5de0b30410e` к разрешённому владельцем commit/push. Получатель должен сверить полный SHA переданной ревизии, содержащей этот handoff и Android-код, с `git rev-parse HEAD`; прежний `cb1d682` не является ревизией готовой передачи. Следующий этап — Linux-сборка на WSL2 другого разработчика. На этом ПК WSL не возвращать. CI/provisioning и iOS отложены. Rust/Slint — единственный host; APK/device proof отсутствует. История ниже не заменяет текущий статус.
|
||||
|
||||
## Текущий этап: реализация Android, CI отложен
|
||||
|
||||
- По последнему указанию пользователя работа переключена с 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.
|
||||
|
||||
### Продолжение перед передачей другому разработчику
|
||||
|
||||
- Закрыты дополнительные 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.
|
||||
|
||||
|
||||
## Принятая Windows-база и мобильная ветка
|
||||
|
||||
@@ -44,6 +94,17 @@
|
||||
- Пользователь подтвердил **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
|
||||
|
||||
|
||||
@@ -106,6 +106,8 @@ impl RuntimeServices {
|
||||
&&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.
|
||||
@@ -115,6 +117,8 @@ impl RuntimeServices {
|
||||
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)}
|
||||
|
||||
@@ -58,6 +58,12 @@ async fn platform(ctx:&Arc<RuntimeServices>,runtime:&Weak<AppRuntime>,state:&mut
|
||||
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?;}},
|
||||
|
||||
@@ -59,14 +59,20 @@ pub(super) async fn save_document(ctx:&RuntimeServices,target:&Target,name:Strin
|
||||
let selected=ctx.pick(PickRequest::Save{suggested_name:name,mime_type:mime.into()}).await?;
|
||||
ctx.require_target(target)?;
|
||||
let Some(Selection::Document(grant))=selected else{return Ok(None)};
|
||||
#[cfg(not(target_os="android"))]
|
||||
if grant.size()?.is_some()&&!confirm(ctx,target,Operation::ConfirmOverwrite,catalog(ctx)?.format("files.confirm.replace_local",&[("name",grant.display_name())]),Some(grant.display_name().into())).await?{return Ok(None)}
|
||||
ctx.require_target(target)?;Ok(Some(grant))
|
||||
}
|
||||
pub(super) async fn child_document(ctx:&RuntimeServices,target:&Target,directory:Arc<dyn DirectoryGrant>,name:&str)->Result<Option<Arc<dyn DocumentGrant>>>{
|
||||
ctx.require_target(target)?;
|
||||
match directory.child(name,false){Ok(grant)=>Ok(Some(grant)),Err(e)if matches!(e.code.as_str(),"overwrite_confirmation"|"file_exists"|"confirmation_required")=>{
|
||||
if !confirm(ctx,target,Operation::ConfirmOverwrite,catalog(ctx)?.format("files.confirm.replace_local",&[("name",name)]),Some(name.into())).await?{return Ok(None)}
|
||||
ctx.require_target(target)?;Ok(Some(directory.child(name,true)?))
|
||||
#[cfg(target_os="android")]
|
||||
{return save_document(ctx,target,name.into(),"application/octet-stream").await;}
|
||||
#[cfg(not(target_os="android"))]
|
||||
{
|
||||
if !confirm(ctx,target,Operation::ConfirmOverwrite,catalog(ctx)?.format("files.confirm.replace_local",&[("name",name)]),Some(name.into())).await?{return Ok(None)}
|
||||
ctx.require_target(target)?;Ok(Some(directory.child(name,true)?))
|
||||
}
|
||||
},Err(e)=>Err(e)}
|
||||
}
|
||||
/// A new OS descriptor and its grant are retained together throughout all reads.
|
||||
|
||||
@@ -8,7 +8,12 @@ impl RuntimeServices {
|
||||
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;
|
||||
if call.as_ref().is_some_and(|(current,enabled)|current==key&&(*enabled||!microphone)){return Ok(())}
|
||||
#[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;}}
|
||||
@@ -24,6 +29,31 @@ impl RuntimeServices {
|
||||
}
|
||||
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(())}
|
||||
|
||||
@@ -18,6 +18,8 @@ async fn sync_audio_to(ctx:Arc<RuntimeServices>,active:(bool,bool))->Result<()>
|
||||
let _configuration=ctx.audio_configuration.lock().await;
|
||||
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());
|
||||
#[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)));
|
||||
ctx.audio.revoke_capture();
|
||||
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());
|
||||
|
||||
@@ -32,7 +32,24 @@ pub(super) async fn invoke(ctx:Arc<RuntimeServices>,op:Operation)->Result<Workfl
|
||||
let Some(Selection::Document(grant))=ctx.pick(PickRequest::Save{suggested_name:"identity.ini".into(),mime_type:"text/plain".into()}).await? else{return done()};
|
||||
let check=grant.clone();let existing=tokio::task::spawn_blocking(move||check.size()).await.map_err(|_|bad("Export worker stopped"))??;
|
||||
if existing.is_some_and(|size|size!=0)&&!confirm(&ctx,"Overwrite identity export","The selected file already contains data. Replace it with this private identity?").await?{return done()}
|
||||
ctx.mutate(move|p|{let data=Zeroizing::new(p.identities.export_ini(&uid,true)?);let mut file=GrantedFile::write(grant,true)?;file.write_all(data.as_bytes())?;file.sync_all()?;Ok(())}).await?;done()
|
||||
#[cfg(target_os="android")]
|
||||
{
|
||||
let identities=ctx.profile()?.identities.clone();
|
||||
let folder=ctx.root.join("file-workflows").join("identity-exports").join(uuid::Uuid::new_v4().to_string());
|
||||
let staging=folder.clone();
|
||||
let source=tokio::task::spawn_blocking(move||->Result<std::path::PathBuf>{
|
||||
let data=Zeroizing::new(identities.export_ini(&uid,true)?);
|
||||
teamspeach_core::secure_fs::ensure_private_dir(&staging)?;
|
||||
let path=staging.join("identity.ini");
|
||||
teamspeach_core::secure_fs::write_atomic(&path,data.as_bytes(),true)?;
|
||||
Ok(path)
|
||||
}).await.map_err(|_|bad("Export worker stopped"))??;
|
||||
ctx.commit_document(grant,source,None).await?;
|
||||
tokio::task::spawn_blocking(move||std::fs::remove_dir_all(folder)).await.map_err(|_|bad("Export worker stopped"))??;
|
||||
}
|
||||
#[cfg(not(target_os="android"))]
|
||||
ctx.mutate(move|p|{let data=Zeroizing::new(p.identities.export_ini(&uid,true)?);let mut file=GrantedFile::write(grant,true)?;file.write_all(data.as_bytes())?;file.sync_all()?;Ok(())}).await?;
|
||||
done()
|
||||
},
|
||||
Operation::IdentityImprove(uid)=>{
|
||||
ctx.require_idle()?;
|
||||
|
||||
@@ -94,6 +94,13 @@ 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}
|
||||
#[cfg(target_os="android")]
|
||||
if let AndroidCallAudio{key,token,revision,..}=&event {
|
||||
if !platform::android::voice_audio_current(key,*token,*revision){return}
|
||||
self.release_held();
|
||||
}
|
||||
#[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 self.enqueue(app::runtime::RuntimeCommand::Platform(event)).is_err(){self.cancel.send_replace(true);}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use crate::{AppConfig, AppRuntime, app::connections::SessionKey, services::{Resu
|
||||
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};
|
||||
@@ -17,7 +18,7 @@ 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>, _runtime: Arc<AppRuntime> }
|
||||
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> }
|
||||
@@ -141,7 +142,7 @@ pub async fn request_permission(permission: Permission, policy: ActionPolicy) ->
|
||||
/// 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, _runtime: runtime }); }
|
||||
{ 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);
|
||||
@@ -163,7 +164,7 @@ pub async fn set_voice_capture(key: &SessionKey, enabled: bool, policy: ActionPo
|
||||
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.capture_change=None;true}else{false}};
|
||||
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};
|
||||
@@ -174,9 +175,25 @@ pub async fn set_voice_capture(key: &SessionKey, enabled: bool, policy: ActionPo
|
||||
_=>Err(error("call_capture_failed","Android did not acknowledge the microphone service transition")),
|
||||
}
|
||||
}
|
||||
fn revoke_voice_capture(token:u64) {
|
||||
let pending={let mut slot=VOICE.lock().expect("Android voice");if let Some(voice)=slot.as_mut().filter(|voice|voice.token==token){voice.microphone=false;voice.capture_revision=0;voice.capture_change.take()}else{None}};
|
||||
if let Some(id)=pending{complete(id,Err(error("call_capture_revoked","The Android call continues receive-only; microphone authorization ended")));}
|
||||
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 } };
|
||||
@@ -259,6 +276,18 @@ pub async fn open_store(policy: ActionPolicy) -> Result<()> {
|
||||
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 {
|
||||
@@ -314,15 +343,14 @@ pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeText(mut
|
||||
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;true}else{false}};
|
||||
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){
|
||||
if !VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|voice.token==token as u64){return;}
|
||||
match event{2=>{lifecycle::emit(PlatformEvent::AudioInterruption{began:value!=0,should_resume:value==0});},3=>{lifecycle::emit(PlatformEvent::AudioRouteChanged);},_=>{}}
|
||||
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{
|
||||
@@ -334,11 +362,11 @@ pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceCapt
|
||||
}
|
||||
#[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)){voice.microphone=enabled!=0;voice.capture_change=None;true}else{false}};
|
||||
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){revoke_voice_capture(token as u64);}
|
||||
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}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Android call authorization; focus/route changes never restore microphone consent.
|
||||
#[derive(Default)]
|
||||
pub(super) struct CallAudioState {
|
||||
revision: u64,
|
||||
focused: bool,
|
||||
capture: bool,
|
||||
restart_output: bool,
|
||||
}
|
||||
impl CallAudioState {
|
||||
pub fn start(&mut self, capture: bool) { self.focused = true; self.capture = capture; }
|
||||
pub fn change_capture(&mut self, enabled: bool) -> bool {
|
||||
if enabled && !self.focused { return false; }
|
||||
self.capture = enabled;
|
||||
self.revision = self.revision.checked_add(1).expect("Android audio revision exhausted");
|
||||
true
|
||||
}
|
||||
pub fn interrupt(&mut self, focused: bool) -> u64 {
|
||||
self.focused = focused;
|
||||
self.restart_output = true;
|
||||
self.revoke_capture()
|
||||
}
|
||||
pub fn revoke_capture(&mut self) -> u64 {
|
||||
self.capture = false;
|
||||
self.revision = self.revision.checked_add(1).expect("Android audio revision exhausted");
|
||||
self.revision
|
||||
}
|
||||
pub fn route_changed(&mut self) -> u64 {
|
||||
self.restart_output = true;
|
||||
self.revoke_capture()
|
||||
}
|
||||
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 allows(&self, microphone: bool) -> bool { self.focused && (!microphone || self.capture) }
|
||||
pub fn is_current(&self, revision: u64) -> bool { self.revision == revision }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::CallAudioState;
|
||||
#[test]
|
||||
fn focus_gain_restores_only_receive_authorization() {
|
||||
let mut state = CallAudioState::default();
|
||||
assert!(!state.allows(false));
|
||||
state.start(true);
|
||||
let lost = state.interrupt(false);
|
||||
assert!(!state.allows(false));
|
||||
assert!(!state.change_capture(true));
|
||||
let gained = state.interrupt(true);
|
||||
assert!(state.allows(false));
|
||||
assert!(!state.allows(true));
|
||||
assert!(!state.is_current(lost));
|
||||
assert!(state.is_current(gained));
|
||||
assert!(state.change_capture(true));
|
||||
assert!(state.allows(true));
|
||||
assert!(!state.is_current(gained), "queued recovery must not mute a newer explicit activation");
|
||||
}
|
||||
#[test]
|
||||
fn route_or_permission_revocation_keeps_receive_only() {
|
||||
let mut state = CallAudioState::default();
|
||||
state.start(true);
|
||||
let route = state.revoke_capture();
|
||||
assert!(state.allows(false));
|
||||
assert!(!state.allows(true));
|
||||
state.change_capture(true);
|
||||
let permission = state.revoke_capture();
|
||||
assert!(!state.is_current(route));
|
||||
assert!(state.is_current(permission));
|
||||
assert!(!state.allows(true));
|
||||
}
|
||||
#[test]
|
||||
fn later_microphone_revocation_preserves_pending_output_recovery() {
|
||||
let mut state = CallAudioState::default();
|
||||
state.start(true);
|
||||
let route = state.route_changed();
|
||||
let permission = state.revoke_capture();
|
||||
assert!(!state.is_current(route));
|
||||
assert!(state.restart_output());
|
||||
state.acknowledge_output(route);
|
||||
assert!(state.restart_output());
|
||||
state.acknowledge_output(permission);
|
||||
assert!(!state.restart_output());
|
||||
assert!(state.allows(false));
|
||||
assert!(!state.allows(true));
|
||||
}
|
||||
}
|
||||
@@ -8,13 +8,23 @@ impl Drop for Grant { fn drop(&mut self) { let _=with_env(|env,_|{java(env.call_
|
||||
pub(super) struct Document { grant: Arc<Grant> }
|
||||
struct Directory { grant: Arc<Grant> }
|
||||
fn grant(env:&mut JNIEnv<'_>,object:JObject<'_>)->Result<Arc<Grant>> {
|
||||
let name=java(env.get_field(&object,"name","Ljava/lang/String;"))?.l().map_err(|_|error("document_grant","Provider returned no document name"))?;
|
||||
let name=JString::from(name); let name=java(env.get_string(&name))?.into();
|
||||
Ok(Arc::new(Grant{object:java(env.new_global_ref(object))?,name}))
|
||||
let result=(||{
|
||||
let name=java(env.get_field(&object,"name","Ljava/lang/String;"))?.l().map_err(|_|error("document_grant","Provider returned no document name"))?;
|
||||
if name.is_null(){return Err(error("document_grant","Provider returned no document name"));}
|
||||
let name=JString::from(name); let name=java(env.get_string(&name))?.into();
|
||||
Ok(Arc::new(Grant{object:java(env.new_global_ref(&object))?,name}))
|
||||
})();
|
||||
if result.is_err(){
|
||||
let _=env.exception_clear();
|
||||
let _=env.call_method(&object,"close","()V",&[]);
|
||||
let _=env.exception_clear();
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(super) fn selection(env:&mut JNIEnv<'_>,object:JObject<'_>)->Result<Selection>{
|
||||
let directory=java(env.get_field(&object,"directory","Z"))?.z().unwrap_or(false);
|
||||
let grant=grant(env,object)?;
|
||||
let result=env.get_field(grant.object.as_obj(),"directory","Z");
|
||||
let directory=result.map_err(|_|provider_error(env))?.z().map_err(|_|error("document_grant","Invalid document capability kind"))?;
|
||||
Ok(if directory{Selection::Directory(Arc::new(Directory{grant}))}else{Selection::Document(Arc::new(Document{grant}))})
|
||||
}
|
||||
|
||||
@@ -34,12 +44,12 @@ fn provider_error(env:&mut JNIEnv<'_>)->crate::services::ServiceError {
|
||||
}
|
||||
}
|
||||
let _=env.exception_clear();
|
||||
error("document_provider_error","The Android document provider denied access, was revoked, or failed. Source staging is retained; choose another destination.")
|
||||
error("document_provider_error","The Android document provider denied access, was revoked, or failed. Choose the document or destination again.")
|
||||
}
|
||||
impl DocumentGrant for Document {
|
||||
fn as_any(&self)->&dyn std::any::Any{self}
|
||||
fn display_name(&self)->&str{&self.grant.name}
|
||||
fn size(&self)->Result<Option<u64>>{with_env(|env,_|{let length=java(env.call_method(self.grant.object.as_obj(),"size","()J",&[]))?.j().map_err(|_|error("document_grant","Invalid document size"))?;Ok((length>=0).then_some(length as u64))})}
|
||||
fn size(&self)->Result<Option<u64>>{with_env(|env,_|{let result=env.call_method(self.grant.object.as_obj(),"size","()J",&[]);let length=result.map_err(|_|provider_error(env))?.j().map_err(|_|error("document_grant","Invalid document size"))?;Ok((length>=0).then_some(length as u64))})}
|
||||
fn open_read(&self)->Result<File>{self.open(false,false)}
|
||||
fn open_write(&self,truncate:bool)->Result<File>{self.open(true,truncate)}
|
||||
fn commit_from(&self,source:&Path,cancelled:&dyn Fn()->bool)->Result<()> {
|
||||
@@ -96,7 +106,9 @@ impl DirectoryGrant for Directory {
|
||||
fn display_name(&self)->&str{&self.grant.name}
|
||||
fn child(&self,name:&str,overwrite:bool)->Result<Arc<dyn DocumentGrant>>{
|
||||
require_component(name)?;
|
||||
with_env(|env,_|{let name=java(env.new_string(name))?;let object=java(env.call_method(self.grant.object.as_obj(),"child","(Ljava/lang/String;Z)Ldev/teamspeach/mobile/SafGrant;",&[JValue::Object(&name),JValue::Bool(overwrite as u8)]))?.l().map_err(|_|error("document_grant","Provider refused the directory child"))?;
|
||||
with_env(|env,_|{let name=java(env.new_string(name))?;
|
||||
let result=env.call_method(self.grant.object.as_obj(),"child","(Ljava/lang/String;Z)Ldev/teamspeach/mobile/SafGrant;",&[JValue::Object(&name),JValue::Bool(overwrite as u8)]);
|
||||
let object=result.map_err(|_|provider_error(env))?.l().map_err(|_|error("document_grant","Provider refused the directory child"))?;
|
||||
if object.is_null(){return Err(error("document_grant","Provider refused the directory child"));}
|
||||
Ok(Arc::new(Document{grant:grant(env,object)?}) as Arc<dyn DocumentGrant>)
|
||||
})
|
||||
|
||||
@@ -26,6 +26,9 @@ pub enum PlatformEvent {
|
||||
ScreenLocked(bool),
|
||||
PermissionChanged{permission:Permission,granted:bool},
|
||||
CallLeaseEnded{key:SessionKey},
|
||||
/// OS callbacks are tied to the exact Android lease and authorization revision.
|
||||
#[cfg(target_os="android")]
|
||||
AndroidCallAudio{key:SessionKey,token:u64,revision:u64,restart_output:bool},
|
||||
Notification{key:SessionKey,action:NotificationAction},
|
||||
MemoryPressure,
|
||||
Quit,
|
||||
|
||||
@@ -91,7 +91,7 @@ fn update(ui:&AppWindow,runtime:&AppRuntime,bindings:&mut Bindings){
|
||||
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&&!new_frames.is_empty(){bindings.shell.update_frames(ui,&new_frames);}
|
||||
{let shell=ui.global::<ShellBridge>();let compact=ui.window().size().width as f32/ui.window().scale_factor()<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);}
|
||||
{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{
|
||||
UiEffect::FormComplete{id,target,result}=>bindings.shell.complete(ui,&id,&target,result.map_err(|error|error.message)),
|
||||
UiEffect::SettingsAcknowledge(id)=>bindings.settings.acknowledge(&id),
|
||||
@@ -110,6 +110,8 @@ fn update(ui:&AppWindow,runtime:&AppRuntime,bindings:&mut Bindings){
|
||||
UiEffect::StreamClose{target}=>{let _=bindings.shell.stream_effect(ui,&target,false,true);},
|
||||
UiEffect::Quit=>{let _=ui.hide();let _=slint::quit_event_loop();},
|
||||
UiEffect::Theme(theme)=>{let mut current=(*snapshot).clone();current.theme=Some(theme);apply_theme(ui,¤t);},
|
||||
#[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(),
|
||||
_=>{}
|
||||
}}
|
||||
}
|
||||
@@ -117,6 +119,7 @@ fn apply_theme(ui:&AppWindow,snapshot:&Snapshot){
|
||||
use crate::services::themes::TokenValue;
|
||||
let theme=ui.global::<Theme>();let prefs=&snapshot.settings.prefs;let dark=if prefs["theme"]=="system"{snapshot.theme.as_ref().and_then(|resolved|resolved.base_values.get("--tsv-bg")).and_then(|value|if let TokenValue::Color(color)=value{super::theme::color(color)}else{None}).is_none_or(|color|u32::from(color.red())+u32::from(color.green())+u32::from(color.blue())<384)}else{prefs["theme"]!="light"};theme.set_dark(dark);theme.set_high_contrast(snapshot.high_contrast);theme.set_reduced_motion(snapshot.reduced_motion);
|
||||
theme.set_safe_top(snapshot.insets.top);theme.set_safe_right(snapshot.insets.right);theme.set_safe_bottom(snapshot.insets.bottom);theme.set_safe_left(snapshot.insets.left);theme.set_ime_inset(snapshot.insets.keyboard);
|
||||
theme.set_android(cfg!(target_os="android"));
|
||||
theme.set_touch_target(if cfg!(target_os="android"){48.}else{44.});
|
||||
if let Some(resolved)=&snapshot.theme{
|
||||
let color=|name:&str|resolved.values.get(name).and_then(|value|if let TokenValue::Color(value)=value{super::theme::color(value)}else{None}).or_else(||resolved.base_values.get(name).and_then(|value|if let TokenValue::Color(value)=value{super::theme::color(value)}else{None}));
|
||||
|
||||
+54
-11
@@ -22,10 +22,11 @@ struct State {
|
||||
fields:Rc<VecModel<ShellField>>, tree:Rc<VecModel<ShellRow>>, bookmarks:Rc<VecModel<ShellRow>>, contacts:Rc<VecModel<ShellRow>>, entries: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,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,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<_>>())) }
|
||||
@@ -78,6 +79,12 @@ fn project_editor(ui:&AppWindow,state:&mut State) {
|
||||
}
|
||||
fn release_hold(state:&mut State,emit:&Arc<dyn Fn(ShellAction)+Send+Sync>){if let Some(target)=state.held_target.take(){emit(ShellAction::PushToTalk{target,held:false});}}
|
||||
|
||||
// These operations produce a detail view rather than changing server state. Revealing that
|
||||
// view must not also select, join, download, or otherwise act on its captured target.
|
||||
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)
|
||||
}
|
||||
|
||||
pub fn bind(ui:&AppWindow,emit:Arc<dyn Fn(ShellAction)+Send+Sync>)->ShellBinding {
|
||||
let state=Rc::new(RefCell::new(State::default()));
|
||||
{
|
||||
@@ -88,10 +95,10 @@ pub fn bind(ui:&AppWindow,emit:Arc<dyn Fn(ShellAction)+Send+Sync>)->ShellBinding
|
||||
{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_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||{release_hold(&mut s.borrow_mut(),&e);});}
|
||||
{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();}else{s.stack.push(target.clone());}if let Some(ui)=weak.upgrade(){ui.global::<ShellBridge>().set_depth(s.stack.len() as i32);}e(ShellAction::Select(target));}});}
|
||||
{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();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};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));});}
|
||||
{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));});}
|
||||
{
|
||||
let state=state.clone();let emit=emit.clone();let weak=ui.as_weak();
|
||||
b.on_row_press(move|id,held|{
|
||||
@@ -102,6 +109,7 @@ pub fn bind(ui:&AppWindow,emit:Arc<dyn Fn(ShellAction)+Send+Sync>)->ShellBinding
|
||||
let state=state.clone();let emit=emit.clone();let weak=weak.clone();
|
||||
slint::Timer::single_shot(std::time::Duration::from_millis(550),move||{
|
||||
let mut s=state.borrow_mut();if s.press_epoch!=epoch||s.pressed_row.as_deref()!=Some(id.as_str())||s.targets.get(id.as_str())!=Some(&target){return}
|
||||
if cfg!(target_os="android"){release_hold(&mut s,&emit);}
|
||||
s.suppress_click=Some(id.to_string());s.menu_target=Some(target.clone());
|
||||
let actions=s.contexts.get(id.as_str()).cloned().unwrap_or_default();
|
||||
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);}
|
||||
@@ -109,10 +117,11 @@ pub fn bind(ui:&AppWindow,emit:Arc<dyn Fn(ShellAction)+Send+Sync>)->ShellBinding
|
||||
});
|
||||
});
|
||||
}
|
||||
{let s=state.clone();let weak=ui.as_weak();b.on_menu(move||{if let Some(ui)=weak.upgrade(){let mut s=s.borrow_mut();let actions=s.presentation.actions.clone();s.menu_target=None;let b=ui.global::<ShellBridge>();b.set_menu_title(s.presentation.catalog.text("native.shell.actions").into());b.set_menu_actions(commands(&mut s,"menu",&actions));b.set_menu_visible(true);}});}
|
||||
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_menu(move||{if let Some(ui)=weak.upgrade(){let mut s=s.borrow_mut();if cfg!(target_os="android"){release_hold(&mut s,&e);}let actions=s.presentation.actions.clone();s.menu_target=None;let b=ui.global::<ShellBridge>();b.set_menu_title(s.presentation.catalog.text("native.shell.actions").into());b.set_menu_actions(commands(&mut s,"menu",&actions));b.set_menu_visible(true);}});}
|
||||
{let weak=ui.as_weak();b.on_close_menu(move||{if let Some(ui)=weak.upgrade(){ui.global::<ShellBridge>().set_menu_visible(false);}});}
|
||||
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_invoke(move|id|{
|
||||
let mut s=s.borrow_mut();let Some(action)=s.actions.get(id.as_str()).cloned().filter(|a|a.enabled)else{return};
|
||||
if cfg!(target_os="android"){release_hold(&mut s,&e);}
|
||||
if let Some(ui)=weak.upgrade(){
|
||||
ui.global::<ShellBridge>().set_menu_visible(false);
|
||||
if matches!(action.operation,Operation::StreamFullscreen|Operation::StreamPopout){
|
||||
@@ -122,7 +131,14 @@ pub fn bind(ui:&AppWindow,emit:Arc<dyn Fn(ShellAction)+Send+Sync>)->ShellBinding
|
||||
else if let Err(error)=open_popout(&ui,&mut s,&stream){ui.global::<ShellBridge>().set_error(error.into());}
|
||||
}
|
||||
}else if let Some(form)=action.form{s.editor=Some(Editor::new(form));project_editor(&ui,&mut s);}
|
||||
else{e(ShellAction::Invoke{target:action.target,operation:action.operation});}
|
||||
else{
|
||||
if cfg!(target_os="android") && opens_detail(action.operation){
|
||||
if s.stack.last()!=Some(&action.target){s.stack.push(action.target.clone());}
|
||||
s.selection_actions=false;
|
||||
let bridge=ui.global::<ShellBridge>();bridge.set_depth(s.stack.len() as i32);bridge.set_stage(0);
|
||||
}
|
||||
e(ShellAction::Invoke{target:action.target,operation:action.operation});
|
||||
}
|
||||
}
|
||||
});}
|
||||
{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}});}});}
|
||||
@@ -144,8 +160,19 @@ 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") && 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()));}
|
||||
}
|
||||
}
|
||||
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>){
|
||||
@@ -174,21 +201,28 @@ impl ShellBinding {
|
||||
/// Call on the Slint event loop after runtime has coalesced a snapshot.
|
||||
pub fn present(&self,ui:&AppWindow,p:ShellPresentation){
|
||||
let mut s=self.state.borrow_mut();
|
||||
if s.held_target.as_ref().is_some_and(|target|p.voice.as_ref().is_none_or(|v|&v.target!=target||!v.ptt_enabled)){release_hold(&mut s,&self.emit);}
|
||||
if s.held_target.as_ref().is_some_and(|target|p.voice.as_ref().is_none_or(|v|&v.target!=target||!v.ptt_enabled)||cfg!(target_os="android")&&(p.dialog.is_some()||p.profile_form.is_some())){release_hold(&mut s,&self.emit);}
|
||||
s.targets.clear();s.actions.clear();s.contexts.clear();
|
||||
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();
|
||||
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",&p.detail.entries);reconcile(&s.entries,entries);
|
||||
let entries=rows(&mut s,"entry",&detail.entries);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",&p.detail.actions));
|
||||
b.set_info(model(p.detail.rows.iter().map(|r|ShellInfo{label:r.label.clone().into(),value:r.value.clone().into()}).collect()));
|
||||
b.set_actions(commands(&mut s,"global",&p.actions));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();
|
||||
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));
|
||||
b.set_title(p.detail.title.clone().into());b.set_subtitle(p.detail.subtitle.clone().into());b.set_description(p.detail.description.clone().into());b.set_detail_loading(p.detail.loading);b.set_detail_error(p.detail.error.clone().into());b.set_status(p.status.clone().into());b.set_error(p.error.clone().into());b.set_loading(p.loading);b.set_searchable(p.detail.search_target.is_some());b.set_search(p.detail.search.clone().into());b.set_has_previous(p.detail.page_offset>0);b.set_has_next(p.detail.has_more);
|
||||
b.set_title(detail.title.clone().into());b.set_subtitle(detail.subtitle.clone().into());b.set_description(detail.description.clone().into());b.set_detail_loading(detail.loading);b.set_detail_error(detail.error.clone().into());b.set_status(p.status.clone().into());b.set_error(p.error.clone().into());b.set_loading(p.loading);b.set_searchable(detail.search_target.is_some());b.set_search(detail.search.clone().into());b.set_has_previous(detail.page_offset>0);b.set_has_next(detail.has_more);
|
||||
b.set_destination(destination_index(s.destination));b.set_depth(s.stack.len() as i32);
|
||||
b.set_destinations(strings(["native.navigation.servers","native.navigation.chats","native.navigation.contacts","native.navigation.settings"].map(|k|c.text(k))));
|
||||
b.set_stages(strings(["native.shell.details","native.shell.chat","native.shell.streams"].map(|k|c.text(k))));
|
||||
@@ -247,4 +281,13 @@ mod tests {
|
||||
let mut acknowledged=form;acknowledged.acknowledged_revision=1;editor.merge(acknowledged);
|
||||
assert_eq!(editor.raw.get("name").map(String::as_str),Some(""));assert!(editor.dirty.is_empty());
|
||||
}
|
||||
#[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));
|
||||
}
|
||||
for operation in [Operation::JoinChannel,Operation::Connect,Operation::ToggleMicrophone,Operation::ToggleDeafen,Operation::FileDownload,Operation::FileDelete] {
|
||||
assert!(!opens_detail(operation));
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
-6
@@ -222,13 +222,15 @@ export component ChatScreen inherits Rectangle {
|
||||
private property <bool> show-tools;
|
||||
private property <bool> show-emoji;
|
||||
private property <bool> show-search;
|
||||
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;
|
||||
changed height => { allocated-height = self.height; }
|
||||
changed width => { ChatBridge.layout(max(16, (root.width - 32px) / 1px), max(16, (root.width - 40px) / 1px)); }
|
||||
VerticalLayout {
|
||||
spacing: 0px;
|
||||
if ChatBridge.tabs.length > 0: ScrollView {
|
||||
if ChatBridge.tabs.length > 0 && !root.typing: ScrollView {
|
||||
height: Theme.touch-target; vertical-stretch: 0;
|
||||
HorizontalLayout {
|
||||
spacing: 4px;
|
||||
@@ -239,7 +241,7 @@ export component ChatScreen inherits Rectangle {
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalLayout {
|
||||
if !root.typing: 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(); } }
|
||||
@@ -250,7 +252,7 @@ export component ChatScreen inherits Rectangle {
|
||||
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 ChatBridge.has-older || ChatBridge.older-page || ChatBridge.loading: HorizontalLayout {
|
||||
if !root.typing && (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); } }
|
||||
@@ -280,7 +282,7 @@ export component ChatScreen inherits Rectangle {
|
||||
if ChatBridge.error != "": Text { 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: max(120px, root.allocated-height * 0.55); vertical-stretch: 0;
|
||||
min-height: 92px; max-height: Theme.android ? max(120px, root.allocated-height) : max(120px, root.allocated-height * 0.55); vertical-stretch: 0;
|
||||
VerticalLayout {
|
||||
padding: 8px; spacing: 4px;
|
||||
if ChatBridge.toolbar-visible && (!ChatBridge.toolbar-dynamic || input.has-focus || root.show-tools || root.show-emoji): HorizontalLayout {
|
||||
@@ -295,17 +297,23 @@ export component ChatScreen inherits Rectangle {
|
||||
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: 160px;
|
||||
height: Theme.android ? clamp(root.allocated-height - 240px, 48px, 160px) : 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(160px, ChatBridge.completions.length * Theme.touch-target);
|
||||
height: min(Theme.android ? clamp(root.allocated-height - 240px, 48px, 160px) : 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; } }
|
||||
}
|
||||
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;
|
||||
changed visible-height => {
|
||||
if Theme.android && input.has-focus {
|
||||
if root.caret-y + self.content-y < 0px { self.content-y = -root.caret-y; }
|
||||
if root.caret-y + self.content-y > self.visible-height - 24px { self.content-y = min(0px, self.visible-height - root.caret-y - 24px); }
|
||||
}
|
||||
}
|
||||
VerticalLayout {
|
||||
spacing: 0px;
|
||||
editor-content := Rectangle {
|
||||
@@ -322,6 +330,7 @@ export component ChatScreen inherits Rectangle {
|
||||
changed preedit-text => { ChatBridge.composing = self.preedit-text != ""; ChatBridge.composition-changed(ChatBridge.composing); }
|
||||
edited => { ChatBridge.draft-edited(self.text, self.anchor-position-byte-offset, self.cursor-position-byte-offset); }
|
||||
cursor-position-changed(point) => {
|
||||
root.caret-y = point.y + self.y;
|
||||
ChatBridge.selection-changed(self.anchor-position-byte-offset, self.cursor-position-byte-offset);
|
||||
if point.y + self.y + editor-scroll.content-y < 0px { editor-scroll.content-y = -point.y - self.y; }
|
||||
if point.y + self.y + editor-scroll.content-y > editor-scroll.visible-height - 24px { editor-scroll.content-y = editor-scroll.visible-height - point.y - self.y - 24px; }
|
||||
@@ -344,6 +353,9 @@ export component ChatScreen inherits Rectangle {
|
||||
if event.text == Key.Return || event.text == Key.Tab { ChatBridge.complete(ChatBridge.completion-index); return accept; }
|
||||
if event.text == Key.Escape { ChatBridge.command("dismiss-completion"); return accept; }
|
||||
}
|
||||
// Android's software keyboard needs an ordinary newline; sending
|
||||
// remains the explicit, composition-safe action below the editor.
|
||||
if Theme.android && event.text == Key.Return && !event.modifiers.shift && !event.modifiers.control && !event.modifiers.meta { return reject; }
|
||||
if event.text == Key.Return { if event.modifiers.shift { if ChatBridge.command("newline") { return accept; } } else { ChatBridge.send(); return accept; } }
|
||||
if event.text == Key.Tab { if ChatBridge.command(event.modifiers.shift ? "outdent" : "indent") { return accept; } }
|
||||
if (event.text == Key.UpArrow || event.text == Key.LeftArrow) && self.cursor-position-byte-offset == 0 { if ChatBridge.command(event.modifiers.shift ? "previous-block-select" : "previous-block") { return accept; } }
|
||||
|
||||
@@ -8,7 +8,7 @@ export component ActionButton inherits Rectangle {
|
||||
in property <bool> destructive: false;
|
||||
callback clicked();
|
||||
min-height: Theme.touch-target;
|
||||
min-width: max(44px, label.preferred-width + 24px);
|
||||
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);
|
||||
@@ -66,7 +66,7 @@ export component Toggle inherits Rectangle {
|
||||
in property <bool> enabled: true;
|
||||
in property <string> label;
|
||||
callback toggled(bool);
|
||||
min-width: 44px;
|
||||
min-width: Theme.android ? 48px : 44px;
|
||||
min-height: Theme.touch-target;
|
||||
preferred-width: 48px;
|
||||
accessible-role: checkbox;
|
||||
|
||||
+19
-8
@@ -43,14 +43,18 @@ export component ShellDialog inherits Rectangle {
|
||||
accessible-role: form;
|
||||
accessible-label: DialogBridge.title;
|
||||
property <bool> advanced: false;
|
||||
property <length> focused-y: 0px;
|
||||
layout := VerticalLayout {
|
||||
padding: 20px; spacing: 12px;
|
||||
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; }
|
||||
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; }
|
||||
form-scroll := ScrollView {
|
||||
min-height: 80px; max-height: 600px;
|
||||
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); } }
|
||||
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;
|
||||
@@ -60,13 +64,13 @@ export component ShellDialog inherits Rectangle {
|
||||
if field.kind == 0 || field.kind == 1 || field.kind == 3 || field.kind == 4: TextField {
|
||||
text: field.value; placeholder: field.label; secret: field.kind == 1; enabled: field.enabled && !DialogBridge.busy;
|
||||
edited(value) => { DialogBridge.edit(field.id,value); }
|
||||
changed has-focus => { if self.has-focus { form-scroll.content-y = clamp(-field-row.y,min(0px,form-scroll.visible-height - form-scroll.content-height),0px); } }
|
||||
changed has-focus => { if self.has-focus { dialog.focused-y = field-row.y; form-scroll.content-y = clamp(-field-row.y,min(0px,form-scroll.visible-height - form-scroll.content-height),0px); } }
|
||||
}
|
||||
if field.kind == 2: TextEdit {
|
||||
text: field.value; enabled: field.enabled && !DialogBridge.busy; wrap: word-wrap; min-height: 110px;
|
||||
accessible-label: field.label;
|
||||
edited => { DialogBridge.edit(field.id,self.text); }
|
||||
changed has-focus => { if self.has-focus { form-scroll.content-y = clamp(-field-row.y,min(0px,form-scroll.visible-height - form-scroll.content-height),0px); } }
|
||||
changed has-focus => { if self.has-focus { dialog.focused-y = field-row.y; form-scroll.content-y = clamp(-field-row.y,min(0px,form-scroll.visible-height - form-scroll.content-height),0px); } }
|
||||
}
|
||||
if field.kind == 5: Toggle { 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; selected(index) => { DialogBridge.choose(field.id,index); } }
|
||||
@@ -78,15 +82,22 @@ 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 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 {
|
||||
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 {
|
||||
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(); } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ export global SettingsBridge {
|
||||
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;
|
||||
preferred-height: self.min-height;
|
||||
@@ -72,6 +73,7 @@ component SettingCell inherits Rectangle {
|
||||
field := TextField {
|
||||
text: 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); }
|
||||
}
|
||||
@@ -112,6 +114,7 @@ export component SettingsScreen inherits Rectangle {
|
||||
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;
|
||||
forward-focus: keyboard;
|
||||
keyboard := FocusScope {
|
||||
key-pressed(event) => {
|
||||
@@ -166,8 +169,12 @@ export component SettingsScreen inherits Rectangle {
|
||||
accessible-role: text; accessible-label: self.text; }
|
||||
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; }
|
||||
ListView {
|
||||
for row in SettingsBridge.rows: SettingCell { setting: row; compact: root.compact; }
|
||||
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 { }
|
||||
}
|
||||
|
||||
+43
-17
@@ -85,6 +85,7 @@ export global ShellBridge {
|
||||
|
||||
component EntryRow inherits Rectangle {
|
||||
in property <ShellRow> item;
|
||||
property <length> indent: Theme.android ? min(item.depth * 14px, max(0px, self.width - 220px)) : item.depth * 14px;
|
||||
height: max(44px, Theme.touch-target);
|
||||
border-radius: 9px;
|
||||
background: item.selected ? Theme.contrast : (touch.has-hover ? Theme.bg : transparent);
|
||||
@@ -99,8 +100,8 @@ component EntryRow inherits Rectangle {
|
||||
accessible-action-expand => { if root.item.expandable { ShellBridge.expand(root.item.id); } }
|
||||
accessible-action-default => { ShellBridge.select(root.item.id); }
|
||||
HorizontalLayout {
|
||||
padding-left: 10px + root.item.depth * 14px; padding-right: 4px; spacing: 8px;
|
||||
if root.item.expandable: ActionButton { width: 44px; text: root.item.expanded ? ShellBridge.label-close : ShellBridge.label-more; clicked => { ShellBridge.expand(root.item.id); } }
|
||||
padding-left: 10px + root.indent; padding-right: 4px; spacing: 8px;
|
||||
if root.item.expandable: ActionButton { width: Theme.android ? 48px : 44px; text: root.item.expanded ? ShellBridge.label-close : ShellBridge.label-more; 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 {
|
||||
spacing: 0px; alignment: center;
|
||||
@@ -113,7 +114,7 @@ component EntryRow inherits Rectangle {
|
||||
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; } }
|
||||
// Explicit overflow is always available on touch; right click never selects a row.
|
||||
touch := TouchArea {
|
||||
x: root.item.expandable ? 54px + root.item.depth * 14px : 0px;
|
||||
x: root.item.expandable ? 10px + (Theme.android ? 48px : 44px) + root.indent : 0px;
|
||||
width: max(0px,parent.width - self.x - 78px);
|
||||
clicked => { focus.focus(); ShellBridge.select(root.item.id); }
|
||||
pointer-event(e) => {
|
||||
@@ -161,6 +162,7 @@ export component ShellScreen inherits Rectangle {
|
||||
preferred-width: 100%; preferred-height: 100%;
|
||||
property <bool> compact: self.width < 600px;
|
||||
property <bool> desktop: self.width >= 1024px;
|
||||
property <bool> typing: Theme.android && Theme.ime-inset > 0px;
|
||||
property <length> sidebar-width <=> ShellBridge.sidebar-width;
|
||||
property <length> server-width <=> ShellBridge.server-width;
|
||||
property <length> actual-sidebar: desktop ? min(sidebar-width, max(62px,self.width - 515px)) : 0px;
|
||||
@@ -170,7 +172,7 @@ export component ShellScreen inherits Rectangle {
|
||||
VerticalLayout {
|
||||
spacing: 0px;
|
||||
Rectangle {
|
||||
height: 44px; background: Theme.header;
|
||||
height: max(44px, Theme.touch-target); background: Theme.header;
|
||||
HorizontalLayout {
|
||||
padding-left: 10px; padding-right: 10px; spacing: 8px;
|
||||
if !root.desktop: ActionButton { text: ShellBridge.label-back; enabled: ShellBridge.depth > 0 || ShellBridge.destination != 0; clicked => { ShellBridge.back(); } }
|
||||
@@ -214,11 +216,18 @@ export component ShellScreen inherits Rectangle {
|
||||
background: Theme.bg;
|
||||
VerticalLayout {
|
||||
spacing: 0px;
|
||||
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 root.compact && ShellBridge.tabs.length == 0: ListView { for item in ShellBridge.bookmarks: EntryRow { item: item; } }
|
||||
if !Theme.android: 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; } }
|
||||
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: CommandList { commands: ShellBridge.actions; }
|
||||
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 && ShellBridge.destination == 0: Rectangle {
|
||||
@@ -230,10 +239,11 @@ export component ShellScreen inherits Rectangle {
|
||||
background: Theme.shaded;
|
||||
VerticalLayout {
|
||||
spacing: 4px;
|
||||
Rectangle { min-height: 71px; background: Theme.shaded;
|
||||
if !Theme.android || !root.compact || (ShellBridge.stage != 1 && ShellBridge.destination != 1): 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; } }
|
||||
}
|
||||
HorizontalLayout { for name[index] in ShellBridge.stages: ActionButton { text: name; primary: ShellBridge.stage == index; clicked => { ShellBridge.stage = index; } } }
|
||||
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; } } } }
|
||||
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;
|
||||
@@ -251,7 +261,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; }
|
||||
} }
|
||||
ListView { for item in ShellBridge.entries: EntryRow { item: item; } }
|
||||
if !Theme.android || ShellBridge.entries.length > 0: 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); } }
|
||||
@@ -264,20 +274,36 @@ export component ShellScreen inherits Rectangle {
|
||||
if ShellBridge.has-voice: Rectangle {
|
||||
min-height: Theme.touch-target + 12px; background: Theme.contrast;
|
||||
VerticalLayout {
|
||||
Text { text: ShellBridge.voice-title + " · " + ShellBridge.voice-status; color: ShellBridge.transmitting ? Theme.success : Theme.fg; overflow: elide; }
|
||||
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: 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: ptt.pressed ? Theme.tint : Theme.bg; border-radius: 4px; accessible-role: button; accessible-label: ShellBridge.label-ptt;
|
||||
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;
|
||||
Text { text: ShellBridge.label-ptt; color: Theme.fg; vertical-alignment: center; horizontal-alignment: center; wrap: word-wrap; }
|
||||
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); } } }
|
||||
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: 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 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 ShellBridge.fullscreen-stream != "": Rectangle {
|
||||
background: Theme.contrast;
|
||||
@@ -293,7 +319,7 @@ export component ShellScreen inherits 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 { 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: 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(); } } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ export global Theme {
|
||||
in-out property <bool> dark: true;
|
||||
in-out property <bool> high-contrast: false;
|
||||
in-out property <bool> reduced-motion: false;
|
||||
in-out property <bool> android: false;
|
||||
in-out property <color> bg: dark ? #2b3346 : #f5f5f5;
|
||||
in-out property <color> shaded: dark ? #222A3C : #ebebeb;
|
||||
in-out property <color> header: dark ? #1C2539 : #e2e5eb;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
|
||||
@@ -24,9 +24,15 @@ public final class PlatformBridge {
|
||||
CaptureBridge.install(value);
|
||||
ConnectivityManager network = value.getSystemService(ConnectivityManager.class);
|
||||
network.registerDefaultNetworkCallback(new ConnectivityManager.NetworkCallback() {
|
||||
@Override public void onAvailable(Network network) { nativeEvent(0, 4, true); }
|
||||
@Override public void onLost(Network network) { nativeEvent(0, 4, false); }
|
||||
@Override public void onCapabilitiesChanged(Network network, NetworkCapabilities caps) { nativeEvent(0, 4, true); }
|
||||
private Network active;
|
||||
@Override public void onAvailable(Network network) {
|
||||
if(network.equals(active))return;
|
||||
active=network;nativeEvent(0,4,true);
|
||||
}
|
||||
@Override public void onLost(Network network) {
|
||||
if(!network.equals(active))return;
|
||||
active=null;nativeEvent(0,4,false);
|
||||
}
|
||||
});
|
||||
IntentFilter screen = new IntentFilter(); screen.addAction(Intent.ACTION_SCREEN_OFF); screen.addAction(Intent.ACTION_USER_PRESENT);
|
||||
BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { nativeEvent(0, 5, Intent.ACTION_SCREEN_OFF.equals(intent.getAction())); } };
|
||||
@@ -101,6 +107,16 @@ public final class PlatformBridge {
|
||||
if(!queued)InstallProvider.release(uri);
|
||||
return queued;
|
||||
}
|
||||
public static boolean openExternalUrl(long id,String url) {
|
||||
return post(() -> {
|
||||
TeamsPeachActivity value=visible();
|
||||
if(value==null){nativeText(id,null,"activity_not_visible");return;}
|
||||
Uri uri=Uri.parse(url);String scheme=uri.getScheme();
|
||||
if(!"https".equals(scheme)&&!"http".equals(scheme)&&!"mailto".equals(scheme)){nativeText(id,null,"URL scheme is not permitted");return;}
|
||||
try{value.startActivity(new Intent(Intent.ACTION_VIEW,uri).addCategory(Intent.CATEGORY_BROWSABLE));nativeText(id,"",null);}
|
||||
catch(RuntimeException error){nativeText(id,null,"No application could open this link");}
|
||||
});
|
||||
}
|
||||
public static boolean openStore(long id) {
|
||||
return post(()->{TeamsPeachActivity value=visible();if(value==null){nativeText(id,null,"activity_not_visible");return;}try{value.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id="+BuildConfig.APPLICATION_ID)));nativeText(id,"",null);}catch(ActivityNotFoundException missing){try{value.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("https://play.google.com/store/apps/details?id="+BuildConfig.APPLICATION_ID)));nativeText(id,"",null);}catch(RuntimeException error){nativeText(id,null,"store_unavailable");}}});
|
||||
}
|
||||
|
||||
@@ -29,7 +29,8 @@ public final class SafGrant implements AutoCloseable {
|
||||
static synchronized SafGrant acquire(Context context, Uri uri, int flags, boolean directory, boolean createdByPicker) throws IOException {
|
||||
if (!"content".equals(uri.getScheme())) throw new IOException("Document provider URI required");
|
||||
int access = flags & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
|
||||
if (access == 0) throw new IOException("No document grant");
|
||||
int required = Intent.FLAG_GRANT_READ_URI_PERMISSION | (directory || createdByPicker ? Intent.FLAG_GRANT_WRITE_URI_PERMISSION : 0);
|
||||
if ((access & required) != required) throw new IOException("Picker did not grant the requested document access");
|
||||
if(directory && !DocumentsContract.isTreeUri(uri))throw new IOException("Directory picker did not supply a tree grant");
|
||||
Uri document = directory ? DocumentsContract.buildDocumentUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri)) : uri;
|
||||
String name = queryName(context, document);
|
||||
@@ -50,7 +51,9 @@ public final class SafGrant implements AutoCloseable {
|
||||
private static String queryName(Context context, Uri uri) throws IOException {
|
||||
try (Cursor cursor = context.getContentResolver().query(uri, new String[]{OpenableColumns.DISPLAY_NAME}, null, null, null)) {
|
||||
if (cursor == null || !cursor.moveToFirst()) throw new IOException("Document no longer available");
|
||||
return cursor.getString(0);
|
||||
String name=cursor.getString(0);
|
||||
if(name==null)throw new IOException("Provider returned no document name");
|
||||
return name;
|
||||
}
|
||||
}
|
||||
private void check() throws IOException { if (closed) throw new IOException("Document grant released"); }
|
||||
@@ -98,6 +101,20 @@ public final class SafGrant implements AutoCloseable {
|
||||
return new SafGrant(lease,child,true,display,null,false);
|
||||
}
|
||||
private CommitException noAtomicReplace(){return new CommitException("provider_atomic_replace_unsupported","This Android document provider exposes no atomic replace guarantee through DocumentsContract (write/rename/delete flags are insufficient). The existing document was not opened for writing. Choose a new destination/name; the source staging file is retained.");}
|
||||
private int detachDescriptor(String mode) throws IOException {
|
||||
ParcelFileDescriptor duplicate=null;
|
||||
try {
|
||||
try(ParcelFileDescriptor source=lease.context.getContentResolver().openFileDescriptor(uri,mode)){
|
||||
if(source==null)throw new IOException("Provider refused document descriptor");
|
||||
duplicate=ParcelFileDescriptor.dup(source.getFileDescriptor());
|
||||
}
|
||||
// Close the provider handle before detaching; a close failure must not orphan a raw fd.
|
||||
return duplicate.detachFd();
|
||||
}catch(IOException|RuntimeException failure){
|
||||
if(duplicate!=null)try{duplicate.close();}catch(IOException|RuntimeException cleanup){failure.addSuppressed(cleanup);}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
public synchronized int beginCommit() throws IOException {
|
||||
check();if(directory)throw new IOException("Document capability required");
|
||||
if(committing)throw new CommitException("document_busy","A document commit is already active");
|
||||
@@ -116,9 +133,8 @@ public final class SafGrant implements AutoCloseable {
|
||||
if((capabilities&DocumentsContract.Document.FLAG_SUPPORTS_WRITE)==0)throw new CommitException("provider_document_write_unsupported","The new document is not writable; choose another destination. Source staging is retained.");
|
||||
if((capabilities&DocumentsContract.Document.FLAG_SUPPORTS_DELETE)==0)throw new CommitException("provider_partial_cleanup_unsupported","This provider cannot delete a cancelled partial new document. No content was written; choose another provider/destination. Source staging is retained.");
|
||||
committing=true;
|
||||
try(ParcelFileDescriptor source=lease.context.getContentResolver().openFileDescriptor(uri,"rw")){
|
||||
if(source==null)throw new IOException("Provider refused new document descriptor");
|
||||
return ParcelFileDescriptor.dup(source.getFileDescriptor()).detachFd();
|
||||
try{
|
||||
return detachDescriptor("rw");
|
||||
}catch(IOException|RuntimeException failure){
|
||||
committing=false;commitConsumed=true;
|
||||
if(!deleteNew())throw new CommitException("provider_partial_cleanup_failed","The provider refused a new document descriptor and could not remove that new destination. Source staging is retained; inspect/remove the destination manually.");
|
||||
@@ -139,7 +155,7 @@ public final class SafGrant implements AutoCloseable {
|
||||
check();
|
||||
if (!directory || name.isEmpty() || name.equals(".") || name.equals("..") || name.length()>255 || name.matches(".*[\\\\/:\\p{Cntrl}].*")) throw new IOException("Invalid child name");
|
||||
Uri existing = find(name);
|
||||
if (existing != null && !overwrite) throw new IOException("Explicit overwrite consent required");
|
||||
if (existing != null && !overwrite) throw new CommitException("file_exists","A document already has this name; choose a new name or destination");
|
||||
if(existing!=null&&isDirectory(existing))throw new CommitException("destination_is_directory","A directory occupies the requested document name");
|
||||
synchronized (SafGrant.class) { lease.users++; }
|
||||
return new SafGrant(lease, existing, false, name, uri, overwrite);
|
||||
@@ -158,11 +174,9 @@ public final class SafGrant implements AutoCloseable {
|
||||
newDocument=true;
|
||||
if (uri == null) throw new IOException("Provider refused document creation");
|
||||
}
|
||||
try (ParcelFileDescriptor source = lease.context.getContentResolver().openFileDescriptor(uri, write ? (truncate ? "rwt" : "rw") : "r")) {
|
||||
if (source == null) throw new IOException("Provider refused descriptor");
|
||||
if(write)newDocument=false;
|
||||
return ParcelFileDescriptor.dup(source.getFileDescriptor()).detachFd();
|
||||
}
|
||||
int descriptor=detachDescriptor(write ? (truncate ? "rwt" : "rw") : "r");
|
||||
if(write)newDocument=false;
|
||||
return descriptor;
|
||||
}
|
||||
@Override public synchronized void close() {
|
||||
if (closed) return; closed=true;
|
||||
|
||||
@@ -59,10 +59,10 @@ public final class TeamsPeachActivity extends NativeActivity {
|
||||
}
|
||||
@Override protected void onDestroy() {
|
||||
CaptureBridge.unbindActivity(this);
|
||||
if (picker != 0) PlatformBridge.nativePick(picker, null, "activity_destroyed");
|
||||
if (picker > 0) PlatformBridge.nativePick(picker, null, "activity_destroyed");
|
||||
if (permissionRequest > 0) PlatformBridge.nativeText(permissionRequest, null, "activity_destroyed");
|
||||
if (pipToken != 0) PlatformBridge.nativePip(pipToken, false, true);
|
||||
if (shareRequest != 0) PlatformBridge.nativeText(shareRequest, null, "activity_destroyed");
|
||||
if (shareRequest > 0) PlatformBridge.nativeText(shareRequest, null, "activity_destroyed");
|
||||
if (sharedGrant != null) { sharedGrant.close(); sharedGrant=null; }
|
||||
if(installerRequest>0)PlatformBridge.nativeText(installerRequest,null,"activity_destroyed");
|
||||
InstallProvider.release(installerUri);installerUri=null;
|
||||
@@ -101,7 +101,8 @@ public final class TeamsPeachActivity extends NativeActivity {
|
||||
if (kind == 1) intent.putExtra(Intent.EXTRA_TITLE, name);
|
||||
else if (types.length > 0) intent.putExtra(Intent.EXTRA_MIME_TYPES, types);
|
||||
}
|
||||
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
|
||||
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
|
||||
if(kind!=0)intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
|
||||
picker = id; pickingDirectory = kind == 2; pickingNewDocument = kind == 1;
|
||||
try { startActivityForResult(intent, PICK); } catch (RuntimeException error) { picker = 0; PlatformBridge.nativePick(id, null, "picker_unavailable"); }
|
||||
}
|
||||
@@ -114,7 +115,8 @@ public final class TeamsPeachActivity extends NativeActivity {
|
||||
if (request==SHARE && shareRequest!=0) { long id=shareRequest;shareRequest=0;if(sharedGrant!=null){sharedGrant.close();sharedGrant=null;}PlatformBridge.nativeText(id,"",null);return; }
|
||||
if (request != PICK || picker == 0) return;
|
||||
long id = picker; picker = 0;
|
||||
if (result != RESULT_OK || data == null || data.getData() == null) { PlatformBridge.nativePick(id, null, null); return; }
|
||||
if (result != RESULT_OK) { PlatformBridge.nativePick(id, null, null); return; }
|
||||
if (data == null || data.getData() == null) { PlatformBridge.nativePick(id, null, "document_picker_invalid_result"); return; }
|
||||
try { PlatformBridge.nativePick(id, SafGrant.acquire(getApplicationContext(), data.getData(), data.getFlags(), pickingDirectory, pickingNewDocument), null); }
|
||||
catch (Exception error) { PlatformBridge.nativePick(id, null, "document_grant_denied"); }
|
||||
}
|
||||
@@ -123,13 +125,14 @@ public final class TeamsPeachActivity extends NativeActivity {
|
||||
if(permission==2 && Build.VERSION.SDK_INT<33){PlatformBridge.nativePermission(id,permission,PlatformBridge.granted(permission));return;}
|
||||
if (PlatformBridge.granted(permission)) { PlatformBridge.nativePermission(id, permission, true); return; }
|
||||
permissionRequest = id; requestedPermission = permission;
|
||||
requestPermissions(new String[]{PlatformBridge.permissionName(permission)}, PERMISSION);
|
||||
try { requestPermissions(new String[]{PlatformBridge.permissionName(permission)}, PERMISSION); }
|
||||
catch (RuntimeException error) { permissionRequest=0; PlatformBridge.nativeText(id,null,"permission_request_unavailable"); }
|
||||
}
|
||||
@Override public void onRequestPermissionsResult(int request, String[] names, int[] grants) {
|
||||
super.onRequestPermissionsResult(request, names, grants);
|
||||
if (request != PERMISSION || permissionRequest == 0) return;
|
||||
long id = permissionRequest; permissionRequest = 0;
|
||||
PlatformBridge.nativePermission(id>0?id:0, requestedPermission, grants.length == 1 && grants[0] == PackageManager.PERMISSION_GRANTED);
|
||||
PlatformBridge.nativePermission(id>0?id:0, requestedPermission, PlatformBridge.granted(requestedPermission));
|
||||
}
|
||||
void cancel(long id) { if (picker == id) { picker = -1; finishActivity(PICK); } if (permissionRequest == id) permissionRequest = -1; if(shareRequest==id){shareRequest=-1;finishActivity(SHARE);if(sharedGrant!=null){sharedGrant.close();sharedGrant=null;}}if(installerRequest==id){installerRequest=-1;finishActivity(INSTALL);finishActivity(INSTALL_PERMISSION);InstallProvider.release(installerUri);installerUri=null;} }
|
||||
void share(long id,String text,SafGrant grant,String mime) {
|
||||
|
||||
@@ -13,6 +13,11 @@ public final class VoiceService extends Service {
|
||||
private boolean microphone;
|
||||
private AudioFocusRequest focus;
|
||||
private AudioDeviceCallback devices;
|
||||
private boolean focused;
|
||||
private boolean communicationMode;
|
||||
private java.util.Set<Integer> deviceIds = java.util.Collections.emptySet();
|
||||
private AudioManager.OnCommunicationDeviceChangedListener communicationDeviceListener;
|
||||
private int communicationDeviceId;
|
||||
private static final int ID = 7240;
|
||||
private static java.lang.ref.WeakReference<VoiceService> current = new java.lang.ref.WeakReference<>(null);
|
||||
static void stop(long token) { VoiceService service=current.get(); if(service!=null && (token==0 || token==service.token)){CaptureBridge.revokeAll();service.stopSelf();} }
|
||||
@@ -29,6 +34,7 @@ public final class VoiceService extends Service {
|
||||
VoiceService service=current.get();
|
||||
if(service==null||service.token!=token||!PlatformBridge.nativeVoiceCaptureValid(token,request)){PlatformBridge.nativeText(request,null,"target_changed");return;}
|
||||
if(enabled && (PlatformBridge.visible()==null||!PlatformBridge.granted(0))){service.receiveOnly();PlatformBridge.nativeText(request,null,"Microphone activation requires a visible user action and RECORD_AUDIO grant");return;}
|
||||
if(enabled && !service.focused){PlatformBridge.nativeText(request,null,"Audio focus is unavailable; wait for the interruption to end");return;}
|
||||
try {
|
||||
service.foreground(enabled);
|
||||
if(!PlatformBridge.nativeVoiceCaptureChanged(token,request,enabled))service.foreground(false);
|
||||
@@ -44,6 +50,26 @@ public final class VoiceService extends Service {
|
||||
PlatformBridge.nativeVoiceCaptureRevoked(token);
|
||||
try{foreground(false);}catch(RuntimeException playbackDenied){PlatformBridge.nativeVoiceStopped(token);stopSelf();}
|
||||
}
|
||||
private java.util.Set<Integer> audioDevices(AudioManager audio) {
|
||||
java.util.Set<Integer> ids = new java.util.HashSet<>();
|
||||
for(AudioDeviceInfo device : audio.getDevices(AudioManager.GET_DEVICES_ALL)) ids.add(device.getId());
|
||||
return ids;
|
||||
}
|
||||
private int communicationDevice(AudioManager audio) {
|
||||
if(Build.VERSION.SDK_INT<31)return 0;
|
||||
AudioDeviceInfo device=audio.getCommunicationDevice();
|
||||
return device==null?0:device.getId();
|
||||
}
|
||||
private void routeChanged(long owner) {
|
||||
if(token!=owner||!PlatformBridge.nativeVoiceValid(owner))return;
|
||||
AudioManager audio=getSystemService(AudioManager.class);
|
||||
java.util.Set<Integer> next = audioDevices(audio);
|
||||
int selected=communicationDevice(audio);
|
||||
if(next.equals(deviceIds)&&selected==communicationDeviceId)return;
|
||||
deviceIds=next;communicationDeviceId=selected;
|
||||
receiveOnly();
|
||||
PlatformBridge.nativeVoiceEvent(owner,3,true);
|
||||
}
|
||||
@Override public void onCreate() { super.onCreate(); current=new java.lang.ref.WeakReference<>(this); getSystemService(NotificationManager.class).createNotificationChannel(new NotificationChannel("voice", "Active voice call", NotificationManager.IMPORTANCE_LOW)); }
|
||||
@Override public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
long incoming = intent == null ? 0 : intent.getLongExtra("token", 0);
|
||||
@@ -53,23 +79,39 @@ public final class VoiceService extends Service {
|
||||
PlatformBridge.nativeVoiceStopped(token);
|
||||
if(focus!=null)getSystemService(AudioManager.class).abandonAudioFocusRequest(focus);
|
||||
if(devices!=null)getSystemService(AudioManager.class).unregisterAudioDeviceCallback(devices);
|
||||
focus=null;devices=null;
|
||||
if(Build.VERSION.SDK_INT>=31&&communicationDeviceListener!=null)getSystemService(AudioManager.class).removeOnCommunicationDeviceChangedListener(communicationDeviceListener);
|
||||
communicationDeviceListener=null;
|
||||
focus=null;devices=null;focused=false;
|
||||
}
|
||||
token = incoming;
|
||||
try {
|
||||
foreground(capture);
|
||||
AudioManager audio = getSystemService(AudioManager.class);
|
||||
audio.setMode(AudioManager.MODE_IN_COMMUNICATION);
|
||||
communicationMode=true;
|
||||
if (focus == null) {
|
||||
final long owner=token;
|
||||
focus = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN).setAudioAttributes(new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION).setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build())
|
||||
.setOnAudioFocusChangeListener(change -> {
|
||||
PlatformBridge.nativeVoiceEvent(owner, 2, change != AudioManager.AUDIOFOCUS_GAIN);
|
||||
if (change == AudioManager.AUDIOFOCUS_LOSS && token==owner && PlatformBridge.nativeVoiceValid(owner)) stopSelf();
|
||||
if(token!=owner||!PlatformBridge.nativeVoiceValid(owner))return;
|
||||
boolean gained=change==AudioManager.AUDIOFOCUS_GAIN;
|
||||
if(focused==gained&&change!=AudioManager.AUDIOFOCUS_LOSS)return;
|
||||
focused=gained;
|
||||
if(!focused)receiveOnly();
|
||||
PlatformBridge.nativeVoiceEvent(owner, 2, !focused);
|
||||
if (change == AudioManager.AUDIOFOCUS_LOSS) stopSelf();
|
||||
}, PlatformBridge.MAIN).build();
|
||||
if (audio.requestAudioFocus(focus) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) throw new IllegalStateException("Audio focus denied");
|
||||
focused=true;
|
||||
deviceIds=audioDevices(audio);
|
||||
communicationDeviceId=communicationDevice(audio);
|
||||
if(Build.VERSION.SDK_INT>=31){
|
||||
communicationDeviceListener=device->routeChanged(owner);
|
||||
audio.addOnCommunicationDeviceChangedListener(PlatformBridge.MAIN::post,communicationDeviceListener);
|
||||
}
|
||||
devices = new AudioDeviceCallback() {
|
||||
@Override public void onAudioDevicesAdded(AudioDeviceInfo[] values) { PlatformBridge.nativeVoiceEvent(owner, 3, true); }
|
||||
@Override public void onAudioDevicesRemoved(AudioDeviceInfo[] values) { PlatformBridge.nativeVoiceEvent(owner, 3, true); }
|
||||
@Override public void onAudioDevicesAdded(AudioDeviceInfo[] values) { routeChanged(owner); }
|
||||
@Override public void onAudioDevicesRemoved(AudioDeviceInfo[] values) { routeChanged(owner); }
|
||||
};
|
||||
audio.registerAudioDeviceCallback(devices, PlatformBridge.MAIN);
|
||||
}
|
||||
@@ -80,6 +122,9 @@ public final class VoiceService extends Service {
|
||||
@Override public void onDestroy() {
|
||||
if (focus != null) getSystemService(AudioManager.class).abandonAudioFocusRequest(focus);
|
||||
if (devices != null) getSystemService(AudioManager.class).unregisterAudioDeviceCallback(devices);
|
||||
if(Build.VERSION.SDK_INT>=31&&communicationDeviceListener!=null)getSystemService(AudioManager.class).removeOnCommunicationDeviceChangedListener(communicationDeviceListener);
|
||||
if(communicationMode)getSystemService(AudioManager.class).setMode(AudioManager.MODE_NORMAL);
|
||||
focused=false;
|
||||
if (token != 0 && PlatformBridge.nativeVoiceStopped(token)) CaptureBridge.revokeAll();
|
||||
if (current.get()==this)current.clear();
|
||||
stopForeground(STOP_FOREGROUND_REMOVE); super.onDestroy();
|
||||
|
||||
+43
-13
@@ -8,33 +8,50 @@ import android.media.projection.MediaProjectionManager;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.util.HashMap;
|
||||
|
||||
/** One fresh, non-persisted MediaProjection consent per request. No token survives recreation. */
|
||||
public final class CaptureConsentActivity extends Activity {
|
||||
private static WeakReference<CaptureConsentActivity> current = new WeakReference<>(null);
|
||||
private static final HashMap<Long, WeakReference<CaptureConsentActivity>> current = new HashMap<>();
|
||||
private long id;
|
||||
private boolean handedOff;
|
||||
private boolean handedOff, resumed, ready, serviceRequested;
|
||||
private Intent projectionToken;
|
||||
private int projectionResult;
|
||||
private static final int PERMISSION = 40, PROJECTION = 41;
|
||||
static void cancel(long id) {
|
||||
CaptureConsentActivity active = current.get();
|
||||
if (active != null && active.id == id) active.finish();
|
||||
WeakReference<CaptureConsentActivity> reference = current.get(id);
|
||||
CaptureConsentActivity active = reference == null ? null : reference.get();
|
||||
if (active != null) { active.finishActivity(PROJECTION); active.finish(); }
|
||||
}
|
||||
static void started(long id) {
|
||||
WeakReference<CaptureConsentActivity> reference = current.get(id);
|
||||
CaptureConsentActivity active = reference == null ? null : reference.get();
|
||||
if (active != null) { active.handedOff = true; active.finish(); }
|
||||
}
|
||||
@Override protected void onResume() { super.onResume(); resumed = true; startServiceWhenVisible(); }
|
||||
@Override protected void onPause() { resumed = false; super.onPause(); }
|
||||
@Override public void onCreate(Bundle saved) {
|
||||
super.onCreate(saved);
|
||||
id = getIntent().getLongExtra("capture_id", 0);
|
||||
current = new WeakReference<>(this);
|
||||
current.put(id, new WeakReference<>(this));
|
||||
if (saved != null || !CaptureBridge.active(id)) { reject("Capture consent cancelled by Activity recreation"); return; }
|
||||
CaptureBridge.Request request = CaptureBridge.REQUESTS.get(id);
|
||||
if (request == null) { finish(); return; }
|
||||
if (!request.camera && request.audioUid >= 0 && Build.VERSION.SDK_INT < 29) { reject("Application playback capture requires Android 10 or later"); return; }
|
||||
String permission = request.camera ? Manifest.permission.CAMERA : request.audioUid >= 0 ? Manifest.permission.RECORD_AUDIO : null;
|
||||
if (permission != null && checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) requestPermissions(new String[] { permission }, PERMISSION);
|
||||
else continueConsent();
|
||||
if (permission != null && checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
|
||||
try { requestPermissions(new String[] { permission }, PERMISSION); }
|
||||
catch (RuntimeException error) { reject("System capture permission request unavailable"); }
|
||||
} else continueConsent();
|
||||
}
|
||||
@Override public void onRequestPermissionsResult(int code, String[] permissions, int[] results) {
|
||||
super.onRequestPermissionsResult(code, permissions, results);
|
||||
if (code != PERMISSION) return;
|
||||
if (results.length != 1 || results[0] != PackageManager.PERMISSION_GRANTED) { reject("Capture permission denied"); return; }
|
||||
CaptureBridge.Request request = CaptureBridge.REQUESTS.get(id);
|
||||
if (request == null || !CaptureBridge.active(id)) { finish(); return; }
|
||||
String permission = request.camera ? Manifest.permission.CAMERA : request.audioUid >= 0 ? Manifest.permission.RECORD_AUDIO : null;
|
||||
if (permission == null || results.length != 1 || results[0] != PackageManager.PERMISSION_GRANTED
|
||||
|| checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { reject("Capture permission denied"); return; }
|
||||
continueConsent();
|
||||
}
|
||||
private void continueConsent() {
|
||||
@@ -52,15 +69,28 @@ public final class CaptureConsentActivity extends Activity {
|
||||
launch(data, result);
|
||||
}
|
||||
private void launch(Intent token, int result) {
|
||||
if (!CaptureBridge.active(id) || handedOff) { finish(); return; }
|
||||
Intent service = new Intent(this, CaptureService.class).putExtra("capture_id", id).putExtra("result_code", result);
|
||||
if (token != null) service.putExtra("projection_token", token);
|
||||
try { startForegroundService(service); handedOff = true; finish(); }
|
||||
if (!CaptureBridge.active(id) || handedOff || serviceRequested) { finish(); return; }
|
||||
projectionToken = token; projectionResult = result; ready = true;
|
||||
startServiceWhenVisible();
|
||||
}
|
||||
private void startServiceWhenVisible() {
|
||||
// Permission/Activity results arrive before onResume. Android 14+ checks
|
||||
// camera's while-in-use grant when the foreground service is created.
|
||||
if (!ready || !resumed || serviceRequested || isFinishing()) return;
|
||||
if (!CaptureBridge.active(id)) { finish(); return; }
|
||||
Intent service = new Intent(this, CaptureService.class).putExtra("capture_id", id).putExtra("result_code", projectionResult);
|
||||
if (projectionToken != null) service.putExtra("projection_token", projectionToken);
|
||||
projectionToken = null; serviceRequested = true;
|
||||
try { startForegroundService(service); }
|
||||
catch (RuntimeException error) { reject("Foreground capture service was not allowed"); }
|
||||
// Keep this Activity visible until CaptureService has entered foreground.
|
||||
}
|
||||
private void reject(String message) { CaptureBridge.ended(id, message); finish(); }
|
||||
@Override protected void onDestroy() {
|
||||
if (current.get() == this) current.clear();
|
||||
WeakReference<CaptureConsentActivity> reference = current.get(id);
|
||||
if (reference != null && reference.get() == this) current.remove(id);
|
||||
projectionToken = null;
|
||||
finishActivity(PROJECTION);
|
||||
if (!handedOff) CaptureBridge.ended(id, "Capture consent cancelled");
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ public final class CaptureService extends Service {
|
||||
int result = intent.getIntExtra("result_code", 0);
|
||||
intent.removeExtra("projection_token");
|
||||
session.start(token, result);
|
||||
CaptureConsentActivity.started(id);
|
||||
} catch (Exception error) { CaptureBridge.ended(id, "Capture service start failed: " + error.getClass().getSimpleName()); }
|
||||
return START_NOT_STICKY;
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ final class CaptureSession implements AutoCloseable {
|
||||
private DisplayManager.DisplayListener displayListener;
|
||||
private int sensorOrientation, lensFacing;
|
||||
private boolean realtimeCamera;
|
||||
private boolean cameraOpening, resourcesClosed;
|
||||
private long lastVideoNs;
|
||||
private int density;
|
||||
CaptureSession(Context context, CaptureBridge.Request request) {
|
||||
@@ -92,7 +93,7 @@ final class CaptureSession implements AutoCloseable {
|
||||
Size size = scaled(width, height);
|
||||
if (reader.getWidth() == size.getWidth() && reader.getHeight() == size.getHeight()) return;
|
||||
// Android 14+ forbids a second createVirtualDisplay with the same consent token.
|
||||
display.setSurface(null); reader.close();
|
||||
display.setSurface(null); reader.setOnImageAvailableListener(null, null); reader.close();
|
||||
createReader(size.getWidth(), size.getHeight(), PixelFormat.RGBA_8888);
|
||||
display.resize(size.getWidth(), size.getHeight(), density); display.setSurface(reader.getSurface());
|
||||
} catch (RuntimeException error) { fail("Capture resize failed"); }
|
||||
@@ -114,6 +115,8 @@ final class CaptureSession implements AutoCloseable {
|
||||
private void createReader(int width, int height, int format) {
|
||||
reader = ImageReader.newInstance(width, height, format, 2);
|
||||
reader.setOnImageAvailableListener(value -> {
|
||||
// A resize may leave an old reader's notification queued on this handler.
|
||||
if (value != reader || !valid()) return;
|
||||
try (Image image = value.acquireLatestImage()) {
|
||||
if (image == null || !valid()) return;
|
||||
long now = System.nanoTime();
|
||||
@@ -167,9 +170,11 @@ final class CaptureSession implements AutoCloseable {
|
||||
if (candidate.getUpper() <= request.fps && (rate == null || candidate.getUpper() > rate.getUpper() || candidate.getUpper().equals(rate.getUpper()) && candidate.getLower() > rate.getLower())) rate = candidate;
|
||||
}
|
||||
final Range<Integer> chosenRate = rate;
|
||||
manager.openCamera(request.device, new CameraDevice.StateCallback() {
|
||||
cameraOpening = true;
|
||||
try { manager.openCamera(request.device, new CameraDevice.StateCallback() {
|
||||
public void onOpened(CameraDevice device) {
|
||||
if (!valid()) { device.close(); return; } camera = device;
|
||||
cameraOpening = false; camera = device;
|
||||
if (!valid()) { device.close(); return; }
|
||||
try {
|
||||
device.createCaptureSession(Collections.singletonList(reader.getSurface()), new CameraCaptureSession.StateCallback() {
|
||||
public void onConfigured(CameraCaptureSession session) {
|
||||
@@ -185,9 +190,20 @@ final class CaptureSession implements AutoCloseable {
|
||||
}, handler);
|
||||
} catch (CameraAccessException | IllegalStateException error) { fail("Selected camera could not open capture session"); }
|
||||
}
|
||||
public void onDisconnected(CameraDevice device) { device.close(); fail("Selected camera disconnected"); }
|
||||
public void onError(CameraDevice device, int error) { device.close(); fail("Selected camera denied, busy, or revoked (" + error + ")"); }
|
||||
}, handler);
|
||||
public void onDisconnected(CameraDevice device) {
|
||||
cameraOpening = false; camera = device; device.close();
|
||||
if (valid()) fail("Selected camera disconnected");
|
||||
}
|
||||
public void onError(CameraDevice device, int error) {
|
||||
cameraOpening = false; camera = device; device.close();
|
||||
if (valid()) fail("Selected camera denied, busy, or revoked (" + error + ")");
|
||||
}
|
||||
@Override public void onClosed(CameraDevice device) {
|
||||
if (camera == device) camera = null;
|
||||
finishClose();
|
||||
}
|
||||
}, handler); }
|
||||
catch (Exception error) { cameraOpening = false; throw error; }
|
||||
}
|
||||
@SuppressWarnings("MissingPermission") private void startPlaybackAudio() {
|
||||
if (Build.VERSION.SDK_INT < 29) throw new UnsupportedOperationException("Playback capture requires Android 10");
|
||||
@@ -227,6 +243,13 @@ final class CaptureSession implements AutoCloseable {
|
||||
audioThread.start();
|
||||
}
|
||||
void awaitStopped() throws InterruptedException { thread.join(); }
|
||||
private void finishClose() {
|
||||
// openCamera is asynchronous: keep dispatching until even a late onOpened
|
||||
// has closed its device, otherwise cancellation can strand the camera.
|
||||
if (resourcesClosed && !cameraOpening && camera == null) {
|
||||
thread.quitSafely(); CaptureService.released(this);
|
||||
}
|
||||
}
|
||||
@Override public void close() {
|
||||
if (!closed.compareAndSet(false, true)) return;
|
||||
// All platform objects are created/closed on their capture handler, not from JNI callbacks.
|
||||
@@ -236,10 +259,11 @@ final class CaptureSession implements AutoCloseable {
|
||||
if (audioThread != null) { try { audioThread.join(); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); } }
|
||||
if (audio != null) audio.release();
|
||||
if (cameraSession != null) cameraSession.close(); if (camera != null) camera.close();
|
||||
if (display != null) display.release(); if (reader != null) reader.close();
|
||||
if (display != null) display.release();
|
||||
if (reader != null) { reader.setOnImageAvailableListener(null, null); reader.close(); }
|
||||
if (projection != null) projection.stop();
|
||||
if (displayManager != null && displayListener != null) displayManager.unregisterDisplayListener(displayListener);
|
||||
} finally { thread.quitSafely(); CaptureService.released(this); }
|
||||
} finally { resourcesClosed = true; finishClose(); }
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user