feat: quick shot mode (2)

This commit is contained in:
zhoubinjia committed 2026-06-18 17:07:12 +08:00
1 parent e7a4a0431d
commit 7bed0817d0
7 files changed
+236 -64

No files matched your search

@@ -1025,6 +1025,109 @@ object GalleryManager {
}
}
suspend fun saveQuickShotBitmapToSystemGallery(
context: Context,
metadata: MediaMetadata,
bitmap: Bitmap,
photoQuality: Int,
photoId: String = UUID.randomUUID().toString()
): String? = withContext(Dispatchers.IO) {
val date = metadata.dateTaken ?: System.currentTimeMillis()
val baseFilename = "PhotonCamera_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date(date))}"
val photoDir = getPhotoDir(context, photoId, true)
var exportedUri: Uri? = null
var tempFile: File? = null
try {
val shouldPreferHeic = ContentRepository.getInstance(context)
.userPreferencesRepository
.userPreferences
.firstOrNull()
?.useHeicExport ?: false
val captureInfo = metadata.toCaptureInfo().copy(
imageWidth = bitmap.width,
imageHeight = bitmap.height
)
var extension = "jpg"
var mimeType = "image/jpeg"
var encodedFile: File? = null
if (shouldPreferHeic) {
val heicFile = File(context.cacheDir, "temp_quick_shot_${System.nanoTime()}.${HeicExportEncoder.EXTENSION}")
val exifData = ExifWriter.buildExifBlock(context.cacheDir, captureInfo)
val heicSaved = exifData != null && HeicExportEncoder.write(
bitmap = bitmap,
outputFile = heicFile,
quality = photoQuality,
exifData = exifData
)
if (heicSaved) {
extension = HeicExportEncoder.EXTENSION
mimeType = HeicExportEncoder.MIME_TYPE
encodedFile = heicFile
} else {
heicFile.delete()
PLog.w(TAG, "Quick-shot HEIC save failed or unsupported, falling back to JPEG")
}
}
if (encodedFile == null) {
val jpegFile = File(context.cacheDir, "temp_quick_shot_${System.nanoTime()}.jpg")
FileOutputStream(jpegFile).use { outputStream ->
writeFinalJpeg(bitmap, outputStream, photoQuality)
}
ExifWriter.writeExif(jpegFile, captureInfo)
encodedFile = jpegFile
}
tempFile = encodedFile
val filename = "$baseFilename.$extension"
val destination = resolvePhotoExportDestination(context)
exportedUri = exportFileToConfiguredPhotoStorage(
context = context,
destination = destination,
collectionUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
displayName = filename,
mimeType = mimeType,
sourceFile = encodedFile
)
val uri = exportedUri ?: run {
photoDir.deleteRecursively()
return@withContext null
}
generateThumbnail(bitmap, getThumbnailFile(context, photoId))
val savedMetadata = metadata.copy(
mediaType = MediaType.IMAGE,
sourceUri = uri.toString(),
exportedUris = emptyList(),
mimeType = mimeType,
width = bitmap.width,
height = bitmap.height,
captureMode = metadata.captureMode ?: "quick_shot"
)
val metadataSaved = saveMetadata(context, photoId, savedMetadata)
if (!metadataSaved) {
discardPhotoExportUri(context, uri)
photoDir.deleteRecursively()
return@withContext null
}
photoDir.setLastModified(date)
notifyPhotoLibraryChanged()
PLog.d(
TAG,
"Quick-shot bitmap saved directly to system gallery: $uri, photoId=$photoId, mimeType=$mimeType"
)
photoId
} catch (e: Exception) {
PLog.e(TAG, "Failed to save quick-shot bitmap to system gallery", e)
exportedUri?.let { discardPhotoExportUri(context, it) }
photoDir.deleteRecursively()
null
} finally {
tempFile?.delete()
}
}
private suspend fun exportEncodedPhotoToMediaStore(
context: Context,
id: String,
@@ -3251,7 +3354,11 @@ object GalleryManager {
return buildList {
addAll(metadata?.exportedUris ?: emptyList())
val sourceUri = metadata?.sourceUri
if (metadata?.mediaType == MediaType.VIDEO && metadata.isImported != true && !sourceUri.isNullOrBlank()) {
val shouldDeleteSourceUri = metadata != null &&
!metadata.isImported &&
!sourceUri.isNullOrBlank() &&
(metadata.mediaType == MediaType.VIDEO || metadata.captureMode == "quick_shot")
if (shouldDeleteSourceUri) {
add(sourceUri)
}
}
@@ -6,6 +6,7 @@ import android.graphics.ColorSpace
import android.graphics.Rect
import android.net.Uri
import android.os.Environment
import android.provider.OpenableColumns
import androidx.core.net.toUri
import com.hinnka.mycamera.camera.AspectRatio
import com.hinnka.mycamera.gallery.GalleryManager
@@ -163,6 +164,11 @@ object GalleryMediaStore {
val dngFile = File(photoDir, DNG_FILE)
val yuvFile = File(photoDir, YUV_FILE)
val originalFile = dngFile.takeIf { it.exists() } ?: yuvFile.takeIf { it.exists() } ?: photoFile
val sourceOnlySize = if (!photoFile.exists()) {
metadata.sourceUri?.let { runCatching { queryContentSize(context, Uri.parse(it)) }.getOrNull() } ?: 0L
} else {
0L
}
val isVideo = metadata.mediaType == MediaType.VIDEO
val dateAdded = if (isVideo) {
photoDir.lastModified().takeIf { it > 0L } ?: System.currentTimeMillis()
@@ -175,7 +181,7 @@ object GalleryMediaStore {
id = photoId,
mediaType = metadata.mediaType.name,
dateAdded = dateAdded,
size = if (photoFile.exists()) photoFile.length() else 0L,
size = if (photoFile.exists()) photoFile.length() else sourceOnlySize,
photoPath = photoFile.absolutePath,
thumbnailPath = thumbnailFile.absolutePath,
videoPath = videoFile.absolutePath,
@@ -308,7 +314,24 @@ object GalleryMediaStore {
)
}
if (!photoFile.exists()) return null
if (!photoFile.exists()) {
val resolvedSourceUri = sourceUri?.let(Uri::parse) ?: return null
return MediaData(
id = id,
uri = resolvedSourceUri,
thumbnailUri = thumbnailUri,
displayName = resolvedSourceUri.lastPathSegment ?: "image_$id",
dateAdded = dateAdded,
size = size,
width = width,
height = height,
mediaType = MediaType.IMAGE,
mimeType = mimeType ?: "image/jpeg",
sourceUri = resolvedSourceUri,
isBurstPhoto = hasBurstPhotos(photoDir),
metadata = metadata
)
}
val originalFile = dngFile.takeIf { it.exists() } ?: yuvFile.takeIf { it.exists() } ?: photoFile
return MediaData(
id = id,
@@ -431,4 +454,16 @@ object GalleryMediaStore {
val burstDir = File(photoDir, BURST_DIR)
return burstDir.exists() && (burstDir.listFiles()?.isNotEmpty() == true)
}
private fun queryContentSize(context: Context, uri: Uri): Long {
context.contentResolver.query(uri, arrayOf(OpenableColumns.SIZE), null, null, null)?.use { cursor ->
val sizeColumn = cursor.getColumnIndex(OpenableColumns.SIZE)
if (sizeColumn >= 0 && cursor.moveToFirst()) {
return cursor.getLong(sizeColumn)
}
}
return context.contentResolver.openFileDescriptor(uri, "r")?.use { descriptor ->
descriptor.statSize
} ?: 0L
}
}
@@ -1961,8 +1961,8 @@ private fun CaptureModeSwitcher(
val knobWidth = 48.dp
val knobOffset by animateDpAsState(
targetValue = when (captureMode) {
CaptureMode.PHOTO -> 0.dp
CaptureMode.QUICK_SHOT -> 48.dp
CaptureMode.QUICK_SHOT -> 0.dp
CaptureMode.PHOTO -> 48.dp
CaptureMode.VIDEO -> 96.dp
},
animationSpec = tween(durationMillis = 220),
@@ -1980,14 +1980,6 @@ private fun CaptureModeSwitcher(
modifier = Modifier.fillMaxSize(),
verticalAlignment = Alignment.CenterVertically
) {
ModeSwitcherItem(
icon = Icons.Default.CameraAlt,
selected = captureMode == CaptureMode.PHOTO,
enabled = enabled,
contentDescription = stringResource(R.string.capture_mode_photo),
onClick = { onModeSelected(CaptureMode.PHOTO) },
modifier = Modifier.weight(1f)
)
ModeSwitcherItem(
icon = Icons.Default.Bolt,
selected = captureMode == CaptureMode.QUICK_SHOT,
@@ -1996,6 +1988,14 @@ private fun CaptureModeSwitcher(
onClick = { onModeSelected(CaptureMode.QUICK_SHOT) },
modifier = Modifier.weight(1f)
)
ModeSwitcherItem(
icon = Icons.Default.CameraAlt,
selected = captureMode == CaptureMode.PHOTO,
enabled = enabled,
contentDescription = stringResource(R.string.capture_mode_photo),
onClick = { onModeSelected(CaptureMode.PHOTO) },
modifier = Modifier.weight(1f)
)
ModeSwitcherItem(
icon = Icons.Default.Videocam,
selected = captureMode == CaptureMode.VIDEO,
@@ -202,27 +202,9 @@ private fun QuickShotTopBar(
)
}
IconButton(onClick = onTimerToggle) {
if (timerSeconds > 0) {
Text(
text = "${timerSeconds}s",
color = Color.Yellow,
fontSize = 14.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.autoRotate()
)
} else {
Icon(
imageVector = Icons.Default.Timer,
contentDescription = stringResource(R.string.timer),
modifier = Modifier.size(20.dp).autoRotate(),
tint = Color.White
)
}
}
IconButton(
onClick = onQuickShotResolutionClick,
modifier = Modifier.size(64.dp, 48.dp),
enabled = quickShotCapabilities.availableResolutions.size > 1
) {
Text(
@@ -425,25 +425,6 @@ fun CameraTopSheet(
Spacer(modifier = Modifier.height(16.dp))
SectionLabel(title = stringResource(R.string.quick_shot_resolution_title))
FlowRow(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
val quickShotResolutions = quickShotCapabilities.availableResolutions
.ifEmpty { listOf(quickShotResolution) }
quickShotResolutions.forEach { resolution ->
VideoOptionChip(
title = quickShotResolutionLabel(resolution),
selected = quickShotResolution == resolution,
onClick = { onQuickShotResolutionChange(resolution) }
)
}
}
Spacer(modifier = Modifier.height(12.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
@@ -4231,6 +4231,18 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
exposureBias = currentState.exposureBias,
)
val spectralFilmSettings = resolveRawSpectralFilmSettings(userPrefs)
val captureInfo = cameraController.rebuildCaptureInfo(
result = null,
imageWidth = bitmap.width,
imageHeight = bitmap.height,
latitude = currentState.latitude,
longitude = currentState.longitude
)
val computationalAperture = if (currentState.isVirtualApertureEnabled) {
currentState.virtualAperture
} else {
null
}
val metadata = MediaMetadata(
lutId = if (storeRenderedLookMetadata) currentLutId.value else null,
@@ -4265,18 +4277,44 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
height = bitmap.height,
ratio = ratio,
rotation = 0,
deviceModel = Build.MODEL,
brand = Build.MANUFACTURER,
dateTaken = System.currentTimeMillis(),
latitude = currentState.latitude,
longitude = currentState.longitude,
deviceModel = captureInfo.model,
brand = captureInfo.make,
dateTaken = captureInfo.captureTime,
latitude = captureInfo.latitude,
longitude = captureInfo.longitude,
altitude = captureInfo.altitude,
iso = captureInfo.iso,
shutterSpeed = captureInfo.formatExposureTime(),
focalLength = captureInfo.formatFocalLength(),
focalLength35mm = captureInfo.formatFocalLength35mm(),
aperture = captureInfo.formatAperture(),
exposureBias = currentState.exposureBias,
droMode = droMode.value,
isMirrored = shouldMirror,
colorSpace = captureInfo.colorSpace,
dynamicRangeProfile = currentState.currentDynamicRangeProfile,
computationalAperture = computationalAperture,
focusPointX = currentState.focusPoint?.first,
focusPointY = currentState.focusPoint?.second,
captureMode = metadataCaptureMode
)
if (metadataCaptureMode == "quick_shot") {
val photoId = GalleryManager.saveQuickShotBitmapToSystemGallery(
context = context,
metadata = metadata,
bitmap = bitmap,
photoQuality = photoQualityValue
)
if (photoId == null) {
PLog.e(TAG, "Failed to save quick-shot bitmap capture to system gallery")
return
}
PLog.d(TAG, "Quick-shot bitmap capture saved to system gallery: $photoId")
_imageSavedEvent.emit(Unit)
return
}
val photoId = GalleryManager.preparePhoto(
context,
metadata,
@@ -4330,6 +4368,18 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
isRawCapture = false,
exposureBias = currentState.exposureBias,
)
val captureInfo = cameraController.rebuildCaptureInfo(
result = null,
imageWidth = bitmap.width,
imageHeight = bitmap.height,
latitude = currentState.latitude,
longitude = currentState.longitude
)
val computationalAperture = if (currentState.isVirtualApertureEnabled) {
currentState.virtualAperture
} else {
null
}
if (GalleryManager.loadMetadata(context, photoId) == null) {
val metadata = MediaMetadata(
@@ -4365,15 +4415,25 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
height = bitmap.height,
ratio = currentState.aspectRatio,
rotation = 0,
deviceModel = Build.MODEL,
brand = Build.MANUFACTURER,
dateTaken = System.currentTimeMillis(),
latitude = currentState.latitude,
longitude = currentState.longitude,
deviceModel = captureInfo.model,
brand = captureInfo.make,
dateTaken = captureInfo.captureTime,
latitude = captureInfo.latitude,
longitude = captureInfo.longitude,
altitude = captureInfo.altitude,
iso = captureInfo.iso,
shutterSpeed = captureInfo.formatExposureTime(),
focalLength = captureInfo.formatFocalLength(),
focalLength35mm = captureInfo.formatFocalLength35mm(),
aperture = captureInfo.formatAperture(),
exposureBias = currentState.exposureBias,
droMode = droMode.value,
isMirrored = shouldMirror,
colorSpace = captureInfo.colorSpace,
dynamicRangeProfile = currentState.currentDynamicRangeProfile,
computationalAperture = computationalAperture,
focusPointX = currentState.focusPoint?.first,
focusPointY = currentState.focusPoint?.second,
captureMode = "quick_shot"
)
@@ -1486,7 +1486,11 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
val sourceUri = metadata?.sourceUri
if (metadata?.mediaType == MediaType.VIDEO && metadata.isImported != true && !sourceUri.isNullOrBlank()) {
val shouldDeleteSourceUri = metadata != null &&
!metadata.isImported &&
!sourceUri.isNullOrBlank() &&
(metadata.mediaType == MediaType.VIDEO || metadata.captureMode == "quick_shot")
if (shouldDeleteSourceUri) {
try {
allExportedUris.add(sourceUri.toUri())
} catch (e: Exception) {
@@ -2399,11 +2403,14 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
val isSystem = selectedTab == GalleryTab.SYSTEM
val sourceBackedUri = photo.sourceUri ?: finalMetadata.sourceUri?.toUri()
val canLoadExternalUri = isSystem || sourceBackedUri != null
val externalUri = sourceBackedUri ?: photo.uri
// 2. 原始底图缓存(按 maxEdge 加载,快速预览走小尺寸,正式预览走高分辨率)
val currentBitmap = bitmap ?: if (showOrigin) {
GalleryManager.loadOriginalBitmap(context, photo.id, maxEdge, isSystem)
?: if (isSystem) GalleryManager.loadBitmap(context, photo.uri, maxEdge, isSystem) else null
?: if (canLoadExternalUri) GalleryManager.loadBitmap(context, externalUri, maxEdge, isSystem) else null
} else {
val bokehFile = GalleryManager.getBokehFile(context, photo.id)
when {
@@ -2414,7 +2421,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
maxEdge
)
else -> GalleryManager.loadOriginalBitmap(context, photo.id, maxEdge)
} ?: if (isSystem) GalleryManager.loadBitmap(context, photo.uri, maxEdge) else null
} ?: if (canLoadExternalUri) GalleryManager.loadBitmap(context, externalUri, maxEdge, isSystem) else null
} ?: return@withContext null
// 只在全分辨率路径下缓存原始底图(避免低分辨率污染 origin 缓存)