feat(profiles): система управления профилями подключения

Добавлена система профилей: сохранение текущей конфигурации (SSH + клиент)
как именованного профиля, переключение, переименование, удаление, обновление
активного профиля из текущих настроек.

- Profile, ProfilesSnapshot, JSON-сериализация
- ProfilesScreen (bottom sheet) с пустым состоянием и карточками
- ProfileNameDialog с проверкой уникальности
- ActiveProfileBar на главном экране — единая точка входа
- HapticModifier — централизованный haptic для не-MD компонентов
- Иконки: cached, edit, manage_accounts, more_vert, save, switch_account, host
- Удалены неиспользуемые: key, link
- MD3 аудит: ElevatedCard вместо Card+elevation(2.dp), token pairing
  через onSurfaceVariant вместо alpha-копий, captcha-строка в strings.xml,
  navigationBarsPadding на ActiveProfileBar, tween 600→500ms
This commit is contained in:
samosvalishe committed 2026-04-29 01:03:30 +03:00
1 parent 8691a9a8cb
commit 4f0d393d2e
18 files changed
+1070 -53

No files matched your search

@@ -26,7 +26,6 @@ class MainActivity : ComponentActivity() {
val splashScreen = installSplashScreen()
super.onCreate(savedInstanceState)
// Удерживаем системный splash пока ViewModel не инициализируется
splashScreen.setKeepOnScreenCondition { !viewModel.isInitialized.value }
HapticUtil.perform(this, HapticUtil.Pattern.LAUNCH)
@@ -32,8 +32,9 @@ data class SshConfig(
data class ClientConfig(
val serverAddress: String = "",
val vkLink: String = "",
val vkLinks: List<String> = emptyList(),
val threads: Int = 4,
val allocsPerStream: Int = 1,
val useUdp: Boolean = true,
val manualCaptcha: Boolean = false,
val localPort: String = "127.0.0.1:9000",
@@ -48,6 +49,21 @@ data class ClientConfig(
val debugMode: Boolean = false
)
/**
* Парсит сохранённые звонковые ссылки. Сначала пробует новый ключ
* (newline-joined), потом legacy (одиночная ссылка). Тримит, дропает пустые.
*/
internal fun decodeVkLinks(joined: String?, legacy: String?): List<String> {
val fromNew = joined
?.split('\n', '\r')
?.map { it.trim() }
?.filter { it.isNotEmpty() }
?: emptyList()
if (fromNew.isNotEmpty()) return fromNew
val one = legacy?.trim().orEmpty()
return if (one.isNotEmpty()) listOf(one) else emptyList()
}
object DnsMode {
const val AUTO = "auto"
const val UDP = "udp"
@@ -66,8 +82,14 @@ class AppPreferences(context: Context) {
val SSH_HOST_FP = stringPreferencesKey("ssh_host_fp")
val ONBOARDING_DONE = booleanPreferencesKey("onboarding_done")
val CLIENT_SERVER_ADDR = stringPreferencesKey("client_server_addr")
// Legacy single-link key. Читается только для миграции, перезаписывается
// первой ссылкой из списка для обратной совместимости со старыми билдами.
val CLIENT_VK_LINK = stringPreferencesKey("client_vk_link")
// Список звонковых ссылок, разделитель — \n. URL не содержит перевод строки,
// поэтому простой join безопасен и не требует JSON-эскейпа.
val CLIENT_VK_LINKS = stringPreferencesKey("client_vk_links")
val CLIENT_THREADS = intPreferencesKey("client_threads")
val CLIENT_ALLOCS_PER_STREAM = intPreferencesKey("client_allocs_per_stream")
val CLIENT_UDP = booleanPreferencesKey("client_udp")
val CLIENT_MANUAL_CAPTCHA = booleanPreferencesKey("client_manual_captcha")
val CLIENT_LOCAL_PORT = stringPreferencesKey("client_local_port")
@@ -86,6 +108,8 @@ class AppPreferences(context: Context) {
val PROXY_CONNECT = stringPreferencesKey("proxy_connect")
val DYNAMIC_THEME = booleanPreferencesKey("dynamic_theme")
val TG_SUBSCRIBE_SHOWN = booleanPreferencesKey("tg_subscribe_shown")
val PROFILES_JSON = stringPreferencesKey("profiles_json")
val ACTIVE_PROFILE_ID = stringPreferencesKey("active_profile_id")
// Устаревшие ключи — используются только для миграции
private val SSH_PASS_LEGACY = stringPreferencesKey("ssh_pass")
@@ -130,8 +154,9 @@ class AppPreferences(context: Context) {
.map { prefs ->
ClientConfig(
serverAddress = prefs[CLIENT_SERVER_ADDR] ?: "",
vkLink = prefs[CLIENT_VK_LINK] ?: "",
vkLinks = decodeVkLinks(prefs[CLIENT_VK_LINKS], prefs[CLIENT_VK_LINK]),
threads = prefs[CLIENT_THREADS] ?: 4,
allocsPerStream = prefs[CLIENT_ALLOCS_PER_STREAM] ?: 1,
useUdp = prefs[CLIENT_UDP] ?: true,
manualCaptcha = prefs[CLIENT_MANUAL_CAPTCHA] ?: false,
localPort = prefs[CLIENT_LOCAL_PORT] ?: "127.0.0.1:9000",
@@ -165,6 +190,28 @@ class AppPreferences(context: Context) {
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
.map { prefs -> prefs[TG_SUBSCRIBE_SHOWN] ?: false }
val profilesFlow: Flow<List<Profile>> = context.dataStore.data
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
.map { prefs -> ProfileJson.decodeList(prefs[PROFILES_JSON]) }
val activeProfileIdFlow: Flow<String?> = context.dataStore.data
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
.map { prefs -> prefs[ACTIVE_PROFILE_ID]?.takeIf { it.isNotBlank() } }
/** Заменяет весь список профилей. */
suspend fun saveProfiles(list: List<Profile>) {
context.dataStore.edit { prefs ->
prefs[PROFILES_JSON] = ProfileJson.encodeList(list)
}
}
suspend fun setActiveProfileId(id: String?) {
context.dataStore.edit { prefs ->
if (id == null) prefs.remove(ACTIVE_PROFILE_ID)
else prefs[ACTIVE_PROFILE_ID] = id
}
}
suspend fun saveSshConfig(config: SshConfig) {
// Чувствительные данные — в зашифрованное хранилище
withContext(Dispatchers.IO) {
@@ -192,8 +239,13 @@ class AppPreferences(context: Context) {
suspend fun saveClientConfig(config: ClientConfig) {
context.dataStore.edit { prefs ->
prefs[CLIENT_SERVER_ADDR] = config.serverAddress
prefs[CLIENT_VK_LINK] = config.vkLink
val cleaned = config.vkLinks.map { it.trim() }.filter { it.isNotEmpty() }
prefs[CLIENT_VK_LINKS] = cleaned.joinToString("\n")
// Дублируем первую ссылку в legacy-ключ — чтобы откат на старый бинарь
// не сломал базовый сценарий с одной ссылкой.
prefs[CLIENT_VK_LINK] = cleaned.firstOrNull() ?: ""
prefs[CLIENT_THREADS] = config.threads
prefs[CLIENT_ALLOCS_PER_STREAM] = config.allocsPerStream
prefs[CLIENT_UDP] = config.useUdp
prefs[CLIENT_MANUAL_CAPTCHA] = config.manualCaptcha
// Мигрируем старый ключ: noDtls удалён из приложения.
@@ -230,6 +282,19 @@ class AppPreferences(context: Context) {
}
}
/**
* Снимок: список + id активного. Объединено в один Flow, чтобы UI получал
* консистентную пару (нет окна, в котором активный id указывает на удалённый).
*/
val profilesSnapshot: Flow<ProfilesSnapshot> = context.dataStore.data
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
.map { prefs ->
ProfilesSnapshot(
list = ProfileJson.decodeList(prefs[PROFILES_JSON]),
activeId = prefs[ACTIVE_PROFILE_ID]?.takeIf { it.isNotBlank() }
)
}
/** Полный сброс: DataStore + EncryptedSharedPreferences + кастомный бинарник */
suspend fun resetAll() {
context.dataStore.edit { it.clear() }
@@ -0,0 +1,127 @@
package com.freeturn.app.data
import org.json.JSONArray
import org.json.JSONObject
import java.util.UUID
/**
* Именованный снимок настроек: SSH-сервер + клиентские параметры.
* Хранится сериализованным в DataStore. Активный профиль — это id из общего
* списка; его SshConfig/ClientConfig дублируются в legacy-ключах prefs, чтобы
* существующие экраны и ViewModel могли работать без переписывания.
*/
data class Profile(
val id: String = UUID.randomUUID().toString(),
val name: String,
val ssh: SshConfig = SshConfig(),
val client: ClientConfig = ClientConfig(),
val proxyListen: String = "0.0.0.0:56000",
val proxyConnect: String = "127.0.0.1:40537"
)
data class ProfilesSnapshot(
val list: List<Profile> = emptyList(),
val activeId: String? = null
) {
val active: Profile? get() = list.firstOrNull { it.id == activeId }
}
private fun decodeProfileVkLinks(o: JSONObject): List<String> {
val arr = o.optJSONArray("vkLinks")
if (arr != null) {
val out = (0 until arr.length()).mapNotNull {
arr.optString(it).trim().takeIf { s -> s.isNotEmpty() }
}
if (out.isNotEmpty()) return out
}
val legacy = o.optString("vkLink").trim()
return if (legacy.isNotEmpty()) listOf(legacy) else emptyList()
}
internal object ProfileJson {
fun encodeList(list: List<Profile>): String {
val arr = JSONArray()
list.forEach { arr.put(encode(it)) }
return arr.toString()
}
fun decodeList(raw: String?): List<Profile> {
if (raw.isNullOrBlank()) return emptyList()
return try {
val arr = JSONArray(raw)
(0 until arr.length()).map { decode(arr.getJSONObject(it)) }
} catch (_: Throwable) {
emptyList()
}
}
private fun encode(p: Profile): JSONObject = JSONObject().apply {
put("id", p.id)
put("name", p.name)
put("ssh", JSONObject().apply {
put("ip", p.ssh.ip)
put("port", p.ssh.port)
put("username", p.ssh.username)
put("password", p.ssh.password)
put("authType", p.ssh.authType)
put("sshKey", p.ssh.sshKey)
put("hostFingerprint", p.ssh.hostFingerprint)
})
put("client", JSONObject().apply {
put("serverAddress", p.client.serverAddress)
// Legacy single-link для обратной совместимости со старыми билдами.
put("vkLink", p.client.vkLinks.firstOrNull().orEmpty())
put("vkLinks", JSONArray().apply { p.client.vkLinks.forEach { put(it) } })
put("threads", p.client.threads)
put("allocsPerStream", p.client.allocsPerStream)
put("useUdp", p.client.useUdp)
put("manualCaptcha", p.client.manualCaptcha)
put("localPort", p.client.localPort)
put("isRawMode", p.client.isRawMode)
put("rawCommand", p.client.rawCommand)
put("vlessMode", p.client.vlessMode)
put("dnsMode", p.client.dnsMode)
put("forcePort443", p.client.forcePort443)
put("debugMode", p.client.debugMode)
})
put("proxyListen", p.proxyListen)
put("proxyConnect", p.proxyConnect)
}
private fun decode(o: JSONObject): Profile {
val sshO = o.optJSONObject("ssh") ?: JSONObject()
val cliO = o.optJSONObject("client") ?: JSONObject()
return Profile(
id = o.optString("id").ifBlank { UUID.randomUUID().toString() },
name = o.optString("name").ifBlank { "Без названия" },
ssh = SshConfig(
ip = sshO.optString("ip"),
port = sshO.optInt("port", 22),
username = sshO.optString("username", "root"),
password = sshO.optString("password"),
authType = sshO.optString("authType", "PASSWORD"),
sshKey = sshO.optString("sshKey"),
hostFingerprint = sshO.optString("hostFingerprint")
),
client = ClientConfig(
serverAddress = cliO.optString("serverAddress"),
vkLinks = decodeProfileVkLinks(cliO),
threads = cliO.optInt("threads", 4),
allocsPerStream = cliO.optInt("allocsPerStream", 1),
useUdp = cliO.optBoolean("useUdp", true),
manualCaptcha = cliO.optBoolean("manualCaptcha", false),
localPort = cliO.optString("localPort", "127.0.0.1:9000"),
isRawMode = cliO.optBoolean("isRawMode", false),
rawCommand = cliO.optString("rawCommand"),
vlessMode = cliO.optBoolean("vlessMode", false),
dnsMode = cliO.optString("dnsMode", DnsMode.AUTO).let {
if (it in DnsMode.ALL) it else DnsMode.AUTO
},
forcePort443 = cliO.optBoolean("forcePort443", false),
debugMode = cliO.optBoolean("debugMode", false)
),
proxyListen = o.optString("proxyListen").ifBlank { "0.0.0.0:56000" },
proxyConnect = o.optString("proxyConnect").ifBlank { "127.0.0.1:40537" }
)
}
}
@@ -0,0 +1,74 @@
package com.freeturn.app.ui.components
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.freeturn.app.R
import com.freeturn.app.ui.HapticUtil
/**
* Универсальный диалог ввода имени профиля (создание/переименование).
*
* @param takenNames множество уже используемых имён (case-insensitive). Имя `initial`
* автоматически исключается из проверки — пользователь может оставить
* текущее имя при переименовании.
*/
@Composable
fun ProfileNameDialog(
title: String,
initial: String,
takenNames: Collection<String> = emptyList(),
confirmLabel: String = stringResource(R.string.profile_save),
onDismiss: () -> Unit,
onConfirm: (String) -> Unit
) {
val context = LocalContext.current
var name by rememberSaveable { mutableStateOf(initial) }
val takenSet = remember(takenNames, initial) {
takenNames.map { it.trim().lowercase() }.toSet() - initial.trim().lowercase()
}
val trimmed = name.trim()
val isDuplicate = trimmed.isNotEmpty() && trimmed.lowercase() in takenSet
val isEmpty = trimmed.isEmpty()
val canConfirm = !isEmpty && !isDuplicate
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(title) },
text = {
OutlinedTextField(
value = name,
onValueChange = { name = it },
label = { Text(stringResource(R.string.profile_name_label)) },
placeholder = { Text(stringResource(R.string.profile_name_placeholder)) },
singleLine = true,
isError = isDuplicate,
supportingText = if (isDuplicate) {
{ Text(stringResource(R.string.profile_name_taken)) }
} else null
)
},
confirmButton = {
TextButton(
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.SUCCESS)
onConfirm(trimmed)
},
enabled = canConfirm
) { Text(confirmLabel) }
},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
}
)
}
@@ -34,8 +34,7 @@ import androidx.compose.ui.res.stringResource
import com.freeturn.app.R
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.CircularWavyProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
@@ -149,8 +148,11 @@ fun HomeScreen(
}
val privacyMode by viewModel.privacyMode.collectAsStateWithLifecycle()
val profilesSnapshot by viewModel.profilesSnapshot.collectAsStateWithLifecycle()
val showBottomSheet = rememberSaveable { mutableStateOf(false) }
val showProfilesSheet = rememberSaveable { mutableStateOf(false) }
val bottomSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val profilesSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val snackbarHostState = remember { SnackbarHostState() }
Scaffold(
@@ -162,7 +164,7 @@ fun HomeScreen(
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
onNavigateToSshSetup()
}) {
Icon(painterResource(R.drawable.key_24px), contentDescription = stringResource(R.string.connection))
Icon(painterResource(R.drawable.host_24px), contentDescription = stringResource(R.string.connection))
}
IconButton(onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
@@ -175,10 +177,10 @@ fun HomeScreen(
},
snackbarHost = { SnackbarHost(snackbarHostState) }
) { padding ->
Box(modifier = Modifier.fillMaxSize().padding(padding)) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
@@ -220,7 +222,7 @@ fun HomeScreen(
}
is ProxyState.Starting -> stringResource(R.string.proxy_connecting)
is ProxyState.Error -> s.message
is ProxyState.CaptchaRequired -> "Требуется прохождение капчи"
is ProxyState.CaptchaRequired -> stringResource(R.string.proxy_captcha_required)
else -> stringResource(R.string.proxy_press_to_start)
},
// "tnum" — tabular numbers: все цифры одинаковой ширины. Без него
@@ -238,17 +240,17 @@ fun HomeScreen(
if (isConfigured) {
Spacer(Modifier.height(40.dp))
Card(
ElevatedCard(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 24.dp),
elevation = CardDefaults.cardElevation(2.dp)
.padding(horizontal = 24.dp)
) {
Column(modifier = Modifier.padding(20.dp)) {
Text(stringResource(R.string.current_settings), style = MaterialTheme.typography.titleSmall)
Spacer(Modifier.height(12.dp))
ConfigRow(stringResource(R.string.server), clientConfig.serverAddress.redact(privacyMode))
ConfigRow(stringResource(R.string.threads), "${clientConfig.threads}")
ConfigRow(stringResource(R.string.allocs_per_stream_label), "${clientConfig.allocsPerStream}")
ConfigRow(
stringResource(R.string.transport_protocol),
if (clientConfig.vlessMode) "VLESS"
@@ -304,6 +306,23 @@ fun HomeScreen(
}
Spacer(Modifier.height(32.dp))
// Резерв под прилипший к низу переключатель — он виден всегда.
Spacer(Modifier.height(96.dp))
}
// Прилипший к низу переключатель — точка входа в управление профилями.
// Виден всегда: даже без сохранённых профилей показывает «Несохранённая
// конфигурация» и открывает sheet с действиями save/import.
ActiveProfileBar(
snapshot = profilesSnapshot,
onSwitch = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
showProfilesSheet.value = true
},
modifier = Modifier
.align(Alignment.BottomCenter)
.padding(horizontal = 16.dp, vertical = 12.dp)
)
}
}
@@ -323,6 +342,22 @@ fun HomeScreen(
}
}
if (showProfilesSheet.value) {
val sheetColor = MaterialTheme.colorScheme.surfaceContainerLow
ModalBottomSheet(
onDismissRequest = { showProfilesSheet.value = false },
sheetState = profilesSheetState,
containerColor = sheetColor
) {
com.freeturn.app.ui.screens.ProfilesSheetContent(
viewModel = viewModel,
snapshot = profilesSnapshot,
containerColor = sheetColor,
onClose = { showProfilesSheet.value = false }
)
}
}
UpdateDialogs(viewModel)
}
@@ -435,7 +470,7 @@ private fun ProxyToggleButton(state: ProxyState, onClick: () -> Unit) {
MaterialTheme.colorScheme.secondaryContainer
else -> MaterialTheme.colorScheme.primaryContainer
},
animationSpec = tween(600),
animationSpec = tween(500),
label = "btn_bg"
)
val contentColor by animateColorAsState(
@@ -446,7 +481,7 @@ private fun ProxyToggleButton(state: ProxyState, onClick: () -> Unit) {
MaterialTheme.colorScheme.onSecondaryContainer
else -> MaterialTheme.colorScheme.onPrimaryContainer
},
animationSpec = tween(600),
animationSpec = tween(500),
label = "btn_fg"
)
val scale by animateFloatAsState(
@@ -464,7 +499,7 @@ private fun ProxyToggleButton(state: ProxyState, onClick: () -> Unit) {
.semantics { contentDescription = buttonLabel },
shape = CircleShape,
color = containerColor,
tonalElevation = if (state is ProxyState.Running) 6.dp else 1.dp
tonalElevation = if (state is ProxyState.Running) 3.dp else 1.dp
) {
Column(
modifier = Modifier.fillMaxSize(),
@@ -754,32 +789,101 @@ private fun RepoLinkItem(
onHaptic: () -> Unit,
onOpen: (String) -> Unit
) {
ListItem(
headlineContent = { Text(title) },
colors = ListItemDefaults.colors(containerColor = containerColor),
supportingContent = if (subtitle != null) ({
Text(
subtitle,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary
)
}) else null,
trailingContent = {
Icon(
painterResource(R.drawable.open_in_new_24px),
contentDescription = stringResource(R.string.btn_open),
modifier = Modifier.size(18.dp),
tint = MaterialTheme.colorScheme.primary
)
},
modifier = Modifier.clickable {
Surface(
onClick = {
onHaptic()
onOpen(url)
}
)
},
color = containerColor
) {
ListItem(
headlineContent = { Text(title) },
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
supportingContent = if (subtitle != null) ({
Text(
subtitle,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary
)
}) else null,
trailingContent = {
Icon(
painterResource(R.drawable.open_in_new_24px),
contentDescription = stringResource(R.string.btn_open),
modifier = Modifier.size(18.dp),
tint = MaterialTheme.colorScheme.primary
)
}
)
}
}
/**
* Прилипшая к низу M3 «карточка» — единственная точка входа в управление профилями.
* Виден всегда: с сохранённым активным профилем показывает его имя, без — лейбл
* «несохранённая конфигурация» с приглашением открыть sheet.
*/
@Composable
private fun ActiveProfileBar(
snapshot: com.freeturn.app.data.ProfilesSnapshot,
onSwitch: () -> Unit,
modifier: Modifier = Modifier
) {
val active = snapshot.active
val title: String = active?.name ?: stringResource(R.string.profile_unsaved_label)
val subtitle: String? = if (active != null) stringResource(R.string.profile_active_label) else null
Surface(
modifier = modifier
.fillMaxWidth()
.navigationBarsPadding(),
shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.surfaceContainerHigh,
tonalElevation = 3.dp,
onClick = onSwitch
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.weight(1f)
) {
Icon(
painterResource(R.drawable.manage_accounts_24px),
contentDescription = null,
tint = if (active != null) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant
)
Column {
if (subtitle != null) {
Text(
subtitle,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Text(
title,
style = MaterialTheme.typography.titleSmall
)
}
}
Icon(
painterResource(R.drawable.arrow_forward_24px),
contentDescription = stringResource(R.string.profile_switch_action),
tint = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
internal fun String.redact(enabled: Boolean) = if (enabled) "••••••" else this
/**
@@ -78,7 +78,6 @@ fun OnboardingScreen(
) {
Spacer(Modifier.height(56.dp))
// Illustration + text
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Box(
modifier = Modifier
@@ -115,7 +114,6 @@ fun OnboardingScreen(
Spacer(Modifier.height(28.dp))
// Privacy notice
Card(
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant
@@ -142,7 +140,6 @@ fun OnboardingScreen(
}
}
// Action buttons
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
@@ -160,7 +157,7 @@ fun OnboardingScreen(
Text(stringResource(R.string.setup_server), style = MaterialTheme.typography.labelLarge)
}
Spacer(Modifier.height(12.dp))
Spacer(Modifier.height(8.dp))
TextButton(onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.SELECTION)
@@ -0,0 +1,378 @@
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
package com.freeturn.app.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.selected
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.freeturn.app.R
import com.freeturn.app.data.Profile
import com.freeturn.app.data.ProfilesSnapshot
import com.freeturn.app.ui.HapticUtil
import com.freeturn.app.ui.components.ProfileNameDialog
import com.freeturn.app.ui.util.hapticClickable
import com.freeturn.app.viewmodel.MainViewModel
@Composable
fun ProfilesSheetContent(
viewModel: MainViewModel,
snapshot: ProfilesSnapshot,
containerColor: Color,
@Suppress("UNUSED_PARAMETER") onClose: () -> Unit
) {
val context = LocalContext.current
val updatedMsg = stringResource(R.string.profile_updated_toast)
var showSaveDialog by rememberSaveable { mutableStateOf(false) }
var renameTarget by rememberSaveable { mutableStateOf<String?>(null) }
var deleteTarget by rememberSaveable { mutableStateOf<String?>(null) }
var menuTarget by rememberSaveable { mutableStateOf<String?>(null) }
val listColors = ListItemDefaults.colors(containerColor = containerColor)
val takenNames = remember(snapshot.list) { snapshot.list.map { it.name } }
val hasActive = snapshot.activeId != null
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.navigationBarsPadding()
) {
Text(
stringResource(R.string.profiles_title),
style = MaterialTheme.typography.titleLarge,
modifier = Modifier.padding(start = 24.dp, end = 24.dp, top = 8.dp, bottom = 8.dp)
)
if (hasActive) {
ListItem(
headlineContent = { Text(stringResource(R.string.profile_update_current)) },
supportingContent = { Text(stringResource(R.string.profile_update_current_hint)) },
leadingContent = { Icon(painterResource(R.drawable.cached_24px), null) },
colors = listColors,
modifier = Modifier.hapticClickable(HapticUtil.Pattern.SUCCESS) {
viewModel.updateActiveProfileFromCurrent()
android.widget.Toast.makeText(context, updatedMsg, android.widget.Toast.LENGTH_SHORT).show()
}
)
}
ListItem(
headlineContent = { Text(stringResource(R.string.profile_save_current)) },
supportingContent = { Text(stringResource(R.string.profile_save_current_hint)) },
leadingContent = { Icon(painterResource(R.drawable.save_24px), null) },
colors = listColors,
modifier = Modifier.hapticClickable(HapticUtil.Pattern.CLICK) {
showSaveDialog = true
}
)
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
if (snapshot.list.isEmpty()) {
ProfilesEmptyState(
onSave = { showSaveDialog = true },
modifier = Modifier
.fillMaxWidth()
.weight(1f)
)
} else {
Text(
stringResource(R.string.profile_section_saved),
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = 24.dp, top = 8.dp, bottom = 4.dp)
)
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.weight(1f),
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(snapshot.list, key = { it.id }) { p ->
ProfileCard(
profile = p,
isActive = snapshot.activeId == p.id,
menuExpanded = menuTarget == p.id,
onApply = {
if (snapshot.activeId != p.id) viewModel.applyProfile(p.id)
},
onMenuToggle = { menuTarget = if (menuTarget == p.id) null else p.id },
onMenuDismiss = { menuTarget = null },
onRename = {
menuTarget = null
renameTarget = p.id
},
onDelete = {
menuTarget = null
deleteTarget = p.id
}
)
}
}
}
}
if (showSaveDialog) {
ProfileNameDialog(
title = stringResource(R.string.profile_save_dialog_title),
initial = "",
takenNames = takenNames,
onDismiss = { showSaveDialog = false },
onConfirm = { name ->
viewModel.saveCurrentAsProfile(name)
showSaveDialog = false
}
)
}
renameTarget?.let { id ->
val profile = snapshot.list.firstOrNull { it.id == id }
if (profile == null) {
renameTarget = null
} else {
ProfileNameDialog(
title = stringResource(R.string.profile_rename),
initial = profile.name,
takenNames = takenNames,
onDismiss = { renameTarget = null },
onConfirm = { name ->
viewModel.renameProfile(id, name)
renameTarget = null
}
)
}
}
deleteTarget?.let { id ->
val profile = snapshot.list.firstOrNull { it.id == id }
if (profile == null) {
deleteTarget = null
} else {
AlertDialog(
onDismissRequest = { deleteTarget = null },
title = { Text(stringResource(R.string.profile_delete_title)) },
text = { Text(stringResource(R.string.profile_delete_desc, profile.name)) },
confirmButton = {
TextButton(
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.ERROR)
viewModel.deleteProfile(id)
deleteTarget = null
},
colors = ButtonDefaults.textButtonColors(
contentColor = MaterialTheme.colorScheme.error
)
) { Text(stringResource(R.string.profile_delete)) }
},
dismissButton = {
TextButton(onClick = { deleteTarget = null }) {
Text(stringResource(R.string.cancel))
}
}
)
}
}
}
@Composable
private fun ProfileCard(
profile: Profile,
isActive: Boolean,
menuExpanded: Boolean,
onApply: () -> Unit,
onMenuToggle: () -> Unit,
onMenuDismiss: () -> Unit,
onRename: () -> Unit,
onDelete: () -> Unit,
) {
val context = LocalContext.current
val containerColor = if (isActive)
MaterialTheme.colorScheme.secondaryContainer
else
MaterialTheme.colorScheme.surfaceContainerLow
val onContainer = if (isActive)
MaterialTheme.colorScheme.onSecondaryContainer
else
MaterialTheme.colorScheme.onSurface
val onContainerVariant = if (isActive)
MaterialTheme.colorScheme.onSecondaryContainer
else
MaterialTheme.colorScheme.onSurfaceVariant
Card(
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
onApply()
},
enabled = !isActive,
modifier = Modifier
.fillMaxWidth()
.semantics { selected = isActive },
colors = CardDefaults.cardColors(containerColor = containerColor),
shape = MaterialTheme.shapes.medium
) {
Row(
modifier = Modifier.padding(start = 16.dp, end = 4.dp, top = 12.dp, bottom = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
if (isActive) {
Icon(
painterResource(R.drawable.check_circle_24px),
contentDescription = stringResource(R.string.profile_active),
tint = MaterialTheme.colorScheme.primary
)
} else {
Spacer(Modifier.size(24.dp))
}
Column(modifier = Modifier.weight(1f)) {
Text(
profile.name,
style = MaterialTheme.typography.titleMedium,
color = onContainer
)
val sub = listOfNotNull(
profile.client.serverAddress.takeIf { it.isNotBlank() },
profile.ssh.ip.takeIf { it.isNotBlank() }?.let { "SSH $it" }
).joinToString(" · ").ifBlank { "—" }
Text(
sub,
style = MaterialTheme.typography.bodySmall,
color = onContainerVariant
)
}
Box {
IconButton(onClick = onMenuToggle) {
Icon(
painterResource(R.drawable.more_vert_24px),
contentDescription = stringResource(R.string.profile_more),
tint = onContainer
)
}
DropdownMenu(
expanded = menuExpanded,
onDismissRequest = onMenuDismiss
) {
DropdownMenuItem(
text = { Text(stringResource(R.string.profile_rename)) },
leadingIcon = { Icon(painterResource(R.drawable.edit_24px), null) },
onClick = onRename
)
HorizontalDivider()
DropdownMenuItem(
text = {
Text(
stringResource(R.string.profile_delete),
color = MaterialTheme.colorScheme.error
)
},
leadingIcon = {
Icon(
painterResource(R.drawable.delete_24px),
contentDescription = null,
tint = MaterialTheme.colorScheme.error
)
},
onClick = onDelete
)
}
}
}
}
}
@Composable
private fun ProfilesEmptyState(
onSave: () -> Unit,
modifier: Modifier = Modifier
) {
val context = LocalContext.current
Column(
modifier = modifier.padding(horizontal = 32.dp, vertical = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Surface(
shape = CircleShape,
color = MaterialTheme.colorScheme.surfaceContainerHigh,
modifier = Modifier.size(96.dp)
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
Icon(
painterResource(R.drawable.manage_accounts_24px),
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(48.dp)
)
}
}
Spacer(Modifier.height(16.dp))
Text(
stringResource(R.string.profiles_empty_title),
style = MaterialTheme.typography.titleMedium,
textAlign = TextAlign.Center
)
Spacer(Modifier.height(8.dp))
Text(
stringResource(R.string.profiles_empty_desc),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
Spacer(Modifier.height(20.dp))
FilledTonalButton(onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
onSave()
}) {
Icon(painterResource(R.drawable.save_24px), null)
Spacer(Modifier.size(8.dp))
Text(stringResource(R.string.profile_save_current))
}
}
}
@@ -0,0 +1,30 @@
package com.freeturn.app.ui.util
import androidx.compose.foundation.clickable
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.platform.LocalContext
import com.freeturn.app.ui.HapticUtil
/**
* Кликабельность с тактильным откликом. Унифицирует haptic feedback для всех
* интерактивных элементов вне Material-компонентов (которые могут иметь свой).
*/
fun Modifier.hapticClickable(
pattern: HapticUtil.Pattern = HapticUtil.Pattern.CLICK,
enabled: Boolean = true,
onClick: () -> Unit
): Modifier = composed {
val context = LocalContext.current
clickable(enabled = enabled) {
HapticUtil.perform(context, pattern)
onClick()
}
}
@Composable
fun rememberHaptic(): (HapticUtil.Pattern) -> Unit {
val context = LocalContext.current
return { pattern -> HapticUtil.perform(context, pattern) }
}
@@ -10,7 +10,10 @@ import com.freeturn.app.ProxyService
import com.freeturn.app.ProxyServiceState
import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.ClientConfig
import com.freeturn.app.data.Profile
import com.freeturn.app.data.ProfilesSnapshot
import com.freeturn.app.data.SshConfig
import java.util.UUID
import com.freeturn.app.domain.AppUpdater
import com.freeturn.app.domain.LocalProxyManager
import com.freeturn.app.domain.SshRepository
@@ -22,6 +25,7 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
class MainViewModel(application: Application) : AndroidViewModel(application) {
@@ -102,6 +106,138 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
val tgSubscribeShown: StateFlow<Boolean> = prefs.tgSubscribeShownFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
val profilesSnapshot: StateFlow<ProfilesSnapshot> = prefs.profilesSnapshot
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ProfilesSnapshot())
/** Сохранить текущие настройки как новый профиль и сделать активным. */
fun saveCurrentAsProfile(name: String) {
viewModelScope.launch {
val current = prefs.profilesSnapshot.first()
val ssh = prefs.sshConfigFlow.first()
val client = prefs.clientConfigFlow.first()
val listen = prefs.proxyListenFlow.first()
val connect = prefs.proxyConnectFlow.first()
val base = name.trim().ifBlank { defaultProfileName(client.serverAddress) }
val profile = Profile(
id = UUID.randomUUID().toString(),
name = uniqueProfileName(base, current.list, excludingId = null),
ssh = ssh,
client = client,
proxyListen = listen,
proxyConnect = connect
)
prefs.saveProfiles(current.list + profile)
prefs.setActiveProfileId(profile.id)
}
}
/**
* Гарантирует уникальность имени профиля. Защита от deep-link / автоматических
* сценариев, где UI-диалог не валидирует ввод. Дубль превращается в
* "имя (2)", "имя (3)" и т.д.
*/
private fun uniqueProfileName(
base: String,
existing: List<Profile>,
excludingId: String?
): String {
val taken = existing
.filter { it.id != excludingId }
.map { it.name.trim().lowercase() }
.toSet()
val trimmed = base.trim()
if (trimmed.lowercase() !in taken) return trimmed
var i = 2
while ("$trimmed ($i)".lowercase() in taken) i++
return "$trimmed ($i)"
}
/** Публичный триггер пересохранения активного профиля текущими настройками. */
fun updateActiveProfileFromCurrent() {
viewModelScope.launch { mirrorActiveProfile() }
}
/**
* Зеркалирует текущие prefs (ssh+client) в активный профиль. Источник истины —
* профиль, но legacy-ключи остаются «scratch»-областью для случая «нет профилей».
* Вызывается автоматически после каждой записи ssh/client конфига, чтобы
* пользовательские правки не терялись при переключении профилей.
*/
private suspend fun mirrorActiveProfile() {
val current = prefs.profilesSnapshot.first()
val activeId = current.activeId ?: return
val ssh = prefs.sshConfigFlow.first()
val client = prefs.clientConfigFlow.first()
val listen = prefs.proxyListenFlow.first()
val connect = prefs.proxyConnectFlow.first()
val updated = current.list.map {
if (it.id == activeId)
it.copy(ssh = ssh, client = client, proxyListen = listen, proxyConnect = connect)
else it
}
if (updated != current.list) prefs.saveProfiles(updated)
}
fun renameProfile(id: String, name: String) {
viewModelScope.launch {
val current = prefs.profilesSnapshot.first()
val target = current.list.firstOrNull { it.id == id } ?: return@launch
val base = name.trim().ifBlank { target.name }
val unique = uniqueProfileName(base, current.list, excludingId = id)
val updated = current.list.map {
if (it.id == id) it.copy(name = unique) else it
}
prefs.saveProfiles(updated)
}
}
/**
* Применяет профиль: загружает его ssh/client в legacy-ключи (которые читают
* существующие экраны) и помечает активным. Если прокси запущен — перезапускает,
* иначе логика клиента продолжит использовать старые настройки.
*/
fun applyProfile(id: String) {
viewModelScope.launch {
val current = prefs.profilesSnapshot.first()
val target = current.list.firstOrNull { it.id == id } ?: return@launch
prefs.saveSshConfig(target.ssh)
prefs.saveClientConfig(target.client)
prefs.saveProxyConfig(target.proxyListen, target.proxyConnect)
prefs.setActiveProfileId(target.id)
if (ProxyServiceState.isRunning.value) {
proxyManager.stopProxy()
// Ждём фактической остановки сервиса вместо магического delay,
// иначе onStartCommand может стартовать со старыми аргументами.
withTimeoutOrNull(2_000) {
ProxyServiceState.isRunning.first { !it }
}
proxyManager.startProxy(target.client)
}
}
}
fun deleteProfile(id: String) {
viewModelScope.launch {
val current = prefs.profilesSnapshot.first()
val remaining = current.list.filterNot { it.id == id }
prefs.saveProfiles(remaining)
if (current.activeId == id) {
val next = remaining.firstOrNull()
prefs.setActiveProfileId(next?.id)
if (next != null) {
prefs.saveSshConfig(next.ssh)
prefs.saveClientConfig(next.client)
prefs.saveProxyConfig(next.proxyListen, next.proxyConnect)
}
}
}
}
private fun defaultProfileName(serverAddr: String): String =
serverAddr.substringBefore(':').takeIf { it.isNotBlank() }
?: getApplication<Application>().getString(com.freeturn.app.R.string.profile_default_name)
fun setDynamicTheme(enabled: Boolean) {
viewModelScope.launch { prefs.setDynamicTheme(enabled) }
}
@@ -119,10 +255,12 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
fun connectSsh(config: SshConfig) {
viewModelScope.launch {
prefs.saveSshConfig(config)
mirrorActiveProfile()
val (success, fp) = sshRepository.connectSsh(config)
if (success) {
if (config.hostFingerprint.isEmpty() && fp != null) {
prefs.saveSshFingerprint(fp)
mirrorActiveProfile()
}
HapticUtil.perform(getApplication(), HapticUtil.Pattern.SUCCESS)
} else {
@@ -166,6 +304,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
if (current.vlessMode == enabled) return
viewModelScope.launch {
prefs.saveClientConfig(current.copy(vlessMode = enabled))
mirrorActiveProfile()
val serverRunning = (serverState.value as? ServerState.Known)?.running == true
if (serverRunning) {
sshRepository.stopServer()
@@ -195,11 +334,17 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
// Preferences
fun saveClientConfig(config: ClientConfig) {
viewModelScope.launch { prefs.saveClientConfig(config) }
viewModelScope.launch {
prefs.saveClientConfig(config)
mirrorActiveProfile()
}
}
fun saveProxyServerConfig(listen: String, connect: String) {
viewModelScope.launch { prefs.saveProxyConfig(listen, connect) }
viewModelScope.launch {
prefs.saveProxyConfig(listen, connect)
mirrorActiveProfile()
}
}
fun setOnboardingDone() {