feat: selective backup categories

This commit is contained in:
zhoubinjia committed 2026-10-09 10:25:57 +08:00
1 parent 041290c24a
commit 60aca31250
12 files changed
+709 -45

No files matched your search

@@ -0,0 +1,12 @@
package com.hinnka.mycamera.data
/** Keeps each resource index together with the files needed to restore it. */
enum class BackupCategory(internal val paths: List<String>) {
SETTINGS(listOf("datastore")),
PRESETS(listOf(BackupPreferenceSanitizer.USER_PREFERENCES_ENTRY)),
LUTS(listOf("custom_luts.json", "custom_luts", "category_overrides.json")),
FRAMES(listOf("custom_frames.json", "custom_frames", "custom_fonts", "custom_logos")),
DCP_PROFILES(listOf("custom_dcps.json", "custom_dcps")),
RAW_NOISE_PROFILES(listOf("custom_raw_noise_profiles.json", "custom_raw_noise_profiles")),
CAPTURE_SOUNDS(listOf("capture_sounds")),
}
@@ -1,6 +1,7 @@
package com.hinnka.mycamera.data
import com.google.gson.GsonBuilder
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import java.io.File
@@ -29,9 +30,16 @@ internal object BackupDeviceMetadata {
private const val SCHEMA_VERSION = 1
private val gson = GsonBuilder().setPrettyPrinting().create()
fun write(identity: BackupDeviceIdentity, output: OutputStream) {
fun write(
identity: BackupDeviceIdentity,
output: OutputStream,
categories: Set<BackupCategory>? = null,
) {
val root = JsonObject().apply {
addProperty("schema_version", SCHEMA_VERSION)
categories?.let { selected ->
add("categories", JsonArray().apply { selected.forEach { add(it.name) } })
}
add(
"device",
JsonObject().apply {
@@ -60,6 +68,21 @@ internal object BackupDeviceMetadata {
}.getOrNull()
}
/** Missing selection metadata identifies a legacy backup with unsplit preferences. */
fun readCategories(restoreDir: File): Set<BackupCategory>? {
val metadataFile = File(restoreDir, ENTRY_NAME)
if (!metadataFile.isFile) return null
val root = metadataFile.reader(Charsets.UTF_8).use(JsonParser::parseReader).asJsonObject
val selection = root.get("categories") ?: return null
require(root.get("schema_version")?.asInt == SCHEMA_VERSION) {
"Unsupported backup selection schema"
}
require(selection.isJsonArray) { "Invalid backup categories" }
return selection.asJsonArray.map { BackupCategory.valueOf(it.asString) }.toSet().also {
require(it.isNotEmpty()) { "No backup categories in manifest" }
}
}
private fun JsonObject.requiredString(name: String): String {
return get(name)
?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isString }
@@ -25,21 +25,20 @@ object BackupManager {
private const val BUFFER_SIZE = 64 * 1024
// 需备份的目录/文件相对路径列表 (相对于 context.filesDir)
private val BACKUP_ENTRIES = listOf(
"datastore", // DataStore 默认存放目录
"custom_luts.json",
"custom_frames.json",
"custom_dcps.json",
"custom_raw_noise_profiles.json",
"category_overrides.json",
"custom_luts",
"custom_frames",
"custom_dcps",
"custom_raw_noise_profiles",
"custom_fonts",
"custom_logos",
"capture_sounds"
)
private val BACKUP_ENTRIES = BackupCategory.entries.flatMap { it.paths }
.map { it.substringBefore('/') }.distinct()
suspend fun availableCategories(context: Context): Set<BackupCategory> =
withContext(Dispatchers.IO) {
BackupCategory.entries.filterTo(linkedSetOf()) { category ->
category.paths.any { path ->
val entry = File(context.filesDir, path)
entry.walkTopDown()
.onEnter { !it.isHidden }
.any { it.isFile && !it.isHidden }
}
}
}
// These imported profiles describe a particular camera sensor and must stay with its device.
private val DEVICE_SPECIFIC_BACKUP_ENTRIES = setOf(
@@ -53,23 +52,34 @@ object BackupManager {
* 执行备份
* @param context Context
* @param outputUri 目标 zip 文件的 URI (通过 SAF 选择)
* @param categories 需要备份的内容分类
* @return 备份是否成功
*/
suspend fun performBackup(context: Context, outputUri: Uri): Boolean = withContext(Dispatchers.IO) {
suspend fun performBackup(
context: Context,
outputUri: Uri,
categories: Set<BackupCategory> = BackupCategory.entries.toSet(),
): Boolean = withContext(Dispatchers.IO) {
val tempZip = File(context.cacheDir, "backup-${UUID.randomUUID()}.zip")
try {
require(categories.isNotEmpty()) { "No backup categories selected" }
// SETTINGS already walks datastore, so do not write the shared preset file twice.
val selectedEntries = categories.flatMap { it.paths }.toSet().filterNot {
BackupCategory.SETTINGS in categories &&
it == BackupPreferenceSanitizer.USER_PREFERENCES_ENTRY
}
FileOutputStream(tempZip).use { fileOutput ->
ZipOutputStream(fileOutput).use { zos ->
val filesDir = context.filesDir
zos.putNextEntry(ZipEntry(BackupDeviceMetadata.ENTRY_NAME))
BackupDeviceMetadata.write(currentDeviceIdentity(), zos)
BackupDeviceMetadata.write(currentDeviceIdentity(), zos, categories)
zos.closeEntry()
for (entryName in BACKUP_ENTRIES) {
for (entryName in selectedEntries) {
val fileOrDir = File(filesDir, entryName)
if (fileOrDir.exists()) {
zipFile(fileOrDir, fileOrDir.name, zos)
zipFile(fileOrDir, entryName, zos, categories)
} else {
PLog.d(TAG, "Skip missing backup entry: $entryName")
}
@@ -94,7 +104,7 @@ object BackupManager {
validateBackupZip(input)
} ?: throw IllegalStateException("Cannot read written backup from URI: $outputUri")
PLog.d(TAG, "Backup successfully completed to $outputUri, size=${tempZip.length()}")
PLog.d(TAG, "Backup successfully completed to $outputUri, categories=$categories, size=${tempZip.length()}")
true
} catch (e: Exception) {
PLog.e(TAG, "Backup failed", e)
@@ -106,7 +116,12 @@ object BackupManager {
}
}
private fun zipFile(fileToZip: File, fileName: String, zos: ZipOutputStream) {
private fun zipFile(
fileToZip: File,
fileName: String,
zos: ZipOutputStream,
categories: Set<BackupCategory>,
) {
if (fileToZip.isHidden) {
return
}
@@ -121,7 +136,7 @@ object BackupManager {
val children = fileToZip.listFiles()
if (children != null) {
for (childFile in children) {
zipFile(childFile, fileName + "/" + childFile.name, zos)
zipFile(childFile, fileName + "/" + childFile.name, zos, categories)
}
}
return
@@ -131,7 +146,12 @@ object BackupManager {
zos.putNextEntry(zipEntry)
if (BackupPreferenceSanitizer.isUserPreferencesEntry(fileName)) {
val removedPreferenceCount =
BackupPreferenceSanitizer.writeUserPreferencesWithoutNonPortableKeys(fileToZip, zos)
BackupPreferenceSanitizer.writeUserPreferencesWithoutNonPortableKeys(
fileToZip,
zos,
includeSettings = BackupCategory.SETTINGS in categories,
includePresets = BackupCategory.PRESETS in categories,
)
if (removedPreferenceCount > 0) {
PLog.d(
TAG,
@@ -172,6 +192,7 @@ object BackupManager {
}
unzipBackupToDirectory(tempZip, restoreDir)
val categories = BackupDeviceMetadata.readCategories(restoreDir)
val backupDeviceIdentity = BackupDeviceMetadata.read(restoreDir)
val currentDeviceIdentity = currentDeviceIdentity()
val isSameDevice = backupDeviceIdentity?.matches(currentDeviceIdentity) == true
@@ -187,6 +208,8 @@ object BackupManager {
restoreDir = restoreDir,
currentFilesDir = context.filesDir,
preserveCurrentDeviceSpecificPreferences = !isSameDevice,
restoreSettings = categories == null || BackupCategory.SETTINGS in categories,
restorePresets = categories == null || BackupCategory.PRESETS in categories,
)
if (preferenceSanitization.removedNonPortablePreferenceCount > 0) {
PLog.d(
@@ -11,8 +11,13 @@ import java.io.OutputStream
import java.util.UUID
internal object BackupPreferenceSanitizer {
private const val USER_PREFERENCES_ENTRY = "datastore/user_preferences.preferences_pb"
const val USER_PREFERENCES_ENTRY = "datastore/user_preferences.preferences_pb"
private const val CUSTOM_PRESETS_KEY = "custom_presets_json"
private val presetPreferenceKeys = setOf(
CUSTOM_PRESETS_KEY,
"active_preset_id",
"deleted_built_in_ids",
)
data class RestoreResult(
val removedNonPortablePreferenceCount: Int = 0,
@@ -80,10 +85,19 @@ internal object BackupPreferenceSanitizer {
fun writeUserPreferencesWithoutNonPortableKeys(
preferencesFile: File,
output: OutputStream
output: OutputStream,
includeSettings: Boolean = true,
includePresets: Boolean = true,
): Int {
val (preferenceMap, removedCount) = readPreferenceMapWithoutNonPortableKeys(preferencesFile)
preferenceMap.writeTo(output)
val builder = preferenceMap.toBuilder()
removeKeys(
builder,
preferenceMap.preferencesMap.keys.filterTo(mutableSetOf()) { key ->
if (key in presetPreferenceKeys) !includePresets else !includeSettings
},
)
builder.build().writeTo(output)
return removedCount
}
@@ -99,11 +113,16 @@ internal object BackupPreferenceSanitizer {
restoreDir: File,
currentFilesDir: File?,
preserveCurrentDeviceSpecificPreferences: Boolean,
restoreSettings: Boolean = true,
restorePresets: Boolean = true,
): RestoreResult {
val preferencesFile = File(restoreDir, USER_PREFERENCES_ENTRY)
if (!preferencesFile.isFile) {
return RestoreResult()
}
require(restoreSettings || restorePresets) {
"Backup contains user preferences outside its selected categories"
}
val restoredBuilder = FileInputStream(preferencesFile).use { input ->
PreferenceMap.parseFrom(input).toBuilder()
@@ -114,29 +133,39 @@ internal object BackupPreferenceSanitizer {
?.let { currentFile ->
FileInputStream(currentFile).use(PreferenceMap::parseFrom)
}
val removedCount = preserveCurrentValues(
// Replace only the selected group, including deletions, and retain the other group exactly.
val preservedKeys = (restoredBuilder.preferencesMap.keys +
currentPreferenceMap?.preferencesMap.orEmpty().keys).filterTo(mutableSetOf()) { key ->
if (key in presetPreferenceKeys) !restorePresets else !restoreSettings
}
preserveCurrentValues(restoredBuilder, currentPreferenceMap, preservedKeys)
val removedCount = if (restoreSettings) preserveCurrentValues(
restoredBuilder = restoredBuilder,
currentPreferenceMap = currentPreferenceMap,
keys = nonPortablePreferenceKeys,
)
) else 0
var skippedDeviceSpecificCount = 0
if (preserveCurrentDeviceSpecificPreferences) {
skippedDeviceSpecificCount += preserveCurrentValues(
restoredBuilder = restoredBuilder,
currentPreferenceMap = currentPreferenceMap,
keys = deviceSpecificPreferenceKeys,
)
skippedDeviceSpecificCount += preserveCurrentPresetDeviceFields(
restoredBuilder = restoredBuilder,
currentPreferenceMap = currentPreferenceMap,
)
if (restoreSettings) {
skippedDeviceSpecificCount += preserveCurrentValues(
restoredBuilder = restoredBuilder,
currentPreferenceMap = currentPreferenceMap,
keys = deviceSpecificPreferenceKeys,
)
}
if (restorePresets) {
skippedDeviceSpecificCount += preserveCurrentPresetDeviceFields(
restoredBuilder = restoredBuilder,
currentPreferenceMap = currentPreferenceMap,
)
}
}
if (
removedCount == 0 &&
currentFilesDir == null &&
!preserveCurrentDeviceSpecificPreferences
!preserveCurrentDeviceSpecificPreferences && restoreSettings && restorePresets
) {
return RestoreResult()
}
@@ -0,0 +1,375 @@
package com.hinnka.mycamera.ui.components
import android.graphics.BlurMaskFilter
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.RenderEffect
import android.graphics.RuntimeShader
import android.graphics.Shader
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
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.drawWithCache
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.geometry.isSpecified
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.PaintingStyle
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.asComposeRenderEffect
import androidx.compose.ui.graphics.drawscope.clipPath
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.layer.GraphicsLayer
import androidx.compose.ui.graphics.layer.drawLayer
import androidx.compose.ui.graphics.rememberGraphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import kotlin.math.ceil
import kotlin.math.floor
/**
* Real-time AndroidLiquidGlass material for Compose UI.
*
* Shares the optical model of [com.hinnka.mycamera.frame.FrameLiquidGlass] (Kyant's rounded-rect SDF
* refraction, vibrancy, 5% surface and directional rim highlight, all with the same parameters), but runs entirely on the RenderThread:
* the backdrop is a [GraphicsLayer] (RenderNode) referenced by the glass layer, and the effect chain
* vibrancy -> blur -> lens is a platform RenderEffect. No pixels are read back to the CPU, and the
* glass node is only re-rendered when its backdrop or geometry changes, not when panel content does.
*
* Capability tiers: API 33+ full lens + highlight; API 31-32 vibrancy with a flat rim;
* API 30 an opaque fallback color without backdrop capture.
*/
@Immutable
data class LiquidGlassStyle(
// Defaults mirror FrameLiquidGlass: pure lens without blur, 24dp edge profile, 48dp displacement.
val blurRadius: Dp = 0.dp,
val refractionHeight: Dp = 24.dp,
val refractionAmount: Dp = 48.dp,
val saturation: Float = 1.5f,
// Upstream glass surface treatment: black at 5%.
val tint: Color = Color(0x0D000000),
// Highlight.Default: .5dp inner stroke, .25dp mask blur, white at .5 alpha, additive.
val highlightWidth: Dp = 0.5.dp,
val highlightBlur: Dp = 0.25.dp,
val highlightAlpha: Float = 0.5f,
val fallbackColor: Color = Color(0xF0141414),
)
/** Backdrop captured by [liquidGlassBackdropSource] and sampled by [LiquidGlassSurface]. */
@Stable
class LiquidGlassBackdrop internal constructor(internal val layer: GraphicsLayer) {
internal var positionInRoot by mutableStateOf(Offset.Unspecified)
internal var size by mutableStateOf(IntSize.Zero)
}
@Composable
fun rememberLiquidGlassBackdrop(): LiquidGlassBackdrop {
val layer = rememberGraphicsLayer()
return remember(layer) { LiquidGlassBackdrop(layer) }
}
/** Records this node's content into [backdrop] while drawing it unchanged. */
fun Modifier.liquidGlassBackdropSource(backdrop: LiquidGlassBackdrop): Modifier {
if (!BACKDROP_SUPPORTED) return this
return this
.onGloballyPositioned {
backdrop.positionInRoot = it.positionInRoot()
backdrop.size = it.size
}
.drawWithContent {
backdrop.layer.record { this@drawWithContent.drawContent() }
drawLayer(backdrop.layer)
}
}
/**
* A rounded-rect glass container. With [openBottomEdge] the shape continues past the bottom bound
* (e.g. a bottom sheet touching the screen edge), so neither refraction nor rim appears there.
*/
@Composable
fun LiquidGlassSurface(
backdrop: LiquidGlassBackdrop,
modifier: Modifier = Modifier,
cornerRadius: Dp = 24.dp,
openBottomEdge: Boolean = false,
style: LiquidGlassStyle = LiquidGlassStyle(),
content: @Composable BoxScope.() -> Unit,
) {
val glassStyle = style
var positionInRoot by remember { mutableStateOf(Offset.Unspecified) }
val shaders = remember { if (LENS_SUPPORTED) GlassShaders() else null }
Box(
modifier = modifier
.onGloballyPositioned { positionInRoot = it.positionInRoot() }
// Like Surface: the panel never lets touches fall through to the content underneath.
.pointerInput(Unit) {}
.drawWithCache {
val width = size.width
val height = size.height
val radius = cornerRadius.toPx().coerceAtMost(minOf(width, height) / 2f)
// Same rounding as FrameLiquidGlass: whole-pixel half width, doubled for the clipped inner stroke.
val highlightStroke = ceil(minOf(style.highlightWidth.toPx(), minOf(width, height) / 2f)) * 2f
val refractionHeight = style.refractionHeight.toPx()
// Extend the geometry below the bounds so its bottom edge stays out of view.
val geometryHeight = if (openBottomEdge) height + refractionHeight + highlightStroke else height
val bottomRadius = if (openBottomEdge) 0f else radius
val outline = Path().apply {
addRoundRect(
RoundRect(
rect = Rect(0f, 0f, width, geometryHeight),
topLeft = CornerRadius(radius),
topRight = CornerRadius(radius),
bottomRight = CornerRadius(bottomRadius),
bottomLeft = CornerRadius(bottomRadius),
)
)
}
val backdropPosition = backdrop.positionInRoot
val backdropSize = backdrop.size
if (!BACKDROP_SUPPORTED) {
return@drawWithCache onDrawBehind {
clipRect { drawPath(outline, style.fallbackColor) }
}
}
if (!positionInRoot.isSpecified || !backdropPosition.isSpecified ||
backdropSize == IntSize.Zero || width <= 0f || height <= 0f
) {
return@drawWithCache onDrawBehind {}
}
// Glass layer covers the surface plus blur padding (the lens only samples inward), limited to the backdrop bounds so
// clamped blur edges come from real content instead of transparent pixels.
val blurRadius = style.blurRadius.toPx()
val padding = blurRadius * 2f
val backdropOrigin = backdropPosition - positionInRoot
val captureRect = Rect(-padding, -padding, width + padding, height + padding)
.intersect(Rect(backdropOrigin, backdropSize.toSize()))
val layerOffset = IntOffset(floor(captureRect.left).toInt(), floor(captureRect.top).toInt())
val layerSize = IntSize(
ceil(captureRect.right).toInt() - layerOffset.x,
ceil(captureRect.bottom).toInt() - layerOffset.y,
)
if (layerSize.width <= 0 || layerSize.height <= 0) {
return@drawWithCache onDrawBehind {}
}
val glassLayer = obtainGraphicsLayer().apply {
topLeft = layerOffset
renderEffect = glassEffect(
style = style,
blurRadius = blurRadius,
refractionHeight = refractionHeight,
refractionAmount = style.refractionAmount.toPx(),
shapeOffset = Offset(-layerOffset.x.toFloat(), -layerOffset.y.toFloat()),
shapeWidth = width,
shapeHeight = geometryHeight,
radius = radius,
bottomRadius = bottomRadius,
shaders = shaders,
).asComposeRenderEffect()
record(size = layerSize) {
translate(backdropOrigin.x - layerOffset.x, backdropOrigin.y - layerOffset.y) {
drawLayer(backdrop.layer)
}
}
}
val highlightPaint = Paint().apply {
this.style = PaintingStyle.Stroke
strokeWidth = highlightStroke
blendMode = BlendMode.Plus
if (shaders != null) {
shaders.setHighlightUniforms(width, geometryHeight, radius, bottomRadius, glassStyle.highlightAlpha)
shader = shaders.highlight
} else {
color = Color.White.copy(alpha = glassStyle.highlightAlpha * 0.3f)
}
val highlightBlur = glassStyle.highlightBlur.toPx()
if (highlightBlur > 0f) {
asFrameworkPaint().maskFilter = BlurMaskFilter(highlightBlur, BlurMaskFilter.Blur.NORMAL)
}
}
onDrawBehind {
clipRect {
clipPath(outline) {
drawLayer(glassLayer)
drawRect(style.tint)
drawIntoCanvas { it.drawPath(outline, highlightPaint) }
}
}
}
},
content = content,
)
}
private fun IntSize.toSize() = androidx.compose.ui.geometry.Size(width.toFloat(), height.toFloat())
@RequiresApi(Build.VERSION_CODES.S)
private fun glassEffect(
style: LiquidGlassStyle,
blurRadius: Float,
refractionHeight: Float,
refractionAmount: Float,
shapeOffset: Offset,
shapeWidth: Float,
shapeHeight: Float,
radius: Float,
bottomRadius: Float,
shaders: GlassShaders?,
): RenderEffect {
// AndroidLiquidGlass vibrancy(): saturation matrix, same as frame_glass/color.frag.
val vibrancy = RenderEffect.createColorFilterEffect(
ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(style.saturation) })
)
val blur = if (blurRadius > 0f) {
RenderEffect.createBlurEffect(blurRadius, blurRadius, vibrancy, Shader.TileMode.CLAMP)
} else {
vibrancy
}
if (shaders == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return blur
return shaders.lensEffect(blur, shapeOffset, shapeWidth, shapeHeight, radius, bottomRadius,
refractionHeight, refractionAmount)
}
/** Compiled once per surface; uniforms are snapshotted when an effect is created or a draw is recorded. */
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private class GlassShaders {
private val lens = RuntimeShader(LENS_SHADER)
val highlight = RuntimeShader(HIGHLIGHT_SHADER)
fun lensEffect(
input: RenderEffect,
shapeOffset: Offset,
width: Float,
height: Float,
radius: Float,
bottomRadius: Float,
refractionHeight: Float,
refractionAmount: Float,
): RenderEffect {
lens.setFloatUniform("shapeOffset", shapeOffset.x, shapeOffset.y)
lens.setFloatUniform("size", width, height)
lens.setFloatUniform("cornerRadii", radius, radius, bottomRadius, bottomRadius)
lens.setFloatUniform("refractionHeight", refractionHeight)
// Negative amount samples inward, matching FrameGlassGpu.setUniforms.
lens.setFloatUniform("refractionAmount", -refractionAmount)
lens.setFloatUniform("depthEffect", 1f)
return RenderEffect.createChainEffect(RenderEffect.createRuntimeShaderEffect(lens, "content"), input)
}
fun setHighlightUniforms(width: Float, height: Float, radius: Float, bottomRadius: Float, alpha: Float) {
highlight.setFloatUniform("size", width, height)
highlight.setFloatUniform("cornerRadii", radius, radius, bottomRadius, bottomRadius)
highlight.setFloatUniform("angle", HIGHLIGHT_ANGLE)
highlight.setFloatUniform("falloff", HIGHLIGHT_FALLOFF)
highlight.setFloatUniform("alpha", alpha)
}
}
private val BACKDROP_SUPPORTED = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
private val LENS_SUPPORTED = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
private const val HIGHLIGHT_ANGLE = 0.7853981633974483f
private const val HIGHLIGHT_FALLOFF = 2f
// AGSL port of Kyant's RoundedRectSDF (see assets/shaders/frame_glass), Apache License 2.0.
private const val SDF_FUNCTIONS = """
float radiusAt(float2 coord, float4 radii) {
if (coord.x >= 0.0) {
return coord.y <= 0.0 ? radii.y : radii.z;
}
return coord.y <= 0.0 ? radii.x : radii.w;
}
float sdRoundedRect(float2 coord, float2 halfSize, float radius) {
float2 cornerCoord = abs(coord) - (halfSize - float2(radius));
float outside = length(max(cornerCoord, 0.0)) - radius;
float inside = min(max(cornerCoord.x, cornerCoord.y), 0.0);
return outside + inside;
}
float2 gradSdRoundedRect(float2 coord, float2 halfSize, float radius) {
float2 cornerCoord = abs(coord) - (halfSize - float2(radius));
if (cornerCoord.x >= 0.0 || cornerCoord.y >= 0.0) {
return sign(coord) * normalize(max(cornerCoord, 0.0));
}
float gradX = step(cornerCoord.y, cornerCoord.x);
return sign(coord) * float2(gradX, 1.0 - gradX);
}
float2 directionOrZero(float2 v) {
float magnitude = length(v);
return magnitude > 0.0 ? v / magnitude : float2(0.0);
}
"""
private const val LENS_SHADER = """
uniform shader content;
uniform float2 shapeOffset;
uniform float2 size;
uniform float4 cornerRadii;
uniform float refractionHeight;
uniform float refractionAmount;
uniform float depthEffect;
$SDF_FUNCTIONS
float circleMap(float x) {
return 1.0 - sqrt(1.0 - x * x);
}
half4 main(float2 fragCoord) {
float2 halfSize = size * 0.5;
float2 centered = fragCoord - shapeOffset - halfSize;
float radius = radiusAt(centered, cornerRadii);
float sd = sdRoundedRect(centered, halfSize, radius);
if (-sd >= refractionHeight) {
return content.eval(fragCoord);
}
sd = min(sd, 0.0);
float d = circleMap(1.0 - -sd / refractionHeight) * refractionAmount;
float gradRadius = min(radius * 1.5, min(halfSize.x, halfSize.y));
float2 grad = gradSdRoundedRect(centered, halfSize, gradRadius);
grad = directionOrZero(grad + depthEffect * directionOrZero(centered));
return content.eval(fragCoord + d * grad);
}
"""
private const val HIGHLIGHT_SHADER = """
uniform float2 size;
uniform float4 cornerRadii;
uniform float angle;
uniform float falloff;
uniform float alpha;
$SDF_FUNCTIONS
half4 main(float2 coord) {
float2 halfSize = size * 0.5;
float2 centered = coord - halfSize;
float radius = radiusAt(centered, cornerRadii);
float gradRadius = min(radius * 1.5, min(halfSize.x, halfSize.y));
float2 grad = gradSdRoundedRect(centered, halfSize, gradRadius);
float2 normal = float2(cos(angle), sin(angle));
float intensity = pow(abs(dot(grad, normal)), falloff);
return half4(intensity * alpha);
}
"""
@@ -0,0 +1,118 @@
package com.hinnka.mycamera.ui.settings
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.hinnka.mycamera.R
import com.hinnka.mycamera.data.BackupCategory
import com.hinnka.mycamera.ui.theme.AccentColor
@Composable
internal fun BackupSelectionDialog(
availableCategories: Set<BackupCategory>,
selectedCategories: Set<BackupCategory>,
onSelectionChange: (Set<BackupCategory>) -> Unit,
onDismiss: () -> Unit,
onConfirm: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
containerColor = Color(0xFF1A1A1A),
title = { Text(stringResource(R.string.backup_select_content), color = Color.White) },
text = {
Column(Modifier.verticalScroll(rememberScrollState())) {
Text(
stringResource(R.string.backup_select_content_description),
color = Color.White.copy(alpha = 0.6f),
fontSize = 13.sp,
)
TextButton(
onClick = { onSelectionChange(availableCategories) },
enabled = selectedCategories != availableCategories,
) {
Text(stringResource(R.string.select_all))
}
BackupCategory.entries.forEach { category ->
val available = category in availableCategories
val checked = category in selectedCategories
Row(
modifier = Modifier
.fillMaxWidth()
.toggleable(
value = checked,
enabled = available,
role = Role.Checkbox,
onValueChange = { selected ->
onSelectionChange(
if (selected) selectedCategories + category
else selectedCategories - category
)
},
)
.padding(vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Checkbox(
checked = checked,
onCheckedChange = null,
enabled = available,
colors = CheckboxDefaults.colors(
checkedColor = AccentColor,
uncheckedColor = Color.White.copy(alpha = 0.6f),
),
)
Column(Modifier.weight(1f).padding(start = 12.dp)) {
Text(
stringResource(category.labelResource),
color = Color.White.copy(alpha = if (available) 1f else 0.4f),
)
if (!available) {
Text(
stringResource(R.string.backup_no_content),
color = Color.White.copy(alpha = 0.4f),
fontSize = 12.sp,
)
}
}
}
}
}
},
confirmButton = {
TextButton(onClick = onConfirm, enabled = selectedCategories.isNotEmpty()) {
Text(stringResource(R.string.backup_continue))
}
},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
},
)
}
private val BackupCategory.labelResource: Int
get() = when (this) {
BackupCategory.SETTINGS -> R.string.backup_category_settings
BackupCategory.PRESETS -> R.string.backup_category_presets
BackupCategory.LUTS -> R.string.backup_category_luts
BackupCategory.FRAMES -> R.string.backup_category_frames
BackupCategory.DCP_PROFILES -> R.string.backup_category_dcps
BackupCategory.RAW_NOISE_PROFILES -> R.string.backup_category_raw_noise
BackupCategory.CAPTURE_SOUNDS -> R.string.backup_category_sounds
}
@@ -113,6 +113,8 @@ import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import com.hinnka.mycamera.BuildConfig
import com.hinnka.mycamera.R
import com.hinnka.mycamera.data.BackupCategory
import com.hinnka.mycamera.data.BackupManager
import com.hinnka.mycamera.camera.AspectRatio
import com.hinnka.mycamera.camera.GridStyle
import com.hinnka.mycamera.camera.CameraInfo
@@ -458,6 +460,10 @@ fun SettingsScreen(
var showExternalLensStabilizationDialog by remember { mutableStateOf(false) }
var showCustomVendorKeysDialog by remember { mutableStateOf(false) }
var backupOperation by remember { mutableStateOf<BackupOperation?>(null) }
var showBackupSelectionDialog by rememberSaveable { mutableStateOf(false) }
var availableBackupCategories by rememberSaveable { mutableStateOf(emptyList<String>()) }
var selectedBackupCategories by rememberSaveable { mutableStateOf(emptyList<String>()) }
var pendingBackupCategories by rememberSaveable { mutableStateOf<List<String>?>(null) }
LaunchedEffect(
rawExposureCompensation,
@@ -603,11 +609,13 @@ fun SettingsScreen(
val backupLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.CreateDocument("application/zip")
) { uri ->
uri?.let {
val categories = pendingBackupCategories?.map(BackupCategory::valueOf)?.toSet()
pendingBackupCategories = null
if (uri != null && !categories.isNullOrEmpty()) {
backupOperation = BackupOperation.BACKUP
coroutineScope.launch {
backupOperation = BackupOperation.BACKUP
try {
val success = com.hinnka.mycamera.data.BackupManager.performBackup(context, it)
val success = BackupManager.performBackup(context, uri, categories)
if (success) {
android.widget.Toast.makeText(context, R.string.backup_success, android.widget.Toast.LENGTH_SHORT).show()
} else {
@@ -2830,9 +2838,16 @@ fun SettingsScreen(
} else {
stringResource(R.string.settings_backup_settings_description)
},
enabled = backupOperation == null,
enabled = backupOperation == null && pendingBackupCategories == null,
showProgress = backupOperation == BackupOperation.BACKUP,
onClick = { backupLauncher.launch("photon_camera_backup_${System.currentTimeMillis()}.zip") }
onClick = {
coroutineScope.launch {
val categories = BackupManager.availableCategories(context).map { it.name }
availableBackupCategories = categories
selectedBackupCategories = categories
showBackupSelectionDialog = true
}
}
)
HorizontalDivider(
@@ -2847,7 +2862,7 @@ fun SettingsScreen(
} else {
stringResource(R.string.settings_restore_settings_description)
},
enabled = backupOperation == null,
enabled = backupOperation == null && pendingBackupCategories == null,
showProgress = backupOperation == BackupOperation.RESTORE,
onClick = { restoreLauncher.launch("*/*") }
)
@@ -3021,6 +3036,20 @@ fun SettingsScreen(
}
}
if (showBackupSelectionDialog) {
BackupSelectionDialog(
availableCategories = availableBackupCategories.map(BackupCategory::valueOf).toSet(),
selectedCategories = selectedBackupCategories.map(BackupCategory::valueOf).toSet(),
onSelectionChange = { selectedBackupCategories = it.map { category -> category.name } },
onDismiss = { showBackupSelectionDialog = false },
onConfirm = {
pendingBackupCategories = selectedBackupCategories.toList()
showBackupSelectionDialog = false
backupLauncher.launch("photon_camera_backup_${System.currentTimeMillis()}.zip")
},
)
}
// 显示日志查看器弹窗
if (showLogViewerDialog) {
LogViewerDialog(
@@ -596,6 +596,17 @@
<string name="settings_restore_settings">還原設定</string>
<string name="settings_restore_settings_description">從之前的備份 ZIP 檔案中還原。應用可能需要重啟才能生效。</string>
<string name="backup_success">備份成功</string>
<string name="backup_select_content">選擇備份內容</string>
<string name="backup_select_content_description">請至少選擇一項。首選項和預設可分別備份,所需的自訂資源請一併勾選。</string>
<string name="backup_category_settings">首選項</string>
<string name="backup_category_presets">預設</string>
<string name="backup_category_luts">自訂 LUT 與分類</string>
<string name="backup_category_frames">自訂邊框、字型與 Logo</string>
<string name="backup_category_dcps">自訂 DCP 配置</string>
<string name="backup_category_raw_noise">自訂 RAW 噪聲配置</string>
<string name="backup_category_sounds">自訂快門聲音</string>
<string name="backup_no_content">暫無可備份內容</string>
<string name="backup_continue">選擇儲存位置</string>
<string name="backup_failed">備份失敗</string>
<string name="backup_in_progress">正在備份設定和自訂內容...</string>
<string name="restore_success">還原成功,請重新啟動應用。</string>
@@ -617,6 +617,17 @@
<string name="settings_restore_settings">恢复设置</string>
<string name="settings_restore_settings_description">从之前的备份 ZIP 文件中恢复。应用可能需要重启才能生效。</string>
<string name="backup_success">备份成功</string>
<string name="backup_select_content">选择备份内容</string>
<string name="backup_select_content_description">请至少选择一项。首选项和预设可分别备份,所需的自定义资源请一并勾选。</string>
<string name="backup_category_settings">首选项</string>
<string name="backup_category_presets">预设</string>
<string name="backup_category_luts">自定义 LUT 与分类</string>
<string name="backup_category_frames">自定义边框、字体与 Logo</string>
<string name="backup_category_dcps">自定义 DCP 配置</string>
<string name="backup_category_raw_noise">自定义 RAW 噪声配置</string>
<string name="backup_category_sounds">自定义快门声音</string>
<string name="backup_no_content">暂无可备份内容</string>
<string name="backup_continue">选择保存位置</string>
<string name="backup_failed">备份失败</string>
<string name="backup_in_progress">正在备份设置和自定义内容...</string>
<string name="restore_success">恢复成功,请重新启动应用。</string>
@@ -596,6 +596,17 @@
<string name="settings_restore_settings">還原設定</string>
<string name="settings_restore_settings_description">從之前的備份 ZIP 檔案中還原。應用可能需要重啟才能生效。</string>
<string name="backup_success">備份成功</string>
<string name="backup_select_content">選擇備份內容</string>
<string name="backup_select_content_description">請至少選擇一項。首選項和預設可分別備份,所需的自訂資源請一併勾選。</string>
<string name="backup_category_settings">首選項</string>
<string name="backup_category_presets">預設</string>
<string name="backup_category_luts">自訂 LUT 與分類</string>
<string name="backup_category_frames">自訂邊框、字型與 Logo</string>
<string name="backup_category_dcps">自訂 DCP 配置</string>
<string name="backup_category_raw_noise">自訂 RAW 噪聲配置</string>
<string name="backup_category_sounds">自訂快門聲音</string>
<string name="backup_no_content">暫無可備份內容</string>
<string name="backup_continue">選擇儲存位置</string>
<string name="backup_failed">備份失敗</string>
<string name="backup_in_progress">正在備份設定和自訂內容...</string>
<string name="restore_success">還原成功,請重新啟動應用。</string>
@@ -596,6 +596,17 @@
<string name="settings_restore_settings">還原設定</string>
<string name="settings_restore_settings_description">從之前的備份 ZIP 檔案中還原。應用可能需要重啟才能生效。</string>
<string name="backup_success">備份成功</string>
<string name="backup_select_content">選擇備份內容</string>
<string name="backup_select_content_description">請至少選擇一項。首選項和預設可分別備份,所需的自訂資源請一併勾選。</string>
<string name="backup_category_settings">首選項</string>
<string name="backup_category_presets">預設</string>
<string name="backup_category_luts">自訂 LUT 與分類</string>
<string name="backup_category_frames">自訂邊框、字型與 Logo</string>
<string name="backup_category_dcps">自訂 DCP 配置</string>
<string name="backup_category_raw_noise">自訂 RAW 噪聲配置</string>
<string name="backup_category_sounds">自訂快門聲音</string>
<string name="backup_no_content">暫無可備份內容</string>
<string name="backup_continue">選擇儲存位置</string>
<string name="backup_failed">備份失敗</string>
<string name="backup_in_progress">正在備份設定和自訂內容...</string>
<string name="restore_success">還原成功,請重新啟動應用。</string>
+11
View File
@@ -639,6 +639,17 @@
<string name="settings_restore_settings">Restore Settings</string>
<string name="settings_restore_settings_description">Restore from a previous backup ZIP file. App may require a restart to apply.</string>
<string name="backup_success">Backup completed successfully</string>
<string name="backup_select_content">Choose backup contents</string>
<string name="backup_select_content_description">Choose at least one category. Preferences and presets can be backed up separately; select any custom resources they need as well.</string>
<string name="backup_category_settings">Preferences</string>
<string name="backup_category_presets">Presets</string>
<string name="backup_category_luts">Custom LUTs and categories</string>
<string name="backup_category_frames">Custom frames, fonts and logos</string>
<string name="backup_category_dcps">Custom DCP profiles</string>
<string name="backup_category_raw_noise">Custom RAW noise profiles</string>
<string name="backup_category_sounds">Custom shutter sounds</string>
<string name="backup_no_content">No content to back up</string>
<string name="backup_continue">Choose save location</string>
<string name="backup_failed">Backup failed</string>
<string name="backup_in_progress">Backing up settings and custom content...</string>
<string name="restore_success">Restore completed successfully. Please restart the app.</string>