From d82ee7a302e59f634cf902ad4b465efa21ba1295 Mon Sep 17 00:00:00 2001 From: samosvalishe Date: Wed, 10 Jun 2026 14:15:50 +0300 Subject: [PATCH] =?UTF-8?q?feat(ui):=20=D0=BF=D0=B5=D1=80=D0=B5=D1=80?= =?UTF-8?q?=D0=B0=D0=B1=D0=BE=D1=82=D0=BA=D0=B0=20=D1=8D=D0=BA=D1=80=D0=B0?= =?UTF-8?q?=D0=BD=D0=BE=D0=B2=20=D0=BD=D0=B0=D1=81=D1=82=D1=80=D0=BE=D0=B9?= =?UTF-8?q?=D0=BA=D0=B8=20=D0=BD=D0=B0=20=D0=BE=D0=B1=D1=89=D0=B8=D1=85=20?= =?UTF-8?q?settings-=D1=81=D1=82=D1=80=D0=BE=D0=BA=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - SettingsGroup: общий набор строк (SettingsFieldSlot, SettingsControlLabel, SettingsSwitchRow) для всех экранов настройки - ClientSetup: секции (подключение/производительность/DNS/дополнительно), ручной DNS гасит свитч DNS оператора через DnsList, невалидные токены подсвечиваются; Uri-клавиатура на адресных полях - ServerManagement: черновики apply-модели с одним рестартом; пустой obf-ключ блокирует apply, если живой SSH + sync не сгенерят его - LargeFlexibleTopAppBar и единые отступы на экранах настройки --- .../app/ui/components/SettingsGroup.kt | 131 +++ .../app/ui/screens/ClientSetupScreen.kt | 514 +++++----- .../app/ui/screens/ConnectionModeScreen.kt | 20 +- .../app/ui/screens/ServerManagementScreen.kt | 896 +++++++----------- .../freeturn/app/ui/screens/SshSetupScreen.kt | 384 ++++---- app/src/main/res/values/strings.xml | 63 +- 6 files changed, 1015 insertions(+), 993 deletions(-) diff --git a/app/src/main/java/com/freeturn/app/ui/components/SettingsGroup.kt b/app/src/main/java/com/freeturn/app/ui/components/SettingsGroup.kt index 092bd20..53e53b9 100644 --- a/app/src/main/java/com/freeturn/app/ui/components/SettingsGroup.kt +++ b/app/src/main/java/com/freeturn/app/ui/components/SettingsGroup.kt @@ -11,18 +11,25 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.shape.CornerSize +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.MaterialShapes import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface +import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.toShape import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource +import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.heading import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp @@ -66,6 +73,130 @@ fun SettingsCard(content: @Composable ColumnScope.() -> Unit) { } } +// Внутренний радиус сегментированной группы (между элементами). Внешний — shapes.large, +// чтобы группа из одного элемента визуально совпадала с SettingsCard. +private val GroupInnerCorner = CornerSize(5.dp) + +/** + * Форма элемента сегментированной группы (M3 expressive, как в системных настройках + * Android 16): наружные углы группы большие, внутренние — маленькие, между элементами + * микро-зазор (см. [SettingsGroup]). + */ +@Composable +fun settingsItemShape(index: Int, count: Int): Shape { + val outer = MaterialTheme.shapes.large.topStart + return RoundedCornerShape( + topStart = if (index == 0) outer else GroupInnerCorner, + topEnd = if (index == 0) outer else GroupInnerCorner, + bottomStart = if (index == count - 1) outer else GroupInnerCorner, + bottomEnd = if (index == count - 1) outer else GroupInnerCorner + ) +} + +/** + * Слот для произвольного контрола внутри [SettingsCard] — текстовое поле, слайдер, + * сегменты, метка. Единый внутренний отступ (как у строк) + вертикальный зазор между + * вложенными элементами. Несколько слотов в одной карточке разделяй [SettingsRowDivider]. + */ +@Composable +fun SettingsFieldSlot( + verticalSpacing: androidx.compose.ui.unit.Dp = 12.dp, + content: @Composable ColumnScope.() -> Unit +) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(verticalSpacing), + content = content + ) +} + +/** Заголовок + пояснение над контролом (сегменты/слайдер): пара с плотным зазором. */ +@Composable +fun SettingsControlLabel(title: String, desc: String? = null) { + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(title, style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurface) + if (desc != null) { + Text(desc, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } +} + +/** Колонка сегментированной группы: элементы с зазором 2dp вместо разделителей. */ +@Composable +fun SettingsGroup(content: @Composable ColumnScope.() -> Unit) { + Column( + verticalArrangement = Arrangement.spacedBy(2.dp), + modifier = Modifier.fillMaxWidth(), + content = content + ) +} + +/** Элемент сегментированной группы: тональный контейнер с формой по позиции. */ +@Composable +fun SettingsGroupItem(index: Int, count: Int, content: @Composable ColumnScope.() -> Unit) { + Surface( + shape = settingsItemShape(index, count), + color = MaterialTheme.colorScheme.surfaceContainerLow, + modifier = Modifier.fillMaxWidth() + ) { + Column(content = content) + } +} + +/** + * Строка-свитч в стиле [SettingsEntryRow]: тональная иконка (опц.), заголовок/подзаголовок, + * trailing Switch с галкой в thumb (M3 expressive). Семантику несёт вся строка — + * toggleable + [Role.Switch], TalkBack озвучивает как переключатель с состоянием. + * Haptic встроен; [onCheckedChange] — чистое действие. + */ +@Composable +fun SettingsSwitchRow( + title: String, + checked: Boolean, + onCheckedChange: (Boolean) -> Unit, + iconRes: Int? = null, + subtitle: String? = null, + enabled: Boolean = true +) { + val context = LocalContext.current + // MD3 disabled content = 0.38 альфы; заголовок и подзаголовок гаснут синхронно. + val titleColor = if (enabled) MaterialTheme.colorScheme.onSurface + else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f) + val subtitleColor = if (enabled) MaterialTheme.colorScheme.onSurfaceVariant + else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.38f) + Row( + modifier = Modifier + .fillMaxWidth() + .toggleable( + value = checked, + enabled = enabled, + role = Role.Switch, + onValueChange = { v -> + HapticUtil.perform( + context, + if (v) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF + ) + onCheckedChange(v) + } + ) + .padding(horizontal = 16.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(16.dp) + ) { + if (iconRes != null) SettingsRowIcon(iconRes, enabled = enabled) + Column(modifier = Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.bodyLarge, color = titleColor) + if (subtitle != null) { + Text(subtitle, style = MaterialTheme.typography.bodyMedium, color = subtitleColor) + } + } + // null → display-only: клики и семантику несёт строка (один haptic, один фокус). + Switch(checked = checked, onCheckedChange = null, enabled = enabled) + } +} + /** Тональная иконка-кружок (Sunny) строки настроек. Один источник формы/размера. */ @Composable fun SettingsRowIcon(iconRes: Int, enabled: Boolean = true) { diff --git a/app/src/main/java/com/freeturn/app/ui/screens/ClientSetupScreen.kt b/app/src/main/java/com/freeturn/app/ui/screens/ClientSetupScreen.kt index f7d8062..5963189 100644 --- a/app/src/main/java/com/freeturn/app/ui/screens/ClientSetupScreen.kt +++ b/app/src/main/java/com/freeturn/app/ui/screens/ClientSetupScreen.kt @@ -7,7 +7,6 @@ package com.freeturn.app.ui.screens import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize @@ -18,23 +17,20 @@ import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button -import androidx.compose.material3.DividerDefaults -import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton +import androidx.compose.material3.LargeFlexibleTopAppBar import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField -import androidx.compose.ui.res.painterResource import androidx.compose.material3.Scaffold import androidx.compose.material3.SegmentedButton import androidx.compose.material3.SegmentedButtonDefaults import androidx.compose.material3.SingleChoiceSegmentedButtonRow import androidx.compose.material3.Slider -import androidx.compose.material3.Switch import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -48,14 +44,26 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp -import com.freeturn.app.R import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.freeturn.app.R import com.freeturn.app.data.ClientConfig +import com.freeturn.app.data.DnsList import com.freeturn.app.data.DnsMode import com.freeturn.app.data.Provider import com.freeturn.app.ui.HapticUtil +import com.freeturn.app.ui.components.SectionLabel +import com.freeturn.app.ui.components.SettingsCard +import com.freeturn.app.ui.components.SettingsContentMaxWidth +import com.freeturn.app.ui.components.SettingsControlLabel +import com.freeturn.app.ui.components.SettingsFieldSlot +import com.freeturn.app.ui.components.SettingsGroup +import com.freeturn.app.ui.components.SettingsGroupItem +import com.freeturn.app.ui.components.SettingsRowDivider +import com.freeturn.app.ui.components.SettingsSwitchRow import com.freeturn.app.viewmodel.ServerViewModel import com.freeturn.app.viewmodel.SettingsViewModel import kotlin.math.roundToInt @@ -119,8 +127,7 @@ fun ClientSetupScreen( var streamsPerCred by remember(saved.streamsPerCred) { mutableFloatStateOf(saved.streamsPerCred.toFloat()) } var localPort by remember(saved.localPort) { mutableStateOf(saved.localPort) } var magicTurn by remember(saved.magicTurn) { mutableStateOf(saved.magicTurn) } - var lastSliderInt by remember(saved.threads) { mutableIntStateOf(saved.threads) } - var lastStreamsInt by remember(saved.streamsPerCred) { mutableIntStateOf(saved.streamsPerCred) } + var customDns by remember(saved.customDns) { mutableStateOf(saved.customDns) } // Автозаполнение адреса сервера из SSH-конфига если поле пустое LaunchedEffect(effSshIp, effProxyListen) { @@ -134,7 +141,7 @@ fun ClientSetupScreen( // clientEdit сам маршрутизирует запись в профиль by-id либо в legacy и под // mutex сверяет цель — защита от гонки переключения за время дебаунса. LaunchedEffect( - serverAddress, vkLink, threads, streamsPerCred, localPort, magicTurn + serverAddress, vkLink, threads, streamsPerCred, localPort, magicTurn, customDns ) { delay(600) clientEdit { current -> @@ -144,17 +151,18 @@ fun ClientSetupScreen( threads = threads.roundToInt(), streamsPerCred = streamsPerCred.roundToInt(), localPort = localPort.trim(), - magicTurn = magicTurn.trim() + magicTurn = magicTurn.trim(), + customDns = customDns.trim() ) } } - val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() + val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior() Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { - TopAppBar( + LargeFlexibleTopAppBar( title = { Text(stringResource(R.string.provider_connection_settings)) }, navigationIcon = { if (onBack != null) { @@ -181,258 +189,231 @@ fun ClientSetupScreen( ) { Column( modifier = Modifier - .widthIn(max = 840.dp) + .widthIn(max = SettingsContentMaxWidth) .fillMaxWidth() - .padding(horizontal = 24.dp), + .padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(16.dp) ) { - Spacer(Modifier.height(4.dp)) - - // Подключение - Text(stringResource(R.string.connection_title), style = MaterialTheme.typography.titleMedium) - - OutlinedTextField( - value = serverAddress.redact(privacyMode), - onValueChange = { if (!privacyMode) serverAddress = it }, - label = { Text(stringResource(R.string.server_address_label)) }, - placeholder = { Text(stringResource(R.string.server_address_placeholder)) }, - modifier = Modifier.fillMaxWidth(), - singleLine = true, - readOnly = privacyMode, - supportingText = { Text(stringResource(R.string.server_address_support)) } - ) - - if (saved.provider == Provider.VK) { - OutlinedTextField( - value = vkLink.redact(privacyMode), - onValueChange = { if (!privacyMode) vkLink = it }, - label = { Text(stringResource(R.string.call_link_label)) }, - placeholder = { Text(stringResource(R.string.call_link_placeholder)) }, - modifier = Modifier.fillMaxWidth(), - singleLine = true, - readOnly = privacyMode, - supportingText = { Text(stringResource(R.string.call_link_support)) } - ) - } - - OutlinedTextField( - value = localPort.redact(privacyMode), - onValueChange = { if (!privacyMode) localPort = it }, - label = { Text(stringResource(R.string.local_listen_address)) }, - placeholder = { Text(stringResource(R.string.local_listen_placeholder)) }, - modifier = Modifier.fillMaxWidth(), - singleLine = true, - readOnly = privacyMode, - supportingText = { Text(stringResource(R.string.local_listen_support)) } - ) - - HorizontalDivider(Modifier, DividerDefaults.Thickness, DividerDefaults.color) - - // Параметры - Text(stringResource(R.string.parameters_title), style = MaterialTheme.typography.titleMedium) - - Column { - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth() - ) { - Column(modifier = Modifier.weight(1f)) { - Text(stringResource(R.string.threads_format, threads.roundToInt()), style = MaterialTheme.typography.bodyMedium) - Text( - stringResource(R.string.threads_recommendation), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant + // --- Подключение: адреса сервера/звонка/локальный --- + SectionLabel(stringResource(R.string.connection_title)) + SettingsCard { + SettingsFieldSlot { + OutlinedTextField( + value = serverAddress.redact(privacyMode), + onValueChange = { if (!privacyMode) serverAddress = it }, + label = { Text(stringResource(R.string.server_address_label)) }, + placeholder = { Text(stringResource(R.string.server_address_placeholder)) }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + readOnly = privacyMode, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri), + supportingText = { Text(stringResource(R.string.server_address_support)) } + ) + } + if (saved.provider == Provider.VK) { + SettingsRowDivider() + SettingsFieldSlot { + OutlinedTextField( + value = vkLink.redact(privacyMode), + onValueChange = { if (!privacyMode) vkLink = it }, + label = { Text(stringResource(R.string.call_link_label)) }, + placeholder = { Text(stringResource(R.string.call_link_placeholder)) }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + readOnly = privacyMode, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri), + supportingText = { Text(stringResource(R.string.call_link_support)) } ) } } - Slider( - value = threads, - onValueChange = { - val newInt = it.roundToInt() - if (newInt != lastSliderInt) { - HapticUtil.perform(context, HapticUtil.Pattern.SELECTION) - lastSliderInt = newInt - } - threads = it - }, - valueRange = 1f..128f, - steps = 0, - modifier = Modifier.fillMaxWidth() - ) - } - - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - Text( - stringResource(R.string.streams_per_cred_format, streamsPerCred.roundToInt()), - style = MaterialTheme.typography.bodyMedium - ) - Text( - stringResource(R.string.streams_per_cred_recommendation), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - Slider( - value = streamsPerCred, - onValueChange = { - val v = it.roundToInt() - if (v != lastStreamsInt) { - HapticUtil.perform(context, HapticUtil.Pattern.SELECTION) - lastStreamsInt = v - } - streamsPerCred = it - }, - valueRange = 1f..50f, - steps = 0, - modifier = Modifier.fillMaxWidth() - ) - } - - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - Column { - Text(stringResource(R.string.dns_mode_title), style = MaterialTheme.typography.bodyMedium) - Text( - stringResource(R.string.dns_mode_desc), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant + SettingsRowDivider() + SettingsFieldSlot { + OutlinedTextField( + value = localPort.redact(privacyMode), + onValueChange = { if (!privacyMode) localPort = it }, + label = { Text(stringResource(R.string.local_listen_address)) }, + placeholder = { Text(stringResource(R.string.local_listen_placeholder)) }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + readOnly = privacyMode, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri), + supportingText = { Text(stringResource(R.string.local_listen_support)) } ) } - val dnsOptions = listOf( - DnsMode.AUTO to stringResource(R.string.dns_mode_auto), - DnsMode.PLAIN to stringResource(R.string.dns_mode_udp), - DnsMode.DOH to stringResource(R.string.dns_mode_doh) + } + + // --- Производительность: потоки и потоки-на-аккаунт --- + SectionLabel(stringResource(R.string.client_section_performance)) + SettingsCard { + SettingsFieldSlot { + SliderRow( + valueLabel = stringResource(R.string.threads_format, threads.roundToInt()), + hint = stringResource(R.string.threads_recommendation), + value = threads, + valueRange = 1f..128f, + onValueChange = { threads = it }, + context = context + ) + } + SettingsRowDivider() + SettingsFieldSlot { + SliderRow( + valueLabel = stringResource(R.string.streams_per_cred_format, streamsPerCred.roundToInt()), + hint = stringResource(R.string.streams_per_cred_recommendation), + value = streamsPerCred, + valueRange = 1f..50f, + onValueChange = { streamsPerCred = it }, + context = context + ) + } + } + + // --- DNS: режим резолвера, ручной список, DNS оператора --- + SectionLabel(stringResource(R.string.client_section_dns)) + // Ручной DNS. UI и движок (ProxyService) нормализуют ввод одним DnsList: + // свитч оператора гасится только когда ручной список РЕАЛЬНО применится, + // невалидные токены подсвечиваются isError — поле не врёт про приоритет. + val dnsEffective = DnsList.normalize(customDns) + val dnsHasInvalid = DnsList.hasInvalidTokens(customDns) + SettingsCard { + SettingsFieldSlot { + SettingsControlLabel( + title = stringResource(R.string.dns_mode_title), + desc = stringResource(R.string.dns_mode_desc) + ) + val dnsOptions = listOf( + DnsMode.AUTO to stringResource(R.string.dns_mode_auto), + DnsMode.PLAIN to stringResource(R.string.dns_mode_udp), + DnsMode.DOH to stringResource(R.string.dns_mode_doh) + ) + SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { + dnsOptions.forEachIndexed { idx, (value, label) -> + SegmentedButton( + selected = saved.dnsMode == value, + onClick = { + HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON) + clientEdit { it.copy(dnsMode = value) } + }, + shape = SegmentedButtonDefaults.itemShape(index = idx, count = dnsOptions.size) + ) { Text(label) } + } + } + } + SettingsRowDivider() + SettingsFieldSlot { + OutlinedTextField( + value = customDns, + onValueChange = { customDns = it }, + label = { Text(stringResource(R.string.dns_custom_label)) }, + placeholder = { Text("8.8.8.8, 1.1.1.1") }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + isError = dnsHasInvalid, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Ascii), + supportingText = { + Text(stringResource( + if (dnsHasInvalid) R.string.dns_custom_invalid else R.string.dns_custom_hint + )) + } + ) + } + SettingsRowDivider() + // DNS оператора — ниже ручного ввода, т.к. ручной список имеет приоритет + // (см. ProxyService). При действующем ручном списке гасим свитч, чтобы + // не вводить в заблуждение «включён, но не действует». + SettingsSwitchRow( + title = stringResource(R.string.use_carrier_dns), + subtitle = if (dnsEffective.isEmpty()) stringResource(R.string.use_carrier_dns_desc) + else stringResource(R.string.use_carrier_dns_overridden), + checked = saved.useCarrierDns, + enabled = dnsEffective.isEmpty(), + onCheckedChange = { v -> clientEdit { it.copy(useCarrierDns = v) } } ) - SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { - dnsOptions.forEachIndexed { idx, (value, label) -> + } + + // --- Дополнительно: транспорт TURN + флаги --- + SectionLabel(stringResource(R.string.client_section_advanced)) + // TURN-транспорт (-transport tcp|udp) ортогонален режиму туннеля. + SettingsCard { + SettingsFieldSlot { + SettingsControlLabel( + title = stringResource(R.string.transport_protocol), + desc = stringResource(R.string.transport_protocol_desc) + ) + SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { SegmentedButton( - selected = saved.dnsMode == value, + selected = !saved.useUdp, onClick = { HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON) - clientEdit { it.copy(dnsMode = value) } + clientEdit { it.copy(useUdp = false) } }, - shape = SegmentedButtonDefaults.itemShape(index = idx, count = dnsOptions.size) - ) { Text(label) } + shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2) + ) { Text(stringResource(R.string.tcp)) } + SegmentedButton( + selected = saved.useUdp, + onClick = { + HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON) + clientEdit { it.copy(useUdp = true) } + }, + shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2) + ) { Text(stringResource(R.string.udp)) } } } } - // TURN-транспорт (-transport tcp|udp) ортогонален режиму туннеля. - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - Column { - Text(stringResource(R.string.transport_protocol), style = MaterialTheme.typography.bodyMedium) - Text( - stringResource(R.string.transport_protocol_desc), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant + // Капча + Bond — сегментированная группа свитчей. + // Bond — client-only флаг (сервер детектит сам), только в TCP-режиме. + val toggleCount = if (effectiveTcpForward) 2 else 1 + SettingsGroup { + SettingsGroupItem(0, toggleCount) { + SettingsSwitchRow( + title = stringResource(R.string.manual_captcha), + subtitle = stringResource(R.string.manual_captcha_desc), + checked = saved.manualCaptcha, + onCheckedChange = { v -> clientEdit { it.copy(manualCaptcha = v) } } ) } - SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { - SegmentedButton( - selected = !saved.useUdp, - onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON) - clientEdit { it.copy(useUdp = false) } - }, - shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2) - ) { Text(stringResource(R.string.tcp)) } - SegmentedButton( - selected = saved.useUdp, - onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON) - clientEdit { it.copy(useUdp = true) } - }, - shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2) - ) { Text(stringResource(R.string.udp)) } - } - } - - - - SwitchRow( - label = stringResource(R.string.manual_captcha), - description = stringResource(R.string.manual_captcha_desc), - checked = saved.manualCaptcha, - onCheckedChange = { v -> - HapticUtil.perform(context, if (v) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF) - clientEdit { it.copy(manualCaptcha = v) } - } - ) - - SwitchRow( - label = stringResource(R.string.use_carrier_dns), - description = stringResource(R.string.use_carrier_dns_desc), - checked = saved.useCarrierDns, - onCheckedChange = { v -> - HapticUtil.perform(context, if (v) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF) - clientEdit { it.copy(useCarrierDns = v) } - } - ) - - SwitchRow( - label = stringResource(R.string.debug_mode), - description = stringResource(R.string.debug_mode_desc), - checked = saved.debugMode, - onCheckedChange = { v -> - HapticUtil.perform(context, if (v) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF) - clientEdit { it.copy(debugMode = v) } - } - ) - - SwitchRow( - label = stringResource(R.string.magic_switch), - description = stringResource(R.string.magic_switch_desc), - checked = saved.magicSwitch, - onCheckedChange = { v -> - HapticUtil.perform(context, if (v) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF) - clientEdit { it.copy(magicSwitch = v) } - } - ) - - if (saved.magicSwitch) { - OutlinedTextField( - value = magicTurn.redact(privacyMode), - onValueChange = { if (!privacyMode) magicTurn = it }, - label = { Text(stringResource(R.string.magic_switch_address_label)) }, - placeholder = { Text(stringResource(R.string.magic_switch_address_placeholder)) }, - modifier = Modifier.fillMaxWidth(), - singleLine = true, - readOnly = privacyMode, - supportingText = { Text(stringResource(R.string.magic_switch_address_support)) } - ) - } - - // Bond — client-only флаг (сервер детектит сам). SSH не нужен; - // показываем только в TCP-форвард режиме. - if (effectiveTcpForward) { - SwitchRow( - label = stringResource(R.string.client_bond), - description = stringResource(R.string.client_bond_desc), - checked = saved.bond, - onCheckedChange = { v -> - HapticUtil.perform(context, if (v) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF) - // bond триггерит рестарт прокси только у активного; иначе пишем данные. - if (isActive) settingsViewModel.setBond(v) else clientEdit { it.copy(bond = v) } + if (effectiveTcpForward) { + SettingsGroupItem(1, toggleCount) { + SettingsSwitchRow( + title = stringResource(R.string.client_bond), + subtitle = stringResource(R.string.client_bond_desc), + checked = saved.bond, + // bond триггерит рестарт прокси только у активного; иначе пишем данные. + onCheckedChange = { v -> + if (isActive) settingsViewModel.setBond(v) else clientEdit { it.copy(bond = v) } + } + ) } - ) + } } - HorizontalDivider(Modifier, DividerDefaults.Thickness, DividerDefaults.color) - - // Режим подключения (Proxy/VPN) и WireGuard-конфиг вынесены в отдельный - // экран «Режим подключения» (ConnectionModeScreen). Здесь — клиентские - // параметры ядра и тоггл логов. - - SwitchRow( - label = stringResource(R.string.logs_enabled), - description = stringResource(R.string.logs_enabled_desc), - checked = saved.logsEnabled, - onCheckedChange = { v -> - HapticUtil.perform(context, if (v) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF) - clientEdit { it.copy(logsEnabled = v) } + // Альтернативный TURN-узел — свитч + адрес (раскрывается при включении). + SettingsCard { + SettingsSwitchRow( + title = stringResource(R.string.magic_switch), + subtitle = stringResource(R.string.magic_switch_desc), + checked = saved.magicSwitch, + onCheckedChange = { v -> clientEdit { it.copy(magicSwitch = v) } } + ) + if (saved.magicSwitch) { + SettingsRowDivider() + SettingsFieldSlot { + OutlinedTextField( + value = magicTurn.redact(privacyMode), + onValueChange = { if (!privacyMode) magicTurn = it }, + label = { Text(stringResource(R.string.magic_switch_address_label)) }, + placeholder = { Text(stringResource(R.string.magic_switch_address_placeholder)) }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + readOnly = privacyMode, + supportingText = { Text(stringResource(R.string.magic_switch_address_support)) } + ) + } } - ) + } - - // Кнопка «Завершить» — только в онбординг-флоу + // Кнопка «Завершить» — только в онбординг-флоу. if (showFinishButton && onFinish != null) { Spacer(Modifier.height(8.dp)) Button( @@ -451,33 +432,32 @@ fun ClientSetupScreen( } } +/** + * Ползунок с подписью-значением и пояснением. Хаптик щёлкает на каждое целочисленное + * деление (а не на каждый float-кадр) — состояние держится локально внутри строки. + */ @Composable -internal fun SwitchRow( - label: String, - description: String, - checked: Boolean, - enabled: Boolean = true, - onCheckedChange: (Boolean) -> Unit +private fun SliderRow( + valueLabel: String, + hint: String, + value: Float, + valueRange: ClosedFloatingPointRange, + onValueChange: (Float) -> Unit, + context: android.content.Context ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, + var lastInt by remember { mutableIntStateOf(value.roundToInt()) } + SettingsControlLabel(title = valueLabel, desc = hint) + Slider( + value = value, + onValueChange = { + val newInt = it.roundToInt() + if (newInt != lastInt) { + HapticUtil.perform(context, HapticUtil.Pattern.SELECTION) + lastInt = newInt + } + onValueChange(it) + }, + valueRange = valueRange, modifier = Modifier.fillMaxWidth() - ) { - Column(modifier = Modifier.weight(1f)) { - Text( - label, - style = MaterialTheme.typography.bodyMedium, - color = if (enabled) MaterialTheme.colorScheme.onSurface - else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f) - ) - Text( - description, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - Switch(checked = checked, enabled = enabled, onCheckedChange = onCheckedChange) - } + ) } - diff --git a/app/src/main/java/com/freeturn/app/ui/screens/ConnectionModeScreen.kt b/app/src/main/java/com/freeturn/app/ui/screens/ConnectionModeScreen.kt index 003bc1a..3912116 100644 --- a/app/src/main/java/com/freeturn/app/ui/screens/ConnectionModeScreen.kt +++ b/app/src/main/java/com/freeturn/app/ui/screens/ConnectionModeScreen.kt @@ -1,4 +1,7 @@ -@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) +@file:OptIn( + androidx.compose.material3.ExperimentalMaterial3Api::class, + androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class +) package com.freeturn.app.ui.screens @@ -19,6 +22,7 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Icon import androidx.compose.material3.IconButton +import androidx.compose.material3.LargeFlexibleTopAppBar import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold @@ -26,7 +30,7 @@ import androidx.compose.material3.SegmentedButton import androidx.compose.material3.SegmentedButtonDefaults import androidx.compose.material3.SingleChoiceSegmentedButtonRow import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect @@ -39,6 +43,7 @@ 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.input.nestedscroll.nestedScroll import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource @@ -152,9 +157,11 @@ fun ConnectionModeScreen( } } + val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior() Scaffold( + modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { - TopAppBar( + LargeFlexibleTopAppBar( title = { Text(stringResource(R.string.connection_mode_title)) }, navigationIcon = { if (onBack != null) { @@ -165,7 +172,8 @@ fun ConnectionModeScreen( ) } } - } + }, + scrollBehavior = scrollBehavior ) }, // Всегда внутри NavigationSuite — нижний бар держит навбар-инсет сам. @@ -183,11 +191,9 @@ fun ConnectionModeScreen( modifier = Modifier .widthIn(max = SettingsContentMaxWidth) .fillMaxWidth() - .padding(horizontal = 24.dp), + .padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(16.dp) ) { - Spacer(Modifier.height(4.dp)) - SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { SegmentedButton( selected = !isVpn, diff --git a/app/src/main/java/com/freeturn/app/ui/screens/ServerManagementScreen.kt b/app/src/main/java/com/freeturn/app/ui/screens/ServerManagementScreen.kt index 1a0ad2b..573f5f0 100644 --- a/app/src/main/java/com/freeturn/app/ui/screens/ServerManagementScreen.kt +++ b/app/src/main/java/com/freeturn/app/ui/screens/ServerManagementScreen.kt @@ -1,32 +1,31 @@ -@file:OptIn(androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class) +@file:OptIn( + androidx.compose.material3.ExperimentalMaterial3Api::class, + androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class +) package com.freeturn.app.ui.screens -import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut +import androidx.compose.animation.scaleIn +import androidx.compose.animation.scaleOut import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.ui.res.painterResource @@ -34,18 +33,14 @@ import androidx.compose.ui.res.stringResource import com.freeturn.app.R import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults import androidx.compose.material3.CircularWavyProgressIndicator -import androidx.compose.material3.DividerDefaults import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExtendedFloatingActionButton import androidx.compose.material3.FilledTonalButton -import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton -import androidx.compose.material3.LinearWavyProgressIndicator +import androidx.compose.material3.LargeFlexibleTopAppBar import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField @@ -55,9 +50,9 @@ import androidx.compose.material3.SegmentedButtonDefaults import androidx.compose.material3.SingleChoiceSegmentedButtonRow import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -70,10 +65,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.semantics.heading -import androidx.compose.ui.semantics.semantics import kotlinx.coroutines.delay -import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.ui.text.input.KeyboardType @@ -81,12 +73,18 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.freeturn.app.data.ObfProfile import com.freeturn.app.ui.HapticUtil +import com.freeturn.app.ui.components.SectionLabel +import com.freeturn.app.ui.components.SettingsCard +import com.freeturn.app.ui.components.SettingsContentMaxWidth +import com.freeturn.app.ui.components.SettingsControlLabel +import com.freeturn.app.ui.components.SettingsFieldSlot +import com.freeturn.app.ui.components.SettingsRowDivider import com.freeturn.app.viewmodel.ServerState import com.freeturn.app.viewmodel.SshConnectionState import com.freeturn.app.viewmodel.ServerViewModel import com.freeturn.app.viewmodel.SettingsViewModel +import com.freeturn.app.viewmodel.serverSettingsAvailable -@OptIn(ExperimentalMaterial3Api::class) @Composable fun ServerManagementScreen( serverViewModel: ServerViewModel, @@ -114,22 +112,25 @@ fun ServerManagementScreen( val legacyConnect by settingsViewModel.proxyConnect.collectAsStateWithLifecycle() val savedListen = profile?.proxyListen ?: legacyListen val savedConnect = profile?.proxyConnect ?: legacyConnect - val sshLog by serverViewModel.sshLog.collectAsStateWithLifecycle() val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle() val clientCfg by settingsViewModel.clientConfig.collectAsStateWithLifecycle() - val serverLogs by serverViewModel.serverLogs.collectAsStateWithLifecycle() val serverOpts by serverViewModel.serverOpts.collectAsStateWithLifecycle() val isRegen by serverViewModel.isRegeneratingObfKey.collectAsStateWithLifecycle() + // Источник серверных черновиков: активный профиль рулит ЖИВЫМ конфигом (legacy/global — + // его обновляет regen на сервере), неактивный — снимком профиля by-id (sync OFF, клиент-локально). + val effClient = if (isActive) clientCfg else (profile?.client ?: clientCfg) + val effServer = if (isActive) serverOpts else (profile?.server ?: serverOpts) + // --- Черновики конфигурации (без авто-сохранения) --- var proxyListenIp by rememberSaveable(savedListen) { mutableStateOf(savedListen.substringBeforeLast(":", "0.0.0.0").ifBlank { "0.0.0.0" }) } var proxyListenPort by rememberSaveable(savedListen) { mutableStateOf(savedListen.substringAfterLast(":", "56000")) } var proxyConnect by rememberSaveable(savedConnect) { mutableStateOf(savedConnect) } - var tcpDraft by rememberSaveable(clientCfg.tcpForward) { mutableStateOf(clientCfg.tcpForward) } - var obfDraft by rememberSaveable(serverOpts.obfProfile) { mutableStateOf(serverOpts.obfProfile) } - var keyDraft by rememberSaveable(serverOpts.obfKey) { mutableStateOf(serverOpts.obfKey) } + var tcpDraft by rememberSaveable(effClient.tcpForward) { mutableStateOf(effClient.tcpForward) } + var obfDraft by rememberSaveable(effServer.obfProfile) { mutableStateOf(effServer.obfProfile) } + var keyDraft by rememberSaveable(effServer.obfKey) { mutableStateOf(effServer.obfKey) } // SSH-сессию держит хаб (ServerDetailScreen): этот экран в settings-флоу открыт только // при активном подключении, в онбординг сюда приходят уже Connected. Свой реконнект @@ -138,40 +139,50 @@ fun ServerManagementScreen( val context = LocalContext.current val snackbarHostState = remember { SnackbarHostState() } var showServerMenu by rememberSaveable { mutableStateOf(false) } - val isConnected = sshState is SshConnectionState.Connected - // Дебаунс карточки сопряжения: при открытии config грузится из DataStore async, - // а sshState стартует Disconnected — без задержки карточка мигает на доли секунды - // до прихода Connected. Ошибку показываем сразу (уже устаканившееся состояние). - var pairingPromptVisible by remember { mutableStateOf(false) } - LaunchedEffect(isConnected) { - if (isConnected) { - pairingPromptVisible = false - } else { - delay(400) - pairingPromptVisible = true - } - } - val showPairing = sshState is SshConnectionState.Error || pairingPromptVisible + // «Подключено» = ЖИВОЙ SSH ЭТОГО профиля. Живая сессия принадлежит активному серверу, + // поэтому для неактивного профиля всегда false (иначе чужой коннект протёк бы сюда). + val isConnected = isActive && sshState is SshConnectionState.Connected + val syncOn = effClient.syncServerSwitches val isWorking = serverState is ServerState.Working || serverState is ServerState.Checking val serverKnown = serverState as? ServerState.Known - val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() + val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior() // --- Dirty-детект для apply-модели --- - val obfKeyRegex = remember { Regex("^[0-9a-fA-F]{64}$") } val listenFull = "${proxyListenIp.ifBlank { "0.0.0.0" }}:$proxyListenPort" val proxyDirty = listenFull != savedListen || proxyConnect != savedConnect val configDirty = settingsFlow && (proxyDirty || - tcpDraft != clientCfg.tcpForward || - obfDraft != serverOpts.obfProfile || - keyDraft != serverOpts.obfKey) - // Ключ валиден для применения: обфускация выкл, ИЛИ пусто (сервер сгенерит), ИЛИ 64 hex. - val keyOkForApply = obfDraft == ObfProfile.NONE || keyDraft.isBlank() || keyDraft.matches(obfKeyRegex) + tcpDraft != effClient.tcpForward || + obfDraft != effServer.obfProfile || + keyDraft != effServer.obfKey) + // Ключ валиден для применения: обфускация выкл, 64 hex, либо пусто при живом SSH + // и sync ON — только тогда applyServerConfig сгенерит ключ на сервере. Иначе пустой + // ключ блокирует apply: в конфиг уехала бы обфускация без ключа, которую CoreArgs + // молча отбросит при запуске клиента. + val keyOkForApply = obfDraft == ObfProfile.NONE || ObfProfile.isValidKey(keyDraft) || + (keyDraft.isBlank() && isConnected && syncOn) + // Плавающий «Применить» виден только когда есть что применять: фиксирует весь черновик + // одним рестартом и уходит назад в хаб. Невалидный/занятый стейт — FAB просто прячется + // (поле obf-ключа само подсвечивает ошибку), действие появляется когда оно осмысленно. + val canApply = settingsFlow && serverSettingsAvailable(isConnected, syncOn) && + configDirty && keyOkForApply && !isWorking + fun applyConfig() { + HapticUtil.perform(context, HapticUtil.Pattern.CLICK) + // Активный — apply в живой рантайм (один рестарт). Неактивный — пишем только снимок профиля. + if (isActive) { + settingsViewModel.applyServerConfig(listenFull, proxyConnect, tcpDraft, obfDraft, keyDraft) + } else { + profileId?.let { + settingsViewModel.applyProfileServerConfig(it, listenFull, proxyConnect, tcpDraft, obfDraft, keyDraft) + } + } + onBack?.invoke() + } Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { - TopAppBar( + LargeFlexibleTopAppBar( title = { Text(stringResource( if (onBack != null) R.string.provider_server_settings else R.string.server @@ -189,8 +200,7 @@ fun ServerManagementScreen( }, scrollBehavior = scrollBehavior, actions = { - // App bar разгружен: SSH-статус живёт в карточке статуса ниже, смена - // сервера спрятана в overflow ⋮ — заголовок остаётся в одну строку. + // Смена сервера спрятана в overflow ⋮ — заголовок остаётся чистым. if (isActive && onEditConnection != null) { Box { IconButton(onClick = { showServerMenu = true }) { @@ -221,6 +231,19 @@ fun ServerManagementScreen( ) }, snackbarHost = { SnackbarHost(snackbarHostState) }, + floatingActionButton = { + AnimatedVisibility( + visible = canApply, + enter = scaleIn() + fadeIn(), + exit = scaleOut() + fadeOut() + ) { + ExtendedFloatingActionButton( + onClick = { applyConfig() }, + icon = { Icon(painterResource(R.drawable.check_circle_24px), contentDescription = null) }, + text = { Text(stringResource(R.string.server_apply)) } + ) + } + }, // Settings-флоу (onBack != null) — внутри NavigationSuite, бар держит навбар-инсет. // Онбординг (onBack == null) — полноэкранный, инсет держим сами. contentWindowInsets = if (onBack != null) WindowInsets(0, 0, 0, 0) else WindowInsets.navigationBars @@ -235,18 +258,21 @@ fun ServerManagementScreen( ) { Column( modifier = Modifier - .widthIn(max = 840.dp) + .widthIn(max = SettingsContentMaxWidth) .fillMaxWidth() - .padding(horizontal = 24.dp), + .padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(16.dp) ) { - Spacer(Modifier.height(4.dp)) - - // Неактивный профиль: живая SSH-сессия и управление ядром недоступны. - // Предлагаем сделать активным — после этого SSH/управление оживают. - if (!isActive) { - InactiveServerCard( - onMakeActive = { + // Неактивный профиль + sync ON: серверные правки нужно пушить на сервер, а + // живая SSH-сессия принадлежит активному. Предлагаем сделать активным. + // При sync OFF настройки клиент-локальны — редактируем снимок профиля ниже. + if (!isActive && syncOn) { + HeroCard( + iconRes = R.drawable.host_24px, + title = stringResource(R.string.server_inactive_title), + desc = stringResource(R.string.server_inactive_desc), + actionLabel = stringResource(R.string.make_active), + onAction = { HapticUtil.perform(context, HapticUtil.Pattern.CLICK) profileId?.let { settingsViewModel.applyProfile(it) } } @@ -255,528 +281,327 @@ fun ServerManagementScreen( return@Column } - // Settings-флоу без активного сопряжения → приглашение/прогресс/ошибка - // вместо бесполезных задизейбленных контролов. В онбординге сюда приходят - // уже Connected, поэтому ветка management как раньше. - if (settingsFlow && !isConnected) { - // showPairing дебаунсит первичный показ — пустой экран до 400мс - // вместо мигающей карточки при загрузке config / авто-сопряжении. - if (showPairing) { - SshPairingPrompt( - state = sshState, - configBlank = sshConfig.ip.isBlank(), - onConnect = { onEditConnection?.invoke() }, - onRetry = { serverViewModel.reconnectSsh() } + // SSH-сессия не активна (упала или ещё поднимается): конфиг и действия + // требуют живого подключения, без карточки экран остаётся пустым. + // Исключение — settings-флоу с sync OFF: серверные настройки клиент-локальны, + // показываем их ниже как обычно. 400мс дебаунс гасит мигание на холодном + // заходе (config грузится async); ошибка — устоявшееся состояние, сразу. + var lostVisible by remember { mutableStateOf(false) } + LaunchedEffect(isConnected) { + if (isConnected) lostVisible = false else { delay(400); lostVisible = true } + } + if (!isConnected && (syncOn || !settingsFlow)) { + if (sshState is SshConnectionState.Error || lostVisible) { + val isErr = sshState is SshConnectionState.Error + HeroCard( + iconRes = if (isErr) R.drawable.error_24px else R.drawable.host_24px, + iconTint = if (isErr) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary, + title = stringResource(R.string.server_connection_lost_title), + desc = stringResource(R.string.server_connection_lost_desc), + descTint = if (isErr) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + actionLabel = stringResource(R.string.reconnect), + onAction = { + HapticUtil.perform(context, HapticUtil.Pattern.CLICK) + serverViewModel.reconnectSsh() + } ) - Spacer(Modifier.height(24.dp)) } + Spacer(Modifier.height(24.dp)) return@Column } AnimatedVisibility( - visible = !clientCfg.syncServerSwitches, + visible = !syncOn, enter = fadeIn() + expandVertically(), exit = fadeOut() + shrinkVertically() ) { - Card( - modifier = Modifier.fillMaxWidth(), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.errorContainer - ) + Surface( + shape = MaterialTheme.shapes.large, + color = MaterialTheme.colorScheme.errorContainer, + modifier = Modifier.fillMaxWidth() ) { Text( stringResource(R.string.sync_off_banner), - style = MaterialTheme.typography.bodySmall, + style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onErrorContainer, modifier = Modifier.padding(16.dp) ) } } - // Статус сервера теперь в хабе (ServerDetailScreen.ServerStatusCard) — - // тут не дублируем. На этом экране — конфиг (apply-модель) + действия. - - // Server config - Text( - stringResource(R.string.server_config), - style = MaterialTheme.typography.titleMedium, - modifier = Modifier.semantics { heading() } - ) - - OutlinedTextField( - value = proxyListenIp, - onValueChange = { v -> proxyListenIp = v.filter { c -> c.isDigit() || c == '.' || c == ':' } }, - label = { Text(stringResource(R.string.listen_ip)) }, - placeholder = { Text(stringResource(R.string.listen_ip_placeholder)) }, - modifier = Modifier.fillMaxWidth(), - singleLine = true, - supportingText = { Text(stringResource(R.string.listen_ip_desc)) } - ) - - OutlinedTextField( - value = proxyListenPort, - onValueChange = { proxyListenPort = it.filter { c -> c.isDigit() } }, - label = { Text(stringResource(R.string.listen_port)) }, - placeholder = { Text(stringResource(R.string.listen_port_placeholder)) }, - modifier = Modifier.fillMaxWidth(), - singleLine = true, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), - supportingText = { Text(stringResource(R.string.listen_port_desc)) } - ) - - OutlinedTextField( - value = proxyConnect, - onValueChange = { proxyConnect = it }, - label = { Text(stringResource(R.string.turn_client_address)) }, - placeholder = { Text(stringResource(R.string.turn_client_placeholder)) }, - modifier = Modifier.fillMaxWidth(), - singleLine = true, - supportingText = { Text(stringResource(R.string.turn_client_desc)) } - ) - - // --- Синхронные настройки сервера (apply-модель, только settings-флоу) --- - if (settingsFlow) { - HorizontalDivider(Modifier, DividerDefaults.Thickness, DividerDefaults.color) - - Text( - stringResource(R.string.server_sync_section), - style = MaterialTheme.typography.titleMedium, - modifier = Modifier.semantics { heading() } - ) - - // Проброс: UDP / TCP. - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - Text(stringResource(R.string.tcp_forward_mode), style = MaterialTheme.typography.bodyMedium) - SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { - SegmentedButton( - selected = !tcpDraft, - onClick = { HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON); tcpDraft = false }, - shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2) - ) { Text(stringResource(R.string.udp)) } - SegmentedButton( - selected = tcpDraft, - onClick = { HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON); tcpDraft = true }, - shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2) - ) { Text(stringResource(R.string.tcp)) } - } - } - - // Профиль обфускации. - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - Text(stringResource(R.string.obf_profile_title), style = MaterialTheme.typography.bodyMedium) - SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { - ObfProfile.ALL.forEachIndexed { idx, value -> - SegmentedButton( - selected = obfDraft == value, - onClick = { HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON); obfDraft = value }, - shape = SegmentedButtonDefaults.itemShape(index = idx, count = ObfProfile.ALL.size) - ) { Text(obfProfileLabel(value)) } - } - } - } - - // obf-ключ (черновик) + регенерация на сервере (живая SSH-операция). - if (obfDraft != ObfProfile.NONE) { - OutlinedTextField( - value = if (privacyMode) serverOpts.obfKey.redact(true) else keyDraft, - onValueChange = { if (!privacyMode) keyDraft = it }, - label = { Text(stringResource(R.string.server_obf_key_label)) }, - modifier = Modifier.fillMaxWidth(), - readOnly = privacyMode, - singleLine = true, - isError = keyDraft.isNotBlank() && !keyDraft.matches(obfKeyRegex), - trailingIcon = { - if (serverOpts.obfKey.isNotBlank() && !privacyMode) { - IconButton(onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - val cm = context.getSystemService(android.content.ClipboardManager::class.java) - cm?.setPrimaryClip(android.content.ClipData.newPlainText("obf-key", serverOpts.obfKey)) - }) { - Icon( - painterResource(R.drawable.content_copy_24px), - contentDescription = stringResource(R.string.copy) - ) - } - } - }, - supportingText = { - when { - keyDraft.isBlank() -> Text(stringResource(R.string.obf_key_empty_hint)) - !keyDraft.matches(obfKeyRegex) -> Text( - stringResource(R.string.obf_key_invalid_hint), - color = MaterialTheme.colorScheme.error - ) - } - } - ) - if (isConnected && !privacyMode) { - TextButton( - onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - serverViewModel.regenerateObfKey() - }, - enabled = !isRegen, - modifier = Modifier.fillMaxWidth() - ) { - if (isRegen) { - CircularWavyProgressIndicator(modifier = Modifier.size(20.dp)) - Spacer(Modifier.width(8.dp)) - Text(stringResource(R.string.obf_key_regen_in_progress)) - } else { - Text(stringResource(R.string.obf_key_regen)) - } - } - } - } - - // Применить — фиксирует весь черновик одним рестартом, затем назад в хаб. - Button( - onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - settingsViewModel.applyServerConfig(listenFull, proxyConnect, tcpDraft, obfDraft, keyDraft) - onBack?.invoke() - }, - enabled = configDirty && keyOkForApply && !isWorking, - modifier = Modifier.fillMaxWidth(), - shape = MaterialTheme.shapes.large - ) { - Icon(painterResource(R.drawable.check_circle_24px), null) - Spacer(Modifier.width(8.dp)) - Text(stringResource(R.string.server_apply)) - } - Text( - stringResource(R.string.server_apply_restart_note), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - - HorizontalDivider(Modifier, DividerDefaults.Thickness, DividerDefaults.color) - } - - - // Action buttons - FilledTonalButton( - onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - settingsViewModel.saveProxyServerConfig("${proxyListenIp.ifBlank { "0.0.0.0" }}:$proxyListenPort", proxyConnect) - serverViewModel.installServer() - }, - enabled = isConnected && !isWorking, - modifier = Modifier.fillMaxWidth(), - shape = MaterialTheme.shapes.large - ) { - Icon(painterResource(R.drawable.cloud_download_24px), null) - Spacer(Modifier.width(8.dp)) - Text(stringResource(R.string.install)) - } - - Button( - onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - settingsViewModel.saveProxyServerConfig("${proxyListenIp.ifBlank { "0.0.0.0" }}:$proxyListenPort", proxyConnect) - serverViewModel.startServer() - }, - enabled = (isConnected && !isWorking - && serverKnown?.installed == true) && !serverKnown.running, - modifier = Modifier.fillMaxWidth(), - shape = MaterialTheme.shapes.large - ) { - Icon(painterResource(R.drawable.play_arrow_24px), null) - Spacer(Modifier.width(8.dp)) - Text(stringResource(R.string.start_server)) - } - - OutlinedButton( - onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - serverViewModel.stopServer() - }, - enabled = isConnected && !isWorking && serverKnown?.running == true, - modifier = Modifier.fillMaxWidth(), - shape = MaterialTheme.shapes.large, - colors = ButtonDefaults.outlinedButtonColors( - contentColor = MaterialTheme.colorScheme.error - ) - ) { - Icon(painterResource(R.drawable.stop_24px), null) - Spacer(Modifier.width(8.dp)) - Text(stringResource(R.string.stop_server)) - } - - // «Продолжить к настройке клиента» — шаг мастера онбординга (onBack == null). - // В settings-флоу (onBack != null) этой кнопки нет — там провайдер уже - // даёт отдельный вход в «Настройки подключения». - if (serverKnown?.running == true && onBack == null) { - Spacer(Modifier.height(4.dp)) - Button( - onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - onContinue?.invoke() - }, - modifier = Modifier.fillMaxWidth(), - shape = MaterialTheme.shapes.large - ) { - Text(stringResource(R.string.continue_client_setup)) - Spacer(Modifier.width(8.dp)) - Icon(painterResource(R.drawable.arrow_forward_24px), null) - } - } - - // Журнал сервера (journalctl/server.log через SSH). - // Скрываем без SSH-подключения — симметрично с SSH-логом ниже. + // --- Серверный конфиг (listen/connect) — SSH-only, скрыт без подключения --- if (isConnected) { - Card(modifier = Modifier.fillMaxWidth()) { - Column(modifier = Modifier.padding(20.dp)) { - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth() - ) { - Text( - stringResource(R.string.server_journal_title), - style = MaterialTheme.typography.titleMedium, - modifier = Modifier.weight(1f) + SectionLabel(stringResource(R.string.server_config)) + SettingsCard { + SettingsFieldSlot { + OutlinedTextField( + value = proxyListenIp, + onValueChange = { v -> proxyListenIp = v.filter { c -> c.isDigit() || c == '.' || c == ':' } }, + label = { Text(stringResource(R.string.listen_ip)) }, + placeholder = { Text(stringResource(R.string.listen_ip_placeholder)) }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri), + supportingText = { Text(stringResource(R.string.listen_ip_desc)) } ) - IconButton( - onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - serverViewModel.fetchServerLogs() - }, - enabled = isConnected && serverLogs != "…" - ) { - Icon( - painter = painterResource(R.drawable.refresh_24px), - contentDescription = stringResource(R.string.server_journal_refresh) - ) - } - if (serverLogs != null) { - IconButton( - onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - serverViewModel.clearServerLogs() - }, - enabled = serverLogs != "…" - ) { - Icon( - painter = painterResource(R.drawable.delete_24px), - contentDescription = stringResource(R.string.server_journal_clear) - ) - } - } } - if (serverLogs != null) { - Spacer(Modifier.height(12.dp)) - Card( - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant - ) - ) { - val text = when (serverLogs) { - "…" -> stringResource(R.string.server_journal_loading) - "(лог пуст)" -> stringResource(R.string.server_journal_empty) - else -> serverLogs ?: "" - } - Text( - text = text, - style = MaterialTheme.typography.bodySmall.copy( - fontFamily = FontFamily.Monospace - ), - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier - .fillMaxWidth() - .heightIn(max = 400.dp) - .verticalScroll(rememberScrollState()) - .padding(10.dp) - ) - } + SettingsRowDivider() + SettingsFieldSlot { + OutlinedTextField( + value = proxyListenPort, + onValueChange = { proxyListenPort = it.filter { c -> c.isDigit() } }, + label = { Text(stringResource(R.string.listen_port)) }, + placeholder = { Text(stringResource(R.string.listen_port_placeholder)) }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + supportingText = { Text(stringResource(R.string.listen_port_desc)) } + ) + } + SettingsRowDivider() + SettingsFieldSlot { + OutlinedTextField( + value = proxyConnect, + onValueChange = { proxyConnect = it }, + label = { Text(stringResource(R.string.turn_client_address)) }, + placeholder = { Text(stringResource(R.string.turn_client_placeholder)) }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri), + supportingText = { Text(stringResource(R.string.turn_client_desc)) } + ) } } } - } - // SSH-лог (вывод всех команд) - if (sshLog.isNotEmpty()) { - Card(modifier = Modifier.fillMaxWidth()) { - Column(modifier = Modifier.padding(20.dp)) { - Text(stringResource(R.string.ssh_log_title), style = MaterialTheme.typography.titleMedium) - Spacer(Modifier.height(12.dp)) - val listState = rememberLazyListState() - LaunchedEffect(sshLog.size) { - if (sshLog.isNotEmpty()) listState.animateScrollToItem(sshLog.lastIndex) + // --- Синхронные настройки (apply-модель) --- + // Гейт общий со входом в экран (ServerDetailScreen) — serverSettingsAvailable. + if (settingsFlow && serverSettingsAvailable(isConnected, syncOn)) { + SectionLabel(stringResource(R.string.server_sync_section)) + SettingsCard { + // Проброс: UDP / TCP. + SettingsFieldSlot { + SettingsControlLabel(stringResource(R.string.tcp_forward_mode)) + SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { + SegmentedButton( + selected = !tcpDraft, + onClick = { HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON); tcpDraft = false }, + shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2) + ) { Text(stringResource(R.string.udp)) } + SegmentedButton( + selected = tcpDraft, + onClick = { HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON); tcpDraft = true }, + shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2) + ) { Text(stringResource(R.string.tcp)) } } - Card( - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceVariant - ) - ) { - LazyColumn( - state = listState, - modifier = Modifier - .fillMaxWidth() - .heightIn(max = 400.dp) - .padding(10.dp) - ) { - items(sshLog) { line -> - val isHeader = line.startsWith("===") - val isError = line.contains("ERROR", ignoreCase = true) || - line.contains("error", ignoreCase = true) || - line.contains("failed", ignoreCase = true) - Text( - text = line, - style = MaterialTheme.typography.bodySmall.copy( - fontFamily = FontFamily.Monospace - ), - color = when { - isHeader -> MaterialTheme.colorScheme.primary - isError -> MaterialTheme.colorScheme.error - else -> MaterialTheme.colorScheme.onSurfaceVariant + } + SettingsRowDivider() + // Профиль обфускации. + SettingsFieldSlot { + SettingsControlLabel(stringResource(R.string.obf_profile_title)) + SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { + ObfProfile.ALL.forEachIndexed { idx, value -> + SegmentedButton( + selected = obfDraft == value, + onClick = { HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON); obfDraft = value }, + shape = SegmentedButtonDefaults.itemShape(index = idx, count = ObfProfile.ALL.size) + ) { Text(obfProfileLabel(value)) } + } + } + } + SettingsRowDivider() + // obf-ключ (черновик) + регенерация на сервере (живая SSH-операция). + if (obfDraft != ObfProfile.NONE) { + SettingsFieldSlot { + OutlinedTextField( + value = if (privacyMode) effServer.obfKey.redact(true) else keyDraft, + onValueChange = { if (!privacyMode) keyDraft = it }, + label = { Text(stringResource(R.string.server_obf_key_label)) }, + modifier = Modifier.fillMaxWidth(), + readOnly = privacyMode, + singleLine = true, + isError = (keyDraft.isNotBlank() && !ObfProfile.isValidKey(keyDraft)) || + (keyDraft.isBlank() && !(isConnected && syncOn)), + trailingIcon = { + if (effServer.obfKey.isNotBlank() && !privacyMode) { + IconButton(onClick = { + HapticUtil.perform(context, HapticUtil.Pattern.CLICK) + val cm = context.getSystemService(android.content.ClipboardManager::class.java) + cm?.setPrimaryClip(android.content.ClipData.newPlainText("obf-key", effServer.obfKey)) + }) { + Icon( + painterResource(R.drawable.content_copy_24px), + contentDescription = stringResource(R.string.copy) + ) } - ) + } + }, + supportingText = { + when { + keyDraft.isBlank() && !isConnected -> Text( + stringResource(R.string.obf_key_manual_hint), + color = MaterialTheme.colorScheme.error + ) + keyDraft.isBlank() && !syncOn -> Text( + stringResource(R.string.obf_key_empty_hint), + color = MaterialTheme.colorScheme.error + ) + keyDraft.isBlank() -> Text(stringResource(R.string.obf_key_empty_hint)) + !ObfProfile.isValidKey(keyDraft) -> Text( + stringResource(R.string.obf_key_invalid_hint), + color = MaterialTheme.colorScheme.error + ) + } + } + ) + if (isConnected && !privacyMode) { + TextButton( + onClick = { + HapticUtil.perform(context, HapticUtil.Pattern.CLICK) + serverViewModel.regenerateObfKey() + }, + enabled = !isRegen, + modifier = Modifier.fillMaxWidth() + ) { + if (isRegen) { + CircularWavyProgressIndicator(modifier = Modifier.size(20.dp)) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.obf_key_regen_in_progress)) + } else { + Text(stringResource(R.string.obf_key_regen)) + } } } } + } else { + // obfDraft == NONE — подсказка выбрать профиль. + SettingsFieldSlot { + Text( + stringResource(R.string.obf_select_profile_hint), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + + } + + // --- SSH-only операции: Install / Start / Stop / Continue --- + // Только онбординг (onBack == null). В settings-флоу управление ядром живёт + // в меню ⋮ хаба (ServerDetailScreen) — тут оставляем лишь конфиг + журналы. + if (isConnected && onBack == null) { + FilledTonalButton( + onClick = { + HapticUtil.perform(context, HapticUtil.Pattern.CLICK) + settingsViewModel.saveProxyServerConfig("${proxyListenIp.ifBlank { "0.0.0.0" }}:$proxyListenPort", proxyConnect) + serverViewModel.installServer() + }, + enabled = !isWorking, + modifier = Modifier.fillMaxWidth(), + shape = MaterialTheme.shapes.large + ) { + Icon(painterResource(R.drawable.cloud_download_24px), null) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.install)) + } + + Button( + onClick = { + HapticUtil.perform(context, HapticUtil.Pattern.CLICK) + settingsViewModel.saveProxyServerConfig("${proxyListenIp.ifBlank { "0.0.0.0" }}:$proxyListenPort", proxyConnect) + serverViewModel.startServer() + }, + enabled = !isWorking && serverKnown?.installed == true && !serverKnown.running, + modifier = Modifier.fillMaxWidth(), + shape = MaterialTheme.shapes.large + ) { + Icon(painterResource(R.drawable.play_arrow_24px), null) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.start_server)) + } + + OutlinedButton( + onClick = { + HapticUtil.perform(context, HapticUtil.Pattern.CLICK) + serverViewModel.stopServer() + }, + enabled = !isWorking && serverKnown?.running == true, + modifier = Modifier.fillMaxWidth(), + shape = MaterialTheme.shapes.large, + colors = ButtonDefaults.outlinedButtonColors( + contentColor = MaterialTheme.colorScheme.error + ) + ) { + Icon(painterResource(R.drawable.stop_24px), null) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.stop_server)) + } + + // «Продолжить к настройке клиента» — шаг мастера онбординга. Весь блок + // уже под onBack == null, так что отдельная проверка тут не нужна. + if (serverKnown?.running == true) { + Spacer(Modifier.height(4.dp)) + Button( + onClick = { + HapticUtil.perform(context, HapticUtil.Pattern.CLICK) + onContinue?.invoke() + }, + modifier = Modifier.fillMaxWidth(), + shape = MaterialTheme.shapes.large + ) { + Text(stringResource(R.string.continue_client_setup)) + Spacer(Modifier.width(8.dp)) + Icon(painterResource(R.drawable.arrow_forward_24px), null) } } } - Spacer(Modifier.height(24.dp)) + // Клиренс под плавающую кнопку, чтобы FAB не перекрывал нижний контент. + Spacer(Modifier.height(if (canApply) 88.dp else 24.dp)) } } } } -/** Карточка для неактивного профиля: управление ядром требует активного сервера. */ -@Composable -private fun InactiveServerCard(onMakeActive: () -> Unit) { - Card(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.padding(24.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(16.dp) - ) { - Icon( - painterResource(R.drawable.host_24px), - contentDescription = null, - tint = MaterialTheme.colorScheme.primary - ) - Text( - stringResource(R.string.server_inactive_title), - style = MaterialTheme.typography.titleMedium, - textAlign = TextAlign.Center - ) - Text( - stringResource(R.string.server_inactive_desc), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - Button( - onClick = onMakeActive, - modifier = Modifier.fillMaxWidth(), - shape = MaterialTheme.shapes.large - ) { Text(stringResource(R.string.make_active)) } - } - } -} - /** - * Состояние сопряжения для основной вкладки сервера, когда соединение ещё не - * установлено: приглашение подключиться (нет конфига), прогресс (идёт авто-/ручное - * сопряжение) или ошибка с повтором. + * Hero-карточка состояния (неактивный профиль / потеря связи): тональный контейнер, + * центрированная иконка + заголовок + пояснение + основная кнопка. Один источник стиля + * для пустых/аварийных состояний экрана. */ @Composable -private fun SshPairingPrompt( - state: SshConnectionState, - configBlank: Boolean, - onConnect: () -> Unit, - onRetry: () -> Unit +private fun HeroCard( + iconRes: Int, + title: String, + desc: String, + actionLabel: String, + onAction: () -> Unit, + iconTint: androidx.compose.ui.graphics.Color = MaterialTheme.colorScheme.primary, + descTint: androidx.compose.ui.graphics.Color = MaterialTheme.colorScheme.onSurfaceVariant ) { - val context = LocalContext.current - // Disconnected с сохранённым конфигом — транзитное: авто-сопряжение вот-вот - // сработает, показываем прогресс, а не кнопку «Подключиться» (без мигания). - val connecting = state is SshConnectionState.Connecting || - (state is SshConnectionState.Disconnected && !configBlank) - // Ключ для AnimatedContent: морфим только при смене фазы, а не при каждом - // обновлении state.message внутри Error. - val phase = when { - state is SshConnectionState.Error -> "error" - connecting -> "connecting" - else -> "prompt" - } - - Card(modifier = Modifier.fillMaxWidth()) { - AnimatedContent( - targetState = phase, - label = "ssh-pairing", - modifier = Modifier.fillMaxWidth() - ) { target -> - Column( - modifier = Modifier.padding(24.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(16.dp) - ) { - when (target) { - "error" -> { - val message = (state as? SshConnectionState.Error)?.message.orEmpty() - // Иконка + текст — единый узел для TalkBack: озвучивается как ошибка. - Column( - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(16.dp), - modifier = Modifier.semantics(mergeDescendants = true) {} - ) { - Icon( - painterResource(R.drawable.error_24px), - contentDescription = null, - tint = MaterialTheme.colorScheme.error - ) - Text( - message, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center - ) - } - Button( - onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - onRetry() - }, - modifier = Modifier.fillMaxWidth(), - shape = MaterialTheme.shapes.large - ) { Text(stringResource(R.string.reconnect)) } - } - - "connecting" -> { - Text( - stringResource(R.string.ssh_connecting), - style = MaterialTheme.typography.titleMedium, - textAlign = TextAlign.Center - ) - LinearWavyProgressIndicator(modifier = Modifier.fillMaxWidth()) - } - - else -> { - Icon( - painterResource(R.drawable.host_24px), - contentDescription = null, - tint = MaterialTheme.colorScheme.primary - ) - Text( - stringResource(R.string.server_not_paired_prompt), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - Button( - onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - onConnect() - }, - modifier = Modifier.fillMaxWidth(), - shape = MaterialTheme.shapes.large - ) { Text(stringResource(R.string.connect_btn)) } - } - } - } + Surface( + shape = MaterialTheme.shapes.large, + color = MaterialTheme.colorScheme.surfaceContainerLow, + modifier = Modifier.fillMaxWidth() + ) { + Column( + modifier = Modifier.padding(24.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + Icon(painterResource(iconRes), contentDescription = null, tint = iconTint) + Text(title, style = MaterialTheme.typography.titleMedium, textAlign = TextAlign.Center) + Text( + desc, + style = MaterialTheme.typography.bodyMedium, + color = descTint, + textAlign = TextAlign.Center + ) + Button( + onClick = onAction, + modifier = Modifier.fillMaxWidth(), + shape = MaterialTheme.shapes.large + ) { Text(actionLabel) } } } } @@ -787,4 +612,3 @@ private fun obfProfileLabel(value: String): String = when (value) { ObfProfile.RTPOPUS -> stringResource(R.string.obf_rtpopus) else -> value } - diff --git a/app/src/main/java/com/freeturn/app/ui/screens/SshSetupScreen.kt b/app/src/main/java/com/freeturn/app/ui/screens/SshSetupScreen.kt index 5c1ae8b..1427da0 100644 --- a/app/src/main/java/com/freeturn/app/ui/screens/SshSetupScreen.kt +++ b/app/src/main/java/com/freeturn/app/ui/screens/SshSetupScreen.kt @@ -1,7 +1,15 @@ -@file:OptIn(androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class) +@file:OptIn( + androidx.compose.material3.ExperimentalMaterial3Api::class, + androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class +) package com.freeturn.app.ui.screens +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.scaleIn +import androidx.compose.animation.scaleOut import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -18,22 +26,20 @@ import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.Button -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExposedDropdownMenuBox +import androidx.compose.material3.ExposedDropdownMenuAnchorType import androidx.compose.material3.ExposedDropdownMenuDefaults +import androidx.compose.material3.ExtendedFloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton +import androidx.compose.material3.LargeFlexibleTopAppBar import androidx.compose.material3.LinearWavyProgressIndicator import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ExposedDropdownMenuAnchorType import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource @@ -57,18 +63,37 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.freeturn.app.data.SshConfig import com.freeturn.app.ui.HapticUtil +import com.freeturn.app.ui.components.SectionLabel +import com.freeturn.app.ui.components.SettingsCard +import com.freeturn.app.ui.components.SettingsContentMaxWidth +import com.freeturn.app.ui.components.SettingsFieldSlot +import com.freeturn.app.ui.components.SettingsRowDivider import com.freeturn.app.viewmodel.ServerViewModel import com.freeturn.app.viewmodel.SshConnectionState import com.freeturn.app.viewmodel.SettingsViewModel -@OptIn(ExperimentalMaterial3Api::class) +private const val AUTH_PASSWORD = "PASSWORD" +private const val AUTH_SSH_KEY = "SSH_KEY" + @Composable fun SshSetupScreen( serverViewModel: ServerViewModel, settingsViewModel: SettingsViewModel, onConnected: () -> Unit, - onBack: () -> Unit + onBack: () -> Unit, + // Settings-флоу: экран не профиль-скоупный (правит активный SSH). true — выходим назад, + // если все профили удалены (напр. с главного экрана), пока экран висел в стеке вкладки: + // иначе заполнение формы writes в осиротевший конфиг. В онбординге профиля ещё нет → false. + popWhenNoProfiles: Boolean = false ) { + if (popWhenNoProfiles) { + val snapshot by settingsViewModel.profilesSnapshot.collectAsStateWithLifecycle() + if (snapshot.loaded && snapshot.list.isEmpty()) { + LaunchedEffect(Unit) { onBack() } + return + } + } + val sshState by serverViewModel.sshState.collectAsStateWithLifecycle() val savedConfig by serverViewModel.sshConfig.collectAsStateWithLifecycle() @@ -79,7 +104,6 @@ fun SshSetupScreen( var authType by rememberSaveable(savedConfig.authType) { mutableStateOf(savedConfig.authType) } var sshKey by rememberSaveable(savedConfig.sshKey) { mutableStateOf(savedConfig.sshKey) } var showPassword by remember { mutableStateOf(false) } - var authDropdownExpanded by remember { mutableStateOf(false) } // Переходим только если подключение было установлено ПОСЛЕ открытия экрана. // Если sshState уже Connected при входе (пользователь хочет изменить настройки) — @@ -92,12 +116,19 @@ fun SshSetupScreen( val isConnecting = sshState is SshConnectionState.Connecting val context = LocalContext.current - val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() + val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior() + + // Форма заполнена достаточно для попытки коннекта — гейтит появление плавающей кнопки. + val formValid = ip.isNotBlank() && when (authType) { + AUTH_SSH_KEY -> sshKey.isNotBlank() + else -> password.isNotBlank() + } + val showConnectFab = !isConnecting && formValid Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { - TopAppBar( + LargeFlexibleTopAppBar( title = { Text(stringResource(R.string.connect_to_server)) }, scrollBehavior = scrollBehavior, navigationIcon = { @@ -110,38 +141,15 @@ fun SshSetupScreen( } ) }, - contentWindowInsets = WindowInsets(0, 0, 0, 0) - ) { padding -> - Column( - modifier = Modifier - .fillMaxSize() - .padding(padding) - .imePadding() - .verticalScroll(rememberScrollState()), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Column( - modifier = Modifier - .widthIn(max = 840.dp) - .fillMaxWidth() - .padding(horizontal = 24.dp), - verticalArrangement = Arrangement.spacedBy(16.dp) - ) { - Spacer(Modifier.height(4.dp)) - - if (!isConnecting) { - FormSection( - ip = ip, onIpChange = { ip = it }, - port = port, onPortChange = { port = it }, - username = username, onUsernameChange = { username = it }, - password = password, onPasswordChange = { password = it }, - showPassword = showPassword, onTogglePassword = { showPassword = !showPassword }, - authType = authType, onAuthTypeChange = { authType = it }, - sshKey = sshKey, onSshKeyChange = { sshKey = it }, - authDropdownExpanded = authDropdownExpanded, - onAuthDropdownChange = { authDropdownExpanded = it }, - sshState = sshState, - onConnect = { + floatingActionButton = { + AnimatedVisibility( + visible = showConnectFab, + enter = scaleIn() + fadeIn(), + exit = scaleOut() + fadeOut() + ) { + ExtendedFloatingActionButton( + onClick = { + HapticUtil.perform(context, HapticUtil.Pattern.CLICK) serverViewModel.connectSsh( SshConfig( ip = ip.trim(), @@ -152,20 +160,51 @@ fun SshSetupScreen( sshKey = sshKey ) ) - } + }, + icon = { Icon(painterResource(R.drawable.host_24px), contentDescription = null) }, + text = { Text(stringResource(R.string.connect_btn)) } ) - } else { - Spacer(Modifier.height(32.dp)) - ConnectionProgressCard(step = stringResource(R.string.ssh_connecting)) } + }, + contentWindowInsets = WindowInsets(0, 0, 0, 0) + ) { padding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(padding) + .imePadding() + .verticalScroll(rememberScrollState()), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Column( + modifier = Modifier + .widthIn(max = SettingsContentMaxWidth) + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + if (!isConnecting) { + FormSection( + ip = ip, onIpChange = { ip = it }, + port = port, onPortChange = { port = it.filter { c -> c.isDigit() } }, + username = username, onUsernameChange = { username = it }, + password = password, onPasswordChange = { password = it }, + showPassword = showPassword, onTogglePassword = { showPassword = !showPassword }, + authType = authType, onAuthTypeChange = { authType = it }, + sshKey = sshKey, onSshKeyChange = { sshKey = it }, + sshState = sshState + ) + } else { + ConnectionProgressCard(step = stringResource(R.string.ssh_connecting)) + } - Spacer(Modifier.height(24.dp)) - } + // Клиренс под плавающую кнопку, чтобы FAB не перекрывал нижнее поле. + Spacer(Modifier.height(if (showConnectFab) 88.dp else 24.dp)) + } } } } -@OptIn(ExperimentalMaterial3Api::class) @Composable private fun FormSection( ip: String, onIpChange: (String) -> Unit, @@ -175,111 +214,136 @@ private fun FormSection( showPassword: Boolean, onTogglePassword: () -> Unit, authType: String, onAuthTypeChange: (String) -> Unit, sshKey: String, onSshKeyChange: (String) -> Unit, - authDropdownExpanded: Boolean, onAuthDropdownChange: (Boolean) -> Unit, - sshState: SshConnectionState, - onConnect: () -> Unit + sshState: SshConnectionState ) { val context = LocalContext.current - Text(stringResource(R.string.server_data), style = MaterialTheme.typography.titleMedium) - OutlinedTextField( - value = ip, - onValueChange = onIpChange, - label = { Text(stringResource(R.string.server_ip_label)) }, - placeholder = { Text(stringResource(R.string.server_ip_placeholder)) }, - modifier = Modifier.fillMaxWidth(), - singleLine = true, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri) - ) - - OutlinedTextField( - value = port, - onValueChange = onPortChange, - label = { Text(stringResource(R.string.ssh_port)) }, - modifier = Modifier.fillMaxWidth(), - singleLine = true, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number) - ) - - OutlinedTextField( - value = username, - onValueChange = onUsernameChange, - label = { Text(stringResource(R.string.username)) }, - modifier = Modifier.fillMaxWidth(), - singleLine = true - ) - - ExposedDropdownMenuBox( - expanded = authDropdownExpanded, - onExpandedChange = onAuthDropdownChange, - modifier = Modifier.fillMaxWidth() - ) { - OutlinedTextField( - value = if (authType == "PASSWORD") stringResource(R.string.password) else stringResource(R.string.private_key), - onValueChange = {}, - readOnly = true, - label = { Text(stringResource(R.string.authentication)) }, - trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = authDropdownExpanded) }, - modifier = Modifier - .fillMaxWidth() - .menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable) - ) - ExposedDropdownMenu( - expanded = authDropdownExpanded, - onDismissRequest = { onAuthDropdownChange(false) } - ) { - DropdownMenuItem(text = { Text(stringResource(R.string.password)) }, - onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.SELECTION) - onAuthTypeChange("PASSWORD") - onAuthDropdownChange(false) - }) - DropdownMenuItem(text = { Text(stringResource(R.string.private_key)) }, - onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.SELECTION) - onAuthTypeChange("SSH_KEY") - onAuthDropdownChange(false) - }) + // --- Сервер: адрес и порт --- + SectionLabel(stringResource(R.string.server_data)) + SettingsCard { + SettingsFieldSlot { + OutlinedTextField( + value = ip, + onValueChange = onIpChange, + label = { Text(stringResource(R.string.server_ip_label)) }, + placeholder = { Text(stringResource(R.string.server_ip_placeholder)) }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri) + ) + } + SettingsRowDivider() + SettingsFieldSlot { + OutlinedTextField( + value = port, + onValueChange = onPortChange, + label = { Text(stringResource(R.string.ssh_port)) }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number) + ) } } - if (authType == "PASSWORD") { - OutlinedTextField( - value = password, - onValueChange = onPasswordChange, - label = { Text(stringResource(R.string.password)) }, - modifier = Modifier.fillMaxWidth(), - singleLine = true, - visualTransformation = if (showPassword) VisualTransformation.None else PasswordVisualTransformation(), - trailingIcon = { - IconButton(onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.SELECTION) - onTogglePassword() - }) { - Icon( - painterResource(if (showPassword) R.drawable.visibility_off_24px else R.drawable.visibility_24px), - contentDescription = if (showPassword) stringResource(R.string.hide_password) else stringResource(R.string.show_password) + // --- Аутентификация: логин, способ входа, секрет --- + SectionLabel(stringResource(R.string.authentication)) + SettingsCard { + SettingsFieldSlot { + OutlinedTextField( + value = username, + onValueChange = onUsernameChange, + label = { Text(stringResource(R.string.username)) }, + modifier = Modifier.fillMaxWidth(), + singleLine = true + ) + } + SettingsRowDivider() + // Способ входа — выпадающий селект (дропдаун вернули вместо сегментов). + SettingsFieldSlot { + var authDropdownExpanded by remember { mutableStateOf(false) } + ExposedDropdownMenuBox( + expanded = authDropdownExpanded, + onExpandedChange = { authDropdownExpanded = it }, + modifier = Modifier.fillMaxWidth() + ) { + OutlinedTextField( + value = if (authType == AUTH_PASSWORD) stringResource(R.string.password) + else stringResource(R.string.private_key), + onValueChange = {}, + readOnly = true, + label = { Text(stringResource(R.string.ssh_auth_method)) }, + trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = authDropdownExpanded) }, + modifier = Modifier + .fillMaxWidth() + .menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable) + ) + ExposedDropdownMenu( + expanded = authDropdownExpanded, + onDismissRequest = { authDropdownExpanded = false } + ) { + DropdownMenuItem( + text = { Text(stringResource(R.string.password)) }, + onClick = { + HapticUtil.perform(context, HapticUtil.Pattern.SELECTION) + onAuthTypeChange(AUTH_PASSWORD) + authDropdownExpanded = false + } + ) + DropdownMenuItem( + text = { Text(stringResource(R.string.private_key)) }, + onClick = { + HapticUtil.perform(context, HapticUtil.Pattern.SELECTION) + onAuthTypeChange(AUTH_SSH_KEY) + authDropdownExpanded = false + } ) } - }, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password) - ) - } else { - OutlinedTextField( - value = sshKey, - onValueChange = onSshKeyChange, - label = { Text(stringResource(R.string.private_key_pem)) }, - placeholder = { Text(stringResource(R.string.private_key_placeholder)) }, - modifier = Modifier - .fillMaxWidth() - .height(160.dp), - maxLines = 10 - ) + } + } + SettingsRowDivider() + SettingsFieldSlot { + if (authType == AUTH_PASSWORD) { + OutlinedTextField( + value = password, + onValueChange = onPasswordChange, + label = { Text(stringResource(R.string.password)) }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + visualTransformation = if (showPassword) VisualTransformation.None else PasswordVisualTransformation(), + trailingIcon = { + IconButton(onClick = { + HapticUtil.perform(context, HapticUtil.Pattern.SELECTION) + onTogglePassword() + }) { + Icon( + painterResource(if (showPassword) R.drawable.visibility_off_24px else R.drawable.visibility_24px), + contentDescription = if (showPassword) stringResource(R.string.hide_password) else stringResource(R.string.show_password) + ) + } + }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password) + ) + } else { + OutlinedTextField( + value = sshKey, + onValueChange = onSshKeyChange, + label = { Text(stringResource(R.string.private_key_pem)) }, + placeholder = { Text(stringResource(R.string.private_key_placeholder)) }, + modifier = Modifier + .fillMaxWidth() + .height(160.dp), + maxLines = 10 + ) + } + } } + // Ошибка подключения — тональная карточка в тон ошибки. if (sshState is SshConnectionState.Error) { - Card( - colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer) + Surface( + shape = MaterialTheme.shapes.large, + color = MaterialTheme.colorScheme.errorContainer, + modifier = Modifier.fillMaxWidth() ) { Row(modifier = Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) { Icon(painterResource(R.drawable.error_24px), null, tint = MaterialTheme.colorScheme.error) @@ -292,25 +356,12 @@ private fun FormSection( } } } - - Button( - onClick = { - HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - onConnect() - }, - modifier = Modifier - .fillMaxWidth() - .height(56.dp), - enabled = ip.isNotBlank() && when (authType) { - "SSH_KEY" -> sshKey.isNotBlank() - else -> password.isNotBlank() - }, - shape = MaterialTheme.shapes.large - ) { - Text(stringResource(R.string.connect_btn), style = MaterialTheme.typography.labelLarge) - } } +/** + * Прогресс сопряжения: wavy-индикатор + чек-лист шагов (подключение → авторизация → + * проверка SSH). Тональная карточка в едином стиле настроек. + */ @Composable private fun ConnectionProgressCard(step: String) { val steps = listOf( @@ -320,9 +371,10 @@ private fun ConnectionProgressCard(step: String) { ) val currentIndex = steps.indexOf(step).coerceAtLeast(0) - Card( - modifier = Modifier.fillMaxWidth(), - elevation = CardDefaults.cardElevation(1.dp) + Surface( + shape = MaterialTheme.shapes.large, + color = MaterialTheme.colorScheme.surfaceContainerLow, + modifier = Modifier.fillMaxWidth() ) { Column( modifier = Modifier.padding(24.dp), @@ -333,7 +385,7 @@ private fun ConnectionProgressCard(step: String) { Text( text = step, - style = MaterialTheme.typography.bodyLarge, + style = MaterialTheme.typography.titleMedium, textAlign = TextAlign.Center ) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 7729232..ab47e7e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -14,7 +14,8 @@ UDP SSH: сопряжение… Повторить сопряжение - Сервер не сопряжён. Подключитесь, чтобы управлять им. + Нет подключения к серверу + SSH-сессия не активна. Повторите сопряжение, чтобы управлять сервером. Прокси активен - нажмите для остановки Ошибка - нажмите для повторного запуска Запустить прокси @@ -39,6 +40,9 @@ 127.0.0.1:9000 Адрес, на котором клиент принимает трафик от WireGuard/XRay Параметры + Производительность + DNS + Дополнительно Потоки: %1$d Рекомендуется 8–12 Сколько TURN-потоков обслуживает один VK-аккаунт @@ -56,26 +60,27 @@ Генерация ключа… Синхронные настройки сервера Синхронизировать с сервером - При выкл. флаги меняются только у клиента, серверный процесс не перезапускается - Sync с сервером выключен. Cледите за совпадением вручную. - Журнал - Обновить - Загрузка журнала… - Журнал пуст - Очистить + Sync с сервером выключен. Следите за совпадением вручную. Транспорт UDP снижает задержки, TCP - стабильнее Ручной ввод капчи Решать капчу вручную вместо автоматического распознавания DNS оператора связи Использовать DNS текущей сети вместо системного резолвера + Отключено: действует ручной DNS-список выше DNS-резолвер Авто - пробует системный DNS, переключается на DNS-over-HTTPS при блокировке Авто UDP/53 DoH + DNS-серверы (вручную) + Через запятую/пробел. Приоритет над DNS оператора. Пусто — не задавать. + Часть значений не похожа на DNS-адреса — они будут пропущены Завершить настройку + Выберите профиль rtpopus, чтобы задать ключ обфускации. + Без SSH-подключения введите/вставьте 64-hex ключ вручную. + Логи Копировать @@ -94,14 +99,16 @@ 127.0.0.1:40537 Локальный WireGuard/Xray-клиент на стороне сервера Установить / обновить - Актуально - Обновлено + Установить + Обновить Obf-ключ (64 hex) Сгенерировать новый ключ на сервере Запустить сервер Остановить сервер Продолжить настройку клиента SSH-лог + Журнал сервера + Лог пуст Показать пароль @@ -147,10 +154,10 @@ Установлена последняя версия Ошибка: %1$s - Debug-режим - Расширенный вывод в логах + Подробное логирование + Детальный вывод ядра Альтернативный TURN-узел - Принудительно использовать указанный TURN-сервер вместо автоподбора. Помогает при блокировке стандартных адресов. + Указанный TURN-сервер вместо автоподбора Адрес TURN-узла 255.255.255.255 IP или хост альтернативного TURN-сервера @@ -221,8 +228,28 @@ Серверы - Сбор логов - Показывать вывод ядра на экране логов. Выключите для экономии памяти. + Показывать логи + Вывод ядра и кнопка логов на главном экране + + + Продвинутые + Отладка и диагностика + Режим отладки + Открывает отладочную информацию: состояние ядра, журнал сервера и подробные логи + Отладочная информация + Состояние ядра, журнал сервера и SSH-лог + Состояние ядра + Состояние + Работает + Остановлен + Не установлено + Версия + Параметры запуска + Сервер + Клиент + Да + Нет + Открыть логи Настройки @@ -242,13 +269,15 @@ Сервер остановлен Не удалось подключиться Ядро не установлено + Синхронизация выключена Подключение… SSH не настроен Сервер неактивен - Настройте подключение к серверу ниже + Настройте SSH-подключение к серверу + Настроить подключение + Способ входа Применить - Изменения перезапустят сервер Сервер не активен Чтобы управлять ядром и SSH-подключением, сделайте этот сервер активным. Сделать активным