feat: system gallery integration
This commit is contained in:
1 parent
a912696e17
commit
234aabd926
10 files changed
+644
-134
No files matched your search
@@ -12,6 +12,7 @@
|
||||
android:maxSdkVersion="32" />
|
||||
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
|
||||
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
|
||||
|
||||
<uses-feature
|
||||
android:name="android.hardware.camera"
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.hinnka.mycamera.gallery
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.MediaStore
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
@@ -14,39 +15,39 @@ import kotlinx.coroutines.withContext
|
||||
* 负责从私有存储读取和管理 PhotonCamera 拍摄的照片
|
||||
*/
|
||||
class GalleryRepository(private val context: Context) {
|
||||
|
||||
|
||||
companion object {
|
||||
private const val TAG = "GalleryRepository"
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取所有照片(按时间倒序)
|
||||
*/
|
||||
fun getPhotos(): Flow<List<PhotoData>> = flow {
|
||||
emit(queryPhotos())
|
||||
}.flowOn(Dispatchers.IO)
|
||||
|
||||
|
||||
/**
|
||||
* 同步获取所有照片
|
||||
*/
|
||||
suspend fun getPhotosSync(): List<PhotoData> = withContext(Dispatchers.IO) {
|
||||
queryPhotos()
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取最新的一张照片
|
||||
*/
|
||||
suspend fun getLatestPhoto(): PhotoData? = withContext(Dispatchers.IO) {
|
||||
queryPhotos(limit = 1).firstOrNull()
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 删除单张照片
|
||||
*/
|
||||
suspend fun deletePhoto(photo: PhotoData): Boolean = withContext(Dispatchers.IO) {
|
||||
PhotoManager.deletePhoto(context, photo.id)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 批量删除照片
|
||||
*/
|
||||
@@ -59,14 +60,75 @@ class GalleryRepository(private val context: Context) {
|
||||
}
|
||||
deletedCount
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 查询系统相册照片
|
||||
*/
|
||||
suspend fun getSystemPhotos(offset: Int, limit: Int): List<PhotoData> = withContext(Dispatchers.IO) {
|
||||
val photos = mutableListOf<PhotoData>()
|
||||
val projection = arrayOf(
|
||||
MediaStore.Images.Media._ID,
|
||||
MediaStore.Images.Media.DISPLAY_NAME,
|
||||
MediaStore.Images.Media.DATE_ADDED,
|
||||
MediaStore.Images.Media.SIZE,
|
||||
MediaStore.Images.Media.WIDTH,
|
||||
MediaStore.Images.Media.HEIGHT
|
||||
)
|
||||
|
||||
val sortOrder = "${MediaStore.Images.Media.DATE_ADDED} DESC"
|
||||
|
||||
val queryArgs = android.os.Bundle().apply {
|
||||
putInt(android.content.ContentResolver.QUERY_ARG_OFFSET, offset)
|
||||
putInt(android.content.ContentResolver.QUERY_ARG_LIMIT, limit)
|
||||
putString(android.content.ContentResolver.QUERY_ARG_SQL_SORT_ORDER, sortOrder)
|
||||
}
|
||||
|
||||
val cursor = context.contentResolver.query(
|
||||
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
|
||||
projection,
|
||||
queryArgs,
|
||||
null
|
||||
)
|
||||
|
||||
cursor?.use {
|
||||
val idColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
|
||||
val nameColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)
|
||||
val dateColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED)
|
||||
val sizeColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE)
|
||||
val widthColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.WIDTH)
|
||||
val heightColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.HEIGHT)
|
||||
|
||||
while (it.moveToNext()) {
|
||||
val id = it.getLong(idColumn)
|
||||
val contentUri = android.content.ContentUris.withAppendedId(
|
||||
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
|
||||
id
|
||||
)
|
||||
|
||||
photos.add(
|
||||
PhotoData(
|
||||
id = id.toString(),
|
||||
uri = contentUri,
|
||||
thumbnailUri = contentUri, // Coil can load thumbnails from content URIs
|
||||
displayName = it.getString(nameColumn),
|
||||
dateAdded = it.getLong(dateColumn) * 1000, // MediaStore is in seconds
|
||||
size = it.getLong(sizeColumn),
|
||||
width = it.getInt(widthColumn),
|
||||
height = it.getInt(heightColumn)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
photos
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询私有存储中的照片
|
||||
*/
|
||||
private fun queryPhotos(limit: Int = Int.MAX_VALUE): List<PhotoData> {
|
||||
val photos = mutableListOf<PhotoData>()
|
||||
val photoIds = PhotoManager.getPhotoIds(context)
|
||||
|
||||
|
||||
photoIds.take(limit).forEach { id ->
|
||||
val photoFile = PhotoManager.getPhotoFile(context, id)
|
||||
|
||||
@@ -87,7 +149,7 @@ class GalleryRepository(private val context: Context) {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return photos
|
||||
}
|
||||
}
|
||||
@@ -383,7 +383,7 @@ object PhotoManager {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun exportDng(context: Context, data: ByteArray, metadata: PhotoMetadata) =
|
||||
suspend fun exportDng(context: Context, photoId: String, data: ByteArray, metadata: PhotoMetadata) =
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)
|
||||
@@ -409,15 +409,12 @@ object PhotoManager {
|
||||
}
|
||||
PLog.d(TAG, "DNG exported: $uri")
|
||||
|
||||
val photoId = getPhotoIds(context).firstOrNull()
|
||||
if (photoId != null) {
|
||||
val currentMetadata = loadMetadata(context, photoId) ?: metadata
|
||||
val updatedMetadata = currentMetadata.copy(
|
||||
exportedUris = currentMetadata.exportedUris + uri.toString()
|
||||
)
|
||||
saveMetadata(context, photoId, updatedMetadata)
|
||||
PLog.d(TAG, "Exported URI saved: $uri")
|
||||
}
|
||||
val currentMetadata = loadMetadata(context, photoId) ?: metadata
|
||||
val updatedMetadata = currentMetadata.copy(
|
||||
exportedUris = currentMetadata.exportedUris + uri.toString()
|
||||
)
|
||||
saveMetadata(context, photoId, updatedMetadata)
|
||||
PLog.d(TAG, "Exported URI saved: $uri")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to export DNG", e)
|
||||
@@ -609,7 +606,7 @@ object PhotoManager {
|
||||
it.write(array)
|
||||
}
|
||||
if (shouldAutoSave) {
|
||||
exportDng(context, array, metadata)
|
||||
exportDng(context, photoId, array, metadata)
|
||||
}
|
||||
|
||||
val bitmap = RawDemosaicProcessor.getInstance().process(
|
||||
@@ -1127,6 +1124,16 @@ object PhotoManager {
|
||||
?: emptyList()
|
||||
}
|
||||
|
||||
/**
|
||||
* 为直接传入的系统 URI 创建删除请求(用于 Android 11+)
|
||||
*/
|
||||
fun createSystemDeleteRequest(context: Context, uri: Uri): PendingIntent? {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
|
||||
return null
|
||||
}
|
||||
return MediaStore.createDeleteRequest(context.contentResolver, listOf(uri))
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建删除系统相册照片的请求(弹出确认对话框)
|
||||
*
|
||||
@@ -1251,7 +1258,11 @@ object PhotoManager {
|
||||
if (!photoFile.exists()) {
|
||||
return null
|
||||
}
|
||||
val source = ImageDecoder.createSource(photoFile)
|
||||
return loadBitmap(context, Uri.fromFile(photoFile), maxEdge)
|
||||
}
|
||||
|
||||
fun loadBitmap(context: Context, uri: Uri, maxEdge: Int? = null): Bitmap? {
|
||||
val source = ImageDecoder.createSource(context.contentResolver, uri)
|
||||
return runCatching {
|
||||
ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
|
||||
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
|
||||
@@ -1286,7 +1297,13 @@ object PhotoManager {
|
||||
/**
|
||||
* 从系统相册导入照片
|
||||
*/
|
||||
suspend fun importPhoto(context: Context, uri: Uri, lutId: String?, photoId: String? = null): String? {
|
||||
suspend fun importPhoto(
|
||||
context: Context,
|
||||
uri: Uri,
|
||||
lutId: String?,
|
||||
photoId: String? = null,
|
||||
sourceUri: String? = null
|
||||
): String? {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val photoId = photoId ?: UUID.randomUUID().toString()
|
||||
@@ -1299,7 +1316,9 @@ object PhotoManager {
|
||||
|
||||
// 2. 读取元数据以获取旋转信息
|
||||
val metadata = PhotoMetadata.fromUri(context, uri).copy(
|
||||
lutId = lutId
|
||||
lutId = lutId,
|
||||
sourceUri = sourceUri ?: metadataFile.takeIf { it.exists() }
|
||||
?.let { PhotoMetadata.fromJson(it.readText())?.sourceUri }
|
||||
)
|
||||
|
||||
// 1. 检测是否为 RAW 文件
|
||||
|
||||
@@ -19,7 +19,7 @@ import kotlin.math.log2
|
||||
* 保存 LUT、边框水印、编辑信息和拍摄参数,用于非破坏性编辑和边框水印渲染
|
||||
*/
|
||||
data class PhotoMetadata(
|
||||
val version: Int = 9, // 升级版本以支持细节处理参数
|
||||
val version: Int = 10, // Added sourceUri
|
||||
// 编辑配置
|
||||
val lutId: String? = null,
|
||||
// 色彩配方配置
|
||||
@@ -48,6 +48,7 @@ data class PhotoMetadata(
|
||||
val aperture: String? = null,
|
||||
val exposureBias: Float? = null,
|
||||
val isImported: Boolean = false,
|
||||
val sourceUri: String? = null, // 原始系统相册 URI (用于关联)
|
||||
// 边框水印自定义
|
||||
val customProperties: Map<String, String> = emptyMap(),
|
||||
// 导出到系统相册的 URI 列表
|
||||
@@ -95,13 +96,14 @@ data class PhotoMetadata(
|
||||
}
|
||||
}
|
||||
|
||||
val lv: Float get() {
|
||||
val aperture = aperture?.substringAfter("/")?.toFloatOrNull() ?: return 0f
|
||||
val shutterSpeed = parseExposureTime(shutterSpeed)?.let { it * 1f / 1_000_000_000L } ?: return 0f
|
||||
val iso = iso ?: return 0f
|
||||
val ev = log2((aperture * aperture) / shutterSpeed)
|
||||
return ev - log2(iso / 100f)
|
||||
}
|
||||
val lv: Float
|
||||
get() {
|
||||
val aperture = aperture?.substringAfter("/")?.toFloatOrNull() ?: return 0f
|
||||
val shutterSpeed = parseExposureTime(shutterSpeed)?.let { it * 1f / 1_000_000_000L } ?: return 0f
|
||||
val iso = iso ?: return 0f
|
||||
val ev = log2((aperture * aperture) / shutterSpeed)
|
||||
return ev - log2(iso / 100f)
|
||||
}
|
||||
|
||||
/**
|
||||
* 分辨率字符串 (用于边框水印显示)
|
||||
@@ -142,7 +144,8 @@ data class PhotoMetadata(
|
||||
put("width", width)
|
||||
put("height", height)
|
||||
put("ratio", ratio?.getDisplayName() ?: JSONObject.NULL)
|
||||
put("cropRegion", if (cropRegion != null) {
|
||||
put(
|
||||
"cropRegion", if (cropRegion != null) {
|
||||
JSONObject().apply {
|
||||
put("left", cropRegion.left)
|
||||
put("top", cropRegion.top)
|
||||
@@ -165,6 +168,7 @@ data class PhotoMetadata(
|
||||
put("aperture", aperture ?: JSONObject.NULL)
|
||||
put("exposureBias", exposureBias ?: JSONObject.NULL)
|
||||
put("isImported", isImported)
|
||||
put("sourceUri", sourceUri ?: JSONObject.NULL)
|
||||
// 边框水印自定义
|
||||
val customPropsObj = JSONObject()
|
||||
customProperties.forEach { (k, v) -> customPropsObj.put(k, v) }
|
||||
@@ -252,6 +256,7 @@ data class PhotoMetadata(
|
||||
aperture = if (obj.isNull("aperture")) null else obj.optString("aperture"),
|
||||
exposureBias = if (obj.isNull("exposureBias")) null else obj.optDouble("exposureBias").toFloat(),
|
||||
isImported = obj.optBoolean("isImported", false),
|
||||
sourceUri = if (obj.isNull("sourceUri")) null else obj.optString("sourceUri"),
|
||||
customProperties = mutableMapOf<String, String>().apply {
|
||||
val customPropsObj = obj.optJSONObject("customProperties")
|
||||
customPropsObj?.keys()?.forEach { key ->
|
||||
|
||||
@@ -260,7 +260,7 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
|
||||
val lutId = userPreferencesRepository.userPreferences.map { it.lutId }.firstOrNull()
|
||||
?: availableLutList.firstOrNull { it.isDefault }?.id
|
||||
val existingPhotoId = if (processingInfo?.uri == uri) processingInfo?.photoId else null
|
||||
val photoId = PhotoManager.importPhoto(context, uri, lutId, existingPhotoId) ?: run {
|
||||
val photoId = PhotoManager.importPhoto(context, uri, lutId, existingPhotoId, uri.toString()) ?: run {
|
||||
return@withContext
|
||||
}
|
||||
val metadata = PhotoManager.loadMetadata(context, photoId) ?: run {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.hinnka.mycamera.ui.gallery
|
||||
|
||||
import android.app.Activity
|
||||
import android.os.Build
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.IntentSenderRequest
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
@@ -31,8 +32,12 @@ import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.AddPhotoAlternate
|
||||
import androidx.compose.material.icons.filled.BurstMode
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
@@ -51,6 +56,7 @@ import com.hinnka.mycamera.R
|
||||
import com.hinnka.mycamera.gallery.PhotoData
|
||||
import com.hinnka.mycamera.ui.camera.autoRotate
|
||||
import com.hinnka.mycamera.ui.theme.AccentOrange
|
||||
import com.hinnka.mycamera.viewmodel.GalleryTab
|
||||
import com.hinnka.mycamera.viewmodel.GalleryViewModel
|
||||
|
||||
/**
|
||||
@@ -64,11 +70,14 @@ fun GalleryScreen(
|
||||
onPhotoClick: (Int) -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val photos by viewModel.photos.collectAsState()
|
||||
val photos by viewModel.currentPhotos.collectAsState()
|
||||
val isLoading by viewModel.isLoading.collectAsState()
|
||||
val isSystemLoadingMore by viewModel.isSystemLoadingMore.collectAsState()
|
||||
val isSharing by viewModel.isSharing.collectAsState()
|
||||
val isSelectionMode = viewModel.isSelectionMode
|
||||
val selectedPhotos = viewModel.selectedPhotos
|
||||
val selectedTab = viewModel.selectedTab
|
||||
val hasPermission = viewModel.hasGalleryPermission
|
||||
|
||||
val launcher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.GetMultipleContents()
|
||||
@@ -78,6 +87,14 @@ fun GalleryScreen(
|
||||
}
|
||||
}
|
||||
|
||||
val permissionLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission()
|
||||
) { granted ->
|
||||
if (granted) {
|
||||
viewModel.checkGalleryPermission()
|
||||
}
|
||||
}
|
||||
|
||||
// Activity Result Launcher for batch delete confirmation
|
||||
val batchDeleteLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartIntentSenderForResult()
|
||||
@@ -107,10 +124,24 @@ fun GalleryScreen(
|
||||
|
||||
var showDeleteDialog by remember { mutableStateOf(false) }
|
||||
|
||||
// 监听生命周期,onResume 时刷新列表
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
DisposableEffect(lifecycleOwner) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME) {
|
||||
viewModel.loadCurrentTabData()
|
||||
}
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
onDispose {
|
||||
lifecycleOwner.lifecycle.removeObserver(observer)
|
||||
}
|
||||
}
|
||||
|
||||
// 延迟加载照片列表,避免与跳转动画冲突导致卡顿
|
||||
LaunchedEffect(Unit) {
|
||||
kotlinx.coroutines.delay(500) // 等待跳转动画完成
|
||||
viewModel.loadPhotos()
|
||||
viewModel.loadCurrentTabData()
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
@@ -124,10 +155,41 @@ fun GalleryScreen(
|
||||
color = Color.White
|
||||
)
|
||||
} else {
|
||||
Text(
|
||||
text = stringResource(R.string.gallery),
|
||||
color = Color.White
|
||||
)
|
||||
TabRow(
|
||||
selectedTabIndex = selectedTab.ordinal,
|
||||
containerColor = Color.Transparent,
|
||||
contentColor = Color.White,
|
||||
indicator = { tabPositions ->
|
||||
TabRowDefaults.SecondaryIndicator(
|
||||
Modifier.tabIndicatorOffset(tabPositions[selectedTab.ordinal]),
|
||||
color = AccentOrange
|
||||
)
|
||||
},
|
||||
divider = {}
|
||||
) {
|
||||
Tab(
|
||||
selected = selectedTab == GalleryTab.PHOTON,
|
||||
onClick = { viewModel.selectTab(GalleryTab.PHOTON) },
|
||||
text = {
|
||||
Text(
|
||||
text = stringResource(R.string.gallery_photon),
|
||||
fontSize = 14.sp,
|
||||
fontWeight = if (selectedTab == GalleryTab.PHOTON) FontWeight.Bold else FontWeight.Normal
|
||||
)
|
||||
}
|
||||
)
|
||||
Tab(
|
||||
selected = selectedTab == GalleryTab.SYSTEM,
|
||||
onClick = { viewModel.selectTab(GalleryTab.SYSTEM) },
|
||||
text = {
|
||||
Text(
|
||||
text = stringResource(R.string.gallery_system),
|
||||
fontSize = 14.sp,
|
||||
fontWeight = if (selectedTab == GalleryTab.SYSTEM) FontWeight.Bold else FontWeight.Normal
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
navigationIcon = {
|
||||
@@ -243,11 +305,38 @@ fun GalleryScreen(
|
||||
.fillMaxSize()
|
||||
.padding(paddingValues)
|
||||
) {
|
||||
if (isLoading) {
|
||||
if (isLoading && photos.isEmpty()) {
|
||||
CircularProgressIndicator(
|
||||
color = AccentOrange,
|
||||
modifier = Modifier.align(Alignment.Center)
|
||||
)
|
||||
} else if (selectedTab == GalleryTab.SYSTEM && !hasPermission) {
|
||||
// 权限缺失提示
|
||||
Column(
|
||||
modifier = Modifier.align(Alignment.Center).padding(32.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.permission_required_gallery),
|
||||
color = Color.White.copy(alpha = 0.6f),
|
||||
fontSize = 16.sp,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
Button(
|
||||
onClick = {
|
||||
val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
android.Manifest.permission.READ_MEDIA_IMAGES
|
||||
} else {
|
||||
android.Manifest.permission.READ_EXTERNAL_STORAGE
|
||||
}
|
||||
permissionLauncher.launch(permission)
|
||||
},
|
||||
colors = ButtonDefaults.buttonColors(containerColor = AccentOrange)
|
||||
) {
|
||||
Text(stringResource(R.string.grant_permission))
|
||||
}
|
||||
}
|
||||
} else if (photos.isEmpty()) {
|
||||
// 空状态
|
||||
Column(
|
||||
@@ -262,6 +351,7 @@ fun GalleryScreen(
|
||||
)
|
||||
}
|
||||
} else {
|
||||
val currentPhotos = photos
|
||||
// 照片网格
|
||||
LazyVerticalGrid(
|
||||
columns = GridCells.Fixed(3),
|
||||
@@ -269,10 +359,10 @@ fun GalleryScreen(
|
||||
modifier = Modifier.fillMaxSize()
|
||||
) {
|
||||
items(
|
||||
items = photos,
|
||||
items = currentPhotos,
|
||||
key = { it.id }
|
||||
) { photo ->
|
||||
val index = photos.indexOf(photo)
|
||||
val index = currentPhotos.indexOf(photo)
|
||||
PhotoGridItem(
|
||||
photo = photo,
|
||||
viewModel = viewModel,
|
||||
@@ -293,6 +383,30 @@ fun GalleryScreen(
|
||||
viewModel.togglePhotoSelection(photo)
|
||||
}
|
||||
)
|
||||
|
||||
// 触底加载更多 (仅限系统相册)
|
||||
if (selectedTab == GalleryTab.SYSTEM && photo == currentPhotos.lastOrNull()) {
|
||||
LaunchedEffect(Unit) {
|
||||
viewModel.loadSystemPhotos(reset = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedTab == GalleryTab.SYSTEM && isSystemLoadingMore) {
|
||||
item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
CircularProgressIndicator(
|
||||
color = AccentOrange,
|
||||
modifier = Modifier.size(24.dp),
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -311,25 +425,27 @@ fun GalleryScreen(
|
||||
Text(
|
||||
text = stringResource(R.string.delete_multiple_confirm, selectedPhotos.size)
|
||||
)
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.clickable { deleteExported = !deleteExported }
|
||||
) {
|
||||
Checkbox(
|
||||
checked = deleteExported,
|
||||
onCheckedChange = { deleteExported = it },
|
||||
colors = CheckboxDefaults.colors(
|
||||
checkedColor = Color(0xFFFF6B35),
|
||||
uncheckedColor = Color.White.copy(alpha = 0.6f)
|
||||
if (viewModel.selectedTab == GalleryTab.PHOTON) {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.clickable { deleteExported = !deleteExported }
|
||||
) {
|
||||
Checkbox(
|
||||
checked = deleteExported,
|
||||
onCheckedChange = { deleteExported = it },
|
||||
colors = CheckboxDefaults.colors(
|
||||
checkedColor = Color(0xFFFF6B35),
|
||||
uncheckedColor = Color.White.copy(alpha = 0.6f)
|
||||
)
|
||||
)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.delete_exported_photos),
|
||||
color = Color.White.copy(alpha = 0.9f),
|
||||
fontSize = 14.sp
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.delete_exported_photos),
|
||||
color = Color.White.copy(alpha = 0.9f),
|
||||
fontSize = 14.sp
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -63,6 +63,7 @@ import androidx.core.view.isVisible
|
||||
import androidx.media3.ui.AspectRatioFrameLayout
|
||||
import com.hinnka.mycamera.utils.DeviceUtil
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import com.hinnka.mycamera.viewmodel.GalleryTab
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
@@ -79,7 +80,7 @@ fun PhotoDetailScreen(
|
||||
onViewBurst: ((String) -> Unit)? = null,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val photos by viewModel.photos.collectAsState()
|
||||
val photos by viewModel.currentPhotos.collectAsState()
|
||||
val context = LocalContext.current
|
||||
|
||||
var showDeleteDialog by remember { mutableStateOf(false) }
|
||||
@@ -96,7 +97,7 @@ fun PhotoDetailScreen(
|
||||
if (result.resultCode == Activity.RESULT_OK) {
|
||||
// User confirmed deletion, delete internal photo
|
||||
viewModel.deletePhotoAfterConfirmation { success ->
|
||||
if (success && photos.isEmpty()) {
|
||||
if (success) {
|
||||
onBack()
|
||||
}
|
||||
}
|
||||
@@ -106,6 +107,20 @@ fun PhotoDetailScreen(
|
||||
}
|
||||
}
|
||||
|
||||
val systemDeletePhotoLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartIntentSenderForResult()
|
||||
) { result ->
|
||||
if (result.resultCode == Activity.RESULT_OK) {
|
||||
viewModel.deleteSystemPhotoAfterConfirmation { success ->
|
||||
if (success) {
|
||||
onBack()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
viewModel.clearDeleteRequest()
|
||||
}
|
||||
}
|
||||
|
||||
// Monitor deletePendingIntent and launch system delete dialog
|
||||
LaunchedEffect(viewModel.deletePendingIntent) {
|
||||
viewModel.deletePendingIntent?.let { pendingIntent ->
|
||||
@@ -120,6 +135,18 @@ fun PhotoDetailScreen(
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(viewModel.systemDeletePendingIntent) {
|
||||
viewModel.systemDeletePendingIntent?.let { pendingIntent ->
|
||||
try {
|
||||
systemDeletePhotoLauncher.launch(
|
||||
IntentSenderRequest.Builder(pendingIntent.intentSender).build()
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
viewModel.clearDeleteRequest()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val pagerState = rememberPagerState(
|
||||
initialPage = initialIndex,
|
||||
pageCount = { photos.size }
|
||||
@@ -286,24 +313,26 @@ fun PhotoDetailScreen(
|
||||
}
|
||||
|
||||
// 导出
|
||||
IconButton(
|
||||
onClick = { currentPhoto?.let { showExportDialog = true } },
|
||||
modifier = Modifier
|
||||
.size(56.dp)
|
||||
.background(Color.White.copy(alpha = 0.1f), CircleShape)
|
||||
) {
|
||||
if (isSaving) {
|
||||
CircularProgressIndicator(
|
||||
color = Color.White,
|
||||
modifier = Modifier.size(24.dp),
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
} else {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Output,
|
||||
contentDescription = stringResource(R.string.export),
|
||||
tint = AccentOrange
|
||||
)
|
||||
if (viewModel.selectedTab == GalleryTab.PHOTON || currentPhoto?.metadata?.sourceUri != null) {
|
||||
IconButton(
|
||||
onClick = { currentPhoto?.let { showExportDialog = true } },
|
||||
modifier = Modifier
|
||||
.size(56.dp)
|
||||
.background(Color.White.copy(alpha = 0.1f), CircleShape)
|
||||
) {
|
||||
if (isSaving) {
|
||||
CircularProgressIndicator(
|
||||
color = Color.White,
|
||||
modifier = Modifier.size(24.dp),
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
} else {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Output,
|
||||
contentDescription = stringResource(R.string.export),
|
||||
tint = AccentOrange
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,25 +494,27 @@ fun PhotoDetailScreen(
|
||||
text = {
|
||||
Column {
|
||||
Text(stringResource(R.string.delete_confirm))
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.clickable { deleteExported = !deleteExported }
|
||||
) {
|
||||
Checkbox(
|
||||
checked = deleteExported,
|
||||
onCheckedChange = { deleteExported = it },
|
||||
colors = CheckboxDefaults.colors(
|
||||
checkedColor = Color(0xFFFF6B35),
|
||||
uncheckedColor = Color.White.copy(alpha = 0.6f)
|
||||
if (viewModel.selectedTab == GalleryTab.PHOTON) {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.clickable { deleteExported = !deleteExported }
|
||||
) {
|
||||
Checkbox(
|
||||
checked = deleteExported,
|
||||
onCheckedChange = { deleteExported = it },
|
||||
colors = CheckboxDefaults.colors(
|
||||
checkedColor = Color(0xFFFF6B35),
|
||||
uncheckedColor = Color.White.copy(alpha = 0.6f)
|
||||
)
|
||||
)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.delete_exported_photos),
|
||||
color = Color.White.copy(alpha = 0.9f),
|
||||
fontSize = 14.sp
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.delete_exported_photos),
|
||||
color = Color.White.copy(alpha = 0.9f),
|
||||
fontSize = 14.sp
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -14,6 +14,7 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.runtime.snapshots.SnapshotStateMap
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
@@ -36,6 +37,13 @@ import java.io.FileOutputStream
|
||||
import java.util.*
|
||||
import kotlin.math.max
|
||||
|
||||
/**
|
||||
* 相册 Tab
|
||||
*/
|
||||
enum class GalleryTab {
|
||||
PHOTON, SYSTEM
|
||||
}
|
||||
|
||||
/**
|
||||
* 相册 ViewModel
|
||||
* 管理照片列表、选择状态和各种操作
|
||||
@@ -85,13 +93,46 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
// 水印编辑弹窗状态
|
||||
var showWatermarkSheet by mutableStateOf(false)
|
||||
|
||||
// 当前选中的 Tab
|
||||
var selectedTab by mutableStateOf(GalleryTab.PHOTON)
|
||||
private set
|
||||
|
||||
// 照片列表
|
||||
private val _photos = MutableStateFlow<List<PhotoData>>(emptyList())
|
||||
val photos: StateFlow<List<PhotoData>> = _photos.asStateFlow()
|
||||
val photos = _photos.asStateFlow()
|
||||
private val _systemPhotos = MutableStateFlow<List<PhotoData>>(emptyList())
|
||||
val systemPhotos = _systemPhotos.asStateFlow()
|
||||
val currentPhotos = combine(photos, systemPhotos, snapshotFlow { selectedTab }) { p, s, tab ->
|
||||
if (tab == GalleryTab.PHOTON) {
|
||||
p
|
||||
} else {
|
||||
// Map system photos to their internal associated copies if they exist
|
||||
s.map { systemPhoto ->
|
||||
val systemUriString = systemPhoto.uri.toString()
|
||||
p.find {
|
||||
isSameSystemUri(it.metadata?.sourceUri, systemUriString) ||
|
||||
it.metadata?.exportedUris?.any { exportedUri ->
|
||||
isSameSystemUri(exportedUri, systemUriString)
|
||||
} == true
|
||||
} ?: systemPhoto
|
||||
}
|
||||
}
|
||||
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
||||
|
||||
private var systemOffset = 0
|
||||
private val pageSize = 50
|
||||
var hasMoreSystemPhotos by mutableStateOf(true)
|
||||
private set
|
||||
|
||||
// 加载状态
|
||||
private val _isLoading = MutableStateFlow(false)
|
||||
val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()
|
||||
val isLoading = _isLoading.asStateFlow()
|
||||
|
||||
private val _isSystemLoadingMore = MutableStateFlow(false)
|
||||
val isSystemLoadingMore: StateFlow<Boolean> = _isSystemLoadingMore.asStateFlow()
|
||||
|
||||
// 权限状态
|
||||
var hasGalleryPermission by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
// 分享状态
|
||||
private val _isSharing = MutableStateFlow(false)
|
||||
@@ -132,6 +173,11 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
var editLutConfig: LutConfig? by mutableStateOf(null)
|
||||
private set
|
||||
|
||||
// 系统相册删除
|
||||
var systemDeletePendingIntent by mutableStateOf<android.app.PendingIntent?>(null)
|
||||
private set
|
||||
private var pendingDeleteSystemPhoto: PhotoData? = null
|
||||
|
||||
// 当前照片的元数据
|
||||
var currentPhotoMetadata: PhotoMetadata? by mutableStateOf(null)
|
||||
private set
|
||||
@@ -185,6 +231,9 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
init {
|
||||
loadPhotos()
|
||||
|
||||
// 检查系统相册权限
|
||||
checkGalleryPermission()
|
||||
|
||||
// 订阅 ContentRepository 的 StateFlow,结合用户自定义排序
|
||||
viewModelScope.launch {
|
||||
contentRepository.availableLuts.combine(
|
||||
@@ -217,6 +266,82 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载当前选中的 Tab 内容
|
||||
*/
|
||||
fun loadCurrentTabData() {
|
||||
// 始终刷新内部照片元数据,以确保系统相册关联(sourceUri/exportedUris)是最新的
|
||||
loadPhotos()
|
||||
|
||||
if (selectedTab == GalleryTab.SYSTEM) {
|
||||
loadSystemPhotos(reset = true)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换 Tab
|
||||
*/
|
||||
fun selectTab(tab: GalleryTab) {
|
||||
if (selectedTab != tab) {
|
||||
selectedTab = tab
|
||||
if (tab == GalleryTab.SYSTEM && _systemPhotos.value.isEmpty()) {
|
||||
loadSystemPhotos(reset = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查并更新权限状态
|
||||
*/
|
||||
fun checkGalleryPermission() {
|
||||
val context = getApplication<Application>()
|
||||
hasGalleryPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
context.checkSelfPermission(android.Manifest.permission.READ_MEDIA_IMAGES) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
} else {
|
||||
context.checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
if (hasGalleryPermission && selectedTab == GalleryTab.SYSTEM && _systemPhotos.value.isEmpty()) {
|
||||
loadSystemPhotos(reset = true)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载系统照片
|
||||
*/
|
||||
fun loadSystemPhotos(reset: Boolean = false) {
|
||||
if (!hasGalleryPermission) return
|
||||
if (!reset && (!hasMoreSystemPhotos || _isSystemLoadingMore.value)) return
|
||||
|
||||
viewModelScope.launch {
|
||||
if (reset) {
|
||||
if (_systemPhotos.value.isEmpty()) {
|
||||
_isLoading.value = true
|
||||
}
|
||||
systemOffset = 0
|
||||
hasMoreSystemPhotos = true
|
||||
} else {
|
||||
_isSystemLoadingMore.value = true
|
||||
}
|
||||
|
||||
try {
|
||||
val newPhotos = repository.getSystemPhotos(systemOffset, pageSize)
|
||||
if (reset) {
|
||||
_systemPhotos.value = newPhotos
|
||||
} else {
|
||||
_systemPhotos.value += newPhotos
|
||||
}
|
||||
|
||||
systemOffset += newPhotos.size
|
||||
hasMoreSystemPhotos = newPhotos.size >= pageSize
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to load system photos", e)
|
||||
} finally {
|
||||
_isLoading.value = false
|
||||
_isSystemLoadingMore.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载照片列表
|
||||
*/
|
||||
@@ -238,7 +363,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
val context = getApplication<Application>()
|
||||
|
||||
// 3. Eagerly load metadata for the first ~30 items (visible area)
|
||||
val topItemsToLoad = mergedList.take(30).filter { it.metadata == null }
|
||||
// Always refresh metadata for the first 30 items to ensure recent exports/mappings are picked up
|
||||
val topItemsToLoad = mergedList.take(30)
|
||||
val topItemsLoaded = if (topItemsToLoad.isNotEmpty()) {
|
||||
withContext(Dispatchers.IO) {
|
||||
topItemsToLoad.map { photo ->
|
||||
@@ -374,7 +500,18 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
val photo = getCurrentPhoto() ?: return
|
||||
viewModelScope.launch {
|
||||
val context = getApplication<Application>()
|
||||
currentPhotoMetadata = PhotoManager.loadMetadata(context, photo.id)
|
||||
|
||||
// 如果是系统相册,尝试通过 sourceUri 关联已导入的光子相册照片
|
||||
if (selectedTab == GalleryTab.SYSTEM) {
|
||||
val associatedPhoto = _photos.value.find { it.metadata?.sourceUri == photo.uri.toString() }
|
||||
if (associatedPhoto != null) {
|
||||
currentPhotoMetadata = associatedPhoto.metadata
|
||||
} else {
|
||||
currentPhotoMetadata = PhotoMetadata.fromUri(context, photo.uri)
|
||||
}
|
||||
} else {
|
||||
currentPhotoMetadata = PhotoManager.loadMetadata(context, photo.id)
|
||||
}
|
||||
|
||||
// 更新编辑状态
|
||||
currentPhotoMetadata?.let { metadata ->
|
||||
@@ -455,7 +592,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
* 设置当前查看的照片
|
||||
*/
|
||||
fun setCurrentPhoto(index: Int) {
|
||||
currentPhotoIndex = index.coerceIn(0, (_photos.value.size - 1).coerceAtLeast(0))
|
||||
currentPhotoIndex = index.coerceIn(0, (currentPhotos.value.size - 1).coerceAtLeast(0))
|
||||
loadCurrentPhotoMetadata()
|
||||
}
|
||||
|
||||
@@ -463,7 +600,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
* 获取当前照片
|
||||
*/
|
||||
fun getCurrentPhoto(): PhotoData? {
|
||||
return _photos.value.getOrNull(currentPhotoIndex)
|
||||
return currentPhotos.value.getOrNull(currentPhotoIndex)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -486,6 +623,20 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
* 4. 如果没有导出的照片,或者在 Android 10 及以下,直接删除照片
|
||||
*/
|
||||
fun requestDeletePhoto(photo: PhotoData, deleteExported: Boolean = true) {
|
||||
if (selectedTab == GalleryTab.SYSTEM) {
|
||||
// 系统相册删除
|
||||
val pendingIntent = PhotoManager.createSystemDeleteRequest(getApplication(), photo.uri)
|
||||
if (pendingIntent != null) {
|
||||
pendingDeleteSystemPhoto = photo
|
||||
systemDeletePendingIntent = pendingIntent
|
||||
PLog.d(TAG, "Set system delete pending intent for photo ${photo.id}")
|
||||
} else {
|
||||
// TODO: Handle Android 10- or direct deletion if needed, but usually createSystemDeleteRequest covers API 30+
|
||||
PLog.w(TAG, "Failed to create system delete request for ${photo.id}")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (!deleteExported) {
|
||||
// 不删除系统相册照片,直接删除应用内部照片
|
||||
deletePhotoOnlyInternal(photo)
|
||||
@@ -537,6 +688,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
fun clearDeleteRequest() {
|
||||
pendingDeletePhoto = null
|
||||
deletePendingIntent = null
|
||||
pendingDeleteSystemPhoto = null
|
||||
systemDeletePendingIntent = null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -585,6 +738,25 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 系统相册照片删除确认后的回调
|
||||
*/
|
||||
fun deleteSystemPhotoAfterConfirmation(onComplete: (Boolean) -> Unit = {}) {
|
||||
val photo = pendingDeleteSystemPhoto ?: return
|
||||
viewModelScope.launch {
|
||||
// 系统照片已经被 MediaStore 删除,我们只需要刷新列表
|
||||
loadSystemPhotos(reset = true)
|
||||
|
||||
// 调整索引
|
||||
if (currentPhotoIndex >= currentPhotos.value.size) {
|
||||
currentPhotoIndex = (currentPhotos.value.size - 1).coerceAtLeast(0)
|
||||
}
|
||||
|
||||
clearDeleteRequest()
|
||||
onComplete(true)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除当前照片
|
||||
*/
|
||||
@@ -622,6 +794,30 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
val toDelete = selectedPhotos.toList()
|
||||
if (toDelete.isEmpty()) return
|
||||
|
||||
if (selectedTab == GalleryTab.SYSTEM) {
|
||||
// 系统相册批量删除
|
||||
viewModelScope.launch {
|
||||
val context = getApplication<Application>()
|
||||
val uris = toDelete.map { photo ->
|
||||
// 如果是本地关联的照片,优先取 sourceUri;否则直接取 photo.uri
|
||||
photo.metadata?.sourceUri?.let { Uri.parse(it) } ?: photo.uri
|
||||
}
|
||||
|
||||
try {
|
||||
val pendingIntent = MediaStore.createDeleteRequest(
|
||||
context.contentResolver,
|
||||
uris
|
||||
)
|
||||
pendingDeletePhotos = toDelete
|
||||
batchDeletePendingIntent = pendingIntent
|
||||
PLog.d(TAG, "Set system batch delete pending intent for ${toDelete.size} photos")
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to create system batch delete request", e)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (!deleteExported) {
|
||||
// 不删除系统相册照片,直接删除应用内部照片
|
||||
deleteBatchPhotosOnlyInternal(toDelete)
|
||||
@@ -716,23 +912,29 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
if (photos.isEmpty()) return
|
||||
|
||||
viewModelScope.launch {
|
||||
val context = getApplication<Application>()
|
||||
var deletedCount = 0
|
||||
if (selectedTab == GalleryTab.SYSTEM) {
|
||||
// 系统相册刷新
|
||||
loadSystemPhotos(reset = true)
|
||||
} else {
|
||||
// 原有的内部照片删除逻辑
|
||||
val context = getApplication<Application>()
|
||||
var deletedCount = 0
|
||||
|
||||
withContext(Dispatchers.IO) {
|
||||
photos.forEach { photo ->
|
||||
val success = PhotoManager.deletePhotoOnly(context, photo.id)
|
||||
if (success) {
|
||||
deletedCount++
|
||||
withContext(Dispatchers.IO) {
|
||||
photos.forEach { photo ->
|
||||
val success = PhotoManager.deletePhotoOnly(context, photo.id)
|
||||
if (success) {
|
||||
deletedCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
loadPhotos()
|
||||
PLog.d(TAG, "Batch deleted $deletedCount internal photos after confirmation")
|
||||
}
|
||||
|
||||
exitSelectionMode()
|
||||
loadPhotos()
|
||||
clearBatchDeleteRequest()
|
||||
onComplete(deletedCount)
|
||||
PLog.d(TAG, "Batch deleted $deletedCount photos after confirmation")
|
||||
onComplete(photos.size)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -949,7 +1151,12 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
/**
|
||||
* 获取应用 LUT 和边框后的预览 Bitmap
|
||||
*/
|
||||
suspend fun getPreviewBitmap(photo: PhotoData, useGlobalEdit: Boolean = false, showOrigin: Boolean = false, bitmap: Bitmap? = null): Bitmap? {
|
||||
suspend fun getPreviewBitmap(
|
||||
photo: PhotoData,
|
||||
useGlobalEdit: Boolean = false,
|
||||
showOrigin: Boolean = false,
|
||||
bitmap: Bitmap? = null
|
||||
): Bitmap? {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val context = getApplication<Application>()
|
||||
@@ -959,7 +1166,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
val finalNR: Float
|
||||
val finalCNR: Float
|
||||
|
||||
val metadata = photo.metadata ?: PhotoManager.loadMetadata(getApplication(), photo.id) ?: PhotoMetadata()
|
||||
val metadata =
|
||||
photo.metadata ?: PhotoManager.loadMetadata(getApplication(), photo.id) ?: PhotoMetadata()
|
||||
|
||||
if (useGlobalEdit) {
|
||||
finalMetadata = (currentPhotoMetadata ?: metadata).copy(
|
||||
@@ -982,7 +1190,11 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
?: (if (finalMetadata.isImported) 0f else chromaNoiseReduction.value)
|
||||
}
|
||||
|
||||
val bitmap = bitmap ?: PhotoManager.loadBitmap(context, photo.id, 4096) ?: return@withContext null
|
||||
val bitmap = bitmap ?: if (selectedTab == GalleryTab.PHOTON) {
|
||||
PhotoManager.loadBitmap(context, photo.id, 4096)
|
||||
} else {
|
||||
PhotoManager.loadBitmap(context, photo.uri, 4096)
|
||||
} ?: return@withContext null
|
||||
|
||||
if (showOrigin) {
|
||||
bitmap
|
||||
@@ -1020,31 +1232,57 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val context = getApplication<Application>()
|
||||
|
||||
// 处理系统相册照片:自动导入并关联
|
||||
val targetPhotoId = if (selectedTab == GalleryTab.SYSTEM) {
|
||||
// 检查是否已经导入过
|
||||
val existing = _photos.value.find { it.metadata?.sourceUri == photo.uri.toString() }
|
||||
existing?.id ?: PhotoManager.importPhoto(
|
||||
context,
|
||||
photo.uri,
|
||||
editLutId.value,
|
||||
sourceUri = photo.uri.toString()
|
||||
)
|
||||
} else {
|
||||
photo.id
|
||||
}
|
||||
|
||||
if (targetPhotoId == null) {
|
||||
onComplete(false)
|
||||
return@launch
|
||||
}
|
||||
|
||||
val metadata = (currentPhotoMetadata ?: PhotoMetadata()).copy(
|
||||
lutId = editLutId.value,
|
||||
frameId = editFrameId.value,
|
||||
colorRecipeParams = editLutRecipeParams.value,
|
||||
sharpening = editSharpening.value,
|
||||
noiseReduction = editNoiseReduction.value,
|
||||
chromaNoiseReduction = editChromaNoiseReduction.value
|
||||
chromaNoiseReduction = editChromaNoiseReduction.value,
|
||||
sourceUri = if (selectedTab == GalleryTab.SYSTEM) photo.uri.toString() else currentPhotoMetadata?.sourceUri
|
||||
)
|
||||
val success = PhotoManager.saveMetadata(context, photo.id, metadata)
|
||||
val success = PhotoManager.saveMetadata(context, targetPhotoId, metadata)
|
||||
|
||||
if (success) {
|
||||
currentPhotoMetadata = metadata
|
||||
|
||||
// 更新 photos 列表中对应照片的 metadata,触发 UI 刷新
|
||||
val updatedPhotos = _photos.value.map { p ->
|
||||
if (p.id == photo.id) {
|
||||
p.copy(metadata = metadata)
|
||||
} else {
|
||||
p
|
||||
// 如果是新导入的,刷相册列表
|
||||
if (selectedTab == GalleryTab.SYSTEM) {
|
||||
loadPhotos()
|
||||
} else {
|
||||
// 更新 photos 列表中对应照片的 metadata,触发 UI 刷新
|
||||
val updatedPhotos = _photos.value.map { p ->
|
||||
if (p.id == targetPhotoId) {
|
||||
p.copy(metadata = metadata)
|
||||
} else {
|
||||
p
|
||||
}
|
||||
}
|
||||
_photos.value = updatedPhotos
|
||||
}
|
||||
_photos.value = updatedPhotos
|
||||
|
||||
// 同步更新 latestPhoto
|
||||
if (_latestPhoto.value?.id == photo.id) {
|
||||
if (_latestPhoto.value?.id == targetPhotoId) {
|
||||
_latestPhoto.value = _latestPhoto.value?.copy(metadata = metadata)
|
||||
}
|
||||
|
||||
@@ -1063,7 +1301,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
*/
|
||||
fun refreshRawPreview(photo: PhotoData, onComplete: (Boolean) -> Unit = {}) {
|
||||
if (refreshingPhotos.contains(photo.id)) return
|
||||
|
||||
|
||||
viewModelScope.launch {
|
||||
refreshingPhotos.add(photo.id)
|
||||
try {
|
||||
@@ -1072,7 +1310,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
if (result != null) {
|
||||
// 更新刷新密钥以强制 UI 重新加载
|
||||
photoRefreshKeys[photo.id] = System.currentTimeMillis()
|
||||
|
||||
|
||||
// 触发列表更新
|
||||
val updatedPhotos = _photos.value.map { p ->
|
||||
if (p.id == photo.id) {
|
||||
@@ -1095,13 +1333,20 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
/**
|
||||
* 导出照片到公共目录(带 LUT 烘焙)
|
||||
*/
|
||||
fun exportPhoto(photo: PhotoData, bitmap: Bitmap? = null, suffix: String? = null, onComplete: (Boolean) -> Unit = {}) {
|
||||
fun exportPhoto(
|
||||
photo: PhotoData,
|
||||
bitmap: Bitmap? = null,
|
||||
suffix: String? = null,
|
||||
onComplete: (Boolean) -> Unit = {}
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
val metadata = PhotoManager.loadMetadata(getApplication(), photo.id) ?: photo.metadata ?: PhotoMetadata()
|
||||
val context = getApplication<Application>()
|
||||
PhotoManager.exportPhoto(context, photo.id, bitmap, contentRepository.photoProcessor, metadata,
|
||||
PhotoManager.exportPhoto(
|
||||
context, photo.id, bitmap, contentRepository.photoProcessor, metadata,
|
||||
sharpening.value, noiseReduction.value,
|
||||
chromaNoiseReduction.value, photoQuality.firstOrNull() ?: 95, suffix) { success ->
|
||||
chromaNoiseReduction.value, photoQuality.firstOrNull() ?: 95, suffix
|
||||
) { success ->
|
||||
if (success) {
|
||||
exitEditMode()
|
||||
loadPhotos()
|
||||
@@ -1154,7 +1399,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
var successCount = 0
|
||||
|
||||
withContext(Dispatchers.IO) {
|
||||
val lutId = defaultLutId.firstOrNull() ?: contentRepository.getAvailableLuts().firstOrNull { it.isDefault }?.id
|
||||
val lutId = defaultLutId.firstOrNull() ?: contentRepository.getAvailableLuts()
|
||||
.firstOrNull { it.isDefault }?.id
|
||||
uris.forEach { uri ->
|
||||
val photoId = PhotoManager.importPhoto(context, uri, lutId)
|
||||
if (photoId != null) {
|
||||
@@ -1214,6 +1460,30 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
}
|
||||
|
||||
private fun isSameSystemUri(uri1: String?, uri2: String?): Boolean {
|
||||
if (uri1 == null || uri2 == null) return uri1 == uri2
|
||||
if (uri1 == uri2) return true
|
||||
|
||||
// Try to compare by MediaStore ID if both are MediaStore URIs
|
||||
try {
|
||||
val u1 = Uri.parse(uri1)
|
||||
val u2 = Uri.parse(uri2)
|
||||
|
||||
val isMediaStore1 = u1.authority?.contains("media") == true
|
||||
val isMediaStore2 = u2.authority?.contains("media") == true
|
||||
|
||||
if (isMediaStore1 && isMediaStore2) {
|
||||
val id1 = u1.lastPathSegment
|
||||
val id2 = u2.lastPathSegment
|
||||
return id1 != null && id1 == id2
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// Fallback to string comparison (already done above)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* 估计 Bitmap 的平均亮度(调试用)
|
||||
*/
|
||||
|
||||
@@ -37,6 +37,9 @@
|
||||
|
||||
<!-- Gallery -->
|
||||
<string name="gallery">相册</string>
|
||||
<string name="gallery_photon">光子相册</string>
|
||||
<string name="gallery_system">系统相册</string>
|
||||
<string name="permission_required_gallery">需要媒体访问权限以显示系统相册</string>
|
||||
<string name="photo_detail">照片详情</string>
|
||||
<string name="share">分享</string>
|
||||
<string name="delete">删除</string>
|
||||
|
||||
@@ -37,6 +37,9 @@
|
||||
|
||||
<!-- Gallery -->
|
||||
<string name="gallery">Gallery</string>
|
||||
<string name="gallery_photon">Photon</string>
|
||||
<string name="gallery_system">System</string>
|
||||
<string name="permission_required_gallery">Media permission is required to access system gallery</string>
|
||||
<string name="photo_detail">Photo Detail</string>
|
||||
<string name="share">Share</string>
|
||||
<string name="delete">Delete</string>
|
||||
|
||||
Reference in new issue
Block a user