diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 00000000..b7191298 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,77 @@ +name: Bug report +description: Something does not work as expected +labels: [bug] +body: + - type: markdown + attributes: + value: | + Thanks for the report. Please check first whether the issue already exists. + - type: input + id: version + attributes: + label: DiskUsage version + description: Shown in the About dialog (`⋮ → About`) or in the release file name. + placeholder: "5.0.0" + validations: + required: true + - type: input + id: android + attributes: + label: Android version + description: Android version and, if relevant, the ROM (One UI, LineageOS, …). + placeholder: "Android 16 (API 36), LineageOS 23" + validations: + required: true + - type: input + id: device + attributes: + label: Device + placeholder: "Pixel 8" + validations: + required: true + - type: dropdown + id: permissions + attributes: + label: Which permissions are granted? + multiple: true + options: + - All files access + - Usage access + - Root + - None + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce + placeholder: | + 1. Open DiskUsage + 2. Select "Storage card" + 3. ... + validations: + required: true + - type: textarea + id: expected + attributes: + label: Expected behaviour + validations: + required: true + - type: textarea + id: actual + attributes: + label: Actual behaviour + validations: + required: true + - type: textarea + id: logs + attributes: + label: Logs + description: | + `adb logcat -d | grep -i diskusage` (or a crash report) helps a lot. + render: shell + - type: textarea + id: additional + attributes: + label: Additional context + description: Screenshots, whether the storage is a removable SD card or USB drive, … diff --git a/.github/workflows/build-apk.yml b/.github/workflows/build-apk.yml deleted file mode 100644 index 3b29eb2a..00000000 --- a/.github/workflows/build-apk.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Build APK - -on: - push: - workflow_dispatch: - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Set up JDK 17 - uses: actions/setup-java@v4 - with: - distribution: 'temurin' - java-version: '17' - - - name: Set up Android SDK - uses: android-actions/setup-android@v3 - - - name: Grant execute permission for gradlew - run: chmod +x gradlew - - - name: Install NDK (needed for the native scan.c build) - run: sdkmanager "ndk;25.2.9519653" - - - name: Build debug APK - run: ./gradlew assembleDebug --stacktrace - - - name: Upload APK - uses: actions/upload-artifact@v4 - with: - name: diskusage-debug-apk - path: app/build/outputs/apk/debug/*.apk diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..dea4e1ef --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,93 @@ +name: CI + +on: + push: + pull_request: + workflow_dispatch: + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + JAVA_VERSION: '17' + GRADLE_OPTS: >- + -Dorg.gradle.jvmargs=-Xmx4g + -Dorg.gradle.daemon=false + -Dkotlin.incremental=false + +jobs: + build: + name: Build, test and lint + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - name: Checkout + uses: actions/checkout@v7 + + - name: Set up JDK + uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: ${{ env.JAVA_VERSION }} + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v6 + with: + cache-read-only: ${{ github.event_name == 'pull_request' }} + + - name: Install Android SDK components + uses: android-actions/setup-android@v4 + with: + packages: >- + platforms;android-37.0 + build-tools;36.0.0 + ndk;28.2.13676358 + + - name: Unit tests + run: ./gradlew testDebugUnitTest --stacktrace + + - name: Assemble debug APK + run: ./gradlew assembleDebug --stacktrace + + - name: Lint + run: ./gradlew lintDebug --stacktrace + + - name: Upload debug APK + uses: actions/upload-artifact@v7 + with: + name: diskusage-debug-${{ github.sha }} + path: app/build/outputs/apk/debug/*.apk + retention-days: 14 + if-no-files-found: error + + - name: Upload reports + if: always() + uses: actions/upload-artifact@v7 + with: + name: reports-${{ github.sha }} + path: | + app/build/reports/tests/** + app/build/reports/lint-results-*.html + retention-days: 14 + if-no-files-found: ignore + + - name: Verify 16 KB page size support of native libraries + run: | + set -euo pipefail + apk=$(ls app/build/outputs/apk/debug/*.apk | head -n1) + mkdir -p /tmp/apk-libs + unzip -q -o "$apk" 'lib/*' -d /tmp/apk-libs + readelf="$ANDROID_HOME/ndk/28.2.13676358/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-readelf" + for so in /tmp/apk-libs/lib/arm64-v8a/*.so /tmp/apk-libs/lib/x86_64/*.so; do + [ -e "$so" ] || continue + align=$("$readelf" -l "$so" | awk '/LOAD/ {print $NF}' | sort -u | tr '\n' ' ') + echo "$(basename "$so"): $align" + case "$align" in + *0x4000*) ;; + *) echo "::error::$so is not 16 KB aligned"; exit 1 ;; + esac + done diff --git a/.gitignore b/.gitignore index 35c70283..5cc55e99 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,7 @@ /local.properties /DiskUsage.iml /app/app.iml +/keystore.properties +*.jks +*.keystore +/dist diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..4c0bdce2 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,92 @@ +# Changelog + +All notable changes to this project are documented here. The format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), versions follow +[Semantic Versioning](https://semver.org/). + +## [Unreleased] + +## [5.0.1] - 2026-11-18 + +### Fixed + +* **"Show" on a folder** now offers the system Files app instead of a random + selection of apps. The external storage document URI is used (Android has no + standard "open this folder" intent) and the read-grant flag is no longer added + for URIs the app does not own — that flag made the system throw a + `SecurityException`, which silently fell through to a useless chooser. + Folders that cannot be opened now offer to copy the path. +* **Crash when app data was just cleared** (`NullPointerException` in the app + list): `getExternalCacheDir()`/`getExternalFilesDir()` can return `null` + (MIUI/HyperOS, full storage), which aborted the whole application list. +* **Scan progress stuck at 0 %**: the native tree walker buffered the entire + result before handing it over. It now streams records while walking, so the + progress bar and the current path update live and memory stays flat. +* **Usage access shown as denied although the toggle was enabled**: several + ROMs keep the app-op at "default" after the user grants it. The state is now + verified against `UsageStatsManager` and no longer blocks startup; it is + shown in *menu → Permissions* together with "All files access". +* **"Internal storage" was labelled "SD card"** in German (and "Storage card" in + English) although it is the primary volume. +* Progress dialog layout: the percentage was printed on top of the path. +* **Back button left the user in a loop**: with predictive back (Android 13+) + `KEYCODE_BACK` no longer reached the graph view, so the activity fell back to + a plain `finish()` and surfaced the volume chooser again — hardware back and + the navigation bar behaved differently. Back is now handled through + `OnBackPressedDispatcher`: on a single-volume device it leaves the app (task + retained, `alwaysRetainTaskState`), on multi-volume devices it returns to the + chooser. Cancelling the scan or the permission dialog now also leaves the app + instead of reopening the chooser. + +## [5.0.0] - 2026-11-18 + +Complete modernization of the Android build and the app itself. + +### Changed + +* Build toolchain: AGP 9.5.1, Gradle 9.9.1, built-in Kotlin, JDK 17, version + catalog, R8 with resource shrinking, configuration cache. +* `compileSdk`/`targetSdk` 37 (Android 17), `minSdk` 24 (Android 7.0). +* NDK r28c, native scanner rebuilt for all four ABIs with 16 KB page-size + alignment. +* UI migrated to AppCompat activities with real toolbars, DayNight theme and + edge-to-edge insets (required from Android 15/16 on). +* Volume discovery uses `StorageManager.getStorageVolumes()`; SD cards and USB + drives are listed with their user-visible description. +* App storage list is built from the package manager instead of + `UsageStatsManager`; cache sizes are reported again. +* Delete confirmation lists content on a worker thread instead of the UI thread. +* `PermissionRequestActivity` re-checks permissions in `onResume` and only + requests what the running Android version needs. +* Timestamps and version information come from `version.properties`. + +### Added + +* Automatic GitHub releases (tag + APK + SHA256) and a daily nightly prerelease. +* CI with unit tests, lint, debug APK artifact and a 16 KB page-size check. +* F-Droid metadata (`fastlane/`), icon, feature graphic, screenshots and + changelogs in English and German; submission guide in `docs/fdroid`. +* Adaptive, round and monochrome (themed) launcher icons, TV banner and leanback + launcher entry, per-app language configuration. +* Used/free space is shown with the occupied percentage. +* Double tap opens files and folders. +* Unit tests for volume path handling. + +### Fixed + +* The native scanner never worked on modern Android: the shared library was + executed as a child process (segfault), the protocol had a stale leading NUL + byte and the build was missing the JNI entry point. It now runs in-process via + JNI, so scanning is fast again; failures still fall back to the Java scanner + (`Error: no more data`, `Cannot run program …libscan.so`). +* "No viewer found" and wrong MIME types when opening files; content URIs now + carry explicit read grants. +* Scan worker could leave the progress dialog on screen forever. +* Missing internal storage / SD card / USB volumes in the chooser. +* Apps without recent usage statistics disappeared from the app list. +* NPE when the option menu updated without a selection. +* Automatic selection when only one volume is available. + +[Unreleased]: https://github.com/bartman081523/diskusage/compare/v5.0.1...HEAD +[5.0.1]: https://github.com/bartman081523/diskusage/releases/tag/v5.0.1 +[5.0.0]: https://github.com/bartman081523/diskusage/releases/tag/v5.0.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..990a4fd2 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,68 @@ +# Contributing + +Thanks for helping with DiskUsage. + +## Before you start + +* The app targets Android 17 (API 37) and supports Android 7.0 (API 24) and + newer. +* Please keep changes focused. A bug fix should not contain unrelated + refactoring. +* Java and Kotlin are both used. New UI/data code should be Kotlin; the scanner + and renderer cores stay Java (they are performance critical and use a lot of + bit twiddling). + +## Build + +```bash +export JAVA_HOME=/path/to/jdk-17 +export ANDROID_HOME=$HOME/Android/Sdk +./gradlew assembleDebug testDebugUnitTest lintDebug +``` + +Required SDK components: + +* `platforms;android-37.0` +* `build-tools;36.0.0` +* `ndk;28.2.13676358` + +## Pull requests + +1. Fork the repository and create a topic branch. +2. Make sure `./gradlew testDebugUnitTest lintDebug assembleDebug` passes. +3. Update `CHANGELOG.md` under `## [Unreleased]` for user-visible changes. +4. Describe *what* changes and *why*; mention related issue numbers. +5. Do not add gradle wrappers, binaries or generated files. + +## Translations + +Translations live in `app/src/main/res/values-/strings.xml`. Adding a +locale additionally requires: + +* an entry in `app/src/main/res/xml/locales_config.xml`, +* a `fastlane/metadata/android//` folder (title, descriptions, + changelog) if store metadata should be translated. + +## Commit messages + +Conventional Commits are appreciated as they feed the release notes: + +``` +fix: detect USB volumes on Android 14 +feat: show the occupied percentage +docs: explain the F-Droid submission +``` + +## Reporting bugs + +Use the GitHub issue template. A useful report contains: + +* Android version and device/ROM, +* whether "All files access" and "Usage access" are granted, +* steps to reproduce, expected and actual behaviour, +* a logcat excerpt (`adb logcat | grep -i diskusage`) for crashes. + +## License + +By contributing you agree that your changes are licensed under the GNU General +Public License version 2 or later, like the rest of the project. diff --git a/README.md b/README.md index cf444243..bb2ef81b 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,116 @@ -DiskUsage -========= +# DiskUsage -For a better maintained version of this project have a look at: -https://github.com/WhiredPlanck/diskusage +Find out what is eating your storage — and delete it. -DiskUsage app for Android +[![CI](https://github.com/bartman081523/diskusage/actions/workflows/ci.yml/badge.svg)](https://github.com/bartman081523/diskusage/actions/workflows/ci.yml) +[![Release](https://github.com/bartman081523/diskusage/actions/workflows/release.yml/badge.svg)](https://github.com/bartman081523/diskusage/actions/workflows/release.yml) +[![License: GPL-2.0-or-later](https://img.shields.io/badge/license-GPL--2.0--or--later-blue.svg)](COPYING.txt) -DiskUsage provides a way to find files and directories on storage card which consumes a lot of space.
-It displays diagram on which directories are displayed proportional to their size, also a few levels of subdirectories are displayed. Users are allowed to zoom in to look at specific directory content.
-Purpose of the program is to provide a way to find and cleanup spacehogs on storage card. It is not general purpose file manager.
+DiskUsage is an Android storage analyser. Instead of a plain file list it draws a +map of your storage: every directory is a rectangle whose area is proportional to +the space it occupies, and several levels of subdirectories are shown at once. +Zoom into a region to see what is inside, then delete the big blocks to free up +space. -Screenshot for an ancient version:
- +

+ Storage overview + Directory graph +

-YouTube video: -https://www.youtube.com/watch?v=TIiCQfWdtVg +## Features + +* Visual map of internal storage, SD cards and USB drives +* Per-application breakdown into code, data and cache sizes +* Used / free space including the occupied percentage +* Search across the scanned tree +* Delete whole directories with a confirmation screen that lists the content +* Optional root support for any mounted file system +* Dark mode, adaptive and themed launcher icons, per-app language selection +* No ads, no tracking, no network permission + +## Requirements + +* Android 7.0 (API 24) or newer +* Android 17 (API 37) is the target SDK, so the app runs with the latest + platform behaviour (edge-to-edge, 16 KB page sizes) + +## Permissions + +| Permission | Why | +|---|---| +| `MANAGE_EXTERNAL_STORAGE` (Android 11+) | Analysing the storage requires reading every directory. Without it only the app's own files are visible. | +| `READ/WRITE_EXTERNAL_STORAGE` (≤ Android 12) | Same purpose on older releases. | +| `PACKAGE_USAGE_STATS` (optional) | Exact per-app data/cache sizes via `StorageStatsManager`. The app still works without it, but only reports APK sizes. | +| `QUERY_ALL_PACKAGES` | Listing installed applications. | + +No internet permission is requested, and the app contains no advertising or +analytics code. + +## Install + +* **F-Droid** — metadata is prepared in [`fastlane/metadata`](fastlane/metadata); + submission is described in [docs/fdroid](docs/fdroid/README.md). +* **GitHub Releases** — every release contains a signed APK and `SHA256SUMS.txt`. + See the [releases page](https://github.com/bartman081523/diskusage/releases). +* **Nightly builds** — the [nightly prerelease](https://github.com/bartman081523/diskusage/releases/tag/nightly) + is rebuilt every day from `main`. It is debug-signed, don't mix it with a + release installation. + +## Build + +```bash +# JDK 17+, Android SDK with platform 37.0, build-tools 36.0.0 and NDK r28c +export ANDROID_HOME=$HOME/Android/Sdk +./gradlew assembleDebug # app/build/outputs/apk/debug/ +./gradlew testDebugUnitTest # JVM unit tests +./gradlew lintDebug # Android Lint +./gradlew assembleRelease # unsigned release APK unless a keystore is configured +``` + +Local release builds read `keystore.properties` from the repository root: + +```properties +storeFile=/absolute/path/to/release.jks +storePassword=… +keyAlias=… +keyPassword=… +``` + +The file is git-ignored. CI uses `RELEASE_KEYSTORE_BASE64` plus +`RELEASE_KEYSTORE_PASSWORD`, `RELEASE_KEY_ALIAS` and `RELEASE_KEY_PASSWORD` +secrets instead; see [docs/RELEASING.md](docs/RELEASING.md). + +## Project layout + +| Path | Contents | +|---|---| +| `app/src/main/java/.../core` | Native (C) scanner and the Java fallback scanner | +| `app/src/main/java/.../datasource` | Storage access abstraction (files, package stats) | +| `app/src/main/java/.../filesystem` | Volume discovery, app loader, deletion | +| `app/src/main/java/.../opengl`, `ui` | Rendering threads and activities | +| `app/src/main/jni` | `libscan.so`, the `ndk-build` tree walker, called through JNI | +| `fastlane/metadata` | Store/F-Droid metadata (icon, screenshots, descriptions) | +| `docs` | Release process, F-Droid submission, issue triage | + +## Versioning + +`version.properties` is the single source of truth. `versionCode` is derived from +the semantic version (`5.1.2` → `50102`). Tags are `v`. + +```bash +./scripts/bump-version.sh patch # 5.0.0 -> 5.0.1 +``` + +## Contributing + +Bug reports and pull requests are welcome. Please read +[CONTRIBUTING.md](CONTRIBUTING.md) first. + +## License + +DiskUsage is free software, licensed under the GNU General Public License +version 2 or later. See [COPYING.txt](COPYING.txt). + +The project started as [IvanVolosyuk/diskusage](https://github.com/IvanVolosyuk/diskusage); +this repository continues it with a modern build toolchain and current Android +support. diff --git a/app/build.gradle b/app/build.gradle index de2438d3..b59ee742 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,63 +1,155 @@ -apply plugin: 'com.android.application' -apply plugin: 'kotlin-android' +import java.util.Properties + +plugins { + alias(libs.plugins.android.application) +} + +// Single source of truth for the app version. CI overrides these values with +// -PversionName=... / -PversionCode=... when building a tagged release. +def versionPropsFile = rootProject.file("version.properties") +def versionProps = new Properties() +if (versionPropsFile.exists()) { + versionPropsFile.withInputStream { versionProps.load(it) } +} +def resolvedVersionName = (project.findProperty("versionName") + ?: versionProps.getProperty("versionName") + ?: "0.0.0").toString() +def resolvedVersionCode = (project.findProperty("versionCode") + ?: versionProps.getProperty("versionCode") + ?: "1").toString().toInteger() + android { - namespace 'com.google.android.diskusage' - compileSdk 34 - buildToolsVersion "34.0.0" - ndkVersion "25.2.9519653" + namespace = "com.google.android.diskusage" + compileSdk = 37 + ndkVersion = "28.2.13676358" defaultConfig { - applicationId "com.google.android.diskusage" - targetSdk 33 - minSdk 21 + applicationId = "com.google.android.diskusage" + minSdk = 24 + targetSdk = 37 + versionCode = resolvedVersionCode + versionName = resolvedVersionName } + buildFeatures { - viewBinding true - buildConfig true + buildConfig = true + viewBinding = true + // AGP 9 disables resValues by default; the debug build overrides app_name. + resValues = true } + compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 - } - kotlinOptions { - jvmTarget = "1.8" - } - sourceSets { - main { - java { - srcDir 'src/main/java' - } - } + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 } buildTypes { + debug { + applicationIdSuffix = ".debug" + versionNameSuffix = "-debug" + // Distinct label so both builds can be told apart in the launcher. + resValue "string", "app_name", "DiskUsage Debug" + } release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' + minifyEnabled = true + shrinkResources = true + proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" } } + + packaging { + jniLibs { + // Libraries are loaded via System.loadLibrary(); keeping them + // uncompressed and page aligned is what 16 KB devices expect. + useLegacyPackaging = false + } + resources { + excludes += ["META-INF/*.kotlin_module", "META-INF/LICENSE*", "META-INF/NOTICE*"] + } + } + + androidResources { + generateLocaleConfig = false + } + + lint { + abortOnError = false + checkReleaseBuilds = false + } + externalNativeBuild { ndkBuild { - path file('src/main/jni/Android.mk') + path = file("src/main/jni/Android.mk") + } + } +} + +// Optional release signing, driven either by keystore.properties (local) or by +// environment variables (CI secrets). +def keystorePropertiesFile = rootProject.file("keystore.properties") +def envKeystoreFile = System.getenv("RELEASE_KEYSTORE_FILE") +def hasEnvKeystore = envKeystoreFile != null && !envKeystoreFile.trim().isEmpty() +if (keystorePropertiesFile.exists() || hasEnvKeystore) { + def props = new Properties() + if (keystorePropertiesFile.exists()) { + keystorePropertiesFile.withInputStream { props.load(it) } + } + android { + signingConfigs { + release { + storeFile = file(hasEnvKeystore ? envKeystoreFile : props.getProperty("storeFile")) + storePassword = System.getenv("RELEASE_KEYSTORE_PASSWORD") + ?: props.getProperty("storePassword") + keyAlias = System.getenv("RELEASE_KEY_ALIAS") + ?: props.getProperty("keyAlias") + keyPassword = System.getenv("RELEASE_KEY_PASSWORD") + ?: props.getProperty("keyPassword") + } + } + buildTypes { + release { + signingConfig = signingConfigs.release + } } } } -android.applicationVariants.all { variant -> - variant.outputs.all { - outputFileName = "diskusage-v${variant.versionName}-${variant.name}.apk" +// Without a release keystore the APK stays unsigned (required for F-Droid and +// reproducible builds). CI sets ALLOW_DEBUG_SIGNING=true so that automatic +// releases in forks without secrets are still installable. +if (!keystorePropertiesFile.exists() && !hasEnvKeystore + && System.getenv("ALLOW_DEBUG_SIGNING") == "true") { + android { + buildTypes { + release { + signingConfig = signingConfigs.debug + } + } } } dependencies { - // implementation files('src/main/extra/system.jar') - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - implementation 'androidx.core:core-ktx:1.12.0' - implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3' - implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3' - implementation 'me.zhanghai.android.appiconloader:appiconloader:1.5.0' - implementation "com.louiscad.splitties:splitties-toast:$splitties_version" - implementation "com.louiscad.splitties:splitties-resources:$splitties_version" - - testImplementation 'junit:junit:4.13.2' + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.appcompat) + implementation(libs.androidx.activity.ktx) + implementation(libs.androidx.constraintlayout) + implementation(libs.androidx.recyclerview) + implementation(libs.androidx.lifecycle.viewmodel.ktx) + implementation(libs.androidx.preference) + implementation(libs.kotlinx.coroutines.android) + implementation(libs.timber) + implementation(libs.appiconloader) + implementation(libs.splitties.toast) + implementation(libs.splitties.resources) + + testImplementation(libs.junit) +} + +androidComponents { + onVariants(selector().all()) { variant -> + variant.outputs.each { output -> + // Public variant API, no AGP internals. + output.outputFileName.set("diskusage-${variant.name}-${resolvedVersionName}.apk") + } + } } diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 00000000..09f52896 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,17 @@ +# Keep the Timber log calls but make sure no logging remains in release builds. +-assumenosideeffects class timber.log.Timber { + public static *** d(...); + public static *** v(...); + public static *** i(...); +} + +# The application class is referenced from the manifest. +-keep class com.google.android.diskusage.DiskUsageApplication { *; } + +# Keep the AIDL stub used for package size lookups on older platform versions. +-keep class com.google.android.diskusage.datasource.AppStatsCallback { *; } + +# Called from native code (JNI looks the method up by name). +-keep class com.google.android.diskusage.datasource.fast.NativeScannerStream$NativeSink { + void onData(byte[]); +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index b94bf9b2..2215e329 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,45 +1,109 @@ - - - - - - - - - - + xmlns:tools="http://schemas.android.com/tools" + android:installLocation="auto"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - + + + + + + + + + + android:resource="@xml/provider_paths" /> - - + + diff --git a/app/src/main/aidl/android/content/pm/IPackageStatsObserver.aidl b/app/src/main/aidl/android/content/pm/IPackageStatsObserver.aidl deleted file mode 100644 index 22077719..00000000 --- a/app/src/main/aidl/android/content/pm/IPackageStatsObserver.aidl +++ /dev/null @@ -1,31 +0,0 @@ -// https://github.com/aosp-mirror/platform_frameworks_base/raw/master/core/java/android/content/pm/IPackageStatsObserver.aidl -/* -** -** Copyright 2007, The Android Open Source Project -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -*/ - -package android.content.pm; - -import android.content.pm.PackageStats; -/** - * API for package data change related callbacks from the Package Manager. - * Some usage scenarios include deletion of cache directory, generate - * statistics related to code, data, cache usage(TODO) - * {@hide} - */ -interface IPackageStatsObserver { - - void onGetStatsCompleted(in PackageStats pStats, boolean succeeded); -} diff --git a/app/src/main/java/com/google/android/diskusage/DiskUsageApplication.kt b/app/src/main/java/com/google/android/diskusage/DiskUsageApplication.kt index 965aa9cd..159aada7 100644 --- a/app/src/main/java/com/google/android/diskusage/DiskUsageApplication.kt +++ b/app/src/main/java/com/google/android/diskusage/DiskUsageApplication.kt @@ -1,6 +1,7 @@ package com.google.android.diskusage import android.app.Application +import timber.log.Timber class DiskUsageApplication: Application() { companion object { @@ -12,5 +13,32 @@ class DiskUsageApplication: Application() { override fun onCreate() { super.onCreate() instance = this + try { + if (BuildConfig.DEBUG) { + Timber.plant( + object : Timber.DebugTree() { + override fun createStackElementTag(element: StackTraceElement): String = + "${super.createStackElementTag(element)}|${element.fileName}:${element.lineNumber}" + + override fun log( + priority: Int, + tag: String?, + message: String, + t: Throwable?, + ) { + super.log( + priority, + "[${Thread.currentThread().name}] ${tag?.substringBefore('|')}", + "${tag?.substringAfter('|')}] $message", + t, + ) + } + }, + ) + } + } catch (e: Exception) { + e.fillInStackTrace() + return + } } } \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/core/NativeScanner.java b/app/src/main/java/com/google/android/diskusage/core/NativeScanner.java index a4bba98b..4679ab84 100644 --- a/app/src/main/java/com/google/android/diskusage/core/NativeScanner.java +++ b/app/src/main/java/com/google/android/diskusage/core/NativeScanner.java @@ -29,7 +29,7 @@ import com.google.android.diskusage.filesystem.entity.FileSystemFile; import com.google.android.diskusage.filesystem.mnt.MountPoint; import com.google.android.diskusage.ui.DiskUsage.ProgressGenerator; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -171,9 +171,9 @@ public NativeScanner(Context context, long blockSize, long allocatedBlocks, int this.context = context; // this.blockAllowance = (allocatedBlocks << FileSystemEntry.blockOffset) / 2; // this.blockAllowance = (maxHeap / 2) * sizeThreshold; - Logger.getLOGGER().d("NativeScanner: allocatedBlocks %s", allocatedBlocks); - Logger.getLOGGER().d("NativeScanner: maxHeap %s", maxHeap); - Logger.getLOGGER().d("NativeScanner: sizeThreshold = %s", sizeThreshold / (float) (1 << FileSystemEntry.blockOffset)); + Timber.d("NativeScanner: allocatedBlocks %s", allocatedBlocks); + Timber.d("NativeScanner: maxHeap %s", maxHeap); + Timber.d("NativeScanner: sizeThreshold = %s", sizeThreshold / (float) (1 << FileSystemEntry.blockOffset)); } private void print(String msg, @NonNull SmallList list) { @@ -182,7 +182,7 @@ private void print(String msg, @NonNull SmallList list) { for(FileSystemEntry p = list.parent; p != null; p = p.parent) { hidden_path.insert(0, p.name + "/"); } - Logger.getLOGGER().d("%s %s = %s %s", msg, hidden_path, list.heapSize, list.spaceEfficiency); + Timber.d("%s %s = %s %s", msg, hidden_path, list.heapSize, list.spaceEfficiency); } public FileSystemEntry scan(@NonNull MountPoint mountPoint) throws IOException, InterruptedException { @@ -192,7 +192,7 @@ public FileSystemEntry scan(@NonNull MountPoint mountPoint) throws IOException, Type type = getType(); if (type != Type.DIR) throw new RuntimeException("Error: no mount point"); scanDirectory(null, getString(), 0); - Logger.getLOGGER().d("NativeScanner.scan(): Allocated %s B of heap", createdNodeSize); + Timber.d("scan: Allocated %s B of heap", createdNodeSize); int extraHeap = 0; @@ -215,8 +215,8 @@ public FileSystemEntry scan(@NonNull MountPoint mountPoint) throws IOException, list.parent.children = newChildren; extraHeap += list.heapSize; } - Logger.getLOGGER().d("allocated " + extraHeap + " B of extra heap"); - Logger.getLOGGER().d("allocated " + (extraHeap + createdNodeSize) + " B total"); + Timber.d("allocated " + extraHeap + " B of extra heap"); + Timber.d("allocated " + (extraHeap + createdNodeSize) + " B total"); if (offset != allocated) throw new RuntimeException("Error: extra data, " + (allocated - offset) + " bytes"); is.close(); return createdNode; diff --git a/app/src/main/java/com/google/android/diskusage/core/Scanner.java b/app/src/main/java/com/google/android/diskusage/core/Scanner.java index 1ef25893..5ce9b6a6 100644 --- a/app/src/main/java/com/google/android/diskusage/core/Scanner.java +++ b/app/src/main/java/com/google/android/diskusage/core/Scanner.java @@ -29,7 +29,7 @@ import com.google.android.diskusage.filesystem.entity.FileSystemEntrySmall; import com.google.android.diskusage.filesystem.entity.FileSystemFile; import com.google.android.diskusage.ui.DiskUsage; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; import java.io.IOException; import java.util.ArrayList; import java.util.PriorityQueue; @@ -86,9 +86,9 @@ public Scanner(int maxDepth, long blockSize, long allocatedBlocks, int maxHeap) this.maxHeapSize = maxHeap; // this.blockAllowance = (allocatedBlocks << FileSystemEntry.blockOffset) / 2; // this.blockAllowance = (maxHeap / 2) * sizeThreshold; - Logger.getLOGGER().d("Scanner: allocatedBlocks %s", allocatedBlocks); - Logger.getLOGGER().d("Scanner: maxHeap %s", maxHeap); - Logger.getLOGGER().d("Scanner: sizeThreshold = %s", sizeThreshold / (float) (1 << FileSystemEntry.blockOffset)); + Timber.d("Scanner: allocatedBlocks %s", allocatedBlocks); + Timber.d("Scanner: maxHeap %s", maxHeap); + Timber.d("Scanner: sizeThreshold = %s", sizeThreshold / (float) (1 << FileSystemEntry.blockOffset)); } public FileSystemEntry scan(LegacyFile file) throws IOException { @@ -122,8 +122,8 @@ public FileSystemEntry scan(LegacyFile file) throws IOException { list.parent.children = newChildren; extraHeap += list.heapSize; } - Logger.getLOGGER().d("allocated " + extraHeap + " B of extra heap"); - Logger.getLOGGER().d("allocated " + (extraHeap + createdNodeSize) + " B total"); + Timber.d("allocated " + extraHeap + " B of extra heap"); + Timber.d("allocated " + (extraHeap + createdNodeSize) + " B total"); return createdNode; } @@ -154,7 +154,7 @@ private void scanDirectory(FileSystemEntry parent, @NonNull LegacyFile file, int try { listNames = file.list(); } catch (SecurityException io) { - Logger.getLOGGER().d("list files", io); + Timber.d(io, "list files failed"); } if (listNames == null) return; @@ -322,7 +322,7 @@ private long calculateSize(@NonNull LegacyFile file) { try { list = file.listFiles(); } catch (SecurityException io) { - Logger.getLOGGER().e("Scanner.calculateSize(): list files", io); + Timber.e(io, "calculateSize: list files"); } if (list == null) return 0; long size = 1; diff --git a/app/src/main/java/com/google/android/diskusage/datasource/AppInfo.java b/app/src/main/java/com/google/android/diskusage/datasource/AppInfo.java deleted file mode 100644 index 701799b9..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/AppInfo.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.google.android.diskusage.datasource; - -import android.annotation.TargetApi; -import android.os.Build; - -public interface AppInfo { - int getFlags(); - String getDataDir(); - boolean isEnabled(); - String getName(); - String getPackageName(); - String getPublicSourceDir(); - String getSourceDir(); - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - String[] getSplitSourceDirs(); - public String getApplicationLabel(); -} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/datasource/AppInfo.kt b/app/src/main/java/com/google/android/diskusage/datasource/AppInfo.kt new file mode 100644 index 00000000..51fe9a7e --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/datasource/AppInfo.kt @@ -0,0 +1,14 @@ +package com.google.android.diskusage.datasource + +interface AppInfo { + val flags: Int + val dataDir: String? + val isEnabled: Boolean + val name: String? + val packageName: String? + val publicSourceDir: String? + val sourceDir: String? + + val splitSourceDirs: Array? + val applicationLabel: String? +} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/datasource/AppStats.java b/app/src/main/java/com/google/android/diskusage/datasource/AppStats.java deleted file mode 100644 index aca8d7e3..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/AppStats.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.google.android.diskusage.datasource; - -import android.annotation.TargetApi; -import android.os.Build; - -public interface AppStats { - long getCacheSize(); - long getDataSize(); - long getCodeSize(); - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - long getExternalCacheSize(); - @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) - long getExternalCodeSize(); - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - long getExternalDataSize(); - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - long getExternalMediaSize(); - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - long getExternalObbSize(); -} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/datasource/AppStatsCallback.java b/app/src/main/java/com/google/android/diskusage/datasource/AppStatsCallback.java deleted file mode 100644 index ec7312eb..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/AppStatsCallback.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.google.android.diskusage.datasource; - -public interface AppStatsCallback { - void onGetStatsCompleted(AppStats stats, boolean succeeded); -} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/datasource/DataSource.java b/app/src/main/java/com/google/android/diskusage/datasource/DataSource.java deleted file mode 100644 index 73d98416..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/DataSource.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.google.android.diskusage.datasource; - -import java.lang.reflect.Method; -import java.util.List; -import android.annotation.TargetApi; -import android.content.Context; -import android.content.pm.PackageManager; -import android.os.Build; -import com.google.android.diskusage.ui.LoadableActivity; -import com.google.android.diskusage.datasource.fast.DefaultDataSource; - -public abstract class DataSource { - private static DataSource currentDataSource = new DefaultDataSource(); - - public static DataSource get() { - return currentDataSource; - } - - public static void override(DataSource dataSource) { - LoadableActivity.resetStoredStates(); - currentDataSource = dataSource; - } - - public abstract List getInstalledPackages(PackageManager pm); - - public abstract StatFsSource statFs(String mountPoint); - - @TargetApi(Build.VERSION_CODES.FROYO) - public abstract PortableFile getExternalFilesDir(Context context); - - public abstract PortableFile getExternalStorageDirectory(); - - public abstract LegacyFile createLegacyScanFile(String root); - - public abstract void getPackageSizeInfo( - PkgInfo pkgInfo, - Method getPackageSizeInfo, - PackageManager pm, - AppStatsCallback callback) throws Exception; - - public abstract PortableFile getParentFile(PortableFile file); -} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/DataSource.kt b/app/src/main/java/com/google/android/diskusage/datasource/DataSource.kt new file mode 100644 index 00000000..f3827415 --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/datasource/DataSource.kt @@ -0,0 +1,26 @@ +package com.google.android.diskusage.datasource + +import android.content.Context +import android.content.pm.PackageManager +import com.google.android.diskusage.datasource.fast.DefaultDataSource +import com.google.android.diskusage.ui.LoadableActivity + +abstract class DataSource { + abstract fun getInstalledPackages(pm: PackageManager): List + abstract fun statFs(mountPoint: String?): StatFsSource + abstract fun getExternalFilesDir(context: Context): PortableFile? + abstract val externalStorageDirectory: PortableFile? + abstract fun createLegacyScanFile(root: String): LegacyFile? + + abstract fun getParentFile(file: PortableFile): PortableFile? + + companion object { + private var currentDataSource: DataSource = DefaultDataSource() + fun get(): DataSource = currentDataSource + + fun override(dataSource: DataSource) { + LoadableActivity.resetStoredStates() + currentDataSource = dataSource + } + } +} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.java b/app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.java deleted file mode 100644 index 9c282fee..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.google.android.diskusage.datasource; - -import java.io.IOException; - -public interface LegacyFile { - String getName(); - String getCanonicalPath() throws IOException; - - boolean isLink(); - boolean isFile(); - long length(); - - LegacyFile[] listFiles(); - String[] list(); - - LegacyFile getChild(String string); -} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.kt b/app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.kt new file mode 100644 index 00000000..6cb60504 --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.kt @@ -0,0 +1,16 @@ +package com.google.android.diskusage.datasource + +import java.io.IOException + +interface LegacyFile { + val name: String? + + @get:Throws(IOException::class) + val canonicalPath: String? + val isLink: Boolean + val isFile: Boolean + fun length(): Long + fun listFiles(): Array? + fun list(): Array? + fun getChild(string: String): LegacyFile? +} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.java b/app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.java deleted file mode 100644 index 6b67d57e..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.google.android.diskusage.datasource; - - -public interface PkgInfo { - String getPackageName(); - AppInfo getApplicationInfo(); -} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.kt b/app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.kt new file mode 100644 index 00000000..3e0928c3 --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.kt @@ -0,0 +1,6 @@ +package com.google.android.diskusage.datasource + +interface PkgInfo { + val packageName: String? + val applicationInfo: AppInfo? +} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java b/app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java deleted file mode 100644 index c9bc5821..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.google.android.diskusage.datasource; - -import android.annotation.TargetApi; -import android.os.Build; - -public interface PortableFile { - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - boolean isExternalStorageEmulated(); - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - boolean isExternalStorageRemovable(); - - /** Retries with getAbsolutePath() on IOException */ - String getCanonicalPath(); - String getAbsolutePath(); - - @TargetApi(Build.VERSION_CODES.GINGERBREAD) - long getTotalSpace(); -} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/PortableFile.kt b/app/src/main/java/com/google/android/diskusage/datasource/PortableFile.kt new file mode 100644 index 00000000..3edc314e --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/datasource/PortableFile.kt @@ -0,0 +1,11 @@ +package com.google.android.diskusage.datasource + +interface PortableFile { + val isExternalStorageEmulated: Boolean + val isExternalStorageRemovable: Boolean + + /** Retries with getAbsolutePath() on IOException */ + val canonicalPath: String + val absolutePath: String + val totalSpace: Long +} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/SearchManager.java b/app/src/main/java/com/google/android/diskusage/datasource/SearchManager.java deleted file mode 100644 index 83035c85..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/SearchManager.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.google.android.diskusage.datasource; - -import com.google.android.diskusage.filesystem.entity.FileSystemEntry; -import com.google.android.diskusage.filesystem.entity.FileSystemSuperRoot; -import com.google.android.diskusage.ui.DiskUsageMenu; - -public class SearchManager { - private final DiskUsageMenu menu; - private Search finishedSearch; - private Search activeSearch; - private String query; - - private class Search extends Thread { - public final String query; - public FileSystemSuperRoot baseRoot; - public FileSystemSuperRoot newRoot; - - Search(String query, FileSystemSuperRoot baseRoot) { - this.query = query; - this.baseRoot = baseRoot; - } - - public void run() { - try { - FileSystemSuperRoot root = menu.masterRoot; - this.newRoot = (FileSystemSuperRoot) - root.filter(this.query, baseRoot.getDisplayBlockSize()); - if (isInterrupted()) return; - menu.diskusage.handler.post(() -> searchFinished(Search.this)); - } catch (FileSystemEntry.SearchInterruptedException ignored) {} - } - } - - public SearchManager(DiskUsageMenu menu) { - this.menu = menu; - } - - public void search(String newQuery) { - newQuery = newQuery.toLowerCase(); - query = newQuery; - if (activeSearch != null) { - if (newQuery.contains(activeSearch.query)) { - // pending search, return - return; - } else { - activeSearch.interrupt(); - activeSearch = null; - } - } - - startSearch(); - } - - private void startSearch() { - FileSystemSuperRoot baseRoot = menu.masterRoot; - if (finishedSearch != null) { - if (query.contains(finishedSearch.query)) { - baseRoot = finishedSearch.newRoot; - } else { - finishedSearch = null; - } - } - - if (baseRoot != null) { - Search search = new Search(query, baseRoot); - search.start(); - } else { - menu.finishedSearch(null, null); - } - } - - private void searchFinished(Search search) { - if (activeSearch == search) { - activeSearch = null; - } - finishedSearch = search; - - if (!query.equals(search.query)) { - startSearch(); - } - menu.finishedSearch(search.newRoot, search.query); - } - - public void cancelSearch() { - if (activeSearch != null) activeSearch.interrupt(); - activeSearch = null; - finishedSearch = null; - } -} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/datasource/SearchManager.kt b/app/src/main/java/com/google/android/diskusage/datasource/SearchManager.kt new file mode 100644 index 00000000..2fa59be5 --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/datasource/SearchManager.kt @@ -0,0 +1,74 @@ +package com.google.android.diskusage.datasource + +import com.google.android.diskusage.filesystem.entity.FileSystemEntry.SearchInterruptedException +import com.google.android.diskusage.filesystem.entity.FileSystemSuperRoot +import com.google.android.diskusage.ui.DiskUsageMenu + +class SearchManager(private val menu: DiskUsageMenu) { + private var finishedSearch: Search? = null + private var activeSearch: Search? = null + private lateinit var query: String + + private inner class Search( + val query: String, + var baseRoot: FileSystemSuperRoot + ) : Thread() { + var newRoot: FileSystemSuperRoot? = null + override fun run() { + try { + val root = menu.masterRoot + newRoot = root?.filter(this.query, baseRoot.displayBlockSize) as FileSystemSuperRoot + if (isInterrupted) return + menu.diskusage.handler.post { searchFinished(this@Search) } + } catch (ignored: SearchInterruptedException) { + } + } + } + + fun search(newQuery: String) { + query = newQuery.lowercase() + activeSearch?.let { + if (newQuery.contains(it.query)) { + return + } else { + it.interrupt() + activeSearch = null + } + } + startSearch() + } + + private fun startSearch() { + var baseRoot = menu.masterRoot + finishedSearch?.let { + if (query.contains(it.query)) { + baseRoot = it.newRoot + } else { + finishedSearch = null + } + } + if (baseRoot != null) { + val search = Search(query, baseRoot!!) + search.start() + } else { + menu.finishedSearch(null, null) + } + } + + private fun searchFinished(search: Search) { + if (activeSearch === search) { + activeSearch = null + } + finishedSearch = search + if (query != search.query) { + startSearch() + } + menu.finishedSearch(search.newRoot, search.query) + } + + fun cancelSearch() { + activeSearch?.interrupt() + activeSearch = null + finishedSearch = null + } +} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.java b/app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.java deleted file mode 100644 index 32de2f39..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.google.android.diskusage.datasource; - -import android.annotation.TargetApi; -import android.os.Build; - -public interface StatFsSource { - - @Deprecated - int getAvailableBlocks(); - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) - public long getAvailableBlocksLong(); - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) - public long getAvailableBytes(); - - @Deprecated - public int getBlockCount(); - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) - public long getBlockCountLong(); - - @Deprecated - public int getBlockSize(); - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) - public long getBlockSizeLong(); - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) - public long getFreeBytes(); - - @Deprecated - public int getFreeBlocks(); - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) - public long getFreeBlocksLong(); - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) - public long getTotalBytes(); -} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.kt b/app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.kt new file mode 100644 index 00000000..f71efb8a --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.kt @@ -0,0 +1,22 @@ +package com.google.android.diskusage.datasource + +interface StatFsSource { + @Deprecated("Use availableBlocksLong instead", ReplaceWith("availableBlocksLong")) + val availableBlocks: Int + val availableBlocksLong: Long + val availableBytes: Long + + @Deprecated("Use blockCountLong instead", ReplaceWith("blockCountLong")) + val blockCount: Int + val blockCountLong: Long + + @Deprecated("Use blockSizeLing instead", ReplaceWith("blockSizeLong")) + val blockSize: Int + val blockSizeLong: Long + val freeBytes: Long + + @Deprecated("Use freeBlocksLing instead", ReplaceWith("freeBlocksLong")) + val freeBlocks: Int + val freeBlocksLong: Long + val totalBytes: Long +} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/AppInfoImpl.java b/app/src/main/java/com/google/android/diskusage/datasource/fast/AppInfoImpl.java deleted file mode 100644 index e47da313..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/fast/AppInfoImpl.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.google.android.diskusage.datasource.fast; - -import android.annotation.TargetApi; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.os.Build; - -import com.google.android.diskusage.datasource.AppInfo; - -public class AppInfoImpl implements AppInfo { - private final ApplicationInfo app; - private final PackageManager pm; - - AppInfoImpl(ApplicationInfo app, PackageManager pm) { - this.app = app; - this.pm = pm; - } - - @Override - public int getFlags() { - return app.flags; - } - - @Override - public String getDataDir() { - return app.dataDir; - } - - @Override - public boolean isEnabled() { - return app.enabled; - } - - @Override - public String getName() { - return app.name; - } - - @Override - public String getPackageName() { - return app.packageName; - } - - @Override - public String getPublicSourceDir() { - return app.publicSourceDir; - } - - @Override - public String getSourceDir() { - return app.sourceDir; - } - - @Override - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - public String[] getSplitSourceDirs() { - return app.splitSourceDirs; - } - - @Override - public String getApplicationLabel() { - return pm.getApplicationLabel(app).toString(); - } -} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/AppInfoImpl.kt b/app/src/main/java/com/google/android/diskusage/datasource/fast/AppInfoImpl.kt new file mode 100644 index 00000000..25703f73 --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/datasource/fast/AppInfoImpl.kt @@ -0,0 +1,30 @@ +package com.google.android.diskusage.datasource.fast + +import android.content.pm.ApplicationInfo +import android.content.pm.PackageManager +import com.google.android.diskusage.datasource.AppInfo + +class AppInfoImpl( + private val app: ApplicationInfo, + private val pm: PackageManager +) : AppInfo { + override val flags: Int + get() = app.flags + override val dataDir: String + get() = app.dataDir + override val isEnabled: Boolean + get() = app.enabled + override val name: String + get() = app.name + override val packageName: String + get() = app.packageName + override val publicSourceDir: String + get() = app.publicSourceDir + override val sourceDir: String + get() = app.sourceDir + + override val splitSourceDirs: Array? + get() = app.splitSourceDirs + override val applicationLabel: String + get() = pm.getApplicationLabel(app).toString() +} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/AppStatsImpl.java b/app/src/main/java/com/google/android/diskusage/datasource/fast/AppStatsImpl.java deleted file mode 100644 index b3be11ee..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/fast/AppStatsImpl.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.google.android.diskusage.datasource.fast; - -import android.annotation.TargetApi; -import android.content.pm.PackageStats; -import android.os.Build; -import com.google.android.diskusage.datasource.AppStats; - -class AppStatsImpl implements AppStats { - private final PackageStats packageStats; - - public AppStatsImpl(PackageStats packageStats) { - this.packageStats = packageStats; - } - - @Override - public long getCacheSize() { - return packageStats.cacheSize; - } - - @Override - public long getDataSize() { - return packageStats.dataSize; - } - - @Override - public long getCodeSize() { - return packageStats.codeSize; - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - @Override - public long getExternalCacheSize() { - return packageStats.externalCacheSize; - } - - @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) - @Override - public long getExternalCodeSize() { - return packageStats.externalCodeSize; - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - @Override - public long getExternalDataSize() { - return packageStats.externalDataSize; - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - @Override - public long getExternalMediaSize() { - return packageStats.externalMediaSize; - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - @Override - public long getExternalObbSize() { - return packageStats.externalObbSize; - } -} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.java b/app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.java deleted file mode 100644 index 203487b1..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.google.android.diskusage.datasource.fast; - -import com.google.android.diskusage.datasource.AppStatsCallback; -import com.google.android.diskusage.datasource.DataSource; -import com.google.android.diskusage.datasource.LegacyFile; -import com.google.android.diskusage.datasource.PkgInfo; -import com.google.android.diskusage.datasource.PortableFile; -import com.google.android.diskusage.datasource.StatFsSource; -import android.annotation.TargetApi; -import android.content.Context; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.os.Build; -import android.os.Environment; -import androidx.annotation.NonNull; -import java.io.File; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -public class DefaultDataSource extends DataSource { - - @Override - public List getInstalledPackages(@NonNull PackageManager pm) { - final List installedPackages = pm.getInstalledPackages( - PackageManager.GET_META_DATA | PackageManager.GET_UNINSTALLED_PACKAGES); - List packageInfos = new ArrayList<>(); - for (PackageInfo info : installedPackages) { - packageInfos.add(new PkgInfoImpl(info, pm)); - } - return packageInfos; - } - - @Override - public StatFsSource statFs(String mountPoint) { - return new StatFsSourceImpl(mountPoint); - } - - @TargetApi(Build.VERSION_CODES.FROYO) - @Override - public PortableFile getExternalFilesDir(Context context) { - return PortableFileImpl.make(context.getExternalFilesDir(null)); - } - - @Override - public LegacyFile createLegacyScanFile(String root) { - return LegacyFileImpl.createRoot(root); - } - - @Override - public void getPackageSizeInfo( - PkgInfo pkgInfo, - Method getPackageSizeInfo, - PackageManager pm, - final AppStatsCallback callback) throws Exception { - // This legacy pre-Android-8 reflection path relied on the hidden - // android.content.pm.IPackageStatsObserver AIDL interface, which the - // SDK no longer exposes as of API 34. It was never actually called in - // practice (modern devices use Apps2SDLoader/StorageStatsManager - // instead), so it now just reports "unavailable" rather than crash. - callback.onGetStatsCompleted(null, false); - } - - @Override - public PortableFile getExternalStorageDirectory() { - return PortableFileImpl.make(Environment.getExternalStorageDirectory()); - } - - @Override - public PortableFile getParentFile(PortableFile file) { - return PortableFileImpl.make(new File(file.getAbsolutePath()).getParentFile()); - } -} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.kt b/app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.kt new file mode 100644 index 00000000..e357d27b --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.kt @@ -0,0 +1,47 @@ +package com.google.android.diskusage.datasource.fast + +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.os.Environment +import com.google.android.diskusage.datasource.DataSource +import com.google.android.diskusage.datasource.LegacyFile +import com.google.android.diskusage.datasource.PkgInfo +import com.google.android.diskusage.datasource.PortableFile +import com.google.android.diskusage.datasource.StatFsSource +import java.io.File + +class DefaultDataSource : DataSource() { + override fun getInstalledPackages(pm: PackageManager): List { + val flags = + PackageManager.GET_META_DATA or + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + PackageManager.MATCH_UNINSTALLED_PACKAGES + } else { + @Suppress("DEPRECATION") + PackageManager.GET_UNINSTALLED_PACKAGES + } + return pm.getInstalledPackages(flags) + .map { info -> PkgInfoImpl(info, pm) } + } + + override fun statFs(mountPoint: String?): StatFsSource { + return StatFsSourceImpl(mountPoint) + } + + override fun getExternalFilesDir(context: Context): PortableFile? { + return PortableFileImpl.make(context.getExternalFilesDir(null)) + } + + override fun createLegacyScanFile(root: String): LegacyFile { + return LegacyFileImpl.createRoot(root) + } + + + override val externalStorageDirectory: PortableFile? + get() = PortableFileImpl.make(Environment.getExternalStorageDirectory()) + + override fun getParentFile(file: PortableFile): PortableFile? { + return PortableFileImpl.make(File(file.absolutePath).getParentFile()) + } +} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/LegacyFileImpl.java b/app/src/main/java/com/google/android/diskusage/datasource/fast/LegacyFileImpl.java deleted file mode 100644 index ad87a197..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/fast/LegacyFileImpl.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.google.android.diskusage.datasource.fast; - -import androidx.annotation.NonNull; -import java.io.File; -import java.io.IOException; - -import com.google.android.diskusage.datasource.LegacyFile; - -import org.jetbrains.annotations.Contract; - -public class LegacyFileImpl implements LegacyFile { - - private final File file; - - private LegacyFileImpl(File file) { - this.file = file; - } - - @NonNull - @Contract("_ -> new") - public static LegacyFile createRoot(String root) { - return new LegacyFileImpl(new File(root)); - } - - @Override - public String getName() { - return file.getName(); - } - - @Override - public String getCanonicalPath() throws IOException { - return file.getCanonicalPath(); - } - - @Override - public boolean isLink() { - try { - if (file.getCanonicalPath().equals(file.getPath())) return false; - } catch(Throwable ignored) {} - return true; - } - - @Override - public boolean isFile() { - return file.isFile(); - } - - @Override - public long length() { - return file.length(); - } - - @Override - public LegacyFile[] listFiles() { - File[] children = file.listFiles(); - LegacyFile[] res = new LegacyFile[children.length]; - for (int i = 0; i < children.length; i++) { - res[i] = new LegacyFileImpl(children[i]); - } - return res; - } - - @Override - public String[] list() { - return file.list(); - } - - @Override - public LegacyFile getChild(String childName) { - return new LegacyFileImpl(new File(file, childName)); - } -} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/LegacyFileImpl.kt b/app/src/main/java/com/google/android/diskusage/datasource/fast/LegacyFileImpl.kt new file mode 100644 index 00000000..1cff5499 --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/datasource/fast/LegacyFileImpl.kt @@ -0,0 +1,49 @@ +package com.google.android.diskusage.datasource.fast + +import com.google.android.diskusage.datasource.LegacyFile +import java.io.File +import java.io.IOException + +class LegacyFileImpl private constructor(private val file: File) : LegacyFile { + override val name: String + get() = file.getName() + + @get:Throws(IOException::class) + override val canonicalPath: String + get() = file.getCanonicalPath() + + override val isLink: Boolean + get() { + try { + if (file.getCanonicalPath() == file.path) return false + } catch (ignored: Throwable) { + } + return true + } + + override val isFile: Boolean + get() = file.isFile + + override fun length(): Long { + return file.length() + } + + override fun listFiles(): Array? { + return file.listFiles()?.map { LegacyFileImpl(it) }?.toTypedArray() + } + + override fun list(): Array? { + return file.list() + } + + override fun getChild(string: String): LegacyFile { + return LegacyFileImpl(File(file, string)) + } + + companion object { + @JvmStatic + fun createRoot(root: String): LegacyFile { + return LegacyFileImpl(File(root)) + } + } +} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/NativeScannerStream.java b/app/src/main/java/com/google/android/diskusage/datasource/fast/NativeScannerStream.java deleted file mode 100644 index a0796fca..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/fast/NativeScannerStream.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.google.android.diskusage.datasource.fast; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import androidx.annotation.NonNull; -import com.google.android.diskusage.utils.AppHelper; -import com.google.android.diskusage.utils.DeviceHelper; -import org.jetbrains.annotations.Contract; - -public class NativeScannerStream extends InputStream { - - private final InputStream is; - private final Process process; - - public NativeScannerStream(InputStream is, Process process) { - this.is = is; - this.process = process; - } - - @Override - public int read() throws IOException { - return is.read(); - } - - @Override - public int read(byte[] buffer) throws IOException { - return is.read(buffer); - } - - @Override - public int read(byte[] buffer, int byteOffset, int byteCount) - throws IOException { - return is.read(buffer, byteOffset, byteCount); - } - - @Override - public void close() throws IOException { - is.close(); - try { - process.waitFor(); - } catch (InterruptedException e) { - throw new IOException(e.getMessage()); - } - } - - - - public static class Factory { - // private static final boolean remove = true; - - @NonNull - @Contract("_, _ -> new") - public static NativeScannerStream create(String path, boolean rootRequired) - throws IOException, InterruptedException { - return runScanner(path, rootRequired); - } - - @NonNull - @Contract("_, _ -> new") - private static NativeScannerStream runScanner(String root, boolean rootRequired) - throws IOException, InterruptedException { - String binaryName = "libscan.so"; - Process process = null; - - if (!(rootRequired && DeviceHelper.isDeviceRooted())) { - process = Runtime.getRuntime().exec(new String[] { - getScanBinaryPath(binaryName), root}); - } else { - IOException e = null; - for (String su : new String[] { "su", "/system/bin/su", "/system/xbin/su" }) { - try { - process = Runtime.getRuntime().exec(new String[] { su }); - break; - } catch (IOException newe) { - e = newe; - } - } - - if (process == null) { - throw e; - } - - OutputStream os = process.getOutputStream(); - os.write((getScanBinaryPath(binaryName) + " " + root).getBytes("UTF-8")); - os.flush(); - os.close(); - } - InputStream is = process.getInputStream(); - return new NativeScannerStream(is, process); - } - - @NonNull - private static String getScanBinaryPath(String binaryName) { - return AppHelper.getAppContext().getApplicationInfo().nativeLibraryDir - + "/" + binaryName; - } - } -} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/NativeScannerStream.kt b/app/src/main/java/com/google/android/diskusage/datasource/fast/NativeScannerStream.kt new file mode 100644 index 00000000..57b62a3a --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/datasource/fast/NativeScannerStream.kt @@ -0,0 +1,168 @@ +package com.google.android.diskusage.datasource.fast + +import androidx.annotation.Keep +import com.google.android.diskusage.utils.AppHelper.appContext +import com.google.android.diskusage.utils.DeviceHelper.isDeviceRooted +import timber.log.Timber +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.io.PipedInputStream +import java.io.PipedOutputStream + +/** + * Reads the serialised directory tree produced by `libscan.so`. + * + * The tree is generated in-process through JNI (`app/src/main/jni/scan.c`) and + * streamed chunk by chunk into a pipe, so the parser and the progress dialog see + * data while the scan is still running. The historical approach — executing the + * shared library as a child process — does not work on Android 10+ (the ELF has + * no startup routine and the platform forbids executing app binaries); it is + * only attempted for root mode. + */ +class NativeScannerStream private constructor( + private val input: InputStream, + private val process: Process?, + private val producer: Thread? +) : InputStream() { + + @Throws(IOException::class) + override fun read(): Int = input.read() + + @Throws(IOException::class) + override fun read(buffer: ByteArray): Int = input.read(buffer) + + @Throws(IOException::class) + override fun read(buffer: ByteArray, byteOffset: Int, byteCount: Int): Int = + input.read(buffer, byteOffset, byteCount) + + @Throws(IOException::class) + override fun close() { + try { + // Closing the read end unblocks a producer that is stuck writing to + // a full pipe. + input.close() + } finally { + process?.let { awaitExit(it) } + producer?.let { thread -> + thread.interrupt() + runCatching { thread.join(CLOSE_TIMEOUT_MS) } + } + } + } + + /** + * Waits for the child process to terminate, but never blocks forever: a + * stuck helper used to leave the app on the "Scanning directories" dialog. + */ + private fun awaitExit(process: Process, timeoutMs: Long = EXIT_TIMEOUT_MS) { + val deadline = System.currentTimeMillis() + timeoutMs + while (System.currentTimeMillis() < deadline) { + try { + process.exitValue() + return + } catch (e: IllegalThreadStateException) { + try { + Thread.sleep(POLL_INTERVAL_MS) + } catch (interrupted: InterruptedException) { + Thread.currentThread().interrupt() + break + } + } + } + process.destroy() + process.destroyForcibly() + } + + /** Receives the chunks of the serialised tree from native code. */ + class NativeSink internal constructor(private val out: OutputStream) { + @Keep + fun onData(chunk: ByteArray) { + out.write(chunk) + } + } + + companion object Factory { + private const val LIBSCAN = "libscan.so" + private const val EXIT_TIMEOUT_MS = 5_000L + private const val CLOSE_TIMEOUT_MS = 1_000L + private const val POLL_INTERVAL_MS = 20L + private const val PIPE_SIZE = 64 * 1024 + + private val nativeAvailable: Boolean = try { + System.loadLibrary("scan") + true + } catch (t: Throwable) { + Timber.w(t, "libscan.so could not be loaded") + false + } + + @JvmStatic + @Throws(IOException::class) + fun create(path: String, rootRequired: Boolean): NativeScannerStream { + if (rootRequired && isDeviceRooted()) { + return runScannerAsRoot(path) + } + if (nativeAvailable) { + try { + return nativeScanner(path) + } catch (t: Throwable) { + Timber.w(t, "native scan of %s could not be started", path) + } + } + // Fall back to the child process; the caller falls back to the Java + // scanner if this fails as well. + return runScanner(path) + } + + private fun nativeScanner(path: String): NativeScannerStream { + val pipeOut = PipedOutputStream() + val pipeIn = PipedInputStream(PIPE_SIZE) + pipeOut.connect(pipeIn) + val sink = NativeSink(pipeOut) + val producer = Thread({ + var complete = false + try { + complete = scanNative(path, sink) + } catch (t: Throwable) { + Timber.w(t, "native scan of %s failed", path) + } finally { + if (!complete) { + Timber.w("native scan of %s was not completed", path) + } + runCatching { pipeOut.close() } + } + }, "diskusage-scan") + producer.isDaemon = true + producer.start() + return NativeScannerStream(pipeIn, null, producer) + } + + /** + * Runs the tree walker in-process and streams the serialised tree into + * [sink]. Returns false when the walk was aborted. + */ + @JvmStatic + private external fun scanNative(path: String, sink: NativeSink): Boolean + + private fun runScanner(root: String): NativeScannerStream { + val libscanPath = "${appContext.applicationInfo.nativeLibraryDir}/$LIBSCAN" + val process = ProcessBuilder(libscanPath, root).start() + return NativeScannerStream(process.inputStream, process, null) + } + + private fun runScannerAsRoot(root: String): NativeScannerStream { + val libscanPath = "${appContext.applicationInfo.nativeLibraryDir}/$LIBSCAN" + val su = arrayOf("su", "/system/bin/su", "/system/xbin/su").firstNotNullOfOrNull { candidate -> + runCatching { ProcessBuilder(candidate).start() }.getOrNull() + } ?: throw IOException("No su binary found") + + su.outputStream.use { out -> + out.write("$libscanPath $root\n".toByteArray()) + out.write("exit\n".toByteArray()) + out.flush() + } + return NativeScannerStream(su.inputStream, su, null) + } + } +} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/PkgInfoImpl.java b/app/src/main/java/com/google/android/diskusage/datasource/fast/PkgInfoImpl.java deleted file mode 100644 index 99c7b128..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/fast/PkgInfoImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.google.android.diskusage.datasource.fast; - -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; - -import com.google.android.diskusage.datasource.AppInfo; -import com.google.android.diskusage.datasource.PkgInfo; - -public class PkgInfoImpl implements PkgInfo { - private final PackageInfo info; - private final PackageManager pm; - - public PkgInfoImpl(PackageInfo info, PackageManager pm) { - this.info = info; - this.pm = pm; - } - - @Override - public String getPackageName() { - return info.packageName; - } - - @Override - public AppInfo getApplicationInfo() { - return new AppInfoImpl(info.applicationInfo, pm); - } -} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/PkgInfoImpl.kt b/app/src/main/java/com/google/android/diskusage/datasource/fast/PkgInfoImpl.kt new file mode 100644 index 00000000..c872447b --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/datasource/fast/PkgInfoImpl.kt @@ -0,0 +1,16 @@ +package com.google.android.diskusage.datasource.fast + +import android.content.pm.ApplicationInfo +import android.content.pm.PackageInfo +import android.content.pm.PackageManager +import com.google.android.diskusage.datasource.AppInfo +import com.google.android.diskusage.datasource.PkgInfo + +class PkgInfoImpl(private val info: PackageInfo, private val pm: PackageManager) : PkgInfo { + override val packageName: String + get() = info.packageName + override val applicationInfo: AppInfo? + // applicationInfo is annotated as nullable since Android 14 (packages + // without any code, e.g. stubs, can be returned by the platform). + get() = (info.applicationInfo as ApplicationInfo?)?.let { AppInfoImpl(it, pm) } +} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/PortableFileImpl.java b/app/src/main/java/com/google/android/diskusage/datasource/fast/PortableFileImpl.java deleted file mode 100644 index 9b90a70e..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/fast/PortableFileImpl.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.google.android.diskusage.datasource.fast; - -import java.io.File; -import android.annotation.TargetApi; -import android.os.Build; -import android.os.Environment; -import androidx.annotation.NonNull; -import com.google.android.diskusage.datasource.PortableFile; -import com.google.android.diskusage.utils.PathHelper; - -public class PortableFileImpl implements PortableFile { - private final File file; - - private PortableFileImpl(File file) { - this.file = file; - } - - public static PortableFileImpl make(File file) { - if (file == null) { - return null; - } - return new PortableFileImpl(file); - } - - @NonNull - public static PortableFile[] getExternalAppFilesDirs() { - final File[] externalAppFilesPaths = PathHelper.getExternalAppFilesPaths(); - final PortableFile[] result = new PortableFile[externalAppFilesPaths.length]; - int i = 0; - for (final File dir : externalAppFilesPaths) { - result[i++] = make(dir); - } - return result; - } - - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - @Override - public boolean isExternalStorageEmulated() { - try { - return Environment.isExternalStorageEmulated(file); - } catch (Exception e) { - return false; - } - } - - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - @Override - public boolean isExternalStorageRemovable() { - try { - return Environment.isExternalStorageRemovable(file); - } catch (Exception e) { - return false; - } - - } - - @Override - public String getCanonicalPath() { - try { - return file.getCanonicalPath(); - } catch (Exception e) { - return file.getAbsolutePath(); - } - } - - @Override - public String getAbsolutePath() { - return file.getAbsolutePath(); - } - - @TargetApi(Build.VERSION_CODES.GINGERBREAD) - @Override - public long getTotalSpace() { - return file.getTotalSpace(); - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof PortableFile)) { - return false; - } - PortableFile other = (PortableFile) o; - return other.getAbsolutePath().equals(getAbsolutePath()); - } - - @Override - public int hashCode() { - return getAbsolutePath().hashCode(); - } -} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/PortableFileImpl.kt b/app/src/main/java/com/google/android/diskusage/datasource/fast/PortableFileImpl.kt new file mode 100644 index 00000000..5acebc2e --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/datasource/fast/PortableFileImpl.kt @@ -0,0 +1,53 @@ +package com.google.android.diskusage.datasource.fast + +import android.os.Environment +import com.google.android.diskusage.datasource.PortableFile +import com.google.android.diskusage.utils.PathHelper +import java.io.File + +class PortableFileImpl private constructor(private val file: File) : PortableFile { + override val isExternalStorageEmulated: Boolean + get() = try { + Environment.isExternalStorageEmulated(file) + } catch (e: Exception) { + false + } + override val isExternalStorageRemovable: Boolean + get() = try { + Environment.isExternalStorageRemovable(file) + } catch (e: Exception) { + false + } + override val canonicalPath: String + get() = try { + file.canonicalPath + } catch (e: Exception) { + file.absolutePath + } + override val absolutePath: String + get() = file.absolutePath + override val totalSpace: Long + get() = file.getTotalSpace() + + override fun equals(other: Any?): Boolean { + if (other !is PortableFile) { + return false + } + return other.absolutePath == absolutePath + } + + override fun hashCode(): Int { + return absolutePath.hashCode() + } + + companion object { + @JvmStatic + fun make(file: File?): PortableFileImpl? { + return file?.let { PortableFileImpl(it) } + } + + @JvmStatic + val externalAppFilesDirs: Array + get() = PathHelper.getExternalAppFilesPaths().map { make(it) }.toTypedArray() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/StatFsSourceImpl.java b/app/src/main/java/com/google/android/diskusage/datasource/fast/StatFsSourceImpl.java deleted file mode 100644 index 5dc5bd65..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/fast/StatFsSourceImpl.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.google.android.diskusage.datasource.fast; - -import android.annotation.TargetApi; -import android.os.Build; -import android.os.StatFs; - -import com.google.android.diskusage.datasource.StatFsSource; - -public class StatFsSourceImpl implements StatFsSource { - - private final StatFs statFs; - - public StatFsSourceImpl(String path) { - this.statFs = new StatFs(path); - } - - @Deprecated - @Override - public int getAvailableBlocks() { - return statFs.getAvailableBlocks(); - } - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) - @Override - public long getAvailableBlocksLong() { - return statFs.getAvailableBlocksLong(); - } - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) - @Override - public long getAvailableBytes() { - return statFs.getAvailableBytes(); - } - - @Deprecated - @Override - public int getBlockCount() { - return statFs.getBlockCount(); - } - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) - @Override - public long getBlockCountLong() { - return statFs.getBlockCountLong(); - } - - @Deprecated - @Override - public int getBlockSize() { - return statFs.getBlockSize(); - } - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) - @Override - public long getBlockSizeLong() { - return statFs.getBlockSizeLong(); - } - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) - @Override - public long getFreeBytes() { - return statFs.getFreeBytes(); - } - - @Deprecated - @Override - public int getFreeBlocks() { - return statFs.getFreeBlocks(); - } - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) - @Override - public long getFreeBlocksLong() { - return statFs.getFreeBlocksLong(); - } - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) - @Override - public long getTotalBytes() { - return statFs.getTotalBytes(); - } -} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/StatFsSourceImpl.kt b/app/src/main/java/com/google/android/diskusage/datasource/fast/StatFsSourceImpl.kt new file mode 100644 index 00000000..38cee06b --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/datasource/fast/StatFsSourceImpl.kt @@ -0,0 +1,42 @@ +package com.google.android.diskusage.datasource.fast + +import android.os.StatFs +import com.google.android.diskusage.datasource.StatFsSource + +class StatFsSourceImpl(path: String?) : StatFsSource { + private val statFs: StatFs + + init { + statFs = StatFs(path) + } + + @Deprecated("Use availableBlocksLong instead", replaceWith = ReplaceWith("availableBlocksLong")) + override val availableBlocks: Int + get() = statFs.availableBlocks + override val availableBlocksLong: Long + get() = statFs.availableBlocksLong + override val availableBytes: Long + get() = statFs.availableBytes + + @Deprecated("") + override val blockCount: Int + get() = statFs.blockCount + override val blockCountLong: Long + get() = statFs.blockCountLong + + @Deprecated("Use blockSizeLing instead", replaceWith = ReplaceWith("blockSizeLong")) + override val blockSize: Int + get() = statFs.blockSize + override val blockSizeLong: Long + get() = statFs.blockSizeLong + override val freeBytes: Long + get() = statFs.freeBytes + + @Deprecated("Use freeBlocksLing instead", replaceWith = ReplaceWith("freeBlocksLong")) + override val freeBlocks: Int + get() = statFs.freeBlocks + override val freeBlocksLong: Long + get() = statFs.freeBlocksLong + override val totalBytes: Long + get() = statFs.totalBytes +} diff --git a/app/src/main/java/com/google/android/diskusage/datasource/fast/StreamCopy.java b/app/src/main/java/com/google/android/diskusage/datasource/fast/StreamCopy.java deleted file mode 100644 index 783e809b..00000000 --- a/app/src/main/java/com/google/android/diskusage/datasource/fast/StreamCopy.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.google.android.diskusage.datasource.fast; - -import androidx.annotation.NonNull; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -public class StreamCopy { - public static void copyStream(@NonNull InputStream is, OutputStream os) - throws IOException { - int len; - byte[] buffer = new byte[32768]; - while ((len = is.read(buffer)) != -1) { - os.write(buffer, 0, len); - } - os.close(); - is.close(); - } - - @NonNull - public static byte[] copyToArray(InputStream is) throws IOException { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - copyStream(is, os); - os.flush(); - return os.toByteArray(); - } - - @NonNull - public static byte[] readFully(File file) throws IOException { - return copyToArray(new FileInputStream(file)); - } -} diff --git a/app/src/main/java/com/google/android/diskusage/filesystem/Apps2SDLoader.java b/app/src/main/java/com/google/android/diskusage/filesystem/Apps2SDLoader.java index d5836336..81c7509b 100644 --- a/app/src/main/java/com/google/android/diskusage/filesystem/Apps2SDLoader.java +++ b/app/src/main/java/com/google/android/diskusage/filesystem/Apps2SDLoader.java @@ -21,24 +21,36 @@ import android.app.usage.StorageStats; import android.app.usage.StorageStatsManager; -import android.app.usage.UsageStats; -import android.app.usage.UsageStatsManager; import android.content.Context; import android.content.pm.ApplicationInfo; +import android.content.pm.PackageInfo; import android.content.pm.PackageManager; +import android.os.Build; import android.os.Handler; import android.os.storage.StorageManager; +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; import com.google.android.diskusage.filesystem.entity.FileSystemEntry; import com.google.android.diskusage.filesystem.entity.FileSystemPackage; import com.google.android.diskusage.ui.DiskUsage; import com.google.android.diskusage.ui.common.ScanProgressDialog; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; +import java.io.File; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashSet; import java.util.List; -import java.util.Set; +/** + * Collects the storage footprint of every installed application. + * + *

Historically this used {@code UsageStatsManager.queryUsageStats()} which + * only returns applications the user interacted with recently. On modern + * Android that made most applications disappear from the graph. The package + * manager is the correct source; {@link StorageStatsManager} (API 26+) then + * provides accurate code/data/cache sizes. If the usage-access app-op has not + * been granted, the loader degrades gracefully to the APK size on disk instead + * of dropping the application entirely. + */ public class Apps2SDLoader { private final DiskUsage diskUsage; @@ -50,23 +62,18 @@ public Apps2SDLoader(DiskUsage activity) { this.diskUsage = activity; } - public FileSystemEntry[] load(final long blockSize) throws Throwable { - UsageStatsManager usageStatsManager = (UsageStatsManager) diskUsage.getSystemService(Context.USAGE_STATS_SERVICE); - - - final List queryUsageStats=usageStatsManager.queryUsageStats( - UsageStatsManager.INTERVAL_YEARLY, 0 ,System.currentTimeMillis()); - Logger.getLOGGER().d("Apps2SDLoader.load(): Stats size = %s", queryUsageStats.size()); - StorageStatsManager storageStatsManager = (StorageStatsManager) diskUsage.getSystemService(Context.STORAGE_STATS_SERVICE); - final ArrayList entries = new ArrayList(); - PackageManager packageManager = diskUsage.getApplicationContext().getPackageManager(); - final Set packages = new HashSet<>(); - for (UsageStats s : queryUsageStats) { - packages.add(s.getPackageName()); + final PackageManager packageManager = diskUsage.getApplicationContext().getPackageManager(); + final List packages; + try { + packages = packageManager.getInstalledPackages(0); + } catch (Throwable t) { + Timber.e(t, "load: cannot list installed packages"); + return new FileSystemEntry[0]; } final Handler handler = diskUsage.handler; + final int total = packages.size(); Runnable progressUpdater = new Runnable() { @Override public void run() { @@ -76,46 +83,106 @@ public void run() { dialog.switchToSecondary(); switchToSecondary = false; } - dialog.setMax(packages.size()); + dialog.setMax(total); final CharSequence appName; synchronized (Apps2SDLoader.this) { appName = lastAppName; } dialog.setProgress(numLoadedPackages, appName); } - diskUsage.handler.postDelayed(this, 50); + handler.postDelayed(this, 50); } }; handler.post(progressUpdater); + final ArrayList entries = new ArrayList<>(total); + boolean statsAccessDenied = false; + + try { + for (PackageInfo info : packages) { + ApplicationInfo metadata = info.applicationInfo; + if (metadata == null) continue; + // Do not try to report on apps that are hidden from the launcher and + // have no data at all (instant apps, stubs, ...). + String pkg = info.packageName; + if (pkg == null) continue; + + final String appName; + try { + appName = metadata.loadLabel(packageManager).toString(); + } catch (Throwable t) { + continue; + } + synchronized (this) { + lastAppName = appName; + } + + long apkBytes = apkSizeOf(metadata); + long dataBytes = 0; + long cacheBytes = 0; + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !statsAccessDenied) { + try { + long[] stats = queryStorageStats(pkg, apkBytes); + apkBytes = stats[0]; + dataBytes = stats[1]; + cacheBytes = stats[2]; + if (numLoadedPackages == 0) { + Timber.d("load: storage stats available, first app %s -> apk=%s data=%s cache=%s", + pkg, apkBytes, dataBytes, cacheBytes); + } + } catch (SecurityException e) { + // Usage access not granted: keep listing apps, only sizes degrade. + statsAccessDenied = true; + Timber.w("load: no usage access, falling back to APK sizes"); + } catch (Throwable t) { + Timber.d(t, "load: no storage stats for %s", pkg); + } + } + + if (apkBytes + dataBytes + cacheBytes <= 0) { + numLoadedPackages++; + continue; + } - for (String pkg : packages) { - Logger.getLOGGER().d("app: " + pkg); - try { - ApplicationInfo metadata = packageManager.getApplicationInfo(pkg, PackageManager.GET_META_DATA); - String appName = metadata.loadLabel(packageManager).toString(); - lastAppName = appName; - StorageStats stats = storageStatsManager.queryStatsForPackage( - StorageManager.UUID_DEFAULT, pkg, android.os.Process.myUserHandle()); - Logger.getLOGGER().d("stats: " + stats.getAppBytes() + " " + stats.getDataBytes()); FileSystemPackage p = new FileSystemPackage( - appName, - pkg, - stats.getAppBytes(), - stats.getDataBytes(), - stats.getCacheBytes(), - metadata.flags); + appName, pkg, apkBytes, dataBytes, cacheBytes, metadata.flags); p.applyFilter(blockSize); entries.add(p); numLoadedPackages++; - } catch (PackageManager.NameNotFoundException e) { - Logger.getLOGGER().d("Failed to get package", e); } + } finally { + handler.removeCallbacks(progressUpdater); } - FileSystemEntry[] result = entries.toArray(new FileSystemEntry[] {}); + FileSystemEntry[] result = entries.toArray(new FileSystemEntry[0]); Arrays.sort(result, FileSystemEntry.COMPARE); - handler.removeCallbacks(progressUpdater); return result; } + + /** @return {apkBytes, dataBytes, cacheBytes} */ + @RequiresApi(Build.VERSION_CODES.O) + private long[] queryStorageStats(String pkg, long apkBytes) throws Exception { + StorageStatsManager manager = + (StorageStatsManager) diskUsage.getSystemService(Context.STORAGE_STATS_SERVICE); + if (manager == null) return new long[] {apkBytes, 0, 0}; + StorageStats stats = manager.queryStatsForPackage( + StorageManager.UUID_DEFAULT, pkg, android.os.Process.myUserHandle()); + return new long[] { + Math.max(apkBytes, stats.getAppBytes()), + stats.getDataBytes(), + stats.getCacheBytes() + }; + } + + private static long apkSizeOf(@NonNull ApplicationInfo info) { + long size = 0; + if (info.sourceDir != null) size += new File(info.sourceDir).length(); + if (info.splitSourceDirs != null) { + for (String split : info.splitSourceDirs) { + if (split != null) size += new File(split).length(); + } + } + return Math.max(size, 0); + } } diff --git a/app/src/main/java/com/google/android/diskusage/filesystem/BackgroundDelete.java b/app/src/main/java/com/google/android/diskusage/filesystem/BackgroundDelete.java index 9a372cc9..ddeaadd4 100644 --- a/app/src/main/java/com/google/android/diskusage/filesystem/BackgroundDelete.java +++ b/app/src/main/java/com/google/android/diskusage/filesystem/BackgroundDelete.java @@ -19,11 +19,13 @@ package com.google.android.diskusage.filesystem; -import android.app.ProgressDialog; -import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; +import android.view.LayoutInflater; +import android.widget.LinearLayout; +import android.widget.ProgressBar; import androidx.annotation.NonNull; +import androidx.appcompat.app.AlertDialog; import com.google.android.diskusage.R; import com.google.android.diskusage.core.Scanner; import com.google.android.diskusage.datasource.DataSource; @@ -32,14 +34,14 @@ import com.google.android.diskusage.filesystem.entity.FileSystemPackage; import com.google.android.diskusage.filesystem.mnt.MountPoint; import com.google.android.diskusage.ui.DiskUsage; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; import java.io.File; import java.io.IOException; import splitties.resources.TextResourcesKt; import splitties.toast.ToastKt; public class BackgroundDelete extends Thread { - ProgressDialog dialog; + AlertDialog dialog; File file; String path; String rootPath; @@ -85,21 +87,31 @@ private BackgroundDelete(final DiskUsage diskUsage, @NonNull final FileSystemEnt } return; } - dialog = new ProgressDialog(diskUsage); - dialog.setMessage(TextResourcesKt.appStr(R.string.deleting_path, path)); - dialog.setIndeterminate(true); - dialog.setButton(DialogInterface.BUTTON_POSITIVE, diskUsage.getString(R.string.button_background), - (dialog, which) -> { - background(); - dialog.dismiss(); - }); - dialog.setButton(DialogInterface.BUTTON_NEGATIVE, diskUsage.getString(android.R.string.cancel), - (dialog, which) -> { - cancel(); - dialog.dismiss(); - }); - dialog.setOnDismissListener(x -> dialog = null); - dialog.setOnCancelListener(x -> dialog = null); + // ProgressDialog is deprecated since API 26 and no longer matches the + // app theme, so an AlertDialog with an indeterminate ProgressBar is used. + ProgressBar progressBar = new ProgressBar(diskUsage, null, + android.R.attr.progressBarStyleHorizontal); + progressBar.setIndeterminate(true); + LinearLayout container = new LinearLayout(diskUsage); + int padding = (int) (24 * diskUsage.getResources().getDisplayMetrics().density); + container.setPadding(padding, padding / 2, padding, 0); + container.addView(progressBar, new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); + + dialog = new AlertDialog.Builder(diskUsage) + .setMessage(TextResourcesKt.appStr(R.string.deleting_path, path)) + .setView(container) + .setPositiveButton(R.string.button_background, (d, which) -> { + background(); + d.dismiss(); + }) + .setNegativeButton(android.R.string.cancel, (d, which) -> { + cancel(); + d.dismiss(); + }) + .setOnDismissListener(x -> dialog = null) + .setOnCancelListener(x -> dialog = null) + .create(); dialog.show(); start(); } @@ -138,7 +150,7 @@ public void run() { } public void restore() { - Logger.getLOGGER().d("restore started for " + path); + Timber.d("restore started for " + path); MountPoint mountPoint = MountPoint.getForKey(diskUsage, diskUsage.getKey()); long displayBlockSize = diskUsage.fileSystemState.masterRoot.getDisplayBlockSize(); try { @@ -150,15 +162,15 @@ public void restore() { // FIXME: may be problems in case of two deletions entry.parent.insert(newEntry, displayBlockSize); diskUsage.fileSystemState.restore(newEntry); - Logger.getLOGGER().d("BackgroundDelete.restore(): Restoring undeleted: %s %s", + Timber.d("restore: Restoring undeleted: %s %s", newEntry.name, newEntry.sizeString()); } catch (IOException e) { - Logger.getLOGGER().d("Failed to restore"); + Timber.d("Failed to restore"); } } public void notifyUser() { - Logger.getLOGGER().d("BackgroundDelete.notifyUser(): Delete: status = %s directories %s files %s", + Timber.d("notifyUser: Delete: status = %s directories %s files %s", deletionStatus, numDeletedDirectories, numDeletedFiles); if (deletionStatus == DELETION_SUCCESS) { diff --git a/app/src/main/java/com/google/android/diskusage/filesystem/entity/FileSystemEntry.java b/app/src/main/java/com/google/android/diskusage/filesystem/entity/FileSystemEntry.java index 8b55485e..a8618895 100644 --- a/app/src/main/java/com/google/android/diskusage/filesystem/entity/FileSystemEntry.java +++ b/app/src/main/java/com/google/android/diskusage/filesystem/entity/FileSystemEntry.java @@ -29,7 +29,7 @@ import com.google.android.diskusage.opengl.DrawingCache; import com.google.android.diskusage.opengl.RenderingThread; import com.google.android.diskusage.ui.Cursor; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; @@ -1119,7 +1119,7 @@ public final void insert(@NonNull FileSystemEntry newEntry, long blockSize) { * @param exactMatch TODO */ public FileSystemEntry getEntryByName(@NonNull String path, boolean exactMatch) { - Logger.getLOGGER().d("FileSystemEntry.getEntryByName(): getEntryForName = %s", path); + Timber.d("getEntryByName: getEntryForName = %s", path); String[] pathElements = path.split("/"); FileSystemEntry entry = this; diff --git a/app/src/main/java/com/google/android/diskusage/filesystem/entity/FileSystemPackage.java b/app/src/main/java/com/google/android/diskusage/filesystem/entity/FileSystemPackage.java index ba774d8c..5c9e59c6 100644 --- a/app/src/main/java/com/google/android/diskusage/filesystem/entity/FileSystemPackage.java +++ b/app/src/main/java/com/google/android/diskusage/filesystem/entity/FileSystemPackage.java @@ -21,7 +21,7 @@ import android.content.pm.ApplicationInfo; import androidx.annotation.NonNull; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; import java.util.ArrayList; import java.util.Arrays; @@ -92,19 +92,19 @@ public void addPublicChild(FileSystemRoot child, @NonNull ChildType type, long b switch (type) { case CODE: codeSize -= child.getSizeInBlocks() * blockSize; if (codeSize < 0) { - Logger.getLOGGER().d("FileSystemPackage.addPublicChild(): Code size negative %s for %s", codeSize, pkg); + Timber.d("addPublicChild: Code size negative %s for %s", codeSize, pkg); codeSize = 0; } break; case DATA: dataSize -= child.getSizeInBlocks() * blockSize; if (dataSize < 0) { - Logger.getLOGGER().d("FileSystemPackage.addPublicChild(): Data size negative %s for %s", dataSize, pkg); + Timber.d("addPublicChild: Data size negative %s for %s", dataSize, pkg); dataSize = 0; } break; case CACHE: cacheSize -= child.getSizeInBlocks() * blockSize; if (cacheSize < 0) { - Logger.getLOGGER().d("FileSystemPackage.addPublicChild(): Cache size negative %s for %s", cacheSize, pkg); + Timber.d("addPublicChild: Cache size negative %s for %s", cacheSize, pkg); cacheSize = 0; } break; diff --git a/app/src/main/java/com/google/android/diskusage/filesystem/mnt/MountPoint.java b/app/src/main/java/com/google/android/diskusage/filesystem/mnt/MountPoint.java index 6108a22a..5450bf89 100644 --- a/app/src/main/java/com/google/android/diskusage/filesystem/mnt/MountPoint.java +++ b/app/src/main/java/com/google/android/diskusage/filesystem/mnt/MountPoint.java @@ -20,16 +20,32 @@ package com.google.android.diskusage.filesystem.mnt; import android.content.Context; +import android.os.Build; +import android.os.Environment; +import android.os.storage.StorageManager; +import android.os.storage.StorageVolume; import com.google.android.diskusage.R; -import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.PortableFile; import com.google.android.diskusage.datasource.fast.PortableFileImpl; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Set; +/** + * A volume the user can analyse: internal shared storage, an SD card or a USB + * drive. + * + *

Volume discovery was rewritten for modern Android. Before, only paths + * derived from {@code getExternalFilesDirs()} were used, which silently dropped + * volumes (most notably the internal storage on some OEM ROMs, removable SD + * cards and USB devices). Now {@link StorageManager#getStorageVolumes()} is the + * primary source and the app-private directories are only a fallback. + */ public class MountPoint { private final String title; private final String root; @@ -55,8 +71,9 @@ public boolean isRootRequired() { return false; } + /** Whether the app may delete content on this volume (full-disk access). */ public boolean isDeleteSupported() { - return forceHasApps; + return true; } public String getKey() { @@ -68,7 +85,7 @@ public boolean hasApps() { } private static List mountPoints = new ArrayList<>(); - private static Map mountPointForKey = new HashMap<>(); + private static Map mountPointForKey = new HashMap<>(); int getChecksum() { return RootMountPoint.checksum; @@ -93,17 +110,81 @@ private static void initMountPoints(Context context) { if (init) return; init = true; + Set seen = new LinkedHashSet<>(); + List result = new ArrayList<>(); + + // 1. Ask the framework which volumes exist. This is the authoritative list + // and includes USB mass storage and adopted/external SD cards. + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + StorageManager storageManager = + (StorageManager) context.getSystemService(Context.STORAGE_SERVICE); + if (storageManager != null) { + for (StorageVolume volume : storageManager.getStorageVolumes()) { + String path = directoryOf(volume); + if (path == null || !seen.add(VolumePathHelper.canonical(path))) continue; + boolean primary = volume.isPrimary(); + String description = volume.getDescription(context); + String title = primary + ? context.getString(R.string.storage_card) + : (description != null && description.length() > 0 ? description : path); + result.add(new MountPoint(title, path, primary)); + } + } + } + + // 2. Fallback (and volume list completion): every directory the app can + // write files to is guaranteed to be a mounted volume. for (final PortableFile dir : PortableFileImpl.getExternalAppFilesDirs()) { - String path = dir.getAbsolutePath().replaceFirst("/Android/data/com.google.android.diskusage/files", ""); - Logger.getLOGGER().d("MountPoint.initMountPoints: mountpoint %s", path); + if (dir == null) continue; + String path = VolumePathHelper.stripAppFilesSuffix( + dir.getAbsolutePath(), context.getPackageName()); + if (path == null || !seen.add(VolumePathHelper.canonical(path))) continue; boolean internal = !dir.isExternalStorageRemovable(); - String title = internal ? context.getString(R.string.storage_card) : path; - MountPoint mountPoint = new MountPoint(title, path, internal); + String title = internal ? context.getString(R.string.storage_card) : path; + result.add(new MountPoint(title, path, internal)); + } + + // 3. Always offer the primary shared storage, even if the two sources above + // failed (e.g. on TV devices without external files dirs). + if (seen.isEmpty()) { + File external = Environment.getExternalStorageDirectory(); + if (external != null) { + result.add(new MountPoint(context.getString(R.string.storage_card), + external.getAbsolutePath(), true)); + } + } + + for (MountPoint mountPoint : result) { + Timber.d("MountPoint %s -> %s (apps=%s)", + mountPoint.getTitle(), mountPoint.getRoot(), mountPoint.hasApps()); mountPoints.add(mountPoint); mountPointForKey.put(mountPoint.getKey(), mountPoint); } } + /** + * Resolves the file system path of a storage volume across API levels. + * {@link StorageVolume#getDirectory()} only exists on API 30+, for older + * releases the UUID based mount path is used instead. + */ + private static String directoryOf(StorageVolume volume) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + File dir = volume.getDirectory(); + if (dir != null) return dir.getAbsolutePath(); + } + String uuid = volume.getUuid(); + if (uuid != null) { + File byUuid = new File("/storage/" + uuid); + if (byUuid.isDirectory()) return byUuid.getAbsolutePath(); + } + if (volume.isPrimary() || volume.isEmulated()) { + File primary = Environment.getExternalStorageDirectory(); + if (primary != null) return primary.getAbsolutePath(); + } + return null; + } + + public static void reset() { mountPoints = new ArrayList<>(); mountPointForKey = new HashMap<>(); diff --git a/app/src/main/java/com/google/android/diskusage/filesystem/mnt/RootMountPoint.java b/app/src/main/java/com/google/android/diskusage/filesystem/mnt/RootMountPoint.java index c7b74702..69c06594 100644 --- a/app/src/main/java/com/google/android/diskusage/filesystem/mnt/RootMountPoint.java +++ b/app/src/main/java/com/google/android/diskusage/filesystem/mnt/RootMountPoint.java @@ -21,7 +21,7 @@ import android.content.Context; import com.google.android.diskusage.utils.IOHelper; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; import java.io.BufferedReader; import java.util.ArrayList; import java.util.HashMap; @@ -82,11 +82,11 @@ public static void initMountPoints(Context context) { String line; while ((line = reader.readLine()) != null) { checksum += line.length(); - Logger.getLOGGER().d("RootMountPoint.initMountPoints(): Line: %s", line); + Timber.v("initMountPoints: Line: %s", line); String[] parts = line.split(" +"); if (parts.length < 3) continue; String mountPoint = parts[1]; - Logger.getLOGGER().d("RootMountPoint.initMountPoints(): Mount point: " + mountPoint); + Timber.v("initMountPoints: Mount point: %s", mountPoint); String fsType = parts[2]; if (!mountPoint.startsWith("/mnt/asec/")) { @@ -97,7 +97,7 @@ public static void initMountPoints(Context context) { } reader.close(); } catch (Exception e) { - Logger.getLOGGER().e("RootMountPoint.initMountPoints(): Failed to get mount points", e); + Timber.e(e, "initMountPoints: Failed to get mount points"); } } diff --git a/app/src/main/java/com/google/android/diskusage/filesystem/mnt/VolumePathHelper.java b/app/src/main/java/com/google/android/diskusage/filesystem/mnt/VolumePathHelper.java new file mode 100644 index 00000000..10da4b56 --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/filesystem/mnt/VolumePathHelper.java @@ -0,0 +1,54 @@ +/* + * DiskUsage - displays sdcard usage on android. + * Copyright (C) 2008-2011 Ivan Volosyuk + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + */ + +package com.google.android.diskusage.filesystem.mnt; + +import java.io.File; + +/** + * Pure-Java path helpers used by {@link MountPoint}. They are free of Android + * dependencies so that the volume-path handling is covered by JVM unit tests. + */ +public final class VolumePathHelper { + + private VolumePathHelper() { + } + + /** + * Turns {@code /storage/1234-ABCD/Android/data//files} into + * {@code /storage/1234-ABCD}. Returns {@code null} for {@code null} input. + */ + public static String stripAppFilesSuffix(String path, String packageName) { + if (path == null) return null; + if (packageName != null) { + String suffix = "/Android/data/" + packageName + "/files"; + if (path.endsWith(suffix)) { + return path.substring(0, path.length() - suffix.length()); + } + } + int idx = path.indexOf("/Android/data/"); + if (idx > 0) return path.substring(0, idx); + return path; + } + + /** + * Stable comparison key for volume paths. Two paths pointing at the same + * directory (e.g. {@code /sdcard} and {@code /storage/emulated/0}) must not be + * listed twice. + */ + public static String canonical(String path) { + if (path == null) return null; + try { + return new File(path).getCanonicalPath(); + } catch (Exception e) { + return path; + } + } +} diff --git a/app/src/main/java/com/google/android/diskusage/opengl/AbstractRenderingThread.java b/app/src/main/java/com/google/android/diskusage/opengl/AbstractRenderingThread.java index fadffa44..694e910f 100644 --- a/app/src/main/java/com/google/android/diskusage/opengl/AbstractRenderingThread.java +++ b/app/src/main/java/com/google/android/diskusage/opengl/AbstractRenderingThread.java @@ -1,7 +1,7 @@ package com.google.android.diskusage.opengl; import android.view.SurfaceHolder; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; import java.util.ArrayList; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; @@ -64,9 +64,9 @@ public void run() { } } catch (ExitException e) { - Logger.getLOGGER().e("AbstractRenderingThread.run(): Rendering thread exited cleanly", e); + Timber.d(e, "run: rendering thread stopped"); } catch (InterruptedException e) { - Logger.getLOGGER().e("AbstractRenderingThread.run(): Rendering thread was interrupted", e); + Timber.d(e, "run: rendering thread was interrupted"); } } @@ -78,7 +78,7 @@ public void runEvents() throws InterruptedException { synchronized (events) { if (events.isEmpty()) { if (stopRenderingThread && !surfaceAvailable) { - Logger.getLOGGER().d("*** Rendering thread is about to finish. ***"); + Timber.d("*** Rendering thread is about to finish. ***"); throw new ExitException(); } if (surfaceAvailable && sizeInitialized && !stopRenderingThread @@ -183,7 +183,7 @@ public GL10 getGL() { } public void initSurface(SurfaceHolder holder) { - Logger.getLOGGER().d("*** Init Surface ****"); + Timber.d("*** Init Surface ****"); // Note: I haven't found how to avoid race condition with surfaceCreated // and surfaceDestroyed in SurfaceHolder.Callback and the renderer thread. @@ -191,12 +191,12 @@ public void initSurface(SurfaceHolder holder) { surface = egl.eglCreateWindowSurface(eglDisplay, eglConfig, holder, null); egl.eglMakeCurrent(eglDisplay, surface, surface, eglContext); } catch (Exception e) { - Logger.getLOGGER().e("AbstractRenderingThread.initSurface()", e); + Timber.e(e, "initSurface"); } } public void destroySurface(SurfaceHolder holder) { - Logger.getLOGGER().d("*** Destroy Surface ***"); + Timber.d("*** Destroy Surface ***"); try { egl.eglMakeCurrent(eglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, @@ -205,7 +205,7 @@ public void destroySurface(SurfaceHolder holder) { egl.eglDestroyContext(eglDisplay, eglContext); egl.eglTerminate(eglDisplay); } catch (Exception e) { - Logger.getLOGGER().e("AbstractRenderingThread.destroySurface()", e); + Timber.e(e, "destroySurface"); } } diff --git a/app/src/main/java/com/google/android/diskusage/opengl/FileSystemViewGPU.java b/app/src/main/java/com/google/android/diskusage/opengl/FileSystemViewGPU.java index 0317a3f8..a7c260b0 100644 --- a/app/src/main/java/com/google/android/diskusage/opengl/FileSystemViewGPU.java +++ b/app/src/main/java/com/google/android/diskusage/opengl/FileSystemViewGPU.java @@ -12,7 +12,7 @@ import com.google.android.diskusage.ui.FileSystemState; import com.google.android.diskusage.ui.FileSystemState.FileSystemView; import com.google.android.diskusage.ui.FileSystemState.MyMotionEvent; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; public final class FileSystemViewGPU extends SurfaceView implements FileSystemView, SurfaceHolder.Callback { @@ -25,7 +25,7 @@ public FileSystemViewGPU(Context context, @NonNull FileSystemState eventHandler) this.eventHandler = eventHandler; setFocusable(true); setFocusableInTouchMode(true); - Logger.getLOGGER().d("new FileSystemViewGPU"); + Timber.d("new FileSystemViewGPU"); // setBackgroundColor(Color.GRAY); SurfaceHolder holder = getHolder(); @@ -87,7 +87,7 @@ protected final void onLayout(boolean changed, int left, int top, int right, int @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { - Logger.getLOGGER().d("Surface changed to: %s x %s", width, height); + Timber.d("Surface changed to: %s x %s", width, height); thread.addEvent(thread.new SurfaceChangedEvent(holder, width, height)); requestRepaintGPU(); } @@ -105,7 +105,7 @@ public void surfaceDestroyed(@NonNull SurfaceHolder holder) { @Override protected void onDetachedFromWindow() { - Logger.getLOGGER().d("FileSystemViewGPU.onDetachedFromWindow"); + Timber.d("FileSystemViewGPU.onDetachedFromWindow"); super.onDetachedFromWindow(); thread.addEvent(thread.new ExitEvent()); } diff --git a/app/src/main/java/com/google/android/diskusage/opengl/RenderingThread.java b/app/src/main/java/com/google/android/diskusage/opengl/RenderingThread.java index ccaf8af2..499ea2ef 100644 --- a/app/src/main/java/com/google/android/diskusage/opengl/RenderingThread.java +++ b/app/src/main/java/com/google/android/diskusage/opengl/RenderingThread.java @@ -14,7 +14,7 @@ import com.google.android.diskusage.R; import com.google.android.diskusage.filesystem.entity.FileSystemEntry; import com.google.android.diskusage.ui.FileSystemState; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; @@ -98,7 +98,7 @@ public void updateFonts(@NonNull Context context) { int min = Math.min(width, height); float minInch = min / dpi; // my tablet: 5 inch height // my phone: 2 inc width - Logger.getLOGGER().d("RenderingThread.updateFonts(): Screen inch = %s", minInch); + Timber.d("updateFonts: Screen inch = %s", minInch); float defaultSize = textPaint.getTextSize(); textPaint.setTextSize(20); @@ -666,13 +666,13 @@ public boolean renderFrame(@NonNull GL10 gl) { @Override public void createResources(GL10 gl) { - Logger.getLOGGER().d("***** Surface Created *****"); + Timber.d("***** Surface Created *****"); // Load textures LoadTextures(gl); } public void releaseResources(GL10 gl) { - Logger.getLOGGER().d("***** Surface Destroyed *****"); + Timber.d("***** Surface Destroyed *****"); for (BitmapMap bitmap : bitmaps) { bitmap.destroy(); } @@ -682,7 +682,7 @@ public void releaseResources(GL10 gl) { @Override public void sizeChanged(@NonNull GL10 gl, int width, int height) { - Logger.getLOGGER().d("***** Surface Size Changed *****"); + Timber.d("***** Surface Size Changed *****"); // FileSystemEntry.elementWidth = 100;// FIXME??; // FileSystemEntry.fontSize = 20; // FIXME eventHandler.layout(true, 0, 0, width, height, width, height); @@ -691,7 +691,7 @@ public void sizeChanged(@NonNull GL10 gl, int width, int height) { gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glViewport(0, 0, width, height); - Logger.getLOGGER().d("RenderingThread.sizeChanged(): Updated viewport = %s x %s", width, height); + Timber.d("sizeChanged: Updated viewport = %s x %s", width, height); gl.glMatrixMode(GL10.GL_PROJECTION); diff --git a/app/src/main/java/com/google/android/diskusage/ui/DeleteActivity.java b/app/src/main/java/com/google/android/diskusage/ui/DeleteActivity.java index 8c5ed08c..c3fba7f0 100644 --- a/app/src/main/java/com/google/android/diskusage/ui/DeleteActivity.java +++ b/app/src/main/java/com/google/android/diskusage/ui/DeleteActivity.java @@ -19,56 +19,89 @@ package com.google.android.diskusage.ui; -import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.MenuItem; import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.recyclerview.widget.LinearLayoutManager; import com.google.android.diskusage.R; import com.google.android.diskusage.databinding.DeleteViewBinding; import com.google.android.diskusage.filesystem.entity.FileSystemEntry; +import com.google.android.diskusage.ui.common.EdgeToEdge; +import com.google.android.diskusage.ui.common.FileInfo; import com.google.android.diskusage.ui.common.FileInfoAdapter; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; +import java.io.File; +import java.util.ArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; -public class DeleteActivity extends Activity { +/** + * Confirmation screen that lists the content which is about to be removed. + * The listing runs off the UI thread so that huge directories don't cause an + * ANR (issue: "can not delete & scan is slow"). + */ +public class DeleteActivity extends AppCompatActivity { public static final String NUM_FILES_KEY = "numFiles"; public static final String SIZE_KEY = "size"; - + + private static final ExecutorService LISTING_EXECUTOR = Executors.newSingleThreadExecutor(); + Intent responseIntent; + private DeleteViewBinding binding; @Override protected void onResume() { super.onResume(); -// Debug.startMethodTracing("diskusage"); + EdgeToEdge.enable(this); FileSystemEntry.setupStrings(this); - final String path = getIntent().getStringExtra( - DiskUsage.DELETE_PATH_KEY); - final String absolutePath = getIntent().getStringExtra( - DiskUsage.DELETE_ABSOLUTE_PATH_KEY); - Logger.getLOGGER().d("DeleteActivity.onResume(): %s -> %s", path, absolutePath); + final String path = getIntent().getStringExtra(DiskUsage.DELETE_PATH_KEY); + final String absolutePath = getIntent().getStringExtra(DiskUsage.DELETE_ABSOLUTE_PATH_KEY); + Timber.d("onResume: %s -> %s", path, absolutePath); - DeleteViewBinding binding = DeleteViewBinding.inflate(getLayoutInflater()); + binding = DeleteViewBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); + EdgeToEdge.applyInsets(binding.getRoot()); + setSupportActionBar(binding.toolbar); + setTitle(R.string.button_delete); + String sizeString = getIntent().getStringExtra(SIZE_KEY); int count = getIntent().getIntExtra(NUM_FILES_KEY, 0); - FileInfoAdapter.setMessage( - this, binding.summary, count, sizeString); + binding.summary.setText(getString(R.string.delete_summary, count, sizeString)); + + final File file = new File(absolutePath); + binding.list.setLayoutManager(new LinearLayoutManager(this)); + + LISTING_EXECUTOR.execute(() -> { + final ArrayList infos = new ArrayList<>(); + if (file.exists()) { + collect(file, infos, 0); + } + runOnUiThread(() -> { + if (isFinishing() || isDestroyed()) return; + binding.list.setAdapter(new FileInfoAdapter(infos)); + }); + }); responseIntent = new Intent(); responseIntent.putExtra(DiskUsage.DELETE_PATH_KEY, path); - binding.list.setAdapter(new FileInfoAdapter( - this, - absolutePath, - count, - binding.summary)); - /* binding.okButton.setOnClickListener(view -> { - setResult(DiskUsage.RESULT_DELETE_CONFIRMED, responseIntent); - finish(); - }); - binding.cancelButton.setOnClickListener(view -> { - setResult(DiskUsage.RESULT_DELETE_CANCELED); - finish(); - }); **/ + } + + /** Depth-limited listing: enough to recognise the content, bounded memory. */ + private static void collect(File file, ArrayList infos, int depth) { + File[] children = file.listFiles(); + if (children == null) return; + for (File sub : children) { + if (sub.isDirectory()) { + infos.add(new FileInfo("", sub.getName())); + if (depth < 3) { + collect(sub, infos, depth + 1); + } + } else if (sub.isFile()) { + infos.add(new FileInfo(FileSystemEntry.calcSizeString(sub.length()), sub.getName())); + } + } } @Override @@ -91,11 +124,4 @@ public boolean onOptionsItemSelected(@NonNull MenuItem item) { } return super.onOptionsItemSelected(item); } - - /* - @Override - protected void onPause() { - super.onPause(); - // Debug.stopMethodTracing(); - } **/ } diff --git a/app/src/main/java/com/google/android/diskusage/ui/DiskUsage.java b/app/src/main/java/com/google/android/diskusage/ui/DiskUsage.java index 90e3b72d..98c004b9 100644 --- a/app/src/main/java/com/google/android/diskusage/ui/DiskUsage.java +++ b/app/src/main/java/com/google/android/diskusage/ui/DiskUsage.java @@ -20,21 +20,24 @@ package com.google.android.diskusage.ui; import android.app.ActivityManager; -import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; -import android.content.pm.ResolveInfo; +import android.content.ClipData; import android.net.Uri; +import android.os.Environment; +import android.provider.DocumentsContract; import android.os.Build; import android.os.Bundle; -import android.os.FileUriExposedException; import android.os.Handler; import android.provider.Settings; import androidx.annotation.NonNull; +import androidx.activity.OnBackPressedCallback; +import androidx.appcompat.app.AlertDialog; import androidx.core.content.FileProvider; +import androidx.lifecycle.ViewModelProvider; import android.util.Log; import android.view.Menu; @@ -60,8 +63,9 @@ import com.google.android.diskusage.filesystem.entity.FileSystemRoot; import com.google.android.diskusage.filesystem.entity.FileSystemSuperRoot; import com.google.android.diskusage.filesystem.entity.FileSystemSystemSpace; +import com.google.android.diskusage.ui.common.EdgeToEdge; import com.google.android.diskusage.ui.common.ScanProgressDialog; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; import org.jetbrains.annotations.Contract; import java.io.File; @@ -69,7 +73,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import java.util.List; +import java.util.Locale; + import splitties.toast.ToastKt; public class DiskUsage extends LoadableActivity { @@ -88,16 +93,32 @@ public class DiskUsage extends LoadableActivity { private String pathToDelete; - public DiskUsageMenu menu = DiskUsageMenu.getInstance(this); + public DiskUsageMenu menu = new DiskUsageMenu(this); RendererManager rendererManager = new RendererManager(this); @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); - Logger.getLOGGER().d("DiskUsage.onCreate()"); + final DiskUsageViewModel viewModel = new ViewModelProvider(this).get(DiskUsageViewModel.class); + Timber.d("DiskUsage.onCreate()"); + EdgeToEdge.enable(this); ActivityCommonBinding binding = ActivityCommonBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); - menu.onCreate(); + EdgeToEdge.applyInsets(binding.getRoot()); + binding.toolbar.setVisibility(android.view.View.VISIBLE); + setSupportActionBar(binding.toolbar); + menu.onCreate(viewModel); + + // Handle back ourselves: with Android 13+ predictive back the framework no + // longer delivers KEYCODE_BACK to the view, so the old handler in + // FileSystemState never ran and the app fell back to "finish DiskUsage", + // which surfaced the volume chooser again. + getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) { + @Override + public void handleOnBackPressed() { + finishOnBack(); + } + }); Intent i = getIntent(); @@ -114,8 +135,9 @@ protected void onCreate(Bundle icicle) { finish(); return; } - Logger.getLOGGER().d("DiskUsage.onCreate(), rootPath = %s, receivedState = %s", + Timber.d("DiskUsage.onCreate(), rootPath = %s, receivedState = %s", mountPoint.getRoot(), receivedState); + setTitle(mountPoint.getTitle()); if (receivedState != null) onRestoreInstanceState(receivedState); } @@ -179,7 +201,8 @@ public void onActivityResult(int a, int result, Intent i) { @Override public boolean onCreateOptionsMenu(Menu menu) { - return super.onCreateOptionsMenu(menu); + this.menu.setupToolbarMenu(menu); + return true; } private static abstract class VersionedPackageViewer { @@ -194,7 +217,7 @@ public static VersionedPackageViewer newInstance(DiskUsage context) { private final class GingerbreadPackageViewer extends VersionedPackageViewer { @Override void viewPackage(String pkg) { - Logger.getLOGGER().d("Show package = %s", pkg); + Timber.d("Show package = %s", pkg); Intent viewIntent = new Intent( Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + pkg)); @@ -223,7 +246,7 @@ void continueDelete(String path) { public void askForDeletion(@NonNull final FileSystemEntry entry) { final String path = entry.path2(); final String fullPath = entry.absolutePath(); - Logger.getLOGGER().d("Deletion requested for %s", path); + Timber.d("Deletion requested for %s", path); if (entry instanceof FileSystemEntrySmall) { ToastKt.toast("Delete directory instead"); @@ -256,17 +279,16 @@ public void askForDeletion(@NonNull final FileSystemEntry entry) { } } - public boolean isIntentAvailable(Intent intent) { - final PackageManager packageManager = getPackageManager(); - List res = packageManager.queryIntentActivities( - intent, PackageManager.MATCH_DEFAULT_ONLY); - return res.size() > 0; - } - + /** + * Opens the selected entry in an external application. + * + * Android 11+ requires a content URI plus an explicit read grant; the old + * code used a file:// URI, a bogus "binary/octet-stream" fallback and a + * provider whose paths didn't cover removable volumes. That combination is + * the root cause of the "no viewer found" and "video opens in a strange + * mode" reports. + */ public void view(FileSystemEntry entry) { - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.addCategory(Intent.CATEGORY_DEFAULT); - if (entry instanceof FileSystemEntrySmall) { entry = entry.parent; } @@ -279,93 +301,160 @@ public void view(FileSystemEntry entry) { return; } - String path = entry.absolutePath(); - File file = new File(path); - Uri uri = Uri.fromFile(file); + final String path = entry.absolutePath(); + final File file = new File(path); + if (!file.exists()) { + ToastKt.toast(getString(R.string.path_doesnt_exist, path)); + return; + } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + final Uri uri; + try { uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file); + } catch (IllegalArgumentException e) { + Timber.w(e, "No provider path configured for %s", path); + ToastKt.toast(R.string.no_viewer_found); + return; } if (file.isDirectory()) { - // Go on with default file manager - // Shoud this be optional? - intent = new Intent(Intent.ACTION_VIEW); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - intent.setDataAndType(uri, "inode/directory"); - - try { - startActivity(intent); - return; - } catch (ActivityNotFoundException ignored) { - } - - intent = new Intent("org.openintents.action.VIEW_DIRECTORY"); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - intent.setData(uri); - - try { - startActivity(intent); - return; - } catch (ActivityNotFoundException|FileUriExposedException ignored) { - } - - intent = new Intent("org.openintents.action.PICK_DIRECTORY"); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - intent.setData(uri); - intent.putExtra("org.openintents.extra.TITLE", - getString(R.string.title_in_oi_file_manager)); - intent.putExtra("org.openintents.extra.BUTTON_TEXT", - getString(R.string.button_text_in_oi_file_manager)); - - try { - startActivity(intent); - return; - } catch (ActivityNotFoundException|FileUriExposedException ignored) { - } + viewDirectory(uri, file); + return; + } - // old Astro - intent = new Intent(Intent.ACTION_VIEW); - intent.addCategory(Intent.CATEGORY_DEFAULT); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - intent.setDataAndType(uri, "vnd.android.cursor.item/com.metago.filemanager.dir"); + if (startViewIntent(uri, file.getName(), guessMimeType(file.getName()))) return; + // Unknown extension or no handler for the specific type: let the user pick. + if (startViewIntent(uri, file.getName(), "*/*")) return; + ToastKt.toast(R.string.no_viewer_found); + } - try { - startActivity(intent); - return; - } catch (ActivityNotFoundException|FileUriExposedException ignored) { - } + private static String guessMimeType(String fileName) { + int dot = fileName.lastIndexOf('.'); + if (dot < 0 || dot == fileName.length() - 1) return null; + String extension = fileName.substring(dot + 1).toLowerCase(Locale.ROOT); + return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); + } - ToastKt.toast(R.string.no_viewer_found); + private boolean startViewIntent(Uri uri, String name, String mime) { + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.addCategory(Intent.CATEGORY_DEFAULT); + intent.setDataAndType(uri, mime == null ? "*/*" : mime); + intent.setClipData(ClipData.newRawUri(name, uri)); + // Our own FileProvider URI: the viewer needs an explicit read grant. + intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + return startViewIntent(intent); + } + + private boolean startViewIntent(@NonNull Intent intent) { + // No FLAG_GRANT_READ_URI_PERMISSION here: the caller decides. Granting read + // access for a URI we do not own (e.g. the system documents provider) makes + // UriGrantsManagerService throw a SecurityException, which used to silently + // fall back to a useless chooser. + try { + startActivity(intent); + return true; + } catch (ActivityNotFoundException | SecurityException e) { + Timber.d(e, "No activity for %s", intent); + return false; + } + } + + /** + * Opens a directory in a file manager. + * + * Android has no standard "show this folder" intent, and most file managers + * do not register for a {@code content://} URI of a foreign provider. The + * reliable route is the system documents provider: a document URI of the + * "externalstorage" provider plus {@code vnd.android.document/directory} opens + * the preinstalled Files app directly at that folder. The generic intents are + * still tried first-but-one so third-party managers keep working, and a + * copy-path dialog is offered when nothing can handle the folder. + */ + private void viewDirectory(Uri uri, @NonNull File folder) { + Intent documents = documentsIntent(folder); + Timber.d("viewDirectory: folder=%s documentsIntent=%s", folder, documents); + if (documents != null) { + boolean started = startViewIntent(documents); + Timber.d("viewDirectory: documents intent started=%s", started); + if (started) return; + } + + // Third-party file managers that accept any provider (Material Files & co). + for (String mime : new String[] {"resource/folder", "inode/directory"}) { + if (startViewIntent(uri, folder.getName(), mime)) return; + } + + // Legacy integrations (OI File Manager, Astro, ...). + Intent intent = new Intent("org.openintents.action.VIEW_DIRECTORY"); + intent.setData(uri); + intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + intent.setClipData(ClipData.newRawUri("folder", uri)); + try { + startActivity(intent); return; + } catch (ActivityNotFoundException | SecurityException ignored) { } - String fileName = entry.name; - int dot = fileName.lastIndexOf("."); - Log.d("diskusage", "name: " + fileName + " path: " + path + " dot: " + dot); - if (dot != -1) { - String extension = fileName.substring(dot + 1).toLowerCase(); + showNoFileManagerDialog(folder.getAbsolutePath()); + } - MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); - String mime = mimeTypeMap.getMimeTypeFromExtension(extension); - Log.d("diskusage", "extension: " + extension + " mime: " + mime); + /** + * Builds a {@code content://com.android.externalstorage.documents/...} URI for + * [folder], which the system Files app (DocumentsUI) understands. + * Returns null for paths outside the shared storage volumes. + */ + private Intent documentsIntent(@NonNull File folder) { + final String path = folder.getAbsolutePath(); + String docId = null; - try { - intent = new Intent(Intent.ACTION_VIEW); - intent.addCategory(Intent.CATEGORY_DEFAULT); - if (mime != null) { - intent.setDataAndType(uri, mime); - } else { - intent.setDataAndType(uri, "binary/octet-stream"); - } - intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); - startActivity(intent); - return; - } catch (ActivityNotFoundException|FileUriExposedException ignored) { - Log.e("diskusage", "Can't open viewer and crash", ignored); + File primary = Environment.getExternalStorageDirectory(); + if (primary != null) { + String primaryPath = primary.getAbsolutePath(); + if (path.equals(primaryPath)) { + docId = "primary:"; + } else if (path.startsWith(primaryPath + "/")) { + docId = "primary:" + path.substring(primaryPath.length() + 1); } } - ToastKt.toast(R.string.no_viewer_found); + if (docId == null && path.startsWith("/storage/")) { + // Removable / USB volume: /storage// + String[] parts = path.split("/", 4); + if (parts.length >= 3 && parts[2].length() > 0 && !parts[2].equals("emulated") + && !parts[2].equals("self")) { + docId = parts[2] + ":" + (parts.length > 3 ? parts[3] : ""); + } + } + if (docId == null) return null; + + try { + Uri documentUri = + DocumentsContract.buildDocumentUri("com.android.externalstorage.documents", docId); + Intent intent = new Intent(Intent.ACTION_VIEW); + // The provider manages its own permissions; adding a read grant for a + // foreign URI would throw a SecurityException in UriGrantsManagerService. + intent.setDataAndType(documentUri, DocumentsContract.Document.MIME_TYPE_DIR); + return intent; + } catch (Throwable t) { + Timber.w(t, "Cannot build documents URI for %s", path); + return null; + } + } + + /** Nothing could open the folder: at least let the user copy the path. */ + private void showNoFileManagerDialog(final String path) { + new AlertDialog.Builder(this) + .setTitle(R.string.no_viewer_found) + .setMessage(getString(R.string.no_file_manager_found_desc, path)) + .setPositiveButton(R.string.button_copy_path, (dialog, which) -> { + android.content.ClipboardManager clipboard = + (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); + if (clipboard != null) { + clipboard.setPrimaryClip(ClipData.newPlainText("path", path)); + ToastKt.toast(R.string.path_copied); + } + }) + .setNegativeButton(android.R.string.cancel, null) + .show(); } public void rescan() { @@ -382,7 +471,15 @@ public void finishOnBack() { result.putExtra(DiskUsage.STATE_KEY, outState); result.putExtra(DiskUsage.KEY_KEY, key); setResult(0, result); - finish(); + + if (MountPoint.getMountPoints(this).size() > 1) { + // More than one volume: go back to the chooser so the user can switch. + finish(); + } else { + // Single volume: back means "leave the app". The task (and with it the + // scan result) is kept, so reopening is instant. + moveTaskToBack(true); + } } public void setSelectedEntity(FileSystemEntry position) { @@ -410,7 +507,7 @@ protected void onSaveInstanceState(@NonNull Bundle outState) { @Override protected void onRestoreInstanceState(@NonNull final Bundle inState) { - Logger.getLOGGER().d("DiskUsage.onRestoreInstanceState(), rootPath = %s", inState.getString(KEY_KEY)); + Timber.d("DiskUsage.onRestoreInstanceState(), rootPath = %s", inState.getString(KEY_KEY)); if (fileSystemState != null) fileSystemState.restoreStateInRenderThread(inState); @@ -441,7 +538,7 @@ class MemoryClassDetected extends MemoryClass { @Override int maxHeap() { ActivityManager manager = (ActivityManager) DiskUsage.this.getSystemService(Context.ACTIVITY_SERVICE); - return manager.getMemoryClass() * 1024 * 1024; + return manager.getLargeMemoryClass() * 1024 * 1024; } } MemoryClass memoryClass = MemoryClass.getInstance(this); @@ -463,7 +560,7 @@ public FileSystemStats(@NonNull MountPoint mountPoint) { try { stats = new StatFsSourceImpl(mountPoint.getRoot()); } catch (IllegalArgumentException e) { - Logger.getLOGGER().e(e, "Failed to get filesystem stats for " + mountPoint.getRoot()); + Timber.e(e, "Failed to get filesystem stats for " + mountPoint.getRoot()); } if (stats != null) { blockSize = stats.getBlockSizeLong(); @@ -475,11 +572,15 @@ public FileSystemStats(@NonNull MountPoint mountPoint) { blockSize = 512; } } - public String formatUsageInfo() { - if (totalBlocks == 0) return "Used "; - return String.format("Used %s of %s", - FileSystemEntry.calcSizeString(busyBlocks * blockSize), - FileSystemEntry.calcSizeString(totalBlocks * blockSize)); + public String formatUsageInfo(Context context) { + if (totalBlocks == 0) return context.getString(R.string.usage_info_unknown); + long usedBytes = busyBlocks * blockSize; + long totalBytes = totalBlocks * blockSize; + int percent = totalBytes > 0 ? (int) (usedBytes * 100 / totalBytes) : 0; + return context.getString(R.string.usage_info, + FileSystemEntry.calcSizeString(usedBytes), + FileSystemEntry.calcSizeString(totalBytes), + percent); } } @@ -523,7 +624,11 @@ FileSystemSuperRoot scan() throws IOException, InterruptedException { handler.post(progressUpdater); rootElement = scanner.scan(mountPoint); handler.removeCallbacks(progressUpdater); - } catch (RuntimeException e) { + if (rootElement == null || rootElement.children == null) { + throw new IOException("Native scanner returned no data"); + } + } catch (IOException | RuntimeException e) { + Timber.w(e, "Native scan failed, falling back to the Java scanner"); final Scanner scanner = new Scanner(20, stats.blockSize, stats.busyBlocks, heap); progressUpdater = makeProgressUpdater(scanner, stats); handler.post(progressUpdater); @@ -580,7 +685,7 @@ protected FileSystemEntry[] loadApps2SD(long blockSize) { try { return (new Apps2SDLoader(this).load(blockSize)); } catch (Throwable t) { - Logger.getLOGGER().e("DiskUsage.loadApps2SD(): Problem loading apps2sd info", t); + Timber.e(t, "loadApps2SD: Problem loading apps2sd info"); return null; } } @@ -599,92 +704,79 @@ void moveIntoPackage(FileSystemPackage pkg, } } - void moveAppData(@NonNull FileSystemEntry[] apps, FileSystemRoot media, long blockSize) { - String diskusage = "com.google.android.diskusage"; - for (FileSystemEntry a : apps) { - FileSystemPackage app = (FileSystemPackage) a; - try { - String cacheDir = getCacheDir().getCanonicalPath().replaceAll(diskusage, app.pkg); - moveIntoPackage(app, media, cacheDir, "Cache", FileSystemPackage.ChildType.CACHE, blockSize); - } catch (IOException ignored) { - } - } - for (FileSystemEntry a : apps) { - FileSystemPackage app = (FileSystemPackage) a; - try { - String dir = getCodeCacheDir().getCanonicalPath().replaceAll(diskusage, app.pkg); - moveIntoPackage(app, media, dir, "CodeCache", FileSystemPackage.ChildType.CACHE, blockSize); - } catch (IOException ignored) { - } - } - for (FileSystemEntry a : apps) { - FileSystemPackage app = (FileSystemPackage) a; - try { - String dir = getExternalCacheDir().getCanonicalPath().replaceAll(diskusage, app.pkg); - moveIntoPackage(app, media, dir, "ExternalCache", FileSystemPackage.ChildType.CACHE, blockSize); - } catch (IOException ignored) { - } - } - for (FileSystemEntry a : apps) { - FileSystemPackage app = (FileSystemPackage) a; - try { - String dir = getDataDir().getCanonicalPath().replaceAll(diskusage, app.pkg); - moveIntoPackage(app, media, dir, "Data", FileSystemPackage.ChildType.DATA, blockSize); - } catch (IOException ignored) { - } - } - for (FileSystemEntry a : apps) { - FileSystemPackage app = (FileSystemPackage) a; - try { - String dir = getFilesDir().getCanonicalPath().replaceAll(diskusage, app.pkg); - moveIntoPackage(app, media, dir, "InternalFiles", FileSystemPackage.ChildType.DATA, blockSize); - } catch (IOException ignored) { - } + /** + * Canonical path of a possibly absent directory, or null. + * + * `Context.getExternalCacheDir()`, `getObbDirs()` and friends return null when + * the volume is not ready (storage full, external storage just reset, MIUI + * blocking the app dir). The previous code called `getCanonicalPath()` on the + * result and crashed with a NullPointerException, which aborted the whole + * application list. + */ + private static String canonicalPath(File file) { + if (file == null) return null; + try { + return file.getCanonicalPath(); + } catch (IOException e) { + return null; } + } - for (FileSystemEntry a : apps) { - FileSystemPackage app = (FileSystemPackage) a; - try { - String dir = getExternalFilesDir(null).getCanonicalPath().replaceAll(diskusage, app.pkg); - moveIntoPackage(app, media, dir, "Files", FileSystemPackage.ChildType.DATA, blockSize); - } catch (IOException ignored) { + private void moveAppDirectory(FileSystemEntry[] apps, FileSystemRoot media, + String sourcePath, String newName, + FileSystemPackage.ChildType type, long blockSize) { + if (sourcePath == null) return; + try { + for (FileSystemEntry a : apps) { + if (!(a instanceof FileSystemPackage)) continue; + FileSystemPackage app = (FileSystemPackage) a; + String dir = sourcePath.replace(diskUsagePackage, app.pkg); + moveIntoPackage(app, media, dir, newName, type, blockSize); } + } catch (Throwable t) { + Timber.w(t, "Cannot map %s for the app list", newName); } - for (FileSystemEntry a : apps) { - FileSystemPackage app = (FileSystemPackage) a; - try { - for (File mediaDir : getExternalMediaDirs()) { - String dir = mediaDir.getCanonicalPath().replaceAll(diskusage, app.pkg); - moveIntoPackage(app, media, dir, "MediaFiles", FileSystemPackage.ChildType.DATA, blockSize); - } - } catch (IOException ignored) { - } + } + + private static final String diskUsagePackage = "com.google.android.diskusage"; + + void moveAppData(@NonNull FileSystemEntry[] apps, FileSystemRoot media, long blockSize) { + moveAppDirectory(apps, media, canonicalPath(getCacheDir()), + "Cache", FileSystemPackage.ChildType.CACHE, blockSize); + moveAppDirectory(apps, media, canonicalPath(getCodeCacheDir()), + "CodeCache", FileSystemPackage.ChildType.CACHE, blockSize); + moveAppDirectory(apps, media, canonicalPath(getExternalCacheDir()), + "ExternalCache", FileSystemPackage.ChildType.CACHE, blockSize); + moveAppDirectory(apps, media, canonicalPath(getDataDir()), + "Data", FileSystemPackage.ChildType.DATA, blockSize); + moveAppDirectory(apps, media, canonicalPath(getFilesDir()), + "InternalFiles", FileSystemPackage.ChildType.DATA, blockSize); + moveAppDirectory(apps, media, canonicalPath(getExternalFilesDir(null)), + "Files", FileSystemPackage.ChildType.DATA, blockSize); + + for (File mediaDir : getExternalMediaDirs()) { + if (mediaDir == null) continue; + moveAppDirectory(apps, media, canonicalPath(mediaDir), + "MediaFiles", FileSystemPackage.ChildType.DATA, blockSize); + } + for (File obbDir : getObbDirs()) { + if (obbDir == null) continue; + moveAppDirectory(apps, media, canonicalPath(obbDir), + "Obb", FileSystemPackage.ChildType.CODE, blockSize); } + for (FileSystemEntry a : apps) { - FileSystemPackage app = (FileSystemPackage) a; + if (!(a instanceof FileSystemPackage)) continue; + FileSystemPackage app = (FileSystemPackage) a; try { - for (File mediaDir : getObbDirs()) { - String dir = mediaDir.getCanonicalPath().replaceAll(diskusage, app.pkg); - moveIntoPackage(app, media, dir, "Obb", FileSystemPackage.ChildType.CODE, blockSize); - } - } catch (IOException ignored) { + app.applyFilter(blockSize); + } catch (Throwable t) { + Timber.w(t, "Cannot finalise app entry %s", app.pkg); } } - - for (FileSystemEntry a : apps) { - FileSystemPackage app = (FileSystemPackage) a; - app.applyFilter(blockSize); - } Arrays.sort(apps, FileSystemEntry.COMPARE); } - @Override - public boolean onPrepareOptionsMenu(Menu menu) { - super.onPrepareOptionsMenu(menu); - this.menu.onPrepareOptionsMenu(menu); - return true; - } - @Override public String getKey() { return key; diff --git a/app/src/main/java/com/google/android/diskusage/ui/DiskUsageMenu.java b/app/src/main/java/com/google/android/diskusage/ui/DiskUsageMenu.java deleted file mode 100644 index 9556b43c..00000000 --- a/app/src/main/java/com/google/android/diskusage/ui/DiskUsageMenu.java +++ /dev/null @@ -1,205 +0,0 @@ -package com.google.android.diskusage.ui; - -import android.content.pm.PackageManager; -import android.graphics.BitmapFactory; -import android.os.Bundle; -import android.os.Process; -import android.text.Html; -import android.text.method.LinkMovementMethod; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import androidx.annotation.NonNull; -import android.app.AlertDialog; -import com.google.android.diskusage.R; -import com.google.android.diskusage.databinding.AboutDialogBinding; -import com.google.android.diskusage.datasource.SearchManager; -import com.google.android.diskusage.filesystem.entity.FileSystemEntry; -import com.google.android.diskusage.filesystem.entity.FileSystemSpecial; -import com.google.android.diskusage.filesystem.entity.FileSystemSuperRoot; -import com.google.android.diskusage.filesystem.mnt.MountPoint; -import com.google.android.diskusage.utils.AppIconCache; - -import org.jetbrains.annotations.Contract; - -public abstract class DiskUsageMenu { - public final DiskUsage diskusage; - protected String searchPattern; - private FileSystemEntry selectedEntity; - public FileSystemSuperRoot masterRoot; - SearchManager searchManager = new SearchManager(this); - - protected MenuItem searchMenuItem; - protected MenuItem showMenuItem; - protected MenuItem rescanMenuItem; - protected MenuItem deleteMenuItem; - protected MenuItem rendererMenuItem; - protected MenuItem aboutMenuItem; - - public DiskUsageMenu(DiskUsage diskusage) { - this.diskusage = diskusage; - } - - @NonNull - @Contract("_ -> new") - public static DiskUsageMenu getInstance(DiskUsage diskusage) { - return new DiskUsageMenuHoneycomb(diskusage); - } - - public abstract void onCreate(); - public abstract boolean readyToFinish(); - public abstract void searchRequest(); - public abstract MenuItem makeSearchMenuEntry(Menu menu); - - public final void onSaveInstanceState(@NonNull Bundle outState) { - outState.putString("search", searchPattern); - } - - public final void onRestoreInstanceState(@NonNull Bundle inState) { - searchPattern = inState.getString("search"); - } - - public void wrapAndSetContentView(View view, FileSystemSuperRoot newRoot) { - this.masterRoot = newRoot; - updateMenu(); - } - - public void applyPattern(String searchQuery) { - if (searchQuery == null || masterRoot == null) return; - - if (searchQuery.length() == 0) { - searchManager.cancelSearch(); - finishedSearch(masterRoot, searchQuery); - } else { - searchManager.search(searchQuery); - } - } - - public boolean finishedSearch(FileSystemSuperRoot newRoot, String searchQuery) { - boolean matched = newRoot != null; - if (!matched) newRoot = masterRoot; - diskusage.applyPatternNewRoot(newRoot, searchQuery); - return matched; - } - - public void addRescanMenuEntry(@NonNull Menu menu) { - menu.add(getString(R.string.button_rescan)) - .setOnMenuItemClickListener(item -> { - diskusage.rescan(); - return true; - }); - } - - public void update(FileSystemEntry position) { - this.selectedEntity = position; - updateMenu(); - } - - private String getString(int id) { - return diskusage.getString(id); - } - - public boolean onPrepareOptionsMenu(@NonNull Menu menu) { - menu.clear(); - searchMenuItem = makeSearchMenuEntry(menu); - - showMenuItem = menu.add(getString(R.string.button_show)); - showMenuItem.setOnMenuItemClickListener(item -> { - if (selectedEntity != null) { - diskusage.view(selectedEntity); - } - return true; - }); - rescanMenuItem = menu.add(getString(R.string.button_rescan)); - rescanMenuItem.setOnMenuItemClickListener(item -> { - diskusage.rescan(); - return true; - }); - - deleteMenuItem = menu.add(getString(R.string.button_delete)); - deleteMenuItem.setOnMenuItemClickListener(item -> { - diskusage.askForDeletion(selectedEntity); - return true; - }); - - rendererMenuItem = menu.add("Renderer"); - rendererMenuItem.setVisible(true); - rendererMenuItem.setOnMenuItemClickListener(item -> { - diskusage.rendererManager.switchRenderer(masterRoot); - return true; - }); - - aboutMenuItem = menu.add(R.string.action_about); - aboutMenuItem.setOnMenuItemClickListener(item -> { - final AboutDialogBinding binding = - AboutDialogBinding.inflate(LayoutInflater.from(diskusage), null, false); - binding.sourceCode.setMovementMethod(LinkMovementMethod.getInstance()); - binding.sourceCode.setText(Html.fromHtml(diskusage.getString( - R.string.about_view_source_code, - "GitHub" - )) - ); - binding.icon.setImageBitmap( - AppIconCache.getOrLoadBitmap( - diskusage, - diskusage.getApplicationInfo(), - Process.myUid() / 100000, - diskusage.getResources().getDimensionPixelSize(R.dimen.default_app_icon_size) - ) - ); - try { - binding.versionName.setText(diskusage.getPackageManager().getPackageInfo( - diskusage.getPackageName(), 0 - ).versionName); - } catch (PackageManager.NameNotFoundException e) { - e.printStackTrace(); - } - new AlertDialog.Builder(diskusage) - .setView(binding.getRoot()) - .show(); - return true; - }); - - updateMenu(); - return true; - } - - private void updateMenu() { - if (showMenuItem == null) return; - - if (diskusage.fileSystemState == null) { - searchMenuItem.setEnabled(false); - showMenuItem.setEnabled(false); - rescanMenuItem.setEnabled(false); - deleteMenuItem.setEnabled(false); - rendererMenuItem.setEnabled(false); - return; - } - - if (diskusage.fileSystemState.sdcardIsEmpty()) { - searchMenuItem.setEnabled(false); - showMenuItem.setEnabled(false); - rescanMenuItem.setEnabled(true); - deleteMenuItem.setEnabled(false); - rendererMenuItem.setEnabled(false); - } - - rendererMenuItem.setEnabled(true); - final boolean isGPU = diskusage.fileSystemState.isGPU(); - rendererMenuItem.setTitle(isGPU ? "Software Renderer" : "Hardware Renderer"); - - rescanMenuItem.setEnabled(true); - searchMenuItem.setEnabled(true); - - - boolean view = !(selectedEntity == diskusage.fileSystemState.masterRoot.children[0] - || selectedEntity instanceof FileSystemSpecial); - showMenuItem.setEnabled(view); - - boolean fileOrNotSearching = searchPattern == null || selectedEntity.children == null; - MountPoint mountPoint = MountPoint.getForKey(diskusage, diskusage.getKey()); - deleteMenuItem.setEnabled(view && selectedEntity.isDeletable() - && fileOrNotSearching && mountPoint.isDeleteSupported()); - } -} diff --git a/app/src/main/java/com/google/android/diskusage/ui/DiskUsageMenu.kt b/app/src/main/java/com/google/android/diskusage/ui/DiskUsageMenu.kt new file mode 100644 index 00000000..b8a33906 --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/ui/DiskUsageMenu.kt @@ -0,0 +1,321 @@ +package com.google.android.diskusage.ui + +import android.app.AlertDialog +import android.content.pm.PackageManager +import android.graphics.Color +import android.graphics.drawable.Drawable +import android.os.Build +import android.os.Bundle +import android.os.Process +import android.text.Html +import android.view.LayoutInflater +import android.view.Menu +import android.view.MenuItem +import android.view.View +import android.view.ViewGroup +import android.widget.SearchView +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.forEach +import com.google.android.diskusage.R +import com.google.android.diskusage.databinding.AboutDialogBinding +import com.google.android.diskusage.datasource.SearchManager +import com.google.android.diskusage.filesystem.entity.FileSystemEntry +import com.google.android.diskusage.filesystem.entity.FileSystemSpecial +import com.google.android.diskusage.filesystem.entity.FileSystemSuperRoot +import com.google.android.diskusage.filesystem.mnt.MountPoint +import com.google.android.diskusage.ui.common.Permissions +import com.google.android.diskusage.utils.AppIconCache.getOrLoadBitmap +import com.google.android.diskusage.utils.item +import splitties.resources.styledColor +import timber.log.Timber + +class DiskUsageMenu(val diskusage: DiskUsage) { + var masterRoot: FileSystemSuperRoot? = null + private var searchPattern: String? = null + private val searchManager by lazy { SearchManager(this) } + private var selectedEntity: FileSystemEntry? = null + private var searchView: SearchView? = null + private var origSearchBackground: Drawable? = null + private lateinit var viewModel: DiskUsageViewModel + + fun onCreate(viewModel: DiskUsageViewModel) { + this.viewModel = viewModel +// val actionBar = checkNotNull(diskusage.actionBar) +// actionBar.setDisplayHomeAsUpEnabled(true) + } + + fun readyToFinish(): Boolean { + return true + } + + fun searchRequest() { + } + + private fun setupSearchMenuItem(menu: Menu): MenuItem { + val iconTint = diskusage.styledColor(android.R.attr.colorControlNormal) + return menu.item( + R.string.button_search, + android.R.drawable.ic_search_category_default, + iconTint, + true + ).apply { + actionView = SearchView(diskusage).also { + searchView = it + origSearchBackground = it.background + if (searchPattern != null) { + it.isIconified = false + it.setQuery(searchPattern, false) + } + it.setOnSearchClickListener { + // Give the query the whole toolbar instead of squeezing it + // next to an ellipsized title. + (diskusage as? AppCompatActivity)?.supportActionBar + ?.setDisplayShowTitleEnabled(false) + } + it.setOnCloseListener { + Timber.d("Search process closed") + searchPattern = null + (diskusage as? AppCompatActivity)?.supportActionBar + ?.setDisplayShowTitleEnabled(true) + diskusage.applyPatternNewRoot(masterRoot, null) + false + } + it.setOnQueryTextListener(object : SearchView.OnQueryTextListener { + override fun onQueryTextSubmit(query: String): Boolean { + onQueryTextChange(query) + return false + } + + override fun onQueryTextChange(newText: String): Boolean { + Timber.d("Search query changed to: %s", newText) + searchPattern = newText + applyPattern(searchPattern) + return true + } + }) + } + } + } + + fun onSaveInstanceState(outState: Bundle) { + outState.putString("search", searchPattern) + } + + fun onRestoreInstanceState(inState: Bundle) { + searchPattern = inState.getString("search") + } + + fun wrapAndSetContentView(view: View?, newRoot: FileSystemSuperRoot?) { + masterRoot = newRoot + updateMenu() + // Swap only the content container: the toolbar and the window insets + // stay in place. Replacing the whole content view (the old behaviour) + // dropped the toolbar and broke edge-to-edge on Android 15+. + val container = diskusage.findViewById(R.id.container) + if (container == null) { + diskusage.setContentView(view) + } else { + container.removeAllViews() + if (view != null) { + container.addView( + view, + ViewGroup.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT + ) + ) + } + } + diskusage.invalidateOptionsMenu() + } + + fun applyPattern(searchQuery: String?) { + if (searchQuery == null || masterRoot == null) return + + if (searchQuery.isEmpty()) { + searchManager.cancelSearch() + finishedSearch(masterRoot, searchQuery) + } else { + searchManager.search(searchQuery) + } + } + + fun finishedSearch(newRoot: FileSystemSuperRoot?, searchQuery: String?): Boolean { + return if (newRoot != null) { + searchView?.background = origSearchBackground + diskusage.applyPatternNewRoot(newRoot, searchQuery) + true + } else { + searchView?.setBackgroundColor(Color.parseColor("#FFDDDD")) + diskusage.applyPatternNewRoot(masterRoot, searchQuery) + false + } + } + + fun update(position: FileSystemEntry?) { + this.selectedEntity = position + updateMenu() + } + + fun setupToolbarMenu(menu: Menu) { + setupSearchMenuItem(menu) + + menu.item(R.string.button_show, showAsAction = true) { + if (selectedEntity != null) { + diskusage.view(selectedEntity) + } + }.apply { + viewModel.showButton.observe(diskusage) { + isVisible = it + } + } + + menu.item(R.string.button_rescan) { + diskusage.rescan() + }.apply { + viewModel.rescanButton.observe(diskusage) { + isVisible = it + } + } + + menu.item(R.string.button_delete) { + selectedEntity?.let { diskusage.askForDeletion(it) } + }.apply { + viewModel.deleteButton.observe(diskusage) { + isVisible = it + } + } + + menu.item(R.string.rederer) { + diskusage.rendererManager.switchRenderer(masterRoot) + }.apply { + viewModel.rendererButtonTitle.observe(diskusage) { + title = it + } + } + + menu.item(R.string.action_permissions) { + showPermissionsDialog() + } + + viewModel.toolbarActionButtonVisible.observe(diskusage) { + menu.forEach { item -> item.isVisible = it } + } + + menu.forEach { it.isVisible = false } + + menu.item(R.string.action_about) { + val binding = + AboutDialogBinding.inflate( + LayoutInflater.from( + diskusage + ), null, false + ) + binding.sourceCode.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + Html.fromHtml( + diskusage.getString( + R.string.about_view_source_code, + "GitHub" + ), + Html.FROM_HTML_MODE_LEGACY + ) + } else { + @Suppress("DEPRECATION") + Html.fromHtml( + diskusage.getString( + R.string.about_view_source_code, + "GitHub" + ) + ) + } + binding.icon.setImageBitmap( + getOrLoadBitmap( + diskusage, + diskusage.applicationInfo, + Process.myUid() / 100000, + diskusage.resources.getDimensionPixelSize(R.dimen.default_app_icon_size) + ) + ) + try { + binding.versionName.text = diskusage.packageManager.getPackageInfo( + diskusage.packageName, 0 + ).versionName + } catch (e: PackageManager.NameNotFoundException) { + Timber.e(e, "Package '${diskusage.packageName}' not found") + } + AlertDialog.Builder(diskusage) + .setView(binding.root) + .show() + } + updateMenu() + } + + /** + * Shows the state of the two special permissions and links to the right + * system settings. Both are app-ops, so Android's own "Permissions" screen + * for the app lists nothing — which used to look like "no permissions + * requested". + */ + private fun showPermissionsDialog() { + val granted = diskusage.getString(R.string.permission_granted) + val denied = diskusage.getString(R.string.permission_denied) + val allFiles = Permissions.hasAllFilesAccess() + val usage = Permissions.hasUsageAccess(diskusage) + AlertDialog.Builder(diskusage) + .setTitle(R.string.action_permissions) + .setMessage( + diskusage.getString( + R.string.permissions_dialog_message, + if (allFiles) granted else denied, + if (usage) granted else denied + ) + ) + .setPositiveButton(R.string.button_all_files_access) { _, _ -> + Permissions.openAllFilesAccessSettings(diskusage) + } + .setNeutralButton(R.string.button_usage_access) { _, _ -> + Permissions.openUsageAccessSettings(diskusage) + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } + + private fun updateMenu() { + if (diskusage.fileSystemState == null) { + viewModel.hideToolBarActionButton() + return + } + + if (diskusage.fileSystemState.sdcardIsEmpty()) { + viewModel.hideToolBarActionButton() + viewModel.enableRescanButton() + } + + viewModel.showToolbarActionButton() + + val isGPU = diskusage.fileSystemState.isGPU + val title = if (isGPU) { + diskusage.getString(R.string.software_renderer) + } else { + diskusage.getString(R.string.hardware_renderer) + } + viewModel.setRendererButtonTitle(title) + + val view = !(selectedEntity === diskusage.fileSystemState.masterRoot.children[0] + || selectedEntity is FileSystemSpecial) + if (view) { + viewModel.enableRescanButton() + } else { + viewModel.disableShowButton() + } + + val entity = selectedEntity ?: return + val fileOrNotSearching = searchPattern == null || entity.children == null + val mountPoint = MountPoint.getForKey(diskusage, diskusage.getKey()) ?: return + if (view && entity.isDeletable && fileOrNotSearching && mountPoint.isDeleteSupported) { + viewModel.enableDeleteButton() + } else { + viewModel.disableDeleteButton() + } + } +} diff --git a/app/src/main/java/com/google/android/diskusage/ui/DiskUsageMenuHoneycomb.java b/app/src/main/java/com/google/android/diskusage/ui/DiskUsageMenuHoneycomb.java deleted file mode 100644 index c51bfe68..00000000 --- a/app/src/main/java/com/google/android/diskusage/ui/DiskUsageMenuHoneycomb.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.google.android.diskusage.ui; - -import android.app.ActionBar; -import android.graphics.Color; -import android.graphics.drawable.Drawable; -import androidx.annotation.NonNull; -import android.util.Log; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.widget.SearchView; -import android.widget.SearchView.OnCloseListener; -import android.widget.SearchView.OnQueryTextListener; -import com.google.android.diskusage.R; -import com.google.android.diskusage.filesystem.entity.FileSystemSuperRoot; -import com.google.android.diskusage.utils.Logger; - -public class DiskUsageMenuHoneycomb extends DiskUsageMenu { - private SearchView searchView; - private Drawable origSearchBackground; - - public DiskUsageMenuHoneycomb(DiskUsage diskusage) { - super(diskusage); - } - - @Override - public void onCreate() { - ActionBar actionBar = diskusage.getActionBar(); - actionBar.setDisplayHomeAsUpEnabled(true); - } - - @Override - public boolean readyToFinish() { - return true; - } - - @Override - public void wrapAndSetContentView(View view, FileSystemSuperRoot newRoot) { - super.wrapAndSetContentView(view, newRoot); - diskusage.setContentView(view); - diskusage.invalidateOptionsMenu(); - } - - - public void setShowAsAction(@NonNull MenuItem item) { - item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); - } - - @Override - public boolean finishedSearch(FileSystemSuperRoot newRoot, String searchQuery) { - boolean matched = super.finishedSearch(newRoot, searchQuery); - if (matched) { - searchView.setBackgroundDrawable(origSearchBackground); - } else { - searchView.setBackgroundColor(Color.parseColor("#FFDDDD")); - } - return matched; - } - - @Override - public MenuItem makeSearchMenuEntry(@NonNull Menu menu) { - MenuItem item = menu.add(R.string.button_search); - searchView = new SearchView(diskusage); - origSearchBackground = searchView.getBackground(); - item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); - item.setIcon(android.R.drawable.ic_search_category_default); - item.setActionView(searchView); - if (searchPattern != null) { - searchView.setIconified(false); - searchView.setQuery(searchPattern, false); - } - searchView.setOnCloseListener(new OnCloseListener() { - @Override - public boolean onClose() { - Logger.getLOGGER().d("Search process closed"); - searchPattern = null; - diskusage.applyPatternNewRoot(masterRoot, null); - return false; - } - }); - searchView.setOnQueryTextListener(new OnQueryTextListener() { - @Override - public boolean onQueryTextSubmit(String query) { - onQueryTextChange(query); - return false; - } - - @Override - public boolean onQueryTextChange(String newText) { - Logger.getLOGGER().d("Search query changed to: %s", newText); - searchPattern = newText; - applyPattern(searchPattern); - return true; - } - }); - return item; - } - - @Override - public boolean onPrepareOptionsMenu(@NonNull Menu menu) { - super.onPrepareOptionsMenu(menu); - setShowAsAction(showMenuItem); - return true; - } - - - @Override - public void searchRequest() { - // FIXME: implement something? - // TODO Auto-generated method stub - - } -} diff --git a/app/src/main/java/com/google/android/diskusage/ui/DiskUsageViewModel.kt b/app/src/main/java/com/google/android/diskusage/ui/DiskUsageViewModel.kt new file mode 100644 index 00000000..e4ad45fa --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/ui/DiskUsageViewModel.kt @@ -0,0 +1,54 @@ +package com.google.android.diskusage.ui + +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.ViewModel +import com.google.android.diskusage.R +import com.google.android.diskusage.utils.AppHelper + +class DiskUsageViewModel : ViewModel() { + val toolbarActionButtonVisible = MutableLiveData(false) + + val showButton = MutableLiveData(false) + + val rescanButton = MutableLiveData(false) + + val deleteButton = MutableLiveData(false) + + val rendererButtonTitle = MutableLiveData(AppHelper.appContext.getString(R.string.rederer)) + + fun showToolbarActionButton() { + toolbarActionButtonVisible.value = true + } + + fun hideToolBarActionButton() { + toolbarActionButtonVisible.value = false + } + + fun enableShowButton() { + showButton.value = true + } + + fun disableShowButton() { + showButton.value = false + } + + fun enableRescanButton() { + rescanButton.value = true + } + + fun disableRescanButton() { + rescanButton.value = false + } + + fun enableDeleteButton() { + deleteButton.value = true + } + + fun disableDeleteButton() { + deleteButton.value = false + } + + fun setRendererButtonTitle(title: String) { + rendererButtonTitle.value = title + } +} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/ui/FileSystemState.java b/app/src/main/java/com/google/android/diskusage/ui/FileSystemState.java index f2ae084d..af508061 100644 --- a/app/src/main/java/com/google/android/diskusage/ui/FileSystemState.java +++ b/app/src/main/java/com/google/android/diskusage/ui/FileSystemState.java @@ -26,12 +26,11 @@ import com.google.android.diskusage.filesystem.entity.FileSystemSystemSpace; import com.google.android.diskusage.opengl.FileSystemViewGPU; import com.google.android.diskusage.opengl.RenderingThread; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Bundle; import android.os.SystemClock; -import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.animation.DecelerateInterpolator; @@ -159,6 +158,10 @@ public void searchRequest() { private float maxLevels = 3.2f; private boolean fullZoom; + + private static final long DOUBLE_TAP_TIMEOUT = 350L; + private FileSystemEntry lastTapEntry; + private long lastTapTime; private boolean warnOnFileSelect; private float touchDepth; @@ -479,7 +482,7 @@ public final boolean onTouchEvent(MyMotionEvent ev) { touchEntry = masterRoot.findEntry((int)touchDepth + 1, touchPoint); if (touchEntry == masterRoot) { touchEntry = null; - Logger.getLOGGER().d("warning: masterRoot selected in onTouchEvent"); + Timber.d("warning: masterRoot selected in onTouchEvent"); } speedX = 0; speedY = 0; @@ -499,11 +502,31 @@ public final boolean onTouchEvent(MyMotionEvent ev) { if (!touchMovement) { if (touchEntry == null) { - Logger.getLOGGER().d("touchEntry == null"); + Timber.d("touchEntry == null"); return true; } if (masterRoot.depth(touchEntry) > (int)touchDepth + 1) return true; - touchSelect(touchEntry, ev.getEventTime()); + + // Double tap on a file (or an empty directory) opens it with the + // registered viewer. Tapping once only selects, so users could not open + // a file without going through the menu (issue #89). + final long eventTime = ev.getEventTime(); + final boolean isLeaf = touchEntry.children == null || touchEntry.children.length == 0; + final boolean isSpecial = touchEntry == masterRoot.children[0] + || touchEntry instanceof FileSystemFreeSpace + || touchEntry instanceof FileSystemSystemSpace; + if (isLeaf && !isSpecial + && lastTapEntry == touchEntry + && eventTime - lastTapTime < DOUBLE_TAP_TIMEOUT) { + lastTapEntry = null; + lastTapTime = 0; + mainThreadAction.view(touchEntry); + return true; + } + lastTapEntry = touchEntry; + lastTapTime = eventTime; + + touchSelect(touchEntry, eventTime); return true; } touchMovement = false; @@ -750,7 +773,7 @@ public boolean onDrawGPU(RenderingThread rt) { paintSlowGPU(rt, displayTop, displayBottom, viewDepth, screenWidth, screenHeight); return postDraw(animation); } catch (Throwable t) { - Logger.getLOGGER().d("FileSystemState.onDrawGPU(): Got exception", t); + Timber.d(t, "onDrawGPU: Got exception"); } return false; } @@ -775,7 +798,7 @@ public final void onDraw2(final Canvas canvas) { requestRepaint(); } } catch (Throwable t) { - Logger.getLOGGER().d("FileSystemState.onDraw2(): Got exception", t); + Timber.d(t, "onDraw2: Got exception"); } } @@ -1058,7 +1081,7 @@ private void deleteDeletingEntry() { } for (FileSystemEntry e : masterRoot.children[0].children) { - Log.d("diskusage", "entry = " + e.name + " " + e.getSizeInBlocks()); + Timber.d("entry = " + e.name + " " + e.getSizeInBlocks()); } if (freeSpace != null) { @@ -1277,7 +1300,7 @@ public final void layout( MotionFilter.dx = (screenHeight + screenWidth) / 50f; minDistance = screenHeight > screenWidth ? screenHeight / 10f : screenWidth / 10f; - Logger.getLOGGER().d("FileSystemState: Screen = %s x %s", screenWidth, screenHeight); + Timber.d("Screen = %s x %s", screenWidth, screenHeight); FileSystemEntry.elementWidth = targetElementWidth = (int) (screenWidth / maxLevels); setZoomState(); } diff --git a/app/src/main/java/com/google/android/diskusage/ui/FileSystemViewCPU.java b/app/src/main/java/com/google/android/diskusage/ui/FileSystemViewCPU.java index b752c000..b635f1be 100644 --- a/app/src/main/java/com/google/android/diskusage/ui/FileSystemViewCPU.java +++ b/app/src/main/java/com/google/android/diskusage/ui/FileSystemViewCPU.java @@ -10,7 +10,7 @@ import androidx.annotation.NonNull; import com.google.android.diskusage.filesystem.entity.FileSystemEntry; import com.google.android.diskusage.ui.FileSystemState.FileSystemView; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; public final class FileSystemViewCPU extends View implements FileSystemView { private final FileSystemState eventHandler; @@ -28,7 +28,7 @@ public FileSystemViewCPU(Context context, @SuppressLint("ClickableViewAccessibility") @Override public final boolean onTouchEvent(@NonNull MotionEvent ev) { - Logger.getLOGGER().d("FileSystemViewCPU.onTouchEvent(): Touch = %s:%s", ev.getX(), ev.getY()); + Timber.d("onTouchEvent: Touch = %s:%s", ev.getX(), ev.getY()); eventHandler.onTouchEvent( eventHandler.multitouchHandler.newMyMotionEvent(ev)); return true; diff --git a/app/src/main/java/com/google/android/diskusage/ui/LoadableActivity.java b/app/src/main/java/com/google/android/diskusage/ui/LoadableActivity.java index fd3721eb..aa8c0e38 100644 --- a/app/src/main/java/com/google/android/diskusage/ui/LoadableActivity.java +++ b/app/src/main/java/com/google/android/diskusage/ui/LoadableActivity.java @@ -20,202 +20,213 @@ package com.google.android.diskusage.ui; import android.app.Activity; -import android.app.AlertDialog; +import androidx.appcompat.app.AlertDialog; import android.os.Bundle; import android.os.Handler; + +import androidx.appcompat.app.AppCompatActivity; + import com.google.android.diskusage.R; import com.google.android.diskusage.filesystem.entity.FileSystemEntry; import com.google.android.diskusage.filesystem.entity.FileSystemPackage; import com.google.android.diskusage.filesystem.entity.FileSystemSuperRoot; import com.google.android.diskusage.ui.DiskUsage.AfterLoad; import com.google.android.diskusage.ui.common.ScanProgressDialog; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; + import java.io.IOException; import java.util.Map; import java.util.TreeMap; + import splitties.toast.ToastKt; -public abstract class LoadableActivity extends Activity { - FileSystemPackage pkg_removed; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - FileSystemEntry.setupStrings(this); - } - - public abstract String getKey(); - - abstract FileSystemSuperRoot scan() throws IOException, InterruptedException; - - public static class PersistantActivityState { - FileSystemSuperRoot root; - AfterLoad afterLoad; - public ScanProgressDialog loading; - } - - private static final Map persistantActivityState = - new TreeMap<>(); - - public static void resetStoredStates() { - persistantActivityState.clear(); - } - - - // FIXME: use it wisely - static boolean forceCleanup() { - boolean success = false; - for (PersistantActivityState state : persistantActivityState.values()) { - if (state.afterLoad == null && state.root != null) { - state.root = null; - success = true; - } - } - return success; - } - - public PersistantActivityState getPersistantState() { - String key = getKey(); - - PersistantActivityState state = persistantActivityState.get(key); - if (state != null) return state; - state = new PersistantActivityState(); - persistantActivityState.put(key, state); - return state; - } - - void LoadFiles(final LoadableActivity activity, - final AfterLoad runAfterLoad, boolean force) { - boolean scanRunning; - final PersistantActivityState state = getPersistantState(); - Logger.getLOGGER().d("LoadableActivity.LoadFiles(), afterLoad = %s", runAfterLoad); - - if (force) { - state.root = null; +public abstract class LoadableActivity extends AppCompatActivity { + private static final Map persistantActivityState = + new TreeMap<>(); + FileSystemPackage pkg_removed; + + public static void resetStoredStates() { + persistantActivityState.clear(); } - if (state.root != null) { - runAfterLoad.run(state.root, true); - return; + // FIXME: use it wisely + static boolean forceCleanup() { + boolean success = false; + for (PersistantActivityState state : persistantActivityState.values()) { + if (state.afterLoad == null && state.root != null) { + state.root = null; + success = true; + } + } + return success; } - scanRunning = state.afterLoad != null; - state.afterLoad = runAfterLoad; - Logger.getLOGGER().d("LoadableActivity.LoadFiles(): Created new progress dialog"); - state.loading = new ScanProgressDialog(activity); - - final ScanProgressDialog thisLoading = state.loading; - state.loading.setOnCancelListener(dialog -> { - state.loading = null; - activity.finish(); - }); - thisLoading.setCancelable(true); -// thisLoading.setIndeterminate(true); - thisLoading.setMax(1); - thisLoading.setMessage(activity.getString(R.string.scaning_directories)); - thisLoading.show(); + private static void handleOutOfMemory(final Activity activity) { + try { + // Can fail if the main window is already closed. + new AlertDialog.Builder(activity) + .setTitle(activity.getString(R.string.out_of_memory)) + .setOnCancelListener(dialog -> activity.finish()).create().show(); + } catch (Throwable t) { + ToastKt.toast("DiskUsage is out of memory. Sorry."); + } + } - if (scanRunning) return; - final Handler handler = new Handler(); + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + FileSystemEntry.setupStrings(this); + } - new Thread() { - @Override - public void run() { - String error; - try { - Logger.getLOGGER().d("LoadableActivity.LoadFiles(): Running scan for %s", getKey()); - final FileSystemSuperRoot newRoot = scan(); - - handler.post(() -> { - if (state.loading == null) { - Logger.getLOGGER().d("LoadableActivity.LoadFiles(): No dialog, doesn't run afterLoad"); - state.afterLoad = null; - if (newRoot.children[0].children != null) { - Logger.getLOGGER().d("LoadableActivity.LoadFiles(): No dialog, updating root still"); - state.root = newRoot; - } - return; + public abstract String getKey(); + + abstract FileSystemSuperRoot scan() throws IOException, InterruptedException; + + public PersistantActivityState getPersistantState() { + String key = getKey(); + + PersistantActivityState state = persistantActivityState.get(key); + if (state != null) return state; + state = new PersistantActivityState(); + persistantActivityState.put(key, state); + return state; + } + + void LoadFiles(final LoadableActivity activity, + final AfterLoad runAfterLoad, boolean force) { + boolean scanRunning; + final PersistantActivityState state = getPersistantState(); + Timber.d("LoadableActivity.LoadFiles(), afterLoad = %s", runAfterLoad); + + if (force) { + state.root = null; + } + + if (state.root != null) { + runAfterLoad.run(state.root, true); + return; + } + + scanRunning = state.afterLoad != null; + state.afterLoad = runAfterLoad; + Timber.d("LoadFiles: Created new progress dialog"); + state.loading = new ScanProgressDialog(activity); + + final ScanProgressDialog thisLoading = state.loading; + state.loading.setOnCancelListener(dialog -> { + state.loading = null; + activity.finish(); + }); + thisLoading.setCancelable(true); +// thisLoading.setIndeterminate(true); + thisLoading.setMax(1); + thisLoading.setMessage(activity.getString(R.string.scaning_directories)); + thisLoading.show(); + + if (scanRunning) return; + final Handler handler = new Handler(); + + new Thread() { + @Override + public void run() { + String error; + try { + Timber.d("LoadFiles: Running scan for %s", getKey()); + final FileSystemSuperRoot newRoot = scan(); + + handler.post(() -> { + if (state.loading == null) { + Timber.d("LoadFiles: No dialog, doesn't run afterLoad"); + state.afterLoad = null; + if (newRoot.children[0].children != null) { + Timber.d("LoadFiles: No dialog, updating root still"); + state.root = newRoot; + } + return; + } + if (state.loading.isShowing()) state.loading.dismiss(); + state.loading = null; + AfterLoad afterLoadCopy = state.afterLoad; + state.afterLoad = null; + Timber.d("LoadFiles: Dismissed dialog"); + + if (newRoot.children[0].children == null) { + Timber.d("LoadFiles: Empty card"); + handleEmptySDCard(activity, runAfterLoad); + return; + } + state.root = newRoot; + pkg_removed = null; + Timber.d("LoadFiles: Run afterLoad = %s", afterLoadCopy); + afterLoadCopy.run(state.root, false); + }); + return; + } catch (final OutOfMemoryError e) { + state.root = null; + state.afterLoad = null; + Timber.d("LoadFiles: Out of memory!"); + handler.post(() -> { + if (state.loading == null) return; + state.loading.dismiss(); + handleOutOfMemory(activity); + }); + return; + } catch (InterruptedException e) { + error = activity.getString(R.string.scan_interrupted); + Timber.d(e, "LoadFiles: scan interrupted"); + } catch (IOException | RuntimeException e) { + error = e.getClass().getName() + ":" + e.getMessage(); + Timber.e(e, "LoadFiles: Native error"); + } catch (final StackOverflowError e) { + error = "Filesystem is damaged."; + } catch (final Throwable e) { + // Never let the worker thread die silently: the dialog would + // stay on screen forever ("DiskUsage hangs" reports). + error = e.getClass().getName() + ":" + e.getMessage(); + Timber.e(e, "LoadFiles: unexpected error"); + } + final String finalError = error; + state.root = null; + state.afterLoad = null; + Timber.d("LoadFiles: Exception in scan!"); + handler.post(() -> { + if (state.loading == null) return; + state.loading.dismiss(); + new AlertDialog.Builder(activity) + .setTitle(finalError) + .setOnCancelListener(dialog -> activity.finish()) + .show(); + }); } + }.start(); + } + + @Override + protected void onPause() { + PersistantActivityState state = getPersistantState(); + if (state.loading != null) { if (state.loading.isShowing()) state.loading.dismiss(); + Timber.d("onPause: Removed progress dialog"); state.loading = null; - AfterLoad afterLoadCopy = state.afterLoad; - state.afterLoad = null; - Logger.getLOGGER().d("LoadableActivity.LoadFiles(): Dismissed dialog"); - - if (newRoot.children[0].children == null) { - Logger.getLOGGER().d("LoadableActivity.LoadFiles(): Empty card"); - handleEmptySDCard(activity, runAfterLoad); - return; - } - state.root = newRoot; - pkg_removed = null; - Logger.getLOGGER().d("LoadableActivity.LoadFiles(): Run afterLoad = %s", afterLoadCopy); - afterLoadCopy.run(state.root, false); - }); - return; - } catch (final OutOfMemoryError e) { - state.root = null; - state.afterLoad = null; - Logger.getLOGGER().d("LoadableActivity.LoadFiles(): Out of memory!"); - handler.post(() -> { - if (state.loading == null) return; - state.loading.dismiss(); - handleOutOfMemory(activity); - }); - return; - } catch (InterruptedException | IOException | RuntimeException e) { - error = e.getClass().getName() + ":" + e.getMessage(); - Logger.getLOGGER().e("LoadableActivity.LoadFiles(): Native error", e); - } catch (final StackOverflowError e) { - error = "Filesystem is damaged."; } - final String finalError = error; - state.root = null; - state.afterLoad = null; - Logger.getLOGGER().d("LoadableActivity.LoadFiles(): Exception in scan!"); - handler.post(() -> { - if (state.loading == null) return; - state.loading.dismiss(); - new AlertDialog.Builder(activity) - .setTitle(finalError) - .setOnCancelListener(dialog -> activity.finish()) - .show(); - }); - } - }.start(); - } - - @Override - protected void onPause() { - PersistantActivityState state = getPersistantState(); - if (state.loading != null) { - if (state.loading.isShowing()) state.loading.dismiss(); - Logger.getLOGGER().d("LoadableActivity.onPause(): Removed progress dialog"); - state.loading = null; + super.onPause(); + } + + private void handleEmptySDCard(final LoadableActivity activity, + final AfterLoad afterLoad) { + new AlertDialog.Builder(activity) + .setTitle(activity.getString(R.string.empty_or_missing_sdcard)) + .setPositiveButton(activity.getString(R.string.button_rescan), (dialog, which) -> { + if (afterLoad == null) + throw new RuntimeException("LoadableActivity.handleEmptySDCard(): afterLoad is empty"); + LoadFiles(activity, afterLoad, true); + }) + .setOnCancelListener(dialog -> activity.finish()).create().show(); } - super.onPause(); - } - - private void handleEmptySDCard(final LoadableActivity activity, - final AfterLoad afterLoad) { - new AlertDialog.Builder(activity) - .setTitle(activity.getString(R.string.empty_or_missing_sdcard)) - .setPositiveButton(activity.getString(R.string.button_rescan), (dialog, which) -> { - if (afterLoad == null) - throw new RuntimeException("LoadableActivity.handleEmptySDCard(): afterLoad is empty"); - LoadFiles(activity, afterLoad, true); - }) - .setOnCancelListener(dialog -> activity.finish()).create().show(); - } - - private static void handleOutOfMemory(final Activity activity) { - try { - // Can fail if the main window is already closed. - new AlertDialog.Builder(activity) - .setTitle(activity.getString(R.string.out_of_memory)) - .setOnCancelListener(dialog -> activity.finish()).create().show(); - } catch (Throwable t) { - ToastKt.toast("DiskUsage is out of memory. Sorry."); + + public static class PersistantActivityState { + public ScanProgressDialog loading; + FileSystemSuperRoot root; + AfterLoad afterLoad; } - } } diff --git a/app/src/main/java/com/google/android/diskusage/ui/PermissionRequestActivity.java b/app/src/main/java/com/google/android/diskusage/ui/PermissionRequestActivity.java index 8c362401..65c842a1 100644 --- a/app/src/main/java/com/google/android/diskusage/ui/PermissionRequestActivity.java +++ b/app/src/main/java/com/google/android/diskusage/ui/PermissionRequestActivity.java @@ -19,70 +19,96 @@ package com.google.android.diskusage.ui; -import android.Manifest; -import android.app.Activity; -import android.app.AlertDialog; -import android.app.AppOpsManager; -import android.content.Context; import android.content.Intent; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.net.Uri; -import android.os.Build; import android.os.Bundle; -import android.os.Environment; -import android.provider.Settings; -import android.util.Log; -import android.widget.Toast; +import androidx.activity.result.ActivityResultLauncher; +import androidx.activity.result.contract.ActivityResultContracts; +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatActivity; import com.google.android.diskusage.R; import com.google.android.diskusage.databinding.ActivityCommonBinding; import com.google.android.diskusage.filesystem.mnt.MountPoint; +import com.google.android.diskusage.ui.common.EdgeToEdge; +import com.google.android.diskusage.ui.common.Permissions; import splitties.toast.ToastKt; -import com.google.android.diskusage.utils.Logger; -public class PermissionRequestActivity extends Activity { - private final static int DISKUSAGE_REQUEST_CODE = 10; - private final static int PERMISSION_REQUEST_USAGE_ACCESS_CODE = 11; - private final static int PERMISSION_REQUEST_EXTERNAL_STORAGE_CODE = 12; +/** + * Makes sure the app can read the storage before {@link DiskUsage} starts. + * + * Only "All files access" (Android 11+) is mandatory — without it the scanner + * sees nothing but the app's own directory. Usage access is optional (exact app + * sizes) and is therefore not requested here any more: blocking on it confused + * users on ROMs like HyperOS, where the toggle does not always map to the app + * op. It can be granted later from within the graph (menu → Permissions). + */ +public class PermissionRequestActivity extends AppCompatActivity { + private static final int DISKUSAGE_REQUEST_CODE = 10; + + private boolean forwarded = false; + + private final ActivityResultLauncher legacyStoragePermissionLauncher = + registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), + result -> forwardToDiskUsage()); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + EdgeToEdge.enable(this); ActivityCommonBinding binding = ActivityCommonBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); - Intent i = getIntent(); + EdgeToEdge.applyInsets(binding.getRoot()); + Intent i = getIntent(); final String key = i.getStringExtra(DiskUsage.KEY_KEY); if (key == null) { - // Just close instead of crashing later finish(); return; } - MountPoint mountPoint = MountPoint.getForKey(this, key); if (mountPoint == null) { finish(); return; } - if ((!mountPoint.hasApps()) || isAccessGranted()) { + + if (Permissions.hasAllFilesAccess()) { + forwardToDiskUsage(); + } else { + showAllFilesAccessDialog(); + } + } + + @Override + protected void onResume() { + super.onResume(); + // Re-check instead of relying on the result callback: several ROMs do not + // deliver it, or return the user to a different task. + if (!forwarded && Permissions.hasAllFilesAccess()) { forwardToDiskUsage(); - return; } + } + private void showAllFilesAccessDialog() { new AlertDialog.Builder(this) - .setTitle(R.string.dialog_usage_access_title) - .setMessage(R.string.dialog_usage_access_desc) - .setPositiveButton(android.R.string.ok, (dialogInterface, i1) -> { - Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); - startActivityForResult(intent, PERMISSION_REQUEST_USAGE_ACCESS_CODE); + .setTitle(R.string.dialog_all_files_access_title) + .setMessage(R.string.dialog_all_files_access_desc) + .setPositiveButton(R.string.button_open_settings, (dialog, which) -> { + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) { + Permissions.openAllFilesAccessSettings(this); + } else { + legacyStoragePermissionLauncher.launch(new String[] { + android.Manifest.permission.READ_EXTERNAL_STORAGE, + android.Manifest.permission.WRITE_EXTERNAL_STORAGE + }); + } }) - .setNegativeButton(android.R.string.cancel, (dialogInterface, i12) -> - forwardToDiskUsage()).create().show(); - - requestExternalStoragePermission(); + .setNegativeButton(android.R.string.cancel, (dialog, which) -> finish()) + .setOnCancelListener(dialog -> finish()) + .show(); } public void forwardToDiskUsage() { + if (forwarded) return; + forwarded = true; Intent input = getIntent(); Intent diskusage = new Intent(this, DiskUsage.class); diskusage.putExtra(DiskUsage.KEY_KEY, input.getStringExtra(DiskUsage.KEY_KEY)); @@ -96,66 +122,6 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == DISKUSAGE_REQUEST_CODE) { setResult(0, data); finish(); - } else if (requestCode == PERMISSION_REQUEST_USAGE_ACCESS_CODE) { - forwardToDiskUsage(); - } else if (requestCode == PERMISSION_REQUEST_EXTERNAL_STORAGE_CODE) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - if (Environment.isExternalStorageManager()) { - forwardToDiskUsage(); - } else { - ToastKt.toast(R.string.dialog_external_storage_access_error); - } - } } } - - private void requestExternalStoragePermission() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - if (Environment.isExternalStorageManager()) { - forwardToDiskUsage(); - return; - } else { - try { - final Intent i = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION); - i.setData(Uri.parse("package:" + getPackageName())); - startActivityForResult(i, PERMISSION_REQUEST_EXTERNAL_STORAGE_CODE); - return; - } catch (Exception e) { - Log.d("diskusage", "failed to obtain all files access", e); - } - } - } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE - ) == PackageManager.PERMISSION_GRANTED && - checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE - ) == PackageManager.PERMISSION_GRANTED) { - forwardToDiskUsage(); - } else { - requestPermissions( - new String[] { - Manifest.permission.READ_EXTERNAL_STORAGE, - Manifest.permission.WRITE_EXTERNAL_STORAGE - }, - PERMISSION_REQUEST_EXTERNAL_STORAGE_CODE - ); - } - } - } - - private boolean isAccessGranted() { - try { - PackageManager packageManager = getPackageManager(); - ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0); - AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE); - int mode = 0; - mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, - applicationInfo.uid, applicationInfo.packageName); - return (mode == AppOpsManager.MODE_ALLOWED); - - } catch (PackageManager.NameNotFoundException e) { - return false; - } - } - } diff --git a/app/src/main/java/com/google/android/diskusage/ui/SelectActivity.java b/app/src/main/java/com/google/android/diskusage/ui/SelectActivity.java index 52e886bb..5d8daafe 100644 --- a/app/src/main/java/com/google/android/diskusage/ui/SelectActivity.java +++ b/app/src/main/java/com/google/android/diskusage/ui/SelectActivity.java @@ -19,22 +19,25 @@ package com.google.android.diskusage.ui; -import android.app.Activity; -import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; +import android.os.Looper; import androidx.annotation.NonNull; +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.view.ViewCompat; import com.google.android.diskusage.R; import com.google.android.diskusage.databinding.ActivityCommonBinding; import com.google.android.diskusage.filesystem.entity.FileSystemEntry; import com.google.android.diskusage.filesystem.mnt.MountPoint; import com.google.android.diskusage.filesystem.mnt.RootMountPoint; +import com.google.android.diskusage.ui.common.EdgeToEdge; import com.google.android.diskusage.utils.DeviceHelper; import com.google.android.diskusage.utils.IOHelper; -import com.google.android.diskusage.utils.Logger; +import timber.log.Timber; import java.io.BufferedReader; import java.util.ArrayList; import java.util.Map; @@ -42,12 +45,20 @@ import java.util.Set; import java.util.TreeMap; -public class SelectActivity extends Activity { +/** + * Entry point: lets the user pick the volume (or, with root, any mount point) + * that should be analysed. + */ +public class SelectActivity extends AppCompatActivity { private static final String BUNDLE_KEYS = "keys"; private AlertDialog dialog; - Map bundles = new TreeMap<>(); - ArrayList actionList = new ArrayList<>(); + final Map bundles = new TreeMap<>(); + final ArrayList actionList = new ArrayList<>(); private boolean expandRootMountPoints; + /** Guards against re-entering the graph in a loop when the user presses back. */ + private boolean autoSelected; + /** True when the graph returned a state bundle (back on a multi-volume device). */ + private boolean childReturnedState; private abstract class AbstractUsageAction implements Runnable { public void runAction(String key, Class viewer) { @@ -80,27 +91,26 @@ public void run() { } } - public Handler handler = new Handler(); - public Runnable checkForMountsUpdates = new Runnable() { + public final Handler handler = new Handler(Looper.getMainLooper()); + private final Runnable checkForMountsUpdates = new Runnable() { @Override public void run() { boolean reload = false; - try { - BufferedReader reader = IOHelper.getProcMountsReader(); + try (BufferedReader reader = IOHelper.getProcMountsReader()) { String line; int checksum = 0; while ((line = reader.readLine()) != null) { checksum += line.length(); } - reader.close(); if (checksum != RootMountPoint.checksum) { - Logger.getLOGGER().d("%s vs %s", checksum, RootMountPoint.checksum); + Timber.d("%s vs %s", checksum, RootMountPoint.checksum); reload = true; } - } catch (Throwable ignored) {} + } catch (Throwable ignored) { + } if (reload) { - dialog.hide(); + dismissDialog(); MountPoint.reset(); makeDialog(); } @@ -108,19 +118,26 @@ public void run() { } }; + private void dismissDialog() { + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + } + dialog = null; + } public void makeDialog() { + dismissDialog(); + ArrayList options = new ArrayList<>(); actionList.clear(); -// PortableFile[] fileDirs = DataSource.get().getExternalFilesDirs(this); for (MountPoint mountPoint : MountPoint.getMountPoints(this)) { options.add(mountPoint.getTitle()); actionList.add(new DiskUsageAction(mountPoint)); } if (DeviceHelper.isDeviceRooted()) { - SharedPreferences prefs = getSharedPreferences("ignore_list", Context.MODE_PRIVATE); + SharedPreferences prefs = getSharedPreferences("ignore_list", Context.MODE_PRIVATE); Map ignoreList = prefs.getAll(); if (!ignoreList.keySet().isEmpty()) { Set ignores = ignoreList.keySet(); @@ -129,74 +146,78 @@ public void makeDialog() { options.add(mountPoint.getRoot()); actionList.add(new DiskUsageAction(mountPoint)); } - options.add("[Show/hide]"); + options.add(getString(R.string.show_hide_mount_points)); actionList.add(new ShowHideAction()); } else if (expandRootMountPoints) { for (MountPoint mountPoint : RootMountPoint.getRootedMountPoints(this)) { options.add(mountPoint.getRoot()); actionList.add(new DiskUsageAction(mountPoint)); } - options.add("[Show/hide]"); + options.add(getString(R.string.show_hide_mount_points)); actionList.add(new ShowHideAction()); } else { - options.add("[Root required]"); + options.add(getString(R.string.root_required)); actionList.add(() -> { expandRootMountPoints = true; makeDialog(); }); - } } + // Autoselect: on devices with a single storage volume the extra tap is + // pointless. The dialog is only skipped on the first visit; after returning + // from the graph the user explicitly gets the chooser. + if (options.size() == 1 && bundles.isEmpty() && !autoSelected && !actionList.isEmpty()) { + autoSelected = true; + actionList.get(0).run(); + return; + } + final String[] optionsArray = options.toArray(new String[0]); dialog = new AlertDialog.Builder(this) - .setItems(optionsArray, - (dialog, which) -> actionList.get(which).run()) - .setTitle(R.string.ask_view) - .setOnCancelListener(dialog -> finish()).create(); - /*try { - if (debugDataSourceBridge != null) { - dialog.getListView().setOnItemLongClickListener( - new OnItemLongClickListener() { - @Override - public boolean onItemLongClick( - AdapterView arg0, View arg1, int arg2, long arg3) { - debugUnhidden = true; - dialog.hide(); - makeDialog(); - return true; + .setItems(optionsArray, (d, which) -> { + if (which >= 0 && which < actionList.size()) { + actionList.get(which).run(); } - }); - } - } catch (Throwable t) { - // api 3 - }*/ + }) + .setTitle(R.string.ask_view) + .setOnCancelListener(d -> finish()) + .create(); dialog.show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + EdgeToEdge.enable(this); FileSystemEntry.setupStrings(this); ActivityCommonBinding binding = ActivityCommonBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); -// ActionBar bar = getActionBar(); -// bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_USE_LOGO); + EdgeToEdge.applyInsets(binding.getRoot()); + ViewCompat.setAccessibilityPaneTitle(binding.getRoot(), getString(R.string.app_name)); } @Override protected void onResume() { super.onResume(); -// ActionBar actionBar = getActionBar(); -// actionBar.setDisplayHomeAsUpEnabled(true); + if (autoSelected && !childReturnedState) { + // We entered a child screen and it went away without handing back a + // state (scan cancelled, permission dialog dismissed, ...): back means + // "leave the app", not "show the volume chooser again". + finish(); + return; + } makeDialog(); handler.post(checkForMountsUpdates); } @Override protected void onPause() { - if (dialog.isShowing()) dialog.dismiss(); + // Coming back from the graph (or from a permission screen) must not + // auto-open it again; show the chooser instead. + autoSelected = true; + dismissDialog(); handler.removeCallbacks(checkForMountsUpdates); super.onPause(); } @@ -207,7 +228,10 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (data == null) return; Bundle state = data.getBundleExtra(DiskUsage.STATE_KEY); String key = data.getStringExtra(DiskUsage.KEY_KEY); - bundles.put(key, state); + if (key != null && state != null) { + bundles.put(key, state); + childReturnedState = true; + } } @Override @@ -221,10 +245,15 @@ protected void onSaveInstanceState(@NonNull Bundle outState) { } @Override - protected void onRestoreInstanceState(Bundle savedInstanceState) { + protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); - for (String key : savedInstanceState.getStringArray(BUNDLE_KEYS)) { - bundles.put(key, savedInstanceState.getBundle(key)); + String[] keys = savedInstanceState.getStringArray(BUNDLE_KEYS); + if (keys == null) return; + for (String key : keys) { + Bundle bundle = savedInstanceState.getBundle(key); + if (bundle != null) { + bundles.put(key, bundle); + } } } } diff --git a/app/src/main/java/com/google/android/diskusage/ui/ShowHideMountPointsActivity.java b/app/src/main/java/com/google/android/diskusage/ui/ShowHideMountPointsActivity.java index 324f4f76..e9af1bce 100644 --- a/app/src/main/java/com/google/android/diskusage/ui/ShowHideMountPointsActivity.java +++ b/app/src/main/java/com/google/android/diskusage/ui/ShowHideMountPointsActivity.java @@ -3,62 +3,93 @@ import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; -import android.preference.CheckBoxPreference; -import android.preference.PreferenceActivity; -import android.preference.PreferenceScreen; +import androidx.appcompat.app.AppCompatActivity; +import androidx.preference.CheckBoxPreference; +import androidx.preference.PreferenceFragmentCompat; +import androidx.preference.PreferenceScreen; import com.google.android.diskusage.R; +import com.google.android.diskusage.databinding.ActivityPreferencesBinding; import com.google.android.diskusage.filesystem.entity.FileSystemEntry; import com.google.android.diskusage.filesystem.mnt.MountPoint; import com.google.android.diskusage.filesystem.mnt.RootMountPoint; import com.google.android.diskusage.ui.DiskUsage.FileSystemStats; +import com.google.android.diskusage.ui.common.EdgeToEdge; import java.util.List; import java.util.Map; import java.util.Set; -public class ShowHideMountPointsActivity extends PreferenceActivity { +/** + * Selects which (root-only) mount points are offered in the volume chooser. + * Migrated from the framework {@code PreferenceActivity}, which is deprecated + * since API 28 and does not support dark mode or edge-to-edge layouts. + */ +public class ShowHideMountPointsActivity extends AppCompatActivity { + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - addPreferencesFromResource(R.xml.mount_points_ignore_list); - getPreferenceScreen().setOrderingAsAdded(true); + EdgeToEdge.enable(this); + ActivityPreferencesBinding binding = ActivityPreferencesBinding.inflate(getLayoutInflater()); + setContentView(binding.getRoot()); + EdgeToEdge.applyInsets(binding.getRoot()); + setSupportActionBar(binding.toolbar); + setTitle(R.string.app_name); + + if (savedInstanceState == null) { + getSupportFragmentManager() + .beginTransaction() + .replace(R.id.settings, new MountPointsFragment()) + .commit(); + } } - @Override - protected void onResume() { - super.onResume(); - List mountPoints = RootMountPoint.getRootedMountPoints(this); - PreferenceScreen prefs = getPreferenceScreen(); - prefs.removeAll(); - SharedPreferences shprefs = getSharedPreferences("ignore_list", Context.MODE_PRIVATE); - Map ignoreList = shprefs.getAll(); - Set ignores = ignoreList.keySet(); + public static class MountPointsFragment extends PreferenceFragmentCompat { + @Override + public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { + setPreferencesFromResource(R.xml.mount_points_ignore_list, rootKey); + getPreferenceScreen().setOrderingAsAdded(true); + } - for (MountPoint mountPoint : mountPoints) { - CheckBoxPreference pref = new CheckBoxPreference(this); - FileSystemEntry.setupStrings(this); - FileSystemStats stats = new FileSystemStats(mountPoint); - pref.setSummary(stats.formatUsageInfo()); - pref.setTitle(mountPoint.getRoot()); - pref.setChecked(!ignores.contains(mountPoint.getRoot())); - prefs.addPreference(pref); + @Override + public void onResume() { + super.onResume(); + Context context = requireContext(); + List mountPoints = RootMountPoint.getRootedMountPoints(context); + PreferenceScreen prefs = getPreferenceScreen(); + prefs.removeAll(); + SharedPreferences shprefs = + context.getSharedPreferences("ignore_list", Context.MODE_PRIVATE); + Map ignoreList = shprefs.getAll(); + Set ignores = ignoreList.keySet(); + + for (MountPoint mountPoint : mountPoints) { + CheckBoxPreference pref = new CheckBoxPreference(context); + FileSystemEntry.setupStrings(context); + FileSystemStats stats = new FileSystemStats(mountPoint); + pref.setSummary(stats.formatUsageInfo(context)); + pref.setTitle(mountPoint.getRoot()); + pref.setChecked(!ignores.contains(mountPoint.getRoot())); + prefs.addPreference(pref); + } } - } - @Override - protected void onPause() { - super.onPause(); - PreferenceScreen prefs = getPreferenceScreen(); - SharedPreferences shprefs = getSharedPreferences("ignore_list", Context.MODE_PRIVATE); - SharedPreferences.Editor editor = shprefs.edit(); - editor.clear(); + @Override + public void onPause() { + super.onPause(); + PreferenceScreen prefs = getPreferenceScreen(); + SharedPreferences shprefs = + requireContext().getSharedPreferences("ignore_list", Context.MODE_PRIVATE); + SharedPreferences.Editor editor = shprefs.edit(); + editor.clear(); - for (int i = 0; i < prefs.getPreferenceCount(); i++) { - CheckBoxPreference pref = (CheckBoxPreference) prefs.getPreference(i); - String root = pref.getTitle().toString(); - if (!pref.isChecked()) { - editor.putBoolean(root, true); + for (int i = 0; i < prefs.getPreferenceCount(); i++) { + CheckBoxPreference pref = (CheckBoxPreference) prefs.getPreference(i); + String root = pref.getTitle().toString(); + if (!pref.isChecked()) { + editor.putBoolean(root, true); + } } + editor.apply(); } - editor.apply(); } } diff --git a/app/src/main/java/com/google/android/diskusage/ui/common/EdgeToEdge.kt b/app/src/main/java/com/google/android/diskusage/ui/common/EdgeToEdge.kt new file mode 100644 index 00000000..039cc7b2 --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/ui/common/EdgeToEdge.kt @@ -0,0 +1,59 @@ +package com.google.android.diskusage.ui.common + +import android.app.Activity +import android.view.View +import androidx.core.graphics.Insets +import androidx.core.view.ViewCompat +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding + +/** + * Modern edge-to-edge handling. + * + * Starting with Android 15 (API 35) apps are drawn edge-to-edge whether they + * want it or not, and Android 16 (API 36) removed the opt-out flag. Instead of + * fighting the platform we let the window extend behind the system bars and + * apply the system bar / cutout insets as padding ourselves. + */ +object EdgeToEdge { + + @JvmStatic + fun enable(activity: Activity) { + WindowCompat.setDecorFitsSystemWindows(activity.window, false) + } + + /** Applies the system bar insets of the current window to [view] as padding. */ + @JvmStatic + fun applyInsets(view: View) { + applyInsets(view, 0, 0) + } + + /** + * Applies top/bottom/left/right system bar insets to [view] as padding. + * [extraTop]/[extraBottom] preserve existing spacing. + */ + @JvmStatic + fun applyInsets(view: View, extraTop: Int, extraBottom: Int) { + val initial = Insets.of( + view.paddingLeft, + view.paddingTop + extraTop, + view.paddingRight, + view.paddingBottom + extraBottom, + ) + ViewCompat.setOnApplyWindowInsetsListener(view) { v, windowInsets -> + val bars: Insets = windowInsets.getInsets( + WindowInsetsCompat.Type.systemBars() or + WindowInsetsCompat.Type.displayCutout() + ) + v.updatePadding( + left = initial.left + bars.left, + top = initial.top + bars.top, + right = initial.right + bars.right, + bottom = initial.bottom + bars.bottom, + ) + windowInsets + } + ViewCompat.requestApplyInsets(view) + } +} diff --git a/app/src/main/java/com/google/android/diskusage/ui/common/FileInfo.kt b/app/src/main/java/com/google/android/diskusage/ui/common/FileInfo.kt new file mode 100644 index 00000000..401dde5e --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/ui/common/FileInfo.kt @@ -0,0 +1,3 @@ +package com.google.android.diskusage.ui.common + +data class FileInfo(val size: String, val name: String) \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/ui/common/FileInfoAdapter.java b/app/src/main/java/com/google/android/diskusage/ui/common/FileInfoAdapter.java deleted file mode 100644 index 8f6bbea4..00000000 --- a/app/src/main/java/com/google/android/diskusage/ui/common/FileInfoAdapter.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * DiskUsage - displays sdcard usage on android. - * Copyright (C) 2008-2011 Ivan Volosyuk - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package com.google.android.diskusage.ui.common; - -import java.io.File; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.Set; -import java.util.TreeSet; -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import android.content.Context; -import android.os.Handler; -import android.os.Looper; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.BaseAdapter; -import android.widget.TextView; -import androidx.annotation.NonNull; -import com.google.android.diskusage.R; -import com.google.android.diskusage.databinding.ListDirItemBinding; -import com.google.android.diskusage.databinding.ListFileItemBinding; -import com.google.android.diskusage.filesystem.entity.FileSystemEntry; - -// TODO: Use RecyclerView and RecyclerAdapter -public class FileInfoAdapter extends BaseAdapter { - private int itemCount; - private final String deletePath; - private final TextView summaryView; - private final Context context; - - public FileInfoAdapter(Context context, String deletePath, - int count, TextView summary) { - this.context = context; - this.itemCount = count; - this.deletePath = deletePath; - this.summaryView = summary; - } - private boolean isFinished = false; - - private final ArrayList entries = new ArrayList<>(); - private final LinkedList workingSet = new LinkedList<>(); - private String parentBase; - private String currentDir = ""; - private long totalSize; - - private LoaderTaskRunner taskRunner; - private static final Executor THREAD_POOL_EXECUTOR = - new ThreadPoolExecutor(5, 128, 1, - TimeUnit.SECONDS, new LinkedBlockingQueue<>()); - - public static void setMessage( - @NonNull Context context, @NonNull TextView textView, int numfiles, String sizeString) { - String text = context.getString( - R.string.delete_summary, numfiles, sizeString); - textView.setText(text); - } - - static class Entry { - String size; - String name; - - Entry(String size, String name) { - this.size = size; - this.name = name; - } - } - - private void prepareRoots() { - File topEntity = new File(deletePath); - parentBase = topEntity.getParent(); - workingSet.add(topEntity.getName()); - } - - private boolean loadOne(ArrayList newEntries) { - if (parentBase == null) prepareRoots(); - - while (!workingSet.isEmpty()) { - //* if (workingSet.isEmpty()) { -// finished = true; -// count = entries.size(); -// notifyDataSetChanged(); -// if (summary != null) -// summary.setText( -// String.format("%d files, total size: %s", -// count, FileSystemEntry.calcSizeString(totalSize))); - //return false; - //} - - String last = workingSet.removeLast(); - File currentEntity = new File(parentBase + File.separatorChar + last); - if (currentEntity.isFile()) { - String dirName = ""; - int sep = last.lastIndexOf(File.separatorChar); - if (sep != -1) { - dirName = last.substring(0, sep); - last = last.substring(sep + 1); - } - if (!dirName.equals(currentDir)) { - newEntries.add(new Entry(null, dirName)); - currentDir = dirName; - } - long size = currentEntity.length(); - totalSize += size; - newEntries.add(new Entry(FileSystemEntry.calcSizeString(size), last)); -// notifyDataSetChanged(); - return true; - } - - File[] entries = currentEntity.listFiles(); - Set dirs = new TreeSet<>(String::compareToIgnoreCase); - Set files = new TreeSet<>(String::compareToIgnoreCase); - - if (entries == null) continue; - - for (File entity : entries) { - String name = entity.getName(); - if (entity.isFile()) { - files.add(last + File.separatorChar + name); - } else { - dirs.add(last + File.separatorChar + name); - } - } - workingSet.addAll(dirs); - workingSet.addAll(files); - } - return false; - } - -//* public void load(int pos) { -// while (!finished && entries.size() <= pos + 10) { -// loadOne(); -// } -// } - - @Override - public int getCount() { - return Math.max(itemCount, entries.size() + (isFinished ? 0 : 1)); - } - - @Override - public int getViewTypeCount() { - return 2; - } - - @Override - public Object getItem(int position) { - if (position >= entries.size()) { - return new Entry("", ". . . . ."); - } - return entries.get(position); - } - - @Override - public int getItemViewType(int position) { - Entry entry = (Entry) getItem(position); - - return (entry.size == null) ? 1 : 0; - } - - @Override - public long getItemId(int position) { - return position; - } - - public boolean isRunning = false; - // TODO: Use Kotlin CoroutineScope - static class LoaderTaskRunner { - private final Executor executor = THREAD_POOL_EXECUTOR; - private final Handler handler = new Handler(Looper.getMainLooper()); - - public interface Callback { - void onComplete(R result); - } - - public void executeAsync(Callable callable, Callback callback) { - executor.execute(() -> { - try { - final R result = callable.call(); - handler.post(() -> { - callback.onComplete(result); - }); - } catch (Exception e) { - e.printStackTrace(); - } - }); - } - } - - class LoaderTask implements Callable> { - // int currentPos; - private final Integer input; - public LoaderTask(/* int currentPos, */Integer input) { - //this.currentPos = currentPos; - this.input = input; - } - - @Override - public ArrayList call() { - int toLoad = input; - ArrayList newEntries = new ArrayList<>(); - for (int i = 0; i < toLoad; i++) { - if (!loadOne(newEntries)) { - return newEntries; - } - } - return newEntries; - } - } - - private int maxPos; - private void onPostExecute(@NonNull ArrayList newEntries) { - isRunning = false; - if (newEntries.size() == 0) { - isFinished = true; - itemCount = entries.size(); - notifyDataSetChanged(); - summaryView.setText(context.getString(R.string.delete_summary, - itemCount, FileSystemEntry.calcSizeString(totalSize))); - } else { - entries.addAll(newEntries); - notifyDataSetChanged(); - - int toLoad = maxPos + 200 - entries.size(); - if (toLoad > 0) { - isRunning = true; - taskRunner.executeAsync(new LoaderTask(20), this::onPostExecute); // request even more - } - } - } - - @Override - public View getView(int position, View view, ViewGroup parent) { - if (!isFinished) { - if (isRunning) { - if (position > maxPos) maxPos = position; - } else { - taskRunner = new LoaderTaskRunner(); - int toLoad = position + 200 - entries.size(); - if (toLoad > 0) { - isRunning = true; - taskRunner.executeAsync(new LoaderTask(20), this::onPostExecute); // request even more - } - } - } - - final Entry entry = (Entry) getItem(position); - final LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); - - if (entry.size == null) { - // directory - final ListDirItemBinding binding; - if (view != null) { - binding = ListDirItemBinding.bind(view); - } else { - binding = ListDirItemBinding.inflate(layoutInflater); - } - binding.name.setText(entry.name); - return binding.getRoot(); - } else { - final ListFileItemBinding binding; - if (view != null) { - binding = ListFileItemBinding.bind(view); - } else { - binding = ListFileItemBinding.inflate(layoutInflater); - } - binding.name.setText(entry.name); - binding.size.setText(entry.size); - return binding.getRoot(); - } - } - - @Override - public boolean areAllItemsEnabled() { - return false; - } - - @Override - public boolean isEnabled(int position) { - return false; - } - - public boolean hasStableIds() { - return true; - } -} diff --git a/app/src/main/java/com/google/android/diskusage/ui/common/FileInfoAdapter.kt b/app/src/main/java/com/google/android/diskusage/ui/common/FileInfoAdapter.kt new file mode 100644 index 00000000..7d472158 --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/ui/common/FileInfoAdapter.kt @@ -0,0 +1,73 @@ +/* + * DiskUsage - displays sdcard usage on android. + * Copyright (C) 2008-2011 Ivan Volosyuk + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package com.google.android.diskusage.ui.common + +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.core.view.updateLayoutParams +import androidx.recyclerview.widget.RecyclerView +import androidx.viewbinding.ViewBinding +import com.google.android.diskusage.databinding.ListDirItemBinding +import com.google.android.diskusage.databinding.ListFileItemBinding + +class FileInfoAdapter(private val infos: List) : + RecyclerView.Adapter() { + class ViewHolder(val ui: ViewBinding) : RecyclerView.ViewHolder(ui.root) + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + val inflater = LayoutInflater.from(parent.context) + val ui = if (viewType == 0) { + ListFileItemBinding.inflate(inflater) + } else { + ListDirItemBinding.inflate(inflater) + } + ui.root.layoutParams = ViewGroup.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT + ) + return ViewHolder(ui) + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + val fileInfo = infos[position] + if (fileInfo.size.isEmpty()) { + // directory + val ui = holder.ui as ListDirItemBinding + ui.name.text = fileInfo.name + } else { + val ui = holder.ui as ListFileItemBinding + ui.name.text = fileInfo.name + ui.size.text = fileInfo.size + } + } + + + override fun getItemCount(): Int { + return infos.size + } + + override fun getItemViewType(position: Int): Int { + val fileInfo = infos[position] + return if ((fileInfo.size.isEmpty())) 1 else 0 + } + + override fun getItemId(position: Int): Long { + return position.toLong() + } +} diff --git a/app/src/main/java/com/google/android/diskusage/ui/common/Permissions.kt b/app/src/main/java/com/google/android/diskusage/ui/common/Permissions.kt new file mode 100644 index 00000000..78667203 --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/ui/common/Permissions.kt @@ -0,0 +1,121 @@ +package com.google.android.diskusage.ui.common + +import android.app.Activity +import android.app.AppOpsManager +import android.app.usage.UsageStatsManager +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.os.Environment +import android.os.Process +import android.provider.Settings +import timber.log.Timber + +/** + * Central place for the two special permissions the analyser needs. + * + * Both are "app ops" and are not listed under *Settings → Apps → Permissions*, + * which is why the app shows their state itself (menu → Permissions). + */ +object Permissions { + + /** "All files access" on Android 11+, always true on older releases. */ + @JvmStatic + fun hasAllFilesAccess(): Boolean { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return true + return try { + Environment.isExternalStorageManager() + } catch (t: Throwable) { + false + } + } + + /** + * Usage access, needed only for exact per-app data sizes. + * + * `AppOpsManager.checkOpNoThrow` reports `MODE_DEFAULT` on several ROMs + * (MIUI/HyperOS in particular) even after the user enabled the toggle, so a + * query is used as a second opinion before reporting "denied". + */ + @JvmStatic + fun hasUsageAccess(context: Context): Boolean { + val appOps = try { + context.getSystemService(Context.APP_OPS_SERVICE) as? AppOpsManager + } catch (t: Throwable) { + null + } + if (appOps != null) { + try { + val mode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + appOps.unsafeCheckOpNoThrow( + AppOpsManager.OPSTR_GET_USAGE_STATS, Process.myUid(), context.packageName + ) + } else { + @Suppress("DEPRECATION") + appOps.checkOpNoThrow( + AppOpsManager.OPSTR_GET_USAGE_STATS, Process.myUid(), context.packageName + ) + } + Timber.d("hasUsageAccess: app-op mode = %s", mode) + when (mode) { + AppOpsManager.MODE_ALLOWED -> return true + AppOpsManager.MODE_IGNORED, AppOpsManager.MODE_ERRORED -> return false + // MODE_DEFAULT: the platform has no explicit decision yet, ask + // the stats service whether the data is actually readable. + } + } catch (t: Throwable) { + // Fall through to the query below. + } + } + return usageStatsReadable(context) + } + + private fun usageStatsReadable(context: Context): Boolean { + return try { + val manager = context.getSystemService(Context.USAGE_STATS_SERVICE) as? UsageStatsManager + ?: return false + val now = System.currentTimeMillis() + val stats = manager.queryUsageStats( + UsageStatsManager.INTERVAL_DAILY, now - 24 * 60 * 60 * 1000L, now + ) + Timber.d("hasUsageAccess: query returned %s entries", stats?.size ?: -1) + // An empty list can be legitimate (fresh device), but in that case + // there is nothing to gain from usage access either. + !stats.isNullOrEmpty() + } catch (t: Throwable) { + false + } + } + + @JvmStatic + fun openAllFilesAccessSettings(activity: Activity) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return + try { + activity.startActivity( + Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION) + .setData(Uri.parse("package:" + activity.packageName)) + ) + } catch (t: Throwable) { + runCatching { + activity.startActivity(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)) + } + } + } + + @JvmStatic + fun openUsageAccessSettings(activity: Activity) { + try { + activity.startActivity(Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)) + } catch (t: Throwable) { + // Some ROMs hide the activity; fall back to the app details page. + try { + activity.startActivity( + Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) + .setData(Uri.parse("package:" + activity.packageName)) + ) + } catch (ignored: Throwable) { + } + } + } +} diff --git a/app/src/main/java/com/google/android/diskusage/ui/common/ScanProgressDialog.java b/app/src/main/java/com/google/android/diskusage/ui/common/ScanProgressDialog.java index 513b3bee..6953a9d7 100644 --- a/app/src/main/java/com/google/android/diskusage/ui/common/ScanProgressDialog.java +++ b/app/src/main/java/com/google/android/diskusage/ui/common/ScanProgressDialog.java @@ -22,7 +22,7 @@ import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collections; -import android.app.AlertDialog; +import androidx.appcompat.app.AlertDialog; import android.content.Context; import android.graphics.Paint; import android.os.Bundle; diff --git a/app/src/main/java/com/google/android/diskusage/utils/AppHelper.kt b/app/src/main/java/com/google/android/diskusage/utils/AppHelper.kt index a1f961e2..145d2227 100644 --- a/app/src/main/java/com/google/android/diskusage/utils/AppHelper.kt +++ b/app/src/main/java/com/google/android/diskusage/utils/AppHelper.kt @@ -1,9 +1,10 @@ package com.google.android.diskusage.utils +import android.content.Context import com.google.android.diskusage.DiskUsageApplication object AppHelper { @JvmStatic - val appContext get() = DiskUsageApplication.getInstance().applicationContext + val appContext: Context get() = DiskUsageApplication.getInstance().applicationContext } \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/utils/DeviceHelper.kt b/app/src/main/java/com/google/android/diskusage/utils/DeviceHelper.kt index 81d05623..76c2a2b1 100644 --- a/app/src/main/java/com/google/android/diskusage/utils/DeviceHelper.kt +++ b/app/src/main/java/com/google/android/diskusage/utils/DeviceHelper.kt @@ -3,20 +3,15 @@ package com.google.android.diskusage.utils import java.io.File object DeviceHelper { + private val SU = "su" + private val suLocations = arrayOf( + "/system/bin/", "/system/xbin/", "/sbin/", "/system/sd/xbin/", + "/system/bin/failsafe/", "/data/local/xbin/", "/data/local/bin/", "/data/local/", + "/system/sbin/", "/usr/bin/", "/vendor/bin/" + ) @JvmStatic fun isDeviceRooted(): Boolean { - val su = "su" - val locations = arrayOf( - "/system/bin/", "/system/xbin/", "/sbin/", "/system/sd/xbin/", - "/system/bin/failsafe/", "/data/local/xbin/", "/data/local/bin/", "/data/local/", - "/system/sbin/", "/usr/bin/", "/vendor/bin/" - ) - for (location in locations) { - if (File("${location}${su}").exists()) { - return true - } - } - return false + return suLocations.any { location -> File(location, SU).exists() } } } diff --git a/app/src/main/java/com/google/android/diskusage/utils/Logger.kt b/app/src/main/java/com/google/android/diskusage/utils/Logger.kt deleted file mode 100644 index a6893347..00000000 --- a/app/src/main/java/com/google/android/diskusage/utils/Logger.kt +++ /dev/null @@ -1,117 +0,0 @@ -package com.google.android.diskusage.utils - -import android.util.Log -import java.util.Locale - -class Logger(val TAG: String) { - companion object { - @JvmStatic - val LOGGER: Logger = Logger("DiskUsage") - } - - fun isLoggable(tag: String, level: Int): Boolean { - return true - } - - fun v(msg: String) { - if (isLoggable(TAG, Log.VERBOSE)) { - Log.v(TAG, msg) - } - } - - fun v(fmt: String, vararg args: Any?) { - if (isLoggable(TAG, Log.VERBOSE)) { - Log.v(TAG, String.format(Locale.ENGLISH, fmt, *args)) - } - } - - fun v(msg: String, tr: Throwable) { - if (isLoggable(TAG, Log.VERBOSE)) { - Log.v(TAG, msg, tr) - } - } - - fun d(msg: String) { - if (isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, msg) - } - } - - fun d(fmt: String, vararg args: Any?) { - if (isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, String.format(Locale.ENGLISH, fmt, *args)) - } - } - - fun d(msg: String, tr: Throwable) { - if (isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, msg, tr) - } - } - - fun i(msg: String) { - if (isLoggable(TAG, Log.INFO)) { - Log.i(TAG, msg) - } - } - - fun i(fmt: String, vararg args: Any?) { - if (isLoggable(TAG, Log.INFO)) { - Log.i(TAG, String.format(Locale.ENGLISH, fmt, *args)) - } - } - - fun i(msg: String, tr: Throwable) { - if (isLoggable(TAG, Log.INFO)) { - Log.i(TAG, msg, tr) - } - } - - fun w(msg: String) { - if (isLoggable(TAG, Log.WARN)) { - Log.w(TAG, msg) - } - } - - fun w(fmt: String, vararg args: Any?) { - if (isLoggable(TAG, Log.WARN)) { - Log.w(TAG, String.format(Locale.ENGLISH, fmt, *args)) - } - } - - fun w(tr: Throwable, fmt: String, vararg args: Any?) { - if (isLoggable(TAG, Log.WARN)) { - Log.w(TAG, String.format(Locale.ENGLISH, fmt, *args), tr) - } - } - - fun w(msg: String, tr: Throwable) { - if (isLoggable(TAG, Log.WARN)) { - Log.w(TAG, msg, tr) - } - } - - fun e(msg: String) { - if (isLoggable(TAG, Log.ERROR)) { - Log.e(TAG, msg) - } - } - - fun e(fmt: String, vararg args: Any?) { - if (isLoggable(TAG, Log.ERROR)) { - Log.e(TAG, String.format(Locale.ENGLISH, fmt, *args)) - } - } - - fun e(tr: Throwable, fmt: String, vararg args: Any?) { - if (isLoggable(TAG, Log.ERROR)) { - Log.e(TAG, String.format(Locale.ENGLISH, fmt, *args), tr) - } - } - - fun e(msg: String, tr: Throwable) { - if (isLoggable(TAG, Log.ERROR)) { - Log.e(TAG, msg, tr) - } - } -} \ No newline at end of file diff --git a/app/src/main/java/com/google/android/diskusage/utils/Menu.kt b/app/src/main/java/com/google/android/diskusage/utils/Menu.kt new file mode 100644 index 00000000..fe49db81 --- /dev/null +++ b/app/src/main/java/com/google/android/diskusage/utils/Menu.kt @@ -0,0 +1,72 @@ +package com.google.android.diskusage.utils + +import android.content.res.ColorStateList +import android.os.Build +import android.view.Menu +import android.view.MenuItem +import android.view.SubMenu +import androidx.annotation.ColorInt +import androidx.annotation.DrawableRes +import androidx.annotation.StringRes +import splitties.resources.drawable + +fun MenuItem.setup( + @DrawableRes icon: Int, + @ColorInt iconTint: Int, + showAsAction: Boolean, + onClick: Function0? +): MenuItem { + if (icon != 0 && iconTint != 0) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + iconTintList = ColorStateList.valueOf(iconTint) + setIcon(icon) + } else { + setIcon(AppHelper.appContext.drawable(icon)?.apply { setTint(iconTint) }) + } + } + if (showAsAction) { + setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM) + } + if (onClick != null) { + setOnMenuItemClickListener { + // return false only when the actual callback returns false + onClick.invoke() != false + } + } + return this +} + +fun Menu.item( + @StringRes title: Int, + @DrawableRes icon: Int = 0, + @ColorInt iconTint: Int = 0, + showAsAction: Boolean = false, + onClick: Function0? = null +): MenuItem { + val item = add(title).setup(icon, iconTint, showAsAction, onClick) + return item +} + +fun Menu.item( + title: CharSequence, + @DrawableRes icon: Int = 0, + @ColorInt iconTint: Int = 0, + showAsAction: Boolean = false, + onClick: Function0? = null +): MenuItem { + val item = add(title).setup(icon, iconTint, showAsAction, onClick) + return item +} + +fun Menu.subMenu( + @StringRes title: Int, + @DrawableRes icon: Int, + @ColorInt iconTint: Int, + showAsAction: Boolean = false, + initSubMenu: SubMenu.() -> Unit +): SubMenu { + val sub = addSubMenu(title) + sub.item.setup(icon, iconTint, showAsAction, null) + initSubMenu.invoke(sub) + return sub +} diff --git a/app/src/main/jni/Android.mk b/app/src/main/jni/Android.mk index e3a11202..d6b3aa72 100644 --- a/app/src/main/jni/Android.mk +++ b/app/src/main/jni/Android.mk @@ -19,10 +19,7 @@ include $(CLEAR_VARS) LOCAL_MODULE := scan LOCAL_SRC_FILES := scan.c -# It seems that Google will not allow to run executable from app private -# directory like `/data/data` or /data/user/0` since Android 10. A workaround -# for this is that renaming executable like `libxxx.so`, and Gradle build -# tools will pack it into apk, and app can run it from native library -# directory. But it seems that marking BUILD_SHARED_LIBRARY is the only way to -# do so for Android.mk. +# Built as a shared library and called through JNI. (The historical approach - +# renaming an executable to libscan.so and exec'ing it - crashes on modern +# Android because a shared object has no startup routine.) include $(BUILD_SHARED_LIBRARY) diff --git a/app/src/main/jni/Application.mk b/app/src/main/jni/Application.mk new file mode 100644 index 00000000..af1eaeb6 --- /dev/null +++ b/app/src/main/jni/Application.mk @@ -0,0 +1,13 @@ +# ndk-build configuration for the scanner helper. +# +# The library is loaded through System.loadLibrary(), no longer executed as a +# child process, so the default (compressed, aligned) packaging is fine. + +APP_PLATFORM := android-24 +APP_ABI := arm64-v8a armeabi-v7a x86 x86_64 + +# Build every 64-bit library 16 KB page-size compatible (required on Android 15+ +# devices with 16 KB pages). This makes the linker align LOAD segments to 16 KB. +APP_SUPPORT_FLEXIBLE_PAGE_SIZES := true + +APP_CFLAGS := -O2 -Wall -Wextra -Wno-unused-parameter diff --git a/app/src/main/jni/scan.c b/app/src/main/jni/scan.c index e65b9b4f..298bfe5b 100644 --- a/app/src/main/jni/scan.c +++ b/app/src/main/jni/scan.c @@ -1,3 +1,40 @@ +/* + * Copyright (C) 2008-2011 Ivan Volosyuk + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +/* + * Fast directory tree scanner. + * + * The scanner serialises one entity per record: + * + * 'D' | name NUL | blocks NUL | bytes NUL (directory) + * 'F' | name NUL | blocks NUL | bytes NUL (file) + * 'D' | name NUL | "" | ... (unreadable directory) + * 'Z' (end of directory listing) + * + * + * Historically the code was compiled as a shared library that was executed as + * a child process ("rename it to lib*.so so Android lets you exec it"). That + * stopped working: the resulting ELF is a shared object without a startup + * routine, so exec() crashes immediately on modern Android. The tree walk is + * now called through JNI; the child process path is only kept as a last resort + * for root mode. + */ + #include #include #include @@ -6,10 +43,28 @@ #include #include #include +#include +#include + +#define MAX_OUTPUT_BYTES (128u * 1024u * 1024u) +/* Records are forwarded to Java once this many bytes accumulated. Streaming + keeps memory flat and lets the UI show progress while the tree is walked. */ +#define FLUSH_THRESHOLD (32u * 1024u) +static dev_t dev; +static const char sep = 0; -dev_t dev; -static const int sep = 0; +static char *out_buf; +static size_t out_len; +static size_t out_cap; +static int out_overflow; +static pthread_mutex_t out_lock = PTHREAD_MUTEX_INITIALIZER; + +/* JNI sink used while a scan is running. Guarded by out_lock. */ +static JNIEnv *sink_env; +static jobject sink_object; +static jmethodID sink_on_data; +static int sink_aborted; struct Entity { long long sizeInBlocks; @@ -21,99 +76,171 @@ struct Entity { void scan_dir(const char *path, struct Entity *entity); -const char *getName(const char *path) { - return strrchr(path, '/') + 1; +static const char *getName(const char *path) { + const char *slash = strrchr(path, '/'); + return slash ? slash + 1 : path; +} + +/* Defined below; forwards the current buffer to the Java sink. */ +static void flush_output(void); + +static int out_reserve(size_t extra) { + if (out_overflow || sink_aborted) return -1; + if (out_len + extra > MAX_OUTPUT_BYTES) { + out_overflow = 1; + return -1; + } + if (out_len + extra <= out_cap) return 0; + size_t new_cap = out_cap ? out_cap * 2 : 65536; + while (new_cap < out_len + extra) new_cap *= 2; + if (new_cap > MAX_OUTPUT_BYTES) new_cap = MAX_OUTPUT_BYTES; + char *grown = (char *) realloc(out_buf, new_cap); + if (grown == NULL) { + out_overflow = 1; + return -1; + } + out_buf = grown; + out_cap = new_cap; + return 0; +} + +static void out_bytes(const char *data, size_t len) { + if (out_reserve(len) != 0) return; + memcpy(out_buf + out_len, data, len); + out_len += len; + if (out_len >= FLUSH_THRESHOLD) { + flush_output(); + } +} + +static void out_char(char c) { + out_bytes(&c, 1); +} + +static void out_str(const char *s) { + out_bytes(s, strlen(s)); +} + +static void out_long(long long value) { + char buffer[32]; + int len = snprintf(buffer, sizeof(buffer), "%lld", value); + if (len > 0) out_bytes(buffer, (size_t) len); } -int nfiles = 0; +static void out_reset(void) { + out_len = 0; + out_overflow = 0; + sink_aborted = 0; +} -void dump_file(struct Entity *entity) { - if (entity->isdir) { - putchar('D'); - } else { - putchar('F'); +static void flush_output(void) { + if (out_len == 0) return; + if (sink_env == NULL || sink_object == NULL || sink_on_data == NULL) { + /* Buffered mode (main(): write everything at the end). */ + return; + } + jbyteArray chunk = (*sink_env)->NewByteArray(sink_env, (jsize) out_len); + if (chunk == NULL) { + (*sink_env)->ExceptionClear(sink_env); + sink_aborted = 1; + out_len = 0; + return; + } + (*sink_env)->SetByteArrayRegion(sink_env, chunk, 0, (jsize) out_len, + (const jbyte *) out_buf); + (*sink_env)->CallVoidMethod(sink_env, sink_object, sink_on_data, chunk); + (*sink_env)->DeleteLocalRef(sink_env, chunk); + out_len = 0; + if ((*sink_env)->ExceptionCheck(sink_env)) { + (*sink_env)->ExceptionClear(sink_env); + sink_aborted = 1; } - printf("%s", entity->name); - putchar(sep); - printf("%lld", entity->sizeInBlocks); - putchar(sep); - printf("%lld", entity->sizeInBytes); - putchar(sep); - nfiles++; - if (nfiles % 10 == 0) fflush(stdout); } -void dump(char type) { - putchar(type); +static void dump(char type) { + out_char(type); +} + +static void dump_file(struct Entity *entity) { + out_char(entity->isdir ? 'D' : 'F'); + out_str(entity->name); + out_char(sep); + out_long(entity->sizeInBlocks); + out_char(sep); + out_long(entity->sizeInBytes); + out_char(sep); } -const char *get_error() { - switch(errno) { +static const char *get_error(void) { + switch (errno) { case EACCES: - return "%c%s "; + return " "; case ENOENT: case ENOTDIR: - return "%c%s "; + return " "; default: - return "%c%s "; + return " "; } } -void dump_error(char type, const char *path, - long long sizeInBlocks, long long sizeInBytes) { - printf(get_error(), type, getName(path)); - putchar(sep); - printf("%lld", sizeInBlocks); - putchar(sep); - printf("%lld", sizeInBytes); - putchar(sep); +static void dump_error(char type, const char *path, + long long sizeInBlocks, long long sizeInBytes) { + const char *suffix = get_error(); + out_char(type); + out_str(getName(path)); + out_str(suffix); + out_char(sep); + out_long(sizeInBlocks); + out_char(sep); + out_long(sizeInBytes); + out_char(sep); } -struct Entity *make_entity_internal( - const char *path, - struct stat *stbuf) { - struct Entity *e = malloc(sizeof(struct Entity)); +static struct Entity *make_entity_internal(const char *path, struct stat *stbuf) { + struct Entity *e = (struct Entity *) malloc(sizeof(struct Entity)); + if (e == NULL) return NULL; e->name = strdup(getName(path)); + if (e->name == NULL) { + free(e); + return NULL; + } e->sizeInBlocks = stbuf->st_blocks; e->sizeInBytes = stbuf->st_size; e->isdir = S_ISDIR(stbuf->st_mode); + e->next = NULL; return e; } -struct Entity *make_entity(const char *path) { +static struct Entity *make_entity(const char *path) { struct stat stbuf; - int res = lstat(path, &stbuf); - if (res < 0) { - return NULL; - } - if (stbuf.st_dev != dev) { - return NULL; - } + /* lstat(): symbolic links are reported as links and never followed, so a + link does not "take" the space of its target. */ + if (lstat(path, &stbuf) < 0) return NULL; + if (stbuf.st_dev != dev) return NULL; return make_entity_internal(path, &stbuf); } -char *makePath(const char *base, const char *name) { - int baseLen = strlen(base); - int nameLen = strlen(name); - char *res = (char*) malloc(baseLen + nameLen + 2); - strncpy(res, base, baseLen); +static char *makePath(const char *base, const char *name) { + size_t baseLen = strlen(base); + size_t nameLen = strlen(name); + char *res = (char *) malloc(baseLen + nameLen + 2); + if (res == NULL) return NULL; + memcpy(res, base, baseLen); res[baseLen] = '/'; - strncpy(res + baseLen + 1, name, nameLen); + memcpy(res + baseLen + 1, name, nameLen); res[baseLen + 1 + nameLen] = 0; return res; } void scan_dir(const char *path, struct Entity *dirEntity) { - DIR *dir = opendir(path); - struct Entity *e; struct Entity *curr; struct Entity *prev; - struct Entity *first; + struct Entity *first = NULL; struct Entity **last = &first; + DIR *dir = opendir(path); if (dir == NULL) { - dump_error('D', path, dirEntity->sizeInBlocks, - dirEntity->sizeInBytes); + dump_error('D', path, dirEntity->sizeInBlocks, dirEntity->sizeInBytes); dump('Z'); return; } @@ -121,17 +248,20 @@ void scan_dir(const char *path, struct Entity *dirEntity) { struct dirent *entity; while ((entity = readdir(dir)) != NULL) { - if (entity->d_name[0] == 0 || (entity->d_name[0] == '.' && ( - entity->d_name[1] == 0 || ( - entity->d_name[1] == '.' && entity->d_name[2] == 0)) - )) continue; - const char *entityPath = makePath(path, entity->d_name); + if (entity->d_name[0] == 0 || + (entity->d_name[0] == '.' && + (entity->d_name[1] == 0 || + (entity->d_name[1] == '.' && entity->d_name[2] == 0)))) { + continue; + } + char *entityPath = makePath(path, entity->d_name); + if (entityPath == NULL) continue; struct Entity *e = make_entity(entityPath); - free((void*)entityPath); + free(entityPath); if (e == NULL) continue; if (!e->isdir) { dump_file(e); - free((void*)e->name); + free((void *) e->name); free(e); continue; } @@ -143,12 +273,13 @@ void scan_dir(const char *path, struct Entity *dirEntity) { closedir(dir); curr = first; - while (curr != NULL) { - const char *entityPath = makePath(path, curr->name); - scan_dir(entityPath, curr); - free((void*)entityPath); - free((void*)curr->name); + char *entityPath = makePath(path, curr->name); + if (entityPath != NULL) { + scan_dir(entityPath, curr); + free(entityPath); + } + free((void *) curr->name); prev = curr; curr = curr->next; free(prev); @@ -156,27 +287,88 @@ void scan_dir(const char *path, struct Entity *dirEntity) { dump('Z'); } -void scan_tree(const char *path) { +static void scan_tree(const char *path) { struct stat stbuf; - int res = lstat(path, &stbuf); - if (res == -1) { + if (lstat(path, &stbuf) == -1) { dump_error('D', path, 1, 0); dump('Z'); return; } dev = stbuf.st_dev; - scan_dir(path, make_entity_internal(path, &stbuf)); + struct Entity *root = make_entity_internal(path, &stbuf); + if (root == NULL) { + dump_error('D', path, 1, 0); + dump('Z'); + return; + } + scan_dir(path, root); + free((void *) root->name); + free(root); +} + +/* + * JNI entry point: walks the tree and streams the serialised records to + * `sink.onData(byte[])`. The Java side consumes them incrementally, so the + * progress dialog updates while the scan is running. + * + * Returns JNI_TRUE when the whole tree was delivered. + */ +JNIEXPORT jboolean JNICALL +Java_com_google_android_diskusage_datasource_fast_NativeScannerStream_scanNative( + JNIEnv *env, jclass clazz, jstring jpath, jobject sink) { + (void) clazz; + const char *path = (*env)->GetStringUTFChars(env, jpath, NULL); + if (path == NULL) return JNI_FALSE; + + jclass sink_class = (*env)->GetObjectClass(env, sink); + if (sink_class == NULL) { + (*env)->ReleaseStringUTFChars(env, jpath, path); + return JNI_FALSE; + } + jmethodID on_data = (*env)->GetMethodID(env, sink_class, "onData", "([B)V"); + if (on_data == NULL) { + (*env)->ExceptionClear(env); + (*env)->ReleaseStringUTFChars(env, jpath, path); + return JNI_FALSE; + } + + pthread_mutex_lock(&out_lock); + sink_env = env; + sink_object = sink; + sink_on_data = on_data; + out_reset(); + scan_tree(path); + flush_output(); + jboolean complete = (!sink_aborted && !out_overflow) ? JNI_TRUE : JNI_FALSE; + sink_env = NULL; + sink_object = NULL; + sink_on_data = NULL; + free(out_buf); + out_buf = NULL; + out_cap = 0; + out_len = 0; + pthread_mutex_unlock(&out_lock); + (*env)->ReleaseStringUTFChars(env, jpath, path); + return complete; } +/* Fallback entry point for the legacy child-process mode. */ int main(int argc, char **argv) { - if (argv[1] == 0) { - printf("Need directory argument\n"); - exit(1); + if (argc < 2) { + fprintf(stderr, "Usage: %s \n", argv[0]); + return 1; } if (strchr(argv[1], '/') == NULL) { - printf("Need absolute path\n"); - exit(1); + fprintf(stderr, "Need an absolute path\n"); + return 1; } - putchar(0); + out_reset(); scan_tree(argv[1]); + if (out_len > 0) { + fwrite(out_buf, 1, out_len, stdout); + fflush(stdout); + } + free(out_buf); + out_buf = NULL; + return out_overflow ? 2 : 0; } diff --git a/app/src/main/res/drawable-xhdpi/tv_banner.png b/app/src/main/res/drawable-xhdpi/tv_banner.png new file mode 100644 index 00000000..ba1f8405 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/tv_banner.png differ diff --git a/app/src/main/res/drawable/ic_launcher_monochrome.xml b/app/src/main/res/drawable/ic_launcher_monochrome.xml new file mode 100644 index 00000000..5414812a --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_monochrome.xml @@ -0,0 +1,15 @@ + + + + + + diff --git a/app/src/main/res/layout/activity_common.xml b/app/src/main/res/layout/activity_common.xml index e6f77a64..1d2f8846 100644 --- a/app/src/main/res/layout/activity_common.xml +++ b/app/src/main/res/layout/activity_common.xml @@ -1,12 +1,23 @@ - + android:layout_height="match_parent" + android:orientation="vertical"> + + + android:layout_height="0dp" + android:layout_weight="1" /> - + diff --git a/app/src/main/res/layout/activity_preferences.xml b/app/src/main/res/layout/activity_preferences.xml new file mode 100644 index 00000000..f47f6a8c --- /dev/null +++ b/app/src/main/res/layout/activity_preferences.xml @@ -0,0 +1,22 @@ + + + + + + + + diff --git a/app/src/main/res/layout/delete_view.xml b/app/src/main/res/layout/delete_view.xml index 400cab51..0aa092c7 100644 --- a/app/src/main/res/layout/delete_view.xml +++ b/app/src/main/res/layout/delete_view.xml @@ -1,86 +1,46 @@ - - - - - - - + android:ellipsize="marquee" + android:gravity="start" + android:padding="10dp" + android:singleLine="true" + android:text="placeholder" + app:layout_constraintBottom_toBottomOf="parent" + app:layout_constraintEnd_toEndOf="parent" + app:layout_constraintStart_toStartOf="parent" + app:layout_constraintTop_toBottomOf="@id/list" /> + + + diff --git a/app/src/main/res/layout/list_dir_item.xml b/app/src/main/res/layout/list_dir_item.xml index c602981a..70d3b62e 100644 --- a/app/src/main/res/layout/list_dir_item.xml +++ b/app/src/main/res/layout/list_dir_item.xml @@ -2,7 +2,7 @@ + android:orientation="horizontal"> \ No newline at end of file diff --git a/app/src/main/res/layout/progress.xml b/app/src/main/res/layout/progress.xml index 89800d2e..ab3995a5 100644 --- a/app/src/main/res/layout/progress.xml +++ b/app/src/main/res/layout/progress.xml @@ -14,40 +14,47 @@ limitations under the License. --> - - - - - + + + + + + + + + diff --git a/app/src/main/res/menu/ask_for_delete_menu.xml b/app/src/main/res/menu/ask_for_delete_menu.xml index 55b2ac97..bbc33419 100644 --- a/app/src/main/res/menu/ask_for_delete_menu.xml +++ b/app/src/main/res/menu/ask_for_delete_menu.xml @@ -1,9 +1,10 @@ -

+ + app:showAsAction="ifRoom" /> + app:showAsAction="ifRoom" /> \ No newline at end of file diff --git a/app/src/main/res/menu/menu.xml b/app/src/main/res/menu/menu.xml deleted file mode 100644 index 1ba047d9..00000000 --- a/app/src/main/res/menu/menu.xml +++ /dev/null @@ -1,1128 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 00000000..9c0a599d --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 00000000..9c0a599d --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 00000000..d0813512 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..4d99106f Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 00000000..ab6a55ed Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 00000000..f19902ac Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..a03d78d0 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 00000000..509b96d3 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 00000000..3f1dcd63 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..e9fc2b9d Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 00000000..acdf07d6 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 00000000..c1c4b401 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..a8865dcd Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 00000000..b6bc93ce Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 00000000..2ea673f9 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..05451744 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 00000000..f9f480e9 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index f26fed58..0825af64 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -54,7 +54,7 @@ %s (leer) %1$s (%2$s) App Speicher -SD-Karte +Interner Speicher %1$d Dateien, Gesamtgröße: %2$s Filter... Nur interner Speicher @@ -85,4 +85,22 @@ Frei Systemdaten Auswahl + erteilt + nicht erteilt + Zugriff auf alle Dateien: %1$s\nNutzungsdaten-Zugriff: %2$s\n\nDer Zugriff auf alle Dateien ist nötig, damit DiskUsage jeden Ordner lesen kann. Ohne ihn sind nur die eigenen Dateien der App sichtbar.\n\nDer Zugriff auf Nutzungsdaten ist optional und verbessert nur die Genauigkeit der App-Größen.\n\nBeides sind besondere App-Berechtigungen, deshalb bleibt die normale Berechtigungsliste in den Android-Einstellungen leer. + Alle Dateien + Nutzungsdaten + Einstellungen öffnen + Zugriff auf alle Dateien nötig + Um den gesamten Speicher zu analysieren, braucht DiskUsage den Zugriff auf alle Dateien.\n\nÖffne die Einstellungen und erlaube DiskUsage den Zugriff, dann kehre zu diesem Bildschirm zurück. + Einhängepunkte ein-/ausblenden + Root erforderlich + Belegt: %1$s von %2$s (%3$d%%) + Belegt: <keine Angabe> + Scan abgebrochen + Berechtigungen + Doppeltippen zum Öffnen - Menü für weitere Optionen + Keine App kann diesen Ordner direkt öffnen.\n\nPfad:\n%1$s + Pfad kopieren + Pfad kopiert diff --git a/app/src/main/res/values-night/themes.xml b/app/src/main/res/values-night/themes.xml new file mode 100644 index 00000000..0cf5d066 --- /dev/null +++ b/app/src/main/res/values-night/themes.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml index 6936bc9e..eb817bba 100644 --- a/app/src/main/res/values/colors.xml +++ b/app/src/main/res/values/colors.xml @@ -1,24 +1,10 @@ - - - #00000000 + + #4E7A3A + #35582A + #7BA05B + #FFFFFFFF + #CCFFFFFF #CFFFFFFF diff --git a/app/src/main/res/values/ic_launcher_background.xml b/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 00000000..f42ada65 --- /dev/null +++ b/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #FFFFFF + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 5213a8f7..1623755c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -19,7 +19,7 @@ --> DiskUsage -Utility to examine SD card content and cleanup some space there. +Find the files and directories that use the most space and free up storage again. Scanning directories... Show Delete @@ -55,7 +55,7 @@ %1$s (%2$s) Uninstall multiple apps not supported App Storage -Storage card +Internal storage %1$d files, total size: %2$s Filter... Apps Filter @@ -83,7 +83,7 @@ Install Solid Explorer Media Apps - Press menu to preview or delete + Double tap to open - menu for more options On device. On SD card. @@ -96,4 +96,24 @@ About + Renderer + Software Renderer + Hardware Renderer + All files access needed + To analyse the whole storage DiskUsage needs the "All files access" permission.\n\nOpen Settings and allow access for DiskUsage, then return to this screen. + Show/hide mount points + Root required + Used %1$s of %2$s (%3$d%%) + Used <no information> + Scan interrupted + Permissions + granted + not granted + All files access: %1$s\nUsage access: %2$s\n\nAll files access is required so that DiskUsage can read every folder. Without it only the app\'s own files are visible.\n\nUsage access is optional and only improves how precise the per-app sizes are.\n\nBoth are special app permissions, so the normal permission list in Android\'s app settings stays empty. + All files access + Usage access + Open settings + No app can open this folder directly.\n\nPath:\n%1$s + Copy path + Path copied diff --git a/app/src/main/res/values/theme.xml b/app/src/main/res/values/theme.xml deleted file mode 100644 index 7aeb532c..00000000 --- a/app/src/main/res/values/theme.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 00000000..e4c92f49 --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + diff --git a/app/src/main/res/xml/data_extraction_rules.xml b/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 00000000..736062dd --- /dev/null +++ b/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/xml/locales_config.xml b/app/src/main/res/xml/locales_config.xml new file mode 100644 index 00000000..20356054 --- /dev/null +++ b/app/src/main/res/xml/locales_config.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/app/src/test/java/com/google/android/diskusage/filesystem/mnt/VolumePathHelperTest.java b/app/src/test/java/com/google/android/diskusage/filesystem/mnt/VolumePathHelperTest.java new file mode 100644 index 00000000..ac216f98 --- /dev/null +++ b/app/src/test/java/com/google/android/diskusage/filesystem/mnt/VolumePathHelperTest.java @@ -0,0 +1,49 @@ +package com.google.android.diskusage.filesystem.mnt; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +public class VolumePathHelperTest { + + private static final String PKG = "com.google.android.diskusage"; + + @Test + public void stripsAppFilesSuffixForPrimaryStorage() { + assertEquals("/storage/emulated/0", + VolumePathHelper.stripAppFilesSuffix( + "/storage/emulated/0/Android/data/" + PKG + "/files", PKG)); + } + + @Test + public void stripsAppFilesSuffixForRemovableVolume() { + assertEquals("/storage/1234-ABCD", + VolumePathHelper.stripAppFilesSuffix( + "/storage/1234-ABCD/Android/data/" + PKG + "/files", PKG)); + } + + @Test + public void stripsAndroidDataWithoutMatchingPackage() { + assertEquals("/storage/1234-ABCD", + VolumePathHelper.stripAppFilesSuffix( + "/storage/1234-ABCD/Android/data/other.app/files", PKG)); + } + + @Test + public void keepsPlainVolumePath() { + assertEquals("/storage/1234-ABCD", + VolumePathHelper.stripAppFilesSuffix("/storage/1234-ABCD", PKG)); + } + + @Test + public void handlesNull() { + assertNull(VolumePathHelper.stripAppFilesSuffix(null, PKG)); + assertNull(VolumePathHelper.canonical(null)); + } + + @Test + public void canonicalisesRelativeSegments() { + assertEquals("/tmp", VolumePathHelper.canonical("/tmp/./")); + } +} diff --git a/build.gradle b/build.gradle index 7e559a47..29368883 100644 --- a/build.gradle +++ b/build.gradle @@ -1,24 +1,8 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. -buildscript { - ext.kotlin_version = '1.9.22' - ext.splitties_version = '3.0.0' - repositories { - google() - mavenCentral() - } - dependencies { - classpath 'com.android.tools.build:gradle:8.1.4' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } +plugins { + alias(libs.plugins.android.application) apply false } -allprojects { - repositories { - google() - mavenCentral() - } -} - -task clean(type: Delete) { - delete rootProject.buildDir +tasks.register('clean', Delete) { + delete rootProject.layout.buildDirectory } diff --git a/diskusage-modernize.patch b/diskusage-modernize.patch deleted file mode 100644 index b6cd7a6d..00000000 --- a/diskusage-modernize.patch +++ /dev/null @@ -1,135 +0,0 @@ -diff -ruN '--exclude=.git' diskusage-orig/.github/workflows/build-apk.yml diskusage/.github/workflows/build-apk.yml ---- diskusage-orig/.github/workflows/build-apk.yml 1970-01-01 00:00:00.000000000 +0000 -+++ diskusage/.github/workflows/build-apk.yml 2026-09-05 10:26:57.530054304 +0000 -@@ -0,0 +1,35 @@ -+name: Build APK -+ -+on: -+ push: -+ workflow_dispatch: -+ -+jobs: -+ build: -+ runs-on: ubuntu-latest -+ steps: -+ - uses: actions/checkout@v4 -+ -+ - name: Set up JDK 17 -+ uses: actions/setup-java@v4 -+ with: -+ distribution: 'temurin' -+ java-version: '17' -+ -+ - name: Set up Android SDK -+ uses: android-actions/setup-android@v3 -+ -+ - name: Grant execute permission for gradlew -+ run: chmod +x gradlew -+ -+ - name: Install NDK (needed for the native scan.c build) -+ run: sdkmanager "ndk;25.2.9519653" -+ -+ - name: Build debug APK -+ run: ./gradlew assembleDebug --stacktrace -+ -+ - name: Upload APK -+ uses: actions/upload-artifact@v4 -+ with: -+ name: diskusage-debug-apk -+ path: app/build/outputs/apk/debug/*.apk -diff -ruN '--exclude=.git' diskusage-orig/app/build.gradle diskusage/app/build.gradle ---- diskusage-orig/app/build.gradle 2026-09-05 10:28:13.898964623 +0000 -+++ diskusage/app/build.gradle 2026-09-05 10:27:02.435411492 +0000 -@@ -1,13 +1,14 @@ - apply plugin: 'com.android.application' - apply plugin: 'kotlin-android' --apply plugin: 'com.google.protobuf' - android { -- compileSdkVersion 31 -- buildToolsVersion "31" -+ namespace 'com.google.android.diskusage' -+ compileSdk 34 -+ buildToolsVersion "34.0.0" -+ ndkVersion "25.2.9519653" - - defaultConfig { - applicationId "com.google.android.diskusage" -- targetSdkVersion 30 -+ targetSdk 33 - minSdk 21 - } - buildFeatures { -@@ -47,12 +48,12 @@ - dependencies { - // implementation files('src/main/extra/system.jar') - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" -- implementation 'androidx.core:core-ktx:1.6.0' -- implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2' -- implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2' -- implementation 'me.zhanghai.android.appiconloader:appiconloader:1.3.1' -+ implementation 'androidx.core:core-ktx:1.12.0' -+ implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3' -+ implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3' -+ implementation 'me.zhanghai.android.appiconloader:appiconloader:1.5.0' - implementation "com.louiscad.splitties:splitties-toast:$splitties_version" - implementation "com.louiscad.splitties:splitties-resources:$splitties_version" - -- testImplementation 'junit:junit:4.13.1' -+ testImplementation 'junit:junit:4.13.2' - } -diff -ruN '--exclude=.git' diskusage-orig/app/src/main/AndroidManifest.xml diskusage/app/src/main/AndroidManifest.xml ---- diskusage-orig/app/src/main/AndroidManifest.xml 2026-09-05 10:28:13.900718409 +0000 -+++ diskusage/app/src/main/AndroidManifest.xml 2026-09-05 10:20:19.616269798 +0000 -@@ -1,6 +1,5 @@ - - -@@ -27,7 +26,7 @@ - android:theme="@style/Theme" - android:hardwareAccelerated="true" - android:requestLegacyExternalStorage="true"> -- -+ - - - -diff -ruN '--exclude=.git' diskusage-orig/build.gradle diskusage/build.gradle ---- diskusage-orig/build.gradle 2026-09-05 10:28:13.913377214 +0000 -+++ diskusage/build.gradle 2026-09-05 10:19:36.113573971 +0000 -@@ -1,22 +1,19 @@ - // Top-level build file where you can add configuration options common to all sub-projects/modules. - buildscript { -- ext.kotlin_version = '1.6.20' -+ ext.kotlin_version = '1.9.22' - ext.splitties_version = '3.0.0' - repositories { -- jcenter() - google() - mavenCentral() - } - dependencies { -- classpath 'com.android.tools.build:gradle:7.1.2' -- classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.18' -+ classpath 'com.android.tools.build:gradle:8.1.4' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } - } - - allprojects { - repositories { -- jcenter() - google() - mavenCentral() - } -diff -ruN '--exclude=.git' diskusage-orig/gradle/wrapper/gradle-wrapper.properties diskusage/gradle/wrapper/gradle-wrapper.properties ---- diskusage-orig/gradle/wrapper/gradle-wrapper.properties 2026-09-05 10:28:13.932891197 +0000 -+++ diskusage/gradle/wrapper/gradle-wrapper.properties 2026-09-05 10:19:40.243482848 +0000 -@@ -3,4 +3,4 @@ - distributionPath=wrapper/dists - zipStoreBase=GRADLE_USER_HOME - zipStorePath=wrapper/dists --distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip -+distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip diff --git a/docs/ISSUES.md b/docs/ISSUES.md new file mode 100644 index 00000000..dae8c3a3 --- /dev/null +++ b/docs/ISSUES.md @@ -0,0 +1,122 @@ +# Issue triage: IvanVolosyuk/diskusage + +This file tracks the open issues of the upstream repository +([IvanVolosyuk/diskusage/issues](https://github.com/IvanVolosyuk/diskusage/issues), +snapshot: November 2026) and what this fork does about them. + +Legend: + +| Symbol | Meaning | +|---|---| +| ✅ | Addressed by a code change in this repository | +| 🧩 | Partially addressed / mitigation, the remaining part needs something else | +| 📄 | Answered by documentation, no code change possible or sensible | +| ⛔ | Out of scope (needs root, a Google Play account, a specific device or a new feature) | +| 🕰️ | Obsolete: concerns Android versions below the current `minSdk` (24) | + +## Build / runtime / platform + +| # | Issue | Status | Notes | +|---|---|---|---| +| 104 | Android 15 | ✅ | `compileSdk`/`targetSdk` 37, edge-to-edge insets, 16 KB page-size native libs. | +| 100 | Doesn't work on Android 14 | ✅ | Same as above plus the all-files-access flow on API 30+; volume discovery rewritten. | +| 84 | not compatible with Android 14 | ✅ | Closed upstream, same fix. | +| 106 | Modernize build tooling | ✅ | AGP 9.5, Gradle 9.9, built-in Kotlin, SDK 37, NDK r28c, version catalog, R8. | +| 73 | Support various Android versions | ✅ | `minSdk` 24, `targetSdk` 37, per-version permission handling. | +| 65 | Android 10 compatibility | ✅ | Scoped-storage aware access, `requestLegacyExternalStorage` retained for API 29. | +| 59 | No support android x86(x64) 7.0 | ✅ | All four ABIs are built (`arm64-v8a`, `armeabi-v7a`, `x86`, `x86_64`). | +| 11 | зависает / hangs | 🧩 | The scan worker catches every throwable, the progress dialog is always dismissed, and a stuck helper process is killed after 5 s. A wedged *filesystem* can still look like a hang. | +| 16 | `RuntimeException: Error: no more data` | ✅ | Root cause fixed: the bundled scanner produced no output at all (the exec'd shared object crashed) *and* it emitted a legacy leading NUL byte. Both are fixed; failures still fall back to the Java scanner instead of crashing. | +| 33 | `RuntimeException: Error: no more data` | ✅ | Same fix as #16. | +| 55 | `IOException: Cannot run program "/data/user/0/…"` | ✅ | The scanner is no longer executed as a child process (that is blocked since Android 10 and the ELF segfaulted anyway). It runs in-process through JNI; a failure falls back to the Java scanner instead of crashing. | +| 50 | Version 4.0.2 only for Oreo? | 🕰️ | No longer relevant. | +| 52 | App information missing on 5.1 | 🕰️ | No longer relevant. | + +## Storage detection and scanning + +| # | Issue | Status | Notes | +|---|---|---|---| +| 83 | Disk Usage does not display internal memory for scan | ✅ | `StorageManager.getStorageVolumes()` is now the primary source, with `getExternalFilesDirs()` as fallback. | +| 78 | Support USB storage | ✅ | USB volumes are reported by `StorageManager` and listed with their description. | +| 85 | Android 13: "Download" not separate, added to system storage | 🧩 | `Download` is part of the primary shared volume by design; it is now reachable in the graph. A separate pseudo volume is not planned. | +| 99 | Hidden directories shown as system | 🧩 | Hidden directories are scanned (they are real space usage). "System data" is computed as *total − visible*, so unreadable areas still land there. Granting all-files access reduces the gap. | +| 90 | Can not delete & scan is slow | 🧩 | The delete confirmation lists content on a worker thread (no more ANR), deletion uses all-files access, and scanning now really uses the native scanner (in-process via JNI) instead of always falling back to the Java implementation. | +| 31 | Removable SD not selectable | ✅ | Volume list rewritten. | +| 28 | Unable to scan external sdcard | ✅ | Volume list rewritten. | +| 27 | External SD card not scanned | ✅ | Volume list rewritten. | +| 21 | Folder `/storage/extSdCard` | ✅ | Volume list rewritten. | +| 13 | `/Removable` doesn't show up | ✅ | Volume list rewritten. | +| 26 | Won't scan "o2 space" folder | ✅ | All mounted volumes are listed. | +| 29 | Internal storage mixed with internal sdcard (CM 11) | 🕰️ | CyanogenMod 11 is far below `minSdk`. | +| 25 | Deleted directories still shown after reboot | 🧩 | Cached trees are dropped on "Rescan"; the stale cache is no longer reused across deletions. | +| 20 | Autoselect when only one volume exists | ✅ | The chooser is skipped when exactly one volume is reported. | +| 17 | Links counted as taking the target space | ✅ | The native scanner uses `lstat()` and never follows symlinks (verified, no change needed). | +| 49 | Memory info doesn't match Android settings | 📄 | `StatFs` reports blocks of the mounted volume (including reserved blocks); Android's settings screen uses a different accounting. | +| 56 | "Where has the space gone?" feature | ⛔ | Feature request, not a bug. | +| 66 | Visualise by number of files | ⛔ | Feature request. | +| 91 | Alternative visualisation (pie chart) | ⛔ | Feature request. | +| 94 | UI changes | 🧩 | Dark mode, real toolbars, adaptive/themed icons and a percentage readout landed; a full redesign is out of scope. | +| 15 | Wider columns | ⛔ | Layout preference. | + +## Apps / app storage + +| # | Issue | Status | Notes | +|---|---|---|---| +| 98 | cannot read apps | ✅ | The app list no longer depends on `UsageStatsManager` (which only returns recently used apps). | +| 34 | Cannot scan App Storage | ✅ | Same fix; degrades to APK size when usage access is missing. | +| 105 | App cache sizes not showing (OxygenOS 15) | ✅ | `StorageStats.getCacheBytes()` is used again and cache is no longer subtracted from the data size. | +| 67 | Apps reported as System Data | 🧩 | Apps are now listed independently of usage stats, so fewer bytes fall into "System data". | +| 87 | Analysing `/data` with root does not work | ⛔ | Root mode still relies on executing a helper through `su`; modern Android blocks executing app-provided binaries and SELinux restricts direct `/data` reads. Not fixable reliably across ROMs. | +| 58 | Can't delete a file in `/data` when in root mode | ⛔ | Same as above. | +| 39 | How to delete System data | 📄 | System data is not deletable without root. | +| 22 | [ROOT] FolderMount | ⛔ | Root-only integration. | +| 32 | No root access with Lollipop | 🕰️ | Below `minSdk`. | +| 41 | System memory on Galaxy S5 | 🕰️ | Device-specific, below `minSdk`. | + +## Opening files / integrations + +| # | Issue | Status | Notes | +|---|---|---|---| +| 86 | Regression: no viewer found | ✅ | Content URIs with explicit read grants, real MIME types, `*/*` fallback and directory MIME types (`resource/folder`). | +| 88 | Opening a video in a "strange" mode | ✅ | Same fix: the correct MIME type is sent instead of `binary/octet-stream`. | +| 89 | Double click on a file has no effect | ✅ | Double-tap opens the entry; single tap still selects. | +| 72 | Integration with Material Files | ✅ | `content://` URI + `resource/folder`/`inode/directory`, matching Material Files' intent filters. Folders that no app can open fall back to the system documents provider (Files app) and finally to a copy-path dialog. | +| 74 | Audiobook file type support | ✅ | File type detection now works for any extension known to `MimeTypeMap`, with a `*/*` fallback. | +| 53 | No viewer found | ✅ | Same as #86. | +| 60 | Changing default file manager | 📄 | Android decides which app handles `VIEW`; DiskUsage offers all candidates. | +| 35 | Location of non-installed APK files | 📄 | Use the search function on a directory that contains APK files. | +| 101 | Without actual paths the info is not valuable | 🧩 | The title bar always shows the path of the selected entry; long paths are shortened in the graph. | + +## Distribution / project + +| # | Issue | Status | Notes | +|---|---|---|---| +| 82 | Release the APK on GitHub | ✅ | Automatic releases with APK + `SHA256SUMS.txt`; nightly prerelease. | +| 95 | Add icon and screenshots to F-Droid | ✅ | `fastlane/metadata/android/{en-US,de-DE}` with icon, feature graphic, screenshots and changelogs. | +| 36 | Create git tags for releases | ✅ | Tags `v` are created by the release workflow; `docs/RELEASING.md` documents the scheme. | +| 23 | Sources for 3.4.1 | ✅ | Every release is reproducible from a tag. | +| 92 | Themed icon | ✅ | Adaptive icon with `` layer (Android 13+). | +| 102 | Add Play Store link to the readme | 📄 | The app is not distributed on Google Play; F-Droid and GitHub Releases are the channels. | +| 97 | Google Play not available | 📄 | Same. | +| 63 | App no longer available on Google Play | 📄 | Same. | +| 62 | Android TV | 🧩 | Leanback launcher entry and TV banner added; D-pad navigation already worked. No TV-specific layout. | +| 69 | Kotlin version of the app | 🧩 | Data sources and UI glue are Kotlin; the renderer/scanner core remains Java for performance and history reasons. | +| 57 | Updated zh-rCN translation | 📄 | Translation PRs are welcome; no translation work in this change set. | +| 51 | Estonian translation | 📄 | Same. | +| 18 | Patch for `values/strings.xml` | 🕰️ | Already merged upstream. | +| 14 | Update "Wifi Keyboard" | ⛔ | Unrelated app. | +| 96 | "thanks for the update" | 📄 | Not a defect. | +| 74 | Audiobooks support (see above) | ✅ | — | + +## Verification + +* `./gradlew assembleDebug`, `assembleRelease`, `testDebugUnitTest`, `lintDebug` + pass (AGP 9.5.1, Gradle 9.9.1, JDK 17, SDK 37, NDK r28c). +* The shipped `libscan.so` uses 16 KB LOAD-segment alignment for the 64-bit ABIs + and the APK is 16 KB zip-aligned; the CI workflow enforces this on every push. +* Runtime smoke test on an Android 15 (API 35) emulator with the minified release + build: volume detection, native scan, graph, selection, double tap, file/app + opening, search, renderer switch, delete confirmation and the About dialog were + exercised. Screenshots are not checked in. +* Device-specific issues (vendor ROMs, root, TV hardware) are marked 🧩/⛔ rather + than ✅ because they cannot be verified in this environment. diff --git a/docs/RELEASING.md b/docs/RELEASING.md new file mode 100644 index 00000000..f6ee5521 --- /dev/null +++ b/docs/RELEASING.md @@ -0,0 +1,78 @@ +# Releasing + +Releases are automated with GitHub Actions. Two workflows exist: + +| Workflow | Trigger | Result | +|---|---|---| +| `ci.yml` | every push to a branch / pull request | build, unit tests, lint, debug APK artifact, 16 KB page-size check | +| `release.yml` | every push to `main` (or manual dispatch) | signed release APK, GitHub release, version bump commit | +| `nightly.yml` | daily at 03:00 UTC | refreshed `nightly` prerelease from `main` | + +## Version scheme + +* `version.properties` holds `versionName` and `versionCode`. +* `versionCode` = `major * 10000 + minor * 100 + patch` (`5.1.2` → `50102`). +* A release is published for `v` (for example `v5.0.0`). +* After a successful release, `release.yml` runs `scripts/bump-version.sh patch` + and commits the next development version with `[skip release]`. That commit + is ignored by the workflow (`paths-ignore: version.properties`), so it does not + start another release. + +Manual release with a different bump: + +``` +Actions → Release → Run workflow → bump: minor +``` + +## Signing + +Create a keystore once: + +```bash +keytool -genkeypair -v -keystore release.jks -keyalg RSA -keysize 4096 \ + -validity 10000 -alias diskusage +base64 -w0 release.jks > release.jks.b64 +``` + +Add these repository secrets: + +| Secret | Value | +|---|---| +| `RELEASE_KEYSTORE_BASE64` | contents of `release.jks.b64` | +| `RELEASE_KEYSTORE_PASSWORD` | keystore password | +| `RELEASE_KEY_ALIAS` | `diskusage` | +| `RELEASE_KEY_PASSWORD` | key password | + +Without the secrets the workflow still runs and publishes an APK signed with the +debug key (`ALLOW_DEBUG_SIGNING=true`). Such an APK is **not** upgrade-compatible +with an F-Droid installation. The build itself stays unsigned otherwise, which is +what F-Droid and reproducible builds expect. + +> Keep the keystore outside the repository and back it up. Losing it means users +> cannot upgrade without uninstalling the app. + +## Release notes + +`softprops/action-gh-release` generates the notes from the commits since the +previous tag. Write commit messages in a readable way, e.g. +`fix: detect USB volumes`, `feat: show occupied percentage`. + +## Branch protection + +The release workflow pushes the version bump commit to `main`. If `main` is +protected, allow the GitHub Actions bot to push (or run the bump manually and +push it yourself). + +## Nightly builds + +`nightly.yml` publishes a rolling prerelease with `tag_name: nightly`. It is +replaced on every run; `make_latest: false` keeps it out of the "latest" slot. + +## Local release build + +```bash +./scripts/bump-version.sh minor +./gradlew assembleRelease # signed when keystore.properties exists +git tag v$(sed -n 's/^versionName=//p' version.properties) +git push origin --tags +``` diff --git a/fastlane/metadata/android/de-DE/changelogs/50000.txt b/fastlane/metadata/android/de-DE/changelogs/50000.txt new file mode 100644 index 00000000..aac055d2 --- /dev/null +++ b/fastlane/metadata/android/de-DE/changelogs/50000.txt @@ -0,0 +1,8 @@ +* Unterstützung für Android 17 (API 37), Edge-to-Edge ab Android 15 +* Neue Erkennung von Speichermedien: intern, SD-Karte und USB +* App-Liste ohne Nutzungsdaten, Cache-Größen werden angezeigt +* Dateien und Ordner öffnen wieder zuverlässig in anderen Apps +* Absturz bei Scan-Fehlern behoben (Fallback auf Java-Scanner) +* Dunkelmodus, adaptive und thematische App-Symbole +* Native Bibliotheken mit 16-KB-Seitengröße +* Automatische Releases und F-Droid-Metadaten diff --git a/fastlane/metadata/android/de-DE/full_description.txt b/fastlane/metadata/android/de-DE/full_description.txt new file mode 100644 index 00000000..2de533a7 --- /dev/null +++ b/fastlane/metadata/android/de-DE/full_description.txt @@ -0,0 +1,25 @@ +DiskUsage zeigt, welche Dateien und Verzeichnisse den Speicher deines Geräts +belegen. + +Statt einer einfachen Dateiliste zeichnet die App eine Karte des Speichers: +Jedes Verzeichnis ist ein Rechteck, dessen Fläche proportional zum belegten +Platz ist. Einige Ebenen von Unterverzeichnissen werden gleichzeitig +dargestellt. Zoome in einen Bereich, um hineinzuschauen, und entferne die +großen Blöcke, um Platz zu schaffen. + +Funktionen +* Übersichtskarte für internen Speicher, SD-Karten und USB-Geräte +* Aufschlüsselung je App in Code-, Daten- und Cache-Größe +* Belegter und freier Speicher inklusive Prozentangabe +* Suche über den gesamten gescannten Baum +* Verzeichnisse mit Bestätigungsdialog löschen +* Optionaler Root-Zugriff für beliebige eingebundene Dateisysteme +* Keine Werbung, kein Tracking, kein Netzzugriff + +Ab Android 11 benötigt die App die Berechtigung "Alle Dateien verwalten", +weil zum Analysieren jeder Ordner gelesen werden muss. Ohne sie sind nur die +eigenen Dateien sichtbar. Der Zugriff auf Nutzungsdaten ist optional und wird +nur für exakte App-Datengrößen verwendet. + +DiskUsage ist freie Software unter der GNU General Public License, Version 2 +oder später. diff --git a/fastlane/metadata/android/de-DE/images/featureGraphic.png b/fastlane/metadata/android/de-DE/images/featureGraphic.png new file mode 100644 index 00000000..73a8557e Binary files /dev/null and b/fastlane/metadata/android/de-DE/images/featureGraphic.png differ diff --git a/fastlane/metadata/android/de-DE/images/icon.png b/fastlane/metadata/android/de-DE/images/icon.png new file mode 100644 index 00000000..52fa2358 Binary files /dev/null and b/fastlane/metadata/android/de-DE/images/icon.png differ diff --git a/fastlane/metadata/android/de-DE/images/phoneScreenshots/1_storage_overview.png b/fastlane/metadata/android/de-DE/images/phoneScreenshots/1_storage_overview.png new file mode 100644 index 00000000..2379abdf Binary files /dev/null and b/fastlane/metadata/android/de-DE/images/phoneScreenshots/1_storage_overview.png differ diff --git a/fastlane/metadata/android/de-DE/images/phoneScreenshots/2_directory_graph.png b/fastlane/metadata/android/de-DE/images/phoneScreenshots/2_directory_graph.png new file mode 100644 index 00000000..894342b3 Binary files /dev/null and b/fastlane/metadata/android/de-DE/images/phoneScreenshots/2_directory_graph.png differ diff --git a/fastlane/metadata/android/de-DE/images/phoneScreenshots/3_landscape.png b/fastlane/metadata/android/de-DE/images/phoneScreenshots/3_landscape.png new file mode 100644 index 00000000..78d4fd60 Binary files /dev/null and b/fastlane/metadata/android/de-DE/images/phoneScreenshots/3_landscape.png differ diff --git a/fastlane/metadata/android/de-DE/short_description.txt b/fastlane/metadata/android/de-DE/short_description.txt new file mode 100644 index 00000000..744c5ac4 --- /dev/null +++ b/fastlane/metadata/android/de-DE/short_description.txt @@ -0,0 +1 @@ +Finde heraus, was deinen Speicher belegt - und lösche es. diff --git a/fastlane/metadata/android/de-DE/title.txt b/fastlane/metadata/android/de-DE/title.txt new file mode 100644 index 00000000..256000f0 --- /dev/null +++ b/fastlane/metadata/android/de-DE/title.txt @@ -0,0 +1 @@ +DiskUsage diff --git a/fastlane/metadata/android/en-US/changelogs/50000.txt b/fastlane/metadata/android/en-US/changelogs/50000.txt new file mode 100644 index 00000000..6a96f973 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/50000.txt @@ -0,0 +1,8 @@ +* Android 17 (API 37) support, edge-to-edge UI on Android 15+ +* Volume detection rewritten: internal storage, SD cards and USB drives +* App list no longer depends on usage statistics; cache sizes are shown +* Fixed opening files and folders in other apps (content URIs, explicit grants) +* Scanner failures no longer crash the app; the Java fallback is used +* Dark mode, adaptive and themed launcher icons +* 16 KB page size compatible native code +* Automatic releases and F-Droid metadata diff --git a/fastlane/metadata/android/en-US/full_description.txt b/fastlane/metadata/android/en-US/full_description.txt new file mode 100644 index 00000000..7388b5b6 --- /dev/null +++ b/fastlane/metadata/android/en-US/full_description.txt @@ -0,0 +1,23 @@ +DiskUsage shows which files and directories occupy the space on your device. + +Instead of a plain file list it draws a map of your storage: every directory is +a rectangle whose area is proportional to the space it consumes, and a few +levels of subdirectories are shown at the same time. Zoom into a region to see +what is inside, and remove the big blocks to free up space. + +Features +* Visual map of internal storage, SD cards and USB drives +* Per-application breakdown of code, data and cache sizes +* Shows used and free space including the percentage that is occupied +* Search across the scanned tree +* Delete whole directories with a confirmation screen +* Optional root support to analyse any mounted file system +* No ads, no tracking, no network access + +The app needs the "All files access" permission on Android 11 and newer, because +analysing the storage requires reading every directory. Without it only the +app's own files are visible. Usage access is optional and only used to show +exact per-app data sizes. + +DiskUsage is free software, licensed under the GNU General Public License +version 2 or later. diff --git a/fastlane/metadata/android/en-US/images/featureGraphic.png b/fastlane/metadata/android/en-US/images/featureGraphic.png new file mode 100644 index 00000000..73a8557e Binary files /dev/null and b/fastlane/metadata/android/en-US/images/featureGraphic.png differ diff --git a/fastlane/metadata/android/en-US/images/icon.png b/fastlane/metadata/android/en-US/images/icon.png new file mode 100644 index 00000000..52fa2358 Binary files /dev/null and b/fastlane/metadata/android/en-US/images/icon.png differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/1_storage_overview.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/1_storage_overview.png new file mode 100644 index 00000000..2379abdf Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/1_storage_overview.png differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/2_directory_graph.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/2_directory_graph.png new file mode 100644 index 00000000..894342b3 Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/2_directory_graph.png differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/3_landscape.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/3_landscape.png new file mode 100644 index 00000000..78d4fd60 Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/3_landscape.png differ diff --git a/fastlane/metadata/android/en-US/short_description.txt b/fastlane/metadata/android/en-US/short_description.txt new file mode 100644 index 00000000..98e09aba --- /dev/null +++ b/fastlane/metadata/android/en-US/short_description.txt @@ -0,0 +1 @@ +Find out what is eating your storage and delete it. diff --git a/fastlane/metadata/android/en-US/title.txt b/fastlane/metadata/android/en-US/title.txt new file mode 100644 index 00000000..256000f0 --- /dev/null +++ b/fastlane/metadata/android/en-US/title.txt @@ -0,0 +1 @@ +DiskUsage diff --git a/gradle.properties b/gradle.properties index 5465fec0..8c89456e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,2 +1,8 @@ -android.enableJetifier=true -android.useAndroidX=true \ No newline at end of file +# Project-wide Gradle settings. +org.gradle.jvmargs=-Xmx3072m -Dfile.encoding=UTF-8 +org.gradle.parallel=true +org.gradle.caching=true +org.gradle.configuration-cache=true + +android.useAndroidX=true +android.nonTransitiveRClass=true diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 00000000..5a80b106 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,32 @@ +[versions] +agp = "9.5.1" +coreKtx = "1.19.1" +appcompat = "1.8.0" +activity = "1.13.0" +constraintlayout = "2.2.2" +recyclerview = "1.4.0" +lifecycle = "2.11.0" +preference = "1.2.1" +coroutines = "1.11.0" +timber = "5.0.1" +appiconloader = "1.5.0" +splitties = "3.0.0" +junit = "4.13.2" + +[libraries] +androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "coreKtx" } +androidx-appcompat = { module = "androidx.appcompat:appcompat", version.ref = "appcompat" } +androidx-activity-ktx = { module = "androidx.activity:activity-ktx", version.ref = "activity" } +androidx-constraintlayout = { module = "androidx.constraintlayout:constraintlayout", version.ref = "constraintlayout" } +androidx-recyclerview = { module = "androidx.recyclerview:recyclerview", version.ref = "recyclerview" } +androidx-lifecycle-viewmodel-ktx = { module = "androidx.lifecycle:lifecycle-viewmodel-ktx", version.ref = "lifecycle" } +androidx-preference = { module = "androidx.preference:preference", version.ref = "preference" } +kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "coroutines" } +timber = { module = "com.jakewharton.timber:timber", version.ref = "timber" } +appiconloader = { module = "me.zhanghai.android.appiconloader:appiconloader", version.ref = "appiconloader" } +splitties-toast = { module = "com.louiscad.splitties:splitties-toast", version.ref = "splitties" } +splitties-resources = { module = "com.louiscad.splitties:splitties-resources", version.ref = "splitties" } +junit = { module = "junit:junit", version.ref = "junit" } + +[plugins] +android-application = { id = "com.android.application", version.ref = "agp" } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 46bb3b13..60d3852c 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ -#Fri Sep 22 18:26:44 AEST 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip diff --git a/scripts/bump-version.sh b/scripts/bump-version.sh new file mode 100755 index 00000000..f6c797e1 --- /dev/null +++ b/scripts/bump-version.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# Bumps versionName/versionCode in version.properties. +# +# Usage: scripts/bump-version.sh [patch|minor|major|] +# versionCode = major * 10000 + minor * 100 + patch (5.1.2 -> 50102) +set -euo pipefail + +cd "$(dirname "$0")/.." + +bump="${1:-patch}" +current=$(sed -n 's/^versionName=//p' version.properties | tr -d '[:space:]') +if [ -z "$current" ]; then + echo "versionName missing in version.properties" >&2 + exit 1 +fi + +case "$bump" in + major|minor|patch) + IFS=. read -r major minor patch <<< "$current" + case "$bump" in + major) major=$((major + 1)); minor=0; patch=0 ;; + minor) minor=$((minor + 1)); patch=0 ;; + patch) patch=$((patch + 1)) ;; + esac + next="$major.$minor.$patch" + ;; + *) + if ! [[ "$bump" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "Invalid version: $bump" >&2 + exit 1 + fi + next="$bump" + IFS=. read -r major minor patch <<< "$next" + ;; +esac + +code=$((major * 10000 + minor * 100 + patch)) +printf 'versionName=%s\nversionCode=%s\n' "$next" "$code" > version.properties +printf 'versionName=%s versionCode=%s (was %s)\n' "$next" "$code" "$current" diff --git a/settings.gradle b/settings.gradle index e7b4def4..4ea65111 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1,24 @@ +pluginManagement { + repositories { + google { + content { + includeGroupByRegex "com\\.android.*" + includeGroupByRegex "com\\.google.*" + includeGroupByRegex "androidx.*" + } + } + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode = RepositoriesMode.PREFER_SETTINGS + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "DiskUsage" include ':app' diff --git a/version.properties b/version.properties new file mode 100644 index 00000000..70ff31b1 --- /dev/null +++ b/version.properties @@ -0,0 +1,2 @@ +versionName=5.0.2 +versionCode=50002