Fix Android sandbox onboarding and surface insets; checkpoint application cache
android-ci / android-arm64 (push) Successful in 18m47s

This commit is contained in:
bit9992 committed 2026-11-12 13:25:41 +03:00
1 parent 52d2c22ec0
commit fd41389d63
9 files changed
+365 -33

No files matched your search

+159
View File
@@ -0,0 +1,159 @@
#!/usr/bin/env python3
"""CI-only Cargo cache bookkeeping; never manufactures build/provenance receipts.
Cargo compares checkout source mtimes with cached dep-info/build-script timestamps.
A fresh checkout otherwise invalidates unchanged workspace and vendored crates.
Restore a recorded timestamp only for the same path, SHA-256, kind and mode; a
changed input keeps its real mtime. WebRTC is handled only AFTER xtask deps has
rebuilt/verified it, so identical republished headers/archives can retain their
original timestamps without trusting cached dependency provenance.
"""
import argparse
import hashlib
import json
import os
import pathlib
import stat
import subprocess
import time
ROOT = pathlib.Path.cwd().resolve()
STATE = ROOT / '.android-ci'
RECEIPT = STATE / 'application-cache-inputs.json'
PENDING = STATE / 'application-cache-pending.json'
def digest(path):
with path.open('rb') as source:
return hashlib.file_digest(source, 'sha256').hexdigest()
def tracked_paths():
return [os.fsdecode(name) for name in subprocess.check_output(
['git', 'ls-files', '-z']).split(b'\0') if name]
def identity():
names = {name for name in tracked_paths() if pathlib.PurePosixPath(name).name == 'Cargo.toml'}
names.update(('Cargo.lock', 'rust-toolchain.toml', '.cargo/config.toml',
'.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh',
'.gitea/build-android-variant.sh', '.gitea/android-rustc-low-memory.sh',
'.gitea/android-application-cache.py', 'xtask/src/build_native.rs',
'xtask/src/deps.rs', '.gitea/prepare-android-dependency-cache.py'))
policy = json.loads((ROOT / 'native/native-deps.lock.json').read_text())
policy.pop('builds', None)
inputs = {name: digest(ROOT / name) for name in sorted(names)}
inputs['dependency-policy'] = policy
inputs['target'] = os.environ['TARGET']
inputs['low-memory'] = os.environ['TEAMSPEACH_ANDROID_LOW_MEMORY']
inputs['profile'] = 'release'
inputs['variant'] = 'harness'
for name in ('RUSTFLAGS', 'CARGO_ENCODED_RUSTFLAGS', 'RUSTC_WRAPPER', 'RUSTC_WORKSPACE_WRAPPER'):
inputs[name] = os.environ.get(name, '')
fingerprint = hashlib.sha256(json.dumps(inputs, sort_keys=True).encode()).hexdigest()
mode = 'low-memory' if inputs['low-memory'] == 'true' else 'normal'
return f"android-application-linux-x64-{inputs['target']}-release-{mode}-harness-v1-{fingerprint}"
def record(path):
info = path.lstat()
mode = stat.S_IMODE(info.st_mode)
if stat.S_ISREG(info.st_mode):
kind, value = 'file', digest(path)
elif stat.S_ISDIR(info.st_mode):
kind = 'directory'
value = hashlib.sha256(json.dumps(sorted(os.listdir(path))).encode()).hexdigest()
else:
# Never follow checkout/cache symlinks, including symlinked ancestors.
raise ValueError(f'Unsupported cache input: {path}')
return {'kind': kind, 'sha256': value, 'mode': mode, 'mtime_ns': info.st_mtime_ns}
def collect(names):
result = {}
for name in sorted(set(names)):
path = ROOT / name
if not path.exists():
continue
if not path.resolve().is_relative_to(ROOT) or any(parent.is_symlink() for parent in (path, *path.parents)):
raise ValueError(f'Unconfined cache input: {name}')
result[name] = record(path)
return result
def load():
if not RECEIPT.exists():
return {'inputs': {}, 'completed_ns': 0}
data = json.loads(RECEIPT.read_text())
if data['schema'] != 1 or data['identity'] != identity() or data['workspace'] != str(ROOT):
raise ValueError('Application cache input identity/workspace mismatch')
return data
def save(path, inputs):
STATE.mkdir(exist_ok=True)
temporary = path.with_suffix('.tmp')
temporary.write_text(json.dumps({'schema': 1, 'identity': identity(),
'workspace': str(ROOT), 'inputs': inputs,
'completed_ns': time.time_ns()}, sort_keys=True))
temporary.replace(path)
def restore(current, previous):
restored = 0
for name, item in current.items():
old = previous['inputs'].get(name)
if old is None or any(item[key] != old[key] for key in ('kind', 'sha256', 'mode')):
# Changed/new inputs must postdate the previous compilation. Reject
# clock regressions rather than making stale outputs appear fresh.
if previous['completed_ns'] and item['mtime_ns'] <= previous['completed_ns']:
raise ValueError(f'Changed input predates cached compilation: {name}; refuse stale Cargo reuse')
continue
if old['mtime_ns'] > item['mtime_ns']:
raise ValueError(f'Cached input timestamp is in the future: {name}')
path = ROOT / name
os.utime(path, ns=(path.stat().st_atime_ns, old['mtime_ns']), follow_symlinks=False)
item['mtime_ns'] = old['mtime_ns']
restored += 1
print(f'Restored {restored}/{len(current)} content-matched input timestamps', flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('key', 'sources', 'dependencies', 'snapshot'))
action = parser.parse_args().action
if action == 'key':
with open(os.environ['GITHUB_OUTPUT'], 'a') as out:
out.write(f'key={identity()}\n')
return
previous = load()
if action == 'sources':
names = set(tracked_paths())
# Cargo's directory rerun rules also inspect directory mtimes. Preserve
# those only if their exact child-name inventory and mode still match.
for name in tuple(names):
names.update(str(parent) for parent in pathlib.Path(name).parents if parent != pathlib.Path('.'))
current = collect(names)
restore(current, previous)
save(PENDING, current)
elif action == 'dependencies':
base = pathlib.Path('target/native-deps') / os.environ['TARGET'] / 'webrtc'
if not base.is_dir():
raise ValueError('Verified WebRTC artifact tree is missing')
current = collect([str(base), *(str(path) for path in base.rglob('*'))])
restore(current, previous)
pending = json.loads(PENDING.read_text())['inputs']
pending.update(current)
save(PENDING, pending)
else:
pending = json.loads(PENDING.read_text())['inputs']
current = collect(pending)
# Only retain inputs whose bytes/mode/mtime stayed stable throughout the
# build. A generated or concurrently edited file is never backdated.
stable = {name: item for name, item in current.items() if item == pending[name]}
save(RECEIPT, stable)
print(f'Recorded {len(stable)} stable application/dependency inputs', flush=True)
if __name__ == '__main__':
main()
+47 -9
View File
@@ -34,6 +34,7 @@ jobs:
ANDROID_CI_PROVISION: container ANDROID_CI_PROVISION: container
CARGO_TERM_COLOR: never CARGO_TERM_COLOR: never
CARGO_BUILD_JOBS: "4" CARGO_BUILD_JOBS: "4"
TEAMSPEACH_ANDROID_LOW_MEMORY: "false"
CARGO_TARGET_DIR: ${{ github.workspace }}/.android-ci/cargo-target CARGO_TARGET_DIR: ${{ github.workspace }}/.android-ci/cargo-target
CMAKE_BUILD_PARALLEL_LEVEL: "4" CMAKE_BUILD_PARALLEL_LEVEL: "4"
steps: steps:
@@ -79,7 +80,8 @@ jobs:
clean: true clean: true
persist-credentials: false persist-credentials: false
- name: Restore isolated tool and Cargo cache # Keep provisioned tools/registry sources separate from completed Cargo outputs.
- name: Restore isolated tool and Cargo source cache
if: ${{ github.event.inputs.mode != 'inventory' }} if: ${{ github.event.inputs.mode != 'inventory' }}
id: cache id: cache
uses: actions/cache/restore@v3 uses: actions/cache/restore@v3
@@ -91,10 +93,31 @@ jobs:
.android-ci/tools/android-sdk .android-ci/tools/android-sdk
.android-ci/tools/skia-m153-0.101.2 .android-ci/tools/skia-m153-0.101.2
.android-ci/tools/gradle .android-ci/tools/gradle
.android-ci/cargo-target key: android-tools-linux-x64-arm64-v2-${{ hashFiles('.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh', 'Cargo.lock', 'rust-toolchain.toml', 'platform/android/gradle/wrapper/gradle-wrapper.properties') }}-${{ github.sha }}
key: android-arm64-v1-${{ hashFiles('.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh', 'Cargo.lock', 'rust-toolchain.toml', 'platform/android/gradle/wrapper/gradle-wrapper.properties') }}-${{ github.sha }}
restore-keys: | restore-keys: |
android-arm64-v1-${{ hashFiles('.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh', 'Cargo.lock', 'rust-toolchain.toml', 'platform/android/gradle/wrapper/gradle-wrapper.properties') }}- android-tools-linux-x64-arm64-v2-${{ hashFiles('.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh', 'Cargo.lock', 'rust-toolchain.toml', 'platform/android/gradle/wrapper/gradle-wrapper.properties') }}-
- name: Compute isolated application cache identity
if: ${{ github.event.inputs.mode != 'inventory' }}
id: application-key
run: python3 .gitea/android-application-cache.py key
- name: Restore completed application compilation
if: ${{ github.event.inputs.mode != 'inventory' }}
id: application-cache
uses: actions/cache/restore@v3
with:
path: |
.android-ci/cargo-target
.android-ci/application-cache-inputs.json
key: ${{ steps.application-key.outputs.key }}-${{ github.sha }}-${{ github.run_id }}
restore-keys: |
${{ steps.application-key.outputs.key }}-${{ github.sha }}-
${{ steps.application-key.outputs.key }}-
- name: Restore timestamps only for content-matched Cargo source inputs
if: ${{ github.event.inputs.mode != 'inventory' }}
run: python3 .gitea/android-application-cache.py sources
- name: Provision pinned Android tools in the job container - name: Provision pinned Android tools in the job container
if: ${{ github.event.inputs.mode != 'inventory' }} if: ${{ github.event.inputs.mode != 'inventory' }}
@@ -144,6 +167,7 @@ jobs:
set -euo pipefail set -euo pipefail
python3 .gitea/prepare-android-dependency-cache.py python3 .gitea/prepare-android-dependency-cache.py
cargo run --locked -p xtask -- deps --target "$TARGET" --llvm-dir "$LLVM_HOME" --jobs "$CARGO_BUILD_JOBS" cargo run --locked -p xtask -- deps --target "$TARGET" --llvm-dir "$LLVM_HOME" --jobs "$CARGO_BUILD_JOBS"
python3 .gitea/android-application-cache.py dependencies
- name: Checkpoint verified WebRTC before application build - name: Checkpoint verified WebRTC before application build
if: ${{ success() && github.event.inputs.mode != 'inventory' && steps.webrtc-cache.outputs.cache-hit != 'true' }} if: ${{ success() && github.event.inputs.mode != 'inventory' && steps.webrtc-cache.outputs.cache-hit != 'true' }}
@@ -163,20 +187,35 @@ jobs:
.android-ci/tools/android-sdk .android-ci/tools/android-sdk
.android-ci/tools/skia-m153-0.101.2 .android-ci/tools/skia-m153-0.101.2
.android-ci/tools/gradle .android-ci/tools/gradle
.android-ci/cargo-target
key: ${{ steps.cache.outputs.cache-primary-key }}-checkpoint key: ${{ steps.cache.outputs.cache-primary-key }}-checkpoint
- name: Build and verify full-feature test APK - name: Build and verify full-feature test APK
if: ${{ github.event.inputs.mode != 'inventory' }} if: ${{ github.event.inputs.mode != 'inventory' }}
id: application-build
run: | run: |
set -euo pipefail set -euo pipefail
export TEAMSPEACH_ANDROID_LOW_MEMORY=false
unset RUSTC_WORKSPACE_WRAPPER unset RUSTC_WORKSPACE_WRAPPER
mkdir -p .android-ci/diagnostics mkdir -p .android-ci/diagnostics
bash .gitea/android-memory-report.sh | tee .android-ci/diagnostics/before.txt bash .gitea/android-memory-report.sh | tee .android-ci/diagnostics/before.txt
trap 'status=$?; trap - EXIT; bash .gitea/android-memory-report.sh | tee .android-ci/diagnostics/after.txt; exit "$status"' EXIT trap 'status=$?; trap - EXIT; bash .gitea/android-memory-report.sh | tee .android-ci/diagnostics/after.txt; exit "$status"' EXIT
/usr/bin/time -v -o .android-ci/diagnostics/build-time.txt bash .gitea/build-android-variant.sh harness /usr/bin/time -v -o .android-ci/diagnostics/build-time.txt bash .gitea/build-android-variant.sh harness
# Save immediately after compilation/package verification, not after uploads.
# always()+outcome also checkpoints a successful APK if later diagnostics fail.
- name: Record stable inputs of the completed application build
if: ${{ always() && steps.application-build.outcome == 'success' && github.event.inputs.mode != 'inventory' }}
id: application-snapshot
run: python3 .gitea/android-application-cache.py snapshot
- name: Save completed application compilation
if: ${{ always() && steps.application-snapshot.outcome == 'success' && steps.application-cache.outputs.cache-hit != 'true' && github.event.inputs.mode != 'inventory' }}
uses: actions/cache/save@v3
with:
path: |
.android-ci/cargo-target
.android-ci/application-cache-inputs.json
key: ${{ steps.application-cache.outputs.cache-primary-key }}
- name: Report container memory evidence on build failure - name: Report container memory evidence on build failure
if: ${{ always() && steps.tools.outcome == 'success' && github.event.inputs.mode != 'inventory' }} if: ${{ always() && steps.tools.outcome == 'success' && github.event.inputs.mode != 'inventory' }}
run: | run: |
@@ -205,8 +244,8 @@ jobs:
if-no-files-found: error if-no-files-found: error
retention-days: 14 retention-days: 14
- name: Save verified build tool and Cargo cache - name: Save populated tool and Cargo source cache
if: ${{ success() && github.event.inputs.mode != 'inventory' && steps.cache.outputs.cache-hit != 'true' }} if: ${{ always() && steps.application-build.outcome == 'success' && github.event.inputs.mode != 'inventory' && steps.cache.outputs.cache-hit != 'true' }}
uses: actions/cache/save@v3 uses: actions/cache/save@v3
with: with:
path: | path: |
@@ -216,5 +255,4 @@ jobs:
.android-ci/tools/android-sdk .android-ci/tools/android-sdk
.android-ci/tools/skia-m153-0.101.2 .android-ci/tools/skia-m153-0.101.2
.android-ci/tools/gradle .android-ci/tools/gradle
.android-ci/cargo-target
key: ${{ steps.cache.outputs.cache-primary-key }} key: ${{ steps.cache.outputs.cache-primary-key }}
+15
View File
@@ -484,3 +484,18 @@ Host-side actual Slint rendering and pointer hit checks passed at360×760 and360
test and Rust syntax passed. New APK has not been built/installed, so fixed identity creation and test and Rust syntax passed. New APK has not been built/installed, so fixed identity creation and
Cancel on the physical phone are pending. Evidence paths and privacy boundaries are in the handoff. Cancel on the physical phone are pending. Evidence paths and privacy boundaries are in the handoff.
### Android sandbox and inset follow-up, 2026-11-12
Run4863 built and installed successfully; phone testing exposed a further `PermissionDenied` during
fresh profile creation and IME-covered actions. See [handoff](mobile-port-progress.md) for exact evidence.
Android's search-only ancestors cannot be opened with `O_RDONLY`. The Android branch of
[profile_import.rs](../native/src/services/profile_import.rs) now pins ancestor directories with
`O_PATH|O_DIRECTORY|O_NOFOLLOW`; final entries retain read access and symlink/type rejection.
No Windows/Apple permission policy was relaxed. Added an Android search-only-ancestor regression case;
its unit execution and the new APK's runtime result are not yet verified.
[TeamsPeachActivity](../platform/android/src/main/java/dev/teamspeach/mobile/TeamsPeachActivity.java)
projects system/IME insets onto the actual rendering surface to avoid consumed child insets and double
subtraction after adjustResize. Slint uses the maximum bottom obstruction. Gesture/three-button and IME
acceptance still require the new phone build; host geometry reasoning is not device acceptance.
+41
View File
@@ -109,6 +109,47 @@ Updated **2026-11-11**. Windows baseline remains `05e8d34bcf0e24a44f76e65220293c
AndroidLocationsBuildService initialization error. Setup defined conflicting Android preference AndroidLocationsBuildService initialization error. Setup defined conflicting Android preference
roots: ANDROID_USER_HOME=tools/android-user versus ANDROID_SDK_HOME=tools/home (implies home/.android). roots: ANDROID_USER_HOME=tools/android-user versus ANDROID_SDK_HOME=tools/home (implies home/.android).
Align both conventions to isolated HOME/.android; do not change compiler mode for this packaging error. Align both conventions to isolated HOME/.android; do not change compiler mode for this packaging error.
- **Run4863 SUCCESS (17m51s)** on `52d2c22ec0519a3e423dd3a38a9649dc96a4fdc7`: normal optimized
Rust/Slint/WebRTC build, Gradle package/verify and artifact upload succeeded; low-memory fallback
NOT used. Fixed Android user preference paths resolved the packaging failure.
- Downloaded full `android-harness-arm64-52d2c22ec0519a3e423dd3a38a9649dc96a4fdc7` bundle into
`dist/android-ci-4863/`; all build-info SHA256 entries matched, verification.passed=true,
optimization.scope=`workspace release defaults`. APK `TeamsPeach-0.1.7-android-arm64-harness-test.apk`,
124332719 bytes, SHA256 `477c60ee4da9b62a6b894de44a36db960d8e82ac307404c4fccb80006320e1ee`.
Exact receipts retained alongside APK. No release publication, phone installation or profile deletion;
device onboarding/voice acceptance of this new APK remains to be performed explicitly.
- Owner authorized installing new test APKs and checking the selected USB phone after builds.
Mic/server scenarios remain separately scoped; do not read real profiles or delete app data implicitly.
- Device smoke of run4863: initial unauthorized/USB transport failures cleared after owner confirmation
and cable reconnection. Update rejected INSTALL_FAILED_UPDATE_INCOMPATIBLE. Owner explicitly approved
deleting the old disposable installation/data; uninstall and fresh test APK install both returned Success.
- Actual TECNO KJ7/API34 UI: fullscreen onboarding and compact nickname input visible without scrolling;
Cancel returned to launcher and relaunch worked. Assistant entered disposable nickname AndroidSmoke
(no existing identity read). Keyboard covered bottom actions despite host-side preview pass; after
dismissing keyboard, Create reached Loading but remained there across observations. Identity creation
and profile-ready state NOT accepted; no matching error-level runtime/crash message was found.
Captures: target/desktop-acceptance/android-4863-{onboarding,keyboard,create-result,onboarded}.png.
No microphone grant/server connection performed. New device defects: real IME insets and bootstrap
completion require investigation; do not present successful APK build as functional phone acceptance.
- **2026-11-12 follow-up on the same run4863 installation:** after restart/unlock and disposable
AndroidSmoke submission the UI displayed `File operation failed (PermissionDenied)`, not a proven
identity-generation deadlock. Known profile owner/prefs/vault files were absent (existence checks only).
App-UID read-open checks denied `/`, `/data`, `/data/data`, while the private app directory/files
opened successfully. `profile_import.rs` had requested read access on every absolute ancestor.
- Android-only traversal now uses `O_PATH|O_DIRECTORY|O_NOFOLLOW` for ancestor handles; the final
entry still requires read access, metadata/type checks and no-follow protection remain. A regression
case exercises fresh profile initialization through a search-only ancestor and rejects a directory
symlink. Device verification of this fix is pending the next APK; no profile contents were inspected.
- Insets now come from the window and are projected onto the actual Slint SurfaceView, subtracting
already excluded bars/IME. Content reserves `max(navigation, IME)`, not their sum. Android onboarding
adds a small top gap, reduces bottom padding, and omits Import backup; Settings → Identities already
retains the existing identity-import action. Both keyboard and navigation-mode behavior await phone proof.
- CI completed-application cache is separated from provisioning/Cargo sources, partitioned by target,
tool/dependency/release/harness/optimization identity, and saved before uploads. SHA256/type/mode
matching restores only unchanged input timestamps after mandatory dependency verification. Python
syntax, YAML ordering and temporary content/change/directory/clock fixtures passed; Windows fixtures
adapted only unsupported no-follow utime, so Linux syscall/cache-service behavior awaits CI.
## First Android APK build ## First Android APK build
+15 -2
View File
@@ -428,6 +428,13 @@ impl ConfinedSource {
} }
#[cfg(unix)] #[cfg(unix)]
fn open_unix_absolute(path: &Path) -> Result<File> { fn open_unix_absolute(path: &Path) -> Result<File> {
// Android grants search, not directory-read access, above the app sandbox.
#[cfg(target_os = "android")]
let root = {
use std::os::unix::fs::OpenOptionsExt;
OpenOptions::new().read(true).custom_flags(libc::O_PATH | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC).open("/")?
};
#[cfg(not(target_os = "android"))]
let root = File::open("/")?; let root = File::open("/")?;
open_unix_relative(&root, path.strip_prefix("/").map_err(|_| err("invalid_profile_path", "Invalid absolute path"))?) open_unix_relative(&root, path.strip_prefix("/").map_err(|_| err("invalid_profile_path", "Invalid absolute path"))?)
} }
@@ -445,10 +452,16 @@ fn open_unix_relative(root: &File, path: &Path) -> Result<File> {
#[cfg(any(target_os = "macos", target_os = "ios"))] const NONBLOCK: i32 = 4; #[cfg(any(target_os = "macos", target_os = "ios"))] const NONBLOCK: i32 = 4;
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))] const NONBLOCK: i32 = 0x800; #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))] const NONBLOCK: i32 = 0x800;
let mut file = root.try_clone()?; let mut file = root.try_clone()?;
for component in path.components() { let mut components = path.components().peekable();
while let Some(component) = components.next() {
let Component::Normal(name) = component else { return Err(err("invalid_profile_path", "Invalid path component")) }; let Component::Normal(name) = component else { return Err(err("invalid_profile_path", "Invalid path component")) };
let name = CString::new(name.as_bytes()).map_err(|_| err("invalid_profile_path", "Invalid path byte"))?; let name = CString::new(name.as_bytes()).map_err(|_| err("invalid_profile_path", "Invalid path byte"))?;
let fd = unsafe { openat(file.as_raw_fd(), name.as_ptr(), NOFOLLOW | CLOEXEC | NONBLOCK) }; // nonblocking prevents FIFO hangs; regular files unaffected let flags = NOFOLLOW | CLOEXEC | NONBLOCK;
// Pin ancestors without requesting read/list permission. The final entry
// still needs normal read access; O_DIRECTORY + NOFOLLOW reject links.
#[cfg(target_os = "android")]
let flags = if components.peek().is_some() { flags | libc::O_PATH | libc::O_DIRECTORY } else { flags };
let fd = unsafe { openat(file.as_raw_fd(), name.as_ptr(), flags) }; // nonblocking prevents FIFO hangs; regular files unaffected
if fd < 0 { return Err(std::io::Error::last_os_error().into()); } if fd < 0 { return Err(std::io::Error::last_os_error().into()); }
file = unsafe { File::from_raw_fd(fd) }; file = unsafe { File::from_raw_fd(fd) };
deny_link(&file.metadata()?)?; deny_link(&file.metadata()?)?;
@@ -204,6 +204,27 @@ fn descriptor_relative_opens_reject_directory_and_file_links() {
assert!(open_unix_relative(&root, Path::new("file-link")).is_err()); assert!(open_unix_relative(&root, Path::new("file-link")).is_err());
} }
#[cfg(target_os = "android")]
#[test]
fn onboarding_traverses_search_only_ancestors_without_following_links() {
use std::os::unix::fs::{PermissionsExt, symlink};
let fixture = Fixture::new();
let ancestor = fixture.0.join("search-only");
let container = ancestor.join("files");
fs::create_dir_all(&container).unwrap();
let destination = container.join("profile-v1");
symlink(&container, ancestor.join("linked-files")).unwrap();
fs::set_permissions(&ancestor, fs::Permissions::from_mode(0o100)).unwrap();
let created = initialize_native_root(&destination);
let inspected = inspect_native_root(&destination);
let escaped = open_unix_absolute(&ancestor.join("linked-files/profile-v1"));
// Restore directory access before assertions so Fixture always cleans up.
fs::set_permissions(&ancestor, fs::Permissions::from_mode(0o700)).unwrap();
created.unwrap();
assert_eq!(inspected.unwrap(), ProfileRootState::Native);
assert!(escaped.is_err());
}
#[test] #[test]
fn legacy_discovery_returns_all_real_candidates_without_opening_keys() { fn legacy_discovery_returns_all_real_candidates_without_opening_keys() {
let fixture = Fixture::new(); let fixture = Fixture::new();
+3 -1
View File
@@ -16,7 +16,7 @@ export component AppWindow inherits Window {
preferred-width: 1280px; preferred-width: 1280px;
preferred-height: 800px; preferred-height: 800px;
min-width: 320px; min-width: 320px;
min-height: 360px; min-height: Theme.android ? 0px : 360px;
default-font-family: Theme.font-family; default-font-family: Theme.font-family;
default-font-size: Theme.font-size; default-font-size: Theme.font-size;
background: Theme.shaded; background: Theme.shaded;
@@ -32,6 +32,8 @@ export component AppWindow inherits Window {
} }
measure := Text { visible: false; accessible-role: none; } measure := Text { visible: false; accessible-role: none; }
keyboard := FocusScope { keyboard := FocusScope {
// Android reports only the overlap remaining inside the rendering surface.
// Bars and IME overlap at the bottom: reserve their maximum, not their sum.
x: Theme.safe-left; y: Theme.safe-top; x: Theme.safe-left; y: Theme.safe-top;
width: max(0px, parent.width - Theme.safe-left - Theme.safe-right); width: max(0px, parent.width - Theme.safe-left - Theme.safe-right);
height: max(0px, parent.height - Theme.safe-top - max(Theme.safe-bottom, Theme.ime-inset)); height: max(0px, parent.height - Theme.safe-top - max(Theme.safe-bottom, Theme.ime-inset));
+4 -6
View File
@@ -32,9 +32,12 @@ component AndroidOnboarding inherits Rectangle {
background: Theme.shaded; background: Theme.shaded;
accessible-role: form; accessible-role: form;
accessible-label: DialogBridge.title; accessible-label: DialogBridge.title;
property <bool> typing: Theme.ime-inset > 0px; // A resized Android surface can exclude the IME entirely, leaving a zero overlap inset.
property <bool> typing: Theme.ime-inset > 0px || root.height < 480px;
VerticalLayout { VerticalLayout {
padding: root.typing ? 12px : 24px; padding: root.typing ? 12px : 24px;
padding-top: root.typing ? 16px : 28px;
padding-bottom: 8px;
spacing: root.typing ? 6px : 16px; spacing: root.typing ? 6px : 16px;
Text { text: DialogBridge.title; color: Theme.fg; font-size: Theme.font-size * (root.typing ? 1.25 : 1.8); font-weight: 700; wrap: word-wrap; } Text { text: DialogBridge.title; color: Theme.fg; font-size: Theme.font-size * (root.typing ? 1.25 : 1.8); font-weight: 700; wrap: word-wrap; }
if !root.typing: Text { text: DialogBridge.description; color: Theme.fg; font-size: Theme.font-size; wrap: word-wrap; } if !root.typing: Text { text: DialogBridge.description; color: Theme.fg; font-size: Theme.font-size; wrap: word-wrap; }
@@ -60,11 +63,6 @@ component AndroidOnboarding inherits Rectangle {
if DialogBridge.error != "": Text { text: DialogBridge.error; color: Theme.error; wrap: word-wrap; accessible-live-region: assertive; } 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.fg; } if DialogBridge.busy: Text { text: DialogBridge.loading-label; color: Theme.fg; }
Rectangle { vertical-stretch: 1; min-height: 0px; } Rectangle { vertical-stretch: 1; min-height: 0px; }
if !root.typing: VerticalLayout {
spacing: 4px;
vertical-stretch: 0;
for action in DialogBridge.actions: ActionButton { text: action.label; enabled: action.enabled && !DialogBridge.busy; destructive: action.destructive; clicked => { ShellBridge.invoke(action.id); } }
}
ActionButton { height: Theme.touch-target; vertical-stretch: 0; text: DialogBridge.submit-label; primary: true; enabled: !DialogBridge.busy; clicked => { DialogBridge.submit(); } } ActionButton { height: Theme.touch-target; vertical-stretch: 0; text: DialogBridge.submit-label; primary: true; enabled: !DialogBridge.busy; clicked => { DialogBridge.submit(); } }
ActionButton { height: Theme.touch-target; vertical-stretch: 0; text: DialogBridge.cancel-label; enabled: !DialogBridge.busy; clicked => { DialogBridge.cancel(); } } ActionButton { height: Theme.touch-target; vertical-stretch: 0; text: DialogBridge.cancel-label; enabled: !DialogBridge.busy; clicked => { DialogBridge.cancel(); } }
} }
@@ -22,6 +22,13 @@ public final class TeamsPeachActivity extends NativeActivity {
private SafGrant sharedGrant; private SafGrant sharedGrant;
private android.net.Uri installerUri; private android.net.Uri installerUri;
private int requestedPermission; private int requestedPermission;
private SurfaceView renderSurface;
private final Rect insetWindow = new Rect(), visibleWindow = new Rect();
private final int[] decorLocation = new int[2], surfaceLocation = new int[2];
private final ViewTreeObserver.OnGlobalLayoutListener insetLayout = this::reportInsets;
private int insetTop, insetRight, insetBottom, insetLeft, insetKeyboard;
private float insetScale;
private long insetGeneration;
private static final int PICK = 501, PERMISSION = 502, SHARE = 503, INSTALL = 504, INSTALL_PERMISSION = 505; private static final int PICK = 501, PERMISSION = 502, SHARE = 503, INSTALL = 504, INSTALL_PERMISSION = 505;
@Override protected void onCreate(Bundle state) { @Override protected void onCreate(Bundle state) {
PlatformBridge.activity = new java.lang.ref.WeakReference<>(this); PlatformBridge.activity = new java.lang.ref.WeakReference<>(this);
@@ -31,22 +38,59 @@ public final class TeamsPeachActivity extends NativeActivity {
addContentView(accessibility, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); addContentView(accessibility, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
// Slint 1.18.1 already owns API34+ predictive-back and the decor's inset listener. // Slint 1.18.1 already owns API34+ predictive-back and the decor's inset listener.
if (Build.VERSION.SDK_INT == 33) getOnBackInvokedDispatcher().registerOnBackInvokedCallback(android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT, () -> PlatformBridge.nativeBack(generation)); if (Build.VERSION.SDK_INT == 33) getOnBackInvokedDispatcher().registerOnBackInvokedCallback(android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT, () -> PlatformBridge.nativeBack(generation));
// Observe without replacing Slint's decor listener or IME animation callback.
accessibility.setOnApplyWindowInsetsListener((view, insets) -> { accessibility.setOnApplyWindowInsetsListener((view, insets) -> {
float scale = getResources().getDisplayMetrics().density; reportInsets();
int top, right, bottom, left, keyboard = 0;
if (Build.VERSION.SDK_INT >= 30) {
android.graphics.Insets safe = getWindowManager().getCurrentWindowMetrics().getWindowInsets().getInsets(WindowInsets.Type.systemBars() | WindowInsets.Type.displayCutout());
top = safe.top; right = safe.right; bottom = safe.bottom; left = safe.left;
keyboard = insets.getInsets(WindowInsets.Type.ime()).bottom;
} else {
top = insets.getSystemWindowInsetTop(); right = insets.getSystemWindowInsetRight(); bottom = insets.getSystemWindowInsetBottom(); left = insets.getSystemWindowInsetLeft();
Rect visible = new Rect(); view.getWindowVisibleDisplayFrame(visible);
int difference = view.getRootView().getHeight() - visible.bottom;
if (difference > 100 * scale) keyboard = difference;
}
PlatformBridge.nativeInsets(generation, top / scale, right / scale, bottom / scale, left / scale, keyboard / scale);
return insets; return insets;
}); });
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(insetLayout);
}
private void reportInsets() {
if (generation == 0 || renderSurface == null || !renderSurface.isAttachedToWindow()
|| renderSurface.getWidth() == 0 || renderSurface.getHeight() == 0) return;
View decor = getWindow().getDecorView();
// A child receives consumed insets on some ROMs. The root retains the IME state.
WindowInsets insets = decor.getRootWindowInsets();
if (insets == null) return;
float scale = getResources().getDisplayMetrics().density;
decor.getLocationOnScreen(decorLocation);
insetWindow.set(decorLocation[0], decorLocation[1], decorLocation[0] + decor.getWidth(), decorLocation[1] + decor.getHeight());
int top, right, bottom, left, keyboard = 0;
if (Build.VERSION.SDK_INT >= 30) {
WindowMetrics metrics = getWindowManager().getCurrentWindowMetrics();
insetWindow.set(metrics.getBounds());
android.graphics.Insets safe = metrics.getWindowInsets().getInsets(WindowInsets.Type.systemBars() | WindowInsets.Type.displayCutout());
top = safe.top; right = safe.right; bottom = safe.bottom; left = safe.left;
keyboard = insets.getInsets(WindowInsets.Type.ime()).bottom;
} else {
// Stable bars exclude the keyboard on API26-29; legacy system insets can include it.
top = insets.getStableInsetTop(); right = insets.getStableInsetRight();
bottom = insets.getStableInsetBottom(); left = insets.getStableInsetLeft();
if (Build.VERSION.SDK_INT >= 28 && insets.getDisplayCutout() != null) {
DisplayCutout cutout = insets.getDisplayCutout();
top = Math.max(top, cutout.getSafeInsetTop()); right = Math.max(right, cutout.getSafeInsetRight());
bottom = Math.max(bottom, cutout.getSafeInsetBottom()); left = Math.max(left, cutout.getSafeInsetLeft());
}
decor.getWindowVisibleDisplayFrame(visibleWindow);
int obscured = Math.max(insets.getSystemWindowInsetBottom(), insetWindow.bottom - visibleWindow.bottom);
if (obscured > bottom + 100 * scale) keyboard = obscured;
}
renderSurface.getLocationOnScreen(surfaceLocation);
// adjustResize / non-edge-to-edge windows already exclude some bars or the IME.
// Send only the overlap with Slint's actual surface, never the full window inset twice.
int excludedTop = Math.max(0, surfaceLocation[1] - insetWindow.top);
int excludedLeft = Math.max(0, surfaceLocation[0] - insetWindow.left);
int excludedRight = Math.max(0, insetWindow.right - surfaceLocation[0] - renderSurface.getWidth());
int excludedBottom = Math.max(0, insetWindow.bottom - surfaceLocation[1] - renderSurface.getHeight());
top = Math.max(0, top - excludedTop); right = Math.max(0, right - excludedRight);
bottom = Math.max(0, bottom - excludedBottom); left = Math.max(0, left - excludedLeft);
keyboard = Math.max(0, keyboard - excludedBottom);
// Global layout also runs after unrelated UI updates; do not feed those back into Slint.
if (insetGeneration == generation && insetScale == scale && insetTop == top && insetRight == right
&& insetBottom == bottom && insetLeft == left && insetKeyboard == keyboard) return;
insetGeneration = generation; insetScale = scale;
insetTop = top; insetRight = right; insetBottom = bottom; insetLeft = left; insetKeyboard = keyboard;
PlatformBridge.nativeInsets(generation, top / scale, right / scale, bottom / scale, left / scale, keyboard / scale);
} }
@Override protected void onResume() { @Override protected void onResume() {
super.onResume(); resumed = true; PlatformBridge.activity = new java.lang.ref.WeakReference<>(this); CaptureBridge.bindActivity(this); super.onResume(); resumed = true; PlatformBridge.activity = new java.lang.ref.WeakReference<>(this); CaptureBridge.bindActivity(this);
@@ -59,6 +103,7 @@ public final class TeamsPeachActivity extends NativeActivity {
} }
@Override protected void onDestroy() { @Override protected void onDestroy() {
CaptureBridge.unbindActivity(this); CaptureBridge.unbindActivity(this);
getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(insetLayout);
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 (permissionRequest > 0) PlatformBridge.nativeText(permissionRequest, null, "activity_destroyed");
if (pipToken != 0) PlatformBridge.nativePip(pipToken, false, true); if (pipToken != 0) PlatformBridge.nativePip(pipToken, false, true);
@@ -81,8 +126,8 @@ public final class TeamsPeachActivity extends NativeActivity {
// Keep its invisible IME proxy out of TalkBack without changing its input connection. // Keep its invisible IME proxy out of TalkBack without changing its input connection.
java.util.ArrayDeque<View> views=new java.util.ArrayDeque<>();views.add(getWindow().getDecorView()); java.util.ArrayDeque<View> views=new java.util.ArrayDeque<>();views.add(getWindow().getDecorView());
int visited=0; int visited=0;
while(!views.isEmpty() && visited++<256){View view=views.removeFirst();if("SlintInputView".equals(view.getClass().getSimpleName()))view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);if(view instanceof ViewGroup){ViewGroup group=(ViewGroup)view;for(int i=0;i<group.getChildCount();i++)views.addLast(group.getChildAt(i));}} while(!views.isEmpty() && visited++<256){View view=views.removeFirst();if(view instanceof SurfaceView)renderSurface=(SurfaceView)view;if("SlintInputView".equals(view.getClass().getSimpleName()))view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);if(view instanceof ViewGroup){ViewGroup group=(ViewGroup)view;for(int i=0;i<group.getChildCount();i++)views.addLast(group.getChildAt(i));}}
accessibility.bringToFront();accessibility.requestApplyInsets(); accessibility.bringToFront();accessibility.requestApplyInsets();reportInsets();
} }
@Override public void onConfigurationChanged(Configuration value) { super.onConfigurationChanged(value); reportConfiguration(); } @Override public void onConfigurationChanged(Configuration value) { super.onConfigurationChanged(value); reportConfiguration(); }
@Override public void onTrimMemory(int level) { super.onTrimMemory(level); if (level >= TRIM_MEMORY_RUNNING_LOW) PlatformBridge.nativeEvent(generation, 6, true); } @Override public void onTrimMemory(int level) { super.onTrimMemory(level); if (level >= TRIM_MEMORY_RUNNING_LOW) PlatformBridge.nativeEvent(generation, 6, true); }