package com.cottondb.android.platform import android.content.Context import android.content.SharedPreferences /** The two device-local paper arrangements; a screen owns its grid column arithmetic. */ enum class PaperLayout(val storageValue: String) { Grid("grid"), List("list"); companion object { fun stored(value: String): PaperLayout = values().firstOrNull { it.storageValue == value } ?: throw PaperLayoutPreferenceException("Saved paper layout is invalid.") } } /** A device-local layout preference, deliberately separate from a person's synced records. */ class AndroidPaperLayoutPreferences private constructor( private val preferences: SharedPreferences, ) { constructor(context: Context, preferenceName: String = PREFERENCE_NAME) : this( context.applicationContext.getSharedPreferences(preferenceName, Context.MODE_PRIVATE), ) /** * Reads may wait for SharedPreferences' first disk load; screen hosts call this off Main. * Only a missing key receives [default]; malformed or unknown persisted values are refused. */ fun read(key: String, default: PaperLayout): PaperLayout { requireKey(key) val stored = try { preferences.getString(key, null) } catch (failure: Throwable) { throw PaperLayoutPreferenceException("Saved paper layout is unavailable.", failure) } ?: return default return try { PaperLayout.stored(stored) } catch (failure: PaperLayoutPreferenceException) { throw PaperLayoutPreferenceException("Saved paper layout is unavailable.", failure) } } /** Writes the process cache now and schedules disk persistence; it does not promise a disk flush. */ fun write(key: String, layout: PaperLayout) { requireKey(key) preferences.edit().putString(key, layout.storageValue).apply() } fun isGrid(key: String, default: PaperLayout): Boolean = read(key, default) == PaperLayout.Grid companion object { internal const val PREFERENCE_NAME = "paper-layout-v1" fun key(screen: String): String { require(screen.isNotBlank()) { "screen must not be blank." } return "paperLayout.$screen" } } private fun requireKey(key: String) { require(key.isNotBlank()) { "key must not be blank." } } } class PaperLayoutPreferenceException(message: String, cause: Throwable? = null) : IllegalStateException(message, cause)