diff --git a/android/README.md b/android/README.md index 8d504538..108db232 100644 --- a/android/README.md +++ b/android/README.md @@ -1907,6 +1907,53 @@ inner display at 390 dpi); an Android 8/9 device branch (the `layoutInDisplayCut Mode = SHORT_EDGES` fallback is compiled and lint-guarded but only the API 36 path ran). +## Page between artifacts in the full-screen viewer (17 Oct 2026) + +The full-screen viewer is now a pager: a horizontal drag or flick moves to the +previous/next image artifact in gallery order, and the header shows the open +artifact's position ("2 of 5", reloading that artifact's own name, content type, +image and actions). `ArtifactGallery` owns the one viewer instance over +`pagedArtifacts(groups)` (group by group, each group's images in recorded order — +the order the grid draws), and each tile resolves its viewer index through the new +`viewerIndexByUrl` from that same list, so the grid and the viewer cannot disagree +about which artifact a tap opens (previously a second, untested running counter). + +- **Gesture.** The paging/dismiss drag sits on a single full-screen surface in + `ArtifactViewerBody`, not on the image, so a drag that starts on the letterbox + around a fitted image pages too. The rule is "page only at fit": a pinch, or any + drag once the image is zoomed (`canPageAtScale`), pans via the shared + `zoomAbout`/`clampImageOffset` exactly as before. At the first/last artifact the + drag is damped (`PAGE_RESISTANCE`) and never wraps; a one-artifact gallery is + inert; a downward drag at fit still dismisses. The previous/next `IconButton`s + (disabled at each end) keep both neighbours reachable without a swipe, and a + loading/error/unavailable artifact shows its own state while its neighbours stay + reachable. The header, actions and page buttons share one `viewerCapsule()` + scrim background. +- **Pure helpers.** `pagedArtifacts`, `viewerIndexByUrl`, `pagedIndex` (the one + clamp shared by the gesture and the buttons) and `canPageAtScale` in + `ArtifactViewer.kt`. +- **Checks.** `gradle :app:testDebugUnitTest :app:assembleDebug --no-daemon` → + `BUILD SUCCESSFUL`; **317 tests, 0 failures, 0 errors, 0 skipped**. The paging + tests are in `ArtifactViewerTest` (`pagedIndex` next/previous, clamping at both + ends, a single-item and an empty list; `aZoomedViewerDoesNotPage`; + `pagedArtifactsAreTheGalleryImagesInGridOrder`; and + `theGridTileViewerIndicesMatchTheViewerOrder`, which walks the grid's draw order + and asserts every tile resolves to its viewer position). `gradle + :app:lintDebug` → only the two pre-existing `windowLightNavigationBar` NewApi + errors (`values/themes.xml`, `values-night/themes.xml`); 0 findings attributed to + `ArtifactViewer.kt` or `Artifacts.kt`. +- **APK publish.** `~/.local/share/pipelines/data/artifacts/224/3/pipelines-debug-wip-18db2f9.apk` + (`18db2f9` = `git rev-parse --short HEAD`), 18,093,313 bytes, md5 + `540168beaf3c7f5b7f19eaecd2c3099a`; `curl -I + http://10.0.0.75:8080/artifacts/224/3/pipelines-debug-wip-18db2f9.apk` returned + `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18093313`. Built with Gradle 8.11.1, AGP 8.7.2, JDK 17.0.10 + (Android Studio JBR), `compileSdk 35`/`build-tools 35.0.0`, minSdk 26. + +Not verified in this pass: the on-device swipe/zoom/back-gesture behaviour and the +narrow/wide covered-pane strip (the device is visual review's); this pass verified +only the build and the unit tests. + ## Share every artifact, from the grid cells and the per-visit rows (16 Oct 2026) Every artifact item now carries a real share action: each image cell in a gallery 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 9cca040f..3a6efc00 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 @@ -1,10 +1,11 @@ package net.awan.pipelines.ui.graph -import android.graphics.Bitmap import android.os.Build import android.view.WindowManager +import androidx.compose.animation.core.animate import androidx.compose.foundation.Image import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.detectTransformGestures import androidx.compose.foundation.layout.Arrangement @@ -13,14 +14,18 @@ import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.automirrored.filled.ArrowForward import androidx.compose.material.icons.automirrored.filled.OpenInNew 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.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.IconButton @@ -33,6 +38,8 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -49,39 +56,36 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalView import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import androidx.compose.ui.window.DialogWindowProvider +import kotlin.math.abs +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import net.awan.pipelines.data.protocol.StageArtifact +import net.awan.pipelines.ui.ArtifactGroup +import net.awan.pipelines.ui.components.MotionQuick import net.awan.pipelines.ui.components.copyText import net.awan.pipelines.ui.components.paneSafeArea +import net.awan.pipelines.ui.components.spec import net.awan.pipelines.ui.theme.SPACING_M +import net.awan.pipelines.ui.theme.SPACING_S import net.awan.pipelines.ui.theme.SPACING_XL import net.awan.pipelines.ui.theme.SPACING_XS +import net.awan.pipelines.ui.theme.SPACING_XXS import net.awan.pipelines.ui.theme.pipelinesText -import kotlin.math.abs /** * The full-screen media viewer opened by tapping a gallery tile (the run summary * grid, the per-visit artifacts section and the stage pane all render through * [ArtifactGallery], so they all open this): an image at full size, or a video's - * poster frame (the platform retriever extracts it, [video] = true) with the - * external-open action to actually play it. It replaces the former small centred - * dialog rather than stacking on top of it. + * poster frame with the external-open action to actually play it. It replaces the + * former small centred dialog rather than stacking on top of it. * - * It is a [Dialog] whose window is laid out edge to edge (`decorFitsSystemWindows - * = false`): the dark [MaterialTheme.colorScheme.scrim] backdrop fills the whole - * screen, while the interactive content clears the pane safe area - * ([paneSafeArea]) so nothing sits under the status bar, a cutout or the - * navigation bar. As a dialog it is drawn above every pane of the stack, and the - * platform routes Back to it ([DialogProperties.dismissOnBackPress]) so system - * Back closes the viewer and not the screen behind it. - * - * The image loads through the same cached, off-main-thread path as the inline - * preview ([rememberArtifactBitmap]); while it downloads a spinner is shown and a - * failed fetch/decode shows a distinct error message. The open-in-new and - * copy-link actions are kept from the artifact rows, and a tap on the image is - * deliberately not a dismissal (only the close button, a downward swipe at fit - * scale, or Back close it). + * A single-artifact shortcut ([url], [name], [video]) is kept for callers such as + * [net.awan.pipelines.ui.graph.StageVerdict] that already resolve one url. */ @Composable internal fun ArtifactViewer( @@ -91,6 +95,68 @@ internal fun ArtifactViewer( onDismiss: () -> Unit, video: Boolean = false, ) { + val artifact = remember(url) { + StageArtifact( + name = name, + contentType = if (video) "video/*" else "image/*", + url = url, + sizeBytes = 0, + ) + } + val artifacts = remember(url) { listOf(artifact) } + ArtifactViewer( + artifacts = artifacts, + index = 0, + configuredServerUrl = "", + fetchBytes = fetchBytes, + onIndexChange = {}, + onDismiss = onDismiss, + ) +} + +/** + * The full-screen artifact viewer opened by tapping a gallery thumbnail (the run + * summary grid, the per-visit artifacts list and the stage pane all render + * through [ArtifactGallery], so they all open this). It replaces the former + * small centred dialog rather than stacking on top of it. + * + * It is a [Dialog] whose window is laid out edge to edge (`decorFitsSystemWindows + * = false`): the dark [MaterialTheme.colorScheme.scrim] backdrop fills the whole + * screen, while the interactive content clears the pane safe area + * ([paneSafeArea]) so nothing sits under the status bar, a cutout or the + * navigation bar. As a dialog it is drawn above every pane of the stack, and the + * platform routes Back to it ([DialogProperties.dismissOnBackPress]) so system + * Back closes the viewer and not the screen behind it. + * + * It shows one [artifacts] entry at a time and pages horizontally through the + * neighbours in gallery order ([artifacts] is that order): a swipe left/right at + * fit moves to the next/previous artifact, and the position ("2 of 5"), name and + * content type of the open artifact are always shown. A horizontal drag is only + * a page while the image is at fit — a zoomed image still pans — because the + * viewer is zoomable and pannable; at the first/last artifact the drag is damped + * and never wraps. A one-artifact gallery is inert (no page, no resistance). The + * previous/next [IconButton]s keep both neighbours reachable without a swipe. + * + * Images load at full resolution through [rememberArtifactBitmap]; videos load + * their first sync frame through [rememberArtifactVideoFrame]. While the content + * loads a spinner is shown and a failed fetch/decode shows a distinct error + * message, and paging keeps working so a broken artifact never strands the + * viewer. The open-in-new, copy-link and share actions are kept from the + * artifact rows, a tap on the image is deliberately not a dismissal (only the + * close button, a downward swipe at fit, or Back close it), and each artifact + * reloads its own content, name and actions rather than reusing the previous + * one's. + */ +@Composable +internal fun ArtifactViewer( + artifacts: List, + index: Int, + configuredServerUrl: String, + fetchBytes: suspend (String) -> ByteArray?, + onIndexChange: (Int) -> Unit, + onDismiss: () -> Unit, +) { + val count = artifacts.size Dialog( onDismissRequest = onDismiss, properties = DialogProperties( @@ -134,101 +200,119 @@ internal fun ArtifactViewer( .background(MaterialTheme.colorScheme.scrim) .windowInsetsPadding(paneSafeArea()), ) { - val state = if (video) { - rememberArtifactVideoFrame(url, FULL_RESOLUTION, fetchBytes) - } else { - rememberArtifactBitmap(url, FULL_RESOLUTION, fetchBytes) - } - when (state) { - is ArtifactImageState.Ready -> ZoomableArtifact(state.bitmap, name, url, onDismiss) - ArtifactImageState.Loading -> ViewerMessage( - if (video) "Loading video frame…" else "Loading image…", - spinner = true, - ) - ArtifactImageState.Error -> ViewerMessage( - if (video) "Couldn't load the video frame." else "Couldn't load image.", - ) - ArtifactImageState.Unavailable -> ViewerMessage( - if (video) "Video unavailable." else "Image unavailable.", - ) - } - ArtifactViewerActions( - name = name, - url = url, + val artifact = artifacts.getOrNull(index) ?: return@Box + ArtifactViewerBody( + artifact = artifact, + resolvedUrl = resolvedArtifactUrl(artifact, configuredServerUrl), + index = index, + count = count, + fetchBytes = fetchBytes, + // Clamp through the one paging rule, so a page attempt at an end + // resolves to the same index and the viewer never leaves range. + onPage = { delta -> onIndexChange(pagedIndex(index, delta, count)) }, onDismiss = onDismiss, - modifier = Modifier.align(Alignment.TopEnd), ) } } } /** - * The loaded bitmap, pannable and zoomable. The image is first fitted into the - * measured viewport ([fitImageSize]); [scale] and [offset] are then the live - * gesture transform, drawn with a top-left [TransformOrigin] so - * `displayed = point * scale + offset` and [clampImageOffset] can keep the - * scaled image inside the viewport on every axis — when it is larger than the - * viewport its edges never move inside it, and when it is smaller the axis is - * centred, so the image can never be dragged off screen. + * One open artifact: the zoomable image or video poster frame (or its + * loading/error panel) plus the fixed position header and the action/page + * affordances. The paging/dismiss gesture and its animation live on the + * full-screen surface here, above the per-artifact content, so the swipe offset + * survives the artifact swap and the page slides rather than jumping — and so a + * drag that starts anywhere in the viewer, including the letterbox around a + * fitted image, reaches the page rule. * - * A pinch zooms about the gesture centroid and a drag pans (both through the - * shared [zoomAbout]); a double-tap toggles between fit and [DOUBLE_TAP_SCALE]; a - * downward swipe while at fit dismisses. All zoom state is remembered on [url], - * so closing the viewer or opening another image starts again at fit/centred. + * This one full-screen surface owns both gestures: a horizontal drag at fit pages + * (a downward drag at fit dismisses), while a pinch or a drag at any zoomed scale + * is the pan/zoom transform instead — the pan clamp leaves a fitted image + * centred, so the same drag is free to page. The image itself is drawn at its + * fitted size and transformed inside this surface; it carries no gesture of its + * own, so the loading/error/unavailable panel and the image share exactly one + * paging implementation. */ @Composable -private fun ZoomableArtifact( - bitmap: Bitmap, - name: String, - url: String, +private fun ArtifactViewerBody( + artifact: StageArtifact, + resolvedUrl: String?, + index: Int, + count: Int, + fetchBytes: suspend (String) -> ByteArray?, + onPage: (Int) -> Unit, onDismiss: () -> Unit, ) { - // Clip the zoom/pan transform to the safe-area viewport: Compose does not clip - // children by default, so a zoomed image would otherwise draw over the status - // bar / cutout the backdrop clears. + val kind = remember(artifact.contentType, artifact.name) { + artifactKind(artifact.contentType, artifact.name) + } + val isVideo = kind == ArtifactKind.Video + val imageState = if (isVideo) { + rememberArtifactVideoFrame(resolvedUrl, FULL_RESOLUTION, fetchBytes) + } else { + rememberArtifactBitmap(resolvedUrl, FULL_RESOLUTION, fetchBytes) + } + // The two neighbours are derived through the same clamp the page commit + // uses, so an affordance and the gesture can never disagree about an end. + val hasPrevious = pagedIndex(index, -1, count) != index + val hasNext = pagedIndex(index, 1, count) != index + // Keying the zoom state on the open url means paging (a new url) starts the + // neighbour at fit/centred instead of inheriting the previous one's transform. + val url = resolvedUrl ?: artifact.url + BoxWithConstraints(Modifier.fillMaxSize().clipToBounds()) { val density = LocalDensity.current val viewport = Size(with(density) { maxWidth.toPx() }, with(density) { maxHeight.toPx() }) - val base = remember(viewport, bitmap) { - fitImageSize(viewport, Size(bitmap.width.toFloat(), bitmap.height.toFloat())) + val paging = rememberArtifactPaging( + viewport = { viewport }, + pagingEnabled = { count > 1 }, + hasPrevious = { hasPrevious }, + hasNext = { hasNext }, + onPage = onPage, + onDismiss = onDismiss, + ) + + // The fitted image size (zero until a bitmap is ready), kept on the bitmap + // so a decode does not re-fit on every recomposition. + val ready = imageState as? ArtifactImageState.Ready + val base = remember(viewport, ready?.bitmap) { + ready?.let { fitImageSize(viewport, Size(it.bitmap.width.toFloat(), it.bitmap.height.toFloat())) } + ?: Size.Zero + } + // The fitted image's centred offset, so a freshly-opened (or freshly + // paged-to) artifact is drawn already centred rather than flashing at the + // origin for a frame before the effect below re-centres it. + val centredOffset = remember(url, viewport, base) { + clampImageOffset(Offset.Zero, scaled(base, FIT_SCALE), viewport) } var scale by remember(url) { mutableFloatStateOf(FIT_SCALE) } - var offset by remember(url) { mutableStateOf(Offset.Zero) } - var swipeDown by remember(url) { mutableFloatStateOf(0f) } - + var offset by remember(url) { mutableStateOf(centredOffset) } // Centre the fitted image on first layout and re-clamp it whenever the // fitted geometry changes; scale changes are handled by the gestures. LaunchedEffect(url, viewport, base) { offset = clampImageOffset(offset, scaled(base, scale), viewport) } - if (base.width > 0f && base.height > 0f) { - val imageModifier = Modifier - .size(with(density) { base.width.toDp() }, with(density) { base.height.toDp() }) - .graphicsLayer { - transformOrigin = TransformOrigin(0f, 0f) - scaleX = scale - scaleY = scale - translationX = offset.x - translationY = offset.y - } + // The full-screen gesture surface. Its graphicsLayer carries the page + // offset, so the whole content (image and its letterbox) slides as one. + Box( + modifier = Modifier + .fillMaxSize() + .graphicsLayer { translationX = paging.offsetPx } .pointerInput(url, viewport, base) { detectTransformGestures { centroid, pan, zoom, _ -> - val zoomed = zoomAbout(offset, scale, centroid, zoom, MIN_ZOOM, MAX_ZOOM) - scale = zoomed.scale - offset = clampImageOffset(zoomed.offset + pan, scaled(base, scale), viewport) - // Swipe down to dismiss only at fit (a drag while zoomed - // pans); a mostly-horizontal or pinch gesture is ignored. - if (scale <= FIT_SCALE + ZOOM_EPSILON && zoom == 1f && - pan.y > 0f && pan.y >= abs(pan.x) - ) { - swipeDown += pan.y - if (swipeDown >= viewport.height * SWIPE_DISMISS_FRACTION) onDismiss() + // Page/dismiss only at fit (a pinch has zoom != 1); while + // zoomed the pan below is the gesture instead. + if (canPageAtScale(scale) && zoom == 1f) { + paging.onPan(pan.x, pan.y, atFit = true) } else { - swipeDown = 0f + val zoomed = zoomAbout(offset, scale, centroid, zoom, MIN_ZOOM, MAX_ZOOM) + scale = zoomed.scale + offset = clampImageOffset(zoomed.offset + pan, scaled(base, scale), viewport) } } } + .settlePageDrag(paging) .pointerInput(url) { detectTapGestures( // A plain tap is not a gesture: it never closes. @@ -246,14 +330,103 @@ private fun ZoomableArtifact( offset = clampImageOffset(zoomed.offset, scaled(base, scale), viewport) }, ) - } - Image( - bitmap = bitmap.asImageBitmap(), - contentDescription = name, - contentScale = ContentScale.Fit, - modifier = imageModifier, + }, + ) { + when (imageState) { + is ArtifactImageState.Ready -> + if (base.width > 0f && base.height > 0f) { + Image( + bitmap = imageState.bitmap.asImageBitmap(), + contentDescription = artifact.name, + contentScale = ContentScale.Fit, + modifier = Modifier + .size(with(density) { base.width.toDp() }, with(density) { base.height.toDp() }) + .graphicsLayer { + transformOrigin = TransformOrigin(0f, 0f) + scaleX = scale + scaleY = scale + translationX = offset.x + translationY = offset.y + }, + ) + } + ArtifactImageState.Loading -> ViewerMessage( + if (isVideo) "Loading video frame…" else "Loading image…", + spinner = true, + ) + ArtifactImageState.Error -> ViewerMessage( + if (isVideo) "Couldn't load the video frame." else "Couldn't load image.", + ) + ArtifactImageState.Unavailable -> ViewerMessage( + if (isVideo) "Video unavailable." else "Image unavailable.", + ) + } + } + + // Name/position on the left and the actions on the right, in one bounded + // row so a long artifact name ellipsizes instead of running under the + // actions. + Row( + modifier = Modifier.align(Alignment.TopStart).fillMaxWidth().padding(SPACING_S), + horizontalArrangement = Arrangement.spacedBy(SPACING_S), + verticalAlignment = Alignment.Top, + ) { + ArtifactViewerHeader( + artifact = artifact, + index = index, + count = count, + modifier = Modifier.weight(1f), + ) + ArtifactViewerActions( + artifact = artifact, + resolvedUrl = resolvedUrl, + fetchBytes = fetchBytes, + onDismiss = onDismiss, ) } + // A one-artifact gallery pages nowhere, so it shows no page affordances. + if (count > 1) { + ArtifactViewerPageButtons( + hasPrevious = hasPrevious, + hasNext = hasNext, + onPrevious = { paging.page(-1) }, + onNext = { paging.page(1) }, + modifier = Modifier.align(Alignment.BottomCenter).padding(SPACING_M), + ) + } + } +} + +/** + * The open artifact's name and position ("2 of 5") over the image, in the light + * [androidx.compose.material3.ColorScheme.inverseSurface] used by [ViewerMessage] + * (the backdrop is the always-dark scrim), on the same translucent capsule as the + * actions so it reads over a bright image. + */ +@Composable +private fun ArtifactViewerHeader( + artifact: StageArtifact, + index: Int, + count: Int, + modifier: Modifier = Modifier, +) { + val text = pipelinesText() + Column( + modifier = modifier.viewerCapsule().padding(horizontal = SPACING_M, vertical = SPACING_XS), + verticalArrangement = Arrangement.spacedBy(SPACING_XXS), + ) { + Text( + artifact.name.ifBlank { "(unnamed artifact)" }, + style = text.label, + color = MaterialTheme.colorScheme.inverseSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + artifactViewerPositionLabel(index, count, artifact.contentType), + style = text.meta, + color = MaterialTheme.colorScheme.inverseSurface, + ) } } @@ -282,37 +455,233 @@ private fun ViewerMessage(text: String, spinner: Boolean = false) { } } -/** The viewer's kept open-in-new and copy-link actions plus the close affordance. */ +/** + * The open artifact's open-in-new, copy-link and share actions plus the close + * affordance. Each acts on the *open* artifact ([resolvedUrl]), so paging + * reloads the actions with the artifact rather than reusing the previous one's. + * A translucent scrim capsule behind the row keeps the light action icons legible + * over a bright image; over the black backdrop it is invisible. + */ @Composable private fun ArtifactViewerActions( - name: String, - url: String, + artifact: StageArtifact, + resolvedUrl: String?, + fetchBytes: suspend (String) -> ByteArray?, onDismiss: () -> Unit, modifier: Modifier = Modifier, ) { val context = LocalContext.current val clipboard = LocalClipboardManager.current - // A translucent scrim capsule behind the row keeps the light action icons - // legible over a bright image; over the black backdrop it is invisible. + val scope = rememberCoroutineScope() + val name = artifact.name Row( - modifier = modifier.background( - color = MaterialTheme.colorScheme.scrim.copy(alpha = ARTIFACT_ACTION_SCRIM_ALPHA), - shape = CircleShape, - ), + modifier = modifier.viewerCapsule(), horizontalArrangement = Arrangement.spacedBy(SPACING_XS), ) { - IconButton(onClick = { openArtifact(context, url) }) { + IconButton(onClick = { openArtifact(context, resolvedUrl) }, enabled = resolvedUrl != null) { Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = "Open $name externally") } - IconButton(onClick = { clipboard.copyText(url) }) { + IconButton( + onClick = { resolvedUrl?.let { clipboard.copyText(it) } }, + enabled = resolvedUrl != null, + ) { Icon(Icons.Default.ContentCopy, contentDescription = "Copy link to $name") } + IconButton( + onClick = { + resolvedUrl?.let { url -> + scope.launch { shareArtifact(context, url, name, artifact.contentType, fetchBytes) } + } + }, + enabled = resolvedUrl != null, + ) { + Icon(Icons.Default.Share, contentDescription = "Share ${name.ifBlank { "artifact" }}") + } IconButton(onClick = onDismiss) { Icon(Icons.Default.Close, contentDescription = "Close viewer") } } } +/** + * The focusable previous/next affordances, so a person who cannot swipe can still + * reach both neighbours. Each is a 48dp [IconButton] disabled exactly when that + * neighbour does not exist (the first/last artifact). + */ +@Composable +private fun ArtifactViewerPageButtons( + hasPrevious: Boolean, + hasNext: Boolean, + onPrevious: () -> Unit, + onNext: () -> Unit, + modifier: Modifier = Modifier, +) { + Row( + modifier = modifier.viewerCapsule(), + horizontalArrangement = Arrangement.spacedBy(SPACING_XS), + ) { + IconButton(onClick = onPrevious, enabled = hasPrevious) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Previous artifact") + } + IconButton(onClick = onNext, enabled = hasNext) { + Icon(Icons.AutoMirrored.Filled.ArrowForward, contentDescription = "Next artifact") + } + } +} + +/** + * The translucent scrim capsule behind the viewer's floating controls (the + * header, the action row and the page buttons): it keeps the light icons and + * text legible over a bright image and is invisible over the black backdrop. + */ +@Composable +private fun Modifier.viewerCapsule(): Modifier = background( + color = MaterialTheme.colorScheme.scrim.copy(alpha = ARTIFACT_ACTION_SCRIM_ALPHA), + shape = CircleShape, +) + +/** + * The full-screen viewer's horizontal paging state, fed by the one full-screen + * gesture surface the viewer shows, so the page rule lives in exactly one place. + * + * A horizontal drag at fit follows the finger ([offsetPx]); at an end — or for a + * one-artifact gallery — it is damped ([PAGE_RESISTANCE]) and never wraps, and the + * drag springs back to rest when the pointers lift ([settle]). A predominantly + * downward drag at fit still dismisses, exactly as the single-artifact viewer + * did. Once the drag crosses [PAGE_SWIPE_FRACTION] of the viewport width it + * commits one page: the open content slides out, the index changes, and the + * neighbour slides in; while that runs further drags are ignored so an animation + * can never fight itself. All state is plain (only [offsetPx] is observable), so + * a drag schedules no recomposition beyond the translation it actually changes. + */ +private class ArtifactPaging( + private val viewport: () -> Size, + private val pagingEnabled: () -> Boolean, + private val hasPrevious: () -> Boolean, + private val hasNext: () -> Boolean, + private val onPage: (Int) -> Unit, + private val onDismiss: () -> Unit, + private val scope: CoroutineScope, +) { + /** The live page translation in pixels; positive drags the content right. */ + var offsetPx by mutableFloatStateOf(0f) + private set + + private var paging = false + private var swipeDown = 0f + private var settleJob: Job? = null + + /** Feeds one pan event; [atFit] is false while zoomed or pinching. */ + fun onPan(panX: Float, panY: Float, atFit: Boolean) { + if (!atFit || paging) { + swipeDown = 0f + return + } + if (abs(panX) > abs(panY)) { + swipeDown = 0f + if (!pagingEnabled()) return + // A leftward drag (negative x) advances to the next artifact. + val direction = if (panX < 0f) 1 else -1 + val available = if (direction > 0) hasNext() else hasPrevious() + val proposed = offsetPx + panX + settleJob?.cancel() + offsetPx = if (available) proposed else proposed * PAGE_RESISTANCE + if (available && abs(offsetPx) >= viewport().width * PAGE_SWIPE_FRACTION) startPage(direction) + } else if (panY > 0f && panY >= abs(panX)) { + swipeDown += panY + if (swipeDown >= viewport().height * SWIPE_DISMISS_FRACTION) onDismiss() + } else { + swipeDown = 0f + } + } + + /** Springs a resisted (uncommitted) drag back to rest when the fingers lift. */ + fun settle() { + if (paging || offsetPx == 0f) return + settleJob?.cancel() + settleJob = scope.launch { + animate(offsetPx, 0f, animationSpec = MotionQuick.spec()) { value, _ -> offsetPx = value } + } + } + + /** Commits one page in [direction] (+1 next, -1 previous) without a drag. */ + fun page(direction: Int) { + if (!paging) startPage(direction) + } + + private fun startPage(direction: Int) { + paging = true + swipeDown = 0f + settleJob?.cancel() + val width = viewport().width + scope.launch { + // Slide the open artifact out, swap in its neighbour, then slide that + // in from the opposite side — one page, in the drag's direction. + animate(offsetPx, -direction * width, animationSpec = MotionQuick.spec()) { value, _ -> + offsetPx = value + } + onPage(direction) + offsetPx = direction * width + animate(offsetPx, 0f, animationSpec = MotionQuick.spec()) { value, _ -> offsetPx = value } + paging = false + } + } +} + +/** + * The one [ArtifactPaging] remembered across the artifact swaps of a viewer + * session, reading its latest viewport/availability/callbacks through + * [rememberUpdatedState] so the instance can outlive a composition that a page + * has already changed. + */ +@Composable +private fun rememberArtifactPaging( + viewport: () -> Size, + pagingEnabled: () -> Boolean, + hasPrevious: () -> Boolean, + hasNext: () -> Boolean, + onPage: (Int) -> Unit, + onDismiss: () -> Unit, +): ArtifactPaging { + val viewportState = rememberUpdatedState(viewport) + val enabledState = rememberUpdatedState(pagingEnabled) + val previousState = rememberUpdatedState(hasPrevious) + val nextState = rememberUpdatedState(hasNext) + val pageState = rememberUpdatedState(onPage) + val dismissState = rememberUpdatedState(onDismiss) + val scope = rememberCoroutineScope() + return remember { + ArtifactPaging( + viewport = { viewportState.value() }, + pagingEnabled = { enabledState.value() }, + hasPrevious = { previousState.value() }, + hasNext = { nextState.value() }, + onPage = { pageState.value(it) }, + onDismiss = { dismissState.value() }, + scope = scope, + ) + } +} + +/** + * Observes gesture ends without consuming the events (the zoom/pan detector + * above owns the drag), so a resisted page drag springs back to rest the moment + * the fingers lift. A committed page owns its own animation and is a no-op here. + */ +private fun Modifier.settlePageDrag(paging: ArtifactPaging): Modifier = + this.pointerInput(paging) { + awaitPointerEventScope { + while (true) { + awaitFirstDown(requireUnconsumed = false) + var pressed = true + while (pressed) { + pressed = awaitPointerEvent().changes.any { it.pressed } + } + paging.settle() + } + } + } + /** The fitted base size scaled by the current [scale], in pixels. */ private fun scaled(base: Size, scale: Float): Size = Size(base.width * scale, base.height * scale) @@ -333,6 +702,62 @@ private const val ZOOM_EPSILON = 0.01f /** Fraction of the viewport height a downward swipe must cross to dismiss. */ private const val SWIPE_DISMISS_FRACTION = 0.22f +/** Fraction of the viewport width a horizontal drag must cross to page. */ +private const val PAGE_SWIPE_FRACTION = 0.18f + +/** How far a drag past the first/last artifact moves before it is stopped. */ +private const val PAGE_RESISTANCE = 0.35f + +/** + * The media artifacts [groups] hold, in the exact order the gallery draws them + * (group by group, each group's images and videos in recorded order): the + * neighbours the full-screen viewer pages through, so a swipe visits the same + * list the grid showed. Non-media artifacts open externally instead of in the + * viewer and are not part of it. Pure, so the ordering is unit tested. + */ +internal fun pagedArtifacts(groups: List): List = + groups.flatMap { group -> + group.artifacts.filter { artifact -> + artifactKind(artifact.contentType, artifact.name).let { + it == ArtifactKind.Image || it == ArtifactKind.Video + } + } + } + +/** + * Each gallery media artifact's url mapped to its position in [pagedArtifacts] + * — the same ordered list the viewer pages through. The grid's tiles resolve + * their viewer index here, so the tile and the viewer derive from one source and + * cannot drift. The first occurrence of a url wins. Pure, so the mapping is unit + * tested against the grid's draw order. + */ +internal fun viewerIndexByUrl(groups: List): Map { + val indices = LinkedHashMap() + pagedArtifacts(groups).forEachIndexed { index, artifact -> indices.putIfAbsent(artifact.url, index) } + return indices +} + +/** + * The index paging from [current] by [delta] within a list of [count], clamped at + * both ends so a page never wraps (and an empty list is index 0). The one paging + * rule the gesture, the buttons and the commit all share. Pure. + */ +internal fun pagedIndex(current: Int, delta: Int, count: Int): Int = + if (count <= 0) 0 else (current + delta).coerceIn(0, count - 1) + +/** + * Whether a horizontal drag at [scale] may page: only at the default fit scale, + * so a zoomed viewer pans instead. Pure, so the rule is unit tested. + */ +internal fun canPageAtScale(scale: Float, fit: Float = FIT_SCALE): Boolean = + scale <= fit + ZOOM_EPSILON + +/** The viewer's position label, e.g. `2 of 5 · image/png`. Pure. */ +internal fun artifactViewerPositionLabel(index: Int, count: Int, contentType: String): String { + val type = contentType.substringBefore(';').trim().ifBlank { "artifact" } + return "${index + 1} of $count · $type" +} + /** * The size [image] is drawn at to fit inside [viewport] with its aspect ratio * preserved, never upscaling past 1:1 (a small image keeps its native size). 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 7ad3c3ad..a696a709 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 @@ -29,11 +29,9 @@ import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -55,7 +53,6 @@ import net.awan.pipelines.ui.artifactsSummary import net.awan.pipelines.ui.components.copyText import net.awan.pipelines.ui.components.galleryGrid import net.awan.pipelines.ui.humanBytes -import net.awan.pipelines.ui.isImageContentType import net.awan.pipelines.ui.theme.ARTIFACT_BADGE_DP import net.awan.pipelines.ui.theme.ARTIFACT_PLAY_BADGE_DP import net.awan.pipelines.ui.theme.ARTIFACT_TILE_ACTION_DP @@ -140,6 +137,16 @@ internal fun ArtifactGallery( onSelectionChange: (ArtifactSelection) -> Unit = {}, ) { val text = pipelinesText() + // The media artifacts in the exact order the grid draws them: the neighbours + // the full-screen viewer pages through, so a swipe visits the same list the + // grid showed. Held once per data change, never per recomposition. + val viewable = remember(groups) { pagedArtifacts(groups) } + // Each media tile opens the viewer at the position it holds in [viewable], + // derived from that same ordered list rather than a second running counter, + // so the grid and the viewer can never disagree about which artifact is which. + val viewerIndexOf = remember(groups) { viewerIndexByUrl(groups) } + // The open viewer's index into [viewable], or [NO_VIEWER] when it is closed. + val viewerIndex = remember(groups) { mutableIntStateOf(NO_VIEWER) } BoxWithConstraints(modifier.fillMaxWidth()) { val grid = galleryGrid( availableWidth = maxWidth, @@ -167,6 +174,7 @@ internal fun ArtifactGallery( tile = grid.cell, selection = selection, onSelectionChange = onSelectionChange, + onOpen = { viewerIndexOf[artifact.url]?.let { viewerIndex.intValue = it } }, ) } // Keep a partial last row's tiles aligned to the grid. @@ -178,8 +186,23 @@ internal fun ArtifactGallery( } } } + // The one viewer instance the gallery owns, so a swipe pages through + // [viewable] rather than a per-tile viewer that has no neighbours. + if (viewerIndex.intValue in viewable.indices) { + ArtifactViewer( + artifacts = viewable, + index = viewerIndex.intValue, + configuredServerUrl = configuredServerUrl, + fetchBytes = fetchArtifactBytes, + onIndexChange = { viewerIndex.intValue = it }, + onDismiss = { viewerIndex.intValue = NO_VIEWER }, + ) + } } +/** No artifact is open in this gallery's viewer. */ +private const val NO_VIEWER = -1 + /** * The absolute url a gallery artifact is previewed/opened at, or null when it * cannot be resolved against the configured server (blank or invalid). The one @@ -211,6 +234,7 @@ private fun ArtifactTile( tile: Dp, selection: ArtifactSelection, onSelectionChange: (ArtifactSelection) -> Unit, + onOpen: () -> Unit, ) { val context = LocalContext.current // Resolve and classify once per data change, not on every recomposition. @@ -221,7 +245,6 @@ private fun ArtifactTile( artifactKind(artifact.contentType, artifact.name) } val media = kind == ArtifactKind.Image || kind == ArtifactKind.Video - var showFull by remember(artifact.url) { mutableStateOf(false) } val selected = selection.contains(artifact.url) Box( @@ -248,7 +271,7 @@ private fun ArtifactTile( selection.active -> onSelectionChange(selection.toggle(artifact.url)) // An image or video opens the full-screen viewer; any // other type uses the existing open action. - media -> if (resolved != null) showFull = true + media -> if (resolved != null) onOpen() else -> openArtifact(context, resolved) } }, @@ -299,19 +322,6 @@ private fun ArtifactTile( ) } } - - // The tap opens the full-screen viewer (one shared instance across the run - // summary grid, the per-visit section and the stage pane, so they never - // disagree); there is no separate smaller preview to stack on top of it. - if (showFull && resolved != null) { - ArtifactViewer( - url = resolved, - name = artifact.name, - fetchBytes = fetchArtifactBytes, - onDismiss = { showFull = false }, - video = kind == ArtifactKind.Video, - ) - } } /** diff --git a/android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactViewerTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactViewerTest.kt index 590e5aff..9f2fd85e 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactViewerTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactViewerTest.kt @@ -3,8 +3,11 @@ package net.awan.pipelines.ui.graph import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color +import net.awan.pipelines.data.protocol.StageArtifact +import net.awan.pipelines.ui.ArtifactGroup import net.awan.pipelines.ui.theme.PipelinesDarkColors import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test @@ -118,4 +121,129 @@ class ArtifactViewerTest { assertEquals(Color(0xFF000000), scheme.scrim) assertTrue(contrastRatio(scheme.inverseSurface, scheme.scrim) >= 4.5) } + + @Test + fun pagedIndexMovesByOneWithinTheList() { + // Three artifacts: from the middle, next and previous move by exactly one. + assertEquals(2, pagedIndex(current = 1, delta = 1, count = 3)) + assertEquals(0, pagedIndex(current = 1, delta = -1, count = 3)) + } + + @Test + fun pagedIndexClampsAtBothEndsWithoutWrapping() { + // At the first artifact a swipe back stays put (no wrap to the last), and + // at the last a swipe forward stays put (no wrap to the first). + assertEquals(0, pagedIndex(current = 0, delta = -1, count = 3)) + assertEquals(2, pagedIndex(current = 2, delta = 1, count = 3)) + } + + @Test + fun pagedIndexIsZeroForASingleItemListAndAnEmptyList() { + assertEquals(0, pagedIndex(current = 0, delta = 1, count = 1)) + assertEquals(0, pagedIndex(current = 0, delta = -1, count = 1)) + assertEquals(0, pagedIndex(current = 4, delta = 1, count = 0)) + } + + @Test + fun aZoomedViewerDoesNotPage() { + // Only the fit scale pages; any zoomed-in scale pans instead. + assertTrue(canPageAtScale(scale = 1f)) + assertTrue(canPageAtScale(scale = 1.0001f)) + assertFalse(canPageAtScale(scale = 1.5f)) + assertFalse(canPageAtScale(scale = 4f)) + } + + @Test + fun pagedArtifactsAreTheGalleryMediaInGridOrder() { + // Each group contributes its images and videos in recorded order, and the + // groups follow each other; non-media artifacts (opened externally) are + // not in the viewer's list. + val groups = listOf( + ArtifactGroup( + stageKey = "build", + visit = 1, + artifacts = listOf( + artifact("shot1.png", "image/png"), + artifact("log.txt", "text/plain"), + artifact("shot2.jpg", "image/jpeg"), + artifact("clip.mp4", "video/mp4"), + ), + ), + ArtifactGroup( + stageKey = "test", + visit = 1, + artifacts = listOf( + artifact("report.pdf", "application/pdf"), + artifact("shot3.png", "image/png"), + ), + ), + ) + assertEquals( + listOf("shot1.png", "shot2.jpg", "clip.mp4", "shot3.png"), + pagedArtifacts(groups).map { it.name }, + ) + } + + @Test + fun pagedArtifactsIsEmptyWithoutMedia() { + val groups = listOf( + ArtifactGroup("build", 1, listOf(artifact("log.txt", "text/plain"))), + ) + assertTrue(pagedArtifacts(groups).isEmpty()) + } + + /** + * The gallery draws each group's media artifacts in recorded order; walking + * that draw order independently and resolving every media tile through + * [viewerIndexByUrl] must land on consecutive positions in [pagedArtifacts]. + * This is the invariant that keeps a tile's tap opening the very artifact the + * viewer then shows — the grid and the viewer derive their index from one source now. + */ + @Test + fun theGridTileViewerIndicesMatchTheViewerOrder() { + val groups = listOf( + ArtifactGroup( + stageKey = "build", + visit = 1, + artifacts = listOf( + artifact("shot1.png", "image/png"), + artifact("log.txt", "text/plain"), + artifact("shot2.jpg", "image/jpeg"), + artifact("clip.mp4", "video/mp4"), + ), + ), + ArtifactGroup( + stageKey = "test", + visit = 1, + artifacts = listOf( + artifact("report.pdf", "application/pdf"), + artifact("shot3.png", "image/png"), + ), + ), + ) + val indices = viewerIndexByUrl(groups) + var expected = 0 + groups.forEach { group -> + group.artifacts.filter { + val kind = artifactKind(it.contentType, it.name) + kind == ArtifactKind.Image || kind == ArtifactKind.Video + }.forEach { media -> + assertEquals(expected++, indices[media.url]) + } + } + assertEquals(pagedArtifacts(groups).size, expected) + } + + @Test + fun thePositionLabelNamesTheOpenArtifactAndItsType() { + // One-based position, the count, and the artifact's own content type (a + // blank type falls back to "artifact") — what the viewer must reload per + // artifact rather than reusing the previous one's. + assertEquals("2 of 5 · image/png", artifactViewerPositionLabel(1, 5, "image/png")) + assertEquals("1 of 1 · image/jpeg", artifactViewerPositionLabel(0, 1, "image/jpeg; q=0.9")) + assertEquals("3 of 4 · artifact", artifactViewerPositionLabel(2, 4, "")) + } + + private fun artifact(name: String, contentType: String): StageArtifact = + StageArtifact(name = name, sizeBytes = 1, contentType = contentType, url = "/artifacts/$name") }