diff --git a/app/src/main/java/com/nextcloud/utils/extensions/OwnCloudClientExtensions.kt b/app/src/main/java/com/nextcloud/utils/extensions/OwnCloudClientExtensions.kt index 1e61bc13f15b..fcbe04697832 100644 --- a/app/src/main/java/com/nextcloud/utils/extensions/OwnCloudClientExtensions.kt +++ b/app/src/main/java/com/nextcloud/utils/extensions/OwnCloudClientExtensions.kt @@ -29,6 +29,17 @@ fun OwnCloudClient.getPreviewEndpoint(localFileId: Long, x: Int, y: Int): String "&x=" + (x / 2) + "&y=" + (y / 2) + "&a=1&mode=cover&forceIcon=0" +/** + * With mode=cover the shorter side is at least [minSide], capped by the original size and the server's + * preview limits, so tall images keep their full width. + */ +fun OwnCloudClient.getFullDetailPreviewEndpoint(localFileId: Long, minSide: Int): String = baseUri + .toString() + + "/index.php/core/preview?fileId=" + + localFileId + + "&x=" + minSide + "&y=" + minSide + + "&a=1&mode=cover&forceIcon=0" + fun OwnCloudClient.getVideoPreviewEndpoint(localFileId: Long, size: Int): String = baseUri .toString() + "/index.php/core/preview?fileId=" + diff --git a/app/src/main/java/com/nextcloud/utils/thumbnail/ResizedImageGenerator.kt b/app/src/main/java/com/nextcloud/utils/thumbnail/ResizedImageGenerator.kt index 654d30842559..aa551c6beef2 100644 --- a/app/src/main/java/com/nextcloud/utils/thumbnail/ResizedImageGenerator.kt +++ b/app/src/main/java/com/nextcloud/utils/thumbnail/ResizedImageGenerator.kt @@ -12,6 +12,7 @@ import android.graphics.BitmapFactory import android.graphics.Point import com.nextcloud.utils.AppConstants import com.nextcloud.utils.extensions.getBigThumbnailKey +import com.nextcloud.utils.extensions.getFullDetailPreviewEndpoint import com.nextcloud.utils.extensions.getPreviewEndpoint import com.nextcloud.utils.extensions.getVideoPreviewEndpoint import com.nextcloud.utils.extensions.isPNG @@ -26,6 +27,8 @@ import com.owncloud.android.utils.BitmapUtils import com.owncloud.android.utils.MimeTypeUtil import org.apache.commons.httpclient.HttpStatus import org.apache.commons.httpclient.methods.GetMethod +import java.io.InputStream +import kotlin.math.min object ResizedImageGenerator { private const val TAG = "ResizedImageGenerator" @@ -33,6 +36,34 @@ object ResizedImageGenerator { @Suppress("MagicNumber") private val VIDEO_PREVIEW_SIZES = listOf(1024, 512, 256, 128, 64) + private const val FULL_DETAIL_SCREEN_FACTOR = 2 + + /** + * Image for the full-screen viewer with enough pixels to zoom into; not cached. Returns null for videos + * and when out of memory, so the caller can fall back to [getOrCreate]. + */ + fun getFullDetail(file: OCFile, client: OwnCloudClient): Bitmap? { + if (MimeTypeUtil.isVideo(file)) { + return null + } + + return try { + val image = if (file.isDown) { + BitmapUtils.decodeFileForViewer(file.storagePath) + } else { + val screenSize = ScreenMetrics.size() + val minSide = FULL_DETAIL_SCREEN_FACTOR * min(screenSize.x, screenSize.y) + val uri = client.getFullDetailPreviewEndpoint(file.localId, minSide) + downloadPreview(file, client, uri) { BitmapUtils.decodeBytesForViewer(it.readBytes()) } + } ?: return null + + withPngBackground(file, image) + } catch (e: OutOfMemoryError) { + Log_OC.e(TAG, "out of memory loading full detail: ${file.remotePath}", e) + null + } + } + fun getOrCreate(file: OCFile, client: OwnCloudClient, storageManager: FileDataStorageManager): Bitmap? { val cacheKey = file.getBigThumbnailKey() val cachedImage = ThumbnailsCacheManager.getBitmapFromDiskCache(cacheKey) @@ -90,21 +121,28 @@ object ResizedImageGenerator { downloadPreview(file, client, client.getPreviewEndpoint(file.localId, screenSize.x, screenSize.y)) } ?: return null - val image = if (file.isPNG()) { - BitmapUtils.centerCropOnPngBackground(preview, preview.width, preview.height) - } else { - preview - } + val image = withPngBackground(file, preview) ThumbnailsCacheManager.addBitmapToCache(cacheKey, image) return image } + private fun withPngBackground(file: OCFile, image: Bitmap): Bitmap = if (file.isPNG()) { + BitmapUtils.centerCropOnPngBackground(image, image.width, image.height) + } else { + image + } + private fun downloadVideoPreview(file: OCFile, client: OwnCloudClient): Bitmap? = VIDEO_PREVIEW_SIZES.firstNotNullOfOrNull { size -> downloadPreview(file, client, client.getVideoPreviewEndpoint(file.localId, size)) } - private fun downloadPreview(file: OCFile, client: OwnCloudClient, uri: String): Bitmap? { + private fun downloadPreview( + file: OCFile, + client: OwnCloudClient, + uri: String, + decode: (InputStream) -> Bitmap? = BitmapFactory::decodeStream + ): Bitmap? { Log_OC.d(TAG, "downloading preview: ${file.remotePath}, uri: $uri") var getMethod: GetMethod? = null @@ -118,7 +156,7 @@ object ResizedImageGenerator { return null } - getMethod.responseBodyAsStream.use { BitmapFactory.decodeStream(it) } + getMethod.responseBodyAsStream.use(decode) } catch (e: Exception) { Log_OC.e(TAG, "preview download failed: ${file.remotePath}", e) null diff --git a/app/src/main/java/com/nextcloud/utils/thumbnail/job/ResizedImageGenerationJob.kt b/app/src/main/java/com/nextcloud/utils/thumbnail/job/ResizedImageGenerationJob.kt index a9f9de0323db..5fbfa3469f4b 100644 --- a/app/src/main/java/com/nextcloud/utils/thumbnail/job/ResizedImageGenerationJob.kt +++ b/app/src/main/java/com/nextcloud/utils/thumbnail/job/ResizedImageGenerationJob.kt @@ -42,6 +42,10 @@ class ResizedImageGenerationJob( suspend fun load(file: OCFile, imageView: ImageView, progressContainer: FrameLayout) { val image = getOrCreateDisplayImage(file) + if (image == null && imageView.visibility == View.VISIBLE && imageView.drawable != null) { + Log_OC.w(TAG, "full detail load failed, keeping cached preview: ${file.remotePath}") + return + } if (image == null) { Log_OC.e(TAG, "load failed, no resized image: ${file.remotePath}") showLoadError() @@ -73,7 +77,9 @@ class ResizedImageGenerationJob( } private fun getOrCreateWithVideoOverlay(file: OCFile, client: OwnCloudClient): Bitmap? = try { - val resizedImage = ResizedImageGenerator.getOrCreate(file, client, storageManager) + // getOrCreate only returns a screen-sized image, which looks blurry when zoomed in + val resizedImage = ResizedImageGenerator.getFullDetail(file, client) + ?: ResizedImageGenerator.getOrCreate(file, client, storageManager) if (resizedImage != null && MimeTypeUtil.isVideo(file)) { VideoOverlayGenerator.addOverlay(resizedImage, MainApp.getAppContext()) } else { diff --git a/app/src/main/java/com/owncloud/android/ui/preview/media/DetailZoomPhotoView.kt b/app/src/main/java/com/owncloud/android/ui/preview/media/DetailZoomPhotoView.kt new file mode 100644 index 000000000000..681fdb9a8a05 --- /dev/null +++ b/app/src/main/java/com/owncloud/android/ui/preview/media/DetailZoomPhotoView.kt @@ -0,0 +1,42 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.owncloud.android.ui.preview.media + +import android.content.Context +import android.graphics.drawable.BitmapDrawable +import android.graphics.drawable.Drawable +import android.util.AttributeSet +import com.github.chrisbanes.photoview.PhotoView + +/** [PhotoView] whose zoom levels follow the image's shape, see [DetailZoomScaleLevels]. */ +class DetailZoomPhotoView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : + PhotoView(context, attrs, defStyle) { + + override fun setImageDrawable(drawable: Drawable?) { + super.setImageDrawable(drawable) + updateScaleLevels() + } + + override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { + super.onSizeChanged(w, h, oldw, oldh) + updateScaleLevels() + } + + private fun updateScaleLevels() { + // also called from the ImageView constructor, before PhotoView's attacher exists; the view has no size + // yet then, so no levels are computed + val image = drawable ?: return + val levels = DetailZoomScaleLevels.of( + viewWidth = width - paddingLeft - paddingRight, + viewHeight = height - paddingTop - paddingBottom, + imageWidth = image.intrinsicWidth, + imageHeight = image.intrinsicHeight, + bitmapWidth = (image as? BitmapDrawable)?.bitmap?.width ?: image.intrinsicWidth + ) ?: return + setScaleLevels(levels.minimum, levels.medium, levels.maximum) + } +} diff --git a/app/src/main/java/com/owncloud/android/ui/preview/media/DetailZoomScaleLevels.kt b/app/src/main/java/com/owncloud/android/ui/preview/media/DetailZoomScaleLevels.kt new file mode 100644 index 000000000000..5632b72a1552 --- /dev/null +++ b/app/src/main/java/com/owncloud/android/ui/preview/media/DetailZoomScaleLevels.kt @@ -0,0 +1,53 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.owncloud.android.ui.preview.media + +import kotlin.math.max +import kotlin.math.min + +/** + * PhotoView zoom levels, relative to the image fitted inside the view. + * + * PhotoView's fixed 1x / 1.75x / 3x leave a very tall image only a few dozen pixels wide even at maximum zoom. + * Here, double tap fills the view along the image's short side for images whose aspect ratio differs strongly + * from the view's, and the maximum zoom always reaches beyond both that level and one image pixel per screen pixel. + */ +data class DetailZoomScaleLevels(val minimum: Float, val medium: Float, val maximum: Float) { + companion object { + private const val DEFAULT_MINIMUM_SCALE = 1f + private const val DEFAULT_MEDIUM_SCALE = 1.75f + private const val DEFAULT_MAXIMUM_SCALE = 3f + private const val ELONGATED_FILL_SCALE = 2f + private const val DETAIL_HEADROOM = 3f + + /** + * [imageWidth] and [imageHeight] are the drawable's intrinsic size; [bitmapWidth] is its width in pixels, + * which differs when the bitmap is scaled for the screen density. Returns null until all sizes are known. + */ + fun of( + viewWidth: Int, + viewHeight: Int, + imageWidth: Int, + imageHeight: Int, + bitmapWidth: Int + ): DetailZoomScaleLevels? { + if (minOf(minOf(viewWidth, viewHeight, imageWidth), minOf(imageHeight, bitmapWidth)) <= 0) { + return null + } + + val widthRatio = viewWidth.toFloat() / imageWidth + val heightRatio = viewHeight.toFloat() / imageHeight + val fitScale = min(widthRatio, heightRatio) + val fillScale = max(widthRatio, heightRatio) / fitScale + val onePixelScale = bitmapWidth / (imageWidth * fitScale) + + val medium = if (fillScale >= ELONGATED_FILL_SCALE) fillScale else DEFAULT_MEDIUM_SCALE + val maximum = maxOf(DEFAULT_MAXIMUM_SCALE, medium * DETAIL_HEADROOM, onePixelScale * DETAIL_HEADROOM) + return DetailZoomScaleLevels(DEFAULT_MINIMUM_SCALE, medium, maximum) + } + } +} diff --git a/app/src/main/java/com/owncloud/android/ui/preview/media/PreviewMediaFragment.kt b/app/src/main/java/com/owncloud/android/ui/preview/media/PreviewMediaFragment.kt index 8306217a58e4..0eb699c92f91 100644 --- a/app/src/main/java/com/owncloud/android/ui/preview/media/PreviewMediaFragment.kt +++ b/app/src/main/java/com/owncloud/android/ui/preview/media/PreviewMediaFragment.kt @@ -267,22 +267,22 @@ class PreviewMediaFragment : } private fun adjustResizedImage(thumbnail: Bitmap?, width: Int, height: Int) { + // the cached preview is screen-sized and too blurry to zoom into, so full detail is always loaded val resizedImage = getResizedBitmap(file, width, height) + binding.image.setImageBitmap(resizedImage ?: thumbnail) if (resizedImage != null && !file.isUpdateThumbnailNeeded) { - binding.image.setImageBitmap(resizedImage) binding.image.visibility = View.VISIBLE binding.emptyListView.visibility = View.GONE binding.emptyListProgress.visibility = View.GONE binding.image.setBackgroundColor(resources.getColor(R.color.background_color_inverse)) - } else { - val storageManager = containerActivity.storageManager ?: return - val job = ResizedImageGenerationJob(this, storageManager, connectivityService, clientRepository) - binding.image.setImageBitmap(resizedImage ?: thumbnail) - resizedImageJob?.cancel() - resizedImageJob = viewLifecycleOwner.lifecycleScope.launch { - job.load(file, binding.image, binding.emptyListProgress) - } + } + + val storageManager = containerActivity.storageManager ?: return + val job = ResizedImageGenerationJob(this, storageManager, connectivityService, clientRepository) + resizedImageJob?.cancel() + resizedImageJob = viewLifecycleOwner.lifecycleScope.launch { + job.load(file, binding.image, binding.emptyListProgress) } } @@ -467,9 +467,7 @@ class PreviewMediaFragment : val storagePath = ocFile.storagePath try { val maxDownScale = 3 // could be a parameter passed to doInBackground(...) - val screenSize = ScreenMetrics.size(activity) - var minWidth = screenSize.x - var minHeight = screenSize.y + var maxPixels = BitmapUtils.VIEWER_MAX_PIXELS var i = 0 while (i < maxDownScale && bitmapResult == null && drawableResult == null) { if (MIME_TYPE_SVG.equals(ocFile.mimeType, ignoreCase = true)) { @@ -497,7 +495,7 @@ class PreviewMediaFragment : } try { - bitmapResult = BitmapUtils.retrieveBitmapFromFile(storagePath, minWidth, minHeight) + bitmapResult = BitmapUtils.decodeFileForViewer(storagePath, maxPixels) if (isCancelled) { return LoadImage(bitmapResult, null, ocFile) @@ -512,8 +510,7 @@ class PreviewMediaFragment : mErrorMessageId = R.string.common_error_out_memory if (i < maxDownScale - 1) { Log_OC.w(TAG, "Out of memory rendering file $storagePath ; scaling down") - minWidth /= 2 - minHeight /= 2 + maxPixels /= OUT_OF_MEMORY_PIXEL_DIVISOR } else { Log_OC.w(TAG, "Out of memory rendering file $storagePath ; failing") } @@ -771,6 +768,7 @@ class PreviewMediaFragment : private const val MIME_TYPE_PNG = "image/png" private const val MIME_TYPE_GIF = "image/gif" private const val MIME_TYPE_SVG = "image/svg+xml" + private const val OUT_OF_MEMORY_PIXEL_DIVISOR = 4 private val TAG: String = PreviewMediaFragment::class.java.simpleName diff --git a/app/src/main/java/com/owncloud/android/utils/BitmapUtils.kt b/app/src/main/java/com/owncloud/android/utils/BitmapUtils.kt index 5e04925d52f4..fc71caa63142 100644 --- a/app/src/main/java/com/owncloud/android/utils/BitmapUtils.kt +++ b/app/src/main/java/com/owncloud/android/utils/BitmapUtils.kt @@ -45,7 +45,6 @@ import com.owncloud.android.ui.StatusDrawable import java.security.MessageDigest import java.security.NoSuchAlgorithmException import kotlin.math.max -import kotlin.math.min import kotlin.math.roundToInt import com.nextcloud.utils.decodeSampledBitmapFromFile as decodeSampledBitmap @@ -92,17 +91,41 @@ object BitmapUtils { fun decodeSampledBitmapFromFile(srcPath: String?, reqWidth: Int, reqHeight: Int): Bitmap? = decodeSampledBitmap(srcPath, reqWidth, reqHeight) - fun retrieveBitmapFromFile(storagePath: String, minWidth: Int, minHeight: Int): Bitmap? { - val (originalWidth, originalHeight) = getImageResolution(storagePath) - if (originalWidth <= 0 || originalHeight <= 0) { + /** + * About 64 MB as ARGB_8888: below Android's 100 MB limit for drawing a single bitmap, and large enough + * to keep tall strips and typical photos at full resolution. + */ + const val VIEWER_MAX_PIXELS = 16_000_000L + + fun decodeFileForViewer(storagePath: String, maxPixels: Long = VIEWER_MAX_PIXELS): Bitmap? = + decodeWithinPixels(maxPixels) { BitmapFactory.decodeFile(storagePath, it) } + .rotateBitmapViaExif(readExifOrientation(storagePath)) + + fun decodeBytesForViewer(data: ByteArray, maxPixels: Long = VIEWER_MAX_PIXELS): Bitmap? = + decodeWithinPixels(maxPixels) { BitmapFactory.decodeByteArray(data, 0, data.size, it) } + + private inline fun decodeWithinPixels(maxPixels: Long, decode: (BitmapFactory.Options) -> Bitmap?): Bitmap? { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + decode(bounds) + if (bounds.outWidth <= 0 || bounds.outHeight <= 0) { return null } - val scaleFactor = min(minWidth.toFloat() / originalWidth, minHeight.toFloat() / originalHeight) - val scaledWidth = (originalWidth * scaleFactor).toInt() - val scaledHeight = (originalHeight * scaleFactor).toInt() - return decodeSampledBitmap(storagePath, scaledWidth, scaledHeight) - .rotateBitmapViaExif(readExifOrientation(storagePath)) + return decode( + BitmapFactory.Options().apply { + inSampleSize = viewerSampleSize(bounds.outWidth, bounds.outHeight, maxPixels) + } + ) + } + + /** Smallest power-of-two sample size that brings [width] x [height] within [maxPixels]. */ + @JvmStatic + fun viewerSampleSize(width: Int, height: Int, maxPixels: Long): Int { + var sampleSize = 1 + while ((width.toLong() / sampleSize) * (height.toLong() / sampleSize) > maxPixels) { + sampleSize *= 2 + } + return sampleSize } @JvmStatic diff --git a/app/src/main/res/layout/preview_image_fragment.xml b/app/src/main/res/layout/preview_image_fragment.xml index e385e4bff8c8..1388007873b7 100644 --- a/app/src/main/res/layout/preview_image_fragment.xml +++ b/app/src/main/res/layout/preview_image_fragment.xml @@ -37,7 +37,7 @@ app:drawableStartCompat="@drawable/ic_live_photo" tools:visibility="visible" /> - = levels.medium * 3) + assertTrue(540 * fitScale(540, 21242) * levels.maximum >= 540) + } + + @Test + fun `image shaped like the view keeps PhotoView default double tap level`() { + val levels = levels(1080, 2400) + + assertEquals(1f, levels.minimum) + assertEquals(1.75f, levels.medium) + assertTrue(levels.maximum >= 3f) + } + + @Test + fun `maximum zoom reaches one pixel per screen pixel for a large photo`() { + val levels = levels(8000, 6000) + + assertTrue(8000 * fitScale(8000, 6000) * levels.maximum >= 8000) + } + + @Test + fun `density-scaled drawable uses bitmap pixels for one pixel per screen pixel`() { + val levels = levels(imageWidth = 540, imageHeight = 1200, bitmapWidth = 2160) + + assertTrue(540 * fitScale(540, 1200) * levels.maximum >= 2160) + } + + @Test + fun `levels are unknown before the view is laid out`() { + assertNull(DetailZoomScaleLevels.of(0, 0, 540, 21242, 540)) + } +} diff --git a/app/src/test/java/com/owncloud/android/utils/BitmapUtilsViewerSampleSizeTest.kt b/app/src/test/java/com/owncloud/android/utils/BitmapUtilsViewerSampleSizeTest.kt new file mode 100644 index 000000000000..202755e447fe --- /dev/null +++ b/app/src/test/java/com/owncloud/android/utils/BitmapUtilsViewerSampleSizeTest.kt @@ -0,0 +1,41 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.owncloud.android.utils + +import org.junit.Assert.assertEquals +import org.junit.Test + +@Suppress("MagicNumber") +class BitmapUtilsViewerSampleSizeTest { + + private val maxPixels = BitmapUtils.VIEWER_MAX_PIXELS + + @Test + fun `tall strip within the budget is decoded at full resolution`() { + assertEquals(1, BitmapUtils.viewerSampleSize(540, 21242, maxPixels)) + } + + @Test + fun `image exactly at the budget is decoded at full resolution`() { + assertEquals(1, BitmapUtils.viewerSampleSize(4000, 4000, maxPixels)) + } + + @Test + fun `image over the budget is halved`() { + assertEquals(2, BitmapUtils.viewerSampleSize(6000, 4000, maxPixels)) + } + + @Test + fun `very large image is sampled until it fits the budget`() { + assertEquals(8, BitmapUtils.viewerSampleSize(20000, 20000, maxPixels)) + } + + @Test + fun `dimensions whose pixel count overflows Int are handled`() { + assertEquals(16, BitmapUtils.viewerSampleSize(50000, 50000, maxPixels)) + } +}