Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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=" +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -26,13 +27,43 @@ 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"

@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)
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
}
}
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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)
Expand All @@ -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")
}
Expand Down Expand Up @@ -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

Expand Down
41 changes: 32 additions & 9 deletions app/src/main/java/com/owncloud/android/utils/BitmapUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/res/layout/preview_image_fragment.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
app:drawableStartCompat="@drawable/ic_live_photo"
tools:visibility="visible" />

<com.github.chrisbanes.photoview.PhotoView
<com.owncloud.android.ui.preview.media.DetailZoomPhotoView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
Expand Down
Loading