photos: add wallpaper screen #352
- Commit
73db5012c0655b71a73c8a51a66aa29db542a5fe- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-27 18:55 UTC (4 months ago)
- Parents
eabb99a
Diff
library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt b/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.ktindex ac3c3da871..3f2c2eea41 100644--- a/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt+++ b/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt@@ -98,6 +98,11 @@ class DefaultConverters { fun fromInstant(value: Instant) = value.epochSeconds @TypeConverter fun toInstant(value: Long) = Instant.fromEpochSeconds(value)+ @TypeConverter+ fun fromInstantNullable(value: Instant?): Long? = value?.epochSeconds+ @TypeConverter+ fun toInstantNullable(value: Long?): Instant? = value?.let { Instant.fromEpochSeconds(it) }+ @TypeConverter fun fromList(value: List<Long>?): String? { return value?.let { Json.encodeToString(it) }@@ -119,6 +124,10 @@ class DefaultConverters { fun fromDuration(value: Duration) = value.inWholeMilliseconds @TypeConverter fun toDuration(value: Long) = value.milliseconds+ @TypeConverter+ fun fromDurationNullable(value: Duration?): Long? = value?.inWholeMilliseconds+ @TypeConverter+ fun toDurationNullable(value: Long?): Duration? = value?.milliseconds @TypeConverter fun fromLocalTime(value: LocalTime) = value.toSecondOfDay()
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex 8c50bd529b..27880325fc 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -189,6 +189,7 @@ import androidx.compose.material.icons.filled.VisibilityOff import androidx.compose.material.icons.filled.WaterDrop import androidx.compose.material.icons.filled.WbSunny import androidx.compose.material.icons.filled.Whatshot+import androidx.compose.material.icons.filled.Wallpaper import androidx.compose.material.icons.filled.Work import androidx.compose.material.icons.outlined.HighlightAlt import androidx.compose.material.icons.outlined.Inbox@@ -1014,3 +1015,7 @@ fun IconShapeArrowFill(modifier: Modifier = Modifier, tint: Color = LocalContent @Composable fun IconShapeArrowOutline(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) = AppIcon(Icons.Outlined.ArrowRightAlt, "Arrow outline", modifier, tint)++@Composable+fun IconWallpaper(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.Wallpaper, "Wallpaper", modifier, tint)
photos/src/main/AndroidManifest.xml
diff --git a/photos/src/main/AndroidManifest.xml b/photos/src/main/AndroidManifest.xmlindex bb212ba731..4446269317 100644--- a/photos/src/main/AndroidManifest.xml+++ b/photos/src/main/AndroidManifest.xml@@ -15,6 +15,9 @@ <!-- For managing media files without popup on Android 12+ --> <uses-permission android:name="android.permission.MANAGE_MEDIA" /> + <uses-permission android:name="android.permission.SET_WALLPAPER" />+ <uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" />+ <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
photos/src/main/java/com/vayunmathur/photos/MainActivity.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt b/photos/src/main/java/com/vayunmathur/photos/MainActivity.ktindex 5dfc0fbf69..c4f5ab74ed 100644--- a/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt+++ b/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt@@ -75,6 +75,7 @@ import com.vayunmathur.photos.ui.PeoplePage import com.vayunmathur.photos.ui.PhotoPage import com.vayunmathur.photos.ui.SecureFolderPage import com.vayunmathur.photos.ui.TrashPage+import com.vayunmathur.photos.ui.WallpaperPage import com.vayunmathur.photos.util.GalleryViewModel import com.vayunmathur.photos.util.GalleryViewModelFactory import com.vayunmathur.photos.util.ImageLoader@@ -239,6 +240,9 @@ sealed interface Route: NavKey { @Serializable data object SecureFolder: Route++ @Serializable+ data class Wallpaper(val id: Long, val uri: String? = null) : Route } @Composable@@ -282,7 +286,11 @@ fun Navigation( } entry<Route.PhotoPage> {- PhotoPage(galleryViewModel, photoMapViewModel, it.id, it.overridePhotosList, it.pendingUri)+ PhotoPage(galleryViewModel, photoMapViewModel, it.id, it.overridePhotosList, it.pendingUri, backStack)+ }++ entry<Route.Wallpaper> {+ WallpaperPage(backStack, it.id, it.uri) } entry<Route.Trash> {
photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.ktindex 06dae269be..d0424adf0c 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt@@ -69,7 +69,10 @@ import coil.compose.AsyncImage import coil.request.ImageRequest import com.vayunmathur.library.ui.IconEdit import com.vayunmathur.library.ui.IconShare+import com.vayunmathur.library.ui.IconWallpaper+import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.photos.R+import com.vayunmathur.photos.Route import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.util.GalleryViewModel import com.vayunmathur.photos.util.PhotoMapViewModel@@ -87,7 +90,7 @@ import kotlinx.datetime.toLocalDateTime data class ZoomState(val scale: Float = 1f, val offset: Offset = Offset.Zero) @Composable-fun PhotoPage(galleryViewModel: GalleryViewModel, photoMapViewModel: PhotoMapViewModel, id: Long, overridePhotosList: List<Photo>?, pendingUri: String? = null) {+fun PhotoPage(galleryViewModel: GalleryViewModel, photoMapViewModel: PhotoMapViewModel, id: Long, overridePhotosList: List<Photo>?, pendingUri: String? = null, backStack: NavBackStack<Route>? = null) { val photosAll by galleryViewModel.photos.collectAsState() val photos = overridePhotosList ?: photosAll.filter { !it.isTrashed } val context = LocalContext.current@@ -168,6 +171,9 @@ fun PhotoPage(galleryViewModel: GalleryViewModel, photoMapViewModel: PhotoMapVie putExtra("photo_id", photo.id) } context.startActivity(intent)+ },+ onSetWallpaper = { p ->+ backStack?.add(Route.Wallpaper(p.id, p.uri)) } ) }@@ -207,7 +213,8 @@ fun PhotoDetailView( onZoomUpdate: (ZoomState) -> Unit, onToggleMetadata: () -> Unit, refreshKey: Int = 0,- onEditPhoto: () -> Unit+ onEditPhoto: () -> Unit,+ onSetWallpaper: (Photo) -> Unit = {} ) { val countryNames by photoMapViewModel.countryNames.collectAsState() val countryName = countryNames[photo.id]@@ -427,6 +434,9 @@ fun PhotoDetailView( verticalAlignment = Alignment.CenterVertically ) { if (photo.videoData == null) {+ IconButton(onClick = { onSetWallpaper(photo) }) {+ IconWallpaper(tint = Color.White)+ } IconButton(onClick = onEditPhoto) { IconEdit(tint = Color.White) } } IconButton(
photos/src/main/java/com/vayunmathur/photos/ui/WallpaperPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/WallpaperPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/WallpaperPage.ktnew file mode 100644index 0000000000..401970db6e--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/ui/WallpaperPage.kt@@ -0,0 +1,489 @@+package com.vayunmathur.photos.ui++import android.app.Application+import android.app.WallpaperManager+import android.graphics.Rect+import android.view.WindowManager+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.Image+import androidx.compose.foundation.border+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.calculatePan+import androidx.compose.foundation.gestures.calculateZoom+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.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.SideEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.saveable.Saver+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size as ComposeSize+import androidx.compose.ui.graphics.Color+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.LocalConfiguration+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.FilledTonalButton+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.SegmentedButton+import com.vayunmathur.library.ui.SingleChoiceSegmentedButtonRow+import com.vayunmathur.library.ui.SnackbarHost+import com.vayunmathur.library.ui.SnackbarHostState+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Switch+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.photos.R+import com.vayunmathur.photos.Route+import com.vayunmathur.photos.util.WallpaperLoadState+import com.vayunmathur.photos.util.WallpaperUtil+import com.vayunmathur.photos.util.WallpaperViewModel+import com.vayunmathur.photos.util.WallpaperViewModelFactory+import kotlinx.coroutines.launch++private data class PreviewSnapshot(+ val containerW: Float,+ val containerH: Float,+ val baseW: Float,+ val baseH: Float,+ val viewportW: Float,+ val viewportH: Float,+)++private val OffsetSaver = Saver<Offset, List<Float>>(+ save = { listOf(it.x, it.y) },+ restore = { Offset(it[0], it[1]) },+)++@Composable+fun WallpaperPage(+ backStack: NavBackStack<Route>,+ id: Long,+ uri: String?,+) {+ val context = LocalContext.current+ val app = context.applicationContext as Application+ val viewModel: WallpaperViewModel = viewModel(factory = WallpaperViewModelFactory(app))++ val bitmap by viewModel.bitmap.collectAsState()+ val loadState by viewModel.loadState.collectAsState()++ // Accurate window size on minSdk 31+ via WindowMetrics — recomputes on config change.+ val localConfig = LocalConfiguration.current+ val windowManager = remember(context) { context.getSystemService(WindowManager::class.java) }+ val (screenW, screenH) = remember(localConfig, windowManager) {+ val bounds = windowManager.currentWindowMetrics.bounds+ bounds.width() to bounds.height()+ }++ val wm = remember(context) { WallpaperManager.getInstance(context) }+ // Unified scrollable width: max(desiredMinimumWidth, screenW*2) — single source of truth.+ val (scrollableW, scrollableH) = remember(wm, screenW, screenH) {+ val baseW = wm.desiredMinimumWidth+ val baseH = wm.desiredMinimumHeight+ val sW = maxOf(baseW.takeIf { it > 0 } ?: 0, screenW * 2).coerceAtLeast(screenW)+ val sH = (baseH.takeIf { it > 0 } ?: screenH).coerceAtLeast(screenH)+ sW to sH+ }++ var isScrollable by rememberSaveable { mutableStateOf(false) }+ var which by rememberSaveable { mutableStateOf(WallpaperManager.FLAG_SYSTEM) }+ var isSetting by rememberSaveable { mutableStateOf(false) }+ var zoomScale by rememberSaveable { mutableFloatStateOf(1f) }+ var zoomOffset by rememberSaveable(stateSaver = OffsetSaver) { mutableStateOf(Offset.Zero) }++ // Keep latest offset/scale fresh for gesture lambda without capturing stale values.+ val zoomScaleUpdated by rememberUpdatedState(zoomScale)+ val zoomOffsetUpdated by rememberUpdatedState(zoomOffset)++ val targetW = if (isScrollable) scrollableW else screenW+ val targetH = if (isScrollable) scrollableH else screenH++ val snackbarHostState = remember { SnackbarHostState() }+ val scope = rememberCoroutineScope()+ val density = LocalDensity.current++ // Composition-measured snapshot — updated via SideEffect so Set button always reads current layout+ // without LaunchedEffect lag (fixes rotation stale bug). SideEffect runs after commit.+ var latestPreview by remember { mutableStateOf<PreviewSnapshot?>(null) }+ val latestPreviewRef by rememberUpdatedState(latestPreview)++ LaunchedEffect(uri) {+ val uriToLoad = uri ?: return@LaunchedEffect+ viewModel.load(uriToLoad)+ }++ Scaffold(+ containerColor = Color.Black,+ topBar = {+ TopAppBar(+ title = { Text(stringResource(R.string.set_as_wallpaper), color = Color.White) },+ navigationIcon = { IconNavigation(backStack) },+ )+ },+ snackbarHost = { SnackbarHost(snackbarHostState) },+ ) { padding ->+ Column(+ modifier = Modifier+ .fillMaxSize()+ .padding(padding),+ ) {+ // ----- preview: Lavender-style dim outside viewport ----------------+ BoxWithConstraints(+ modifier = Modifier+ .weight(1f)+ .fillMaxWidth(),+ contentAlignment = Alignment.Center,+ ) {+ val containerW = constraints.maxWidth.toFloat()+ val containerH = constraints.maxHeight.toFloat()++ when {+ loadState == WallpaperLoadState.Loading ||+ (bitmap == null && loadState == WallpaperLoadState.Idle) -> {+ CircularProgressIndicator(+ modifier = Modifier.size(48.dp),+ color = Color.White,+ )+ }+ loadState == WallpaperLoadState.Failed || bitmap == null -> {+ Text(+ stringResource(R.string.wallpaper_load_failed),+ color = Color.White,+ )+ }+ else -> {+ val bmp = bitmap!!++ val fitScale = minOf(+ containerW / bmp.width.toFloat(),+ containerH / bmp.height.toFloat(),+ ).coerceAtLeast(0.01f)+ val baseDisplayW = bmp.width * fitScale+ val baseDisplayH = bmp.height * fitScale++ val targetAspect = if (targetW > 0 && targetH > 0) {+ targetW.toFloat() / targetH.toFloat()+ } else 9f / 16f++ val (viewportW, viewportH) = run {+ val maxW = containerW * 0.90f+ val maxH = containerH * 0.90f+ var vw = maxH * targetAspect+ var vh = maxH+ if (vw > maxW) {+ vw = maxW+ vh = maxW / targetAspect+ }+ vw to vh+ }++ val coverMin = WallpaperUtil.coverMinScale(+ baseDisplayW = baseDisplayW,+ baseDisplayH = baseDisplayH,+ viewportW = viewportW,+ viewportH = viewportH,+ )++ // Push snapshot synchronously after composition committed (SideEffect) so rotation is not stale.+ SideEffect {+ latestPreview = PreviewSnapshot(+ containerW = containerW,+ containerH = containerH,+ baseW = baseDisplayW,+ baseH = baseDisplayH,+ viewportW = viewportW,+ viewportH = viewportH,+ )+ }++ LaunchedEffect(coverMin) {+ if (zoomScale < coverMin) {+ zoomScale = coverMin+ zoomOffset = Offset.Zero+ }+ }++ fun clampOffset(off: Offset, scale: Float): Offset {+ val effW = baseDisplayW * scale+ val effH = baseDisplayH * scale+ val maxX = kotlin.math.max(0f, (effW - viewportW) / 2f)+ val maxY = kotlin.math.max(0f, (effH - viewportH) / 2f)+ return Offset(+ x = off.x.coerceIn(-maxX, maxX),+ y = off.y.coerceIn(-maxY, maxY),+ )+ }++ Box(+ modifier = Modifier+ .fillMaxSize()+ .pointerInput(baseDisplayW, baseDisplayH, viewportW, viewportH, coverMin) {+ awaitEachGesture {+ awaitFirstDown(requireUnconsumed = false)+ do {+ val event = awaitPointerEvent()+ val zoomChange = event.calculateZoom()+ val panChange = event.calculatePan()++ if (zoomChange != 1f || panChange != Offset.Zero) {+ val newScale = (zoomScaleUpdated * zoomChange)+ .coerceIn(coverMin, 5f)+ val newOffset = clampOffset(+ zoomOffsetUpdated + panChange,+ newScale,+ )+ zoomScale = newScale+ zoomOffset = newOffset+ event.changes.forEach { it.consume() }+ }+ } while (event.changes.any { it.pressed })+ }+ },+ contentAlignment = Alignment.Center,+ ) {+ val imageBitmap = remember(bmp) { bmp.asImageBitmap() }+ Image(+ bitmap = imageBitmap,+ contentDescription = null,+ modifier = Modifier+ .size(+ with(density) { baseDisplayW.toDp() },+ with(density) { baseDisplayH.toDp() },+ )+ .graphicsLayer {+ scaleX = zoomScale+ scaleY = zoomScale+ translationX = zoomOffset.x+ translationY = zoomOffset.y+ },+ contentScale = ContentScale.FillBounds,+ )++ // Lavender-style: dim scrim outside viewport (4-rect hole)+ Canvas(modifier = Modifier.fillMaxSize()) {+ val cw = size.width+ val ch = size.height+ val vpLeft = (cw - viewportW) / 2f+ val vpTop = (ch - viewportH) / 2f+ val dim = Color.Black.copy(alpha = 0.60f)++ // Top+ drawRect(dim, topLeft = Offset(0f, 0f), size = ComposeSize(cw, vpTop))+ // Bottom+ drawRect(+ dim,+ topLeft = Offset(0f, vpTop + viewportH),+ size = ComposeSize(cw, ch - (vpTop + viewportH)),+ )+ // Left+ drawRect(dim, topLeft = Offset(0f, vpTop), size = ComposeSize(vpLeft, viewportH))+ // Right+ drawRect(+ dim,+ topLeft = Offset(vpLeft + viewportW, vpTop),+ size = ComposeSize(cw - (vpLeft + viewportW), viewportH),+ )+ }++ // Phone-shaped viewport border — rounded 28dp, white 60% (Lavender polish)+ Box(+ modifier = Modifier+ .size(+ with(density) { viewportW.toDp() },+ with(density) { viewportH.toDp() },+ )+ .border(+ width = 1.5.dp,+ color = Color.White.copy(alpha = 0.75f),+ shape = RoundedCornerShape(28.dp),+ ),+ )+ }+ }+ }+ }++ // ----- bottom controls -----------------------------------------+ Surface(+ color = Color(0xFF121212),+ modifier = Modifier.fillMaxWidth(),+ ) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ // minSdk 31 — always show Home/Lock/Both+ SingleChoiceSegmentedButtonRow(+ modifier = Modifier.fillMaxWidth(),+ ) {+ SegmentedButton(+ selected = which == WallpaperManager.FLAG_SYSTEM,+ onClick = { which = WallpaperManager.FLAG_SYSTEM },+ shape = RoundedCornerShape(topStart = 12.dp, bottomStart = 12.dp),+ label = { Text(stringResource(R.string.wallpaper_home)) },+ )+ SegmentedButton(+ selected = which == WallpaperManager.FLAG_LOCK,+ onClick = { which = WallpaperManager.FLAG_LOCK },+ shape = RoundedCornerShape(0.dp),+ label = { Text(stringResource(R.string.wallpaper_lock)) },+ )+ SegmentedButton(+ selected = which ==+ (WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK),+ onClick = {+ which = WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK+ },+ shape = RoundedCornerShape(topEnd = 12.dp, bottomEnd = 12.dp),+ label = { Text(stringResource(R.string.wallpaper_both)) },+ )+ }++ Row(+ modifier = Modifier.fillMaxWidth(),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.SpaceBetween,+ ) {+ Column(modifier = Modifier.weight(1f)) {+ Text(+ stringResource(R.string.wallpaper_scrollable),+ color = Color.White,+ style = MaterialTheme.typography.titleSmall,+ )+ if (isScrollable) {+ Spacer(Modifier.height(2.dp))+ Text(+ stringResource(R.string.wallpaper_scrollable_desc),+ color = Color.White.copy(alpha = 0.65f),+ style = MaterialTheme.typography.bodySmall,+ )+ }+ }+ Spacer(Modifier.width(12.dp))+ Switch(+ checked = isScrollable,+ onCheckedChange = { checked ->+ isScrollable = checked+ zoomOffset = Offset.Zero+ },+ )+ }++ val currentBmp = bitmap+ FilledTonalButton(+ onClick = {+ val bmpForSet = currentBmp ?: return@FilledTonalButton+ if (isSetting) return@FilledTonalButton+ val snapshot = latestPreviewRef ?: return@FilledTonalButton+ if (snapshot.viewportW <= 0f) return@FilledTonalButton+ isSetting = true++ val zoomAtClick = zoomScale+ val offsetAtClick = zoomOffset++ scope.launch {+ try {+ val cropRect: Rect = WallpaperUtil.computeCropRect(+ srcW = bmpForSet.width,+ srcH = bmpForSet.height,+ baseDisplayW = snapshot.baseW,+ baseDisplayH = snapshot.baseH,+ zoom = zoomAtClick,+ offsetX = offsetAtClick.x,+ offsetY = offsetAtClick.y,+ viewportW = snapshot.viewportW,+ viewportH = snapshot.viewportH,+ containerW = snapshot.containerW,+ containerH = snapshot.containerH,+ )++ val result = WallpaperUtil.setWallpaper(+ context = context,+ source = bmpForSet,+ viewport = cropRect,+ targetWidth = targetW,+ targetHeight = targetH,+ which = which,+ isScrollable = isScrollable,+ screenW = screenW,+ screenH = screenH,+ )++ when (result) {+ is WallpaperUtil.SetResult.Success -> {+ snackbarHostState.showSnackbar(+ context.getString(R.string.wallpaper_set_success),+ )+ backStack.pop()+ }+ is WallpaperUtil.SetResult.Failure -> {+ val msg = context.getString(+ R.string.wallpaper_set_failed,+ result.exception.message ?: "Unknown",+ )+ snackbarHostState.showSnackbar(msg)+ }+ }+ } finally {+ isSetting = false+ }+ }+ },+ modifier = Modifier.fillMaxWidth(),+ enabled = currentBmp != null &&+ !isSetting &&+ loadState == WallpaperLoadState.Loaded &&+ latestPreview != null,+ ) {+ if (isSetting) {+ CircularProgressIndicator(+ modifier = Modifier.size(20.dp),+ strokeWidth = 2.dp,+ )+ Spacer(Modifier.width(8.dp))+ Text(stringResource(R.string.setting_wallpaper))+ } else {+ Text(stringResource(R.string.set_wallpaper))+ }+ }+ }+ }+ }+ }+}
photos/src/main/java/com/vayunmathur/photos/util/WallpaperHelper.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/WallpaperHelper.kt b/photos/src/main/java/com/vayunmathur/photos/util/WallpaperHelper.ktnew file mode 100644index 0000000000..e3f751de94--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/util/WallpaperHelper.kt@@ -0,0 +1,254 @@+package com.vayunmathur.photos.util++import android.app.Application+import android.app.WallpaperManager+import android.content.Context+import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.ImageDecoder+import android.graphics.Rect+import android.util.Log+import androidx.core.net.toUri+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.viewModelScope+import androidx.lifecycle.viewmodel.initializer+import androidx.lifecycle.viewmodel.viewModelFactory+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlin.math.max+import kotlin.math.min+import kotlin.math.roundToInt++// --- ViewModel ------------------------------------------------------------------++enum class WallpaperLoadState { Idle, Loading, Loaded, Failed }++class WallpaperViewModel(application: Application) : AndroidViewModel(application) {++ private val _bitmap = MutableStateFlow<Bitmap?>(null)+ val bitmap: StateFlow<Bitmap?> = _bitmap.asStateFlow()++ private val _loadState = MutableStateFlow(WallpaperLoadState.Idle)+ val loadState: StateFlow<WallpaperLoadState> = _loadState.asStateFlow()++ fun load(uriString: String) {+ if (_loadState.value == WallpaperLoadState.Loading) return+ _loadState.value = WallpaperLoadState.Loading+ val ctx: Context = getApplication()+ viewModelScope.launch(Dispatchers.IO) {+ val prev = _bitmap.value+ try {+ val uri = uriString.toUri()+ val source = ImageDecoder.createSource(ctx.contentResolver, uri)+ val bmp = ImageDecoder.decodeBitmap(source) { decoder, info, _ ->+ val w = info.size.width+ val h = info.size.height+ // Cap at 4096 on the longest edge to avoid OOM while keeping quality+ val maxEdge = 4096+ if (w > maxEdge || h > maxEdge) {+ val scale = maxEdge.toFloat() / max(w, h)+ decoder.setTargetSize((w * scale).roundToInt(), (h * scale).roundToInt())+ }+ decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE+ }+ val argb = if (bmp.config == Bitmap.Config.ARGB_8888) bmp+ else bmp.copy(Bitmap.Config.ARGB_8888, true).also {+ if (bmp !== it) runCatching { bmp.recycle() }+ }+ prev?.recycle()+ _bitmap.value = argb+ _loadState.value = WallpaperLoadState.Loaded+ } catch (e: Exception) {+ Log.e(TAG, "wallpaper decode failed for $uriString", e)+ prev?.let { _bitmap.value = it }+ _loadState.value = WallpaperLoadState.Failed+ }+ }+ }++ override fun onCleared() {+ super.onCleared()+ _bitmap.value?.recycle()+ _bitmap.value = null+ }++ companion object {+ private const val TAG = "WallpaperViewModel"+ }+}++@Suppress("FunctionName")+fun WallpaperViewModelFactory(application: Application): ViewModelProvider.Factory =+ viewModelFactory {+ initializer { WallpaperViewModel(application) }+ }++// --- Wallpaper application utility ----------------------------------------------++object WallpaperUtil {++ const val TAG = "WallpaperUtil"++ /**+ * Result of the set-wallpaper operation.+ */+ sealed class SetResult {+ data object Success : SetResult()+ data class Failure(val exception: Exception) : SetResult()+ }++ /**+ * Set [source] as wallpaper.+ *+ * @param context Application or activity context.+ * @param source Full-resolution source bitmap (not recycled by this call).+ * @param viewport Pre-computed crop in source-pixel coordinates.+ * @param targetWidth Final output width (screen or desiredMinimumWidth).+ * @param targetHeight Final output height (screen or desiredMinimumHeight).+ * @param which WallpaperManager.FLAG_SYSTEM / FLAG_LOCK / combined.+ * @param isScrollable Whether to request a wider launcher hint.+ * @param screenW Physical screen width in px (for suggestDesiredDimensions static path).+ * @param screenH Physical screen height in px.+ */+ suspend fun setWallpaper(+ context: Context,+ source: Bitmap,+ viewport: Rect,+ targetWidth: Int,+ targetHeight: Int,+ which: Int,+ isScrollable: Boolean,+ screenW: Int,+ screenH: Int,+ ): SetResult = withContext(Dispatchers.IO) {+ try {+ val wm = WallpaperManager.getInstance(context)++ // Unified scrollable width: must match the target we scale to. On minSdk 31 the launcher+ // hint controls parallax: scrollableW = max(desiredMinimumWidth, 2*screenW) wider = parallax,+ // static = screenW. Using targetWidth directly avoids the earlier 1.5x/2x mismatch.+ if (isScrollable) {+ wm.suggestDesiredDimensions(targetWidth, targetHeight.coerceAtLeast(screenH))+ } else {+ wm.suggestDesiredDimensions(screenW, screenH)+ }++ // Crop → scale+ val cropped = runCatching {+ // Guard against empty / OOB rects+ val safeRect = Rect(+ viewport.left.coerceIn(0, source.width - 1),+ viewport.top.coerceIn(0, source.height - 1),+ viewport.right.coerceIn(1, source.width),+ viewport.bottom.coerceIn(1, source.height),+ )+ // Ensure non-empty+ if (safeRect.width() <= 0 || safeRect.height() <= 0) {+ Rect(0, 0, source.width, source.height)+ } else safeRect+ }.getOrElse { Rect(0, 0, source.width, source.height) }++ val cropBmp = Bitmap.createBitmap(source, cropped.left, cropped.top, cropped.width(), cropped.height())+ val finalBmp = Bitmap.createScaledBitmap(cropBmp, targetWidth, targetHeight, true)+ if (cropBmp !== finalBmp) cropBmp.recycle()++ // PNG alpha → black background (wallpaper does not support alpha)+ val opaqueBmp = if (finalBmp.hasAlpha()) {+ val opaque = Bitmap.createBitmap(finalBmp.width, finalBmp.height, Bitmap.Config.ARGB_8888)+ Canvas(opaque).apply {+ drawColor(0xFF000000.toInt())+ drawBitmap(finalBmp, 0f, 0f, null)+ }+ finalBmp.recycle()+ opaque+ } else finalBmp++ try {+ // minSdk 31 — FLAG_LOCK available, no legacy branch needed.+ wm.setBitmap(opaqueBmp, null, true, which)+ SetResult.Success+ } finally {+ opaqueBmp.recycle()+ }+ } catch (e: Exception) {+ Log.e(TAG, "setWallpaper failed", e)+ SetResult.Failure(e)+ } catch (oom: OutOfMemoryError) {+ Log.e(TAG, "setWallpaper OOM", oom)+ SetResult.Failure(RuntimeException("Out of memory: image too large", oom))+ }+ }++ /**+ * Compute source-pixel crop rect from the current viewport state.+ *+ * @param srcW Source bitmap width.+ * @param srcH Source bitmap height.+ * @param baseDisplayW Display width of source when fitted (no zoom).+ * @param baseDisplayH Display height of source when fitted (no zoom).+ * @param zoom Current zoom multiplier (>= cover-min-scale).+ * @param offsetX/Y Current pan offset in px (graphicsLayer translation).+ * @param viewportW/H The visible crop window size in px (device pixels).+ * @param containerW/H The parent container size for centering math.+ */+ fun computeCropRect(+ srcW: Int,+ srcH: Int,+ baseDisplayW: Float,+ baseDisplayH: Float,+ zoom: Float,+ offsetX: Float,+ offsetY: Float,+ viewportW: Float,+ viewportH: Float,+ containerW: Float,+ containerH: Float,+ ): Rect {+ if (srcW <= 0 || srcH <= 0 || baseDisplayW <= 0f || baseDisplayH <= 0f) {+ return Rect(0, 0, srcW.coerceAtLeast(1), srcH.coerceAtLeast(1))+ }+ val effW = baseDisplayW * zoom+ val effH = baseDisplayH * zoom++ // Where the effective displayed image is positioned inside the container+ // (centered + pan offset)+ val imgLeft = (containerW - effW) / 2f + offsetX+ val imgTop = (containerH - effH) / 2f + offsetY++ // Where the viewport rect is positioned inside the container (centered)+ val vpLeft = (containerW - viewportW) / 2f+ val vpTop = (containerH - viewportH) / 2f++ // Top-left of the viewport relative to the effective image's top-left+ val relLeft = vpLeft - imgLeft+ val relTop = vpTop - imgTop++ val scaleX = srcW / effW+ val scaleY = srcH / effH++ val cropLeft = (relLeft * scaleX).roundToInt().coerceIn(0, srcW - 1)+ val cropTop = (relTop * scaleY).roundToInt().coerceIn(0, srcH - 1)+ val cropW = (viewportW * scaleX).roundToInt().coerceIn(1, srcW - cropLeft)+ val cropH = (viewportH * scaleY).roundToInt().coerceIn(1, srcH - cropTop)++ return Rect(cropLeft, cropTop, cropLeft + cropW, cropTop + cropH)+ }++ /**+ * Minimum zoom that ensures the image covers the viewport (no letterbox gap).+ */+ fun coverMinScale(+ baseDisplayW: Float,+ baseDisplayH: Float,+ viewportW: Float,+ viewportH: Float,+ ): Float {+ if (baseDisplayW <= 0f || baseDisplayH <= 0f) return 1f+ return max(viewportW / baseDisplayW, viewportH / baseDisplayH).coerceAtLeast(1f)+ }+}
photos/src/main/res/values/strings.xml
diff --git a/photos/src/main/res/values/strings.xml b/photos/src/main/res/values/strings.xmlindex 356ae83e9f..7ba0799610 100644--- a/photos/src/main/res/values/strings.xml+++ b/photos/src/main/res/values/strings.xml@@ -397,6 +397,32 @@ <!-- Tool: eyedropper pick color from image. Noun --> <string name="tool_eyedropper">Eyedropper</string> + <!-- Wallpaper setting screen -->+ <!-- Title for wallpaper crop/preview screen. Verb phrase -->+ <string name="set_as_wallpaper">Set as wallpaper</string>+ <!-- Segment: home screen wallpaper target. Noun -->+ <string name="wallpaper_home">Home</string>+ <!-- Segment: lock screen wallpaper target. Noun phrase -->+ <string name="wallpaper_lock">Lock</string>+ <!-- Segment: both home and lock screens. Noun phrase -->+ <string name="wallpaper_both">Both</string>+ <!-- Toggle label: static (no parallax) wallpaper mode. Adjective -->+ <string name="wallpaper_static">Static</string>+ <!-- Toggle label: scrollable (parallax) wallpaper mode. Adjective -->+ <string name="wallpaper_scrollable">Scrollable</string>+ <!-- Description for scrollable wallpaper: wider image that moves with home screens. Sentence -->+ <string name="wallpaper_scrollable_desc">Scrollable wallpapers are wider and move when you swipe between home screens</string>+ <!-- Button: confirm and apply wallpaper. Verb phrase -->+ <string name="set_wallpaper">Set wallpaper</string>+ <!-- Loading text while wallpaper is being applied. Verb phrase with gerund -->+ <string name="setting_wallpaper">Setting wallpaper…</string>+ <!-- Success snackbar after wallpaper applied. Exclamation -->+ <string name="wallpaper_set_success">Wallpaper applied!</string>+ <!-- Failure snackbar when wallpaper setting failed. Sentence with error detail placeholder %1$s -->+ <string name="wallpaper_set_failed">Failed to set wallpaper: <xliff:g id="error" example="IO error">%1$s</xliff:g></string>+ <!-- Error when full-res image cannot be decoded for wallpaper. Sentence -->+ <string name="wallpaper_load_failed">Failed to load image</string>+ <!-- Empty description when no mode active --> <string name="editor_desc_none"></string> <!-- Desc: fine-tune light and color with sliders -->