From d339827b5f0d6fc7eb192f99de3b7fd95e9c103b Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 06:35:08 +0100 Subject: [PATCH] Open artifact images in a full-screen zoomable viewer Tapping an image artifact (run summary grid, per-visit list or stage pane, all rendered through ArtifactGallery) now opens a new scrim-backed full-screen viewer instead of the former small centred dialog, which is removed rather than stacked. - ArtifactViewer.kt renders a full-bleed Dialog (usePlatformDefaultWidth = false, decorFitsSystemWindows = false) whose content re-applies paneSafeArea() so the dark backdrop reaches the edges while respecting status bar, cutout and navigation bar. A top-right row keeps the open-in-new and copy-link actions and adds a close button over a translucent scrim capsule. - Gestures: pinch zooms about the centroid, drag pans via the existing graph zoomAbout, double-tap toggles fit <-> 2.5x, and a downward swipe at fit dismisses; a plain tap does nothing. Zoom clamps to [1x, 5x] and the new pure clampImageOffset keeps pan inside the scaled image. Zoom state is keyed on the url, so closing the viewer or opening another image resets to fit/centred. System Back and the close button dismiss the viewer without closing the pane behind it. - Loading goes through the existing cached, off-main-thread rememberArtifactBitmap/ArtifactImageState path with distinct loading and error states, drawn in the light inverseSurface role that contrasts with the always-black scrim. - Pure helpers fitImageSize, clampImageOffset and toggleZoomScale are covered by the new ArtifactViewerTest. ArtifactImage.kt widens rememberArtifactBitmap/ArtifactImageState to internal and Artifacts.kt replaces FullSizeArtifactDialog with ArtifactViewer (openArtifact made internal). - android/README.md documents the viewer, its gestures and the evidence gathered on emulator-5554. --- android/README.md | 87 +++++ .../awan/pipelines/ui/graph/ArtifactImage.kt | 4 +- .../awan/pipelines/ui/graph/ArtifactViewer.kt | 360 ++++++++++++++++++ .../net/awan/pipelines/ui/graph/Artifacts.kt | 48 +-- .../pipelines/ui/graph/ArtifactViewerTest.kt | 121 ++++++ 5 files changed, 575 insertions(+), 45 deletions(-) create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactViewer.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactViewerTest.kt diff --git a/android/README.md b/android/README.md index f7b6c173..54f568de 100644 --- a/android/README.md +++ b/android/README.md @@ -1673,3 +1673,90 @@ image validated): http://10.0.0.249:8080/artifacts/86/1/pipelines-debug-wip-5ad4b58.apk` returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, `Content-Length: 18029402`. + +## Full-screen artifact image viewer (16 Oct 2026) + +Tapping an image artifact now opens a full-screen viewer (in the run summary +grid, the per-visit artifacts list and the stage pane, which all render through +`ArtifactGallery`), replacing the former small centred dialog rather than stacking +on it. `android/` only; no dependency was added, no run was started from the app, +and every device command targeted `emulator-5554` (never the attached Pixel, never +`emulator-5556`). + +- **Viewer.** New `ui/graph/ArtifactViewer.kt` renders a scrim-backed full-screen + `Dialog` (`usePlatformDefaultWidth = false`, `decorFitsSystemWindows = false`); + a `SideEffect` stretches the dialog window to `MATCH_PARENT`, fits no system + insets and draws into the display cutout (each API-guarded), so the dark backdrop + reaches every edge while the content re-applies `paneSafeArea()` (status bar, + cutout, navigation bar) itself. A top-right row keeps the open-in-new and + copy-link actions and adds a close button, backed by a translucent scrim + capsule so the light icons stay legible over a bright image. `dumpsys window` + confirms the dialog + window frame is `[0,0][2076,2152]` (previously inset to `[0,136][2076,2074]`). +- **Gestures.** Pinch zooms about the centroid and a drag pans via the existing + graph `zoomAbout`; a double-tap toggles between fit and 2.5x; a downward swipe at + fit dismisses; a plain tap does nothing. Zoom is clamped to `[1x, 5x]` of fit and + pan is clamped by the new pure `clampImageOffset` so the scaled image can never + be dragged off screen (each axis centred when smaller than the viewport, pinned + to `[viewport - content, 0]` when larger). Zoom state is remembered on the url, + so closing the viewer or opening another image starts again at fit/centred. + System Back and the close button dismiss the viewer without closing the pane + behind it (verified: 0 `Close viewer` nodes and the run detail still shown after + Back). The image loads through the existing cached, off-main-thread + `rememberArtifactBitmap` (now `internal`, reusing the shared fetch/decode path), + with a "Loading image…" spinner and a distinct "Couldn't load image." state. The + loading/error/unavailable message is drawn in the light `inverseSurface` role, + which contrasts with the always-black scrim (the previous `inverseOnSurface` + was a dark colour on the scrim, measured ~1.6:1). +- **Pure helpers.** `fitImageSize`, `clampImageOffset` and `toggleZoomScale` in + `ArtifactViewer.kt`; `ArtifactViewerTest` covers them (fitting, centre/edge + clamping, the toggle, and an anchored-zoom-then-clamp invariant). `zoomAbout` + and the loading path are the existing shared ones, not copies. + +Evidence obtained in this pass (macOS, JDK 17 from Homebrew `openjdk@17`, Gradle +8.11.1 from the wrapper cache, `ANDROID_HOME=/Users/alan/Library/Android/sdk`): + +- `gradle :app:testDebugUnitTest :app:assembleDebug --console=plain` → + `BUILD SUCCESSFUL`; the result XMLs aggregate to **149 tests, 0 failures, 0 + errors, 0 skipped** (up from 140: the new `ArtifactViewerTest`). + `app/build/outputs/apk/debug/app-debug.apk` is 18,043,579 bytes, sha256 + `1b3653dbdce9d62fc8dcfdcb986635829b70db38437d6769c77f91d16b7d6b3a`. +- `gradle :app:lintDebug` → only the two **pre-existing** `windowLightNavigationBar` + NewApi errors (`values/themes.xml`, `values-night/themes.xml`); no new lint + finding is attributed to `ArtifactViewer.kt` (39 warnings, down from 40 once the + cutout constant was API-guarded). +- On `emulator-5554` against the live server, the run 90 summary artifacts grid + was opened and `captures/viewer/` (git-ignored, every PNG validated by + `scripts/capture_png.sh -s emulator-5554`) holds: `01_viewer_open`, + `02_doubletap_zoom`, `03_pinch_zoom`, `04_pan`, `05_clamp_1..3`, + `06_fit_reset`, `07_swipedown_dismissed`, `08_back_dismissed`, `09_loading`, + `10_error`, `contact_sheet.png` and `viewer_gestures.mp4` (29 s). Pairwise + pixel diffs (`captures/imgdiff.py`): open→double-tap 19.72, double-tap→pinch + 6.72, pinch→pan 5.29, and `05_clamp_1→2` 0.75 → `05_clamp_2→3` **0.0** (the + image is pinned at its bound and cannot be panned further off screen); + fit-reset diff 0.01 (double-tap restores fit exactly). After a swipe-down and + after Back the UI dump has 0 `Close viewer` nodes and the run detail is shown; + a single tap leaves the viewer open (diff 0.02). `Loading image…` and + `Couldn't load image.` were produced against a hanging and a 404 endpoint. +- `adb shell input` cannot synthesise a two-finger pinch (it injects one pointer) + and the shell cannot write `/dev/input` (`sendevent` is permission-denied on + this production image), so pinch and the timed double-tap were driven with a + test-only `app_process` injector (`captures/viewer/tools/Injector.java` → + `Injector.jar`) that injects multi-pointer `MotionEvent`s via the hidden + `InputManager.injectInputEvent`, the same mechanism the platform `input` command + uses. It is verification tooling only, not part of the app or its dependencies. +- `adb -s emulator-5554 logcat -d` held 0 `FATAL EXCEPTION` / 0 `E AndroidRuntime` + lines. +- **APK publish.** Copied to + `~/.local/share/pipelines/data/artifacts/91/1/pipelines-debug-wip-7b61906.apk` + (`7b61906` = `git rev-parse --short HEAD`). `curl -I + http://10.0.0.249:8080/artifacts/91/1/pipelines-debug-wip-7b61906.apk` returned + `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18043579`, and a streamed `GET | shasum -a 256` equalled the + local file's `1b3653db…`. At 17.2 MiB it exceeds the 8 MiB per-file inventory + cap, so it is served by direct URL only. + +Not verified in this pass: a real hardware fold (the emulator is the 2076x2152 +inner display at 390 dpi); an Android 8/9 device branch (the `layoutInDisplayCutout +Mode = SHORT_EDGES` fallback is compiled and lint-guarded but only the API 36 path +ran). diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactImage.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactImage.kt index b8e7aa76..96394c65 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactImage.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactImage.kt @@ -63,7 +63,7 @@ private const val MAX_CACHED_BITMAPS = 24 * failure mark (that would blame a load that never happened). [Error] is reserved * for a fetch or decode that was actually attempted and failed. */ -private sealed interface ArtifactImageState { +internal sealed interface ArtifactImageState { data object Loading : ArtifactImageState data object Unavailable : ArtifactImageState data object Error : ArtifactImageState @@ -120,7 +120,7 @@ internal fun ArtifactImage( } @Composable -private fun rememberArtifactBitmap( +internal fun rememberArtifactBitmap( url: String?, maxDim: Int, fetchBytes: suspend (String) -> ByteArray?, 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 new file mode 100644 index 00000000..de0576c4 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/ArtifactViewer.kt @@ -0,0 +1,360 @@ +package net.awan.pipelines.ui.graph + +import android.graphics.Bitmap +import android.os.Build +import android.view.WindowManager +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.gestures.detectTransformGestures +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +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.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.OpenInNew +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.TransformOrigin +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.ContentScale +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.paneSafeArea +import net.awan.pipelines.ui.theme.pipelinesText +import kotlin.math.abs + +/** + * The full-screen image 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. + * + * 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). + */ +@Composable +internal fun ArtifactViewer( + url: String, + name: String, + fetchBytes: suspend (String) -> ByteArray?, + onDismiss: () -> Unit, +) { + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties( + usePlatformDefaultWidth = false, + decorFitsSystemWindows = false, + // A tap on the backdrop/image is not a gesture, so it must never + // close the viewer. + dismissOnClickOutside = false, + ), + ) { + // Stretch the dialog window over the whole display (behind the status + // bar, cutout and navigation bar) so the dark backdrop is truly full + // screen; the content below then applies the safe-area insets itself. + val dialogWindow = (LocalView.current.parent as? DialogWindowProvider)?.window + SideEffect { + dialogWindow?.let { window -> + window.setLayout( + WindowManager.LayoutParams.MATCH_PARENT, + WindowManager.LayoutParams.MATCH_PARENT, + ) + val attrs = window.attributes + // Fit no system insets and draw into the display cutout too, so + // the backdrop reaches every edge; the content re-applies the + // safe area itself with windowInsetsPadding. Each field/constant + // is guarded by its own API level (fitInsetsTypes and + // CUTOUT_MODE_ALWAYS are API 30, SHORT_EDGES is API 28). + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + attrs.fitInsetsTypes = 0 + attrs.layoutInDisplayCutoutMode = + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + attrs.layoutInDisplayCutoutMode = + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES + } + window.attributes = attrs + } + } + Box( + modifier = Modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.scrim) + .windowInsetsPadding(paneSafeArea()), + ) { + when (val state = rememberArtifactBitmap(url, FULL_RESOLUTION, fetchBytes)) { + is ArtifactImageState.Ready -> ZoomableArtifact(state.bitmap, name, url, onDismiss) + ArtifactImageState.Loading -> ViewerMessage("Loading image…", spinner = true) + ArtifactImageState.Error -> ViewerMessage("Couldn't load image.") + ArtifactImageState.Unavailable -> ViewerMessage("Image unavailable.") + } + ArtifactViewerActions( + name = name, + url = url, + 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. + * + * 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. + */ +@Composable +private fun ZoomableArtifact( + bitmap: Bitmap, + name: String, + url: String, + 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. + 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())) + } + var scale by remember(url) { mutableFloatStateOf(FIT_SCALE) } + var offset by remember(url) { mutableStateOf(Offset.Zero) } + var swipeDown by remember(url) { mutableFloatStateOf(0f) } + + // 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 + } + .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() + } else { + swipeDown = 0f + } + } + } + .pointerInput(url) { + detectTapGestures( + // A plain tap is not a gesture: it never closes. + onTap = { }, + onDoubleTap = { position -> + val zoomed = zoomAbout( + offset, + scale, + position, + toggleZoomScale(scale) / scale, + MIN_ZOOM, + MAX_ZOOM, + ) + scale = zoomed.scale + offset = clampImageOffset(zoomed.offset, scaled(base, scale), viewport) + }, + ) + } + Image( + bitmap = bitmap.asImageBitmap(), + contentDescription = name, + contentScale = ContentScale.Fit, + modifier = imageModifier, + ) + } + } +} + +/** + * The viewer's loading/error/unavailable message, centred on the backdrop. The + * backdrop is the always-black scrim, so the message uses the light + * [androidx.compose.material3.ColorScheme.inverseSurface] rather than + * `inverseOnSurface` (a dark colour on the scrim, previously illegible). + */ +@Composable +private fun ViewerMessage(text: String, spinner: Boolean = false) { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Column( + modifier = Modifier.padding(24.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + if (spinner) CircularProgressIndicator() + Text( + text = text, + style = pipelinesText().meta, + color = MaterialTheme.colorScheme.inverseSurface, + textAlign = TextAlign.Center, + ) + } + } +} + +/** The viewer's kept open-in-new and copy-link actions plus the close affordance. */ +@Composable +private fun ArtifactViewerActions( + name: String, + url: String, + 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. + Row( + modifier = modifier.background( + color = MaterialTheme.colorScheme.scrim.copy(alpha = ACTION_SCRIM_ALPHA), + shape = CircleShape, + ), + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + IconButton(onClick = { openArtifact(context, url) }) { + Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = "Open $name externally") + } + IconButton(onClick = { clipboard.setText(AnnotatedString(url)) }) { + Icon(Icons.Default.ContentCopy, contentDescription = "Copy link to $name") + } + IconButton(onClick = onDismiss) { + Icon(Icons.Default.Close, contentDescription = "Close viewer") + } + } +} + +/** 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) + +/** Full resolution for the explicit viewer (the inline previews downsample). */ +private const val FULL_RESOLUTION = 0 + +/** Fit scale (the image fits the viewport) and the double-tap zoomed level. */ +private const val FIT_SCALE = 1f +private const val DOUBLE_TAP_SCALE = 2.5f + +/** Zoom limits for the viewer, as multiples of the fitted image. */ +private const val MIN_ZOOM = 1f +private const val MAX_ZOOM = 5f + +/** Tolerance for deciding the image is back at fit. */ +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 + +/** Opacity of the scrim capsule that backs the top action row over the image. */ +private const val ACTION_SCRIM_ALPHA = 0.5f + +/** + * 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). + * Degenerate (zero/negative) sizes return [Size.Zero] rather than dividing by + * zero, so callers never see NaN. Pure, so the fitting is unit tested. + */ +internal fun fitImageSize(viewport: Size, image: Size): Size { + if (image.width <= 0f || image.height <= 0f || viewport.width <= 0f || viewport.height <= 0f) { + return Size.Zero + } + val scale = minOf(1f, viewport.width / image.width, viewport.height / image.height) + return Size(image.width * scale, image.height * scale) +} + +/** + * Bounds a pan [offset] of the scaled [content] inside [viewport]: on an axis + * where the content is larger than the viewport the offset stays in + * `[viewport - content, 0]` (its edges never move inside the viewport, so the + * image cannot be dragged off screen); on an axis where it is smaller the offset + * is the centred value. Degenerate content is returned unchanged. Pure, so the + * clamping is unit tested without a device. + */ +internal fun clampImageOffset(offset: Offset, content: Size, viewport: Size): Offset { + if (content.width <= 0f || content.height <= 0f) return offset + return Offset( + x = clampImageAxis(offset.x, content.width, viewport.width), + y = clampImageAxis(offset.y, content.height, viewport.height), + ) +} + +private fun clampImageAxis(value: Float, content: Float, viewport: Float): Float = + if (content <= viewport) (viewport - content) / 2f else value.coerceIn(viewport - content, 0f) + +/** + * The scale a double-tap toggles to: back to [fit] when already zoomed in, + * otherwise the [zoomed] level. Pure, so the toggle is unit tested. + */ +internal fun toggleZoomScale(current: Float, fit: Float = FIT_SCALE, zoomed: Float = DOUBLE_TAP_SCALE): Float = + if (current > fit + ZOOM_EPSILON) fit else zoomed 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 9b6335af..051e6808 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 @@ -36,7 +36,6 @@ import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp -import androidx.compose.ui.window.Dialog import net.awan.pipelines.data.protocol.RunStep import net.awan.pipelines.data.protocol.StageArtifact import net.awan.pipelines.data.transport.ServerUrl @@ -214,8 +213,11 @@ private fun ArtifactTile( ) } + // The tap opens the full-screen viewer (one shared instance across the run + // summary grid, the per-visit list and the stage pane, so they never + // disagree); there is no separate smaller preview to stack on top of it. if (showFull && resolved != null) { - FullSizeArtifactDialog( + ArtifactViewer( url = resolved, name = artifact.name, fetchBytes = fetchArtifactBytes, @@ -289,45 +291,8 @@ private fun ArtifactRow( } } -/** The explicit full-resolution view, opened by tapping an image thumbnail. */ -@Composable -private fun FullSizeArtifactDialog( - url: String, - name: String, - fetchBytes: suspend (String) -> ByteArray?, - onDismiss: () -> Unit, -) { - val text = pipelinesText() - Dialog(onDismissRequest = onDismiss) { - Surface( - shape = RoundedCornerShape(16.dp), - color = MaterialTheme.colorScheme.surfaceContainerHighest, - ) { - Column( - modifier = Modifier.padding(12.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text( - name.ifBlank { "Artifact" }, - style = text.cardTitle, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - ) - ArtifactImage( - url = url, - contentDescription = name, - maxDim = 0, - fetchBytes = fetchBytes, - size = FULL_SIZE_PREVIEW_DP.dp, - ) - } - } - } -} - /** Opens the resolved artifact url externally, tolerating a missing handler. */ -private fun openArtifact(context: Context, url: String?) { +internal fun openArtifact(context: Context, url: String?) { if (url == null) return runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) } } @@ -335,9 +300,6 @@ private fun openArtifact(context: Context, url: String?) { /** Longest edge of a list thumbnail decode. */ private const val THUMBNAIL_MAX_DIM = 160 -/** Fixed box for the full-size preview. */ -private const val FULL_SIZE_PREVIEW_DP = 320 - /** Preferred side of one square gallery thumbnail tile (the named size token). */ private val ARTIFACT_TILE_DP = 96.dp 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 new file mode 100644 index 00000000..590e5aff --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/graph/ArtifactViewerTest.kt @@ -0,0 +1,121 @@ +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.ui.theme.PipelinesDarkColors +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class ArtifactViewerTest { + + @Test + fun fitImageSizePreservesAspectAndFitsInsideTheViewport() { + // A wide image in a tall viewport is limited by width; the height follows + // the aspect ratio, so the whole image fits without distortion. + val fitted = fitImageSize(viewport = Size(400f, 800f), image = Size(2000f, 1000f)) + assertEquals(400f, fitted.width, 0.001f) + assertEquals(200f, fitted.height, 0.001f) + assertTrue(fitted.width <= 400f && fitted.height <= 800f) + } + + @Test + fun fitImageSizeUsesTheTighterAxis() { + val fitted = fitImageSize(viewport = Size(1000f, 600f), image = Size(500f, 1000f)) + assertEquals(300f, fitted.width, 0.001f) + assertEquals(600f, fitted.height, 0.001f) + } + + @Test + fun fitImageSizeNeverUpscalesAnImageSmallerThanTheViewport() { + val fitted = fitImageSize(viewport = Size(1000f, 800f), image = Size(200f, 100f)) + assertEquals(200f, fitted.width, 0.001f) + assertEquals(100f, fitted.height, 0.001f) + } + + @Test + fun fitImageSizeIsZeroForDegenerateInputs() { + assertEquals(Size.Zero, fitImageSize(Size(0f, 100f), Size(50f, 50f))) + assertEquals(Size.Zero, fitImageSize(Size(100f, 100f), Size(0f, 50f))) + } + + @Test + fun clampImageOffsetCentresAnAxisSmallerThanTheViewport() { + // The content is wider but shorter than the viewport: the overflowing x is + // clamped to the viewport edge, the short y is centred. + val clamped = clampImageOffset( + offset = Offset(x = 9999f, y = 9999f), + content = Size(1000f, 500f), + viewport = Size(400f, 800f), + ) + assertEquals(0f, clamped.x, 0.001f) + assertEquals(150f, clamped.y, 0.001f) + } + + @Test + fun clampImageOffsetNeverLetsTheScaledImageLeaveTheViewport() { + val content = Size(1000f, 500f) + val viewport = Size(400f, 800f) + // Dragging far in either direction stays within [viewport - content, 0] on + // the overflowing axis: the image edge can never move inside the viewport. + assertEquals(-600f, clampImageOffset(Offset(-9999f, 0f), content, viewport).x, 0.001f) + assertEquals(0f, clampImageOffset(Offset(9999f, 0f), content, viewport).x, 0.001f) + } + + @Test + fun clampImageOffsetReturnsDegenerateContentUnchanged() { + val offset = Offset(12f, -34f) + assertEquals(offset, clampImageOffset(offset, Size(0f, 100f), Size(400f, 800f))) + assertEquals(offset, clampImageOffset(offset, Size(100f, 0f), Size(400f, 800f))) + } + + @Test + fun toggleZoomScaleTogglesBetweenFitAndTheZoomedLevel() { + // At fit, a double-tap zooms to the declared level; zoomed in, it returns + // to fit. + val zoomed = toggleZoomScale(current = 1f) + assertTrue(zoomed > 1f) + assertEquals(1f, toggleZoomScale(current = zoomed), 0.0001f) + // A value within the fit tolerance still counts as fit, so it zooms. + assertEquals(zoomed, toggleZoomScale(current = 1.0001f), 0.0001f) + } + + /** + * A zoom anchored off-centre followed by the clamp still cannot push the + * scaled image past a viewport edge: the invariant the pan clamp exists for. + */ + @Test + fun anAnchoredZoomThenClampStaysWithinTheImageViewport() { + val base = Size(300f, 200f) + val viewport = Size(300f, 600f) + val zoomed = zoomAbout( + offset = Offset(0f, 200f), + scale = 1f, + centroid = Offset(280f, 20f), + zoom = 2.5f, + 1f, + 5f, + ) + val content = Size(base.width * zoomed.scale, base.height * zoomed.scale) + val clamped = clampImageOffset(zoomed.offset, content, viewport) + // Wider than the viewport: the image still covers it horizontally (no gap + // at either edge). Shorter than the viewport: the axis is centred. + assertTrue(content.width > viewport.width) + assertTrue(clamped.x <= 0f && clamped.x + content.width >= viewport.width) + assertEquals((viewport.height - content.height) / 2f, clamped.y, 0.001f) + } + + /** + * [ViewerMessage] draws on the always-black scrim, so its foreground must be + * the light `inverseSurface` role (the previous `inverseOnSurface` was a dark + * colour on the scrim and measured 1.60:1). This guards that pairing against + * the shipped dark scheme. + */ + @Test + fun theViewerMessageContrastsWithTheScrimItIsDrawnOn() { + val scheme = PipelinesDarkColors + assertEquals(Color(0xFF000000), scheme.scrim) + assertTrue(contrastRatio(scheme.inverseSurface, scheme.scrim) >= 4.5) + } +}