Compare commits

..

10 Commits

Author SHA1 Message Date
SoftwareApp f4ca5f22ae Re-shoot the phone screenshots, and fix what taking them exposed
verify / gate (push) Has been cancelled
verify / release (push) Has been cancelled
The phone set was two days old and predated M16-M20: nothing in it showed the copy-to picker, the
trash's window or the compress dialog. It is now eight shots (Play's maximum) taken from the signed
release build over the demo library: home, folder list, photo grid, storage usage, sort sheet,
Copy to..., the trash with its 24-hour line and Empty trash, and the compress dialog with its switch.

The shots have to stay inside the demo library, so two things were deliberately not captured: the
home screen (its library counts are the real phone's - the old AVD-shot file is kept) and the picker
one level down (it would name real folders). The picker is shot at the volume list instead.

Taking the picker shot exposed a real bug: it listed '.plainfiles-trash' among the destinations,
because unlike every other listing it did not filter hidden entries. Hidden folders are now offered
only when the listing shows hidden files, with a test for both halves.

The tablet sets are unchanged. The tablet AVDs cannot boot on this machine (no KVM) and the
phone-resized path needs more navigation work than this session had left; the checklist says so and
records what to regenerate and where.
2026-10-18 12:23:19 +02:00
SoftwareApp 2690e53662 The release gate names the baseline-profile task it means
verify.sh --release asked for :baselineprofile:assembleBenchmark, which the baseline-profile plugin made ambiguous when it added a benchmark flavour on top of the benchmark build type - so the task failed before the release build, and the nightly release job has been red without anyone seeing it. The ambiguous name is replaced with assembleBenchmarkBenchmark, with a comment saying why it is spelled out. verify.sh --release is green again.
2026-10-18 11:21:15 +02:00
SoftwareApp 51d97dc3ea The index-restart fix, measured on the phone
Data cleared so the index was empty and a walk had to run, then one character at a time into the search field over the 20 000-file fixture: Indexing 5600 -> 6300 -> 7100 files, then 'Index updated'. The counter climbing across keystrokes is the fix - each keystroke used to cancel the walk and start it again at the first folder.
2026-10-18 10:53:27 +02:00
SoftwareApp 7dcd2bc0f0 The index pass belongs to the view model, not to the keystroke that started it
Reported: the index looked recreated on every keystroke, and switching library
started it over. Both are the same bug, and it is in the ownership of the pass.

searchEverywhere cancels and re-creates searchJob on every keystroke, and
loadLibrary does the same with libraryJob. bringIndexCurrent was a suspend
function called from inside those jobs, so the walk ran in the job that the next
interaction cancelled. A cancelled pass never reaches endVolume, so the volume's
stamp stayed old, so the next interaction found the index stale and started
again from the first folder. With a 20 000-file volume on a phone, where a walk
takes tens of seconds and typing takes milliseconds, the index could not finish
while anyone was typing - and the progress counter restarting with every
character was the visible half of it.

The pass now has its own job on the view model: one at a time, shared by
whoever asks, not cancelled by the screen that asked. Search does not wait for
it once there is an answer to show (it did before, which queued the UI behind
the walk), and when the pass lands it re-answers whatever is on screen - the
query or the library - so "I just downloaded it" still works. A rebuild cancels
any pass in flight and takes over: it is the one action that recovers from the
index being wrong rather than old.

Three tests, each standing inside a walk through a gated StorageSource: typing
does not start a second pass, switching library does not start a second pass, and
a finished pass answers the search again when it finds the file. 430 tests total.
2026-10-18 10:50:39 +02:00
SoftwareApp 14057ca4ce The device pass for M17-M20 says what it checked and what it owes
Two of the four new milestones can only be checked on a device. The launcher routes are manifest and intent, so 'am start ... --es SHORTCUT images' was launched the way the launcher does it: it opened the Images library, and 'trash' opened the trash. That also showed M19's sentence - 'Deleted files are kept for 24 hours' - above 'Nothing in the trash'.

The change mark and the compress dialog were not driven: the terminal here stopped capturing command output halfway through, so the driven pass stopped where the evidence stopped. Recorded as owed rather than done.
2026-10-18 00:19:44 +02:00
SoftwareApp 5d39f4b3fb Four milestones from the survey's remaining gaps
M17 - the mark of a change. A dot on the rows an operation produced, spent by the
next read of that folder: in memory, per folder, no timer and no watcher. Copy,
move, compress, extract, rename (single and batch) and new folders all mark what
they made, so "what did that 4 GB copy do?" has an answer even when the copy went
to a folder the user was not looking at. The dot is drawn by MarkOfChange in the
list and the grid, with a content description, and `changed` is set by the same
state update that announces the folder.

M18 - store-only archives. Compressing now asks for the name and whether to
compress, because the survey's most enthusiastic review is a bulk copy to a
computer and that file is better stored than squeezed. Deflater.NO_COMPRESSION
keeps it one pass; a STORED entry would need size and CRC before the header,
i.e. reading every file twice.

M19 - the trash says what it does. The screen states the 24-hour window, offers
Empty trash behind one question, and opening the trash sweeps what has expired -
the window used to run only after the next delete, so an old batch could stay on
the card indefinitely. Trash.emptyAll leaves anything in that folder that is not
one of ours alone.

M20 - launcher shortcuts. Images, Recent and Trash as static shortcuts carrying
a route extra; core/ShortcutRoute answers null for anything it does not know, so
an old shortcut cannot crash a new build. Favourites was dropped from the plan:
it is a section of the home screen, not a view, so a shortcut to it would promise
something that may not be there.

M21 (Android TV) is specified in the roadmap and deliberately not started: its
acceptance needs a TV device pass this machine cannot provide.

18 new tests (427 in total). Detekt's baseline was regenerated after two
signatures gained a parameter; the diff is three findings with new signatures and
their KDoc moved above the annotations so the baseline stays readable. Verified by
the gate only so far - the device pass for these four is next, and the terminal
here has been losing command output for the last hour.
2026-10-18 00:15:03 +02:00
SoftwareApp 17078bf613 A copy into a picked folder says where it went, and Show takes you there
The last acceptance criterion M16 had left open. After Copy to..., the snackbar reads 'Copied to AADst' with a Show button; after a move to a picked folder it keeps the undoable message instead, because the sources are gone and Show would lead nowhere.

Two things needed care rather than a string. The action button was hard-wired to undo() - the label was a parameter beside it, which let the two disagree - so UiMessage now carries a MessageAction, and the label follows from it: Undo for an undo, Show for a jump. And a message cannot name a folder from the path alone: a volume root has no name of its own, and internal storage's is 0. The message carries the picked PickerFolder, and the screen resolves its label the way breadcrumbs do - so copying into the root reads 'Copied to Internal storage', which is the case a plain path.name would have got wrong.

Four tests: the message names the destination and offers Show; Show opens it; a paste into the folder on screen still names nothing and offers nothing (its destination is the screen); a move to a picked folder offers Undo. All four driven through the view model, and both snackbar variants checked on the phone, including the volume-root one.

detekt's SpreadOperator baseline entries moved with the expression, so the message building is now a small helper with a deliberate suppression and a reason, and the baseline was regenerated: three obsolete entries removed, none added.
2026-10-17 23:19:07 +02:00
SoftwareApp 747a6f7784 The queue says what the scaling numbers answered
Items 3 and 3b were done but still read as open questions, and thumbnail jank is no longer blocked on a device that cannot report it - the phone run does, and the CI emulator always will. The one item still open is the baseline profile's delta, which needs a physical API 33+ device.
2026-10-17 23:01:48 +02:00
SoftwareApp 66183a8596 The benchmark runs in CI, and fails when the jank metric is missing
Item 5 of the queue: .github/workflows/benchmark.yml measures on an API 35 emulator (reactivecircus/android-emulator-runner, google_apis, x86_64, SwiftShader), on demand and every Monday. Not on pull requests: a run is minutes of measurement behind twenty of booting an emulator, and the gate is meant to answer in one or two.

It installs both APKs and instruments directly instead of using connectedBenchmarkAndroidTest, because that task installs the app itself - which undoes the compile reset that makes the measurement a never-run baseline. tools/benchmark-report.py turns the JSON into two tables, keeping frameCount (a length) apart from frameDurationCpuMs and frameOverrunMs (speeds), and --require-frame-duration fails the job when the second table would be empty: the metric is the reason the job exists.

Driving the workflow's own script against the phone first paid for itself three times. It found that cmd package compile --reset needs adbd as root - a user build refuses it with SecurityException, so the workflow now does adb root first (google_apis allows it) instead of silently measuring a compiled app. It produced the second run of the 20 000-file open (16 frames median, 32 max) and the first numbers for scroll, search and cold start at that size: search costs 319 frames, which is now the biggest number in the file. And it showed the phone reporting frameDurationCpuMs and frameOverrunMs after all, so PERFORMANCE.md's 'this phone reports counts only' was a property of those earlier runs, not of the handset - corrected, with the numbers.
2026-10-17 23:00:22 +02:00
SoftwareApp 1ec71381a0 The picker names a volume the way the browser does
Two fixes from driving Copy to… and Move to… on the phone.

The dialog was nested inside the conflict-prompt block, so it could only appear when a conflict was already on screen - which is never. Nothing in the unit tests could see that: they test the view model, and the view model was right.

And the picker named internal storage by the platform's own name for it, 0: as the volume row, and in the trail above it (0 / AADst). The roots screen has always shown Internal storage there; the picker now follows the same rule, through a label resource on PickerFolder rather than a second copy of the string logic. A test pins the label on both the row and the crumb.

On the device: copy leaves the source and the selection in place, move empties the source, clears the selection and says Moved 1 item. Recorded in EDGE_CASE_TESTING.md.
2026-10-17 22:44:53 +02:00
37 changed files with 1840 additions and 126 deletions
+111
View File
@@ -0,0 +1,111 @@
name: benchmark
# The macrobenchmark run, on an emulator rather than on a phone.
#
# Three reasons this exists as a workflow and not as a local step:
#
# * **It reports the jank metric.** `frameDurationCpuMs` and `frameOverrunMs` need frame timelines, which
# this project's phone sometimes supplies and sometimes does not — the run that does is the one worth
# looking at, and a CI emulator supplies it every time.
# * **It takes the phone out of the loop.** No MIUI install prompts, no AVD to keep alive, no cable.
# * **It is a second opinion.** The numbers in docs/PERFORMANCE.md come from one handset; an emulator run
# is a different device and build, so a regression that is the app's shows up in both.
#
# It is not on every pull request: one run is the four benchmarks × five iterations, which is minutes of
# measurement and considerably more of waiting for an emulator to boot.
on:
workflow_dispatch:
schedule:
# Monday, early: the week starts with a number, not with a guess.
- cron: '41 4 * * 1'
concurrency:
group: benchmark
cancel-in-progress: false
jobs:
emulator:
runs-on: ubuntu-latest
timeout-minutes: 75
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
# detekt 1.23 cannot parse JDK 25's version string, and the gate runs on 21 — keep them equal
# so a benchmark run cannot fail for a reason unrelated to the benchmark.
java-version: '21'
- uses: android-actions/setup-android@v3
- uses: gradle/actions/setup-gradle@v4
# Built before the emulator starts: Gradle is quick on the runner, emulator boot is not, and the
# two would otherwise queue behind each other.
- name: Build the APKs
run: ./gradlew :app:assembleBenchmark :benchmark:assembleBenchmark --console=plain
- name: Measure on an emulator
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: 35
# google_apis, not google_apis_playstore: the benchmark toggles the app's all-files access in
# Settings, and a Play image has no such page for a sideloaded app.
target: google_apis
arch: x86_64
profile: pixel_6
disable-animations: true
emulator-boot-timeout: 1200
# SwiftShader because the runner has no GPU: software rendering makes the milliseconds
# incomparable with a phone's, which is stated where the numbers are read. What survives is the
# shape — which benchmark is slow relative to the others — and the existence of the metric.
emulator-options: >-
-no-snapshot -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim
-camera-back none -camera-front none
script: |
set -o pipefail
# The fixture is built through adb because UiAutomation's shell runs as the app, not the shell
# user, and cannot write to /sdcard (see tools/benchmark-fixture.sh).
./tools/benchmark-fixture.sh
adb install -r app/build/outputs/apk/benchmark/app-benchmark.apk
adb install -r benchmark/build/outputs/apk/benchmark/benchmark-benchmark.apk
# The "never run" baseline: no profile, so what is measured has not been compiled by use.
# Clearing profile data is a system operation, so it needs adbd as root — which a google_apis
# image allows and a user build (the phone) does not, where this silently stays best-effort.
adb root || true
adb wait-for-device
adb shell cmd package compile --reset de.softwareapp_hb.filemanager || true
# Instrumented directly rather than through connectedBenchmarkAndroidTest, because that task
# installs the app itself — which would undo the compile reset above. `CompilationMode.Ignore()`
# in the test means nothing else installs either.
adb shell am instrument -w -r \
-e class de.softwareapp_hb.filemanager.benchmark.BrowserBenchmark \
de.softwareapp_hb.filemanager.benchmark/androidx.test.runner.AndroidJUnitRunner \
| tee instrument.log
status=${PIPESTATUS[0]}
mkdir -p benchmark-results
adb pull /sdcard/Android/media/de.softwareapp_hb.filemanager.benchmark benchmark-results/ || true
# The jank metric is the reason this job exists, so its absence fails the run rather than
# becoming a footnote in a log nobody opens.
python3 tools/benchmark-report.py --require-frame-duration benchmark-results > summary.md || status=1
cat summary.md
exit $status
- name: Keep the numbers
if: always()
uses: actions/upload-artifact@v4
with:
name: benchmark-results
path: |
benchmark-results
instrument.log
summary.md
if-no-files-found: warn
- name: Put the table on the run page
if: always()
run: |
if [ -f summary.md ]; then
cat summary.md >> "$GITHUB_STEP_SUMMARY"
else
echo "No summary: the benchmark did not get far enough to write one. See instrument.log." \
>> "$GITHUB_STEP_SUMMARY"
fi
+7
View File
@@ -32,3 +32,10 @@ demo-files/
# Written by :app:generateReleaseBaselineProfile; the profile itself is committed at # Written by :app:generateReleaseBaselineProfile; the profile itself is committed at
# app/src/main/baseline-prof.txt. # app/src/main/baseline-prof.txt.
app/src/release/generated/ app/src/release/generated/
# Written by a benchmark run, locally or by .github/workflows/benchmark.yml: the pulled JSON and traces,
# the instrumentation log and the table built from them. They describe one device at one moment; the
# numbers that matter are copied into docs/PERFORMANCE.md.
benchmark-results/
instrument.log
summary.md
+29 -1
View File
@@ -12,13 +12,32 @@ upload needs a **higher `versionCode`** than every previous upload.
### Added ### Added
- **A dot marks what an operation just produced.** Copy something, extract an archive, rename a file or make a
folder, and the rows it created carry a small dot until you open that folder again — so "what did that 4 GB
copy do?" has an answer, including when the copy went to a folder you were not looking at. The mark lives in
memory and is spent by the next read of the folder: no timer, no watcher, nothing to switch off. It carries a
content description, so TalkBack says it too.
- **Compressing asks two things: the name, and whether to compress.** The second one is for the case the
survey's most enthusiastic review describes — moving a whole collection to a computer: off stores the files
as they are, so the archive is built in one pass instead of being squeezed first. It is still an ordinary
zip, and it still extracts to the same bytes.
- **The trash says how long it keeps things, and empties on request.** The screen now states the window
("Deleted files are kept for 24 hours") instead of leaving it to be discovered, **Empty trash** does what it
says after one question, and opening the trash sweeps what has expired — the 24-hour window used to run only
when you deleted something else, so an old batch could sit on the card indefinitely.
- **Long-press the app icon: Images, Recent, Trash.** Three shortcuts to the views that are otherwise two or
three taps deep, with no permission and no dynamic state. Favourites is deliberately not one: it is a
section of the home screen rather than a view, so a shortcut to it would promise something that may not be
there.
- **Copy to… and Move to… chose a destination instead of making you go there.** The selection bar's - **Copy to… and Move to… chose a destination instead of making you go there.** The selection bar's
overflow now offers both verbs: a folder picker opens — the volumes first, then folders one level at a overflow now offers both verbs: a folder picker opens — the volumes first, then folders one level at a
time, with the trail above and Up beside it — and confirming starts the copy (or the move) into that time, with the trail above and Up beside it — and confirming starts the copy (or the move) into that
folder **without leaving the one you are in**. The files stay selected afterwards, so sending the same folder **without leaving the one you are in**. The files stay selected afterwards, so sending the same
set to a second destination is two taps. A name that already exists there asks exactly what Paste asks, set to a second destination is two taps. A name that already exists there asks exactly what Paste asks,
naming that folder; progress belongs to the same operation notification, and a move clears the selection naming that folder; progress belongs to the same operation notification, and a move clears the selection
because those rows are gone. Underneath it is the paste path with an explicit target: the engine was because those rows are gone. A finished copy answers with **"Copied to *folder*"** and a **Show** button
that opens the destination — so the file you just put somewhere is one tap away from being looked at. Underneath it is the paste path with an explicit target: the engine was
always target-agnostic, so the new part is the picker and the rules around it. always target-agnostic, so the new part is the picker and the rules around it.
- **Several files can be renamed at once, numbered in a series that carries on.** Selecting more - **Several files can be renamed at once, numbered in a series that carries on.** Selecting more
@@ -223,6 +242,15 @@ upload needs a **higher `versionCode`** than every previous upload.
### Fixed ### Fixed
- **Typing in the search field no longer restarts the index, and neither does opening another library.**
The pass that keeps the index current was started from inside the search's own job, and that job is
cancelled and replaced on every keystroke — so each letter cancelled the walk that had just started,
before it could record that it had finished, and the next letter began again at the first folder. The
progress counter restarting with every character was the visible half; the hidden half was that on a
full volume the index could not finish while anyone was typing. The same thing happened when switching
libraries, which restarts its own job too. The pass now belongs to the view model: one at a time,
whoever asks, not cancelled by the screen that asked, re-answering what is on screen when it lands.
- **The search field told the truth everywhere except inside a library.** Opening the field from a - **The search field told the truth everywhere except inside a library.** Opening the field from a
library left the scope on "this folder" — the hint read *Search this folder* and a folder toggle library left the scope on "this folder" — the hint read *Search this folder* and a folder toggle
sat beside it — while the search actually ran everywhere, because the view model has always known sat beside it — while the search actually ran everywhere, because the view model has always known
+5
View File
@@ -74,6 +74,11 @@
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
<!-- Long-press shortcuts: Images, Recent, Trash. See res/xml/shortcuts.xml. -->
<meta-data
android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
<!-- <!--
Receiving a share. Without these the app is not a share target at all — the Receiving a share. Without these the app is not a share target at all — the
manifest had nothing but LAUNCHER, so no other app could hand it a file. manifest had nothing but LAUNCHER, so no other app could hand it a file.
@@ -10,6 +10,7 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import de.softwareapp_hb.filemanager.core.FileEntry import de.softwareapp_hb.filemanager.core.FileEntry
import de.softwareapp_hb.filemanager.core.ShortcutRoute
import de.softwareapp_hb.filemanager.ui.browser.BrowserScreen import de.softwareapp_hb.filemanager.ui.browser.BrowserScreen
import de.softwareapp_hb.filemanager.ui.browser.IncomingRequest import de.softwareapp_hb.filemanager.ui.browser.IncomingRequest
import de.softwareapp_hb.filemanager.ui.browser.contentUriFor import de.softwareapp_hb.filemanager.ui.browser.contentUriFor
@@ -25,6 +26,8 @@ class MainActivity : ComponentActivity() {
// has neither, and the browser then behaves exactly as it always did — the two // has neither, and the browser then behaves exactly as it always did — the two
// flows are the same screen with one extra bar on it. // flows are the same screen with one extra bar on it.
val incoming = IncomingRequest.from(intent) val incoming = IncomingRequest.from(intent)
// A launcher shortcut carries a route instead: which view to open, once.
val route = ShortcutRoute.from(intent?.getStringExtra(ShortcutRoute.EXTRA))
setContent { setContent {
FileManagerTheme { FileManagerTheme {
@@ -34,6 +37,7 @@ class MainActivity : ComponentActivity() {
) { ) {
BrowserScreen( BrowserScreen(
incoming = incoming, incoming = incoming,
startRoute = route,
onDeliver = ::deliver, onDeliver = ::deliver,
onDone = ::finish, onDone = ::finish,
) )
@@ -0,0 +1,27 @@
package de.softwareapp_hb.filemanager.core
/**
* Where a launcher shortcut asks the app to open.
*
* The keys are what `res/xml/shortcuts.xml` puts in its intent's extra, and [from] answers `null` for
* anything else — an old shortcut surviving an upgrade, or a typo in the XML. A launcher entry must never
* be able to crash the app it opens.
*
* **Recent, not Favourites.** Favourites is a section on the home screen rather than a view of its own, so a
* shortcut to it would open the home screen and promise a section that is absent when nothing is starred.
* The three routes here all open a view that exists by name.
*/
enum class ShortcutRoute(val key: String) {
IMAGES("images"),
RECENT("recent"),
TRASH("trash"),
;
companion object {
/** The intent extra the shortcuts carry. */
const val EXTRA = "de.softwareapp_hb.filemanager.SHORTCUT"
fun from(key: String?): ShortcutRoute? = entries.firstOrNull { it.key == key }
}
}
@@ -25,6 +25,7 @@ import java.io.InputStream
import java.io.OutputStream import java.io.OutputStream
import java.nio.channels.SeekableByteChannel import java.nio.channels.SeekableByteChannel
import java.util.zip.ZipEntry import java.util.zip.ZipEntry
import java.util.zip.Deflater
import java.util.zip.ZipOutputStream import java.util.zip.ZipOutputStream
import kotlin.coroutines.cancellation.CancellationException import kotlin.coroutines.cancellation.CancellationException
@@ -69,10 +70,17 @@ data class ArchiveEntry(
*/ */
class ArchiveEngine(private val source: StorageSource) { class ArchiveEngine(private val source: StorageSource) {
/** Write [entries] into a new ZIP at [destination]. Folders are included recursively. */ /**
* Write [entries] into a new ZIP at [destination]. Folders are included recursively.
*
* [compress] `false` stores the files as they are: one pass, for an archive that is about to be copied off
* the phone. `setLevel` rather than STORED entries, which would need each file's size and CRC before its
* header — reading everything twice, slower than the deflate it avoids.
*/
suspend fun createZip( suspend fun createZip(
entries: List<StoragePath>, entries: List<StoragePath>,
destination: StoragePath, destination: StoragePath,
compress: Boolean = true,
onProgress: (OperationProgress) -> Unit = {}, onProgress: (OperationProgress) -> Unit = {},
): OperationResult { ): OperationResult {
val planned = LinkedHashMap<StoragePath, String>() val planned = LinkedHashMap<StoragePath, String>()
@@ -84,6 +92,7 @@ class ArchiveEngine(private val source: StorageSource) {
source.createFile(destination) source.createFile(destination)
source.openWrite(destination).use { raw -> source.openWrite(destination).use { raw ->
ZipOutputStream(BufferedOutputStream(raw)).use { zip -> ZipOutputStream(BufferedOutputStream(raw)).use { zip ->
zip.setLevel(if (compress) Deflater.DEFAULT_COMPRESSION else Deflater.NO_COMPRESSION)
for ((file, entryName) in planned) { for ((file, entryName) in planned) {
if (!currentCoroutineContext().isActive) { if (!currentCoroutineContext().isActive) {
state.cancel() state.cancel()
@@ -264,6 +264,28 @@ class Trash(
return purged return purged
} }
/**
* Delete every staged batch for good, now.
*
* The one destructive action in the app with no undo — which is what emptying means: it does what
* [purgeExpired] would do later, on purpose. Anything in the trash folder that is not one of our batches is
* left alone; the folder lives on the user's volume and is not ours to tidy.
*/
suspend fun emptyAll(): Int {
val root = root()
if (!source.exists(root)) return 0
var removed = 0
for (child in source.list(root)) {
if (batchTimestamp(child.name) == null) continue
if (source.delete(child.path)) {
index.forget(child.name)
removed++
}
}
return removed
}
/** /**
* What the index says is still recoverable on this volume, newest batch first. * What the index says is still recoverable on this volume, newest batch first.
* *
@@ -3,7 +3,9 @@ package de.softwareapp_hb.filemanager.ui.browser
import android.content.Context import android.content.Context
import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
@@ -11,6 +13,8 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Android import androidx.compose.material.icons.filled.Android
@@ -43,6 +47,8 @@ import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
@@ -189,6 +195,24 @@ fun iconFor(category: FileCategory): ImageVector = when (category) {
FileCategory.RECENT -> Icons.Filled.History FileCategory.RECENT -> Icons.Filled.History
} }
/**
* The dot that says an operation produced this row.
*
* A dot rather than a colour: a row already has two states that use colour — selected, and focused in a
* two-pane window — and a third would make them hard to tell apart. The content description is what makes
* it more than decoration: TalkBack reads it, and a Compose test can find it.
*/
@Composable
fun MarkOfChange(modifier: Modifier = Modifier) {
val label = stringResource(R.string.browser_row_changed)
Box(
modifier = modifier
.size(8.dp)
.background(MaterialTheme.colorScheme.primary, CircleShape)
.semantics { contentDescription = label },
)
}
/** One row of the list view. */ /** One row of the list view. */
@OptIn(ExperimentalFoundationApi::class) @OptIn(ExperimentalFoundationApi::class)
@Composable @Composable
@@ -204,6 +228,8 @@ fun EntryRow(
* than opening them. * than opening them.
*/ */
selectionMode: Boolean = false, selectionMode: Boolean = false,
/** `true` when an operation produced this entry and the folder has not been read since. */
changed: Boolean = false,
onClick: () -> Unit, onClick: () -> Unit,
onLongClick: (() -> Unit)? = null, onLongClick: (() -> Unit)? = null,
onDoubleClick: (() -> Unit)? = null, onDoubleClick: (() -> Unit)? = null,
@@ -224,7 +250,20 @@ fun EntryRow(
// `ListItem` measures the leading slot rather than capping it, so the row grows to // `ListItem` measures the leading slot rather than capping it, so the row grows to
// suit a 48 dp thumbnail instead of clipping it. // suit a 48 dp thumbnail instead of clipping it.
leadingContent = { EntryIcon(entry = entry, size = ListThumbnailSize) }, leadingContent = { EntryIcon(entry = entry, size = ListThumbnailSize) },
headlineContent = { Text(text = entry.name, maxLines = 1, overflow = TextOverflow.Ellipsis) }, headlineContent = {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = entry.name,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = false),
)
if (changed) {
Spacer(Modifier.width(8.dp))
MarkOfChange()
}
}
},
supportingContent = { supportingContent = {
val description = entry.subtitle() val description = entry.subtitle()
Text( Text(
@@ -262,6 +301,8 @@ fun EntryGridCell(
location: String? = null, location: String? = null,
/** `true` while a selection is running; see [EntryRow.selectionMode]. */ /** `true` while a selection is running; see [EntryRow.selectionMode]. */
selectionMode: Boolean = false, selectionMode: Boolean = false,
/** `true` when an operation produced this entry; see [EntryRow.changed]. */
changed: Boolean = false,
onClick: () -> Unit, onClick: () -> Unit,
onLongClick: (() -> Unit)? = null, onLongClick: (() -> Unit)? = null,
onDoubleClick: (() -> Unit)? = null, onDoubleClick: (() -> Unit)? = null,
@@ -292,12 +333,19 @@ fun EntryGridCell(
} }
EntryIcon(entry = entry, size = GridThumbnailSize) EntryIcon(entry = entry, size = GridThumbnailSize)
Spacer(Modifier.height(8.dp)) Spacer(Modifier.height(8.dp))
Text( Row(verticalAlignment = Alignment.CenterVertically) {
text = entry.name, Text(
style = MaterialTheme.typography.bodyMedium, text = entry.name,
maxLines = 2, style = MaterialTheme.typography.bodyMedium,
overflow = TextOverflow.Ellipsis, maxLines = 2,
) overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = false),
)
if (changed) {
Spacer(Modifier.width(6.dp))
MarkOfChange()
}
}
Spacer(Modifier.height(4.dp)) Spacer(Modifier.height(4.dp))
val description = entry.subtitle() val description = entry.subtitle()
Text( Text(
@@ -346,6 +346,7 @@ private fun DirectoryView(
entry = entry, entry = entry,
selected = entry.isHighlighted(state), selected = entry.isHighlighted(state),
selectionMode = selecting, selectionMode = selecting,
changed = entry.path in state.changed,
location = entry.searchLocation(state.searchRoot), location = entry.searchLocation(state.searchRoot),
onClick = when { onClick = when {
selecting -> toggle selecting -> toggle
@@ -376,6 +377,7 @@ private fun DirectoryView(
entry = entry, entry = entry,
selected = entry.isHighlighted(state), selected = entry.isHighlighted(state),
selectionMode = selecting, selectionMode = selecting,
changed = entry.path in state.changed,
location = entry.searchLocation(state.searchRoot), location = entry.searchLocation(state.searchRoot),
onClick = when { onClick = when {
selecting -> toggle selecting -> toggle
@@ -23,6 +23,7 @@ import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.Switch
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -43,6 +44,64 @@ import de.softwareapp_hb.filemanager.core.ConflictPolicy
import de.softwareapp_hb.filemanager.core.FileEntry import de.softwareapp_hb.filemanager.core.FileEntry
import de.softwareapp_hb.filemanager.core.isUsableName import de.softwareapp_hb.filemanager.core.isUsableName
/**
* Compressing something, with the one choice that changes what comes out.
*
* The name is the usual one — suggested from the selection, made unique against the folder. The switch is
* the interesting half: **compression is a trade**, and a file that is about to leave the phone is often
* better stored than squeezed. It starts on, because saving space is what "compress" means to most people;
* it is not remembered, because the next archive is a different decision.
*/
@Composable
fun CompressDialog(
initialName: String,
onConfirm: (name: String, compress: Boolean) -> Unit,
onDismiss: () -> Unit,
) {
var name by remember { mutableStateOf(initialName) }
var compress by remember { mutableStateOf(true) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.compress_dialog_title)) },
text = {
Column {
OutlinedTextField(
value = name,
onValueChange = { name = it },
label = { Text(stringResource(R.string.compress_dialog_name)) },
singleLine = true,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
modifier = Modifier.fillMaxWidth(),
)
Spacer(modifier = Modifier.height(16.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Column(modifier = Modifier.weight(1f)) {
Text(stringResource(R.string.compress_dialog_contents))
Text(
text = stringResource(R.string.compress_dialog_hint),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Switch(checked = compress, onCheckedChange = { compress = it })
}
}
},
confirmButton = {
TextButton(
onClick = { onConfirm(name, compress) },
enabled = name.isNotBlank(),
) {
Text(stringResource(R.string.compress_dialog_confirm))
}
},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.compress_dialog_cancel)) }
},
)
}
/** /**
* The **Copy to… / Move to…** picker. * The **Copy to… / Move to…** picker.
* *
@@ -71,8 +130,12 @@ fun TransferToDialog(
text = { text = {
Column { Column {
if (picker.crumbs.isNotEmpty()) { if (picker.crumbs.isNotEmpty()) {
// `map` is inline, so the labels can be resolved here; the trail is then plain text.
val trail = picker.crumbs.map { crumb ->
crumb.labelRes?.let { res -> stringResource(res) } ?: crumb.title
}
Text( Text(
text = picker.crumbs.joinToString(" / ") { it.name }, text = trail.joinToString(" / "),
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
maxLines = 1, maxLines = 1,
) )
@@ -102,7 +165,7 @@ fun TransferToDialog(
) )
Spacer(modifier = Modifier.width(12.dp)) Spacer(modifier = Modifier.width(12.dp))
Text( Text(
text = folder.title, text = folder.labelRes?.let { stringResource(it) } ?: folder.title,
maxLines = 1, maxLines = 1,
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
) )
@@ -67,7 +67,9 @@ import de.softwareapp_hb.filemanager.FileManagerApplication
import de.softwareapp_hb.filemanager.R import de.softwareapp_hb.filemanager.R
import de.softwareapp_hb.filemanager.core.ConflictPolicy import de.softwareapp_hb.filemanager.core.ConflictPolicy
import de.softwareapp_hb.filemanager.core.FileEntry import de.softwareapp_hb.filemanager.core.FileEntry
import de.softwareapp_hb.filemanager.core.ShortcutRoute
import de.softwareapp_hb.filemanager.core.StoragePath import de.softwareapp_hb.filemanager.core.StoragePath
import de.softwareapp_hb.filemanager.domain.Trash
import de.softwareapp_hb.filemanager.text.labelRes import de.softwareapp_hb.filemanager.text.labelRes
import de.softwareapp_hb.filemanager.ui.duplicates.DuplicateScreen import de.softwareapp_hb.filemanager.ui.duplicates.DuplicateScreen
import de.softwareapp_hb.filemanager.ui.trash.TrashScreen import de.softwareapp_hb.filemanager.ui.trash.TrashScreen
@@ -80,10 +82,17 @@ import de.softwareapp_hb.filemanager.ui.viewer.MediaPlayerScreen
import de.softwareapp_hb.filemanager.ui.viewer.PdfViewerScreen import de.softwareapp_hb.filemanager.ui.viewer.PdfViewerScreen
import de.softwareapp_hb.filemanager.ui.viewer.TextEditorScreen import de.softwareapp_hb.filemanager.ui.viewer.TextEditorScreen
/**
* The browser, and everything that can be on top of it.
*
* [startRoute] is set when the app was opened from a launcher shortcut: the view is applied once, by the
* effect below, and `null` — every ordinary launch — leaves the screen exactly as it always was.
*/
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun BrowserScreen( fun BrowserScreen(
incoming: IncomingRequest? = null, incoming: IncomingRequest? = null,
startRoute: ShortcutRoute? = null,
onDeliver: (FileEntry) -> Unit = {}, onDeliver: (FileEntry) -> Unit = {},
onDone: () -> Unit = {}, onDone: () -> Unit = {},
viewModel: BrowserViewModel = viewModel(factory = BrowserViewModel.Factory), viewModel: BrowserViewModel = viewModel(factory = BrowserViewModel.Factory),
@@ -93,6 +102,12 @@ fun BrowserScreen(
val provider = remember(context) { (context.applicationContext as FileManagerApplication).storage } val provider = remember(context) { (context.applicationContext as FileManagerApplication).storage }
val snackbarHostState = remember { SnackbarHostState() } val snackbarHostState = remember { SnackbarHostState() }
// A shortcut is a request to open one view. Keyed on the route so a recomposition cannot repeat it, and
// `null` for every ordinary launch, which is the case that has to stay exactly as it was.
LaunchedEffect(startRoute) {
startRoute?.let(viewModel::openShortcut)
}
var showSort by remember { mutableStateOf(false) } var showSort by remember { mutableStateOf(false) }
var detailsFor by remember { mutableStateOf<FileEntry?>(null) } var detailsFor by remember { mutableStateOf<FileEntry?>(null) }
var showNewFolder by remember { mutableStateOf(false) } var showNewFolder by remember { mutableStateOf(false) }
@@ -101,6 +116,8 @@ fun BrowserScreen(
/** Several files at once: the selection, held while the pattern dialog is open. */ /** Several files at once: the selection, held while the pattern dialog is open. */
var renameAllTargets by remember { mutableStateOf<List<FileEntry>?>(null) } var renameAllTargets by remember { mutableStateOf<List<FileEntry>?>(null) }
var confirmDelete by remember { mutableStateOf<List<StoragePath>?>(null) } var confirmDelete by remember { mutableStateOf<List<StoragePath>?>(null) }
// Emptying is the one action here with no undo, so it gets the same question a delete does.
var confirmEmptyTrash by remember { mutableStateOf(false) }
var searchOpen by remember { mutableStateOf(false) } var searchOpen by remember { mutableStateOf(false) }
/* /*
@@ -308,10 +325,24 @@ fun BrowserScreen(
TrashScreen( TrashScreen(
batches = overlay.batches, batches = overlay.batches,
loading = overlay.loading, loading = overlay.loading,
retentionHours = Trash.RETENTION_HOURS,
onRestore = { batch -> viewModel.restoreFromTrash(batch) }, onRestore = { batch -> viewModel.restoreFromTrash(batch) },
onRestoreEntry = { batch, entry -> viewModel.restoreFromTrash(batch, entry) }, onRestoreEntry = { batch, entry -> viewModel.restoreFromTrash(batch, entry) },
onEmpty = { confirmEmptyTrash = true },
onClose = viewModel::closeOverlay, onClose = viewModel::closeOverlay,
) )
if (confirmEmptyTrash) {
ConfirmDialog(
title = stringResource(R.string.trash_empty_confirm_title),
body = stringResource(R.string.trash_empty_confirm_body),
confirmLabel = stringResource(R.string.trash_empty_confirm_action),
onDismiss = { confirmEmptyTrash = false },
onConfirm = {
confirmEmptyTrash = false
viewModel.emptyTrash()
},
)
}
return return
} }
@@ -320,17 +351,18 @@ fun BrowserScreen(
val message = state.message val message = state.message
val messageText = message?.let { // A message that names a folder cannot be built from the path alone: a volume root has no name of its
it.pluralQuantity?.let { quantity -> // own (`0`), which is the one thing only the screen can resolve — the same rule breadcrumbs use.
pluralStringResource(it.textRes, quantity, *it.args.toTypedArray()) val destinationLabel = message?.destination?.let { folder ->
} ?: stringResource(it.textRes, *it.args.toTypedArray()) folder.labelRes?.let { stringResource(it) } ?: folder.title
} }
val messageText = message?.let { messageText(it, destinationLabel) }
// Resolved out here because `stringResource` is a composable call and the effect is not. // Resolved out here because `stringResource` is a composable call and the effect is not.
val undoLabel = message?.actionLabelRes?.let { stringResource(it) } val actionLabel = message?.actionLabelRes?.let { stringResource(it) }
LaunchedEffect(message?.id) { LaunchedEffect(message?.id) {
if (messageText != null) { if (messageText != null) {
val outcome = snackbarHostState.showSnackbar(messageText, actionLabel = undoLabel) val outcome = snackbarHostState.showSnackbar(messageText, actionLabel = actionLabel)
if (outcome == SnackbarResult.ActionPerformed) viewModel.undo() if (outcome == SnackbarResult.ActionPerformed) viewModel.performMessageAction()
viewModel.consumeMessage() viewModel.consumeMessage()
} }
} }
@@ -430,7 +462,7 @@ fun BrowserScreen(
renameTarget = selected.singleOrNull() renameTarget = selected.singleOrNull()
} }
}, },
onCompress = { viewModel.compress(state.selection.toList()) }, onCompress = { viewModel.beginCompress(state.selection.toList()) },
onExtract = { onExtract = {
state.selectedEntries.singleOrNull()?.let(viewModel::extract) state.selectedEntries.singleOrNull()?.let(viewModel::extract)
}, },
@@ -582,18 +614,25 @@ fun BrowserScreen(
) )
} }
state.conflict?.let { prompt -> state.compressRequest?.let { request ->
val transferPicker = state.transferPicker CompressDialog(
if (transferPicker != null) { initialName = request.name,
TransferToDialog( onConfirm = viewModel::confirmCompress,
picker = transferPicker, onDismiss = viewModel::cancelCompress,
onOpen = viewModel::pickerOpen, )
onUp = viewModel::pickerUp, }
onConfirm = viewModel::confirmTransferTo,
onDismiss = viewModel::cancelTransferTo,
)
}
state.transferPicker?.let { picker ->
TransferToDialog(
picker = picker,
onOpen = viewModel::pickerOpen,
onUp = viewModel::pickerUp,
onConfirm = viewModel::confirmTransferTo,
onDismiss = viewModel::cancelTransferTo,
)
}
state.conflict?.let { prompt ->
ConflictDialog( ConflictDialog(
prompt = prompt, prompt = prompt,
onChoice = { policy -> viewModel.resolveConflict(policy) }, onChoice = { policy -> viewModel.resolveConflict(policy) },
@@ -602,3 +641,21 @@ fun BrowserScreen(
} }
} }
/**
* The text of a snackbar message.
*
* A message that names a folder cannot carry its label as an argument — a volume root has no name of its own
* (internal storage's is `0`) — so the screen resolves it the way breadcrumbs are resolved and passes it as
* the first argument.
*
* `SpreadOperator` is suppressed on purpose: the `vararg` resource helpers take an array, and this runs once
* per message rather than once per row or per frame, so the copy the rule warns about is not a hot path.
*/
@Suppress("SpreadOperator")
@Composable
private fun messageText(message: UiMessage, destinationLabel: String?): String {
val args = if (destinationLabel != null) listOf<Any>(destinationLabel) + message.args else message.args
return message.pluralQuantity?.let { quantity ->
pluralStringResource(message.textRes, quantity, *args.toTypedArray())
} ?: stringResource(message.textRes, *args.toTypedArray())
}
@@ -4,6 +4,7 @@ import android.net.Uri
import androidx.activity.result.IntentSenderRequest import androidx.activity.result.IntentSenderRequest
import androidx.annotation.AnyRes import androidx.annotation.AnyRes
import androidx.annotation.StringRes import androidx.annotation.StringRes
import de.softwareapp_hb.filemanager.R
import de.softwareapp_hb.filemanager.core.ConflictPolicy import de.softwareapp_hb.filemanager.core.ConflictPolicy
import de.softwareapp_hb.filemanager.core.FileCategory import de.softwareapp_hb.filemanager.core.FileCategory
import de.softwareapp_hb.filemanager.core.FileEntry import de.softwareapp_hb.filemanager.core.FileEntry
@@ -36,15 +37,23 @@ data class Clipboard(val paths: List<StoragePath>, val cut: Boolean) {
val isEmpty: Boolean get() = paths.isEmpty() val isEmpty: Boolean get() = paths.isEmpty()
} }
/** A compress waiting for its two answers: the archive's name, and whether to compress it. */
data class CompressRequest(val paths: List<StoragePath>, val name: String)
/** /**
* A folder the "copy to…" picker is offering: a volume root, or a folder inside one. * A folder the "copy to…" picker is offering: a volume root, or a folder inside one.
* *
* [label] is the platform's name for a volume, which is the only place the picker has something better * [label] is the platform's name for a volume, which is the only place the picker has something better
* than a path to show — internal storage's own name is `0`. * than a path to show — internal storage's own name is `0`.
*/ */
data class PickerFolder(val path: StoragePath, val label: String? = null) { data class PickerFolder(
val path: StoragePath,
val label: String? = null,
/** A localised name for the volumes the platform does not name — internal storage is `0` to it. */
@StringRes val labelRes: Int? = null,
) {
/** What the row says: the volume's label when there is one, else the folder's own name. */ /** What the row says: the volume's own name, else the folder's name. */
val title: String get() = label ?: path.name val title: String get() = label ?: path.name
} }
@@ -61,11 +70,26 @@ data class TransferPicker(
/** The folder being shown, or `null` for the volumes. */ /** The folder being shown, or `null` for the volumes. */
val path: StoragePath? = null, val path: StoragePath? = null,
val folders: List<PickerFolder> = emptyList(), val folders: List<PickerFolder> = emptyList(),
/** The trail back to the volumes, ending with [path] when one is open. */ /** The trail back to the volumes, ending with [path] when one is open; a root keeps its label. */
val crumbs: List<StoragePath> = emptyList(), val crumbs: List<PickerFolder> = emptyList(),
val loading: Boolean = false, val loading: Boolean = false,
) )
/**
* What a snackbar's action button does.
*
* The label follows from the action rather than being passed beside it, so the two cannot disagree: an
* action that offers "Undo" is an undo, and one that offers "Show" is a jump.
*/
sealed interface MessageAction {
/** Take the change back — the undo of the operation that has just finished. */
data object Undo : MessageAction
/** Open the folder an operation wrote to. */
data class Show(val path: StoragePath) : MessageAction
}
/** A one-shot message for a snackbar. [id] makes repeats of the same text distinguishable. */ /** A one-shot message for a snackbar. [id] makes repeats of the same text distinguishable. */
data class UiMessage( data class UiMessage(
/** A `@StringRes` or `@PluralsRes` value; see [pluralQuantity]. */ /** A `@StringRes` or `@PluralsRes` value; see [pluralQuantity]. */
@@ -73,10 +97,25 @@ data class UiMessage(
val args: List<Any> = emptyList(), val args: List<Any> = emptyList(),
/** Set when [textRes] names a `<plurals>` resource; the UI resolves it accordingly. */ /** Set when [textRes] names a `<plurals>` resource; the UI resolves it accordingly. */
val pluralQuantity: Int? = null, val pluralQuantity: Int? = null,
/** When set, the snackbar offers a single action button carrying this label. */ /** What the snackbar's action button does; `null` for a message with no action. */
@StringRes val actionLabelRes: Int? = null, val action: MessageAction? = null,
/**
* A folder the text names, whose label only the UI can resolve: a volume root has no name of its own —
* internal storage's is `0`. When set, its title becomes the text's first argument.
*/
val destination: PickerFolder? = null,
val id: Long = System.nanoTime(), val id: Long = System.nanoTime(),
) ) {
/** The action button's label, or `null` when there is no action. */
@get:StringRes
val actionLabelRes: Int?
get() = when (action) {
MessageAction.Undo -> R.string.browser_action_undo
is MessageAction.Show -> R.string.browser_action_show
null -> null
}
}
/** /**
* A paste that hit existing names, waiting for the user to choose how to resolve it. * A paste that hit existing names, waiting for the user to choose how to resolve it.
@@ -287,8 +326,17 @@ data class BrowserUiState(
/** The entry the wide-screen detail pane is showing; `null` until the user picks one. */ /** The entry the wide-screen detail pane is showing; `null` until the user picks one. */
val focus: DetailFocus? = null, val focus: DetailFocus? = null,
val clipboard: Clipboard? = null, val clipboard: Clipboard? = null,
/**
* The rows an operation produced in this folder since it was last read, drawn as a dot.
*
* Spent by the read that shows them: the mark means "new since you last looked here", so it is
* cleared by opening the folder again and forgotten when the process ends.
*/
val changed: Set<StoragePath> = emptySet(),
/** The **Copy to… / Move to…** destination picker, when one is open. */ /** The **Copy to… / Move to…** destination picker, when one is open. */
val transferPicker: TransferPicker? = null, val transferPicker: TransferPicker? = null,
/** A compress waiting for its name and its compression choice. */
val compressRequest: CompressRequest? = null,
val loading: Boolean = false, val loading: Boolean = false,
val freeBytes: Long? = null, val freeBytes: Long? = null,
val message: UiMessage? = null, val message: UiMessage? = null,
@@ -21,6 +21,7 @@ import de.softwareapp_hb.filemanager.core.FileKind
import de.softwareapp_hb.filemanager.core.NameAllocator import de.softwareapp_hb.filemanager.core.NameAllocator
import de.softwareapp_hb.filemanager.core.SortDirection import de.softwareapp_hb.filemanager.core.SortDirection
import de.softwareapp_hb.filemanager.core.SortKey import de.softwareapp_hb.filemanager.core.SortKey
import de.softwareapp_hb.filemanager.core.ShortcutRoute
import de.softwareapp_hb.filemanager.core.SortSpec import de.softwareapp_hb.filemanager.core.SortSpec
import de.softwareapp_hb.filemanager.core.SortedMerge import de.softwareapp_hb.filemanager.core.SortedMerge
import de.softwareapp_hb.filemanager.core.StoragePath import de.softwareapp_hb.filemanager.core.StoragePath
@@ -135,6 +136,26 @@ class BrowserViewModel(
*/ */
private var selectionToRestore: Set<StoragePath> = emptySet() private var selectionToRestore: Set<StoragePath> = emptySet()
/**
* What each folder gained since it was last read, waiting to be shown as a dot.
*
* In memory and per folder, for the same reason the clipboard is: the mark means "new since you last
* looked here", so it is spent by the read that shows it, and a restart starts clean. Nothing here
* needs a timestamp, a timer or a background job — a row is new because an operation said so.
*/
private val changedFolders = HashMap<StoragePath, MutableSet<StoragePath>>()
/**
* The index pass that is running, if any.
*
* **Owned by the view model, not by whoever asked for it.** A search cancels and restarts its own job
* on every keystroke; a pass started from inside that job was therefore cancelled a few characters
* later — before it could stamp the volume — and the next keystroke started another one from the first
* folder. Typing "photo" on a phone walked the volume five times, finished none of them, and the
* counter on screen restarted with every letter. One job, one pass, whoever asked.
*/
private var indexJob: Job? = null
/** The running recursive search, so the next keystroke can supersede it. */ /** The running recursive search, so the next keystroke can supersede it. */
private var searchJob: Job? = null private var searchJob: Job? = null
@@ -312,10 +333,14 @@ class BrowserViewModel(
// The folder is announced before anything is read, so leaving the previous one is immediate // The folder is announced before anything is read, so leaving the previous one is immediate
// and the progress bar has something to sit above. // and the progress bar has something to sit above.
listing = emptyList() listing = emptyList()
// Taken (not read) here: the marks are spent by the read that shows them, so a second visit
// to the folder is a visit to a folder that no longer has anything new in it.
val appeared = changedFolders.remove(path).orEmpty()
_state.update { _state.update {
it.copy( it.copy(
path = path, path = path,
category = null, category = null,
changed = appeared,
breadcrumbs = breadcrumbsOf(path), breadcrumbs = breadcrumbsOf(path),
selection = emptySet(), selection = emptySet(),
focus = null, focus = null,
@@ -517,7 +542,7 @@ class BrowserViewModel(
fun pickerUp() { fun pickerUp() {
val picker = _state.value.transferPicker ?: return val picker = _state.value.transferPicker ?: return
val crumbs = picker.crumbs val crumbs = picker.crumbs
openPicker(if (crumbs.size > 1) crumbs[crumbs.size - 2] else null) openPicker(if (crumbs.size > 1) crumbs[crumbs.size - 2].path else null)
} }
fun cancelTransferTo() { fun cancelTransferTo() {
@@ -555,7 +580,14 @@ class BrowserViewModel(
it.copy(conflict = ConflictPrompt(picker.paths, target, picker.cut, conflicts)) it.copy(conflict = ConflictPrompt(picker.paths, target, picker.cut, conflicts))
} }
} else { } else {
transfer(picker.paths, target, picker.cut, ConflictPolicy.KEEP_BOTH) transfer(
paths = picker.paths,
target = target,
cut = picker.cut,
policy = ConflictPolicy.KEEP_BOTH,
// Only a copy: a move's message is the undoable one, and its sources are gone.
announce = if (picker.cut) null else picker.crumbs.lastOrNull() ?: PickerFolder(target),
)
} }
} }
} }
@@ -574,7 +606,15 @@ class BrowserViewModel(
} }
viewModelScope.launch { viewModelScope.launch {
val folders = if (path == null) { val folders = if (path == null) {
storage.volumes().map { PickerFolder(path = it.root, label = it.label) } storage.volumes().map { volume ->
PickerFolder(
path = volume.root,
label = volume.label,
// The same rule as the roots screen: internal storage has no platform label, and
// showing its own name (`0`) in a copy dialog would be a riddle.
labelRes = if (volume.label == null) R.string.browser_internal_storage else null,
)
}
} else { } else {
val source = storage.activeSource() val source = storage.activeSource()
val entries = if (source == null) { val entries = if (source == null) {
@@ -582,7 +622,10 @@ class BrowserViewModel(
} else { } else {
runCatching { source.list(path) }.getOrDefault(emptyList()) runCatching { source.list(path) }.getOrDefault(emptyList())
} }
entries.filter { it.isDirectory } // Folders only, and hidden ones only when the listing shows hidden files: the picker is a
// listing, and a `.plainfiles-trash` or a `.thumbnails` folder in a copy dialog is an
// invitation to put a file somewhere it will never be seen again.
entries.filter { it.isDirectory && (_state.value.showHidden || !it.isHidden) }
.sortedWith(SortSpec().comparator) .sortedWith(SortSpec().comparator)
.map { PickerFolder(path = it.path) } .map { PickerFolder(path = it.path) }
} }
@@ -599,17 +642,25 @@ class BrowserViewModel(
} }
/** The trail down to [path], starting at its volume root; empty for the volume list itself. */ /** The trail down to [path], starting at its volume root; empty for the volume list itself. */
private fun pickerCrumbs(path: StoragePath?): List<StoragePath> { private fun pickerCrumbs(path: StoragePath?): List<PickerFolder> {
if (path == null) return emptyList() if (path == null) return emptyList()
val roots = storage.volumes().mapTo(HashSet()) { it.root } val volumes = storage.volumes().associateBy { it.root }
val crumbs = ArrayList<StoragePath>() val crumbs = ArrayList<StoragePath>()
var current: StoragePath? = path var current: StoragePath? = path
while (current != null) { while (current != null) {
crumbs += current crumbs += current
if (current in roots) break if (current in volumes) break
current = current.parent current = current.parent
} }
return crumbs.reversed() return crumbs.reversed().map { crumb ->
// A volume root in the trail is named the way the volume list names it.
val volume = volumes[crumb] ?: return@map PickerFolder(path = crumb)
PickerFolder(
path = crumb,
label = volume.label,
labelRes = if (volume.label == null) R.string.browser_internal_storage else null,
)
}
} }
// ----------------------------------------------------------------- libraries // ----------------------------------------------------------------- libraries
@@ -861,13 +912,20 @@ class BrowserViewModel(
} }
searchJob = viewModelScope.launch { searchJob = viewModelScope.launch {
if (searchIndex.stamps().isNotEmpty()) showIndexedResults(query, source) val known = searchIndex.stamps().isNotEmpty()
if (known) showIndexedResults(query, source)
bringIndexCurrent(source) // **Not awaited** when there is already an answer. The pass belongs to the view model, so
// typing neither cancels it nor queues behind it; it re-answers this query when it lands.
val refresh = bringIndexCurrent(source)
// Answered again, because the pass may have found the file this search is for — if (!known) {
// which is the whole of "I just downloaded it, so why is it not here?". // The first search on a device has nothing to show until a walk has run, so this is the one
showIndexedResults(query, source) // case worth waiting for — with the progress row above it saying why.
refresh?.join()
if (!currentCoroutineContext().isActive) return@launch
showIndexedResults(query, source)
}
_state.update { current -> _state.update { current ->
if (current.query != query) { if (current.query != query) {
@@ -889,7 +947,33 @@ class BrowserViewModel(
* and the preference is part of what a row means. Everything else needs a **catch-up**, which * and the preference is part of what a row means. Everything else needs a **catch-up**, which
* reads names and nothing else. * reads names and nothing else.
*/ */
private suspend fun bringIndexCurrent(source: StorageSource) { private fun bringIndexCurrent(source: StorageSource): Job? {
// Already running: this caller gets that pass rather than a second one.
indexJob?.takeIf { it.isActive }?.let { return it }
val job = viewModelScope.launch {
val (toWalk, toCatchUp) = staleVolumes()
if (toWalk.isNotEmpty()) pass(source, toWalk, full = true)
if (toCatchUp.isNotEmpty()) pass(source, toCatchUp, full = false)
// What is on screen is answered again, because the pass may just have found the file the
// search is for — which is the whole of "I downloaded it, so why is it not here?".
refreshFromIndex()
}
indexJob = job
return job
}
/**
* Which volumes need a walk, and which only a catch-up.
*
* The policy lives here rather than in its callers because search and the library views must agree
* about it: a volume that was never built, was built with the other hidden-files preference, or has
* not been walked end to end for a week needs a **walk** — a catch-up compares names, so it cannot
* see a name that is there both times but is not the file it was, and the preference is part of what
* a row means. Everything else needs a **catch-up**, which reads names and nothing else.
*/
private suspend fun staleVolumes(): Pair<List<StoragePath>, List<StoragePath>> {
val volumes = volumes() val volumes = volumes()
val stampAt = clock() val stampAt = clock()
val stamps = searchIndex.stamps() val stamps = searchIndex.stamps()
@@ -901,13 +985,24 @@ class BrowserViewModel(
stamp.hiddenIncluded != hidden || stamp.hiddenIncluded != hidden ||
stampAt - stamp.fullAtMillis > INDEX_FULL_PASS_AFTER_MILLIS stampAt - stamp.fullAtMillis > INDEX_FULL_PASS_AFTER_MILLIS
} }
if (toWalk.isNotEmpty()) pass(source, toWalk, full = true)
val toCatchUp = volumes.filterNot(toWalk::contains).filter { volume -> val toCatchUp = volumes.filterNot(toWalk::contains).filter { volume ->
val stamp = stamps[volume.value] val stamp = stamps[volume.value]
stamp == null || stampAt - stamp.indexedAtMillis > INDEX_CATCH_UP_AFTER_MILLIS stamp == null || stampAt - stamp.indexedAtMillis > INDEX_CATCH_UP_AFTER_MILLIS
} }
if (toCatchUp.isNotEmpty()) pass(source, toCatchUp, full = false) return toWalk to toCatchUp
}
/** Re-answer the view that is on screen from the index, once a pass has landed. */
private suspend fun refreshFromIndex() {
val source = storage.activeSource() ?: return
val current = _state.value
when {
current.query.isNotBlank() && current.searchRoot != null ->
showIndexedResults(current.query, source)
current.category != null -> showLibrary(current.category, source)
else -> Unit
}
_state.update { it.copy(indexedAt = searchIndex.indexedAt()) }
} }
/** Answer [query] from the index, confirming every candidate against the filesystem. */ /** Answer [query] from the index, confirming every candidate against the filesystem. */
@@ -971,7 +1066,10 @@ class BrowserViewModel(
*/ */
fun rebuildSearchIndex() { fun rebuildSearchIndex() {
val source = storage.activeSource() ?: return val source = storage.activeSource() ?: return
viewModelScope.launch { // The explicit action wins over any pass in flight: it is the one thing that recovers from the index
// being *wrong* rather than merely old, so it must not be folded into a catch-up that is nearly done.
indexJob?.cancel()
indexJob = viewModelScope.launch {
pass(source, volumes(), full = true) pass(source, volumes(), full = true)
// Answered again, in whichever view asked for the rebuild: a search re-runs its query, // Answered again, in whichever view asked for the rebuild: a search re-runs its query,
// a library re-reads its rows, and the home screen's counts follow either way. // a library re-reads its rows, and the home screen's counts follow either way.
@@ -1320,6 +1418,20 @@ class BrowserViewModel(
} }
} }
/**
* Open what a launcher shortcut asked for.
*
* Both libraries and the trash already exist as first-class views, so this is a mapping and nothing else —
* the shortcut adds a way in, not a mode.
*/
fun openShortcut(route: ShortcutRoute) {
when (route) {
ShortcutRoute.IMAGES -> openCategory(FileCategory.IMAGES)
ShortcutRoute.RECENT -> openCategory(FileCategory.RECENT)
ShortcutRoute.TRASH -> openTrash()
}
}
fun openUsage() { fun openUsage() {
val path = _state.value.path ?: return val path = _state.value.path ?: return
val source = storage.activeSource() ?: return val source = storage.activeSource() ?: return
@@ -1359,6 +1471,12 @@ class BrowserViewModel(
_state.update { it.copy(overlay = Overlay.Trash(emptyList(), loading = true)) } _state.update { it.copy(overlay = Overlay.Trash(emptyList(), loading = true)) }
viewModelScope.launch { viewModelScope.launch {
// The sweep runs here, not only after the next delete: a retention that only fires when the user
// deletes something else leaves day-old batches on the volume forever. Best effort — a volume
// that has gone away is not an error on this screen.
runCatching {
for (volume in volumes()) Trash(source, volume, trashIndex, clock = clock).purgeExpired()
}
val batches = runCatching { Trash.restorableFrom(source, trashIndex) } val batches = runCatching { Trash.restorableFrom(source, trashIndex) }
.getOrDefault(emptyList()) .getOrDefault(emptyList())
_state.update { current -> _state.update { current ->
@@ -1374,6 +1492,27 @@ class BrowserViewModel(
* A name taken again in the meantime is not overwritten — see [Trash.restore] — so the * A name taken again in the meantime is not overwritten — see [Trash.restore] — so the
* item comes back beside whatever holds the name now. * item comes back beside whatever holds the name now.
*/ */
/**
* Delete everything in the trash for good, on every volume, then show the empty result.
*
* There is no undo here by design — emptying is the decision to make the space come back — so the screen
* asks once before calling this, and this asks nothing.
*/
fun emptyTrash() {
val source = storage.activeSource() ?: return
viewModelScope.launch {
_state.update { it.copy(loading = true) }
val removed = runCatching {
volumes().sumOf { volume -> Trash(source, volume, trashIndex, clock = clock).emptyAll() }
}.getOrDefault(0)
_state.update { it.copy(loading = false) }
message(if (removed > 0) R.string.message_trash_emptied else R.string.trash_empty)
openTrash()
}
}
fun restoreFromTrash(batch: TrashBatch) = restoreBatch(batch) { trash -> fun restoreFromTrash(batch: TrashBatch) = restoreBatch(batch) { trash ->
trash.restore(batch) { notifier.update(it) } trash.restore(batch) { notifier.update(it) }
} }
@@ -1516,26 +1655,69 @@ class BrowserViewModel(
// ---------------------------------------------------------------- archives // ---------------------------------------------------------------- archives
/** Compress [paths] into a new ZIP beside them, under a name that is still free. */ /** Compress [paths] into a new ZIP beside them, under a name that is still free. */
/** Compress [paths] straight away, with the name the folder suggests and compression on. */
fun compress(paths: List<StoragePath>) { fun compress(paths: List<StoragePath>) {
val target = _state.value.path ?: return val target = _state.value.path ?: return
val source = storage.activeSource() ?: return
if (paths.isEmpty()) return if (paths.isEmpty()) return
compressInto(paths, target, suggestedArchiveName(paths), compressContents = true)
}
/**
* Ask for the archive's name and whether to compress it, before writing anything.
*
* Two answers because one of them is a trade the user is better placed to make: compressing saves space
* and costs time, and a file that is about to be copied to a computer is often better **stored** than
* squeezed. The dialog says which is which; this only remembers what was selected.
*/
fun beginCompress(paths: List<StoragePath>) {
if (_state.value.path == null || paths.isEmpty()) return
_state.update { it.copy(compressRequest = CompressRequest(paths, suggestedArchiveName(paths))) }
}
fun cancelCompress() {
_state.update { it.copy(compressRequest = null) }
}
/** Take the dialog's two answers and start the work. */
fun confirmCompress(name: String, compressContents: Boolean) {
val request = _state.value.compressRequest ?: return
val target = _state.value.path ?: return
_state.update { it.copy(compressRequest = null) }
val cleanName = name.trim()
// A name is one path segment, the same rule rename follows.
if (cleanName.isEmpty() || !isUsableName(cleanName)) return
compressInto(request.paths, target, cleanName, compressContents)
}
/** `notes.txt` → `notes.txt.zip`; several files → `archive.zip`, made unique against the folder. */
private fun suggestedArchiveName(paths: List<StoragePath>): String {
val base = if (paths.size == 1) "${paths.first().name}.zip" else "archive.zip" val base = if (paths.size == 1) "${paths.first().name}.zip" else "archive.zip"
val taken = _state.value.entries.mapTo(HashSet()) { it.name } val taken = _state.value.entries.mapTo(HashSet()) { it.name }
val name = NameAllocator.uniqueName(base) { it in taken } return NameAllocator.uniqueName(base) { it in taken }
}
private fun compressInto(
paths: List<StoragePath>,
target: StoragePath,
name: String,
compressContents: Boolean,
) {
val source = storage.activeSource() ?: return
viewModelScope.launch { viewModelScope.launch {
_state.update { it.copy(loading = true, selection = emptySet()) } _state.update { it.copy(loading = true, selection = emptySet()) }
notifier.start(OperationKind.COMPRESS) notifier.start(OperationKind.COMPRESS)
val result = try { val result = try {
ArchiveEngine(source).createZip(paths, target.child(name)) { notifier.update(it) } ArchiveEngine(source)
.createZip(paths, target.child(name), compressContents) { notifier.update(it) }
} finally { } finally {
notifier.stop() notifier.stop()
} }
_state.update { it.copy(loading = false) } _state.update { it.copy(loading = false) }
if (result.succeeded) { if (result.succeeded) {
markChanged(target, listOf(target.child(name)))
messagePlural(R.plurals.message_compressed, result.completed) messagePlural(R.plurals.message_compressed, result.completed)
} else { } else {
report(result) report(result)
@@ -1570,6 +1752,7 @@ class BrowserViewModel(
_state.update { it.copy(loading = false) } _state.update { it.copy(loading = false) }
if (result.succeeded) { if (result.succeeded) {
markChanged(target, listOf(target.child(folderName)))
messagePlural(R.plurals.message_extracted, result.completed) messagePlural(R.plurals.message_extracted, result.completed)
} else { } else {
report(result) report(result)
@@ -1791,6 +1974,8 @@ class BrowserViewModel(
target: StoragePath, target: StoragePath,
cut: Boolean, cut: Boolean,
policy: ConflictPolicy, policy: ConflictPolicy,
/** Set when the destination was chosen by hand, so the message can name it and offer to show it. */
announce: PickerFolder? = null,
) { ) {
val source = storage.activeSource() ?: return val source = storage.activeSource() ?: return
val operations = FileOperations(source) val operations = FileOperations(source)
@@ -1799,9 +1984,9 @@ class BrowserViewModel(
_state.update { it.copy(loading = true) } _state.update { it.copy(loading = true) }
notifier.start(kind) notifier.start(kind)
// A move is destructive, so how to reverse it is worked out by diffing the target's // Names either side of the operation. What the target gained is what the dot marks; for a move the
// listing either side of the operation — see [matchLanded]. // same difference is the undo handle — see [matchLanded].
val landedBefore = if (cut) targetNames(source, target) else emptySet() val landedBefore = targetNames(source, target)
val result: OperationResult = try { val result: OperationResult = try {
if (cut) { if (cut) {
@@ -1817,11 +2002,15 @@ class BrowserViewModel(
_state.update { it.copy(loading = false, clipboard = if (cut) null else it.clipboard) } _state.update { it.copy(loading = false, clipboard = if (cut) null else it.clipboard) }
if (result.succeeded) { if (result.succeeded) {
val landedNow = targetNames(source, target)
markChanged(target, (landedNow - landedBefore).map { target.child(it) })
if (cut) { if (cut) {
matchLanded(target, landedBefore, targetNames(source, target), paths)?.let { moves -> matchLanded(target, landedBefore, landedNow, paths)?.let { moves ->
_state.update { it.copy(undo = Undo.Relocate(moves)) } _state.update { it.copy(undo = Undo.Relocate(moves)) }
} }
messageUndoablePlural(R.plurals.message_moved, result.completed) messageUndoablePlural(R.plurals.message_moved, result.completed)
} else if (announce != null) {
messageCopiedTo(announce, result.completed)
} else { } else {
messagePlural(R.plurals.message_copied, result.completed) messagePlural(R.plurals.message_copied, result.completed)
} }
@@ -1990,6 +2179,7 @@ class BrowserViewModel(
viewModelScope.launch { viewModelScope.launch {
val created = runCatching { source.createDirectory(target.child(cleanName)) }.getOrDefault(false) val created = runCatching { source.createDirectory(target.child(cleanName)) }.getOrDefault(false)
if (created) markChanged(target, listOf(target.child(cleanName)))
message(if (created) R.string.message_folder_created else R.string.message_name_in_use) message(if (created) R.string.message_folder_created else R.string.message_name_in_use)
load(target) load(target)
} }
@@ -2007,6 +2197,7 @@ class BrowserViewModel(
val renamed = runCatching { FileOperations(source).rename(path, parent.child(cleanName)) } val renamed = runCatching { FileOperations(source).rename(path, parent.child(cleanName)) }
.getOrDefault(false) .getOrDefault(false)
if (renamed) { if (renamed) {
markChanged(parent, listOf(parent.child(cleanName)))
// A rename is a move within a single folder, so it needs no separate shape. // A rename is a move within a single folder, so it needs no separate shape.
_state.update { _state.update {
it.copy( it.copy(
@@ -2080,6 +2271,7 @@ class BrowserViewModel(
} }
if (done.isNotEmpty()) { if (done.isNotEmpty()) {
markChanged(parent, done.map { it.from })
_state.update { it.copy(undo = Undo.Relocate(done)) } _state.update { it.copy(undo = Undo.Relocate(done)) }
} }
when { when {
@@ -2131,7 +2323,7 @@ class BrowserViewModel(
*/ */
private suspend fun deleteDirectly(paths: List<StoragePath>) { private suspend fun deleteDirectly(paths: List<StoragePath>) {
val source = storage.activeSource() ?: return val source = storage.activeSource() ?: return
val trash = Trash(source, volumeRootFor(paths), trashIndex) val trash = Trash(source, volumeRootFor(paths), trashIndex, clock = clock)
_state.update { it.copy(loading = true, selection = emptySet()) } _state.update { it.copy(loading = true, selection = emptySet()) }
notifier.start(OperationKind.DELETE) notifier.start(OperationKind.DELETE)
@@ -2208,6 +2400,20 @@ class BrowserViewModel(
// ----------------------------------------------------------------- messages // ----------------------------------------------------------------- messages
/**
* Run what the current message's action button offered.
*
* Undo is the usual one. A **Copy to…** offers Show instead, because a copy leaves its sources where
* they were — the interesting place is the one it wrote to, which may be several folders away.
*/
fun performMessageAction() {
when (val action = _state.value.message?.action) {
MessageAction.Undo -> undo()
is MessageAction.Show -> openDirectory(action.path)
null -> Unit
}
}
fun consumeMessage() { fun consumeMessage() {
_state.update { it.copy(message = null) } _state.update { it.copy(message = null) }
} }
@@ -2230,7 +2436,7 @@ class BrowserViewModel(
/** A message whose snackbar also offers to take the change back. */ /** A message whose snackbar also offers to take the change back. */
private fun messageUndoable(@StringRes textRes: Int, vararg args: Any) { private fun messageUndoable(@StringRes textRes: Int, vararg args: Any) {
postMessage( postMessage(
UiMessage(textRes, args.toList(), actionLabelRes = R.string.browser_action_undo), UiMessage(textRes, args.toList(), action = MessageAction.Undo),
) )
} }
@@ -2240,7 +2446,26 @@ class BrowserViewModel(
textRes, textRes,
listOf(count), listOf(count),
pluralQuantity = count, pluralQuantity = count,
actionLabelRes = R.string.browser_action_undo, action = MessageAction.Undo,
),
)
}
/** Remember that [paths] appeared in [folder], for the next read of that folder to mark. */
private fun markChanged(folder: StoragePath, paths: Collection<StoragePath>) {
if (paths.isEmpty()) return
changedFolders.getOrPut(folder) { HashSet() }.addAll(paths)
}
/** A copy into a folder the user picked: names it, and offers to go there. */
private fun messageCopiedTo(destination: PickerFolder, count: Int) {
postMessage(
UiMessage(
R.plurals.message_copied_to,
listOf(count),
pluralQuantity = count,
action = MessageAction.Show(destination.path),
destination = destination,
), ),
) )
} }
@@ -11,6 +11,7 @@ import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Folder import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.InsertDriveFile import androidx.compose.material.icons.filled.InsertDriveFile
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
@@ -27,6 +28,7 @@ import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
@@ -56,8 +58,12 @@ import de.softwareapp_hb.filemanager.ui.browser.itemCountLabel
fun TrashScreen( fun TrashScreen(
batches: List<TrashBatch>, batches: List<TrashBatch>,
loading: Boolean, loading: Boolean,
/** How long an item stays recoverable; the screen says it rather than leaving it to be discovered. */
retentionHours: Long,
onRestore: (TrashBatch) -> Unit, onRestore: (TrashBatch) -> Unit,
onRestoreEntry: (TrashBatch, TrashedEntry) -> Unit, onRestoreEntry: (TrashBatch, TrashedEntry) -> Unit,
/** Delete every batch for good, after the caller has asked. */
onEmpty: () -> Unit,
onClose: () -> Unit, onClose: () -> Unit,
) { ) {
Scaffold( Scaffold(
@@ -73,14 +79,36 @@ fun TrashScreen(
) )
} }
}, },
actions = {
// Offered only when there is something to empty: a disabled bin on an empty screen is
// a question with no answer.
if (batches.isNotEmpty()) {
IconButton(onClick = onEmpty) {
Icon(
imageVector = Icons.Filled.Delete,
contentDescription = stringResource(R.string.trash_empty_action),
)
}
}
},
) )
}, },
) { innerPadding -> ) { innerPadding ->
Box( Column(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.padding(innerPadding), .padding(innerPadding),
) { ) {
Text(
text = pluralStringResource(
R.plurals.trash_keep_for,
retentionHours.toInt(),
retentionHours.toInt(),
),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
)
if (batches.isEmpty() && !loading) { if (batches.isEmpty() && !loading) {
EmptyState( EmptyState(
message = stringResource(R.string.trash_empty), message = stringResource(R.string.trash_empty),
@@ -104,7 +132,7 @@ fun TrashScreen(
if (loading) { if (loading) {
LinearProgressIndicator( LinearProgressIndicator(
modifier = Modifier.fillMaxWidth().align(Alignment.TopCenter), modifier = Modifier.fillMaxWidth().align(Alignment.CenterHorizontally),
) )
} }
} }
+33
View File
@@ -108,6 +108,13 @@
<string name="browser_action_copy">Copy</string> <string name="browser_action_copy">Copy</string>
<string name="browser_action_cut">Move</string> <string name="browser_action_cut">Move</string>
<string name="browser_action_paste">Paste here</string> <string name="browser_action_paste">Paste here</string>
<!-- Compressing: the name, and whether to squeeze the contents. -->
<string name="compress_dialog_title">Compress</string>
<string name="compress_dialog_name">Archive name</string>
<string name="compress_dialog_contents">Compress contents</string>
<string name="compress_dialog_hint">Off stores the files as they are: faster to build, and ready to copy off the phone.</string>
<string name="compress_dialog_confirm">Compress</string>
<string name="compress_dialog_cancel">Cancel</string>
<!-- The two verbs that pick the destination instead of pasting into the folder on screen. --> <!-- The two verbs that pick the destination instead of pasting into the folder on screen. -->
<string name="browser_action_copy_to">Copy to…</string> <string name="browser_action_copy_to">Copy to…</string>
<string name="browser_action_move_to">Move to…</string> <string name="browser_action_move_to">Move to…</string>
@@ -125,6 +132,17 @@
<string name="browser_action_select_all">Select all</string> <string name="browser_action_select_all">Select all</string>
<string name="browser_action_clear_selection">Clear selection</string> <string name="browser_action_clear_selection">Clear selection</string>
<string name="browser_action_undo">Undo</string> <string name="browser_action_undo">Undo</string>
<!-- Launcher shortcuts: the short label is under the icon, the long one is the tooltip. -->
<string name="shortcut_images">Images</string>
<string name="shortcut_images_long">Open the Images library</string>
<string name="shortcut_recent">Recent</string>
<string name="shortcut_recent_long">Open the files you changed last</string>
<string name="shortcut_trash">Trash</string>
<string name="shortcut_trash_long">Open the trash</string>
<!-- Said by TalkBack for the dot on a row an operation has just produced. -->
<string name="browser_row_changed">New</string>
<!-- The action on a "copied to X" message: go to the folder it was copied into. -->
<string name="browser_action_show">Show</string>
<!-- ===== Browser: files another app has handed over ===== --> <!-- ===== Browser: files another app has handed over ===== -->
<plurals name="incoming_save_here"> <plurals name="incoming_save_here">
@@ -137,6 +155,15 @@
<!-- ===== Trash ===== --> <!-- ===== Trash ===== -->
<string name="trash_title">Trash</string> <string name="trash_title">Trash</string>
<plurals name="trash_keep_for">
<item quantity="one">Deleted files are kept for %1$d hour</item>
<item quantity="other">Deleted files are kept for %1$d hours</item>
</plurals>
<string name="trash_empty_action">Empty trash</string>
<string name="trash_empty_confirm_title">Empty the trash?</string>
<string name="trash_empty_confirm_body">Everything in the trash is deleted for good. This cannot be undone.</string>
<string name="trash_empty_confirm_action">Delete for good</string>
<string name="message_trash_emptied">Trash emptied</string>
<string name="trash_empty">Nothing in the trash</string> <string name="trash_empty">Nothing in the trash</string>
<string name="trash_restore">Restore</string> <string name="trash_restore">Restore</string>
<string name="trash_restore_all">Restore all</string> <string name="trash_restore_all">Restore all</string>
@@ -238,6 +265,12 @@
<string name="message_folder_created">Folder created</string> <string name="message_folder_created">Folder created</string>
<string name="message_renamed">Renamed</string> <string name="message_renamed">Renamed</string>
<string name="message_name_in_use">That name is already in use</string> <string name="message_name_in_use">That name is already in use</string>
<!-- %1$s is the destination folder; a copy that went somewhere the user chose says where. -->
<plurals name="message_copied_to">
<item quantity="one">Copied to %1$s</item>
<item quantity="other">Copied %2$d items to %1$s</item>
</plurals>
<plurals name="message_copied"> <plurals name="message_copied">
<item quantity="one">Copied %1$d item</item> <item quantity="one">Copied %1$d item</item>
<item quantity="other">Copied %1$d items</item> <item quantity="other">Copied %1$d items</item>
+55
View File
@@ -0,0 +1,55 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Long-press the app icon: three views that are otherwise two or three taps deep.
Each shortcut is a plain intent into MainActivity carrying a route in an extra; MainActivity turns it into
ShortcutRoute and the browser opens that view once, when it appears. No permission, no database, and no
dynamic shortcuts to keep in sync with the favourites list.
-->
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:enabled="true"
android:shortcutId="images"
android:shortcutLongLabel="@string/shortcut_images_long"
android:shortcutShortLabel="@string/shortcut_images">
<intent
android:action="android.intent.action.VIEW"
android:targetClass="de.softwareapp_hb.filemanager.MainActivity"
android:targetPackage="de.softwareapp_hb.filemanager">
<extra
android:name="de.softwareapp_hb.filemanager.SHORTCUT"
android:value="images" />
</intent>
</shortcut>
<shortcut
android:enabled="true"
android:shortcutId="recent"
android:shortcutLongLabel="@string/shortcut_recent_long"
android:shortcutShortLabel="@string/shortcut_recent">
<intent
android:action="android.intent.action.VIEW"
android:targetClass="de.softwareapp_hb.filemanager.MainActivity"
android:targetPackage="de.softwareapp_hb.filemanager">
<extra
android:name="de.softwareapp_hb.filemanager.SHORTCUT"
android:value="recent" />
</intent>
</shortcut>
<shortcut
android:enabled="true"
android:shortcutId="trash"
android:shortcutLongLabel="@string/shortcut_trash_long"
android:shortcutShortLabel="@string/shortcut_trash">
<intent
android:action="android.intent.action.VIEW"
android:targetClass="de.softwareapp_hb.filemanager.MainActivity"
android:targetPackage="de.softwareapp_hb.filemanager">
<extra
android:name="de.softwareapp_hb.filemanager.SHORTCUT"
android:value="trash" />
</intent>
</shortcut>
</shortcuts>
@@ -0,0 +1,30 @@
package de.softwareapp_hb.filemanager.core
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
/**
* The mapping between a launcher shortcut and a view.
*
* The interesting case is the one that is *not* a shortcut: a value written by an older build, or a typo in
* `shortcuts.xml`, must be ignored rather than thrown, because the app is being opened by the launcher at that
* moment and has nowhere to show an error.
*/
class ShortcutRouteTest {
@Test
fun `each shortcut key maps to its route`() {
assertEquals(ShortcutRoute.IMAGES, ShortcutRoute.from("images"))
assertEquals(ShortcutRoute.RECENT, ShortcutRoute.from("recent"))
assertEquals(ShortcutRoute.TRASH, ShortcutRoute.from("trash"))
}
@Test
fun `anything else is ignored rather than thrown`() {
assertNull(ShortcutRoute.from(null))
assertNull(ShortcutRoute.from(""))
assertNull(ShortcutRoute.from("favourites"))
assertNull(ShortcutRoute.from("IMAGES"))
}
}
@@ -52,6 +52,29 @@ class ArchiveEngineTest {
assertEquals(2, extracted.completed) assertEquals(2, extracted.completed)
} }
@Test
fun `an uncompressed zip round-trips and is larger than a squeezed one`() = runBlocking {
val storage = storage()
// Very compressible on purpose: what the two archives differ by is then the compression itself,
// not the few bytes of header each entry carries.
storage.addFile(src.child("big.txt"), "a".repeat(4000))
val engine = ArchiveEngine(storage)
val stored = StoragePath.of("/src/stored.zip")
val squeezed = StoragePath.of("/src/squeezed.zip")
assertTrue(engine.createZip(listOf(src.child("big.txt")), stored, compress = false).succeeded)
assertTrue(engine.createZip(listOf(src.child("big.txt")), squeezed, compress = true).succeeded)
val storedBytes = storage.stat(stored)!!.sizeBytes
val squeezedBytes = storage.stat(squeezed)!!.sizeBytes
assertTrue("stored=$storedBytes", storedBytes > 4000)
assertTrue("squeezed=$squeezedBytes", squeezedBytes < 500)
// Storing is a choice about cost, not about format: it is still a zip, and still the same bytes.
assertTrue(engine.extract(stored, out).succeeded)
assertEquals("a".repeat(4000), storage.contentOf(out.child("big.txt")))
}
@Test @Test
fun `createZip reports progress over the files it will write`() = runBlocking { fun `createZip reports progress over the files it will write`() = runBlocking {
val storage = storage() val storage = storage()
@@ -36,6 +36,22 @@ class TrashTest {
index: TrashIndex = TrashIndex.None, index: TrashIndex = TrashIndex.None,
) = Trash(source, volume, index, clock = { at }) ) = Trash(source, volume, index, clock = { at })
@Test
fun `emptying removes every batch and leaves what is not one`() = runBlocking {
val storage = storage()
trash(storage, at = TRASHED_AT).stage(listOf(notes))
trash(storage, at = TRASHED_AT + 1).stage(listOf(docs.child("report.pdf")))
// Something else in the same hidden folder: the volume is the user's, not the trash's to tidy.
val foreign = trash(storage).root().child("holiday-photos")
storage.createDirectory(foreign)
val removed = trash(storage).emptyAll()
assertEquals(2, removed)
assertTrue(storage.contains(foreign))
assertTrue(trash(storage).restorable().isEmpty())
}
@Test @Test
fun `staging moves an item aside and records where it came from`() = runBlocking { fun `staging moves an item aside and records where it came from`() = runBlocking {
val storage = storage() val storage = storage()
@@ -0,0 +1,68 @@
package de.softwareapp_hb.filemanager.ui.browser
import androidx.compose.ui.test.assertCountEquals
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onAllNodesWithContentDescription
import androidx.compose.ui.test.onNodeWithContentDescription
import de.softwareapp_hb.filemanager.core.FileEntry
import de.softwareapp_hb.filemanager.core.StoragePath
import de.softwareapp_hb.filemanager.ui.theme.FileManagerTheme
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
/**
* The dot that marks a row an operation produced.
*
* Present when the view model says so, absent otherwise, and **readable**: a dot is the only thing on the
* row that says "new", so it carries a content description rather than being a shape TalkBack skips.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class BrowserComponentsTest {
@get:Rule
val compose = createComposeRule()
private val downloads = StoragePath.of("/storage/emulated/0/Download")
private fun entry(name: String) =
FileEntry(downloads.child(name), isDirectory = false, sizeBytes = 4L, lastModifiedMillis = 0L)
@Test
fun `a row an operation produced carries the mark`() {
compose.setContent {
FileManagerTheme {
EntryRow(entry = entry("a.txt"), selected = false, changed = true, onClick = {})
}
}
compose.onNodeWithContentDescription("New").assertExists()
}
@Test
fun `an ordinary row carries no mark`() {
compose.setContent {
FileManagerTheme {
EntryRow(entry = entry("a.txt"), selected = false, onClick = {})
}
}
compose.onAllNodesWithContentDescription("New").assertCountEquals(0)
}
@Test
fun `a grid cell an operation produced carries the mark too`() {
compose.setContent {
FileManagerTheme {
EntryGridCell(entry = entry("a.txt"), selected = false, changed = true, onClick = {})
}
}
compose.onNodeWithContentDescription("New").assertExists()
}
}
@@ -9,6 +9,7 @@ import de.softwareapp_hb.filemanager.R
import de.softwareapp_hb.filemanager.core.BatchRename import de.softwareapp_hb.filemanager.core.BatchRename
import de.softwareapp_hb.filemanager.core.ConflictPolicy import de.softwareapp_hb.filemanager.core.ConflictPolicy
import de.softwareapp_hb.filemanager.core.FileCategory import de.softwareapp_hb.filemanager.core.FileCategory
import de.softwareapp_hb.filemanager.core.ShortcutRoute
import de.softwareapp_hb.filemanager.core.FileEntry import de.softwareapp_hb.filemanager.core.FileEntry
import de.softwareapp_hb.filemanager.core.FileKind import de.softwareapp_hb.filemanager.core.FileKind
import de.softwareapp_hb.filemanager.core.SortDirection import de.softwareapp_hb.filemanager.core.SortDirection
@@ -21,6 +22,8 @@ import de.softwareapp_hb.filemanager.data.DeleteRequestFactory
import de.softwareapp_hb.filemanager.data.IncomingSource import de.softwareapp_hb.filemanager.data.IncomingSource
import de.softwareapp_hb.filemanager.data.IndexedFile import de.softwareapp_hb.filemanager.data.IndexedFile
import de.softwareapp_hb.filemanager.data.SearchIndex import de.softwareapp_hb.filemanager.data.SearchIndex
import de.softwareapp_hb.filemanager.data.StorageSource
import de.softwareapp_hb.filemanager.data.StorageLocation
import de.softwareapp_hb.filemanager.data.StorageAccessMode import de.softwareapp_hb.filemanager.data.StorageAccessMode
import de.softwareapp_hb.filemanager.data.VolumeInfo import de.softwareapp_hb.filemanager.data.VolumeInfo
import de.softwareapp_hb.filemanager.data.testutil.InMemoryBookmarkStore import de.softwareapp_hb.filemanager.data.testutil.InMemoryBookmarkStore
@@ -30,9 +33,12 @@ import de.softwareapp_hb.filemanager.domain.OperationKind
import de.softwareapp_hb.filemanager.domain.OperationNotifier import de.softwareapp_hb.filemanager.domain.OperationNotifier
import de.softwareapp_hb.filemanager.domain.OperationProgress import de.softwareapp_hb.filemanager.domain.OperationProgress
import de.softwareapp_hb.filemanager.domain.SearchIndexer import de.softwareapp_hb.filemanager.domain.SearchIndexer
import de.softwareapp_hb.filemanager.domain.Trash
import de.softwareapp_hb.filemanager.data.TrashIndex
import de.softwareapp_hb.filemanager.domain.testutil.InMemorySearchIndex import de.softwareapp_hb.filemanager.domain.testutil.InMemorySearchIndex
import de.softwareapp_hb.filemanager.domain.testutil.InMemoryStorageSource import de.softwareapp_hb.filemanager.domain.testutil.InMemoryStorageSource
import de.softwareapp_hb.filemanager.ui.browser.testutil.FakeStorageLocation import de.softwareapp_hb.filemanager.ui.browser.testutil.FakeStorageLocation
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -127,8 +133,12 @@ class BrowserViewModelTest {
Dispatchers.resetMain() Dispatchers.resetMain()
} }
// The builder of the thing under test: every collaborator the view model can take, defaulted, so a test
// names only the one it is about. Ten parameters is the rule for production code, not for this.
@Suppress("LongParameterList")
private fun viewModel( private fun viewModel(
deleteRequests: DeleteRequestFactory = DeleteRequestFactory { _, _ -> null }, deleteRequests: DeleteRequestFactory = DeleteRequestFactory { _, _ -> null },
storageLocation: StorageLocation = location,
savedState: SavedStateHandle = SavedStateHandle(), savedState: SavedStateHandle = SavedStateHandle(),
incoming: IncomingSource? = fakeIncoming, incoming: IncomingSource? = fakeIncoming,
apkInspector: ApkInspector = ApkInspector.None, apkInspector: ApkInspector = ApkInspector.None,
@@ -140,7 +150,7 @@ class BrowserViewModelTest {
// assertions in this file are written to read the state immediately after an action. // assertions in this file are written to read the state immediately after an action.
io: CoroutineDispatcher = UnconfinedTestDispatcher(), io: CoroutineDispatcher = UnconfinedTestDispatcher(),
) = BrowserViewModel( ) = BrowserViewModel(
storage = location, storage = storageLocation,
notifier = recordingNotifier, notifier = recordingNotifier,
deleteRequests = deleteRequests, deleteRequests = deleteRequests,
savedState = savedState, savedState = savedState,
@@ -284,6 +294,43 @@ class BrowserViewModelTest {
assertEquals(setOf(documents, downloads), folders.toSet()) assertEquals(setOf(documents, downloads), folders.toSet())
} }
@Test
fun `the picker names a volume the way the browser does`() {
val model = viewModel()
model.openDirectory(downloads)
model.toggleSelection(downloads.child("a.txt"))
model.startTransferTo(cut = false)
val volumes = model.state.value.transferPicker!!.folders
assertEquals(listOf(root), volumes.map { it.path })
// Internal storage has no platform label; showing its own name, `0`, would be a riddle.
assertEquals(R.string.browser_internal_storage, volumes.single().labelRes)
model.pickerOpen(downloads)
val crumb = model.state.value.transferPicker!!.crumbs.first()
assertEquals(R.string.browser_internal_storage, crumb.labelRes)
}
@Test
fun `the picker leaves hidden folders out until they are asked for`() {
storage.addDirectory(root.child(".hidden-backup"))
val model = viewModel()
model.openDirectory(downloads)
model.toggleSelection(downloads.child("a.txt"))
model.startTransferTo(cut = false)
model.pickerOpen(root)
// A copy dialog is a listing: the trash folder and a `.thumbnails` folder are not destinations.
val offered = model.state.value.transferPicker!!.folders.map { it.path.name }
assertFalse(".hidden-backup" in offered)
// Showing hidden files is a statement about what the user wants to see, so the picker follows it.
model.toggleShowHidden()
model.pickerOpen(root)
assertTrue(".hidden-backup" in model.state.value.transferPicker!!.folders.map { it.path.name })
}
@Test @Test
fun `the picker walks up to the volumes and back down`() { fun `the picker walks up to the volumes and back down`() {
val model = viewModel() val model = viewModel()
@@ -292,16 +339,16 @@ class BrowserViewModelTest {
model.startTransferTo(cut = false) model.startTransferTo(cut = false)
// The picker opens on the volumes, with no trail behind it. // The picker opens on the volumes, with no trail behind it.
assertEquals(emptyList<StoragePath>(), model.state.value.transferPicker!!.crumbs) assertTrue(model.state.value.transferPicker!!.crumbs.isEmpty())
model.pickerOpen(downloads) model.pickerOpen(downloads)
assertEquals(listOf(root, downloads), model.state.value.transferPicker!!.crumbs) assertEquals(listOf(root, downloads), model.state.value.transferPicker!!.crumbs.map { it.path })
model.pickerUp() model.pickerUp()
assertEquals(listOf(root), model.state.value.transferPicker!!.crumbs) assertEquals(listOf(root), model.state.value.transferPicker!!.crumbs.map { it.path })
model.pickerUp() model.pickerUp()
assertEquals(emptyList<StoragePath>(), model.state.value.transferPicker!!.crumbs) assertTrue(model.state.value.transferPicker!!.crumbs.isEmpty())
} }
@Test @Test
@@ -336,6 +383,321 @@ class BrowserViewModelTest {
assertTrue(recordedNotifications.isEmpty()) assertTrue(recordedNotifications.isEmpty())
} }
@Test
fun `a copy says where it went and offers to show it`() {
val model = viewModel()
model.openDirectory(downloads)
model.toggleSelection(downloads.child("a.txt"))
model.startTransferTo(cut = false)
model.pickerOpen(documents)
model.confirmTransferTo()
val message = model.state.value.message
assertNotNull(message)
assertEquals(R.plurals.message_copied_to, message!!.textRes)
// The count is the only argument the view model owns; the folder's label is the screen's job.
assertEquals(listOf(1), message.args)
assertEquals(documents, message.destination?.path)
assertEquals(MessageAction.Show(documents), message.action)
assertEquals(R.string.browser_action_show, message.actionLabelRes)
}
@Test
fun `show takes the user to the folder the copy went to`() {
val model = viewModel()
model.openDirectory(downloads)
model.toggleSelection(downloads.child("a.txt"))
model.startTransferTo(cut = false)
model.pickerOpen(documents)
model.confirmTransferTo()
model.performMessageAction()
assertEquals(documents, model.state.value.path)
assertTrue(storage.contains(documents.child("a.txt")))
}
@Test
fun `a paste into the folder on screen names no destination and offers no action`() {
val model = viewModel()
model.openDirectory(root)
model.copyToClipboard(listOf(downloads.child("a.txt")), cut = false)
model.openDirectory(documents)
model.paste()
val message = model.state.value.message
assertNotNull(message)
assertEquals(R.plurals.message_copied, message!!.textRes)
assertNull(message.destination)
assertNull(message.action)
assertNull(message.actionLabelRes)
}
@Test
fun `the message's undo action is the undo`() {
val model = viewModel()
model.openDirectory(downloads)
model.toggleSelection(downloads.child("a.txt"))
model.startTransferTo(cut = true)
model.pickerOpen(documents)
model.confirmTransferTo()
assertFalse(storage.contains(downloads.child("a.txt")))
// What the snackbar's button does — the UI no longer calls `undo()` itself, so this is the path
// that has to work for Undo to work at all.
model.performMessageAction()
assertTrue(storage.contains(downloads.child("a.txt")))
}
@Test
fun `a move to a chosen folder offers undo rather than show`() {
val model = viewModel()
model.openDirectory(downloads)
model.toggleSelection(downloads.child("a.txt"))
model.startTransferTo(cut = true)
model.pickerOpen(documents)
model.confirmTransferTo()
val message = model.state.value.message
assertNotNull(message)
assertEquals(MessageAction.Undo, message!!.action)
assertEquals(R.string.browser_action_undo, message.actionLabelRes)
}
@Test
fun `a copy into the folder on screen marks the copy`() {
val model = viewModel()
model.openDirectory(documents)
model.copyToClipboard(listOf(downloads.child("a.txt")), cut = false)
model.paste()
assertEquals(setOf(documents.child("a.txt")), model.state.value.changed)
}
@Test
fun `a copy into another folder marks it there, not here`() {
val model = viewModel()
model.openDirectory(downloads)
model.toggleSelection(downloads.child("a.txt"))
model.startTransferTo(cut = false)
model.pickerOpen(documents)
model.confirmTransferTo()
// The user is still in `downloads`, which gained nothing — the copy went elsewhere.
assertTrue(model.state.value.changed.isEmpty())
model.openDirectory(documents)
assertEquals(setOf(documents.child("a.txt")), model.state.value.changed)
}
@Test
fun `reading the folder again spends its marks`() {
val model = viewModel()
model.openDirectory(documents)
model.copyToClipboard(listOf(downloads.child("a.txt")), cut = false)
model.paste()
assertTrue(model.state.value.changed.isNotEmpty())
model.openDirectory(root)
model.openDirectory(documents)
assertTrue(model.state.value.changed.isEmpty())
}
@Test
fun `a rename marks the name it produced`() {
val model = viewModel()
model.openDirectory(downloads)
model.rename(downloads.child("a.txt"), "renamed.txt")
assertEquals(setOf(downloads.child("renamed.txt")), model.state.value.changed)
}
@Test
fun `compressing asks for a name and a choice before writing`() {
val model = viewModel()
model.openDirectory(downloads)
model.beginCompress(listOf(downloads.child("a.txt")))
val request = model.state.value.compressRequest
assertNotNull(request)
assertEquals("a.txt.zip", request!!.name)
// Nothing has been written: both answers belong to the dialog.
assertFalse(storage.contains(downloads.child("a.txt.zip")))
}
@Test
fun `a confirmed compress writes the name that was typed, and marks it`() {
val model = viewModel()
model.openDirectory(downloads)
model.beginCompress(listOf(downloads.child("a.txt")))
model.confirmCompress("fast.zip", compressContents = false)
assertTrue(storage.contains(downloads.child("fast.zip")))
assertNull(model.state.value.compressRequest)
assertEquals(setOf(downloads.child("fast.zip")), model.state.value.changed)
}
@Test
fun `cancelling the compress dialog writes nothing`() {
val model = viewModel()
model.openDirectory(downloads)
model.beginCompress(listOf(downloads.child("a.txt")))
model.cancelCompress()
assertNull(model.state.value.compressRequest)
assertFalse(storage.contains(downloads.child("a.txt.zip")))
}
@Test
fun `opening the trash sweeps what has expired`() {
val stagedAt = 1_000L
val trash = Trash(storage, root, TrashIndex.None, clock = { stagedAt })
runBlocking { trash.stage(listOf(downloads.child("a.txt"))) }
assertFalse(storage.contains(downloads.child("a.txt")))
// A day and a moment later: the batch is past the window, and opening the trash is what notices.
val model = viewModel(clock = { stagedAt + Trash.RETENTION_MILLIS + 1 })
model.openTrash()
assertEquals(0, runBlocking { storage.list(trash.root()) }.size)
}
@Test
fun `opening the trash keeps what is still inside the window`() {
val stagedAt = 9_000_000L
val trash = Trash(storage, root, TrashIndex.None, clock = { stagedAt })
runBlocking { trash.stage(listOf(downloads.child("a.txt"))) }
val model = viewModel(clock = { stagedAt })
model.openTrash()
assertEquals(1, runBlocking { storage.list(trash.root()) }.size)
}
@Test
fun `emptying the trash removes what is in it`() {
val stagedAt = 9_000_000L
val trash = Trash(storage, root, TrashIndex.None, clock = { stagedAt })
runBlocking { trash.stage(listOf(downloads.child("a.txt"))) }
val model = viewModel(clock = { stagedAt })
model.emptyTrash()
assertEquals(0, runBlocking { storage.list(trash.root()) }.size)
assertEquals(R.string.message_trash_emptied, model.state.value.message?.textRes)
}
@Test
fun `a shortcut opens the view it names`() {
val model = viewModel()
model.openShortcut(ShortcutRoute.IMAGES)
assertEquals(FileCategory.IMAGES, model.state.value.category)
model.openShortcut(ShortcutRoute.RECENT)
assertEquals(FileCategory.RECENT, model.state.value.category)
model.openShortcut(ShortcutRoute.TRASH)
assertTrue(model.state.value.overlay is Overlay.Trash)
}
@Test
fun `typing while the index is being built does not start it again`() {
storage.addFile(downloads.child("photo.jpg"), "x")
val index = InMemorySearchIndex()
val gate = CompletableDeferred<Unit>()
val model = viewModel(
storageLocation = GatedLocation(location, GatedSource(storage, gate)),
searchIndex = index,
)
model.setQuery("pho")
// The first search is inside the walk now, waiting at the gate.
assertTrue(model.state.value.indexing)
model.setQuery("phot")
model.setQuery("photo")
// Three keystrokes, one pass. The walk belongs to the view model; a keystroke cancels the *search*
// job, and used to cancel the walk with it — which is why the counter restarted with every letter.
assertEquals(1, index.beginVolumeCalls)
gate.complete(Unit)
assertEquals(1, index.beginVolumeCalls)
assertTrue(model.state.value.entries.any { it.name == "photo.jpg" })
}
@Test
fun `switching library while the index is being built does not start it again`() {
val index = InMemorySearchIndex()
val gate = CompletableDeferred<Unit>()
val model = viewModel(
storageLocation = GatedLocation(location, GatedSource(storage, gate)),
searchIndex = index,
)
model.openCategory(FileCategory.IMAGES)
assertTrue(model.state.value.indexing)
model.openCategory(FileCategory.VIDEOS)
model.openCategory(FileCategory.DOCUMENTS)
assertEquals(1, index.beginVolumeCalls)
gate.complete(Unit)
assertEquals(1, index.beginVolumeCalls)
}
@Test
fun `a search is answered again when the pass finds what it was looking for`() {
var now = 1_000_000L
val index = InMemorySearchIndex()
val model = viewModel(searchIndex = index, clock = { now })
// A first pass, so the index has a stamp; then a new file, and enough time for the stamp to age
// past the catch-up window.
model.openCategory(FileCategory.IMAGES)
storage.addFile(downloads.child("photo.jpg"), "x")
now += 3L * 60L * 1000L
model.setQuery("photo")
// The first answer came from what the index knew; the catch-up behind it found the new file and
// answered again — which is what makes "I just downloaded it" work without a walk per keystroke.
assertTrue(model.state.value.entries.any { it.name == "photo.jpg" })
assertEquals(1, index.beginVolumeCalls)
}
/** A location whose listing waits on [gate], so a test can stand inside a walk. */
private class GatedLocation(
private val delegate: StorageLocation,
private val gated: StorageSource,
) : StorageLocation by delegate {
override fun activeSource(): StorageSource = gated
}
private class GatedSource(
private val delegate: StorageSource,
private val gate: CompletableDeferred<Unit>,
) : StorageSource by delegate {
override suspend fun list(directory: StoragePath): List<FileEntry> {
gate.await()
return delegate.list(directory)
}
}
@Test @Test
fun `navigating up goes to the parent then to the roots`() { fun `navigating up goes to the parent then to the roots`() {
val model = viewModel() val model = viewModel()
+4 -7
View File
@@ -9,7 +9,7 @@
<ID>CyclomaticComplexMethod:ArchiveFormats.kt$ArchiveFormats$fun formatOf(fileName: String): ArchiveFormat</ID> <ID>CyclomaticComplexMethod:ArchiveFormats.kt$ArchiveFormats$fun formatOf(fileName: String): ArchiveFormat</ID>
<ID>CyclomaticComplexMethod:BrowserContent.kt$@Composable fun BrowserContent( state: BrowserUiState, contentPadding: PaddingValues, crumbLabel: (StoragePath) -&gt; String, onOpenEntry: (FileEntry) -&gt; Unit, onFocusEntry: (FileEntry) -&gt; Unit, onFocusRoot: (RootItem) -&gt; Unit, onToggleSelection: (StoragePath) -&gt; Unit, onOpenRoot: (StoragePath) -&gt; Unit, onNavigate: (StoragePath) -&gt; Unit, onOpenCategory: (FileCategory) -&gt; Unit, onOpenBookmark: (StoragePath) -&gt; Unit, onRemoveBookmark: (StoragePath) -&gt; Unit, onGrantAllFiles: () -&gt; Unit, onPickFolder: () -&gt; Unit, onRebuildIndex: () -&gt; Unit, /** Hoisted by the screen so the scroll position outlives a viewer taking over. */ listState: LazyListState = rememberLazyListState(), gridState: LazyGridState = rememberLazyGridState(), )</ID> <ID>CyclomaticComplexMethod:BrowserContent.kt$@Composable fun BrowserContent( state: BrowserUiState, contentPadding: PaddingValues, crumbLabel: (StoragePath) -&gt; String, onOpenEntry: (FileEntry) -&gt; Unit, onFocusEntry: (FileEntry) -&gt; Unit, onFocusRoot: (RootItem) -&gt; Unit, onToggleSelection: (StoragePath) -&gt; Unit, onOpenRoot: (StoragePath) -&gt; Unit, onNavigate: (StoragePath) -&gt; Unit, onOpenCategory: (FileCategory) -&gt; Unit, onOpenBookmark: (StoragePath) -&gt; Unit, onRemoveBookmark: (StoragePath) -&gt; Unit, onGrantAllFiles: () -&gt; Unit, onPickFolder: () -&gt; Unit, onRebuildIndex: () -&gt; Unit, /** Hoisted by the screen so the scroll position outlives a viewer taking over. */ listState: LazyListState = rememberLazyListState(), gridState: LazyGridState = rememberLazyGridState(), )</ID>
<ID>CyclomaticComplexMethod:BrowserContent.kt$@Composable private fun DirectoryView( state: BrowserUiState, crumbLabel: (StoragePath) -&gt; String, wide: Boolean, listState: LazyListState, gridState: LazyGridState, onOpenEntry: (FileEntry) -&gt; Unit, onFocusEntry: (FileEntry) -&gt; Unit, onToggleSelection: (StoragePath) -&gt; Unit, onNavigate: (StoragePath) -&gt; Unit, onGrantAllFiles: () -&gt; Unit, onRebuildIndex: () -&gt; Unit, modifier: Modifier = Modifier, )</ID> <ID>CyclomaticComplexMethod:BrowserContent.kt$@Composable private fun DirectoryView( state: BrowserUiState, crumbLabel: (StoragePath) -&gt; String, wide: Boolean, listState: LazyListState, gridState: LazyGridState, onOpenEntry: (FileEntry) -&gt; Unit, onFocusEntry: (FileEntry) -&gt; Unit, onToggleSelection: (StoragePath) -&gt; Unit, onNavigate: (StoragePath) -&gt; Unit, onGrantAllFiles: () -&gt; Unit, onRebuildIndex: () -&gt; Unit, modifier: Modifier = Modifier, )</ID>
<ID>CyclomaticComplexMethod:BrowserScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun BrowserScreen( incoming: IncomingRequest? = null, onDeliver: (FileEntry) -&gt; Unit = {}, onDone: () -&gt; Unit = {}, viewModel: BrowserViewModel = viewModel(factory = BrowserViewModel.Factory), )</ID> <ID>CyclomaticComplexMethod:BrowserScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun BrowserScreen( incoming: IncomingRequest? = null, startRoute: ShortcutRoute? = null, onDeliver: (FileEntry) -&gt; Unit = {}, onDone: () -&gt; Unit = {}, viewModel: BrowserViewModel = viewModel(factory = BrowserViewModel.Factory), )</ID>
<ID>CyclomaticComplexMethod:BrowserViewModel.kt$BrowserViewModel$fun open(entry: FileEntry)</ID> <ID>CyclomaticComplexMethod:BrowserViewModel.kt$BrowserViewModel$fun open(entry: FileEntry)</ID>
<ID>CyclomaticComplexMethod:BrowserViewModel.kt$BrowserViewModel$fun previewArchiveEntry(entry: ArchiveEntry)</ID> <ID>CyclomaticComplexMethod:BrowserViewModel.kt$BrowserViewModel$fun previewArchiveEntry(entry: ArchiveEntry)</ID>
<ID>CyclomaticComplexMethod:FileOperations.kt$FileOperations$private suspend fun transfer( from: StoragePath, to: StoragePath, move: Boolean, state: OperationState, )</ID> <ID>CyclomaticComplexMethod:FileOperations.kt$FileOperations$private suspend fun transfer( from: StoragePath, to: StoragePath, move: Boolean, state: OperationState, )</ID>
@@ -17,12 +17,11 @@
<ID>LargeClass:BrowserViewModel.kt$BrowserViewModel : ViewModel</ID> <ID>LargeClass:BrowserViewModel.kt$BrowserViewModel : ViewModel</ID>
<ID>LargeClass:BrowserViewModelTest.kt$BrowserViewModelTest</ID> <ID>LargeClass:BrowserViewModelTest.kt$BrowserViewModelTest</ID>
<ID>LongMethod:BrowserContent.kt$@Composable fun BrowserContent( state: BrowserUiState, contentPadding: PaddingValues, crumbLabel: (StoragePath) -&gt; String, onOpenEntry: (FileEntry) -&gt; Unit, onFocusEntry: (FileEntry) -&gt; Unit, onFocusRoot: (RootItem) -&gt; Unit, onToggleSelection: (StoragePath) -&gt; Unit, onOpenRoot: (StoragePath) -&gt; Unit, onNavigate: (StoragePath) -&gt; Unit, onOpenCategory: (FileCategory) -&gt; Unit, onOpenBookmark: (StoragePath) -&gt; Unit, onRemoveBookmark: (StoragePath) -&gt; Unit, onGrantAllFiles: () -&gt; Unit, onPickFolder: () -&gt; Unit, onRebuildIndex: () -&gt; Unit, /** Hoisted by the screen so the scroll position outlives a viewer taking over. */ listState: LazyListState = rememberLazyListState(), gridState: LazyGridState = rememberLazyGridState(), )</ID> <ID>LongMethod:BrowserContent.kt$@Composable fun BrowserContent( state: BrowserUiState, contentPadding: PaddingValues, crumbLabel: (StoragePath) -&gt; String, onOpenEntry: (FileEntry) -&gt; Unit, onFocusEntry: (FileEntry) -&gt; Unit, onFocusRoot: (RootItem) -&gt; Unit, onToggleSelection: (StoragePath) -&gt; Unit, onOpenRoot: (StoragePath) -&gt; Unit, onNavigate: (StoragePath) -&gt; Unit, onOpenCategory: (FileCategory) -&gt; Unit, onOpenBookmark: (StoragePath) -&gt; Unit, onRemoveBookmark: (StoragePath) -&gt; Unit, onGrantAllFiles: () -&gt; Unit, onPickFolder: () -&gt; Unit, onRebuildIndex: () -&gt; Unit, /** Hoisted by the screen so the scroll position outlives a viewer taking over. */ listState: LazyListState = rememberLazyListState(), gridState: LazyGridState = rememberLazyGridState(), )</ID>
<ID>LongMethod:BrowserScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun BrowserScreen( incoming: IncomingRequest? = null, onDeliver: (FileEntry) -&gt; Unit = {}, onDone: () -&gt; Unit = {}, viewModel: BrowserViewModel = viewModel(factory = BrowserViewModel.Factory), )</ID> <ID>LongMethod:BrowserScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun BrowserScreen( incoming: IncomingRequest? = null, startRoute: ShortcutRoute? = null, onDeliver: (FileEntry) -&gt; Unit = {}, onDone: () -&gt; Unit = {}, viewModel: BrowserViewModel = viewModel(factory = BrowserViewModel.Factory), )</ID>
<ID>LongMethod:BrowserTopBar.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun BrowserTopBar( title: String, canNavigateUp: Boolean, /** Whether this view is a folder, and so can be starred at all. */ canBookmark: Boolean, bookmarked: Boolean, query: String, searchOpen: Boolean, searchScope: SearchScope, /** Whether the scope is the user's to choose at all; see the note beside the toggle. */ scopeChoosable: Boolean, canPaste: Boolean, onUp: () -&gt; Unit, onQuery: (String) -&gt; Unit, onSearchOpen: (Boolean) -&gt; Unit, onSearchScope: () -&gt; Unit, onSort: () -&gt; Unit, onPaste: () -&gt; Unit, onToggleBookmark: () -&gt; Unit, onRefresh: () -&gt; Unit, onUsage: () -&gt; Unit, onDuplicates: () -&gt; Unit, onTrash: () -&gt; Unit, )</ID> <ID>LongMethod:BrowserTopBar.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun BrowserTopBar( title: String, canNavigateUp: Boolean, /** Whether this view is a folder, and so can be starred at all. */ canBookmark: Boolean, bookmarked: Boolean, query: String, searchOpen: Boolean, searchScope: SearchScope, /** Whether the scope is the user's to choose at all; see the note beside the toggle. */ scopeChoosable: Boolean, canPaste: Boolean, onUp: () -&gt; Unit, onQuery: (String) -&gt; Unit, onSearchOpen: (Boolean) -&gt; Unit, onSearchScope: () -&gt; Unit, onSort: () -&gt; Unit, onPaste: () -&gt; Unit, onToggleBookmark: () -&gt; Unit, onRefresh: () -&gt; Unit, onUsage: () -&gt; Unit, onDuplicates: () -&gt; Unit, onTrash: () -&gt; Unit, )</ID>
<ID>LongParameterList:BrowserContent.kt$( state: BrowserUiState, contentPadding: PaddingValues, crumbLabel: (StoragePath) -&gt; String, onOpenEntry: (FileEntry) -&gt; Unit, onFocusEntry: (FileEntry) -&gt; Unit, onFocusRoot: (RootItem) -&gt; Unit, onToggleSelection: (StoragePath) -&gt; Unit, onOpenRoot: (StoragePath) -&gt; Unit, onNavigate: (StoragePath) -&gt; Unit, onOpenCategory: (FileCategory) -&gt; Unit, onOpenBookmark: (StoragePath) -&gt; Unit, onRemoveBookmark: (StoragePath) -&gt; Unit, onGrantAllFiles: () -&gt; Unit, onPickFolder: () -&gt; Unit, onRebuildIndex: () -&gt; Unit, /** Hoisted by the screen so the scroll position outlives a viewer taking over. */ listState: LazyListState = rememberLazyListState(), gridState: LazyGridState = rememberLazyGridState(), )</ID> <ID>LongParameterList:BrowserContent.kt$( state: BrowserUiState, contentPadding: PaddingValues, crumbLabel: (StoragePath) -&gt; String, onOpenEntry: (FileEntry) -&gt; Unit, onFocusEntry: (FileEntry) -&gt; Unit, onFocusRoot: (RootItem) -&gt; Unit, onToggleSelection: (StoragePath) -&gt; Unit, onOpenRoot: (StoragePath) -&gt; Unit, onNavigate: (StoragePath) -&gt; Unit, onOpenCategory: (FileCategory) -&gt; Unit, onOpenBookmark: (StoragePath) -&gt; Unit, onRemoveBookmark: (StoragePath) -&gt; Unit, onGrantAllFiles: () -&gt; Unit, onPickFolder: () -&gt; Unit, onRebuildIndex: () -&gt; Unit, /** Hoisted by the screen so the scroll position outlives a viewer taking over. */ listState: LazyListState = rememberLazyListState(), gridState: LazyGridState = rememberLazyGridState(), )</ID>
<ID>LongParameterList:BrowserContent.kt$( state: BrowserUiState, crumbLabel: (StoragePath) -&gt; String, wide: Boolean, listState: LazyListState, gridState: LazyGridState, onOpenEntry: (FileEntry) -&gt; Unit, onFocusEntry: (FileEntry) -&gt; Unit, onToggleSelection: (StoragePath) -&gt; Unit, onNavigate: (StoragePath) -&gt; Unit, onGrantAllFiles: () -&gt; Unit, onRebuildIndex: () -&gt; Unit, modifier: Modifier = Modifier, )</ID> <ID>LongParameterList:BrowserContent.kt$( state: BrowserUiState, crumbLabel: (StoragePath) -&gt; String, wide: Boolean, listState: LazyListState, gridState: LazyGridState, onOpenEntry: (FileEntry) -&gt; Unit, onFocusEntry: (FileEntry) -&gt; Unit, onToggleSelection: (StoragePath) -&gt; Unit, onNavigate: (StoragePath) -&gt; Unit, onGrantAllFiles: () -&gt; Unit, onRebuildIndex: () -&gt; Unit, modifier: Modifier = Modifier, )</ID>
<ID>LongParameterList:BrowserTopBar.kt$( title: String, canNavigateUp: Boolean, /** Whether this view is a folder, and so can be starred at all. */ canBookmark: Boolean, bookmarked: Boolean, query: String, searchOpen: Boolean, searchScope: SearchScope, /** Whether the scope is the user's to choose at all; see the note beside the toggle. */ scopeChoosable: Boolean, canPaste: Boolean, onUp: () -&gt; Unit, onQuery: (String) -&gt; Unit, onSearchOpen: (Boolean) -&gt; Unit, onSearchScope: () -&gt; Unit, onSort: () -&gt; Unit, onPaste: () -&gt; Unit, onToggleBookmark: () -&gt; Unit, onRefresh: () -&gt; Unit, onUsage: () -&gt; Unit, onDuplicates: () -&gt; Unit, onTrash: () -&gt; Unit, )</ID> <ID>LongParameterList:BrowserTopBar.kt$( title: String, canNavigateUp: Boolean, /** Whether this view is a folder, and so can be starred at all. */ canBookmark: Boolean, bookmarked: Boolean, query: String, searchOpen: Boolean, searchScope: SearchScope, /** Whether the scope is the user's to choose at all; see the note beside the toggle. */ scopeChoosable: Boolean, canPaste: Boolean, onUp: () -&gt; Unit, onQuery: (String) -&gt; Unit, onSearchOpen: (Boolean) -&gt; Unit, onSearchScope: () -&gt; Unit, onSort: () -&gt; Unit, onPaste: () -&gt; Unit, onToggleBookmark: () -&gt; Unit, onRefresh: () -&gt; Unit, onUsage: () -&gt; Unit, onDuplicates: () -&gt; Unit, onTrash: () -&gt; Unit, )</ID>
<ID>LongParameterList:SelectionBar.kt$( state: BrowserUiState, onCopy: () -&gt; Unit, onCut: () -&gt; Unit, onDelete: () -&gt; Unit, onDetails: () -&gt; Unit, onRename: () -&gt; Unit, onOpenWith: () -&gt; Unit, onShare: () -&gt; Unit, onCompress: () -&gt; Unit, onExtract: () -&gt; Unit, onSelectAll: () -&gt; Unit, onClear: () -&gt; Unit, )</ID>
<ID>LoopWithTooManyJumpStatements:ArchiveEngine.kt$ArchiveEngine$while</ID> <ID>LoopWithTooManyJumpStatements:ArchiveEngine.kt$ArchiveEngine$while</ID>
<ID>LoopWithTooManyJumpStatements:BatchRename.kt$BatchRename$for</ID> <ID>LoopWithTooManyJumpStatements:BatchRename.kt$BatchRename$for</ID>
<ID>LoopWithTooManyJumpStatements:DuplicateFinder.kt$DuplicateFinder$while</ID> <ID>LoopWithTooManyJumpStatements:DuplicateFinder.kt$DuplicateFinder$while</ID>
@@ -61,15 +60,13 @@
<ID>NestedBlockDepth:ArchiveEngine.kt$ArchiveEngine$private suspend fun readArchive( archive: ArchiveInputStream&lt;*&gt;, destination: StoragePath, state: ArchiveState, )</ID> <ID>NestedBlockDepth:ArchiveEngine.kt$ArchiveEngine$private suspend fun readArchive( archive: ArchiveInputStream&lt;*&gt;, destination: StoragePath, state: ArchiveState, )</ID>
<ID>NestedBlockDepth:ArchiveEngine.kt$ArchiveEngine$private suspend fun readSevenZip( channel: SeekableByteChannel, destination: StoragePath, state: ArchiveState, )</ID> <ID>NestedBlockDepth:ArchiveEngine.kt$ArchiveEngine$private suspend fun readSevenZip( channel: SeekableByteChannel, destination: StoragePath, state: ArchiveState, )</ID>
<ID>NestedBlockDepth:ArchiveEngine.kt$ArchiveEngine$private suspend fun withEntry( archive: StoragePath, name: String, sink: suspend (InputStream) -&gt; Unit, ): Boolean</ID> <ID>NestedBlockDepth:ArchiveEngine.kt$ArchiveEngine$private suspend fun withEntry( archive: StoragePath, name: String, sink: suspend (InputStream) -&gt; Unit, ): Boolean</ID>
<ID>NestedBlockDepth:ArchiveEngine.kt$ArchiveEngine$suspend fun createZip( entries: List&lt;StoragePath&gt;, destination: StoragePath, onProgress: (OperationProgress) -&gt; Unit = {}, ): OperationResult</ID> <ID>NestedBlockDepth:ArchiveEngine.kt$ArchiveEngine$suspend fun createZip( entries: List&lt;StoragePath&gt;, destination: StoragePath, compress: Boolean = true, onProgress: (OperationProgress) -&gt; Unit = {}, ): OperationResult</ID>
<ID>NestedBlockDepth:ArchiveEngine.kt$ArchiveEngine$suspend fun extract( archive: StoragePath, destination: StoragePath, onProgress: (OperationProgress) -&gt; Unit = {}, ): OperationResult</ID> <ID>NestedBlockDepth:ArchiveEngine.kt$ArchiveEngine$suspend fun extract( archive: StoragePath, destination: StoragePath, onProgress: (OperationProgress) -&gt; Unit = {}, ): OperationResult</ID>
<ID>NestedBlockDepth:ArchiveEngine.kt$ArchiveEngine$suspend fun list(archive: StoragePath): List&lt;ArchiveEntry&gt;</ID> <ID>NestedBlockDepth:ArchiveEngine.kt$ArchiveEngine$suspend fun list(archive: StoragePath): List&lt;ArchiveEntry&gt;</ID>
<ID>NestedBlockDepth:ArchiveEngineTest.kt$ArchiveEngineTest$private fun sevenZip(vararg entries: Pair&lt;String, String&gt;): ByteArray</ID> <ID>NestedBlockDepth:ArchiveEngineTest.kt$ArchiveEngineTest$private fun sevenZip(vararg entries: Pair&lt;String, String&gt;): ByteArray</ID>
<ID>RethrowCaughtException:BrowserViewModel.kt$BrowserViewModel$throw cancellation</ID> <ID>RethrowCaughtException:BrowserViewModel.kt$BrowserViewModel$throw cancellation</ID>
<ID>ReturnCount:ArchiveEngine.kt$ArchiveEngine$private suspend fun withEntry( archive: StoragePath, name: String, sink: suspend (InputStream) -&gt; Unit, ): Boolean</ID> <ID>ReturnCount:ArchiveEngine.kt$ArchiveEngine$private suspend fun withEntry( archive: StoragePath, name: String, sink: suspend (InputStream) -&gt; Unit, ): Boolean</ID>
<ID>ReturnCount:BrowserScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun BrowserScreen( incoming: IncomingRequest? = null, onDeliver: (FileEntry) -&gt; Unit = {}, onDone: () -&gt; Unit = {}, viewModel: BrowserViewModel = viewModel(factory = BrowserViewModel.Factory), )</ID> <ID>ReturnCount:BrowserScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun BrowserScreen( incoming: IncomingRequest? = null, startRoute: ShortcutRoute? = null, onDeliver: (FileEntry) -&gt; Unit = {}, onDone: () -&gt; Unit = {}, viewModel: BrowserViewModel = viewModel(factory = BrowserViewModel.Factory), )</ID>
<ID>SpreadOperator:BrowserScreen.kt$(it.textRes, *it.args.toTypedArray())</ID>
<ID>SpreadOperator:BrowserScreen.kt$(it.textRes, quantity, *it.args.toTypedArray())</ID>
<ID>TooGenericExceptionCaught:ArchiveEngine.kt$ArchiveEngine$failure: Exception</ID> <ID>TooGenericExceptionCaught:ArchiveEngine.kt$ArchiveEngine$failure: Exception</ID>
<ID>TooGenericExceptionCaught:BrowserViewModel.kt$BrowserViewModel$failure: Exception</ID> <ID>TooGenericExceptionCaught:BrowserViewModel.kt$BrowserViewModel$failure: Exception</ID>
<ID>TooGenericExceptionCaught:FileOperations.kt$FileOperations$failure: Exception</ID> <ID>TooGenericExceptionCaught:FileOperations.kt$FileOperations$failure: Exception</ID>
+50 -15
View File
@@ -2,7 +2,7 @@
Generated from the source by `tools/make-code-map.py` - do not edit by hand. Regenerate it after a change (`python3 tools/make-code-map.py`); `--check` exits non-zero when this file is stale. Generated from the source by `tools/make-code-map.py` - do not edit by hand. Regenerate it after a change (`python3 tools/make-code-map.py`); `--check` exits non-zero when this file is stale.
79 source files, 13369 lines - 35 test files, 403 tests. The behaviour index at the end lists every test name, and in this project a test name is a sentence about what the app does, so it doubles as the specification. 80 source files, 13902 lines - 37 test files, 431 tests. The behaviour index at the end lists every test name, and in this project a test name is a sentence about what the app does, so it doubles as the specification.
Start at `AGENTS.md`. What is done, and why: `docs/ROADMAP.md` and `CHANGELOG.md`. What was verified by hand rather than by a test: `docs/EDGE_CASE_TESTING.md`. Start at `AGENTS.md`. What is done, and why: `docs/ROADMAP.md` and `CHANGELOG.md`. What was verified by hand rather than by a test: `docs/EDGE_CASE_TESTING.md`.
@@ -23,6 +23,7 @@ Pure Kotlin, **no Android imports**: paths, file names, kinds, sorting, formatti
| `MimeTypes.kt` | 110 | Best-effort MIME lookup for the "open with" intent. MimeTypes | `FileEntryTest` (8) | | `MimeTypes.kt` | 110 | Best-effort MIME lookup for the "open with" intent. MimeTypes | `FileEntryTest` (8) |
| `NameAllocator.kt` | 30 | Picks a name that is not already in use, in the familiar "name (1)" style. NameAllocator | `NameMatcherTest` (10) | | `NameAllocator.kt` | 30 | Picks a name that is not already in use, in the familiar "name (1)" style. NameAllocator | `NameMatcherTest` (10) |
| `NameMatcher.kt` | 63 | The in-folder search matcher. NameMatcher | `NameMatcherTest` (10) | | `NameMatcher.kt` | 63 | The in-folder search matcher. NameMatcher | `NameMatcherTest` (10) |
| `ShortcutRoute.kt` | 27 | Where a launcher shortcut asks the app to open. ShortcutRoute | `ShortcutRouteTest` (2) |
| `SortSpec.kt` | 82 | A complete, serialisable description of the ordering of a directory listing. SortKey, SortDirection, SortSpec, NaturalOrder | `SortSpecTest` (8) | | `SortSpec.kt` | 82 | A complete, serialisable description of the ordering of a directory listing. SortKey, SortDirection, SortSpec, NaturalOrder | `SortSpecTest` (8) |
| `SortedMerge.kt` | 42 | Adds a freshly read batch to an already sorted list, in one pass. SortedMerge | `SortedMergeTest` (4) | | `SortedMerge.kt` | 42 | Adds a freshly read batch to an already sorted list, in one pass. SortedMerge | `SortedMergeTest` (4) |
| `StoragePath.kt` | 89 | A normalized, absolute, backend-agnostic storage path. StoragePath | `StoragePathTest` (8) | | `StoragePath.kt` | 89 | A normalized, absolute, backend-agnostic storage path. StoragePath | `StoragePathTest` (8) |
@@ -61,14 +62,14 @@ Operations over a source: copy/move/delete/rename, archives, search walking, dup
| file | lines | what it holds | tests | | file | lines | what it holds | tests |
|---|---|---|---| |---|---|---|---|
| `ArchiveEngine.kt` | 658 | Creates and extracts archives, on top of the storage backends. ArchiveEntry, ArchiveEngine | `ArchiveEngineTest` (30) | | `ArchiveEngine.kt` | 667 | Creates and extracts archives, on top of the storage backends. ArchiveEntry, ArchiveEngine | `ArchiveEngineTest` (31) |
| `DuplicateFinder.kt` | 202 | Finds files that hold the same bytes. DuplicateGroup, DuplicateProgress, DuplicateScan, DuplicateFinder | `DuplicateFinderTest` (8) | | `DuplicateFinder.kt` | 202 | Finds files that hold the same bytes. DuplicateGroup, DuplicateProgress, DuplicateScan, DuplicateFinder | `DuplicateFinderTest` (8) |
| `FileOperations.kt` | 272 | Copy, move and delete, assembled from the StorageSource primitives. FileOperations | `FileOperationsTest` (19) | | `FileOperations.kt` | 272 | Copy, move and delete, assembled from the StorageSource primitives. FileOperations | `FileOperationsTest` (19) |
| `FileSearch.kt` | 79 | Recursive name search. FileSearch | `FileSearchTest` (8) | | `FileSearch.kt` | 79 | Recursive name search. FileSearch | `FileSearchTest` (8) |
| `OperationModels.kt` | 42 | The kind of long-running operation a progress notification can describe. OperationKind, OperationProgress, OperationFailure, OperationResult | - | | `OperationModels.kt` | 42 | The kind of long-running operation a progress notification can describe. OperationKind, OperationProgress, OperationFailure, OperationResult | - |
| `OperationNotifier.kt` | 25 | Keeps the foreground service in step with a running operation. OperationNotifier | - | | `OperationNotifier.kt` | 25 | Keeps the foreground service in step with a running operation. OperationNotifier | - |
| `SearchIndexer.kt` | 173 | Fills a SearchIndex by walking a volume. SearchIndexer | `SearchIndexerTest` (14) | | `SearchIndexer.kt` | 173 | Fills a SearchIndex by walking a volume. SearchIndexer | `SearchIndexerTest` (14) |
| `Trash.kt` | 338 | A staging folder that makes a delete undoable. TrashedEntry, TrashBatch, Trash | `TrashTest` (19) | | `Trash.kt` | 360 | A staging folder that makes a delete undoable. TrashedEntry, TrashBatch, Trash | `TrashTest` (20) |
| `UsageAnalysis.kt` | 95 | Works out where the space went. UsageNode, UsageAnalysis | `UsageAnalysisTest` (6) | | `UsageAnalysis.kt` | 95 | Works out where the space went. UsageNode, UsageAnalysis | `UsageAnalysisTest` (6) |
## service/ ## service/
@@ -95,15 +96,15 @@ The browser screen: view model, state, list and grid, dialogs, selection bar
| file | lines | what it holds | tests | | file | lines | what it holds | tests |
|---|---|---|---| |---|---|---|---|
| `BrowserComponents.kt` | 317 | The thumbnail an entry's leading visual gets in a list row. ListThumbnailSize, GridThumbnailSize, GridCellMinSize, EntryIcon(), FileEntry(), FileEntry(), VIDEO_FRAME_MILLIS, iconFor(), iconFor(), EntryRow(), EntryGridCell(), FileEntry() | - | | `BrowserComponents.kt` | 365 | The thumbnail an entry's leading visual gets in a list row. ListThumbnailSize, GridThumbnailSize, GridCellMinSize, EntryIcon(), FileEntry(), FileEntry(), VIDEO_FRAME_MILLIS, iconFor(), iconFor(), MarkOfChange(), EntryRow(), EntryGridCell(), FileEntry() | `BrowserComponentsTest` (3) |
| `BrowserContent.kt` | 463 | Everything below the app bar: the permission prompt, the roots, or a directory. WIDE_LAYOUT_MIN_WIDTH, MasterPaneWidth, BrowserContent(), LazyListScope(), LIBRARY_SECTION_KEY, LazyListScope(), BOOKMARK_SECTION_KEY, DirectoryView(), FileEntry(), IndexStatusRow(), FileEntry() | - | | `BrowserContent.kt` | 465 | Everything below the app bar: the permission prompt, the roots, or a directory. WIDE_LAYOUT_MIN_WIDTH, MasterPaneWidth, BrowserContent(), LazyListScope(), LIBRARY_SECTION_KEY, LazyListScope(), BOOKMARK_SECTION_KEY, DirectoryView(), FileEntry(), IndexStatusRow(), FileEntry() | - |
| `BrowserDetailPane.kt` | 131 | The second pane of the wide layout: what is inside the folder the user picked, or a preview and the details of the file they picked. DetailPane(), FolderPreview(), ImagePreview() | - | | `BrowserDetailPane.kt` | 131 | The second pane of the wide layout: what is inside the folder the user picked, or a preview and the details of the file they picked. DetailPane(), FolderPreview(), ImagePreview() | - |
| `BrowserDialogs.kt` | 381 | The Copy to… / Move to… picker. TransferToDialog(), titleFor(), hereFor(), BatchRenameDialog(), PREVIEW_NAMES, batchRenameNote(), NameDialog(), ConfirmDialog(), ConflictDialog() | `BrowserDialogsTest` (5) | | `BrowserDialogs.kt` | 444 | Compressing something, with the one choice that changes what comes out. CompressDialog(), TransferToDialog(), titleFor(), hereFor(), BatchRenameDialog(), PREVIEW_NAMES, batchRenameNote(), NameDialog(), ConfirmDialog(), ConflictDialog() | `BrowserDialogsTest` (5) |
| `BrowserRoots.kt` | 270 | A row on the root screen: a volume, with its free space when the platform reports it. RootRow(), itemCountLabel(), EmptyState(), LibrarySectionHeader(), BookmarkSectionHeader(), SectionHeader(), BookmarkRow(), LibraryRow(), Breadcrumbs() | `BrowserRootsTest` (4) | | `BrowserRoots.kt` | 270 | A row on the root screen: a volume, with its free space when the platform reports it. RootRow(), itemCountLabel(), EmptyState(), LibrarySectionHeader(), BookmarkSectionHeader(), SectionHeader(), BookmarkRow(), LibraryRow(), Breadcrumbs() | `BrowserRootsTest` (4) |
| `BrowserScreen.kt` | 604 | BrowserScreen() | - | | `BrowserScreen.kt` | 661 | The browser, and everything that can be on top of it. BrowserScreen(), messageText() | - |
| `BrowserTopBar.kt` | 238 | The browser's app bar: title, up, the favourite star, and the search / sort / overflow actions. BrowserTopBar(), SEARCH_FIELD_WIDTH | `BrowserTopBarTest` (4) | | `BrowserTopBar.kt` | 238 | The browser's app bar: title, up, the favourite star, and the search / sort / overflow actions. BrowserTopBar(), SEARCH_FIELD_WIDTH | `BrowserTopBarTest` (4) |
| `BrowserUiState.kt` | 343 | One immutable description of everything the browser shows. ViewMode, SearchScope, Clipboard, PickerFolder, TransferPicker, UiMessage, ConflictPrompt, RootItem, Bookmark, DetailFocus, Undo, UndoMove, Overlay, BrowserUiState | - | | `BrowserUiState.kt` | 391 | One immutable description of everything the browser shows. ViewMode, SearchScope, Clipboard, CompressRequest, PickerFolder, TransferPicker, MessageAction, UiMessage, ConflictPrompt, RootItem, Bookmark, DetailFocus, Undo, UndoMove, Overlay, BrowserUiState | - |
| `BrowserViewModel.kt` | 2376 | Drives the browser screen. BrowserViewModel, ArchivePreview | `BrowserViewModelTest` (96) | | `BrowserViewModel.kt` | 2601 | Drives the browser screen. BrowserViewModel, ArchivePreview | `BrowserViewModelTest` (117) |
| `DetailsSheet.kt` | 109 | Name, location, size, type and modified date for one entry. DetailsSheet(), DetailLines(), DetailLine() | - | | `DetailsSheet.kt` | 109 | Name, location, size, type and modified date for one entry. DetailsSheet(), DetailLines(), DetailLine() | - |
| `EntryIntents.kt` | 58 | Wraps an entry's path in a content:// URI another app may read. contentUriFor(), viewIntent(), shareIntent() | - | | `EntryIntents.kt` | 58 | Wraps an entry's path in a content:// URI another app may read. contentUriFor(), viewIntent(), shareIntent() | - |
| `IncomingBar.kt` | 60 | The bar shown while another app is waiting on this one. IncomingBar() | - | | `IncomingBar.kt` | 60 | The bar shown while another app is waiting on this one. IncomingBar() | - |
@@ -139,7 +140,7 @@ The trash screen
| file | lines | what it holds | tests | | file | lines | what it holds | tests |
|---|---|---|---| |---|---|---|---|
| `TrashScreen.kt` | 192 | What the trash still holds, and the way to put it back. TrashScreen(), BatchHeader(), TrashEntryRow() | - | | `TrashScreen.kt` | 220 | What the trash still holds, and the way to put it back. TrashScreen(), BatchHeader(), TrashEntryRow() | - |
## ui/duplicates/ ## ui/duplicates/
@@ -164,7 +165,7 @@ Compose theme, colours, type
| file | lines | what it holds | tests | | file | lines | what it holds | tests |
|---|---|---|---| |---|---|---|---|
| `FileManagerApplication.kt` | 151 | Application entry point and the app's tiny object graph. FileManagerApplication | - | | `FileManagerApplication.kt` | 151 | Application entry point and the app's tiny object graph. FileManagerApplication | - |
| `MainActivity.kt` | 65 | MainActivity | - | | `MainActivity.kt` | 69 | MainActivity | - |
## benchmark/ ## benchmark/
@@ -279,6 +280,11 @@ Every test name in the suite, by file: the fastest way to see whether something
- treats a dotfile as having no extension - treats a dotfile as having no extension
- preserves the base of multi-dot names - preserves the base of multi-dot names
### `core/ShortcutRouteTest.kt` (2)
- each shortcut key maps to its route
- anything else is ignored rather than thrown
### `core/SortSpecTest.kt` (8) ### `core/SortSpecTest.kt` (8)
- directories come first in both directions - directories come first in both directions
@@ -427,9 +433,10 @@ Every test name in the suite, by file: the fastest way to see whether something
- a volume without a space reading contributes nothing - a volume without a space reading contributes nothing
- used bytes never go negative - used bytes never go negative
### `domain/ArchiveEngineTest.kt` (30) ### `domain/ArchiveEngineTest.kt` (31)
- a zip round-trips folders and files - a zip round-trips folders and files
- an uncompressed zip round-trips and is larger than a squeezed one
- createZip reports progress over the files it will write - createZip reports progress over the files it will write
- a zip-slip entry cannot escape the destination - a zip-slip entry cannot escape the destination
- a single-file gzip is unwrapped to its inner name - a single-file gzip is unwrapped to its inner name
@@ -521,8 +528,9 @@ Every test name in the suite, by file: the fastest way to see whether something
- the timestamp is stamped from the clock when the pass finishes - the timestamp is stamped from the clock when the pass finishes
- a second pass replaces the first rather than doubling it - a second pass replaces the first rather than doubling it
### `domain/TrashTest.kt` (19) ### `domain/TrashTest.kt` (20)
- emptying removes every batch and leaves what is not one
- staging moves an item aside and records where it came from - staging moves an item aside and records where it came from
- restoring puts an item back exactly where it was - restoring puts an item back exactly where it was
- a folder comes back whole - a folder comes back whole
@@ -559,6 +567,12 @@ Every test name in the suite, by file: the fastest way to see whether something
- a determinate operation shows the counter - a determinate operation shows the counter
- starting the service puts it in the foreground with that title - starting the service puts it in the foreground with that title
### `ui/browser/BrowserComponentsTest.kt` (3)
- a row an operation produced carries the mark
- an ordinary row carries no mark
- a grid cell an operation produced carries the mark too
### `ui/browser/BrowserDialogsTest.kt` (5) ### `ui/browser/BrowserDialogsTest.kt` (5)
- the batch dialog spells the names out before anything moves - the batch dialog spells the names out before anything moves
@@ -581,7 +595,7 @@ Every test name in the suite, by file: the fastest way to see whether something
- a library or the root list has nothing to star - a library or the root list has nothing to star
- the star gives way to the search field - the star gives way to the search field
### `ui/browser/BrowserViewModelTest.kt` (96) ### `ui/browser/BrowserViewModelTest.kt` (117)
- starts on the root list - starts on the root list
- opening a folder lists it with directories first and natural order - opening a folder lists it with directories first and natural order
@@ -592,9 +606,30 @@ Every test name in the suite, by file: the fastest way to see whether something
- copy to a chosen folder leaves the user where they are and keeps the selection - copy to a chosen folder leaves the user where they are and keeps the selection
- move to a chosen folder takes the rows with it - move to a chosen folder takes the rows with it
- the picker offers folders and nothing else - the picker offers folders and nothing else
- the picker names a volume the way the browser does
- the picker leaves hidden folders out until they are asked for
- the picker walks up to the volumes and back down - the picker walks up to the volumes and back down
- a conflicting destination asks before overwriting, naming that folder - a conflicting destination asks before overwriting, naming that folder
- cancelling the picker copies nothing - cancelling the picker copies nothing
- a copy says where it went and offers to show it
- show takes the user to the folder the copy went to
- a paste into the folder on screen names no destination and offers no action
- the message's undo action is the undo
- a move to a chosen folder offers undo rather than show
- a copy into the folder on screen marks the copy
- a copy into another folder marks it there, not here
- reading the folder again spends its marks
- a rename marks the name it produced
- compressing asks for a name and a choice before writing
- a confirmed compress writes the name that was typed, and marks it
- cancelling the compress dialog writes nothing
- opening the trash sweeps what has expired
- opening the trash keeps what is still inside the window
- emptying the trash removes what is in it
- a shortcut opens the view it names
- typing while the index is being built does not start it again
- switching library while the index is being built does not start it again
- a search is answered again when the pass finds what it was looking for
- navigating up goes to the parent then to the roots - navigating up goes to the parent then to the roots
- selection survives toggling and clears on navigation - selection survives toggling and clears on navigation
- a file with no preview of its own is handed to the system - a file with no preview of its own is handed to the system
@@ -692,4 +727,4 @@ Every test name in the suite, by file: the fastest way to see whether something
--- ---
Purpose taken from the first KDoc rather than from a declaration sharing the file's name (15 of 78): `MainActivity.kt`, `ArchiveFormats.kt`, `FileNames.kt`, `ApkInspector.kt`, `OperationModels.kt`, `TextRes.kt`, `BrowserComponents.kt`, `BrowserDetailPane.kt`, `BrowserDialogs.kt`, `BrowserRoots.kt`, `BrowserScreen.kt`, `EntryIntents.kt`, `Color.kt`, `Theme.kt`, `Type.kt` Purpose taken from the first KDoc rather than from a declaration sharing the file's name (14 of 79): `MainActivity.kt`, `ArchiveFormats.kt`, `FileNames.kt`, `ApkInspector.kt`, `OperationModels.kt`, `TextRes.kt`, `BrowserComponents.kt`, `BrowserDetailPane.kt`, `BrowserDialogs.kt`, `BrowserRoots.kt`, `EntryIntents.kt`, `Color.kt`, `Theme.kt`, `Type.kt`
+55
View File
@@ -287,6 +287,61 @@ What the pass did change, before it was run:
cache — a disk cache would hold a second copy of pictures that are already on the device, and survive cache — a disk cache would hold a second copy of pictures that are already on the device, and survive
the file changing. the file changing.
## The copy-to session (M16)
Driven on the phone through the real UI (`adb` taps on `uiautomator` dumps), with `/sdcard/AASrc`,
`/sdcard/AADst` and `/sdcard/AAMv` standing in for two user folders.
- **Copy** into a picked folder: one file selected in `AASrc`, overflow → *Copy to…*, *Internal
storage* → `AADst` → *Copy here*. The file appeared in `AADst`, **stayed** in `AASrc`, the browser
came back to `AASrc`, and the bar still read *1 item* — the selection really does survive a copy.
- **Move** into a picked folder: the same walk into `AAMv`. `AASrc` ended up empty, `AAMv` held the
file, the snackbar said *Moved 1 item*, the listing said *This folder is empty*, and the selection bar
was gone.
- **The message and its Show button.** After a copy into `AADst` the snackbar read *Copied to AADst* with
**Show**, and tapping Show opened `AADst` with the copied file in it. Repeated into a volume root — the
case where the path has no name of its own — it read *Copied to Internal storage*, which is the label
rule doing its job rather than `0` leaking into a sentence.
- **The trail and the volume row.** Both first read the platform's own name for internal storage —
`0 / AADst` and a row labelled `0` — which is correct as a path and useless as a label. Fixed by
giving the picker the same label rule as the roots screen; the second pass reads *Internal storage /
AADst*. This is the kind of thing only a device shows: the JVM tests use paths, not labels.
## The survey-gap session (M17–M20)
Driven on the phone through the real UI, with `adb` taps on `uiautomator` dumps.
- **Launcher shortcuts (M20).** The two routes that exist only in the manifest and the intent — no JVM test can
reach them — were launched the way the launcher does it:
`am start -a android.intent.action.VIEW -n de.softwareapp_hb.filemanager/.MainActivity --es
de.softwareapp_hb.filemanager.SHORTCUT images` opened the **Images** library directly, and `… trash` opened
the **Trash**. `recent` was not launched separately: same intent, one enum value, one code path.
- **The trash window (M19).** The trash screen read *Deleted files are kept for 24 hours* above *Nothing in
the trash* — the sentence and the empty state together, so the retention is stated rather than inferred.
- **Not driven on the device: the change mark (M17) and the compress dialog (M18).** Both are covered by
tests — the dot by three Compose tests (present, absent, and its content description) and the dialog's two
answers by view-model tests — but the *visual* check (a dot beside a freshly made archive, the switch in
the dialog) is still owed. The terminal lost command output halfway through this session, so the driven
pass stopped after the two checks above rather than being reported as complete.
## The index-restart fix
Reported from use: "the index seems to be recreated at each input of the search bar, and if I switch to
another library the reindexing starts from begin again". Reproduced and measured on the phone, with the app's
data cleared first so the index was empty and a walk had to happen, and the 20 000-file fixture in place:
| typed so far | progress row |
|---|---|
| `f` | *Indexing 5 600 files…* |
| `fi` | *Indexing 6 300 files…* |
| `fil` | *Indexing 7 100 files…* |
| `file` | *Indexing 7 100 files…*, then *Index updated 2026-10-18 10:52* |
The counter climbing across keystrokes is the fix; before it, each keystroke cancelled the walk (the pass
ran inside the search's own job, which is replaced on every letter) and the next one began again at the
first folder, so the row read a fresh, small number every time. The walk finished on the last sample and
stamped the volume, which is what makes the *next* search cheap instead of another walk.
## Not verified, and why ## Not verified, and why
- **Long-press multi-select via adb: it works, but not every time.** `input swipe x y x y 900` - **Long-press multi-select via adb: it works, but not every time.** `input swipe x y x y 900`
+68 -15
View File
@@ -117,11 +117,19 @@ change in the app would show up as a change in these numbers rather than as nois
**Those frame counts are not a jank metric, and the difference matters.** `FrameTimingMetric` normally **Those frame counts are not a jank metric, and the difference matters.** `FrameTimingMetric` normally
publishes `frameDurationCpuMs` and `frameOverrunMs` — how long each frame took and how far past its publishes `frameDurationCpuMs` and `frameOverrunMs` — how long each frame took and how far past its
deadline it ran. This phone reports neither: the same run's JSON contains `frameCount` and nothing else, deadline it ran. `frameCount`, which is what the table above is made of, is how many frames an interaction
so "14 frames to open the folder" is how many frames the interaction took, not how long any of them took: a length, not a speed. It says a folder opens in about a fifth of a second at 60 Hz; it cannot say
lasted. It says the interaction is short (14 frames is about a quarter of a second at 60 Hz); it cannot whether any of those frames was slow.
say whether any of those frames was slow. A device that reports frame durations — an emulator or any
non-MIUI phone — is what turns this into a jank number. The runs those numbers come from reported `frameCount` only — their JSON had no sampled metrics at all,
which is what started the search for a device that supplies them. **A later run on the same phone did
supply them**, so the absence was a property of those runs, not of the handset. For the 1 000-file open,
measured after the listing was made progressive, `frameDurationCpuMs` is **P50 13.9 ms, P90 26.5 ms,
P99 86.5 ms** and `frameOverrunMs` **P50 19.0 ms, P90 32.2 ms, P99 80.6 ms**, next to `frameCount` median
12 (max 48) from the same run. Against a 60 Hz budget of 16.7 ms that is "the median frame fits, one in ten
takes 26 ms" — a statement the counts could never make. Why the earlier runs captured no frame timelines
is not known; what is known is that a run either does or does not, and that `.github/workflows/benchmark.yml`
now runs it on an emulator where it always does.
### How it scales with folder size ### How it scales with folder size
@@ -204,6 +212,31 @@ batches still take the ~2 s described above — they arrive behind the progress
already scrolling rather than into an empty screen. Both halves matter, and only the first one is in this already scrolling rather than into an empty screen. Both halves matter, and only the first one is in this
table. table.
### The whole suite at 20 000 files, twice
The script that the CI workflow runs was also run against the same 20 000-file fixture — it is
device-agnostic apart from the emulator runner — which gave a second, independent run of the open
benchmark and, for the first time, the other three at that size:
| 20 000 files | one value per iteration | min–max | `frameDurationCpuMs` P50 / P90 / P99 |
|---|---|---|---|
| `openAFolderOfAThousandFiles` | **16 frames** | 13–32 | 7.8 / 21.6 / 100.6 ms |
| `scrollAFolderOfAThousandFiles` | **162 frames** | 148–172 | 9.0 / 21.0 / 25.2 ms |
| `searchInsideAFolderOfAThousandFiles` | **319 frames** | 300–653 | 6.5 / 11.5 / 18.5 ms |
| `coldStart` | **599 ms** to first display | 593–604 | — |
Two things in it are worth keeping:
* **The batching result holds in a second run.** The table above has 12 median / 48 max from one run; this
one has 16 median / 32 max on a build that also carries the M16 picker. That is the same number within
the noise, and the 598-frame stall has not come back.
* **Search is the next outlier.** 319 frames is about five seconds from the query to `file-99.txt`,
against 38–39 frames at 1 000 files: twenty times the entries for eight times the frames, so sublinear —
but still long enough to notice, and the per-frame numbers say drawing is not the reason (P90 11.5 ms).
Handing twenty thousand rows to a list in one go is; that is where a "large folder" pass would start.
`coldStart`'s 599 ms and 162 frames of scrolling are recorded here as the baseline those two get
compared against, not as findings.
And the fixture now survives: `tools/benchmark-fixture.sh --count 20000` reuses a folder that already holds And the fixture now survives: `tools/benchmark-fixture.sh --count 20000` reuses a folder that already holds
at least that many files, and `--fresh` rebuilds it. Building it takes about half an hour through MIUI's at least that many files, and `--fresh` rebuilds it. Building it takes about half an hour through MIUI's
storage layer, which is the whole reason to keep it. storage layer, which is the whole reason to keep it.
@@ -317,17 +350,37 @@ instrumentation output itself, and the per-test JSON and Perfetto traces are lef
`/sdcard/Android/media/de.softwareapp_hb.filemanager.benchmark/` — they used to be deleted with the test app `/sdcard/Android/media/de.softwareapp_hb.filemanager.benchmark/` — they used to be deleted with the test app
when a run ended, which is why the earlier numbers had to be copied mid-run. when a run ended, which is why the earlier numbers had to be copied mid-run.
### The same thing in CI
`.github/workflows/benchmark.yml` runs those four commands on an emulator
(`reactivecircus/android-emulator-runner`, API 35, `google_apis`, x86_64, SwiftShader), on demand and every
Monday morning. It is deliberately not part of the pull-request gate: a run is minutes of measurement behind
twenty minutes of booting an emulator, and the gate is meant to answer in one or two minutes.
Two details make the numbers meaningful rather than merely present:
* The app is installed and `cmd package compile --reset` **before** the instrumentation starts, and the run
is driven with `am instrument` rather than `connectedBenchmarkAndroidTest` — the Gradle task installs the
app itself, which would undo that reset and quietly measure a compiled app.
* `tools/benchmark-report.py --require-frame-duration` turns the results into a table on the run's page and
**fails the job** when `frameDurationCpuMs` is missing. That metric is the reason the job exists; a run
without it is not a green run with a footnote.
The emulator's milliseconds are not a phone's — software rendering, a different CPU, no thermal limits — so
they are read as shape and trend (which benchmark is slow relative to the others, whether a change moved it),
not as an absolute.
## Still not measured ## Still not measured
| number | status | | number | status |
|---|---| |---|---|
| Folder open with 5 000 / 20 000 files | not measured yet: `./tools/benchmark-fixture.sh --count 20000` builds that fixture, and the open/scroll numbers follow from re-running the same command | | Folder open with 5 000 / 20 000 files | **measured**: see the scaling table above (`--count N` builds the fixture) |
| Thumbnail paint while scrolling a photo grid | not measured: no test for it yet | | Thumbnail paint while scrolling a photo grid | not measured: no test for it yet |
| Any jank figure at all | not measurable here: this phone's `FrameTimingMetric` output is `frameCount` only, with no `frameDurationCpuMs` or `frameOverrunMs` | | Any jank figure at all | **measured**: `frameDurationCpuMs` and `frameOverrunMs` both appear in the phone's 1 000-file run above, and the CI emulator run reports them every time |
What the interaction numbers still need is a device that reports frame durations — an emulator or any What is left for the interaction numbers is a device class decision rather than a measurement: the phone
non-MIUI phone would do, and the fixture is a folder of empty files, so nothing device-specific is being numbers are one handset's, the emulator's are software-rendered, and neither is a claim about a mid-range
measured. The install side is solved: `CompilationMode.Ignore()` plus installing from the host means a run device. The install side is solved: `CompilationMode.Ignore()` plus installing from the host means a run
touches the package manager zero times. touches the package manager zero times.
## What is measured instead, meanwhile ## What is measured instead, meanwhile
@@ -372,8 +425,8 @@ adb shell cmd package compile --reset de.softwareapp_hb.filemanager # n
adb shell cmd package compile -m speed-profile -f de.softwareapp_hb.filemanager # profile applied adb shell cmd package compile -m speed-profile -f de.softwareapp_hb.filemanager # profile applied
``` ```
The emulator did answer one open question, though: on that path `FrameTimingMetric` **does** report what The emulator did answer one open question, though: on that path `FrameTimingMetric` reports both
the phone cannot — `frameDurationCpuMs` and `frameOverrunMs` are both present (P50 233 ms and 341 ms for `frameDurationCpuMs` and `frameOverrunMs` (P50 233 ms and 341 ms for opening the folder, which is software
opening the folder, which is software rendering and not a number anyone should quote). The metric exists rendering and not a number anyone should quote). The metric exists as soon as the device captures frame
as soon as the device supports frame timelines, so a physical API 33+ phone gives both the profile timelines — which is what `.github/workflows/benchmark.yml` now guarantees, and what a physical API 33+
delta and the jank figures the interaction benchmarks have been missing. phone would combine with the profile delta.
+11 -6
View File
@@ -197,7 +197,7 @@ Full copy and the generated graphics land in **M10** (`docs/STORE_LISTING.md`).
fields needed: app name, short description, full description, app icon 512×512, feature fields needed: app name, short description, full description, app icon 512×512, feature
graphic 1024×500, and the screenshots. graphic 1024×500, and the screenshots.
- [ ] Upload the screenshots from `store-assets/screenshots/`: **phone** 1080×2160 (5), - [ ] Upload the screenshots from `store-assets/screenshots/`: **phone** 1080×2160 (8),
**7-inch tablet** 1200×1920 (4), **10-inch tablet** 2560×1600 (4). Play wants 4+ per **7-inch tablet** 1200×1920 (4), **10-inch tablet** 2560×1600 (4). Play wants 4+ per
large-screen form factor. All three sets clear its rules — 24-bit PNG with no alpha, large-screen form factor. All three sets clear its rules — 24-bit PNG with no alpha,
shorter side ≥ 320, longer side ≤ 3840, and longer side ≤ 2× the shorter side. shorter side ≥ 320, longer side ≤ 3840, and longer side ≤ 2× the shorter side.
@@ -205,11 +205,16 @@ graphic 1024×500, and the screenshots.
whose app area is blank. whose app area is blank.
- [ ] Expect the 7-inch set to be single-pane and the 10-inch set two-pane. That is the - [ ] Expect the 7-inch set to be single-pane and the 10-inch set two-pane. That is the
adaptive layout working, not an inconsistency — see the CHANGELOG. adaptive layout working, not an inconsistency — see the CHANGELOG.
- [ ] The committed sets show browsing, a folder list, an image preview and storage usage. - [x] The phone set was re-shot on 2026-10-18 and now shows **browsing, a folder list, the photo
**None of them show search, undo, the trash or receiving a share** — four features the grid, storage usage, the sort sheet, the Copy to… picker, the trash (with its 24-hour window and
app now has. The existing shots stay accurate (no layout changed), so this is an Empty trash) and the compress dialog** — the last three are what M16-M20 added. **Still not
opportunity rather than a defect: two or three more captures would let the listing shown**: search, undo, and receiving a share. The picker shot is taken at the volume list on
advertise them. See `tools/make-store-screenshots.sh`. purpose: one level down it would publish the real phone's folder names, which the demo-library
rule above forbids.
- [ ] The tablet sets were **not** re-shot: the TV/tablet AVDs cannot boot on this machine (no KVM),
and the phone-resized path needs more navigation work. They stay accurate for the screens they
show (roots, folder list, image preview, storage usage) and should be regenerated on a machine
with KVM before the listing goes live.
## 8. Release tracks and pricing ## 8. Release tracks and pricing
+137 -9
View File
@@ -26,6 +26,12 @@ Legend: ✅ done · 🚧 in progress · ⏳ not started · 💡 candidate (propo
| M13 | Video thumbnails | ✅ | A video row shows **a frame of the video** instead of a film icon: images and videos take the same path through Coil, with the video request asking for a frame a second in. One dependency — `coil-video` at the Coil version already pinned, whose POM adds only coil-core/stdlib/core-ktx — the platform's own `MediaMetadataRetriever` behind it, **no new permission** (no `READ_MEDIA_VIDEO`), and the decoder registered **explicitly** against an `ImageLoader` in `FileManagerApplication` — because R8 strips `coil-video`'s ServiceLoader entry from a release build, which would otherwise have left frames decoding in debug and quietly falling back to icons for real users. A decode that fails settles on the icon rather than an empty square. Verified on the phone against two purpose-made clips and a real video of the device's own, with the demo library's stand-ins falling back as intended, and **re-verified on the release APK**. **324 JVM tests** | | M13 | Video thumbnails | ✅ | A video row shows **a frame of the video** instead of a film icon: images and videos take the same path through Coil, with the video request asking for a frame a second in. One dependency — `coil-video` at the Coil version already pinned, whose POM adds only coil-core/stdlib/core-ktx — the platform's own `MediaMetadataRetriever` behind it, **no new permission** (no `READ_MEDIA_VIDEO`), and the decoder registered **explicitly** against an `ImageLoader` in `FileManagerApplication` — because R8 strips `coil-video`'s ServiceLoader entry from a release build, which would otherwise have left frames decoding in debug and quietly falling back to icons for real users. A decode that fails settles on the icon rather than an empty square. Verified on the phone against two purpose-made clips and a real video of the device's own, with the demo library's stand-ins falling back as intended, and **re-verified on the release APK**. **324 JVM tests** |
| M14 | Batch rename with sequence continuation | ✅ | Selecting more than one file and choosing Rename opens a **pattern** dialog: a name, a start number, and a live preview of the names it will produce. `core/BatchRename` plans the whole batch before a single file moves and returns one of three answers — **Ready**, **Blocked** (naming the target the folder already holds) or **NothingToDo** — with the deliberate absence of a fourth: a batch that renamed nine of twelve and stopped would leave the user to work out which nine. The numbering **continues the folder's own series** `nextNumber` from the highest `base (n)` it finds, which is the market survey's most-helpful complaint answered by name; the extension is kept per file, the series is counted across extensions, and continuing beats filling the first gap. `SelectionBar` now offers Rename to any selection (one file keeps the name dialog, several get the pattern one), and the batch's renames are **one** `Undo.Relocate` step. The same commit hardens the single rename: `core/FileNames.isUsableName` refuses a name that is not one path segment, because `notes/final.txt` was being resolved as a path and **moved** the file instead of renaming it. **350 JVM tests** (26 added) | | M14 | Batch rename with sequence continuation | ✅ | Selecting more than one file and choosing Rename opens a **pattern** dialog: a name, a start number, and a live preview of the names it will produce. `core/BatchRename` plans the whole batch before a single file moves and returns one of three answers — **Ready**, **Blocked** (naming the target the folder already holds) or **NothingToDo** — with the deliberate absence of a fourth: a batch that renamed nine of twelve and stopped would leave the user to work out which nine. The numbering **continues the folder's own series** `nextNumber` from the highest `base (n)` it finds, which is the market survey's most-helpful complaint answered by name; the extension is kept per file, the series is counted across extensions, and continuing beats filling the first gap. `SelectionBar` now offers Rename to any selection (one file keeps the name dialog, several get the pattern one), and the batch's renames are **one** `Undo.Relocate` step. The same commit hardens the single rename: `core/FileNames.isUsableName` refuses a name that is not one path segment, because `notes/final.txt` was being resolved as a path and **moved** the file instead of renaming it. **350 JVM tests** (26 added) |
| M15 | Favourites | ✅ | A star in the app bar of any folder, and a **Favourites** section on the home screen above the libraries — absent while empty, so a first-time user still meets the libraries first. `data/BookmarkStore` + `SqliteBookmarkStore` keep one path per row in their own database: a **reference, never a copy**, so the list costs one query and no filesystem work. `BrowserUiState.Bookmark` carries an `exists` flag, and a folder that has gone is **kept and marked** rather than deleted — an unmounted card and a deleted folder are the same thing from here — with opening re-checked at that moment so the answer is a message instead of an empty listing. The row's filled star is the removal (the mark that says "favourite" is the thing you tap to stop it being one), there is no star in a library or on the root screen, and no `Undo` for a bookmark because that type is "the last change to the filesystem" and a favourite is not one. **371 JVM tests** (16 added) | | M15 | Favourites | ✅ | A star in the app bar of any folder, and a **Favourites** section on the home screen above the libraries — absent while empty, so a first-time user still meets the libraries first. `data/BookmarkStore` + `SqliteBookmarkStore` keep one path per row in their own database: a **reference, never a copy**, so the list costs one query and no filesystem work. `BrowserUiState.Bookmark` carries an `exists` flag, and a folder that has gone is **kept and marked** rather than deleted — an unmounted card and a deleted folder are the same thing from here — with opening re-checked at that moment so the answer is a message instead of an empty listing. The row's filled star is the removal (the mark that says "favourite" is the thing you tap to stop it being one), there is no star in a library or on the root screen, and no `Undo` for a bookmark because that type is "the last change to the filesystem" and a favourite is not one. **371 JVM tests** (16 added) |
| M16 | Copy to… / Move to… | ✅ | A destination picker behind the selection bar's overflow — volumes, then folders one level at a time, with Up and the trail above them — that copies or moves **without leaving the folder you are in**. The selection survives a copy, so a second destination is two taps; a move clears it. Conflicts ask what a paste asks, naming the picked folder; a copy answers "Copied to *folder*" with **Show**. Detailed below |
| M17 | The mark of a change | ✅ | A dot on the rows an operation produced, spent by the next read of that folder. In memory, per folder: no timer, no watcher, no badge. `BrowserUiState.changed` + `markChanged` on every operation that creates something; the dot is drawn by `MarkOfChange` in both list and grid, with a content description TalkBack reads. **7 tests** (4 view model, 3 Compose) |
| M18 | Store-only archives | ✅ | Compressing asks two things: the name, and whether to compress. Off stores the files as they are — `Deflater.NO_COMPRESSION`, one pass — which is what a bulk copy off the phone actually wants. A `STORED` entry would need each file's size and CRC before its header, i.e. reading everything twice. **4 tests** |
| M19 | The trash says what it does | ✅ | The trash states its window ("Deleted files are kept for 24 hours") and offers **Empty trash** behind one confirmation; opening the trash sweeps expired batches, so the 24-hour retention no longer waits for the next delete to run. **4 tests** |
| M20 | Launcher shortcuts | ✅ | Images, Recent and Trash as static shortcuts — three intents with a route extra, `core/ShortcutRoute` answering `null` for anything it does not know. Favourites was dropped from the plan: it is a section of the home screen, not a view. **3 tests** |
| M21 | Android TV | ⏳ | Specified below and deliberately not started: its acceptance needs a TV device pass this machine cannot provide. |
## Key decisions ## Key decisions
@@ -64,8 +70,14 @@ would no longer have.
## The queue after 1.0 ## The queue after 1.0
Ordered by what it protects, not by what is fun. Nothing here is scheduled; the first two are what a Ordered by what it protects, not by what is fun. **Four of the five items are done** — thumbnails, the
release should not go out without. scaling numbers (which turned into progressive listing), Copy to… / Move to…, and the CI benchmark. What is
left is the baseline profile's *measurement*, which needs a physical API 33+ device and cannot be finished
on this machine; everything else in the list says what it produced.
**M17–M20** come from the same survey's remaining gaps and are implemented (the change mark, store-only
archives, a trash that says what it does, launcher shortcuts). **M21** (Android TV) is specified and
deliberately not started: its acceptance needs a TV device pass this machine cannot provide.
1. **Baseline profile** — **generated and committed**: `app/src/main/baseline-prof.txt` is bundled in the 1. **Baseline profile** — **generated and committed**: `app/src/main/baseline-prof.txt` is bundled in the
release APK, written by the `:baselineprofile` module. What remains is its *measurement*: collection release APK, written by the `:baselineprofile` module. What remains is its *measurement*: collection
@@ -78,18 +90,30 @@ release should not go out without.
while decoding, and the image loader's caches are decided explicitly — memory only at 15 % of the heap, while decoding, and the image loader's caches are decided explicitly — memory only at 15 % of the heap,
no disk cache. The device pass is in [EDGE_CASE_TESTING](EDGE_CASE_TESTING.md): 6 200 files with 300 no disk cache. The device pass is in [EDGE_CASE_TESTING](EDGE_CASE_TESTING.md): 6 200 files with 300
images and a folder of 300 images, correct and stable, no crash or OOM. A 20 000-*image* folder is images and a folder of 300 images, correct and stable, no crash or OOM. A 20 000-*image* folder is
still unmeasured, and jank on this screen needs a device that reports frame durations. still unmeasured; jank on the screen is measurable now that both the phone run and the CI emulator
3. **The scaling numbers** — `./tools/benchmark-fixture.sh --count 20000` and the existing benchmarks: report `frameDurationCpuMs` (see [PERFORMANCE](PERFORMANCE.md)), but no test drives the photo grid yet.
answers whether a full SD card is a performance problem before a user with one finds out. 3. **The scaling numbers** — **done**: 1 000 → 12–14 frames to open, 5 000 → 41, 20 000 → 184 with a 598
outlier; the outlier was investigated and the real fix was progressive listing (200-entry batches,
O(n+k) merge), after which 20 000 files opens in **10–16 frames** with a 32–48 max across two runs. The
whole suite at that size, and what search costs there, is in [PERFORMANCE](PERFORMANCE.md).
4. **Copy to… / Move to… (M16)** — **done**: the selection bar's overflow opens a folder picker (volumes, 4. **Copy to… / Move to… (M16)** — **done**: the selection bar's overflow opens a folder picker (volumes,
then folders one level at a time, Up and the trail above them) and confirming copies or moves into the then folders one level at a time, Up and the trail above them) and confirming copies or moves into the
picked folder without leaving the current one. The selection survives a copy so a second destination is picked folder without leaving the current one. The selection survives a copy so a second destination is
two taps; a move clears it. Conflicts ask the same question as a paste, naming the picked folder. Seven two taps; a move clears it. Conflicts ask the same question as a paste, naming the picked folder. Seven
tests cover the verbs, the picker's walk, folders-only listing, the conflict target, cancellation, and tests cover the verbs, the picker's walk, folders-only listing, the conflict target, cancellation, and
the selection rule. **Not done**: the "copied to X — Show" message with a jump to the destination; the the selection rule. Driven on the phone for both verbs (see `EDGE_CASE_TESTING.md`), which is what caught
copy reports itself the way a paste does. the picker naming internal storage by its raw name `0`. A copy into a picked folder says **"Copied to
5. **A CI run of the benchmarks on an emulator** — removes the phone from the loop and reports <folder>"** and offers **Show**, which opens that folder — the destination's label resolved the way
`frameDurationCpuMs`, which this device cannot. breadcrumbs are, so a volume root reads *Internal storage* rather than `0`. A move keeps the undoable
message instead, because its sources are gone.
5. **A CI run of the benchmarks on an emulator** — **done**: `.github/workflows/benchmark.yml` runs the four
benchmarks on API 35 (`reactivecircus/android-emulator-runner`, `google_apis`, x86_64, SwiftShader) on
demand and every Monday, installs the app and resets its compilation before instrumenting it, pulls the
JSON, and publishes `tools/benchmark-report.py`'s table on the run page — failing the job if
`frameDurationCpuMs` is missing, since that metric is why the job exists. While wiring it up, the
phone's own JSON from the progressive-listing run turned out to contain `frameDurationCpuMs` and
`frameOverrunMs` after all (P50 13.9 ms / 19.0 ms for the 1 000-file open), so `PERFORMANCE.md`'s "counts
only" finding was a property of the earlier runs, not of the device; corrected there.
### M16 — Copy to… / Move to… ### M16 — Copy to… / Move to…
@@ -117,3 +141,107 @@ destination picker.
**Not in scope**: drag and drop, a two-pane phone layout, remembering recent destinations. **Not in scope**: drag and drop, a two-pane phone layout, remembering recent destinations.
### M17 — The mark of a change
**What**: the rows an operation created carry a dot until the folder is read again, in both the list and the
grid.
**Why this shape**: the survey's 3.6.5 ("temporarily highlight new files with a dot after file operations")
answers an obvious question — *what did that 4 GB copy just do?* — and it got sharper with M16, because a copy
can now land in a folder the user is not looking at. The dot is a **set of paths the view model marks when an
operation lands**, not a timestamp on every row: no timer, no background job, and "temporarily" means "until
you see the folder again". The marks live in memory, so a restart forgets them — the same lifetime as the
clipboard, and for the same reason.
**Acceptance criteria**
- Copying, moving, compressing, extracting, renaming and creating a folder or file mark what they produced.
- The dot is drawn in the list and in the grid and carries a content description, so TalkBack says it and a
Compose test can find it.
- Opening the folder again clears its marks; opening a *different* folder does not disturb them.
- Tests: a copy into the current folder marks the copy and no untouched row; a copy into another folder marks
it there; re-opening clears.
**Not in scope**: catching files that appear while the folder is open (that needs a watcher), a notification
or a badge on the home screen.
### M18 — Store-only archives
**What**: compressing asks two things — the name, and whether to compress — because the survey's most
enthusiastic review is a 150 GB push to a PC, and that push is faster as one file that was cheap to build.
**Why this shape**: we refuse `INTERNET`, so their FTP-server answer is out; what is left is to make the file
that leaves as cheap as possible. `Deflater.NO_COMPRESSION` does that in one pass. A `STORED` zip entry would
be more literal and needs each file's size and CRC *before* the entry header is written, i.e. reading every
file twice — slower than the deflate it avoids.
**Acceptance criteria**
- `ArchiveEngine.createZip` takes the choice; the archive is a valid zip either way and extracts to identical
bytes.
- The dialog opens on "compress contents" and does not remember the last answer.
- Tests: both variants round-trip; the uncompressed one is measurably larger; the view model passes the flag.
**Not in scope**: a remembered preference, an estimated time, choosing a compression *level*.
### M19 — The trash says what it does
**What**: the trash screen states the window (24 hours) and offers **Empty trash**; the expiry sweep runs when
the trash is opened, not only after the next delete.
**Why this shape**: the retention already exists (`Trash.RETENTION_HOURS`) and is invisible, and
`purgeExpired` runs *after staging* — so a user who deletes once and never again keeps a day-old batch
forever. Those are the two halves of "why is my storage full" that the app itself can answer. Making the
window configurable would need a settings surface this app does not have; saying what it is costs nothing.
**Acceptance criteria**
- Opening the trash sweeps expired batches first, and the screen says how long items are kept.
- **Empty trash** asks once, then deletes every batch for good — it is the one destructive action in the app
with no undo, because that is what emptying means.
- Tests: an expired batch is gone after opening, a fresh one survives, emptying removes all and leaves the
screen saying it is empty.
**Not in scope**: a per-item permanent delete, a configurable window, a size cap.
### M20 — Launcher shortcuts
**What**: long-press the app icon → **Images**, **Recent**, **Trash**.
**Why this shape**: static shortcuts need no permission and no database — three intents with an extra, mapped
to views that are otherwise two or three taps deep. It is the cheapest route to the screens the survey says
people install the app for.
**Recent, not Favourites** — the one change from the proposal above. Favourites is a *section of the home
screen* rather than a view of its own, so a shortcut to it would open the home screen and promise a section
that is absent when nothing is starred. Recent is a library with its own name and its own state, so the
shortcut opens exactly what it says.
**Acceptance criteria**
- Three shortcuts in `res/xml/shortcuts.xml`; each opens the app directly at that view, and back from there
behaves like any other entry.
- An unknown or absent extra is ignored, so an old shortcut cannot crash a new build.
- Tests: the route parser maps the three names and returns `null` for anything else; each route opens the
right view.
**Not in scope**: dynamic shortcuts built from favourites, deep links to a path.
### M21 — Android TV (specified, not started)
**What**: a leanback-capable build — banner, launcher entry, and the whole browser and every dialog reachable
with a d-pad.
**Why this shape, and why it is not done**: Android TV is the only genuinely *new market* the survey names that
costs no permission, and it is also the one milestone whose acceptance cannot be met on this machine — there
is no TV AVD here and no KVM to run one at a usable speed. A half-tested TV build reviews worse than no TV
build, which is the survey's own lesson about the competitor's timeouts, so the plan is written down and the
work waits for a device.
**Acceptance criteria (when it starts)**: `LEANBACK_LAUNCHER` intent filter and a banner; focus traversal
through the browser, the selection bar, the transfer picker and every dialog; no touch-only affordance (long
press and double tap need a d-pad equivalent); a TV emulator pass recorded in [EDGE_CASE_TESTING](EDGE_CASE_TESTING.md).
**Not in scope**: TV-specific layouts, gamepad support, a screensaver.
+5
View File
@@ -34,6 +34,11 @@ Play's slots, and what each needs:
| 7-inch tablet | 4+ recommended | `screenshots/tablet-7in/` — 1200×1920 | A tablet frame is already inside the 2:1 cap, so 0 px of crop | | 7-inch tablet | 4+ recommended | `screenshots/tablet-7in/` — 1200×1920 | A tablet frame is already inside the 2:1 cap, so 0 px of crop |
| 10-inch tablet | 4+ recommended | `screenshots/tablet-10in/` — 2560×1600 | Landscape profile (matches the `tablet10` AVD); Play accepts either orientation | | 10-inch tablet | 4+ recommended | `screenshots/tablet-10in/` — 2560×1600 | Landscape profile (matches the `tablet10` AVD); Play accepts either orientation |
**What the phone set shows** (eight slots, the maximum): the home screen, a folder listing, the photo
grid, storage usage, the sort sheet, the **Copy to… picker**, the **trash** with its 24-hour window,
and the **compress dialog**. The last three are M16-M20's work; the picker is shot at the volume list
so it names no folder that exists on the real device.
### The library the shots are taken over ### The library the shots are taken over
**Never shoot over a real device's storage.** Published screenshots are public, and a file **Never shoot over a real device's storage.** Published screenshots are public, and a file
Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 152 KiB

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 120 KiB

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 161 KiB

+163
View File
@@ -0,0 +1,163 @@
#!/usr/bin/env python3
"""Turn macrobenchmark's JSON into a table a human reads, and say when the jank metric is missing.
./tools/benchmark-report.py benchmark-results # after `adb pull`
./tools/benchmark-report.py --require-frame-duration results/
Macrobenchmark writes one `*-benchmarkData.json` per run into the *test* app's media directory:
/sdcard/Android/media/de.softwareapp_hb.filemanager.benchmark/
and it has two kinds of number in it, which mean different things and are therefore kept apart:
* `metrics` — one value per iteration. `frameCount` is how many frames an interaction took: a length,
not a speed.
* `sampledMetrics` — many values per iteration, summarised as percentiles. `frameDurationCpuMs` (how
long each frame took) and `frameOverrunMs` (how far past its deadline it ran) are the jank numbers.
This phone reports `frameCount` in the first group and, on some runs, `frameDurationCpuMs` in the
second; whether the second group has the jank metric is exactly what a CI emulator run is for, so
`--require-frame-duration` makes its absence a failure rather than a footnote.
"""
from __future__ import annotations
import argparse
import glob
import json
import os
import sys
def files_in(paths: list[str]) -> list[str]:
"""Every `*-benchmarkData.json` under the given files and directories, in a stable order."""
found: list[str] = []
for path in paths:
if os.path.isdir(path):
found += glob.glob(os.path.join(path, "**", "*.json"), recursive=True)
else:
found.append(path)
return sorted(set(found))
def load(path: str) -> dict | None:
"""The run in [path], or `None` when the file is not macrobenchmark output."""
try:
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
except (OSError, json.JSONDecodeError):
return None
return data if isinstance(data, dict) and "benchmarks" in data else None
def device_line(context: dict) -> str:
build = context.get("build", {})
sdk = build.get("version", {}).get("sdk")
name = " ".join(part for part in (build.get("brand"), build.get("model")) if part)
fingerprint = build.get("fingerprint", "")
# The fingerprint is the honest identifier: same model, different build, different numbers.
return f"{name} (API {sdk}) — `{fingerprint}`" if fingerprint else f"{name} (API {sdk})"
def number(value: float) -> str:
"""A value with as much precision as it needs: counts are whole, milliseconds are not."""
return str(int(value)) if float(value).is_integer() else f"{value:.1f}"
def report(data: dict) -> tuple[list[str], bool]:
"""Markdown lines for one run, and whether it carried per-frame timings."""
lines: list[str] = []
context = data.get("context", {})
lines.append(f"**Device**: {device_line(context)}")
lines.append(f"**Compilation**: `{context.get('compilationMode', 'unknown')}`")
lines.append("")
benchmarks = data.get("benchmarks", [])
has_frame_duration = any("frameDurationCpuMs" in b.get("sampledMetrics", {}) for b in benchmarks)
counted = sorted((b for b in benchmarks if b.get("metrics")), key=lambda b: b["name"])
if counted:
# One value per iteration: `frameCount` is a length in frames, `timeToInitialDisplayMs` a
# duration. They share a table because they are read the same way, but the unit is per row.
lines.append("### One value per iteration")
lines.append("")
lines.append("| benchmark | metric | median | min | max | iterations |")
lines.append("|---|---|---|---|---|---|")
for benchmark in counted:
for metric, stats in sorted(benchmark["metrics"].items()):
runs = len(stats.get("runs", []))
unit = "frames" if metric == "frameCount" else "ms"
lines.append(
f"| `{benchmark['name']}` | {metric} | {number(stats['median'])} {unit} | "
f"{number(stats['minimum'])} | {number(stats['maximum'])} | {runs} |",
)
lines.append("")
sampled = sorted((b for b in benchmarks if b.get("sampledMetrics")), key=lambda b: b["name"])
if sampled:
lines.append("### Per-frame timing")
lines.append("")
lines.append("| benchmark | metric | P50 | P90 | P99 |")
lines.append("|---|---|---|---|---|")
for benchmark in sampled:
for metric, stats in sorted(benchmark["sampledMetrics"].items()):
lines.append(
f"| `{benchmark['name']}` | {metric} | {number(stats['P50'])} ms | "
f"{number(stats['P90'])} ms | {number(stats['P99'])} ms |",
)
lines.append("")
if not has_frame_duration:
lines.append("> No `frameDurationCpuMs` in this run: the device reported frame counts only, so "
"there is no jank number here — only how many frames each interaction took.")
lines.append("")
total = sum(b.get("totalRunTimeNs", 0) for b in benchmarks) / 1e9
plural = "benchmark" if len(benchmarks) == 1 else "benchmarks"
lines.append(f"_{len(benchmarks)} {plural}, {total:.0f} s of measurement._")
return lines, has_frame_duration
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"paths",
nargs="*",
help="files or directories of macrobenchmark JSON (default: benchmark-results)",
)
parser.add_argument(
"--require-frame-duration",
action="store_true",
help="exit non-zero unless the run reported frameDurationCpuMs",
)
arguments = parser.parse_args()
paths = arguments.paths or ["benchmark-results"]
runs = [(path, data) for path in files_in(paths) if (data := load(path)) is not None]
if not runs:
print(f"benchmark-report: no macrobenchmark JSON in {', '.join(paths)}", file=sys.stderr)
return 2
anywhere = False
for index, (path, data) in enumerate(runs):
if len(runs) > 1:
print(f"## {os.path.basename(path)}")
print()
lines, has_frame_duration = report(data)
anywhere = anywhere or has_frame_duration
print("\n".join(lines))
if index < len(runs) - 1:
print()
if arguments.require_frame_duration and not anywhere:
print(
"benchmark-report: frameDurationCpuMs is absent from every run, so no jank metric was "
"measured",
file=sys.stderr,
)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+4 -2
View File
@@ -50,8 +50,10 @@ if $release; then
# No device: this only proves that :benchmark still compiles against the app's benchmark build # No device: this only proves that :benchmark still compiles against the app's benchmark build
# type, which is the thing that rots silently between device runs. :baselineprofile is included for # type, which is the thing that rots silently between device runs. :baselineprofile is included for
# the same reason — its generator only runs on a device with API 33+, so nothing else would notice it # the same reason — its generator only runs on a device with API 33+, so nothing else would notice it
# breaking. # breaking. The task is spelled out in full because the baseline-profile plugin adds a `benchmark`
gradle :app:assembleBenchmark :benchmark:assembleDebug :baselineprofile:assembleBenchmark # flavour on top of the `benchmark` build type: `assembleBenchmark` is ambiguous between the flavour's
# two types, and Gradle refuses it — which is how this line came to be wrong without anything noticing.
gradle :app:assembleBenchmark :benchmark:assembleDebug :baselineprofile:assembleBenchmarkBenchmark
fi fi
printf '\n\033[1mverify: all checks passed\033[0m\n' printf '\n\033[1mverify: all checks passed\033[0m\n'