π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add Android wallpaper setting from Photos
Neeraj Gupta78c799eab585
diff --git a/mobile/apps/photos/changes/android-wallpaper.md b/mobile/apps/photos/changes/android-wallpaper.mdnew file mode 100644index 0000000000..71681670e6--- /dev/null+++ b/mobile/apps/photos/changes/android-wallpaper.md@@ -0,0 +1 @@+- Set photos as your home screen, lock screen, or both wallpapers on Android, with a preview to adjust the crop.diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/build.gradle b/mobile/apps/photos/plugins/ente_photos_platform/android/build.gradleindex d908db8522..00bd3fba24 100644--- a/mobile/apps/photos/plugins/ente_photos_platform/android/build.gradle+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/build.gradle@@ -39,9 +39,21 @@ android {sourceSets {main.java.srcDirs += 'src/main/kotlin'+ main.assets.srcDir layout.buildDirectory.dir('generated/wallpaperAssets')}defaultConfig {minSdkVersion 23}}++def wallpaperFonts = tasks.register('prepareWallpaperFonts', Copy) {+ from '../../../../../packages/ente_components/fonts'+ include 'Inter-Regular.ttf', 'Inter-SemiBold.ttf'+ into layout.buildDirectory.dir('generated/wallpaperAssets')+}+tasks.named('preBuild').configure { dependsOn wallpaperFonts }++dependencies {+ implementation 'androidx.exifinterface:exifinterface:1.3.7'+}diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/AndroidManifest.xml b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/AndroidManifest.xmlindex a2f47b6057..d039972950 100644--- a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/AndroidManifest.xml+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/AndroidManifest.xml@@ -1,2 +1,16 @@<manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <uses-permission android:name="android.permission.SET_WALLPAPER" />+ <application>+ <activity+ android:name="io.ente.photos.platform.wallpaper.WallpaperActivity"+ android:exported="true"+ android:label="@string/wallpaper"+ android:theme="@style/WallpaperTheme">+ <intent-filter>+ <action android:name="android.intent.action.ATTACH_DATA" />+ <category android:name="android.intent.category.DEFAULT" />+ <data android:mimeType="image/*" />+ </intent-filter>+ </activity>+ </application></manifest>diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/Crop.kt b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/Crop.ktnew file mode 100644index 0000000000..67d4819155--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/Crop.kt@@ -0,0 +1,21 @@+package io.ente.photos.platform.wallpaper++import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.Color+import android.graphics.Paint+import android.graphics.Point+import android.graphics.RectF++// The region is normalized to the image after applying EXIF orientation.+internal data class Crop(val region: RectF, val size: Point) {+ fun render(image: Bitmap): Bitmap {+ val result = Bitmap.createBitmap(size.x, size.y, Bitmap.Config.ARGB_8888)+ val canvas = Canvas(result)+ canvas.drawColor(Color.BLACK)+ canvas.scale(size.x / (region.width() * image.width), size.y / (region.height() * image.height))+ canvas.translate(-region.left * image.width, -region.top * image.height)+ canvas.drawBitmap(image, 0f, 0f, Paint(Paint.FILTER_BITMAP_FLAG))+ return result+ }+}diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/DestinationSheet.kt b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/DestinationSheet.ktnew file mode 100644index 0000000000..5161fdf35e--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/DestinationSheet.kt@@ -0,0 +1,94 @@+package io.ente.photos.platform.wallpaper++import android.app.Dialog+import android.content.Context+import android.content.res.ColorStateList+import android.graphics.Color+import android.graphics.Typeface+import android.graphics.drawable.ColorDrawable+import android.graphics.drawable.GradientDrawable+import android.graphics.drawable.RippleDrawable+import android.view.Gravity+import android.view.Window+import android.view.ViewGroup.LayoutParams.MATCH_PARENT+import android.view.ViewGroup.LayoutParams.WRAP_CONTENT+import android.widget.ImageButton+import android.widget.Button+import android.widget.LinearLayout+import android.widget.TextView+import io.ente.photos.platform.R++internal class DestinationSheet(context: Context, onSelected: (Destination) -> Unit) : Dialog(context) {+ private val regular = Typeface.createFromAsset(context.assets, "Inter-Regular.ttf")+ private val semibold = Typeface.createFromAsset(context.assets, "Inter-SemiBold.ttf")++ init {+ requestWindowFeature(Window.FEATURE_NO_TITLE)+ window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))+ val content = LinearLayout(context).apply {+ orientation = LinearLayout.VERTICAL+ setPadding(dp(20), dp(20), dp(20), dp(20))+ // Matches ente_components' dark backgroundBase and bottomSheet radius.+ background = GradientDrawable().apply {+ setColor(0xFF161616.toInt())+ cornerRadii = floatArrayOf(dp(20).toFloat(), dp(20).toFloat(), dp(20).toFloat(), dp(20).toFloat(), 0f, 0f, 0f, 0f)+ }+ }+ val header = LinearLayout(context).apply { gravity = Gravity.CENTER_VERTICAL }+ header.addView(TextView(context).apply {+ setText(R.string.wallpaper_set)+ textSize = 18f+ typeface = semibold+ setTextColor(Color.WHITE)+ }, LinearLayout.LayoutParams(0, WRAP_CONTENT, 1f))+ header.addView(ImageButton(context).apply {+ setImageResource(R.drawable.wallpaper_close)+ contentDescription = context.getString(android.R.string.cancel)+ background = surface(24)+ setOnClickListener { dismiss() }+ }, LinearLayout.LayoutParams(dp(48), dp(48)))+ content.addView(header, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply { bottomMargin = dp(16) })+ for (destination in Destination.entries) {+ content.addView(Button(context).apply {+ setText(destination.label)+ isAllCaps = false+ letterSpacing = 0f+ stateListAnimator = null+ textSize = 16f+ typeface = regular+ setTextColor(Color.WHITE)+ gravity = Gravity.CENTER_VERTICAL+ minHeight = dp(56)+ setPadding(dp(20), dp(16), dp(20), dp(16))+ background = surface(20)+ setOnClickListener {+ dismiss()+ onSelected(destination)+ }+ }, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply { bottomMargin = dp(8) })+ }+ setContentView(content)+ setCanceledOnTouchOutside(true)+ }++ override fun onStart() {+ super.onStart()+ window!!.apply {+ setGravity(Gravity.BOTTOM)+ setLayout(MATCH_PARENT, WRAP_CONTENT)+ setDimAmount(0.55f)+ navigationBarColor = 0xFF161616.toInt()+ }+ }++ private fun surface(radius: Int) = RippleDrawable(+ ColorStateList.valueOf(0x29FFFFFF),+ GradientDrawable().apply {+ setColor(0xFF212121.toInt())+ cornerRadius = dp(radius).toFloat()+ },+ null,+ )++ private fun dp(value: Int) = (value * context.resources.displayMetrics.density).toInt()+}diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperActivity.kt b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperActivity.ktnew file mode 100644index 0000000000..593bb83441--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperActivity.kt@@ -0,0 +1,216 @@+package io.ente.photos.platform.wallpaper++import android.app.Activity+import android.content.ContentResolver+import android.content.res.ColorStateList+import android.graphics.Color+import android.graphics.Point+import android.graphics.Typeface+import android.graphics.drawable.GradientDrawable+import android.graphics.drawable.RippleDrawable+import android.net.Uri+import android.os.Bundle+import android.util.Log+import android.view.Gravity+import android.view.View+import android.widget.Button+import android.widget.FrameLayout+import android.widget.ImageButton+import android.widget.LinearLayout+import android.widget.ProgressBar+import android.widget.TextView+import android.widget.Toast+import io.ente.photos.platform.R+import java.util.concurrent.CompletableFuture+import java.util.concurrent.Executors++class WallpaperActivity : Activity() {+ private val executor = Executors.newSingleThreadExecutor()+ private lateinit var preview: WallpaperCropView+ private lateinit var applyButton: Button+ private lateinit var progress: ProgressBar+ private lateinit var service: WallpaperService+ private lateinit var imageUri: Uri+ private var pendingApply: CompletableFuture<Unit>? = null+ private var destinationSheet: DestinationSheet? = null+ private var loaded = false++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ @Suppress("UNCHECKED_CAST", "DEPRECATION")+ val retained = lastNonConfigurationInstance as? CompletableFuture<Unit>+ pendingApply = retained+ service = WallpaperService(this)+ if (!service.isAvailable) {+ Toast.makeText(this, R.string.wallpaper_unavailable, Toast.LENGTH_LONG).show()+ finish()+ return+ }+ val uri = intent.data+ if (uri?.scheme != ContentResolver.SCHEME_CONTENT) {+ showFailure(IllegalArgumentException("Expected an image content URI"))+ finish()+ return+ }+ imageUri = uri+ val displaySize = Point()+ @Suppress("DEPRECATION")+ windowManager.defaultDisplay.getRealSize(displaySize)+ preview = WallpaperCropView(this, displaySize)+ preview.restoreCrop(savedInstanceState?.getFloatArray("crop"))+ val content = LinearLayout(this).apply {+ orientation = LinearLayout.VERTICAL+ setOnApplyWindowInsetsListener { view, insets ->+ @Suppress("DEPRECATION")+ view.setPadding(+ insets.systemWindowInsetLeft,+ insets.systemWindowInsetTop,+ insets.systemWindowInsetRight,+ insets.systemWindowInsetBottom,+ )+ insets+ }+ }+ val semibold = Typeface.createFromAsset(assets, "Inter-SemiBold.ttf")+ val header = LinearLayout(this).apply {+ gravity = Gravity.CENTER_VERTICAL+ setPadding(dp(8), dp(4), dp(20), dp(4))+ }+ header.addView(ImageButton(this).apply {+ setImageResource(R.drawable.wallpaper_close)+ contentDescription = getString(android.R.string.cancel)+ background = RippleDrawable(ColorStateList.valueOf(0x29FFFFFF), null, null)+ setOnClickListener { finish() }+ }, LinearLayout.LayoutParams(dp(48), dp(48)))+ header.addView(TextView(this).apply {+ setText(R.string.wallpaper)+ typeface = semibold+ textSize = 18f+ setTextColor(Color.WHITE)+ })+ content.addView(header)+ content.addView(preview, LinearLayout.LayoutParams(-1, 0, 1f))+ applyButton = Button(this).apply {+ setText(R.string.wallpaper_set)+ isAllCaps = false+ letterSpacing = 0f+ stateListAnimator = null+ typeface = semibold+ textSize = 16f+ minHeight = dp(56)+ setPadding(dp(20), dp(14), dp(20), dp(14))+ background = RippleDrawable(+ ColorStateList.valueOf(0x29000000),+ GradientDrawable().apply {+ setColor(0xFF08C225.toInt())+ cornerRadius = dp(20).toFloat()+ },+ null,+ )+ setOnClickListener { chooseDestination() }+ }+ progress = ProgressBar(this).apply {+ isIndeterminate = true+ indeterminateTintList = ColorStateList.valueOf(Color.WHITE)+ }+ val action = FrameLayout(this).apply {+ addView(applyButton, FrameLayout.LayoutParams(-1, -2))+ addView(progress, FrameLayout.LayoutParams(dp(24), dp(24), Gravity.CENTER))+ }+ content.addView(action, LinearLayout.LayoutParams(-1, -2).apply {+ setMargins(dp(20), dp(16), dp(20), dp(16))+ })+ setBusy(true)+ setContentView(content)+ retained?.let(::observeApply)+ executor.execute {+ try {+ val bitmap = service.decode(uri, displaySize)+ runOnUiThread {+ if (isDestroyed) {+ bitmap.recycle()+ } else {+ preview.setImage(bitmap)+ loaded = true+ setBusy(pendingApply != null)+ }+ }+ } catch (error: Exception) {+ runOnUiThread {+ if (!isDestroyed) {+ showFailure(error)+ finish()+ }+ }+ }+ }+ }++ private fun chooseDestination() {+ destinationSheet = DestinationSheet(this, ::applyWallpaper).also { it.show() }+ }++ private fun applyWallpaper(destination: Destination) {+ if (pendingApply != null) return+ setBusy(true)+ val crop = preview.selection()+ val task = CompletableFuture.supplyAsync({+ val bitmap = service.render(imageUri, crop)+ try {+ service.apply(bitmap, destination)+ } finally {+ bitmap.recycle()+ }+ }, executor)+ pendingApply = task+ observeApply(task)+ }++ private fun observeApply(task: CompletableFuture<Unit>) {+ task.whenComplete { _, error ->+ runOnUiThread {+ if (isDestroyed) return@runOnUiThread+ if (error == null) {+ Toast.makeText(this, R.string.wallpaper_done, Toast.LENGTH_SHORT).show()+ setResult(RESULT_OK)+ finish()+ } else {+ showFailure(error)+ pendingApply = null+ setBusy(!loaded)+ }+ }+ }+ }++ private fun setBusy(busy: Boolean) {+ applyButton.isEnabled = !busy+ applyButton.alpha = if (busy) 0.4f else 1f+ applyButton.setTextColor(if (busy) Color.TRANSPARENT else Color.WHITE)+ preview.isEnabled = !busy+ progress.visibility = if (busy) View.VISIBLE else View.GONE+ }++ private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()++ private fun showFailure(error: Throwable) {+ Log.e("Wallpaper", "Wallpaper operation failed", error)+ Toast.makeText(this, R.string.wallpaper_failed, Toast.LENGTH_LONG).show()+ }++ override fun onSaveInstanceState(outState: Bundle) {+ if (::preview.isInitialized) outState.putFloatArray("crop", preview.saveCrop())+ super.onSaveInstanceState(outState)+ }++ @Suppress("OVERRIDE_DEPRECATION")+ override fun onRetainNonConfigurationInstance(): Any? = pendingApply++ override fun onDestroy() {+ destinationSheet?.dismiss()+ executor.shutdown()+ if (::preview.isInitialized) preview.release()+ super.onDestroy()+ }+}diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperCropView.kt b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperCropView.ktnew file mode 100644index 0000000000..ec94db709c--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperCropView.kt@@ -0,0 +1,132 @@+package io.ente.photos.platform.wallpaper++import android.content.Context+import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.Color+import android.graphics.Paint+import android.graphics.Point+import android.graphics.RectF+import android.view.MotionEvent+import android.view.ScaleGestureDetector+import android.view.View+import kotlin.math.max+import kotlin.math.min++internal class WallpaperCropView(context: Context, private val displaySize: Point) : View(context) {+ private var bitmap: Bitmap? = null+ private val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)+ private val frame = RectF()+ private var zoom = 1f+ private var centerX = 0.5f+ private var centerY = 0.5f+ private var lastX = 0f+ private var lastY = 0f+ private val gestures = ScaleGestureDetector(context,+ object : ScaleGestureDetector.SimpleOnScaleGestureListener() {+ override fun onScale(detector: ScaleGestureDetector): Boolean {+ val image = bitmap ?: return false+ val before = scale(image)+ zoom = (zoom * detector.scaleFactor).coerceIn(1f, 4f)+ val after = scale(image)+ centerX += (detector.focusX - frame.centerX()) * (1 / before - 1 / after) / image.width+ centerY += (detector.focusY - frame.centerY()) * (1 / before - 1 / after) / image.height+ constrain()+ invalidate()+ return true+ }+ },+ )++ fun setImage(image: Bitmap) {+ bitmap = image+ constrain()+ invalidate()+ }++ fun saveCrop() = floatArrayOf(zoom, centerX, centerY)++ fun restoreCrop(crop: FloatArray?) {+ if (crop == null) return+ zoom = crop[0]+ centerX = crop[1]+ centerY = crop[2]+ }++ fun selection(): Crop {+ val image = checkNotNull(bitmap)+ val scale = scale(image)+ val halfWidth = frame.width() / (2 * scale * image.width)+ val halfHeight = frame.height() / (2 * scale * image.height)+ return Crop(RectF(centerX - halfWidth, centerY - halfHeight, centerX + halfWidth, centerY + halfHeight), displaySize)+ }++ fun release() {+ bitmap?.recycle()+ bitmap = null+ }++ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {+ val fit = min(w.toFloat() / displaySize.x, h.toFloat() / displaySize.y)+ val frameWidth = displaySize.x * fit+ val frameHeight = displaySize.y * fit+ frame.set((w - frameWidth) / 2, (h - frameHeight) / 2, (w + frameWidth) / 2, (h + frameHeight) / 2)+ constrain()+ }++ override fun onDraw(canvas: Canvas) {+ canvas.drawColor(Color.BLACK)+ canvas.save()+ canvas.clipRect(frame)+ drawImage(canvas)+ canvas.restore()+ }++ private fun drawImage(canvas: Canvas) {+ val image = bitmap ?: return+ canvas.translate(frame.centerX(), frame.centerY())+ val scale = scale(image)+ canvas.scale(scale, scale)+ canvas.drawBitmap(image, -centerX * image.width, -centerY * image.height, paint)+ }++ override fun onTouchEvent(event: MotionEvent): Boolean {+ val image = bitmap ?: return false+ if (!isEnabled) return false+ gestures.onTouchEvent(event)+ when (event.actionMasked) {+ MotionEvent.ACTION_MOVE -> {+ if (!gestures.isInProgress && event.pointerCount == 1) {+ val scale = scale(image)+ centerX -= (event.x - lastX) / (scale * image.width)+ centerY -= (event.y - lastY) / (scale * image.height)+ constrain()+ invalidate()+ }+ }+ MotionEvent.ACTION_UP -> performClick()+ }+ val pointer = if (event.actionMasked == MotionEvent.ACTION_POINTER_UP && event.actionIndex == 0) 1 else 0+ lastX = event.getX(pointer)+ lastY = event.getY(pointer)+ return true+ }++ override fun performClick(): Boolean {+ super.performClick()+ return true+ }++ private fun constrain() {+ val image = bitmap ?: return+ if (frame.isEmpty) return+ val scale = scale(image)+ val halfWidth = min(0.5f, frame.width() / (2 * scale * image.width))+ val halfHeight = min(0.5f, frame.height() / (2 * scale * image.height))+ centerX = centerX.coerceIn(halfWidth, 1 - halfWidth)+ centerY = centerY.coerceIn(halfHeight, 1 - halfHeight)+ }++ private fun scale(image: Bitmap) = max(frame.width() / image.width, frame.height() / image.height) * zoom++}diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperService.kt b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperService.ktnew file mode 100644index 0000000000..af86cc7b08--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperService.kt@@ -0,0 +1,141 @@+package io.ente.photos.platform.wallpaper++import android.app.WallpaperManager+import android.content.Context+import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.graphics.BitmapRegionDecoder+import android.graphics.ImageDecoder+import android.graphics.Matrix+import android.graphics.Point+import android.graphics.Rect+import android.graphics.RectF+import android.net.Uri+import android.os.Build+import androidx.exifinterface.media.ExifInterface+import io.ente.photos.platform.R+import java.io.IOException+import kotlin.math.max+import kotlin.math.min++internal enum class Destination(val label: Int, val flags: Int) {+ HOME(R.string.wallpaper_home, WallpaperManager.FLAG_SYSTEM),+ LOCK(R.string.wallpaper_lock, WallpaperManager.FLAG_LOCK),+ BOTH(R.string.wallpaper_both, WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK),+}++internal class WallpaperService(context: Context) {+ private val resolver = context.contentResolver+ private val manager = WallpaperManager.getInstance(context)++ val isAvailable: Boolean+ get() = manager.isWallpaperSupported && manager.isSetWallpaperAllowed++ fun apply(bitmap: Bitmap, destination: Destination) {+ check(isAvailable) { "Wallpaper changes are not allowed" }+ check(manager.setBitmap(bitmap, null, false, destination.flags) != 0) {+ "Wallpaper manager did not set the image"+ }+ }++ fun render(uri: Uri, crop: Crop): Bitmap {+ val decoder = try {+ resolver.openInputStream(uri)!!.use {+ @Suppress("DEPRECATION")+ requireNotNull(BitmapRegionDecoder.newInstance(it, false))+ }+ } catch (_: IOException) {+ // Formats without a region decoder (for example GIF) keep the preview path.+ val image = decode(uri, crop.size)+ return try { crop.render(image) } finally { image.recycle() }+ }+ try {+ val transform = orientation(uri)+ val unit = RectF(0f, 0f, 1f, 1f)+ transform.mapRect(unit)+ transform.postTranslate(-unit.left, -unit.top)+ val inverse = Matrix()+ transform.invert(inverse)+ val storageRegion = RectF(crop.region)+ inverse.mapRect(storageRegion)+ storageRegion.set(+ storageRegion.left * decoder.width, storageRegion.top * decoder.height,+ storageRegion.right * decoder.width, storageRegion.bottom * decoder.height,+ )+ val bounds = Rect()+ storageRegion.roundOut(bounds)+ bounds.intersect(0, 0, decoder.width, decoder.height)+ val axes = floatArrayOf(1f, 0f)+ transform.mapVectors(axes)+ val swapAxes = kotlin.math.abs(axes[0]) < 0.5f+ val targetWidth = if (swapAxes) crop.size.y else crop.size.x+ val targetHeight = if (swapAxes) crop.size.x else crop.size.y+ val options = BitmapFactory.Options().apply {+ inSampleSize = max(1, Integer.highestOneBit(min(bounds.width() / targetWidth, bounds.height() / targetHeight)))+ }+ val decoded = requireNotNull(decoder.decodeRegion(bounds, options)) { "Unsupported image region" }+ val image = orient(decoded, transform)+ val available = RectF(+ bounds.left.toFloat() / decoder.width, bounds.top.toFloat() / decoder.height,+ bounds.right.toFloat() / decoder.width, bounds.bottom.toFloat() / decoder.height,+ )+ transform.mapRect(available)+ val region = RectF(+ (crop.region.left - available.left) / available.width(),+ (crop.region.top - available.top) / available.height(),+ (crop.region.right - available.left) / available.width(),+ (crop.region.bottom - available.top) / available.height(),+ )+ return try { Crop(region, crop.size).render(image) } finally { image.recycle() }+ } finally {+ decoder.recycle()+ }+ }++ fun decode(uri: Uri, displaySize: Point): Bitmap {+ // Keep two screen lengths of detail for zooming, without decoding full-resolution photos.+ val maxSize = 2 * max(displaySize.x, displaySize.y)+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {+ return ImageDecoder.decodeBitmap(ImageDecoder.createSource(resolver, uri)) { decoder, info, _ ->+ decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE+ val scale = minOf(1.0, maxSize.toDouble() / max(info.size.width, info.size.height))+ decoder.setTargetSize(+ max(1, (info.size.width * scale).toInt()),+ max(1, (info.size.height * scale).toInt()),+ )+ }+ }+ return decodeSampled(uri, maxSize)+ }++ fun decodeSampled(uri: Uri, maxSize: Int): Bitmap {+ val options = BitmapFactory.Options().apply {+ inJustDecodeBounds = true+ inSampleSize = 1+ }+ resolver.openInputStream(uri)!!.use { BitmapFactory.decodeStream(it, null, options) }+ while (max(options.outWidth, options.outHeight) / options.inSampleSize > maxSize) {+ options.inSampleSize *= 2+ }+ options.inJustDecodeBounds = false+ val bitmap = resolver.openInputStream(uri)!!.use {+ requireNotNull(BitmapFactory.decodeStream(it, null, options)) { "Unsupported image" }+ }+ return orient(bitmap, orientation(uri))+ }++ private fun orientation(uri: Uri): Matrix {+ val exif = resolver.openInputStream(uri)!!.use { ExifInterface(it) }+ return Matrix().apply {+ if (exif.isFlipped) postScale(-1f, 1f)+ postRotate(exif.rotationDegrees.toFloat())+ }+ }++ private fun orient(bitmap: Bitmap, transform: Matrix): Bitmap {+ return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, transform, true).also {+ if (it !== bitmap) bitmap.recycle()+ }+ }+}diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/res/drawable/wallpaper_close.xml b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/res/drawable/wallpaper_close.xmlnew file mode 100644index 0000000000..4ef9633150--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/res/drawable/wallpaper_close.xml@@ -0,0 +1,11 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="20dp"+ android:height="20dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path+ android:pathData="M6,6 L18,18 M18,6 L6,18"+ android:strokeColor="#FFFFFF"+ android:strokeWidth="1.8"+ android:strokeLineCap="round" />+</vector>diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/res/values/wallpaper.xml b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/res/values/wallpaper.xmlnew file mode 100644index 0000000000..62d7557dc6--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/res/values/wallpaper.xml@@ -0,0 +1,17 @@+<resources>+ <string name="wallpaper">Wallpaper</string>+ <string name="wallpaper_set">Set wallpaper</string>+ <string name="wallpaper_home">Home screen</string>+ <string name="wallpaper_lock">Lock screen</string>+ <string name="wallpaper_both">Home and lock screens</string>+ <string name="wallpaper_done">Wallpaper set</string>+ <string name="wallpaper_failed">Could not set wallpaper</string>+ <string name="wallpaper_unavailable">Wallpaper changes are not allowed on this device</string>+ <style name="WallpaperTheme" parent="android:style/Theme.Material.NoActionBar">+ <item name="android:colorAccent">#08C225</item>+ <item name="android:windowBackground">#000000</item>+ <item name="android:statusBarColor">#000000</item>+ <item name="android:navigationBarColor">#000000</item>+ <item name="android:windowLightStatusBar">false</item>+ </style>+</resources>