1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
package com.vauth.foxyvpn.ui.screens
import com.vauth.foxyvpn.ui.l10n.s
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Public
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateMap
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.vauth.foxyvpn.data.ProxyStateStore
import com.vauth.foxyvpn.data.RECOMMENDED_COUNTRY_CODE
import com.vauth.foxyvpn.data.ServerListClient
import com.vauth.foxyvpn.data.SettingsStore
import com.vauth.foxyvpn.data.model.ProxyCandidate
import com.vauth.foxyvpn.data.model.VpnCountry
import com.vauth.foxyvpn.data.model.emojiFlag
import com.vauth.foxyvpn.ui.theme.AppearanceController
import com.vauth.foxyvpn.vpn.PingUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
private sealed class LocationRow {
data class RecommendedRow(val country: VpnCountry) : LocationRow()
data class CountryHeader(val country: VpnCountry) : LocationRow()
data class CityRow(val country: VpnCountry, val cityIndex: Int) : LocationRow()
}
private enum class PingState { PENDING, DONE, FAILED }
@Composable
fun ServerListScreen(
serverListClient: ServerListClient,
proxyStateStore: ProxyStateStore,
settingsStore: SettingsStore,
appearance: AppearanceController,
onServerSelected: () -> Unit,
onBack: () -> Unit,
) {
var countries by remember { mutableStateOf<List<VpnCountry>>(emptyList()) }
var isLoading by remember { mutableStateOf(true) }
var errorMessage by remember { mutableStateOf<String?>(null) }
val selectedState by proxyStateStore.selectedProxyFlow.collectAsState()
val pingResults = remember { mutableStateMapOf<String, Int>() }
val pingStates = remember { mutableStateMapOf<String, PingState>() }
LaunchedEffect(Unit) {
val cached = withContext(Dispatchers.IO) { serverListClient.loadCachedCountries() }
if (cached.isNotEmpty()) {
countries = cached
isLoading = false
}
runCatching { serverListClient.fetchCountries() }
.onSuccess { fresh ->
countries = fresh
errorMessage = null
}
.onFailure {
if (countries.isEmpty()) {
errorMessage = it.message ?: "Failed to load server list"
}
}
isLoading = false
}
val ordered = remember(countries) {
countries.sortedWith(compareBy({ it.code != RECOMMENDED_COUNTRY_CODE }, { it.name }))
}
val rows = remember(ordered) {
buildList {
for (country in ordered) {
if (country.code == RECOMMENDED_COUNTRY_CODE) {
add(LocationRow.RecommendedRow(country))
continue
}
add(LocationRow.CountryHeader(country))
country.cities.indices.forEach { index -> add(LocationRow.CityRow(country, index)) }
}
}
}
Scaffold(
topBar = {
TopAppBar(
title = { Text(s("Choose location")) },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
}
},
)
},
) { padding ->
Box(Modifier.fillMaxSize().padding(padding)) {
when {
isLoading -> CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
errorMessage != null && countries.isEmpty() -> Text(
text = errorMessage.orEmpty(),
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.error,
modifier = Modifier
.align(Alignment.Center)
.fillMaxWidth()
.padding(24.dp),
)
else -> {
if (appearance.doubleColumnDisplay) {
LocationGrid(
rows = rows,
countries = countries,
selectedState = selectedState,
showPing = appearance.showServerPing,
showUsage = appearance.showServerUsage,
monospace = appearance.monospaceAddress,
pingResults = pingResults,
pingStates = pingStates,
proxyStateStore = proxyStateStore,
onError = { errorMessage = it },
onServerSelected = onServerSelected,
)
} else {
LazyColumn {
items(
rows,
key = { row ->
when (row) {
is LocationRow.RecommendedRow -> "recommended:${row.country.code}"
is LocationRow.CountryHeader -> "country:${row.country.code}"
is LocationRow.CityRow ->
"city:${row.country.code}:${row.country.cities[row.cityIndex].code}"
}
},
) { row ->
val selected = selectedState
when (row) {
is LocationRow.RecommendedRow -> ListItem(
leadingContent = {
Icon(Icons.Filled.Public, contentDescription = null)
},
headlineContent = { Text(s("Recommended"), fontWeight = FontWeight.SemiBold) },
supportingContent = { Text(s("Automatically chosen for the best performance")) },
trailingContent = {
if (row.country.code == selected?.countryCode) {
Icon(Icons.Filled.CheckCircle, contentDescription = "Selected")
}
},
modifier = Modifier
.padding(horizontal = 8.dp)
.clickable {
val candidates = ServerListClient.candidatesForCountry(countries, row.country.code)
val chosen = candidates.randomOrNull()
if (chosen != null) {
proxyStateStore.save(chosen)
onServerSelected()
} else {
errorMessage = "No available servers for ${row.country.name}"
}
},
)
is LocationRow.CountryHeader -> ListItem(
leadingContent = {
Text(
text = row.country.emojiFlag,
style = MaterialTheme.typography.titleLarge,
)
},
headlineContent = { Text(row.country.name, fontWeight = FontWeight.SemiBold) },
modifier = Modifier.padding(horizontal = 8.dp),
)
is LocationRow.CityRow -> {
val city = row.country.cities[row.cityIndex]
val serverCount = city.servers.size
val pingKey = "${row.country.code}:${city.code}"
val pingMs = pingResults[pingKey]
val pingState = pingStates[pingKey] ?: PingState.PENDING
if (appearance.showServerPing) {
LaunchedEffect(pingKey) {
if (pingStates.containsKey(pingKey)) return@LaunchedEffect
val target = city.servers.firstOrNull { !it.quarantined }
?.let { ServerListClient.defaultConnectTarget(it) }
if (target == null) {
pingStates[pingKey] = PingState.FAILED
return@LaunchedEffect
}
val result = PingUtil.measureTcpLatencyMs(target.first, target.second)
if (result != null) {
pingResults[pingKey] = result
pingStates[pingKey] = PingState.DONE
} else {
pingStates[pingKey] = PingState.FAILED
}
}
}
ListItem(
headlineContent = { Text(city.code) },
supportingContent = {
val primaryHostname = city.servers.firstOrNull()?.hostname
val serverLabel = when {
primaryHostname == null -> "No servers available"
serverCount > 1 -> "$primaryHostname (+${serverCount - 1} more)"
else -> primaryHostname
}
val pingLabel = when {
!appearance.showServerPing -> null
pingMs != null -> "$pingMs ms"
pingState == PingState.FAILED -> "ping unavailable"
else -> "pinging\u2026"
}
Text(
text = if (pingLabel != null) "$serverLabel \u2022 $pingLabel" else serverLabel,
fontFamily = if (appearance.monospaceAddress) androidx.compose.ui.text.font.FontFamily.Monospace
else androidx.compose.ui.text.font.FontFamily.Default,
)
},
trailingContent = {
if (row.country.code == selected?.countryCode &&
city.code == selected?.cityCode
) {
Icon(Icons.Filled.CheckCircle, contentDescription = "Selected")
}
},
modifier = Modifier
.padding(start = 24.dp, end = 8.dp)
.clickable {
val candidates = ServerListClient.candidatesForCity(countries, row.country.code, city.code)
val chosen = candidates.randomOrNull()
if (chosen != null) {
proxyStateStore.save(chosen)
onServerSelected()
} else {
errorMessage = "No available servers in ${city.code}"
}
},
)
}
}
}
}
}
}
}
}
}
}
/** Two-column card grid for the location list (double-column display setting). */
@Composable
private fun LocationGrid(
rows: List<LocationRow>,
countries: List<VpnCountry>,
selectedState: ProxyCandidate?,
showPing: Boolean,
showUsage: Boolean,
monospace: Boolean,
pingResults: SnapshotStateMap<String, Int>,
pingStates: SnapshotStateMap<String, PingState>,
proxyStateStore: ProxyStateStore,
onError: (String) -> Unit,
onServerSelected: () -> Unit,
) {
val cs = MaterialTheme.colorScheme
LazyVerticalGrid(
columns = GridCells.Fixed(2),
contentPadding = PaddingValues(12.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
items(
rows,
key = { row ->
when (row) {
is LocationRow.RecommendedRow -> "recommended:${row.country.code}"
is LocationRow.CountryHeader -> "country:${row.country.code}"
is LocationRow.CityRow ->
"city:${row.country.code}:${row.country.cities[row.cityIndex].code}"
}
},
span = { row ->
when (row) {
is LocationRow.CityRow -> GridItemSpan(1)
else -> GridItemSpan(2)
}
},
) { row ->
when (row) {
is LocationRow.RecommendedRow -> {
Surface(
shape = RoundedCornerShape(20.dp),
color = cs.primaryContainer,
modifier = Modifier
.fillMaxWidth()
.clickable {
val candidates = ServerListClient.candidatesForCountry(countries, row.country.code)
val chosen = candidates.randomOrNull()
if (chosen != null) {
proxyStateStore.save(chosen)
onServerSelected()
} else {
onError("No available servers for ${row.country.name}")
}
},
) {
Row(
Modifier.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(Icons.Filled.Public, contentDescription = null, tint = cs.onPrimaryContainer)
Spacer(Modifier.size(12.dp))
Column(Modifier.weight(1f)) {
Text(s("Recommended"), fontWeight = FontWeight.SemiBold, color = cs.onPrimaryContainer)
Text(
"Best performance",
style = MaterialTheme.typography.bodySmall,
color = cs.onPrimaryContainer.copy(alpha = 0.75f),
)
}
if (row.country.code == selectedState?.countryCode) {
Icon(Icons.Filled.CheckCircle, contentDescription = "Selected", tint = cs.onPrimaryContainer)
}
}
}
}
is LocationRow.CountryHeader -> {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp, bottom = 2.dp),
) {
Text(row.country.emojiFlag, style = MaterialTheme.typography.titleMedium)
Spacer(Modifier.size(8.dp))
Text(row.country.name, fontWeight = FontWeight.SemiBold)
}
}
is LocationRow.CityRow -> {
val city = row.country.cities[row.cityIndex]
val pingKey = "${row.country.code}:${city.code}"
val pingMs = pingResults[pingKey]
val pingState = pingStates[pingKey] ?: PingState.PENDING
val isSelected = row.country.code == selectedState?.countryCode &&
city.code == selectedState?.cityCode
if (showPing) {
LaunchedEffect(pingKey) {
if (pingStates.containsKey(pingKey)) return@LaunchedEffect
val target = city.servers.firstOrNull { !it.quarantined }
?.let { ServerListClient.defaultConnectTarget(it) }
if (target == null) {
pingStates[pingKey] = PingState.FAILED
return@LaunchedEffect
}
val result = PingUtil.measureTcpLatencyMs(target.first, target.second)
if (result != null) {
pingResults[pingKey] = result
pingStates[pingKey] = PingState.DONE
} else {
pingStates[pingKey] = PingState.FAILED
}
}
}
Surface(
shape = RoundedCornerShape(20.dp),
color = if (isSelected) cs.primaryContainer else cs.surfaceContainerHigh,
border = if (isSelected) androidx.compose.foundation.BorderStroke(2.dp, cs.primary) else null,
modifier = Modifier.clickable {
val candidates = ServerListClient.candidatesForCity(countries, row.country.code, city.code)
val chosen = candidates.randomOrNull()
if (chosen != null) {
proxyStateStore.save(chosen)
onServerSelected()
} else {
onError("No available servers in ${city.code}")
}
},
) {
Column(Modifier.padding(14.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
city.code,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
if (isSelected) {
Icon(
Icons.Filled.CheckCircle,
contentDescription = "Selected",
tint = cs.primary,
modifier = Modifier.size(18.dp),
)
}
}
if (showUsage) {
Spacer(Modifier.height(4.dp))
Text(
text = "${city.servers.size} server(s)",
style = MaterialTheme.typography.labelSmall,
color = cs.onSurfaceVariant,
)
}
Spacer(Modifier.height(4.dp))
Text(
text = city.servers.firstOrNull()?.hostname ?: "No servers",
style = MaterialTheme.typography.bodySmall.copy(
fontFamily = if (monospace) FontFamily.Monospace else FontFamily.Default,
),
color = cs.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (showPing) {
Spacer(Modifier.height(4.dp))
Text(
text = when {
pingMs != null -> "$pingMs ms"
pingState == PingState.FAILED -> "ping unavailable"
else -> "pinging…"
},
style = MaterialTheme.typography.labelSmall,
color = cs.onSurfaceVariant,
)
}
}
}
}
}
}
}
}