Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 4 additions & 45 deletions app/src/main/java/com/freeturn/app/data/AppPreferences.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
Expand Down Expand Up @@ -158,9 +157,7 @@ class AppPreferences(context: Context) {

/** Конфиг активного сервера; правила туннелирования общие, если включена галочка. */
val clientConfigFlow: Flow<ClientConfig> =
activeServerFlow.combine(splitSharedFlow) { server, shared ->
(server?.client ?: ClientConfig()).withShared(shared)
}.distinctUntilChanged()
prefFlow { p -> p.activeSplitClient() }.distinctUntilChanged()

private fun ClientConfig.withShared(shared: SplitRules?): ClientConfig =
if (splitTunnelShared && shared != null) {
Expand Down Expand Up @@ -429,50 +426,12 @@ class AppPreferences(context: Context) {

/** Правка правил: в общий набор, если у активного сервера включена галочка, иначе в его свои. */
suspend fun setSplitTunnelRule(mode: String? = null, apps: String? = null) {
val cfg = clientConfigFlow.first()
if (cfg.splitTunnelShared) {
context.dataStore.edit { p ->
p[SPLIT_SHARED_MODE] = mode ?: cfg.splitTunnelMode
p[SPLIT_SHARED_APPS] = apps ?: cfg.splitTunnelApps
}
} else {
updateActiveServer { s ->
s.copy(
client = s.client.copy(
splitTunnelMode = mode ?: s.client.splitTunnelMode,
splitTunnelApps = apps ?: s.client.splitTunnelApps
)
)
}
}
context.dataStore.edit { it.updateSplitTunnelRule(mode, apps) }
}

/**
* Включение: общий набор создаётся из правил этого сервера, если его ещё нет.
* Выключение: общий набор копируется в собственные правила сервера, остальные не меняются.
*/
/** Общий набор и флаг профиля меняются одним атомарным снимком. */
suspend fun setSplitShared(enabled: Boolean) {
val own = serversSnapshot.first().active?.client ?: return
val shared = splitSharedFlow.first()
if (enabled) {
if (shared == null) {
context.dataStore.edit {
it[SPLIT_SHARED_MODE] = own.splitTunnelMode
it[SPLIT_SHARED_APPS] = own.splitTunnelApps
}
}
updateActiveServer { s -> s.copy(client = s.client.copy(splitTunnelShared = true)) }
} else {
updateActiveServer { s ->
s.copy(
client = s.client.copy(
splitTunnelShared = false,
splitTunnelMode = shared?.mode ?: s.client.splitTunnelMode,
splitTunnelApps = shared?.apps ?: s.client.splitTunnelApps
)
)
}
}
context.dataStore.edit { it.updateSplitShared(enabled) }
}

suspend fun setTgSubscribeShown() {
Expand Down
60 changes: 60 additions & 0 deletions app/src/main/java/com/freeturn/app/data/SplitTunnelPreferences.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.freeturn.app.data

import androidx.datastore.preferences.core.MutablePreferences
import androidx.datastore.preferences.core.Preferences
import com.freeturn.app.data.AppPreferences.Companion.ACTIVE_SERVER_ID
import com.freeturn.app.data.AppPreferences.Companion.SERVERS_JSON
import com.freeturn.app.data.AppPreferences.Companion.SPLIT_SHARED_APPS
import com.freeturn.app.data.AppPreferences.Companion.SPLIT_SHARED_MODE
import com.freeturn.app.data.config.ClientConfig
import com.freeturn.app.data.server.Server
import com.freeturn.app.data.server.ServerJson

/** Read effective rules from the same snapshot as the active profile. */
internal fun Preferences.activeSplitClient(): ClientConfig {
val own = ServerJson.decodeList(this[SERVERS_JSON])
.firstOrNull { it.id == this[ACTIVE_SERVER_ID] }?.client ?: return ClientConfig()
val mode = this[SPLIT_SHARED_MODE]
return if (own.splitTunnelShared && mode != null) own.copy(
splitTunnelMode = mode, splitTunnelApps = this[SPLIT_SHARED_APPS].orEmpty()
) else own
}

private fun MutablePreferences.editActiveSplit(transform: (Server) -> Server) {
val activeId = this[ACTIVE_SERVER_ID] ?: return
val list = ServerJson.decodeListOrNull(this[SERVERS_JSON]) ?: return
if (list.none { it.id == activeId }) return
this[SERVERS_JSON] = ServerJson.encodeList(list.map { if (it.id == activeId) transform(it) else it })
}

/** Called only inside DataStore.edit: never merge with a pre-transaction snapshot. */
internal fun MutablePreferences.updateSplitTunnelRule(mode: String?, apps: String?) {
editActiveSplit { server ->
if (server.client.splitTunnelShared) {
this[SPLIT_SHARED_MODE] = mode ?: this[SPLIT_SHARED_MODE] ?: server.client.splitTunnelMode
this[SPLIT_SHARED_APPS] = apps ?: this[SPLIT_SHARED_APPS] ?: server.client.splitTunnelApps
server
} else server.copy(client = server.client.copy(
splitTunnelMode = mode ?: server.client.splitTunnelMode,
splitTunnelApps = apps ?: server.client.splitTunnelApps
))
}
}

internal fun MutablePreferences.updateSplitShared(enabled: Boolean) {
editActiveSplit { server ->
val own = server.client
if (own.splitTunnelShared == enabled) return@editActiveSplit server
if (enabled) {
if (this[SPLIT_SHARED_MODE] == null) {
this[SPLIT_SHARED_MODE] = own.splitTunnelMode
this[SPLIT_SHARED_APPS] = own.splitTunnelApps
}
server.copy(client = own.copy(splitTunnelShared = true))
} else server.copy(client = own.copy(
splitTunnelShared = false,
splitTunnelMode = this[SPLIT_SHARED_MODE] ?: own.splitTunnelMode,
splitTunnelApps = this[SPLIT_SHARED_APPS] ?: own.splitTunnelApps
))
}
}
14 changes: 14 additions & 0 deletions app/src/main/java/com/freeturn/app/data/config/DecorSeason.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.freeturn.app.data.config

/** Calendar seasons for the northern hemisphere; independent of locale language. */
enum class DecorSeason { SPRING, SUMMER, AUTUMN, WINTER }

internal fun decorSeason(month: Int): DecorSeason {
require(month in 1..12)
return when (month) {
3, 4, 5 -> DecorSeason.SPRING
6, 7, 8 -> DecorSeason.SUMMER
9, 10, 11 -> DecorSeason.AUTUMN
else -> DecorSeason.WINTER
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import androidx.compose.ui.unit.dp
import androidx.graphics.shapes.Morph
import androidx.graphics.shapes.RoundedPolygon
import androidx.graphics.shapes.toPath
import com.freeturn.app.data.config.DecorSeason
import com.freeturn.app.R
import com.freeturn.app.ui.theme.LocalReducedMotion
import com.freeturn.app.ui.theme.extendedColorScheme
Expand All @@ -75,12 +76,13 @@ internal fun ConnectionHero(
uptimeText: String?,
showStreams: Boolean,
decorEnabled: Boolean,
season: DecorSeason,
onToggle: () -> Unit,
modifier: Modifier = Modifier
) {
val kind = status.phase.heroKind()
val reducedMotion = LocalReducedMotion.current
val decor = AUTUMN_VIBE && decorEnabled
val decor = decorEnabled
// Ноль - ещё не жали: с него разлёт не запускается.
var burstKey by remember { mutableIntStateOf(0) }

Expand All @@ -93,6 +95,7 @@ internal fun ConnectionHero(
tunnelActive = status.tunnelUp,
reducedMotion = reducedMotion,
decor = decor,
season = season,
burstKey = burstKey,
onClick = {
if (decor && !reducedMotion) burstKey++
Expand Down Expand Up @@ -128,6 +131,7 @@ private fun HeroToggleButton(
tunnelActive: Boolean,
reducedMotion: Boolean,
decor: Boolean,
season: DecorSeason,
burstKey: Int,
onClick: () -> Unit
) {
Expand Down Expand Up @@ -192,7 +196,7 @@ private fun HeroToggleButton(

Box(contentAlignment = Alignment.Center) {
if (decor) {
AutumnHeroGlow(
SeasonalHeroGlow(
color = containerColor,
strong = kind == HeroKind.Running,
buttonSize = HeroButtonSize
Expand Down Expand Up @@ -226,7 +230,7 @@ private fun HeroToggleButton(
}

if (decor) {
AutumnLeafBurst(burstKey = burstKey, buttonSize = HeroButtonSize)
SeasonalParticleBurst(burstKey = burstKey, buttonSize = HeroButtonSize, season = season)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package com.freeturn.app.ui.screens.home

import android.text.format.Formatter
import android.widget.Toast
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
Expand All @@ -21,6 +20,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
Expand Down Expand Up @@ -55,11 +55,7 @@ internal fun ConnectionStatsCard(
if (shown) {
Surface(
shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.surfaceContainerLow,
border = BorderStroke(
1.dp,
MaterialTheme.colorScheme.outlineVariant
),
color = Color.Transparent,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = Spacing.xxl)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.freeturn.app.ui.screens.home

import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.repeatOnLifecycle
import com.freeturn.app.data.config.DecorSeason
import com.freeturn.app.data.config.decorSeason
import kotlinx.coroutines.delay
import java.time.Duration
import java.time.ZonedDateTime

/** Refresh on resume and local midnight; stop the timer while the screen is stopped. */
@Composable
internal fun rememberDecorSeason(): DecorSeason {
val owner = LocalLifecycleOwner.current
fun current() = decorSeason(ZonedDateTime.now().monthValue)
val season by produceState(current(), owner) {
owner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
while (true) {
value = current()
val now = ZonedDateTime.now()
val midnight = now.toLocalDate().plusDays(1).atStartOfDay(now.zone)
delay(Duration.between(now, midnight).toMillis().coerceAtLeast(1_000))
}
}
}
return season
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ fun HomeScreen(
val updateState by settingsViewModel.updateState.collectAsStateWithLifecycle()
val suppressUpdatePrompt by settingsViewModel.suppressUpdatePrompt.collectAsStateWithLifecycle()
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
val season = rememberDecorSeason()
val seasonalDecor by settingsViewModel.seasonalDecor.collectAsStateWithLifecycle()
val serversSnapshot by serverConfigViewModel.serversSnapshot.collectAsStateWithLifecycle()

Expand Down Expand Up @@ -164,6 +165,7 @@ fun HomeScreen(
// direct - всегда один поток, счётчик ничего не сообщает.
showStreams = clientConfig.provider != Provider.DIRECT,
decorEnabled = seasonalDecor,
season = season,
onToggle = {
// Любая непокоящаяся фаза (включая капчу и старт) - остановка.
if (status.busy) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.freeturn.app.data.config.DecorSeason
import com.freeturn.app.R
import com.freeturn.app.ui.util.HapticUtil
import kotlinx.coroutines.launch
Expand All @@ -46,15 +47,7 @@ import kotlin.math.roundToInt
import kotlin.math.sin
import kotlin.random.Random

/**
* Сезонное оформление героя: вращение фигуры кнопки пальцем, тёплый ореол и разлёт
* листвы по нажатию. Флаг про сезон, а не про вкус пользователя: вкус живёт тумблером
* в настройках, а этим снимается вся тема целиком, когда осень прошла. Форму и палитру
* кнопки не трогаем: на Material You цвета приходят с обоев, и своя пара выбивалась бы
* из темы пользователя.
*/
internal const val AUTUMN_VIBE = true

/** Seasonal particles reuse one short animation; no frames run while idle. */
private const val LEAF_COUNT = 7
private const val BURST_MS = 950

Expand All @@ -66,27 +59,20 @@ private const val SPIN_TICK_MIN_MS = 30L
private const val SPREAD_FROM_DEG = -170f
private const val SPREAD_TO_DEG = -10f

private val autumnLeavesLight = listOf(
Color(0xFFB4530A),
Color(0xFFD97706),
Color(0xFF8B3A0F),
Color(0xFFC98A12),
Color(0xFF9A6212),
)

private val autumnLeavesDark = listOf(
Color(0xFFFFB787),
Color(0xFFFFC46B),
Color(0xFFE98A4F),
Color(0xFFD9A441),
Color(0xFFFFD9A0),
)

// Тема не отдаёт darkTheme наружу, а Material You подменяет всю схему - светлота фона
// единственный признак, верный и для статичных схем, и для динамических.
@Composable
private fun autumnLeafColors(): List<Color> =
if (MaterialTheme.colorScheme.surface.luminance() < 0.5f) autumnLeavesDark else autumnLeavesLight
private fun seasonalColors(season: DecorSeason): List<Color> {
val dark = MaterialTheme.colorScheme.surface.luminance() < 0.5f
return when (season) {
DecorSeason.WINTER -> listOf(Color.White)
DecorSeason.SPRING, DecorSeason.SUMMER -> if (dark) listOf(Color(0xFF86EFAC), Color(0xFF4ADE80), Color(0xFFA3E635))
else listOf(Color(0xFF15803D), Color(0xFF16A34A), Color(0xFF4D7C0F))
DecorSeason.AUTUMN -> if (dark) listOf(
Color(0xFFFFB787), Color(0xFFFFC46B), Color(0xFFE98A4F), Color(0xFFD9A441), Color(0xFFFFD9A0)
) else listOf(
Color(0xFFB4530A), Color(0xFFD97706), Color(0xFF8B3A0F), Color(0xFFC98A12), Color(0xFF9A6212)
)
}
}

@Immutable
private class Leaf(
Expand Down Expand Up @@ -124,7 +110,7 @@ private fun leafBatch(seed: Int, colorCount: Int): List<Leaf> {
* снаружи - анимация контейнера уже посчитана вызывающим.
*/
@Composable
internal fun AutumnHeroGlow(
internal fun SeasonalHeroGlow(
color: Color,
strong: Boolean,
buttonSize: Dp,
Expand All @@ -151,17 +137,20 @@ internal fun AutumnHeroGlow(
* родитель не должен клипать содержимое.
*/
@Composable
internal fun AutumnLeafBurst(
internal fun SeasonalParticleBurst(
burstKey: Int,
buttonSize: Dp,
season: DecorSeason,
modifier: Modifier = Modifier
) {
val colors = autumnLeafColors()
val painter = painterResource(R.drawable.eco_24px)
val colors = seasonalColors(season)
val painter = painterResource(if (season == DecorSeason.WINTER) R.drawable.snowflake_outlined_24px else R.drawable.eco_24px)
val progress = remember { Animatable(1f) }
var batch by remember { mutableStateOf(emptyList<Leaf>()) }

LaunchedEffect(burstKey) {
LaunchedEffect(burstKey, season) {
progress.snapTo(1f)
batch = emptyList()
if (burstKey == 0) return@LaunchedEffect
batch = leafBatch(burstKey, colors.size)
progress.snapTo(0f)
Expand Down
Loading
Loading