feat: reset settings, LazyColumn logs, bottom sheet M3 fix, polish

This commit is contained in:
samosvalishe committed 2026-03-31 00:43:31 +03:00
1 parent 8a11c3a56e
commit 2c3dcce8e5
8 files changed
+156 -39

No files matched your search

@@ -27,7 +27,6 @@ import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
sealed class StartupResult {
@@ -39,13 +38,28 @@ class ProxyService : Service() {
companion object {
const val MAX_RESTARTS = 8
private const val MAX_LOG_LINES = 200
val isRunning = MutableStateFlow(false)
val logs = MutableStateFlow<List<String>>(emptyList())
val proxyFailed = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
val startupResult = MutableStateFlow<StartupResult?>(null)
// P3-3: ArrayDeque — O(1) addLast/removeFirst вместо O(n) list concatenation
private val logBuffer = ArrayDeque<String>(MAX_LOG_LINES)
fun addLog(msg: String) {
logs.update { (it + msg).takeLast(200) }
synchronized(logBuffer) {
logBuffer.addLast(msg)
while (logBuffer.size > MAX_LOG_LINES) logBuffer.removeFirst()
logs.value = logBuffer.toList()
}
}
fun clearLogs() {
synchronized(logBuffer) {
logBuffer.clear()
logs.value = emptyList()
}
}
}
@@ -94,9 +94,6 @@ class SSHManager {
}
}
fun disconnect() {
// Все сессии в executeSilentCommand временные и закрываются в finally-блоке
}
}
/**
@@ -12,6 +12,7 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
import androidx.core.content.edit
@@ -171,4 +172,13 @@ class AppPreferences(context: Context) {
prefs[PROXY_CONNECT] = connect
}
}
/** Полный сброс: DataStore + EncryptedSharedPreferences + кастомный бинарник */
suspend fun resetAll() {
context.dataStore.edit { it.clear() }
withContext(Dispatchers.IO) {
encryptedPrefs.edit { clear() }
File(context.filesDir, "custom_vkturn").delete()
}
}
}
@@ -67,6 +67,7 @@ object Routes {
const val SERVER_MANAGEMENT = "server_management"
const val SERVER_MANAGEMENT_OB = "server_management_ob" // только в мастере онбординга
const val CLIENT_SETUP = "client_setup"
const val CLIENT_SETUP_OB = "client_setup_onboarding"
const val HOME = "home"
}
@@ -156,14 +157,14 @@ fun AppNavigation(viewModel: MainViewModel) {
ServerManagementScreen(
viewModel = viewModel,
onContinue = {
navController.navigate(Routes.CLIENT_SETUP + "_onboarding") {
navController.navigate(Routes.CLIENT_SETUP_OB) {
launchSingleTop = true
}
}
)
}
composable(Routes.CLIENT_SETUP + "_onboarding") {
composable(Routes.CLIENT_SETUP_OB) {
ClientSetupScreen(
viewModel = viewModel,
showFinishButton = true,
@@ -84,7 +84,7 @@ fun ClientSetupScreen(
var noDtls by rememberSaveable(saved.noDtls) { mutableStateOf(saved.noDtls) }
var localPort by rememberSaveable(saved.localPort) { mutableStateOf(saved.localPort) }
var showAdvanced by rememberSaveable { mutableStateOf(false) }
var lastSliderInt by remember { mutableIntStateOf(saved.threads) }
var lastSliderInt by rememberSaveable { mutableIntStateOf(saved.threads) }
// Автозаполнение адреса сервера из SSH-конфига если поле пустое
LaunchedEffect(sshConfig.ip, proxyListen) {
@@ -21,6 +21,9 @@ import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
@@ -32,6 +35,8 @@ import androidx.compose.material.icons.filled.Error
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
@@ -39,6 +44,7 @@ import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Scaffold
@@ -70,6 +76,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.graphics.Color
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.platform.LocalContext
@@ -277,12 +284,15 @@ fun HomeScreen(
}
if (showBottomSheet.value) {
val sheetColor = MaterialTheme.colorScheme.surfaceContainerLow
ModalBottomSheet(
onDismissRequest = { showBottomSheet.value = false },
sheetState = bottomSheetState
sheetState = bottomSheetState,
containerColor = sheetColor
) {
InfoBottomSheet(
viewModel = viewModel,
containerColor = sheetColor,
onNavigateToSshSetup = {
showBottomSheet.value = false
onNavigateToSshSetup()
@@ -357,6 +367,7 @@ private fun ProxyToggleButton(state: ProxyState, onClick: () -> Unit) {
@Composable
private fun InfoBottomSheet(
viewModel: MainViewModel,
containerColor: Color,
onNavigateToSshSetup: () -> Unit
) {
val context = LocalContext.current
@@ -364,6 +375,7 @@ private fun InfoBottomSheet(
val sshState by viewModel.sshState.collectAsStateWithLifecycle()
val logs by viewModel.logs.collectAsStateWithLifecycle()
var showLogs by rememberSaveable { mutableStateOf(false) }
var showResetDialog by rememberSaveable { mutableStateOf(false) }
val appVersion = remember {
try { context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "—" }
@@ -378,8 +390,10 @@ private fun InfoBottomSheet(
) {
// ── SSH ────────────────────────────────────────────────────────────
val isConnected = sshState is SshConnectionState.Connected
val listColors = ListItemDefaults.colors(containerColor = containerColor)
ListItem(
headlineContent = { Text("Соединение", style = MaterialTheme.typography.titleSmall) },
colors = listColors,
trailingContent = {
TextButton(onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
@@ -391,6 +405,7 @@ private fun InfoBottomSheet(
ListItem(
headlineContent = { Text("SSH-статус") },
colors = listColors,
supportingContent = {
Text(
when (sshState) {
@@ -429,6 +444,7 @@ private fun InfoBottomSheet(
// ── Логи ──────────────────────────────────────────────────────────
ListItem(
headlineContent = { Text("Логи", style = MaterialTheme.typography.titleSmall) },
colors = listColors,
trailingContent = {
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(
@@ -468,11 +484,13 @@ private fun InfoBottomSheet(
// ── О приложении ───────────────────────────────────────────────────
ListItem(
headlineContent = { Text("О приложении", style = MaterialTheme.typography.titleSmall) }
headlineContent = { Text("О приложении", style = MaterialTheme.typography.titleSmall) },
colors = listColors
)
ListItem(
headlineContent = { Text("FreeTurn") },
colors = listColors,
supportingContent = { Text("Версия $appVersion") }
)
@@ -480,6 +498,7 @@ private fun InfoBottomSheet(
title = "Android-клиент",
subtitle = "Fork MYSOREZ/vk-turn-proxy-android",
url = "https://github.com/MYSOREZ/vk-turn-proxy-android",
containerColor = containerColor,
onHaptic = { HapticUtil.perform(context, HapticUtil.Pattern.SELECTION) },
onOpen = { uriHandler.openUri(it) }
)
@@ -488,9 +507,52 @@ private fun InfoBottomSheet(
title = "Прокси-ядро",
subtitle = "cacggghp/vk-turn-proxy",
url = "https://github.com/cacggghp/vk-turn-proxy",
containerColor = containerColor,
onHaptic = { HapticUtil.perform(context, HapticUtil.Pattern.SELECTION) },
onOpen = { uriHandler.openUri(it) }
)
HorizontalDivider()
// ── Сброс ─────────────────────────────────────────────────────────
ListItem(
headlineContent = { Text("Сбросить настройки") },
colors = listColors,
supportingContent = { Text("SSH, клиент, прокси и кастомное ядро") },
trailingContent = {
TextButton(
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
showResetDialog = true
},
colors = ButtonDefaults.textButtonColors(
contentColor = MaterialTheme.colorScheme.error
)
) { Text("Сбросить") }
}
)
if (showResetDialog) {
AlertDialog(
onDismissRequest = { showResetDialog = false },
title = { Text("Сбросить все настройки?") },
text = { Text("Все настройки будут удалены, прокси остановлен. Приложение перезапустится.") },
confirmButton = {
TextButton(
onClick = {
showResetDialog = false
viewModel.resetAllSettings(context)
},
colors = ButtonDefaults.textButtonColors(
contentColor = MaterialTheme.colorScheme.error
)
) { Text("Сбросить") }
},
dismissButton = {
TextButton(onClick = { showResetDialog = false }) { Text("Отмена") }
}
)
}
}
}
@@ -499,11 +561,13 @@ private fun RepoLinkItem(
title: String,
subtitle: String,
url: String,
containerColor: Color = MaterialTheme.colorScheme.surface,
onHaptic: () -> Unit,
onOpen: (String) -> Unit
) {
ListItem(
headlineContent = { Text(title) },
colors = ListItemDefaults.colors(containerColor = containerColor),
supportingContent = {
Text(
subtitle,
@@ -528,29 +592,29 @@ private fun RepoLinkItem(
@Composable
private fun LogsPanel(logs: List<String>, modifier: Modifier = Modifier) {
val scrollState = rememberScrollState()
val listState = rememberLazyListState()
LaunchedEffect(logs.size) {
scrollState.animateScrollTo(scrollState.maxValue)
if (logs.isNotEmpty()) listState.animateScrollToItem(logs.lastIndex)
}
Card(
modifier = modifier,
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)
) {
Column(
modifier = Modifier
.heightIn(max = 320.dp)
.verticalScroll(scrollState)
.padding(vertical = 8.dp)
) {
if (logs.isEmpty()) {
Text(
"Нет логов",
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f)
)
} else {
logs.forEachIndexed { index, line ->
if (logs.isEmpty()) {
Text(
"Нет логов",
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f)
)
} else {
LazyColumn(
state = listState,
modifier = Modifier
.heightIn(max = 320.dp)
.padding(vertical = 8.dp)
) {
itemsIndexed(logs) { index, line ->
LogLine(line = line, isEven = index % 2 == 0)
}
}
@@ -15,6 +15,9 @@ 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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
@@ -267,23 +270,23 @@ fun ServerManagementScreen(
)
} else {
Spacer(Modifier.height(12.dp))
val scrollState = rememberScrollState()
val listState = rememberLazyListState()
LaunchedEffect(sshLog.size) {
scrollState.animateScrollTo(scrollState.maxValue)
if (sshLog.isNotEmpty()) listState.animateScrollToItem(sshLog.lastIndex)
}
Card(
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant
)
) {
Column(
LazyColumn(
state = listState,
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 400.dp)
.verticalScroll(scrollState)
.padding(10.dp)
) {
sshLog.forEach { line ->
items(sshLog) { line ->
val isHeader = line.startsWith("===")
val isError = line.contains("ERROR", ignoreCase = true) ||
line.contains("error", ignoreCase = true) ||
@@ -86,8 +86,12 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
private val _sshLog = MutableStateFlow<List<String>>(emptyList())
val sshLog: StateFlow<List<String>> = _sshLog.asStateFlow()
// P3-10: ArrayDeque — O(1) вместо O(n) list concatenation
private val sshLogBuffer = ArrayDeque<String>(500)
private fun appendSshLog(vararg lines: String) {
_sshLog.value = (_sshLog.value + lines).takeLast(500)
lines.forEach { sshLogBuffer.addLast(it) }
while (sshLogBuffer.size > 500) sshLogBuffer.removeFirst()
_sshLog.value = sshLogBuffer.toList()
}
private fun logCommand(target: String, cmd: String) {
@@ -173,8 +177,6 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
viewModelScope.launch {
prefs.saveSshConfig(config)
}
sshManager.disconnect()
// P2-6: сразу начинаем реальное подключение, без фейковых delay(400)/delay(300)
_sshState.value = SshConnectionState.Connecting()
viewModelScope.launch {
@@ -371,7 +373,10 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
}
}
fun clearSshLog() { _sshLog.value = emptyList() }
fun clearSshLog() {
sshLogBuffer.clear()
_sshLog.value = emptyList()
}
// ── Local proxy ────────────────────────────────────────────────────────
@@ -395,7 +400,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
viewModelScope.launch {
prefs.saveClientConfig(cfg)
ProxyService.logs.value = emptyList()
ProxyService.clearLogs()
ProxyService.startupResult.value = null
context.startForegroundService(Intent(context, ProxyService::class.java))
@@ -447,7 +452,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
}
fun clearLogs() {
ProxyService.logs.value = emptyList()
ProxyService.clearLogs()
}
// ── Custom kernel ──────────────────────────────────────────────────────
@@ -475,8 +480,31 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
ProxyService.addLog("Кастомное ядро удалено, используется встроенное")
}
fun resetAllSettings(context: Context) {
viewModelScope.launch {
if (ProxyService.isRunning.value) {
context.stopService(Intent(context, ProxyService::class.java))
}
prefs.resetAll()
activeSshConfig = null
_sshState.value = SshConnectionState.Disconnected
_serverState.value = ServerState.Unknown
_serverVersion.value = null
_serverLogs.value = null
_sshLog.value = emptyList()
sshLogBuffer.clear()
_proxyState.value = ProxyState.Idle
_customKernelExists.value = false
ProxyService.clearLogs()
val intent = (context as? android.app.Activity)?.intent
?: Intent(context, com.freeturn.app.MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
context.startActivity(intent)
}
}
override fun onCleared() {
super.onCleared()
sshManager.disconnect()
}
}