feat: typed preferences framework and migration

This commit is contained in:
zhoubinjia committed 2026-11-06 13:06:58 +08:00
1 parent 2cc00816d8
commit 8d85d1746e
34 files changed
+1888 -4254

No files matched your search

@@ -1,5 +1,8 @@
package com.hinnka.mycamera
import com.hinnka.mycamera.ui.prefs.rememberUserPreferencesRepository
import com.hinnka.mycamera.ui.prefs.preferenceValue
import com.hinnka.mycamera.data.ContentRepository
import android.Manifest
import android.content.Intent
import android.content.pm.ActivityInfo
@@ -190,6 +193,9 @@ private val EXTERNAL_GALLERY_REVIEW_ACTIONS = setOf(
class MainActivity : AppCompatActivity() {
private val cameraViewModel: CameraViewModel by viewModels()
private val userPreferencesRepository by lazy {
ContentRepository.getInstance(this).userPreferencesRepository
}
private val galleryViewModel: GalleryViewModel by viewModels()
private val permissions =
@@ -247,8 +253,8 @@ class MainActivity : AppCompatActivity() {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
combine(
cameraViewModel.useHdrScreenMode,
cameraViewModel.useP3ColorSpace
userPreferencesRepository.flow { it.useHdrScreenMode },
userPreferencesRepository.flow { it.useP3ColorSpace }
) { useHdrScreen, useP3 ->
useHdrScreen to useP3
}.collect { (useHdrScreen, useP3) ->
@@ -260,7 +266,7 @@ class MainActivity : AppCompatActivity() {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
cameraViewModel.windowScreenBrightness.collect { brightness ->
userPreferencesRepository.flow { it.windowScreenBrightness }.collect { brightness ->
applyWindowScreenBrightness(brightness)
}
}
@@ -268,7 +274,7 @@ class MainActivity : AppCompatActivity() {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
cameraViewModel.autoRotateEnabled.collect { enabled ->
userPreferencesRepository.flow { it.autoRotateEnabled }.collect { enabled ->
OrientationObserver.updateUiAutoRotateEnabled(enabled)
}
}
@@ -305,7 +311,7 @@ class MainActivity : AppCompatActivity() {
setContent {
StartupComposeReadyEffect()
val currentRecipeParams by cameraViewModel.currentRecipeParams.collectAsState()
val phantomPipCrop by cameraViewModel.phantomPipCrop.collectAsState()
val phantomPipCrop by preferenceValue { it.phantomPipCrop }
ScreenCaptureRenderConfigStore.save(
creativeLutConfig = cameraViewModel.currentLutConfig,
creativeColorRecipeParams = currentRecipeParams,
@@ -706,7 +712,7 @@ fun NavigationHost(
locateLutId = lutId,
videoLut = cameraViewModel.state.value.captureMode ==
CaptureMode.VIDEO &&
cameraViewModel.separateVideoLutEnabled.value
cameraViewModel.userPreferences.value.separateVideoLutEnabled
)
)
},
@@ -769,7 +775,7 @@ fun NavigationHost(
locateLutId = lutId,
videoLut = cameraViewModel.state.value.captureMode ==
CaptureMode.VIDEO &&
cameraViewModel.separateVideoLutEnabled.value
cameraViewModel.userPreferences.value.separateVideoLutEnabled
)
)
},
@@ -933,12 +939,13 @@ fun NavigationHost(
}
composable(Routes.PHANTOM_PIP_CROP) {
val crop by cameraViewModel.phantomPipCrop.collectAsState()
val crop by preferenceValue { it.phantomPipCrop }
val preferencesRepository = rememberUserPreferencesRepository()
PhantomPipCropScreen(
initialCrop = crop,
onBack = { navController.popBackStack() },
onSave = {
cameraViewModel.setPhantomPipCrop(it)
preferencesRepository.updateAsync { phantomPipCrop = it }
navController.popBackStack()
}
)
@@ -778,7 +778,7 @@ class CameraDiscovery(private val context: Context) {
private fun saveIszLensConfigs(configs: List<IszLensConfig>) {
try {
runBlocking {
userPreferencesRepository.saveIszLensConfigs(configs)
userPreferencesRepository.update { iszLensConfigs = configs }
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to persist migrated ISZ lens crop coordinates", e)
@@ -871,7 +871,7 @@ class CameraDiscovery(private val context: Context) {
runBlocking {
val preferences = userPreferencesRepository.userPreferences.firstOrNull()
LogicalCameraDiscoveryConfig(
autoDiscoveryEnabled = preferences?.enableLogicalMultiCameraDiscovery ?: false,
autoDiscoveryEnabled = userPreferencesRepository.latest().enableLogicalMultiCameraDiscovery,
forcedBindings = parseLogicalCameraBindingRequests(
preferences?.logicalCameraBindingWhitelist ?: emptyList()
)
@@ -72,7 +72,7 @@ class CaptureSoundRepository(
// File ownership and the preference update must commit together, even on cancellation.
withContext(NonCancellable) {
val previous = currentFileName(isBurst)
preferences.saveCaptureSound(isBurst, file.name)
preferences.update { if (isBurst) burstSoundFileName = file.name else shutterSoundFileName = file.name }
committed = true
deletePrevious(previous)
}
@@ -85,7 +85,7 @@ class CaptureSoundRepository(
suspend fun reset(isBurst: Boolean) = mutex.withLock {
withContext(Dispatchers.IO + NonCancellable) {
val previous = currentFileName(isBurst)
preferences.saveCaptureSound(isBurst, null)
preferences.update { if (isBurst) burstSoundFileName = null else shutterSoundFileName = null }
deletePrevious(previous)
}
}
@@ -0,0 +1,873 @@
package com.hinnka.mycamera.data
import androidx.datastore.preferences.core.MutablePreferences
import androidx.datastore.preferences.core.Preferences
import com.hinnka.mycamera.data.PreferenceKeys as K
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.floatPreferencesKey
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import com.hinnka.mycamera.camera.AspectRatio
import com.hinnka.mycamera.camera.CustomCaptureSettings
import com.hinnka.mycamera.camera.CustomFocalLengthValue
import com.hinnka.mycamera.camera.CustomVendorKeySettings
import com.hinnka.mycamera.camera.GridStyle
import com.hinnka.mycamera.camera.IszLensConfig
import com.hinnka.mycamera.camera.IszRawDngMetadataCorrections
import com.hinnka.mycamera.camera.MeteringMode
import com.hinnka.mycamera.camera.MultiFrameConfig
import com.hinnka.mycamera.camera.NoiseReductionLevel
import com.hinnka.mycamera.camera.VendorCaptureSettingsByLens
import com.hinnka.mycamera.color.TransferCurve
import com.hinnka.mycamera.gallery.PhotoSavePath
import com.hinnka.mycamera.model.AppAppearance
import com.hinnka.mycamera.model.CameraPreset
import com.hinnka.mycamera.model.EffectParams
import com.hinnka.mycamera.model.LutSelectorMode
import com.hinnka.mycamera.processor.MgcRawMaxMode
import com.hinnka.mycamera.raw.CanonPictureStyle
import com.hinnka.mycamera.raw.ColorSpace
import com.hinnka.mycamera.raw.HncsFilmCurveMode
import com.hinnka.mycamera.raw.HncsProfileManager
import com.hinnka.mycamera.raw.HncsRenderIntent
import com.hinnka.mycamera.raw.LumixPhotoStyle
import com.hinnka.mycamera.raw.RawColorCalibrationMode
import com.hinnka.mycamera.raw.RawDenoiseDefaults
import com.hinnka.mycamera.raw.RawNoiseProfileManager
import com.hinnka.mycamera.raw.RawOutputUpscaleMode
import com.hinnka.mycamera.raw.RawProcessingPreferences
import com.hinnka.mycamera.raw.RawRenderingEngine
import com.hinnka.mycamera.raw.RawSceneExposureMath
import com.hinnka.mycamera.raw.RawSharpeningDefaults
import com.hinnka.mycamera.raw.RawToneMappingParameters
import com.hinnka.mycamera.raw.SpectralFilmTuning
import com.hinnka.mycamera.screencapture.PhantomPipCrop
import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD
import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_STRENGTH
import com.hinnka.mycamera.stabilization.ExternalLensStabilizationConfig
import com.hinnka.mycamera.stabilization.normalizeStabilizationLookahead
import com.hinnka.mycamera.stabilization.normalizeStabilizationStrength
import com.hinnka.mycamera.video.CaptureMode
import com.hinnka.mycamera.video.VIDEO_AUDIO_INPUT_AUTO
import com.hinnka.mycamera.video.VideoAspectRatio
import com.hinnka.mycamera.video.VideoBitratePreset
import com.hinnka.mycamera.video.VideoFpsPreset
import com.hinnka.mycamera.video.VideoLogLutMode
import com.hinnka.mycamera.video.VideoLogProfile
import com.hinnka.mycamera.video.VideoRecordingPath
import com.hinnka.mycamera.video.VideoResolutionPreset
import com.hinnka.mycamera.video.VideoStabilizationMode
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* 用户偏好设置。
*
* 每个实例对应 DataStore 的一份快照,同一实例上读取的所有字段彼此一致。
* 每个设置项只需在这里用一行委托声明(key、默认值、编码方式):
*
* ```
* var keepScreenOn by bool("keep_screen_on", false)
* ```
*
* 读取:任何使用点直接 `prefs.keepScreenOn`(`UserPreferencesRepository.current` / `flow` / Compose `preferenceValue`)。
* 写入:`repository.update { keepScreenOn = true }`,同一个 block 内的多个赋值在一次事务中原子写入。
* 在 `update {}`(或 [edited])之外给字段赋值会直接报错。
*/
class UserPreferences internal constructor(
internal val raw: Preferences = emptyPreferences(),
private val writable: Boolean = false,
) {
constructor() : this(emptyPreferences(), false)
private val cache = HashMap<String, Any?>()
@Suppress("UNCHECKED_CAST")
internal fun <T> cached(name: String, compute: () -> T): T = synchronized(cache) {
if (cache.containsKey(name)) cache[name] as T else compute().also { cache[name] = it }
}
internal fun mutablePreferences(): MutablePreferences {
val preferences = raw
check(writable && preferences is MutablePreferences) {
"UserPreferences 只能在 UserPreferencesRepository.update {} 或 edited {} 中修改"
}
invalidate()
return preferences
}
internal fun invalidate() = synchronized(cache) { cache.clear() }
/** 在内存中得到修改后的副本(不落盘),用于"假如改成这样"的计算。 */
fun edited(block: UserPreferences.() -> Unit): UserPreferences {
val preferences = raw.toMutablePreferences()
UserPreferences(preferences, writable = true).block()
return UserPreferences(preferences.toPreferences())
}
override fun equals(other: Any?): Boolean = other is UserPreferences && other.raw == raw
override fun hashCode(): Int = raw.hashCode()
override fun toString(): String = "UserPreferences($raw)"
var captureMode by enum("capture_mode", CaptureMode.PHOTO)
var aspectRatio by string("aspect_ratio", "RATIO_4_3")
var videoLutId by nullableString("video_lut_id")
var rawBaselineLutId by nullableString("raw_baseline_lut_id")
var rawDcpId by nullableString("raw_dcp_id")
var rawExposureCompensation by float("raw_exposure_compensation", 0f, normalize = { it.coerceIn(-4f, 4f) })
var rawHighlightsAdjustment by float("raw_highlights_adjustment", 0f, normalize = { it.coerceIn(-1f, 1f) })
var rawShadowsAdjustment by float("raw_shadows_adjustment", 0f, normalize = { it.coerceIn(-1f, 1f) })
var rawDROEnabled by bool("raw_dro_enabled", false)
var rawBlackPointCorrection by float("raw_black_point_correction", 0f, normalize = { it.coerceIn(-1f, 1f) })
var rawWhitePointCorrection by float("raw_white_point_correction", 0f, normalize = { it.coerceIn(-1f, 1f) })
var frameId by nullableString("frame_id")
var phantomFrameId by nullableString("phantom_frame_id")
var shutterSoundFileName by nullableString("shutter_sound_file_name")
var burstSoundFileName by nullableString("burst_sound_file_name")
var zoomDisplayMode by string("zoom_display_mode", "FOCAL_LENGTH")
var useMultipleExposure by bool("use_multiple_exposure", false) // 是否启用多重曝光
var rawDigitalZoomResamplingEnabled by bool("raw_digital_zoom_resampling_enabled", false)
var useLivePhoto by bool("use_live_photo", false) // 是否启用 Live Photo (Motion Photo)
var developAnimationStyle by enum("develop_animation_style", DevelopAnimationStyle.FILM)
var backgroundImage by string("background_image", "camera_bg") // 背景图资源名或文件路径
var captureButtonColor by int("capture_button_color", 0xFFFFFFFF.toInt())
var colorSpace by enum("color_space", ColorSpace.SRGB)
var videoAspectRatio by enum("video_aspect_ratio", VideoAspectRatio.RATIO_16_9)
var videoLogLutMode by enum("video_log_lut_mode", VideoLogLutMode.MONITOR_ONLY)
var videoBitrate by enum("video_bitrate", VideoBitratePreset.P1)
var oppoSuperStabilizationEnabled by bool("oppo_super_stabilization_enabled", false)
var photoPreviewStabilizationEnabled by bool("photo_preview_stabilization_enabled", false)
var videoCodec by enum("video_codec", com.hinnka.mycamera.video.VideoCodec.H264)
var ultraHdrGainMapEnabled by bool("auto_enable_hdr_for_hdr_capture", false)
var phantomMode by bool("phantom_mode", false)
var widgetTheme by enum("widget_theme", WidgetTheme.FOLLOW_SYSTEM)
var openAIBaseUrl by nullableString("openai_base_url")
var openAIModel by nullableString("openai_model")
var referencePhotoUrl by nullableString("reference_photo_url")
var rawSpectralFilmStock by nullableString("raw_spectral_film_stock")
var rawSpectralFilmPrint by nullableString("raw_spectral_film_print")
var rawFotufilmDocument by nullableString("raw_fotufilm_document")
var activeEffectParamsJson by string("active_effect_params_json", "")
var customPresetsJson by string("custom_presets_json", "")
var activePresetId by nullableString("active_preset_id")
var deletedBuiltInIds by string("deleted_built_in_ids", "")
var showLevelIndicator by bool("show_level_indicator", false) // 水平仪显示
var focusPeakingEnabled by bool("focus_peaking_enabled", true) // 手动对焦峰值显示
var showHistogram by bool("show_histogram", true)
var showGrid by bool("show_grid", false) // 网格线显示
var eyeFocusEnabled by bool("eye_focus_enabled", false) // MediaPipe 人眼对焦
var shutterSoundEnabled by bool("shutter_sound_enabled", true) // 快门声音
var vibrationEnabled by bool("vibration_enabled", true) // 拍摄震动
var keepScreenOn by bool("keep_screen_on", false) // 屏幕常亮
var volumeKeyAction by enum("volume_key_action", VolumeKeyAction.CAPTURE) // 音量键操作
var autoSaveAfterCapture by bool("auto_save_after_capture", true) // 自动保存
var retainCaptureSettings by bool("retain_capture_settings", false) // 保留拍摄参数;关闭时须同时清除 customCaptureSettings
var edgeLevel by int("edge_level", 1) // 锐化等级:0=Off, 1=Fast, 2=High Quality, 3=Real-time
var videoEdgeLevel by int("video_edge_level", 1)
var rawLensShadingCorrectionEnabled by bool("raw_lens_shading_correction_enabled", true)
var rawMinShutterSpeedNs by long("raw_min_shutter_speed_ns", 0L)
var exportDngWithRawExport by bool("export_dng_with_raw_export", false)
var defaultFocalLength by float("default_focal_length", 0f) // 默认焦段 (mm),0表示不设置
var multipleExposureCount by int("multiple_exposure_count", 2, normalize = { it.coerceIn(2, 9) }) // 多重曝光张数
var photoQuality by int("photo_quality", 95) // 照片质量: 90, 95, 100
var enableDevelopAnimation by bool("enable_develop_animation", false) // 是否启用拍摄后的显影动画
var colorPaletteEnabled by bool("color_palette_enabled", false)
var autoRotateEnabled by bool("auto_rotate_enabled", true) // App 内界面元素是否跟随设备方向自适应旋转
var applyUltraHDR by bool("apply_ultra_hdr", false) // 是否应用 Ultra HDR 策略
var useP010 by bool("use_p010", false)
var useP3ColorSpace by bool("use_p3_color_space", false)
var videoAudioInputId by string("video_audio_input_id", VIDEO_AUDIO_INPUT_AUTO)
var videoTorchEnabled by bool("video_torch_enabled", false)
var videoLensLockEnabled by bool("video_lens_lock_enabled", false)
var videoWhiteBalanceLockEnabled by bool("video_white_balance_lock_enabled", false)
var phantomButtonHidden by bool("phantom_button_hidden", false)
var launchCameraOnPhantomMode by bool("launch_camera_on_phantom_mode", false)
var phantomPipPreview by bool("phantom_pip_preview", false)
var mirrorFrontCamera by bool("mirror_front_camera", true)
var saveLocation by bool("save_location", false)
var useBuiltInAiService by bool("use_built_in_ai_service", false)
var phantomSaveAsNew by bool("phantom_save_as_new", false)
var defaultVirtualAperture by float("default_virtual_aperture", 0f) // 默认虚化光圈,0表示关闭
var useHdrScreenMode by bool("use_hdr_screen_mode", true)
var deleteExported by bool("delete_exported", true)
var enableLogicalMultiCameraDiscovery by bool("enable_logical_multi_camera_discovery", false) // 是否自动探测逻辑多摄物理镜头绑定
// ---------------------------------------------------------------------------------------
// 以下字段涉及多个 key、旧版本 key、解析或写入归一化,用 stored(read, write) 声明读写逻辑。
var customAspectRatios: List<AspectRatio> by stored({ p -> parseCustomAspectRatios(p[K.CUSTOM_ASPECT_RATIOS]) }) { p, v ->
p[K.CUSTOM_ASPECT_RATIOS] = AspectRatio.sanitizeCustomRatios(v).joinToString(",") { it.name }
}
var topSheetAspectRatios: List<AspectRatio> by stored({ p ->
parseTopSheetAspectRatios(p[K.TOP_SHEET_ASPECT_RATIOS], AspectRatio.entries + customAspectRatios)
}) { p, v ->
p[K.TOP_SHEET_ASPECT_RATIOS] = AspectRatio.sanitizeTopSheetRatios(v).joinToString(",") { it.name }
}
/** 不提供默认值,由 CameraViewModel 根据配置文件设置。写入后需调用 PhotonLookContract.notifyLookChanged。 */
var lutId: String? by stored({ p -> p[K.LUT_ID_KEY] ?: p[K.LEGACY_PHANTOM_LUT_ID_KEY] }) { p, v ->
p.put(K.LUT_ID_KEY, v)
p.remove(K.LEGACY_PHANTOM_LUT_ID_KEY)
}
var separateVideoLutEnabled by bool("separate_video_lut_enabled", false)
var rawBaselineLutConfigured: Boolean by stored({ p ->
p[K.RAW_BASELINE_LUT_CONFIGURED_KEY] ?: p.contains(K.RAW_BASELINE_LUT_ID_KEY)
}) { p, v -> p[K.RAW_BASELINE_LUT_CONFIGURED_KEY] = v }
var rawDcpIdsByLens: Map<String, String?> by stored({ p -> parseNullableStringMap(p[K.RAW_DCP_IDS_BY_LENS_KEY]) }) { p, v ->
p.put(K.RAW_DCP_IDS_BY_LENS_KEY, CameraPreset.normalizeRawDcpIdsByLens(v).takeIf { it.isNotEmpty() }?.let(::serializeNullableStringMap))
}
var rawNoiseProfileId: String by stored({ p ->
p[K.RAW_NOISE_PROFILE_ID_KEY]?.takeIf { it.isNotBlank() } ?: RawNoiseProfileManager.DEFAULT_PROFILE_ID
}) { p, v -> p[K.RAW_NOISE_PROFILE_ID_KEY] = v.takeIf { it.isNotBlank() } ?: RawNoiseProfileManager.DEFAULT_PROFILE_ID }
var rawNoiseProfileIdsByLens: Map<String, String> by stored({ p ->
normalizeNoiseProfileIdsByLens(parseNullableStringMap(p[K.RAW_NOISE_PROFILE_IDS_BY_LENS_KEY]))
}) { p, v ->
p.put(
K.RAW_NOISE_PROFILE_IDS_BY_LENS_KEY,
normalizeNoiseProfileIdsByLens(v).toSortedMap().takeIf { it.isNotEmpty() }?.let(::serializeNullableStringMap),
)
}
val rawHncsProfileId: String? get() = HncsProfileManager.DEFAULT_PROFILE_ID
val rawHncsRenderIntent: HncsRenderIntent get() = HncsRenderIntent.Standard
var rawHncsFilmCurveMode: HncsFilmCurveMode by stored({ p ->
HncsFilmCurveMode.fromPersistedValue(p[K.RAW_HNCS_FILM_CURVE_MODE_KEY])
}) { p, v -> p[K.RAW_HNCS_FILM_CURVE_MODE_KEY] = v.persistedValue }
var rawRenderingEngine: RawRenderingEngine by stored({ p ->
RawRenderingEngine.fromPersistedName(p[K.RAW_COLOR_ENGINE_KEY])
}) { p, v -> p[K.RAW_COLOR_ENGINE_KEY] = v.name }
var rawToneMappingParameters: RawToneMappingParameters by stored({ p ->
RawToneMappingParameters(
agxBlackRelativeExposure = p[K.RAW_AGX_BLACK_RELATIVE_EXPOSURE_KEY]
?: RawToneMappingParameters.AGX_BLACK_RELATIVE_EXPOSURE_DEFAULT,
agxWhiteRelativeExposure = p[K.RAW_AGX_WHITE_RELATIVE_EXPOSURE_KEY]
?: RawToneMappingParameters.AGX_WHITE_RELATIVE_EXPOSURE_DEFAULT,
agxToe = p[K.RAW_AGX_TOE_KEY] ?: RawToneMappingParameters.AGX_TOE_DEFAULT,
agxShoulder = p[K.RAW_AGX_SHOULDER_KEY] ?: RawToneMappingParameters.AGX_SHOULDER_DEFAULT,
filmicBlackRelativeExposure = p[K.RAW_FILMIC_BLACK_RELATIVE_EXPOSURE_KEY]
?: RawToneMappingParameters.FILMIC_BLACK_RELATIVE_EXPOSURE_DEFAULT,
filmicWhiteRelativeExposure = p[K.RAW_FILMIC_WHITE_RELATIVE_EXPOSURE_KEY]
?: RawToneMappingParameters.FILMIC_WHITE_RELATIVE_EXPOSURE_DEFAULT,
useProfileToneMap = p[K.RAW_PROFILE_TONE_MAP_KEY] ?: true,
useOppoMasterToneMap = p[K.RAW_OPPO_MASTER_TONE_MAP_KEY] ?: false,
// Capture development has one supported adaptive-exposure path: HDRNet.
// Photo-level metadata may still disable it for an imported DNG.
lumixPhotoStyle = LumixPhotoStyle.fromPersistedValue(p[K.RAW_LUMIX_PHOTO_STYLE_KEY]),
canonPictureStyle = CanonPictureStyle.fromPersistedValue(p[K.RAW_CANON_PICTURE_STYLE_KEY]),
canonExposureCompensationEv = p[K.RAW_CANON_EXPOSURE_COMPENSATION_KEY]
?: RawToneMappingParameters.CANON_EXPOSURE_COMPENSATION_DEFAULT,
lumixColorMatchingEnabled = p[K.RAW_LUMIX_COLOR_MATCHING_KEY] ?: true,
hncsColorMatchingEnabled = p[K.RAW_HNCS_COLOR_MATCHING_KEY] ?: true,
canonUseR5ColorMatrix = p[K.RAW_CANON_USE_R5_COLOR_MATRIX_KEY] ?: false,
leicaUseM9ColorMatrix = p[K.RAW_LEICA_USE_M9_COLOR_MATRIX_KEY] ?: false,
usePhotonHdr = true
).normalized()
}) { p, value ->
val v = value.withPhotonHdr(true)
p[K.RAW_AGX_BLACK_RELATIVE_EXPOSURE_KEY] = v.agxBlackRelativeExposure
p[K.RAW_AGX_WHITE_RELATIVE_EXPOSURE_KEY] = v.agxWhiteRelativeExposure
p[K.RAW_AGX_TOE_KEY] = v.agxToe
p[K.RAW_AGX_SHOULDER_KEY] = v.agxShoulder
p[K.RAW_FILMIC_BLACK_RELATIVE_EXPOSURE_KEY] = v.filmicBlackRelativeExposure
p[K.RAW_FILMIC_WHITE_RELATIVE_EXPOSURE_KEY] = v.filmicWhiteRelativeExposure
p[K.RAW_PROFILE_TONE_MAP_KEY] = v.useProfileToneMap
p[K.RAW_OPPO_MASTER_TONE_MAP_KEY] = v.useOppoMasterToneMap
p[K.RAW_LUMIX_PHOTO_STYLE_KEY] = v.lumixPhotoStyle.assetName
p[K.RAW_CANON_PICTURE_STYLE_KEY] = v.canonPictureStyle.persistedValue
p[K.RAW_CANON_EXPOSURE_COMPENSATION_KEY] = v.canonExposureCompensationEv
p[K.RAW_LUMIX_COLOR_MATCHING_KEY] = v.lumixColorMatchingEnabled
p[K.RAW_HNCS_COLOR_MATCHING_KEY] = v.hncsColorMatchingEnabled
p[K.RAW_CANON_USE_R5_COLOR_MATRIX_KEY] = v.canonUseR5ColorMatrix
p[K.RAW_LEICA_USE_M9_COLOR_MATRIX_KEY] = v.leicaUseM9ColorMatrix
}
val rawAutoExposure: Boolean get() = false
/** 以下五项按 cameraId 存储 DNG 元数据校正。 */
var rawBlackLevelModes: Map<String, String> by stored({ p -> parseMapString(p[K.RAW_BLACK_LEVEL_MODES_KEY]) }) { p, v ->
p[K.RAW_BLACK_LEVEL_MODES_KEY] = serializeMapString(v)
}
var rawCustomBlackLevels: Map<String, Float> by stored({ p -> parseMapFloat(p[K.RAW_CUSTOM_BLACK_LEVELS_KEY]) }) { p, v ->
p[K.RAW_CUSTOM_BLACK_LEVELS_KEY] = serializeMapFloat(v)
}
var rawWhiteLevelModes: Map<String, String> by stored({ p -> parseMapString(p[K.RAW_WHITE_LEVEL_MODES_KEY]) }) { p, v ->
p[K.RAW_WHITE_LEVEL_MODES_KEY] = serializeMapString(v)
}
var rawCustomWhiteLevels: Map<String, Float> by stored({ p -> parseMapFloat(p[K.RAW_CUSTOM_WHITE_LEVELS_KEY]) }) { p, v ->
p[K.RAW_CUSTOM_WHITE_LEVELS_KEY] = serializeMapFloat(v)
}
var rawCfaCorrectionModes: Map<String, String> by stored({ p -> parseMapString(p[K.RAW_CFA_CORRECTION_MODES_KEY]) }) { p, v ->
p[K.RAW_CFA_CORRECTION_MODES_KEY] = serializeMapString(v)
}
var rawMaxSharpening: Float by stored({ p ->
RawSharpeningDefaults.normalize(p[K.RAW_MAX_SHARPENING_KEY] ?: RawSharpeningDefaults.DEFAULT_STRENGTH)
}) { p, v -> p[K.RAW_MAX_SHARPENING_KEY] = RawSharpeningDefaults.normalize(v) }
var rawMaxNoiseReduction: Float by stored({ p ->
RawDenoiseDefaults.normalize(p[K.RAW_MAX_NOISE_REDUCTION_KEY] ?: RawDenoiseDefaults.RAW_MAX_LUMA_STRENGTH)
}) { p, v -> p[K.RAW_MAX_NOISE_REDUCTION_KEY] = RawDenoiseDefaults.normalize(v) }
var rawMaxChromaNoiseReduction: Float by stored({ p ->
RawDenoiseDefaults.normalize(p[K.RAW_MAX_CHROMA_NOISE_REDUCTION_KEY] ?: RawDenoiseDefaults.RAW_MAX_CHROMA_STRENGTH)
}) { p, v -> p[K.RAW_MAX_CHROMA_NOISE_REDUCTION_KEY] = RawDenoiseDefaults.normalize(v) }
var gridStyle: GridStyle by stored({ p -> GridStyle.fromPersistedName(p[K.GRID_STYLE]) }) { p, v -> p[K.GRID_STYLE] = v.name }
/** Activity 窗口屏幕亮度,null 表示使用系统默认。 */
var windowScreenBrightness: Float? by stored({ p -> p[K.WINDOW_SCREEN_BRIGHTNESS]?.coerceIn(0f, 1f) }) { p, v ->
p.put(K.WINDOW_SCREEN_BRIGHTNESS, v?.coerceIn(0f, 1f))
}
var photoSavePath: PhotoSavePath by stored({ p -> PhotoSavePath.fromPersistedName(p[K.PHOTO_SAVE_PATH]) }) { p, v ->
p[K.PHOTO_SAVE_PATH] = v.name
}
/** 仅在 [photoSavePath] 为 EXTERNAL_TREE 时有意义。 */
var photoSaveTreeUri: String? by stored({ p -> p[K.PHOTO_SAVE_TREE_URI]?.takeIf { it.isNotBlank() } }) { p, v ->
p.put(K.PHOTO_SAVE_TREE_URI, v?.takeIf { it.isNotBlank() })
}
var vendorCaptureSettingsByLens: VendorCaptureSettingsByLens by stored({ p ->
VendorCaptureSettingsByLens.deserialize(p[K.VENDOR_CAPTURE_SETTINGS])
}) { p, v -> p.put(K.VENDOR_CAPTURE_SETTINGS, v.takeIf { it.isEnabled }?.serialize()) }
var customVendorKeySettings: CustomVendorKeySettings by stored({ p ->
CustomVendorKeySettings.deserialize(p[K.CUSTOM_VENDOR_KEY_SETTINGS])
}) { p, v -> p.put(K.CUSTOM_VENDOR_KEY_SETTINGS, v.takeIf { it.isEnabled }?.serialize()) }
var meteringMode: MeteringMode by stored({ p ->
MeteringMode.valueOf(p[K.METERING_MODE] ?: MeteringMode.SYSTEM_DEFAULT.name)
}) { p, v -> p[K.METERING_MODE] = v.name }
/** 摄像头方向校正:Map<CameraId, 旋转偏移角度(90/180/270)>,0 度不存储。 */
var cameraOrientationOffsets: Map<String, Int> by stored({ p ->
parseCameraOrientationOffsets(p[K.CAMERA_ORIENTATION_OFFSETS])
}) { p, v -> p[K.CAMERA_ORIENTATION_OFFSETS] = serializeCameraOrientationOffsets(v.filterValues { it != 0 }) }
/** 滤镜排序(ID 列表)。 */
var filterOrder: List<String> by stored({ p -> p[K.FILTER_ORDER]?.split(",")?.filter { it.isNotEmpty() } ?: emptyList() }) { p, v ->
p[K.FILTER_ORDER] = v.joinToString(",")
}
/** 边框排序(ID 列表)。 */
var frameOrder: List<String> by stored({ p -> p[K.FRAME_ORDER]?.split(",")?.filter { it.isNotEmpty() } ?: emptyList() }) { p, v ->
p[K.FRAME_ORDER] = v.joinToString(",")
}
/** 已保存的分类及排序,允许空分类。 */
var categoryOrder: List<String> by stored({ p -> readCategoryOrder(p) }) { p, v ->
p[K.CATEGORY_ORDER_JSON] = serializeCategoryOrder(v)
p.remove(K.CATEGORY_ORDER)
}
var lutSelectorMode: LutSelectorMode by stored({ p ->
runCatching { LutSelectorMode.valueOf(p[K.LUT_SELECTOR_MODE] ?: LutSelectorMode.Style.name) }
.getOrDefault(LutSelectorMode.Style)
}) { p, v -> p[K.LUT_SELECTOR_MODE] = v.name }
// 拍摄模式:RAW / JPG MAX / RAW MAX(含旧版本 key 推导)
private val storedUseRaw: Boolean by derived { p -> p[K.USE_RAW] ?: false }
private val hasCurrentMaxPreferences: Boolean by derived { p -> p.contains(K.USE_JPG_MAX) || p.contains(K.USE_RAW_MAX) }
private val legacyMultiFrameEnabled: Boolean by derived { p ->
p[K.LEGACY_USE_MULTI_FRAME] == true || p[K.LEGACY_USE_SUPER_RESOLUTION] == true
}
/** YUV 多帧降噪。RAW/HDR+ 与 YUV 降噪属于不同拍摄模式,专业模式下保留该偏好以便回到 PHOTO 时恢复。 */
var useJpgMax: Boolean by stored({ p ->
if (hasCurrentMaxPreferences) {
p[K.USE_JPG_MAX] ?: false
} else {
!storedUseRaw && (legacyMultiFrameEnabled || p[K.LEGACY_USE_HDR_COMPOSITION] == true)
}
}) { p, v -> p[K.USE_JPG_MAX] = v }
/** HDR+:RAW 多帧融合。 */
var useRawMax: Boolean by stored({ p ->
val requested = if (hasCurrentMaxPreferences) p[K.USE_RAW_MAX] ?: false else storedUseRaw && legacyMultiFrameEnabled
requested || storedUseRaw
}) { p, v -> p[K.USE_RAW_MAX] = v }
/** 使用 RAW 格式拍摄。读取结果综合 [useRawMax]/[useJpgMax];写入只记录 RAW 开关本身。 */
var useRaw: Boolean
get() = when {
useRawMax -> true
useJpgMax -> false
else -> storedUseRaw
}
set(value) {
mutablePreferences()[K.USE_RAW] = value
}
/** 多帧降噪固定不启用包围曝光。 */
val useJpgMaxHdrComposition: Boolean get() = false
var jpgMultiFrameDenoiseFrameCount: Int by stored({ p ->
p[K.JPG_MULTI_FRAME_DENOISE_FRAME_COUNT]?.let(MultiFrameConfig::normalizeDenoiseFrameCount)
?: MultiFrameConfig.DEFAULT_DENOISE_FRAME_COUNT
}) { p, v -> p[K.JPG_MULTI_FRAME_DENOISE_FRAME_COUNT] = MultiFrameConfig.normalizeDenoiseFrameCount(v) }
var jpgMultiFrameDenoiseOutputScale: Float by stored({ p ->
p[K.JPG_MULTI_FRAME_DENOISE_OUTPUT_SCALE]?.let {
MultiFrameConfig.normalizeOutputScale(outputScale = it, fallback = MultiFrameConfig.DEFAULT_SUPER_RESOLUTION_SCALE)
} ?: MultiFrameConfig.DEFAULT_SUPER_RESOLUTION_SCALE
}) { p, v ->
p[K.JPG_MULTI_FRAME_DENOISE_OUTPUT_SCALE] =
MultiFrameConfig.normalizeOutputScale(outputScale = v, fallback = MultiFrameConfig.DEFAULT_SUPER_RESOLUTION_SCALE)
}
/** 切换到不支持包围曝光的模式时同时关闭包围曝光。 */
var hdrPlusMergeMode: MgcRawMaxMode by stored({ p ->
MgcRawMaxMode.entries.firstOrNull { it.name == p[K.HDR_PLUS_MERGE_MODE] } ?: MgcRawMaxMode.DEFAULT
}) { p, v ->
p[K.HDR_PLUS_MERGE_MODE] = v.name
if (!v.supportsBracketExposure) p[K.HDR_PLUS_BRACKET_EXPOSURE_ENABLED] = false
}
/** 写入时按当前合成模式约束,并按新状态重新归一化帧数。 */
var hdrPlusBracketExposureEnabled: Boolean by stored({ p ->
hdrPlusMergeMode.supportsBracketExposure &&
(p[K.HDR_PLUS_BRACKET_EXPOSURE_ENABLED] ?: MultiFrameConfig.DEFAULT_HDR_PLUS_BRACKET_EXPOSURE)
}) { p, v ->
val enabled = v && hdrPlusMergeMode.supportsBracketExposure
p[K.HDR_PLUS_BRACKET_EXPOSURE_ENABLED] = enabled
p[K.HDR_PLUS_FRAME_COUNT] = MultiFrameConfig.normalizeHdrPlusFrameCount(
p[K.HDR_PLUS_FRAME_COUNT] ?: MultiFrameConfig.DEFAULT_HDR_PLUS_FRAME_COUNT,
bracketExposureEnabled = enabled,
)
}
var hdrPlusFrameCount: Int by stored({ p ->
p[K.HDR_PLUS_FRAME_COUNT]?.let {
MultiFrameConfig.normalizeHdrPlusFrameCount(it, bracketExposureEnabled = hdrPlusBracketExposureEnabled)
} ?: MultiFrameConfig.DEFAULT_HDR_PLUS_FRAME_COUNT
}) { p, v ->
p[K.HDR_PLUS_FRAME_COUNT] =
MultiFrameConfig.normalizeHdrPlusFrameCount(v, bracketExposureEnabled = hdrPlusBracketExposureEnabled)
}
var hdrPlusLongFrameExposureEv: Float by stored({ p ->
MultiFrameConfig.normalizeLongFrameExposureEv(
p[K.HDR_PLUS_LONG_FRAME_EXPOSURE_EV] ?: MultiFrameConfig.LONG_FRAME_EXPOSURE_EV.toFloat(),
)
}) { p, v -> p[K.HDR_PLUS_LONG_FRAME_EXPOSURE_EV] = MultiFrameConfig.normalizeLongFrameExposureEv(v) }
var hdrPlusShortFrameExposureEv: Float by stored({ p ->
MultiFrameConfig.normalizeShortFrameExposureEv(
p[K.HDR_PLUS_SHORT_FRAME_EXPOSURE_EV] ?: MultiFrameConfig.DEFAULT_SHORT_FRAME_EXPOSURE_EV,
)
}) { p, v -> p[K.HDR_PLUS_SHORT_FRAME_EXPOSURE_EV] = MultiFrameConfig.normalizeShortFrameExposureEv(v) }
var mlAeMaxHdrRatio: Float by stored({ p ->
RawSceneExposureMath.normalizeConfiguredMaxHdrRatio(
p[K.ML_AE_MAX_HDR_RATIO] ?: RawSceneExposureMath.FAST_MOMENTS_MAX_HDR_RATIO,
)
}) { p, v -> p[K.ML_AE_MAX_HDR_RATIO] = RawSceneExposureMath.normalizeConfiguredMaxHdrRatio(v) }
/** RAWmax 输出放大算法。RAISR 自带放大倍率,选中时把输出倍率锁定到该倍率。 */
var rawOutputUpscaleMode: RawOutputUpscaleMode by stored({ p ->
RawOutputUpscaleMode.fromName(p[K.RAW_OUTPUT_UPSCALE_MODE])
}) { p, v ->
p[K.RAW_OUTPUT_UPSCALE_MODE] = v.name
v.pinnedOutputScale?.let { p[K.RAW_MAX_OUTPUT_SCALE] = it }
}
/** RAWmax 输出倍率。 */
var rawMaxOutputScale: Float by stored({ p ->
rawOutputUpscaleMode.resolveOutputScale(
(p[K.RAW_MAX_OUTPUT_SCALE] ?: p[K.LEGACY_RAW_SUPER_RESOLUTION_SCALE])?.let {
MultiFrameConfig.normalizeOutputScale(outputScale = it, fallback = MultiFrameConfig.DEFAULT_SUPER_RESOLUTION_SCALE)
} ?: MultiFrameConfig.DEFAULT_SUPER_RESOLUTION_SCALE
)
}) { p, v -> p[K.RAW_MAX_OUTPUT_SCALE] = rawOutputUpscaleMode.resolveOutputScale(v) }
/** RAW 色彩标定矩阵来源。 */
var rawColorCalibrationMode: RawColorCalibrationMode by stored({ p ->
RawColorCalibrationMode.fromName(p[K.RAW_COLOR_CALIBRATION_MODE])
}) { p, v -> p[K.RAW_COLOR_CALIBRATION_MODE] = v.name }
/** 是否优先使用 HEIC 导出,开启时关闭 JPEG 4:4:4。 */
var useHeicExport: Boolean by stored({ p -> p[K.USE_HEIC_EXPORT] ?: false }) { p, v ->
p[K.USE_HEIC_EXPORT] = v
if (v) p[K.USE_JPEG_444_EXPORT] = false
}
/** 是否使用 JPEG 4:4:4 色度采样导出(与 HEIC 互斥)。 */
var useJpeg444Export: Boolean by stored({ p -> (p[K.USE_JPEG_444_EXPORT] ?: false) && !useHeicExport }) { p, v ->
p[K.USE_JPEG_444_EXPORT] = v
if (v) p[K.USE_HEIC_EXPORT] = false
}
var accentColor: Int by stored({ p ->
AppAppearance.opaqueAccent(p[K.ACCENT_COLOR] ?: AppAppearance.DEFAULT_ACCENT_COLOR)
}) { p, v -> p[K.ACCENT_COLOR] = AppAppearance.opaqueAccent(v) }
var captureButtonStyle: CaptureButtonStyle by stored({ p ->
CaptureButtonStyle.fromPersistedName(p[K.CAPTURE_BUTTON_STYLE])
}) { p, v -> p[K.CAPTURE_BUTTON_STYLE] = v.name }
var captureButtonImagePath: String? by stored({ p -> p[K.CAPTURE_BUTTON_IMAGE_PATH]?.takeIf { it.isNotBlank() } }) { p, v ->
p.put(K.CAPTURE_BUTTON_IMAGE_PATH, v)
}
/** DRO 模式(预设携带,拍摄时用于曝光补偿与处理)。 */
var droMode: String by stored({ p ->
p[K.DRO_MODE] ?: if (p[K.RAW_DRO_ENABLED_KEY] == true) "DR100" else "OFF"
}) { p, v ->
val mode = RawProcessingPreferences.DROMode.fromPersistedName(v)
p[K.DRO_MODE] = mode.name
p[K.RAW_DRO_ENABLED_KEY] = mode.isEnabled
}
var logCurve: TransferCurve by stored({ p ->
TransferCurve.fromPersistedName(p[K.LOG_CURVE] ?: TransferCurve.SRGB.name)
}) { p, v -> p[K.LOG_CURVE] = v.name }
/** 按 Log 曲线名存储的 RAW 还原 LUT(未保存的曲线返回默认值)。写入时只保存有变化的条目。 */
var rawLuts: Map<String, String> by stored({ p -> parseRawLuts(p) }) { p, v ->
val current = parseRawLuts(p)
v.forEach { (curve, lut) -> if (current[curve] != lut) p[stringPreferencesKey("${curve}_raw_lut")] = lut }
}
var videoResolution: VideoResolutionPreset by stored({ p ->
VideoResolutionPreset.entries.firstOrNull { it.name == p[K.VIDEO_RESOLUTION] } ?: VideoResolutionPreset.FHD_1080P
}) { p, v -> p[K.VIDEO_RESOLUTION] = v.name }
var videoFps: VideoFpsPreset by stored({ p ->
VideoFpsPreset.entries.firstOrNull { it.name == p[K.VIDEO_FPS] } ?: VideoFpsPreset.FPS_30
}) { p, v -> p[K.VIDEO_FPS] = v.name }
var videoLogProfile: VideoLogProfile by stored({ p -> VideoLogProfile.fromPersistedName(p[K.VIDEO_LOG_PROFILE]) }) { p, v ->
p[K.VIDEO_LOG_PROFILE] = v.name
}
var videoRecordingPath: VideoRecordingPath by stored({ p ->
VideoRecordingPath.fromPersistedName(p[K.VIDEO_RECORDING_PATH])
}) { p, v -> p[K.VIDEO_RECORDING_PATH] = v.name }
/** 仅在 [videoRecordingPath] 为 EXTERNAL_TREE 时有意义。 */
var videoRecordingTreeUri: String? by stored({ p -> p[K.VIDEO_RECORDING_TREE_URI]?.takeIf { it.isNotBlank() } }) { p, v ->
p.put(K.VIDEO_RECORDING_TREE_URI, v?.takeIf { it.isNotBlank() })
}
var videoStabilizationMode: VideoStabilizationMode by stored({ p ->
if (p[K.VIDEO_ENHANCED_STABILIZATION_ENABLED] == true) {
VideoStabilizationMode.ENHANCED
} else {
VideoStabilizationMode.entries.firstOrNull { it.name == p[K.VIDEO_STABILIZATION_MODE] }
?: VideoStabilizationMode.OIS
}
}) { p, v ->
p[K.VIDEO_STABILIZATION_MODE] = v.name
p.remove(K.VIDEO_ENHANCED_STABILIZATION_ENABLED)
}
var videoEnhancedStabilizationStrength: Float by stored({ p ->
normalizeStabilizationStrength(p[K.VIDEO_ENHANCED_STABILIZATION_STRENGTH] ?: DEFAULT_VIDEO_STABILIZATION_STRENGTH)
}) { p, v -> p[K.VIDEO_ENHANCED_STABILIZATION_STRENGTH] = normalizeStabilizationStrength(v) }
var videoEnhancedStabilizationLookahead: Int by stored({ p ->
normalizeStabilizationLookahead(p[K.VIDEO_ENHANCED_STABILIZATION_LOOKAHEAD] ?: DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD)
}) { p, v -> p[K.VIDEO_ENHANCED_STABILIZATION_LOOKAHEAD] = normalizeStabilizationLookahead(v) }
var externalLensStabilizationConfig: ExternalLensStabilizationConfig by stored({ p ->
ExternalLensStabilizationConfig(
physicalCameraId = p[K.EXTERNAL_LENS_STABILIZATION_CAMERA_ID].orEmpty(),
magnification = p[K.EXTERNAL_LENS_STABILIZATION_MAGNIFICATION]
?: ExternalLensStabilizationConfig.Disabled.magnification,
).normalized()
}) { p, value ->
val v = value.normalized()
if (v.isEnabled) {
p[K.EXTERNAL_LENS_STABILIZATION_CAMERA_ID] = v.physicalCameraId
p[K.EXTERNAL_LENS_STABILIZATION_MAGNIFICATION] = v.magnification
} else {
p.remove(K.EXTERNAL_LENS_STABILIZATION_CAMERA_ID)
p.remove(K.EXTERNAL_LENS_STABILIZATION_MAGNIFICATION)
}
}
var phantomPipCrop: PhantomPipCrop by stored({ p ->
PhantomPipCrop(
left = p[K.PHANTOM_PIP_CROP_LEFT] ?: 0f,
top = p[K.PHANTOM_PIP_CROP_TOP] ?: 0f,
right = p[K.PHANTOM_PIP_CROP_RIGHT] ?: 1f,
bottom = p[K.PHANTOM_PIP_CROP_BOTTOM] ?: 1f
).normalized()
}) { p, value ->
val v = value.normalized()
p[K.PHANTOM_PIP_CROP_LEFT] = v.left
p[K.PHANTOM_PIP_CROP_TOP] = v.top
p[K.PHANTOM_PIP_CROP_RIGHT] = v.right
p[K.PHANTOM_PIP_CROP_BOTTOM] = v.bottom
}
/** 加密存储;写入空白值删除。 */
var openAIApiKey: String? by stored({ p ->
p[ENCRYPTED_OPEN_AI_API_KEY_PREFERENCE]?.let { encrypted ->
runCatching { openAiApiKeyCipher.decrypt(encrypted) }.getOrNull()
}
}) { p, v ->
p.put(ENCRYPTED_OPEN_AI_API_KEY_PREFERENCE, v?.takeIf { it.isNotBlank() }?.let(openAiApiKeyCipher::encrypt))
}
/** 自定义焦段/倍率,正数为 35mm 等效焦段,负数为精确倍率。 */
var customFocalLengths: List<Float> by stored({ p ->
p[K.CUSTOM_FOCAL_LENGTHS]?.split(",")?.filter { it.isNotEmpty() }
?.mapNotNull { CustomFocalLengthValue.parsePersisted(it) }
?: listOf(35f, 50f, 85f, 200f)
}) { p, v -> p[K.CUSTOM_FOCAL_LENGTHS] = v.joinToString(",") { CustomFocalLengthValue.serialize(it) } }
/** 自定义镜头 ID。 */
var customLensIds: List<String> by stored({ p -> parseLensIds(p[K.CUSTOM_LENS_IDS]) }) { p, v ->
p[K.CUSTOM_LENS_IDS] = normalizeLensIds(v).joinToString(",")
}
/** 所有发现来源共用的镜头 ID 黑名单。 */
var lensIdBlacklist: List<String> by stored({ p -> parseLensIds(p[K.LENS_ID_BLACKLIST]) }) { p, v ->
p[K.LENS_ID_BLACKLIST] = normalizeLensIds(v).joinToString(",")
}
/** 用户新增的 ISZ 虚拟镜头。 */
var iszLensConfigs: List<IszLensConfig> by stored({ p -> IszLensConfig.deserializeList(p[K.ISZ_LENS_CONFIGS]) }) { p, v ->
val sanitized = v.filter { it.baseCameraId.isNotBlank() && it.iszZoomRatio >= 1f }.distinctBy { it.virtualCameraId }
p.put(K.ISZ_LENS_CONFIGS, sanitized.takeIf { it.isNotEmpty() }?.let(IszLensConfig::serializeList))
}
/** 用户选择的主摄 ID。 */
var preferredMainCameraId: String? by stored({ p -> p[K.PREFERRED_MAIN_CAMERA_ID]?.takeIf { it.isNotBlank() } }) { p, v ->
p.put(K.PREFERRED_MAIN_CAMERA_ID, v?.trim()?.takeIf { it.isNotEmpty() })
}
/** 用户选择的微距镜头 ID。 */
var preferredMacroCameraId: String? by stored({ p -> p[K.PREFERRED_MACRO_CAMERA_ID]?.takeIf { it.isNotBlank() } }) { p, v ->
p.put(K.PREFERRED_MACRO_CAMERA_ID, v?.trim()?.takeIf { it.isNotEmpty() })
}
/** 强制启用的逻辑/物理镜头绑定,格式 logical/physical。 */
var logicalCameraBindingWhitelist: List<String> by stored({ p ->
parseLogicalCameraBindingWhitelist(p[K.LOGICAL_CAMERA_BINDING_WHITELIST])
}) { p, v -> p[K.LOGICAL_CAMERA_BINDING_WHITELIST] = normalizeLogicalCameraBindingWhitelist(v).joinToString(",") }
/** 隐藏的焦段(35mm 等效)。 */
var hiddenFocalLengths: List<Float> by stored({ p ->
p[K.HIDDEN_FOCAL_LENGTHS]?.split(",")?.filter { it.isNotEmpty() }?.mapNotNull { it.toFloatOrNull() } ?: emptyList()
}) { p, v -> p[K.HIDDEN_FOCAL_LENGTHS] = v.joinToString(",") }
var rawSpectralFilmTuningsByStock: Map<String, SpectralFilmTuning> by stored({ p ->
parseSpectralFilmTunings(p[K.RAW_SPECTRAL_FILM_TUNINGS_BY_STOCK_KEY])
}) { p, v -> p[K.RAW_SPECTRAL_FILM_TUNINGS_BY_STOCK_KEY] = serializeSpectralFilmTunings(v.mapValues { it.value.normalized() }) }
var customCaptureSettings by json(
"custom_capture_settings_v1",
decode = CustomCaptureSettings::fromJson,
encode = CustomCaptureSettings::toJson,
)
/** 降噪等级:0=Off, 1=Fast, 2=High Quality, 3=ZSL, 4=Minimal。 */
var nrLevel by int("nr_level", NoiseReductionLevel.DEFAULT, normalize = NoiseReductionLevel::normalize)
var videoNrLevel by int("video_nr_level", NoiseReductionLevel.DEFAULT, normalize = NoiseReductionLevel::normalize)
var activeEffectParams: EffectParams by stored({ EffectParams.fromJson(activeEffectParamsJson) }) { _, v ->
activeEffectParamsJson = v.toJson()
}
var customPresets: List<CameraPreset> by stored({ CameraPreset.listFromJson(customPresetsJson) }) { _, v ->
customPresetsJson = CameraPreset.listToJson(v)
}
/** 一次写入某个镜头的全部 DNG 元数据校正,保证它们对应同一个 cameraId。 */
fun putRawDngMetadataCorrections(cameraId: String, corrections: IszRawDngMetadataCorrections) {
if (cameraId.isBlank()) return
rawBlackLevelModes = rawBlackLevelModes + (cameraId to corrections.blackLevelMode)
rawCustomBlackLevels = rawCustomBlackLevels + (cameraId to corrections.customBlackLevel)
rawWhiteLevelModes = rawWhiteLevelModes + (cameraId to corrections.whiteLevelMode)
rawCustomWhiteLevels = rawCustomWhiteLevels + (cameraId to corrections.customWhiteLevel)
rawCfaCorrectionModes = rawCfaCorrectionModes + (cameraId to corrections.cfaCorrectionMode)
}
fun removeRawDngMetadataCorrections(cameraId: String) {
if (cameraId.isBlank()) return
rawBlackLevelModes = rawBlackLevelModes - cameraId
rawCustomBlackLevels = rawCustomBlackLevels - cameraId
rawWhiteLevelModes = rawWhiteLevelModes - cameraId
rawCustomWhiteLevels = rawCustomWhiteLevels - cameraId
rawCfaCorrectionModes = rawCfaCorrectionModes - cameraId
}
fun rawDcpIdForLens(lensId: String?): String? = resolveRawDcpIdForLens(rawDcpId, rawDcpIdsByLens, lensId)
fun hasRawDcpLensOverride(lensId: String?): Boolean {
val normalizedLensId = lensId?.takeIf { it.isNotBlank() } ?: return false
return rawDcpIdsByLens.containsKey(normalizedLensId)
}
fun rawNoiseProfileIdForLens(lensId: String?): String {
val normalizedLensId = lensId?.takeIf { it.isNotBlank() }
?: return rawNoiseProfileId
return rawNoiseProfileIdsByLens[normalizedLensId] ?: rawNoiseProfileId
}
companion object {
fun resolveRawDcpIdForLens(
rawDcpId: String?,
rawDcpIdsByLens: Map<String, String?>,
lensId: String?,
): String? {
val normalizedLensId = lensId?.takeIf { it.isNotBlank() } ?: return rawDcpId
return if (rawDcpIdsByLens.containsKey(normalizedLensId)) rawDcpIdsByLens[normalizedLensId] else rawDcpId
}
}
}
internal val openAiApiKeyCipher = OpenAiApiKeyCipher()
// ------------------------------------------------------------------------------------------------
// 字段委托
/** 单 key 字段:读取时解码,写入时编码;写入 null 删除 key。 */
private class KeyField<S, T>(
private val key: Preferences.Key<S>,
private val default: T,
private val decode: (S) -> T,
private val encode: (T & Any) -> S,
) : ReadWriteProperty<UserPreferences, T> {
override fun getValue(thisRef: UserPreferences, property: KProperty<*>): T =
thisRef.raw[key]?.let(decode) ?: default
override fun setValue(thisRef: UserPreferences, property: KProperty<*>, value: T) {
val preferences = thisRef.mutablePreferences()
if (value == null) preferences.remove(key) else preferences[key] = encode(value)
}
}
/** 由一个或多个 key 计算出的只读字段,同一实例内只计算一次。 */
private class DerivedField<T>(
private val read: UserPreferences.(Preferences) -> T,
) : ReadOnlyProperty<UserPreferences, T> {
override fun getValue(thisRef: UserPreferences, property: KProperty<*>): T =
thisRef.cached(property.name) { thisRef.read(thisRef.raw) }
}
/** 由一个或多个 key 读写的字段:读取结果同一实例内只计算一次,写入后失效。 */
private class StoredField<T>(
private val read: UserPreferences.(Preferences) -> T,
private val write: UserPreferences.(MutablePreferences, T) -> Unit,
) : ReadWriteProperty<UserPreferences, T> {
override fun getValue(thisRef: UserPreferences, property: KProperty<*>): T =
thisRef.cached(property.name) { thisRef.read(thisRef.raw) }
override fun setValue(thisRef: UserPreferences, property: KProperty<*>, value: T) {
thisRef.write(thisRef.mutablePreferences(), value)
thisRef.invalidate()
}
}
/** 以字符串(JSON 等)存储的可空字段,同一实例内只解码一次;写入 null 删除 key。 */
private class JsonField<T : Any>(
private val key: Preferences.Key<String>,
private val decode: (String?) -> T?,
private val encode: (T) -> String,
) : ReadWriteProperty<UserPreferences, T?> {
override fun getValue(thisRef: UserPreferences, property: KProperty<*>): T? =
thisRef.cached(property.name) { decode(thisRef.raw[key]) }
override fun setValue(thisRef: UserPreferences, property: KProperty<*>, value: T?) {
val preferences = thisRef.mutablePreferences()
if (value == null) preferences.remove(key) else preferences[key] = encode(value)
}
}
private fun bool(key: String, default: Boolean): ReadWriteProperty<UserPreferences, Boolean> =
KeyField(booleanPreferencesKey(key), default, { it }, { it })
private fun int(key: String, default: Int, normalize: (Int) -> Int = { it }): ReadWriteProperty<UserPreferences, Int> =
KeyField(intPreferencesKey(key), default, normalize, normalize)
private fun long(key: String, default: Long): ReadWriteProperty<UserPreferences, Long> =
KeyField(longPreferencesKey(key), default, { it }, { it })
private fun float(key: String, default: Float, normalize: (Float) -> Float = { it }): ReadWriteProperty<UserPreferences, Float> =
KeyField(floatPreferencesKey(key), default, normalize, normalize)
private fun string(key: String, default: String): ReadWriteProperty<UserPreferences, String> =
KeyField(stringPreferencesKey(key), default, { it }, { it })
private fun nullableString(key: String): ReadWriteProperty<UserPreferences, String?> =
KeyField(stringPreferencesKey(key), null, { it }, { it })
/** 以枚举名存储;存储值无法识别时回退到 [default]。 */
private inline fun <reified E : Enum<E>> enum(key: String, default: E): ReadWriteProperty<UserPreferences, E> =
KeyField(stringPreferencesKey(key), default, { stored -> enumValues<E>().firstOrNull { it.name == stored } ?: default }, { it.name })
private fun <T : Any> json(key: String, decode: (String?) -> T?, encode: (T) -> String): ReadWriteProperty<UserPreferences, T?> =
JsonField(stringPreferencesKey(key), decode, encode)
private fun <T> stored(
read: UserPreferences.(Preferences) -> T,
write: UserPreferences.(MutablePreferences, T) -> Unit,
): ReadWriteProperty<UserPreferences, T> = StoredField(read, write)
/** 值为 null 时删除 key。 */
private fun <T> MutablePreferences.put(key: Preferences.Key<T>, value: T?) {
if (value == null) remove(key) else this[key] = value
}
private fun normalizeLensIds(lensIds: List<String>): List<String> =
lensIds.map { it.trim() }.filter { it.isNotEmpty() }.distinct()
private fun normalizeNoiseProfileIdsByLens(profileIdsByLens: Map<String, String?>): Map<String, String> =
profileIdsByLens.mapNotNull { (lensId, profileId) ->
val normalizedLensId = lensId.takeIf { it.isNotBlank() }
val normalizedProfileId = profileId?.takeIf { it.isNotBlank() }
if (normalizedLensId != null && normalizedProfileId != null) normalizedLensId to normalizedProfileId else null
}.toMap()
private fun <T> derived(read: UserPreferences.(Preferences) -> T): ReadOnlyProperty<UserPreferences, T> = DerivedField(read)
// ------------------------------------------------------------------------------------------------
// 多 key 字段与旧版本兼容读取使用的 key。key 字符串是持久化数据的一部分,不可修改。
internal object PreferenceKeys {
val TOP_SHEET_ASPECT_RATIOS = stringPreferencesKey("top_sheet_aspect_ratios")
val CUSTOM_ASPECT_RATIOS = stringPreferencesKey("custom_aspect_ratios")
val LUT_ID_KEY = stringPreferencesKey("lut_id")
val LEGACY_PHANTOM_LUT_ID_KEY = stringPreferencesKey("phantom_lut_id")
val RAW_BASELINE_LUT_ID_KEY = stringPreferencesKey("raw_baseline_lut_id")
val RAW_BASELINE_LUT_CONFIGURED_KEY = booleanPreferencesKey("raw_baseline_lut_configured")
val RAW_DCP_IDS_BY_LENS_KEY = stringPreferencesKey("raw_dcp_ids_by_lens")
val RAW_NOISE_PROFILE_ID_KEY = stringPreferencesKey("raw_noise_profile_id")
val RAW_NOISE_PROFILE_IDS_BY_LENS_KEY = stringPreferencesKey("raw_noise_profile_ids_by_lens")
val RAW_HNCS_FILM_CURVE_MODE_KEY = stringPreferencesKey("raw_hncs_film_curve_mode")
val RAW_COLOR_ENGINE_KEY = stringPreferencesKey("raw_color_engine")
val RAW_AGX_BLACK_RELATIVE_EXPOSURE_KEY = floatPreferencesKey("raw_agx_black_relative_exposure")
val RAW_AGX_WHITE_RELATIVE_EXPOSURE_KEY = floatPreferencesKey("raw_agx_white_relative_exposure")
val RAW_AGX_TOE_KEY = floatPreferencesKey("raw_agx_toe")
val RAW_AGX_SHOULDER_KEY = floatPreferencesKey("raw_agx_shoulder")
val RAW_FILMIC_BLACK_RELATIVE_EXPOSURE_KEY = floatPreferencesKey("raw_filmic_black_relative_exposure")
val RAW_FILMIC_WHITE_RELATIVE_EXPOSURE_KEY = floatPreferencesKey("raw_filmic_white_relative_exposure")
val RAW_PROFILE_TONE_MAP_KEY = booleanPreferencesKey("raw_profile_tone_map")
val RAW_OPPO_MASTER_TONE_MAP_KEY = booleanPreferencesKey("raw_oppo_master_tone_map")
val RAW_LUMIX_PHOTO_STYLE_KEY = stringPreferencesKey("raw_lumix_photo_style")
val RAW_CANON_PICTURE_STYLE_KEY = stringPreferencesKey("raw_canon_picture_style")
val RAW_CANON_EXPOSURE_COMPENSATION_KEY = floatPreferencesKey("raw_canon_exposure_compensation_ev")
val RAW_LUMIX_COLOR_MATCHING_KEY = booleanPreferencesKey("raw_lumix_color_matching_enabled")
val RAW_HNCS_COLOR_MATCHING_KEY = booleanPreferencesKey("raw_hncs_color_matching_enabled")
val RAW_CANON_USE_R5_COLOR_MATRIX_KEY = booleanPreferencesKey("raw_canon_use_r5_color_matrix")
val RAW_LEICA_USE_M9_COLOR_MATRIX_KEY = booleanPreferencesKey("raw_leica_use_m9_color_matrix")
val RAW_DRO_ENABLED_KEY = booleanPreferencesKey("raw_dro_enabled")
val RAW_SPECTRAL_FILM_TUNINGS_BY_STOCK_KEY = stringPreferencesKey("raw_spectral_film_tunings_by_stock")
val RAW_BLACK_LEVEL_MODES_KEY = stringPreferencesKey("raw_black_level_modes")
val RAW_CUSTOM_BLACK_LEVELS_KEY = stringPreferencesKey("raw_custom_black_levels")
val RAW_WHITE_LEVEL_MODES_KEY = stringPreferencesKey("raw_white_level_modes")
val RAW_CUSTOM_WHITE_LEVELS_KEY = stringPreferencesKey("raw_custom_white_levels")
val RAW_CFA_CORRECTION_MODES_KEY = stringPreferencesKey("raw_cfa_correction_modes")
val RAW_MAX_SHARPENING_KEY = floatPreferencesKey("raw_max_sharpening")
val RAW_MAX_NOISE_REDUCTION_KEY = floatPreferencesKey("raw_max_noise_reduction")
val RAW_MAX_CHROMA_NOISE_REDUCTION_KEY = floatPreferencesKey("raw_max_chroma_noise_reduction")
val GRID_STYLE = stringPreferencesKey("grid_style")
val WINDOW_SCREEN_BRIGHTNESS = floatPreferencesKey("window_screen_brightness")
val PHOTO_SAVE_PATH = stringPreferencesKey("photo_save_path")
val PHOTO_SAVE_TREE_URI = stringPreferencesKey("photo_save_tree_uri")
val VENDOR_CAPTURE_SETTINGS = stringPreferencesKey("vendor_capture_settings")
val CUSTOM_VENDOR_KEY_SETTINGS = stringPreferencesKey("custom_vendor_key_settings")
val USE_RAW = booleanPreferencesKey("use_raw")
val METERING_MODE = stringPreferencesKey("metering_mode")
val FILTER_ORDER = stringPreferencesKey("filter_order")
val FRAME_ORDER = stringPreferencesKey("frame_order")
val CATEGORY_ORDER = stringPreferencesKey("category_order")
val CATEGORY_ORDER_JSON = stringPreferencesKey("category_order_json")
val LUT_SELECTOR_MODE = stringPreferencesKey("lut_selector_mode")
val CAMERA_ORIENTATION_OFFSETS = stringPreferencesKey("camera_orientation_offsets")
val USE_JPG_MAX = booleanPreferencesKey("use_jpg_max")
val USE_RAW_MAX = booleanPreferencesKey("use_raw_max")
val LEGACY_USE_MULTI_FRAME = booleanPreferencesKey("use_multi_frame")
val LEGACY_USE_HDR_COMPOSITION = booleanPreferencesKey("use_hdr_composition")
val JPG_MULTI_FRAME_DENOISE_FRAME_COUNT = intPreferencesKey("jpg_multi_frame_denoise_frame_count")
val JPG_MULTI_FRAME_DENOISE_OUTPUT_SCALE = floatPreferencesKey("jpg_multi_frame_denoise_output_scale")
val HDR_PLUS_FRAME_COUNT = intPreferencesKey("hdr_plus_frame_count")
val HDR_PLUS_MERGE_MODE = stringPreferencesKey("hdr_plus_merge_mode")
val HDR_PLUS_BRACKET_EXPOSURE_ENABLED = booleanPreferencesKey("hdr_plus_bracket_exposure_enabled")
val HDR_PLUS_LONG_FRAME_EXPOSURE_EV = floatPreferencesKey("hdr_plus_long_frame_exposure_ev")
val HDR_PLUS_SHORT_FRAME_EXPOSURE_EV = floatPreferencesKey("hdr_plus_short_frame_exposure_ev")
val ML_AE_MAX_HDR_RATIO = floatPreferencesKey("ml_ae_max_hdr_ratio")
val LEGACY_USE_SUPER_RESOLUTION = booleanPreferencesKey("use_super_resolution")
val RAW_MAX_OUTPUT_SCALE = floatPreferencesKey("raw_max_output_scale")
val RAW_OUTPUT_UPSCALE_MODE = stringPreferencesKey("raw_output_upscale_mode")
val RAW_COLOR_CALIBRATION_MODE = stringPreferencesKey("raw_color_calibration_mode")
val LEGACY_RAW_SUPER_RESOLUTION_SCALE = floatPreferencesKey("raw_super_resolution_scale")
val USE_HEIC_EXPORT = booleanPreferencesKey("use_heic_export")
val USE_JPEG_444_EXPORT = booleanPreferencesKey("use_jpeg_444_export")
val CAPTURE_BUTTON_STYLE = stringPreferencesKey("capture_button_style")
val ACCENT_COLOR = intPreferencesKey("ui_accent_color")
val CAPTURE_BUTTON_IMAGE_PATH = stringPreferencesKey("capture_button_image_path")
val DRO_MODE = stringPreferencesKey("dro_mode")
val COLOR_SPACE = stringPreferencesKey("color_space")
val LOG_CURVE = stringPreferencesKey("log_curve")
val VIDEO_RESOLUTION = stringPreferencesKey("video_resolution")
val VIDEO_FPS = stringPreferencesKey("video_fps")
val VIDEO_LOG_PROFILE = stringPreferencesKey("video_log_profile")
val VIDEO_BITRATE = stringPreferencesKey("video_bitrate")
val VIDEO_RECORDING_PATH = stringPreferencesKey("video_recording_path")
val VIDEO_RECORDING_TREE_URI = stringPreferencesKey("video_recording_tree_uri")
val VIDEO_STABILIZATION_MODE = stringPreferencesKey("video_stabilization_mode")
val VIDEO_ENHANCED_STABILIZATION_ENABLED = booleanPreferencesKey("video_enhanced_stabilization_enabled")
val VIDEO_ENHANCED_STABILIZATION_STRENGTH = floatPreferencesKey("video_enhanced_stabilization_strength")
val VIDEO_ENHANCED_STABILIZATION_LOOKAHEAD = intPreferencesKey("video_enhanced_stabilization_lookahead")
val EXTERNAL_LENS_STABILIZATION_CAMERA_ID = stringPreferencesKey("external_lens_stabilization_camera_id")
val EXTERNAL_LENS_STABILIZATION_MAGNIFICATION = floatPreferencesKey("external_lens_stabilization_magnification")
val PHANTOM_PIP_CROP_LEFT = floatPreferencesKey("phantom_pip_crop_left")
val PHANTOM_PIP_CROP_TOP = floatPreferencesKey("phantom_pip_crop_top")
val PHANTOM_PIP_CROP_RIGHT = floatPreferencesKey("phantom_pip_crop_right")
val PHANTOM_PIP_CROP_BOTTOM = floatPreferencesKey("phantom_pip_crop_bottom")
val CUSTOM_FOCAL_LENGTHS = stringPreferencesKey("custom_focal_lengths")
val CUSTOM_LENS_IDS = stringPreferencesKey("custom_lens_ids")
val LENS_ID_BLACKLIST = stringPreferencesKey("lens_id_blacklist")
val ISZ_LENS_CONFIGS = stringPreferencesKey("isz_lens_configs")
val PREFERRED_MAIN_CAMERA_ID = stringPreferencesKey("preferred_main_camera_id")
val PREFERRED_MACRO_CAMERA_ID = stringPreferencesKey("preferred_macro_camera_id")
val LOGICAL_CAMERA_BINDING_WHITELIST = stringPreferencesKey("logical_camera_binding_whitelist")
val HIDDEN_FOCAL_LENGTHS = stringPreferencesKey("hidden_focal_lengths")
}
@@ -0,0 +1,231 @@
package com.hinnka.mycamera.data
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.stringPreferencesKey
import com.hinnka.mycamera.MyCameraApplication
import com.hinnka.mycamera.R
import com.hinnka.mycamera.camera.AspectRatio
import com.hinnka.mycamera.color.TransferCurve
import com.hinnka.mycamera.model.CameraPreset
import com.hinnka.mycamera.raw.SpectralFilmTuning
import org.json.JSONArray
import org.json.JSONObject
// UserPreferences 字段的解析 / 序列化函数,Repository 的写入方法与 UserPreferences 的读取共用。
/** 内置分类在当前语言下的显示名;持久化时以稳定标识存储。 */
internal fun builtInCategoryLabel(): String = MyCameraApplication.instance.getString(R.string.built_in)
/**
* 解析摄像头方向偏移字符串
* 格式:cameraId1:offset1,cameraId2:offset2
*/
internal fun parseCameraOrientationOffsets(value: String?): Map<String, Int> {
if (value.isNullOrEmpty()) return emptyMap()
return value.split(",")
.mapNotNull { entry ->
val separatorIndex = entry.lastIndexOf(":")
if (separatorIndex <= 0 || separatorIndex == entry.lastIndex) return@mapNotNull null
val cameraId = entry.substring(0, separatorIndex)
val offset = entry.substring(separatorIndex + 1).toIntOrNull()
if (offset != null && offset in listOf(0, 90, 180, 270)) {
cameraId to offset
} else null
}
.toMap()
}
/**
* 序列化摄像头方向偏移为字符串
*/
internal fun serializeCameraOrientationOffsets(offsets: Map<String, Int>): String {
return offsets.entries
.filter { it.value in listOf(0, 90, 180, 270) }
.joinToString(",") { "${it.key}:${it.value}" }
}
internal fun parseMapString(value: String?): Map<String, String> {
if (value.isNullOrEmpty()) return emptyMap()
return value.split(",")
.mapNotNull { entry ->
val separatorIndex = entry.lastIndexOf(":")
if (separatorIndex <= 0 || separatorIndex == entry.lastIndex) return@mapNotNull null
entry.substring(0, separatorIndex) to entry.substring(separatorIndex + 1)
}
.toMap()
}
internal fun serializeMapString(map: Map<String, String>): String {
return map.entries.joinToString(",") { "${it.key}:${it.value}" }
}
internal fun parseNullableStringMap(value: String?): Map<String, String?> {
if (value.isNullOrEmpty()) return emptyMap()
return runCatching {
val root = JSONObject(value)
buildMap {
val keys = root.keys()
while (keys.hasNext()) {
val key = keys.next()
if (key.isBlank()) continue
val rawValue = if (root.isNull(key)) null else root.optString(key)
put(key, rawValue?.takeIf { it.isNotBlank() })
}
}
}.map { CameraPreset.normalizeRawDcpIdsByLens(it) }.getOrDefault(emptyMap())
}
internal fun serializeNullableStringMap(map: Map<String, String?>): String {
val root = JSONObject()
CameraPreset.normalizeRawDcpIdsByLens(map).forEach { (key, value) ->
root.put(key, value ?: JSONObject.NULL)
}
return root.toString()
}
internal fun parseMapFloat(value: String?): Map<String, Float> {
if (value.isNullOrEmpty()) return emptyMap()
return value.split(",")
.mapNotNull { entry ->
val separatorIndex = entry.lastIndexOf(":")
if (separatorIndex <= 0 || separatorIndex == entry.lastIndex) return@mapNotNull null
val key = entry.substring(0, separatorIndex)
val floatValue = entry.substring(separatorIndex + 1).toFloatOrNull()
if (floatValue != null) key to floatValue else null
}
.toMap()
}
internal fun serializeMapFloat(map: Map<String, Float>): String {
return map.entries.joinToString(",") { "${it.key}:${it.value}" }
}
internal fun parseSpectralFilmTunings(value: String?): Map<String, SpectralFilmTuning> {
if (value.isNullOrEmpty()) return emptyMap()
return value.split(",")
.mapNotNull { entry ->
val parts = entry.split(":")
if (parts.size == 4) {
val c = parts[1].toFloatOrNull()
val m = parts[2].toFloatOrNull()
val y = parts[3].toFloatOrNull()
if (c != null && m != null && y != null) {
parts[0] to SpectralFilmTuning(c, m, y).normalized()
} else {
null
}
} else {
null
}
}
.toMap()
}
internal fun serializeSpectralFilmTunings(map: Map<String, SpectralFilmTuning>): String {
return map.entries.joinToString(",") { (stock, tuning) ->
val t = tuning.normalized()
"$stock:${t.cDensityGain}:${t.mDensityGain}:${t.yDensityGain}"
}
}
internal fun parseLensIds(value: String?): List<String> {
if (value.isNullOrBlank()) return emptyList()
return value.split(",")
.map { it.trim() }
.filter { it.isNotEmpty() }
.distinct()
}
internal fun parseLogicalCameraBindingWhitelist(value: String?): List<String> {
if (value.isNullOrBlank()) return emptyList()
return normalizeLogicalCameraBindingWhitelist(value.split(","))
}
internal fun normalizeLogicalCameraBindingWhitelist(values: Iterable<String>): List<String> {
val normalizedBindings = mutableListOf<Pair<String, String>>()
values.forEach { value ->
val parts = value.trim().split("/", limit = 2)
if (parts.size != 2) return@forEach
val logicalCameraId = parts[0].trim()
val physicalCameraId = parts[1].trim()
if (logicalCameraId.isEmpty() || physicalCameraId.isEmpty()) {
return@forEach
}
val existingIndex = normalizedBindings.indexOfFirst { it.second == physicalCameraId }
if (existingIndex >= 0) {
normalizedBindings.removeAt(existingIndex)
}
normalizedBindings.add(logicalCameraId to physicalCameraId)
}
return normalizedBindings.map { (logicalCameraId, physicalCameraId) ->
"$logicalCameraId/$physicalCameraId"
}
}
internal fun parseRawLuts(preferences: Preferences): Map<String, String> {
val result = mutableMapOf<String, String>()
TransferCurve.entries.forEach { entry ->
val default = when (entry) {
TransferCurve.FLOG2 -> "PROVIA.plut"
TransferCurve.SRGB -> "none"
TransferCurve.LINEAR -> "none"
else -> "sRGB.plut"
}
val value = preferences[stringPreferencesKey("${entry.name}_raw_lut")] ?: default
result[entry.name] = value
}
return result
}
internal fun parseCustomAspectRatios(value: String?): List<AspectRatio> {
if (value.isNullOrBlank()) {
return emptyList()
}
return AspectRatio.sanitizeCustomRatios(
value.split(",")
.mapNotNull { name -> AspectRatio.valueOfOrNull(name) }
)
}
internal fun parseTopSheetAspectRatios(
value: String?,
availableAspectRatios: List<AspectRatio>
): List<AspectRatio> {
if (value.isNullOrBlank()) {
return AspectRatio.defaultTopSheetRatios
}
val availableByName = availableAspectRatios.associateBy { it.name }
val ratios = value.split(",")
.mapNotNull { name ->
availableByName[name] ?: AspectRatio.valueOfOrNull(name)
}
return AspectRatio.sanitizeTopSheetRatios(ratios)
}
internal fun readCategoryOrder(preferences: Preferences): List<String> {
val json = preferences[PreferenceKeys.CATEGORY_ORDER_JSON]
return if (json != null) {
val array = JSONArray(json)
List(array.length()) { index ->
if (array.optJSONObject(index)?.optString("type") == "built_in") {
builtInCategoryLabel()
} else {
array.getString(index)
}
}
} else {
preferences[PreferenceKeys.CATEGORY_ORDER]?.split(",").orEmpty()
}.filter { it.isNotBlank() }.distinct()
}
internal fun serializeCategoryOrder(order: List<String>): String {
val builtInText = builtInCategoryLabel()
val array = JSONArray()
order.filter { it.isNotBlank() }.distinct().forEach { category ->
// 系统分类使用稳定标识,切换语言后不会变成一个自定义空分类。
array.put(if (category == builtInText) JSONObject().put("type", "built_in") else category)
}
return array.toString()
}
File diff suppressed because it is too large. Load diff
@@ -206,8 +206,8 @@ object GalleryManager {
// while an explicit photo-level edit is still honored above.
true
} else {
ContentRepository.getInstance(context).userPreferencesRepository.userPreferences.firstOrNull()
?.rawLensShadingCorrectionEnabled ?: true
ContentRepository.getInstance(context).userPreferencesRepository
.latest().rawLensShadingCorrectionEnabled
}
}
@@ -315,7 +315,7 @@ object GalleryManager {
rawShadowsAdjustment = preferences?.rawShadowsAdjustment ?: 0f,
rawBlackPointCorrection = preferences?.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = preferences?.rawWhitePointCorrection ?: 0f,
rawLensShadingCorrectionEnabled = preferences?.rawLensShadingCorrectionEnabled,
rawLensShadingCorrectionEnabled = repository.userPreferencesRepository.latest().rawLensShadingCorrectionEnabled,
rawBlackLevelMode = RawCfaCorrection.MODE_DEFAULT,
rawCustomBlackLevel = 0f,
rawWhiteLevelMode = RawWhiteLevelCorrection.MODE_DEFAULT,
@@ -88,7 +88,7 @@ class PhotoProcessor(
// while an explicit photo-level edit is still honored above.
true
} else {
userPreferencesRepository.userPreferences.firstOrNull()?.rawLensShadingCorrectionEnabled ?: true
userPreferencesRepository.latest().rawLensShadingCorrectionEnabled
}
}
@@ -34,22 +34,19 @@ class OpenAIApiClient() {
suspend fun initialize(context: Context) {
val userPrefs = ContentRepository.getInstance(context).userPreferencesRepository.userPreferences.firstOrNull()
val isBuiltIn = userPrefs?.openAIApiKey.isNullOrBlank()
val customApiKey = userPrefs?.openAIApiKey?.takeIf { it.isNotBlank() }
val isBuiltIn = customApiKey == null
isBuiltInService = isBuiltIn
apiKey = if (isBuiltIn) {
BUILT_IN_API_KEY
} else {
userPrefs.openAIApiKey
}
apiKey = customApiKey ?: BUILT_IN_API_KEY
apiBaseUrl = if (isBuiltIn) {
BUILT_IN_API_URL
} else {
userPrefs.openAIBaseUrl?.ifBlank { DEFAULT_API_URL } ?: DEFAULT_API_URL
userPrefs?.openAIBaseUrl?.ifBlank { DEFAULT_API_URL } ?: DEFAULT_API_URL
}.trimEnd('/')
model = if (isBuiltIn) {
BUILT_IN_MODEL
} else {
userPrefs.openAIModel?.ifBlank { DEFAULT_MODEL } ?: DEFAULT_MODEL
userPrefs?.openAIModel?.ifBlank { DEFAULT_MODEL } ?: DEFAULT_MODEL
}
}
@@ -119,7 +119,8 @@ class MgcFilterSelectionActivity : AppCompatActivity() {
isSaving = true
lifecycleScope.launch {
runCatching {
contentRepository.userPreferencesRepository.saveLutConfig(lutId)
contentRepository.userPreferencesRepository.update { this.lutId = lutId }
PhotonLookContract.notifyLookChanged(this@MgcFilterSelectionActivity)
}.onSuccess {
setResult(
Activity.RESULT_OK,
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.phantom
import com.hinnka.mycamera.mgc.PhotonLookContract
import android.content.ContentValues
import android.content.Context
import android.content.Intent
@@ -489,9 +490,7 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
syncWindowAndObserver()
lifecycleScope.launch {
userPreferencesRepository.userPreferences
.map { it.phantomPipPreview }
.distinctUntilChanged()
userPreferencesRepository.flow { it.phantomPipPreview }
.collect { enable ->
if (enable) {
val captureAlreadyRunning =
@@ -506,9 +505,7 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
}
lifecycleScope.launch {
userPreferencesRepository.userPreferences
.map { it.phantomButtonHidden }
.distinctUntilChanged()
userPreferencesRepository.flow { it.phantomButtonHidden }
.collect { hidden ->
if (isWindowShown) {
updateWindowParams(hidden)
@@ -584,9 +581,9 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
val preferences = userPreferencesRepository.userPreferences.firstOrNull()
val lutId = preferences?.lutId
?: availableLutList.firstOrNull { it.isDefault }?.id
val saveAsNew = preferences?.phantomSaveAsNew ?: false
val saveAsNew = userPreferencesRepository.latest().phantomSaveAsNew
val phantomFrameId = preferences?.phantomFrameId
val computationalAperture = preferences?.defaultVirtualAperture?.let { if (it > 0f) it else null }
val computationalAperture = userPreferencesRepository.latest().defaultVirtualAperture.takeIf { it > 0f }
val existingPhotoId = if (processingInfo?.uri == uri) processingInfo?.photoId else null
val isRawSource = isRawMedia(name, mimeType)
val photoId =
@@ -948,10 +945,9 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
composeView = ComposeView(overlayContext).apply {
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
setContent {
val phantomButtonHiddenFlow = remember {
userPreferencesRepository.userPreferences.map { it.phantomButtonHidden }
}
val phantomButtonHidden by phantomButtonHiddenFlow.collectAsState(initial = false)
val phantomButtonHidden by remember {
userPreferencesRepository.flow { it.phantomButtonHidden }
}.collectAsState(initial = userPreferencesRepository.current.phantomButtonHidden)
if (phantomButtonHidden) return@setContent
@@ -1097,7 +1093,8 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
thumbnail = processingInfo?.thumbnail?.takeIf { !it.isRecycled },
onLutSelected = { lutId ->
scope.launch {
userPreferencesRepository.saveLutConfig(lutId)
userPreferencesRepository.update { this.lutId = lutId }
PhotonLookContract.notifyLookChanged(context)
syncScreenCaptureRenderConfig(lutId)
closeFilterPicker()
}
@@ -1190,7 +1187,7 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
IconButton(
onClick = {
scope.launch {
userPreferencesRepository.savePhantomMode(false)
userPreferencesRepository.update { phantomMode = false }
}
},
modifier = Modifier.size(48.dp)
@@ -1292,7 +1289,7 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
currentEffects = currentEffectParams,
onEffectsChange = { effects ->
scope.launch {
userPreferencesRepository.saveActiveEffectParams(effects)
userPreferencesRepository.update { activeEffectParams = effects }
syncScreenCaptureRenderConfig(
lutId = currentLutId,
creativeRecipeParamsOverride = editingParams,
@@ -1355,8 +1352,7 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
if (isWindowShown) return
lifecycleScope.launch {
val hidden = userPreferencesRepository.userPreferences.map { it.phantomButtonHidden }
.firstOrNull() ?: false
val hidden = userPreferencesRepository.latest().phantomButtonHidden
updateWindowParams(hidden)
// 关键:将状态标记与实际 addView 放在同一个调度周期或确保同步
@@ -29,10 +29,9 @@ class PhantomShortcutActivity : Activity() {
}
startActivity(intent)
} else {
userPreferencesRepository.savePhantomMode(newMode)
userPreferencesRepository.update { phantomMode = newMode }
if (newMode) {
val prefs = userPreferencesRepository.userPreferences.first()
if (prefs.launchCameraOnPhantomMode) {
if (userPreferencesRepository.latest().launchCameraOnPhantomMode) {
try {
val cameraIntent = Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
@@ -53,11 +53,10 @@ class PhantomTileService : TileService() {
return@launch
}
userPreferencesRepository.savePhantomMode(newMode)
userPreferencesRepository.update { phantomMode = newMode }
updateTileState(newMode)
if (newMode) {
val prefs = userPreferencesRepository.userPreferences.first()
if (prefs.phantomPipPreview) {
if (userPreferencesRepository.latest().phantomPipPreview) {
TileServiceCompat.startActivityAndCollapse(
this@PhantomTileService,
PendingIntentActivityWrapper(
@@ -69,7 +68,7 @@ class PhantomTileService : TileService() {
)
)
}
if (prefs.launchCameraOnPhantomMode) {
if (userPreferencesRepository.latest().launchCameraOnPhantomMode) {
try {
val cameraIntent = Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
@@ -81,12 +81,11 @@ class PhantomWidgetProvider : AppWidgetProvider() {
}
context.startActivity(mainIntent)
} else {
userPreferencesRepository.savePhantomMode(newMode)
userPreferencesRepository.update { phantomMode = newMode }
updateAllWidgets(context)
if (newMode) {
val prefs = userPreferencesRepository.userPreferences.first()
if (prefs.launchCameraOnPhantomMode) {
if (userPreferencesRepository.latest().launchCameraOnPhantomMode) {
try {
val cameraIntent = Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
@@ -76,7 +76,7 @@ class ScreenCapturePipActivity : AppCompatActivity() {
override fun onReceive(context: android.content.Context?, intent: Intent?) {
if (intent?.action == PhantomPipPreviewCoordinator.ACTION_STOP_PHANTOM_PIP_PREVIEW) {
lifecycleScope.launch {
userPreferencesRepository.savePhantomMode(false)
userPreferencesRepository.update { phantomMode = false }
}
controller.stopCapture()
finish()
@@ -173,7 +173,7 @@ class ScreenCapturePipActivity : AppCompatActivity() {
PLog.d(TAG, "handleCaptureClosed")
hasReleasedCapture = true
lifecycleScope.launch {
userPreferencesRepository.savePhantomMode(false)
userPreferencesRepository.update { phantomMode = false }
}
controller.release()
ScreenCapturePipState.setInPipMode(false)
@@ -47,19 +47,12 @@ object ScreenCaptureRenderConfigStore {
) {
val repository = ContentRepository.getInstance(context.applicationContext)
val preferences = repository.userPreferencesRepository.userPreferences.firstOrNull()
val effectivePreferences = preferences?.let {
if (lutIdOverride == null) {
it
} else {
it.copy(lutId = lutIdOverride)
}
}
val creativeLutId = effectivePreferences?.lutId
val creativeLutId = lutIdOverride ?: preferences?.lutId
val creativeRecipeParams = creativeRecipeParamsOverride
?: creativeLutId?.let { repository.lutManager.loadColorRecipeParams(it) }
?: ColorRecipeParams.DEFAULT
val effectParams = effectParamsOverride
?: effectivePreferences?.activeEffectParams
?: preferences?.activeEffectParams
?: EffectParams.DEFAULT
save(
@@ -1,5 +1,9 @@
package com.hinnka.mycamera.ui.camera
import com.hinnka.mycamera.ui.prefs.rememberUserPreferencesRepository
import com.hinnka.mycamera.data.UserPreferences
import com.hinnka.mycamera.ui.prefs.rememberPreference
import com.hinnka.mycamera.ui.prefs.preferenceValue
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
@@ -225,45 +229,49 @@ fun CameraScreen(
onPresetManagementClick: () -> Unit,
modifier: Modifier = Modifier
) {
val preferencesRepository = rememberUserPreferencesRepository()
val context = LocalContext.current
val scope = rememberCoroutineScope()
val state by viewModel.state.collectAsState()
val isCameraInitialized by viewModel.isInitialized.collectAsState()
val latestPhoto by galleryViewModel.latestPhoto.collectAsState()
val showLevelIndicator by viewModel.showLevelIndicator.collectAsState(initial = false)
val focusPeakingEnabled by viewModel.focusPeakingEnabled.collectAsState(initial = true)
val eyeFocusEnabled by viewModel.eyeFocusEnabled.collectAsState()
val keepScreenOn by viewModel.keepScreenOn.collectAsState(initial = false)
val showLevelIndicator by preferenceValue { it.showLevelIndicator }
val focusPeakingEnabled by preferenceValue { it.focusPeakingEnabled }
val eyeFocusEnabled by preferenceValue { it.eyeFocusEnabled }
val keepScreenOn by preferenceValue { it.keepScreenOn }
val currentLutId by viewModel.currentLutId.collectAsState()
val lutSwipeState = rememberLutSwipeState()
val currentRecipeParams by viewModel.currentRecipeParams.collectAsState()
val lutSelectorMode by viewModel.lutSelectorMode.collectAsState()
val activePresetId by viewModel.activePresetId.collectAsState()
val activePresetId by preferenceValue { it.activePresetId }
val activePresetModified by viewModel.isActivePresetModified.collectAsState()
val customPresets by viewModel.customPresets.collectAsState()
val customPresets by preferenceValue { it.customPresets }
val currentBaselineRecipeParams by viewModel.currentBaselineRecipeParams.collectAsState()
val categoryOrder by viewModel.categoryOrder.collectAsState(emptyList())
val useRaw by viewModel.useRaw.collectAsState()
val useJpgMax by viewModel.useJpgMax.collectAsState()
val useMultipleExposure by viewModel.useMultipleExposure.collectAsState()
val useRawMax by viewModel.useRawMax.collectAsState()
val ultraHdrEnabled by viewModel.ultraHdrGainMapEnabled.collectAsState()
val useLivePhoto by viewModel.useLivePhoto.collectAsState()
val enableDevelopAnimation by viewModel.enableDevelopAnimation.collectAsState()
val developAnimationStyle by viewModel.developAnimationStyle.collectAsState()
val phantomMode by viewModel.phantomMode.collectAsState()
val topSheetAspectRatios by viewModel.topSheetAspectRatios.collectAsState()
val videoCodec by viewModel.videoCodec.collectAsState()
val categoryOrder by preferenceValue { it.categoryOrder }
val useRaw by preferenceValue { it.useRaw }
val useJpgMax by preferenceValue { it.useJpgMax }
val useMultipleExposure by preferenceValue { it.useMultipleExposure }
val useRawMax by preferenceValue { it.useRawMax }
val ultraHdrEnabled by preferenceValue { it.ultraHdrGainMapEnabled }
val useLivePhoto by preferenceValue { it.useLivePhoto }
val enableDevelopAnimation by preferenceValue { it.enableDevelopAnimation }
var showHistogram by rememberPreference(UserPreferences::showHistogram)
var videoTorchEnabled by rememberPreference(UserPreferences::videoTorchEnabled)
var videoAudioInputId by rememberPreference(UserPreferences::videoAudioInputId)
val developAnimationStyle by preferenceValue { it.developAnimationStyle }
val phantomMode by preferenceValue { it.phantomMode }
val topSheetAspectRatios by preferenceValue { it.topSheetAspectRatios }
val videoCodec by preferenceValue { it.videoCodec }
val videoAudioInputOptions by viewModel.videoAudioInputOptions.collectAsState()
val phantomPipPreview by viewModel.phantomPipPreview.collectAsState()
val rawDcpId by viewModel.rawDcpId.collectAsState()
val rawDcpIdsByLens by viewModel.rawDcpIdsByLens.collectAsState()
val rawHncsFilmCurveMode by viewModel.rawHncsFilmCurveMode.collectAsState()
val rawColorEngine by viewModel.rawRenderingEngine.collectAsState()
val rawToneMappingParameters by viewModel.rawToneMappingParameters.collectAsState()
val rawSpectralFilmStock by viewModel.rawSpectralFilmStock.collectAsState()
val phantomPipPreview by preferenceValue { it.phantomPipPreview }
val rawDcpId by preferenceValue { it.rawDcpId }
val rawDcpIdsByLens by preferenceValue { it.rawDcpIdsByLens }
val rawHncsFilmCurveMode by preferenceValue { it.rawHncsFilmCurveMode }
val rawColorEngine by preferenceValue { it.rawRenderingEngine }
val rawToneMappingParameters by preferenceValue { it.rawToneMappingParameters }
val rawSpectralFilmStock by preferenceValue { it.rawSpectralFilmStock }
val rawSpectralFilmSelection by viewModel.rawSpectralFilmSelection.collectAsState()
val rawSpectralFilmPrint by viewModel.rawSpectralFilmPrint.collectAsState()
val rawSpectralFilmPrint by preferenceValue { it.rawSpectralFilmPrint }
val rawFotufilmDocument by viewModel.rawFotufilmDocument.collectAsState()
val multipleExposureState = viewModel.multipleExposureState
val canStartShutterAnimation by viewModel.canStartShutterAnimation.collectAsState()
@@ -924,15 +932,13 @@ fun CameraScreen(
},
timerSeconds = state.timerSeconds,
onTimerToggle = { viewModel.toggleTimer() },
showHistogram = viewModel.showHistogram,
onHistogramToggle = {
viewModel.saveShowHistogram(!viewModel.showHistogram)
},
showHistogram = showHistogram,
onHistogramToggle = { showHistogram = !showHistogram },
useLivePhoto = useLivePhoto,
onLivePhotoToggle = { viewModel.setUseLivePhoto(!state.useLivePhoto) },
videoConfig = state.videoConfig,
videoCapabilities = state.videoCapabilities,
onVideoTorchToggle = { viewModel.setVideoTorchEnabled(!state.videoConfig.torchEnabled) },
onVideoTorchToggle = { videoTorchEnabled = !state.videoConfig.torchEnabled },
onVideoStabilizationModeChange = viewModel::setVideoStabilizationMode,
onVideoResolutionClick = {
cycleVideoResolution(state)?.let(viewModel::setVideoResolution)
@@ -1446,7 +1452,7 @@ fun CameraScreen(
}
// 实时直方图 (Overlaid on preview if enabled)
if (isPhotoStyleMode && state.histogram != null && viewModel.showHistogram) {
if (isPhotoStyleMode && state.histogram != null && showHistogram) {
HistogramView(
histogram = state.histogram,
modifier = Modifier
@@ -1735,10 +1741,10 @@ fun CameraScreen(
videoBitrate = state.videoConfig.bitrate,
onVideoBitrateChange = { viewModel.setVideoBitrate(it) },
videoCodec = videoCodec,
onVideoCodecChange = { viewModel.setVideoCodec(it) },
onVideoCodecChange = { preferencesRepository.updateAsync { this.videoCodec = it } },
videoAudioInputId = state.videoConfig.audioInputId,
videoAudioInputOptions = videoAudioInputOptions,
onVideoAudioInputChange = { viewModel.setVideoAudioInputId(it) },
onVideoAudioInputChange = { videoAudioInputId = it },
useRaw = useRaw && state.isRawSupported,
isRawSupported = state.isRawSupported,
rawDcpId = rawDcpId,
@@ -1751,7 +1757,7 @@ fun CameraScreen(
rawSpectralFilmSelection = rawSpectralFilmSelection ?: SpectralFilmSelection(rawSpectralFilmStock ?: "kodak_portra_400"),
rawSpectralFilmPrint = rawSpectralFilmPrint ?: "kodak_portra_endura",
ultraHdrEnabled = ultraHdrEnabled,
onUltraHdrToggle = viewModel::setUltraHdrGainMapEnabled,
onUltraHdrToggle = { preferencesRepository.updateAsync { this.ultraHdrGainMapEnabled = it } },
photoPreviewStabilizationEnabled =
state.photoPreviewStabilizationEnabled,
photoPreviewStabilizationAvailable =
@@ -1772,7 +1778,7 @@ fun CameraScreen(
}
},
onRawColorEngineChange = { viewModel.setRawColorEngine(it) },
onRawToneMappingParametersChange = { viewModel.setRawToneMappingParameters(it) },
onRawToneMappingParametersChange = { preferencesRepository.updateAsync { this.rawToneMappingParameters = it } },
onRawSpectralFilmSelectionChange = { viewModel.setRawSpectralFilmSelection(it) },
onRawSpectralFilmPrintChange = { viewModel.setRawSpectralFilmPrint(it) },
rawFotufilmDocument = rawFotufilmDocument,
@@ -2051,9 +2057,9 @@ private fun Controls(
sideControlInset: Dp?,
modifier: Modifier = Modifier.fillMaxSize()
) {
val captureButtonStyle by viewModel.captureButtonStyle.collectAsState()
val captureButtonColor by viewModel.captureButtonColor.collectAsState()
val captureButtonImagePath by viewModel.captureButtonImagePath.collectAsState()
val captureButtonStyle by preferenceValue { it.captureButtonStyle }
val captureButtonColor by preferenceValue { it.captureButtonColor }
val captureButtonImagePath by preferenceValue { it.captureButtonImagePath }
val captureProcessingState by viewModel.captureProcessingState.collectAsState()
val capturedThumbnail by viewModel.capturedThumbnail.collectAsState()
@@ -255,7 +255,7 @@ private fun ExamplePhotoCard(example: String) {
Button(
onClick = {
coroutineScope.launch {
userPreferencesRepository.saveReferencePhotoUrl(example)
userPreferencesRepository.update { referencePhotoUrl = example }
Toast.makeText(context, R.string.reference_photo_set_success, Toast.LENGTH_SHORT).show()
}
},
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.ui.camera
import com.hinnka.mycamera.ui.prefs.preferenceValue
import androidx.compose.animation.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
@@ -89,8 +90,8 @@ fun ZoomControlBar(
availableCameras.find { it.lensType == if (currentCamera?.lensType == LensType.FRONT) LensType.FRONT else LensType.BACK_MAIN }
// 根据可用相机计算变焦档位
val customFocalLengths by viewModel.customFocalLengths.collectAsState(initial = emptyList())
val hiddenFocalLengths by viewModel.hiddenFocalLengths.collectAsState(initial = emptyList())
val customFocalLengths by preferenceValue { it.customFocalLengths }
val hiddenFocalLengths by preferenceValue { it.hiddenFocalLengths }
val lensZoomStops = viewModel.calculateLensZoomStops(availableCameras, currentCamera)
val zoomStops = viewModel.allZoomStops(lensZoomStops, mainCamera, currentCamera, customFocalLengths, hiddenFocalLengths)
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.ui.camera
import com.hinnka.mycamera.ui.prefs.preferenceValue
import androidx.compose.animation.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
@@ -72,8 +73,8 @@ fun ZoomControlBarVerticel(
availableCameras.find { it.lensType == if (currentCamera?.lensType == LensType.FRONT) LensType.FRONT else LensType.BACK_MAIN }
// 根据可用相机计算变焦档位
val customFocalLengths by viewModel.customFocalLengths.collectAsState(initial = emptyList())
val hiddenFocalLengths by viewModel.hiddenFocalLengths.collectAsState(initial = emptyList())
val customFocalLengths by preferenceValue { it.customFocalLengths }
val hiddenFocalLengths by preferenceValue { it.hiddenFocalLengths }
val lensZoomStops = viewModel.calculateLensZoomStops(availableCameras, currentCamera)
val zoomStops = viewModel.allZoomStops(lensZoomStops, mainCamera, currentCamera, customFocalLengths, hiddenFocalLengths)
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.ui.components
import com.hinnka.mycamera.ui.prefs.preferenceValue
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
@@ -14,7 +15,7 @@ import com.hinnka.mycamera.viewmodel.CameraViewModel
@Composable
fun rememberBackgroundPainter(viewModel: CameraViewModel): Painter {
val bgImage by viewModel.backgroundImage.collectAsState()
val bgImage by preferenceValue { it.backgroundImage }
val context = LocalContext.current
return remember(bgImage) {
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.ui.components
import com.hinnka.mycamera.ui.prefs.preferenceValue
import com.hinnka.mycamera.ui.theme.AccentColor
import androidx.compose.animation.animateColorAsState
@@ -48,10 +49,8 @@ import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.hinnka.mycamera.R
import com.hinnka.mycamera.data.UserPreferencesRepository
import androidx.compose.ui.platform.LocalContext
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.distinctUntilChanged
import com.hinnka.mycamera.model.ColorRecipeParams
import com.hinnka.mycamera.model.EffectParams
import com.hinnka.mycamera.model.RecipeParam
@@ -150,11 +149,7 @@ fun ColorRecipePanel(
param != RecipeParam.LOW_RES
}
val context = LocalContext.current.applicationContext
val preferencesRepository = remember(context) { UserPreferencesRepository(context) }
val paletteEnabled by remember(preferencesRepository) {
preferencesRepository.userPreferences.map { it.colorPaletteEnabled }.distinctUntilChanged()
}.collectAsState(initial = false)
val paletteEnabled by preferenceValue { it.colorPaletteEnabled }
var activeMode by remember(paletteEnabled) {
mutableStateOf(if (paletteEnabled) RecipePanelMode.PALETTE else RecipePanelMode.BASIC)
}
@@ -1,5 +1,8 @@
package com.hinnka.mycamera.ui.gallery
import com.hinnka.mycamera.ui.prefs.preferenceValue
import com.hinnka.mycamera.data.UserPreferences
import com.hinnka.mycamera.ui.prefs.rememberPreference
import com.hinnka.mycamera.ui.components.AppModalBottomSheet
import android.app.Activity
@@ -777,7 +780,7 @@ fun GalleryDetailScreen(
}
}
val deleteExportedPref by viewModel.deleteExported.collectAsState()
var deleteExportedPref by rememberPreference(UserPreferences::deleteExported)
// 删除确认对话框
if (showDeleteDialog && !isCurrentPhotoProcessing) {
@@ -837,7 +840,7 @@ fun GalleryDetailScreen(
currentPhoto?.let { photo ->
val finalDeleteExported = if (viewModel.selectedTab == GalleryTab.PHOTON && exportedPhotosCount > 0) deleteExportedState else true
if (viewModel.selectedTab == GalleryTab.PHOTON && exportedPhotosCount > 0) {
viewModel.setDeleteExported(deleteExportedState)
deleteExportedPref = deleteExportedState
}
viewModel.requestDeletePhoto(photo, finalDeleteExported)
}
@@ -1298,7 +1301,7 @@ private fun AiScoreBottomSheet(
var requestToken by remember(photo.id) { mutableIntStateOf(0) }
var uiState by remember(photo.id) { mutableStateOf<AiEvaluationUiState>(AiEvaluationUiState.Loading) }
val openAIKey by viewModel.openAIApiKey.collectAsState()
val openAIKey by preferenceValue { it.openAIApiKey }
val canEvaluate = isPurchased || !openAIKey.isNullOrBlank()
LaunchedEffect(photo.id, requestToken, canEvaluate) {
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.ui.gallery
import com.hinnka.mycamera.ui.prefs.preferenceValue
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
@@ -234,7 +235,7 @@ fun GalleryEditScreen(
val density = LocalDensity.current
val showPaymentDialog = viewModel.showPaymentDialog
val isPurchased by viewModel.isPurchased.collectAsState()
val categoryOrder by viewModel.categoryOrder.collectAsState()
val categoryOrder by preferenceValue { it.categoryOrder }
val hasCopiedEditSettings by viewModel.hasCopiedEditSettings.collectAsState()
var isSaving by remember { mutableStateOf(false) }
@@ -818,7 +819,7 @@ fun GalleryEditScreen(
.background(Color.Black.copy(alpha = 0.6f))
.clickable {
scope.launch {
userPreferencesRepository.saveReferencePhotoUrl(null)
userPreferencesRepository.update { this.referencePhotoUrl = null }
}
},
contentAlignment = Alignment.Center
@@ -1,5 +1,7 @@
package com.hinnka.mycamera.ui.gallery
import com.hinnka.mycamera.data.UserPreferences
import com.hinnka.mycamera.ui.prefs.rememberPreference
import android.app.Activity
import android.content.Context
import android.content.pm.ApplicationInfo
@@ -621,7 +623,7 @@ fun GalleryScreen(
}
}
val deleteExportedPref by viewModel.deleteExported.collectAsState()
var deleteExportedPref by rememberPreference(UserPreferences::deleteExported)
// 删除确认对话框
if (showDeleteDialog) {
@@ -687,7 +689,7 @@ fun GalleryScreen(
onClick = {
val finalDeleteExported = if (viewModel.selectedTab == GalleryTab.PHOTON && exportedPhotosCount > 0) deleteExportedState else true
if (viewModel.selectedTab == GalleryTab.PHOTON && exportedPhotosCount > 0) {
viewModel.setDeleteExported(deleteExportedState)
deleteExportedPref = deleteExportedState
}
viewModel.deleteSelectedPhotos(finalDeleteExported)
showDeleteDialog = false
@@ -0,0 +1,69 @@
package com.hinnka.mycamera.ui.prefs
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import com.hinnka.mycamera.data.ContentRepository
import com.hinnka.mycamera.data.UserPreferences
import com.hinnka.mycamera.data.UserPreferencesRepository
import kotlin.reflect.KMutableProperty1
/** 进程内共享的设置仓库。 */
@Composable
fun rememberUserPreferencesRepository(): UserPreferencesRepository {
val context = LocalContext.current
return remember(context) {
ContentRepository.getInstance(context).userPreferencesRepository
}
}
/**
* 只读订阅设置中的一个字段(或由多个字段派生的值),只在该值变化时重组:
*
* ```
* val keepScreenOn by preferenceValue { it.keepScreenOn }
* ```
*/
@Composable
fun <T> preferenceValue(select: (UserPreferences) -> T): State<T> {
val repository = rememberUserPreferencesRepository()
val flow = remember(repository) { repository.flow(select) }
return flow.collectAsState(initial = remember(repository) { select(repository.current) })
}
/**
* 在任意 Composable 中直接读写设置中的一个字段:
*
* ```
* var keepScreenOn by rememberPreference(UserPreferences::keepScreenOn)
* Switch(checked = keepScreenOn, onCheckedChange = { keepScreenOn = it })
* ```
*
* 写入在进程作用域执行,不随当前界面销毁而取消。属性引用的 get/set 不依赖 kotlin-reflect。
*/
@Composable
fun <T> rememberPreference(property: KMutableProperty1<UserPreferences, T>): MutableState<T> {
val repository = rememberUserPreferencesRepository()
val state = preferenceValue { property.get(it) }
return remember(repository, state) {
PreferenceState(state) { value -> repository.updateAsync { property.set(this, value) } }
}
}
@Stable
private class PreferenceState<T>(
private val state: State<T>,
private val onSet: (T) -> Unit,
) : MutableState<T> {
override var value: T
get() = state.value
set(value) = onSet(value)
override fun component1(): T = value
override fun component2(): (T) -> Unit = onSet
}
@@ -1,5 +1,7 @@
package com.hinnka.mycamera.ui.settings
import com.hinnka.mycamera.ui.prefs.rememberUserPreferencesRepository
import com.hinnka.mycamera.ui.prefs.preferenceValue
import com.hinnka.mycamera.ui.components.AppModalBottomSheet
import android.annotation.SuppressLint
@@ -112,8 +114,9 @@ fun FilterManagementScreen(
manageVideoLut: Boolean = false,
modifier: Modifier = Modifier
) {
val photoLutId by viewModel.photoLutId.collectAsState()
val videoLutId by viewModel.videoLutId.collectAsState()
val preferencesRepository = rememberUserPreferencesRepository()
val photoLutId by preferenceValue { it.lutId }
val videoLutId by preferenceValue { it.videoLutId }
val isPurchased by viewModel.isPurchased.collectAsState()
val availableLuts = viewModel.availableLutList
val fallbackLutId = availableLuts.firstOrNull { it.isDefault }?.id
@@ -223,7 +226,7 @@ fun FilterManagementScreen(
}
// 分类管理状态
val categoryOrder by viewModel.categoryOrder.collectAsState(emptyList())
val categoryOrder by preferenceValue { it.categoryOrder }
var showCategoryManagement by remember { mutableStateOf(false) }
val builtInText = stringResource(R.string.built_in)
@@ -404,7 +407,7 @@ fun FilterManagementScreen(
IconButton(
onClick = {
// 保存排序顺序
viewModel.saveFilterOrder(localLutList.map { it.id })
preferencesRepository.updateAsync { this.filterOrder = localLutList.map { it.id } }
onBack()
},
modifier = Modifier.autoRotate()
@@ -1403,7 +1406,7 @@ fun FilterManagementScreen(
// 页面退出时保存排序
DisposableEffect(Unit) {
onDispose {
viewModel.saveFilterOrder(localLutList.map { it.id })
preferencesRepository.updateAsync { this.filterOrder = localLutList.map { it.id } }
}
}
@@ -1,5 +1,7 @@
package com.hinnka.mycamera.ui.settings
import com.hinnka.mycamera.ui.prefs.rememberUserPreferencesRepository
import com.hinnka.mycamera.ui.prefs.preferenceValue
import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
@@ -55,8 +57,9 @@ fun FrameManagementScreen(
onEditFrameStyle: (String) -> Unit,
modifier: Modifier = Modifier
) {
val preferencesRepository = rememberUserPreferencesRepository()
val currentFrameId = viewModel.currentFrameId
val phantomFrameId by viewModel.phantomFrameId.collectAsState()
val phantomFrameId by preferenceValue { it.phantomFrameId }
val availableFrames = viewModel.availableFrameList
val customImportManager = viewModel.getCustomImportManager()
val scope = rememberCoroutineScope()
@@ -187,7 +190,7 @@ fun FrameManagementScreen(
IconButton(
onClick = {
// 保存排序顺序
viewModel.saveFrameOrder(localFrameList.map { it.id })
preferencesRepository.updateAsync { this.frameOrder = localFrameList.map { it.id } }
onBack()
},
modifier = Modifier.autoRotate()
@@ -424,7 +427,7 @@ fun FrameManagementScreen(
viewModel.setFrame(null)
}
if (phantomFrameId == deletingFrame!!.id) {
viewModel.setPhantomFrame(null)
preferencesRepository.updateAsync { this.phantomFrameId = null }
}
viewModel.refreshCustomContent()
showDeleteDialog = false
@@ -449,7 +452,7 @@ fun FrameManagementScreen(
// 页面退出时保存排序
DisposableEffect(Unit) {
onDispose {
viewModel.saveFrameOrder(localFrameList.map { it.id })
preferencesRepository.updateAsync { this.frameOrder = localFrameList.map { it.id } }
}
}
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.ui.settings
import com.hinnka.mycamera.ui.prefs.preferenceValue
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.border
@@ -368,7 +369,7 @@ fun PresetEditorScreen(
showTitle = false,
isExpandable = false
) {
val topSheetAspectRatios by viewModel.topSheetAspectRatios.collectAsState()
val topSheetAspectRatios by preferenceValue { it.topSheetAspectRatios }
DropdownSettingItem(
title = stringResource(R.string.aspect_ratio),
value = AspectRatio.valueOf(aspectRatio).getDisplayName(),
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.ui.settings
import com.hinnka.mycamera.ui.prefs.preferenceValue
import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.BackHandler
@@ -96,7 +97,7 @@ fun PresetManagementScreen(
modifier: Modifier = Modifier
) {
val allPresets by viewModel.allPresets.collectAsState()
val activePresetId by viewModel.activePresetId.collectAsState()
val activePresetId by preferenceValue { it.activePresetId }
val activePresetModified by viewModel.isActivePresetModified.collectAsState()
val context = LocalContext.current
val scope = rememberCoroutineScope()
@@ -1,5 +1,8 @@
package com.hinnka.mycamera.ui.settings
import com.hinnka.mycamera.ui.prefs.rememberUserPreferencesRepository
import com.hinnka.mycamera.data.UserPreferences
import com.hinnka.mycamera.ui.prefs.preferenceValue
import com.hinnka.mycamera.ui.components.AppModalBottomSheet
import android.content.Context
@@ -136,6 +139,7 @@ import com.hinnka.mycamera.camera.VendorCaptureSettingsByLens
import com.hinnka.mycamera.camera.VendorCaptureValueType
import com.hinnka.mycamera.data.CaptureButtonStyle
import com.hinnka.mycamera.data.VolumeKeyAction
import com.hinnka.mycamera.ui.prefs.rememberPreference
import com.hinnka.mycamera.frame.FrameInfo
import com.hinnka.mycamera.gallery.PhotoSavePath
import com.hinnka.mycamera.gallery.HeicExportEncoder
@@ -322,113 +326,117 @@ fun SettingsScreen(
onPresetManagementClick: () -> Unit,
modifier: Modifier = Modifier
) {
val preferencesRepository = rememberUserPreferencesRepository()
val state by viewModel.state.collectAsState()
val userPreferences by viewModel.userPreferences.collectAsState()
val showLevelIndicator by viewModel.showLevelIndicator.collectAsState(initial = false)
val focusPeakingEnabled by viewModel.focusPeakingEnabled.collectAsState(initial = true)
val eyeFocusEnabled by viewModel.eyeFocusEnabled.collectAsState()
val showGrid = state.showGrid
val shutterSoundEnabled by viewModel.shutterSoundEnabled.collectAsState(initial = true)
val vibrationEnabled by viewModel.vibrationEnabled.collectAsState(initial = true)
val keepScreenOn by viewModel.keepScreenOn.collectAsState(initial = false)
val windowScreenBrightness by viewModel.windowScreenBrightness.collectAsState()
val volumeKeyAction by viewModel.volumeKeyAction.collectAsState()
val topSheetAspectRatios by viewModel.topSheetAspectRatios.collectAsState()
val customAspectRatios by viewModel.customAspectRatios.collectAsState()
var showLevelIndicator by rememberPreference(UserPreferences::showLevelIndicator)
var focusPeakingEnabled by rememberPreference(UserPreferences::focusPeakingEnabled)
val eyeFocusEnabled by preferenceValue { it.eyeFocusEnabled }
var showGrid by rememberPreference(UserPreferences::showGrid)
var shutterSoundEnabled by rememberPreference(UserPreferences::shutterSoundEnabled)
var vibrationEnabled by rememberPreference(UserPreferences::vibrationEnabled)
var keepScreenOn by rememberPreference(UserPreferences::keepScreenOn)
val windowScreenBrightness by preferenceValue { it.windowScreenBrightness }
var volumeKeyAction by rememberPreference(UserPreferences::volumeKeyAction)
val topSheetAspectRatios by preferenceValue { it.topSheetAspectRatios }
val customAspectRatios by preferenceValue { it.customAspectRatios }
val availablePhotoAspectRatios by viewModel.availablePhotoAspectRatios.collectAsState()
val autoSaveAfterCapture by viewModel.autoSaveAfterCapture.collectAsState(initial = true)
val nrLevel by viewModel.nrLevel.collectAsState(initial = NoiseReductionLevel.DEFAULT)
val edgeLevel by viewModel.edgeLevel.collectAsState(initial = 1)
val vendorCaptureSettingsByLens by viewModel.vendorCaptureSettingsByLens.collectAsState()
val customVendorKeySettings by viewModel.customVendorKeySettings.collectAsState()
val useRaw by viewModel.useRaw.collectAsState(initial = false)
val exportDngWithRawExport by viewModel.exportDngWithRawExport.collectAsState(initial = false)
val defaultFocalLength by viewModel.defaultFocalLength.collectAsState(initial = 0f)
val customLensIds by viewModel.customLensIds.collectAsState(initial = emptyList())
val lensIdBlacklist by viewModel.lensIdBlacklist.collectAsState(initial = emptyList())
val iszLensConfigs by viewModel.iszLensConfigs.collectAsState(initial = emptyList())
val preferredMainCameraId by viewModel.preferredMainCameraId.collectAsState(initial = null)
val preferredMacroCameraId by viewModel.preferredMacroCameraId.collectAsState(initial = null)
val enableLogicalMultiCameraDiscovery by viewModel.enableLogicalMultiCameraDiscovery.collectAsState(initial = false)
val logicalCameraBindingWhitelist by viewModel.logicalCameraBindingWhitelist.collectAsState(initial = emptyList())
val jpgMultiFrameDenoiseFrameCount by viewModel.jpgMultiFrameDenoiseFrameCount.collectAsState()
var autoSaveAfterCapture by rememberPreference(UserPreferences::autoSaveAfterCapture)
var nrLevel by rememberPreference(UserPreferences::nrLevel)
var edgeLevel by rememberPreference(UserPreferences::edgeLevel)
val retainCaptureSettings by preferenceValue { it.retainCaptureSettings }
var videoNrLevel by rememberPreference(UserPreferences::videoNrLevel)
var videoEdgeLevel by rememberPreference(UserPreferences::videoEdgeLevel)
val vendorCaptureSettingsByLens by preferenceValue { it.vendorCaptureSettingsByLens }
val customVendorKeySettings by preferenceValue { it.customVendorKeySettings }
val useRaw by preferenceValue { it.useRaw }
var exportDngWithRawExport by rememberPreference(UserPreferences::exportDngWithRawExport)
var defaultFocalLength by rememberPreference(UserPreferences::defaultFocalLength)
val customLensIds by preferenceValue { it.customLensIds }
val lensIdBlacklist by preferenceValue { it.lensIdBlacklist }
val iszLensConfigs by preferenceValue { it.iszLensConfigs }
val preferredMainCameraId by preferenceValue { it.preferredMainCameraId }
val preferredMacroCameraId by preferenceValue { it.preferredMacroCameraId }
var enableLogicalMultiCameraDiscovery by rememberPreference(UserPreferences::enableLogicalMultiCameraDiscovery)
val logicalCameraBindingWhitelist by preferenceValue { it.logicalCameraBindingWhitelist }
val jpgMultiFrameDenoiseFrameCount by preferenceValue { it.jpgMultiFrameDenoiseFrameCount }
val jpgMultiFrameDenoiseOutputScale by viewModel.jpgMultiFrameDenoiseOutputScale.collectAsState()
val hdrPlusFrameCount by viewModel.hdrPlusFrameCount.collectAsState()
val hdrPlusMergeMode by viewModel.hdrPlusMergeMode.collectAsState()
val hdrPlusBracketExposureEnabled by viewModel.hdrPlusBracketExposureEnabled.collectAsState()
val hdrPlusLongFrameExposureEv by viewModel.hdrPlusLongFrameExposureEv.collectAsState()
val hdrPlusShortFrameExposureEv by viewModel.hdrPlusShortFrameExposureEv.collectAsState()
val mlAeMaxHdrRatio by viewModel.mlAeMaxHdrRatio.collectAsState()
val hdrPlusFrameCount by preferenceValue { it.hdrPlusFrameCount }
val hdrPlusMergeMode by preferenceValue { it.hdrPlusMergeMode }
val hdrPlusBracketExposureEnabled by preferenceValue { it.hdrPlusBracketExposureEnabled }
val hdrPlusLongFrameExposureEv by preferenceValue { it.hdrPlusLongFrameExposureEv }
val hdrPlusShortFrameExposureEv by preferenceValue { it.hdrPlusShortFrameExposureEv }
val mlAeMaxHdrRatio by preferenceValue { it.mlAeMaxHdrRatio }
val effectiveHdrPlusBracketExposure = hdrPlusMergeMode.supportsBracketExposure &&
hdrPlusBracketExposureEnabled
val multipleExposureCount by viewModel.multipleExposureCount.collectAsState()
val enableDevelopAnimation by viewModel.enableDevelopAnimation.collectAsState()
val colorPaletteEnabled by viewModel.colorPaletteEnabled.collectAsState()
val autoRotateEnabled by viewModel.autoRotateEnabled.collectAsState()
val developAnimationStyle by viewModel.developAnimationStyle.collectAsState()
val photoQuality by viewModel.photoQuality.collectAsState(initial = 95)
val useHeicExport by viewModel.useHeicExport.collectAsState(initial = false)
val useJpeg444Export by viewModel.useJpeg444Export.collectAsState(initial = false)
val useP010 by viewModel.useP010.collectAsState()
val useP3ColorSpace by viewModel.useP3ColorSpace.collectAsState()
val ultraHdrGainMapEnabled by viewModel.ultraHdrGainMapEnabled.collectAsState()
val useHdrScreenMode by viewModel.useHdrScreenMode.collectAsState()
var multipleExposureCount by rememberPreference(UserPreferences::multipleExposureCount)
var enableDevelopAnimation by rememberPreference(UserPreferences::enableDevelopAnimation)
var colorPaletteEnabled by rememberPreference(UserPreferences::colorPaletteEnabled)
var autoRotateEnabled by rememberPreference(UserPreferences::autoRotateEnabled)
val developAnimationStyle by preferenceValue { it.developAnimationStyle }
var photoQuality by rememberPreference(UserPreferences::photoQuality)
val useHeicExport by preferenceValue { it.useHeicExport }
val useJpeg444Export by preferenceValue { it.useJpeg444Export }
var useP010 by rememberPreference(UserPreferences::useP010)
val useP3ColorSpace by preferenceValue { it.useP3ColorSpace }
val ultraHdrGainMapEnabled by preferenceValue { it.ultraHdrGainMapEnabled }
var useHdrScreenMode by rememberPreference(UserPreferences::useHdrScreenMode)
val isPurchased by viewModel.isPurchased.collectAsState()
val phantomMode by viewModel.phantomMode.collectAsState()
val phantomButtonHidden by viewModel.phantomButtonHidden.collectAsState()
val launchCameraOnPhantomMode by viewModel.launchCameraOnPhantomMode.collectAsState()
val phantomPipPreview by viewModel.phantomPipPreview.collectAsState()
val mirrorFrontCamera by viewModel.mirrorFrontCamera.collectAsState(initial = true)
val phantomMode by preferenceValue { it.phantomMode }
var phantomButtonHidden by rememberPreference(UserPreferences::phantomButtonHidden)
var launchCameraOnPhantomMode by rememberPreference(UserPreferences::launchCameraOnPhantomMode)
var phantomPipPreview by rememberPreference(UserPreferences::phantomPipPreview)
var mirrorFrontCamera by rememberPreference(UserPreferences::mirrorFrontCamera)
val widgetTheme by viewModel.widgetTheme.collectAsState()
val saveLocation by viewModel.saveLocationEnabled.collectAsState(initial = false)
val photoSavePath by viewModel.photoSavePath.collectAsState()
val photoSaveTreeUri by viewModel.photoSaveTreeUri.collectAsState()
val videoRecordingPath by viewModel.videoRecordingPath.collectAsState()
val videoRecordingTreeUri by viewModel.videoRecordingTreeUri.collectAsState()
val separateVideoLutEnabled by viewModel.separateVideoLutEnabled.collectAsState()
val videoLutId by viewModel.videoLutId.collectAsState()
val videoLensLockEnabled by viewModel.videoLensLockEnabled.collectAsState()
val videoWhiteBalanceLockEnabled by viewModel.videoWhiteBalanceLockEnabled.collectAsState()
val openAIApiKey by viewModel.openAIApiKey.collectAsState()
val openAIUrl by viewModel.openAIUrl.collectAsState()
val openAIModel by viewModel.openAIModel.collectAsState()
var saveLocation by rememberPreference(UserPreferences::saveLocation)
val photoSavePath by preferenceValue { it.photoSavePath }
val photoSaveTreeUri by preferenceValue { it.photoSaveTreeUri }
val videoRecordingPath by preferenceValue { it.videoRecordingPath }
val videoRecordingTreeUri by preferenceValue { it.videoRecordingTreeUri }
val separateVideoLutEnabled by preferenceValue { it.separateVideoLutEnabled }
val videoLutId by preferenceValue { it.videoLutId }
var videoLensLockEnabled by rememberPreference(UserPreferences::videoLensLockEnabled)
var videoWhiteBalanceLockEnabled by rememberPreference(UserPreferences::videoWhiteBalanceLockEnabled)
val openAIApiKey by preferenceValue { it.openAIApiKey }
val openAIUrl by preferenceValue { it.openAIBaseUrl }
val openAIModel by preferenceValue { it.openAIModel }
val availableOpenAIModels by viewModel.availableOpenAIModels.collectAsState()
val isFetchingAIModels by viewModel.isFetchingAIModels.collectAsState()
val phantomSaveAsNew by viewModel.phantomSaveAsNew.collectAsState()
val phantomFrameId by viewModel.phantomFrameId.collectAsState()
val defaultVirtualAperture by viewModel.defaultVirtualAperture.collectAsState(initial = 0f)
val rawBaselineLutId by viewModel.rawBaselineLutId.collectAsState()
val rawDcpId by viewModel.rawDcpId.collectAsState()
val rawDcpIdsByLens by viewModel.rawDcpIdsByLens.collectAsState()
val rawNoiseProfileId by viewModel.rawNoiseProfileId.collectAsState()
val rawNoiseProfileIdsByLens by viewModel.rawNoiseProfileIdsByLens.collectAsState()
val rawHncsFilmCurveMode by viewModel.rawHncsFilmCurveMode.collectAsState()
val rawExposureCompensation by viewModel.rawExposureCompensation.collectAsState()
val rawHighlightsAdjustment by viewModel.rawHighlightsAdjustment.collectAsState()
val rawShadowsAdjustment by viewModel.rawShadowsAdjustment.collectAsState()
val rawMinShutterSpeedNs by viewModel.rawMinShutterSpeedNs.collectAsState()
val droMode by viewModel.droMode.collectAsState()
val rawBlackPointCorrection by viewModel.rawBlackPointCorrection.collectAsState()
val rawWhitePointCorrection by viewModel.rawWhitePointCorrection.collectAsState()
val rawLensShadingCorrectionEnabled by viewModel.rawLensShadingCorrectionEnabled.collectAsState()
val rawBlackLevelModes by viewModel.rawBlackLevelModes.collectAsState()
val rawCustomBlackLevels by viewModel.rawCustomBlackLevels.collectAsState()
val rawWhiteLevelModes by viewModel.rawWhiteLevelModes.collectAsState()
val rawCustomWhiteLevels by viewModel.rawCustomWhiteLevels.collectAsState()
val rawCfaCorrectionModes by viewModel.rawCfaCorrectionModes.collectAsState()
val rawColorEngine by viewModel.rawRenderingEngine.collectAsState()
val rawToneMappingParameters by viewModel.rawToneMappingParameters.collectAsState()
val rawMaxSharpening by viewModel.rawMaxSharpening.collectAsState()
val rawMaxNoiseReduction by viewModel.rawMaxNoiseReduction.collectAsState()
val rawMaxChromaNoiseReduction by viewModel.rawMaxChromaNoiseReduction.collectAsState()
val rawSpectralFilmStock by viewModel.rawSpectralFilmStock.collectAsState()
var phantomSaveAsNew by rememberPreference(UserPreferences::phantomSaveAsNew)
val phantomFrameId by preferenceValue { it.phantomFrameId }
val defaultVirtualAperture by preferenceValue { it.defaultVirtualAperture }
val rawBaselineLutId by preferenceValue { it.rawBaselineLutId }
val rawDcpId by preferenceValue { it.rawDcpId }
val rawDcpIdsByLens by preferenceValue { it.rawDcpIdsByLens }
val rawNoiseProfileId by preferenceValue { it.rawNoiseProfileId }
val rawNoiseProfileIdsByLens by preferenceValue { it.rawNoiseProfileIdsByLens }
val rawHncsFilmCurveMode by preferenceValue { it.rawHncsFilmCurveMode }
val rawExposureCompensation by preferenceValue { it.rawExposureCompensation }
val rawHighlightsAdjustment by preferenceValue { it.rawHighlightsAdjustment }
val rawShadowsAdjustment by preferenceValue { it.rawShadowsAdjustment }
var rawMinShutterSpeedNs by rememberPreference(UserPreferences::rawMinShutterSpeedNs)
val droMode by preferenceValue { it.droMode }
val rawBlackPointCorrection by preferenceValue { it.rawBlackPointCorrection }
val rawWhitePointCorrection by preferenceValue { it.rawWhitePointCorrection }
var rawLensShadingCorrectionEnabled by rememberPreference(UserPreferences::rawLensShadingCorrectionEnabled)
val rawBlackLevelModes by preferenceValue { it.rawBlackLevelModes }
val rawCustomBlackLevels by preferenceValue { it.rawCustomBlackLevels }
val rawWhiteLevelModes by preferenceValue { it.rawWhiteLevelModes }
val rawCustomWhiteLevels by preferenceValue { it.rawCustomWhiteLevels }
val rawCfaCorrectionModes by preferenceValue { it.rawCfaCorrectionModes }
val rawColorEngine by preferenceValue { it.rawRenderingEngine }
val rawToneMappingParameters by preferenceValue { it.rawToneMappingParameters }
val rawMaxSharpening by preferenceValue { it.rawMaxSharpening }
val rawMaxNoiseReduction by preferenceValue { it.rawMaxNoiseReduction }
val rawMaxChromaNoiseReduction by preferenceValue { it.rawMaxChromaNoiseReduction }
val rawSpectralFilmStock by preferenceValue { it.rawSpectralFilmStock }
val rawSpectralFilmSelection by viewModel.rawSpectralFilmSelection.collectAsState()
val rawSpectralFilmPrint by viewModel.rawSpectralFilmPrint.collectAsState()
val rawSpectralFilmPrint by preferenceValue { it.rawSpectralFilmPrint }
val rawFotufilmDocument by viewModel.rawFotufilmDocument.collectAsState()
val rawMaxOutputScale by viewModel.rawMaxOutputScale.collectAsState()
val rawOutputUpscaleMode by viewModel.rawOutputUpscaleMode.collectAsState()
val rawDigitalZoomResamplingEnabled by viewModel.rawDigitalZoomResamplingEnabled.collectAsState()
val rawColorCalibrationMode by viewModel.rawColorCalibrationMode.collectAsState()
val rawOutputUpscaleMode by preferenceValue { it.rawOutputUpscaleMode }
val rawDigitalZoomResamplingEnabled by preferenceValue { it.rawDigitalZoomResamplingEnabled }
val rawColorCalibrationMode by preferenceValue { it.rawColorCalibrationMode }
val availableDcps = viewModel.availableDcps
val availableRawNoiseProfiles = viewModel.availableRawNoiseProfiles.filterNot {
it.id == RawNoiseProfileManager.ADAPTIVE_PROFILE_ID
@@ -502,14 +510,14 @@ fun SettingsScreen(
val normalizedProfileId = rawNoiseProfileId.takeIf(availableProfileIds::contains)
?: RawNoiseProfileManager.DEFAULT_PROFILE_ID
if (normalizedProfileId != rawNoiseProfileId) {
viewModel.setRawNoiseProfileId(normalizedProfileId)
preferencesRepository.updateAsync { this.rawNoiseProfileId = normalizedProfileId }
}
val normalizedIdsByLens = rawNoiseProfileIdsByLens.mapValues { (_, profileId) ->
profileId.takeIf(availableProfileIds::contains)
?: RawNoiseProfileManager.DEFAULT_PROFILE_ID
}
if (normalizedIdsByLens != rawNoiseProfileIdsByLens) {
viewModel.setRawNoiseProfileIdsByLens(normalizedIdsByLens)
preferencesRepository.updateAsync { this.rawNoiseProfileIdsByLens = normalizedIdsByLens }
}
}
@@ -551,15 +559,17 @@ fun SettingsScreen(
fun commitRawSliderValues() {
isRawSliderAdjusting = false
viewModel.setRawExposureCompensation(rawExposureCompensationUi)
viewModel.setRawHighlightsAdjustment(rawHighlightsAdjustmentUi)
viewModel.setRawShadowsAdjustment(rawShadowsAdjustmentUi)
viewModel.setRawBlackPointCorrection(rawBlackPointCorrectionUi)
viewModel.setRawWhitePointCorrection(rawWhitePointCorrectionUi)
viewModel.setRawToneMappingParameters(rawToneMappingParametersUi)
viewModel.setRawMaxSharpening(rawMaxSharpeningUi)
viewModel.setRawMaxNoiseReduction(rawMaxNoiseReductionUi)
viewModel.setRawMaxChromaNoiseReduction(rawMaxChromaNoiseReductionUi)
preferencesRepository.updateAsync {
this.rawExposureCompensation = rawExposureCompensationUi
this.rawHighlightsAdjustment = rawHighlightsAdjustmentUi
this.rawShadowsAdjustment = rawShadowsAdjustmentUi
this.rawBlackPointCorrection = rawBlackPointCorrectionUi
this.rawWhitePointCorrection = rawWhitePointCorrectionUi
this.rawToneMappingParameters = rawToneMappingParametersUi
this.rawMaxSharpening = rawMaxSharpeningUi
this.rawMaxNoiseReduction = rawMaxNoiseReductionUi
this.rawMaxChromaNoiseReduction = rawMaxChromaNoiseReductionUi
}
}
val context = androidx.compose.ui.platform.LocalContext.current
@@ -778,7 +788,7 @@ fun SettingsScreen(
) { permissions ->
val granted = permissions.values.all { it }
if (granted) {
viewModel.setSaveLocation(true)
saveLocation = true
}
}
@@ -1100,7 +1110,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_grid_lines),
description = stringResource(R.string.settings_grid_description),
checked = showGrid,
onCheckedChange = { viewModel.setShowGrid(it) }
onCheckedChange = { showGrid = it }
)
val gridStyleLabels = GridStyle.entries.associateWith { style ->
@@ -1134,7 +1144,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_level_indicator),
description = stringResource(R.string.settings_level_description),
checked = showLevelIndicator,
onCheckedChange = { viewModel.setShowLevelIndicator(it) }
onCheckedChange = { showLevelIndicator = it }
)
HorizontalDivider(
@@ -1146,7 +1156,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_focus_peaking),
description = stringResource(R.string.settings_focus_peaking_description),
checked = focusPeakingEnabled,
onCheckedChange = { viewModel.setFocusPeakingEnabled(it) }
onCheckedChange = { focusPeakingEnabled = it }
)
HorizontalDivider(
@@ -1190,7 +1200,7 @@ fun SettingsScreen(
DefaultFocalLengthSetting(
viewModel = viewModel,
currentFocalLength = defaultFocalLength,
onFocalLengthSelected = { viewModel.setDefaultFocalLength(it) }
onFocalLengthSelected = { defaultFocalLength = it }
)
if (mainCameraIdOptions.size > 1) {
@@ -1347,7 +1357,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_logical_multi_camera_discovery),
description = stringResource(R.string.settings_logical_multi_camera_discovery_description),
checked = enableLogicalMultiCameraDiscovery,
onCheckedChange = { viewModel.setEnableLogicalMultiCameraDiscovery(it) }
onCheckedChange = { enableLogicalMultiCameraDiscovery = it }
)
HorizontalDivider(
@@ -1441,7 +1451,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_mirror_front_camera),
description = stringResource(R.string.settings_mirror_front_camera_description),
checked = mirrorFrontCamera,
onCheckedChange = { viewModel.setMirrorFrontCamera(it) }
onCheckedChange = { mirrorFrontCamera = it }
)
HorizontalDivider(
@@ -1460,7 +1470,7 @@ fun SettingsScreen(
6 to "6"
),
currentLevel = multipleExposureCount,
onLevelSelected = { viewModel.setMultipleExposureCount(it) }
onLevelSelected = { multipleExposureCount = it }
)
HorizontalDivider(
@@ -1477,7 +1487,7 @@ fun SettingsScreen(
100 to "100"
),
currentLevel = photoQuality,
onLevelSelected = { viewModel.setPhotoQuality(it) }
onLevelSelected = { photoQuality = it }
)
if (isHeicExportSupported) {
@@ -1490,7 +1500,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_use_heic_export),
description = stringResource(R.string.settings_use_heic_export_description),
checked = useHeicExport,
onCheckedChange = { viewModel.setUseHeicExport(it) }
onCheckedChange = { preferencesRepository.updateAsync { this.useHeicExport = it } }
)
}
@@ -1504,7 +1514,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_use_jpeg_444_export),
description = stringResource(R.string.settings_use_jpeg_444_export_description),
checked = useJpeg444Export,
onCheckedChange = { viewModel.setUseJpeg444Export(it) }
onCheckedChange = { preferencesRepository.updateAsync { this.useJpeg444Export = it } }
)
}
@@ -1549,7 +1559,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_auto_save),
description = stringResource(R.string.settings_auto_save_description),
checked = autoSaveAfterCapture,
onCheckedChange = { viewModel.setAutoSaveAfterCapture(it) }
onCheckedChange = { autoSaveAfterCapture = it }
)
HorizontalDivider(
@@ -1573,7 +1583,7 @@ fun SettingsScreen(
) == android.content.pm.PackageManager.PERMISSION_GRANTED
if (fineLocation || coarseLocation) {
viewModel.setSaveLocation(true)
saveLocation = true
} else {
locationPermissionLauncher.launch(
arrayOf(
@@ -1583,7 +1593,7 @@ fun SettingsScreen(
)
}
} else {
viewModel.setSaveLocation(false)
saveLocation = false
}
}
)
@@ -1629,8 +1639,8 @@ fun SettingsScreen(
NoiseReductionLevel.ZERO_SHUTTER_LAG to stringResource(R.string.settings_nr_level_zsl),
NoiseReductionLevel.MINIMAL to stringResource(R.string.settings_nr_level_minimal)
),
currentLevel = userPreferences.videoNrLevel,
onLevelSelected = viewModel::setVideoNRLevel
currentLevel = videoNrLevel,
onLevelSelected = { videoNrLevel = it }
)
HorizontalDivider(
@@ -1647,8 +1657,8 @@ fun SettingsScreen(
2 to stringResource(R.string.settings_nr_level_high_quality),
3 to stringResource(R.string.settings_nr_level_zsl)
),
currentLevel = userPreferences.videoEdgeLevel,
onLevelSelected = viewModel::setVideoEdgeLevel
currentLevel = videoEdgeLevel,
onLevelSelected = { videoEdgeLevel = it }
)
HorizontalDivider(
@@ -1853,7 +1863,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_video_lock_lens),
description = stringResource(R.string.settings_video_lock_lens_description),
checked = videoLensLockEnabled,
onCheckedChange = viewModel::setVideoLensLockEnabled
onCheckedChange = { videoLensLockEnabled = it }
)
HorizontalDivider(
@@ -1865,7 +1875,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_video_lock_white_balance),
description = stringResource(R.string.settings_video_lock_white_balance_description),
checked = videoWhiteBalanceLockEnabled,
onCheckedChange = viewModel::setVideoWhiteBalanceLockEnabled
onCheckedChange = { videoWhiteBalanceLockEnabled = it }
)
HorizontalDivider(
@@ -1966,7 +1976,7 @@ fun SettingsScreen(
NoiseReductionLevel.MINIMAL to stringResource(R.string.settings_nr_level_minimal)
),
currentLevel = nrLevel,
onLevelSelected = { viewModel.setNRLevel(it) }
onLevelSelected = { nrLevel = it }
)
HorizontalDivider(
@@ -1984,7 +1994,7 @@ fun SettingsScreen(
3 to stringResource(R.string.settings_nr_level_zsl)
),
currentLevel = edgeLevel,
onLevelSelected = { viewModel.setEdgeLevel(it) }
onLevelSelected = { edgeLevel = it }
)
if (state.isP010Supported) {
@@ -1997,7 +2007,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_use_p010),
description = stringResource(R.string.settings_use_p010_description),
checked = useP010,
onCheckedChange = { viewModel.setUseP010(it) }
onCheckedChange = { useP010 = it }
)
}
@@ -2130,7 +2140,7 @@ fun SettingsScreen(
valueRange = RawSceneExposureMath.MIN_CONFIGURED_MAX_HDR_RATIO..
RawSceneExposureMath.MAX_CONFIGURED_MAX_HDR_RATIO,
onValueChange = { mlAeMaxHdrRatioUi = (it * 10f).roundToInt() / 10f },
onValueChangeFinished = { viewModel.setMlAeMaxHdrRatio(mlAeMaxHdrRatioUi) },
onValueChangeFinished = { preferencesRepository.updateAsync { this.mlAeMaxHdrRatio = mlAeMaxHdrRatioUi } },
resetValue = RawSceneExposureMath.FAST_MOMENTS_MAX_HDR_RATIO,
valueTextFormatter = { String.format(Locale.getDefault(), "%.1f×", it) },
)
@@ -2153,7 +2163,7 @@ fun SettingsScreen(
}
},
currentLevel = rawMinShutterSpeedNs,
onLevelSelected = viewModel::setRawMinShutterSpeedNs,
onLevelSelected = { rawMinShutterSpeedNs = it },
)
}
@@ -2179,7 +2189,7 @@ fun SettingsScreen(
),
),
currentLevel = rawColorCalibrationMode,
onLevelSelected = viewModel::setRawColorCalibrationMode,
onLevelSelected = { preferencesRepository.updateAsync { this.rawColorCalibrationMode = it } },
)
HorizontalDivider(
color = Color.White.copy(alpha = 0.1f),
@@ -2190,7 +2200,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_raw_digital_zoom_resampling),
description = stringResource(R.string.settings_raw_digital_zoom_resampling_description),
checked = rawDigitalZoomResamplingEnabled,
onCheckedChange = viewModel::setRawDigitalZoomResamplingEnabled,
onCheckedChange = { preferencesRepository.updateAsync { this.rawDigitalZoomResamplingEnabled = it } },
)
HorizontalDivider(
color = Color.White.copy(alpha = 0.1f),
@@ -2278,8 +2288,8 @@ fun SettingsScreen(
selectedProfileId = rawNoiseProfileId,
profileIdsByLens = rawNoiseProfileIdsByLens,
availableProfiles = availableRawNoiseProfiles,
onSelectProfile = viewModel::setRawNoiseProfileId,
onProfileIdsByLensChange = viewModel::setRawNoiseProfileIdsByLens,
onSelectProfile = { preferencesRepository.updateAsync { this.rawNoiseProfileId = it } },
onProfileIdsByLensChange = { preferencesRepository.updateAsync { this.rawNoiseProfileIdsByLens = it } },
onImportProfile = {
importRawNoiseProfileLauncher.launch(arrayOf("*/*"))
},
@@ -2410,7 +2420,7 @@ fun SettingsScreen(
R.string.settings_ultra_hdr_gain_map_description
),
checked = ultraHdrGainMapEnabled,
onCheckedChange = viewModel::setUltraHdrGainMapEnabled,
onCheckedChange = { preferencesRepository.updateAsync { this.ultraHdrGainMapEnabled = it } },
)
HorizontalDivider(
@@ -2427,7 +2437,7 @@ fun SettingsScreen(
true to stringResource(R.string.settings_professional_export_raw_jpg),
),
currentLevel = exportDngWithRawExport,
onLevelSelected = viewModel::setExportDngWithRawExport,
onLevelSelected = { exportDngWithRawExport = it },
)
}
@@ -2440,7 +2450,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_raw_lens_shading_correction),
description = stringResource(R.string.settings_raw_lens_shading_correction_description),
checked = rawLensShadingCorrectionEnabled,
onCheckedChange = { viewModel.setRawLensShadingCorrectionEnabled(it) }
onCheckedChange = { rawLensShadingCorrectionEnabled = it }
)
HorizontalDivider(
@@ -2489,7 +2499,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_phantom_button_hidden),
description = stringResource(R.string.settings_phantom_button_hidden_description),
checked = phantomButtonHidden,
onCheckedChange = { viewModel.setPhantomButtonHidden(it) }
onCheckedChange = { phantomButtonHidden = it }
)
HorizontalDivider(
@@ -2501,7 +2511,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_launch_camera_on_phantom_mode),
description = stringResource(R.string.settings_launch_camera_on_phantom_mode_description),
checked = launchCameraOnPhantomMode,
onCheckedChange = { viewModel.setLaunchCameraOnPhantomMode(it) }
onCheckedChange = { launchCameraOnPhantomMode = it }
)
HorizontalDivider(
@@ -2513,7 +2523,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_phantom_pip_preview),
description = stringResource(R.string.settings_phantom_pip_preview_description),
checked = phantomPipPreview,
onCheckedChange = { viewModel.setPhantomPipPreview(it) }
onCheckedChange = { phantomPipPreview = it }
)
HorizontalDivider(
@@ -2536,7 +2546,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_phantom_save_as_new),
description = stringResource(R.string.settings_phantom_save_as_new_description),
checked = phantomSaveAsNew,
onCheckedChange = { viewModel.setPhantomSaveAsNew(it) }
onCheckedChange = { phantomSaveAsNew = it }
)
HorizontalDivider(
@@ -2549,7 +2559,7 @@ fun SettingsScreen(
description = stringResource(R.string.settings_phantom_frame_description),
availableFrames = availableFrames,
currentFrameId = phantomFrameId,
onFrameSelected = viewModel::setPhantomFrame
onFrameSelected = { preferencesRepository.updateAsync { this.phantomFrameId = it } }
)
}
@@ -2581,7 +2591,7 @@ fun SettingsScreen(
AccentColorSetting(
color = userPreferences.accentColor,
onColorSelected = viewModel::setAccentColor
onColorSelected = { preferencesRepository.updateAsync { this.accentColor = it } }
)
HorizontalDivider(
@@ -2617,7 +2627,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_auto_rotate),
description = stringResource(R.string.settings_auto_rotate_description),
checked = autoRotateEnabled,
onCheckedChange = viewModel::setAutoRotateEnabled
onCheckedChange = { autoRotateEnabled = it }
)
HorizontalDivider(
@@ -2629,7 +2639,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_color_palette),
description = stringResource(R.string.settings_color_palette_description),
checked = colorPaletteEnabled,
onCheckedChange = viewModel::setColorPaletteEnabled
onCheckedChange = { colorPaletteEnabled = it }
)
HorizontalDivider(
@@ -2641,7 +2651,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_develop_animation),
description = stringResource(R.string.settings_develop_animation_description),
checked = enableDevelopAnimation,
onCheckedChange = { viewModel.setEnableDevelopAnimation(it) }
onCheckedChange = { enableDevelopAnimation = it }
)
if (enableDevelopAnimation) {
QualityLevelSetting(
@@ -2654,7 +2664,7 @@ fun SettingsScreen(
stringResource(R.string.settings_develop_animation_style_instant_print)
),
currentLevel = developAnimationStyle,
onLevelSelected = { viewModel.setDevelopAnimationStyle(it) },
onLevelSelected = { preferencesRepository.updateAsync { this.developAnimationStyle = it } },
modifier = Modifier.padding(top = 8.dp, bottom = 4.dp)
)
}
@@ -2707,7 +2717,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_openai_api_key),
description = stringResource(R.string.settings_openai_api_key_desc),
value = openAIApiKey ?: "",
onValueChange = { viewModel.setOpenAIApiKey(it) },
onValueChange = { preferencesRepository.updateAsync { this.openAIApiKey = it } },
isSecret = true,
)
@@ -2720,7 +2730,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_openai_base_url),
description = stringResource(R.string.settings_openai_base_url_desc),
value = openAIUrl ?: OpenAIApiClient.DEFAULT_API_URL,
onValueChange = { viewModel.setOpenAIUrl(it) }
onValueChange = { preferencesRepository.updateAsync { this.openAIBaseUrl = it } }
)
HorizontalDivider(
@@ -2742,7 +2752,7 @@ fun SettingsScreen(
customAIModelValue = openAIModel ?: ""
showCustomAIModelDialog = true
} else {
viewModel.setOpenAIModel(it)
preferencesRepository.updateAsync { this.openAIModel = it }
}
}
)
@@ -2758,7 +2768,7 @@ fun SettingsScreen(
SwitchSettingItem(
title = stringResource(R.string.settings_retain_capture_settings),
description = stringResource(R.string.settings_retain_capture_settings_description),
checked = userPreferences.retainCaptureSettings,
checked = retainCaptureSettings,
onCheckedChange = viewModel::setRetainCaptureSettings
)
@@ -2771,7 +2781,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_shutter_sound),
description = stringResource(R.string.settings_shutter_sound_description),
checked = shutterSoundEnabled,
onCheckedChange = { viewModel.setShutterSoundEnabled(it) }
onCheckedChange = { shutterSoundEnabled = it }
)
CaptureSoundSetting(viewModel)
@@ -2785,7 +2795,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_vibration),
description = stringResource(R.string.settings_vibration_description),
checked = vibrationEnabled,
onCheckedChange = { viewModel.setVibrationEnabled(it) }
onCheckedChange = { vibrationEnabled = it }
)
HorizontalDivider(
@@ -2797,7 +2807,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_keep_screen_on),
description = stringResource(R.string.settings_keep_screen_on_description),
checked = keepScreenOn,
onCheckedChange = { viewModel.setKeepScreenOn(it) }
onCheckedChange = { keepScreenOn = it }
)
HorizontalDivider(
@@ -2815,7 +2825,7 @@ fun SettingsScreen(
},
onValueChangeFinished = {
if (windowScreenBrightnessEnabled) {
viewModel.setWindowScreenBrightness(windowScreenBrightnessUi)
preferencesRepository.updateAsync { this.windowScreenBrightness = windowScreenBrightnessUi }
}
},
valueTextFormatter = { String.format("%.2f", it) },
@@ -2823,9 +2833,7 @@ fun SettingsScreen(
toggleValue = windowScreenBrightnessEnabled,
onToggleChange = { enabled ->
windowScreenBrightnessEnabled = enabled
viewModel.setWindowScreenBrightness(
if (enabled) windowScreenBrightnessUi else null
)
preferencesRepository.updateAsync { this.windowScreenBrightness = if (enabled) windowScreenBrightnessUi else null }
}
)
@@ -2839,7 +2847,7 @@ fun SettingsScreen(
title = stringResource(R.string.settings_screen_hdr),
description = stringResource(R.string.settings_screen_hdr_description),
checked = useHdrScreenMode,
onCheckedChange = { viewModel.setUseHdrScreenMode(it) }
onCheckedChange = { useHdrScreenMode = it }
)
}
@@ -2850,7 +2858,7 @@ fun SettingsScreen(
VolumeKeyActionSetting(
action = volumeKeyAction,
onActionSelected = { viewModel.setVolumeKeyAction(it) }
onActionSelected = { volumeKeyAction = it }
)
}
}
@@ -3117,7 +3125,7 @@ fun SettingsScreen(
TextButton(
onClick = {
if (customAIModelValue.isNotBlank()) {
viewModel.setOpenAIModel(customAIModelValue.trim())
preferencesRepository.updateAsync { this.openAIModel = customAIModelValue.trim() }
}
showCustomAIModelDialog = false
}
@@ -6168,8 +6176,8 @@ fun DefaultFocalLengthSetting(
) {
var showAddDialog by remember { mutableStateOf(false) }
var inputValue by remember { mutableStateOf("") }
val customFocalLengths by viewModel.customFocalLengths.collectAsState(initial = emptyList())
val hiddenFocalLengths by viewModel.hiddenFocalLengths.collectAsState(initial = emptyList())
val customFocalLengths by preferenceValue { it.customFocalLengths }
val hiddenFocalLengths by preferenceValue { it.hiddenFocalLengths }
val cameraState by viewModel.state.collectAsState()
Column(modifier = modifier.fillMaxWidth()) {
@@ -6311,7 +6319,8 @@ fun BackgroundSetting(
viewModel: CameraViewModel,
modifier: Modifier = Modifier
) {
val currentBg by viewModel.backgroundImage.collectAsState()
val preferencesRepository = rememberUserPreferencesRepository()
val currentBg by preferenceValue { it.backgroundImage }
val context = androidx.compose.ui.platform.LocalContext.current
val launcher = androidx.activity.compose.rememberLauncherForActivityResult(
@@ -6339,7 +6348,7 @@ fun BackgroundSetting(
BackgroundItem(
name = bgName,
isSelected = currentBg == bgName,
onClick = { viewModel.setBackgroundImage(bgName) }
onClick = { preferencesRepository.updateAsync { this.backgroundImage = bgName } }
)
}
@@ -6366,9 +6375,10 @@ private fun CaptureButtonAppearanceSetting(
viewModel: CameraViewModel,
modifier: Modifier = Modifier
) {
val style by viewModel.captureButtonStyle.collectAsState()
val color by viewModel.captureButtonColor.collectAsState()
val imagePath by viewModel.captureButtonImagePath.collectAsState()
val preferencesRepository = rememberUserPreferencesRepository()
val style by preferenceValue { it.captureButtonStyle }
val color by preferenceValue { it.captureButtonColor }
val imagePath by preferenceValue { it.captureButtonImagePath }
var showColorPicker by remember { mutableStateOf(false) }
val imageLauncher = rememberLauncherForActivityResult(
@@ -6394,7 +6404,7 @@ private fun CaptureButtonAppearanceSetting(
CaptureButtonAppearanceItem(
label = stringResource(R.string.settings_capture_button_default),
selected = style == CaptureButtonStyle.DEFAULT,
onClick = { viewModel.setCaptureButtonStyle(CaptureButtonStyle.DEFAULT) },
onClick = { preferencesRepository.updateAsync { this.captureButtonStyle = CaptureButtonStyle.DEFAULT } },
modifier = Modifier.weight(1f)
) {
Box(
@@ -44,9 +44,9 @@ fun PhotonCameraTheme(
content: @Composable () -> Unit
) {
val context = LocalContext.current
// Observe only appearance, without decoding camera settings or initializing camera resources.
// 只订阅主题色,不初始化相机资源;UserPreferences 字段按需解析。
val accentFlow = remember(context.applicationContext) {
UserPreferencesRepository(context.applicationContext).accentColor
UserPreferencesRepository(context.applicationContext).flow { it.accentColor }
}
val accentArgb by accentFlow.collectAsState(initial = AppAppearance.DEFAULT_ACCENT_COLOR)
val accent = Color(accentArgb)
File diff suppressed because it is too large. Load diff
@@ -123,30 +123,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
// 用户偏好设置仓库
private val userPreferencesRepository = contentRepository.userPreferencesRepository
val rawLensShadingCorrectionEnabled: StateFlow<Boolean> = userPreferencesRepository.userPreferences
.map { it.rawLensShadingCorrectionEnabled }
.stateIn(viewModelScope, SharingStarted.Eagerly, true)
val categoryOrder: StateFlow<List<String>> = userPreferencesRepository.userPreferences
.map { it.categoryOrder }
.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
val photoQuality: Flow<Int> = userPreferencesRepository.userPreferences.map { it.photoQuality }
val defaultLutId: Flow<String?> = userPreferencesRepository.userPreferences.map { it.lutId }
val defaultVirtualAperture: StateFlow<Float> = userPreferencesRepository.userPreferences.map { it.defaultVirtualAperture }
.stateIn(viewModelScope, SharingStarted.Eagerly, 0f)
val droMode: StateFlow<String> = userPreferencesRepository.userPreferences
.map { it.droMode }
.stateIn(viewModelScope, SharingStarted.Eagerly, "OFF")
val openAIApiKey = userPreferencesRepository.userPreferences.map { it.openAIApiKey }
.stateIn(viewModelScope, SharingStarted.Eagerly, "")
val deleteExported: StateFlow<Boolean> = userPreferencesRepository.userPreferences
.map { it.deleteExported }
.stateIn(viewModelScope, SharingStarted.Eagerly, true)
// 计费管理器
private val billingManager = com.hinnka.mycamera.billing.BillingManagerImpl(application)
@@ -1222,7 +1199,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
private fun resolveRawLensShadingCorrectionForEdit(metadata: MediaMetadata?): Boolean {
return metadata?.rawLensShadingCorrectionEnabled
?: if (metadata?.isImported == true) true else rawLensShadingCorrectionEnabled.value
?: if (metadata?.isImported == true) true else userPreferencesRepository.current.rawLensShadingCorrectionEnabled
}
/**
@@ -1874,12 +1851,6 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
fun setDeleteExported(enabled: Boolean) {
viewModelScope.launch {
userPreferencesRepository.saveDeleteExported(enabled)
}
}
/**
* 批量删除选中的照片
*
@@ -2249,7 +2220,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editRawShadowsAdjustment.value = 0f
editRawBlackPointCorrection.value = 0f
editRawWhitePointCorrection.value = 0f
editRawLensShadingCorrectionEnabled.value = rawLensShadingCorrectionEnabled.value
editRawLensShadingCorrectionEnabled.value = userPreferencesRepository.current.rawLensShadingCorrectionEnabled
editRawBlackLevelMode.value = RawCfaCorrection.MODE_DEFAULT
editRawCustomBlackLevel.value = 0f
editRawWhiteLevelMode.value = RawWhiteLevelCorrection.MODE_DEFAULT
@@ -4094,7 +4065,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val context = getApplication<Application>()
val success = GalleryManager.exportPhoto(
context, photoId, bitmap, contentRepository.photoProcessor, metadata,
0f, 0f, 0f, photoQuality.firstOrNull() ?: 95, suffix
0f, 0f, 0f, userPreferencesRepository.latest().photoQuality, suffix
)
if (success) {
exitEditMode()
@@ -4556,7 +4527,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
try {
val context = getApplication<Application>()
val quality = photoQuality.firstOrNull() ?: 95
val quality = userPreferencesRepository.latest().photoQuality
withContext(Dispatchers.IO) {
toExport.forEachIndexed { index, photo ->
@@ -4655,7 +4626,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
// 使用用户设置的照片质量
processedBitmap.compress(
Bitmap.CompressFormat.JPEG,
photoQuality.firstOrNull() ?: 95,
userPreferencesRepository.latest().photoQuality,
out
)
}