Compare commits

...

13 Commits

Author SHA1 Message Date
SoftwareApp ddcd68b4b7 Make Copy to… and Cut to… the selection bar's actions
verify / gate (push) Has been cancelled
verify / release (push) Has been cancelled
The selection bar offered Copy and Move, which only filled an in-app clipboard; the
destination picker then lived behind an overflow menu, and Paste in the top bar. That
made a copy a two-step detour through another folder - the thing M16's picker exists to
avoid.

- The bar's two verbs are now Copy to… and Cut to…, both opening the destination picker.
- The clipboard state, Paste here, and the overflow's duplicate Copy to… / Move to… are
  removed. The picker's cut title and confirm are Cut to… / Cut here.
- A copy still keeps the selection for a second destination; a cut clears it. Conflicts
  still ask before overwriting, naming the picked folder.
- Five clipboard tests are removed; the mark, restart and undo tests now use the picker.
  BrowserTopBar's search and overflow sections are extracted so its two new detekt
  findings are fixed rather than baselined.

Driven on the Xiaomi phone: Copy to… copied 120 x 16 MB through Internal storage ->
AADemo -> Target and reported Copied 121 items to Target; Cut to… moved file001.bin and
offered Undo; a name in the way raised Items already exist here; the top-bar overflow
has no Paste. The foreground-service video was re-recorded against the new bar at 16.1 s.

Verified: ./tools/verify.sh green, the code map current, 426 unit tests pass, and the
video decodes as H.264 1080x2400 with no audio.
2026-10-18 15:07:35 +02:00
SoftwareApp f9305d1070 Show the dataSync copy in a video, and answer its declaration
Play asks separately about FOREGROUND_SERVICE_DATA_SYNC: which use case, what
the service does, what the user loses if the task is deferred or interrupted,
and a video of the user triggering the work. The answers are now in section 5
of the release checklist, and the video is recorded.

The use case is Local processing -> Importing, exporting. Play's own chart
describes it as moving files from an SD card locally, which is what Paste and
Copy to... / Move to... do. The description (482/500 characters) names every
OperationKind - COPY, MOVE, DELETE, COMPRESS, EXTRACT - and states that the app
has no INTERNET permission, so network processing, backup/restore and media
transcoding are explicitly not ticked.

The video (18.0 s, captions burned in) shows a 1.8 GB synthetic folder copied to
another local folder: the selection and Copy, Paste here, the "Copying files"
notification with its progress bar, and the completed folder. It is cut from a
35.2 s raw take to remove the two waits; the target listing stays empty until
the copy completes, so those frames are progress rather than failure. The shade
was cleared of the phone's weather and Play cards first, leaving only Android's
generic USB cards, and every filename is synthetic.

