diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperCurrentDao.kt b/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperCurrentDao.kt index 6d5b669..491c8b5 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperCurrentDao.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperCurrentDao.kt @@ -7,6 +7,7 @@ import androidx.room.Query import com.anthonyla.paperize.core.ScreenType import com.anthonyla.paperize.data.database.entities.WallpaperCurrentEntity import com.anthonyla.paperize.data.database.entities.WallpaperEntity +import kotlinx.coroutines.flow.Flow @Dao interface WallpaperCurrentDao { @@ -23,6 +24,15 @@ interface WallpaperCurrentDao { """) suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): WallpaperEntity? + /** Reactive variant of [getCurrentWallpaper]; re-emits when the recorded wallpaper changes. */ + @Query(""" + SELECT w.* FROM wallpapers w + INNER JOIN wallpaper_current wc ON w.id = wc.wallpaperId + WHERE wc.albumId = :albumId AND wc.screenType = :screenType + LIMIT 1 + """) + fun getCurrentWallpaperFlow(albumId: String, screenType: ScreenType): Flow + /** Record (or overwrite) the current wallpaper for an album/screen pair. */ @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertCurrentWallpaper(entity: WallpaperCurrentEntity) diff --git a/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt b/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt index 90cadc1..d953f70 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt @@ -252,6 +252,9 @@ class WallpaperRepositoryImpl @Inject constructor( override suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): Wallpaper? = wallpaperCurrentDao.getCurrentWallpaper(albumId, screenType)?.toDomainModel() + override fun getCurrentWallpaperFlow(albumId: String, screenType: ScreenType): Flow = + wallpaperCurrentDao.getCurrentWallpaperFlow(albumId, screenType).map { it?.toDomainModel() } + override suspend fun setCurrentWallpaper(albumId: String, screenType: ScreenType, wallpaperId: String) { wallpaperCurrentDao.upsertCurrentWallpaper( WallpaperCurrentEntity(albumId = albumId, screenType = screenType, wallpaperId = wallpaperId) diff --git a/app/src/main/java/com/anthonyla/paperize/domain/repository/WallpaperRepository.kt b/app/src/main/java/com/anthonyla/paperize/domain/repository/WallpaperRepository.kt index 29a97e6..f4d6ce4 100644 --- a/app/src/main/java/com/anthonyla/paperize/domain/repository/WallpaperRepository.kt +++ b/app/src/main/java/com/anthonyla/paperize/domain/repository/WallpaperRepository.kt @@ -103,6 +103,12 @@ interface WallpaperRepository { */ suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): Wallpaper? + /** + * Reactive variant of [getCurrentWallpaper] that re-emits whenever the recorded wallpaper + * for this album/screen changes. Used by the in-app current-wallpaper preview. + */ + fun getCurrentWallpaperFlow(albumId: String, screenType: ScreenType): Flow + /** * Record the wallpaper that was just applied for a given album/screen. * Called by WallpaperChangeService after a successful setBitmap(). diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeScreen.kt index 8b6fc7f..f6d8b36 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeScreen.kt @@ -52,6 +52,8 @@ fun HomeScreen( val appSettings by viewModel.appSettings.collectAsStateWithLifecycle() val wallpaperMode by viewModel.wallpaperMode.collectAsStateWithLifecycle() val showLiveWallpaperPrompt by viewModel.showLiveWallpaperPrompt.collectAsStateWithLifecycle() + val currentHomeWallpaperUri by viewModel.currentHomeWallpaperUri.collectAsStateWithLifecycle() + val currentLockWallpaperUri by viewModel.currentLockWallpaperUri.collectAsStateWithLifecycle() val coroutineScope = rememberCoroutineScope() val context = LocalContext.current @@ -122,7 +124,9 @@ fun HomeScreen( onSelectLockAlbum = { album -> viewModel.selectLockAlbum(album) }, onSelectLiveAlbum = { album -> viewModel.selectLiveAlbum(album) }, onUpdateScheduleSettings = { viewModel.updateScheduleSettings(it) }, - onUpdateScheduleSettingsDebounced = { viewModel.updateScheduleSettingsDebounced(it) } + onUpdateScheduleSettingsDebounced = { viewModel.updateScheduleSettingsDebounced(it) }, + homeWallpaperUri = currentHomeWallpaperUri, + lockWallpaperUri = currentLockWallpaperUri ) } } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeViewModel.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeViewModel.kt index ea281ff..fab35f3 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeViewModel.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeViewModel.kt @@ -17,11 +17,16 @@ import com.anthonyla.paperize.service.wallpaper.WallpaperChangeService import com.anthonyla.paperize.service.worker.WallpaperScheduler import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject @@ -76,6 +81,31 @@ class HomeViewModel @Inject constructor( initialValue = null ) + /** + * URI of the wallpaper Paperize last applied for the home / lock screen, for the in-app preview. + * Reading the source URI (rather than WallpaperManager.getDrawable) avoids the storage permission + * the preview would otherwise need. Falls back to the BOTH-mode record when home/lock are synced. + */ + @OptIn(ExperimentalCoroutinesApi::class) + val currentHomeWallpaperUri: StateFlow = scheduleSettings + .flatMapLatest { settings -> currentWallpaperUriFlow(settings.homeAlbumId, ScreenType.HOME) } + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS), null) + + @OptIn(ExperimentalCoroutinesApi::class) + val currentLockWallpaperUri: StateFlow = scheduleSettings + .flatMapLatest { settings -> currentWallpaperUriFlow(settings.lockAlbumId, ScreenType.LOCK) } + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS), null) + + private fun currentWallpaperUriFlow(albumId: String?, screenType: ScreenType): Flow = + if (albumId == null) { + flowOf(null) + } else { + combine( + wallpaperRepository.getCurrentWallpaperFlow(albumId, screenType), + wallpaperRepository.getCurrentWallpaperFlow(albumId, ScreenType.BOTH) + ) { specific, both -> (specific ?: both)?.uri } + } + // Show prompt to select live wallpaper when enabling changer in LIVE mode private val _showLiveWallpaperPrompt = MutableStateFlow(false) val showLiveWallpaperPrompt: StateFlow = _showLiveWallpaperPrompt diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/WallpaperScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/WallpaperScreen.kt index 203c991..82ed086 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/WallpaperScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/WallpaperScreen.kt @@ -70,6 +70,8 @@ fun WallpaperScreen( onSelectLiveAlbum: (AlbumSummary?) -> Unit, onUpdateScheduleSettings: (ScheduleSettings) -> Unit, onUpdateScheduleSettingsDebounced: (ScheduleSettings) -> Unit, + homeWallpaperUri: String?, + lockWallpaperUri: String?, modifier: Modifier = Modifier ) { var showAlbumSelectionSheet by rememberSaveable { mutableStateOf(false) } @@ -552,7 +554,11 @@ fun WallpaperScreen( // Current Wallpaper Preview (Static Mode Only) if (wallpaperMode == WallpaperMode.STATIC) { - CurrentWallpaperPreview(animate = appSettings.animate) + CurrentWallpaperPreview( + homeWallpaperUri = homeWallpaperUri, + lockWallpaperUri = lockWallpaperUri, + animate = appSettings.animate + ) HorizontalDivider(modifier = Modifier.padding(vertical = AppSpacing.small)) } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/CurrentWallpaperPreview.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/CurrentWallpaperPreview.kt index 4bb4296..ab17079 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/CurrentWallpaperPreview.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/CurrentWallpaperPreview.kt @@ -3,11 +3,6 @@ import com.anthonyla.paperize.presentation.theme.AppMaxWidths import com.anthonyla.paperize.presentation.theme.AppBorderWidths import com.anthonyla.paperize.core.constants.Constants -import android.app.WallpaperManager -import android.graphics.drawable.Drawable -import android.os.Build -import android.os.Handler -import android.os.Looper import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn @@ -22,21 +17,13 @@ import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.ui.graphics.Color import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable -import androidx.compose.runtime.DisposableEffect -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale @@ -45,7 +32,6 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp import com.anthonyla.paperize.R import com.anthonyla.paperize.presentation.theme.AppShapes import com.anthonyla.paperize.presentation.theme.AppSpacing @@ -53,176 +39,42 @@ import coil3.compose.AsyncImage import coil3.request.ImageRequest import coil3.request.crossfade import coil3.size.Size -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.delay -import kotlinx.coroutines.withContext +import kotlin.math.max import kotlin.math.min /** - * Retry helper for reading wallpapers with exponential backoff + * Displays the home and lock wallpapers Paperize last applied. * - * Android's WallpaperManager writes wallpapers to disk asynchronously after setBitmap() returns. - * The encoding process can take 1-2 seconds, during which time reading the wallpaper back will - * fail with ImageDecoder.DecodeException. This helper retries with increasing delays to allow - * the system time to complete encoding. + * The images are loaded from the recorded source URIs ([homeWallpaperUri]/[lockWallpaperUri]) via + * Coil, rather than read back from WallpaperManager.getDrawable(): the latter is privacy-restricted + * on modern Android and returns null without the optional all-files-access permission, which left + * the preview blank. The URIs already carry the album's persisted read access, so no extra + * permission is needed. They update reactively whenever Paperize changes the wallpaper. * - * @param maxAttempts Maximum number of retry attempts (default 4) - * @param delayMs Initial delay in milliseconds between retries (default 500ms) - * @param block The operation to retry - * @return The result of the operation, or null if all attempts fail - */ -private suspend fun retryWallpaperRead( - maxAttempts: Int = 4, - delayMs: Long = Constants.WALLPAPER_READ_INITIAL_DELAY_MS, - block: suspend () -> T -): T? { - var lastException: Exception? = null - - repeat(maxAttempts) { attempt -> - try { - return block() - } catch (e: android.graphics.ImageDecoder.DecodeException) { - lastException = e - // Only delay if we have more attempts left - if (attempt < maxAttempts - 1) { - // Exponential backoff: 500ms, 1000ms, 1500ms, 2000ms - delay(delayMs * (attempt + 1)) - } - } catch (e: Exception) { - // For non-decode exceptions, don't retry - return null - } - } - - // All attempts failed - return null -} - -/** - * Displays current home and lock screen wallpapers + * Note: this shows the source image, not the exact cropped/scaled/effected on-screen result. * - * Automatically updates when wallpapers change using WallpaperManager.OnColorsChangedListener. - * This allows the preview to stay in sync with system wallpaper changes from any source - * (this app's wallpaper changer, system settings, other apps, etc.). - * - * Uses smooth fade animations and placeholder boxes to prevent layout jumping. - * Adapts to different screen sizes and orientations following Material 3 responsive design. - * Respects the app's animate setting for accessibility and user preference. + * Adapts to the device screen aspect ratio and respects the app's animate setting. */ @Composable fun CurrentWallpaperPreview( + homeWallpaperUri: String?, + lockWallpaperUri: String?, animate: Boolean = true, modifier: Modifier = Modifier ) { - val context = LocalContext.current val configuration = LocalConfiguration.current - var homeWallpaper by remember { mutableStateOf(null) } - var lockWallpaper by remember { mutableStateOf(null) } - var hasPermission by remember { mutableStateOf(true) } - - // Use rememberSaveable to prevent reloading on navigation - var refreshTrigger by rememberSaveable { mutableIntStateOf(0) } - var pendingRefresh by remember { mutableStateOf(false) } - var isLoading by remember { mutableStateOf(true) } - - // Calculate appropriate aspect ratio based on device screen - // Use actual screen dimensions for accurate wallpaper preview + // Portrait-oriented preview: shorter screen dimension as width. val screenAspectRatio = remember(configuration) { val screenWidth = configuration.screenWidthDp.toFloat() val screenHeight = configuration.screenHeightDp.toFloat() - // Use the shorter dimension as width for portrait-oriented preview - val aspectRatio = min(screenWidth, screenHeight) / kotlin.math.max(screenWidth, screenHeight) - aspectRatio + min(screenWidth, screenHeight) / max(screenWidth, screenHeight) } - // Listen for wallpaper changes with debouncing - // When both home and lock wallpapers are set, the listener fires twice. - // Debouncing prevents multiple rapid refreshes that can cause UI flashing. - DisposableEffect(Unit) { - val wallpaperManager = WallpaperManager.getInstance(context) - val handler = Handler(Looper.getMainLooper()) - val listener = WallpaperManager.OnColorsChangedListener { _, _ -> - // Mark that a refresh is pending instead of triggering immediately - pendingRefresh = true - } - - // Register listener for both home and lock screen wallpaper changes - wallpaperManager.addOnColorsChangedListener(listener, handler) - - onDispose { - wallpaperManager.removeOnColorsChangedListener(listener) - } - } - - // Debounced refresh effect - // Waits 2 seconds after the last wallpaper change before refreshing - // This ensures both home and lock wallpaper changes complete before preview updates - LaunchedEffect(pendingRefresh) { - if (pendingRefresh) { - delay(Constants.WALLPAPER_CHANGE_DEBOUNCE_MS) - // Atomically update state to prevent race conditions - pendingRefresh = false - refreshTrigger++ - } - } - - // Fetch wallpapers on initial load and when refreshTrigger changes - LaunchedEffect(refreshTrigger) { - // Only set loading on initial load, not on refresh - if (refreshTrigger == 0) { - isLoading = true - } - - val (home, lock, hasAccess) = withContext(Dispatchers.IO) { - try { - val wallpaperManager = WallpaperManager.getInstance(context) - - // API 34+ has getDrawable(int which), earlier versions use getDrawable() - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { - // Get home screen wallpaper with retry logic - val homeDrawable = retryWallpaperRead { - wallpaperManager.getDrawable(WallpaperManager.FLAG_SYSTEM) - } - - // Get lock screen wallpaper with retry logic - val lockDrawable = retryWallpaperRead { - wallpaperManager.getDrawable(WallpaperManager.FLAG_LOCK) - } ?: homeDrawable - - Triple(homeDrawable, lockDrawable, true) - } else { - // For API [31-33], use getDrawable() which returns the current wallpaper - val drawable = retryWallpaperRead { - wallpaperManager.drawable - } - Triple(drawable, drawable, true) - } - } catch (e: SecurityException) { - Triple(null, null, false) - } catch (e: Exception) { - // Handle other exceptions silently - Triple(null, null, true) - } - } - // Update state on main thread - homeWallpaper = home - lockWallpaper = lock - hasPermission = hasAccess - isLoading = false - } - - // Don't show if no permission - if (!hasPermission) { - return - } - - // Always render the Card with reserved space to prevent layout jumping - // Constrain max width for tablets following Material 3 responsive design Card( modifier = modifier .fillMaxWidth() - .widthIn(max = AppMaxWidths.contentMaxWidth) // Material 3 guideline: max content width on large screens + .widthIn(max = AppMaxWidths.contentMaxWidth) .padding(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall), shape = AppShapes.cardShape, colors = CardDefaults.cardColors( @@ -249,8 +101,7 @@ fun CurrentWallpaperPreview( ) { // Lock wallpaper preview (on the left) WallpaperPreviewBox( - wallpaper = lockWallpaper, - isLoading = isLoading, + wallpaperUri = lockWallpaperUri, aspectRatio = screenAspectRatio, contentDescription = stringResource(R.string.content_desc_current_lock_wallpaper), animate = animate, @@ -259,8 +110,7 @@ fun CurrentWallpaperPreview( // Home wallpaper preview (on the right) WallpaperPreviewBox( - wallpaper = homeWallpaper, - isLoading = isLoading, + wallpaperUri = homeWallpaperUri, aspectRatio = screenAspectRatio, contentDescription = stringResource(R.string.content_desc_current_home_wallpaper), animate = animate, @@ -272,15 +122,12 @@ fun CurrentWallpaperPreview( } /** - * Displays a single wallpaper preview with smooth fade animation - * - * Uses device screen aspect ratio for accurate representation and placeholder - * background to prevent layout jumping during loading. + * A single wallpaper preview. Shows a placeholder background until [wallpaperUri] is non-null, + * then fades in the image. Uses the device screen aspect ratio to avoid layout jumps. */ @Composable private fun WallpaperPreviewBox( - wallpaper: Drawable?, - isLoading: Boolean, + wallpaperUri: String?, aspectRatio: Float, contentDescription: String, animate: Boolean, @@ -300,26 +147,16 @@ private fun WallpaperPreviewBox( .background(MaterialTheme.colorScheme.surfaceContainerHighest) ) { AnimatedVisibility( - visible = !isLoading && wallpaper != null, - enter = if (animate) { - fadeIn(animationSpec = tween(Constants.PERMISSION_SCREEN_TRANSITION_DELAY_MS.toInt())) - } else { - fadeIn(animationSpec = tween(0)) - }, - exit = if (animate) { - fadeOut(animationSpec = tween(Constants.PERMISSION_SCREEN_TRANSITION_DELAY_MS.toInt())) - } else { - fadeOut(animationSpec = tween(0)) - } + visible = wallpaperUri != null, + enter = fadeIn(animationSpec = tween(if (animate) Constants.PERMISSION_SCREEN_TRANSITION_DELAY_MS.toInt() else 0)), + exit = fadeOut(animationSpec = tween(if (animate) Constants.PERMISSION_SCREEN_TRANSITION_DELAY_MS.toInt() else 0)) ) { - wallpaper?.let { drawable -> + wallpaperUri?.let { uri -> AsyncImage( model = ImageRequest.Builder(context) - .data(drawable) - .size(Size(Constants.PREVIEW_THUMBNAIL_WIDTH, Constants.PREVIEW_THUMBNAIL_HEIGHT)) // Limit size for performance - suitable for preview + .data(uri) + .size(Size(Constants.PREVIEW_THUMBNAIL_WIDTH, Constants.PREVIEW_THUMBNAIL_HEIGHT)) .crossfade(true) - .memoryCachePolicy(coil3.request.CachePolicy.DISABLED) // Don't cache in memory (already in drawable) - .diskCachePolicy(coil3.request.CachePolicy.DISABLED) // Don't cache on disk (already system-managed) .build(), contentDescription = contentDescription, contentScale = ContentScale.Crop,