feat: support copying and exporting frames in frame management

This commit is contained in:
Hinnka committed 2026-05-16 19:53:58 +08:00
1 parent a4c7cfdc66
commit 6cf7dd1c08
6 files changed
+254 -4

No files matched your search

@@ -17,6 +17,7 @@ import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.util.Locale
import java.util.UUID
/**
@@ -264,6 +265,84 @@ class CustomImportManager(private val context: Context) {
}
}
/**
* 复制边框样式。
*
* 内置边框会从 assets 读取模板,自定义边框会从私有目录读取模板。若模板引用了私有目录内的图片边框资源,
* 会一并复制图片文件并把 imagePath 改为副本路径。
*/
fun copyFrame(frame: com.hinnka.mycamera.frame.FrameInfo, copyName: String): String? {
return try {
val frameId = "custom_${UUID.randomUUID()}"
val sourceTemplate = if (frame.isBuiltIn) {
FrameTemplateParser.parseFromAssets(context, frame.path)
} else {
FrameTemplateParser.parseFromFile(frame.path)
} ?: return null
val copiedLayout = sourceTemplate.layout.imagePath?.let { imagePath ->
copyCustomFrameImageIfNeeded(imagePath, frameId)
}?.let { copiedImagePath ->
sourceTemplate.layout.copy(imagePath = copiedImagePath)
} ?: sourceTemplate.layout
val copiedTemplate = sourceTemplate.copy(
id = frameId,
nameMap = mapOf("en" to copyName, "zh" to copyName),
layout = copiedLayout
)
val validationErrors = FrameTemplateParser.validateTemplate(copiedTemplate)
if (validationErrors.isNotEmpty()) {
PLog.e(TAG, "Copy frame failed, invalid fields: $validationErrors")
return null
}
val frameConfigFile = File(customFrameDir, "$frameId.json")
frameConfigFile.writeText(FrameTemplateParser.serializeTemplate(copiedTemplate))
saveFrameToConfig(frameId, copiedTemplate.nameMap, frameConfigFile.name)
PLog.d(TAG, "Frame copied successfully: $frameId ($copyName)")
frameId
} catch (e: Exception) {
PLog.e(TAG, "Failed to copy frame", e)
null
}
}
fun exportFrameJson(frame: com.hinnka.mycamera.frame.FrameInfo): ByteArray? {
return try {
val json = if (frame.isBuiltIn) {
context.assets.open(frame.path).use { input ->
input.bufferedReader().use { it.readText() }
}
} else {
File(frame.path).takeIf { it.exists() }?.readText() ?: return null
}
json.toByteArray(Charsets.UTF_8)
} catch (e: Exception) {
PLog.e(TAG, "Failed to export frame JSON: ${frame.id}", e)
null
}
}
private fun copyCustomFrameImageIfNeeded(imagePath: String, frameId: String): String? {
val sourceFile = File(imagePath)
if (!sourceFile.exists() || sourceFile.parentFile != customFrameDir) {
return imagePath
}
val extension = sourceFile.extension.takeIf { it.isNotBlank() } ?: "png"
val imageFileName = "${frameId}_image.${extension.lowercase(Locale.US)}"
val copiedFile = File(customFrameDir, imageFileName)
sourceFile.inputStream().use { input ->
copiedFile.outputStream().use { output ->
input.copyTo(output)
}
}
return copiedFile.absolutePath
}
fun importDcp(uri: Uri, displayName: String? = null): String? {
return try {
val fileName = getFileName(uri) ?: "profile_${System.currentTimeMillis()}.dcp"
@@ -1,6 +1,7 @@
package com.hinnka.mycamera.ui.settings
import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
@@ -21,6 +22,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
@@ -29,6 +31,7 @@ import androidx.compose.ui.unit.sp
import com.hinnka.mycamera.R
import com.hinnka.mycamera.frame.FrameInfo
import com.hinnka.mycamera.ui.camera.autoRotate
import com.hinnka.mycamera.utils.PLog
import com.hinnka.mycamera.viewmodel.CameraViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@@ -54,6 +57,7 @@ fun FrameManagementScreen(
val availableFrames = viewModel.availableFrameList
val customImportManager = viewModel.getCustomImportManager()
val scope = rememberCoroutineScope()
val context = LocalContext.current
// 本地可变列表用于拖拽排序
var localFrameList by remember { mutableStateOf(availableFrames) }
@@ -73,12 +77,18 @@ fun FrameManagementScreen(
var renamingFrame by remember { mutableStateOf<FrameInfo?>(null) }
var renameText by remember { mutableStateOf("") }
// 复制对话框状态
var showCopyDialog by remember { mutableStateOf(false) }
var copyingFrame by remember { mutableStateOf<FrameInfo?>(null) }
var copyText by remember { mutableStateOf("") }
// 删除确认对话框状态
var showDeleteDialog by remember { mutableStateOf(false) }
var deletingFrame by remember { mutableStateOf<FrameInfo?>(null) }
// 导入状态
var isImporting by remember { mutableStateOf(false) }
var pendingExportBytes by remember { mutableStateOf(ByteArray(0)) }
// 顶部操作菜单
var showCreateMenu by remember { mutableStateOf(false) }
@@ -99,6 +109,38 @@ fun FrameManagementScreen(
}
}
val exportLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.CreateDocument("application/json")
) { uri: Uri? ->
uri?.let {
scope.launch {
withContext(Dispatchers.IO) {
try {
context.contentResolver.openOutputStream(it)?.use { output ->
output.write(pendingExportBytes)
}
withContext(Dispatchers.Main) {
Toast.makeText(
context,
context.getString(R.string.frame_export_success),
Toast.LENGTH_SHORT
).show()
}
} catch (e: Exception) {
PLog.e("FrameManagementScreen", "Failed to export frame", e)
withContext(Dispatchers.Main) {
Toast.makeText(
context,
context.getString(R.string.frame_export_failed),
Toast.LENGTH_SHORT
).show()
}
}
}
}
}
}
// 拖拽排序状态
val lazyListState = rememberLazyListState()
val reorderableLazyListState = rememberReorderableLazyListState(lazyListState) { from, to ->
@@ -219,14 +261,17 @@ fun FrameManagementScreen(
onSetDefault = {
viewModel.setFrame(null)
},
onEditStyle = null,
onRename = null,
onDelete = null
onEditStyle = null,
onCopy = null,
onExport = null,
onRename = null,
onDelete = null
)
}
itemsIndexed(localFrameList, key = { _, it -> it.id }) { index, frameInfo ->
ReorderableItem(reorderableLazyListState, key = frameInfo.id) { isDragging ->
val copySuffix = stringResource(R.string.copy_suffix)
FrameManagementItem(
name = frameInfo.getName(),
isBuiltIn = frameInfo.isBuiltIn,
@@ -239,6 +284,26 @@ fun FrameManagementScreen(
onEditStyle = {
onEditFrameStyle(frameInfo.id)
},
onCopy = {
copyingFrame = frameInfo
copyText = frameInfo.getName() + copySuffix
showCopyDialog = true
},
onExport = {
scope.launch {
val bytes = viewModel.exportFrameToJson(frameInfo)
if (bytes != null) {
pendingExportBytes = bytes
exportLauncher.launch("${frameInfo.getName()}.json")
} else {
Toast.makeText(
context,
context.getString(R.string.frame_export_failed),
Toast.LENGTH_SHORT
).show()
}
}
},
onRename = if (!frameInfo.isBuiltIn) {
{
renamingFrame = frameInfo
@@ -299,6 +364,41 @@ fun FrameManagementScreen(
)
}
// 复制对话框
if (showCopyDialog && copyingFrame != null) {
AlertDialog(
onDismissRequest = { showCopyDialog = false },
title = {
Text(stringResource(R.string.copy_frame_dialog_title))
},
text = {
OutlinedTextField(
value = copyText,
onValueChange = { copyText = it },
label = { Text(stringResource(R.string.name)) },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
},
confirmButton = {
TextButton(
onClick = {
viewModel.copyFrame(copyingFrame!!, copyText)
showCopyDialog = false
copyingFrame = null
}
) {
Text(stringResource(R.string.confirm))
}
},
dismissButton = {
TextButton(onClick = { showCopyDialog = false }) {
Text(stringResource(R.string.cancel))
}
}
)
}
// 删除确认对话框
if (showDeleteDialog && deletingFrame != null) {
AlertDialog(
@@ -361,6 +461,8 @@ private fun FrameManagementItem(
canDrag: Boolean,
onSetDefault: () -> Unit,
onEditStyle: (() -> Unit)?,
onCopy: (() -> Unit)?,
onExport: (() -> Unit)?,
onRename: (() -> Unit)?,
onDelete: (() -> Unit)?,
dragModifier: Modifier = Modifier,
@@ -456,7 +558,7 @@ private fun FrameManagementItem(
}
}
if (onEditStyle != null || onRename != null || onDelete != null) {
if (onEditStyle != null || onCopy != null || onExport != null || onRename != null || onDelete != null) {
Box {
IconButton(
onClick = { showActionsMenu = true },
@@ -482,6 +584,24 @@ private fun FrameManagementItem(
}
)
}
onCopy?.let {
DropdownMenuItem(
text = { Text(stringResource(R.string.copy)) },
onClick = {
showActionsMenu = false
it()
}
)
}
onExport?.let {
DropdownMenuItem(
text = { Text(stringResource(R.string.export_frame_json)) },
onClick = {
showActionsMenu = false
it()
}
)
}
onRename?.let {
DropdownMenuItem(
text = { Text(stringResource(R.string.rename)) },
@@ -2263,6 +2263,41 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
}
/**
* 复制边框并把副本插入到原边框后面。
*/
fun copyFrame(frame: FrameInfo, copyName: String) {
viewModelScope.launch {
val newFrameId = withContext(Dispatchers.IO) {
contentRepository.getCustomImportManager().copyFrame(frame, copyName)
}
if (newFrameId != null) {
withContext(Dispatchers.IO) {
val currentOrder = userPreferencesRepository.userPreferences.first().frameOrder.toMutableList()
if (currentOrder.isEmpty()) {
val allIds = availableFrameList.map { it.id }.toMutableList()
val index = allIds.indexOf(frame.id)
if (index != -1) {
allIds.add(index + 1, newFrameId)
} else {
allIds.add(newFrameId)
}
userPreferencesRepository.saveFrameOrder(allIds)
} else {
val index = currentOrder.indexOf(frame.id)
if (index != -1) {
currentOrder.add(index + 1, newFrameId)
} else {
currentOrder.add(newFrameId)
}
userPreferencesRepository.saveFrameOrder(currentOrder)
}
contentRepository.refreshCustomContent()
}
}
}
}
fun setAiFocusTargetMode(mode: AiFocusTargetMode) {
viewModelScope.launch {
userPreferencesRepository.saveAiFocusTargetMode(mode)
@@ -3499,6 +3534,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
outputStream.toByteArray()
}
suspend fun exportFrameToJson(frame: FrameInfo): ByteArray? = withContext(Dispatchers.IO) {
contentRepository.getCustomImportManager().exportFrameJson(frame)
}
/**
* 从导入的 .plut URI 中提取嵌入的色彩配方并保存到指定 LUT(仅 v4 文件含有配方)
*/
@@ -467,7 +467,11 @@
<string name="export_lut_cube">导出LUT</string>
<string name="copy">复制</string>
<string name="copy_lut_dialog_title">复制滤镜</string>
<string name="copy_frame_dialog_title">复制边框</string>
<string name="copy_suffix"> (副本)</string>
<string name="export_frame_json">导出边框</string>
<string name="frame_export_success">边框导出成功</string>
<string name="frame_export_failed">边框导出失败</string>
<string name="edit_category">编辑分类</string>
<string name="batch_edit_category">批量编辑分类</string>
<string name="sort_categories">分类排序</string>
@@ -351,7 +351,11 @@
<string name="export_lut_cube">匯出LUT</string>
<string name="copy">複製</string>
<string name="copy_lut_dialog_title">複製濾鏡</string>
<string name="copy_frame_dialog_title">複製邊框</string>
<string name="copy_suffix"> (副本)</string>
<string name="export_frame_json">匯出邊框</string>
<string name="frame_export_success">邊框匯出成功</string>
<string name="frame_export_failed">邊框匯出失敗</string>
<string name="edit_category">編輯分類</string>
<string name="batch_edit_category">批次編輯分類</string>
<string name="sort_categories">分類排序</string>
+4
View File
@@ -472,7 +472,11 @@
<string name="export_lut_cube">Export LUT</string>
<string name="copy">Copy</string>
<string name="copy_lut_dialog_title">Copy LUT</string>
<string name="copy_frame_dialog_title">Copy Frame</string>
<string name="copy_suffix"> (Copy)</string>
<string name="export_frame_json">Export Frame</string>
<string name="frame_export_success">Frame exported successfully</string>
<string name="frame_export_failed">Failed to export frame</string>
<string name="edit_category">Edit Category</string>
<string name="batch_edit_category">Batch Edit Category</string>
<string name="sort_categories">Sort Categories</string>