Two traps are written down: do not press Up after Copy, because the selection
is already in AADemo and an extra Up makes Paste target AADemo ("Items already
exist here"); and open the shade only after cmd notification list shows the
app's notification, or the video shows no evidence of the service.

Verified: ./tools/verify.sh green, the code map current, links resolve, both
videos decode as H.264 1080x2400 with no audio, and the SRT has five cues.
2026-10-18 14:28:19 +02:00
SoftwareApp 9b8a32fbd6 Write the release notes, the permission answers, and the video
verify / gate (push) Has been cancelled
verify / release (push) Has been cancelled
Play asks three separate things before a file manager may keep All files
access: the What's new copy, a justification for why SAF and MediaStore cannot
carry it, and a short video of the permission in use. Writing them exposed two
stale claims and one privacy problem, so those are fixed here rather than
repeated.

- docs/RELEASE_NOTES.md holds the Console field at 450/500 characters, measured,
  and the longer announcement. The first release's copy leads with the claim no
  competitor makes (no ads, no INTERNET permission) and then proves the app is
  still a file manager.

- docs/PLAY_RELEASE_CHECKLIST.md section 5 holds the declaration answer at
  490/500 characters. It argues from what the Storage Access Framework and
  MediaStore cannot do - one picked tree, no volume enumeration or whole-device
  hierarchy, no arbitrary non-media files - and never from performance, which
  Google's wording rejects. Both APIs are named as already used where they can
  be, so the argument is not that they are useless.

- docs/PERMISSION_VIDEO.md and store-assets/video hold a 19.7 s captioned video
  recorded on the release build. The home-screen segment is cut because its
  library counts are the owner's real totals; the published copy resumes on the
  internal-storage listing. Also recorded: the emulator captures one frame in
  three seconds, and only appops set --uid ... deny brings the prompt back after
  Settings has granted the app-op.

- README and ROADMAP caught up with the build: the status stopped at M15, and
  the trash limitation still said there was no Empty trash and that expiry
  waited for the next delete, both changed in M19.

Verified: ./tools/verify.sh green, the code map current, the Play field measured
at 450 characters and the form answer at 490, and the video decoded as H.264
1080x2400, 19.666 s, no audio, with frames checked at the cut and the end state.
2026-10-18 13:59:50 +02:00
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
54 changed files with 2658 additions and 459 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
+3
View File
@@ -118,6 +118,9 @@ comment. `app/src/test/java/…/ProjectInvariantsTest.kt` holds the source-level
| `docs/EDGE_CASE_TESTING.md` | What was verified, on which device or AVD, and what was not | | `docs/EDGE_CASE_TESTING.md` | What was verified, on which device or AVD, and what was not |
| `docs/PERFORMANCE.md` | The numbers that exist, and the ones that deliberately do not yet | | `docs/PERFORMANCE.md` | The numbers that exist, and the ones that deliberately do not yet |
| `docs/PLAY_RELEASE_CHECKLIST.md` | Release only — work it in order | | `docs/PLAY_RELEASE_CHECKLIST.md` | Release only — work it in order |
| `docs/RELEASE_NOTES.md` | The Play **What's new** copy, at 500 characters, and the longer announcement |
| `docs/PERMISSION_VIDEO.md` | The declaration's 23-second video: what it shows, and how to re-shoot it |
| `docs/FGS_VIDEO.md` | The foreground-service video: the local copy, what was cut, and how to re-shoot it |
| `docs/COMPETITIVE_ANALYSIS.md`, `docs/MONETISATION.md`, `docs/STORE_LISTING.md` | Product context, pricing, and length-checked listing copy | | `docs/COMPETITIVE_ANALYSIS.md`, `docs/MONETISATION.md`, `docs/STORE_LISTING.md` | Product context, pricing, and length-checked listing copy |
| `PRIVACY.md` | The policy text the store listing points at | | `PRIVACY.md` | The policy text the store listing points at |
+93 -1
View File
@@ -12,13 +12,82 @@ upload needs a **higher `versionCode`** than every previous upload.
### Added ### Added
- **The release notes exist before the release does, and their length is measured.** `docs/RELEASE_NOTES.md`
holds the copy for the Play Console's **What's new** field — **450 characters**, against Play's 500
limit, counted rather than estimated — plus a longer announcement for a website or GitHub release.
The Console field renders neither Markdown nor bullets, so the copy is plain sentences; the first
release's text leads with the claim the survey says no competitor makes (no ads, no `INTERNET`
permission) and then proves it is still a file manager, because "private" without the verbs reads as
a promise rather than a product. The file also says how the next one is written: move `[Unreleased]`
into a version heading **first**, so the changelog and the notes cannot describe different builds.
Two stale claims were found while writing it and fixed rather than repeated in the announcement: the
README's known limitations still said the trash had no "empty it now" action and that expiry waited
for the next delete (both changed in M19), and its status paragraph still stopped at M15.
- **The Permissions Declaration Form's answer is written down, at 490 characters.** Section 5 of
[PLAY_RELEASE_CHECKLIST](docs/PLAY_RELEASE_CHECKLIST.md) now holds the justification for
`MANAGE_EXTERNAL_STORAGE`, measured against the form's 500-character field. It argues from what the
Storage Access Framework and `MediaStore` cannot do — a grant covers one picked tree, neither
enumerates volumes or presents a whole-device hierarchy, and `MediaStore` exposes media collections
rather than arbitrary files and folders — and never from speed, which Google's own wording rejects.
The app's existing SAF fallback and its single best-effort delete are named, so neither API is
dismissed as useless; it is only unable to carry the core purpose.
- **The permission-use video is recorded, captioned and cut for privacy.** Play's form also asks for a
short video of the permission in use; `store-assets/video/permission-use.mp4` is **19.7 s** at
1080×2400 with six burned-in English captions (no audio), beside an uncaptioned twin and the `.srt`.
It shows the app's prompt, Android's grant screen (the phone's system UI is German, translated in the
captions), internal storage, non-media documents and a folder created through the same permission.
The raw take also showed the home screen, whose library counts are the owner's real totals, so the
published copy **cuts that segment** and resumes on the internal-storage listing. That is a privacy
redaction, not an edit to the evidence, and both copies share it.
Two traps are written down with it: the emulator under software emulation captures **one frame in
three seconds**, so the video has to come from the phone; and after Settings grants the app-op, a
package-level `appops set … deny` leaves the UID mode allowed, so only
`appops set --uid … deny` brings the prompt back.
- **The `dataSync` foreground-service declaration is answered before the Console asks.** Section 5 of
[PLAY_RELEASE_CHECKLIST](docs/PLAY_RELEASE_CHECKLIST.md) now records the
`FOREGROUND_SERVICE_DATA_SYNC` answers: the use case is **Local processing → Importing, exporting**
(Play's own example is moving files from an SD card), the **482-character** functionality
description, and the deferred and interrupted impact. Every `OperationKind` is local — `COPY`,
`MOVE`, `DELETE`, `COMPRESS`, `EXTRACT` — and the app has no `INTERNET` permission, so network
processing, backup/restore and media transcoding are explicitly not ticked. It also records that
the required video is **not** the All files access one: [FGS_VIDEO](docs/FGS_VIDEO.md) holds a
**16.1 s** captioned take of the local copy — selection, **Copy to…**, the destination picker,
**Copy here**, the notification with its progress bar, and the completed folder — cut from a
41.0 s raw recording to remove the two waits, with every filename synthetic. The traps are written
down too: the picker recentres at every level, and open the shade only once the notification
exists and let it settle.
- **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
@@ -209,6 +278,20 @@ upload needs a **higher `versionCode`** than every previous upload.
### Changed ### Changed
- **Copy and Cut are now Copy to… and Cut to…, and the clipboard is gone.** The selection bar's
first two actions open the destination picker directly; choosing a folder starts the copy — or the
cut — without leaving the folder you are in. The separate clipboard state, **Paste here**, and the
overflow's duplicate **Copy to… / Move to…** entries are removed, and the picker's cut verb reads
**Cut to… / Cut here**. A copy still keeps the selection for a second destination; a cut still
clears it because those rows leave; conflicts still ask, naming the picked folder. Five tests that
exercised the clipboard were removed, and the mark, restart and undo tests now go through the
picker; the foreground-service video was re-recorded against the new bar. Driven on the Xiaomi
phone: Copy to… copied 120 × 16 MB and Cut to… moved one file, and the top-bar overflow has no
Paste.
Why: the clipboard made a copy a two-step detour through another folder, which is exactly what M16
built the picker to avoid. Keeping both would have left two meanings for “Copy” in one bar.
- **File thumbnails are bigger.** The leading visual in a list row went from 28 dp to 48 dp and - **File thumbnails are bigger.** The leading visual in a list row went from 28 dp to 48 dp and
the one in a grid cell from 40 dp to 96 dp, with the grid's minimum column width raised from the one in a grid cell from 40 dp to 96 dp, with the grid's minimum column width raised from
108 dp to 144 dp so the larger tile and the two-line name under it still fit. Neither size was 108 dp to 144 dp so the larger tile and the two-line name under it still fit. Neither size was
@@ -223,6 +306,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
+21 -23
View File
@@ -12,25 +12,23 @@ no advertising or tracking SDKs.
## Status ## Status
**M15 — favourites: done.** A star in any folder's app bar puts that folder on the home screen, above **M20 — launcher shortcuts: done.** Long-press the app icon for **Images**, **Recent** and **Trash**.
the libraries, where a folder that has gone is marked *not found* rather than silently dropped and Since the last release build: **M19** gave the trash its 24-hour window, **Empty trash** and a sweep on
the row's own star removes it. Before it: **M14 — renaming a batch** (selecting several files and open; **M18** let compression store files instead of squeezing them; **M17** put a dot on the rows an
choosing Rename opens a **pattern** dialog instead of the single-file one: one name, the number to operation produced; and **M16** added **Copy to… / Cut to…** with a destination picker that does not
start at, and a preview of the names take you out of the folder you are in. Before them: **M15 — favourites** (a star puts a folder on the
it will produce — and the numbering **carries on from the folder's own**, so `series (1)` and home screen), **M14 — batch rename** (one pattern, a start number, and a series that carries on from
`series (2)` already there make the next batch start at 3. A batch that cannot be done is refused the folder's own), **M13 — video thumbnails** (a frame of the video itself rather than a film icon),
before anything moves, naming the file in the way, and the whole batch is one undo step. Before it: **M12 — duplicate finder** (size, then the head of every candidate, then the survivors in full),
**M13 — video thumbnails** (a video row shows a frame of the video itself rather than a film icon — **M11 — library views** (Images, Videos, Audio, Documents, Archives and Recent, counted from the
the platform's own retriever, through Coil, with a frame taken a second in and the icon kept as the search index), and **M10 — store assets**: the app is named **Plain Files**, the icon and feature
fallback when a file cannot be decoded), **M12 — duplicate finder** (size, then the head of every graphic come from the app's own vectors, [docs/STORE_LISTING.md](docs/STORE_LISTING.md) holds
candidate, then the survivors in full), **M11 — library views** (a **Libraries** section on the length-checked listing copy, and [docs/RELEASE_NOTES.md](docs/RELEASE_NOTES.md) holds the copy for the
root screen — Images, Videos, Audio, Documents, Archives and Recent — whose rows open Console's **What's new** field.
ordinary listings of those files, each carrying a count from the search index), and **M10 — store
assets**: the app is named **Plain Files**, the icon and feature graphic come from the app's own Screenshots exist for 8 phone (1080×2160), 4 on a 7-inch tablet (1200×1920) and 4 on a 10-inch
vectors, and [docs/STORE_LISTING.md](docs/STORE_LISTING.md) holds length-checked listing copy. tablet (2560×1600). The phone set was re-shot on 2026-10-18 and covers M16-M20; the tablet sets
Screenshots exist for 5 phone (1080×2160), 4 on a 7-inch tablet (1200×1920) and 4 on a 10-inch **predate M11** and should be regenerated on a machine with KVM before the listing goes live
tablet (2560×1600) — but they **predate M11**, so the home screen in them is the old volume list and
they will need re-shooting, which the library views make a privacy question as well as a cosmetic one
([docs/STORE_LISTING.md](docs/STORE_LISTING.md)). ([docs/STORE_LISTING.md](docs/STORE_LISTING.md)).
## Tech stack ## Tech stack
@@ -179,10 +177,10 @@ UI.** Translated UI text has to be supplied in `values-<locale>/`.
- **The trash is a time window, not a bin you manage.** A delete stages the item in a hidden - **The trash is a time window, not a bin you manage.** A delete stages the item in a hidden
`.plainfiles-trash` folder on the same volume and keeps it for 24 hours; the **Trash** entry `.plainfiles-trash` folder on the same volume and keeps it for 24 hours; the **Trash** entry
in the overflow menu lists what is still there and puts a whole batch back. There is no in the overflow menu lists what is still there, puts a whole batch back, and offers **Empty
"empty it now" action — expired batches are swept the next time something is deleted — and a trash** for when the window is not what you want. Opening the trash sweeps what has expired,
name taken again in the meantime is never overwritten, so a restored item can arrive beside so retention no longer waits for the next delete. A name taken again in the meantime is never
the new one rather than replacing it. overwritten, so a restored item can arrive beside the new one rather than replacing it.
- **Where a trashed item came from is remembered in the app's own database**, not on the - **Where a trashed item came from is remembered in the app's own database**, not on the
volume. The staged files are the truth and the database is only an index, so the two are volume. The staged files are the truth and the database is only an index, so the two are
reconciled in both directions: an entry whose file has gone is not offered back, and a reconciled in both directions: an entry whose file has gone is not offered back, and a
+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 }
}
}
@@ -31,7 +31,7 @@ data class TransferItem(
) )
/** /**
* Turns "copy/paste these items into that folder" into a per-item decision, before a * Turns "copy or move these items into that folder" into a per-item decision, before a
* single byte is written. * single byte is written.
* *
* Doing this as pure logic keeps the awkward cases — a name colliding with another * Doing this as pure logic keeps the awkward cases — a name colliding with another
@@ -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))
Row(verticalAlignment = Alignment.CenterVertically) {
Text( Text(
text = entry.name, text = entry.name,
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
maxLines = 2, maxLines = 2,
overflow = TextOverflow.Ellipsis, 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
@@ -44,14 +45,72 @@ import de.softwareapp_hb.filemanager.core.FileEntry
import de.softwareapp_hb.filemanager.core.isUsableName import de.softwareapp_hb.filemanager.core.isUsableName
/** /**
* The **Copy to… / Move to…** picker. * 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… / Cut to…** picker.
* *
* A folder browser in a dialog: the volumes first, then one level of folders at a time, with the trail * A folder browser in a dialog: the volumes first, then one level of folders at a time, with the trail
* above them. Files are never offered — a file cannot be a destination — and the confirm button stays * above them. Files are never offered — a file cannot be a destination — and the confirm button stays
* disabled on the volume list, because "copy into the volume" is a folder, not the list of volumes. * disabled on the volume list, because "copy into the volume" is a folder, not the list of volumes.
* *
* The picker only chooses; the copy itself goes through the same plan and conflict question as a paste, * The picker only chooses; the copy itself goes through the same plan and conflict question as any
* with the picked folder as the target (see `BrowserViewModel.confirmTransferTo`). * other transfer, with the picked folder as the target (see `BrowserViewModel.confirmTransferTo`).
*/ */
@Composable @Composable
fun TransferToDialog( fun TransferToDialog(
@@ -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,
) )
@@ -125,11 +188,11 @@ fun TransferToDialog(
/** The dialog's title for the verb. */ /** The dialog's title for the verb. */
private fun titleFor(cut: Boolean): Int = private fun titleFor(cut: Boolean): Int =
if (cut) R.string.transfer_picker_move_title else R.string.transfer_picker_copy_title if (cut) R.string.transfer_picker_cut_title else R.string.transfer_picker_copy_title
/** The confirm button's label for the verb. */ /** The confirm button's label for the verb. */
private fun hereFor(cut: Boolean): Int = private fun hereFor(cut: Boolean): Int =
if (cut) R.string.transfer_picker_move_here else R.string.transfer_picker_copy_here if (cut) R.string.transfer_picker_cut_here else R.string.transfer_picker_copy_here
/** /**
* Renaming several files at once, with the numbering worked out before anything moves. * Renaming several files at once, with the numbering worked out before anything moves.
@@ -337,7 +400,7 @@ fun ConfirmDialog(
} }
/** /**
* The prompt shown when a paste would overwrite something. * The prompt shown when a transfer would overwrite something.
* *
* The engine refuses to guess ([ConflictPolicy.ASK] is surfaced rather than resolved), so * The engine refuses to guess ([ConflictPolicy.ASK] is surfaced rather than resolved), so
* the choice is offered here and then applied to the whole batch. * the choice is offered here and then applied to the whole batch.
@@ -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()
} }
} }
@@ -365,7 +397,6 @@ fun BrowserScreen(
searchScope = state.searchScope, searchScope = state.searchScope,
// The choice only exists when there is a folder to make it about. // The choice only exists when there is a folder to make it about.
scopeChoosable = state.path != null, scopeChoosable = state.path != null,
canPaste = state.clipboard?.isEmpty == false,
onUp = viewModel::navigateUp, onUp = viewModel::navigateUp,
onQuery = viewModel::setQuery, onQuery = viewModel::setQuery,
onSearchOpen = { open -> onSearchOpen = { open ->
@@ -390,7 +421,6 @@ fun BrowserScreen(
) )
}, },
onSort = { showSort = true }, onSort = { showSort = true },
onPaste = viewModel::paste,
onToggleBookmark = viewModel::toggleBookmark, onToggleBookmark = viewModel::toggleBookmark,
onRefresh = viewModel::refresh, onRefresh = viewModel::refresh,
onUsage = viewModel::openUsage, onUsage = viewModel::openUsage,
@@ -414,10 +444,8 @@ fun BrowserScreen(
if (state.isSelecting) { if (state.isSelecting) {
SelectionBar( SelectionBar(
state = state, state = state,
onCopy = { viewModel.copyToClipboard(state.selection.toList(), cut = false) },
onCut = { viewModel.copyToClipboard(state.selection.toList(), cut = true) },
onCopyTo = { viewModel.startTransferTo(cut = false) }, onCopyTo = { viewModel.startTransferTo(cut = false) },
onMoveTo = { viewModel.startTransferTo(cut = true) }, onCutTo = { viewModel.startTransferTo(cut = true) },
onDelete = { confirmDelete = state.selection.toList() }, onDelete = { confirmDelete = state.selection.toList() },
onDetails = { detailsFor = state.selectedEntries.firstOrNull() }, onDetails = { detailsFor = state.selectedEntries.firstOrNull() },
onRename = { onRename = {
@@ -430,7 +458,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,11 +610,17 @@ fun BrowserScreen(
) )
} }
state.conflict?.let { prompt -> state.compressRequest?.let { request ->
val transferPicker = state.transferPicker CompressDialog(
if (transferPicker != null) { initialName = request.name,
onConfirm = viewModel::confirmCompress,
onDismiss = viewModel::cancelCompress,
)
}
state.transferPicker?.let { picker ->
TransferToDialog( TransferToDialog(
picker = transferPicker, picker = picker,
onOpen = viewModel::pickerOpen, onOpen = viewModel::pickerOpen,
onUp = viewModel::pickerUp, onUp = viewModel::pickerUp,
onConfirm = viewModel::confirmTransferTo, onConfirm = viewModel::confirmTransferTo,
@@ -594,6 +628,7 @@ fun BrowserScreen(
) )
} }
state.conflict?.let { prompt ->
ConflictDialog( ConflictDialog(
prompt = prompt, prompt = prompt,
onChoice = { policy -> viewModel.resolveConflict(policy) }, onChoice = { policy -> viewModel.resolveConflict(policy) },
@@ -602,3 +637,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())
}
@@ -11,7 +11,6 @@ import androidx.compose.material.icons.filled.FileCopy
import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.PieChart import androidx.compose.material.icons.filled.PieChart
import androidx.compose.material.icons.filled.Public import androidx.compose.material.icons.filled.Public
import androidx.compose.material.icons.filled.ContentPaste
import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Sort import androidx.compose.material.icons.filled.Sort
@@ -42,6 +41,7 @@ import androidx.compose.ui.unit.dp
import de.softwareapp_hb.filemanager.R import de.softwareapp_hb.filemanager.R
/** The browser's app bar: title, up, the favourite star, and the search / sort / overflow actions. */ /** The browser's app bar: title, up, the favourite star, and the search / sort / overflow actions. */
@Suppress("LongParameterList")
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun BrowserTopBar( fun BrowserTopBar(
@@ -55,13 +55,11 @@ fun BrowserTopBar(
searchScope: SearchScope, searchScope: SearchScope,
/** Whether the scope is the user's to choose at all; see the note beside the toggle. */ /** Whether the scope is the user's to choose at all; see the note beside the toggle. */
scopeChoosable: Boolean, scopeChoosable: Boolean,
canPaste: Boolean,
onUp: () -> Unit, onUp: () -> Unit,
onQuery: (String) -> Unit, onQuery: (String) -> Unit,
onSearchOpen: (Boolean) -> Unit, onSearchOpen: (Boolean) -> Unit,
onSearchScope: () -> Unit, onSearchScope: () -> Unit,
onSort: () -> Unit, onSort: () -> Unit,
onPaste: () -> Unit,
onToggleBookmark: () -> Unit, onToggleBookmark: () -> Unit,
onRefresh: () -> Unit, onRefresh: () -> Unit,
onUsage: () -> Unit, onUsage: () -> Unit,
@@ -101,6 +99,81 @@ fun BrowserTopBar(
}, },
actions = { actions = {
if (searchOpen) { if (searchOpen) {
SearchFieldActions(
query = query,
searchScope = searchScope,
scopeChoosable = scopeChoosable,
searchField = searchField,
onQuery = onQuery,
onSearchScope = onSearchScope,
onSearchOpen = onSearchOpen,
)
} else {
if (canBookmark) {
IconButton(onClick = onToggleBookmark) {
Icon(
// An outline is the invitation and a filled star is the state, which is
// how a star behaves everywhere else it appears.
imageVector = if (bookmarked) Icons.Filled.Star else Icons.Filled.StarBorder,
contentDescription = stringResource(
if (bookmarked) {
R.string.browser_action_unbookmark
} else {
R.string.browser_action_bookmark
},
),
tint = if (bookmarked) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
)
}
}
IconButton(onClick = { onSearchOpen(true) }) {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = stringResource(R.string.browser_search_hint),
)
}
IconButton(onClick = onSort) {
Icon(
imageVector = Icons.Filled.Sort,
contentDescription = stringResource(R.string.browser_action_sort),
)
}
Box {
IconButton(onClick = { menuOpen = true }) {
Icon(
imageVector = Icons.Filled.MoreVert,
contentDescription = stringResource(R.string.browser_action_more),
)
}
BrowserOverflowMenu(
expanded = menuOpen,
onDismiss = { menuOpen = false },
onDuplicates = onDuplicates,
onUsage = onUsage,
onTrash = onTrash,
onRefresh = onRefresh,
)
}
}
},
)
}
/** The app bar while the search field is open: the field, its scope toggle, and the close action. */
@Composable
private fun SearchFieldActions(
query: String,
searchScope: SearchScope,
scopeChoosable: Boolean,
searchField: FocusRequester,
onQuery: (String) -> Unit,
onSearchScope: () -> Unit,
onSearchOpen: (Boolean) -> Unit,
) {
OutlinedTextField( OutlinedTextField(
value = query, value = query,
onValueChange = onQuery, onValueChange = onQuery,
@@ -153,81 +226,41 @@ fun BrowserTopBar(
contentDescription = stringResource(R.string.browser_search_clear), contentDescription = stringResource(R.string.browser_search_clear),
) )
} }
} else {
if (canBookmark) {
IconButton(onClick = onToggleBookmark) {
Icon(
// An outline is the invitation and a filled star is the state, which is
// how a star behaves everywhere else it appears.
imageVector = if (bookmarked) Icons.Filled.Star else Icons.Filled.StarBorder,
contentDescription = stringResource(
if (bookmarked) {
R.string.browser_action_unbookmark
} else {
R.string.browser_action_bookmark
},
),
tint = if (bookmarked) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
)
}
}
IconButton(onClick = { onSearchOpen(true) }) {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = stringResource(R.string.browser_search_hint),
)
}
IconButton(onClick = onSort) {
Icon(
imageVector = Icons.Filled.Sort,
contentDescription = stringResource(R.string.browser_action_sort),
)
}
Box {
IconButton(onClick = { menuOpen = true }) {
Icon(
imageVector = Icons.Filled.MoreVert,
contentDescription = stringResource(R.string.browser_action_more),
)
}
DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {
if (canPaste) {
DropdownMenuItem(
text = { Text(stringResource(R.string.browser_action_paste)) },
leadingIcon = { Icon(Icons.Filled.ContentPaste, contentDescription = null) },
onClick = { menuOpen = false; onPaste() },
)
} }
/** The app bar's overflow: the four actions that do not deserve a permanent icon. */
@Composable
private fun BrowserOverflowMenu(
expanded: Boolean,
onDismiss: () -> Unit,
onDuplicates: () -> Unit,
onUsage: () -> Unit,
onTrash: () -> Unit,
onRefresh: () -> Unit,
) {
DropdownMenu(expanded = expanded, onDismissRequest = onDismiss) {
DropdownMenuItem( DropdownMenuItem(
text = { Text(stringResource(R.string.browser_action_duplicates)) }, text = { Text(stringResource(R.string.browser_action_duplicates)) },
leadingIcon = { Icon(Icons.Filled.FileCopy, contentDescription = null) }, leadingIcon = { Icon(Icons.Filled.FileCopy, contentDescription = null) },
onClick = { menuOpen = false; onDuplicates() }, onClick = { onDismiss(); onDuplicates() },
) )
DropdownMenuItem( DropdownMenuItem(
text = { Text(stringResource(R.string.browser_action_disk_usage)) }, text = { Text(stringResource(R.string.browser_action_disk_usage)) },
leadingIcon = { Icon(Icons.Filled.PieChart, contentDescription = null) }, leadingIcon = { Icon(Icons.Filled.PieChart, contentDescription = null) },
onClick = { menuOpen = false; onUsage() }, onClick = { onDismiss(); onUsage() },
) )
DropdownMenuItem( DropdownMenuItem(
text = { Text(stringResource(R.string.browser_action_trash)) }, text = { Text(stringResource(R.string.browser_action_trash)) },
leadingIcon = { Icon(Icons.Filled.Delete, contentDescription = null) }, leadingIcon = { Icon(Icons.Filled.Delete, contentDescription = null) },
onClick = { menuOpen = false; onTrash() }, onClick = { onDismiss(); onTrash() },
) )
DropdownMenuItem( DropdownMenuItem(
text = { Text(stringResource(R.string.browser_action_refresh)) }, text = { Text(stringResource(R.string.browser_action_refresh)) },
leadingIcon = { Icon(Icons.Filled.Refresh, contentDescription = null) }, leadingIcon = { Icon(Icons.Filled.Refresh, contentDescription = null) },
onClick = { menuOpen = false; onRefresh() }, onClick = { onDismiss(); onRefresh() },
) )
} }
} }
}
},
)
}
/** /**
* How wide the search field may be. * How wide the search field may be.
@@ -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
@@ -31,10 +32,8 @@ enum class SearchScope {
EVERYWHERE, EVERYWHERE,
} }
/** What the user has cut or copied, waiting to be pasted somewhere. */ /** A compress waiting for its two answers: the archive's name, and whether to compress it. */
data class Clipboard(val paths: List<StoragePath>, val cut: Boolean) { data class CompressRequest(val paths: List<StoragePath>, val name: String)
val isEmpty: Boolean get() = paths.isEmpty()
}
/** /**
* 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.
@@ -42,18 +41,22 @@ data class Clipboard(val paths: List<StoragePath>, val cut: Boolean) {
* [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
} }
/** /**
* The destination picker behind **Copy to…** and **Move to…**. * The destination picker behind **Copy to…** and **Cut to…**.
* *
* The operation itself is [Clipboard] with an explicit target instead of "the folder I am in", so this * It holds what the picker needs to draw and nothing about the operation: [paths] is what was
* holds what the picker needs to draw and nothing about the copy: [paths] is what was selected when the * selected when the picker opened, [cut] says whether the chosen verb is Cut or Copy.
* picker opened, [cut] says which verb the user chose.
*/ */
data class TransferPicker( data class TransferPicker(
val paths: List<StoragePath>, val paths: List<StoragePath>,
@@ -61,11 +64,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,13 +91,28 @@ 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 transfer that hit existing names, waiting for the user to choose how to resolve it.
* *
* The engine deliberately does not answer conflicts ([ConflictPolicy.ASK] is surfaced * The engine deliberately does not answer conflicts ([ConflictPolicy.ASK] is surfaced
* rather than guessed), so this is where that decision lives. * rather than guessed), so this is where that decision lives.
@@ -134,7 +167,7 @@ data class DetailFocus(
*/ */
sealed interface Undo { sealed interface Undo {
/** /**
* Move each item back where it came from. Covers a rename and a pasted cut alike, * Move each item back where it came from. Covers a rename and a cut alike,
* because both are the same operation seen from different angles. * because both are the same operation seen from different angles.
*/ */
data class Relocate(val moves: List<UndoMove>) : Undo data class Relocate(val moves: List<UndoMove>) : Undo
@@ -286,9 +319,17 @@ data class BrowserUiState(
val selection: Set<StoragePath> = emptySet(), val selection: Set<StoragePath> = emptySet(),
/** 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, /**
/** The **Copy to… / Move to…** destination picker, when one is open. */ * 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… / Cut 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 selection 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,
@@ -490,12 +515,12 @@ class BrowserViewModel(
_state.update { state -> if (state.path == path) state.copy(freeBytes = free) else state } _state.update { state -> if (state.path == path) state.copy(freeBytes = free) else state }
} }
// ------------------------------------------------------- copy to… / move to… // ------------------------------------------------------- copy to… / cut to…
/** /**
* Opens the destination picker for the current selection. * Opens the destination picker for the current selection.
* *
* The same two verbs [paste] offers, except that the destination is chosen here instead of being * The two verbs the selection bar offers, with the destination chosen here instead of being
* whatever folder happens to be on screen — which is the point: copying into another folder no * whatever folder happens to be on screen — which is the point: copying into another folder no
* longer means leaving the one you are in, and because the selection stays, a second destination is * longer means leaving the one you are in, and because the selection stays, a second destination is
* two taps. * two taps.
@@ -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() {
@@ -527,9 +552,9 @@ class BrowserViewModel(
/** /**
* Copies — or moves — the selection into the folder the picker is showing. * Copies — or moves — the selection into the folder the picker is showing.
* *
* A name conflict asks exactly what a paste asks, and the prompt carries the picked folder, so the * A name conflict asks before overwriting, and the prompt carries the picked folder, so the answer
* answer applies to the right one. A copy leaves the selection in place, which is what makes a * applies to the right one. A copy leaves the selection in place, which is what makes a second
* second destination two taps; a move clears it, because those rows are about to go. * destination two taps; a move clears it, because those rows are about to go.
*/ */
fun confirmTransferTo() { fun confirmTransferTo() {
val picker = _state.value.transferPicker ?: return val picker = _state.value.transferPicker ?: return
@@ -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
@@ -743,10 +794,9 @@ class BrowserViewModel(
* *
* Deliberately narrow. A folder is worth coming back to — losing your place deep in a * Deliberately narrow. A folder is worth coming back to — losing your place deep in a
* tree is the most annoying thing an Android file manager can do — and a sort order or * tree is the most annoying thing an Android file manager can do — and a sort order or
* view mode that resets on every process death is just noise. Three things are left * view mode that resets on every process death is just noise. Two things are left
* out on purpose: the **search query**, because restoring one would hide the folder's * out on purpose: the **search query**, because restoring one would hide the folder's
* contents on launch with no visible cause; the **selection**, which is transient; and * contents on launch with no visible cause; and the **selection**, which is transient.
* the **clipboard**, because a paste that survived a reboot would be a nasty surprise.
*/ */
private fun restoredViewState(): BrowserUiState { private fun restoredViewState(): BrowserUiState {
val savedSortKey = savedState.get<String>(KEY_SORT_KEY) val savedSortKey = savedState.get<String>(KEY_SORT_KEY)
@@ -861,13 +911,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
// case worth waiting for — with the progress row above it saying why.
refresh?.join()
if (!currentCoroutineContext().isActive) return@launch
showIndexedResults(query, source) showIndexedResults(query, source)
}
_state.update { current -> _state.update { current ->
if (current.query != query) { if (current.query != query) {
@@ -889,7 +946,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 +984,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 +1065,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 +1417,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 +1470,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 +1491,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 +1654,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 +1751,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)
@@ -1742,40 +1924,6 @@ class BrowserViewModel(
_state.update { it.copy(scratch = null) } _state.update { it.copy(scratch = null) }
} }
// ---------------------------------------------------------------- clipboard
fun copyToClipboard(paths: List<StoragePath>, cut: Boolean) {
_state.update { it.copy(clipboard = Clipboard(paths, cut), selection = emptySet()) }
}
/**
* Paste the clipboard into the current directory.
*
* A clash is not resolved here: the plan is checked first and, if anything would be
* overwritten, the user is asked through [BrowserUiState.conflict].
*/
fun paste() {
val clipboard = _state.value.clipboard ?: return
val target = _state.value.path ?: return
val source = storage.activeSource() ?: return
viewModelScope.launch {
val conflicts = runCatching {
FileOperations(source)
.planTransfer(clipboard.paths, target, ConflictPolicy.ASK)
.count { it.action == TransferAction.ASK }
}.getOrDefault(0)
if (conflicts > 0) {
_state.update {
it.copy(conflict = ConflictPrompt(clipboard.paths, target, clipboard.cut, conflicts))
}
} else {
transfer(clipboard.paths, target, clipboard.cut, ConflictPolicy.KEEP_BOTH)
}
}
}
fun resolveConflict(policy: ConflictPolicy) { fun resolveConflict(policy: ConflictPolicy) {
val prompt = _state.value.conflict ?: return val prompt = _state.value.conflict ?: return
_state.update { it.copy(conflict = null) } _state.update { it.copy(conflict = null) }
@@ -1791,6 +1939,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 +1949,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) {
@@ -1815,13 +1965,17 @@ class BrowserViewModel(
notifier.stop() notifier.stop()
} }
_state.update { it.copy(loading = false, clipboard = if (cut) null else it.clipboard) } _state.update { it.copy(loading = false) }
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)
} }
@@ -1859,7 +2013,7 @@ class BrowserViewModel(
* Save the shared files into [folder] — wherever the user navigated to. * Save the shared files into [folder] — wherever the user navigated to.
* *
* Names come from the sending app where it offers one, and clashes go through the same * Names come from the sending app where it offers one, and clashes go through the same
* [NameAllocator] a paste does, so sharing the same file twice cannot overwrite the * [NameAllocator] a copy does, so sharing the same file twice cannot overwrite the
* first copy. * first copy.
*/ */
fun receiveInto(folder: StoragePath) { fun receiveInto(folder: StoragePath) {
@@ -1990,6 +2144,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 +2162,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 +2236,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 +2288,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 +2365,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 +2401,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 +2411,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,
), ),
) )
} }
@@ -1,13 +1,6 @@
package de.softwareapp_hb.filemanager.ui.browser package de.softwareapp_hb.filemanager.ui.browser
import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Box
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
@@ -23,7 +16,6 @@ import androidx.compose.material.icons.filled.ContentCut
import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.OpenInNew import androidx.compose.material.icons.filled.OpenInNew
import androidx.compose.material.icons.filled.SelectAll import androidx.compose.material.icons.filled.SelectAll
import androidx.compose.material.icons.filled.Share import androidx.compose.material.icons.filled.Share
@@ -86,10 +78,8 @@ fun StorageAccessPrompt(
@Suppress("LongParameterList") @Suppress("LongParameterList")
fun SelectionBar( fun SelectionBar(
state: BrowserUiState, state: BrowserUiState,
onCopy: () -> Unit,
onCut: () -> Unit,
onCopyTo: () -> Unit, onCopyTo: () -> Unit,
onMoveTo: () -> Unit, onCutTo: () -> Unit,
onDelete: () -> Unit, onDelete: () -> Unit,
onDetails: () -> Unit, onDetails: () -> Unit,
onRename: () -> Unit, onRename: () -> Unit,
@@ -127,43 +117,17 @@ fun SelectionBar(
.padding(start = 8.dp), .padding(start = 8.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
) { ) {
IconButton(onClick = onCopy) { IconButton(onClick = onCopyTo) {
Icon(Icons.Filled.ContentCopy, contentDescription = stringResource(R.string.browser_action_copy))
}
IconButton(onClick = onCut) {
Icon(Icons.Filled.ContentCut, contentDescription = stringResource(R.string.browser_action_cut))
}
/*
* Copy to… and Move to… are the same two verbs with a destination picker attached, so they sit
* behind one overflow button rather than adding two more icons to a bar that already scrolls.
*/
var destinationMenu by remember { mutableStateOf(false) }
Box {
IconButton(onClick = { destinationMenu = true }) {
Icon( Icon(
Icons.Filled.MoreVert, Icons.Filled.ContentCopy,
contentDescription = stringResource(R.string.browser_action_more), contentDescription = stringResource(R.string.browser_action_copy_to),
) )
} }
DropdownMenu( IconButton(onClick = onCutTo) {
expanded = destinationMenu, Icon(
onDismissRequest = { destinationMenu = false }, Icons.Filled.ContentCut,
) { contentDescription = stringResource(R.string.browser_action_cut_to),
DropdownMenuItem(
text = { Text(stringResource(R.string.browser_action_copy_to)) },
onClick = {
destinationMenu = false
onCopyTo()
},
) )
DropdownMenuItem(
text = { Text(stringResource(R.string.browser_action_move_to)) },
onClick = {
destinationMenu = false
onMoveTo()
},
)
}
} }
/* /*
* Rename is offered for any selection: one file is renamed by name and several by * Rename is offered for any selection: one file is renamed by name and several by
@@ -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),
) )
} }
} }
+37 -7
View File
@@ -105,16 +105,20 @@
<string name="browser_action_new_folder">New folder</string> <string name="browser_action_new_folder">New folder</string>
<string name="browser_action_sort">Sort</string> <string name="browser_action_sort">Sort</string>
<string name="browser_action_details">Details</string> <string name="browser_action_details">Details</string>
<string name="browser_action_copy">Copy</string> <!-- Compressing: the name, and whether to squeeze the contents. -->
<string name="browser_action_cut">Move</string> <string name="compress_dialog_title">Compress</string>
<string name="browser_action_paste">Paste here</string> <string name="compress_dialog_name">Archive name</string>
<!-- The two verbs that pick the destination instead of pasting into the folder on screen. --> <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 directly. -->
<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_cut_to">Cut to…</string>
<string name="transfer_picker_copy_title">Copy to…</string> <string name="transfer_picker_copy_title">Copy to…</string>
<string name="transfer_picker_move_title">Move to…</string> <string name="transfer_picker_cut_title">Cut to…</string>
<string name="transfer_picker_copy_here">Copy here</string> <string name="transfer_picker_copy_here">Copy here</string>
<string name="transfer_picker_move_here">Move here</string> <string name="transfer_picker_cut_here">Cut here</string>
<string name="transfer_picker_up">Up</string> <string name="transfer_picker_up">Up</string>
<string name="transfer_picker_cancel">Cancel</string> <string name="transfer_picker_cancel">Cancel</string>
<string name="transfer_picker_empty">No folders here</string> <string name="transfer_picker_empty">No folders here</string>
@@ -125,6 +129,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 +152,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 +262,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()
}
}
@@ -43,13 +43,11 @@ class BrowserTopBarTest {
searchOpen = searchOpen, searchOpen = searchOpen,
searchScope = SearchScope.FOLDER, searchScope = SearchScope.FOLDER,
scopeChoosable = true, scopeChoosable = true,
canPaste = false,
onUp = {}, onUp = {},
onQuery = {}, onQuery = {},
onSearchOpen = {}, onSearchOpen = {},
onSearchScope = {}, onSearchScope = {},
onSort = {}, onSort = {},
onPaste = {},
onToggleBookmark = {}, onToggleBookmark = {},
onRefresh = {}, onRefresh = {},
onUsage = {}, onUsage = {},
@@ -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,297 @@ 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 `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 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(downloads)
model.toggleSelection(downloads.child("a.txt"))
model.startTransferTo(cut = false)
model.pickerOpen(documents)
model.confirmTransferTo()
model.openDirectory(documents)
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()
@@ -1234,57 +1572,6 @@ class BrowserViewModelTest {
assertTrue(recordedNotifications.isEmpty()) assertTrue(recordedNotifications.isEmpty())
} }
@Test
fun `copy then paste duplicates into the current folder`() {
val model = viewModel()
model.openDirectory(root)
model.copyToClipboard(listOf(downloads.child("a.txt")), cut = false)
assertNotNull(model.state.value.clipboard)
model.openDirectory(documents)
model.paste()
assertTrue(storage.contains(documents.child("a.txt")))
assertTrue(storage.contains(downloads.child("a.txt")))
assertEquals(listOf(OperationKind.COPY), recordedNotifications)
assertNotNull(model.state.value.clipboard)
}
@Test
fun `cut then paste moves and clears the clipboard`() {
val model = viewModel()
model.openDirectory(root)
model.copyToClipboard(listOf(downloads.child("a.txt")), cut = true)
model.openDirectory(documents)
model.paste()
assertTrue(storage.contains(documents.child("a.txt")))
assertFalse(storage.contains(downloads.child("a.txt")))
assertEquals(listOf(OperationKind.MOVE), recordedNotifications)
assertNull(model.state.value.clipboard)
}
@Test
fun `a pasted name that already exists asks before overwriting`() {
val model = viewModel()
storage.addFile(documents.child("a.txt"), "already here")
model.openDirectory(root)
model.copyToClipboard(listOf(downloads.child("a.txt")), cut = false)
model.openDirectory(documents)
model.paste()
val prompt = model.state.value.conflict
assertNotNull(prompt)
assertEquals(1, prompt!!.conflicts)
assertEquals("already here", storage.contentOf(documents.child("a.txt")))
model.resolveConflict(ConflictPolicy.REPLACE)
assertEquals("first", storage.contentOf(documents.child("a.txt")))
assertNull(model.state.value.conflict)
}
@Test @Test
fun `without any grant the browser asks for a folder`() { fun `without any grant the browser asks for a folder`() {
location.setSource(null) location.setSource(null)
@@ -1430,18 +1717,16 @@ class BrowserViewModelTest {
} }
@Test @Test
fun `a selection and a clipboard do not survive a restart`() { fun `a selection does not survive a restart`() {
val saved = SavedStateHandle() val saved = SavedStateHandle()
viewModel(savedState = saved).apply { viewModel(savedState = saved).apply {
openDirectory(downloads) openDirectory(downloads)
toggleSelection(downloads.child("a.txt")) toggleSelection(downloads.child("a.txt"))
copyToClipboard(listOf(downloads.child("a.txt")), cut = false)
} }
val relaunched = viewModel(savedState = saved) val relaunched = viewModel(savedState = saved)
assertFalse(relaunched.state.value.isSelecting) assertFalse(relaunched.state.value.isSelecting)
assertNull(relaunched.state.value.clipboard)
} }
@Test @Test
@@ -1648,12 +1933,13 @@ class BrowserViewModelTest {
} }
@Test @Test
fun `undoing a cut-paste moves the item back`() { fun `undoing a cut to a chosen folder moves the item back`() {
val model = viewModel() val model = viewModel()
model.openDirectory(downloads) model.openDirectory(downloads)
model.copyToClipboard(listOf(downloads.child("a.txt")), cut = true) model.toggleSelection(downloads.child("a.txt"))
model.openDirectory(documents) model.startTransferTo(cut = true)
model.paste() model.pickerOpen(documents)
model.confirmTransferTo()
assertTrue(storage.contains(documents.child("a.txt"))) assertTrue(storage.contains(documents.child("a.txt")))
model.undo() model.undo()
@@ -1663,13 +1949,13 @@ class BrowserViewModelTest {
} }
@Test @Test
fun `a copy is not undoable, because nothing was changed`() { fun `a copy to a chosen folder is not undoable, because nothing was changed`() {
val model = viewModel() val model = viewModel()
model.openDirectory(root) model.openDirectory(downloads)
model.copyToClipboard(listOf(downloads.child("a.txt")), cut = false) model.toggleSelection(downloads.child("a.txt"))
model.openDirectory(documents) model.startTransferTo(cut = false)
model.pickerOpen(documents)
model.paste() model.confirmTransferTo()
assertNull(model.state.value.undo) assertNull(model.state.value.undo)
} }
@@ -3,7 +3,6 @@ package de.softwareapp_hb.filemanager.ui.browser
import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import de.softwareapp_hb.filemanager.core.FileEntry import de.softwareapp_hb.filemanager.core.FileEntry
import de.softwareapp_hb.filemanager.core.StoragePath import de.softwareapp_hb.filemanager.core.StoragePath
import de.softwareapp_hb.filemanager.ui.theme.FileManagerTheme import de.softwareapp_hb.filemanager.ui.theme.FileManagerTheme
@@ -44,10 +43,8 @@ class SelectionBarTest {
entries = entries, entries = entries,
selection = entries.map { it.path }.toSet(), selection = entries.map { it.path }.toSet(),
), ),
onCopy = {},
onCut = {},
onCopyTo = {}, onCopyTo = {},
onMoveTo = {}, onCutTo = {},
onDelete = {}, onDelete = {},
onDetails = {}, onDetails = {},
onRename = {}, onRename = {},
@@ -63,13 +60,11 @@ class SelectionBarTest {
} }
@Test @Test
fun `the destination verbs live in the overflow menu`() { fun `the destination verbs are on the bar`() {
bar(selected = 1) bar(selected = 1)
compose.onNodeWithContentDescription("More options").performClick() compose.onNodeWithContentDescription("Copy to…").assertExists()
compose.onNodeWithContentDescription("Cut to…").assertExists()
compose.onNodeWithText("Copy to…").assertExists()
compose.onNodeWithText("Move to…").assertExists()
} }
@Test @Test
+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>
+55 -25
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, 13853 lines - 37 test files, 426 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,12 +23,13 @@ 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) |
| `ThumbnailKey.kt` | 22 | The identity of a thumbnail: which file it came from, and which version of that file. ThumbnailKey | `ThumbnailKeyTest` (4) | | `ThumbnailKey.kt` | 22 | The identity of a thumbnail: which file it came from, and which version of that file. ThumbnailKey | `ThumbnailKeyTest` (4) |
| `Timestamps.kt` | 20 | Timestamps for the details sheet. Timestamps | - | | `Timestamps.kt` | 20 | Timestamps for the details sheet. Timestamps | - |
| `TransferPlanner.kt` | 105 | Turns "copy/paste these items into that folder" into a per-item decision, before a single byte is written. ConflictPolicy, TransferAction, TransferSource, TransferItem, TransferPlanner | `TransferPlannerTest` (5) | | `TransferPlanner.kt` | 105 | Turns "copy or move these items into that folder" into a per-item decision, before a single byte is written. ConflictPolicy, TransferAction, TransferSource, TransferItem, TransferPlanner | `TransferPlannerTest` (5) |
## data/ ## data/
@@ -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,20 +96,20 @@ 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` | 657 | 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` | 271 | The browser's app bar: title, up, the favourite star, and the search / sort / overflow actions. BrowserTopBar(), SearchFieldActions(), BrowserOverflowMenu(), 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` | 384 | One immutable description of everything the browser shows. ViewMode, SearchScope, 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` | 2566 | Drives the browser screen. BrowserViewModel, ArchivePreview | `BrowserViewModelTest` (112) |
| `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() | - |
| `IncomingRequest.kt` | 46 | What another app asked this one to do. IncomingRequest | - | | `IncomingRequest.kt` | 46 | What another app asked this one to do. IncomingRequest | - |
| `SelectionBar.kt` | 219 | The contextual action bar shown while entries are selected. StorageAccessPrompt(), SelectionBar() | `SelectionBarTest` (3) | | `SelectionBar.kt` | 183 | The contextual action bar shown while entries are selected. StorageAccessPrompt(), SelectionBar() | `SelectionBarTest` (3) |
| `SortSheet.kt` | 128 | Sort key, direction, hidden files and list/grid — all in one sheet. sortKeyLabel(), SortSheet() | - | | `SortSheet.kt` | 128 | Sort key, direction, hidden files and list/grid — all in one sheet. sortKeyLabel(), SortSheet() | - |
## ui/viewer/ ## ui/viewer/
@@ -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` (112)
- 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,28 @@ 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
- the message's undo action is the undo
- a move to a chosen folder offers undo rather than show
- 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
@@ -641,9 +674,6 @@ Every test name in the suite, by file: the fastest way to see whether something
- rename moves the entry to the new name - rename moves the entry to the new name
- delete removes the selected entries directly when the platform has no dialog - delete removes the selected entries directly when the platform has no dialog
- delete prefers the platform dialog and leaves the files alone until it returns - delete prefers the platform dialog and leaves the files alone until it returns
- copy then paste duplicates into the current folder
- cut then paste moves and clears the clipboard
- a pasted name that already exists asks before overwriting
- without any grant the browser asks for a folder - without any grant the browser asks for a folder
- a granted tree becomes the only root - a granted tree becomes the only root
- focusing a folder in the master pane lists it for the detail pane - focusing a folder in the master pane lists it for the detail pane
@@ -653,7 +683,7 @@ Every test name in the suite, by file: the fastest way to see whether something
- a focused volume previews the contents of that volume - a focused volume previews the contents of that volume
- the browsed folder and view settings survive a restart - the browsed folder and view settings survive a restart
- a search query is not restored, so the folder is not hidden on launch - a search query is not restored, so the folder is not hidden on launch
- a selection and a clipboard do not survive a restart - a selection does not survive a restart
- restarting on the roots screen stays on the roots screen - restarting on the roots screen stays on the roots screen
- search reaches into a subfolder, not just the one being browsed - search reaches into a subfolder, not just the one being browsed
- clearing the query brings the folder back - clearing the query brings the folder back
@@ -668,8 +698,8 @@ Every test name in the suite, by file: the fastest way to see whether something
- a filename cannot be a path - a filename cannot be a path
- a batch rename cannot be given a path either - a batch rename cannot be given a path either
- undoing a rename puts the old name back - undoing a rename puts the old name back
- undoing a cut-paste moves the item back - undoing a cut to a chosen folder moves the item back
- a copy is not undoable, because nothing was changed - a copy to a chosen folder is not undoable, because nothing was changed
- the undo handle is cleared once it has been used - the undo handle is cleared once it has been used
- a shared file is saved into the folder the user chose - a shared file is saved into the folder the user chose
- a shared file never overwrites one already in the folder - a shared file never overwrites one already in the folder
@@ -682,7 +712,7 @@ Every test name in the suite, by file: the fastest way to see whether something
### `ui/browser/SelectionBarTest.kt` (3) ### `ui/browser/SelectionBarTest.kt` (3)
- the destination verbs live in the overflow menu - the destination verbs are on the bar
- several files are offered a rename and not the details - several files are offered a rename and not the details
- a single file keeps both - a single file keeps both
@@ -692,4 +722,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`
+2 -2
View File
@@ -309,7 +309,7 @@ requested feature in the market leader, and the permission line is a claim it ca
| Duplicate finder | **No** | Explicitly requested, with an offer to pay. Pure local computation over a listing we can already do | | Duplicate finder | **No** | Explicitly requested, with an offer to pay. Pure local computation over a listing we can already do |
| Batch rename, including continuing an existing numbering sequence | **No** | **Closed in M14.** Several files are renamed to one name with a number after each, and the numbering continues the folder's own series, so the "Ice (3), Ice (4)" wish from the top complainant is what the dialog now defaults to | | Batch rename, including continuing an existing numbering sequence | **No** | **Closed in M14.** Several files are renamed to one name with a number after each, and the numbering continues the folder's own series, so the "Ice (3), Ice (4)" wish from the top complainant is what the dialog now defaults to |
| Bookmarks | **No** | **Closed in M15.** A star on any folder puts it in **Favourites** on the home screen, above the libraries; a folder that has gone is kept and marked rather than dropped | | Bookmarks | **No** | **Closed in M15.** A star on any folder puts it in **Favourites** on the home screen, above the libraries; a folder that has gone is kept and marked rather than dropped |
| "Copy again" / "Return to source folder" after a paste | **No** | **Closed as superseded.** Both exist because their flow makes you leave the source folder to paste; [ROADMAP](ROADMAP.md) specifies **Copy to… / Move to… (M16)** instead, which never leaves the source — so the selection is still there for the next destination and there is no "back to source" to offer | | "Copy again" / "Return to source folder" after a paste | **No** | **Closed as superseded.** Both exist because their flow makes you leave the source folder to paste; [ROADMAP](ROADMAP.md) specifies **Copy to… / Cut to… (M16)** instead, which never leaves the source — so the selection is still there for the next destination and there is no "back to source" to offer |
| New-file dot after an operation | **No** | Their 3.6.5. Cheap, and it answers "what did that 4 GB copy just do?" | | New-file dot after an operation | **No** | Their 3.6.5. Cheap, and it answers "what did that 4 GB copy just do?" |
| Date-format setting | **No** | We deliberately leave the timestamp pattern unlocalised (README); a *user setting* is a different thing | | Date-format setting | **No** | We deliberately leave the timestamp pattern unlocalised (README); a *user setting* is a different thing |
| Music-player engine switch, video gesture toggle | **No** | Deep settings; low priority for a first release | | Music-player engine switch, video gesture toggle | **No** | Deep settings; low priority for a first release |
@@ -357,7 +357,7 @@ In the ROADMAP's own vocabulary (💡 = candidate, proposed, not scheduled; ✅
Ice (2)" case that the top complainant names. Ice (2)" case that the top complainant names.
4. ✅ **Bookmarks** — shipped as **M15**. ~~💡 "Return to source folder" and "Copy again" after a 4. ✅ **Bookmarks** — shipped as **M15**. ~~💡 "Return to source folder" and "Copy again" after a
paste remain~~ — **closed as superseded**: both are workarounds for having to leave the source folder paste remain~~ — **closed as superseded**: both are workarounds for having to leave the source folder
to paste, and **Copy to… / Move to…** ([ROADMAP](ROADMAP.md), M16) removes that constraint, so the to paste, and **Copy to… / Cut to…** ([ROADMAP](ROADMAP.md), M16) removes that constraint, so the
selection is still there for the next destination and there is no "back to source" to offer. selection is still there for the next destination and there is no "back to source" to offer.
5. 💡 **Highlight files changed by an operation.** Their 3.6.5; answers an obvious question. 5. 💡 **Highlight files changed by an operation.** Their 3.6.5; answers an obvious question.
6. **Thumbnail hardening before the next release**: register an explicit Coil `ImageLoader` with a 6. **Thumbnail hardening before the next release**: register an explicit Coil `ImageLoader` with a
+73 -1
View File
@@ -64,7 +64,7 @@ track to report back.
| Predictive back | **Correct.** `BACK` from inside a folder returns to the root and the activity stays resumed, so the `BackHandler` composed after the overlay branch works under the `OnBackInvoked` dispatcher too. | | Predictive back | **Correct.** `BACK` from inside a folder returns to the root and the activity stays resumed, so the `BackHandler` composed after the overlay branch works under the `OnBackInvoked` dispatcher too. |
| Permission request | **Broke, fixed.** On the shipped build Android 13+ was asked for nothing at all; see below. | | Permission request | **Broke, fixed.** On the shipped build Android 13+ was asked for nothing at all; see below. |
| The progress notification | **Fixed, then verified.** After the fix, a real 220 MB copy posts notification `1001` on channel `file-operations` with `ONGOING_EVENT\|NO_CLEAR\|FOREGROUND_SERVICE` and `category=progress`, then removes it and stops the service when the copy finishes. Before the fix the app's notification importance was `NONE`. | | The progress notification | **Fixed, then verified.** After the fix, a real 220 MB copy posts notification `1001` on channel `file-operations` with `ONGOING_EVENT\|NO_CLEAR\|FOREGROUND_SERVICE` and `category=progress`, then removes it and stops the service when the copy finishes. Before the fix the app's notification importance was `NONE`. |
| Copy to completion | The staged copy landed at `/sdcard/bigfile.bin`, byte-count identical, via the overflow menu's "Paste here". | | Copy to completion | The staged copy landed at `/sdcard/bigfile.bin`, byte-count identical, via the then-current "Paste here" (the clipboard flow that has since become Copy to… / Cut to…). |
| Compress and extract from the UI | **Found a bug, fixed.** Long-pressing a folder and choosing "Compress to ZIP" produced a `tocompress.zip` that the host's `unzip` read back with the right relative paths and contents. Selecting that `.zip` then exposed the selection bar clipping its own actions — see below. | | Compress and extract from the UI | **Found a bug, fixed.** Long-pressing a folder and choosing "Compress to ZIP" produced a `tocompress.zip` that the host's `unzip` read back with the right relative paths and contents. Selecting that `.zip` then exposed the selection bar clipping its own actions — see below. |
| One archive of **every** supported format | **Found a bug, fixed.** A real `.zip`, `.7z`, `.tar`, `.tar.gz`, `.tar.bz2`, `.txt.xz`, `.txt.gz` and `.txt.bz2` were built on the host and all eight extracted through the UI. Each landed with the right entry names and byte-for-byte content — except `.tar.bz2`, which produced a bare `.tar`, recorded below. | | One archive of **every** supported format | **Found a bug, fixed.** A real `.zip`, `.7z`, `.tar`, `.tar.gz`, `.tar.bz2`, `.txt.xz`, `.txt.gz` and `.txt.bz2` were built on the host and all eight extracted through the UI. Each landed with the right entry names and byte-for-byte content — except `.tar.bz2`, which produced a bare `.tar`, recorded below. |
| Long-press from adb | `input swipe x y x y 700` on a single point *did* open the selection bar and reach Copy. The same gesture has been flaky on the MIUI phone, so it still deserves a manual pass. | | Long-press from adb | `input swipe x y x y 700` on a single point *did* open the selection bar and reach Copy. The same gesture has been flaky on the MIUI phone, so it still deserves a manual pass. |
@@ -287,6 +287,78 @@ 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.
## The Copy to… / Cut to… session
The selection bar's clipboard was replaced by **Copy to…** and **Cut to…**, both opening the destination
picker. Driven on the Xiaomi phone (release build, Android 12), against `AADemo`:
| What | Result |
|---|---|
| The bar | **Copy to…** and **Cut to…** only — no Copy/Move labels, and no destination items in its overflow. |
| Copy to… | `Source` → picker (`Internal storage → AADemo → Target`) → **Copy here**: 120 × 16 MB copied; **Copying files** in the shade; completion **Copied 121 items to Target** with **Show**. |
| Cut to… | `file001.bin` → the same picker, titled **Cut to…** with **Cut here**: moved to `Target`; the source count fell from 120 to 119; the selection cleared and **Undo** was offered. |
| A name in the way | Cutting `Source` into a `Target` that already held one raised **Items already exist here**, with Replace / Skip / Cancel / Keep both; Cancel moved nothing. |
| Paste | The top-bar overflow lists Find duplicates, Storage usage, Trash and Refresh — no **Paste here**. |
The copy was recorded as the foreground-service video ([FGS_VIDEO](FGS_VIDEO.md)). Not repeated here:
the SAF-mode picker (the same dialog, but the granted-tree root was not driven), tablet/landscape layout,
and a cut interrupted mid-batch.
## 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`
+148
View File
@@ -0,0 +1,148 @@
# The foreground-service video
The Play Console's foreground-service declaration for `FOREGROUND_SERVICE_DATA_SYNC` requires a video
of the user *triggering* the local import/export, not just a description. This is that video, and the
record of how it was made. The All files access declaration has its own video and page:
[PERMISSION_VIDEO](PERMISSION_VIDEO.md).
## The file
| file | length | what it is |
|---|---|---|
| `store-assets/video/fgs-import-export.mp4` | **16.1 s** | The submission copy: 1080×2400, H.264, **no audio**, English captions burned in |
| `store-assets/video/fgs-import-export-uncaptioned.mp4` | 18.8 s | The same cut without captions, for a voice-over |
| `store-assets/video/fgs-import-export.srt` | — | The five captions and their timings |
**The file is not a link.** Upload it to YouTube **Unlisted**, or Drive shared with "anyone with the
link", and paste that URL into the foreground-service declaration. A private upload cannot be
reviewed.
## What it shows
| time | on screen | what it proves |
|---|---|---|
| 0:00 | `AADemo`, with `Source` selected and **Copy to…** in the action bar | The user starts a local import/export |
| 0:02 | The **Copy to…** picker: `Internal storage`, then `AADemo` | The destination is chosen locally, without leaving the source |
| 0:06 | The picker on `Target`, then **Copy here** | The user triggers the local copy |
| 0:10 | The notification shade: **Copying files** with a moving progress bar | The `dataSync` foreground service is doing the work and reporting it |
| 0:14 | `AADemo` with the snackbar **Copied 121 items to Target** and **Show** | The operation completed at the chosen destination |
The captions, in order:
1. *Copy a 1.8 GB folder with Copy to…*
2. *Pick Internal storage, then AADemo*
3. *Choose Target, then Copy here*
4. *The foreground service reports progress*
5. *Done: Copied 121 items to Target*
## What was cut, and why
The raw take was **41.0 s**; the published copy is three pieces of it:
| kept | what it is |
|---|---|
| 0–9.5 s | Select `Source`, **Copy to…**, pick `Internal storage → AADemo → Target`, **Copy here** |
| 21–25.5 s | The shade with **Copying files** and its progress bar |
| 26–31 s | The completed folder and the **Copied 121 items to Target** snackbar |
The two gaps are elapsed time, not evidence: the wait between **Copy here** and the notification
appearing, and the wait between the shade closing and the listing refreshing. **The app's target
listing stays empty until the copy finishes and then refreshes itself**, so the empty frames are the
operation in progress, not a failure. The notification and the result are from the same take.
Nothing else is edited. No home screen, launcher or library view appears — the recording starts inside
`AADemo`. The shade was cleared of the phone's weather and Play cards before the take; what remains
besides the app's notification is Android's generic USB debugging/transfer pair. The quick-settings
panel shows only icons, battery and data totals; the Wi-Fi name exists in the accessibility tree but
is not drawn on screen.
Every filename is synthetic: the source is `AADemo/Source/file001.bin` … `file120.bin`, made from
`/dev/zero`, and the destination is `AADemo/Target`.
## Re-shooting it
Create the fixture first — 120 files of 16 MB, so the copy lasts long enough to read the notification:
```bash
adb shell 'rm -rf /sdcard/AADemo/Target; mkdir -p /sdcard/AADemo/Source /sdcard/AADemo/Target
for i in $(seq -w 1 120); do
dd if=/dev/zero of=/sdcard/AADemo/Source/file$i.bin bs=1M count=16 2>/dev/null
done'
```
Clear the notification shade before recording: open it, tap **Clear all**, and check with
`adb shell cmd notification list`. The phone's own weather, Play and messaging cards must not appear
in a video that will be published; USB debugging/transfer cards are generic and may stay.
Open the app on **Internal storage → AADemo**, long-press `Source`, and verify the bar says
**1 item** with **Copy to…** before recording. Then:
```bash
adb shell rm -f /sdcard/fgs.mp4
adb shell screenrecord --size 1080x2400 --bit-rate 8000000 --time-limit 55 /sdcard/fgs.mp4 &
sleep 1.5
adb shell input tap 231 2155 # Copy to… in the selection bar
sleep 2
adb shell input tap 540 1148 # Internal storage in the picker
sleep 2
adb shell input tap 540 994 # AADemo
sleep 2
adb shell input tap 540 1302 # Target
sleep 2
adb shell input tap 740 1396 # Copy here
# The notification exists only after Copy here. Wait for it, or the shade shows only USB cards.
for i in $(seq 1 16); do
adb shell cmd notification list | grep -q 'de.softwareapp_hb.filemanager' && break
sleep 0.5
done
adb shell cmd statusbar expand-notifications
sleep 6 # the card can rank below the USB pair for the first second
adb shell cmd statusbar collapse
sleep 18 # the copy must finish and the listing refresh
adb shell pkill -INT screenrecord
adb pull /sdcard/fgs.mp4
```
Cut the two waits, keeping the trigger, the notification and the result. Use `-ss`/`-t` per segment
rather than a filter graph: the phone records variable-frame video, and a `trim` concat came out 6 s
short on this take.
```bash
ffmpeg -y -ss 0 -t 9.5 -i fgs.mp4 -an -c:v libx264 -crf 20 -pix_fmt yuv420p seg-a.mp4
ffmpeg -y -ss 21 -t 4.5 -i fgs.mp4 -an -c:v libx264 -crf 20 -pix_fmt yuv420p seg-b.mp4
ffmpeg -y -ss 26 -t 5 -i fgs.mp4 -an -c:v libx264 -crf 20 -pix_fmt yuv420p seg-c.mp4
printf "file 'seg-a.mp4'\nfile 'seg-b.mp4'\nfile 'seg-c.mp4'\n" > segments.txt
ffmpeg -y -f concat -safe 0 -i segments.txt -c copy fgs-cut.mp4
```
The times are this take's; check the frames before reusing them. The published file is 16.1 s after
the caption pass, because the last segment is shorter than its nominal five seconds.
Three traps cost takes here:
- **The picker recentres as the trail grows.** Its rows and its **Copy here** button move with each
level, so map each screen with `adb shell uiautomator dump`; the coordinates above are this phone's
1080×2400 layout, not a scale factor.
- **Never run `assembleRelease` and `adb install` in one parallel batch.** That race installed the
previous APK, and the bar still said **Copy / Move** even though the new strings were in the built
APK. Install sequentially, then check the phone:
`aapt2 dump resources <installed.apk> | grep browser_action_cut_to`.
- **Open the shade only once the notification exists, and hold it.** Opening it straight after
**Copy here** can show only Android's USB cards, and even when the app's card exists it can rank
below them for the first second. The `cmd notification list` loop plus the 6 s hold is what made
**Copying files** readable.
Also expect the target listing to stay **empty** until the copy completes and the ViewModel reloads
it. That is the operation still running, not a missed **Copy here**; `du -sh /sdcard/AADemo/Target`
is the independent check.
The captions are five PNG overlays at **y = 1900**, not the 2130 used by the all-files video: the
selection bar sits at 2133–2177 on this phone, and a caption there hides the **Copy to…** button —
the very action the video exists to show.
## Uploading it
Upload `store-assets/video/fgs-import-export.mp4` to YouTube **Unlisted** or Drive with link sharing,
and paste the URL into the **foreground-service** declaration. This is a different field from the
All files access video: the permission video shows browsing a whole volume, this one shows the local
copy that the `dataSync` service keeps alive.
+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.
+143
View File
@@ -0,0 +1,143 @@
# The permission-use video
The Permissions Declaration Form asks for a link to a short video that shows
`MANAGE_EXTERNAL_STORAGE` being used — 30 seconds or fewer, with a voice-over or captions where the
UI does not make the use obvious. This file is the record of the video that answers it, and the
instructions for making another.
## The file
| file | length | what it is |
|---|---|---|
| `store-assets/video/permission-use.mp4` | **19.7 s** | The submission copy: 1080×2400, H.264, **no audio**, English captions burned in. The home-screen segment is deliberately cut (below) |
| `store-assets/video/permission-use-uncaptioned.mp4` | 19.7 s | The same cut without captions, for a voice-over instead |
| `store-assets/video/permission-use.srt` | — | The caption text and timings, for a re-upload or translation |
**The file is not a link.** Play asks for a URL, so upload the MP4 — YouTube **Unlisted**, or Google
Drive shared with "anyone with the link" — and paste that URL into the form. A private video or a
sign-in-gated Drive link cannot be reviewed. Unlisted is enough; the video does not need to be
public or searchable.
## What it shows
| time | on screen | what it proves |
|---|---|---|
| 0:00 | The app's **Choose a folder** prompt, with **Grant full access** | The app asks for the permission rather than assuming it |
| 0:01–0:08 | Android's **All files access** screen; the toggle is off, then on | The user grants it through Android's own UI, not an in-app shortcut |
| 0:08–0:12 | *(after a deliberate cut)* Internal storage, then the **AADemo** folder | The permission is what makes a whole-volume listing possible |
| 0:12–0:14 | Documents: `budget.csv`, `itinerary.md`, `offsite-notes.txt`, `quarterly-report.pdf`, `service-agreement.docx` | The use is not media: these are files `MediaStore` does not manage |
| 0:14–0:15 | **New folder** dialog | A write is about to be attempted |
| 0:15–0:19 | **New folder** appears with the change dot; snackbar **Folder created** | The same permission is used to write, not only to read |
**The cut at 0:08 is a privacy redaction, not an edit to the evidence.** The raw take returns to the
app's home screen between the grant and the folder listing, and that screen shows the phone's own
library counts — **6 238 images and 20 248 documents**. [STORE_LISTING](STORE_LISTING.md) forbids
publishing those counts, because they describe the owner's device rather than the app. The published
video removes the home-screen segment and resumes on the internal-storage listing, which is the
first frame that proves the grant took effect. The uncaptioned file is cut at the same two points,
so both copies tell the same story.
The captions, in order:
1. *Plain Files needs All files access*
2. *Android asks to allow all-file management*
3. *Switching on All files access*
4. *Granted: browsing internal storage*
5. *Documents: CSV, MD, TXT, PDF, DOCX*
6. *Writable too: a new folder is created*
## Why the system UI is German
The test phone (Xiaomi M2101K7AG) runs MIUI in German; the app itself is English. Changing the phone's
language to flatter a recording would not change what the permission does, and the two system strings
that matter are translated by the captions: *Zugriff auf alle Dateien* ("All files access") and
*Zugriff zum Verwalten aller Dateien zulassen* ("Allow access to manage all files"). The reviewer sees
the toggle move and the app change state, which is the evidence; the language is incidental.
## Privacy: what is not in the video
- The library is **generated** by `tools/make-demo-library.py`, not taken from the phone. It was
copied to `/sdcard/AADemo` so it sorts first and the recording never has to open `Download`, whose
listing on this device holds the owner's real PDFs.
- Every filename on screen — `budget.csv`, `itinerary.md`, `quarterly-report.pdf`, `AADemo` — is
synthetic. The published cut removes the home screen entirely, because its library counts
(**6 238 images, 20 248 documents**) are the owner's real totals; the uncaptioned file is cut at the
same points. What remains shows synthetic names and Android's own screens.
- Frames were inspected with a contact sheet before and after the cut, and the status bar holds
nothing but the clock, signal, battery and the screen-record indicator.
## Re-shooting it
The take was made on the release build, because that is the artefact the declaration is about:
```bash
./gradlew :app:assembleRelease
adb install -r app/build/outputs/apk/release/app-release.apk
adb shell cp -r /sdcard/Download/PlainFiles-Demo /sdcard/AADemo # only if absent
adb shell appops set --uid de.softwareapp_hb.filemanager MANAGE_EXTERNAL_STORAGE deny
adb shell am force-stop de.softwareapp_hb.filemanager
adb shell am start -n de.softwareapp_hb.filemanager/.MainActivity
```
⚠️ **The `--uid` is the whole trap.** After Android's Settings screen grants the permission, a
package-level `appops set de.softwareapp_hb.filemanager MANAGE_EXTERNAL_STORAGE deny` leaves the
**UID mode** at `allow`, the app keeps `isExternalStorageManager() == true`, and no prompt appears.
The revoke only works with `--uid`, and `appops get` shows both lines so the state can be checked
before recording.
Then, with the prompt verified on screen, record and drive it:
```bash
adb shell rm -f /sdcard/permission-use.mp4
adb shell screenrecord --size 1080x2400 --bit-rate 8000000 --time-limit 30 /sdcard/permission-use.mp4 &
sleep 1
adb shell input tap 540 1358 # Grant full access
sleep 2.5
# If the runtime storage dialog appears, tap ERLAUBEN at (540,1321). It does not when
# READ_EXTERNAL_STORAGE is already granted, which is the normal case on this phone.
sleep 2.5
adb shell input tap 931 526 # All files access toggle
sleep 2
adb shell input keyevent KEYCODE_BACK
sleep 2
adb shell input tap 540 1600 # Internal storage
sleep 2
adb shell input tap 540 644 # AADemo
sleep 2
adb shell input tap 540 644 # Documents
sleep 2
adb shell input tap 959 2146 # New folder (FAB)
sleep 1.5
adb shell input tap 824 1368 # Create; the name is prefilled, so no keyboard appears
sleep 4
adb shell pkill -INT screenrecord
adb pull /sdcard/permission-use.mp4
```
Then cut out the home screen. In this take the last Settings frame is at **8.25 s** and the first
internal-storage frame is at **10.5 s**; re-check those two frames before reusing the numbers, because
the exact times depend on how fast the taps landed:
```bash
ffmpeg -y -i permission-use.mp4 -filter_complex \
"[0:v]trim=0:8.25,setpts=PTS-STARTPTS[a];[0:v]trim=10.5,setpts=PTS-STARTPTS[b];[a][b]concat=n=2:v=1[v]" \
-map "[v]" -c:v libx264 -crf 20 -pix_fmt yuv420p -an permission-use-cut.mp4
```
Do not try to record this on the AVD. Under software emulation `screenrecord` captured **one frame in
three seconds** — a three-second test produced a 1-frame, duration-less file — so the clean emulator
cannot produce video. The phone records properly; the emulator is only useful for checking the demo
library and the permission screens.
Two details are deliberate:
- **Never tap the name field.** On this MIUI build it raises the keyboard, the dialog shifts up, and
the next tap lands on the keyboard instead of **Create** — the first attempt created the folder but
ended on an empty screen. The prefilled *New folder* is enough to show a write.
- **The coordinates assume 1080×2400 at 440 dpi** (the Xiaomi phone). On another device, map each
screen with `adb shell uiautomator dump` and use the bounds rather than scaling these.
The captions were burned in from six transparent PNG overlays with `ffmpeg overlay` (Pillow, DejaVu
Sans Bold 40 px, black 80 % box, bottom-centred above the snackbar). The text and timings are in
`store-assets/video/permission-use.srt`, so a re-upload can carry the same captions without burning
them in.
+75 -6
View File
@@ -152,6 +152,66 @@ This is the step that can block a file manager, and the one to get right.
- [ ] Keep the permission set honest: declaring a permission the app does not use is itself - [ ] Keep the permission set honest: declaring a permission the app does not use is itself
a policy violation. a policy violation.
**The declaration answer (490 / 500 characters, measured):**
```
Plain Files' core purpose is browsing and managing every file and folder on internal storage, SD cards and USB drives: documents, archives, APKs, hidden files and folders created by other apps. The Storage Access Framework grants one user-picked tree at a time and cannot enumerate volumes or present a whole-device hierarchy. MediaStore exposes indexed media collections, not arbitrary files or folder trees. SAF remains a fallback for a chosen folder, but cannot deliver the core purpose.
```
This is a **functional** argument, which is the only kind the form accepts — Google's own wording
says improving performance is not an acceptable reason, so speed is not mentioned. Each claim is true
of this build: `data/SafSource` already provides the folder-tree fallback, and the app's only
`MediaStore` use is the best-effort delete request (section 5's permission audit), so neither API is
being dismissed as unnecessary. What they cannot do is *enumerate every volume*, *present one
hierarchy spanning internal storage and removable media*, or *manage arbitrary non-media files and
folders* — which is what "file manager" means, and why the listing copy leads with it.
If a future form allows fewer characters, cut the last sentence first: the fallback is a point of
honesty, not the justification.
- [ ] Upload `store-assets/video/permission-use.mp4` (**19.7 s**, captions burned in) to YouTube
**Unlisted** or Drive shared with anyone who has the link, then paste that URL into the form's
video field. The repository file is not a link, and a private video cannot be reviewed. What it
shows, why the system UI is German, and how to re-shoot it: [PERMISSION_VIDEO](PERMISSION_VIDEO.md).
### The foreground-service declaration (`dataSync`)
`FileOpService` is a **`dataSync`** foreground service: it keeps a copy, move, delete (into the trash),
compress or extract alive while the user is in another app, and mirrors the engine's progress into an
ongoing, silent notification. It runs no network code and the app has no `INTERNET` permission. Play
asks about this separately from All files access.
- **Use case: Local processing → Importing, exporting.** Play's own chart describes the use case as
*"Includes migration of files from SD card. Show the user manually triggering an import or export
of files locally (for example, as moving files from an SD card)"* — which is what **Copy to…** and
**Cut to…** do. Do **not** tick network processing, backing up/restoring, media
transcoding or "Other tasks": every `OperationKind` is local — `COPY`, `MOVE`, `DELETE`, `COMPRESS`,
`EXTRACT` — and none of them touches a network.
- **Functionality description (482 / 500 characters, measured):**
```
Plain Files is a file manager. Its dataSync service runs user-initiated local file operations: copying and moving files and folders between folders, internal storage, SD cards and USB drives; deleting into a 24-hour trash; creating ZIPs; extracting ZIP, TAR, GZ, BZ2, XZ and 7z archives. It keeps a long operation alive while the user switches apps and posts an ongoing, silent progress notification until the work ends. All operations are local; the app has no INTERNET permission.
```
- **If the task is deferred** (*"does not start immediately"*): *"If deferred, a copy, move, delete,
compress or extract the user just confirmed would not start while Plain Files is in the background:
no progress notification and no visible change until the app returns. A large operation could look
as if it had silently failed, and the user might start it again."*
- **If the task is interrupted** (*"paused and/or restarted"*): *"If interrupted, the work stops.
Items already completed remain, but a file being copied or extracted can be left partly written at
the destination, and the user has to start the operation again. Nothing is overwritten without
asking, and deletes are staged in the 24-hour trash, so completed deletes remain recoverable."*
- [ ] **Upload the foreground-service video.** `store-assets/video/fgs-import-export.mp4` (**16.1 s**,
captions burned in) to YouTube **Unlisted** or Drive with link sharing, then paste that URL into
the foreground-service declaration. It shows the selection, **Copy to…**, the destination
picker (`Internal storage → AADemo → Target`), **Copy here**, the **Copying files**
notification with its progress bar, and **Copied 121 items to Target**. It is a
different field from the All files access video. What was cut, the privacy checks, and how to
re-shoot it: [FGS_VIDEO](FGS_VIDEO.md).
**Verify the shipped permission set** after every release build: **Verify the shipped permission set** after every release build:
```bash ```bash
@@ -197,7 +257,11 @@ 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), The per-release **What's new** field is separate from the listing and is capped at **500 characters**:
its copy, measured, is in [RELEASE_NOTES](RELEASE_NOTES.md), together with the longer announcement
for a website or GitHub release.
- [ ] 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 +269,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
+146
View File
@@ -0,0 +1,146 @@
# Release notes
The copy a buyer reads *before* installing, as opposed to [CHANGELOG](../CHANGELOG.md), which is the
reasoning for whoever maintains the app. Two lengths live here:
- **Play Console → What's new** — plain text, **500 characters per language**, no Markdown and no
bullets (Play renders neither), measured rather than estimated.
- **The longer announcement** — for a website, a forum post or a GitHub release, where the limit is
the reader's patience rather than a Console field.
The source of truth for *what* changed is the changelog, and the source of truth for *what the app
claims* is the [README](../README.md) and [STORE_LISTING](STORE_LISTING.md). This file only chooses
which of those facts a new user should hear first.
## Writing the next one
1. **Version.** `versionName` and `versionCode` are in `app/build.gradle.kts`; the latter must be
higher than every previous upload. The first release is `1.0.0` / `1`.
2. **Changelog first.** Move the entries out of `## [Unreleased]` into a
`## [1.0.0] - YYYY-MM-DD` heading, so this file and the changelog cannot describe different
builds.
3. **Then the Play field.** Say what a user can now do that they could not before — never what the
code did. A first release describes the app instead of a diff.
4. **Measure it.** Play counts characters, line breaks included:
```bash
python3 -c "print(len(open('/tmp/whats-new.txt').read().strip()))"
```
5. **Quote nothing that a device has not shown.** A limitation belongs in the announcement only if
it is already in the README's *Known limitations*; if it is not, the README is what needs fixing.
---
## 1.0.0 — first release
### Play Console → What's new (500 characters max)
```
Plain Files is here: a file manager with no ads, no account and no internet permission, so nothing leaves your device.
Browse internal storage, SD cards and USB drives. Copy, move, rename and delete files; undo a delete, rename or move; search everywhere; find duplicates; unpack ZIP, TAR, GZ, BZ2, XZ and 7z; star the folders you use; and read images, video, PDFs and text inside the app.
One purchase, every feature. No tracking, no subscription.
```
**Measured: 450 characters** (including the two blank lines between paragraphs). The remaining
headroom is deliberate: it leaves room for a sentence about a fix without rewriting the whole field.
Why this shape: the first two sentences are the claim no competitor in the survey makes — no ads and
**no `INTERNET` permission** — and the middle one is the proof that it is still a file manager. The
verbs are the ones people use ("copy, move, rename, delete"), not the app's internal names. Nothing
here is a superlative, an emoji, or the word *free*: the app is paid, and a headline implying
otherwise is both misleading and against Play's editorial policy.
### The longer announcement
> Plain Files 1.0.0 is available for Android 8.0 and later. One purchase, no subscription, no ads,
> and no way for the app to send anything off the device — because it does not hold the network
> permission at all.
#### What it does
**Browsing.** Internal storage, SD cards and USB drives side by side. List or grid, sorted by
name — `file2` before `file10` — size, date or type; hidden files on request; breadcrumbs; and a
search that either stays in the folder you are in or looks everywhere through an on-device index
which says how current its answer is.
**Moving files around.** Copy, move, rename and delete one item or many. **Copy to…** and **Cut
to…** open a folder picker — volumes first, then one level at a time — and start the transfer into
that folder without taking you out of the one you are standing in. A finished copy says
*Copied to folder* and offers **Show**. A name that already exists asks before overwriting, and a
batch that cannot succeed is refused as a whole rather than performed until it
hits the problem. The rows an operation produced carry a dot until you next open that folder, so
"what did that 4 GB copy do?" has an answer even when the destination was elsewhere.
**Undo, and a trash that explains itself.** A delete is a move into a hidden `.plainfiles-trash`
folder on the same volume, kept for **24 hours**; the Trash screen states that window, offers
**Empty trash** behind one question, and sweeps expired batches when you open it. Rename and move
offer undo as well.
**Renaming a batch.** Select several files and Rename opens a pattern rather than the single-file
dialog: one name, the number to start at, and a live preview of the names it will produce. The
numbering **continues the folder's own series** — `Holiday (1)` and `Holiday (2)` already there make
the next batch start at 3 — because a batch rename that always starts at 1 is useless the second
time it is used. A name in the way blocks the batch and is named as it is typed.
**Finding things.** The duplicate finder compares size, then the head of every candidate, then the
survivors in full — never a name or a date. The storage-usage view measures every folder and ranks
it largest first, so the folder eating the card is the one at the top.
**Looking at files.** Image, text, PDF, media and archive viewers, and an APK's own details read
without installing it. Thumbnails show the picture, and a **video shows a frame of itself** rather
than a film icon. An archive can be read without extracting it first, with entry names checked
against zip-slip.
**Archives.** Create ZIP; extract ZIP, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, GZ, BZ2, XZ and 7z. When
compressing, you choose the name and whether to compress at all: for copying a collection to a
computer, storing the files as they are takes one pass and is still an ordinary archive.
**Working with other apps.** Plain Files can receive a share from anywhere and appear in another
app's file chooser. Neither costs a permission.
**Tablets and large windows.** At expanded width the screen splits into two panes: the folder list
on the left, and the contents — or a preview and the details — of the folder or file you pick on the
right.
**Shortcuts.** Long-press the app icon for **Images**, **Recent** and **Trash**.
#### What it deliberately does not do
- **No cloud storage, network shares, FTP/SFTP/WebDAV or web server.** Every one of those needs
`INTERNET`, which is the single permission this app refuses to hold. That is the product, not a
gap in the schedule.
- **RAR is not supported**, because it needs native code this app does not ship — and it says so
rather than failing with a strange error. 7z can be read but not created.
- **Extraction does not restore timestamps or permissions**, and archive passwords are not
supported.
- **Cancelling happens between entries**, so one very large file finishes before a stop is honoured.
- **English is the only language so far.** Every string is in `strings.xml`, so a translation is a
file rather than a refactor.
- **Android TV is specified but not shipped.** Its acceptance needs a TV device pass this machine
cannot provide, and a half-tested TV build reviews worse than none.
- **A library is not restored across process death.** Images or Recent returns to the root screen
after Android kills the process, because a library has no path to persist.
#### Privacy, in one paragraph
The app declares no `INTERNET` permission, contains no advertising or analytics SDK, and has no
account or sign-in. It keeps three things on the device — an index of files for search, an index of
staged deletes for the trash, and the list of starred folders — and none of them leaves it. The
permission set and why "All files access" is the one sensitive declaration are in the
[store listing](STORE_LISTING.md); the policy text is [PRIVACY.md](../PRIVACY.md).
#### Price
**€4.49**, with a **€2.29 launch price for the first 14 days**. One purchase, every feature; no
subscription and nothing to buy inside the app. There is no Billing client in the build — the price
lives on the listing — which is part of how "nothing leaves the device" stays true of the shipped
artefact rather than only of the source.
#### What comes next
Android TV is specified and waits for a device; the post-1.0 queue and the deliberate deferrals are
in [ROADMAP](ROADMAP.md). What will not change is the permission set: features arrive without a new
permission, or they do not arrive.
+154 -26
View File
@@ -1,8 +1,8 @@
# Roadmap # Roadmap
File Manager is built against a fixed milestone plan (**M0–M15**). This file is the File Manager is built against a fixed milestone plan. **M0–M20 are built**; **M21** (Android TV) is
single source of truth for what is done and what remains. **M16** (Copy to… / Move to…) has since been specified and deliberately waits for a device. This file is the single source of truth for what is
built and is specified below; the queue records what is left. done and what remains, and the queue records what is left.
Legend: ✅ done · 🚧 in progress · ⏳ not started · 💡 candidate (proposed, not scheduled) Legend: ✅ done · 🚧 in progress · ⏳ not started · 💡 candidate (proposed, not scheduled)
@@ -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… / Cut to… | ✅ | A destination picker behind the selection bar's **Copy to…** and **Cut to…** actions — 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 cut clears it. Conflicts ask before overwriting, 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
@@ -57,15 +63,21 @@ duplicate finder (M12), batch rename with sequence continuation (M14) and favour
The last one standing there — the post-paste **"copy again"** and **"return to source folder"** — is The last one standing there — the post-paste **"copy again"** and **"return to source folder"** — is
**closed as superseded**, not deferred: both exist only because that app's flow makes you leave the **closed as superseded**, not deferred: both exist only because that app's flow makes you leave the
source folder to paste. `Copy to…` / `Move to…` (in the queue below) removes that constraint, and with it source folder to paste. `Copy to…` / `Cut to…` (in the queue below) removes that constraint, and with it
both features: you never leave the source, so the selection is still there for the next destination, and both features: you never leave the source, so the selection is still there for the next destination, and
there is no "back to source" to offer. Keeping them would be building a workaround for a limitation we there is no "back to source" to offer. Keeping them would be building a workaround for a limitation we
would no longer have. 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… / Cut 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,37 +90,49 @@ 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
4. **Copy to… / Move to… (M16)** — **done**: the selection bar's overflow opens a folder picker (volumes, outlier; the outlier was investigated and the real fix was progressive listing (200-entry batches,
then folders one level at a time, Up and the trail above them) and confirming copies or moves into the O(n+k) merge), after which 20 000 files opens in **10–16 frames** with a 32–48 max across two runs. The
picked folder without leaving the current one. The selection survives a copy so a second destination is whole suite at that size, and what search costs there, is in [PERFORMANCE](PERFORMANCE.md).
two taps; a move clears it. Conflicts ask the same question as a paste, naming the picked folder. Seven 4. **Copy to… / Cut to… (M16)** — **done**: the selection bar's **Copy to…** and **Cut to…** actions
open a folder picker (volumes, 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 two taps; a cut clears it. Conflicts ask before
overwriting, 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… / Cut to…
**What**: from a selection, choose a destination folder and start the copy (or move) immediately, without **What**: from a selection, choose a destination folder and start the copy (or cut) immediately, without
leaving the folder you are in. leaving the folder you are in.
**Why this shape**: `BrowserViewModel.paste()` already calls `planTransfer(paths, target, policy)` with the **Why this shape**: the transfer engine already takes an explicit target — `planTransfer(paths, target,
current folder as `target`; the engine is target-agnostic, so the operation half needs no new machinery — policy)` — and is otherwise independent of what is on screen; `FileOpService` and the conflict prompt
`FileOpService` and the conflict prompt work regardless of what is on screen. What is missing is a work regardless. What was missing was a destination picker.
destination picker.
**Acceptance criteria** **Acceptance criteria**
- Selecting files and choosing *Copy to…* opens a folder picker: folders only, one level at a time, with - Selecting files and choosing *Copy to…* opens a folder picker: folders only, one level at a time, with
Up and breadcrumbs, every root the app can see (internal and SD card), and the granted tree in SAF mode. Up and breadcrumbs, every root the app can see (internal and SD card), and the granted tree in SAF mode.
- Confirming copies into the chosen folder and **leaves the user where they were**, with the selection - Confirming copies into the chosen folder and **leaves the user where they were**, with the selection
still intact — so a second destination is two taps. `Move to…` is the same picker with `cut = true`. still intact — so a second destination is two taps. `Cut to…` is the same picker with `cut = true`.
- A name conflict asks the same question as a paste does, with the picked folder named in it, and resolve - A name conflict asks before overwriting, with the picked folder named in it, and resolve applies to
applies to that folder. that folder.
- Progress belongs to the existing operation notification, not to the screen the user is on. - Progress belongs to the existing operation notification, not to the screen the user is on.
- After a copy, a message names the destination and offers to show it. After a move the selection is - After a copy, a message names the destination and offers to show it. After a move the selection is
cleared and the listing refreshed, because the rows are gone. cleared and the listing refreshed, because the rows are gone.
@@ -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

Binary file not shown.
Binary file not shown.
+19
View File
@@ -0,0 +1,19 @@
1
00:00:00,200 --> 00:00:02,800
Copy a 1.8 GB folder with Copy to…
2
00:00:02,800 --> 00:00:06,200
Pick Internal storage, then AADemo
3
00:00:06,200 --> 00:00:09,600
Choose Target, then Copy here
4
00:00:09,600 --> 00:00:14,200
The foreground service reports progress
5
00:00:14,200 --> 00:00:16,000
Done: Copied 121 items to Target
Binary file not shown.
Binary file not shown.
+23
View File
@@ -0,0 +1,23 @@
1
00:00:00,200 --> 00:00:03,400
Plain Files needs All files access
2
00:00:03,400 --> 00:00:06,200
Android asks to allow all-file management
3
00:00:06,200 --> 00:00:08,250
Switching on All files access
4
00:00:08,250 --> 00:00:11,750
Granted: browsing internal storage
5
00:00:11,750 --> 00:00:13,750
Documents: CSV, MD, TXT, PDF, DOCX
6
00:00:13,750 --> 00:00:19,600
Writable too: a new folder is created
+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'