From 8e9341798ea2ce40dab84a8589a5dca96461930f Mon Sep 17 00:00:00 2001 From: zhoubinjia Date: Tue, 13 Jan 2026 18:16:22 +0800 Subject: [PATCH] feat: custom import --- .../hinnka/mycamera/data/ContentRepository.kt | 81 ++++ .../mycamera/data/CustomImportManager.kt | 350 ++++++++++++++++++ .../com/hinnka/mycamera/lut/LutConverter.kt | 196 ++++++++++ .../com/hinnka/mycamera/lut/LutManager.kt | 56 ++- .../mycamera/ui/components/LutSelector.kt | 23 ++ .../mycamera/ui/gallery/PhotoEditScreen.kt | 27 +- .../ui/settings/CustomImportSection.kt | 335 +++++++++++++++++ .../mycamera/ui/settings/SettingsScreen.kt | 10 + .../mycamera/viewmodel/CameraViewModel.kt | 73 +++- .../mycamera/viewmodel/GalleryViewModel.kt | 70 +++- app/src/main/res/values-zh/strings.xml | 35 +- app/src/main/res/values/strings.xml | 14 + 12 files changed, 1206 insertions(+), 64 deletions(-) create mode 100644 app/src/main/java/com/hinnka/mycamera/data/ContentRepository.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/data/CustomImportManager.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/lut/LutConverter.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/ui/settings/CustomImportSection.kt diff --git a/app/src/main/java/com/hinnka/mycamera/data/ContentRepository.kt b/app/src/main/java/com/hinnka/mycamera/data/ContentRepository.kt new file mode 100644 index 00000000..555a6fe0 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/data/ContentRepository.kt @@ -0,0 +1,81 @@ +package com.hinnka.mycamera.data + +import android.content.Context +import com.hinnka.mycamera.frame.FrameInfo +import com.hinnka.mycamera.frame.FrameManager +import com.hinnka.mycamera.lut.LutInfo +import com.hinnka.mycamera.lut.LutManager +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +/** + * 内容仓库 - 单例模式 + * + * 统一管理 LUT 和 Frame 的加载,避免重复创建实例 + * CameraViewModel 和 GalleryViewModel 共享同一个实例 + * 使用 StateFlow 实现响应式更新 + */ +class ContentRepository private constructor(context: Context) { + + companion object { + @Volatile + private var INSTANCE: ContentRepository? = null + + fun getInstance(context: Context): ContentRepository { + return INSTANCE ?: synchronized(this) { + INSTANCE ?: ContentRepository(context.applicationContext).also { + INSTANCE = it + } + } + } + } + + private val appContext = context.applicationContext + val lutManager = LutManager(appContext) + val frameManager = FrameManager(appContext) + private val customImportManager = CustomImportManager(appContext) + + // 使用 StateFlow 存储可用内容列表,支持响应式更新 + private val _availableLuts = MutableStateFlow>(emptyList()) + val availableLuts: StateFlow> = _availableLuts.asStateFlow() + + private val _availableFrames = MutableStateFlow>(emptyList()) + val availableFrames: StateFlow> = _availableFrames.asStateFlow() + + /** + * 初始化内容 + */ + fun initialize() { + lutManager.initialize() + frameManager.initialize() + _availableLuts.value = lutManager.getAvailableLuts() + _availableFrames.value = frameManager.getAvailableFrames() + } + + /** + * 获取可用 LUT 列表(用于一次性获取) + */ + fun getAvailableLuts(): List = _availableLuts.value + + /** + * 获取可用边框列表(用于一次性获取) + */ + fun getAvailableFrames(): List = _availableFrames.value + + /** + * 获取自定义导入管理器 + */ + fun getCustomImportManager(): CustomImportManager = customImportManager + + /** + * 刷新自定义内容 + * 更新后会自动通知所有订阅者 + */ + fun refreshCustomContent() { + lutManager.initialize() + frameManager.initialize() + _availableLuts.value = lutManager.getAvailableLuts() + _availableFrames.value = frameManager.getAvailableFrames() + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/data/CustomImportManager.kt b/app/src/main/java/com/hinnka/mycamera/data/CustomImportManager.kt new file mode 100644 index 00000000..ed95572d --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/data/CustomImportManager.kt @@ -0,0 +1,350 @@ +package com.hinnka.mycamera.data + +import android.content.Context +import android.net.Uri +import android.util.Log +import com.hinnka.mycamera.lut.LutConverter +import com.hinnka.mycamera.lut.LutInfo +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.io.FileOutputStream +import java.util.UUID + +/** + * 自定义导入管理器 + * + * 管理用户导入的自定义 LUT 和边框样式 + */ +class CustomImportManager(private val context: Context) { + + companion object { + private const val TAG = "CustomImportManager" + + // 自定义LUT目录 + private const val CUSTOM_LUT_DIR = "custom_luts" + + // 自定义边框目录 + private const val CUSTOM_FRAME_DIR = "custom_frames" + + // 配置文件 + private const val CUSTOM_LUT_CONFIG = "custom_luts.json" + private const val CUSTOM_FRAME_CONFIG = "custom_frames.json" + } + + private val customLutDir: File + get() = File(context.filesDir, CUSTOM_LUT_DIR).apply { mkdirs() } + + private val customFrameDir: File + get() = File(context.filesDir, CUSTOM_FRAME_DIR).apply { mkdirs() } + + /** + * 导入 LUT 文件 (.cube) + * + * @param uri 选择的 .cube 文件 URI + * @param displayName 用户自定义的显示名称(可选) + * @return 导入成功的 LUT ID,失败返回 null + */ + fun importLut(uri: Uri, displayName: String? = null): String? { + return try { + val fileName = getFileName(uri) ?: "lut_${System.currentTimeMillis()}.cube" + val lutId = "custom_${UUID.randomUUID()}" + val plutFileName = "$lutId.plut" + val plutFile = File(customLutDir, plutFileName) + + // 读取 .cube 文件并转换为 .plut + context.contentResolver.openInputStream(uri)?.use { inputStream -> + FileOutputStream(plutFile).use { outputStream -> + val success = LutConverter.convertCubeToplut(inputStream, outputStream) + + if (!success) { + plutFile.delete() + return null + } + } + } ?: return null + + // 生成显示名称 + val name = displayName ?: fileName.substringBeforeLast('.') + + // 保存到配置文件 + saveLutToConfig(lutId, name, plutFileName) + + Log.d(TAG, "LUT imported successfully: $lutId ($name)") + lutId + } catch (e: Exception) { + Log.e(TAG, "Failed to import LUT", e) + null + } + } + + /** + * 导入边框样式文件 + * + * @param uri 选择的边框配置文件 URI (JSON) + * @return 导入成功的边框 ID,失败返回 null + */ + fun importFrame(uri: Uri): String? { + return try { + val frameId = "custom_${UUID.randomUUID()}" + val frameConfigFile = File(customFrameDir, "$frameId.json") + + // 复制配置文件 + context.contentResolver.openInputStream(uri)?.use { inputStream -> + FileOutputStream(frameConfigFile).use { outputStream -> + inputStream.copyTo(outputStream) + } + } ?: return null + + // 验证并解析配置 + val configJson = frameConfigFile.readText() + val frameConfig = JSONObject(configJson) + + // 提取边框名称 + val nameObj = frameConfig.getJSONObject("name") + val nameMap = mutableMapOf() + nameObj.keys().forEach { lang -> + nameMap[lang] = nameObj.getString(lang) + } + + // 保存到配置文件 + saveFrameToConfig(frameId, nameMap, "$frameId.json") + + Log.d(TAG, "Frame imported successfully: $frameId") + frameId + } catch (e: Exception) { + Log.e(TAG, "Failed to import frame", e) + null + } + } + + /** + * 获取所有自定义 LUT + */ + fun getCustomLuts(): List { + return try { + val configFile = File(context.filesDir, CUSTOM_LUT_CONFIG) + if (!configFile.exists()) { + return emptyList() + } + + val configJson = configFile.readText() + val jsonArray = JSONArray(configJson) + + val lutList = mutableListOf() + for (i in 0 until jsonArray.length()) { + val lutObj = jsonArray.getJSONObject(i) + val id = lutObj.getString("id") + val nameObj = lutObj.getJSONObject("name") + val fileName = lutObj.getString("fileName") + + // 检查文件是否存在 + val lutFile = File(customLutDir, fileName) + if (!lutFile.exists()) { + continue + } + + val nameMap = mutableMapOf() + nameObj.keys().forEach { lang -> + nameMap[lang] = nameObj.getString(lang) + } + + lutList.add( + LutInfo( + id = id, + nameMap = nameMap, + fileName = lutFile.absolutePath, + isBuiltIn = false, + isDefault = false, + isVip = false + ) + ) + } + + lutList + } catch (e: Exception) { + Log.e(TAG, "Failed to load custom LUTs", e) + emptyList() + } + } + + /** + * 获取所有自定义边框 + */ + fun getCustomFrames(): List { + return try { + val configFile = File(context.filesDir, CUSTOM_FRAME_CONFIG) + if (!configFile.exists()) { + return emptyList() + } + + val configJson = configFile.readText() + val jsonArray = JSONArray(configJson) + + val frameList = mutableListOf() + for (i in 0 until jsonArray.length()) { + val frameObj = jsonArray.getJSONObject(i) + val id = frameObj.getString("id") + val nameObj = frameObj.getJSONObject("name") + + val nameMap = mutableMapOf() + nameObj.keys().forEach { lang -> + nameMap[lang] = nameObj.getString(lang) + } + + frameList.add( + com.hinnka.mycamera.frame.FrameInfo( + id = id, + nameMap = nameMap, + previewResId = 0, + isBuiltIn = false + ) + ) + } + + frameList + } catch (e: Exception) { + Log.e(TAG, "Failed to load custom frames", e) + emptyList() + } + } + + /** + * 删除自定义 LUT + */ + fun deleteCustomLut(lutId: String): Boolean { + return try { + // 从配置文件中移除 + val configFile = File(context.filesDir, CUSTOM_LUT_CONFIG) + if (configFile.exists()) { + val configJson = configFile.readText() + val jsonArray = JSONArray(configJson) + val newArray = JSONArray() + + var fileName: String? = null + for (i in 0 until jsonArray.length()) { + val lutObj = jsonArray.getJSONObject(i) + if (lutObj.getString("id") == lutId) { + fileName = lutObj.getString("fileName") + } else { + newArray.put(lutObj) + } + } + + configFile.writeText(newArray.toString()) + + // 删除文件 + fileName?.let { + File(customLutDir, it).delete() + } + } + + true + } catch (e: Exception) { + Log.e(TAG, "Failed to delete custom LUT", e) + false + } + } + + /** + * 删除自定义边框 + */ + fun deleteCustomFrame(frameId: String): Boolean { + return try { + val configFile = File(context.filesDir, CUSTOM_FRAME_CONFIG) + if (configFile.exists()) { + val configJson = configFile.readText() + val jsonArray = JSONArray(configJson) + val newArray = JSONArray() + + var fileName: String? = null + for (i in 0 until jsonArray.length()) { + val frameObj = jsonArray.getJSONObject(i) + if (frameObj.getString("id") == frameId) { + fileName = frameObj.getString("fileName") + } else { + newArray.put(frameObj) + } + } + + configFile.writeText(newArray.toString()) + + // 删除文件 + fileName?.let { + File(customFrameDir, it).delete() + } + } + + true + } catch (e: Exception) { + Log.e(TAG, "Failed to delete custom frame", e) + false + } + } + + /** + * 保存 LUT 到配置文件 + */ + private fun saveLutToConfig(lutId: String, name: String, fileName: String) { + val configFile = File(context.filesDir, CUSTOM_LUT_CONFIG) + + val jsonArray = if (configFile.exists()) { + JSONArray(configFile.readText()) + } else { + JSONArray() + } + + val lutObj = JSONObject().apply { + put("id", lutId) + put("name", JSONObject().apply { + put("en", name) + put("zh", name) + }) + put("fileName", fileName) + } + + jsonArray.put(lutObj) + configFile.writeText(jsonArray.toString()) + } + + /** + * 保存边框到配置文件 + */ + private fun saveFrameToConfig(frameId: String, nameMap: Map, fileName: String) { + val configFile = File(context.filesDir, CUSTOM_FRAME_CONFIG) + + val jsonArray = if (configFile.exists()) { + JSONArray(configFile.readText()) + } else { + JSONArray() + } + + val frameObj = JSONObject().apply { + put("id", frameId) + put("name", JSONObject().apply { + nameMap.forEach { (lang, name) -> + put(lang, name) + } + }) + put("fileName", fileName) + } + + jsonArray.put(frameObj) + configFile.writeText(jsonArray.toString()) + } + + /** + * 从 URI 获取文件名 + */ + private fun getFileName(uri: Uri): String? { + return try { + context.contentResolver.query(uri, null, null, null, null)?.use { cursor -> + val nameIndex = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME) + cursor.moveToFirst() + cursor.getString(nameIndex) + } + } catch (e: Exception) { + null + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/LutConverter.kt b/app/src/main/java/com/hinnka/mycamera/lut/LutConverter.kt new file mode 100644 index 00000000..6771b86d --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/lut/LutConverter.kt @@ -0,0 +1,196 @@ +package com.hinnka.mycamera.lut + +import java.io.InputStream +import java.io.OutputStream +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.max +import kotlin.math.min + +/** + * LUT 转换器 + * + * 将 .cube 文件转换为专用的 .plut 格式 + * 参考: scripts/convert_luts.py + */ +object LutConverter { + + private const val MAGIC_PLUT = "PLUT" + private const val VERSION = 1 + private const val DATA_TYPE_UINT8 = 0 + + /** + * 将 .cube 文件转换为 .plut 格式 + * + * PLUT 格式: + * - Magic: 'PLUT' (4 bytes) + * - Version: 1 (uint32) + * - Size: Dimension of the 3D LUT, e.g., 32 (uint32) + * - Data Type: 0 for UINT8 RGB, 1 for FLOAT32 RGB (uint32) + * - Payload: Raw RGB data + * + * @param cubeInputStream .cube 文件输入流 + * @param plutOutputStream .plut 文件输出流 + * @return true if conversion succeeded + */ + fun convertCubeToplut( + cubeInputStream: InputStream, + plutOutputStream: OutputStream + ): Boolean { + return try { + // 解析 .cube 文件 + val cubeData = parseCubeFile(cubeInputStream) + + // 写入 .plut 格式 + writePLutFile(cubeData, plutOutputStream) + + true + } catch (e: Exception) { + e.printStackTrace() + false + } + } + + /** + * 解析 .cube 文件 + */ + private fun parseCubeFile(inputStream: InputStream): CubeData { + val lines = try { + inputStream.bufferedReader(Charsets.UTF_8).readLines() + } catch (e: Exception) { + // 尝试 latin-1 编码 + inputStream.bufferedReader(Charsets.ISO_8859_1).readLines() + } + + var size = 0 + var domainMin = floatArrayOf(0f, 0f, 0f) + var domainMax = floatArrayOf(1f, 1f, 1f) + val data = mutableListOf() + + for (line in lines) { + val trimmed = line.trim() + + // 跳过空行和注释 + if (trimmed.isEmpty() || trimmed.startsWith('#')) { + continue + } + + when { + trimmed.startsWith("LUT_3D_SIZE") -> { + size = trimmed.split("\\s+".toRegex())[1].toInt() + } + trimmed.startsWith("DOMAIN_MIN") -> { + val values = trimmed.split("\\s+".toRegex()).drop(1) + domainMin = floatArrayOf( + values[0].toFloat(), + values[1].toFloat(), + values[2].toFloat() + ) + } + trimmed.startsWith("DOMAIN_MAX") -> { + val values = trimmed.split("\\s+".toRegex()).drop(1) + domainMax = floatArrayOf( + values[0].toFloat(), + values[1].toFloat(), + values[2].toFloat() + ) + } + else -> { + // 尝试解析 RGB 数据 + val parts = trimmed.split("\\s+".toRegex()) + if (parts.size == 3) { + try { + val rgb = floatArrayOf( + parts[0].toFloat(), + parts[1].toFloat(), + parts[2].toFloat() + ) + + // 归一化到 [0, 1] 并转换为 uint8 + for (i in 0..2) { + var value = (rgb[i] - domainMin[i]) / (domainMax[i] - domainMin[i]) + value = max(0f, min(1f, value)) + // 转换为 0-255 + data.add((value * 255f + 0.5f).toInt().toByte()) + } + } catch (e: NumberFormatException) { + // 忽略无法解析的行 + } + } + } + } + } + + if (size == 0) { + throw IllegalArgumentException("Could not find LUT_3D_SIZE in .cube file") + } + + val expectedCount = size * size * size * 3 + if (data.size != expectedCount) { + // 补齐或截断数据 + if (data.size < expectedCount) { + repeat(expectedCount - data.size) { + data.add(0) + } + } else { + while (data.size > expectedCount) { + data.removeAt(data.lastIndex) + } + } + } + + return CubeData(size, data.toByteArray()) + } + + /** + * 写入 .plut 文件 + */ + private fun writePLutFile(cubeData: CubeData, outputStream: OutputStream) { + val buffer = ByteBuffer.allocate(16 + cubeData.data.size) + .order(ByteOrder.LITTLE_ENDIAN) + + // Magic + buffer.put(MAGIC_PLUT.toByteArray(Charsets.US_ASCII)) + + // Version + buffer.putInt(VERSION) + + // Size + buffer.putInt(cubeData.size) + + // Data Type (0 = UINT8) + buffer.putInt(DATA_TYPE_UINT8) + + // Data + buffer.put(cubeData.data) + + outputStream.write(buffer.array()) + outputStream.flush() + } + + /** + * .cube 数据 + */ + private data class CubeData( + val size: Int, + val data: ByteArray + ) { + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as CubeData + + if (size != other.size) return false + if (!data.contentEquals(other.data)) return false + + return true + } + + override fun hashCode(): Int { + var result = size + result = 31 * result + data.contentHashCode() + return result + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/LutManager.kt b/app/src/main/java/com/hinnka/mycamera/lut/LutManager.kt index ae2743ed..2104edd9 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/LutManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/LutManager.kt @@ -3,40 +3,49 @@ package com.hinnka.mycamera.lut import android.content.Context import android.util.Log import android.util.LruCache +import com.hinnka.mycamera.data.CustomImportManager /** * LUT 管理器 - * + * * 负责 LUT 的加载、缓存和管理 */ class LutManager(private val context: Context) { - + companion object { private const val TAG = "LutManager" - + // LUT 缓存大小(最多缓存 5 个 LUT) private const val CACHE_SIZE = 5 - + // 内置 LUT 目录 private const val BUILT_IN_LUT_FOLDER = "luts" } - + // LUT 缓存 private val lutCache = LruCache(CACHE_SIZE) - + // 可用 LUT 列表 private var availableLuts: List = emptyList() - + + // 自定义导入管理器 + private val customImportManager = CustomImportManager(context) + /** - * 初始化,扫描可用的 LUT 文件 + * 初始化,扫描可用的 LUT 文件(包括内置和自定义) */ fun initialize() { - availableLuts = LutParser.listAvailableLuts(context, BUILT_IN_LUT_FOLDER) - Log.d(TAG, "Found ${availableLuts.size} LUT files") + val builtInLuts = LutParser.listAvailableLuts(context, BUILT_IN_LUT_FOLDER) + val customLuts = customImportManager.getCustomLuts() + + // 将自定义 LUT 放在最前面 + availableLuts = customLuts + builtInLuts + + Log.d(TAG, "Found ${availableLuts.size} LUT files (${customLuts.size} custom, ${builtInLuts.size} built-in)") } - + /** - * 获取可用的 LUT 列表 + * 获取可用的 LUT 列表(自定义 LUT 在前) */ fun getAvailableLuts(): List = availableLuts @@ -49,7 +58,7 @@ class LutManager(private val context: Context) { /** * 加载 LUT 配置 - * + * * @param id LUT ID * @return LUT 配置,如果加载失败返回 null */ @@ -59,17 +68,25 @@ class LutManager(private val context: Context) { Log.d(TAG, "LUT loaded from cache: $id") return it } - + // 查找 LUT 信息 val lutInfo = getLutInfo(id) ?: run { Log.e(TAG, "LUT not found: $id") return null } - + // 从文件加载 return try { - val lutConfig = LutParser.parseFromAssets(context, lutInfo.fileName) - + val lutConfig = if (lutInfo.isBuiltIn) { + // 内置 LUT 从 assets 加载 + LutParser.parseFromAssets(context, lutInfo.fileName) + } else { + // 自定义 LUT 从文件系统加载 + java.io.File(lutInfo.fileName).inputStream().use { inputStream -> + LutParser.parse(inputStream, lutInfo.getName()) + } + } + if (lutConfig.isValid()) { // 添加到缓存 lutCache.put(id, lutConfig) @@ -84,6 +101,11 @@ class LutManager(private val context: Context) { null } } + + /** + * 获取自定义导入管理器 + */ + fun getCustomImportManager(): CustomImportManager = customImportManager /** * 预加载 LUT diff --git a/app/src/main/java/com/hinnka/mycamera/ui/components/LutSelector.kt b/app/src/main/java/com/hinnka/mycamera/ui/components/LutSelector.kt index 94691297..04cdebfb 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/components/LutSelector.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/components/LutSelector.kt @@ -78,6 +78,7 @@ fun LutSelector( previewBitmap = lutPreviewBitmaps[lut.id], isSelected = currentLutId == lut.id, isVip = lut.isVip, + isCustom = !lut.isBuiltIn, // 添加自定义标识 onClick = { onLutSelected(lut.id) } ) } @@ -95,6 +96,7 @@ private fun LutItem( isVip: Boolean, onClick: () -> Unit, isNone: Boolean = false, + isCustom: Boolean = false, // 添加自定义标识参数 modifier: Modifier = Modifier ) { val backgroundColor = if (isSelected) { @@ -203,6 +205,27 @@ private fun LutItem( ) } } + + // 自定义标识 + if (isCustom) { + Box( + modifier = Modifier + .align(Alignment.TopStart) + .background( + color = Color(0xFF4CAF50), // 绿色表示自定义 + shape = RoundedCornerShape(bottomEnd = 4.dp) + ) + .padding(horizontal = 4.dp, vertical = 2.dp) + ) { + Text( + text = stringResource(R.string.custom_tag), + color = Color.White, + fontSize = 8.sp, + fontWeight = FontWeight.Bold, + lineHeight = 8.sp + ) + } + } } Spacer(modifier = Modifier.height(4.dp)) diff --git a/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt index 85dd54c4..426d6d24 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt @@ -283,6 +283,7 @@ fun PhotoEditScreen( previewBitmap = lutPreviews.getOrNull(index), isSelected = editLutId == lut.id, isVip = lut.isVip, + isCustom = !lut.isBuiltIn, // 添加自定义标识 onClick = { viewModel.setEditLut(lut.id) } ) } @@ -338,15 +339,17 @@ fun PhotoEditScreen( LutOption( name = stringResource(R.string.none), isSelected = editFrameId == null, + isCustom = false, // 无边框不是自定义 onClick = { viewModel.setEditFrame(null) } ) } - + // 边框选项 items(availableFrames) { frame -> LutOption( name = frame.name, isSelected = editFrameId == frame.id, + isCustom = !frame.isBuiltIn, // 添加自定义标识 onClick = { viewModel.setEditFrame(frame.id) } ) } @@ -423,6 +426,7 @@ private fun LutOption( previewBitmap: Bitmap? = null, isSelected: Boolean, isVip: Boolean = false, + isCustom: Boolean = false, // 添加自定义标识参数 onClick: () -> Unit ) { Column( @@ -479,6 +483,27 @@ private fun LutOption( ) } } + + // 自定义标识 + if (isCustom) { + Box( + modifier = Modifier + .align(Alignment.TopStart) + .background( + color = Color(0xFF4CAF50), // 绿色表示自定义 + shape = RoundedCornerShape(bottomEnd = 4.dp) + ) + .padding(horizontal = 4.dp, vertical = 2.dp) + ) { + Text( + text = stringResource(R.string.custom_tag), + color = Color.White, + fontSize = 8.sp, + fontWeight = FontWeight.Bold, + lineHeight = 8.sp + ) + } + } } Spacer(modifier = Modifier.height(4.dp)) diff --git a/app/src/main/java/com/hinnka/mycamera/ui/settings/CustomImportSection.kt b/app/src/main/java/com/hinnka/mycamera/ui/settings/CustomImportSection.kt new file mode 100644 index 00000000..f7a01550 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/ui/settings/CustomImportSection.kt @@ -0,0 +1,335 @@ +package com.hinnka.mycamera.ui.settings + +import android.net.Uri +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material3.* +import androidx.compose.runtime.* +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.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.hinnka.mycamera.R +import com.hinnka.mycamera.data.CustomImportManager +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * 自定义导入设置组件 + * + * 提供 LUT 和边框样式的导入功能 + */ +@Composable +fun CustomImportSection( + customImportManager: CustomImportManager, + onImportSuccess: () -> Unit, + modifier: Modifier = Modifier +) { + var importResult by remember { mutableStateOf(null) } + var customLuts by remember { mutableStateOf(customImportManager.getCustomLuts()) } + var customFrames by remember { mutableStateOf(customImportManager.getCustomFrames()) } + var isImporting by remember { mutableStateOf(false) } // 添加导入中状态 + val scope = rememberCoroutineScope() + + // 刷新自定义内容列表 + fun refreshCustomContent() { + customLuts = customImportManager.getCustomLuts() + customFrames = customImportManager.getCustomFrames() + onImportSuccess() + } + + // LUT 文件选择器 + val lutLauncher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.GetContent() + ) { uri: Uri? -> + scope.launch { + uri?.let { + isImporting = true // 开始导入 + val result = withContext(Dispatchers.IO) { + customImportManager.importLut(it) + } + isImporting = false // 导入完成 + importResult = if (result != null) { + refreshCustomContent() + "LUT 导入成功" + } else { + "LUT 导入失败" + } + } + } + } + + // 边框样式文件选择器 + val frameLauncher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.GetContent() + ) { uri: Uri? -> + scope.launch { + uri?.let { + isImporting = true // 开始导入 + val result = withContext(Dispatchers.IO) { + customImportManager.importFrame(it) + } + isImporting = false // 导入完成 + importResult = if (result != null) { + refreshCustomContent() + "边框样式导入成功" + } else { + "边框样式导入失败" + } + } + } + } + + Column(modifier = modifier.fillMaxWidth()) { + Text( + text = stringResource(R.string.settings_custom_import), + color = Color.White, + fontSize = 16.sp, + fontWeight = FontWeight.Normal, + modifier = Modifier.padding(bottom = 12.dp) + ) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp) + ) { + // 导入 LUT 按钮 + ImportButton( + text = stringResource(R.string.import_lut), + onClick = { lutLauncher.launch("*/*") }, + enabled = !isImporting, // 导入时禁用 + modifier = Modifier.weight(1f) + ) + + // 导入边框样式按钮 + ImportButton( + text = stringResource(R.string.import_frame), + onClick = { frameLauncher.launch("application/json") }, + enabled = !isImporting, // 导入时禁用 + modifier = Modifier.weight(1f) + ) + } + + // 显示导入中状态 + if (isImporting) { + Spacer(modifier = Modifier.height(12.dp)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.Center, + verticalAlignment = Alignment.CenterVertically + ) { + CircularProgressIndicator( + modifier = Modifier.size(20.dp), + color = Color(0xFFFF6B35), + strokeWidth = 2.dp + ) + Spacer(modifier = Modifier.width(12.dp)) + Text( + text = stringResource(R.string.importing), + color = Color.White.copy(alpha = 0.8f), + fontSize = 13.sp + ) + } + } + + // 显示导入结果 + importResult?.let { result -> + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = result, + color = if (result.contains("成功")) Color(0xFF4CAF50) else Color(0xFFFF5252), + fontSize = 12.sp, + modifier = Modifier.padding(top = 4.dp) + ) + LaunchedEffect(result) { + kotlinx.coroutines.delay(3000) + importResult = null + } + } + + Spacer(modifier = Modifier.height(12.dp)) + + Text( + text = stringResource(R.string.settings_import_description), + color = Color.White.copy(alpha = 0.6f), + fontSize = 13.sp + ) + + // 已导入内容管理 + if (customLuts.isNotEmpty() || customFrames.isNotEmpty()) { + Spacer(modifier = Modifier.height(20.dp)) + + Text( + text = stringResource(R.string.custom_content_management), + color = Color.White, + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + modifier = Modifier.padding(bottom = 8.dp) + ) + + // 自定义 LUT 列表 + customLuts.forEach { lut -> + CustomContentItem( + name = lut.getName(), + type = stringResource(R.string.lut_type), + onDelete = { + scope.launch { + withContext(Dispatchers.IO) { + customImportManager.deleteCustomLut(lut.id) + } + importResult = "已删除: ${lut.getName()}" + refreshCustomContent() + } + } + ) + Spacer(modifier = Modifier.height(8.dp)) + } + + // 自定义边框列表 + customFrames.forEach { frame -> + CustomContentItem( + name = frame.name, + type = stringResource(R.string.frame_type), + onDelete = { + scope.launch { + withContext(Dispatchers.IO) { + customImportManager.deleteCustomFrame(frame.id) + } + importResult = "已删除: ${frame.name}" + refreshCustomContent() + } + } + ) + Spacer(modifier = Modifier.height(8.dp)) + } + } + } +} + +/** + * 自定义内容项 + */ +@Composable +private fun CustomContentItem( + name: String, + type: String, + onDelete: () -> Unit, + modifier: Modifier = Modifier +) { + var showDeleteDialog by remember { mutableStateOf(false) } + + Row( + modifier = modifier + .fillMaxWidth() + .background( + Color.White.copy(alpha = 0.1f), + RoundedCornerShape(8.dp) + ) + .padding(horizontal = 12.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = name, + color = Color.White, + fontSize = 14.sp, + fontWeight = FontWeight.Medium + ) + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = type, + color = Color.White.copy(alpha = 0.6f), + fontSize = 12.sp + ) + } + + IconButton( + onClick = { showDeleteDialog = true }, + modifier = Modifier.size(36.dp) + ) { + Icon( + imageVector = Icons.Default.Delete, + contentDescription = stringResource(R.string.delete), + tint = Color(0xFFFF5252) + ) + } + } + + // 删除确认对话框 + if (showDeleteDialog) { + AlertDialog( + onDismissRequest = { showDeleteDialog = false }, + title = { + Text(text = stringResource(R.string.delete_confirm_title)) + }, + text = { + Text(text = stringResource(R.string.delete_custom_content_confirm, name)) + }, + confirmButton = { + TextButton( + onClick = { + onDelete() + showDeleteDialog = false + } + ) { + Text( + text = stringResource(R.string.delete), + color = Color(0xFFFF5252) + ) + } + }, + dismissButton = { + TextButton(onClick = { showDeleteDialog = false }) { + Text(text = stringResource(R.string.cancel)) + } + } + ) + } +} + +/** + * 导入按钮 + */ +@Composable +private fun ImportButton( + text: String, + onClick: () -> Unit, + enabled: Boolean = true, // 添加 enabled 参数 + modifier: Modifier = Modifier +) { + Button( + onClick = onClick, + enabled = enabled, // 使用 enabled 状态 + modifier = modifier.height(48.dp), + shape = RoundedCornerShape(8.dp), + colors = ButtonDefaults.buttonColors( + containerColor = Color(0xFFFF6B35), + disabledContainerColor = Color(0xFFFF6B35).copy(alpha = 0.5f) // 禁用时半透明 + ) + ) { + Icon( + imageVector = Icons.Default.Add, + contentDescription = null, + tint = Color.White.copy(alpha = if (enabled) 1f else 0.5f), + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(4.dp)) + Text( + text = text, + color = Color.White.copy(alpha = if (enabled) 1f else 0.5f), + fontSize = 14.sp, + fontWeight = FontWeight.Medium + ) + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt index aab7a71b..5efbde62 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt @@ -140,6 +140,16 @@ fun SettingsScreen( Spacer(modifier = Modifier.height(24.dp)) + // 自定义导入设置 + SettingsSection(title = stringResource(R.string.settings_section_custom)) { + CustomImportSection( + customImportManager = viewModel.getCustomImportManager(), + onImportSuccess = { viewModel.refreshCustomContent() } + ) + } + + Spacer(modifier = Modifier.height(24.dp)) + // 边框水印设置 SettingsSection(title = stringResource(R.string.settings_section_frame)) { FrameWatermarkSetting( diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt index 420b118a..dc05cff5 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -16,9 +16,9 @@ import com.hinnka.mycamera.camera.AspectRatio import com.hinnka.mycamera.camera.Camera2Controller import com.hinnka.mycamera.camera.CameraState import com.hinnka.mycamera.camera.CaptureInfo +import com.hinnka.mycamera.data.ContentRepository import com.hinnka.mycamera.data.UserPreferencesRepository import com.hinnka.mycamera.frame.FrameInfo -import com.hinnka.mycamera.frame.FrameManager import com.hinnka.mycamera.frame.FrameRenderer import com.hinnka.mycamera.gallery.PhotoManager import com.hinnka.mycamera.gallery.PhotoMetadata @@ -26,7 +26,6 @@ import com.hinnka.mycamera.gallery.PhotoProcessor import com.hinnka.mycamera.lut.LutConfig import com.hinnka.mycamera.lut.LutImageProcessor import com.hinnka.mycamera.lut.LutInfo -import com.hinnka.mycamera.lut.LutManager import com.hinnka.mycamera.utils.OrientationObserver import com.hinnka.mycamera.utils.ShutterSoundPlayer import com.hinnka.mycamera.utils.YuvProcessor @@ -48,18 +47,22 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) // 用户偏好设置仓库 private val userPreferencesRepository = UserPreferencesRepository(application) - // LUT 管理器 - private val lutManager = LutManager(application) + // 内容仓库(单例,与 GalleryViewModel 共享) + private val contentRepository = ContentRepository.getInstance(application) private val lutImageProcessor = LutImageProcessor() // 计费管理器 private val billingManager = com.hinnka.mycamera.billing.BillingManagerImpl(application) val isPurchased = billingManager.isPurchased - // 边框管理器 - private val frameManager = FrameManager(application) + // 边框渲染器 private val frameRenderer = FrameRenderer(application) - private val photoProcessor = PhotoProcessor(lutManager, lutImageProcessor, frameManager, frameRenderer) + private val photoProcessor = PhotoProcessor( + contentRepository.lutManager, + lutImageProcessor, + contentRepository.frameManager, + frameRenderer + ) // 快门音效播放器 private val shutterSoundPlayer = ShutterSoundPlayer(application) @@ -141,13 +144,23 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } } - // 初始化 LUT 管理器 - lutManager.initialize() - availableLutList = lutManager.getAvailableLuts() + // 初始化内容仓库 + contentRepository.initialize() - // 初始化边框管理器 - frameManager.initialize() - availableFrameList = frameManager.getAvailableFrames() + // 订阅 ContentRepository 的 StateFlow,实现自动更新 + viewModelScope.launch { + contentRepository.availableLuts.collect { luts -> + availableLutList = luts + Log.d(TAG, "CameraViewModel: availableLutList updated to ${luts.size} items") + } + } + + viewModelScope.launch { + contentRepository.availableFrames.collect { frames -> + availableFrameList = frames + Log.d(TAG, "CameraViewModel: availableFrameList updated to ${frames.size} items") + } + } // 加载用户偏好设置 viewModelScope.launch { @@ -383,6 +396,28 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) billingManager.purchase(activity) } + // ==================== 自定义导入相关方法 ==================== + + /** + * 获取自定义导入管理器 + */ + fun getCustomImportManager() = contentRepository.getCustomImportManager() + + /** + * 刷新自定义内容(在导入新的LUT或边框后调用) + * StateFlow 会自动通知订阅者更新 + */ + fun refreshCustomContent() { + viewModelScope.launch { + withContext(Dispatchers.IO) { + // 重新初始化内容仓库 + // StateFlow 会自动更新 availableLutList 和 availableFrameList + contentRepository.refreshCustomContent() + } + Log.d(TAG, "Custom content refreshed via ContentRepository") + } + } + // ==================== LUT 相关方法 ==================== /** @@ -395,7 +430,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } else { viewModelScope.launch { currentLutConfig = withContext(Dispatchers.IO) { - lutManager.loadLut(lutId) + contentRepository.lutManager.loadLut(lutId) } } } @@ -421,14 +456,14 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) * 获取 LUT 信息 */ fun getLutInfo(id: String): LutInfo? { - return lutManager.getLutInfo(id) + return contentRepository.lutManager.getLutInfo(id) } /** * 预加载 LUT */ fun preloadLut(id: String) { - lutManager.preloadLut(id) + contentRepository.lutManager.preloadLut(id) } /** @@ -455,7 +490,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) availableLutList.forEach { lutInfo -> val lutConfig = withContext(Dispatchers.IO) { - lutManager.loadLut(lutInfo.id) + contentRepository.lutManager.loadLut(lutInfo.id) } if (lutConfig != null) { @@ -765,9 +800,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) override fun onCleared() { super.onCleared() cameraController.release() - lutManager.clearCache() + contentRepository.lutManager.clearCache() lutImageProcessor.release() - frameManager.clearCache() + contentRepository.frameManager.clearCache() shutterSoundPlayer.release() // 清理 LUT 预览图 diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt index f762b80e..b4c5f85f 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt @@ -14,8 +14,8 @@ import androidx.compose.runtime.* import androidx.core.content.FileProvider import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope +import com.hinnka.mycamera.data.ContentRepository import com.hinnka.mycamera.frame.FrameInfo -import com.hinnka.mycamera.frame.FrameManager import com.hinnka.mycamera.frame.FrameRenderer import com.hinnka.mycamera.gallery.* import com.hinnka.mycamera.lut.* @@ -39,18 +39,24 @@ import kotlin.math.max * 管理照片列表、选择状态和各种操作 */ class GalleryViewModel(application: Application) : AndroidViewModel(application) { - + companion object { private const val TAG = "GalleryViewModel" } - + private val repository = GalleryRepository(application) - private val lutManager = LutManager(application) + + // 内容仓库(单例,与 CameraViewModel 共享) + private val contentRepository = ContentRepository.getInstance(application) private val lutImageProcessor = LutImageProcessor() - private val frameManager = FrameManager(application) private val frameRenderer = FrameRenderer(application) - private val photoProcessor = PhotoProcessor(lutManager, lutImageProcessor, frameManager, frameRenderer) - + private val photoProcessor = PhotoProcessor( + contentRepository.lutManager, + lutImageProcessor, + contentRepository.frameManager, + frameRenderer + ) + // 计费管理器 private val billingManager = com.hinnka.mycamera.billing.BillingManagerImpl(application) val isPurchased = billingManager.isPurchased @@ -123,10 +129,22 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) init { loadPhotos() - lutManager.initialize() - availableLuts = lutManager.getAvailableLuts() - frameManager.initialize() - availableFrames = frameManager.getAvailableFrames() + contentRepository.initialize() + + // 订阅 ContentRepository 的 StateFlow,实现自动更新 + viewModelScope.launch { + contentRepository.availableLuts.collect { luts -> + availableLuts = luts + Log.d(TAG, "GalleryViewModel: availableLuts updated to ${luts.size} items") + } + } + + viewModelScope.launch { + contentRepository.availableFrames.collect { frames -> + availableFrames = frames + Log.d(TAG, "GalleryViewModel: availableFrames updated to ${frames.size} items") + } + } } /** @@ -297,7 +315,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) // 加载 LUT 配置 editLutId?.let { id -> editLutConfig = withContext(Dispatchers.IO) { - lutManager.loadLut(id) + contentRepository.lutManager.loadLut(id) } } } @@ -317,7 +335,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) return availableLuts.map { lutInfo -> val lutConfig = withContext(Dispatchers.IO) { - lutManager.loadLut(lutInfo.id) + contentRepository.lutManager.loadLut(lutInfo.id) } if (lutConfig != null) { @@ -525,7 +543,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) editLutId?.let { id -> viewModelScope.launch { editLutConfig = withContext(Dispatchers.IO) { - lutManager.loadLut(id) + contentRepository.lutManager.loadLut(id) } } } @@ -571,7 +589,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) viewModelScope.launch { editLutConfig = withContext(Dispatchers.IO) { - lutManager.loadLut(lutId) + contentRepository.lutManager.loadLut(lutId) } } } @@ -847,7 +865,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) override fun onCleared() { super.onCleared() lutImageProcessor.release() - lutManager.clearCache() + contentRepository.lutManager.clearCache() } /** @@ -863,4 +881,24 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) fun refreshPurchases() { billingManager.refresh() } + + /** + * 获取自定义导入管理器 + */ + fun getCustomImportManager() = contentRepository.getCustomImportManager() + + /** + * 刷新自定义内容(在导入新的LUT或边框后调用) + * StateFlow 会自动通知订阅者更新 + */ + fun refreshCustomContent() { + viewModelScope.launch { + withContext(Dispatchers.IO) { + // 重新初始化内容仓库 + // StateFlow 会自动更新 availableLuts 和 availableFrames + contentRepository.refreshCustomContent() + } + Log.d(TAG, "Custom content refreshed via ContentRepository") + } + } } diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml index eb6ada24..cdfcf8c5 100644 --- a/app/src/main/res/values-zh/strings.xml +++ b/app/src/main/res/values-zh/strings.xml @@ -1,6 +1,6 @@ Photon Camera - + 拍摄 切换摄像头 @@ -10,31 +10,31 @@ 直方图 网格 返回 - + EV ISO 快门 自动 - + 对焦 点击对焦 - + 画面比例 3:2 4:3 16:9 1:1 - + 需要相机权限 授予权限 - + 变焦 - + 相册 照片详情 @@ -67,14 +67,14 @@ 光圈 ISO 快门速度 - + 边框 无 显示 App 品牌 导出带有边框水印的照片吗? 导入 - + 设置 拍摄设置 @@ -93,7 +93,7 @@ 使用音量键进行拍摄 拍摄后自动保存 拍摄后自动保存照片,否则需要手动确认 - + 滤镜强度 关闭 @@ -114,5 +114,18 @@ 具体价格以所在地区为准 PhotonCamera Pro 解锁全部高级滤镜并支持我们的开发工作 - + + 自定义 + 自定义导入 + 导入自定义内容 + 导入 LUT + 导入边框 + 导入自定义 LUT 滤镜文件 (.cube) 或边框模板文件 (.json) + 已导入内容 + LUT 滤镜 + 边框模板 + 删除确认 + 删除 "%s" 吗? + 导入中... + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ca907894..6f585fd3 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -114,4 +114,18 @@ Price varies by region PhotonCamera Pro Unlock all premium filters and support us. + + + CUSTOM + Custom Import + Import Custom Content + Import LUT + Import Frame + Import custom LUT filters (.cube) or frame templates (.json) + Imported Content + LUT Filter + Frame Template + Delete Confirmation + Delete "%s"? + Importing... \ No newline at end of file