package eu.friedcutlet.yokan.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ColorScheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Shapes import androidx.compose.material3.Typography import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.luminance import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.materialkolor.PaletteStyle import com.materialkolor.dynamiccolor.ColorSpec import com.materialkolor.ktx.themeColor import com.materialkolor.rememberDynamicColorScheme import eu.friedcutlet.yokan.ui.image.decodeImageBitmap import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import yokan.composeapp.generated.resources.Res import yokan.composeapp.generated.resources.atkinson_hyperlegible_regular import yokan.composeapp.generated.resources.inter_regular import yokan.composeapp.generated.resources.jetbrains_mono_regular import yokan.composeapp.generated.resources.lexend_variable import yokan.composeapp.generated.resources.nunito_regular import yokan.composeapp.generated.resources.open_sans_regular import yokan.composeapp.generated.resources.opendyslexic_bold import yokan.composeapp.generated.resources.opendyslexic_regular import yokan.composeapp.generated.resources.poppins_regular import yokan.composeapp.generated.resources.roboto_regular import yokan.composeapp.generated.resources.roboto_slab_regular // Material 3 defaults. FlexColorScheme only overrides component subthemes // (24dp inputs/chips); it does not globally tighten card and dialog shapes. private val YokanShapes = Shapes( extraSmall = RoundedCornerShape(4.dp), small = RoundedCornerShape(8.dp), medium = RoundedCornerShape(12.dp), large = RoundedCornerShape(16.dp), extraLarge = RoundedCornerShape(28.dp), ) private fun buildYokanTypography(family: FontFamily): Typography { val base = Typography() return base.copy( displayLarge = base.displayLarge.withFamily(family), displayMedium = base.displayMedium.withFamily(family), displaySmall = base.displaySmall.withFamily(family), headlineLarge = base.headlineLarge.withFamily(family), headlineMedium = base.headlineMedium.withFamily(family), headlineSmall = base.headlineSmall.withFamily(family), titleLarge = base.titleLarge.withFamily(family), titleMedium = base.titleMedium.withFamily(family), titleSmall = base.titleSmall.withFamily(family), bodyLarge = base.bodyLarge.withFamily(family), bodyMedium = base.bodyMedium.withFamily(family), bodySmall = base.bodySmall.withFamily(family), labelLarge = base.labelLarge.withFamily(family), labelMedium = base.labelMedium.withFamily(family), labelSmall = base.labelSmall.withFamily(family), ) } /** Named font choices exposed in the Appearance picker, ordered for the dropdown. */ val AppFontFamilyChoices: List = listOf( "Default", "Sans", "Serif", "Monospace", "Inter", "Roboto", "Roboto Slab", "Open Sans", "Nunito", "Poppins", "JetBrains Mono", ) /** * Resolve the persisted `appFontFamily` setting to a [FontFamily]. * * - The four system names ("Default", "Sans", "Serif", "Monospace") use the * platform's stock families so they cost nothing to render. * - The named Google Fonts load from bundled regular-weight TTFs in * `composeResources/font/`. Compose Multiplatform synthesises the bold and * italic variants from the actual glyph metrics, which is fine for an app- * wide UI font (we don't need a paragraph-level type system). */ @Composable fun resolveAppFontFamily(name: String?): FontFamily { val n = name?.lowercase().orEmpty() return when (n) { "serif" -> FontFamily.Serif "sans" -> FontFamily.SansSerif "monospace" -> FontFamily.Monospace "inter" -> rememberGoogleFontFamily(Res.font.inter_regular) "roboto" -> rememberGoogleFontFamily(Res.font.roboto_regular) "roboto slab" -> rememberGoogleFontFamily(Res.font.roboto_slab_regular) "open sans" -> rememberGoogleFontFamily(Res.font.open_sans_regular) "nunito" -> rememberGoogleFontFamily(Res.font.nunito_regular) "poppins" -> rememberGoogleFontFamily(Res.font.poppins_regular) "jetbrains mono" -> rememberGoogleFontFamily(Res.font.jetbrains_mono_regular) else -> FontFamily.Default } } /** Resolve fonts offered specifically by the novel reader; Default follows the app choice. */ @Composable fun resolveNovelFontFamily(name: String?, appFontFamily: String?): FontFamily = when (name?.lowercase()) { "opendyslexic" -> rememberNovelFontFamily( Res.font.opendyslexic_regular, Res.font.opendyslexic_bold, ) "lexend" -> rememberNovelFontFamily(Res.font.lexend_variable) "atkinson" -> rememberNovelFontFamily(Res.font.atkinson_hyperlegible_regular) else -> resolveAppFontFamily(appFontFamily) } @Composable private fun rememberNovelFontFamily( regular: org.jetbrains.compose.resources.FontResource, bold: org.jetbrains.compose.resources.FontResource? = null, ): FontFamily { val regularFont = org.jetbrains.compose.resources.Font(regular, FontWeight.Normal) val boldFont = bold?.let { org.jetbrains.compose.resources.Font(it, FontWeight.Bold) } return remember(regular, bold) { if (boldFont == null) FontFamily(regularFont) else FontFamily(regularFont, boldFont) } } val LocalYokanScaffoldColor = androidx.compose.runtime.staticCompositionLocalOf { Color.Unspecified } /** True in e-ink display mode: screens drop motion that would ghost on an e-paper panel. */ val LocalEinkMode = androidx.compose.runtime.staticCompositionLocalOf { false } private val EinkGray = Color(0xFFE0E0E0) /** Pure black on white with gray containers: tonal tints and subtle contrasts vanish on e-paper. */ private val EinkColorScheme = androidx.compose.material3.lightColorScheme( primary = Color.Black, onPrimary = Color.White, primaryContainer = EinkGray, onPrimaryContainer = Color.Black, inversePrimary = Color.White, secondary = Color.Black, onSecondary = Color.White, secondaryContainer = EinkGray, onSecondaryContainer = Color.Black, tertiary = Color.Black, onTertiary = Color.White, tertiaryContainer = EinkGray, onTertiaryContainer = Color.Black, background = Color.White, onBackground = Color.Black, surface = Color.White, onSurface = Color.Black, surfaceVariant = EinkGray, onSurfaceVariant = Color.Black, surfaceTint = Color.White, inverseSurface = Color.Black, inverseOnSurface = Color.White, error = Color.Black, onError = Color.White, errorContainer = EinkGray, onErrorContainer = Color.Black, outline = Color.Black, outlineVariant = Color(0xFF808080), scrim = Color.Black, surfaceBright = Color.White, surfaceDim = EinkGray, surfaceContainerLowest = Color.White, surfaceContainerLow = Color.White, surfaceContainer = Color(0xFFF0F0F0), surfaceContainerHigh = EinkGray, surfaceContainerHighest = EinkGray, ) @Composable fun YokanScaffold( modifier: androidx.compose.ui.Modifier = androidx.compose.ui.Modifier, topBar: @Composable () -> Unit = {}, bottomBar: @Composable () -> Unit = {}, snackbarHost: @Composable () -> Unit = {}, floatingActionButton: @Composable () -> Unit = {}, floatingActionButtonPosition: androidx.compose.material3.FabPosition = androidx.compose.material3.FabPosition.End, contentColor: Color = MaterialTheme.colorScheme.onSurface, contentWindowInsets: androidx.compose.foundation.layout.WindowInsets = androidx.compose.material3.ScaffoldDefaults.contentWindowInsets, content: @Composable (androidx.compose.foundation.layout.PaddingValues) -> Unit, ) { androidx.compose.material3.Scaffold( modifier = modifier, topBar = topBar, bottomBar = bottomBar, snackbarHost = snackbarHost, floatingActionButton = floatingActionButton, floatingActionButtonPosition = floatingActionButtonPosition, containerColor = LocalYokanScaffoldColor.current, contentColor = contentColor, contentWindowInsets = contentWindowInsets, content = content, ) } @Composable private fun yokanDividerColor(): Color = if (MaterialTheme.colorScheme.surface.luminance() < 0.5f) { Color.White.copy(alpha = 31f / 255f) } else { Color.Black.copy(alpha = 31f / 255f) } @Composable fun YokanHorizontalDivider( modifier: androidx.compose.ui.Modifier = androidx.compose.ui.Modifier, thickness: androidx.compose.ui.unit.Dp = 1.dp, color: Color = yokanDividerColor(), ) { androidx.compose.material3.HorizontalDivider( modifier = modifier, thickness = thickness, color = color, ) } private data class ResolvedThemeColors( val scheme: ColorScheme, val scaffold: Color, ) @Composable private fun rememberGoogleFontFamily( resource: org.jetbrains.compose.resources.FontResource, ): FontFamily { val font = org.jetbrains.compose.resources.Font(resource, FontWeight.Normal) return remember(resource) { FontFamily(font) } } private fun TextStyle.withFamily(family: FontFamily): TextStyle = copy(fontFamily = family) fun resolveDarkMode(followSystem: Boolean, themeIsDark: Boolean, systemDark: Boolean): Boolean = if (followSystem) systemDark else themeIsDark @Composable fun YokanTheme( darkTheme: Boolean, schemeIndex: Int = 2, pureBlackDark: Boolean = false, blendLevel: Float = 0.1f, uiScale: Float = 1.0f, seedColorArgb: Int? = null, seedImagePath: String? = null, materialYou: Boolean = false, materialExpressive: Boolean = false, paletteStyleName: String = "TonalSpot", fontFamily: FontFamily = FontFamily.Default, eink: Boolean = false, content: @Composable () -> Unit, ) { val themed = resolveThemeColors( darkTheme = darkTheme, schemeIndex = schemeIndex, pureBlackDark = pureBlackDark, blendLevel = blendLevel, seedColorArgb = seedColorArgb, seedImagePath = seedImagePath, materialYou = materialYou, materialExpressive = materialExpressive, paletteStyleName = paletteStyleName, ) val resolvedColors = if (eink) ResolvedThemeColors(EinkColorScheme, Color.White) else themed val clampedScale = uiScale.coerceIn(0.75f, 2.0f) val baseDensity = androidx.compose.ui.platform.LocalDensity.current val scaledDensity = androidx.compose.ui.unit.Density( density = baseDensity.density * clampedScale, fontScale = baseDensity.fontScale, ) androidx.compose.runtime.CompositionLocalProvider( androidx.compose.ui.platform.LocalDensity provides scaledDensity, LocalYokanScaffoldColor provides resolvedColors.scaffold, LocalEinkMode provides eink, // Ripples animate for hundreds of milliseconds and ghost on e-paper. androidx.compose.material3.LocalRippleConfiguration provides if (eink) null else androidx.compose.material3.LocalRippleConfiguration.current, ) { // `MaterialExpressiveTheme` is not yet stable in Compose Multiplatform's // material3 surface (1.4 marks it `internal`). To still honour the // user's Expressive toggle we feed `PaletteStyle.Expressive` + // `ColorSpec.SPEC_2025` into the color scheme (see `resolvePaletteStyle`), // which is the runtime-visible half of the spec. Motion/typography // upgrades land once material3 exposes the expressive APIs publicly. val typography = remember(fontFamily) { buildYokanTypography(fontFamily) } MaterialTheme( colorScheme = resolvedColors.scheme, typography = typography, shapes = YokanShapes, content = content, ) } } @Composable private fun resolveThemeColors( darkTheme: Boolean, schemeIndex: Int, pureBlackDark: Boolean, blendLevel: Float, seedColorArgb: Int?, seedImagePath: String?, materialYou: Boolean, materialExpressive: Boolean, paletteStyleName: String, ): ResolvedThemeColors { // Material You: defer to the OS palette when the user opted in and the // platform actually exposes one (Android 12+). if (materialYou) { rememberMaterialYouScheme(darkTheme)?.let { return ResolvedThemeColors(scheme = it, scaffold = it.background) } } val legacyFallback = remember(schemeIndex, darkTheme, pureBlackDark, blendLevel) { val scheme = FlexSchemes.getOrElse(schemeIndex) { FlexSchemes[2] } if (darkTheme) { ResolvedThemeColors( scheme = buildDarkScheme(scheme.dark, scheme.light, blendLevel), scaffold = buildDarkScaffoldColor(scheme.dark, blendLevel, pureBlackDark), ) } else { ResolvedThemeColors( scheme = buildLightScheme(scheme.light, blendLevel), scaffold = buildLightScaffoldColor(scheme.light, blendLevel), ) } } // Decoding and quantizing the seed image is file I/O + CPU work: keep it off composition. val fallbackPrimary = legacyFallback.scheme.primary val imageSeed: Color? by produceState(null, seedImagePath, fallbackPrimary) { value = seedImagePath?.takeIf { it.isNotBlank() }?.let { path -> withContext(Dispatchers.Default) { decodeImageBitmap(path)?.themeColor(fallback = fallbackPrimary) } } } // Mangayomi's normal path is FlexThemeData built from the selected // FlexSchemeColor. Do not reinterpret that palette as a Material You seed: // doing so changes every container, badge, tab, and navigation color. if (seedColorArgb == null && imageSeed == null && !materialExpressive) { return legacyFallback } // Precedence: image > explicit seed > legacy palette primary. val seed = imageSeed ?: seedColorArgb?.let { Color(it.toLong() and 0xFFFFFFFFL) } ?: legacyFallback.scheme.primary val style = resolvePaletteStyle(paletteStyleName, materialExpressive) val dynamicScheme = rememberDynamicColorScheme( seedColor = seed, isDark = darkTheme, isAmoled = pureBlackDark && darkTheme, style = style, // SPEC_2025 is required for Material Expressive — when the toggle is off // we still opt into it so users get the latest tonal mapping. specVersion = ColorSpec.SpecVersion.SPEC_2025, ) return ResolvedThemeColors(scheme = dynamicScheme, scaffold = dynamicScheme.background) } private fun resolvePaletteStyle(name: String, materialExpressive: Boolean): PaletteStyle { // Material Expressive overrides whatever the user picked because the spec // pairs Expressive motion with the Expressive palette. if (materialExpressive) return PaletteStyle.Expressive return PaletteStyle.entries.firstOrNull { it.name.equals(name, ignoreCase = true) } ?: PaletteStyle.TonalSpot } /** Names of MaterialKolor palette styles exposed in the settings dropdown. */ val PaletteStyleChoices: List get() = PaletteStyle.entries.map { it.name } @Composable fun rememberSystemDark(): Boolean = isSystemInDarkTheme()