diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 78d347b..d2f8b30 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,5 +1,8 @@ name: Build & Release +# Pull requests: unit tests + debug build + R8 release build of the stable flavor (debug-signed). +# Pushes to main (and v* tags): the same checks, both flavors, signed with the release key, published. + on: push: branches: [main, beta] @@ -23,12 +26,18 @@ on: - 'LICENSE' workflow_dispatch: -permissions: - contents: write +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: build: runs-on: ubuntu-latest + timeout-minutes: 40 + permissions: + contents: write + env: + IS_RELEASE: ${{ github.event_name == 'push' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main') }} steps: - uses: actions/checkout@v4 @@ -37,59 +46,91 @@ jobs: distribution: temurin java-version: 17 + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + with: + cache-read-only: ${{ github.ref != 'refs/heads/main' }} + - name: Setup Android SDK uses: android-actions/setup-android@v3 with: packages: 'platform-tools platforms;android-35 build-tools;35.0.0' - - name: Accept licenses - run: yes | sdkmanager --licenses || true + - name: Make gradlew executable + run: chmod +x gradlew - - - name: Decode release keystore (optional) - id: keystore + # Official repo: signing secrets are mandatory (never publish a debug-signed APK). + # Forks and contributors have no secrets: they get a debug-signed build, as before. + - name: Decode release keystore + id: keys + if: env.IS_RELEASE == 'true' env: RELEASE_KEYSTORE_BASE64: ${{ secrets.RELEASE_KEYSTORE_BASE64 }} RELEASE_STORE_PASSWORD: ${{ secrets.RELEASE_STORE_PASSWORD }} RELEASE_KEY_PASSWORD: ${{ secrets.RELEASE_KEY_PASSWORD }} RELEASE_KEY_ALIAS: ${{ secrets.RELEASE_KEY_ALIAS }} run: | - if [ -n "${RELEASE_KEYSTORE_BASE64:-}" ] && [ -n "${RELEASE_STORE_PASSWORD:-}" ] \ - && [ -n "${RELEASE_KEY_PASSWORD:-}" ] && [ -n "${RELEASE_KEY_ALIAS:-}" ]; then - echo "$RELEASE_KEYSTORE_BASE64" | base64 -d > "$GITHUB_WORKSPACE/release.jks" - echo "path=$GITHUB_WORKSPACE/release.jks" >> "$GITHUB_OUTPUT" - echo "present=true" >> "$GITHUB_OUTPUT" - echo "Release keystore decoded." - else - echo "present=false" >> "$GITHUB_OUTPUT" - echo "Release key secrets not set — release APK will use debug signing (skip)." + if [ -z "${RELEASE_KEYSTORE_BASE64:-}" ] || [ -z "${RELEASE_STORE_PASSWORD:-}" ] \ + || [ -z "${RELEASE_KEY_PASSWORD:-}" ] || [ -z "${RELEASE_KEY_ALIAS:-}" ]; then + if [ "$GITHUB_REPOSITORY" = "wized2/Fern" ]; then + echo "::error::Release signing secrets are missing. Refusing to publish a debug-signed APK." + exit 1 + fi + echo "::warning::No signing secrets in this fork: building with the debug key." + echo "signed=false" >> "$GITHUB_OUTPUT" + exit 0 fi + echo "$RELEASE_KEYSTORE_BASE64" | base64 -d > "$RUNNER_TEMP/release.jks" + echo "Keystore OK: $(wc -c < "$RUNNER_TEMP/release.jks") bytes" + echo "signed=true" >> "$GITHUB_OUTPUT" - - name: Build debug + release APKs + - name: Unit tests and debug build + run: ./gradlew testStableDebugUnitTest assembleStableDebug --stacktrace + + - name: Build release (pull request, stable only) + if: env.IS_RELEASE != 'true' + run: ./gradlew assembleStableRelease --stacktrace + + - name: Build release (stable and beta, signed) + if: env.IS_RELEASE == 'true' env: - RELEASE_STORE_FILE: ${{ steps.keystore.outputs.present == 'true' && format('{0}/release.jks', github.workspace) || '' }} + # Blank when there is no key (forks): Gradle then falls back to the debug key. + RELEASE_STORE_FILE: ${{ steps.keys.outputs.signed == 'true' && format('{0}/release.jks', runner.temp) || '' }} RELEASE_STORE_PASSWORD: ${{ secrets.RELEASE_STORE_PASSWORD }} RELEASE_KEY_ALIAS: ${{ secrets.RELEASE_KEY_ALIAS }} RELEASE_KEY_PASSWORD: ${{ secrets.RELEASE_KEY_PASSWORD }} + run: ./gradlew assembleStableRelease assembleBetaRelease --stacktrace + + - name: Verify release signature + if: env.IS_RELEASE == 'true' && steps.keys.outputs.signed == 'true' run: | - chmod +x gradlew - if [ "${{ steps.keystore.outputs.present }}" = "true" ]; then - export RELEASE_STORE_FILE="$GITHUB_WORKSPACE/release.jks" - echo "Signing release with uploaded keystore" - else - unset RELEASE_STORE_FILE || true - echo "No release keystore — Gradle falls back to debug signing" - fi - ./gradlew assembleStableDebug assembleBetaDebug testStableDebugUnitTest assembleStableRelease assembleBetaRelease --no-daemon --stacktrace + set -euo pipefail + BT=$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -1) + for apk in app/build/outputs/apk/stable/release/*.apk app/build/outputs/apk/beta/release/*.apk; do + "$BT/apksigner" verify --verbose --print-certs "$apk" | tee /tmp/verify.txt + grep -q 'Verified using v2 scheme.*true' /tmp/verify.txt + if grep -qi 'CN=Android Debug' /tmp/verify.txt; then + echo "::error::$apk is signed with the Android debug key" + exit 1 + fi + done + + - name: Upload test reports + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-reports + path: app/build/reports/tests + if-no-files-found: ignore + retention-days: 7 - name: Upload debug APK uses: actions/upload-artifact@v4 with: name: Fern-debug - path: | - app/build/outputs/apk/stable/debug/*.apk - app/build/outputs/apk/beta/debug/*.apk + path: app/build/outputs/apk/stable/debug/*.apk if-no-files-found: error + retention-days: 14 - name: Upload release APK uses: actions/upload-artifact@v4 @@ -100,8 +141,16 @@ jobs: app/build/outputs/apk/beta/release/*.apk if-no-files-found: error + - name: Keep R8 mapping files + if: env.IS_RELEASE == 'true' + uses: actions/upload-artifact@v4 + with: + name: r8-mapping + path: app/build/outputs/mapping/*Release/mapping.txt + if-no-files-found: warn + - name: Read versionName - if: github.event_name == 'push' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main') + if: env.IS_RELEASE == 'true' id: ver run: | VN=$(grep -E 'versionName\s*=' app/build.gradle.kts | head -1 | sed -E 's/.*"([^"]+)".*/\1/') @@ -110,34 +159,13 @@ jobs: echo "Version $VN" - name: Prepare release assets - if: github.event_name == 'push' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main') + if: env.IS_RELEASE == 'true' run: | mkdir -p release-assets cp app/build/outputs/apk/stable/release/*.apk release-assets/Fern-release.apk - cp app/build/outputs/apk/beta/release/*.apk release-assets/Fern-beta.apk || true - # debug APK stays as workflow artifact only (smaller GitHub Releases; avoids large upload timeouts) + cp app/build/outputs/apk/beta/release/*.apk release-assets/Fern-beta.apk ls -la release-assets/ - - name: Load release notes - if: github.event_name == 'push' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main') - id: notes - run: | - if [ -f RELEASE_NOTES.md ]; then - { - echo "body<> "$GITHUB_OUTPUT" - else - { - echo "body<> "$GITHUB_OUTPUT" - fi - - name: Create GitHub Release (tag push) if: startsWith(github.ref, 'refs/tags/v') uses: softprops/action-gh-release@v2 diff --git a/.gradle/8.11/checksums/checksums.lock b/.gradle/8.11/checksums/checksums.lock deleted file mode 100644 index 821e99d..0000000 Binary files a/.gradle/8.11/checksums/checksums.lock and /dev/null differ diff --git a/.gradle/8.11/checksums/md5-checksums.bin b/.gradle/8.11/checksums/md5-checksums.bin deleted file mode 100644 index 9a14336..0000000 Binary files a/.gradle/8.11/checksums/md5-checksums.bin and /dev/null differ diff --git a/.gradle/8.11/checksums/sha1-checksums.bin b/.gradle/8.11/checksums/sha1-checksums.bin deleted file mode 100644 index 88a8b0f..0000000 Binary files a/.gradle/8.11/checksums/sha1-checksums.bin and /dev/null differ diff --git a/.gradle/8.11/fileChanges/last-build.bin b/.gradle/8.11/fileChanges/last-build.bin deleted file mode 100644 index f76dd23..0000000 Binary files a/.gradle/8.11/fileChanges/last-build.bin and /dev/null differ diff --git a/.gradle/8.11/fileHashes/fileHashes.lock b/.gradle/8.11/fileHashes/fileHashes.lock deleted file mode 100644 index 37ddf62..0000000 Binary files a/.gradle/8.11/fileHashes/fileHashes.lock and /dev/null differ diff --git a/.gradle/8.11/gc.properties b/.gradle/8.11/gc.properties deleted file mode 100644 index e69de29..0000000 diff --git a/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/.gradle/buildOutputCleanup/buildOutputCleanup.lock deleted file mode 100644 index 12af055..0000000 Binary files a/.gradle/buildOutputCleanup/buildOutputCleanup.lock and /dev/null differ diff --git a/.gradle/buildOutputCleanup/cache.properties b/.gradle/buildOutputCleanup/cache.properties deleted file mode 100644 index fec1c96..0000000 --- a/.gradle/buildOutputCleanup/cache.properties +++ /dev/null @@ -1,2 +0,0 @@ -#Mon Sep 14 12:45:44 UTC 2026 -gradle.version=8.11 diff --git a/.gradle/vcs-1/gc.properties b/.gradle/vcs-1/gc.properties deleted file mode 100644 index e69de29..0000000 diff --git a/CHANGELOG.md b/CHANGELOG.md index b3901f9..615ed74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,32 +1,50 @@ -## 1.11.0 +# Changelog -* **Advanced mode performance**: phased shell work (Lite/Balanced/Full), 3–15s interval, probe cache, mutex — stops lag from stacking dumpsys -* Manual Refresh still runs a full heavy sample when you need immediate per-app data -* Active Apps search; RAM alert threshold; ZRAM + process count on elevated snapshot -* Core MHz sysfs cached 3s; shorter elevated CPU dwell -* CI: paths-ignore for site/docs-only changes; release body from `RELEASE_NOTES.md` -* Website primary: https://get-fern.vercel.app +All notable changes to Fern are listed here. Versions follow the Android `versionName`. -## 1.10.1 +## 1.12.0 -* Fix CI: AppSort enum must not carry @Composable; ActiveApps is @Composable again -* Primary website: https://get-fern.vercel.app +**Security** +* Force-stop and clear-cache now validate the package name against a strict Android package-name pattern before it reaches the Shizuku/root shell. Previously a name containing `;`, `|`, `$()` or a newline could have injected commands. -# Changelog +**Performance and battery** +* Preferences are written with `apply()` instead of a synchronous `commit()` on the UI thread +* UI state is collected with `collectAsStateWithLifecycle`, so nothing recomposes while the app is in the background +* One sysfs pass per refresh for CPU frequencies (was three); static device info (kernel, security patch, CPU topology, max MHz, sensor count) is read once +* `/proc/stat` and `/proc/loadavg` are skipped for 60 s after repeated failures, and the `cat` subprocess fallback (blocked by the same SELinux policy) is removed +* Overlay pill reads only battery temperature and RAM instead of a full capture on the main thread, pauses while the screen is off, and repositions on rotation -## Unreleased +**UI** +* Status and navigation bar icons follow the selected theme (dark-on-dark in dark mode before) + +**Build and release** +* Pull requests build the stable flavor only; beta and signed builds run on `main` and tags +* On the official repository a release fails if the signing secrets are missing, and the APK signature is verified (not the debug key) before publishing. Forks without secrets still build debug-signed APKs +* Gradle build cache directory is no longer tracked; R8 mapping files are kept as a CI artifact + +## 1.11.3 - Active apps: clearer empty state with Advanced mode guidance - Settings: TalkBack labels on key switches - Details: copy snapshot to clipboard - Tests: more MetricsParse / HistoryExport edge cases - Docs: first contribution in 15 minutes - - -## Unreleased - Details: share plain text, **Markdown snapshot**, and **session history CSV** - Richer bottom navigation content descriptions (accessibility) - HistoryExport helpers + unit tests for CSV/Markdown +## 1.11.0 + +* **Advanced mode performance**: phased shell work (Lite/Balanced/Full), 3–15s interval, probe cache, mutex — stops lag from stacking dumpsys +* Manual Refresh still runs a full heavy sample when you need immediate per-app data +* Active Apps search; RAM alert threshold; ZRAM + process count on elevated snapshot +* Core MHz sysfs cached 3s; shorter elevated CPU dwell +* CI: paths-ignore for site/docs-only changes; release body from `RELEASE_NOTES.md` +* Website primary: https://get-fern.vercel.app + +## 1.10.1 + +* Fix CI: AppSort enum must not carry @Composable; ActiveApps is @Composable again +* Primary website: https://get-fern.vercel.app ## 1.10.0 @@ -128,9 +146,6 @@ - UI: refined top bar + status bar contrast, roomier metric spacing - Theme: OLED-friendlier dark surfaces, consistent corner radii -# Changelog - -All notable changes to Fern are listed here. ## 1.5.22 — 2026-09-17 diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index bcffdd1..112d3aa 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,9 +1,17 @@ -# Fern 1.11.3 +# Fern 1.12.0 -Docs & discoverability polish. +Faster, lighter and safer. No new screens; everything you already use got cheaper to run. -- README badges fixed (workflow path + shields for release / stars) -- Issue templates + funding metadata -- Cross-links to Latch / Subcord +**Security** +- App names are now strictly validated before Force stop / Clear cache reach the Shizuku or root shell (closes a command-injection path). -App logic unchanged from 1.11.2; re-release for store/listing consistency. +**Speed and battery** +- Settings save in the background instead of blocking the screen. +- Nothing redraws while Fern is not visible. +- Far fewer system file reads per refresh; device info that cannot change is read once. +- The floating pill reads only what it shows and sleeps while the screen is off. + +**Fixes** +- Status bar and navigation bar icons are readable in dark theme. + +Fern still asks for no internet permission and sends nothing anywhere. diff --git a/SECURITY.md b/SECURITY.md index 8c5a8f8..c4c24f7 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -8,7 +8,7 @@ Security fixes are applied to the latest release on the `main` branch. Please report security issues privately: -- **Email:** acartoon7668@gmail.com +- **Email:** acartoon7668@gmail.com - Or use GitHub **Private vulnerability reporting** on this repository if enabled. Please include steps to reproduce, affected version/commit, and impact. @@ -19,3 +19,18 @@ Reports related to optional **Shizuku / root** Advanced mode are especially welc ## Coordinated disclosure We aim to acknowledge reports promptly and ship fixes for confirmed high-impact issues in a timely release. + +## Threat model + +What Fern is designed to guarantee, and where the boundaries are. + +| Area | Design | +| --- | --- | +| Network | The app declares no `INTERNET` permission. It cannot send data off the device. | +| Data at rest | Only preferences (theme, thresholds, overlay layout) are stored. `allowBackup` is off. Metrics history lives in memory and is cleared on exit. | +| Permissions | Usage access (Active Apps) and Display over other apps (overlay) are optional and user-granted. Nothing is requested at install time. | +| Elevated mode | Off by default. Needs Shizuku or root that the user has already set up and explicitly granted to Fern. | +| Shell input | The only commands built from variable data are `am force-stop` and `pm clear --cache-only`. The package name must match `^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$` (max 255 chars) before it is used; anything else is refused. | +| Release integrity | On the official repository CI refuses to publish an APK without the release key and verifies the signature with `apksigner` before upload. Forks have no secrets and build debug-signed APKs. | + +Out of scope: a device that is already rooted by malware, or a compromised Shizuku service. diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 6311842..f202da4 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -12,8 +12,8 @@ android { applicationId = "com.endroid.fern" minSdk = 26 targetSdk = 35 - versionCode = 75 - versionName = "1.11.3" + versionCode = 76 + versionName = "1.12.0" resourceConfigurations += listOf("en", "es", "de") ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a") diff --git a/app/src/main/java/com/endroid/fern/MainActivity.kt b/app/src/main/java/com/endroid/fern/MainActivity.kt index ac2dba4..63bb8d1 100644 --- a/app/src/main/java/com/endroid/fern/MainActivity.kt +++ b/app/src/main/java/com/endroid/fern/MainActivity.kt @@ -9,7 +9,10 @@ import androidx.activity.enableEdgeToEdge import androidx.core.view.WindowCompat import androidx.activity.viewModels import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.SideEffect +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.endroid.fern.data.ThemeMode import androidx.compose.runtime.getValue import com.endroid.fern.ui.FernApp import rikka.shizuku.Shizuku @@ -81,13 +84,17 @@ class MainActivity : ComponentActivity() { } catch (e: Exception) { Log.e(TAG, "Shizuku listener register failed", e) } - WindowCompat.getInsetsController(window, window.decorView).isAppearanceLightStatusBars = true - WindowCompat.getInsetsController(window, window.decorView).isAppearanceLightNavigationBars = true setContent { - val theme by viewModel.themeMode.collectAsState() - val seedArgb by viewModel.seedColorArgb.collectAsState() - val amoled by viewModel.amoledDark.collectAsState() - val keepOn by viewModel.keepScreenOn.collectAsState() + val theme by viewModel.themeMode.collectAsStateWithLifecycle() + val seedArgb by viewModel.seedColorArgb.collectAsStateWithLifecycle() + val amoled by viewModel.amoledDark.collectAsStateWithLifecycle() + val keepOn by viewModel.keepScreenOn.collectAsStateWithLifecycle() + val darkBars = theme == ThemeMode.DARK || (theme == ThemeMode.AUTO && isSystemInDarkTheme()) + SideEffect { + val c = WindowCompat.getInsetsController(window, window.decorView) + c.isAppearanceLightStatusBars = !darkBars + c.isAppearanceLightNavigationBars = !darkBars + } LaunchedEffect(keepOn) { if (keepOn) { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) @@ -96,26 +103,26 @@ class MainActivity : ComponentActivity() { } } FernTheme(mode = theme, seedColor = androidx.compose.ui.graphics.Color(seedArgb), amoledDark = amoled) { - val snap by viewModel.snapshot.collectAsState() - val cpu by viewModel.historyCpu.collectAsState() - val ram by viewModel.historyRam.collectAsState() - val bat by viewModel.historyBattery.collectAsState() - val net by viewModel.historyNet.collectAsState() - val storage by viewModel.historyStorage.collectAsState() - val refresh by viewModel.refreshMs.collectAsState() - val lastUpdated by viewModel.lastUpdatedMs.collectAsState() - val haptics by viewModel.haptics.collectAsState() - val pauseBg by viewModel.pauseInBackground.collectAsState() - val peakCpu by viewModel.peakCpu.collectAsState() - val peakRam by viewModel.peakRam.collectAsState() - val peakNet by viewModel.peakNet.collectAsState() - val advancedMode by viewModel.advancedMode.collectAsState() - val elevatedStatus by viewModel.elevatedStatus.collectAsState() - val advancedSnap by viewModel.advancedSnapshot.collectAsState() - val avgCpu by viewModel.avgCpu.collectAsState() - val avgRam by viewModel.avgRam.collectAsState() - val elevatedProfile by viewModel.elevatedProfile.collectAsState() - val elevatedIntervalSec by viewModel.elevatedIntervalSecFlow.collectAsState() + val snap by viewModel.snapshot.collectAsStateWithLifecycle() + val cpu by viewModel.historyCpu.collectAsStateWithLifecycle() + val ram by viewModel.historyRam.collectAsStateWithLifecycle() + val bat by viewModel.historyBattery.collectAsStateWithLifecycle() + val net by viewModel.historyNet.collectAsStateWithLifecycle() + val storage by viewModel.historyStorage.collectAsStateWithLifecycle() + val refresh by viewModel.refreshMs.collectAsStateWithLifecycle() + val lastUpdated by viewModel.lastUpdatedMs.collectAsStateWithLifecycle() + val haptics by viewModel.haptics.collectAsStateWithLifecycle() + val pauseBg by viewModel.pauseInBackground.collectAsStateWithLifecycle() + val peakCpu by viewModel.peakCpu.collectAsStateWithLifecycle() + val peakRam by viewModel.peakRam.collectAsStateWithLifecycle() + val peakNet by viewModel.peakNet.collectAsStateWithLifecycle() + val advancedMode by viewModel.advancedMode.collectAsStateWithLifecycle() + val elevatedStatus by viewModel.elevatedStatus.collectAsStateWithLifecycle() + val advancedSnap by viewModel.advancedSnapshot.collectAsStateWithLifecycle() + val avgCpu by viewModel.avgCpu.collectAsStateWithLifecycle() + val avgRam by viewModel.avgRam.collectAsStateWithLifecycle() + val elevatedProfile by viewModel.elevatedProfile.collectAsStateWithLifecycle() + val elevatedIntervalSec by viewModel.elevatedIntervalSecFlow.collectAsStateWithLifecycle() FernApp( snapshot = snap, cpuHistory = cpu, diff --git a/app/src/main/java/com/endroid/fern/data/Prefs.kt b/app/src/main/java/com/endroid/fern/data/Prefs.kt index 3fb50a0..d6fddae 100644 --- a/app/src/main/java/com/endroid/fern/data/Prefs.kt +++ b/app/src/main/java/com/endroid/fern/data/Prefs.kt @@ -12,133 +12,133 @@ class Prefs(context: Context) { ThemeMode.valueOf(p.getString("theme", ThemeMode.AUTO.name)!!) }.getOrDefault(ThemeMode.AUTO) set(v) { - p.edit().putString("theme", v.name).commit() + p.edit().putString("theme", v.name).apply() } /** ARGB seed for Material palette generation (default Fern green). */ var seedColorArgb: Int get() = p.getInt("seed_color", 0xFF1B7A3D.toInt()) set(v) { - p.edit().putInt("seed_color", v).commit() + p.edit().putInt("seed_color", v).apply() } var refreshMs: Int get() = p.getInt("refresh_ms", 1500).coerceIn(500, 10_000) set(v) { - p.edit().putInt("refresh_ms", v.coerceIn(500, 10_000)).commit() + p.edit().putInt("refresh_ms", v.coerceIn(500, 10_000)).apply() } var keepScreenOn: Boolean get() = p.getBoolean("keep_screen_on", false) set(v) { - p.edit().putBoolean("keep_screen_on", v).commit() + p.edit().putBoolean("keep_screen_on", v).apply() } var haptics: Boolean get() = p.getBoolean("haptics", true) set(v) { - p.edit().putBoolean("haptics", v).commit() + p.edit().putBoolean("haptics", v).apply() } var pauseInBackground: Boolean get() = p.getBoolean("pause_bg", true) set(v) { - p.edit().putBoolean("pause_bg", v).commit() + p.edit().putBoolean("pause_bg", v).apply() } var advancedMode: Boolean get() = p.getBoolean("advanced_mode", false) set(v) { - p.edit().putBoolean("advanced_mode", v).commit() + p.edit().putBoolean("advanced_mode", v).apply() } /** 0=Lite 1=Balanced 2=Full — elevated shell work intensity. */ var elevatedProfile: Int get() = p.getInt("elevated_profile", 1).coerceIn(0, 2) set(v) { - p.edit().putInt("elevated_profile", v.coerceIn(0, 2)).commit() + p.edit().putInt("elevated_profile", v.coerceIn(0, 2)).apply() } var alertRamPercent: Int get() = p.getInt("alert_ram", 0).coerceIn(0, 100) set(v) { - p.edit().putInt("alert_ram", v.coerceIn(0, 100)).commit() + p.edit().putInt("alert_ram", v.coerceIn(0, 100)).apply() } var elevatedIntervalSec: Int get() = p.getInt("elevated_iv_sec", 5).coerceIn(3, 20) set(v) { - p.edit().putInt("elevated_iv_sec", v.coerceIn(3, 20)).commit() + p.edit().putInt("elevated_iv_sec", v.coerceIn(3, 20)).apply() } var overlayEnabled: Boolean get() = p.getBoolean("overlay_enabled", false) set(v) { - p.edit().putBoolean("overlay_enabled", v).commit() + p.edit().putBoolean("overlay_enabled", v).apply() } var overlayWidthDp: Int get() = p.getInt("overlay_w_dp", 168).coerceIn(120, 320) set(v) { - p.edit().putInt("overlay_w_dp", v.coerceIn(120, 320)).commit() + p.edit().putInt("overlay_w_dp", v.coerceIn(120, 320)).apply() } var overlayHeightDp: Int get() = p.getInt("overlay_h_dp", 34).coerceIn(28, 56) set(v) { - p.edit().putInt("overlay_h_dp", v.coerceIn(28, 56)).commit() + p.edit().putInt("overlay_h_dp", v.coerceIn(28, 56)).apply() } var overlayOpacity: Float get() = p.getFloat("overlay_opacity", 0.92f).coerceIn(0.35f, 1f) set(v) { - p.edit().putFloat("overlay_opacity", v.coerceIn(0.35f, 1f)).commit() + p.edit().putFloat("overlay_opacity", v.coerceIn(0.35f, 1f)).apply() } /** Horizontal position 0–100 (% of screen width; 50 = center). */ var overlayXPercent: Int get() = p.getInt("overlay_x_pct", 50).coerceIn(0, 100) set(v) { - p.edit().putInt("overlay_x_pct", v.coerceIn(0, 100)).commit() + p.edit().putInt("overlay_x_pct", v.coerceIn(0, 100)).apply() } /** Vertical offset from top of screen in dp (0–120). */ var overlayYDp: Int get() = p.getInt("overlay_y_dp", 6).coerceIn(0, 120) set(v) { - p.edit().putInt("overlay_y_dp", v.coerceIn(0, 120)).commit() + p.edit().putInt("overlay_y_dp", v.coerceIn(0, 120)).apply() } /** Extra space between temp and RAM (dp), 0–48. */ var overlayGapDp: Int get() = p.getInt("overlay_gap_dp", 12).coerceIn(0, 48) set(v) { - p.edit().putInt("overlay_gap_dp", v.coerceIn(0, 48)).commit() + p.edit().putInt("overlay_gap_dp", v.coerceIn(0, 48)).apply() } /** When true: "Temp 37° · RAM 81%" instead of "37° · 81%". */ var overlayShowLabels: Boolean get() = p.getBoolean("overlay_labels", false) set(v) { - p.edit().putBoolean("overlay_labels", v).commit() + p.edit().putBoolean("overlay_labels", v).apply() } var overlayShowGpu: Boolean get() = p.getBoolean("overlay_show_gpu", true) set(v) { - p.edit().putBoolean("overlay_show_gpu", v).commit() + p.edit().putBoolean("overlay_show_gpu", v).apply() } var overlayShowRam: Boolean get() = p.getBoolean("overlay_show_ram", true) set(v) { - p.edit().putBoolean("overlay_show_ram", v).commit() + p.edit().putBoolean("overlay_show_ram", v).apply() } var overlayShowCpu: Boolean get() = p.getBoolean("overlay_show_cpu", true) set(v) { - p.edit().putBoolean("overlay_show_cpu", v).commit() + p.edit().putBoolean("overlay_show_cpu", v).apply() } /** 0 = off. Alert when CPU is at/above this %. */ @@ -152,21 +152,21 @@ class Prefs(context: Context) { var amoledDark: Boolean get() = p.getBoolean("amoled_dark", false) set(v) { - p.edit().putBoolean("amoled_dark", v).commit() + p.edit().putBoolean("amoled_dark", v).apply() } /** Tighter spacing on Home metric cards. */ var compactUi: Boolean get() = p.getBoolean("compact_ui", false) set(v) { - p.edit().putBoolean("compact_ui", v).commit() + p.edit().putBoolean("compact_ui", v).apply() } /** Accent chart glow on timeline. */ var chartGlow: Boolean get() = p.getBoolean("chart_glow", true) set(v) { - p.edit().putBoolean("chart_glow", v).commit() + p.edit().putBoolean("chart_glow", v).apply() } diff --git a/app/src/main/java/com/endroid/fern/monitor/AdvancedMetrics.kt b/app/src/main/java/com/endroid/fern/monitor/AdvancedMetrics.kt index ae16b8e..8bbf09f 100644 --- a/app/src/main/java/com/endroid/fern/monitor/AdvancedMetrics.kt +++ b/app/src/main/java/com/endroid/fern/monitor/AdvancedMetrics.kt @@ -290,16 +290,18 @@ class AdvancedMetrics(private val access: AdvancedAccess) { suspend fun forceStop(packageName: String, advancedEnabled: Boolean): Boolean { if (!access.isElevatedLive(advancedEnabled)) return false - if (packageName.isBlank() || packageName.contains(' ')) return false - if (access.forceStopPackage(packageName)) return true - val out = access.exec("am force-stop ${packageName.trim()}; echo FERN_STOPPED", 3_000) + val pkg = packageName.trim() + if (!MetricsParse.isValidPackageName(pkg)) return false + if (access.forceStopPackage(pkg)) return true + val out = access.exec("am force-stop $pkg; echo FERN_STOPPED", 3_000) return out != null && out.contains("FERN_STOPPED") } suspend fun clearAppCache(packageName: String, advancedEnabled: Boolean): Boolean { if (!access.isElevatedLive(advancedEnabled)) return false - if (packageName.isBlank() || packageName.contains(' ')) return false - val out = access.exec("pm clear --cache-only ${packageName.trim()} 2>/dev/null; echo FERN_CACHE", 4_000) + val pkg = packageName.trim() + if (!MetricsParse.isValidPackageName(pkg)) return false + val out = access.exec("pm clear --cache-only $pkg 2>/dev/null; echo FERN_CACHE", 4_000) return out != null && (out.contains("FERN_CACHE") || out.contains("Success")) } diff --git a/app/src/main/java/com/endroid/fern/monitor/MetricsParse.kt b/app/src/main/java/com/endroid/fern/monitor/MetricsParse.kt index 11b41c9..07056e0 100644 --- a/app/src/main/java/com/endroid/fern/monitor/MetricsParse.kt +++ b/app/src/main/java/com/endroid/fern/monitor/MetricsParse.kt @@ -5,6 +5,15 @@ package com.endroid.fern.monitor */ object MetricsParse { + private val PACKAGE_NAME = Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+$") + + /** + * True only for a well-formed Android package name (letters, digits, underscore, at least + * one dot, max 255 chars). Anything else must never reach a shell command line. + */ + fun isValidPackageName(name: String?): Boolean = + name != null && name.length <= 255 && PACKAGE_NAME.matches(name) + /** * Parse the aggregate `cpu ` line from /proc/stat. * @return idle (idle+iowait) to total jiffies, or null if not usable diff --git a/app/src/main/java/com/endroid/fern/monitor/SystemMetrics.kt b/app/src/main/java/com/endroid/fern/monitor/SystemMetrics.kt index 33f1f4a..84892b7 100644 --- a/app/src/main/java/com/endroid/fern/monitor/SystemMetrics.kt +++ b/app/src/main/java/com/endroid/fern/monitor/SystemMetrics.kt @@ -82,8 +82,27 @@ object SystemMetrics { @Volatile private var prevTotal: Long = -1 @Volatile private var prevNetBytes: Long = -1 @Volatile private var prevNetAt: Long = 0 - @Volatile private var coreMhzCacheAt: Long = 0 - @Volatile private var coreMhzCache: List = emptyList() + + private val CPU_DIR = Regex("cpu\\d+") + private val WHITESPACE = Regex("\\s+") + + /** After this many consecutive failed reads a /proc file is treated as blocked. */ + private const val BLOCK_AFTER_FAILS = 3 + /** How long a blocked /proc file is skipped before it is probed again. */ + private const val BLOCK_RETRY_MS = 60_000L + + @Volatile private var statFails = 0 + @Volatile private var statBlockedUntil = 0L + @Volatile private var loadFails = 0 + @Volatile private var loadBlockedUntil = 0L + + // Values that cannot change while the process lives are read once. + @Volatile private var cpuDirsCache: List? = null + private val cpuMaxKhz = java.util.concurrent.ConcurrentHashMap() + private val securityPatchCache: String by lazy { readSecurityPatch() } + private val kernelVersionCache: String by lazy { readKernelVersion() } + private val maxMhzCache: Int? by lazy { readMaxCpuMhz() } + @Volatile private var sensorCountCache = -1 fun capture(context: Context): SystemSnapshot { val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager @@ -104,8 +123,9 @@ object SystemMetrics { val battery = readBattery(context) val load = readLoadAvg() val cores = Runtime.getRuntime().availableProcessors().coerceAtLeast(1) - val (cpuPct, cpuOk) = readCpuPercentAccurate(cores, load) - val maxMhz = readMaxCpuMhz() + val freqs = readCurFreqsKhz() + val (cpuPct, cpuOk) = readCpuPercentAccurate(cores, load, freqs) + val maxMhz = maxMhzCache val net = readNetwork(context) val netKBps = readNetworkKBps() val uptime = SystemClock.elapsedRealtime() / 3_600_000f @@ -149,15 +169,16 @@ object SystemMetrics { batteryVoltageMv = battery.voltageMv, batteryCurrentUa = battery.currentUa, batteryTechnology = battery.technology, - securityPatch = readSecurityPatch(), - kernelVersion = readKernelVersion(), + securityPatch = securityPatchCache, + kernelVersion = kernelVersionCache, buildFingerprint = Build.FINGERPRINT ?: "?", displayWidthPx = display.widthPx, displayHeightPx = display.heightPx, displayDensityDpi = display.densityDpi, displayRefreshHz = display.refreshHz, - cpuCurMhz = readCpuCurMhz(), - cpuCoreMhz = readCpuCoreMhz(), + cpuCurMhz = if (freqs.isEmpty()) null + else (freqs.sumOf { it.second } / freqs.size / 1000L).toInt().coerceAtLeast(0), + cpuCoreMhz = freqs.map { (it.second / 1000L).toInt() }, cpuGovernor = readCpuGovernor(), freeRamMb = availRam / (1024 * 1024), localeTag = java.util.Locale.getDefault().toLanguageTag(), @@ -221,31 +242,31 @@ object SystemMetrics { private fun parseProcStatLine(line: String?): Pair? = MetricsParse.parseProcStatLine(line) - private fun readProcStat(): Pair? { - try { - parseProcStatLine(File("/proc/stat").bufferedReader().use { it.readLine() })?.let { return it } - } catch (_: Exception) { } - try { - RandomAccessFile("/proc/stat", "r").use { raf -> - parseProcStatLine(raf.readLine())?.let { return it } - } - } catch (_: Exception) { } + /** First line of [path], or null. Tries two read paths; both fail the same way when SELinux blocks us. */ + private fun readFirstLine(path: String): String? { try { - File("/proc/stat").inputStream().bufferedReader().use { br -> - parseProcStatLine(br.readLine())?.let { return it } - } + File(path).bufferedReader().use { it.readLine() }?.let { return it } } catch (_: Exception) { } try { - val proc = Runtime.getRuntime().exec(arrayOf("cat", "/proc/stat")) - try { - parseProcStatLine(proc.inputStream.bufferedReader().use { it.readLine() })?.let { return it } - } finally { - proc.destroy() - } + RandomAccessFile(path, "r").use { it.readLine() }?.let { return it } } catch (_: Exception) { } return null } + private fun readProcStat(): Pair? { + val now = SystemClock.elapsedRealtime() + if (now < statBlockedUntil) return null + val parsed = parseProcStatLine(readFirstLine("/proc/stat")) + if (parsed != null) { + statFails = 0 + } else if (++statFails >= BLOCK_AFTER_FAILS) { + // Blocked on this device/OS: stop hitting the filesystem every refresh. + statBlockedUntil = now + BLOCK_RETRY_MS + statFails = 0 + } + return parsed + } + private fun cpuFromLoad(cores: Int, load: FloatArray?): Pair { val load1 = load?.getOrNull(0) ?: return 0f to false val c = cores.coerceAtLeast(1) @@ -254,7 +275,11 @@ object SystemMetrics { return pct to false } - private fun readCpuPercentAccurate(cores: Int, load: FloatArray?): Pair { + private fun readCpuPercentAccurate( + cores: Int, + load: FloatArray?, + freqs: List> + ): Pair { // Prefer cross-tick /proc/stat delta (ViewModel samples every refresh interval). val nowStat = readProcStat() if (nowStat != null) { @@ -294,31 +319,60 @@ object SystemMetrics { // dumpsys cpuinfo (may need DUMP permission; still try) readCpuFromDumpsys()?.let { return it to true } // Clock scaling as activity proxy when tick counters are blocked (CPU-Z style fallback) - readCpuFromFreq()?.let { return it to false } + readCpuFromFreq(freqs)?.let { return it to false } return cpuFromLoad(cores, load) } - /** Rough activity from avg(cur/max) across cores — not true utilization but better than a stuck 0. */ - private fun readCpuFromFreq(): Float? { - return try { - val base = File("/sys/devices/system/cpu") - val dirs = base.listFiles()?.filter { it.name.matches(Regex("cpu\\d+")) }.orEmpty() - var sum = 0f - var n = 0 - for (dir in dirs) { - val curF = File(dir, "cpufreq/scaling_cur_freq") - val maxF = File(dir, "cpufreq/cpuinfo_max_freq") - if (!curF.canRead() || !maxF.canRead()) continue - val cur = curF.readText().trim().toFloatOrNull() ?: continue - val max = maxF.readText().trim().toFloatOrNull() ?: continue - if (max <= 0f) continue - sum += (cur / max * 100f).coerceIn(0f, 100f) - n++ - } - if (n == 0) null else (sum / n).coerceIn(0f, 100f) + /** Rough activity from avg(cur/max) across cores: not true utilization but better than a stuck 0. */ + private fun readCpuFromFreq(freqs: List>): Float? { + var sum = 0f + var n = 0 + for ((dir, cur) in freqs) { + val max = maxKhzFor(dir) + if (max <= 0L) continue + sum += (cur.toFloat() / max * 100f).coerceIn(0f, 100f) + n++ + } + return if (n == 0) null else (sum / n).coerceIn(0f, 100f) + } + + private fun readLongFile(f: File): Long? = try { + f.readText().trim().toLongOrNull() + } catch (_: Exception) { + null + } + + /** cpuN directories, sorted by core index. The topology is static, so it is listed once. */ + private fun cpuDirs(): List { + cpuDirsCache?.let { return it } + val dirs = try { + File("/sys/devices/system/cpu").listFiles() + ?.filter { CPU_DIR.matches(it.name) } + ?.sortedBy { it.name.removePrefix("cpu").toIntOrNull() ?: 0 } + .orEmpty() } catch (_: Exception) { - null + emptyList() + } + if (dirs.isNotEmpty()) { + cpuDirsCache = dirs + return dirs } + return listOf(File("/sys/devices/system/cpu/cpu0")) + } + + private fun maxKhzFor(dir: File): Long = + cpuMaxKhz[dir.name] ?: (readLongFile(File(dir, "cpufreq/cpuinfo_max_freq")) ?: 0L).also { + if (it > 0L) cpuMaxKhz[dir.name] = it + } + + /** Current frequency (kHz) of every readable core, in core order. One sysfs pass per capture. */ + private fun readCurFreqsKhz(): List> { + val out = ArrayList>(8) + for (dir in cpuDirs()) { + val khz = readLongFile(File(dir, "cpufreq/scaling_cur_freq")) ?: continue + if (khz > 0L) out.add(dir to khz) + } + return out } fun readCpuFromDumpsys(): Float? { @@ -328,97 +382,27 @@ object SystemMetrics { } private fun readLoadAvg(): FloatArray? { - fun parse(line: String?): FloatArray? { - if (line.isNullOrBlank()) return null - val p = line.trim().split(Regex("\\s+")) - if (p.size < 3) return null - val a = p[0].toFloatOrNull() ?: return null - val b = p[1].toFloatOrNull() ?: return null - val c = p[2].toFloatOrNull() ?: return null - return floatArrayOf(a, b, c) + val now = SystemClock.elapsedRealtime() + if (now < loadBlockedUntil) return null + val p = readFirstLine("/proc/loadavg")?.trim()?.split(WHITESPACE) + val parsed = if (p != null && p.size >= 3) { + val a = p[0].toFloatOrNull() + val b = p[1].toFloatOrNull() + val c = p[2].toFloatOrNull() + if (a != null && b != null && c != null) floatArrayOf(a, b, c) else null + } else null + if (parsed != null) { + loadFails = 0 + } else if (++loadFails >= BLOCK_AFTER_FAILS) { + loadBlockedUntil = now + BLOCK_RETRY_MS + loadFails = 0 } - try { - parse(File("/proc/loadavg").bufferedReader().use { it.readLine() })?.let { return it } - } catch (_: Exception) { } - try { - RandomAccessFile("/proc/loadavg", "r").use { raf -> - parse(raf.readLine())?.let { return it } - } - } catch (_: Exception) { } - try { - val proc = Runtime.getRuntime().exec(arrayOf("cat", "/proc/loadavg")) - try { - parse(proc.inputStream.bufferedReader().use { it.readLine() })?.let { return it } - } finally { - proc.destroy() - } - } catch (_: Exception) { } - return null + return parsed } private fun readMaxCpuMhz(): Int? { - val freqs = mutableListOf() - try { - val base = File("/sys/devices/system/cpu") - val dirs = base.listFiles()?.filter { it.name.matches(Regex("cpu\\d+")) }.orEmpty() - for (dir in dirs) { - val f = File(dir, "cpufreq/cpuinfo_max_freq") - if (!f.canRead()) continue - val khz = f.readText().trim().toLongOrNull() ?: continue - if (khz > 0L) freqs.add(khz) - } - } catch (_: Exception) { } - if (freqs.isNotEmpty()) return (freqs.maxOrNull()!! / 1000L).toInt() - return try { - val path = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" - val khz = File(path).readText().trim().toLongOrNull() ?: return null - (khz / 1000).toInt() - } catch (_: Exception) { - null - } - } - - private fun readCpuCurMhz(): Int? { - // Average scaling_cur_freq across online cores (sysfs often works when /proc/stat does not). - val freqs = mutableListOf() - try { - val base = File("/sys/devices/system/cpu") - val dirs = base.listFiles()?.filter { it.name.matches(Regex("cpu\\d+")) }.orEmpty() - for (dir in dirs) { - val f = File(dir, "cpufreq/scaling_cur_freq") - if (!f.canRead()) continue - val khz = f.readText().trim().toLongOrNull() ?: continue - if (khz > 0L) freqs.add(khz) - } - } catch (_: Exception) { } - if (freqs.isNotEmpty()) { - return (freqs.average() / 1000.0).toInt().coerceAtLeast(0) - } - return try { - val path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq" - val khz = File(path).readText().trim().toLongOrNull() ?: return null - (khz / 1000).toInt() - } catch (_: Exception) { - null - } - } - - - private fun readCpuCoreMhz(): List { - val out = mutableListOf() - try { - val base = File("/sys/devices/system/cpu") - val dirs = base.listFiles()?.filter { it.name.matches(Regex("cpu\\d+")) }?.sortedBy { - it.name.removePrefix("cpu").toIntOrNull() ?: 0 - }.orEmpty() - for (dir in dirs) { - val f = File(dir, "cpufreq/scaling_cur_freq") - if (!f.canRead()) continue - val khz = f.readText().trim().toLongOrNull() ?: continue - if (khz > 0L) out.add((khz / 1000L).toInt()) - } - } catch (_: Exception) { } - return out + val max = cpuDirs().maxOfOrNull { maxKhzFor(it) } ?: 0L + return if (max > 0L) (max / 1000L).toInt() else null } private fun readCpuGovernor(): String { @@ -513,9 +497,10 @@ object SystemMetrics { private fun readSensorCount(context: Context): Int { + if (sensorCountCache >= 0) return sensorCountCache return try { val sm = context.getSystemService(Context.SENSOR_SERVICE) as? android.hardware.SensorManager - sm?.getSensorList(android.hardware.Sensor.TYPE_ALL)?.size ?: 0 + (sm?.getSensorList(android.hardware.Sensor.TYPE_ALL)?.size ?: 0).also { sensorCountCache = it } } catch (_: Exception) { 0 } diff --git a/app/src/main/java/com/endroid/fern/overlay/OverlayService.kt b/app/src/main/java/com/endroid/fern/overlay/OverlayService.kt index 09cdb24..6ef6b11 100644 --- a/app/src/main/java/com/endroid/fern/overlay/OverlayService.kt +++ b/app/src/main/java/com/endroid/fern/overlay/OverlayService.kt @@ -4,7 +4,12 @@ import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent +import android.app.ActivityManager import android.app.Service +import android.content.BroadcastReceiver +import android.content.IntentFilter +import android.os.BatteryManager +import android.content.res.Configuration import android.content.Context import android.content.Intent import android.content.pm.ServiceInfo @@ -26,7 +31,6 @@ import androidx.core.app.NotificationCompat import com.endroid.fern.MainActivity import com.endroid.fern.R import com.endroid.fern.data.Prefs -import com.endroid.fern.monitor.SystemMetrics import kotlin.math.roundToInt /** @@ -43,6 +47,10 @@ class OverlayService : Service() { private val handler = Handler(Looper.getMainLooper()) private var params: WindowManager.LayoutParams? = null + private var ticking = false + private var screenReceiver: BroadcastReceiver? = null + private val memInfo = ActivityManager.MemoryInfo() + private val tick = object : Runnable { override fun run() { refreshStats() @@ -51,6 +59,34 @@ class OverlayService : Service() { } } + private fun startTicking() { + if (ticking) return + ticking = true + handler.post(tick) + } + + private fun stopTicking() { + ticking = false + handler.removeCallbacks(tick) + } + + /** No point refreshing a pill nobody can see: pause while the screen is off. */ + private fun registerScreenReceiver() { + val r = object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + when (intent?.action) { + Intent.ACTION_SCREEN_OFF -> stopTicking() + Intent.ACTION_SCREEN_ON -> startTicking() + } + } + } + screenReceiver = r + registerReceiver(r, IntentFilter().apply { + addAction(Intent.ACTION_SCREEN_OFF) + addAction(Intent.ACTION_SCREEN_ON) + }) + } + override fun onBind(intent: Intent?): IBinder? = null override fun onCreate() { @@ -59,7 +95,14 @@ class OverlayService : Service() { windowManager = getSystemService(WINDOW_SERVICE) as WindowManager startAsForegroundQuiet() attachIsland() - handler.post(tick) + registerScreenReceiver() + startTicking() + } + + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + // Rotation / fold changes the screen width the X position is computed from. + applyLayoutFromPrefs() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { @@ -74,7 +117,10 @@ class OverlayService : Service() { } override fun onDestroy() { + stopTicking() handler.removeCallbacksAndMessages(null) + screenReceiver?.let { runCatching { unregisterReceiver(it) } } + screenReceiver = null detachIsland() prefs.overlayEnabled = false super.onDestroy() @@ -278,13 +324,10 @@ class OverlayService : Service() { } private fun refreshStats() { - val snap = try { - SystemMetrics.capture(this) - } catch (_: Exception) { - null - } - val temp = snap?.batteryTempC - val ram = snap?.ramPercent + // Only two numbers are shown, so read only those (a full SystemMetrics.capture + // touches ~50 files and ran on the main thread every tick). + val temp = readBatteryTempC() + val ram = readRamPercent() val labels = prefs.overlayShowLabels val tempStr = when { temp == null -> if (labels) "Temp —" else "—" @@ -303,6 +346,24 @@ class OverlayService : Service() { island?.contentDescription = "$tempStr, $ramStr" } + private fun readBatteryTempC(): Float? = try { + val t = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) + ?.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, Int.MIN_VALUE) + if (t == null || t == Int.MIN_VALUE) null else t / 10f + } catch (_: Exception) { + null + } + + private fun readRamPercent(): Float? = try { + val am = getSystemService(ACTIVITY_SERVICE) as ActivityManager + am.getMemoryInfo(memInfo) + if (memInfo.totalMem > 0L) { + ((memInfo.totalMem - memInfo.availMem).coerceAtLeast(0L).toFloat() / memInfo.totalMem * 100f) + } else null + } catch (_: Exception) { + null + } + companion object { const val NOTIF_ID = 7701 const val ACTION_STOP = "com.endroid.fern.overlay.STOP" diff --git a/app/src/test/java/com/endroid/fern/SystemMetricsParseTest.kt b/app/src/test/java/com/endroid/fern/SystemMetricsParseTest.kt index 8586d43..a17f08b 100644 --- a/app/src/test/java/com/endroid/fern/SystemMetricsParseTest.kt +++ b/app/src/test/java/com/endroid/fern/SystemMetricsParseTest.kt @@ -167,4 +167,21 @@ class SystemMetricsParseTest { assertTrue(csv.contains("0,1000,")) assertTrue(csv.contains("1,1500,")) } + + @Test + fun packageNameValidationAcceptsRealNames() { + assertTrue(MetricsParse.isValidPackageName("com.android.chrome")) + assertTrue(MetricsParse.isValidPackageName("com.endroid.fern.debug")) + assertTrue(MetricsParse.isValidPackageName("org.example.app_2")) + } + + @Test + fun packageNameValidationRejectsShellMetacharacters() { + val bad = listOf( + null, "", "chrome", "com.a;reboot", "com.a && id", "com.a|id", "com.a\nid", + "\$(id).app", "com.a`id`", "com.a b", "com.a>x", "-f.com.a", ".com.a", "com.a.", + "com..a", "1com.a", "a".repeat(300) + ".b" + ) + for (b in bad) assertTrue("accepted: $b", !MetricsParse.isValidPackageName(b)) + } }