package com.cottondb.android.platformimport android.content.Contextimport android.content.SharedPreferences/** The two device-local paper arrangements; a screen owns its grid column arithmetic. */enumclassPaperLayout(val storageValue: String) {Grid("grid"),List("list");companionobject {fun stored(value: String): PaperLayout = values().firstOrNull { it.storageValue == value } ?: throwPaperLayoutPreferenceException("Saved paper layout is invalid.") }}/** A device-local layout preference, deliberately separate from a person's synced records. */classAndroidPaperLayoutPreferencesprivate constructor(privateval 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) {throwPaperLayoutPreferenceException("Saved paper layout is unavailable.", failure) } ?: returndefaultreturntry {PaperLayout.stored(stored) } catch (failure: PaperLayoutPreferenceException) {throwPaperLayoutPreferenceException("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.Gridcompanionobject {internalconstval PREFERENCE_NAME = "paper-layout-v1"fun key(screen: String): String { require(screen.isNotBlank()) { "screen must not be blank." }return"paperLayout.$screen" } }privatefun requireKey(key: String) { require(key.isNotBlank()) { "key must not be blank." } }}classPaperLayoutPreferenceException(message: String, cause: Throwable? = null) : IllegalStateException(message, cause)