Modern Apps git

← Modern-Apps.git

photos: show image locations & PhotoPage gestures

Commit
9951826054b213aa549a358cbfa2f187c9d8dcc2
Author
Vayun <[email protected]>
When
2026-01-19 21:13 UTC (10 months ago)
Parents
7888f90

Diff

gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex cd3909e8de..0f713deb11 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -2,6 +2,7 @@ # Tooling & Plugins agp = "9.0.0-beta05" coilCompose = "2.7.0"+exifinterface = "1.4.2" kotlin = "2.3.0"  # Core AndroidX & Lifecycle@@ -42,6 +43,7 @@ pdfViewer = "1.0.0-alpha12"  [libraries] # Core AndroidX+androidx-exifinterface = { module = "androidx.exifinterface:exifinterface", version.ref = "exifinterface" } coil-compose = { module = "io.coil-kt:coil-compose", version.ref = "coilCompose" } compose-markdown = { group = "com.github.jeziellago", name = "compose-markdown", version.ref = "composeMarkdown" } 
photos/build.gradle.kts
diff --git a/photos/build.gradle.kts b/photos/build.gradle.ktsindex a403b3ce2d..0b27181c4f 100644--- a/photos/build.gradle.kts+++ b/photos/build.gradle.kts@@ -14,6 +14,7 @@ dependencies {     implementation(libs.androidx.navigation3.runtime)      implementation(libs.coil.compose)+    implementation(libs.androidx.exifinterface)      implementation(libs.androidx.room.runtime)     implementation(libs.androidx.room.ktx)
photos/src/main/AndroidManifest.xml
diff --git a/photos/src/main/AndroidManifest.xml b/photos/src/main/AndroidManifest.xmlindex 00cd50c060..72174f9917 100644--- a/photos/src/main/AndroidManifest.xml+++ b/photos/src/main/AndroidManifest.xml@@ -3,6 +3,8 @@      <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />     <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />+    <uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />+    <uses-permission android:name="android.permission.INTERNET" />      <application         android:icon="@mipmap/ic_launcher"
photos/src/main/java/com/vayunmathur/photos/data/Photo.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt b/photos/src/main/java/com/vayunmathur/photos/data/Photo.ktindex b7b726febc..b0c7b14a03 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt@@ -14,7 +14,9 @@ data class Photo(     val date: Long,     val width: Int,     val height: Int,-    val country: String? = null,+    val exifSet: Boolean,+    val lat: Double?,+    val long: Double?,     override val position: Double = 0.0 ) : DatabaseItem<Photo>() {     override fun withPosition(position: Double): Photo = copy(position = position)
photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.ktindex 18d4b8e330..0adaa2d71d 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt@@ -2,21 +2,14 @@ package com.vayunmathur.photos.ui  import android.content.ContentUris import android.content.Context-import android.graphics.Bitmap-import android.media.ExifInterface import android.provider.MediaStore-import android.util.Size-import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.aspectRatio-import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid@@ -30,17 +23,15 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color-import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.core.net.toUri+import androidx.exifinterface.media.ExifInterface import androidx.navigation3.runtime.NavBackStack import coil.ImageLoader import coil.compose.AsyncImage@@ -50,13 +41,15 @@ import coil.request.ImageRequest import com.vayunmathur.library.util.DatabaseViewModel import com.vayunmathur.photos.Route import com.vayunmathur.photos.data.Photo+import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone import kotlinx.datetime.format.MonthNames-import kotlinx.datetime.number import kotlinx.datetime.toLocalDateTime import kotlin.time.Instant @@ -79,10 +72,13 @@ fun GalleryPage(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel) {         .respectCacheHeaders(false) // Important for local files/mediastore         .build() }     LaunchedEffect(Unit) {-        println(photos.size)-        delay(100)-        if(photos.isEmpty()) {-            addAllPhotos(context, viewModel)+        delay(1000)+        withContext(Dispatchers.IO) {+            if (photos.isEmpty()) {+                addAllPhotos(context, viewModel)+            }+            println(photos.count { !it.exifSet })+            setExifData(photos, viewModel, context)         }     }     val photosGroupedByMonth by remember {@@ -167,7 +163,6 @@ fun addAllPhotos(context: Context, viewModel: DatabaseViewModel) {         val widthColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.WIDTH)         val heightColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.HEIGHT) -         while (cursor.moveToNext()) {             val id = cursor.getLong(idColumn)             val contentUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)@@ -175,8 +170,35 @@ fun addAllPhotos(context: Context, viewModel: DatabaseViewModel) {             val date = cursor.getLong(dateColumn)             val width = cursor.getInt(widthColumn)             val height = cursor.getInt(heightColumn)-            photos += Photo(id, name, contentUri.toString(), date, width, height)++            photos += Photo(id, name, contentUri.toString(), date, width, height, false, null, null)+         }     }     viewModel.upsertAll(photos.sortedByDescending { it.date })+}++suspend fun CoroutineScope.setExifData(photos: List<Photo>, viewModel: DatabaseViewModel, context: Context) {+    val ps = photos.filter { !it.exifSet }.sortedByDescending { it.date }+    ps.chunked(50).forEachIndexed { it, photos ->+        val newPhotos = photos.map { photo ->+            async {+                val (lat, long) = context.contentResolver.openInputStream(+                    MediaStore.setRequireOriginal(+                        photo.uri.toUri()+                    )+                )?.use { inputStream ->+                    val exif = ExifInterface(inputStream)+                    val latLong = exif.latLong+                    val lat = latLong?.getOrNull(0)+                    val long = latLong?.getOrNull(1)+                    listOf(lat, long)+                } ?: listOf(null, null)+                photo.copy(exifSet = true, lat = lat, long = long)+            }+        }.awaitAll()+        viewModel.upsertAll(newPhotos)+        println("${it * 50} / ${ps.size}")+    }+ }\ No newline at end of file
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 b861a51d43..db5f9989e3 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt@@ -1,21 +1,38 @@ package com.vayunmathur.photos.ui +import android.content.Context+import android.location.Geocoder+import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.gestures.detectTransformGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.pager.HorizontalPager+import androidx.compose.foundation.pager.PagerState+import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+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.graphics.Color+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp@@ -26,36 +43,148 @@ import coil.request.ImageRequest import com.vayunmathur.library.util.DatabaseViewModel import com.vayunmathur.photos.Route import com.vayunmathur.photos.data.Photo+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.toLocalDateTime+import kotlin.math.absoluteValue import kotlin.time.Instant  @Composable fun PhotoPage(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel, id: Long) {-    val photo by viewModel.get<Photo>(id)+    val photos by viewModel.data<Photo>().collectAsState(initial = emptyList())     val context = LocalContext.current+    val photosSorted = remember(photos) { photos.sortedByDescending { it.date } } -    Scaffold(-        containerColor = Color.Black // Better for viewing photos-    ) { paddingValues ->-        Box(modifier = Modifier.fillMaxSize().padding(paddingValues)) {-            // 1. Full Screen Image-            AsyncImage(-                model = ImageRequest.Builder(context)-                    .data(photo.uri.toUri())-                    .crossfade(true)-                    .build(),-                contentDescription = photo.name,-                modifier = Modifier.fillMaxSize(),-                contentScale = ContentScale.Fit // Shows the whole photo without cropping-            )+    val initialIndex = remember(photosSorted, id) {+        val index = photosSorted.indexOfFirst { it.id == id }+        if (index == -1) 0 else index+    }++    // State to toggle metadata visibility globally (or per page)+    var isMetadataVisible by remember { mutableStateOf(true) }++    if (photosSorted.isNotEmpty()) {+        val pagerState = rememberPagerState(+            initialPage = initialIndex,+            pageCount = { photosSorted.size }+        )++        Scaffold(containerColor = Color.Black) { paddingValues ->+            HorizontalPager(+                state = pagerState,+                modifier = Modifier.fillMaxSize().padding(paddingValues),+                beyondViewportPageCount = 1,+                // Disable paging if the user is zoomed in (handled in the child)+                userScrollEnabled = true+            ) { pageIndex ->+                val photo = photosSorted[pageIndex]++                PhotoDetailView(+                    photo = photo,+                    context = context,+                    pagerState = pagerState,+                    pageIndex = pageIndex,+                    isMetadataVisible = isMetadataVisible,+                    onToggleMetadata = { isMetadataVisible = !isMetadataVisible }+                )+            }+        }+    }+}++@Composable+fun PhotoDetailView(+    photo: Photo,+    context: Context,+    pagerState: PagerState,+    pageIndex: Int,+    isMetadataVisible: Boolean,+    onToggleMetadata: () -> Unit+) {+    var countryName by remember(photo.id) { mutableStateOf<String?>(null) }++    // Zoom/Pan States+    var scale by remember { mutableStateOf(1f) }+    var offset by remember { mutableStateOf(Offset.Zero) }++    // Reset zoom when the page is swiped away+    LaunchedEffect(pagerState.currentPage) {+        if (pagerState.currentPage != pageIndex) {+            scale = 1f+            offset = Offset.Zero+        }+    }++    LaunchedEffect(photo.id) {+        if (photo.lat != null && photo.long != null) {+            withContext(Dispatchers.IO) {+                try {+                    val geocoder = Geocoder(context)+                    countryName = geocoder.getFromLocation(photo.lat, photo.long, 1)?.firstOrNull()?.countryName+                } catch (e: Exception) { countryName = "Unknown" }+            }+        }+    } -            // 2. Metadata Overlay (Bottom)+    Box(+        modifier = Modifier+            .fillMaxSize()+            .pointerInput(Unit) {+                // Handle Tap to Hide/Show+                detectTapGestures(+                    onTap = { onToggleMetadata() },+                    onDoubleTap = {+                        // Simple double tap to reset or zoom in+                        scale = if (scale > 1f) 1f else 2.5f+                        offset = Offset.Zero+                    }+                )+            }+            .pointerInput(Unit) {+                // Handle Pinch and Pan+                detectTransformGestures { _, pan, zoom, _ ->+                    scale = (scale * zoom).coerceIn(1f, 5f)+                    // Only allow panning if zoomed in+                    if (scale > 1f) {+                        offset += pan+                    } else {+                        offset = Offset.Zero+                    }+                }+            }+    ) {+        // 1. The Zoomable Image+        AsyncImage(+            model = ImageRequest.Builder(context).data(photo.uri.toUri()).build(),+            contentDescription = null,+            modifier = Modifier+                .fillMaxSize()+                .graphicsLayer {+                    scaleX = scale+                    scaleY = scale+                    translationX = offset.x+                    translationY = offset.y+                },+            contentScale = ContentScale.Fit+        )++        // 2. The Fading & Toggling Metadata Overlay+        AnimatedVisibility(+            visible = isMetadataVisible,+            enter = fadeIn(),+            exit = fadeOut(),+            modifier = Modifier.align(Alignment.BottomStart)+        ) {             Column(                 modifier = Modifier-                    .align(Alignment.BottomStart)                     .fillMaxWidth()+                    .graphicsLayer {+                        // Fade out based on swiping distance+                        val pageOffset = ((pagerState.currentPage - pageIndex) + pagerState.currentPageOffsetFraction).absoluteValue+                        alpha = 1f - pageOffset.coerceIn(0f, 1f)+                    }                     .background(Color.Black.copy(alpha = 0.6f))                     .padding(16.dp)             ) {@@ -64,13 +193,13 @@ fun PhotoPage(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel, id:                 val dateFormatted = remember(photo.date) {                     Instant.fromEpochMilliseconds(photo.date)                         .toLocalDateTime(TimeZone.currentSystemDefault())-                        .let { "${it.day} ${it.month} ${it.year}" }+                        .let { "${it.dayOfMonth} ${it.month.name.lowercase().capitalize()} ${it.year}" }                 }                  Text(text = "Taken on: $dateFormatted", color = Color.LightGray)--                // Location and Resolution (assuming they are properties of your Photo class)-                Text(text = "Location: ${photo.country ?: "Unknown"}", color = Color.LightGray)+                if (photo.exifSet) {+                    Text(text = "Location: ${countryName ?: "Detecting..."}", color = Color.LightGray)+                }                 Text(text = "Resolution: ${photo.width} x ${photo.height}", color = Color.LightGray)             }         }