feat: очистка/удаление сервера и вынос BusyProgressIndicator

Раздел "Управление" в детальном экране: удалённая очистка free-turn-proxy
(uninstall по SSH, снос только своего) и удаление сервера из приложения.
ServerDetail переехал в пакет ui/screens/serverdetail, диалоги вынесены в
ServerDetailDialogs. BusyProgressIndicator - переиспользуемый компонент
(wavy + reduced-motion фолбэк) вместо дублей по экранам.
This commit is contained in:
samosvalishe committed 2026-07-03 11:29:37 +03:00
1 parent 1644ab98c2
commit 07209cc962
13 files changed
+376 -110

No files matched your search

@@ -0,0 +1,30 @@
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class)
package com.freeturn.app.ui.components
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.LinearWavyProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.freeturn.app.ui.theme.LocalReducedMotion
/** Wavy-индикатор; при reduced motion - обычная полоса без волновой анимации. */
@Composable
fun BusyProgressIndicator(modifier: Modifier = Modifier) {
if (LocalReducedMotion.current) {
LinearProgressIndicator(modifier = modifier.fillMaxWidth())
} else {
LinearWavyProgressIndicator(modifier = modifier.fillMaxWidth())
}
}
/** Determinate-вариант ([progress] 0..1) с тем же reduced-motion фолбэком. */
@Composable
fun BusyProgressIndicator(progress: () -> Float, modifier: Modifier = Modifier) {
if (LocalReducedMotion.current) {
LinearProgressIndicator(progress = progress, modifier = modifier.fillMaxWidth())
} else {
LinearWavyProgressIndicator(progress = progress, modifier = modifier.fillMaxWidth())
}
}
@@ -55,7 +55,8 @@ import org.koin.androidx.compose.koinViewModel
// MD3 emphasized-кривая + длительности навигационных переходов (единый источник). // MD3 emphasized-кривая + длительности навигационных переходов (единый источник).
private val EmphasizedEasing = CubicBezierEasing(0.2f, 0f, 0f, 1f) private val EmphasizedEasing = CubicBezierEasing(0.2f, 0f, 0f, 1f)
private const val NAV_SLIDE_MS = 300 // internal: экраны откладывают тяжёлую работу на время перехода (ServerDetailScreen).
internal const val NAV_SLIDE_MS = 300
private const val NAV_FADE_IN_MS = 180 private const val NAV_FADE_IN_MS = 180
private const val NAV_FADE_OUT_MS = 120 private const val NAV_FADE_OUT_MS = 120
@@ -8,11 +8,11 @@ import androidx.navigation.toRoute
import com.freeturn.app.ui.screens.clientsetup.ClientSetupScreen import com.freeturn.app.ui.screens.clientsetup.ClientSetupScreen
import com.freeturn.app.ui.screens.connectionmode.ConnectionModeScreen import com.freeturn.app.ui.screens.connectionmode.ConnectionModeScreen
import com.freeturn.app.ui.screens.servermanagement.ServerManagementScreen import com.freeturn.app.ui.screens.servermanagement.ServerManagementScreen
import com.freeturn.app.ui.screens.serverdetail.ServerDetailScreen
import com.freeturn.app.ui.screens.settings.AboutScreen import com.freeturn.app.ui.screens.settings.AboutScreen
import com.freeturn.app.ui.screens.settings.AdvancedScreen import com.freeturn.app.ui.screens.settings.AdvancedScreen
import com.freeturn.app.ui.screens.settings.AppScreen import com.freeturn.app.ui.screens.settings.AppScreen
import com.freeturn.app.ui.screens.settings.NerdScreen import com.freeturn.app.ui.screens.settings.NerdScreen
import com.freeturn.app.ui.screens.settings.ServerDetailScreen
import com.freeturn.app.ui.screens.settings.ServersListScreen import com.freeturn.app.ui.screens.settings.ServersListScreen
import com.freeturn.app.ui.screens.settings.SettingsScreen import com.freeturn.app.ui.screens.settings.SettingsScreen
import com.freeturn.app.ui.screens.sshsetup.SshSetupScreen import com.freeturn.app.ui.screens.sshsetup.SshSetupScreen
@@ -7,7 +7,6 @@ import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.LinearWavyProgressIndicator
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
@@ -22,6 +21,7 @@ import androidx.compose.ui.unit.dp
import com.freeturn.app.R import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil import com.freeturn.app.data.HapticUtil
import com.freeturn.app.domain.UpdateState import com.freeturn.app.domain.UpdateState
import com.freeturn.app.ui.components.BusyProgressIndicator
/** /**
* Диалоги цикла обновления приложения: доступно -> качается -> готово к установке. * Диалоги цикла обновления приложения: доступно -> качается -> готово к установке.
@@ -68,10 +68,7 @@ internal fun UpdateDialogs(
Column { Column {
Text(stringResource(R.string.update_downloading, state.progress)) Text(stringResource(R.string.update_downloading, state.progress))
Spacer(Modifier.height(12.dp)) Spacer(Modifier.height(12.dp))
LinearWavyProgressIndicator( BusyProgressIndicator(progress = { state.progress / 100f })
progress = { state.progress / 100f },
modifier = Modifier.fillMaxWidth()
)
} }
}, },
confirmButton = {} confirmButton = {}
@@ -0,0 +1,220 @@
package com.freeturn.app.ui.screens.serverdetail
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.data.control.UninstallData
import com.freeturn.app.ui.components.BusyProgressIndicator
import com.freeturn.app.ui.theme.Spacing
import com.freeturn.app.viewmodel.settings.ServerCleanupState
/** Подтверждение удаления сервера из приложения (без серверной очистки). */
@Composable
internal fun DeleteServerDialog(
serverName: String,
onConfirm: () -> Unit,
onDismiss: () -> Unit
) {
val context = LocalContext.current
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.server_delete_confirm_title)) },
text = { Text(stringResource(R.string.server_delete_confirm_desc, serverName)) },
confirmButton = {
TextButton(
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.ERROR)
onConfirm()
},
colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error)
) { Text(stringResource(R.string.server_delete)) }
},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
}
)
}
/**
* Машина диалогов очистки сервера от FreeTurn: предупреждение -> wavy -> итог.
* Сервер из приложения НЕ удаляется (отдельное действие).
*/
@Composable
internal fun ServerCleanupDialog(
state: ServerCleanupState,
onConfirm: () -> Unit,
onClose: () -> Unit
) {
val context = LocalContext.current
when (state) {
ServerCleanupState.Running -> AlertDialog(
onDismissRequest = {},
title = { Text(stringResource(R.string.server_delete_cleaning_title)) },
text = {
Column {
Text(stringResource(R.string.server_delete_cleaning_desc))
Spacer(Modifier.height(Spacing.lg))
BusyProgressIndicator()
}
},
confirmButton = {}
)
is ServerCleanupState.Done -> AlertDialog(
onDismissRequest = {},
title = { Text(stringResource(R.string.server_delete_done_title)) },
text = { CleanupResult(state.data) },
confirmButton = {
TextButton(onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
onClose()
}) { Text(stringResource(R.string.server_delete_done_confirm)) }
}
)
else -> {
val err = (state as? ServerCleanupState.Error)?.message
AlertDialog(
onDismissRequest = onClose,
title = { Text(stringResource(R.string.server_clean_confirm_title)) },
text = {
Column {
Text(stringResource(R.string.server_clean_confirm_desc))
err?.let {
Spacer(Modifier.height(Spacing.md))
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error
)
}
}
},
confirmButton = {
TextButton(
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.ERROR)
onConfirm()
},
colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error)
) {
Text(stringResource(if (err != null) R.string.server_delete_retry else R.string.server_clean_confirm_btn))
}
},
dismissButton = {
TextButton(onClick = onClose) { Text(stringResource(R.string.cancel)) }
}
)
}
}
}
@Composable
internal fun RenameServerDialog(
currentName: String,
onSave: (String) -> Unit,
onDismiss: () -> Unit
) {
val context = LocalContext.current
var newName by remember(currentName) { mutableStateOf(currentName) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.rename_server_title)) },
text = {
OutlinedTextField(
value = newName,
onValueChange = { newName = it },
label = { Text(stringResource(R.string.server_name_label)) },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
},
confirmButton = {
TextButton(
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
onSave(newName)
},
enabled = newName.isNotBlank()
) { Text(stringResource(R.string.save)) }
},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
}
)
}
/** Итог удалённой очистки: что снесли с сервера и что не тронули. */
@Composable
private fun CleanupResult(data: UninstallData) {
Column {
Text(
stringResource(R.string.server_delete_done_desc),
style = MaterialTheme.typography.bodyMedium
)
Spacer(Modifier.height(Spacing.md))
val r = data.removed
val removed = buildList {
if (r.binary) add(R.string.cleanup_item_binary)
if (r.unit || r.legacyUnit) add(R.string.cleanup_item_service)
if (r.wgIface) add(R.string.cleanup_item_wg)
if (data.wgPkgRemoved) add(R.string.cleanup_item_wg_pkg)
if (r.ufw) add(R.string.cleanup_item_firewall)
if (r.prefix) add(R.string.cleanup_item_files)
}
if (removed.isEmpty()) {
Text(
stringResource(R.string.cleanup_nothing),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
} else {
Text(
stringResource(R.string.cleanup_removed_label),
style = MaterialTheme.typography.labelLarge
)
removed.forEach {
Text("• " + stringResource(it), style = MaterialTheme.typography.bodySmall)
}
}
if (data.kept.isNotEmpty()) {
Spacer(Modifier.height(Spacing.md))
Text(
stringResource(R.string.cleanup_kept_label),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
data.kept.forEach { token ->
// kept-токены - контракт _kept_add (80-cmd.sh); незнакомый показываем как есть.
val label = when (token) {
"foreign_ft_wg0" -> stringResource(R.string.cleanup_kept_foreign_wg)
"wireguard-tools" -> stringResource(R.string.cleanup_kept_wg_tools)
"ip_forward" -> stringResource(R.string.cleanup_kept_ip_forward)
else -> token
}
Text(
"• $label",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
@@ -3,7 +3,7 @@
androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class
) )
package com.freeturn.app.ui.screens.settings package com.freeturn.app.ui.screens.serverdetail
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
@@ -15,25 +15,19 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.LargeFlexibleTopAppBar import androidx.compose.material3.LargeFlexibleTopAppBar
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
@@ -45,8 +39,8 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.freeturn.app.R import com.freeturn.app.R
import com.freeturn.app.domain.SshConnectionState
import com.freeturn.app.data.HapticUtil import com.freeturn.app.data.HapticUtil
import com.freeturn.app.domain.SshConnectionState
import com.freeturn.app.ui.components.SectionLabel import com.freeturn.app.ui.components.SectionLabel
import com.freeturn.app.ui.components.SettingsBackButton import com.freeturn.app.ui.components.SettingsBackButton
import com.freeturn.app.ui.components.SettingsCard import com.freeturn.app.ui.components.SettingsCard
@@ -55,12 +49,13 @@ import com.freeturn.app.ui.components.SettingsEntryRow
import com.freeturn.app.ui.components.SettingsGroup import com.freeturn.app.ui.components.SettingsGroup
import com.freeturn.app.ui.components.SettingsGroupItem import com.freeturn.app.ui.components.SettingsGroupItem
import com.freeturn.app.ui.components.SettingsSwitchRow import com.freeturn.app.ui.components.SettingsSwitchRow
import com.freeturn.app.ui.navigation.NAV_SLIDE_MS
import com.freeturn.app.ui.theme.Spacing
import com.freeturn.app.ui.util.redact import com.freeturn.app.ui.util.redact
import com.freeturn.app.viewmodel.server.ServerHubState import com.freeturn.app.viewmodel.server.ServerHubState
import com.freeturn.app.viewmodel.server.ServerViewModel import com.freeturn.app.viewmodel.server.ServerViewModel
import com.freeturn.app.viewmodel.settings.SettingsViewModel
import com.freeturn.app.viewmodel.server.serverSettingsAvailable import com.freeturn.app.viewmodel.server.serverSettingsAvailable
import com.freeturn.app.ui.theme.Spacing import com.freeturn.app.viewmodel.settings.SettingsViewModel
/** /**
* Детальный экран сервера - плоский хаб: шапка-сводка, вход в настройки провайдера * Детальный экран сервера - плоский хаб: шапка-сводка, вход в настройки провайдера
@@ -112,13 +107,14 @@ fun ServerDetailScreen(
// одновременно со slide-переходом - это и есть пролаг при заходе. После перехода - плавно. // одновременно со slide-переходом - это и есть пролаг при заходе. После перехода - плавно.
LaunchedEffect(isActive, sshConfig.ip, sshState) { LaunchedEffect(isActive, sshConfig.ip, sshState) {
if (isActive && sshConfig.ip.isNotBlank() && sshState is SshConnectionState.Disconnected) { if (isActive && sshConfig.ip.isNotBlank() && sshState is SshConnectionState.Disconnected) {
kotlinx.coroutines.delay(350) kotlinx.coroutines.delay(NAV_SLIDE_MS + 50L)
serverViewModel.reconnectSsh() serverViewModel.reconnectSsh()
} }
} }
var showMenu by rememberSaveable { mutableStateOf(false) } var showMenu by rememberSaveable { mutableStateOf(false) }
var showDelete by rememberSaveable { mutableStateOf(false) } var showDelete by rememberSaveable { mutableStateOf(false) }
var showCleanup by rememberSaveable { mutableStateOf(false) }
var showRename by rememberSaveable { mutableStateOf(false) } var showRename by rememberSaveable { mutableStateOf(false) }
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior() val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
@@ -220,22 +216,7 @@ fun ServerDetailScreen(
) )
} }
) )
DropdownMenuItem( // Удаление/очистка - в разделе "Управление" внизу хаба, не здесь.
text = {
Text(
stringResource(R.string.menu_delete_server),
color = MaterialTheme.colorScheme.error
)
},
onClick = { showMenu = false; showDelete = true },
leadingIcon = {
Icon(
painterResource(R.drawable.delete_24px),
contentDescription = null,
tint = MaterialTheme.colorScheme.error
)
}
)
} }
} }
} }
@@ -348,62 +329,71 @@ fun ServerDetailScreen(
) )
} }
} }
if (server != null) {
SectionLabel(stringResource(R.string.server_management))
// Очистка - только при SSH-доступе (есть что сносить с удалённого хоста).
val canCleanup = server.ssh.ip.isNotBlank()
val mgmtCount = if (canCleanup) 2 else 1
SettingsGroup {
if (canCleanup) {
SettingsGroupItem(0, mgmtCount) {
SettingsEntryRow(
iconRes = R.drawable.mop_24px,
title = stringResource(R.string.server_clean_title),
subtitle = stringResource(R.string.server_clean_subtitle),
trailingRes = null,
onClick = { showCleanup = true }
)
}
}
SettingsGroupItem(mgmtCount - 1, mgmtCount) {
SettingsEntryRow(
iconRes = R.drawable.delete_24px,
title = stringResource(R.string.server_delete_app),
subtitle = stringResource(R.string.server_delete_app_subtitle),
trailingRes = null,
onClick = { showDelete = true }
)
}
}
}
} }
} }
} }
if (showDelete && server != null) { if (showDelete && server != null) {
AlertDialog( DeleteServerDialog(
onDismissRequest = { showDelete = false }, serverName = server.name,
title = { Text(stringResource(R.string.server_delete_confirm_title)) }, onConfirm = {
text = { Text(stringResource(R.string.server_delete_confirm_desc, server.name)) },
confirmButton = {
TextButton(
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.ERROR)
settingsViewModel.deleteServer(serverId) settingsViewModel.deleteServer(serverId)
showDelete = false showDelete = false
// Навигацию назад делает null-guard выше (server станет null // Навигацию назад делает null-guard выше (server станет null).
// после async-удаления) - не зовём pop тут, иначе двойной pop.
}, },
colors = ButtonDefaults.textButtonColors( onDismiss = { showDelete = false }
contentColor = MaterialTheme.colorScheme.error
) )
) { Text(stringResource(R.string.server_delete)) } }
},
dismissButton = { if (showCleanup && server != null) {
TextButton(onClick = { showDelete = false }) { Text(stringResource(R.string.cancel)) } val cleanupState by settingsViewModel.cleanupState.collectAsStateWithLifecycle()
ServerCleanupDialog(
state = cleanupState,
onConfirm = { settingsViewModel.cleanupServer(serverId) },
onClose = {
showCleanup = false
settingsViewModel.resetCleanupState()
} }
) )
} }
if (showRename && server != null) { if (showRename && server != null) {
var newName by remember(server.id) { mutableStateOf(server.name) } RenameServerDialog(
AlertDialog( currentName = server.name,
onDismissRequest = { showRename = false }, onSave = { name ->
title = { Text(stringResource(R.string.rename_server_title)) }, settingsViewModel.renameServer(serverId, name)
text = {
OutlinedTextField(
value = newName,
onValueChange = { newName = it },
label = { Text(stringResource(R.string.server_name_label)) },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
},
confirmButton = {
TextButton(
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
settingsViewModel.renameServer(serverId, newName)
showRename = false showRename = false
}, },
enabled = newName.isNotBlank() onDismiss = { showRename = false }
) { Text(stringResource(R.string.save)) }
},
dismissButton = {
TextButton(onClick = { showRename = false }) { Text(stringResource(R.string.cancel)) }
}
) )
} }
} }
@@ -3,18 +3,16 @@
androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class
) )
package com.freeturn.app.ui.screens.settings package com.freeturn.app.ui.screens.serverdetail
import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.SizeTransform import androidx.compose.animation.SizeTransform
import androidx.compose.animation.animateColorAsState import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.snap import androidx.compose.animation.core.snap
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut import androidx.compose.animation.fadeOut
@@ -29,7 +27,6 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.LinearWavyProgressIndicator
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -43,9 +40,11 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.lerp import androidx.compose.ui.util.lerp
import com.freeturn.app.R import com.freeturn.app.R
import com.freeturn.app.ui.components.BusyProgressIndicator
import com.freeturn.app.ui.theme.LocalReducedMotion import com.freeturn.app.ui.theme.LocalReducedMotion
import com.freeturn.app.ui.theme.extendedColorScheme import com.freeturn.app.ui.theme.extendedColorScheme
import com.freeturn.app.viewmodel.server.ServerHubState import com.freeturn.app.viewmodel.server.ServerHubState
@@ -68,6 +67,9 @@ internal fun ServerStatusCard(
// сервером не общается. Схлопываем их в нейтральную заглушку. Actionable-состояния // сервером не общается. Схлопываем их в нейтральную заглушку. Actionable-состояния
// (Offline/NotPaired) остаются - это setup, а не live-статус. // (Offline/NotPaired) остаются - это setup, а не live-статус.
val effective = if (!syncOn && status.isLivePhase()) ServerHubState.SyncOff else status val effective = if (!syncOn && status.isLivePhase()) ServerHubState.SyncOff else status
// Спеки из MotionScheme (не сырые spring/tween) - единый источник с SetupInstallStep.
val effectsSpec = MaterialTheme.motionScheme.defaultEffectsSpec<Float>()
val spatialSpec = MaterialTheme.motionScheme.defaultSpatialSpec<IntSize>()
Surface( Surface(
shape = MaterialTheme.shapes.large, shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.surfaceContainerLow, color = MaterialTheme.colorScheme.surfaceContainerLow,
@@ -82,15 +84,8 @@ internal fun ServerStatusCard(
(fadeIn(snap()) togetherWith fadeOut(snap())) (fadeIn(snap()) togetherWith fadeOut(snap()))
.using(SizeTransform(clip = false) { _, _ -> snap() }) .using(SizeTransform(clip = false) { _, _ -> snap() })
} else { } else {
(fadeIn(tween(200)) togetherWith fadeOut(tween(120))) (fadeIn(effectsSpec) togetherWith fadeOut(effectsSpec))
.using( .using(SizeTransform(clip = false) { _, _ -> spatialSpec })
SizeTransform(clip = false) { _, _ ->
spring(
dampingRatio = Spring.DampingRatioNoBouncy,
stiffness = Spring.StiffnessMediumLow
)
}
)
} }
}, },
label = "hub_status", label = "hub_status",
@@ -206,7 +201,7 @@ private fun BusyContent(title: String) {
title = title, title = title,
pulsing = true pulsing = true
) )
LinearWavyProgressIndicator(modifier = Modifier.fillMaxWidth()) BusyProgressIndicator()
} }
/** /**
@@ -27,7 +27,6 @@ import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.FilledTonalButton import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.LargeFlexibleTopAppBar import androidx.compose.material3.LargeFlexibleTopAppBar
import androidx.compose.material3.LinearWavyProgressIndicator
import androidx.compose.material3.LoadingIndicator import androidx.compose.material3.LoadingIndicator
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
@@ -54,6 +53,7 @@ import com.freeturn.app.R
import com.freeturn.app.domain.UpdateState import com.freeturn.app.domain.UpdateState
import com.freeturn.app.data.HapticUtil import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.components.BackupPasswordDialog import com.freeturn.app.ui.components.BackupPasswordDialog
import com.freeturn.app.ui.components.BusyProgressIndicator
import com.freeturn.app.ui.components.SectionLabel import com.freeturn.app.ui.components.SectionLabel
import com.freeturn.app.ui.components.SettingsBackButton import com.freeturn.app.ui.components.SettingsBackButton
import com.freeturn.app.ui.components.SettingsCard import com.freeturn.app.ui.components.SettingsCard
@@ -298,10 +298,7 @@ private fun UpdateCard(
} }
} }
if (state is UpdateState.Downloading) { if (state is UpdateState.Downloading) {
LinearWavyProgressIndicator( BusyProgressIndicator(progress = { state.progress / 100f })
progress = { state.progress / 100f },
modifier = Modifier.fillMaxWidth()
)
} else { } else {
val action = when (state) { val action = when (state) {
is UpdateState.Available -> onDownload is UpdateState.Available -> onDownload
@@ -46,6 +46,7 @@ import androidx.compose.ui.unit.dp
import com.freeturn.app.R import com.freeturn.app.R
import com.freeturn.app.data.config.ObfProfile import com.freeturn.app.data.config.ObfProfile
import com.freeturn.app.data.HapticUtil import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.components.BusyProgressIndicator
import com.freeturn.app.ui.components.InlineErrorCard import com.freeturn.app.ui.components.InlineErrorCard
import com.freeturn.app.ui.theme.LocalReducedMotion import com.freeturn.app.ui.theme.LocalReducedMotion
import com.freeturn.app.ui.theme.extendedColorScheme import com.freeturn.app.ui.theme.extendedColorScheme
@@ -1,13 +1,9 @@
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class)
package com.freeturn.app.ui.screens.setup package com.freeturn.app.ui.screens.setup
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.LinearWavyProgressIndicator
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -17,9 +13,9 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import com.freeturn.app.R import com.freeturn.app.R
import com.freeturn.app.ui.components.BusyProgressIndicator
import com.freeturn.app.ui.components.InlineErrorCard import com.freeturn.app.ui.components.InlineErrorCard
import com.freeturn.app.ui.components.SshFormFields import com.freeturn.app.ui.components.SshFormFields
import com.freeturn.app.ui.theme.LocalReducedMotion
import com.freeturn.app.viewmodel.server.SetupSshDraft import com.freeturn.app.viewmodel.server.SetupSshDraft
import com.freeturn.app.ui.theme.Spacing import com.freeturn.app.ui.theme.Spacing
@@ -75,18 +71,11 @@ fun SetupSshStep(
password = draft.password, onPasswordChange = { onDraftChange(draft.copy(password = it)) }, password = draft.password, onPasswordChange = { onDraftChange(draft.copy(password = it)) },
authType = draft.authType, onAuthTypeChange = { onDraftChange(draft.copy(authType = it)) }, authType = draft.authType, onAuthTypeChange = { onDraftChange(draft.copy(authType = it)) },
sshKey = draft.sshKey, onSshKeyChange = { onDraftChange(draft.copy(sshKey = it)) }, sshKey = draft.sshKey, onSshKeyChange = { onDraftChange(draft.copy(sshKey = it)) },
showErrors = showErrors showErrors = showErrors,
sudoPassword = draft.sudoPassword,
onSudoPasswordChange = { onDraftChange(draft.copy(sudoPassword = it)) },
showSudoPassword = true
) )
if (error != null) InlineErrorCard(error) if (error != null) InlineErrorCard(error)
} }
/** Wavy-индикатор; при reduced motion - обычная полоса без волновой анимации. */
@Composable
internal fun BusyProgressIndicator(modifier: Modifier = Modifier) {
if (LocalReducedMotion.current) {
LinearProgressIndicator(modifier = modifier.fillMaxWidth())
} else {
LinearWavyProgressIndicator(modifier = modifier.fillMaxWidth())
}
}
@@ -22,7 +22,7 @@ import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.freeturn.app.R import com.freeturn.app.R
import com.freeturn.app.ui.screens.setup.BusyProgressIndicator import com.freeturn.app.ui.components.BusyProgressIndicator
import com.freeturn.app.ui.theme.Spacing import com.freeturn.app.ui.theme.Spacing
/** /**
@@ -9,13 +9,16 @@ import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.backup.BackupCrypto import com.freeturn.app.data.backup.BackupCrypto
import com.freeturn.app.data.config.ClientConfig import com.freeturn.app.data.config.ClientConfig
import com.freeturn.app.data.config.ObfProfile import com.freeturn.app.data.config.ObfProfile
import com.freeturn.app.data.control.UninstallData
import com.freeturn.app.data.server.Server import com.freeturn.app.data.server.Server
import com.freeturn.app.data.server.ServersSnapshot import com.freeturn.app.data.server.ServersSnapshot
import com.freeturn.app.domain.backup.BackupManager import com.freeturn.app.domain.backup.BackupManager
import com.freeturn.app.domain.update.AppUpdater import com.freeturn.app.domain.update.AppUpdater
import com.freeturn.app.domain.proxy.LocalProxyManager import com.freeturn.app.domain.proxy.LocalProxyManager
import com.freeturn.app.domain.proxy.ProxyOrchestrator import com.freeturn.app.domain.proxy.ProxyOrchestrator
import com.freeturn.app.domain.server.ServerSetupRepository
import com.freeturn.app.domain.ssh.SshRepository import com.freeturn.app.domain.ssh.SshRepository
import com.freeturn.app.viewmodel.uiError
import com.freeturn.app.domain.UpdateState import com.freeturn.app.domain.UpdateState
import com.freeturn.app.domain.proxy.ProxyServiceState import com.freeturn.app.domain.proxy.ProxyServiceState
import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CancellationException
@@ -39,10 +42,19 @@ import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.withTimeoutOrNull
import java.io.IOException import java.io.IOException
/** Состояние очистки сервера от FreeTurn (snapshot для диалога). */
sealed interface ServerCleanupState {
data object Idle : ServerCleanupState
data object Running : ServerCleanupState
data class Done(val data: UninstallData) : ServerCleanupState
data class Error(val message: String) : ServerCleanupState
}
class SettingsViewModel( class SettingsViewModel(
private val prefs: AppPreferences, private val prefs: AppPreferences,
private val proxyManager: LocalProxyManager, private val proxyManager: LocalProxyManager,
private val sshRepository: SshRepository, private val sshRepository: SshRepository,
private val serverSetup: ServerSetupRepository,
private val appUpdater: AppUpdater, private val appUpdater: AppUpdater,
private val orchestrator: ProxyOrchestrator, private val orchestrator: ProxyOrchestrator,
private val backupManager: BackupManager, private val backupManager: BackupManager,
@@ -210,10 +222,34 @@ class SettingsViewModel(
} }
} }
private val _cleanupState = MutableStateFlow<ServerCleanupState>(ServerCleanupState.Idle)
/** Прогресс очистки сервера от FreeTurn (диалог в разделе "Управление"). */
val cleanupState: StateFlow<ServerCleanupState> = _cleanupState.asStateFlow()
fun resetCleanupState() { _cleanupState.value = ServerCleanupState.Idle }
/** Удаление сервера из приложения (локально, без серверной очистки). */
fun deleteServer(id: String) { fun deleteServer(id: String) {
viewModelScope.launch { prefs.deleteServer(id) } viewModelScope.launch { prefs.deleteServer(id) }
} }
/**
* Снос free-turn-proxy с удалённого сервера по SSH. Сервер из приложения НЕ
* удаляет - это отдельное действие. Результат/ошибка - в [cleanupState].
*/
fun cleanupServer(id: String) {
viewModelScope.launch {
val cfg = serversSnapshot.value.list.firstOrNull { it.id == id }?.ssh ?: return@launch
_cleanupState.value = ServerCleanupState.Running
// Деструктив под верной эскалацией: сохранённый rootMode мог устареть/быть
// дефолтным ROOT (сервер ни разу не подключали) -> preflight перед сносом.
val mode = serverSetup.detectRootMode(cfg) ?: cfg.rootMode
serverSetup.uninstall(cfg.copy(rootMode = mode), withWgPkg = true)
.onSuccess { _cleanupState.value = ServerCleanupState.Done(it) }
.onFailure { _cleanupState.value = ServerCleanupState.Error(it.uiError(appContext)) }
}
}
// Правит client-конфиг сервера по id, НЕ требуя его активации. Для активного // Правит client-конфиг сервера по id, НЕ требуя его активации. Для активного
// дополнительно обновляет глобальный флаг логов (его читает рантайм). // дополнительно обновляет глобальный флаг логов (его читает рантайм).
fun updateServerClient(id: String, transform: (ClientConfig) -> ClientConfig) { fun updateServerClient(id: String, transform: (ClientConfig) -> ClientConfig) {
+10
View File
@@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="960"
android:viewportHeight="960"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M440,440L520,440L520,160Q520,143 508.5,131.5Q497,120 480,120Q463,120 451.5,131.5Q440,143 440,160L440,440ZM200,600L760,600L760,520Q760,520 760,520Q760,520 760,520L200,520Q200,520 200,520Q200,520 200,520L200,600ZM142,840L240,840L240,760Q240,743 251.5,731.5Q263,720 280,720Q297,720 308.5,731.5Q320,743 320,760L320,840L440,840L440,760Q440,743 451.5,731.5Q463,720 480,720Q497,720 508.5,731.5Q520,743 520,760L520,840L640,840L640,760Q640,743 651.5,731.5Q663,720 680,720Q697,720 708.5,731.5Q720,743 720,760L720,840L818,840Q818,840 818,840Q818,840 818,840L778,680L182,680L142,840Q142,840 142,840Q142,840 142,840ZM818,920L142,920Q103,920 79,889Q55,858 65,820L120,600L120,520Q120,487 143.5,463.5Q167,440 200,440L360,440L360,160Q360,110 395,75Q430,40 480,40Q530,40 565,75Q600,110 600,160L600,440L760,440Q793,440 816.5,463.5Q840,487 840,520L840,600L895,820Q908,858 883.5,889Q859,920 818,920ZM760,520L200,520L200,520Q200,520 200,520Q200,520 200,520L760,520Q760,520 760,520Q760,520 760,520ZM520,440L440,440L440,440Q440,440 451.5,440Q463,440 480,440Q497,440 508.5,440Q520,440 520,440Z"/>
</vector>