Initial commit: Foto Dup Finder 1.0.1
An Android duplicate-photo finder. Pure-Kotlin core (SHA-256 + dHash hashing, exact and perceptual union-find grouping, three sensitivity presets) with MediaStore access, a persistent SQLite hash index and a tiered ScanEngine behind a Jetpack Compose UI. No INTERNET permission, no ads, no analytics, no account. Ships versionCode 2 / versionName 1.0.1, carrying the scan-stall hardening (BoundedCall breaker) and verified against a 5,363-photo device library. 80 JVM unit tests, lint clean. Release paperwork is in docs/ (Play checklist, store listing, edge-case testing), the upload-ready Play graphics and screenshots in store-assets/, and the generators for those assets in tools/.
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<!--
|
||||
Photo access. The app only ever READS the media library and asks the system
|
||||
(MediaStore.deleteRequest) to delete user-selected items, so it never needs
|
||||
the highly restricted MANAGE_EXTERNAL_STORAGE permission.
|
||||
-->
|
||||
<uses-permission
|
||||
android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="32" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
|
||||
<!-- Android 14+ partial ("Selected photos") access. -->
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED" />
|
||||
<!--
|
||||
Needed only on Android 10 (API 29) to delete via the legacy MediaStore path.
|
||||
Android 11+ deletes through a user-consented system dialog instead.
|
||||
-->
|
||||
<uses-permission
|
||||
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="29"
|
||||
tools:ignore="ScopedStorage" />
|
||||
|
||||
<!--
|
||||
Foreground service used to keep a long scan alive while the app is backgrounded.
|
||||
The `dataSync` type is the one that matches "user-initiated data processing".
|
||||
-->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<!-- Android 13+: shows the scan progress notification (optional, never required). -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
|
||||
<application
|
||||
android:name=".FotoDupApplication"
|
||||
android:allowBackup="true"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:fullBackupContent="@xml/backup_rules"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:enableOnBackInvokedCallback="true"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.FotoDupFinder"
|
||||
tools:targetApi="33">
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:theme="@style/Theme.FotoDupFinder">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!--
|
||||
No scan logic lives here: it mirrors ScanController's progress into an
|
||||
ongoing notification and keeps the process alive during a long scan.
|
||||
-->
|
||||
<service
|
||||
android:name=".service.ScanService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -0,0 +1,28 @@
|
||||
package de.softwareapp_hb.fotodup.finder
|
||||
|
||||
import android.app.Application
|
||||
import de.softwareapp_hb.fotodup.finder.domain.ScanController
|
||||
|
||||
/**
|
||||
* Application entry point.
|
||||
*
|
||||
* Deliberately lightweight: the app has no background singletons, no dependency
|
||||
* injection graph and no network access. Image loading uses Coil's default loader,
|
||||
* and the duplicate index lives in a small SQLite database opened lazily by the
|
||||
* data layer.
|
||||
*/
|
||||
class FotoDupApplication : Application() {
|
||||
|
||||
/**
|
||||
* Owns the running scan. Living on the Application means the scan survives activity
|
||||
* recreation and keeps going while the app is backgrounded (kept alive by
|
||||
* [de.softwareapp_hb.fotodup.finder.service.ScanService]).
|
||||
*/
|
||||
lateinit var scanController: ScanController
|
||||
private set
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
scanController = ScanController(this)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package de.softwareapp_hb.fotodup.finder
|
||||
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.ui.Modifier
|
||||
import de.softwareapp_hb.fotodup.finder.ui.scanner.ScannerScreen
|
||||
import de.softwareapp_hb.fotodup.finder.ui.theme.FotoDupTheme
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
setContent {
|
||||
FotoDupTheme {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
color = MaterialTheme.colorScheme.background,
|
||||
) {
|
||||
ScannerScreen()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/**
|
||||
* Chooses a Hamming threshold from the observed distribution of pair distances instead of
|
||||
* from a fixed constant.
|
||||
*
|
||||
* A constant cannot work at every library size: unrelated pairs grow with the square of the
|
||||
* library, so the closest accidentally-similar pair keeps getting closer as a library grows.
|
||||
* Measured on the benchmark, the widest pHash threshold with zero false pairs fell from
|
||||
* 13 (120 images) to 5 (2 880 images).
|
||||
*
|
||||
* This estimates the unrelated-pair distribution from the upper part of the observed
|
||||
* histogram — where duplicates are effectively absent — and returns the widest threshold
|
||||
* whose **expected number of accidental matches** stays within [budget]. Budgeting the count
|
||||
* rather than the rate is deliberate: what the user notices is how many *wrong* duplicate
|
||||
* groups appear, not what fraction of all pairs they represent.
|
||||
*/
|
||||
object AdaptiveThreshold {
|
||||
|
||||
/** Distances at or above this are assumed to contain no duplicates. */
|
||||
private const val CLEAN_FROM = 20
|
||||
|
||||
/** Below this many observed pairs the tail cannot be modelled, so the ceiling is used. */
|
||||
private const val MIN_SAMPLE = 200
|
||||
|
||||
private const val SQRT_TWO = 1.4142135623730951
|
||||
|
||||
/**
|
||||
* @property threshold effective maximum Hamming distance.
|
||||
* @property expectedFalsePairs estimated accidental matches at that threshold (NaN when
|
||||
* the fallback was used).
|
||||
* @property usedFallback true when there was too little data to model the tail.
|
||||
*/
|
||||
data class Choice(
|
||||
val threshold: Int,
|
||||
val expectedFalsePairs: Double,
|
||||
val usedFallback: Boolean,
|
||||
)
|
||||
|
||||
fun choose(
|
||||
histogram: IntArray,
|
||||
ceiling: Int,
|
||||
budget: Double,
|
||||
cleanFrom: Int = CLEAN_FROM,
|
||||
minSample: Int = MIN_SAMPLE,
|
||||
): Choice {
|
||||
require(ceiling >= 0) { "ceiling must not be negative" }
|
||||
val population = histogram.sum().toDouble()
|
||||
if (population < minSample) {
|
||||
return Choice(ceiling, Double.NaN, usedFallback = true)
|
||||
}
|
||||
|
||||
var count = 0L
|
||||
var sum = 0.0
|
||||
var sumSquares = 0.0
|
||||
for (distance in cleanFrom until histogram.size) {
|
||||
val observed = histogram[distance]
|
||||
count += observed
|
||||
sum += observed.toDouble() * distance
|
||||
sumSquares += observed.toDouble() * distance * distance
|
||||
}
|
||||
if (count < minSample) {
|
||||
return Choice(ceiling, Double.NaN, usedFallback = true)
|
||||
}
|
||||
|
||||
val mean = sum / count
|
||||
val variance = (sumSquares / count) - mean * mean
|
||||
val sd = sqrt(variance.coerceAtLeast(0.25))
|
||||
|
||||
var threshold = -1
|
||||
var expected = 0.0
|
||||
for (candidate in 0..ceiling) {
|
||||
// Continuity correction: a distance of `candidate` means "at most this many bits".
|
||||
val z = (candidate + 0.5 - mean) / sd
|
||||
val estimate = population * normalCdf(z)
|
||||
if (estimate > budget) break
|
||||
threshold = candidate
|
||||
expected = estimate
|
||||
}
|
||||
|
||||
if (threshold < 0) {
|
||||
// Even zero bits of tolerance blows the budget (a very large library): stay as strict
|
||||
// as a Hamming test can be rather than reporting a threshold of -1.
|
||||
val strict = population * normalCdf((0.5 - mean) / sd)
|
||||
return Choice(0, strict, usedFallback = false)
|
||||
}
|
||||
return Choice(threshold, expected, usedFallback = false)
|
||||
}
|
||||
|
||||
private fun normalCdf(z: Double): Double = 0.5 * (1.0 + erf(z / SQRT_TWO))
|
||||
|
||||
/** Abramowitz & Stegun 7.1.26; |error| < 1.5e-7, ample for a threshold heuristic. */
|
||||
private fun erf(x: Double): Double {
|
||||
val sign = if (x < 0) -1.0 else 1.0
|
||||
val magnitude = abs(x)
|
||||
val t = 1.0 / (1.0 + 0.3275911 * magnitude)
|
||||
val polynomial = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t +
|
||||
0.254829592) * t
|
||||
return sign * (1.0 - polynomial * exp(-magnitude * magnitude))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
import java.io.InputStream
|
||||
|
||||
private const val HEX_DIGITS = "0123456789abcdef"
|
||||
|
||||
/** Lower-case hexadecimal representation of these bytes. */
|
||||
fun ByteArray.toHex(): String {
|
||||
val sb = StringBuilder(size * 2)
|
||||
for (b in this) {
|
||||
val v = b.toInt() and 0xFF
|
||||
sb.append(HEX_DIGITS[v ushr 4])
|
||||
sb.append(HEX_DIGITS[v and 0x0F])
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
/** 8-byte big-endian representation, used to stir the file size into a digest. */
|
||||
fun Long.toBigEndianBytes(): ByteArray {
|
||||
val out = ByteArray(8)
|
||||
for (i in 0 until 8) {
|
||||
out[i] = ((this ushr (56 - i * 8)) and 0xFF).toByte()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads up to [max] bytes from this stream, returning fewer only when the stream
|
||||
* ends. Unlike [InputStream.readNBytes] this is available on every API level the
|
||||
* app supports.
|
||||
*/
|
||||
fun InputStream.readAtMost(max: Int): ByteArray {
|
||||
require(max >= 0) { "max must not be negative" }
|
||||
if (max == 0) return ByteArray(0)
|
||||
val out = ByteArray(max)
|
||||
var total = 0
|
||||
while (total < max) {
|
||||
val read = read(out, total, max - total)
|
||||
// A well-behaved stream never returns 0 for a non-empty request, but a non-blocking
|
||||
// pipe-backed descriptor can report "no bytes, try again" *indefinitely*. Spinning on that
|
||||
// hangs the caller, so treat it as the end of the data.
|
||||
if (read <= 0) break
|
||||
total += read
|
||||
}
|
||||
return if (total == max) out else out.copyOf(total)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
/**
|
||||
* Pure arithmetic used when decoding images defensively.
|
||||
*
|
||||
* Kept in `core` with no Android imports so the awkward cases — zero sizes, and the absurd
|
||||
* dimensions a crafted "decompression bomb" can declare — are unit-testable on the JVM.
|
||||
*/
|
||||
object DecodeMath {
|
||||
|
||||
/**
|
||||
* Dimensions beyond this are treated as suspect. A genuine ultra-high-resolution scan is
|
||||
* nowhere near it, and clamping keeps the computed sample size within a range a decoder will
|
||||
* actually accept.
|
||||
*/
|
||||
const val MAX_DIMENSION = 100_000
|
||||
|
||||
/** Upper bound on the returned sample, so `sample * 2` can never overflow. */
|
||||
private const val MAX_SAMPLE = 1 shl 16
|
||||
|
||||
/**
|
||||
* Largest power-of-two subsample that keeps both edges within roughly twice [target].
|
||||
*
|
||||
* Deliberately written with **division rather than multiplication**: a crafted image can
|
||||
* declare 100 000 x 100 000, and `width * height` or `sample * 2` in the wrong form overflows
|
||||
* `Int` and yields a nonsense (or negative) sample size.
|
||||
*/
|
||||
fun sampleSizeFor(width: Int, height: Int, target: Int): Int {
|
||||
if (target <= 0) return 1
|
||||
val safeWidth = width.coerceIn(0, MAX_DIMENSION)
|
||||
val safeHeight = height.coerceIn(0, MAX_DIMENSION)
|
||||
var sample = 1
|
||||
while (
|
||||
sample < MAX_SAMPLE &&
|
||||
(safeWidth / (sample * 2) >= target || safeHeight / (sample * 2) >= target)
|
||||
) {
|
||||
sample *= 2
|
||||
}
|
||||
return sample
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
/**
|
||||
* Minimal union-find (disjoint set) with path compression and union by rank.
|
||||
*
|
||||
* Used to merge photos into duplicate clusters: similarity is transitive within a
|
||||
* scan, so a chain A~B, B~C puts A, B and C in one group.
|
||||
*/
|
||||
internal class DisjointSet(private val size: Int) {
|
||||
|
||||
private val parent = IntArray(size) { it }
|
||||
private val rank = IntArray(size)
|
||||
|
||||
fun find(x: Int): Int {
|
||||
var root = x
|
||||
while (parent[root] != root) root = parent[root]
|
||||
// Path compression.
|
||||
var current = x
|
||||
while (parent[current] != root) {
|
||||
val next = parent[current]
|
||||
parent[current] = root
|
||||
current = next
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
fun union(a: Int, b: Int) {
|
||||
val rootA = find(a)
|
||||
val rootB = find(b)
|
||||
if (rootA == rootB) return
|
||||
when {
|
||||
rank[rootA] < rank[rootB] -> parent[rootA] = rootB
|
||||
rank[rootA] > rank[rootB] -> parent[rootB] = rootA
|
||||
else -> {
|
||||
parent[rootB] = rootA
|
||||
rank[rootA]++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** All clusters, each sorted ascending by index; includes singletons. */
|
||||
fun groups(): List<List<Int>> {
|
||||
val byRoot = LinkedHashMap<Int, MutableList<Int>>()
|
||||
for (i in 0 until size) {
|
||||
byRoot.getOrPut(find(i)) { mutableListOf() }.add(i)
|
||||
}
|
||||
return byRoot.values.toList()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
/** Why a set of photos was considered duplicates. */
|
||||
enum class GroupKind {
|
||||
/** Byte-identical copies. */
|
||||
EXACT,
|
||||
|
||||
/** Visually similar photos (resized / recompressed / lightly edited). */
|
||||
PERCEPTUAL,
|
||||
}
|
||||
|
||||
/**
|
||||
* A set of photos the engine believes are duplicates of each other.
|
||||
*
|
||||
* @property id stable-ish identifier for UI list keys.
|
||||
* @property members never smaller than two, ordered newest first.
|
||||
*/
|
||||
data class DuplicateGroup(
|
||||
val id: String,
|
||||
val kind: GroupKind,
|
||||
val members: List<PhotoFingerprint>,
|
||||
) {
|
||||
/** Combined size of every copy in the group. */
|
||||
val totalBytes: Long get() = members.sumOf { it.sizeBytes }
|
||||
|
||||
/** Size of the largest copy — the one the app suggests keeping. */
|
||||
val largestBytes: Long get() = members.maxOfOrNull { it.sizeBytes } ?: 0L
|
||||
|
||||
/**
|
||||
* Bytes that could be reclaimed by keeping only the largest copy. This is an
|
||||
* estimate: the user decides what to actually delete.
|
||||
*/
|
||||
val reclaimableBytes: Long get() = (totalBytes - largestBytes).coerceAtLeast(0L)
|
||||
|
||||
/**
|
||||
* The copy the app suggests keeping: the largest file, newest on a tie.
|
||||
*
|
||||
* This is the single source of truth — the "BEST" badge, the "select all but best"
|
||||
* helper and the per-group delete action all use it, so they can never disagree.
|
||||
*/
|
||||
fun suggestedKeep(): PhotoFingerprint? =
|
||||
members.maxWithOrNull(
|
||||
compareBy<PhotoFingerprint> { it.sizeBytes }.thenBy { it.dateModifiedSeconds },
|
||||
)
|
||||
|
||||
/** Every member except [suggestedKeep] — i.e. what the app would remove by default. */
|
||||
fun suggestedRemovals(): List<PhotoFingerprint> {
|
||||
val keepId = suggestedKeep()?.id ?: return emptyList()
|
||||
return members.filterNot { it.id == keepId }
|
||||
}
|
||||
|
||||
/**
|
||||
* The members the user has actually ticked in this group.
|
||||
*
|
||||
* This is what a row-wise "remove" acts on, and what the row's button counts, so the label
|
||||
* can never disagree with the action. Right after a scan the selection holds
|
||||
* [suggestedRemovals], so the default one-tap behaviour is unchanged.
|
||||
*/
|
||||
fun selectedMembers(selectedIds: Set<Long>): List<PhotoFingerprint> =
|
||||
members.filter { it.id in selectedIds }
|
||||
|
||||
/**
|
||||
* Members in the order they should be shown: [suggestedKeep] **first**, so it is
|
||||
* always visible as the reference point, even when the group is collapsed and only
|
||||
* the first few thumbnails are displayed. The remaining copies keep the engine's
|
||||
* order (newest first).
|
||||
*/
|
||||
fun displayOrder(): List<PhotoFingerprint> {
|
||||
val keep = suggestedKeep() ?: return members
|
||||
return buildList(members.size) {
|
||||
add(keep)
|
||||
members.forEach { member -> if (member.id != keep.id) add(member) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This group without [ids].
|
||||
*
|
||||
* Used while photos are staged for removal, so the list shows what is *still*
|
||||
* duplicated. Returns `null` when fewer than two copies would remain, because at that
|
||||
* point the set is no longer a duplicate group and should not be listed at all.
|
||||
*/
|
||||
fun without(ids: Set<Long>): DuplicateGroup? {
|
||||
if (ids.isEmpty()) return this
|
||||
val remaining = members.filterNot { it.id in ids }
|
||||
return if (remaining.size < 2) null else copy(members = remaining)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
/**
|
||||
* Turns a list of fingerprinted photos into groups of duplicates.
|
||||
*
|
||||
* Two passes run, in order:
|
||||
* 1. **Exact** — photos sharing a content hash are byte-identical.
|
||||
* 2. **Perceptual** — photos not already in an exact group that are *visually*
|
||||
* similar. Because near-duplicate comparison is the expensive part, candidates
|
||||
* are indexed by 8-bit bands of the 64-bit hash (a standard locality-sensitive
|
||||
* trick) so only likely pairs are ever compared.
|
||||
*
|
||||
* Pure Kotlin, deterministic and unit-testable.
|
||||
*/
|
||||
object DuplicateGrouper {
|
||||
|
||||
/** Bands used to index perceptual hashes for fast candidate lookup. */
|
||||
private const val BANDS = 8
|
||||
private const val BAND_BITS = 64 / BANDS // 8
|
||||
private const val BAND_MASK = (1L shl BAND_BITS) - 1
|
||||
|
||||
/**
|
||||
* Maximum aspect-ratio difference (as a factor) before two photos are assumed
|
||||
* not to be the same shot. Guards against e.g. a square crop matching a wide
|
||||
* photo purely by coincidence.
|
||||
*/
|
||||
private const val MAX_ASPECT_FACTOR = 1.15f
|
||||
|
||||
/** Widest Hamming distance a 64-bit hash can have. */
|
||||
private const val MAX_DISTANCE = 64
|
||||
|
||||
/**
|
||||
* How many accidental matches the adaptive threshold will tolerate per scan. Budgeting the
|
||||
* count rather than the rate is deliberate: what a user notices is how many *wrong*
|
||||
* duplicate groups appear, not what share of all pairs they represent.
|
||||
*/
|
||||
const val DEFAULT_FALSE_POSITIVE_BUDGET = 2.0
|
||||
|
||||
/** Outcome of a grouping pass, including the thresholds that were actually used. */
|
||||
data class GroupingResult(
|
||||
val groups: List<DuplicateGroup>,
|
||||
val thresholds: PerceptualThresholds,
|
||||
/** True when the library was too small to model the distance tail. */
|
||||
val usedFallbackThreshold: Boolean,
|
||||
/** Candidate pairs the banded index proposed (the population the threshold was fitted to). */
|
||||
val observedPairs: Int,
|
||||
)
|
||||
|
||||
fun findGroups(
|
||||
photos: List<PhotoFingerprint>,
|
||||
policy: DuplicatePolicy = DuplicatePolicy.DEFAULT,
|
||||
): List<DuplicateGroup> = findGroupsDetailed(photos, policy).groups
|
||||
|
||||
fun findGroupsDetailed(
|
||||
photos: List<PhotoFingerprint>,
|
||||
policy: DuplicatePolicy = DuplicatePolicy.DEFAULT,
|
||||
falsePositiveBudget: Double = DEFAULT_FALSE_POSITIVE_BUDGET,
|
||||
): GroupingResult {
|
||||
val groups = mutableListOf<DuplicateGroup>()
|
||||
val alreadyGrouped = HashSet<Long>()
|
||||
|
||||
// --- Pass 1: exact duplicates by content hash -------------------------
|
||||
val byContentHash = photos
|
||||
.filter { it.contentHash != null }
|
||||
.groupBy { it.contentHash!! }
|
||||
|
||||
for ((hash, members) in byContentHash) {
|
||||
if (members.size < 2) continue
|
||||
groups += DuplicateGroup(
|
||||
id = "exact:$hash",
|
||||
kind = GroupKind.EXACT,
|
||||
members = orderMembers(members),
|
||||
)
|
||||
members.forEach { alreadyGrouped += it.id }
|
||||
}
|
||||
|
||||
// --- Pass 2: perceptual duplicates -----------------------------------
|
||||
var thresholds = PerceptualThresholds.forPolicy(policy)
|
||||
var usedFallback = false
|
||||
var observedPairs = 0
|
||||
|
||||
if (policy.includePerceptual) {
|
||||
val candidates = photos.filter {
|
||||
it.perceptualHash != null && it.rgbDHash != null && it.id !in alreadyGrouped
|
||||
}
|
||||
if (candidates.size >= 2) {
|
||||
val hashes = LongArray(candidates.size) { candidates[it].perceptualHash!! }
|
||||
val buckets = buildBuckets(hashes)
|
||||
|
||||
// Pass A: fit the threshold to this library rather than trusting a constant.
|
||||
val histogram = IntArray(MAX_DISTANCE + 1)
|
||||
var pairs = 0
|
||||
forEachCandidatePair(hashes, buckets) { i, j ->
|
||||
histogram[PerceptualHash.hammingDistance(hashes[i], hashes[j])]++
|
||||
pairs++
|
||||
}
|
||||
observedPairs = pairs
|
||||
|
||||
val choice = AdaptiveThreshold.choose(
|
||||
histogram = histogram,
|
||||
ceiling = policy.maxPhashDistance,
|
||||
budget = falsePositiveBudget,
|
||||
)
|
||||
usedFallback = choice.usedFallback
|
||||
thresholds = PerceptualThresholds(choice.threshold, policy.maxRgbDistance)
|
||||
|
||||
// Pass B: apply the conjunction. pHash alone is not enough once a library is
|
||||
// large: requiring the colour structure to agree too is what holds precision.
|
||||
val set = DisjointSet(candidates.size)
|
||||
forEachCandidatePair(hashes, buckets) { i, j ->
|
||||
val a = candidates[i]
|
||||
val b = candidates[j]
|
||||
if (aspectCompatible(a, b) &&
|
||||
PerceptualHash.hammingDistance(hashes[i], hashes[j]) <= thresholds.phashDistance &&
|
||||
a.rgbDHash!!.distanceTo(b.rgbDHash!!) <= thresholds.rgbDistance
|
||||
) {
|
||||
set.union(i, j)
|
||||
}
|
||||
}
|
||||
|
||||
set.groups()
|
||||
.filter { it.size >= 2 }
|
||||
.forEach { cluster ->
|
||||
groups += DuplicateGroup(
|
||||
id = "near:${candidates[cluster.first()].id}",
|
||||
kind = GroupKind.PERCEPTUAL,
|
||||
members = orderMembers(cluster.map { candidates[it] }),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return GroupingResult(
|
||||
groups = groups.sortedByDescending { it.reclaimableBytes },
|
||||
thresholds = thresholds,
|
||||
usedFallbackThreshold = usedFallback,
|
||||
observedPairs = observedPairs,
|
||||
)
|
||||
}
|
||||
|
||||
/** Indexes hashes by each of their 8-bit bands: the locality-sensitive candidate filter. */
|
||||
private fun buildBuckets(hashes: LongArray): Array<HashMap<Long, MutableList<Int>>> {
|
||||
val buckets = Array(BANDS) { HashMap<Long, MutableList<Int>>() }
|
||||
hashes.forEachIndexed { index, hash ->
|
||||
for (band in 0 until BANDS) {
|
||||
val value = (hash ushr (band * BAND_BITS)) and BAND_MASK
|
||||
buckets[band].getOrPut(value) { mutableListOf() }.add(index)
|
||||
}
|
||||
}
|
||||
return buckets
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls [action] once for every candidate pair `(i, j)` with `i < j`.
|
||||
*
|
||||
* Each photo gathers its band-neighbours into a reused scratch array — sorted, so the
|
||||
* duplicates a pair shares across several bands collapse — and therefore **no global set of
|
||||
* compared pairs is kept**. The previous implementation stored one boxed `Long` per
|
||||
* candidate pair, which for a 20 000-photo library meant millions of entries and hundreds of
|
||||
* megabytes of retained garbage. Here memory is bounded by the largest neighbour set.
|
||||
*
|
||||
* Candidate recall is exact for thresholds up to 7: with [BANDS] bands, two hashes differing
|
||||
* in at most 7 bits must share an identical band. [DuplicatePolicy.AGGRESSIVE] reaches 18, so
|
||||
* it can miss the occasional pair — the price of not scanning all n² pairs.
|
||||
*/
|
||||
private inline fun forEachCandidatePair(
|
||||
hashes: LongArray,
|
||||
buckets: Array<HashMap<Long, MutableList<Int>>>,
|
||||
action: (Int, Int) -> Unit,
|
||||
) {
|
||||
var scratch = IntArray(64)
|
||||
for (i in hashes.indices) {
|
||||
val hash = hashes[i]
|
||||
var size = 0
|
||||
for (band in 0 until BANDS) {
|
||||
val bucket = buckets[band][(hash ushr (band * BAND_BITS)) and BAND_MASK] ?: continue
|
||||
val required = size + bucket.size
|
||||
if (required > scratch.size) {
|
||||
var capacity = scratch.size
|
||||
while (capacity < required) capacity *= 2
|
||||
scratch = scratch.copyOf(capacity)
|
||||
}
|
||||
for (index in bucket) {
|
||||
if (index != i) scratch[size++] = index
|
||||
}
|
||||
}
|
||||
if (size == 0) continue
|
||||
|
||||
java.util.Arrays.sort(scratch, 0, size)
|
||||
var previous = -1
|
||||
for (k in 0 until size) {
|
||||
val j = scratch[k]
|
||||
if (j == previous) continue
|
||||
previous = j
|
||||
if (j > i) action(i, j)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun aspectCompatible(a: PhotoFingerprint, b: PhotoFingerprint): Boolean {
|
||||
val ratioA = a.aspectRatio ?: return true
|
||||
val ratioB = b.aspectRatio ?: return true
|
||||
if (ratioA <= 0f || ratioB <= 0f) return true
|
||||
val factor = if (ratioA > ratioB) ratioA / ratioB else ratioB / ratioA
|
||||
return factor <= MAX_ASPECT_FACTOR
|
||||
}
|
||||
|
||||
/** Newest first, then largest — a sane default order for review. */
|
||||
private fun orderMembers(members: List<PhotoFingerprint>): List<PhotoFingerprint> =
|
||||
members.sortedWith(
|
||||
compareByDescending<PhotoFingerprint> { it.dateModifiedSeconds }
|
||||
.thenByDescending { it.sizeBytes },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
/** The thresholds actually used for a perceptual pass, after any adaptive adjustment. */
|
||||
data class PerceptualThresholds(
|
||||
val phashDistance: Int,
|
||||
val rgbDistance: Int,
|
||||
) {
|
||||
companion object {
|
||||
fun forPolicy(policy: DuplicatePolicy) =
|
||||
PerceptualThresholds(policy.maxPhashDistance, policy.maxRgbDistance)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How aggressively the engine considers two photos to be duplicates.
|
||||
*
|
||||
* These values are **policy ceilings, not tuned operating points**. The real operating point is
|
||||
* fitted per scan by [AdaptiveThreshold]; the ceiling only bounds what that fit may decide, and
|
||||
* is used directly when a library is too small to fit. Values come from measurement across
|
||||
* three datasets (COCO, BSDS500, DIV2K), not from guesswork — but see the note on the harness.
|
||||
*
|
||||
* @property maxPhashDistance loosest permitted pHash Hamming distance (0..64).
|
||||
* @property maxRgbDistance loosest permitted summed RGB-channel dHash distance (0..192).
|
||||
*/
|
||||
enum class DuplicatePolicy(val maxPhashDistance: Int, val maxRgbDistance: Int) {
|
||||
/** Only byte-identical files. Fastest, zero false positives. */
|
||||
EXACT_ONLY(maxPhashDistance = -1, maxRgbDistance = -1),
|
||||
|
||||
/**
|
||||
* Byte-identical files plus visually very similar ones. Sensible default: the ceiling sits
|
||||
* at the widest cut that still produced zero false pairs on 300 real photographs, so a small
|
||||
* library gets the full benefit while a large one is tightened by the fit.
|
||||
*/
|
||||
BALANCED(maxPhashDistance = 15, maxRgbDistance = 60),
|
||||
|
||||
/**
|
||||
* Also catches heavier re-edits/recompressions, at the cost of more review. The ceiling is
|
||||
* set above the measured F1 optimum (~18 on real photographs) so it stays a bound rather
|
||||
* than becoming the operating point.
|
||||
*/
|
||||
AGGRESSIVE(maxPhashDistance = 22, maxRgbDistance = 84),
|
||||
;
|
||||
|
||||
val includePerceptual: Boolean get() = this != EXACT_ONLY
|
||||
|
||||
companion object {
|
||||
val DEFAULT: DuplicatePolicy = BALANCED
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
import java.io.InputStream
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* Content hashing used to find byte-identical photos.
|
||||
*
|
||||
* Deliberately pure Kotlin/JVM (only the standard library and `java.security`), so
|
||||
* it is fully unit-testable without an Android device or Robolectric.
|
||||
*
|
||||
* The engine works in tiers, cheapest first:
|
||||
* 1. group by file size (two files of different size can never be identical),
|
||||
* 2. compare a cheap [quickSignature] built from size + head/tail bytes,
|
||||
* 3. only then compute the full [sha256] content hash.
|
||||
*/
|
||||
object Hashing {
|
||||
|
||||
/** Bytes sampled from the head (and, when available, the tail) of a file. */
|
||||
const val SIGNATURE_WINDOW = 32 * 1024
|
||||
|
||||
private const val BUFFER_SIZE = 64 * 1024
|
||||
private const val ALGORITHM = "SHA-256"
|
||||
|
||||
/** Full SHA-256 of the given bytes, hex encoded. */
|
||||
fun sha256(bytes: ByteArray): String =
|
||||
MessageDigest.getInstance(ALGORITHM).digest(bytes).toHex()
|
||||
|
||||
/** Full SHA-256 of everything readable from [input]. The stream is not closed. */
|
||||
fun sha256(input: InputStream): String {
|
||||
val digest = MessageDigest.getInstance(ALGORITHM)
|
||||
val buffer = ByteArray(BUFFER_SIZE)
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
// `read == 0` means "no bytes, try again" — a non-blocking pipe-backed descriptor can
|
||||
// report that indefinitely, and spinning on it hangs the whole scan.
|
||||
if (read <= 0) break
|
||||
digest.update(buffer, 0, read)
|
||||
}
|
||||
return digest.digest().toHex()
|
||||
}
|
||||
|
||||
/**
|
||||
* Cheap "probably identical" signature: SHA-256 over the file size plus the
|
||||
* first and last bytes of the file.
|
||||
*
|
||||
* Two files whose size differs, or whose head/tail bytes differ, are guaranteed
|
||||
* to produce different signatures, which removes the vast majority of
|
||||
* same-size candidates before a full hash is computed. Callers that cannot
|
||||
* cheaply read the tail may pass an empty [tail].
|
||||
*/
|
||||
fun quickSignature(size: Long, head: ByteArray, tail: ByteArray = ByteArray(0)): String {
|
||||
val digest = MessageDigest.getInstance(ALGORITHM)
|
||||
digest.update(size.toBigEndianBytes())
|
||||
digest.update(head)
|
||||
digest.update(tail)
|
||||
return digest.digest().toHex()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/**
|
||||
* Perceptual hashing used to find *near* duplicates: photos that were resized,
|
||||
* recompressed or slightly edited.
|
||||
*
|
||||
* Two 64-bit descriptors are available, both compared with a Hamming distance:
|
||||
*
|
||||
* - [fromArgb] — **dHash**: the image is reduced to a 9x8 grayscale grid and each pixel
|
||||
* is compared with its right-hand neighbour. Cheap (no arithmetic beyond subtraction).
|
||||
* - [phashFromArgb] — **pHash**: a 2-D DCT is applied to a 32x32 grayscale grid and the
|
||||
* low-frequency 8x8 block is thresholded at its median. Costs a small DCT but is more
|
||||
* stable under brightness/gamma shifts and re-encoding.
|
||||
*
|
||||
* `core/bench` compares the two on transformed images so the default can be chosen from
|
||||
* measurements rather than opinion.
|
||||
*
|
||||
* Pure Kotlin: the only input is an ARGB pixel array, so this is unit-testable on the JVM.
|
||||
*/
|
||||
object PerceptualHash {
|
||||
|
||||
const val GRID_WIDTH = 9
|
||||
const val GRID_HEIGHT = 8
|
||||
const val BITS = GRID_WIDTH * GRID_HEIGHT // 64 bits total, (9-1)*8 comparisons
|
||||
|
||||
/**
|
||||
* Builds the 64-bit difference hash from a row-major grayscale grid of
|
||||
* [GRID_WIDTH] x [GRID_HEIGHT] luminance values (0..255).
|
||||
*
|
||||
* A bit is set when a pixel is strictly brighter than the pixel on its right.
|
||||
*/
|
||||
fun fromLumaGrid(luma: IntArray): Long {
|
||||
require(luma.size == GRID_WIDTH * GRID_HEIGHT) {
|
||||
"expected ${GRID_WIDTH * GRID_HEIGHT} luminance values but got ${luma.size}"
|
||||
}
|
||||
var hash = 0L
|
||||
var bit = 0
|
||||
for (y in 0 until GRID_HEIGHT) {
|
||||
val row = y * GRID_WIDTH
|
||||
for (x in 0 until GRID_WIDTH - 1) {
|
||||
if (luma[row + x] > luma[row + x + 1]) {
|
||||
hash = hash or (1L shl bit)
|
||||
}
|
||||
bit++
|
||||
}
|
||||
}
|
||||
return hash
|
||||
}
|
||||
|
||||
/**
|
||||
* Downsamples a [width] x [height] ARGB pixel array into the
|
||||
* [GRID_WIDTH] x [GRID_HEIGHT] grayscale grid used by [fromLumaGrid].
|
||||
*/
|
||||
fun lumaGridFromArgb(pixels: IntArray, width: Int, height: Int): IntArray =
|
||||
lumaGrid(pixels, width, height, GRID_WIDTH, GRID_HEIGHT)
|
||||
|
||||
/**
|
||||
* Area-averaged grayscale downsample of [pixels] to [outWidth] x [outHeight].
|
||||
*
|
||||
* Each target cell is the average luminance of the source region mapped onto it
|
||||
* (area averaging), which is more robust than sampling a single pixel.
|
||||
*/
|
||||
internal fun lumaGrid(
|
||||
pixels: IntArray,
|
||||
width: Int,
|
||||
height: Int,
|
||||
outWidth: Int,
|
||||
outHeight: Int,
|
||||
): IntArray = grid(pixels, width, height, outWidth, outHeight) { luminance(it) }
|
||||
|
||||
/** Area-averaged downsample with an arbitrary per-pixel sampling function. */
|
||||
private fun grid(
|
||||
pixels: IntArray,
|
||||
width: Int,
|
||||
height: Int,
|
||||
outWidth: Int,
|
||||
outHeight: Int,
|
||||
sample: (Int) -> Int,
|
||||
): IntArray {
|
||||
require(width > 0 && height > 0) { "width and height must be positive" }
|
||||
require(pixels.size >= width * height) {
|
||||
"pixel array holds ${pixels.size} values but ${width * height} are required"
|
||||
}
|
||||
val out = IntArray(outWidth * outHeight)
|
||||
for (gy in 0 until outHeight) {
|
||||
val y0 = gy * height / outHeight
|
||||
val y1 = maxOf(y0 + 1, (gy + 1) * height / outHeight)
|
||||
for (gx in 0 until outWidth) {
|
||||
val x0 = gx * width / outWidth
|
||||
val x1 = maxOf(x0 + 1, (gx + 1) * width / outWidth)
|
||||
var sum = 0L
|
||||
var count = 0
|
||||
for (y in y0 until minOf(y1, height)) {
|
||||
val row = y * width
|
||||
for (x in x0 until minOf(x1, width)) {
|
||||
sum += sample(pixels[row + x])
|
||||
count++
|
||||
}
|
||||
}
|
||||
out[gy * outWidth + gx] = if (count == 0) 0 else (sum / count).toInt()
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Convenience: ARGB pixels straight to a 64-bit difference hash. */
|
||||
fun fromArgb(pixels: IntArray, width: Int, height: Int): Long =
|
||||
fromLumaGrid(lumaGridFromArgb(pixels, width, height))
|
||||
|
||||
// --- RGB difference hash (per-channel structure) -------------------------
|
||||
|
||||
/**
|
||||
* One 64-bit difference hash per RGB channel, computed from the same pixels as the pHash.
|
||||
*/
|
||||
fun rgbDHashFromArgb(pixels: IntArray, width: Int, height: Int): RgbDHash = RgbDHash(
|
||||
red = fromLumaGrid(channelGrid(pixels, width, height, shift = 16)),
|
||||
green = fromLumaGrid(channelGrid(pixels, width, height, shift = 8)),
|
||||
blue = fromLumaGrid(channelGrid(pixels, width, height, shift = 0)),
|
||||
)
|
||||
|
||||
private fun channelGrid(pixels: IntArray, width: Int, height: Int, shift: Int): IntArray =
|
||||
grid(pixels, width, height, GRID_WIDTH, GRID_HEIGHT) { (it shr shift) and 0xFF }
|
||||
|
||||
// --- pHash (DCT) --------------------------------------------------------
|
||||
|
||||
/** Edge length of the grayscale grid fed into the DCT. */
|
||||
private const val PHASH_SIZE = 32
|
||||
|
||||
/** Size of the low-frequency block that becomes the 64 bits. */
|
||||
private const val PHASH_BLOCK = 8
|
||||
|
||||
private val COS_TABLE: Array<DoubleArray> = Array(PHASH_SIZE) { x ->
|
||||
DoubleArray(PHASH_SIZE) { u -> cos((2 * x + 1) * u * PI / (2 * PHASH_SIZE)) }
|
||||
}
|
||||
|
||||
private val NORM: DoubleArray = DoubleArray(PHASH_SIZE) { u ->
|
||||
if (u == 0) sqrt(1.0 / PHASH_SIZE) else sqrt(2.0 / PHASH_SIZE)
|
||||
}
|
||||
|
||||
/**
|
||||
* 64-bit DCT perceptual hash ("pHash") from ARGB pixels.
|
||||
*
|
||||
* The image is reduced to a 32x32 grayscale grid, a 2-D DCT-II is applied, and the
|
||||
* top-left 8x8 low-frequency block becomes the hash: a bit is set where the
|
||||
* coefficient is above the median of the block.
|
||||
*/
|
||||
fun phashFromArgb(pixels: IntArray, width: Int, height: Int): Long =
|
||||
phashFromLumaGrid(lumaGrid(pixels, width, height, PHASH_SIZE, PHASH_SIZE))
|
||||
|
||||
/** [phashFromArgb] from an already downsampled [PHASH_SIZE]² grayscale grid. */
|
||||
internal fun phashFromLumaGrid(luma: IntArray): Long {
|
||||
require(luma.size == PHASH_SIZE * PHASH_SIZE) {
|
||||
"expected ${PHASH_SIZE * PHASH_SIZE} luminance values but got ${luma.size}"
|
||||
}
|
||||
|
||||
// Separable DCT-II. Only the coefficients inside the low-frequency block are
|
||||
// needed, so each 1-D pass stops after PHASH_BLOCK terms instead of all 32 —
|
||||
// about 10k multiply-adds per image instead of 1M for a naive 2-D DCT.
|
||||
val rows = Array(PHASH_SIZE) { DoubleArray(PHASH_BLOCK) }
|
||||
for (y in 0 until PHASH_SIZE) {
|
||||
val base = y * PHASH_SIZE
|
||||
for (v in 0 until PHASH_BLOCK) {
|
||||
var sum = 0.0
|
||||
for (x in 0 until PHASH_SIZE) sum += luma[base + x] * COS_TABLE[x][v]
|
||||
rows[y][v] = sum * NORM[v]
|
||||
}
|
||||
}
|
||||
|
||||
val block = DoubleArray(PHASH_BLOCK * PHASH_BLOCK)
|
||||
for (u in 0 until PHASH_BLOCK) {
|
||||
for (v in 0 until PHASH_BLOCK) {
|
||||
var sum = 0.0
|
||||
for (y in 0 until PHASH_SIZE) sum += rows[y][v] * COS_TABLE[y][u]
|
||||
block[u * PHASH_BLOCK + v] = sum * NORM[u]
|
||||
}
|
||||
}
|
||||
|
||||
val sorted = block.clone()
|
||||
sorted.sort()
|
||||
val mid = sorted.size / 2
|
||||
val median = (sorted[mid - 1] + sorted[mid]) / 2.0
|
||||
|
||||
var hash = 0L
|
||||
for (i in block.indices) {
|
||||
if (block[i] > median) hash = hash or (1L shl i)
|
||||
}
|
||||
return hash
|
||||
}
|
||||
|
||||
/** Number of differing bits between two hashes. */
|
||||
fun hammingDistance(a: Long, b: Long): Int = java.lang.Long.bitCount(a xor b)
|
||||
|
||||
/** Integer luminance (0..255) of a packed ARGB pixel using Rec. 601 weights. */
|
||||
fun luminance(argb: Int): Int {
|
||||
val r = (argb shr 16) and 0xFF
|
||||
val g = (argb shr 8) and 0xFF
|
||||
val b = argb and 0xFF
|
||||
return (r * 299 + g * 587 + b * 114) / 1000
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
/**
|
||||
* Everything the duplicate engine knows about one photo.
|
||||
*
|
||||
* The hashes are nullable because the engine fills them in progressively: cheap
|
||||
* ones first, and a value stays `null` when the corresponding tier was skipped
|
||||
* (e.g. [perceptualHash] on an [DuplicatePolicy.EXACT_ONLY] scan).
|
||||
*
|
||||
* Pure data: no Android types, so the engine and its tests run on the JVM.
|
||||
*/
|
||||
data class PhotoFingerprint(
|
||||
val id: Long,
|
||||
val sizeBytes: Long,
|
||||
val dateModifiedSeconds: Long,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
/** Cheap size + head/tail signature. */
|
||||
val quickSignature: String? = null,
|
||||
/** Full content SHA-256, present only once the full hash was computed. */
|
||||
val contentHash: String? = null,
|
||||
/** 64-bit DCT perceptual hash, present once the perceptual pass ran. */
|
||||
val perceptualHash: Long? = null,
|
||||
/**
|
||||
* Per-channel difference hash. Required, together with [perceptualHash], for two photos to
|
||||
* count as near-duplicates: pHash sees luminance structure, this sees colour structure.
|
||||
*/
|
||||
val rgbDHash: RgbDHash? = null,
|
||||
) {
|
||||
/** width / height, or `null` when the dimensions are unknown. */
|
||||
val aspectRatio: Float?
|
||||
get() = if (width > 0 && height > 0) width.toFloat() / height.toFloat() else null
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
/**
|
||||
* Both perceptual descriptors for one photo.
|
||||
*
|
||||
* They are always computed together from the same decoded thumbnail: the pHash sees luminance
|
||||
* structure, the [RgbDHash] sees colour structure, and a pair must satisfy both to count as a
|
||||
* near-duplicate.
|
||||
*/
|
||||
data class PerceptualFingerprint(
|
||||
val phash: Long,
|
||||
val rgb: RgbDHash,
|
||||
)
|
||||
|
||||
/**
|
||||
* One 64-bit difference hash per RGB channel.
|
||||
*
|
||||
* Complements the grayscale pHash: pHash captures **luminance** structure, these capture
|
||||
* **colour** structure. Requiring both to agree is what keeps precision intact as a library
|
||||
* grows, because unrelated pairs accumulate with the square of the library size and a single
|
||||
* threshold cannot hold out against that.
|
||||
*/
|
||||
data class RgbDHash(
|
||||
val red: Long,
|
||||
val green: Long,
|
||||
val blue: Long,
|
||||
) {
|
||||
/** Sum of the three channel Hamming distances, 0..192. */
|
||||
fun distanceTo(other: RgbDHash): Int =
|
||||
java.lang.Long.bitCount(red xor other.red) +
|
||||
java.lang.Long.bitCount(green xor other.green) +
|
||||
java.lang.Long.bitCount(blue xor other.blue)
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package de.softwareapp_hb.fotodup.finder.data
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import androidx.core.content.ContextCompat
|
||||
|
||||
/** How much of the photo library the user has granted access to. */
|
||||
enum class MediaAccess {
|
||||
/** No access yet — the app must ask. */
|
||||
NONE,
|
||||
|
||||
/** Android 14+ "Selected photos" mode: only a user-picked subset is visible. */
|
||||
PARTIAL,
|
||||
|
||||
/** Full access to the photo library. */
|
||||
FULL,
|
||||
}
|
||||
|
||||
/**
|
||||
* Central place for the runtime permissions the app asks for.
|
||||
*
|
||||
* Photo access differs per API level:
|
||||
*
|
||||
* - API 33+ (`TIRAMISU`): `READ_MEDIA_IMAGES`
|
||||
* - API 34+ (`UPSIDE_DOWN_CAKE`): optionally `READ_MEDIA_VISUAL_USER_SELECTED` for
|
||||
* partial access
|
||||
* - older: `READ_EXTERNAL_STORAGE`
|
||||
*
|
||||
* `POST_NOTIFICATIONS` (API 33+) is requested in the same dialog so the user only
|
||||
* sees one prompt. It is used solely for the scan-progress notification; if it is
|
||||
* denied the scan still runs, the notification is just hidden.
|
||||
*/
|
||||
object AppPermissions {
|
||||
|
||||
/**
|
||||
* The permissions to request for the running API level. Requesting the legacy and
|
||||
* the granular photo permissions together is the documented way to support both
|
||||
* old and new devices with a single dialog.
|
||||
*/
|
||||
fun requestablePermissions(): Array<String> = buildList {
|
||||
when {
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE -> {
|
||||
add(Manifest.permission.READ_MEDIA_IMAGES)
|
||||
add(Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED)
|
||||
}
|
||||
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> {
|
||||
add(Manifest.permission.READ_MEDIA_IMAGES)
|
||||
}
|
||||
|
||||
else -> {
|
||||
add(Manifest.permission.READ_EXTERNAL_STORAGE)
|
||||
}
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
add(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
}.toTypedArray()
|
||||
|
||||
fun hasFullAccess(context: Context): Boolean = when {
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU ->
|
||||
isGranted(context, Manifest.permission.READ_MEDIA_IMAGES)
|
||||
|
||||
else -> isGranted(context, Manifest.permission.READ_EXTERNAL_STORAGE)
|
||||
}
|
||||
|
||||
/** True when only the user-selected subset of photos is visible. */
|
||||
fun hasPartialAccess(context: Context): Boolean =
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE &&
|
||||
!hasFullAccess(context) &&
|
||||
isGranted(context, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED)
|
||||
|
||||
fun accessState(context: Context): MediaAccess = when {
|
||||
hasFullAccess(context) -> MediaAccess.FULL
|
||||
hasPartialAccess(context) -> MediaAccess.PARTIAL
|
||||
else -> MediaAccess.NONE
|
||||
}
|
||||
|
||||
private fun isGranted(context: Context, permission: String): Boolean =
|
||||
ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package de.softwareapp_hb.fotodup.finder.data
|
||||
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import java.util.concurrent.Callable
|
||||
import java.util.concurrent.ExecutionException
|
||||
import java.util.concurrent.ExecutorService
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.Future
|
||||
import java.util.concurrent.ThreadFactory
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.TimeoutException
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/**
|
||||
* Runs a blocking platform call on its own thread and abandons it if it overruns a deadline.
|
||||
*
|
||||
* `ContentResolver` calls can block *inside the provider* for a long time — or for ever. On
|
||||
* the test device `ContentResolver.loadThumbnail` never returned for one perfectly valid HEIC,
|
||||
* because the provider hung in its own decode. That froze the entire scan at a single photo,
|
||||
* and it cannot be bounded with `withTimeoutOrNull`: coroutine cancellation is **cooperative**,
|
||||
* so a thread parked in a binder transaction or a native read never reaches a cancellation
|
||||
* point. The only way to put a deadline on such a call is to run it on a thread of its own and
|
||||
* stop *waiting* for it.
|
||||
*
|
||||
* When a call is abandoned the thread carrying it stays parked in the provider. That leak is
|
||||
* deliberate and bounded: the thread does no work of its own, the pool is daemon-only so it can
|
||||
* never keep the process alive, dropping one worker is strictly better than losing the scan — and
|
||||
* once several calls in a row have been abandoned, [orNull] stops submitting altogether until the
|
||||
* provider answers again (see [BREAKER_TRIP]).
|
||||
*
|
||||
* Deliberately free of Android imports, so it is testable on the JVM like the rest of the engine.
|
||||
*/
|
||||
internal object BoundedCall {
|
||||
|
||||
/**
|
||||
* Consecutive abandoned calls after which the provider is treated as *stalled*.
|
||||
*
|
||||
* One slow call is a bad file. Several in a row with nothing succeeding in between is the
|
||||
* provider itself — a `MediaProvider` that is restarting, or a blocked FUSE daemon. At that
|
||||
* point waiting out the deadline for every remaining photo is pointless, and it is what made
|
||||
* a device scan sit at one progress value looking frozen for tens of minutes.
|
||||
*/
|
||||
private const val BREAKER_TRIP = 3
|
||||
|
||||
private val executor: ExecutorService = Executors.newCachedThreadPool(
|
||||
ThreadFactory { runnable -> Thread(runnable, "provider-call").apply { isDaemon = true } },
|
||||
)
|
||||
|
||||
/** Abandoned calls since the provider last answered — i.e. threads parked inside it. */
|
||||
private val parked = AtomicInteger(0)
|
||||
|
||||
/** While `now < stalledUntil`, submissions fast-fail instead of parking more threads. */
|
||||
private val stalledUntil = AtomicLong(0L)
|
||||
|
||||
/**
|
||||
* Returns the result of [block], or `null` if it threw or did not finish within [timeoutMs]
|
||||
* (in which case it is abandoned — including anything it still holds, e.g. an open
|
||||
* `ParcelFileDescriptor`).
|
||||
*
|
||||
* While the provider looks stalled, calls return `null` immediately instead of submitting:
|
||||
* that bounds the number of parked threads to roughly one per cooldown and lets the scan
|
||||
* reach its end (reporting the unreadable files) rather than grinding.
|
||||
*/
|
||||
fun <T> orNull(timeoutMs: Long, block: () -> T?): T? {
|
||||
if (System.currentTimeMillis() < stalledUntil.get()) return null
|
||||
|
||||
val future: Future<T?> = executor.submit(Callable { block() })
|
||||
return try {
|
||||
val value = future.get(timeoutMs, TimeUnit.MILLISECONDS)
|
||||
// The provider answered: whatever stalled is over.
|
||||
providerAlive()
|
||||
value
|
||||
} catch (e: TimeoutException) {
|
||||
// Give back what we can; a thread stuck in a binder call will not notice.
|
||||
future.cancel(true)
|
||||
onTimeout(timeoutMs)
|
||||
null
|
||||
} catch (e: ExecutionException) {
|
||||
val cause = e.cause
|
||||
// Cancelling a scan has to keep propagating through here.
|
||||
if (cause is CancellationException) throw cause
|
||||
// The provider answered, just with an error (missing file, revoked permission).
|
||||
providerAlive()
|
||||
null
|
||||
} catch (e: InterruptedException) {
|
||||
future.cancel(true)
|
||||
Thread.currentThread().interrupt()
|
||||
throw CancellationException("interrupted while waiting for a provider call")
|
||||
}
|
||||
}
|
||||
|
||||
private fun onTimeout(timeoutMs: Long) {
|
||||
if (parked.incrementAndGet() >= BREAKER_TRIP) {
|
||||
// Cooldown scales with the call deadline: long enough not to hammer a stalled
|
||||
// provider (at most a thread or two per window), short enough that a brief
|
||||
// MediaProvider restart is picked up again.
|
||||
stalledUntil.set(System.currentTimeMillis() + timeoutMs.coerceAtLeast(1_000L))
|
||||
}
|
||||
}
|
||||
|
||||
private fun providerAlive() {
|
||||
parked.set(0)
|
||||
stalledUntil.set(0L)
|
||||
}
|
||||
|
||||
/** Threads currently abandoned inside the provider (diagnostics and tests). */
|
||||
internal fun parkedCount(): Int = parked.get()
|
||||
|
||||
/** True while submissions are being suppressed because the provider looks stalled. */
|
||||
internal fun isStalled(): Boolean = System.currentTimeMillis() < stalledUntil.get()
|
||||
|
||||
/** Test hook: forget any stall carried over from an earlier test in the same JVM. */
|
||||
internal fun resetForTest() {
|
||||
parked.set(0)
|
||||
stalledUntil.set(0L)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package de.softwareapp_hb.fotodup.finder.data
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.MediaStore
|
||||
|
||||
/**
|
||||
* Deletes user-selected photos.
|
||||
*
|
||||
* On Android 11+ deletion *always* goes through a system consent dialog
|
||||
* (`MediaStore.createDeleteRequest` / `createTrashRequest`): the app can never
|
||||
* delete silently and therefore never needs the heavily restricted
|
||||
* `MANAGE_EXTERNAL_STORAGE` permission, which Google Play scrutinises closely.
|
||||
*
|
||||
* On Android 10 the legacy `ContentResolver.delete` path is used, guarded by
|
||||
* `WRITE_EXTERNAL_STORAGE` (declared with `maxSdkVersion="29"`).
|
||||
*/
|
||||
class MediaDeleter(context: Context) {
|
||||
|
||||
private val resolver: ContentResolver = context.applicationContext.contentResolver
|
||||
|
||||
/** True when the platform requires a user-consented system dialog to delete. */
|
||||
val requiresSystemConsent: Boolean get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
|
||||
|
||||
/** True when photos can be moved to the system trash instead of deleted. */
|
||||
val supportsTrash: Boolean get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
|
||||
|
||||
/**
|
||||
* Builds the pending intent that shows the system "allow deleting" dialog.
|
||||
* Returns `null` on API levels that do not support the request API.
|
||||
*/
|
||||
fun createDeleteRequest(uris: List<Uri>, useTrash: Boolean): PendingIntent? {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R || uris.isEmpty()) return null
|
||||
return if (useTrash) {
|
||||
MediaStore.createTrashRequest(resolver, uris, true)
|
||||
} else {
|
||||
MediaStore.createDeleteRequest(resolver, uris)
|
||||
}
|
||||
}
|
||||
|
||||
/** Direct deletion used on API 26-29. Returns how many rows were removed. */
|
||||
fun deleteDirectly(uris: List<Uri>): Int {
|
||||
var deleted = 0
|
||||
uris.forEach { uri ->
|
||||
try {
|
||||
deleted += resolver.delete(uri, null, null)
|
||||
} catch (e: SecurityException) {
|
||||
// Not allowed to remove this item — skip it and keep going.
|
||||
}
|
||||
}
|
||||
return deleted
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package de.softwareapp_hb.fotodup.finder.data
|
||||
|
||||
import android.content.ContentUris
|
||||
import android.content.Context
|
||||
import android.database.Cursor
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.MediaStore
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* Reads the device image library through MediaStore.
|
||||
*
|
||||
* Only metadata is read here; pixel data is touched later (and lazily) by
|
||||
* [PhotoHasher], so listing a large library stays cheap.
|
||||
*/
|
||||
class MediaStorePhotoSource(context: Context) {
|
||||
|
||||
private val resolver = context.applicationContext.contentResolver
|
||||
|
||||
suspend fun loadPhotos(): List<PhotoRecord> = withContext(Dispatchers.IO) {
|
||||
val collection = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
|
||||
}
|
||||
|
||||
val projection = buildList {
|
||||
add(MediaStore.Images.Media._ID)
|
||||
add(MediaStore.Images.Media.DISPLAY_NAME)
|
||||
add(MediaStore.Images.Media.SIZE)
|
||||
add(MediaStore.Images.Media.DATE_MODIFIED)
|
||||
add(MediaStore.Images.Media.WIDTH)
|
||||
add(MediaStore.Images.Media.HEIGHT)
|
||||
add(MediaStore.Images.Media.MIME_TYPE)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
add(MediaStore.Images.Media.RELATIVE_PATH)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
add(MediaStore.Images.Media.BUCKET_DISPLAY_NAME)
|
||||
}
|
||||
}.toTypedArray()
|
||||
|
||||
val photos = ArrayList<PhotoRecord>()
|
||||
resolver.query(
|
||||
collection,
|
||||
projection,
|
||||
null,
|
||||
null,
|
||||
"${MediaStore.Images.Media.DATE_MODIFIED} DESC",
|
||||
)?.use { cursor -> readRows(cursor, photos) }
|
||||
photos
|
||||
}
|
||||
|
||||
private fun readRows(cursor: Cursor, out: MutableList<PhotoRecord>) {
|
||||
val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
|
||||
val sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE)
|
||||
val dateColumn = cursor.getColumnIndex(MediaStore.Images.Media.DATE_MODIFIED)
|
||||
val widthColumn = cursor.getColumnIndex(MediaStore.Images.Media.WIDTH)
|
||||
val heightColumn = cursor.getColumnIndex(MediaStore.Images.Media.HEIGHT)
|
||||
val nameColumn = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)
|
||||
val mimeColumn = cursor.getColumnIndex(MediaStore.Images.Media.MIME_TYPE)
|
||||
val folderColumn = cursor.getColumnIndex(
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
MediaStore.Images.Media.RELATIVE_PATH
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
MediaStore.Images.Media.BUCKET_DISPLAY_NAME
|
||||
},
|
||||
)
|
||||
|
||||
while (cursor.moveToNext()) {
|
||||
val id = cursor.getLong(idColumn)
|
||||
val size = cursor.getLong(sizeColumn)
|
||||
// Ignore empty/zero-length entries; they cannot be real photos.
|
||||
if (size <= 0L) continue
|
||||
|
||||
out += PhotoRecord(
|
||||
id = id,
|
||||
uri = ContentUris.withAppendedId(
|
||||
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
|
||||
id,
|
||||
),
|
||||
displayName = nameColumn.takeIf { it >= 0 }?.let { cursor.getStringOrNull(it) },
|
||||
sizeBytes = size,
|
||||
dateModifiedSeconds = dateColumn.takeIf { it >= 0 }?.let { cursor.getLong(it) } ?: 0L,
|
||||
width = widthColumn.takeIf { it >= 0 }?.let { cursor.getInt(it) } ?: 0,
|
||||
height = heightColumn.takeIf { it >= 0 }?.let { cursor.getInt(it) } ?: 0,
|
||||
mimeType = mimeColumn.takeIf { it >= 0 }?.let { cursor.getStringOrNull(it) },
|
||||
folder = folderColumn.takeIf { it >= 0 }?.let { cursor.getStringOrNull(it) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun Cursor.getStringOrNull(columnIndex: Int): String? =
|
||||
if (isNull(columnIndex)) null else getString(columnIndex)
|
||||
|
||||
/** Kept for symmetry with the delete flow which needs photo uris by id. */
|
||||
fun uriFor(id: Long): Uri =
|
||||
ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package de.softwareapp_hb.fotodup.finder.data
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Matrix
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.MediaStore
|
||||
import android.util.Size
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import de.softwareapp_hb.fotodup.finder.core.DecodeMath
|
||||
import de.softwareapp_hb.fotodup.finder.core.Hashing
|
||||
import de.softwareapp_hb.fotodup.finder.core.PerceptualFingerprint
|
||||
import de.softwareapp_hb.fotodup.finder.core.PerceptualHash
|
||||
import de.softwareapp_hb.fotodup.finder.core.readAtMost
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.FileInputStream
|
||||
import java.io.IOException
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
/**
|
||||
* Computes the three hashes the engine needs for one photo.
|
||||
*
|
||||
* All work happens on [Dispatchers.IO]: the heavy parts are file I/O and decoding a
|
||||
* deliberately tiny version of the bitmap.
|
||||
*/
|
||||
class PhotoHasher(
|
||||
context: Context,
|
||||
/**
|
||||
* Deadline for a single provider call.
|
||||
*
|
||||
* Injectable so JVM tests can drive the "provider blocks for ever" path without waiting
|
||||
* the production 10 s per file. Production always uses [PROVIDER_CALL_TIMEOUT_MS].
|
||||
*/
|
||||
private val providerCallTimeoutMs: Long = PROVIDER_CALL_TIMEOUT_MS,
|
||||
) {
|
||||
|
||||
private val resolver = context.applicationContext.contentResolver
|
||||
|
||||
/**
|
||||
* Cheap signature over size + head/tail bytes.
|
||||
*
|
||||
* Opens the file **once** and reads both the head and the tail through the same
|
||||
* channel, so this costs a single file descriptor per photo. Returns `null` when
|
||||
* the file cannot be read (revoked permission, corrupt entry, ...).
|
||||
*/
|
||||
suspend fun quickSignature(photo: PhotoRecord): String? = withContext(Dispatchers.IO) {
|
||||
BoundedCall.orNull(providerCallTimeoutMs) {
|
||||
val window = Hashing.SIGNATURE_WINDOW
|
||||
val descriptor = resolver.openFileDescriptor(photo.uri, "r") ?: return@orNull null
|
||||
descriptor.use { pfd ->
|
||||
val stream = FileInputStream(pfd.fileDescriptor)
|
||||
val head = readAt(stream, offset = 0L, length = window)
|
||||
if (head.isEmpty()) return@orNull null
|
||||
val tail = if (photo.sizeBytes > head.size) {
|
||||
readAt(
|
||||
stream,
|
||||
offset = (photo.sizeBytes - window).coerceAtLeast(0L),
|
||||
length = window,
|
||||
)
|
||||
} else {
|
||||
ByteArray(0)
|
||||
}
|
||||
Hashing.quickSignature(photo.sizeBytes, head, tail)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Full content hash; equal hashes mean byte-identical files. */
|
||||
suspend fun contentHash(photo: PhotoRecord): String? = withContext(Dispatchers.IO) {
|
||||
BoundedCall.orNull(providerCallTimeoutMs) {
|
||||
resolver.openInputStream(photo.uri)?.use { stream -> Hashing.sha256(stream) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Both perceptual descriptors, from a single decoded thumbnail.
|
||||
*
|
||||
* Prefers the media provider's **thumbnail cache**
|
||||
* ([ContentResolver.loadThumbnail]); thumbnails are usually already generated by the
|
||||
* gallery, so this avoids decoding the full-resolution original — the single most expensive
|
||||
* step of a scan. Falls back to a subsampled decode when no thumbnail exists.
|
||||
*
|
||||
* Returns `null` for anything it cannot decode: a truncated file, a corrupt entry, an
|
||||
* unrecognised format such as RAW/DNG, or a provider handing back something unusable. Those
|
||||
* photos simply take no part in near-duplicate matching.
|
||||
*/
|
||||
suspend fun perceptualFingerprint(photo: PhotoRecord): PerceptualFingerprint? =
|
||||
withContext(Dispatchers.IO) {
|
||||
BoundedCall.orNull(providerCallTimeoutMs) {
|
||||
val bitmap = systemThumbnail(photo)
|
||||
?: decodeSampled(photo.uri)
|
||||
?: return@orNull null
|
||||
|
||||
try {
|
||||
val width = bitmap.width
|
||||
val height = bitmap.height
|
||||
// Guard the allocation: a provider could hand back a full-resolution bitmap
|
||||
// where a thumbnail was asked for, and a bogus size would otherwise blow up
|
||||
// deep inside IntArray().
|
||||
val pixelCount = width.toLong() * height
|
||||
if (pixelCount <= 0L || pixelCount > MAX_PIXELS) return@orNull null
|
||||
|
||||
val pixels = IntArray(pixelCount.toInt())
|
||||
bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
|
||||
PerceptualFingerprint(
|
||||
phash = PerceptualHash.phashFromArgb(pixels, width, height),
|
||||
rgb = PerceptualHash.rgbDHashFromArgb(pixels, width, height),
|
||||
)
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Small bitmap straight from the media provider's thumbnail cache, or `null`. */
|
||||
private fun systemThumbnail(photo: PhotoRecord): Bitmap? = if (
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
|
||||
) {
|
||||
resolver.loadThumbnail(photo.uri, Size(THUMBNAIL_EDGE, THUMBNAIL_EDGE), null)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
MediaStore.Images.Thumbnails.getThumbnail(
|
||||
resolver,
|
||||
photo.id,
|
||||
MediaStore.Images.Thumbnails.MICRO_KIND,
|
||||
null,
|
||||
)
|
||||
}
|
||||
|
||||
/** Fallback: decode the original at a heavily subsampled size, EXIF-oriented. */
|
||||
private fun decodeSampled(uri: Uri): Bitmap? {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }
|
||||
val width = bounds.outWidth
|
||||
val height = bounds.outHeight
|
||||
if (width <= 0 || height <= 0) return null
|
||||
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inSampleSize = DecodeMath.sampleSizeFor(width, height, MAX_DECODE_EDGE)
|
||||
inPreferredConfig = Bitmap.Config.RGB_565
|
||||
}
|
||||
val decoded = resolver.openInputStream(uri)?.use {
|
||||
BitmapFactory.decodeStream(it, null, options)
|
||||
} ?: return null
|
||||
return applyExifOrientation(uri, decoded)
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotates/flips according to the EXIF orientation tag.
|
||||
*
|
||||
* `BitmapFactory` ignores EXIF while the media provider's thumbnail does not, so without
|
||||
* this the *same photo* would hash differently depending on which path happened to serve it
|
||||
* — and since the thumbnail cache can be evicted between scans, a cached hash could stop
|
||||
* matching a recomputed one. Normalising here makes both paths agree.
|
||||
*/
|
||||
private fun applyExifOrientation(uri: Uri, bitmap: Bitmap): Bitmap {
|
||||
val orientation = try {
|
||||
resolver.openInputStream(uri)?.use {
|
||||
ExifInterface(it).getAttributeInt(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL,
|
||||
)
|
||||
} ?: ExifInterface.ORIENTATION_NORMAL
|
||||
} catch (e: IOException) {
|
||||
ExifInterface.ORIENTATION_NORMAL
|
||||
}
|
||||
|
||||
val matrix = Matrix()
|
||||
when (orientation) {
|
||||
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90f)
|
||||
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180f)
|
||||
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270f)
|
||||
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.postScale(-1f, 1f)
|
||||
ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.postScale(1f, -1f)
|
||||
ExifInterface.ORIENTATION_TRANSPOSE -> {
|
||||
matrix.postRotate(90f)
|
||||
matrix.postScale(-1f, 1f)
|
||||
}
|
||||
|
||||
ExifInterface.ORIENTATION_TRANSVERSE -> {
|
||||
matrix.postRotate(270f)
|
||||
matrix.postScale(-1f, 1f)
|
||||
}
|
||||
|
||||
else -> return bitmap
|
||||
}
|
||||
|
||||
val oriented = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
|
||||
if (oriented !== bitmap) bitmap.recycle()
|
||||
return oriented
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads [length] bytes at [offset] through [stream]'s channel. Providers that
|
||||
* cannot seek fall back to a sequential read, which only makes sense at offset 0.
|
||||
*/
|
||||
private fun readAt(stream: FileInputStream, offset: Long, length: Int): ByteArray {
|
||||
if (length <= 0) return ByteArray(0)
|
||||
return try {
|
||||
val channel = stream.channel
|
||||
channel.position(offset)
|
||||
val buffer = ByteBuffer.allocate(length)
|
||||
var total = 0
|
||||
while (buffer.hasRemaining()) {
|
||||
val read = channel.read(buffer)
|
||||
// Same hazard as readAtMost: a pipe-backed descriptor can report 0 for ever,
|
||||
// and spinning on it would hang the scan.
|
||||
if (read <= 0) break
|
||||
total += read
|
||||
}
|
||||
buffer.array().copyOf(total)
|
||||
} catch (e: IOException) {
|
||||
if (offset == 0L) stream.readAtMost(length) else ByteArray(0)
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
/**
|
||||
* Deadline for a single call into the media provider.
|
||||
*
|
||||
* A provider call can block indefinitely (see [BoundedCall]); this bounds how long one
|
||||
* photo may hold up a scan before it is skipped. Deliberately shorter than the engine's
|
||||
* per-photo budget so a slow provider still leaves room for the fallback decode.
|
||||
*/
|
||||
const val PROVIDER_CALL_TIMEOUT_MS = 10_000L
|
||||
|
||||
/** Decode target for the fallback path — the 9x8 grid needs very little. */
|
||||
const val MAX_DECODE_EDGE = 64
|
||||
|
||||
/** Edge length requested from the media provider's thumbnail cache. */
|
||||
const val THUMBNAIL_EDGE = 96
|
||||
|
||||
/** Hard ceiling on the pixels we will allocate for one fingerprint. */
|
||||
const val MAX_PIXELS = 4_000_000L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package de.softwareapp_hb.fotodup.finder.data
|
||||
|
||||
import android.content.Context
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import de.softwareapp_hb.fotodup.finder.core.RgbDHash
|
||||
import android.database.sqlite.SQLiteOpenHelper
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** One cached row of the duplicate index. */
|
||||
data class IndexEntry(
|
||||
val id: Long,
|
||||
val sizeBytes: Long,
|
||||
val dateModifiedSeconds: Long,
|
||||
val quickSignature: String?,
|
||||
val contentHash: String?,
|
||||
val perceptualHash: Long?,
|
||||
val rgbDHash: RgbDHash?,
|
||||
)
|
||||
|
||||
/**
|
||||
* Persistent cache of computed hashes, keyed by MediaStore id.
|
||||
*
|
||||
* Re-scanning a big library is then fast: a row is only recomputed when the file's
|
||||
* size or last-modified stamp changed. Implemented on top of the framework
|
||||
* `SQLiteOpenHelper` (no Room/KSP) to keep the build lean.
|
||||
*/
|
||||
class PhotoIndexStore(context: Context) {
|
||||
|
||||
private val helper = Helper(context.applicationContext)
|
||||
|
||||
suspend fun loadAll(): Map<Long, IndexEntry> = withContext(Dispatchers.IO) {
|
||||
val result = HashMap<Long, IndexEntry>()
|
||||
helper.readableDatabase.rawQuery(
|
||||
"SELECT id, size, date_modified, quick_sig, content_hash, perceptual_hash, " +
|
||||
"rgb_red, rgb_green, rgb_blue FROM $TABLE",
|
||||
null,
|
||||
).use { cursor ->
|
||||
while (cursor.moveToNext()) {
|
||||
val id = cursor.getLong(0)
|
||||
val rgb = if (cursor.isNull(6) || cursor.isNull(7) || cursor.isNull(8)) {
|
||||
null
|
||||
} else {
|
||||
RgbDHash(cursor.getLong(6), cursor.getLong(7), cursor.getLong(8))
|
||||
}
|
||||
result[id] = IndexEntry(
|
||||
id = id,
|
||||
sizeBytes = cursor.getLong(1),
|
||||
dateModifiedSeconds = cursor.getLong(2),
|
||||
quickSignature = cursor.getString(3),
|
||||
contentHash = cursor.getString(4),
|
||||
perceptualHash = if (cursor.isNull(5)) null else cursor.getLong(5),
|
||||
rgbDHash = rgb,
|
||||
)
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes entries in one transaction through a compiled statement. A large library
|
||||
* means tens of thousands of rows, and rebuilding a `ContentValues` per row is
|
||||
* needless overhead.
|
||||
*/
|
||||
suspend fun upsert(entries: Collection<IndexEntry>) = withContext(Dispatchers.IO) {
|
||||
if (entries.isEmpty()) return@withContext
|
||||
val db = helper.writableDatabase
|
||||
val statement = db.compileStatement(
|
||||
"INSERT OR REPLACE INTO $TABLE " +
|
||||
"(id, size, date_modified, quick_sig, content_hash, perceptual_hash, " +
|
||||
"rgb_red, rgb_green, rgb_blue) " +
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
)
|
||||
db.beginTransaction()
|
||||
try {
|
||||
entries.forEach { entry ->
|
||||
statement.clearBindings()
|
||||
statement.bindLong(1, entry.id)
|
||||
statement.bindLong(2, entry.sizeBytes)
|
||||
statement.bindLong(3, entry.dateModifiedSeconds)
|
||||
entry.quickSignature
|
||||
?.let { statement.bindString(4, it) }
|
||||
?: statement.bindNull(4)
|
||||
entry.contentHash
|
||||
?.let { statement.bindString(5, it) }
|
||||
?: statement.bindNull(5)
|
||||
entry.perceptualHash
|
||||
?.let { statement.bindLong(6, it) }
|
||||
?: statement.bindNull(6)
|
||||
val rgb = entry.rgbDHash
|
||||
if (rgb == null) {
|
||||
statement.bindNull(7)
|
||||
statement.bindNull(8)
|
||||
statement.bindNull(9)
|
||||
} else {
|
||||
statement.bindLong(7, rgb.red)
|
||||
statement.bindLong(8, rgb.green)
|
||||
statement.bindLong(9, rgb.blue)
|
||||
}
|
||||
statement.executeInsert()
|
||||
}
|
||||
db.setTransactionSuccessful()
|
||||
} finally {
|
||||
db.endTransaction()
|
||||
statement.close()
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes rows for photos that no longer exist in MediaStore. */
|
||||
suspend fun pruneTo(knownIds: Set<Long>) = withContext(Dispatchers.IO) {
|
||||
val db = helper.writableDatabase
|
||||
db.beginTransaction()
|
||||
try {
|
||||
// Deleting by iterating avoids building a huge "NOT IN (...)" clause.
|
||||
val stale = ArrayList<Long>()
|
||||
db.rawQuery("SELECT id FROM $TABLE", null).use { cursor ->
|
||||
while (cursor.moveToNext()) {
|
||||
val id = cursor.getLong(0)
|
||||
if (id !in knownIds) stale += id
|
||||
}
|
||||
}
|
||||
stale.forEach { db.delete(TABLE, "id = ?", arrayOf(it.toString())) }
|
||||
db.setTransactionSuccessful()
|
||||
} finally {
|
||||
db.endTransaction()
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun clear() = withContext(Dispatchers.IO) {
|
||||
helper.writableDatabase.delete(TABLE, null, null)
|
||||
Unit
|
||||
}
|
||||
|
||||
private class Helper(context: Context) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
|
||||
|
||||
override fun onCreate(db: SQLiteDatabase) {
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE $TABLE (
|
||||
id INTEGER PRIMARY KEY,
|
||||
size INTEGER NOT NULL,
|
||||
date_modified INTEGER NOT NULL,
|
||||
quick_sig TEXT,
|
||||
content_hash TEXT,
|
||||
perceptual_hash INTEGER,
|
||||
rgb_red INTEGER,
|
||||
rgb_green INTEGER,
|
||||
rgb_blue INTEGER
|
||||
)
|
||||
""".trimIndent(),
|
||||
)
|
||||
}
|
||||
|
||||
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
|
||||
// The index is a pure cache: dropping and rebuilding is always safe.
|
||||
db.execSQL("DROP TABLE IF EXISTS $TABLE")
|
||||
onCreate(db)
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val DB_NAME = "photo_index.db"
|
||||
|
||||
/**
|
||||
* Bump whenever the *meaning* of a stored hash changes. Version 2 switched the
|
||||
* perceptual hash to the media provider's thumbnail; version 3 replaced dHash with pHash
|
||||
* and added the RGB channel hashes. Stored hashes from an older version are not
|
||||
* comparable, so the index is dropped and rebuilt.
|
||||
*/
|
||||
const val DB_VERSION = 3
|
||||
const val TABLE = "photo_index"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package de.softwareapp_hb.fotodup.finder.data
|
||||
|
||||
import android.net.Uri
|
||||
|
||||
/**
|
||||
* One photo as reported by MediaStore.
|
||||
*
|
||||
* This is the UI/hashing-facing view of a library item; the pure duplicate engine
|
||||
* only ever sees [de.softwareapp_hb.fotodup.finder.core.PhotoFingerprint].
|
||||
*/
|
||||
data class PhotoRecord(
|
||||
val id: Long,
|
||||
val uri: Uri,
|
||||
val displayName: String?,
|
||||
val sizeBytes: Long,
|
||||
val dateModifiedSeconds: Long,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val mimeType: String?,
|
||||
/** Folder the photo lives in, e.g. `DCIM/Camera` (API 29+) or a bucket name. */
|
||||
val folder: String?,
|
||||
) {
|
||||
/** Human readable size, e.g. "3.4 MB". */
|
||||
val readableSize: String get() = humanReadableBytes(sizeBytes)
|
||||
}
|
||||
|
||||
/** Formats a byte count using binary (KiB/MiB/GiB) units. */
|
||||
fun humanReadableBytes(bytes: Long): String {
|
||||
if (bytes < 1024) return "$bytes B"
|
||||
val units = arrayOf("KB", "MB", "GB", "TB")
|
||||
var value = bytes.toDouble() / 1024.0
|
||||
var unitIndex = 0
|
||||
while (value >= 1024.0 && unitIndex < units.lastIndex) {
|
||||
value /= 1024.0
|
||||
unitIndex++
|
||||
}
|
||||
return if (value >= 100) {
|
||||
"${value.toInt()} ${units[unitIndex]}"
|
||||
} else {
|
||||
String.format(java.util.Locale.US, "%.1f %s", value, units[unitIndex])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package de.softwareapp_hb.fotodup.finder.domain
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.sync.Semaphore
|
||||
import kotlinx.coroutines.sync.withPermit
|
||||
|
||||
/** Items handed to a worker at a time: far fewer coroutines, less scheduling churn. */
|
||||
private const val BATCH_SIZE = 32
|
||||
|
||||
/**
|
||||
* Runs [block] for every item, with at most [concurrency] invocations in flight.
|
||||
*
|
||||
* Items are processed in small batches, so a library of tens of thousands of photos
|
||||
* creates a few hundred coroutines instead of tens of thousands — the per-item
|
||||
* coroutine bookkeeping used to be a measurable part of scan time.
|
||||
*/
|
||||
internal suspend fun <T> List<T>.forEachParallel(
|
||||
concurrency: Int,
|
||||
block: suspend (T) -> Unit,
|
||||
) {
|
||||
if (isEmpty()) return
|
||||
val permits = Semaphore(concurrency.coerceAtLeast(1))
|
||||
coroutineScope {
|
||||
chunked(BATCH_SIZE).map { batch ->
|
||||
async(Dispatchers.IO) {
|
||||
permits.withPermit {
|
||||
for (item in batch) block(item)
|
||||
}
|
||||
}
|
||||
}.awaitAll()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Worker count for hashing.
|
||||
*
|
||||
* The work is a mix of file I/O and CPU-bound image decoding. Going much past the
|
||||
* number of performance cores makes decoding contend instead of scale, and saturating
|
||||
* every core starves the UI thread — which makes the app *feel* slow even when the
|
||||
* scan finishes sooner. Hence the ceiling of 6 rather than all cores.
|
||||
*/
|
||||
internal fun defaultConcurrency(): Int =
|
||||
Runtime.getRuntime().availableProcessors().coerceIn(2, 6)
|
||||
@@ -0,0 +1,150 @@
|
||||
package de.softwareapp_hb.fotodup.finder.domain
|
||||
|
||||
import android.content.Context
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicatePolicy
|
||||
import de.softwareapp_hb.fotodup.finder.data.MediaStorePhotoSource
|
||||
import de.softwareapp_hb.fotodup.finder.data.PhotoHasher
|
||||
import de.softwareapp_hb.fotodup.finder.data.PhotoIndexStore
|
||||
import de.softwareapp_hb.fotodup.finder.service.ScanService
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Process-wide state of the (single) running scan.
|
||||
*
|
||||
* @property generation increments every time a scan completes, so observers can tell a
|
||||
* *new* result from a re-emission of the previous one (which happens whenever the
|
||||
* collector restarts, e.g. after a configuration change). Only a new result should
|
||||
* reset the user's selection.
|
||||
*/
|
||||
data class ScanState(
|
||||
val scanning: Boolean = false,
|
||||
val phase: ScanPhase? = null,
|
||||
val done: Int = 0,
|
||||
val total: Int = 0,
|
||||
val result: ScanResult? = null,
|
||||
val error: String? = null,
|
||||
val generation: Int = 0,
|
||||
) {
|
||||
/** 0f..1f, or `null` when the current phase has no measurable total. */
|
||||
val progressFraction: Float?
|
||||
get() = if (total > 0 && done <= total) done.toFloat() / total else null
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the running scan for the whole process.
|
||||
*
|
||||
* The scan deliberately does **not** live in a ViewModel: the first scan of a large
|
||||
* library takes a while and the user will leave the screen. Running it here — with
|
||||
* [ScanService] holding a foreground service for the duration — means the scan keeps
|
||||
* going when the app is backgrounded, and its result survives activity recreation.
|
||||
*/
|
||||
class ScanController(context: Context) {
|
||||
|
||||
private val appContext = context.applicationContext
|
||||
|
||||
private val engine = ScanEngine(
|
||||
source = MediaStorePhotoSource(appContext),
|
||||
hasher = PhotoHasher(appContext),
|
||||
index = PhotoIndexStore(appContext),
|
||||
)
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
private val _state = MutableStateFlow(ScanState())
|
||||
val state: StateFlow<ScanState> = _state.asStateFlow()
|
||||
|
||||
private var job: Job? = null
|
||||
|
||||
val isRunning: Boolean get() = job?.isActive == true
|
||||
|
||||
/** Starts a scan; does nothing if one is already running. */
|
||||
fun start(policy: DuplicatePolicy) {
|
||||
if (isRunning) return
|
||||
|
||||
// Flip to "scanning" *before* starting the service: the service observes this
|
||||
// state and would otherwise stop itself immediately.
|
||||
_state.update {
|
||||
it.copy(
|
||||
scanning = true,
|
||||
phase = ScanPhase.LOADING,
|
||||
done = 0,
|
||||
total = 0,
|
||||
result = null,
|
||||
error = null,
|
||||
)
|
||||
}
|
||||
ScanService.start(appContext)
|
||||
|
||||
job = scope.launch {
|
||||
try {
|
||||
engine.scan(policy).collect(::onProgress)
|
||||
} finally {
|
||||
// Covers completion, failure and cancellation alike.
|
||||
_state.update { current ->
|
||||
if (current.scanning) current.copy(scanning = false, phase = null) else current
|
||||
}
|
||||
job = null
|
||||
ScanService.stop(appContext)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun cancel() {
|
||||
job?.cancel()
|
||||
job = null
|
||||
_state.update { it.copy(scanning = false, phase = null) }
|
||||
ScanService.stop(appContext)
|
||||
}
|
||||
|
||||
private fun onProgress(progress: ScanProgress) {
|
||||
when (progress) {
|
||||
is ScanProgress.Working -> _state.update {
|
||||
it.copy(phase = progress.phase, done = progress.done, total = progress.total)
|
||||
}
|
||||
|
||||
is ScanProgress.Finished -> _state.update {
|
||||
it.copy(
|
||||
scanning = false,
|
||||
phase = null,
|
||||
result = progress.result,
|
||||
generation = it.generation + 1,
|
||||
)
|
||||
}
|
||||
|
||||
is ScanProgress.Failed -> _state.update {
|
||||
it.copy(scanning = false, phase = null, error = progress.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the shared result in sync when the UI deletes photos, so the state is still
|
||||
* correct after an activity restart.
|
||||
*/
|
||||
fun removePhotos(deletedIds: Set<Long>) {
|
||||
_state.update { current ->
|
||||
val result = current.result ?: return@update current
|
||||
val groups = result.groups
|
||||
.map { group -> group.copy(members = group.members.filterNot { it.id in deletedIds }) }
|
||||
.filter { it.members.size >= 2 }
|
||||
val records = result.recordsById.filterKeys { it !in deletedIds }
|
||||
current.copy(
|
||||
result = result.copy(
|
||||
photoCount = records.size,
|
||||
groups = groups,
|
||||
recordsById = records,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Clears a finished error after the UI has shown it. */
|
||||
fun clearError() = _state.update { it.copy(error = null) }
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
package de.softwareapp_hb.fotodup.finder.domain
|
||||
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicateGrouper
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicatePolicy
|
||||
import de.softwareapp_hb.fotodup.finder.core.PerceptualFingerprint
|
||||
import de.softwareapp_hb.fotodup.finder.core.PhotoFingerprint
|
||||
import de.softwareapp_hb.fotodup.finder.data.IndexEntry
|
||||
import de.softwareapp_hb.fotodup.finder.data.MediaStorePhotoSource
|
||||
import de.softwareapp_hb.fotodup.finder.data.PhotoHasher
|
||||
import de.softwareapp_hb.fotodup.finder.data.PhotoIndexStore
|
||||
import de.softwareapp_hb.fotodup.finder.data.PhotoRecord
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.channelFlow
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* Orchestrates a full duplicate scan and streams progress.
|
||||
*
|
||||
* The pipeline is deliberately tiered so that only the photos that *can* be
|
||||
* duplicates get the expensive treatment:
|
||||
*
|
||||
* 1. list the library from MediaStore,
|
||||
* 2. compute a cheap size+head/tail signature for every photo,
|
||||
* 3. full-hash only same-size files that share a signature,
|
||||
* 4. perceptual-hash everything (needed to find *near* duplicates),
|
||||
* 5. persist the hashes so the next scan skips unchanged files,
|
||||
* 6. group the results.
|
||||
*
|
||||
* Steps 2-4 are parallelised across CPU cores. Unchanged photos reuse their
|
||||
* cached hashes, which makes repeat scans cheap.
|
||||
*/
|
||||
/**
|
||||
* Abandon a photo whose decode has not finished in this long.
|
||||
*
|
||||
* A single pathological file (a corrupt entry a provider blocks on, an unusually expensive
|
||||
* HEIC/RAW decode) would otherwise stall the whole scan. Cancelling leaves the file out of the
|
||||
* results instead, which is the same outcome as failing to decode it.
|
||||
*/
|
||||
private const val PER_PHOTO_TIMEOUT_MS = 15_000L
|
||||
|
||||
class ScanEngine(
|
||||
private val source: MediaStorePhotoSource,
|
||||
private val hasher: PhotoHasher,
|
||||
private val index: PhotoIndexStore,
|
||||
) {
|
||||
|
||||
fun scan(policy: DuplicatePolicy = DuplicatePolicy.DEFAULT): Flow<ScanProgress> = channelFlow {
|
||||
val startedAt = System.currentTimeMillis()
|
||||
|
||||
suspend fun report(phase: ScanPhase, done: Int, total: Int) {
|
||||
send(ScanProgress.Working(phase, done, total))
|
||||
}
|
||||
|
||||
try {
|
||||
send(ScanProgress.Working(ScanPhase.LOADING))
|
||||
val photos = source.loadPhotos()
|
||||
if (photos.isEmpty()) {
|
||||
send(ScanProgress.Finished(ScanResult(0, emptyList(), emptyMap(), elapsed(startedAt))))
|
||||
return@channelFlow
|
||||
}
|
||||
|
||||
// Only cached rows whose size and timestamp still match are trustworthy.
|
||||
val freshPrior = freshPriorEntries(photos, index.loadAll())
|
||||
val concurrency = defaultConcurrency()
|
||||
val progressStep = (photos.size / 100).coerceAtLeast(1)
|
||||
|
||||
// KEY OPTIMISATION: a file can only be a byte-for-byte duplicate if
|
||||
// another file has *exactly* the same size. In a typical library the
|
||||
// overwhelming majority of photos have a unique size, so for those we
|
||||
// skip signature and content hashing entirely — no file is ever opened.
|
||||
// Only same-size groups can produce exact duplicates.
|
||||
val ambiguousSizes = photos
|
||||
.groupingBy { it.sizeBytes }
|
||||
.eachCount()
|
||||
.filterValues { count -> count >= 2 }
|
||||
.keys
|
||||
val exactCandidates = photos.filter { it.sizeBytes in ambiguousSizes }
|
||||
|
||||
val signaturesStartedAt = System.currentTimeMillis()
|
||||
val quickSignatures = computeQuickSignatures(
|
||||
exactCandidates, freshPrior, concurrency, progressStep,
|
||||
) { done, total -> report(ScanPhase.SIGNATURES, done, total) }
|
||||
val signaturesMs = System.currentTimeMillis() - signaturesStartedAt
|
||||
|
||||
val contentStartedAt = System.currentTimeMillis()
|
||||
val contentHashes = computeContentHashes(
|
||||
exactCandidates, quickSignatures, freshPrior, concurrency, progressStep,
|
||||
) { done, total -> report(ScanPhase.CONTENT, done, total) }
|
||||
val contentMs = System.currentTimeMillis() - contentStartedAt
|
||||
|
||||
val perceptualStartedAt = System.currentTimeMillis()
|
||||
val perceptual = computePerceptualFingerprints(
|
||||
photos, freshPrior, policy, concurrency, progressStep,
|
||||
) { done, total -> report(ScanPhase.PERCEPTUAL, done, total) }
|
||||
val perceptualMs = System.currentTimeMillis() - perceptualStartedAt
|
||||
|
||||
report(ScanPhase.GROUPING, 0, 0)
|
||||
// The index is a cache: losing a write must not discard the scan that just ran, so a
|
||||
// failure here costs the next scan some re-hashing and nothing else.
|
||||
try {
|
||||
persist(photos, freshPrior, quickSignatures, contentHashes, perceptual)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (t: Throwable) {
|
||||
// ignored on purpose
|
||||
}
|
||||
|
||||
val fingerprints = photos.map { photo ->
|
||||
PhotoFingerprint(
|
||||
id = photo.id,
|
||||
sizeBytes = photo.sizeBytes,
|
||||
dateModifiedSeconds = photo.dateModifiedSeconds,
|
||||
width = photo.width,
|
||||
height = photo.height,
|
||||
quickSignature = quickSignatures[photo.id],
|
||||
contentHash = contentHashes[photo.id],
|
||||
perceptualHash = perceptual[photo.id]?.phash,
|
||||
rgbDHash = perceptual[photo.id]?.rgb,
|
||||
)
|
||||
}
|
||||
val grouping = DuplicateGrouper.findGroupsDetailed(fingerprints, policy)
|
||||
|
||||
// Photos we could not decode still matched exactly; report how many so they are not a
|
||||
// silent gap.
|
||||
val unreadableCount = if (policy.includePerceptual) {
|
||||
photos.count { perceptual[it.id] == null }
|
||||
} else {
|
||||
0
|
||||
}
|
||||
|
||||
val totalMs = elapsed(startedAt)
|
||||
send(
|
||||
ScanProgress.Finished(
|
||||
ScanResult(
|
||||
photoCount = photos.size,
|
||||
groups = grouping.groups,
|
||||
recordsById = photos.associateBy { it.id },
|
||||
durationMs = totalMs,
|
||||
timings = ScanTimings(
|
||||
signaturesMs = signaturesMs,
|
||||
contentMs = contentMs,
|
||||
perceptualMs = perceptualMs,
|
||||
totalMs = totalMs,
|
||||
),
|
||||
perceptualThresholds = grouping.thresholds,
|
||||
thresholdWasFallback = grouping.usedFallbackThreshold,
|
||||
unreadableCount = unreadableCount,
|
||||
),
|
||||
),
|
||||
)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (t: Throwable) {
|
||||
send(ScanProgress.Failed(t.message ?: t::class.java.simpleName))
|
||||
}
|
||||
}
|
||||
|
||||
private fun freshPriorEntries(photos: List<PhotoRecord>, cached: Map<Long, IndexEntry>): Map<Long, IndexEntry> {
|
||||
if (cached.isEmpty()) return emptyMap()
|
||||
val byId = photos.associateBy { it.id }
|
||||
val fresh = HashMap<Long, IndexEntry>()
|
||||
cached.forEach { (id, entry) ->
|
||||
val photo = byId[id] ?: return@forEach
|
||||
if (photo.sizeBytes == entry.sizeBytes && photo.dateModifiedSeconds == entry.dateModifiedSeconds) {
|
||||
fresh[id] = entry
|
||||
}
|
||||
}
|
||||
return fresh
|
||||
}
|
||||
|
||||
/**
|
||||
* Tier 1: a cheap signature for every photo. Reuses the cached value when the
|
||||
* file is unchanged.
|
||||
*/
|
||||
private suspend fun computeQuickSignatures(
|
||||
photos: List<PhotoRecord>,
|
||||
prior: Map<Long, IndexEntry>,
|
||||
concurrency: Int,
|
||||
progressStep: Int,
|
||||
onProgress: suspend (Int, Int) -> Unit,
|
||||
): Map<Long, String> {
|
||||
val result = ConcurrentHashMap<Long, String>()
|
||||
val counter = AtomicInteger()
|
||||
val total = photos.size
|
||||
photos.forEachParallel(concurrency) { photo ->
|
||||
val signature = withTimeoutOrNull(PER_PHOTO_TIMEOUT_MS) {
|
||||
prior[photo.id]?.quickSignature ?: hasher.quickSignature(photo)
|
||||
}
|
||||
if (signature != null) result[photo.id] = signature
|
||||
val done = counter.incrementAndGet()
|
||||
if (done % progressStep == 0 || done > total - progressStep) onProgress(done, total)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Tier 2: full content hashes, but only for photos that share a size *and* a
|
||||
* quick signature with at least one other photo.
|
||||
*/
|
||||
private suspend fun computeContentHashes(
|
||||
photos: List<PhotoRecord>,
|
||||
quickSignatures: Map<Long, String>,
|
||||
prior: Map<Long, IndexEntry>,
|
||||
concurrency: Int,
|
||||
progressStep: Int,
|
||||
onProgress: suspend (Int, Int) -> Unit,
|
||||
): Map<Long, String> {
|
||||
val result = ConcurrentHashMap<Long, String>()
|
||||
val candidates = photos
|
||||
.filter { quickSignatures[it.id] != null }
|
||||
.groupBy { it.sizeBytes to quickSignatures.getValue(it.id) }
|
||||
.values
|
||||
.filter { it.size >= 2 }
|
||||
.flatten()
|
||||
if (candidates.isEmpty()) return result
|
||||
|
||||
val counter = AtomicInteger()
|
||||
val total = candidates.size
|
||||
candidates.forEachParallel(concurrency) { photo ->
|
||||
val hash = withTimeoutOrNull(PER_PHOTO_TIMEOUT_MS) {
|
||||
prior[photo.id]?.contentHash ?: hasher.contentHash(photo)
|
||||
}
|
||||
if (hash != null) result[photo.id] = hash
|
||||
val done = counter.incrementAndGet()
|
||||
if (done % progressStep == 0 || done > total - progressStep) onProgress(done, total)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Tier 3: both perceptual descriptors for every photo, from a single decode each.
|
||||
* Skipped entirely for [DuplicatePolicy.EXACT_ONLY].
|
||||
*/
|
||||
private suspend fun computePerceptualFingerprints(
|
||||
photos: List<PhotoRecord>,
|
||||
prior: Map<Long, IndexEntry>,
|
||||
policy: DuplicatePolicy,
|
||||
concurrency: Int,
|
||||
progressStep: Int,
|
||||
onProgress: suspend (Int, Int) -> Unit,
|
||||
): Map<Long, PerceptualFingerprint> {
|
||||
val result = ConcurrentHashMap<Long, PerceptualFingerprint>()
|
||||
if (!policy.includePerceptual) return result
|
||||
|
||||
val counter = AtomicInteger()
|
||||
val total = photos.size
|
||||
photos.forEachParallel(concurrency) { photo ->
|
||||
val cached = prior[photo.id]
|
||||
val fingerprint = withTimeoutOrNull(PER_PHOTO_TIMEOUT_MS) {
|
||||
if (cached?.perceptualHash != null && cached.rgbDHash != null) {
|
||||
PerceptualFingerprint(cached.perceptualHash, cached.rgbDHash)
|
||||
} else {
|
||||
hasher.perceptualFingerprint(photo)
|
||||
}
|
||||
}
|
||||
if (fingerprint != null) result[photo.id] = fingerprint
|
||||
val done = counter.incrementAndGet()
|
||||
if (done % progressStep == 0 || done > total - progressStep) onProgress(done, total)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private suspend fun persist(
|
||||
photos: List<PhotoRecord>,
|
||||
prior: Map<Long, IndexEntry>,
|
||||
quickSignatures: Map<Long, String>,
|
||||
contentHashes: Map<Long, String>,
|
||||
perceptual: Map<Long, PerceptualFingerprint>,
|
||||
) {
|
||||
val entries = photos.map { photo ->
|
||||
val previous = prior[photo.id]
|
||||
IndexEntry(
|
||||
id = photo.id,
|
||||
sizeBytes = photo.sizeBytes,
|
||||
dateModifiedSeconds = photo.dateModifiedSeconds,
|
||||
quickSignature = quickSignatures[photo.id] ?: previous?.quickSignature,
|
||||
contentHash = contentHashes[photo.id] ?: previous?.contentHash,
|
||||
perceptualHash = perceptual[photo.id]?.phash ?: previous?.perceptualHash,
|
||||
rgbDHash = perceptual[photo.id]?.rgb ?: previous?.rgbDHash,
|
||||
)
|
||||
}
|
||||
index.upsert(entries)
|
||||
index.pruneTo(photos.mapTo(HashSet(photos.size)) { it.id })
|
||||
}
|
||||
|
||||
private fun elapsed(startedAt: Long): Long = System.currentTimeMillis() - startedAt
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package de.softwareapp_hb.fotodup.finder.domain
|
||||
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicateGroup
|
||||
import de.softwareapp_hb.fotodup.finder.core.PerceptualThresholds
|
||||
import de.softwareapp_hb.fotodup.finder.data.PhotoRecord
|
||||
|
||||
/**
|
||||
* The stage of a scan, used to label progress in the UI and the notification.
|
||||
*
|
||||
* Deliberately carries no text: the wording lives in resources and is mapped by
|
||||
* `text.labelRes()`, so the screen and the notification cannot drift apart.
|
||||
*/
|
||||
enum class ScanPhase {
|
||||
LOADING,
|
||||
SIGNATURES,
|
||||
CONTENT,
|
||||
PERCEPTUAL,
|
||||
GROUPING,
|
||||
}
|
||||
|
||||
/** Streamed while a scan runs. */
|
||||
sealed interface ScanProgress {
|
||||
|
||||
/** [total] is 0 while the phase is indeterminate (e.g. loading the library). */
|
||||
data class Working(
|
||||
val phase: ScanPhase,
|
||||
val done: Int = 0,
|
||||
val total: Int = 0,
|
||||
) : ScanProgress
|
||||
|
||||
data class Finished(val result: ScanResult) : ScanProgress
|
||||
|
||||
data class Failed(val message: String) : ScanProgress
|
||||
}
|
||||
|
||||
/**
|
||||
* Wall-clock cost of each scan stage. Surfaced in the UI so it is obvious which part
|
||||
* of a scan is slow on a given device (the perceptual pass is normally dominant).
|
||||
*/
|
||||
data class ScanTimings(
|
||||
val signaturesMs: Long,
|
||||
val contentMs: Long,
|
||||
val perceptualMs: Long,
|
||||
val totalMs: Long,
|
||||
)
|
||||
|
||||
/** Everything the UI needs after a scan. */
|
||||
data class ScanResult(
|
||||
val photoCount: Int,
|
||||
val groups: List<DuplicateGroup>,
|
||||
val recordsById: Map<Long, PhotoRecord>,
|
||||
val durationMs: Long,
|
||||
val timings: ScanTimings? = null,
|
||||
/** Thresholds the perceptual pass actually used (the pHash one is adapted per scan). */
|
||||
val perceptualThresholds: PerceptualThresholds? = null,
|
||||
/** True when the library was too small to fit the distance distribution. */
|
||||
val thresholdWasFallback: Boolean = false,
|
||||
/**
|
||||
* Photos whose pixels could not be read — corrupt, truncated, RAW, or an unsupported format.
|
||||
* They still take part in exact-duplicate matching but not in the perceptual pass.
|
||||
*/
|
||||
val unreadableCount: Int = 0,
|
||||
) {
|
||||
val groupCount: Int get() = groups.size
|
||||
val duplicatePhotoCount: Int get() = groups.sumOf { it.members.size }
|
||||
val reclaimableBytes: Long get() = groups.sumOf { it.reclaimableBytes }
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package de.softwareapp_hb.fotodup.finder.service
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.os.IBinder
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.ServiceCompat
|
||||
import de.softwareapp_hb.fotodup.finder.FotoDupApplication
|
||||
import de.softwareapp_hb.fotodup.finder.MainActivity
|
||||
import de.softwareapp_hb.fotodup.finder.R
|
||||
import de.softwareapp_hb.fotodup.finder.domain.ScanState
|
||||
import de.softwareapp_hb.fotodup.finder.text.labelRes
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Foreground service that keeps a running scan alive while the user is elsewhere.
|
||||
*
|
||||
* It contains no scan logic — [de.softwareapp_hb.fotodup.finder.domain.ScanController]
|
||||
* does the work and publishes progress, and this service mirrors that progress into an
|
||||
* ongoing notification. The notification is also how the user cancels a long scan, and
|
||||
* its presence is what stops Android from freezing the app's process when the app is not
|
||||
* visible.
|
||||
*/
|
||||
class ScanService : Service() {
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
private var observer: Job? = null
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
createChannel()
|
||||
}
|
||||
|
||||
// The service-type constant is inlined at compile time, so referencing it on older
|
||||
// devices is harmless — ServiceCompat ignores the type below API 29.
|
||||
@Suppress("InlinedApi")
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
val controller = (application as FotoDupApplication).scanController
|
||||
|
||||
if (intent?.action == ACTION_CANCEL) {
|
||||
controller.cancel()
|
||||
stopEverything()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
// This must happen within a few seconds of startForegroundService(), so it is
|
||||
// the very first thing we do.
|
||||
ServiceCompat.startForeground(
|
||||
this,
|
||||
NOTIFICATION_ID,
|
||||
buildNotification(controller.state.value),
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC,
|
||||
)
|
||||
|
||||
if (observer == null) {
|
||||
observer = scope.launch {
|
||||
controller.state.collect { state ->
|
||||
if (state.scanning) {
|
||||
notifyProgress(state)
|
||||
} else {
|
||||
stopEverything()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
/**
|
||||
* Android 15+ caps how long a `dataSync` foreground service may run (6 hours in any
|
||||
* 24). If that ever fires, stop cleanly rather than let the system kill the app.
|
||||
*/
|
||||
override fun onTimeout(startId: Int, fgsType: Int) {
|
||||
(application as FotoDupApplication).scanController.cancel()
|
||||
stopEverything()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
observer = null
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun stopEverything() {
|
||||
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
private fun notifyProgress(state: ScanState) {
|
||||
getSystemService(NotificationManager::class.java)
|
||||
?.notify(NOTIFICATION_ID, buildNotification(state))
|
||||
}
|
||||
|
||||
private fun buildNotification(state: ScanState): Notification {
|
||||
val openApp = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
Intent(this, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
},
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
val cancel = PendingIntent.getService(
|
||||
this,
|
||||
1,
|
||||
Intent(this, ScanService::class.java).setAction(ACTION_CANCEL),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(getString(R.string.notification_title))
|
||||
.setContentText(getString(state.phase.labelRes()))
|
||||
.setContentIntent(openApp)
|
||||
.addAction(0, getString(R.string.action_cancel), cancel)
|
||||
.setOngoing(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
.setSilent(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_LOW)
|
||||
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
|
||||
|
||||
val fraction = state.progressFraction
|
||||
if (fraction == null) {
|
||||
builder.setProgress(0, 0, true)
|
||||
} else {
|
||||
builder.setProgress(PROGRESS_MAX, (fraction * PROGRESS_MAX).toInt(), false)
|
||||
}
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
private fun createChannel() {
|
||||
val manager = getSystemService(NotificationManager::class.java) ?: return
|
||||
if (manager.getNotificationChannel(CHANNEL_ID) != null) return
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
getString(R.string.notification_channel_name),
|
||||
NotificationManager.IMPORTANCE_LOW,
|
||||
).apply {
|
||||
description = getString(R.string.notification_channel_description)
|
||||
setShowBadge(false)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL_ID = "scan_progress"
|
||||
private const val NOTIFICATION_ID = 1
|
||||
private const val PROGRESS_MAX = 100
|
||||
private const val ACTION_CANCEL = "de.softwareapp_hb.fotodup.finder.action.CANCEL_SCAN"
|
||||
|
||||
/**
|
||||
* Asks the system to run the service. Safe to call from the background: if the
|
||||
* start is not permitted the exception is swallowed, because the scan itself does
|
||||
* not depend on the service — it only loses the foreground guarantee.
|
||||
*/
|
||||
fun start(context: Context) {
|
||||
try {
|
||||
context.startForegroundService(Intent(context, ScanService::class.java))
|
||||
} catch (e: IllegalStateException) {
|
||||
// e.g. ForegroundServiceStartNotAllowedException on Android 12+.
|
||||
}
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
context.stopService(Intent(context, ScanService::class.java))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package de.softwareapp_hb.fotodup.finder.text
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import de.softwareapp_hb.fotodup.finder.R
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicatePolicy
|
||||
import de.softwareapp_hb.fotodup.finder.domain.ScanPhase
|
||||
|
||||
/**
|
||||
* Maps domain enums to their resource ids.
|
||||
*
|
||||
* Lives outside both `ui` and `service` because the screen and the progress notification must
|
||||
* show the *same* wording — duplicating the mapping is how they drift apart.
|
||||
*/
|
||||
@StringRes
|
||||
fun ScanPhase?.labelRes(): Int = when (this) {
|
||||
ScanPhase.SIGNATURES -> R.string.phase_signatures
|
||||
ScanPhase.CONTENT -> R.string.phase_content
|
||||
ScanPhase.PERCEPTUAL -> R.string.phase_perceptual
|
||||
ScanPhase.GROUPING -> R.string.phase_grouping
|
||||
null, ScanPhase.LOADING -> R.string.phase_loading
|
||||
}
|
||||
|
||||
@StringRes
|
||||
fun DuplicatePolicy.labelRes(): Int = when (this) {
|
||||
DuplicatePolicy.EXACT_ONLY -> R.string.policy_exact_only
|
||||
DuplicatePolicy.BALANCED -> R.string.policy_balanced
|
||||
DuplicatePolicy.AGGRESSIVE -> R.string.policy_aggressive
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package de.softwareapp_hb.fotodup.finder.ui.components
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import coil3.compose.AsyncImage
|
||||
import de.softwareapp_hb.fotodup.finder.R
|
||||
import de.softwareapp_hb.fotodup.finder.data.PhotoRecord
|
||||
|
||||
/**
|
||||
* A single selectable photo tile.
|
||||
*
|
||||
* Selected tiles get a tint plus a check badge; the copy the app suggests keeping
|
||||
* is marked "BEST" so the choice stays understandable.
|
||||
*/
|
||||
@Composable
|
||||
fun PhotoThumbnail(
|
||||
photo: PhotoRecord,
|
||||
selected: Boolean,
|
||||
isBest: Boolean,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Box(
|
||||
modifier = modifier
|
||||
.size(108.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant)
|
||||
.clickable(onClick = onClick),
|
||||
) {
|
||||
AsyncImage(
|
||||
model = photo.uri,
|
||||
contentDescription = photo.displayName,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
|
||||
if (selected) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.error.copy(alpha = 0.35f)),
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.padding(6.dp)
|
||||
.size(22.dp)
|
||||
.clip(RoundedCornerShape(11.dp))
|
||||
.background(MaterialTheme.colorScheme.error),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text = "✓",
|
||||
color = MaterialTheme.colorScheme.onError,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
}
|
||||
} else if (isBest) {
|
||||
Badge(
|
||||
text = stringResource(R.string.badge_best),
|
||||
container = MaterialTheme.colorScheme.primary,
|
||||
content = MaterialTheme.colorScheme.onPrimary,
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopStart)
|
||||
.padding(6.dp),
|
||||
)
|
||||
}
|
||||
|
||||
Badge(
|
||||
text = photo.readableSize,
|
||||
container = Color.Black.copy(alpha = 0.55f),
|
||||
content = Color.White,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomStart)
|
||||
.padding(6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Badge(
|
||||
text: String,
|
||||
container: Color,
|
||||
content: Color,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Box(
|
||||
modifier = modifier
|
||||
.clip(RoundedCornerShape(6.dp))
|
||||
.background(container)
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
) {
|
||||
Text(
|
||||
text = text,
|
||||
color = content,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
package de.softwareapp_hb.fotodup.finder.ui.scanner
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.ElevatedCard
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.softwareapp_hb.fotodup.finder.R
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicateGroup
|
||||
import de.softwareapp_hb.fotodup.finder.core.GroupKind
|
||||
import de.softwareapp_hb.fotodup.finder.data.PhotoRecord
|
||||
import de.softwareapp_hb.fotodup.finder.data.humanReadableBytes
|
||||
import de.softwareapp_hb.fotodup.finder.domain.ScanResult
|
||||
import de.softwareapp_hb.fotodup.finder.ui.components.PhotoThumbnail
|
||||
import java.util.Locale
|
||||
|
||||
/** How many thumbnails a collapsed group shows before offering "Show all". */
|
||||
private const val COLLAPSED_LIMIT = 4
|
||||
|
||||
@Composable
|
||||
internal fun ResultSection(state: ScannerUiState, viewModel: ScannerViewModel) {
|
||||
val result = state.result ?: return
|
||||
|
||||
if (result.groups.isEmpty()) {
|
||||
NoDuplicates(result)
|
||||
return
|
||||
}
|
||||
|
||||
// Staged photos are taken out of the list, so a row disappears the moment the user
|
||||
// removes it — and a group that is no longer duplicated disappears entirely.
|
||||
val groups = state.visibleGroups()
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
item { SummaryCard(groups, result) }
|
||||
item {
|
||||
Column {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
TextButton(onClick = viewModel::selectAllButBest) {
|
||||
Text(stringResource(R.string.action_select_all_but_best))
|
||||
}
|
||||
TextButton(onClick = viewModel::clearSelection) {
|
||||
Text(stringResource(R.string.action_clear_selection))
|
||||
}
|
||||
}
|
||||
Text(
|
||||
text = stringResource(R.string.hint_select_then_remove),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (groups.isEmpty()) {
|
||||
item { EverythingStagedCard(state.markedForRemovalIds.size) }
|
||||
}
|
||||
items(groups, key = { it.id }) { group ->
|
||||
GroupCard(
|
||||
group = group,
|
||||
records = result.recordsById,
|
||||
selectedIds = state.selectedIds,
|
||||
expanded = group.id in state.expandedGroupIds,
|
||||
onToggleExpand = { viewModel.toggleGroupExpanded(group.id) },
|
||||
onTogglePhoto = viewModel::toggleSelected,
|
||||
onSelectGroup = { select -> viewModel.setGroupSelection(group.id, select) },
|
||||
onRemoveDuplicates = { viewModel.markGroupForRemoval(group.id) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Shown when every duplicate is staged, so the empty list is not mistaken for a bug. */
|
||||
@Composable
|
||||
private fun EverythingStagedCard(stagedCount: Int) {
|
||||
ElevatedCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = stringResource(R.string.staged_title),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
text = pluralStringResource(R.plurals.staged_body, stagedCount, stagedCount),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SummaryCard(groups: List<DuplicateGroup>, result: ScanResult) {
|
||||
val reclaimableBytes = groups.sumOf { it.reclaimableBytes }
|
||||
val involvedPhotos = groups.sumOf { it.members.size }
|
||||
|
||||
ElevatedCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = pluralStringResource(R.plurals.summary_groups, groups.size, groups.size),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.summary_involved, involvedPhotos, result.photoCount),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.summary_reclaimable, humanReadableBytes(reclaimableBytes)),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.summary_scanned_in, formatDuration(result.durationMs)),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
result.timings?.let { timings ->
|
||||
Text(
|
||||
text = stringResource(
|
||||
R.string.summary_timings,
|
||||
formatDuration(timings.signaturesMs),
|
||||
formatDuration(timings.contentMs),
|
||||
formatDuration(timings.perceptualMs),
|
||||
),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
result.perceptualThresholds?.let { thresholds ->
|
||||
Text(
|
||||
text = pluralStringResource(
|
||||
if (result.thresholdWasFallback) {
|
||||
R.plurals.summary_cut_default
|
||||
} else {
|
||||
R.plurals.summary_cut_fitted
|
||||
},
|
||||
thresholds.phashDistance,
|
||||
thresholds.phashDistance,
|
||||
),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
if (result.unreadableCount > 0) {
|
||||
Text(
|
||||
text = pluralStringResource(
|
||||
R.plurals.summary_unreadable,
|
||||
result.unreadableCount,
|
||||
result.unreadableCount,
|
||||
),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun NoDuplicates(result: ScanResult) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(32.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Text(text = "\u2728", style = MaterialTheme.typography.displayMedium)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.no_duplicates_title),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
text = pluralStringResource(
|
||||
R.plurals.no_duplicates_body,
|
||||
result.photoCount,
|
||||
result.photoCount,
|
||||
formatDuration(result.durationMs),
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GroupCard(
|
||||
group: DuplicateGroup,
|
||||
records: Map<Long, PhotoRecord>,
|
||||
selectedIds: Set<Long>,
|
||||
expanded: Boolean,
|
||||
onToggleExpand: () -> Unit,
|
||||
onTogglePhoto: (Long) -> Unit,
|
||||
onSelectGroup: (Boolean) -> Unit,
|
||||
onRemoveDuplicates: () -> Unit,
|
||||
) {
|
||||
// Same rule the delete button and "select all but best" use, so the badge shown
|
||||
// here always matches what would actually be kept.
|
||||
val bestId = remember(group) { group.suggestedKeep()?.id }
|
||||
// The suggested keep is shown first, so it stays visible as a reference even when
|
||||
// the group is collapsed. The engine works with pure fingerprints; the UI needs the
|
||||
// full records so it can show the photo and its size.
|
||||
val ordered = remember(group) { group.displayOrder() }
|
||||
val visible = (if (expanded) ordered else ordered.take(COLLAPSED_LIMIT))
|
||||
.mapNotNull { records[it.id] }
|
||||
// Counted from the current tick state, not from the suggestion, so deselecting a copy in
|
||||
// this row immediately updates the label.
|
||||
val removableCount = group.selectedMembers(selectedIds).size
|
||||
|
||||
ElevatedCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = stringResource(group.titleRes()),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
Text(
|
||||
text = stringResource(
|
||||
R.string.group_copies_reclaimable,
|
||||
group.members.size,
|
||||
humanReadableBytes(group.reclaimableBytes),
|
||||
),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
TextButton(onClick = { onSelectGroup(true) }) {
|
||||
Text(stringResource(R.string.group_action_all))
|
||||
}
|
||||
TextButton(onClick = { onSelectGroup(false) }) {
|
||||
Text(stringResource(R.string.group_action_none))
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(visible, key = { it.id }) { photo ->
|
||||
PhotoThumbnail(
|
||||
photo = photo,
|
||||
selected = photo.id in selectedIds,
|
||||
isBest = bestId == photo.id,
|
||||
onClick = { onTogglePhoto(photo.id) },
|
||||
)
|
||||
}
|
||||
}
|
||||
if (group.members.size > COLLAPSED_LIMIT) {
|
||||
TextButton(onClick = onToggleExpand, modifier = Modifier.align(Alignment.End)) {
|
||||
Text(
|
||||
text = if (expanded) {
|
||||
stringResource(R.string.group_show_less)
|
||||
} else {
|
||||
stringResource(R.string.group_show_all, group.members.size)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
// Row-wise staging: hides this row's ticked copies right away and marks them for
|
||||
// removal. Nothing is deleted and no system dialog appears until the user taps Apply.
|
||||
FilledTonalButton(
|
||||
onClick = onRemoveDuplicates,
|
||||
enabled = removableCount > 0,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(
|
||||
text = if (removableCount == 0) {
|
||||
stringResource(R.string.group_nothing_selected)
|
||||
} else {
|
||||
pluralStringResource(
|
||||
R.plurals.group_remove_duplicates,
|
||||
removableCount,
|
||||
removableCount,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@StringRes
|
||||
private fun DuplicateGroup.titleRes(): Int = when (kind) {
|
||||
GroupKind.EXACT -> R.string.group_exact_copies
|
||||
GroupKind.PERCEPTUAL -> R.string.group_visually_similar
|
||||
}
|
||||
|
||||
internal fun formatDuration(millis: Long): String = if (millis < 1000) {
|
||||
"$millis ms"
|
||||
} else {
|
||||
String.format(Locale.US, "%.1f s", millis / 1000.0)
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package de.softwareapp_hb.fotodup.finder.ui.scanner
|
||||
|
||||
import android.app.Activity
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.IntentSenderRequest
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import de.softwareapp_hb.fotodup.finder.R
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicatePolicy
|
||||
import de.softwareapp_hb.fotodup.finder.data.MediaAccess
|
||||
import de.softwareapp_hb.fotodup.finder.data.AppPermissions
|
||||
import de.softwareapp_hb.fotodup.finder.data.humanReadableBytes
|
||||
import de.softwareapp_hb.fotodup.finder.text.labelRes
|
||||
|
||||
@Composable
|
||||
fun ScannerScreen(viewModel: ScannerViewModel = viewModel()) {
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
|
||||
val permissionLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.RequestMultiplePermissions(),
|
||||
) { viewModel.refreshAccess() }
|
||||
|
||||
val deleteLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartIntentSenderForResult(),
|
||||
) { result -> viewModel.onSystemDeleteResult(result.resultCode == Activity.RESULT_OK) }
|
||||
|
||||
// System delete/trash consent dialogs are one-shot; collect and launch each one.
|
||||
LaunchedEffect(viewModel) {
|
||||
viewModel.deleteRequests.collect { sender ->
|
||||
deleteLauncher.launch(IntentSenderRequest.Builder(sender).build())
|
||||
}
|
||||
}
|
||||
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
LaunchedEffect(state.message) {
|
||||
state.message?.let { message ->
|
||||
snackbarHostState.showSnackbar(message)
|
||||
viewModel.dismissMessage()
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = { ScannerTopBar(state, viewModel) },
|
||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
||||
bottomBar = { BottomActionBar(state, viewModel) },
|
||||
) { innerPadding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(innerPadding),
|
||||
) {
|
||||
AccessBanner(state.access) {
|
||||
permissionLauncher.launch(AppPermissions.requestablePermissions())
|
||||
}
|
||||
|
||||
when {
|
||||
state.scanning -> ProgressSection(state, viewModel::cancelScan)
|
||||
state.result != null -> ResultSection(state, viewModel)
|
||||
else -> EmptySection(
|
||||
hasAccess = state.access != MediaAccess.NONE,
|
||||
onScan = viewModel::startScan,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun ScannerTopBar(state: ScannerUiState, viewModel: ScannerViewModel) {
|
||||
var menuOpen by remember { mutableStateOf(false) }
|
||||
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.app_name)) },
|
||||
actions = {
|
||||
if (state.scanning) {
|
||||
TextButton(onClick = viewModel::cancelScan) {
|
||||
Text(stringResource(R.string.action_cancel))
|
||||
}
|
||||
} else {
|
||||
TextButton(
|
||||
onClick = viewModel::startScan,
|
||||
enabled = state.access != MediaAccess.NONE,
|
||||
) { Text(stringResource(R.string.action_scan)) }
|
||||
}
|
||||
TextButton(onClick = { menuOpen = true }) {
|
||||
Text(stringResource(R.string.action_options))
|
||||
}
|
||||
DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.sensitivity_title)) },
|
||||
onClick = {},
|
||||
enabled = false,
|
||||
)
|
||||
DuplicatePolicy.entries.forEach { policy ->
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(policy.labelRes())) },
|
||||
onClick = {
|
||||
viewModel.setPolicy(policy)
|
||||
menuOpen = false
|
||||
},
|
||||
leadingIcon = { Text(if (state.policy == policy) "✓" else " ") },
|
||||
)
|
||||
}
|
||||
HorizontalDivider()
|
||||
DropdownMenuItem(
|
||||
text = {
|
||||
Text(
|
||||
stringResource(
|
||||
if (state.useTrash) {
|
||||
R.string.menu_use_trash
|
||||
} else {
|
||||
R.string.menu_delete_permanently
|
||||
},
|
||||
),
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
viewModel.setUseTrash(!state.useTrash)
|
||||
menuOpen = false
|
||||
},
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The bottom action bar.
|
||||
*
|
||||
* Two-step by design: **"Remove all selected"** only *stages* photos (rows vanish from the
|
||||
* list immediately, nothing is deleted), and **"Apply"** performs the real removal — which
|
||||
* on Android 11+ shows a **single** system confirmation for the whole batch instead of one
|
||||
* dialog per group.
|
||||
*/
|
||||
@Composable
|
||||
private fun BottomActionBar(state: ScannerUiState, viewModel: ScannerViewModel) {
|
||||
val hasMarked = state.markedForRemovalIds.isNotEmpty()
|
||||
val hasSelection = state.selectedIds.isNotEmpty()
|
||||
if (!hasMarked && !hasSelection) return
|
||||
|
||||
Surface(tonalElevation = 3.dp) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
// Reserve room for the system navigation bar: Scaffold does not inset a
|
||||
// custom bottom bar itself.
|
||||
.navigationBarsPadding()
|
||||
.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
) {
|
||||
if (hasMarked) {
|
||||
Text(
|
||||
text = stringResource(
|
||||
R.string.bar_marked_for_removal,
|
||||
state.markedForRemovalIds.size,
|
||||
humanReadableBytes(state.markedBytes),
|
||||
),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (state.useTrash) R.string.bar_will_trash else R.string.bar_will_delete,
|
||||
),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
if (hasSelection) {
|
||||
Text(
|
||||
text = stringResource(
|
||||
R.string.bar_selected,
|
||||
state.selectedIds.size,
|
||||
humanReadableBytes(state.selectedBytes),
|
||||
),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.End,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (hasMarked) {
|
||||
TextButton(onClick = viewModel::discardMarkedForRemoval) {
|
||||
Text(stringResource(R.string.action_discard))
|
||||
}
|
||||
}
|
||||
if (hasSelection) {
|
||||
TextButton(onClick = viewModel::markSelectedForRemoval) {
|
||||
Text(stringResource(R.string.action_remove_selected))
|
||||
}
|
||||
}
|
||||
if (hasMarked) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Button(onClick = viewModel::applyMarkedForRemoval) {
|
||||
Text(stringResource(R.string.action_apply))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package de.softwareapp_hb.fotodup.finder.ui.scanner
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.softwareapp_hb.fotodup.finder.R
|
||||
import de.softwareapp_hb.fotodup.finder.data.MediaAccess
|
||||
import de.softwareapp_hb.fotodup.finder.text.labelRes
|
||||
|
||||
@Composable
|
||||
internal fun AccessBanner(access: MediaAccess, onGrant: () -> Unit) {
|
||||
if (access == MediaAccess.FULL) return
|
||||
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.secondaryContainer,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (access == MediaAccess.PARTIAL) {
|
||||
R.string.access_limited_title
|
||||
} else {
|
||||
R.string.access_needed_title
|
||||
},
|
||||
),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (access == MediaAccess.PARTIAL) {
|
||||
R.string.access_limited_body
|
||||
} else {
|
||||
R.string.access_needed_body
|
||||
},
|
||||
),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Button(onClick = onGrant) { Text(stringResource(R.string.action_grant_access)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ProgressSection(state: ScannerUiState, onCancel: () -> Unit) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(state.phase.labelRes()),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
val fraction = state.progressFraction
|
||||
if (fraction == null) {
|
||||
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||
} else {
|
||||
LinearProgressIndicator(progress = { fraction }, modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
if (state.progressTotal > 0) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
text = stringResource(
|
||||
R.string.progress_counter,
|
||||
state.progressDone,
|
||||
state.progressTotal,
|
||||
),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(24.dp))
|
||||
Button(onClick = onCancel) { Text(stringResource(R.string.action_cancel)) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun EmptySection(hasAccess: Boolean, onScan: () -> Unit) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(32.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Text(text = "\uD83E\uDDF9", style = MaterialTheme.typography.displayMedium)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.intro_title),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.intro_body),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
Button(onClick = onScan, enabled = hasAccess) {
|
||||
Text(stringResource(R.string.action_start_scan))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package de.softwareapp_hb.fotodup.finder.ui.scanner
|
||||
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicateGroup
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicatePolicy
|
||||
import de.softwareapp_hb.fotodup.finder.data.MediaAccess
|
||||
import de.softwareapp_hb.fotodup.finder.domain.ScanPhase
|
||||
import de.softwareapp_hb.fotodup.finder.domain.ScanResult
|
||||
|
||||
/** Everything the scanner screen renders. */
|
||||
data class ScannerUiState(
|
||||
val access: MediaAccess = MediaAccess.NONE,
|
||||
val policy: DuplicatePolicy = DuplicatePolicy.DEFAULT,
|
||||
val scanning: Boolean = false,
|
||||
val phase: ScanPhase? = null,
|
||||
val progressDone: Int = 0,
|
||||
val progressTotal: Int = 0,
|
||||
val result: ScanResult? = null,
|
||||
/** Ids the user currently has ticked (the orange/red selection on the tiles). */
|
||||
val selectedIds: Set<Long> = emptySet(),
|
||||
/**
|
||||
* Ids the user has staged for removal. These disappear from the list immediately but
|
||||
* are **not** deleted until they tap Apply, which triggers the one system dialog.
|
||||
*/
|
||||
val markedForRemovalIds: Set<Long> = emptySet(),
|
||||
val expandedGroupIds: Set<String> = emptySet(),
|
||||
/** Move to trash instead of permanent delete (Android 11+). */
|
||||
val useTrash: Boolean = true,
|
||||
val message: String? = null,
|
||||
) {
|
||||
val selectedBytes: Long
|
||||
get() = bytesOf(selectedIds)
|
||||
|
||||
val markedBytes: Long
|
||||
get() = bytesOf(markedForRemovalIds)
|
||||
|
||||
private fun bytesOf(ids: Set<Long>): Long = result?.recordsById.orEmpty()
|
||||
.filterKeys { it in ids }
|
||||
.values
|
||||
.sumOf { it.sizeBytes }
|
||||
|
||||
/** 0f..1f, or null when the current phase has no measurable total. */
|
||||
val progressFraction: Float?
|
||||
get() = if (progressTotal > 0) progressDone.toFloat() / progressTotal else null
|
||||
|
||||
/**
|
||||
* The groups that are still duplicated, i.e. with everything staged for removal taken
|
||||
* out. A group whose staged copies leave fewer than two members is no longer a
|
||||
* duplicate set and is dropped — that is what makes a row "disappear" when the user
|
||||
* removes it.
|
||||
*/
|
||||
fun visibleGroups(): List<DuplicateGroup> =
|
||||
result?.groups.orEmpty().mapNotNull { it.without(markedForRemovalIds) }
|
||||
|
||||
/** A single group with staged photos removed, or `null` if it is no longer listed. */
|
||||
fun visibleGroup(groupId: String): DuplicateGroup? =
|
||||
result?.groups?.firstOrNull { it.id == groupId }?.without(markedForRemovalIds)
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package de.softwareapp_hb.fotodup.finder.ui.scanner
|
||||
|
||||
import android.app.Application
|
||||
import android.content.IntentSender
|
||||
import androidx.annotation.PluralsRes
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import de.softwareapp_hb.fotodup.finder.FotoDupApplication
|
||||
import de.softwareapp_hb.fotodup.finder.R
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicateGroup
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicatePolicy
|
||||
import de.softwareapp_hb.fotodup.finder.data.AppPermissions
|
||||
import de.softwareapp_hb.fotodup.finder.data.MediaDeleter
|
||||
import de.softwareapp_hb.fotodup.finder.domain.ScanState
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.receiveAsFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* Drives the duplicate scanner screen: permissions, selection and deletion.
|
||||
*
|
||||
* Scanning itself is *not* owned here — [de.softwareapp_hb.fotodup.finder.domain.ScanController]
|
||||
* owns it, so a long scan can outlive this ViewModel and keep running while the app is
|
||||
* backgrounded. This class mirrors the controller's progress into UI state and keeps the
|
||||
* selection local, which is why a selection survives configuration changes.
|
||||
*/
|
||||
class ScannerViewModel(application: Application) : AndroidViewModel(application) {
|
||||
|
||||
private val scanController = (application as FotoDupApplication).scanController
|
||||
private val deleter = MediaDeleter(application)
|
||||
|
||||
private val _state = MutableStateFlow(ScannerUiState())
|
||||
val state: StateFlow<ScannerUiState> = _state.asStateFlow()
|
||||
|
||||
/** One-shot system consent intents the UI has to launch. */
|
||||
private val deleteRequestChannel = Channel<IntentSender>(Channel.BUFFERED)
|
||||
val deleteRequests = deleteRequestChannel.receiveAsFlow()
|
||||
|
||||
/**
|
||||
* Which completed scan the current selection belongs to. Without this, the automatic
|
||||
* "select all but best" would wipe a manual selection every time the controller
|
||||
* re-emits its unchanged result.
|
||||
*/
|
||||
private var appliedGeneration = -1
|
||||
|
||||
/** Which photos the in-flight delete request covers. */
|
||||
private var pendingDeleteIds: Set<Long> = emptySet()
|
||||
|
||||
/**
|
||||
* True while a system confirmation dialog is on screen. Only one can be in flight: a
|
||||
* second request would simply queue *another* approval for the user to dismiss.
|
||||
*/
|
||||
private var deleteDialogPending = false
|
||||
|
||||
init {
|
||||
refreshAccess()
|
||||
viewModelScope.launch {
|
||||
scanController.state.collect(::onScanState)
|
||||
}
|
||||
}
|
||||
|
||||
fun refreshAccess() {
|
||||
_state.update { it.copy(access = AppPermissions.accessState(getApplication())) }
|
||||
}
|
||||
|
||||
fun setPolicy(policy: DuplicatePolicy) = _state.update { it.copy(policy = policy) }
|
||||
|
||||
fun setUseTrash(useTrash: Boolean) = _state.update { it.copy(useTrash = useTrash) }
|
||||
|
||||
fun startScan() = scanController.start(_state.value.policy)
|
||||
|
||||
fun cancelScan() = scanController.cancel()
|
||||
|
||||
private fun onScanState(scan: ScanState) {
|
||||
val freshResult = scan.result?.takeIf { scan.generation != appliedGeneration }
|
||||
if (freshResult != null) appliedGeneration = scan.generation
|
||||
|
||||
_state.update { current ->
|
||||
current.copy(
|
||||
scanning = scan.scanning,
|
||||
phase = scan.phase,
|
||||
progressDone = scan.done,
|
||||
progressTotal = scan.total,
|
||||
result = scan.result,
|
||||
selectedIds = when {
|
||||
freshResult != null -> autoSelection(freshResult.groups)
|
||||
scan.scanning -> emptySet()
|
||||
else -> current.selectedIds
|
||||
},
|
||||
markedForRemovalIds = when {
|
||||
// A fresh scan rebuilds the list, so stale staging would point at
|
||||
// photos that may no longer be there.
|
||||
freshResult != null -> emptySet()
|
||||
scan.scanning -> emptySet()
|
||||
else -> current.markedForRemovalIds
|
||||
},
|
||||
expandedGroupIds = when {
|
||||
freshResult != null ->
|
||||
freshResult.groups.take(DEFAULT_EXPANDED_GROUPS).map(DuplicateGroup::id).toSet()
|
||||
|
||||
scan.scanning -> emptySet()
|
||||
else -> current.expandedGroupIds
|
||||
},
|
||||
message = scan.error ?: current.message,
|
||||
)
|
||||
}
|
||||
if (scan.error != null) scanController.clearError()
|
||||
}
|
||||
|
||||
// --- Selection (ticking tiles) and staging ------------------------------
|
||||
|
||||
fun toggleSelected(id: Long) = _state.update { current ->
|
||||
val next = current.selectedIds.toMutableSet()
|
||||
if (!next.add(id)) next.remove(id)
|
||||
current.copy(selectedIds = next)
|
||||
}
|
||||
|
||||
fun setGroupSelection(groupId: String, selectAll: Boolean) = _state.update { current ->
|
||||
val group = current.visibleGroup(groupId) ?: return@update current
|
||||
val next = current.selectedIds.toMutableSet()
|
||||
group.members.forEach { member ->
|
||||
if (selectAll) next += member.id else next -= member.id
|
||||
}
|
||||
current.copy(selectedIds = next)
|
||||
}
|
||||
|
||||
fun toggleGroupExpanded(groupId: String) = _state.update { current ->
|
||||
val next = current.expandedGroupIds.toMutableSet()
|
||||
if (!next.add(groupId)) next.remove(groupId)
|
||||
current.copy(expandedGroupIds = next)
|
||||
}
|
||||
|
||||
/** Ticks every copy that could go, across all groups that are still duplicated. */
|
||||
fun selectAllButBest() = _state.update { current ->
|
||||
val ids = current.visibleGroups()
|
||||
.flatMap { group -> group.suggestedRemovals().map { it.id } }
|
||||
.toSet()
|
||||
current.copy(selectedIds = ids)
|
||||
}
|
||||
|
||||
fun clearSelection() = _state.update { it.copy(selectedIds = emptySet()) }
|
||||
|
||||
fun dismissMessage() = _state.update { it.copy(message = null) }
|
||||
|
||||
/**
|
||||
* Suggests removing every copy except the best one per group. The keep/remove rule
|
||||
* lives on [DuplicateGroup] so it matches the "BEST" badge exactly.
|
||||
*/
|
||||
private fun autoSelection(groups: List<DuplicateGroup>): Set<Long> =
|
||||
groups.flatMapTo(HashSet()) { group -> group.suggestedRemovals().map { it.id } }
|
||||
|
||||
// --- Staging: mark now, delete once -------------------------------------
|
||||
|
||||
/**
|
||||
* Stages the members of one group the user has ticked, and the row disappears from the list
|
||||
* straight away.
|
||||
*
|
||||
* Nothing is deleted and **no dialog appears** — the actual removal happens when the user
|
||||
* taps Apply, at which point one system confirmation covers everything staged.
|
||||
*/
|
||||
fun markGroupForRemoval(groupId: String) = _state.update { current ->
|
||||
val group = current.visibleGroup(groupId) ?: return@update current
|
||||
val chosen = group.selectedMembers(current.selectedIds).map { it.id }.toSet()
|
||||
if (chosen.isEmpty()) return@update current
|
||||
current.copy(
|
||||
markedForRemovalIds = current.markedForRemovalIds + chosen,
|
||||
selectedIds = current.selectedIds - chosen,
|
||||
)
|
||||
}
|
||||
|
||||
/** Stages everything the user has ticked. */
|
||||
fun markSelectedForRemoval() = _state.update { current ->
|
||||
current.copy(
|
||||
markedForRemovalIds = current.markedForRemovalIds + current.selectedIds,
|
||||
selectedIds = emptySet(),
|
||||
)
|
||||
}
|
||||
|
||||
/** Undoes all staging — the rows come back and nothing was deleted. */
|
||||
fun discardMarkedForRemoval() = _state.update { it.copy(markedForRemovalIds = emptySet()) }
|
||||
|
||||
/**
|
||||
* The single "apply" action: really deletes everything staged. On Android 11+ this
|
||||
* shows **one** system confirmation for the whole batch.
|
||||
*/
|
||||
fun applyMarkedForRemoval() = requestDelete(_state.value.markedForRemovalIds)
|
||||
|
||||
private fun requestDelete(ids: Set<Long>) {
|
||||
if (ids.isEmpty()) return
|
||||
// Only one system dialog at a time — otherwise rapid taps queue up several
|
||||
// confirmations the user has to dismiss.
|
||||
if (deleteDialogPending) return
|
||||
|
||||
val result = _state.value.result ?: return
|
||||
val uris = ids.mapNotNull { result.recordsById[it]?.uri }
|
||||
if (uris.isEmpty()) return
|
||||
|
||||
pendingDeleteIds = ids
|
||||
if (deleter.requiresSystemConsent) {
|
||||
val intent = deleter.createDeleteRequest(uris, _state.value.useTrash) ?: return
|
||||
deleteDialogPending = true
|
||||
viewModelScope.launch { deleteRequestChannel.send(intent.intentSender) }
|
||||
} else {
|
||||
viewModelScope.launch {
|
||||
val removed = withContext(Dispatchers.IO) { deleter.deleteDirectly(uris) }
|
||||
applyDeletion(ids, removed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Result of the system delete dialog that the UI launched for us. */
|
||||
fun onSystemDeleteResult(confirmed: Boolean) {
|
||||
deleteDialogPending = false
|
||||
if (!confirmed) {
|
||||
// Keep the staging so the user can simply tap Apply again.
|
||||
pendingDeleteIds = emptySet()
|
||||
_state.update { it.copy(message = text(R.string.message_not_confirmed)) }
|
||||
return
|
||||
}
|
||||
val ids = pendingDeleteIds
|
||||
applyDeletion(ids, ids.size)
|
||||
}
|
||||
|
||||
private fun applyDeletion(deletedIds: Set<Long>, removedCount: Int) {
|
||||
pendingDeleteIds = emptySet()
|
||||
deleteDialogPending = false
|
||||
// The controller owns the result, so keep it in sync instead of mutating a copy —
|
||||
// otherwise the deleted photos would reappear after an activity restart.
|
||||
scanController.removePhotos(deletedIds)
|
||||
_state.update { current ->
|
||||
current.copy(
|
||||
// Only drop what actually went away, so one delete does not throw away
|
||||
// unrelated selection or staging.
|
||||
selectedIds = current.selectedIds - deletedIds,
|
||||
markedForRemovalIds = current.markedForRemovalIds - deletedIds,
|
||||
message = if (removedCount > 0) {
|
||||
quantity(R.plurals.message_deleted, removedCount)
|
||||
} else {
|
||||
text(R.string.message_nothing_deleted)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Resource helpers: the ViewModel has no Compose context, only the Application. */
|
||||
private fun text(@StringRes id: Int): String = getApplication<Application>().getString(id)
|
||||
|
||||
private fun quantity(@PluralsRes id: Int, count: Int): String =
|
||||
getApplication<Application>().resources.getQuantityString(id, count, count)
|
||||
|
||||
private companion object {
|
||||
const val DEFAULT_EXPANDED_GROUPS = 3
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package de.softwareapp_hb.fotodup.finder.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
// Brand palette: a calm green ("keep it clean") accent with a teal secondary.
|
||||
// Only the roles the app actually uses are overridden; the rest come from the
|
||||
// Material 3 baseline, which keeps the scheme consistent.
|
||||
|
||||
val GreenPrimaryLight = Color(0xFF2E7D32)
|
||||
val GreenOnPrimaryLight = Color(0xFFFFFFFF)
|
||||
val GreenContainerLight = Color(0xFFB7F2B2)
|
||||
val GreenOnContainerLight = Color(0xFF00210A)
|
||||
val TealSecondaryLight = Color(0xFF00696E)
|
||||
val SurfaceLight = Color(0xFFFFFBFE)
|
||||
val SurfaceVariantLight = Color(0xFFDEE4DD)
|
||||
val OnSurfaceLight = Color(0xFF171D18)
|
||||
val ErrorLight = Color(0xFFBA1A1A)
|
||||
|
||||
val GreenPrimaryDark = Color(0xFF9BD79A)
|
||||
val GreenOnPrimaryDark = Color(0xFF00390F)
|
||||
val GreenContainerDark = Color(0xFF15521C)
|
||||
val GreenOnContainerDark = Color(0xFFB7F2B2)
|
||||
val TealSecondaryDark = Color(0xFF4CDADE)
|
||||
val SurfaceDark = Color(0xFF101418)
|
||||
val SurfaceVariantDark = Color(0xFF3F4943)
|
||||
val OnSurfaceDark = Color(0xFFDEE4DD)
|
||||
val ErrorDark = Color(0xFFFFB4AB)
|
||||
@@ -0,0 +1,64 @@
|
||||
package de.softwareapp_hb.fotodup.finder.ui.theme
|
||||
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.dynamicDarkColorScheme
|
||||
import androidx.compose.material3.dynamicLightColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
|
||||
private val LightColors = lightColorScheme(
|
||||
primary = GreenPrimaryLight,
|
||||
onPrimary = GreenOnPrimaryLight,
|
||||
primaryContainer = GreenContainerLight,
|
||||
onPrimaryContainer = GreenOnContainerLight,
|
||||
secondary = TealSecondaryLight,
|
||||
background = SurfaceLight,
|
||||
surface = SurfaceLight,
|
||||
surfaceVariant = SurfaceVariantLight,
|
||||
onSurface = OnSurfaceLight,
|
||||
error = ErrorLight,
|
||||
)
|
||||
|
||||
private val DarkColors = darkColorScheme(
|
||||
primary = GreenPrimaryDark,
|
||||
onPrimary = GreenOnPrimaryDark,
|
||||
primaryContainer = GreenContainerDark,
|
||||
onPrimaryContainer = GreenOnContainerDark,
|
||||
secondary = TealSecondaryDark,
|
||||
background = SurfaceDark,
|
||||
surface = SurfaceDark,
|
||||
surfaceVariant = SurfaceVariantDark,
|
||||
onSurface = OnSurfaceDark,
|
||||
error = ErrorDark,
|
||||
)
|
||||
|
||||
/**
|
||||
* App theme. Uses Material You dynamic colour on Android 12+ when available and
|
||||
* falls back to the branded green scheme otherwise.
|
||||
*/
|
||||
@Composable
|
||||
fun FotoDupTheme(
|
||||
darkTheme: Boolean = isSystemInDarkTheme(),
|
||||
dynamicColor: Boolean = true,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
val colorScheme = when {
|
||||
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
||||
val context = LocalContext.current
|
||||
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
|
||||
}
|
||||
|
||||
darkTheme -> DarkColors
|
||||
else -> LightColors
|
||||
}
|
||||
|
||||
MaterialTheme(
|
||||
colorScheme = colorScheme,
|
||||
typography = FotoDupTypography,
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package de.softwareapp_hb.fotodup.finder.ui.theme
|
||||
|
||||
import androidx.compose.material3.Typography
|
||||
|
||||
/**
|
||||
* The app sticks with the Material 3 default type scale; a dedicated object keeps
|
||||
* a single place to tune typography later (e.g. larger "wasted space" figures).
|
||||
*/
|
||||
val FotoDupTypography = Typography()
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:fillColor="@color/ic_launcher_background"
|
||||
android:pathData="M0,0 h108 v108 h-108 z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Launcher foreground: two offset "photo" frames, hinting at duplicates.
|
||||
Drawn inside the 66dp safe zone of the 108dp adaptive-icon canvas.
|
||||
-->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
|
||||
<!-- Back frame (semi-transparent) -->
|
||||
<group
|
||||
android:scaleX="1.9"
|
||||
android:scaleY="1.9"
|
||||
android:translateX="30"
|
||||
android:translateY="22">
|
||||
<path
|
||||
android:fillAlpha="0.45"
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M4,5 h16 a1,1 0 0 1 1,1 v12 a1,1 0 0 1 -1,1 h-16 a1,1 0 0 1 -1,-1 v-12 a1,1 0 0 1 1,-1 z" />
|
||||
</group>
|
||||
|
||||
<!-- Front frame outline -->
|
||||
<group
|
||||
android:scaleX="1.9"
|
||||
android:scaleY="1.9"
|
||||
android:translateX="24"
|
||||
android:translateY="28">
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M4,5 h16 a1,1 0 0 1 1,1 v12 a1,1 0 0 1 -1,1 h-16 a1,1 0 0 1 -1,-1 v-12 a1,1 0 0 1 1,-1 z"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeWidth="1.6" />
|
||||
<!-- sun -->
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M7.5,9 m-1.4,0 a1.4,1.4 0 1 0 2.8,0 a1.4,1.4 0 1 0 -2.8,0" />
|
||||
<!-- mountain -->
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M4,17 l4,-5 l3,3.5 l3.5,-4.5 l5.5,6 z" />
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Notification small icon. Monochrome on purpose: Android renders notification icons
|
||||
as an alpha mask, so only the alpha channel matters.
|
||||
-->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
|
||||
<!-- back "photo" -->
|
||||
<path
|
||||
android:fillAlpha="0.55"
|
||||
android:fillColor="#FFFFFFFF"
|
||||
android:pathData="M10,2 h10 a2,2 0 0 1 2,2 v10 a2,2 0 0 1 -2,2 h-10 a2,2 0 0 1 -2,-2 v-10 a2,2 0 0 1 2,-2 z" />
|
||||
|
||||
<!-- front "photo" -->
|
||||
<path
|
||||
android:fillColor="#FFFFFFFF"
|
||||
android:pathData="M4,8 h10 a2,2 0 0 1 2,2 v10 a2,2 0 0 1 -2,2 h-10 a2,2 0 0 1 -2,-2 v-10 a2,2 0 0 1 2,-2 z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="window_background">#101418</color>
|
||||
<color name="ic_launcher_background">#1B5E20</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="Theme.FotoDupFinder" parent="android:Theme.Material.NoActionBar">
|
||||
<item name="android:windowBackground">@color/window_background</item>
|
||||
<item name="android:statusBarColor">@android:color/transparent</item>
|
||||
<item name="android:navigationBarColor">@android:color/transparent</item>
|
||||
<item name="android:windowLightStatusBar">false</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="window_background">#FFFBFE</color>
|
||||
<color name="ic_launcher_background">#1B5E20</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,123 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!--
|
||||
All user-visible text lives here. English is currently the only locale, but keeping the
|
||||
text in resources is what makes a translation possible later at all — Play's automatic
|
||||
translation covers the store listing, not the app UI. Plurals are declared properly so a
|
||||
language with more than two plural forms needs no code change.
|
||||
-->
|
||||
<string name="app_name">Foto Dup Finder</string>
|
||||
|
||||
<!-- Top bar and actions -->
|
||||
<string name="action_scan">Scan</string>
|
||||
<string name="action_cancel">Cancel</string>
|
||||
<string name="action_options">Options</string>
|
||||
<string name="action_apply">Apply</string>
|
||||
<string name="action_discard">Discard</string>
|
||||
<string name="action_remove_selected">Remove all selected</string>
|
||||
<string name="action_select_all_but_best">Select all but best</string>
|
||||
<string name="action_clear_selection">Clear selection</string>
|
||||
<string name="action_grant_access">Grant access</string>
|
||||
<string name="action_start_scan">Start scan</string>
|
||||
<string name="sensitivity_title">Sensitivity</string>
|
||||
<string name="menu_use_trash">Move to trash</string>
|
||||
<string name="menu_delete_permanently">Delete permanently</string>
|
||||
|
||||
<!-- Sensitivity presets -->
|
||||
<string name="policy_exact_only">Exact copies only</string>
|
||||
<string name="policy_balanced">Balanced (recommended)</string>
|
||||
<string name="policy_aggressive">Aggressive — finds more</string>
|
||||
|
||||
<!-- Photo access banner -->
|
||||
<string name="access_needed_title">Photo access needed</string>
|
||||
<string name="access_needed_body">The app needs permission to read your photos so it can find duplicates. Nothing ever leaves your device.</string>
|
||||
<string name="access_limited_title">Limited photo access</string>
|
||||
<string name="access_limited_body">You granted access to selected photos only. Grant full access to scan your whole library.</string>
|
||||
|
||||
<!-- Intro / empty state -->
|
||||
<string name="intro_title">Find and remove duplicate photos</string>
|
||||
<string name="intro_body">Fast, ad-free and completely offline. Your photos are never uploaded.</string>
|
||||
|
||||
<!-- Scan phases (also used by the progress notification) -->
|
||||
<string name="phase_loading">Reading your photo library…</string>
|
||||
<string name="phase_signatures">Comparing file signatures…</string>
|
||||
<string name="phase_content">Verifying identical candidates…</string>
|
||||
<string name="phase_perceptual">Looking for visually similar photos…</string>
|
||||
<string name="phase_grouping">Grouping duplicates…</string>
|
||||
<string name="progress_counter">%1$d / %2$d</string>
|
||||
|
||||
<!-- Results summary -->
|
||||
<plurals name="summary_groups">
|
||||
<item quantity="one">%1$d duplicate group</item>
|
||||
<item quantity="other">%1$d duplicate groups</item>
|
||||
</plurals>
|
||||
<!-- Always plural: every group contributes at least two photos. -->
|
||||
<string name="summary_involved" tools:ignore="PluralsCandidate">%1$d of %2$d photos are involved</string>
|
||||
<string name="summary_reclaimable">%1$s reclaimable</string>
|
||||
<string name="summary_scanned_in">Scanned in %1$s</string>
|
||||
<string name="summary_timings">signatures %1$s · exact %2$s · similar %3$s</string>
|
||||
<!-- Genuinely needs plurals: the adaptive fit can legitimately choose a 1-bit cut. -->
|
||||
<plurals name="summary_cut_default">
|
||||
<item quantity="one">similarity cut: pHash ≤ %1$d bit (default)</item>
|
||||
<item quantity="other">similarity cut: pHash ≤ %1$d bits (default)</item>
|
||||
</plurals>
|
||||
<plurals name="summary_cut_fitted">
|
||||
<item quantity="one">similarity cut: pHash ≤ %1$d bit (fitted to this library)</item>
|
||||
<item quantity="other">similarity cut: pHash ≤ %1$d bits (fitted to this library)</item>
|
||||
</plurals>
|
||||
<plurals name="summary_unreadable">
|
||||
<item quantity="one">%1$d photo could not be read (RAW, corrupt or unsupported) and was skipped for similar-photo matching</item>
|
||||
<item quantity="other">%1$d photos could not be read (RAW, corrupt or unsupported) and were skipped for similar-photo matching</item>
|
||||
</plurals>
|
||||
<string name="hint_select_then_remove">Tip: select what you want gone, then use \"Remove all selected\". Android asks for a single confirmation for the whole batch.</string>
|
||||
|
||||
<!-- Duplicate group card -->
|
||||
<string name="group_exact_copies">Exact copies</string>
|
||||
<string name="group_visually_similar">Visually similar</string>
|
||||
<!-- Always plural: a duplicate group has at least two members. -->
|
||||
<string name="group_copies_reclaimable" tools:ignore="PluralsCandidate">%1$d copies · %2$s reclaimable</string>
|
||||
<string name="group_action_all">All</string>
|
||||
<string name="group_action_none">None</string>
|
||||
<string name="group_show_less">Show less</string>
|
||||
<string name="group_show_all">Show all %1$d</string>
|
||||
<plurals name="group_remove_duplicates">
|
||||
<item quantity="one">Remove %1$d duplicate</item>
|
||||
<item quantity="other">Remove %1$d duplicates</item>
|
||||
</plurals>
|
||||
<string name="group_nothing_selected">Nothing selected in this row</string>
|
||||
<string name="badge_best">BEST</string>
|
||||
|
||||
<!-- Everything staged -->
|
||||
<string name="staged_title">All duplicates are ready to go</string>
|
||||
<plurals name="staged_body">
|
||||
<item quantity="one">%1$d photo is marked for removal. Tap Apply to finish, or Discard to bring the groups back.</item>
|
||||
<item quantity="other">%1$d photos are marked for removal. Tap Apply to finish, or Discard to bring the groups back.</item>
|
||||
</plurals>
|
||||
|
||||
<!-- Nothing found -->
|
||||
<string name="no_duplicates_title">No duplicates found</string>
|
||||
<!-- A library really can hold a single photo. -->
|
||||
<plurals name="no_duplicates_body">
|
||||
<item quantity="one">%1$d photo scanned in %2$s.</item>
|
||||
<item quantity="other">%1$d photos scanned in %2$s.</item>
|
||||
</plurals>
|
||||
|
||||
<!-- Bottom action bar -->
|
||||
<!-- "marked for removal" / "selected" are verb phrases, not pluralised nouns. -->
|
||||
<string name="bar_marked_for_removal" tools:ignore="PluralsCandidate">%1$d marked for removal · %2$s</string>
|
||||
<string name="bar_will_trash">Will be moved to the trash when you apply</string>
|
||||
<string name="bar_will_delete">Will be deleted permanently when you apply</string>
|
||||
<string name="bar_selected" tools:ignore="PluralsCandidate">%1$d selected · %2$s</string>
|
||||
|
||||
<!-- Messages -->
|
||||
<plurals name="message_deleted">
|
||||
<item quantity="one">Deleted %1$d photo</item>
|
||||
<item quantity="other">Deleted %1$d photos</item>
|
||||
</plurals>
|
||||
<string name="message_nothing_deleted">Nothing was deleted</string>
|
||||
<string name="message_not_confirmed">Deletion was not confirmed</string>
|
||||
|
||||
<!-- Progress notification -->
|
||||
<string name="notification_channel_name">Scan progress</string>
|
||||
<string name="notification_channel_description">Shows progress while duplicate photos are being searched for</string>
|
||||
<string name="notification_title">Finding duplicate photos</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!--
|
||||
Compose owns the real theming; this XML theme only prevents a jarring flash
|
||||
before the first frame. It is intentionally a framework theme so the app
|
||||
needs no Material Components (View-system) dependency.
|
||||
-->
|
||||
<style name="Theme.FotoDupFinder" parent="android:Theme.Material.Light.NoActionBar">
|
||||
<item name="android:windowBackground">@color/window_background</item>
|
||||
<item name="android:statusBarColor">@android:color/transparent</item>
|
||||
<item name="android:navigationBarColor">@android:color/transparent</item>
|
||||
<item name="android:windowLightStatusBar">true</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
The duplicate index is a cache of MediaStore ids that are only meaningful on the
|
||||
device that created them, so it is deliberately excluded from backup/transfer.
|
||||
-->
|
||||
<full-backup-content>
|
||||
<exclude domain="database" path="." />
|
||||
</full-backup-content>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<data-extraction-rules>
|
||||
<cloud-backup>
|
||||
<exclude domain="database" path="." />
|
||||
</cloud-backup>
|
||||
<device-transfer>
|
||||
<exclude domain="database" path="." />
|
||||
</device-transfer>
|
||||
</data-extraction-rules>
|
||||
Reference in New Issue
Block a user