diff --git a/android/README.md b/android/README.md index 982d102b..14e72c0f 100644 --- a/android/README.md +++ b/android/README.md @@ -1820,3 +1820,194 @@ Not verified in this pass: receiving the shared file inside a third-party app (t chooser was observed, not an app's import); the 24 h / 64 MiB prune bound was not reached on the emulator (only two small files were written). +## Multi-select artifacts: bulk copy and share (16 Oct 2026) + +A long-press on any artifact in a gallery now enters artifact selection: that item +becomes selected with the app's tonal selected treatment, further taps toggle +items instead of opening them, and a contextual action bar offers **Copy links**, +**Share** and a close. It lives in both artifact surfaces — the run-summary grid +(`RunSummaryTab` → `ArtifactGallery`) and the stage pane's per-visit artifacts +list (`ArtifactsSection`) — and nowhere else (runs/pipelines lists are untouched). + +- **Model.** New `ui/graph/ArtifactSelection.kt`: an immutable `ArtifactSelection` + keyed by the artifact url (`enter`, `toggle`, `selectAll`, `clear`, `contains`); + selection mode is exactly "one or more urls selected", so it can never restore + half-applied. `ArtifactSelectionSaver` (a `listSaver`) + `rememberArtifactSelection` + save/restore it across configuration and reseed per run/visit. +- **Action bar.** `ArtifactSelectionBar` is the pane's `TopAppBar` (it replaces the + normal bar while selecting): title `N selected`, a close, a copy and a share, all + Material 3 `IconButton`s (the measured 117x117 px = **48dp** targets) with accurate + descriptions ("Exit selection", "Copy selected links", "Share selected artifacts"). + It applies the same `paneSafeArea()` top/horizontal insets as the bar it replaces, + so it stays inside the status bar/cutout and above — never over — the items. +- **Copy links.** `artifactSelectionLinks` resolves each selected url against the + configured server through the existing `resolvedArtifactUrl` (no hardcoded host), + joins one resolved absolute link per line, and copies it through the new one-line + `components/Clipboard.copyText` (the single copy path, now also used by the code + blocks, the pipeline source, the artifact row and the viewer). A `Snackbar` + confirms `Copied N links`. Back leaves selection mode first (a pane-scoped + `BackHandler`), only then runs the pane's own Back. +- **Bulk share.** `shareArtifacts` fetches every selected artifact through the + existing `AppViewModel.fetchArtifactBytes` and reuses the single-item + `writeSharedArtifact` (same bounded cache, same `FileProvider`, same + `pruneSharedArtifacts`) before one `Intent.ACTION_SEND_MULTIPLE` carrying every + uri. Its type is the new pure `bulkShareMimeType` (the common type, else the + wildcard) and its count is the chooser title. If **any** fetch fails the whole set + degrades in the same action to the resolved links as `text/plain` + (`shareLinks`). No parallel share path and no new dependency (icons come from the + declared `material-icons-extended`). +- **Pure helpers / tests.** `ArtifactSelectionTest` (enter, toggle, deselect-last, + select-all + clear, restored state, the one-per-line link formatting, the labels) + and two new `ArtifactSharingTest` cases (`shareTargets` resolution/drop, + `bulkShareMimeType` common-type vs wildcard). + +Evidence (macOS, JDK 17 Homebrew `openjdk@17`, Gradle 8.11.1 from the wrapper +cache, `ANDROID_HOME=~/Library/Android/sdk`): + +- `gradle :app:testDebugUnitTest :app:assembleDebug --console=plain` → + `BUILD SUCCESSFUL`; the result XMLs aggregate to **168 tests across 21 classes, + 0 failures, 0 errors, 0 skipped** (up from 157: the new `ArtifactSelectionTest` + plus the two bulk-share cases). `app-debug.apk` is 17,913,089 bytes; the current + tree's sha256 and the APK publish are recorded in the section below. +- `gradle :app:lintDebug` → the same **2 pre-existing** `windowLightNavigationBar` + NewApi errors (`values/themes.xml`, `values-night/themes.xml`) and 39 warnings; + the only warning attributed to a touched file is the pre-existing + "Modifier parameter should be the first optional parameter" on `StageDetailPane`. +- On `emulator-5554` (never the physical Pixel, never `emulator-5556`; 2076x2152, + density 390) against the live server, run 94's summary and per-visit list were + driven. Every capture is in `captures/selection/` (git-ignored) and was validated + by `scripts/capture_png.sh -s emulator-5554`: + - `01_longpress_selection.png` — long-press on `grid_cell_share.png` entered the + mode: the action bar reads `1 selected` and the cell shows the tonal ring + + check badge (its per-item share button hidden). + - `02_several_toggled.png` — three cells then a non-image row toggled on: + `4 selected`; the row wears the `secondaryContainer`/`onSecondaryContainer` + treatment. + - `03_bulk_copy_confirmation.png` — **Copy links** showed the `Copied 4 links` + Snackbar; pasting the clipboard into the Pipelines search field + (`06_clipboard_pasted_links.png`) yielded exactly the four resolved absolute + links, one per line, against the configured server + (`http://10.0.2.2:8080/artifacts/94/1/grid_cell_share.png` … `/94/2/lint-results-debug.txt`), + in the gallery's (candidate) order. + - `04_bulk_share_intent.png` — sharing the mixed 4 selected ran the **file path**: + `ActivityTaskManager: START … action.CHOOSER … clip={*/* hasLabel(11) 4 items: + {U(content)} x4}`, chooser titled "Sharing 4 files" (mixed types → wildcard). + - `05_bulk_share_images_png.png` — the 3 image cells alone resolved to a concrete + type: `clip={image/png hasLabel(11) 3 items: …}`, chooser "Sharing 3 images". + - `08_bulk_share_fallback_links.png` — with `cmd connectivity airplane-mode + enable` (10.0.2.2 unreachable) the same Share **fell back** in one action to + `text/plain`: `action.SEND`, chooser "Sharing text" showing the three resolved + links newline-joined. Airplane mode was then disabled. + - `07_per_visit_selection.png` — the stage pane's per-visit list enters the same + mode (`3 selected`) with the action bar in the pane's safe area. + - `09_rotation_restored.png` — after `user_rotation 1` (2152x2076) the `2 selected` + selection restored fully, not half-applied. + - Back in selection mode exited the mode and left run 94 open (0 "Exit selection" + nodes afterwards, the normal app bar returned); closing the stage pane by + tapping the run peek and reopening the same visit showed no selection, + confirming the pane-close clear. + - `adb -s emulator-5554 logcat -d` held 0 `FATAL EXCEPTION` / 0 `E AndroidRuntime`. +- **APK publish.** `app-debug.apk` copied to + `~/.local/share/pipelines/data/artifacts/97/1/pipelines-debug-wip-1195535.apk` + (`1195535` = `git rev-parse --short HEAD`); `curl -I/-o` against + `http://10.0.0.249:8080/artifacts/97/1/pipelines-debug-wip-1195535.apk` (and + `10.0.0.75`) returned `HTTP 200`, `Content-Type: + application/vnd.android.package-archive`, 17,913,089 bytes. + +Not verified in this pass: a narrow-window layout of the selection bar (the +emulator is the 851dp-wide inner display); receiving the bulk share in a +third-party app (the chooser was observed, not an import). + +## Artifact selection: one shared host (16 Oct 2026) + +The first pass left the run-summary and stage-pane selection wiring copy-pasted, +and the refactor that removed the duplication had outrun this README. The final +tree keeps one shared host: both `RunDetailScreen` (the run-summary grid) and +`StageDetailPane` (the per-visit list) call `ArtifactSelectionScaffold`, which +owns the remembered `ArtifactSelection`, the `resolvedSelection` lookup, the +single `artifactSelectionActions` copy/share implementation, the `SnackbarHostState` +and the pane-scoped `BackHandler`, and renders the contextual +`ArtifactSelectionBar` in place of the surface's own top bar while selecting. +Neither screen owns a `SnackbarHostState` or a `BackHandler` of its own. + +`artifactSelectionActions` resolves every selected url through +`resolvedArtifactUrl` (never a hardcoded host), copies the resolved links one per +line through the one `ClipboardManager.copyText`, and shares every selected +artifact through the single-item `writeSharedArtifact`/`shareArtifacts` path. +`artifactSelectionLinks` resolves each selected url; `artifactSelectionActions` +confirms the number of lines it actually produced (`text.lines().size`) rather +than the raw selection size, so an absolute url plus an unresolvable relative one +under no configured server reports the true count. `writeSharedArtifact` captures a +non-null `fileBytes` from the `shareDelivery` check instead of asserting +`bytes!!`. `ArtifactSelection.selectAll` is kept: it is the task's explicit +select-all test surface even though no UI calls it. + +Evidence, re-run on the same environment (`JAVA_HOME=/opt/homebrew/opt/openjdk@17`, +Gradle 8.11.1 from `~/.gradle/wrapper/dists`, `ANDROID_HOME=~/Library/Android/sdk`, +`emulator-5554` only): + +- `gradle :app:testDebugUnitTest :app:assembleDebug --rerun-tasks --console=plain` + → `BUILD SUCCESSFUL`; the result XMLs aggregate to **168 tests across 21 classes, + 0 failures, 0 errors, 0 skipped** (`ArtifactSelectionTest` grew to 9 with + `resolvedSelectionKeepsOnlyTheCandidatesStillSelected`). `app-debug.apk` is + 17,913,089 bytes; its current sha256 and publish are in the doc-accuracy note + below. +- Rebuilt APK reinstalled on `emulator-5554` (2076x2152, density 390); each frame + validated by `scripts/capture_png.sh -s emulator-5554` and kept in + `captures/selection-run100-final/` and + `~/.local/share/pipelines/data/artifacts/100/1/`: + - `01_longpress_selection.png` — long-press on `grid_cell_share.png` entered the + mode: bar reads `1 selected`, the cell wears the tonal ring + check, and every + per-item `Share`/`Open`/`Copy link` node is gone from the `uiautomator` dump. + - `02_several_toggled.png` — three cells then the `lint-results-debug.txt` row + toggled on → the action bar reads `4 selected`; the two action-bar + `IconButton`s measure **117x117 px = 48dp** with the descriptions + "Copy selected links" / "Share selected artifacts" ("Exit selection" for the + close). + - `03_bulk_copy_confirmation.png` — **Copy links** showed the `Copied 4 links` + Snackbar, and the system clipboard preview under the share bar showed the + resolved absolute link (`http://10.0.2.2:8080/artifacts/94/1/grid_cell_share.png…`). + - `04_bulk_share_intent.png` — **Share** of the mixed 4 ran the **file path** + (`dumpsys activity activities`: `Intent { act=android.intent.action.CHOOSER … + clip={*/* hasLabel(11) 4 items: {U(content)} x4} (has extras) }`), i.e. one + `ACTION_SEND_MULTIPLE` carrying 4 fetched files, typed by the mixed-set + wildcard. The file path ran because the configured server (`10.0.2.2:8080`) + was reachable, so every fetch returned bytes; the unchanged `shareLinks` + fallback (unit-covered by `shareDeliveryIsAFileOnlyWhenTheFetchReturnedBytes`) + is the branch a failed fetch would take in the same action. + - `05_per_visit_selection.png` — the stage pane's per-visit list enters the same + mode (`1 selected`) with the bar inside the pane safe area. + - Back exited selection mode first and left Run 94 open (0 "Exit selection" nodes + afterwards, `Run 94` still present); `adb -s emulator-5554 logcat -d` held 0 + `FATAL EXCEPTION` / 0 `E AndroidRuntime`. +- **APK publish.** `app-debug.apk` copied to + `~/.local/share/pipelines/data/artifacts/100/1/pipelines-debug-wip-1195535.apk` + (`1195535` = `git rev-parse --short HEAD`); `curl` against + `http://10.0.0.249:8080/artifacts/100/1/pipelines-debug-wip-1195535.apk` (and + `10.0.0.75`) returned `HTTP 200`, `Content-Type: + application/vnd.android.package-archive`, 17,913,089 bytes. + +- **Doc-accuracy pass (16 Oct 2026).** The `ArtifactSelection.kt` doc comment and + this README's "in selection order" claim said the bulk copy preserves selection + order; it actually writes one resolved link per line in gallery (candidate) + order, because `resolvedSelection` filters the surface's own candidates. Both now + state candidate order; no runtime behavior changed. Re-verified on the same + environment: `gradle :app:testDebugUnitTest :app:assembleDebug --rerun-tasks + --console=plain` → `BUILD SUCCESSFUL`, the result XMLs aggregate to **168 tests + across 21 classes, 0 failures, 0 errors, 0 skipped**; `app-debug.apk` is + 17,913,089 bytes, sha256 + `a6d5caeb0c1e69da879aabfcc7df2eec09e4a44c85000adba3444558a1d3d82b`. The sha is + not a stable tree fingerprint — it moves with any source edit, because the debug + APK embeds Kotlin source info (a comment-only edit to `ArtifactSelection.kt` left + only `classes6.dex` different) — so run 100's build read `763806783f…`. The APK + was published to + `~/.local/share/pipelines/data/artifacts/100/3/pipelines-debug-wip-1195535.apk`; + `curl` against + `http://10.0.0.75:8080/artifacts/100/3/pipelines-debug-wip-1195535.apk` (and + `10.0.0.249`) returned `HTTP 200`, `Content-Type: + application/vnd.android.package-archive`, 17,913,089 bytes. + +Not verified in this pass: the link fallback on-device (the reachable server ran +the file path); a narrow-window layout of the selection bar; receiving the bulk +share in a third-party app (the chooser was observed, not an import). + diff --git a/android/app/src/main/java/net/awan/pipelines/ui/components/Clipboard.kt b/android/app/src/main/java/net/awan/pipelines/ui/components/Clipboard.kt new file mode 100644 index 00000000..7e9d6afe --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/components/Clipboard.kt @@ -0,0 +1,15 @@ +package net.awan.pipelines.ui.components + +import androidx.compose.ui.platform.ClipboardManager +import androidx.compose.ui.text.AnnotatedString + +/** + * The app's single copy-to-clipboard path: copies [text] to the platform + * clipboard through the Compose [ClipboardManager]. Every copy affordance (the + * code blocks, the pipeline source, the artifact link and the bulk artifact + * links) goes through here, so the behaviour and the clipboard payload can never + * drift between screens. + */ +internal fun ClipboardManager.copyText(text: String) { + setText(AnnotatedString(text)) +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/components/CodeBlock.kt b/android/app/src/main/java/net/awan/pipelines/ui/components/CodeBlock.kt index 02f2e9f8..30c729d2 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/components/CodeBlock.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/components/CodeBlock.kt @@ -21,7 +21,6 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalClipboardManager -import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import net.awan.pipelines.ui.theme.pipelinesText @@ -77,7 +76,7 @@ fun CodeBlock( color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f), ) - IconButton(onClick = { clipboard.setText(AnnotatedString(text)) }) { + IconButton(onClick = { clipboard.copyText(text) }) { Icon( imageVector = Icons.Default.ContentCopy, contentDescription = "Copy $label", diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactSelection.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactSelection.kt new file mode 100644 index 00000000..0d478a6b --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactSelection.kt @@ -0,0 +1,302 @@ +package net.awan.pipelines.ui.graph + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.WindowInsetsSides +import androidx.compose.foundation.layout.only +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.Share +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.listSaver +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.platform.LocalContext +import kotlinx.coroutines.launch +import net.awan.pipelines.data.protocol.StageArtifact +import net.awan.pipelines.ui.components.copyText +import net.awan.pipelines.ui.components.paneSafeArea + +/** + * Which artifacts an artifacts gallery currently has selected, identified by + * their recorded url (the app's artifact identity). It is a plain immutable + * value, so entering, toggling and clearing selection are unit-tested without a + * device. + * + * Selection mode is not a separate flag: it is exactly "at least one url is + * selected". That makes the mode impossible to restore half-applied — an empty + * set is never "selecting" — and toggling the last item off simply leaves the + * mode. [urls] keeps selection order, but the bulk copy resolves the surface's + * candidates in their own (gallery) order, so it writes one link per line in + * that order. + */ +internal data class ArtifactSelection(val urls: List = emptyList()) { + /** The mode is active exactly while something is selected. */ + val active: Boolean get() = urls.isNotEmpty() + + /** The number of selected artifacts (what the action bar reports). */ + val count: Int get() = urls.size + + fun contains(url: String): Boolean = url in urls + + /** Long-pressing an item starts selection on that one item. */ + fun enter(url: String): ArtifactSelection = ArtifactSelection(listOf(url)) + + /** A tap while selecting adds/removes [url]; removing the last leaves the mode. */ + fun toggle(url: String): ArtifactSelection = + if (contains(url)) ArtifactSelection(urls - url) else ArtifactSelection(urls + url) + + /** Selects every one of [all] (de-duplicated); an empty input leaves the mode. */ + fun selectAll(all: Collection): ArtifactSelection = ArtifactSelection(all.distinct()) + + /** Leaves selection mode, discarding every selection. */ + fun clear(): ArtifactSelection = ArtifactSelection() +} + +/** + * The [candidates] that [selection] still selects, in candidate order. A + * restored or stale selection whose urls no longer map to the surface's own + * artifacts resolves to nothing, which is what keeps selection mode and the + * resolved set from drifting apart. Pure. + */ +internal fun resolvedSelection( + candidates: List, + selection: ArtifactSelection, +): List = if (selection.active) { + candidates.filter { selection.contains(it.url) } +} else { + emptyList() +} + +/** + * Saves a selection as its selected urls (plain strings a Bundle can hold) and + * restores it through the data class, so a rotation/restore either brings back a + * fully applied selection or none at all. + */ +internal val ArtifactSelectionSaver = listSaver( + save = { it.urls }, + restore = { ArtifactSelection(it) }, +) + +/** + * The artifact selection remembered/saved for the current [inputs] (so a pane + * switching runs or visits reseeds instead of inheriting the other context's + * selection) and restored across configuration changes. + */ +@Composable +internal fun rememberArtifactSelection(vararg inputs: Any?): MutableState = + rememberSaveable(*inputs, stateSaver = ArtifactSelectionSaver) { + mutableStateOf(ArtifactSelection()) + } + +/** + * The selected artifacts' resolved absolute links, one per line, dropping any + * that cannot be resolved against [configuredServerUrl]. The single line-joining + * path the bulk "Copy links" action uses; resolving goes through + * [resolvedArtifactUrl], so no host is ever hardcoded. The caller confirms the + * number of lines it actually produced, so the count can never drift from this + * payload. Pure. + */ +internal fun artifactSelectionLinks( + artifacts: List, + configuredServerUrl: String, +): String = artifacts.mapNotNull { resolvedArtifactUrl(it, configuredServerUrl) }.joinToString("\n") + +/** The action bar's count label, e.g. `3 selected`. Pure. */ +internal fun selectionCountLabel(count: Int): String = "$count selected" + +/** The bulk-copy confirmation, e.g. `Copied 3 links`. Pure. */ +internal fun selectionCopiedMessage(count: Int): String = + "Copied $count ${if (count == 1) "link" else "links"}" + +/** + * The contextual action bar shown while artifacts are selected: the number + * selected, a copy-links action, a share action and a close that leaves + * selection mode. It is the pane's top app bar (not an overlay), so it stays + * inside the safe area [paneSafeArea] via the same top/horizontal insets as the + * bar it replaces, and it can never cover the items it acts on. Every action is a + * 48dp [IconButton] with an accurate content description; the count is the title. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun ArtifactSelectionBar( + count: Int, + onCopyLinks: () -> Unit, + onShare: () -> Unit, + onClose: () -> Unit, + modifier: Modifier = Modifier, + containerColor: Color = MaterialTheme.colorScheme.surface, +) { + TopAppBar( + title = { Text(selectionCountLabel(count)) }, + navigationIcon = { + IconButton(onClick = onClose) { + Icon(Icons.Default.Close, contentDescription = "Exit selection") + } + }, + actions = { + IconButton(onClick = onCopyLinks) { + Icon(Icons.Default.ContentCopy, contentDescription = "Copy selected links") + } + IconButton(onClick = onShare) { + Icon(Icons.Default.Share, contentDescription = "Share selected artifacts") + } + }, + modifier = modifier, + windowInsets = paneSafeArea().only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal), + colors = TopAppBarDefaults.topAppBarColors(containerColor = containerColor), + ) +} + +/** Shown when no server url is configured and there is no absolute link to copy. */ +internal const val ARTIFACT_LINKS_NEED_SERVER_HINT = + "Set the server URL in Settings to copy artifact links." + +/** + * The bulk copy/share actions the artifacts action bar exposes, built by + * [artifactSelectionActions] so the run-summary grid and the stage pane's + * per-visit list share one implementation and can never drift. + */ +internal data class ArtifactSelectionActions( + val copyLinks: () -> Unit, + val shareSelected: () -> Unit, +) + +/** + * The one implementation of the action bar's **Copy links** and **Share** for + * [selectedArtifacts] resolved against [configuredServerUrl]: copy writes one + * absolute link per line through the single clipboard path and confirms it on + * [snackbarHostState] (or shows [ARTIFACT_LINKS_NEED_SERVER_HINT] when nothing + * resolves), and share fetches every selected artifact through + * [fetchArtifactBytes] and sends them together. Both artifact surfaces call this, + * so the payload and the share fallback are identical everywhere. + */ +@Composable +internal fun artifactSelectionActions( + selectedArtifacts: List, + configuredServerUrl: String, + fetchArtifactBytes: suspend (String) -> ByteArray?, + snackbarHostState: SnackbarHostState, +): ArtifactSelectionActions { + val context = LocalContext.current + val clipboard = LocalClipboardManager.current + val scope = rememberCoroutineScope() + return ArtifactSelectionActions( + copyLinks = { + val text = artifactSelectionLinks(selectedArtifacts, configuredServerUrl) + scope.launch { + // No configured server means no absolute link to copy; show the + // hint rather than copying a relative url. The confirmation counts + // the lines actually written, never the raw selection size. + if (text.isBlank()) { + snackbarHostState.showSnackbar(ARTIFACT_LINKS_NEED_SERVER_HINT) + } else { + clipboard.copyText(text) + snackbarHostState.showSnackbar(selectionCopiedMessage(text.lines().size)) + } + } + }, + shareSelected = { + val targets = shareTargets(selectedArtifacts, configuredServerUrl) + scope.launch { shareArtifacts(context, targets, fetchArtifactBytes) } + }, + ) +} + +/** + * The one artifact-selection host both artifact surfaces share (the run + * summary's grid and the stage pane's per-visit list): it owns [selectionState], + * resolves the selected artifacts from [candidates] with [resolvedSelection], + * builds the bulk copy/share actions, runs the Back-leaves-selection-first + * handler and renders the contextual [ArtifactSelectionBar] in place of [topBar] + * while [enabled] and the selection actually maps to artifacts. [content] gets + * the resolved [ArtifactSelection] plus the scaffold padding, so a surface's + * gallery and body stay inside the system bars and the two surfaces can never + * drift. + * + * A selection whose urls no longer map to [candidates] (a stale or restored set) + * is cleared, so selection mode is never active with nothing behind it and a tap + * can never toggle invisibly with no bar to exit. + */ +@Composable +internal fun ArtifactSelectionScaffold( + selectionState: MutableState, + candidates: List, + configuredServerUrl: String, + fetchArtifactBytes: suspend (String) -> ByteArray?, + modifier: Modifier = Modifier, + containerColor: Color = MaterialTheme.colorScheme.surface, + enabled: Boolean = true, + topBar: @Composable () -> Unit, + content: @Composable ( + selection: ArtifactSelection, + onSelectionChange: (ArtifactSelection) -> Unit, + padding: PaddingValues, + ) -> Unit, +) { + val selection = selectionState.value + // Derived once per data change, never per recomposition. + val selectedArtifacts = remember(selection, candidates) { + resolvedSelection(candidates, selection) + } + val selecting = enabled && selectedArtifacts.isNotEmpty() + val onSelectionChange: (ArtifactSelection) -> Unit = { selectionState.value = it } + // Keep the mode and the resolved set in sync: a selection that resolves to + // nothing (stale urls after a data change, or a restore on a surface that no + // longer shows them) is cleared, so `active` always means "taps toggle and a + // bar is showing". + LaunchedEffect(selection, selectedArtifacts, enabled) { + if (selection.active && (selectedArtifacts.isEmpty() || !enabled)) { + selectionState.value = ArtifactSelection() + } + } + // Back leaves selection mode first; only then does the surface's own Back run. + BackHandler(enabled = selecting) { selectionState.value = ArtifactSelection() } + + val snackbarHostState = remember { SnackbarHostState() } + val actions = artifactSelectionActions( + selectedArtifacts = selectedArtifacts, + configuredServerUrl = configuredServerUrl, + fetchArtifactBytes = fetchArtifactBytes, + snackbarHostState = snackbarHostState, + ) + Scaffold( + modifier = modifier, + containerColor = containerColor, + contentWindowInsets = paneSafeArea(), + snackbarHost = { SnackbarHost(snackbarHostState) }, + topBar = { + if (selecting) { + // The contextual bar replaces the app bar (inside the safe area, + // above the items) so it never covers what it acts on. + ArtifactSelectionBar( + count = selectedArtifacts.size, + onCopyLinks = actions.copyLinks, + onShare = actions.shareSelected, + onClose = { selectionState.value = ArtifactSelection() }, + containerColor = containerColor, + ) + } else { + topBar() + } + }, + ) { padding -> content(selection, onSelectionChange, padding) } +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactSharing.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactSharing.kt index ffa3acf1..210d0e73 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactSharing.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactSharing.kt @@ -1,12 +1,15 @@ package net.awan.pipelines.ui.graph import android.content.ClipData +import android.content.ClipDescription import android.content.Context import android.content.Intent +import android.net.Uri import androidx.core.content.FileProvider import java.io.File import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext +import net.awan.pipelines.data.protocol.StageArtifact /** * How a share action delivers an artifact. [File] streams the fetched bytes to a @@ -109,6 +112,38 @@ internal fun shareMimeType(contentType: String, fileName: String): String { ?: "application/octet-stream" } +/** + * One selected artifact resolved for a bulk share: its absolute [url] plus the + * name and content type the intent needs. Built by [shareTargets], so the same + * resolution the single-item share uses is applied to every item. + */ +internal data class ShareTarget(val url: String, val name: String, val contentType: String) + +/** + * The resolved share targets of [artifacts] against [configuredServerUrl]; + * unresolvable urls are dropped. Pure. + */ +internal fun shareTargets( + artifacts: List, + configuredServerUrl: String, +): List = artifacts.mapNotNull { artifact -> + resolvedArtifactUrl(artifact, configuredServerUrl)?.let { + ShareTarget(it, artifact.name, artifact.contentType) + } +} + +/** + * The MIME an intent carrying several [targets] declares: the one type they all + * share (each derived by the single-item [shareMimeType]), or the wildcard type + * for a mixed set. Pure, so the declared type is unit-tested without a device. + */ +internal fun bulkShareMimeType(targets: List): String { + val mimes = targets.map { + shareMimeType(it.contentType, artifactFileName(it.name, it.url, it.contentType)) + }.distinct() + return if (mimes.size == 1) mimes.first() else "*/*" +} + /** * Fetches [url]'s resolved artifact through the app's existing client and shares * it: the bytes go to the app cache and out through [Intent.ACTION_SEND]-with- @@ -126,30 +161,97 @@ internal suspend fun shareArtifact( val bytes = runCatching { fetchBytes(url) }.getOrNull() // A fetched file is preferred; a failed fetch, an unwritable cache or a // provider that cannot hand the file out all degrade to the link. - val sharedFile = shareDelivery(bytes) == ShareDelivery.File && - runCatching { shareFile(context, bytes!!, url, name, contentType) }.getOrDefault(false) + val uri = writeSharedArtifact(context, bytes, url, name, contentType) + val sharedFile = uri != null && runCatching { + launchFileShare(context, uri, url, name, contentType) + }.isSuccess if (!sharedFile) shareLink(context, url) } -/** Writes the fetched bytes and launches the file share; false when no uri could be built. */ -private suspend fun shareFile( +/** + * Fetches and shares every [targets] in one action. Each file goes through the + * same bounded cache and [FileProvider] path as the single share + * ([writeSharedArtifact]), and all the uris then leave together in one + * [Intent.ACTION_SEND_MULTIPLE] whose type is [bulkShareMimeType] and whose + * chooser title carries the item count. If fetching any item fails the whole set + * degrades, in the same action, to its resolved links shared as text. Never + * throws. + */ +internal suspend fun shareArtifacts( context: Context, - bytes: ByteArray, + targets: List, + fetchBytes: suspend (String) -> ByteArray?, +) { + if (targets.isEmpty()) return + // Prepare the bounded shared cache once for the whole set (created + pruned), + // not per item, so a bulk share does its filesystem bookkeeping a single time. + val dir = runCatching { sharedArtifactDir(context) }.getOrNull() + if (dir == null) { + shareLinks(context, targets.map { it.url }) + return + } + val uris = ArrayList(targets.size) + for (target in targets) { + val bytes = runCatching { fetchBytes(target.url) }.getOrNull() + val uri = writeSharedArtifact(context, bytes, target.url, target.name, target.contentType, dir) + if (uri == null) { + // Any failure is the set's failure: fall back to the links for all. + shareLinks(context, targets.map { it.url }) + return + } + uris += uri + } + launchMultiFileShare(context, uris, targets) +} + +/** + * The bounded shared-artifact cache directory, created if missing and pruned. + * Callers that write more than one file prepare it once and pass it to + * [writeSharedArtifact], so the filesystem work is not repeated per artifact. + */ +private suspend fun sharedArtifactDir(context: Context): File = withContext(Dispatchers.IO) { + File(context.applicationContext.cacheDir, SHARED_ARTIFACT_DIR).also { + it.mkdirs() + pruneSharedArtifacts(it) + } +} + +/** + * Writes [bytes] into [dir] (the bounded shared-artifact cache, prepared by + * [sharedArtifactDir] when not supplied) and returns its shareable [Uri], or null + * when there is nothing to write or the cache/provider cannot produce one. Never + * throws, so both the single and the bulk share can degrade to a link instead. + */ +private suspend fun writeSharedArtifact( + context: Context, + bytes: ByteArray?, url: String, name: String, contentType: String?, -): Boolean { - val file = withContext(Dispatchers.IO) { - val dir = File(context.applicationContext.cacheDir, SHARED_ARTIFACT_DIR) - dir.mkdirs() - pruneSharedArtifacts(dir) - File(dir, artifactFileName(name, url, contentType)).also { it.writeBytes(bytes) } - } - val uri = runCatching { + dir: File? = null, +): Uri? { + // Capture the non-null bytes from the delivery check instead of asserting + // them later inside the coroutine, where a stray null would be a crash. + val fileBytes = bytes.takeIf { shareDelivery(it) == ShareDelivery.File } ?: return null + return runCatching { + val file = withContext(Dispatchers.IO) { + val targetDir = dir ?: sharedArtifactDir(context) + File(targetDir, artifactFileName(name, url, contentType)).also { it.writeBytes(fileBytes) } + } FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file) - }.getOrNull() ?: return false + }.getOrNull() +} + +/** Launches the single-file share of an already-written [uri]. */ +private fun launchFileShare( + context: Context, + uri: Uri, + url: String, + name: String, + contentType: String?, +) { val intent = Intent(Intent.ACTION_SEND).apply { - type = shareMimeType(contentType.orEmpty(), file.name) + type = shareMimeType(contentType.orEmpty(), artifactFileName(name, url, contentType)) putExtra(Intent.EXTRA_STREAM, uri) putExtra(Intent.EXTRA_TITLE, name) // A ClipData carrying the same uri lets the sharesheet read the stream @@ -159,21 +261,49 @@ private suspend fun shareFile( addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) } launchShare(context, intent) - return true } -private fun shareLink(context: Context, url: String) { +/** + * Launches the multi-file share: one [Intent.ACTION_SEND_MULTIPLE] carrying every + * [uri], typed by [bulkShareMimeType] and labelled with the item count, with a + * ClipData that carries the same uris and their type so the sharesheet can read + * each stream. The chooser title also names the count. + */ +private fun launchMultiFileShare(context: Context, uris: List, targets: List) { + val label = "${targets.size} artifacts" + val mime = bulkShareMimeType(targets) + val intent = Intent(Intent.ACTION_SEND_MULTIPLE).apply { + type = mime + putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(uris)) + putExtra(Intent.EXTRA_TITLE, label) + clipData = ClipData(ClipDescription(label, arrayOf(mime)), ClipData.Item(uris.first())).apply { + uris.drop(1).forEach { addItem(ClipData.Item(it)) } + } + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + launchShare(context, intent, label) +} + +private fun shareLink(context: Context, url: String) = shareLinks(context, listOf(url)) + +/** Shares [urls] as one newline-joined plain-text payload. */ +private fun shareLinks(context: Context, urls: List) { + val text = urls.joinToString("\n") val intent = Intent(Intent.ACTION_SEND).apply { type = "text/plain" - putExtra(Intent.EXTRA_TEXT, url) - clipData = ClipData.newPlainText(null, url) + putExtra(Intent.EXTRA_TEXT, text) + clipData = ClipData.newPlainText(null, text) } launchShare(context, intent) } -/** Shows the platform chooser for [intent], tolerating a missing handler. */ -private fun launchShare(context: Context, intent: Intent) { - runCatching { context.startActivity(Intent.createChooser(intent, null)) } +/** + * Shows the platform chooser for [intent], tolerating a missing handler. An + * optional [chooserTitle] is the chooser headline (the bulk share puts the item + * count there). + */ +private fun launchShare(context: Context, intent: Intent, chooserTitle: CharSequence? = null) { + runCatching { context.startActivity(Intent.createChooser(intent, chooserTitle)) } } /** diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactViewer.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactViewer.kt index 2b44cb6b..eb4b2158 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactViewer.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactViewer.kt @@ -48,12 +48,12 @@ import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalView -import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import androidx.compose.ui.window.DialogWindowProvider +import net.awan.pipelines.ui.components.copyText import net.awan.pipelines.ui.components.paneSafeArea import net.awan.pipelines.ui.theme.pipelinesText import kotlin.math.abs @@ -287,7 +287,7 @@ private fun ArtifactViewerActions( IconButton(onClick = { openArtifact(context, url) }) { Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = "Open $name externally") } - IconButton(onClick = { clipboard.setText(AnnotatedString(url)) }) { + IconButton(onClick = { clipboard.copyText(url) }) { Icon(Icons.Default.ContentCopy, contentDescription = "Copy link to $name") } IconButton(onClick = onDismiss) { diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/Artifacts.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/Artifacts.kt index f8d9f890..33d7218c 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/graph/Artifacts.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/Artifacts.kt @@ -3,8 +3,10 @@ package net.awan.pipelines.ui.graph import android.content.Context import android.content.Intent import android.net.Uri +import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background -import androidx.compose.foundation.clickable +import androidx.compose.foundation.border +import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints @@ -18,10 +20,12 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.InsertDriveFile import androidx.compose.material.icons.automirrored.filled.OpenInNew +import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.Share import androidx.compose.material3.Icon import androidx.compose.material3.IconButton +import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text @@ -36,7 +40,8 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp @@ -48,6 +53,7 @@ import net.awan.pipelines.ui.ArtifactGroup import net.awan.pipelines.ui.artifactCaptureNotes import net.awan.pipelines.ui.artifactMetaLine import net.awan.pipelines.ui.artifactsSummary +import net.awan.pipelines.ui.components.copyText import net.awan.pipelines.ui.isImageContentType import net.awan.pipelines.ui.theme.pipelinesText @@ -67,6 +73,8 @@ internal fun ArtifactsSection( configuredServerUrl: String, fetchArtifactBytes: suspend (String) -> ByteArray?, modifier: Modifier = Modifier, + selection: ArtifactSelection = ArtifactSelection(), + onSelectionChange: (ArtifactSelection) -> Unit = {}, ) { val text = pipelinesText() // Derived once per data change, never per recomposition (performance requirement). @@ -90,6 +98,8 @@ internal fun ArtifactsSection( configuredServerUrl = configuredServerUrl, fetchArtifactBytes = fetchArtifactBytes, showHeaders = false, + selection = selection, + onSelectionChange = onSelectionChange, ) } } @@ -115,6 +125,8 @@ internal fun ArtifactGallery( fetchArtifactBytes: suspend (String) -> ByteArray?, modifier: Modifier = Modifier, showHeaders: Boolean = true, + selection: ArtifactSelection = ArtifactSelection(), + onSelectionChange: (ArtifactSelection) -> Unit = {}, ) { val text = pipelinesText() BoxWithConstraints(modifier.fillMaxWidth()) { @@ -139,7 +151,14 @@ internal fun ArtifactGallery( horizontalArrangement = Arrangement.spacedBy(ARTIFACT_TILE_SPACING_DP), ) { rowArtifacts.forEach { artifact -> - ArtifactTile(artifact, configuredServerUrl, fetchArtifactBytes, grid.cell) + ArtifactTile( + artifact = artifact, + configuredServerUrl = configuredServerUrl, + fetchArtifactBytes = fetchArtifactBytes, + tile = grid.cell, + selection = selection, + onSelectionChange = onSelectionChange, + ) } // Keep a partial last row's tiles aligned to the grid. repeat(grid.columns - rowArtifacts.size) { @@ -148,7 +167,13 @@ internal fun ArtifactGallery( } } others.forEach { artifact -> - ArtifactRow(artifact, configuredServerUrl, fetchArtifactBytes) + ArtifactRow( + artifact = artifact, + configuredServerUrl = configuredServerUrl, + fetchArtifactBytes = fetchArtifactBytes, + selection = selection, + onSelectionChange = onSelectionChange, + ) } } } @@ -186,25 +211,55 @@ internal fun artifactGrid(availableWidth: Dp, preferred: Dp, spacing: Dp): Artif internal fun resolvedArtifactUrl(artifact: StageArtifact, configuredServerUrl: String): String? = ServerUrl.resolveArtifactUrl(configuredServerUrl, artifact.url) -/** One image artifact as a square thumbnail that opens the full-size view. */ +/** + * One image artifact as a square thumbnail that opens the full-size view. A + * long-press enters artifact selection on this item; while selection mode is + * active a tap toggles it instead of opening, and the selected cell gets the + * app's selected treatment (a tonal ring + check badge in the shared + * secondaryContainer/onSecondaryContainer roles, and the `selected` semantics + * state). The per-item share control is hidden while selecting so the whole cell + * is the toggle target. + */ +@OptIn(ExperimentalFoundationApi::class) @Composable private fun ArtifactTile( artifact: StageArtifact, configuredServerUrl: String, fetchArtifactBytes: suspend (String) -> ByteArray?, tile: Dp, + selection: ArtifactSelection, + onSelectionChange: (ArtifactSelection) -> Unit, ) { // Resolve once per (url, configuration), not on every recomposition. val resolved = remember(artifact.url, configuredServerUrl) { resolvedArtifactUrl(artifact, configuredServerUrl) } var showFull by remember(artifact.url) { mutableStateOf(false) } + val selected = selection.contains(artifact.url) Box( Modifier .size(tile) .clip(RoundedCornerShape(12.dp)) - .clickable(enabled = resolved != null) { showFull = true }, + .then( + if (selected) { + Modifier.border(3.dp, MaterialTheme.colorScheme.secondary, RoundedCornerShape(12.dp)) + } else { + Modifier + }, + ) + .combinedClickable( + onClick = { + if (selection.active) { + onSelectionChange(selection.toggle(artifact.url)) + } else if (resolved != null) { + showFull = true + } + }, + onLongClick = { onSelectionChange(selection.enter(artifact.url)) }, + onLongClickLabel = "Select ${artifact.name}", + ) + .semantics { this.selected = selected }, ) { // Pass the resolved url (null when there is no configured server): a // null never triggers a relative-url fetch, it shows the distinct @@ -216,15 +271,38 @@ private fun ArtifactTile( fetchBytes = fetchArtifactBytes, size = tile, ) - // The share control is its own hit area over the thumbnail: it consumes - // the tap, so sharing never falls through to open the full-size view. - ArtifactShareButton( - artifact = artifact, - resolved = resolved, - fetchArtifactBytes = fetchArtifactBytes, - modifier = Modifier.align(Alignment.TopEnd), - scrim = true, - ) + if (selection.active) { + // While the gallery is selecting, no item exposes its own share + // control: every tap toggles, so only the selected cells carry the + // check badge and the whole tile stays a toggle target. + if (selected) { + Box( + Modifier + .align(Alignment.TopStart) + .padding(4.dp) + .background(MaterialTheme.colorScheme.secondaryContainer, CircleShape), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.Default.Check, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSecondaryContainer, + modifier = Modifier.padding(4.dp).size(16.dp), + ) + } + } + } else { + // The share control is its own hit area over the thumbnail: it + // consumes the tap, so sharing never falls through to open the + // full-size view. + ArtifactShareButton( + artifact = artifact, + resolved = resolved, + fetchArtifactBytes = fetchArtifactBytes, + modifier = Modifier.align(Alignment.TopEnd), + scrim = true, + ) + } } // The tap opens the full-screen viewer (one shared instance across the run @@ -240,12 +318,22 @@ private fun ArtifactTile( } } -/** One non-image artifact: a file glyph, name, size/type and open/share/copy actions. */ +/** + * One non-image artifact: a file glyph, name, size/type and open/share/copy + * actions. A long-press enters artifact selection on this item; while selection + * mode is active a tap toggles it and the row wears the app's selected treatment + * (the secondaryContainer/onSecondaryContainer roles the list rows use, plus the + * `selected` semantics state), with the per-item actions swapped for a check. + * When not selecting, a tap opens the artifact. + */ +@OptIn(ExperimentalFoundationApi::class) @Composable private fun ArtifactRow( artifact: StageArtifact, configuredServerUrl: String, fetchArtifactBytes: suspend (String) -> ByteArray?, + selection: ArtifactSelection, + onSelectionChange: (ArtifactSelection) -> Unit, ) { val text = pipelinesText() val context = LocalContext.current @@ -255,11 +343,34 @@ private fun ArtifactRow( resolvedArtifactUrl(artifact, configuredServerUrl) } val metaLine = remember(artifact) { artifactMetaLine(artifact) } + val selected = selection.contains(artifact.url) Surface( shape = RoundedCornerShape(12.dp), - color = MaterialTheme.colorScheme.surfaceContainerHigh, - modifier = Modifier.fillMaxWidth(), + color = if (selected) { + MaterialTheme.colorScheme.secondaryContainer + } else { + MaterialTheme.colorScheme.surfaceContainerHigh + }, + contentColor = if (selected) { + MaterialTheme.colorScheme.onSecondaryContainer + } else { + LocalContentColor.current + }, + modifier = Modifier + .fillMaxWidth() + .combinedClickable( + onClick = { + if (selection.active) { + onSelectionChange(selection.toggle(artifact.url)) + } else { + openArtifact(context, resolved) + } + }, + onLongClick = { onSelectionChange(selection.enter(artifact.url)) }, + onLongClickLabel = "Select ${artifact.name}", + ) + .semantics { this.selected = selected }, ) { Row( modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp), @@ -273,7 +384,7 @@ private fun ArtifactRow( Icon( imageVector = Icons.AutoMirrored.Filled.InsertDriveFile, contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, + tint = LocalContentColor.current, ) } Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { @@ -290,23 +401,37 @@ private fun ArtifactRow( overflow = TextOverflow.Ellipsis, ) } - IconButton( - onClick = { openArtifact(context, resolved) }, - enabled = resolved != null, - ) { - Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = "Open ${artifact.name}") + if (selection.active) { + // While selecting, the row's own open/copy/share controls are + // hidden so a tap anywhere on it toggles the selection instead + // of acting on the single item; only the selected row shows the + // check. + if (selected) { + Icon( + imageVector = Icons.Default.Check, + contentDescription = null, + modifier = Modifier.padding(horizontal = 12.dp), + ) + } + } else { + IconButton( + onClick = { openArtifact(context, resolved) }, + enabled = resolved != null, + ) { + Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = "Open ${artifact.name}") + } + IconButton( + onClick = { resolved?.let { clipboard.copyText(it) } }, + enabled = resolved != null, + ) { + Icon(Icons.Default.ContentCopy, contentDescription = "Copy link to ${artifact.name}") + } + ArtifactShareButton( + artifact = artifact, + resolved = resolved, + fetchArtifactBytes = fetchArtifactBytes, + ) } - IconButton( - onClick = { resolved?.let { clipboard.setText(AnnotatedString(it)) } }, - enabled = resolved != null, - ) { - Icon(Icons.Default.ContentCopy, contentDescription = "Copy link to ${artifact.name}") - } - ArtifactShareButton( - artifact = artifact, - resolved = resolved, - fetchArtifactBytes = fetchArtifactBytes, - ) } } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt index 1d021e22..c7d82d00 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt @@ -17,7 +17,6 @@ import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.PrimaryScrollableTabRow -import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Tab import androidx.compose.material3.Text @@ -298,7 +297,7 @@ internal fun showVisitTabs(visitCount: Int): Boolean = visitCount > 1 /** * The stage pane's content: opened as the rightmost level of the sliding stack * from a timeline entry or a graph node, exactly like the list and detail panes, - * so there is no popup anywhere. It carries its own [Scaffold]/[TopAppBar] with a + * so there is no popup anywhere. It carries its own Scaffold/[TopAppBar] with a * back arrow that pops one level (the same step as the peek tap and system Back). * * [runSteps] is every recorded visit of the stage in order; when there is more @@ -334,10 +333,32 @@ fun StageDetailPane( ) return } - Scaffold( + + // The selected visit is owned here so the selection's copy/share actions in + // the top bar and the body's per-visit artifacts section read the same step. + // Reset when the stage changes; saved across configuration. + var visitIndex by rememberSaveable(stageKey) { + mutableIntStateOf(clampVisitIndex(initialVisitIndex, runSteps.size)) + } + val clampedVisit = clampVisitIndex(visitIndex, runSteps.size) + val selectedStep = runSteps.getOrNull(clampedVisit) + val visitArtifacts = remember(selectedStep) { selectedStep?.artifacts.orEmpty() } + + // The artifact selection for this visit: a long-press enters it, a tap + // toggles. Keyed on the visit, so switching visits leaves selection mode; it + // restores fully (or not at all) after rotation. + val selectionState = rememberArtifactSelection(stageKey, clampedVisit) + + // The shared selection host owns the selection, the contextual bar, the bulk + // copy/share actions and Back-leaves-selection-first; the two artifact + // surfaces go through it so they can never drift. + ArtifactSelectionScaffold( + selectionState = selectionState, + candidates = visitArtifacts, + configuredServerUrl = configuredServerUrl, + fetchArtifactBytes = fetchArtifactBytes, modifier = modifier, containerColor = paneContainerColor(), - contentWindowInsets = paneSafeArea(), topBar = { TopAppBar( title = { Text(GraphSemantics.nodeLabel(stageKey)) }, @@ -350,16 +371,20 @@ fun StageDetailPane( colors = TopAppBarDefaults.topAppBarColors(containerColor = paneContainerColor()), ) }, - ) { padding -> + ) { selection, onSelectionChange, padding -> StageDetailBody( stageKey = stageKey, graph = graph, runSteps = runSteps, - initialVisitIndex = initialVisitIndex, + selectedStep = selectedStep, + visitIndex = clampedVisit, + onVisitIndexChange = { visitIndex = it }, configuredServerUrl = configuredServerUrl, fetchArtifactBytes = fetchArtifactBytes, wide = wide, runContext = runContext, + selection = selection, + onSelectionChange = onSelectionChange, modifier = Modifier.padding(padding), ) } @@ -372,11 +397,15 @@ private fun StageDetailBody( stageKey: String, graph: Graph, runSteps: List, - initialVisitIndex: Int, + selectedStep: RunStep?, + visitIndex: Int, + onVisitIndexChange: (Int) -> Unit, configuredServerUrl: String, fetchArtifactBytes: suspend (String) -> ByteArray?, wide: Boolean, runContext: Boolean, + selection: ArtifactSelection, + onSelectionChange: (ArtifactSelection) -> Unit, modifier: Modifier = Modifier, ) { val text = pipelinesText() @@ -386,13 +415,7 @@ private fun StageDetailBody( } val typeLabel = if (stage != null) effectiveStageType(stage.type) else "terminal" - // Reset the selected visit when the stage (but not the user's tap within it) - // changes; saved so it survives recomposition/configuration. - var visitIndex by rememberSaveable(stageKey) { - mutableIntStateOf(clampVisitIndex(initialVisitIndex, runSteps.size)) - } val clampedVisit = clampVisitIndex(visitIndex, runSteps.size) - val selectedStep = runSteps.getOrNull(clampedVisit) // Derived once per selected step, not per recomposition. Only the run-side // facts lead the pane; the stage's own configs stay in the definition section. val runFields = remember(selectedStep) { selectedStep?.let(::runStepFields).orEmpty() } @@ -434,7 +457,7 @@ private fun StageDetailBody( runSteps.forEachIndexed { index, _ -> Tab( selected = index == clampedVisit, - onClick = { visitIndex = index }, + onClick = { onVisitIndexChange(index) }, text = { Text("visit ${index + 1}", maxLines = 1) }, ) } @@ -458,6 +481,8 @@ private fun StageDetailBody( step = selectedStep, configuredServerUrl = configuredServerUrl, fetchArtifactBytes = fetchArtifactBytes, + selection = selection, + onSelectionChange = onSelectionChange, ) } StageResultSection.Output -> if (outputFields.isNotEmpty()) { diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt index 41a9fe67..8e97e4ab 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt @@ -42,7 +42,6 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalClipboardManager -import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import net.awan.pipelines.data.ErrorMessages @@ -58,6 +57,7 @@ import net.awan.pipelines.ui.components.LoadingState import net.awan.pipelines.ui.components.PaneIdentity import net.awan.pipelines.ui.components.paneSafeArea import net.awan.pipelines.ui.components.collapsibleSection +import net.awan.pipelines.ui.components.copyText import net.awan.pipelines.ui.components.pipelineDetailTabs import net.awan.pipelines.ui.components.rememberSectionExpansion import net.awan.pipelines.ui.graph.StageFieldRow @@ -289,7 +289,7 @@ private fun PipelineSourceTab(detail: PipelineDetail, modifier: Modifier) { OutlinedButton(onClick = { showRaw = !showRaw }) { Text(if (showRaw) "Rendered" else "Raw") } - OutlinedButton(onClick = { clipboard.setText(AnnotatedString(detail.source)) }) { + OutlinedButton(onClick = { clipboard.copyText(detail.source) }) { Icon( imageVector = Icons.Default.ContentCopy, contentDescription = null, diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt index 99e2caed..8dc11405 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt @@ -28,7 +28,6 @@ import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar @@ -51,6 +50,7 @@ import net.awan.pipelines.data.protocol.RunGraphState import net.awan.pipelines.data.protocol.RunStep import net.awan.pipelines.data.protocol.SessionEvidence import net.awan.pipelines.ui.AppViewModel +import net.awan.pipelines.ui.ArtifactGroup import net.awan.pipelines.ui.LoadState import net.awan.pipelines.ui.components.CodeBlock import net.awan.pipelines.ui.components.DetailTabBody @@ -63,6 +63,7 @@ import net.awan.pipelines.ui.components.paneSafeArea import net.awan.pipelines.ui.components.RunStatusIcon import net.awan.pipelines.ui.components.StatusChip import net.awan.pipelines.ui.components.collapsibleSection +import net.awan.pipelines.ui.components.clampTabIndex import net.awan.pipelines.ui.components.rememberSectionExpansion import net.awan.pipelines.ui.components.runDetailTabs import net.awan.pipelines.ui.components.runStateOf @@ -70,7 +71,10 @@ import net.awan.pipelines.ui.displayText import net.awan.pipelines.ui.formatDuration import net.awan.pipelines.ui.artifactsEmptyMessage import net.awan.pipelines.ui.graph.ArtifactGallery +import net.awan.pipelines.ui.graph.ArtifactSelection +import net.awan.pipelines.ui.graph.ArtifactSelectionScaffold import net.awan.pipelines.ui.graph.WorkflowGraph +import net.awan.pipelines.ui.graph.rememberArtifactSelection import net.awan.pipelines.ui.runArtifactGroups import net.awan.pipelines.ui.theme.pipelinesText import net.awan.pipelines.ui.visitCount @@ -95,6 +99,11 @@ fun RunDetailScreen( var confirmRetry by remember { mutableStateOf(false) } var actionError by remember { mutableStateOf(null) } + // The artifacts selection for this run: entered by a long-press on any + // artifact in the summary grid, remembered/saved per run so it restores fully + // (or not at all) across rotation and never leaks into another run. + val selectionState = rememberArtifactSelection(runId) + LaunchedEffect(runId) { // Scope evidence to this run: drop the previous run's records, then fetch // this run's evidence once (on demand; never part of the 1s poll). @@ -116,6 +125,14 @@ fun RunDetailScreen( } } + // Aggregated once per step-list change; it drives the grid and the + // selection's copy/share actions, never recomputed per recomposition. + val artifactGroups = remember(run?.steps) { runArtifactGroups(run?.steps.orEmpty()) } + val candidateArtifacts = remember(artifactGroups) { + artifactGroups.flatMap { it.artifacts }.distinctBy { it.url } + } + val summaryTab = runDetailTabs.getOrNull(clampTabIndex(selectedSection, runDetailTabs.size))?.key + // A covered pane shows its compact identity only; the tab rail, timeline and // graphs must never be drawn squeezed into the peek strip. if (covered) { @@ -127,9 +144,16 @@ fun RunDetailScreen( return } - Scaffold( + // The shared selection host owns the selection, the contextual bar, the bulk + // copy/share actions and Back-leaves-selection-first. Selection applies only + // on the summary tab, where the grid lives; leaving it clears the selection. + ArtifactSelectionScaffold( + selectionState = selectionState, + candidates = candidateArtifacts, + configuredServerUrl = configuredServerUrl, + fetchArtifactBytes = vm::fetchArtifactBytes, modifier = modifier, - contentWindowInsets = paneSafeArea(), + enabled = summaryTab == "summary", topBar = { TopAppBar( title = { Text(run?.let { "Run ${it.id}" } ?: "Run") }, @@ -156,7 +180,7 @@ fun RunDetailScreen( }, ) }, - ) { padding -> + ) { selection, onSelectionChange, padding -> when { run == null && state.error != null -> ErrorState( state.error!!, @@ -180,6 +204,9 @@ fun RunDetailScreen( modifier = contentModifier, configuredServerUrl = configuredServerUrl, fetchArtifactBytes = vm::fetchArtifactBytes, + artifactGroups = artifactGroups, + selection = selection, + onSelectionChange = onSelectionChange, ) "graph" -> RunGraphTab( run = run, @@ -291,11 +318,12 @@ private fun RunSummaryTab( modifier: Modifier, configuredServerUrl: String, fetchArtifactBytes: suspend (String) -> ByteArray?, + artifactGroups: List, + selection: ArtifactSelection, + onSelectionChange: (ArtifactSelection) -> Unit, ) { val text = pipelinesText() val state = runStateOf(run.status) - // Aggregated once per step-list change, never per recomposition. - val artifactGroups = remember(run.steps) { runArtifactGroups(run.steps) } DetailTabBody(wide, modifier) { columnModifier -> LazyColumn( modifier = columnModifier, @@ -317,6 +345,8 @@ private fun RunSummaryTab( groups = artifactGroups, configuredServerUrl = configuredServerUrl, fetchArtifactBytes = fetchArtifactBytes, + selection = selection, + onSelectionChange = onSelectionChange, ) } } diff --git a/android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactSelectionTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactSelectionTest.kt new file mode 100644 index 00000000..d76bcb3a --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactSelectionTest.kt @@ -0,0 +1,109 @@ +package net.awan.pipelines.ui.graph + +import net.awan.pipelines.data.protocol.StageArtifact +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Pure-logic tests for the artifact selection model and the bulk "Copy links" + * formatting: entering/toggling/selecting-all/clearing selection, the restored + * (post-rotation) state, and the one-per-line resolved link payload. No device or + * network is involved. + */ +class ArtifactSelectionTest { + + private val shot = StageArtifact("shot.png", 10, "image/png", "/artifacts/1/1/shot.png") + private val log = StageArtifact("log.txt", 20, "text/plain", "/artifacts/1/1/log.txt") + + @Test + fun enterSelectsOnlyTheLongPressedItem() { + val selection = ArtifactSelection().enter(shot.url) + assertTrue(selection.active) + assertEquals(1, selection.count) + assertTrue(selection.contains(shot.url)) + assertFalse(selection.contains(log.url)) + } + + @Test + fun toggleAddsThenRemovesAnItem() { + var selection = ArtifactSelection().enter(shot.url) + selection = selection.toggle(log.url) + assertEquals(listOf(shot.url, log.url), selection.urls) + selection = selection.toggle(shot.url) + assertEquals(listOf(log.url), selection.urls) + assertTrue(selection.active) + } + + @Test + fun deselectingTheLastItemLeavesSelectionMode() { + val selection = ArtifactSelection().enter(shot.url).toggle(shot.url) + assertFalse(selection.active) + assertEquals(0, selection.count) + } + + @Test + fun selectAllTakesEveryUrlOnceAndClearLeavesTheMode() { + val selected = ArtifactSelection().selectAll(listOf(shot.url, log.url, shot.url)) + assertEquals(2, selected.count) + assertTrue(selected.active) + val cleared = selected.clear() + assertFalse(cleared.active) + assertTrue(cleared.urls.isEmpty()) + } + + @Test + fun restoredStateIsFullyAppliedOrNotActiveAtAll() { + val restored = ArtifactSelectionSaver.restore(listOf(shot.url, log.url)) + assertEquals(2, restored?.count) + assertTrue(restored!!.active) + // An empty saved set can never come back as a half-applied selection mode. + val empty = ArtifactSelectionSaver.restore(emptyList()) + assertFalse(empty!!.active) + } + + @Test + fun resolvedSelectionKeepsOnlyTheCandidatesStillSelected() { + val selection = ArtifactSelection().enter(shot.url).toggle(log.url) + assertEquals(listOf(shot, log), resolvedSelection(listOf(shot, log), selection)) + // A restored/stale url that is not among the surface's own artifacts + // resolves to nothing, so a tap can never toggle invisibly with no bar. + val stale = ArtifactSelection(listOf("/artifacts/9/9/gone.png")) + assertTrue(resolvedSelection(listOf(shot, log), stale).isEmpty()) + // An inactive selection resolves to nothing regardless of the candidates. + assertTrue(resolvedSelection(listOf(shot, log), ArtifactSelection()).isEmpty()) + } + + @Test + fun selectionLinksJoinResolvedUrlsOnePerLine() { + val text = artifactSelectionLinks( + listOf(shot, log), + "ws://10.0.0.5:8081/connect", + ) + assertEquals( + "http://10.0.0.5:8081/artifacts/1/1/shot.png\n" + + "http://10.0.0.5:8081/artifacts/1/1/log.txt", + text, + ) + } + + @Test + fun selectionLinksDropUnresolvableRelativeUrlsButKeepAbsoluteOnes() { + assertEquals("", artifactSelectionLinks(listOf(shot), "")) + assertEquals( + "https://cdn.example/abs.png", + artifactSelectionLinks( + listOf(StageArtifact("abs.png", 1, "image/png", "https://cdn.example/abs.png")), + "", + ), + ) + } + + @Test + fun countAndConfirmationLabelsNameTheNumber() { + assertEquals("3 selected", selectionCountLabel(3)) + assertEquals("Copied 1 link", selectionCopiedMessage(1)) + assertEquals("Copied 2 links", selectionCopiedMessage(2)) + } +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactSharingTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactSharingTest.kt index 924a18ac..dfc88e46 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactSharingTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactSharingTest.kt @@ -68,4 +68,34 @@ class ArtifactSharingTest { assertEquals("application/pdf", shareMimeType("", "report_2.pdf")) assertEquals("application/octet-stream", shareMimeType("", "odd_3.xyz")) } + + @Test + fun shareTargetsResolveAgainstTheServerAndDropUnresolvableUrls() { + val artifacts = listOf( + net.awan.pipelines.data.protocol.StageArtifact( + "shot.png", 10, "image/png", imageUrl, + ), + net.awan.pipelines.data.protocol.StageArtifact("", 0, "", ""), + ) + val targets = shareTargets(artifacts, "ws://10.0.0.5:8081/connect") + assertEquals(1, targets.size) + assertEquals("http://10.0.0.5:8081/artifacts/60/4/00_start.png", targets.first().url) + assertEquals("image/png", targets.first().contentType) + // No configured server: a relative url resolves to nothing, so no target. + assertTrue(shareTargets(artifacts, "").isEmpty()) + } + + @Test + fun bulkShareMimeIsTheCommonTypeElseWildcard() { + val png = ShareTarget("http://h/a.png", "a.png", "image/png") + val png2 = ShareTarget("http://h/b.png", "b.png", "image/png") + val txt = ShareTarget("http://h/c.txt", "c.txt", "text/plain") + assertEquals("image/png", bulkShareMimeType(listOf(png, png2))) + assertEquals("*/*", bulkShareMimeType(listOf(png, txt))) + // A blank content type is inferred from the file's own extension. + assertEquals( + "application/pdf", + bulkShareMimeType(listOf(ShareTarget("http://h/r.pdf", "r.pdf", ""))), + ) + } }