Compare commits

...
Author SHA1 Message Date
atsunatsu a082abb72c build: bump version to 4.4.7-ba7opf.15.7 (504) 2026-09-24 11:11:31 +08:00
atsunatsu a2e41a0c1a fix: don't crash the AMSAT list update on unknown satellite names
resolvePerName crashed with NoSuchElementException (all.first()) when an
AMSAT live-page name had no matching local entry (TEVEL2-1..9, RS95S, any
brand-new sat not yet in the local TLE). The exception was swallowed by
updateAmSatLiveLists' runCatching, so the FM/Linear lists were NEVER
rewritten — they stayed at the stale pre-whitelist snapshot containing
all five ISS modules, which is why ISS kept showing as DESTINY despite the
15.4/15.5/15.6 disambiguation fixes.

Fix: return an empty set for names with no local match (correct skip
semantics) so the rest of the page still resolves and the ISS module
collapse runs. Regression test covers the real AMSAT page mix (ISS +
unknown names).
2026-09-24 11:11:04 +08:00
atsunatsu e1daf70f11 build: bump version to 4.4.7-ba7opf.15.6 (503) 2026-09-24 10:48:46 +08:00
atsunatsu ca9f93c1ed fix: persist All source type ids so the All filter shows satellites
Root cause of "All filter is empty": 'All' is a real TLE source type
(CelesTrak active group) in satelliteDataUrls, but setSatelliteTypeIds
had an upstream-legacy 'if (type == "All") return' that silently dropped
its ids on every sync. Selecting 'All' in the type dialog then resolved
to an empty catnum set -> empty list, while entries stayed populated
(which is why satellite counts looked normal).

Also fix getTypesList: removeAt(0) removed the alphabetically-first real
source ('ARISS') instead of the intended placeholder; now excludes only
'Other' (empty URL), so all real source types incl. 'All'/'ARISS' are
selectable.

Tests: remote update persists All ids; All type resolves to persisted
CelesTrak active ids; getTypesList excludes only Other.
2026-09-24 10:48:22 +08:00
atsunatsu 42bd55e180 build: bump version to 4.4.7-ba7opf.15.5 (502) 2026-09-24 09:40:56 +08:00
atsunatsu 7401e1451b fix: re-resolve AMSAT virtual types after sync; clean stale FM lists
Two independent defects kept ISS (DESTINY) visible in the satellite-page
AMSAT Live FM filter even after installing the fix and syncing data:

1. UI-layer staleness (SelectionRepo): resolveTypeIds ran only when the
   filter type changed and snapshotted the catnum set. A background data
   sync rewriting the FM/Linear lists never re-triggered resolution, so
   the UI kept filtering with the pre-sync (dirty) set until restart or a
   type toggle. ISettingsRepo now exposes a monotonic amSatListsVersion
   StateFlow, bumped by SettingsRepo.setAmSatCatnums; SelectionRepo
   combines it with currentTypes so every rewrite re-resolves instantly.

2. Data-layer staleness (DatabaseRepo): when the AMSAT FM page fetch
   failed, the previous list was kept verbatim — including pre-whitelist
   era lists containing all five ISS module entries. The stale list is now
   re-disambiguated: previous catnums are looked up by local name and run
   through the same whitelist / smallest-catnum collapse, so ISS modules
   always collapse to the primary ZARYA (25544).
2026-09-24 09:40:42 +08:00
atsunatsu fa51fb2b44 build: bump version to 4.4.7-ba7opf.15.4 (501) 2026-09-24 09:17:55 +08:00
atsunatsu 75a251eb98 fix: keep last good AMSAT live lists on fetch failures; whitelist mirror
- Failed whitelist fetch (raw.githubusercontent.com unreachable on some
  networks) no longer wipes the persisted whitelist or admits every ISS
  module alias: fall back to the persisted whitelist, and only persist
  when a stream was actually fetched.
- Multi-match collapse without any whitelist now keeps the primary entry
  (smallest catnum, ISS ZARYA=25544) instead of every alias (DESTINY etc.).
- Failed FM/Linear page fetch keeps the previous lists instead of
  clearing the filters.
- Amateur whitelist gets a jsDelivr CDN mirror as fallback source.
2026-09-24 09:17:17 +08:00
atsunatsu 91b5269740 build: bump version to 4.4.7-ba7opf.15.3 (500) 2026-09-24 08:49:53 +08:00
atsunatsu 522cac25e8 fix: correct AMSAT live filter satellite lists
- Resolve ISS station modules (ZARYA/UNITY/ZVEZDA/DESTINY/NAUKA) to the
  primary 25544 instead of whichever module appears first in the TLE source
- Match OSCAR designators to local names spelled 'OSCAR N'/'AMSAT-OSCAR N'
  (AO-7 -> OSCAR 7) so Linear lists keep AO-7 on SatNOGS-sourced data
- SSTV virtual type now uses the transceiver service class (Amateur only)
  plus launcher-debris name exclusion, dropping retired weather birds
  (TIROS) and rocket bodies (ARIANE 6 R/B) while keeping ISS/CSS/TEIKYOSAT
- Persist the AMSAT active-frequency whitelist (palewire mirror) on sync;
  used only to disambiguate multi-match names, never as a hard filter
2026-09-24 08:49:53 +08:00
atsunatsu 732412deb2 build: bump version to 4.4.7-ba7opf.15.2 (499) 2026-09-24 02:53:53 +08:00
atsunatsu 30000a913e fix: AMSAT name matching token-based; SSTV filters to in-orbit only
- matchesAmSatName: exact token match instead of substring contains,
  so 'ISS' no longer matches AISSAT-1 and 'AO-7' no longer matches
  AO-73 (FUNCUBE-1); resolves missing ISS in FM and missing AO-7 in
  Linear lists
- resolveTypeIds: intersect SSTV catnums with current in-orbit TLE set,
  excluding retired satellites (e.g. TIROS) whose radios are tagged SSTV
- add regression tests for token matching
2026-09-24 02:53:34 +08:00
atsunatsu e7754a4c9e build: bump version to 4.4.7-ba7opf.15.1 (498) 2026-09-24 00:51:21 +08:00
atsunatsu cf1e2b99b4 fix: transponder filters - mutual exclusion and beacon-free fallback
Two correctness fixes for the FM/Linear/SSTV filters:

1. Satellite type picker: virtual transponder types (AMSAT Live FM,
   AMSAT Live Linear, Live SSTV) are now mutually exclusive with the
   regular TLE-source types - ticking a virtual type clears Amateur/
   CubeSat/etc and vice versa, so selecting 'AMSAT Live FM' no longer
   unions in hundreds of non-transponder satellites. Virtual types
   still combine with each other. Also: an empty virtual-type resolve
   now yields an empty list instead of falling back to 'show all'.

2. Mutual-match fallback: when the AMSAT lists are empty (first run /
   sync failure) the DB mode filter used downlinkMode alone, so any
   downlink-only beacon sharing a mode label was misclassified
   (ISS/IO-86 CW beacons into Linear, FO-29's FM Digitalker into FM).
   New getIdsWithModesAndUplink() requires uplinkLow IS NOT NULL,
   matching real transponders only. SSTV filter keeps the old query
   (SSTV sats are often downlink-only).

Shared virtual-type names moved to Sources.virtualTypeNames.
2026-09-24 00:51:13 +08:00
atsunatsu b295500d14 build: bump version to 4.4.7-ba7opf.15 (497) 2026-09-23 23:26:03 +08:00
atsunatsu 0163c7b217 feat: satellite page transponder/activity filters as virtual types
The satellite selection screen's 'Select satellite type' dialog now lists
three virtual types first (AMSAT Live FM, AMSAT Live Linear, Live SSTV)
before the TLE-source types. Selecting one filters the satellite list to
that transponder/activity set; multiple selections union. 'All' is kept.

- SelectionRepo.getTypesList: virtual types prepended (All preserved)
- SelectionRepo.resolveTypeIds: FM/Linear -> AMSAT catnum sets,
  Live SSTV -> mode=SSTV radios; other types via persisted IDs
- Tests: virtual-type filtering, union, clear, list-order assertion
2026-09-23 23:25:52 +08:00
atsunatsu 85a4b9cfa3 feat: mutual pass FM/Linear transponder filters (AMSAT Live source)
Mutual match page gains FM/Linear transponder-type filters. The
authoritative source is AMSAT's human-maintained Live FM/Linear
Satellites pages, fetched during data sync and stored as catnum sets;
filters resolve to those sets (falling back to DB mode filter when
empty), and unchecking both shows a prompt instead of querying.

- DataParser.parseAmSatLivePage: table rows to satellite names,
  TEVEL2-1 thru TEVEL2-9 range expansion, bracket-alias matching
- SettingsRepo: AMSAT FM/Linear catnum sets persisted in prefs
- DatabaseRepo: fetch AMSAT pages in updateFromRemote, best-effort
  (failure keeps previous list, never blocks the update)
- getIdsWithModes: AND isAlive = 1
- MutualScreen: FilterChip row inside MatchSearchCard
- Tests: parser (4) + viewmodel (3) + repo fakes
2026-09-23 23:25:37 +08:00
atsunatsu c4c4dd682d build: bump to 4.4.7-ba7opf.14.2 2026-09-23 15:54:59 +08:00
atsunatsu 62ad995aeb feat(map): multiple marked stations per grid with pin-to-top
- MarkedStation storage upgraded to an ordered list per grid
  (Map<String, List<MarkedStation>>); JSON array shape with legacy
  v14.1 single-object migration on read
- MapAction: SetMarkedStation appends (duplicate callsign ignored),
  RemoveMarkedStation deletes by callsign, PinMarkedStation moves a
  mark to the top of the list
- MaidenheadGridOverlay: red fill for any marked grid unchanged;
  first-call label mode shows the FIRST (pinned) marked callsign
- MapScreen: one row per mark (pale-yellow callsign), pin icon
  (冖 + stroke ↑, drawn in-app) left of the Marked label — shown only
  when the grid has 2+ marks; pinned row's icon grey, others pale
  yellow; delete icon per row
- New ic_pin.xml vector drawable; strings grid_mark_pin
2026-09-23 15:47:17 +08:00
atsunatsu c8fdd2e93e build: bump to 4.4.7-ba7opf.14.1 2026-09-23 15:15:47 +08:00
atsunatsu dc013f920d feat(map,mutual): uppercase callsign input; mutual match honors historical pass window
- MapScreen: mark-a-station callsign input uppercases as you type
- MutualViewModel: read passesSettings.hoursBefore, shift the mutual
  match query start to now-hoursBefore so historical passes are
  included when the main Passes page has a lookback window set;
  endTime stays at now+hoursAhead
2026-09-23 15:08:46 +08:00
atsunatsu f36a426855 build: bump to 4.4.7-ba7opf.14 2026-09-23 13:26:00 +08:00
atsunatsu 4da59bdd17 feat(map): mark a station you want to contact in unworked grids
- New MarkedStation model + ISettingsRepo/SettingsRepo persistence
  (single JSON key markedGridStations, org.json only)
- MapState/MapViewModel: markedGrids state, Set/RemoveMarkedStation
  actions; marks auto-clear once the grid becomes worked
- MaidenheadGridOverlay: red fill (alpha 90, same as green worked
  fill) for marked grids at both zoom levels; first-call label mode
  shows the marked callsign in pale yellow on red cells
- MapScreen: unworked-grid dialog gains a 'mark a station you want
  to contact' button + callsign input dialog; marked row shows red
  callsign, 'Marked' in the count column, marking date, delete icon
- i18n: values/ + values-zh/ (grid_mark_*)
2026-09-23 13:14:38 +08:00
atsunatsu b8138c948b build: bump to 4.4.7-ba7opf.13 2026-09-22 16:41:59 +08:00
atsunatsu 0e28231c4a feat(map): run the Match query before navigating to the mutual page
Tapping the grid-QSO dialog "Match" button now starts the pass query on
the map page and only navigates to the match page once it finishes, so the
page's first frame already contains the results — the time-range card at
the top and the pass curves right below, with no scroll flicker. The dialog
button shows a spinner and is disabled while calculating. A uiState
collector in MainScreen performs the actual navigation (still a push, so
the back gesture returns to the map). Failures/exceptions still navigate so
the user is never stuck on the map page.
2026-09-22 16:41:55 +08:00
atsunatsu d6bdf5ecb6 fix(mutual): keep scroll position when re-querying from the match page
queryMutualPasses() reset listScrollIndex to 0 on every query, so tapping
"query" on the match page jumped the list back to the top. Now the default
keeps the current position; the stale results stay on screen while the new
query runs (clearing them shrank the list below a screen and clamped the
position away) and are replaced when the new results arrive. New VM test
covers position + stale-results behaviour through a settled re-query.
2026-09-22 16:41:51 +08:00
atsunatsu 6962a4bfa1 fix(mutual): retry prefill scroll until it really lands
On a device the first frame of the match page only contains the station
cards and the time-range card, which can be shorter than the viewport —
scrollToItem(1) then has no scroll range and silently does nothing, and
by the time the async query results grow the list past one screen the
one-shot flag is already consumed. Retry every 100ms (up to 2s) until
firstVisibleItemIndex reaches the time-range card. Verified with a new
Robolectric test that grows the content after a delay. Bump 12.6.
2026-09-22 15:50:31 +08:00
atsunatsu 94a1a4f7b7 diagnostics(mutual): log prefill scroll path under tag Look4SatMutual
Temporary Log.d probes at prefill, list-layout gate, scroll effect entry,
scrollToItem outcome and consume, to locate why the map Match prefill
scroll does not land on the device (Robolectric covers it). Bump 12.5.
2026-09-22 15:13:47 +08:00
atsunatsu dbf2229774 chore: bump version to 4.4.7-ba7opf.12.4 (versionCode 490) 2026-09-22 14:49:32 +08:00
atsunatsu f2fc1b7b28 test(mutual): portrait-size Robolectric + NavDisplay entry scenario
Run the scroll tests at 411x891dp portrait (device-like layout) and add
a NavDisplay entryProvider scenario that composes MutualScreen the way
the app does, so the prefill scroll is exercised end-to-end.
2026-09-22 14:49:04 +08:00
atsunatsu d600836e19 fix(mutual): gate prefill scroll on real list layout (onGloballyPositioned)
On a device the Mutual entry is composed inside the NavDisplay transition;
LaunchedEffect could run before the LazyColumn is measurable and the
scrollToItem then never lands, leaving the page at the top. Only scroll
once onGloballyPositioned confirms the list has actually been laid out.
2026-09-22 14:49:00 +08:00
atsunatsu 94bffe80b0 chore: bump version to 4.4.7-ba7opf.12.3 (versionCode 489) 2026-09-22 13:13:11 +08:00
atsunatsu 4260fbb096 fix(nav): map Match prefill pushes Mutual onto the stack
The grid-QSO dialog Match button now adds Mutual on top of the Map entry
instead of clearing the stack, so the system back gesture pops back to
the map page (the page the user came from). Bottom-nav tab switches keep
their replace semantics.
2026-09-22 13:13:08 +08:00
atsunatsu 3d5b55faa3 test(mutual): Robolectric Compose UI tests for prefill scroll; bump 4.4.7-ba7opf.12.2
MutualMatchPrefillScrollTest verifies the map grid-QSO Match prefill:
time-range card lands at the top after scrollToItem, default open stays
at station inputs, and the query auto-starts with grid+24h pre-filled.
Adds Robolectric + compose ui-test-junit4 to the mutual test classpath.
2026-09-22 12:23:55 +08:00
atsunatsu 466f2f6088 fix(mutual): map Match prefill scrolls to time-range card via scrollToItem
Compose ui 1.11.x (BOM 2026.06.01) ignores the LazyListState
firstVisibleItemIndex constructor parameter - the list always starts at
item 0. Restore the scrollToItem approach (verified effective by
Robolectric Compose UI tests) and keep the auto-started query.
2026-09-22 12:23:50 +08:00
atsunatsu 14bd984327 chore: bump version to 4.4.7-ba7opf.12.1 (versionCode 487) 2026-09-22 11:05:50 +08:00
atsunatsu d5c100903b fix(mutual,passes): map Match prefill opens at time-range card; whats-new dialog scrollable
- Match prefill now positions the LazyColumn via its initial state
  (queryMutualPasses(initialScrollIndex = 1)) instead of a post-layout
  scrollToItem, so the page reliably opens with the time-range card at the
  top while the 24h query runs.
- The install-time what's new dialog text now scrolls inside a bounded box
  (max 360dp) instead of overflowing the fixed dialog frame.
2026-09-22 11:05:47 +08:00
atsunatsu 1c6388f3bc chore: bump version to 4.4.7-ba7opf.12 (versionCode 486) 2026-09-22 10:47:00 +08:00
atsunatsu 3e0874e6a8 feat(map): grid QSO dialog Match button prefills the match page
- Grid-QSO dialog gains a Match action (radio-tower icon + label) in its
  header; tapping it navigates to the match page pre-filled with the tapped
  grid as the opposite station and a 24h time range, auto-starts the query,
  and scrolls the page straight to the time-range card.
- Every grid is now tappable (previously only worked grids opened the
  dialog); unworked grids show an empty QSO list instead of a hint.
2026-09-22 10:46:56 +08:00
atsunatsu 6beaeb3e1a chore: bump version to 4.4.7-ba7opf.11.4 (versionCode 485) 2026-09-21 16:51:50 +08:00
atsunatsu 91f0cb1c56 fix(map): grid labels match first-call font size and display zoom 2026-09-21 16:51:13 +08:00
atsunatsu 3b72f8d68a fix(res): rename pass-history slider label 先前时间 to 历史过境时间 (values-zh) 2026-09-21 16:51:09 +08:00
atsunatsu 3bc2983d26 fix(passes): expire finished passes beyond history window, refresh keeps lookback 2026-09-21 16:51:06 +08:00
39 changed files with 2047 additions and 130 deletions

No files matched your search

@@ -177,6 +177,28 @@ fun MainScreen(
factory = MapFilterViewModel.factory()
)
// Map grid-QSO dialog "Match" button: pre-fill the match page for that
// grid and run the query BEFORE navigating, so the page's first frame
// already contains the results (time-range card at the top, pass curves
// right below — no scroll flicker). Navigation happens once the query
// finishes (see the collector below).
val mutualState by mutualViewModel.uiState.collectAsStateWithLifecycle()
val matchCalculating = mutualState.pendingNavigation && mutualState.isCalculating
LaunchedEffect(mutualViewModel) {
mutualViewModel.uiState.collect { state ->
if (state.pendingNavigation && !state.isCalculating) {
mutualViewModel.consumePendingNavigation()
// Push Mutual on top of the Map entry instead of replacing the
// stack (bottom-nav style): the system back gesture then pops
// back to the map page, which is the page the user came from.
if (backStack.lastOrNull() !is Screen.Mutual) {
backStack.add(Screen.Mutual)
}
}
}
}
CompositionLocalProvider(
LocalElevationThresholds provides ElevationThresholds(
low = otherSettings.lowElevation,
@@ -244,7 +266,18 @@ fun MainScreen(
)
}
entry<Screen.Map> {
MapDestination(mapFilterViewModel = mapFilterViewModel)
MapDestination(
mapFilterViewModel = mapFilterViewModel,
matchCalculating = matchCalculating,
onMatchGrid = { grid ->
// Grid-QSO dialog "Match" button: pre-fill
// the match page for that grid and start the
// query. Navigation to the match page is
// handled by the uiState collector above,
// once the query finishes.
mutualViewModel.prefillMatchFromGrid(grid)
}
)
}
entry<Screen.Mutual> {
MutualScreen(
@@ -45,9 +45,22 @@ interface Look4SatDao {
@Query("DELETE FROM entries")
suspend fun deleteEntries()
@Query("SELECT catnum FROM radios WHERE downlinkMode IN (:modes)")
@Query("SELECT catnum FROM radios WHERE downlinkMode IN (:modes) AND isAlive = 1")
suspend fun getIdsWithModes(modes: List<String>): List<Int>
/** Like [getIdsWithModes] but only matches transponder records with an uplink,
* excluding downlink-only beacons/telemetry that share the same mode label
* (e.g. CW beacons, FM voice-synthesis beacons) from FM/Linear filter fallback. */
@Query("SELECT catnum FROM radios WHERE downlinkMode IN (:modes) AND uplinkLow IS NOT NULL AND isAlive = 1")
suspend fun getIdsWithModesAndUplink(modes: List<String>): List<Int>
/** Like [getIdsWithModes] but only matches records whose service class is
* "Amateur", so the SSTV filter never matches weather birds (TIROS),
* launcher debris or other non-amateur transmitters that happen to carry
* an SSTV-labelled downlink. */
@Query("SELECT catnum FROM radios WHERE downlinkMode IN (:modes) AND service = 'Amateur' AND isAlive = 1")
suspend fun getIdsWithModesAndAmateur(modes: List<String>): List<Int>
@Query("SELECT COUNT(*) FROM radios")
suspend fun getRadiosTotal(): Int
@@ -24,7 +24,7 @@ import androidx.sqlite.db.SupportSQLiteDatabase
import com.rtbishop.look4sat.core.data.database.entity.SatEntry
import com.rtbishop.look4sat.core.data.database.entity.SatRadio
@Database(entities = [SatEntry::class, SatRadio::class], version = 2, exportSchema = false)
@Database(entities = [SatEntry::class, SatRadio::class], version = 3, exportSchema = false)
abstract class Look4SatDb : RoomDatabase() {
abstract fun look4SatDao(): Look4SatDao
}
@@ -37,3 +37,11 @@ val MIGRATION_1_2 = object : Migration(1, 2) {
db.execSQL("ALTER TABLE radios ADD COLUMN isCustom INTEGER NOT NULL DEFAULT 0")
}
}
/** Adds the transceiver service class ("Amateur" etc.), used by the SSTV virtual
* filter to tell amateur satellites apart from debris/weather/launcher stages. */
val MIGRATION_2_3 = object : Migration(2, 3) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE radios ADD COLUMN service TEXT")
}
}
@@ -33,6 +33,10 @@ data class SatRadio(
val uplinkMode: String?,
val isInverted: Boolean,
val catnum: Int?,
/** Service class from the transceiver source ("Amateur"/"Unknown" etc.).
* Used to tell amateur satellites apart from debris / weather birds
* (TIROS) / launcher stages (Ariane 6 R/B) in the SSTV virtual filter. */
val service: String? = null,
/** Set for manually imported transceivers, which remote updates must not replace. */
val isCustom: Boolean = false
)
@@ -25,6 +25,7 @@ import android.location.LocationManager
import androidx.room.Room
import com.rtbishop.look4sat.core.data.database.Look4SatDb
import com.rtbishop.look4sat.core.data.database.MIGRATION_1_2
import com.rtbishop.look4sat.core.data.database.MIGRATION_2_3
import com.rtbishop.look4sat.core.data.framework.BluetoothReporter
import com.rtbishop.look4sat.core.data.framework.Ft817Controller
import com.rtbishop.look4sat.core.data.framework.Ic705Controller
@@ -169,7 +170,7 @@ class MainContainer(private val context: Context) : IMainContainer {
private fun provideLocalSource(): ILocalSource {
val builder = Room.databaseBuilder(context, Look4SatDb::class.java, "Look4SatDBv400")
val database = builder
.addMigrations(MIGRATION_1_2)
.addMigrations(MIGRATION_1_2, MIGRATION_2_3)
.fallbackToDestructiveMigration(false)
.build()
return LocalSource(database.look4SatDao())
@@ -23,6 +23,7 @@ import com.rtbishop.look4sat.core.domain.repository.IDatabaseRepo
import com.rtbishop.look4sat.core.domain.repository.ISettingsRepo
import com.rtbishop.look4sat.core.domain.source.ILocalSource
import com.rtbishop.look4sat.core.domain.source.IRemoteSource
import com.rtbishop.look4sat.core.domain.source.NetworkResult
import com.rtbishop.look4sat.core.domain.source.Sources
import com.rtbishop.look4sat.core.domain.utility.DataParser
import kotlinx.coroutines.CoroutineDispatcher
@@ -115,12 +116,97 @@ class DatabaseRepo(
localSource.insertRadios(importedRadios)
}
if (importedEntries.isNotEmpty()) localSource.insertEntries(importedEntries)
updateAmSatLiveLists()
setUpdateSuccessful(System.currentTimeMillis())
}
/**
* Refresh the AMSAT Live FM/Linear satellite lists (transponders currently
* on the air). Best effort: any failure keeps the previous lists and never
* blocks the rest of the data update, so the mutual-match filter simply
* falls back to the last successful snapshot.
*/
private suspend fun updateAmSatLiveLists() = withContext(dispatcher) {
runCatching {
val entries = localSource.getEntriesList() // catnum -> name
val jobs = Sources.amSatLiveUrls.map { (type, url) ->
async { type to remoteSource.getNetworkStream(url) }
} + async { "Active" to fetchAmSatActiveStream() }
val results = jobs.awaitAll()
val fmNames = results.firstOrNull { it.first == "FM" }?.second?.stream
?.let { dataParser.parseAmSatLivePage(it) }.orEmpty()
val linearNames = results.firstOrNull { it.first == "Linear" }?.second?.stream
?.let { dataParser.parseAmSatLivePage(it) }.orEmpty()
// Amateur whitelist: a failed fetch yields an empty result, which
// must NOT wipe out the last good snapshot. Fall back to the
// persisted whitelist, and only persist when this fetch actually
// returned a stream.
val activeStream = results.firstOrNull { it.first == "Active" }?.second?.stream
val activeCatnums = activeStream
?.let { dataParser.parseAmSatActiveCatnums(it) }
.orEmpty()
.ifEmpty { settingsRepo.getAmSatActiveCatnums() }
if (activeStream != null) settingsRepo.setAmSatActiveCatnums(activeCatnums)
val nameToCatnum = entries.associate { it.name.uppercase() to it.catnum }
// Resolve every matching local entry per AMSAT name. A single match
// is kept as-is (so satellites absent from the amateur whitelist,
// e.g. JO-97/TO-108, are never dropped). Only when several local
// entries share the name (ISS station modules ZARYA/UNITY/ZVEZDA/
// DESTINY/NAUKA) is the whitelist used to pick the primary one.
fun resolvePerName(name: String): Set<Int> {
val keys = dataParser.normalizeAmSatName(name)
val all = nameToCatnum.filter { (localName, _) ->
dataParser.matchesAmSatName(localName, keys)
}.values.toSet()
// No local entry matches this AMSAT name (e.g. a brand-new
// satellite not yet in the local TLE, like TEVEL2/RS95S):
// skip it. Returning empty is correct — crashing here (via
// all.first()) aborted the WHOLE list update and kept the
// stale pre-whitelist FM list with all five ISS modules.
if (all.isEmpty()) return emptySet()
if (all.size <= 1) return all
val preferred = all.intersect(activeCatnums)
if (preferred.isNotEmpty()) return preferred
// Whitelist unavailable: keep only the primary entry (smallest
// catnum — ISS ZARYA=25544 is the smallest of its five module
// entries) instead of admitting every alias (DESTINY etc.).
return setOf(all.minOrNull() ?: all.first())
}
// A failed FM/Linear page fetch yields an empty list here; do NOT
// keep the stale list verbatim (it may predate the whitelist and
// still contain ISS module aliases like DESTINY). Instead re-run
// the multi-match disambiguation on the previous catnums via their
// local names, so the whitelist / smallest-catnum rules clean it.
fun cleanStaleList(previous: Set<Int>): Set<Int> =
previous.mapNotNull { catnum ->
nameToCatnum.entries.firstOrNull { it.value == catnum }?.key
}.flatMap { resolvePerName(it) }.toSet()
val fmCatnums = fmNames.flatMap { resolvePerName(it) }.toSet()
.ifEmpty { cleanStaleList(settingsRepo.getAmSatFmCatnums()) }
val linearCatnums = linearNames.flatMap { resolvePerName(it) }.toSet()
.ifEmpty { cleanStaleList(settingsRepo.getAmSatLinearCatnums()) }
settingsRepo.setAmSatCatnums(fmCatnums, linearCatnums)
println("AMSAT live lists updated: FM=${fmCatnums.size}, Linear=${linearCatnums.size}, Active=${activeCatnums.size}")
}.onFailure {
// Keep the previous lists; the mutual filter stays on the last good snapshot.
println("AMSAT live lists update failed: $it")
}
}
/** Try the amateur-whitelist sources in order and return the first
* NetworkResult that carried a stream (or null if all failed). */
private suspend fun fetchAmSatActiveStream(): NetworkResult? {
for (url in Sources.amSatActiveUrls) {
val result = remoteSource.getNetworkStream(url)
if (result.stream != null) return result
}
return null
}
override suspend fun clearAllData() = withContext(dispatcher) {
localSource.deleteEntries()
localSource.deleteRadios()
settingsRepo.setAmSatCatnums(emptySet(), emptySet())
setUpdateSuccessful(0L)
}
@@ -65,6 +65,12 @@ class SatelliteRepo(
override suspend fun getRadiosWithId(id: Int) = localStorage.getRadiosWithId(id)
override suspend fun getSatelliteIdsWithModes(modes: List<String>) = localStorage.getIdsWithModes(modes)
override suspend fun getSatelliteIdsWithModesAndUplink(modes: List<String>) = localStorage.getIdsWithModesAndUplink(modes)
override suspend fun getSatelliteIdsWithModesAndAmateur(modes: List<String>) = localStorage.getIdsWithModesAndAmateur(modes)
override suspend fun initRepository() = withContext(dispatcher) {
combine(
settingsRepo.selectedIds,
@@ -25,6 +25,7 @@ import com.rtbishop.look4sat.core.domain.source.Sources
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
@@ -43,17 +44,23 @@ class SelectionRepo(
// Resolve type IDs once when types change, then filter items reactively.
// The HashSet gives O(1) catnum lookups instead of O(n) with a List.
private val itemsWithTypes = currentTypes.flatMapLatest { types: List<String> ->
val catnumSet: Set<Int>? = if (types.isEmpty()) {
null // null = no filtering
} else {
val ids = settingsRepo.getSatelliteTypesIds(types)
if (ids.isEmpty()) null else ids.toHashSet()
// The three virtual types ("AMSAT Live FM", "AMSAT Live Linear", "Live SSTV")
// are resolved from live transponder data instead of SharedPreferences.
// The AMSAT list version counter re-triggers resolution when a background
// data sync rewrites the FM/Linear lists, so the UI reflects the new list
// without a restart or type toggle.
private val itemsWithTypes = combine(currentTypes, settingsRepo.amSatListsVersion) { types, _ -> types }
.flatMapLatest { types: List<String> ->
val catnumSet: Set<Int>? = if (types.isEmpty()) {
null // null = no filtering
} else {
val ids = resolveTypeIds(types)
if (ids.isEmpty()) emptySet() else ids.toHashSet()
}
currentItems.map { items ->
if (catnumSet == null) items else items.filter { it.catnum in catnumSet }
}
}
currentItems.map { items ->
if (catnumSet == null) items else items.filter { it.catnum in catnumSet }
}
}
private val itemsWithQuery = currentQuery.flatMapLatest { query ->
itemsWithTypes.map { items -> filterByQuery(items, query) }
@@ -61,8 +68,44 @@ class SelectionRepo(
override fun getCurrentTypes() = currentTypes.value
override fun getTypesList() = Sources.satelliteDataUrls.keys.sorted().toMutableList().apply {
removeAt(0)
/**
* Resolves a list of type names to satellite catnums. The three virtual
* transponder/activity types are resolved from live data; all other types
* come from the per-type ID lists persisted by [ISettingsRepo].
*/
private suspend fun resolveTypeIds(types: List<String>): List<Int> {
val idsSet = mutableSetOf<Int>()
types.forEach { type ->
when (type) {
Sources.virtualTypeNames[0] -> idsSet.addAll(settingsRepo.getAmSatFmCatnums())
Sources.virtualTypeNames[1] -> idsSet.addAll(settingsRepo.getAmSatLinearCatnums())
// Live SSTV: mode=SSTV transponder records whose service class
// is "Amateur", excluding launcher debris / rocket bodies
// (names ending in "R/B" or "DEB" — e.g. Ariane 6 R/B) that
// carry an amateur payload transponder but are not satellites.
Sources.virtualTypeNames[2] -> {
val sstvIds = localSource.getIdsWithModesAndAmateur(listOf("SSTV")).toSet()
val inOrbitNames = currentItems.value.associate { it.catnum to it.name }
val filtered = sstvIds.filter { catnum ->
val name = inOrbitNames[catnum]?.uppercase().orEmpty()
!name.endsWith(" R/B") && !name.endsWith(" DEB") &&
!name.endsWith("R/B") && !name.endsWith("DEB")
}
idsSet.addAll(filtered)
}
else -> idsSet.addAll(settingsRepo.getSatelliteTypesIds(listOf(type)))
}
}
return idsSet.toList()
}
override fun getTypesList() = buildList {
// 三个转发器/活动虚拟类型排在最前.
addAll(Sources.virtualTypeNames)
// 所有真实 TLE 源类型均可选(含 "All" = CelesTrak active);只排除
// "Other"(空 URL 占位,无数据)。不要用 removeAt(0) —— 字母序第一个
// 是 "All"/"ARISS" 这类真实源,删掉会让用户勾不到它们。
addAll(Sources.satelliteDataUrls.keys.sorted().filterNot { it == "Other" })
}
override suspend fun getEntriesFlow() = withContext(dispatcher) {
@@ -107,6 +107,9 @@ class SettingsRepo(
private val keySatelliteEnabled = "satelliteEnabled"
private val keyTransceiversEnabled = "transceiversEnabled"
private val keySatnogsTleSourceMigration = "satnogsTleSourceMigration"
private val keyAmSatFmCatnums = "amSatFmCatnums"
private val keyAmSatLinearCatnums = "amSatLinearCatnums"
private val keyAmSatActiveCatnums = "amSatActiveCatnums"
private val separatorComma = ","
private val separatorUrl = "\n"
private val legacyCelestrakSatnogsUrl =
@@ -269,6 +272,59 @@ class SettingsRepo(
preferences.edit { putString(keyRoamedGrids, array.toString()) }
}
// Marked stations in unworked gridsquares, persisted as a single JSON
// object: {"OL62":[{"c":call,"t":epochMs}, ...]}. Each grid holds an
// ordered list (first = pinned/top). v14.1 stored a single object per
// grid; reads transparently migrate that old shape to a one-element list.
private val keyMarkedGridStations = "markedGridStations"
override fun getMarkedGridStations(): Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>> {
val json = preferences.getString(keyMarkedGridStations, null).orEmpty()
if (json.isBlank()) return emptyMap()
return try {
val root = org.json.JSONObject(json)
val result = mutableMapOf<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>>()
for (grid in root.keys()) {
val value = root.opt(grid)
val list = when (value) {
// v14.2+ shape: JSON array of station objects.
is org.json.JSONArray -> (0 until value.length()).mapNotNull { i ->
val o = value.optJSONObject(i) ?: return@mapNotNull null
val call = o.optString("c").ifBlank { return@mapNotNull null }
com.rtbishop.look4sat.core.domain.model.MarkedStation(call = call, epochMs = o.optLong("t"))
}
// v14.1 legacy shape: a single station object per grid.
is org.json.JSONObject -> {
val call = value.optString("c").ifBlank { null }
if (call == null) emptyList()
else listOf(com.rtbishop.look4sat.core.domain.model.MarkedStation(call = call, epochMs = value.optLong("t")))
}
else -> emptyList()
}
if (list.isNotEmpty()) result[grid] = list
}
result
} catch (_: Exception) {
emptyMap()
}
}
override fun setMarkedGridStations(stations: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>>) {
val root = org.json.JSONObject()
for ((grid, list) in stations) {
val array = org.json.JSONArray()
for (station in list) {
array.put(
org.json.JSONObject()
.put("c", station.call)
.put("t", station.epochMs)
)
}
root.put(grid, array)
}
preferences.edit { putString(keyMarkedGridStations, root.toString()) }
}
// LoTW credentials (stored locally on the device only)
private val keyLoTWCall = "lotwCallsign"
private val keyLoTWPass = "lotwPassword"
@@ -442,7 +498,9 @@ class SettingsRepo(
}
override fun setSatelliteTypeIds(type: String, ids: List<Int>) {
if (type == "All") return
// "All" is a real TLE source type (CelesTrak active group) whose ids
// must be persisted like any other type — skipping it made the "All"
// filter resolve to an empty set and show nothing.
val typesString = ids.joinToString(separatorComma)
preferences.edit { putString("type$type", typesString) }
}
@@ -692,6 +750,40 @@ class SettingsRepo(
}
//endregion
//region # AMSAT live-transponder lists
private val _amSatListsVersion = MutableStateFlow(0)
override val amSatListsVersion: StateFlow<Int> = _amSatListsVersion
override fun getAmSatFmCatnums(): Set<Int> {
val raw = preferences.getString(keyAmSatFmCatnums, null) ?: return emptySet()
return raw.split(separatorComma).mapNotNull { it.toIntOrNull() }.toSet()
}
override fun getAmSatLinearCatnums(): Set<Int> {
val raw = preferences.getString(keyAmSatLinearCatnums, null) ?: return emptySet()
return raw.split(separatorComma).mapNotNull { it.toIntOrNull() }.toSet()
}
override fun setAmSatCatnums(fmCatnums: Set<Int>, linearCatnums: Set<Int>) {
preferences.edit {
putString(keyAmSatFmCatnums, fmCatnums.sorted().joinToString(separatorComma))
putString(keyAmSatLinearCatnums, linearCatnums.sorted().joinToString(separatorComma))
}
_amSatListsVersion.update { it + 1 }
}
override fun getAmSatActiveCatnums(): Set<Int> {
val raw = preferences.getString(keyAmSatActiveCatnums, null) ?: return emptySet()
return raw.split(separatorComma).mapNotNull { it.toIntOrNull() }.toSet()
}
override fun setAmSatActiveCatnums(catnums: Set<Int>) {
preferences.edit {
putString(keyAmSatActiveCatnums, catnums.sorted().joinToString(separatorComma))
}
}
//endregion
//region # Radio control settings
private val keyRadioControlEnabled = "radioControlEnabled"
private val keyRadioModel = "radioModel"
@@ -48,6 +48,8 @@ class LocalSource(private val look4SatDao: Look4SatDao) : ILocalSource {
override suspend fun deleteEntries() = look4SatDao.deleteEntries()
override suspend fun getIdsWithModes(modes: List<String>) = look4SatDao.getIdsWithModes(modes)
override suspend fun getIdsWithModesAndUplink(modes: List<String>) = look4SatDao.getIdsWithModesAndUplink(modes)
override suspend fun getIdsWithModesAndAmateur(modes: List<String>) = look4SatDao.getIdsWithModesAndAmateur(modes)
private fun FrameworkEntry.toDomain() = OrbitalData(
this.name, this.epoch, this.meanmo, this.eccn, this.incl,
@@ -83,12 +85,14 @@ class LocalSource(private val look4SatDao: Look4SatDao) : ILocalSource {
private fun DomainRadio.toFramework() = FrameworkRadio(
this.uuid, this.info, this.isAlive, this.downlinkLow, this.downlinkHigh, this.downlinkMode,
this.uplinkLow, this.uplinkHigh, this.uplinkMode, this.isInverted, this.catnum, this.isCustom
this.uplinkLow, this.uplinkHigh, this.uplinkMode, this.isInverted, this.catnum,
this.service, this.isCustom
)
private fun FrameworkRadio.toDomain() = DomainRadio(
this.uuid, this.info, this.isAlive, this.downlinkLow, this.downlinkHigh, this.downlinkMode,
this.uplinkLow, this.uplinkHigh, this.uplinkMode, this.isInverted, this.catnum, this.isCustom
this.uplinkLow, this.uplinkHigh, this.uplinkMode, this.isInverted, this.catnum,
this.service, this.isCustom
)
private fun List<DomainRadio>.toFrameworkRadios() = this.map { radio -> radio.toFramework() }
@@ -127,6 +127,29 @@ class DatabaseRepoTest {
assertEquals(listOf(98248), settingsRepo.satelliteTypeIdsByType["SatNOGS"])
}
@Test
fun `remote update persists All source type ids`() = runTest(dispatcher) {
// Regression: "All" (CelesTrak active) is a real TLE source type whose
// ids must be persisted on sync — the old `if (type == "All") return`
// silently dropped them, making the "All" filter resolve to nothing.
val allUrl = Sources.satelliteDataUrls.getValue("All")
val localSource = FakeLocalSource()
val remoteSource = FakeRemoteSource().apply {
networkStreams[allUrl] = { validCsvStream() }
}
val settingsRepo = FakeSettingsRepo(
dataSources = DataSourcesSettings(
satelliteUrls = listOf(allUrl),
transceiversUrls = emptyList()
)
)
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
repository.updateFromRemote()
assertEquals(listOf(25544), settingsRepo.satelliteTypeIdsByType["All"])
}
private fun validCsvStream(): InputStream = """
OBJECT_NAME,OBJECT_ID,EPOCH,MEAN_MOTION,ECCENTRICITY,INCLINATION,RA_OF_ASC_NODE,ARG_OF_PERICENTER,MEAN_ANOMALY,EPHEMERIS_TYPE,CLASSIFICATION_TYPE,NORAD_CAT_ID,ELEMENT_SET_NO,REV_AT_EPOCH,BSTAR,MEAN_MOTION_DOT,MEAN_MOTION_DDOT
ISS (ZARYA),1998-067A,2021-11-16T12:28:09.322176,15.48582035,.0004694,51.6447,309.4881,203.6966,299.8876,0,U,25544,999,31220,.31985E-4,.1288E-4,0
@@ -143,6 +166,139 @@ class DatabaseRepoTest {
1 98248U 26237.16675926 .00015724 00000-0 97477-3 0 00013
2 98248 097.5373 310.9694 0011309 278.1232 340.7230 15.09766181000012
""".trimIndent().byteInputStream()
@Test
fun `amsat fm list disambiguates ISS modules via persisted whitelist when active csv fetch fails`() =
runTest(dispatcher) {
val satnogsUrl = Sources.satelliteDataUrls.getValue("SatNOGS")
val localSource = FakeLocalSource()
val remoteSource = FakeRemoteSource().apply {
networkStreams[satnogsUrl] = { issModulesCsvStream() }
networkStreams[Sources.amSatLiveUrls.getValue("FM")] = { amsatFmPageStream() }
// Amateur-whitelist URLs intentionally NOT registered -> fetch fails.
}
val settingsRepo = FakeSettingsRepo(
dataSources = DataSourcesSettings(
satelliteUrls = listOf(satnogsUrl),
transceiversUrls = emptyList()
)
).apply { amSatActive = setOf(25544) } // whitelist persisted by an earlier good sync
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
repository.updateFromRemote()
// Whitelist fetch fails on both sources, but the persisted whitelist
// still disambiguates: only primary ISS (ZARYA) survives,
// ISS (DESTINY) = 26700 must NOT enter the FM list.
assertTrue(25544 in settingsRepo.amSatFm)
assertTrue(26700 !in settingsRepo.amSatFm)
}
@Test
fun `amsat fm list keeps only smallest catnum when whitelist never available`() = runTest(dispatcher) {
val satnogsUrl = Sources.satelliteDataUrls.getValue("SatNOGS")
val localSource = FakeLocalSource()
val remoteSource = FakeRemoteSource().apply {
networkStreams[satnogsUrl] = { issModulesCsvStream() }
networkStreams[Sources.amSatLiveUrls.getValue("FM")] = { amsatFmPageStream() }
}
val settingsRepo = FakeSettingsRepo(
dataSources = DataSourcesSettings(
satelliteUrls = listOf(satnogsUrl),
transceiversUrls = emptyList()
)
) // no persisted whitelist at all
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
repository.updateFromRemote()
// Without any whitelist, the multi-match collapse keeps the primary
// entry (smallest catnum = ISS ZARYA 25544), never every module alias.
assertEquals(setOf(25544), settingsRepo.amSatFm)
}
@Test
fun `amsat fm list cleans stale ISS module aliases when fm page fetch fails`() = runTest(dispatcher) {
val satnogsUrl = Sources.satelliteDataUrls.getValue("SatNOGS")
val localSource = FakeLocalSource()
val remoteSource = FakeRemoteSource().apply {
networkStreams[satnogsUrl] = { issModulesCsvStream() }
// FM page NOT registered -> 404 -> empty parse.
}
val settingsRepo = FakeSettingsRepo(
dataSources = DataSourcesSettings(
satelliteUrls = listOf(satnogsUrl),
transceiversUrls = emptyList()
)
).apply {
// Pre-whitelist era stale list: ALL five ISS module entries.
amSatFm = setOf(25544, 25575, 26400, 26700, 49044)
}
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
repository.updateFromRemote()
// The stale list is not kept verbatim: with the FM page down, the
// previous catnums are re-disambiguated via local names, collapsing
// the five ISS modules to the primary ZARYA (25544).
assertEquals(setOf(25544), settingsRepo.amSatFm)
}
@Test
fun `amsat fm list survives unknown satellite names and still disambiguates ISS`() = runTest(dispatcher) {
// Regression: AMSAT pages list satellites absent from the local TLE
// (TEVEL2-1..9, RS95S). resolvePerName used to crash on the empty
// match set (all.first()), aborting the WHOLE list update and keeping
// the stale pre-whitelist FM list with all five ISS modules.
val satnogsUrl = Sources.satelliteDataUrls.getValue("SatNOGS")
val localSource = FakeLocalSource()
val remoteSource = FakeRemoteSource().apply {
networkStreams[satnogsUrl] = { issModulesCsvStream() }
networkStreams[Sources.amSatLiveUrls.getValue("FM")] = { amsatFmPageWithUnknownStream() }
}
val settingsRepo = FakeSettingsRepo(
dataSources = DataSourcesSettings(
satelliteUrls = listOf(satnogsUrl),
transceiversUrls = emptyList()
)
).apply { amSatActive = setOf(25544) }
val repository = DatabaseRepo(dispatcher, dataParser, localSource, remoteSource, settingsRepo)
repository.updateFromRemote()
// No crash; ISS still collapses to the primary ZARYA (25544).
assertEquals(setOf(25544), settingsRepo.amSatFm)
}
private fun amsatFmPageWithUnknownStream(): InputStream = """
<table>
<thead><tr><th>Satellite</th><th>Uplink</th><th>Downlink</th><th>Comment</th></tr></thead>
<tbody>
<tr><td>ISS</td><td>145.990 MHz</td><td>437.800 MHz</td><td></td></tr>
<tr><td>TEVEL2-1 thru TEVEL2-9</td><td>145.970 MHz</td><td>436.400 MHz</td><td></td></tr>
<tr><td>RS95S(QMR-KWT-2)</td><td>145.920 MHz</td><td>436.950 MHz</td><td></td></tr>
</tbody>
</table>
""".trimIndent().byteInputStream()
private fun issModulesCsvStream(): InputStream = """
OBJECT_NAME,OBJECT_ID,EPOCH,MEAN_MOTION,ECCENTRICITY,INCLINATION,RA_OF_ASC_NODE,ARG_OF_PERICENTER,MEAN_ANOMALY,EPHEMERIS_TYPE,CLASSIFICATION_TYPE,NORAD_CAT_ID,ELEMENT_SET_NO,REV_AT_EPOCH,BSTAR,MEAN_MOTION_DOT,MEAN_MOTION_DDOT
ISS (ZARYA),1998-067A,2021-11-16T12:28:09.322176,15.48582035,.0004694,51.6447,309.4881,203.6966,299.8876,0,U,25544,999,31220,.31985E-4,.1288E-4,0
ISS (UNITY),1998-067B,2021-11-16T12:28:09.322176,15.48582035,.0004694,51.6447,309.4881,203.6966,299.8876,0,U,25575,999,31220,.31985E-4,.1288E-4,0
ISS (ZVEZDA),1998-067C,2021-11-16T12:28:09.322176,15.48582035,.0004694,51.6447,309.4881,203.6966,299.8876,0,U,26400,999,31220,.31985E-4,.1288E-4,0
ISS (DESTINY),1998-067D,2021-11-16T12:28:09.322176,15.48582035,.0004694,51.6447,309.4881,203.6966,299.8876,0,U,26700,999,31220,.31985E-4,.1288E-4,0
ISS (NAUKA),1998-067E,2021-11-16T12:28:09.322176,15.48582035,.0004694,51.6447,309.4881,203.6966,299.8876,0,U,49044,999,31220,.31985E-4,.1288E-4,0
""".trimIndent().byteInputStream()
private fun amsatFmPageStream(): InputStream = """
<table class="has-background">
<thead><tr><th>Satellite</th><th>Uplink</th><th>Downlink</th><th>Comment</th></tr></thead>
<tbody>
<tr><td>ISS</td><td>145.990 MHz</td><td>437.800 MHz</td><td></td></tr>
<tr><td>AO-91(RadFxSat / Fox-1B)</td><td>435.250 MHz</td><td>145.960 MHz</td><td></td></tr>
</tbody>
</table>
""".trimIndent().byteInputStream()
}
private class FakeRemoteSource : IRemoteSource {
@@ -167,7 +323,8 @@ private class FakeLocalSource : ILocalSource {
override suspend fun getEntriesTotal(): Int = insertedEntries.size
override suspend fun getEntriesList(): List<SatItem> = emptyList()
override suspend fun getEntriesList(): List<SatItem> =
insertedEntries.map { SatItem(it.catnum, it.name) }
override suspend fun getEntriesWithIds(ids: List<Int>): List<OrbitalObject> = emptyList()
@@ -180,6 +337,8 @@ private class FakeLocalSource : ILocalSource {
}
override suspend fun getIdsWithModes(modes: List<String>): List<Int> = emptyList()
override suspend fun getIdsWithModesAndUplink(modes: List<String>): List<Int> = emptyList()
override suspend fun getIdsWithModesAndAmateur(modes: List<String>): List<Int> = emptyList()
override suspend fun getRadiosTotal(): Int = insertedRadios.size
@@ -269,6 +428,22 @@ private class FakeSettingsRepo(dataSources: DataSourcesSettings = defaultDataSou
(dataSourcesStatus as? MutableStateFlow)?.value = status
}
var amSatFm: Set<Int> = emptySet()
var amSatLinear: Set<Int> = emptySet()
var amSatActive: Set<Int> = emptySet()
override val amSatListsVersion: StateFlow<Int> = MutableStateFlow(0)
override fun getAmSatFmCatnums(): Set<Int> = amSatFm
override fun getAmSatLinearCatnums(): Set<Int> = amSatLinear
override fun setAmSatCatnums(fmCatnums: Set<Int>, linearCatnums: Set<Int>) {
amSatFm = fmCatnums
amSatLinear = linearCatnums
}
override fun getAmSatActiveCatnums(): Set<Int> = amSatActive
override fun setAmSatActiveCatnums(catnums: Set<Int>) {
amSatActive = catnums
}
override fun updateRadioControlSettings(settings: RadioControlSettings) = Unit
override fun getSatelliteOffset(catnum: Int): String = ""
@@ -312,6 +487,10 @@ private class FakeSettingsRepo(dataSources: DataSourcesSettings = defaultDataSou
override fun setRoamedGrids(grids: Set<String>) {
roamedGrids.value = grids
}
override fun getMarkedGridStations(): Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>> = emptyMap()
override fun setMarkedGridStations(stations: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>>) = Unit
}
private fun defaultDataSourcesSettings(): DataSourcesSettings {
@@ -112,22 +112,200 @@ class SelectionRepoSearchTest {
assertTrue(repo.getEntriesFlow().first().isEmpty())
}
private fun createRepo(items: List<SatItem>): ISelectionRepo {
return SelectionRepo(
@Test
fun `FM virtual type shows only AMSAT FM list satellites`() = runTest {
val repo = createRepo(
items = sampleItems,
amSatFm = setOf(25544, 39444)
)
repo.setTypes(listOf("AMSAT Live FM"))
val results = repo.getEntriesFlow().first()
assertEquals(listOf(25544, 39444), results.map { it.catnum })
}
@Test
fun `SSTV virtual type shows only satellites with SSTV radios`() = runTest {
val repo = createRepo(
items = sampleItems,
sstvIds = listOf(43803)
)
repo.setTypes(listOf("Live SSTV"))
val results = repo.getEntriesFlow().first()
assertEquals(listOf(43803), results.map { it.catnum })
}
@Test
fun `SSTV virtual type uses the amateur-only radio query`() = runTest {
// The repo delegates to getIdsWithModesAndAmateur: the fake returns
// only catnums the DAO would have filtered to Amateur service (43803).
val repo = createRepo(
items = sampleItems,
sstvIds = listOf(43803),
amSatActive = setOf(43803)
)
repo.setTypes(listOf("Live SSTV"))
val results = repo.getEntriesFlow().first()
assertEquals(listOf(43803), results.map { it.catnum })
}
@Test
fun `SSTV virtual type excludes rocket-body debris by name`() = runTest {
// 60239 is "ARIANE 6 R/B" (launcher debris carrying an amateur SSTV
// payload); it must be dropped even though its radio is Amateur.
val items = sampleItems + SatItem(catnum = 60239, name = "ARIANE 6 R/B")
val repo = createRepo(
items = items,
sstvIds = listOf(43803, 60239),
amSatActive = setOf(43803, 60239)
)
repo.setTypes(listOf("Live SSTV"))
val results = repo.getEntriesFlow().first()
assertEquals(listOf(43803), results.map { it.catnum })
}
@Test
fun `multiple virtual types union their satellites`() = runTest {
val repo = createRepo(
items = sampleItems,
amSatFm = setOf(25544),
amSatLinear = setOf(7530),
sstvIds = listOf(43803)
)
repo.setTypes(listOf("AMSAT Live FM", "Live SSTV"))
val results = repo.getEntriesFlow().first()
assertEquals(setOf(25544, 43803), results.map { it.catnum }.toSet())
}
@Test
fun `clearing types restores full list`() = runTest {
val repo = createRepo(items = sampleItems, amSatFm = setOf(25544))
repo.setTypes(listOf("AMSAT Live FM"))
assertTrue(repo.getEntriesFlow().first().isNotEmpty())
repo.setTypes(emptyList())
assertEquals(sampleItems.size, repo.getEntriesFlow().first().size)
}
@Test
fun `virtual type with empty AMSAT list shows empty not everything`() = runTest {
// 根因2回归: AMSAT 清单未同步(空)时, 选虚拟类型应显示空列表, 而非全部卫星.
val repo = createRepo(items = sampleItems, amSatFm = emptySet())
repo.setTypes(listOf("AMSAT Live FM"))
assertTrue(repo.getEntriesFlow().first().isEmpty())
}
@Test
fun `virtual type combined with regular type unions both lists`() = runTest {
val repo = createRepo(
items = sampleItems,
amSatFm = setOf(25544),
amSatLinear = setOf(7530)
)
repo.setTypes(listOf("AMSAT Live FM", "AMSAT Live Linear"))
val results = repo.getEntriesFlow().first()
assertEquals(setOf(25544, 7530), results.map { it.catnum }.toSet())
}
@Test
fun `types list has virtual transponder types first and keeps All`() {
val repo = createRepo(sampleItems)
val types = repo.getTypesList()
assertTrue(types.size >= 4)
assertEquals("AMSAT Live FM", types[0])
assertEquals("AMSAT Live Linear", types[1])
assertEquals("Live SSTV", types[2])
// "All" must be kept in the list (first original type shown after virtual ones).
assertTrue("All" in types)
}
@Test
fun `All type resolves to persisted CelesTrak active ids`() = runTest {
// Regression: "All" is a real TLE source type (CelesTrak active). Its
// ids are persisted on sync like any other type; selecting it must
// show the synced satellites, NOT an empty list.
val fake = FakeSettingsRepoForSearch()
fake.setSatelliteTypeIds("All", sampleItems.map { it.catnum })
val repo = SelectionRepo(
dispatcher = Dispatchers.Unconfined,
localSource = FakeLocalSourceForSearch(sampleItems),
settingsRepo = fake
)
repo.setTypes(listOf("All"))
val results = repo.getEntriesFlow().first()
assertEquals(sampleItems.map { it.catnum }.toSet(), results.map { it.catnum }.toSet())
}
@Test
fun `getTypesList excludes only the Other placeholder`() = runTest {
val repo = createRepo(sampleItems)
val types = repo.getTypesList()
// All real TLE source types must be selectable, including "All"
// (CelesTrak active) and "ARISS" (removed by the old removeAt(0)).
assertTrue("All" in types)
assertTrue("ARISS" in types)
assertTrue("R4UAB" in types)
assertTrue("SatNOGS" in types)
assertTrue("Other" !in types)
}
@Test
fun `all types shows all items`() = runTest {
val repo = createRepo(sampleItems)
repo.setTypes(emptyList()) // "All" = no type filtering
val results = repo.getEntriesFlow().first()
assertEquals(sampleItems.size, results.size)
assertEquals(sampleItems.map { it.catnum }.toSet(), results.map { it.catnum }.toSet())
}
@Test
fun `amsat list version bump re-resolves FM filter after data sync`() = runTest {
// ISS module aliases: dirty pre-sync FM list contains both ZARYA and DESTINY.
val items = listOf(
SatItem(25544, "ISS (ZARYA)"),
SatItem(26700, "ISS (DESTINY)")
)
val fake = FakeSettingsRepoForSearch(amSatFm = setOf(25544, 26700))
val repo = SelectionRepo(
dispatcher = Dispatchers.Unconfined,
localSource = FakeLocalSourceForSearch(items),
settingsRepo = FakeSettingsRepoForSearch()
settingsRepo = fake
)
repo.setTypes(listOf("AMSAT Live FM"))
assertEquals(setOf(25544, 26700), repo.getEntriesFlow().first().map { it.catnum }.toSet())
// Simulate a background data sync: lists rewritten + version bumped.
fake.setAmSatCatnums(fmCatnums = setOf(25544), linearCatnums = emptySet())
// The FM filter must reflect the new list WITHOUT a type toggle or restart.
assertEquals(listOf(25544), repo.getEntriesFlow().first().map { it.catnum })
}
private fun createRepo(
items: List<SatItem>,
amSatFm: Set<Int> = emptySet(),
amSatLinear: Set<Int> = emptySet(),
sstvIds: List<Int> = emptyList(),
amSatActive: Set<Int> = emptySet()
): ISelectionRepo {
return SelectionRepo(
dispatcher = Dispatchers.Unconfined,
localSource = FakeLocalSourceForSearch(items, sstvIds),
settingsRepo = FakeSettingsRepoForSearch(amSatFm, amSatLinear, amSatActive)
)
}
}
private class FakeLocalSourceForSearch(private val items: List<SatItem>) : ILocalSource {
private class FakeLocalSourceForSearch(
private val items: List<SatItem>,
private val sstvIds: List<Int> = emptyList()
) : ILocalSource {
override suspend fun getEntriesTotal(): Int = items.size
override suspend fun getEntriesList(): List<SatItem> = items
override suspend fun getEntriesWithIds(ids: List<Int>): List<OrbitalObject> = emptyList()
override suspend fun insertEntries(entries: List<OrbitalData>) = Unit
override suspend fun deleteEntries() = Unit
override suspend fun getIdsWithModes(modes: List<String>): List<Int> = emptyList()
override suspend fun getIdsWithModes(modes: List<String>): List<Int> = sstvIds
override suspend fun getIdsWithModesAndUplink(modes: List<String>): List<Int> = sstvIds
override suspend fun getIdsWithModesAndAmateur(modes: List<String>): List<Int> = sstvIds
override suspend fun getRadiosTotal(): Int = 0
override suspend fun getRadiosWithId(id: Int): List<SatRadio> = emptyList()
override suspend fun insertRadios(radios: List<SatRadio>, isCustom: Boolean) = Unit
@@ -135,7 +313,12 @@ private class FakeLocalSourceForSearch(private val items: List<SatItem>) : ILoca
override suspend fun deleteRadios() = Unit
}
private class FakeSettingsRepoForSearch : ISettingsRepo {
private class FakeSettingsRepoForSearch(
var amSatFm: Set<Int> = emptySet(),
var amSatLinear: Set<Int> = emptySet(),
private var amSatActive: Set<Int> = emptySet()
) : ISettingsRepo {
private val typeIds = mutableMapOf<String, List<Int>>()
override val appVersionName: String = "test"
override val selectedIds: StateFlow<List<Int>> = MutableStateFlow(emptyList())
override val selectedTypes: StateFlow<List<String>> = MutableStateFlow(emptyList())
@@ -170,13 +353,27 @@ private class FakeSettingsRepoForSearch : ISettingsRepo {
override fun setStationPosition(latitude: Double, longitude: Double, altitude: Double): Boolean = true
override fun setStationPosition(): Boolean = true
override fun setStationPosition(locator: String): Boolean = true
override fun getSatelliteTypesIds(types: List<String>): List<Int> = emptyList()
override fun setSatelliteTypeIds(type: String, ids: List<Int>) = Unit
override fun getSatelliteTypesIds(types: List<String>): List<Int> =
types.flatMap { typeIds[it].orEmpty() }.distinct()
override fun setSatelliteTypeIds(type: String, ids: List<Int>) {
typeIds[type] = ids
}
override fun updateDatabaseState(state: DatabaseState) = Unit
override fun updateRCSettings(settings: RCSettings) = Unit
override fun updateOtherSettings(transform: (OtherSettings) -> OtherSettings) = Unit
override fun updateDataSourcesSettings(settings: DataSourcesSettings) = Unit
override fun updateDataSourcesStatus(status: Map<String, Int>) = Unit
override fun getAmSatFmCatnums(): Set<Int> = amSatFm
override fun getAmSatLinearCatnums(): Set<Int> = amSatLinear
override val amSatListsVersion: StateFlow<Int> = MutableStateFlow(0)
override fun setAmSatCatnums(fmCatnums: Set<Int>, linearCatnums: Set<Int>) {
amSatFm = fmCatnums
amSatLinear = linearCatnums
(amSatListsVersion as MutableStateFlow<Int>).value++
}
override fun getAmSatActiveCatnums(): Set<Int> = amSatActive
override fun setAmSatActiveCatnums(catnums: Set<Int>) { amSatActive = catnums }
override fun updateRadioControlSettings(settings: RadioControlSettings) = Unit
override fun getSatelliteOffset(catnum: Int): String = ""
override fun setSatelliteOffset(catnum: Int, offset: String) = Unit
@@ -189,6 +386,8 @@ private class FakeSettingsRepoForSearch : ISettingsRepo {
override fun setWorkedGridQsos(qsos: Map<String, List<com.rtbishop.look4sat.core.domain.model.GridQso>>) = Unit
override fun getRoamedGrids(): Set<String> = emptySet()
override fun setRoamedGrids(grids: Set<String>) = Unit
override fun getMarkedGridStations(): Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>> = emptyMap()
override fun setMarkedGridStations(stations: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>>) = Unit
override fun updateLoTWSettings(settings: com.rtbishop.look4sat.core.domain.model.LoTWSettings) = Unit
override fun getLastLotwSyncDate(): String = ""
override fun setLastLotwSyncDate(date: String) = Unit
@@ -0,0 +1,31 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.model
/**
* A station the user marked in a gridsquare they have NOT yet worked — a
* reminder to try to contact that callsign. Stored per 4-char grid (one mark
* per grid).
*
* @param call the callsign the user wants to work (uppercase)
* @param epochMs the moment the mark was created, UTC milliseconds
*/
data class MarkedStation(
val call: String,
val epochMs: Long
)
@@ -33,6 +33,10 @@ data class SatRadio(
@SerialName("uplink_mode") val uplinkMode: String?,
@SerialName("invert") val isInverted: Boolean,
@SerialName("norad_cat_id") val catnum: Int?,
/** Service class from the transceiver source ("Amateur"/"Unknown" etc.).
* Used by the SSTV virtual filter to tell amateur satellites apart from
* debris / weather birds (TIROS) / launcher stages (Ariane 6 R/B). */
@SerialName("service") val service: String? = null,
/** Set for manually imported transceivers, which remote updates must not replace. */
val isCustom: Boolean = false
)
@@ -65,4 +65,19 @@ interface ISatelliteRepo {
/** Fetch radio transceivers for a satellite by its catalog number. */
suspend fun getRadiosWithId(id: Int): List<SatRadio>
/** Satellite catnums whose radios carry any of the given downlink modes.
* Empty modes -> empty result; used to filter the mutual-match satellite
* set to transponder satellites (FM voice / linear). */
suspend fun getSatelliteIdsWithModes(modes: List<String>): List<Int>
/** Like [getSatelliteIdsWithModes] but only matches records with an uplink
* (real transponders), excluding downlink-only beacons/telemetry that share
* the same mode label. Used by the FM/Linear fallback filter. */
suspend fun getSatelliteIdsWithModesAndUplink(modes: List<String>): List<Int>
/** Like [getSatelliteIdsWithModes] but only matches records whose service
* class is "Amateur", so SSTV never matches weather birds (TIROS),
* launcher debris or other non-amateur transmitters. */
suspend fun getSatelliteIdsWithModesAndAmateur(modes: List<String>): List<Int>
}
@@ -79,6 +79,23 @@ interface ISettingsRepo {
fun updateDataSourcesStatus(status: Map<String, Int>)
//endregion
//region # AMSAT live-transponder lists
/** Catalog numbers of satellites listed on AMSAT's "Live FM Satellites" page. */
fun getAmSatFmCatnums(): Set<Int>
/** Catalog numbers of satellites listed on AMSAT's "Live Linear Satellites" page. */
fun getAmSatLinearCatnums(): Set<Int>
fun setAmSatCatnums(fmCatnums: Set<Int>, linearCatnums: Set<Int>)
/** Catalog numbers of active *amateur* satellites from AMSAT's
* active-transponder table (whitelist for the virtual type filters). */
fun getAmSatActiveCatnums(): Set<Int>
fun setAmSatActiveCatnums(catnums: Set<Int>)
/** Monotonic version counter, incremented every time the AMSAT live
* FM/Linear lists are rewritten. Consumers that resolve the virtual
* types (SelectionRepo) should re-resolve on change so a background
* data sync is reflected in the UI without a restart. */
val amSatListsVersion: StateFlow<Int>
//endregion
//region # Radio control settings
val radioControlSettings: StateFlow<RadioControlSettings>
fun updateRadioControlSettings(settings: RadioControlSettings)
@@ -105,6 +122,11 @@ interface ISettingsRepo {
/** Distinct 4-char gridsquares the account operated from (LoTW <MY_GRIDSQUARE>). */
fun getRoamedGrids(): Set<String>
fun setRoamedGrids(grids: Set<String>)
/** Stations the user marked as "want to contact" in unworked gridsquares
* (grid -> ordered list of marks; the first is the pinned/top one). The
* whole grid clears automatically once it becomes worked. */
fun getMarkedGridStations(): Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>>
fun setMarkedGridStations(stations: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>>)
//endregion
//region # LoTW confirmed-grids settings
@@ -29,6 +29,8 @@ interface ILocalSource {
suspend fun insertEntries(entries: List<OrbitalData>)
suspend fun deleteEntries()
suspend fun getIdsWithModes(modes: List<String>): List<Int>
suspend fun getIdsWithModesAndUplink(modes: List<String>): List<Int>
suspend fun getIdsWithModesAndAmateur(modes: List<String>): List<Int>
suspend fun getRadiosTotal(): Int
suspend fun getRadiosWithId(id: Int): List<SatRadio>
suspend fun insertRadios(radios: List<SatRadio>, isCustom: Boolean = false)
@@ -55,4 +55,31 @@ object Sources {
"SatNOGS" to "https://db.satnogs.org/api/transmitters/?format=json&status=active",
"R4UAB" to "https://r4uab.ru/transmitters.json"
)
/** AMSAT "Live FM/Linear Satellites" pages: human-maintained lists of
* transponders currently on the air. Parsed into the mutual-match filter
* (satellites that actually carry a working FM-voice / linear repeater). */
val amSatLiveUrls = mapOf(
"FM" to "https://www.amsat.org/live-fm-satellites/",
"Linear" to "https://www.amsat.org/live-linear-satellites/"
)
/** Machine-readable AMSAT active-transponder table (palewire mirror of
* amsat.org's active-frequency pages): one CSV row per active amateur
* transponder with its NORAD catnum. Used as the authoritative whitelist
* of *amateur* satellites, so the virtual filters never match
* non-amateur debris (Ariane 6 R/B), retired weather sats (TIROS), or
* ISS station-module aliases (ISS (DESTINY) etc.). Primary source plus
* a jsDelivr CDN mirror: raw.githubusercontent.com is unreachable on
* some networks (e.g. mainland China mobile), and a failed whitelist
* fetch would silently disable the module disambiguation. */
val amSatActiveUrls = listOf(
"https://raw.githubusercontent.com/palewire/amateur-satellite-database/main/data/amsat-active-frequencies.csv",
"https://cdn.jsdelivr.net/gh/palewire/amateur-satellite-database@main/data/amsat-active-frequencies.csv"
)
/** Virtual satellite-selection types: transponder/activity filters shown
* at the top of the type picker. They resolve to live lists (AMSAT pages
* or mode=SSTV radios) instead of persisted per-type IDs, and are
* mutually exclusive with the regular TLE-source types in the picker. */
val virtualTypeNames = listOf("AMSAT Live FM", "AMSAT Live Linear", "Live SSTV")
}
@@ -40,6 +40,21 @@ class DataParser(private val dispatcher: CoroutineDispatcher) {
}
}
/** Parse AMSAT's active-transponder CSV (palewire mirror) and return the
* set of NORAD catnums of active *amateur* satellites. Header row has a
* norad_id column; some rows carry alphanumeric IDs (Bluebird A0241 etc.)
* which are skipped. */
suspend fun parseAmSatActiveCatnums(stream: InputStream): Set<Int> = withContext(dispatcher) {
stream.bufferedReader().useLines { lines ->
val header = lines.firstOrNull() ?: return@useLines emptySet()
val noradIdx = header.split(",").indexOfFirst { it.trim().equals("norad_id", true) }
if (noradIdx < 0) return@useLines emptySet()
lines.mapNotNull { line ->
line.split(",").getOrNull(noradIdx)?.trim()?.toIntOrNull()
}.toSet()
}
}
suspend fun parseTLEStream(stream: InputStream): List<OrbitalData> = withContext(dispatcher) {
stream.bufferedReader().readLines()
.chunked(3)
@@ -58,6 +73,101 @@ class DataParser(private val dispatcher: CoroutineDispatcher) {
}.getOrDefault(emptyList())
}
/**
* Parse an AMSAT "Live FM/Linear Satellites" page into satellite names.
* The page is an HTML table whose first column is the satellite name,
* sometimes written as an alias list ("AO-91(RadFxSat / Fox-1B)") or a
* range ("TEVEL2-1 thru TEVEL2-9"). Returns the distinct expanded names.
*/
suspend fun parseAmSatLivePage(stream: InputStream): List<String> = withContext(dispatcher) {
runCatching {
val html = stream.bufferedReader().readText()
// Grab table rows, take the first cell of each row, keep rows that
// look like satellite names (start with letters/digits, not a header).
val rows = Regex("<tr[^>]*>(.*?)</tr>", RegexOption.IGNORE_CASE)
.findAll(html)
.mapNotNull { match ->
val cells = Regex("<t[dh][^>]*>(.*?)</t[dh]>", RegexOption.IGNORE_CASE)
.findAll(match.groupValues[1])
.map { cell -> stripHtml(cell.groupValues[1]).trim() }
.toList()
cells.firstOrNull()?.takeIf { it.isNotBlank() && !it.equals("Satellite", ignoreCase = true) }
}
.toList()
rows.flatMap { expandNameRange(it) }.distinct()
}.getOrDefault(emptyList())
}
private fun stripHtml(raw: String): String =
raw.replace(Regex("<[^>]+>"), " ").replace(Regex("\\s+"), " ").trim()
/** Expand "NAME1 thru NAME9" ranges (e.g. TEVEL2-1 thru TEVEL2-9). */
private fun expandNameRange(name: String): List<String> {
val m = Regex("^(.*?)(\\d+)\\s+thru\\s+(.*?)(\\d+)$", RegexOption.IGNORE_CASE).find(name)
if (m == null) return listOf(name)
val prefix1 = m.groupValues[1].trim()
val startNum = m.groupValues[2].toIntOrNull() ?: return listOf(name)
val endNum = m.groupValues[4].toIntOrNull() ?: return listOf(name)
val prefix2 = m.groupValues[3].trim()
if (startNum > endNum) return listOf(name)
// Suffix after the end number, if any (e.g. "TEVEL2-1 thru TEVEL2-9 ").
val suffix = name.substringAfterLast(m.groupValues[4]).trim()
return (startNum..endNum).map { "$prefix1$it$suffix" }
}
/**
* Normalize a satellite name from the AMSAT live pages into lookup keys
* used to match against the local entries table:
* - primary key: the leading designator ("AO-91" from "AO-91 (RadFxSat / Fox-1B)")
* - alias keys: every bracketed alias, uppercased, digits preserved
* The local entry names are normalized the same way in [matchesAmSatName].
*/
fun normalizeAmSatName(name: String): List<String> {
val keys = mutableListOf<String>()
// Primary: everything before the first '(' (or '['), then the first token.
val primary = name.substringBefore('(').substringBefore('[').trim()
primary.split(Regex("\\s+")).firstOrNull()?.takeIf { it.isNotBlank() }?.let {
keys += it.uppercase()
}
// Aliases inside parentheses / brackets: "RadFxSat / Fox-1B" -> two keys.
Regex("\\(([^)]*)\\)").findAll(name).forEach { m ->
m.groupValues[1].split('/', '|').forEach { alias ->
alias.trim().takeIf { it.isNotBlank() }?.let { keys += it.uppercase() }
}
}
Regex("\\[([^]]*)]").findAll(name).forEach { m ->
m.groupValues[1].split('/', '|').forEach { alias ->
alias.trim().takeIf { it.isNotBlank() }?.let { keys += it.uppercase() }
}
}
return keys.distinct()
}
/** True if a local entry name matches any of the AMSAT normalized keys.
* Token-based exact match (split on spaces/brackets/slashes), so a key
* like "ISS" does not substring-match "AISSAT-1" — the key must equal a
* whole name token (case-insensitive). OSCAR designators are expanded so
* that "AO-7" also matches local names spelled "OSCAR 7" / "AMSAT-OSCAR 7"
* (the form used by CelesTrak/SatNOGS TLE sources). */
fun matchesAmSatName(localName: String, amSatKeys: List<String>): Boolean {
val localUpper = localName.uppercase()
val localTokens = localUpper
.split(Regex("[\\s()\\[\\]/]+"))
.filter { it.isNotBlank() }
.toSet()
return amSatKeys.any { key ->
val k = key.uppercase()
if (k in localTokens) return@any true
// "AO-7" -> also match local "OSCAR 7" or "AMSAT-OSCAR 7".
val oscar = Regex("^([A-Z]{1,3})-(\\d+)$").find(k)
if (oscar != null) {
val num = oscar.groupValues[2]
if ("OSCAR $num" in localUpper || "AMSAT-OSCAR $num" in localUpper) return@any true
}
false
}
}
private fun parseCSV(values: List<String>): OrbitalData? = runCatching {
val name = values[0]
val timestamp = values[2]
@@ -239,4 +239,60 @@ class DataParserTest {
// Matches the CSV test data epoch: 2021-11-16 → day 320
assert(dataParser.getDayOfYear(2021, 11, 16) == 320)
}
@Test
fun `AMSAT FM page parses satellite names and expands thru ranges`() = runTest(testDispatcher) {
val html = """
<html><body><table>
<tr><th>Satellite</th><th>Uplink</th><th>Downlink</th><th>Comment</th></tr>
<tr><td>AO-91(RadFxSat / Fox-1B)</td><td>435.250</td><td>145.960</td></tr>
<tr><td>SO-50(SaudiSat-1C)</td><td>145.850</td><td>436.795</td></tr>
<tr><td>TEVEL2-1 thru TEVEL2-9</td><td>145.970</td><td>436.400</td></tr>
</table></body></html>
""".trimIndent().byteInputStream()
val names = dataParser.parseAmSatLivePage(html)
assert(names.contains("AO-91(RadFxSat / Fox-1B)"))
assert(names.contains("SO-50(SaudiSat-1C)"))
assert(names.contains("TEVEL2-1"))
assert(names.contains("TEVEL2-9"))
assert(names.size == 11) // 2 singles + 9 expanded TEVEL2
}
@Test
fun `AMSAT linear page keeps mode-suffixed names`() = runTest(testDispatcher) {
val html = """
<table>
<tr><th>Satellite</th><th>Frequencies</th><th>Comment</th></tr>
<tr><td>AO-7 Mode B U/v Inverting Analog</td><td>Uplink LSB</td></tr>
<tr><td>FO-29 (JAS-2)V/u Inverting Analog</td><td>Uplink LSB</td></tr>
</table>
""".trimIndent().byteInputStream()
val names = dataParser.parseAmSatLivePage(html)
assert(names.contains("AO-7 Mode B U/v Inverting Analog"))
assert(names.contains("FO-29 (JAS-2)V/u Inverting Analog"))
}
@Test
fun `AMSAT name normalization produces primary and alias keys`() {
assert(dataParser.normalizeAmSatName("AO-91(RadFxSat / Fox-1B)") == listOf("AO-91", "RADFXSAT", "FOX-1B"))
assert(dataParser.normalizeAmSatName("QO-100 (Es'hail-2/P4A) S/x") == listOf("QO-100", "ES'HAIL-2", "P4A"))
assert(dataParser.normalizeAmSatName("ISS") == listOf("ISS"))
assert(dataParser.matchesAmSatName("AO-91 (RADFXSAT)", listOf("AO-91", "RADFXSAT")))
assert(!dataParser.matchesAmSatName("SO-50", listOf("AO-91")))
// Regression: "ISS" must not substring-match "AISSAT-1" (token match only).
assert(dataParser.matchesAmSatName("ISS (ZARYA)", listOf("ISS")))
assert(!dataParser.matchesAmSatName("AISSAT-1", listOf("ISS")))
assert(!dataParser.matchesAmSatName("TESS", listOf("ISS")))
// OSCAR designators match local names spelled "OSCAR N"/"AMSAT-OSCAR N".
assert(dataParser.matchesAmSatName("OSCAR 7", listOf("AO-7")))
assert(dataParser.matchesAmSatName("AMSAT-OSCAR 7", listOf("AO-7")))
assert(dataParser.matchesAmSatName("CATSAT", listOf("CATSAT")))
assert(dataParser.matchesAmSatName("RS-44 & BREEZE-KM R/B", listOf("RS-44")))
}
@Test
fun `AMSAT live page with no table returns empty`() = runTest(testDispatcher) {
val html = "<html><body>No data</body></html>".byteInputStream()
assert(dataParser.parseAmSatLivePage(html).isEmpty())
}
}
@@ -21,6 +21,7 @@ import com.rtbishop.look4sat.core.domain.model.DatabaseState
import com.rtbishop.look4sat.core.domain.model.DataSourcesSettings
import com.rtbishop.look4sat.core.domain.model.GridQso
import com.rtbishop.look4sat.core.domain.model.LoTWSettings
import com.rtbishop.look4sat.core.domain.model.MarkedStation
import com.rtbishop.look4sat.core.domain.model.OtherSettings
import com.rtbishop.look4sat.core.domain.model.PassesSettings
import com.rtbishop.look4sat.core.domain.model.RCSettings
@@ -261,6 +262,9 @@ class LoTWGridSyncTest {
override fun setWorkedGridQsos(qsos: Map<String, List<GridQso>>) { workedGridQsos = qsos }
override fun getRoamedGrids(): Set<String> = roamedGrids
override fun setRoamedGrids(grids: Set<String>) { roamedGrids = grids }
private var markedGridStations: Map<String, List<MarkedStation>> = emptyMap()
override fun getMarkedGridStations(): Map<String, List<MarkedStation>> = markedGridStations
override fun setMarkedGridStations(stations: Map<String, List<MarkedStation>>) { markedGridStations = stations }
override fun getLastLotwSyncDate(): String = lastSyncDate
override fun setLastLotwSyncDate(date: String) { lastSyncDate = date }
override fun getLastLotwSyncCallsign(): String = lastSyncCallsign
@@ -279,6 +283,12 @@ class LoTWGridSyncTest {
override fun updateOtherSettings(transform: (OtherSettings) -> OtherSettings) = TODO()
override fun updateDataSourcesSettings(settings: DataSourcesSettings) = TODO()
override fun updateDataSourcesStatus(status: Map<String, Int>) = TODO()
override fun getAmSatFmCatnums(): Set<Int> = emptySet()
override fun getAmSatLinearCatnums(): Set<Int> = emptySet()
override val amSatListsVersion: StateFlow<Int> = MutableStateFlow(0)
override fun setAmSatCatnums(fmCatnums: Set<Int>, linearCatnums: Set<Int>) = Unit
override fun getAmSatActiveCatnums(): Set<Int> = emptySet()
override fun setAmSatActiveCatnums(catnums: Set<Int>) = Unit
override fun updateRadioControlSettings(settings: RadioControlSettings) = TODO()
override fun getSatelliteOffset(catnum: Int): String = ""
override fun setSatelliteOffset(catnum: Int, offset: String) = TODO()
@@ -0,0 +1,20 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<!-- 冖 (秃宝盖): 顶横 + 两侧短竖, 笔画型 -->
<path
android:pathData="M5,4 L19,4 M5,4 L5,8.5 M19,4 L19,8.5"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:fillColor="#00000000" />
<!-- 笔画型向上箭头 ↑: 竖杆 + 两斜线箭头头 -->
<path
android:pathData="M12,9 L12,20 M12,9 L7.5,14 M12,9 L16.5,14"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:fillColor="#00000000" />
</vector>
@@ -28,7 +28,7 @@
<string name="pass_filter_title">筛选过境</string>
<string name="pass_filter_elev">仰角值</string>
<string name="pass_filter_hours">提前时间</string>
<string name="pass_filter_history_hours">先前时间</string>
<string name="pass_filter_history_hours">历史过境时间</string>
<string name="pass_filter_aos_time">AOS 时间段</string>
<string name="pass_filter_invert_time">反选 AOS 时间段</string>
<string name="pass_filter_deep_space">DeepSpace(周期 &gt;225分钟)</string>
@@ -41,7 +41,7 @@
<string name="pass_welcome_message">请务必在设置中通过GPS、经纬度或QTH定位您的位置\n建议至少每周更新一次数据库,以确保预测结果的准确性</string>
<!-- AMSAT Status screen -->
<string name="pass_whatsnew_message">4.4.6 以来的全部更新(4.4.7 系列):\n\n• 网格模式地图:LoTW 已确认网格绿色填充、漫游网格蓝色条纹、当前网格加粗框;右上角网格/卫星模式开关。\n\n• 首通呼号(VUCC 视图):绿格显示该格最早通联的呼号,非绿格空白。\n\n• worked 网格可按操作网格筛选(含“全部”);点击网格弹出 QSO 明细;每格 QSO 计数。\n\n• 各操作网格独立 VUCC 计数;极区网格标签;反经线修复;漫游条纹密度一致。\n\n• WAPC/WAJA 地图标签随系统语言。\n\n• 网格模式视口与筛选跨页保持。\n\n• LoTW 同步:账号直连、全量/增量模式、实时进度、可取消、启动自动同步(独立开关)、设置页显示上次同步时间。\n\n• 历史过境:过境筛选可回看过去数小时(先前时间)。\n\n• 指南针校准:8 字动作精度指示 + 手动航向偏置。\n\n• AMSAT 状态页:连续相同状态报告计数。\n\n• 过境/雷达:UTC 切换重算过境;日出日落与仰角颜色修复;卫星模糊搜索;相互过境页滚动保持、跟随 UTC、雷达快捷入口。\n\n• CW 解码器支持 32/64 位设备;Android 17 (API 37) 适配。</string>
<string name="pass_whatsnew_message">4.4.6 以来的全部更新(4.4.7 系列):\n\n• 网格模式地图:LoTW 已确认网格绿色填充、漫游网格蓝色条纹、当前网格加粗框;右上角网格/卫星模式开关。\n\n• 首通呼号(VUCC 视图):绿格显示该格最早通联的呼号,非绿格空白。\n\n• worked 网格可按操作网格筛选(含“全部”);点击网格弹出 QSO 明细;每格 QSO 计数。\n\n• 各操作网格独立 VUCC 计数;极区网格标签;反经线修复;漫游条纹密度一致。\n\n• WAPC/WAJA 地图标签随系统语言。\n\n• 网格模式视口与筛选跨页保持。\n\n• LoTW 同步:账号直连、全量/增量模式、实时进度、可取消、启动自动同步(独立开关)、设置页显示上次同步时间。\n\n• 历史过境:过境筛选可回看过去数小时(历史过境时间)。\n\n• 指南针校准:8 字动作精度指示 + 手动航向偏置。\n\n• AMSAT 状态页:连续相同状态报告计数。\n\n• 过境/雷达:UTC 切换重算过境;日出日落与仰角颜色修复;卫星模糊搜索;相互过境页滚动保持、跟随 UTC、雷达快捷入口。\n\n• CW 解码器支持 32/64 位设备;Android 17 (API 37) 适配。</string>
<string name="nav_amsat">AMSAT</string>
<string name="amsat_title">AMSAT 卫星状态</string>
@@ -130,6 +130,14 @@
<string name="grid_qso_count_many">%d QSOs</string>
<string name="grid_qso_first">首通</string>
<string name="grid_qso_no_sat">卫星未知</string>
<string name="grid_qso_match">匹配</string>
<!-- 未通联网格中的“标记想通联的电台”提醒 -->
<string name="grid_mark_station">标记你想通联的电台</string>
<string name="grid_mark_callsign">呼号</string>
<string name="grid_mark_confirm">标记</string>
<string name="grid_mark_label">标记</string>
<string name="grid_mark_delete">删除标记</string>
<string name="grid_mark_pin">置顶</string>
<string name="map_visible">日照中</string>
<!-- Settings screen -->
@@ -300,6 +308,9 @@
<string name="mutual_grid_hint">支持 4/6/8 位 Maidenhead 网格;也可直接输入经纬度</string>
<string name="mutual_min_elevation">最小仰角:%d°</string>
<string name="mutual_time_range">时间范围</string>
<string name="mutual_filter_transponder">转发器</string>
<string name="mutual_filter_fm">FM</string>
<string name="mutual_filter_linear">线性</string>
<string name="mutual_calculating">计算中…</string>
<string name="mutual_query">查询匹配</string>
<string name="mutual_elevation_you">你:%d°</string>
@@ -150,6 +150,14 @@
<string name="grid_qso_count_many">%d QSOs</string>
<string name="grid_qso_first">First</string>
<string name="grid_qso_no_sat">satellite unknown</string>
<string name="grid_qso_match">Match</string>
<!-- Mark-a-station reminder in unworked grids -->
<string name="grid_mark_station">Mark a station you want to contact</string>
<string name="grid_mark_callsign">Callsign</string>
<string name="grid_mark_confirm">Mark</string>
<string name="grid_mark_label">Marked</string>
<string name="grid_mark_delete">Remove mark</string>
<string name="grid_mark_pin">Pin to top</string>
<string name="map_visible">Visible</string>
<!-- Settings screen -->
@@ -330,6 +338,9 @@
<string name="mutual_grid_hint">Supports 4/6/8-char Maidenhead grid; or enter lat/lon directly</string>
<string name="mutual_min_elevation">Min elevation: %d°</string>
<string name="mutual_time_range">Time range</string>
<string name="mutual_filter_transponder">Transponders</string>
<string name="mutual_filter_fm">FM</string>
<string name="mutual_filter_linear">Linear</string>
<string name="mutual_calculating">Calculating…</string>
<string name="mutual_query">Query Match</string>
<string name="mutual_elevation_you">You: %d°</string>
@@ -46,15 +46,16 @@ class MaidenheadGridOverlay : Overlay() {
style = Paint.Style.STROKE
color = Color.argb(160, 255, 224, 130)
}
// 网格标签与首通呼号标签同字号 (用户要求 2026-09-21: 字体一样大)
private val labelPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textSize = 26f
textSize = LABEL_TEXT_SIZE
style = android.graphics.Paint.Style.FILL
color = Color.argb(220, 255, 224, 130)
setShadowLayer(3f, 2f, 2f, Color.BLACK)
}
// 首通呼号标签: 比 4 字符网格代码略小, 以容纳更长的呼号(如 BG2GQG).
// 首通呼号标签: 与网格标签同字号.
private val firstCallPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textSize = 20f
textSize = LABEL_TEXT_SIZE
style = android.graphics.Paint.Style.FILL
color = Color.argb(230, 255, 224, 130)
setShadowLayer(3f, 2f, 2f, Color.BLACK)
@@ -63,6 +64,11 @@ class MaidenheadGridOverlay : Overlay() {
style = android.graphics.Paint.Style.FILL
color = Color.argb(90, 76, 217, 100)
}
// 标记(想通联)网格填充: 红色, 透明度与绿色 workedPaint 一致(alpha 90).
private val markedPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = android.graphics.Paint.Style.FILL
color = Color.argb(90, 255, 59, 48)
}
private val roamStripePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeWidth = 14f
@@ -86,6 +92,12 @@ class MaidenheadGridOverlay : Overlay() {
/** Worked gridsquares (4-char, uppercase) to highlight, e.g. {"OL62", "PM95"}. */
var workedGrids: Set<String> = emptySet()
/** Marked gridsquares (4-char, uppercase) — unworked grids the user has
* marked stations they want to contact in; drawn red, same alpha as the
* green worked fill. Value is the ordered mark list (first = pinned);
* label mode shows the FIRST marked callsign. */
var markedGrids: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>> = emptyMap()
/** Grid-mode first-call labels: label worked (green) cells with the first
* callsign worked in that grid instead of the Maidenhead code; non-worked
* cells get no label at all. Only meaningful at sub-square zoom. */
@@ -188,6 +200,9 @@ class MaidenheadGridOverlay : Overlay() {
if (cellLabel(lat, lon, zoom) in workedGrids) {
canvas.drawRect(xLeft, yTop, xRight, yBottom, workedPaint)
}
if (cellLabel(lat, lon, zoom) in markedGrids) {
canvas.drawRect(xLeft, yTop, xRight, yBottom, markedPaint)
}
}
}
} else {
@@ -214,6 +229,22 @@ class MaidenheadGridOverlay : Overlay() {
canvas.drawRect(xLeft, yTop, xRight, yBottom, workedPaint)
}
}
for (grid in markedGrids.keys) {
val cell = gridCellBounds(grid) ?: continue
for (turn in -colRepeats..colRepeats) {
val dLon = turn * 360.0
if (cell.lonRight + dLon <= leftLon || cell.lonLeft + dLon >= rightLon) continue
val yTop = projectionToY(projection, cell.latTop) ?: continue
val yBottom = projectionToY(projection, cell.latBottom) ?: continue
val xLeftBase = projectionToX(projection, cell.lonLeft, centerLon, worldWidthPx) ?: continue
val xRightBase = projectionToX(projection, cell.lonRight, centerLon, worldWidthPx) ?: continue
val xLeft = xLeftBase + turn * worldWidthPx.toFloat()
val xRight = xRightBase + turn * worldWidthPx.toFloat()
if (xRight < 0f || xLeft > canvas.width) continue
if (yBottom < 0f || yTop > canvas.height) continue
canvas.drawRect(xLeft, yTop, xRight, yBottom, markedPaint)
}
}
}
}
@@ -362,21 +393,15 @@ class MaidenheadGridOverlay : Overlay() {
// Labels: centered in each cell, only when the cell is large enough on
// screen to hold a label (avoid clutter at low zoom).
// Field (2-char) labels show at every zoom, subject only to the pixel-
// size check below; sub-square (4-char) labels only from LABEL_ZOOM_SUB
// (one level above the grid lines, so zoom 6 shows lines but no names).
// size check below; sub-square (4-char) labels appear together with the
// grid LINES at GRID_ZOOM_SUB (user req 2026-09-21: 与首通呼号同一显示缩放).
// First-call labels replace the 4-char grid codes and only exist at
// sub-square zoom; at field zoom NO labels are drawn at all (the user
// requirement is that non-worked cells carry no grid characters).
// Show as soon as the 4-char grid LINES appear (GRID_ZOOM_SUB), not
// only at the name-label zoom — user req 2026-09-21.
if (showFirstCallLabels && zoom < GRID_ZOOM_SUB) return
// First-call labels gate on the grid-LINE zoom; normal labels keep the
// name-label zoom (one level above the lines).
val showLabels = if (showFirstCallLabels) {
zoom >= GRID_ZOOM_SUB
} else {
zoom >= LABEL_ZOOM_SUB || cellLat == FIELD_LAT
}
// 网格标签与首通呼号同一显示缩放 (用户要求 2026-09-21): 子方块(4字符)
// 标签与首通呼号都在网格线出现的 GRID_ZOOM_SUB 同时显示, 不再晚一档.
val showLabels = zoom >= GRID_ZOOM_SUB || cellLat == FIELD_LAT
if (!showLabels) return
// Estimate on-screen cell height to avoid clutter at low zoom:
// project two points 1° apart in latitude and measure the pixel distance.
@@ -384,10 +409,9 @@ class MaidenheadGridOverlay : Overlay() {
val y2 = projectionToY(projection, 1.0)
if (y1 == null || y2 == null) return
val pixelsPerDegree = Math.abs(y2 - y1)
// First-call labels must appear as soon as the 4-char grid LINES do
// (zoom 6.0), where 1° cells are ~45 px on the equator — below the
// 48 px normal-label threshold. Relax the pixel gate for this mode only.
val minCellPx = if (showFirstCallLabels) MIN_LABEL_CELL_PX * 0.6f else MIN_LABEL_CELL_PX
// 两种模式同一像素门限: GRID_ZOOM_SUB 处 1° 格约 45px, 低于 48px
// 常规阈值, 统一用放宽的 0.6x 门限, 保证网格标签与首通呼号同时出现.
val minCellPx = MIN_LABEL_CELL_PX * 0.6f
if (pixelsPerDegree * cellLat < minCellPx) return
val activePaint = if (showFirstCallLabels) firstCallPaint else labelPaint
@@ -420,12 +444,15 @@ class MaidenheadGridOverlay : Overlay() {
if (xRight < 0f || xLeft > canvas.width) continue
val label = cellLabel(lat, lon, zoom)
if (showFirstCallLabels) {
// 首通呼号模式: 只有绿格(worked)标注该格第一个通联的呼号,
// 非绿格空着不写网格字符.
if (label in workedGrids) {
firstCallsByGrid[label]?.let { call ->
// 首通呼号模式: 绿格(worked)标注该格第一个通联的呼号, 红格(marked)
// 标注用户标记想通联的呼号, 均淡黄文字; 其它格空着不写网格字符.
when {
label in workedGrids -> firstCallsByGrid[label]?.let { call ->
canvas.drawText(call, (xLeft + xRight) / 2f, yCenter, firstCallPaint)
}
label in markedGrids -> markedGrids[label]?.firstOrNull()?.let { station ->
canvas.drawText(station.call, (xLeft + xRight) / 2f, yCenter, firstCallPaint)
}
}
} else {
canvas.drawText(label, (xLeft + xRight) / 2f, yCenter, labelPaint)
@@ -547,9 +574,8 @@ class MaidenheadGridOverlay : Overlay() {
// the sub-square grid is too dense to read; 6 roughly doubles the
// on-screen size of each square.
const val GRID_ZOOM_SUB = 6.0
// Zoom at which the 4-char sub-square names appear (one level above the
// grid lines: zoom 6 = lines only, zoom 6.5+ = lines + names).
const val LABEL_ZOOM_SUB = 6.5
// 网格标签与首通呼号标签统一字号 (用户要求 2026-09-21: 字体一样大).
const val LABEL_TEXT_SIZE = 20f
const val MIN_LABEL_CELL_PX = 48f
const val MAX_OVERSHOOT_PX = 64
/** Center-to-center spacing of the roamed-grid zebra stripes, in px. */
@@ -31,10 +31,12 @@ import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
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.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
@@ -46,10 +48,13 @@ import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
@@ -63,6 +68,7 @@ import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color as ComposeColor
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@@ -145,7 +151,13 @@ private val moonIconPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
@Composable
fun MapDestination(
mapFilterViewModel: MapFilterViewModel
mapFilterViewModel: MapFilterViewModel,
// Invoked with the tapped grid when the QSO dialog's "Match" button is
// pressed: navigate to the match page pre-filled for that grid.
onMatchGrid: (String) -> Unit = {},
// True while the map "Match" query is running (the page only navigates
// once the query finished, so the match page opens with results ready).
matchCalculating: Boolean = false
) {
val context = LocalContext.current
val container = (context.applicationContext as IContainerProvider).getMainContainer()
@@ -182,7 +194,7 @@ fun MapDestination(
viewModel.onAction(MapAction.SetVisible(false))
}
}
MapScreen(uiState, viewModel::onAction, mapView, mapFilterViewModel)
MapScreen(uiState, viewModel::onAction, mapView, mapFilterViewModel, onMatchGrid, matchCalculating)
}
@Composable
@@ -190,7 +202,9 @@ private fun MapScreen(
uiState: MapState,
onAction: (MapAction) -> Unit,
mapView: MapView,
mapFilterViewModel: MapFilterViewModel
mapFilterViewModel: MapFilterViewModel,
onMatchGrid: (String) -> Unit,
matchCalculating: Boolean
) {
val rotateMod = Modifier.rotate(180f)
val timeString = uiState.mapData?.aosTime ?: "00:00:00"
@@ -258,10 +272,11 @@ private fun MapScreen(
if (!isGridMode || p == null) return false
val zoom = mapView.zoomLevelDouble
// Allow tapping worked cells as soon as the 4-char grid LINES
// appear (GRID_ZOOM_SUB), not only when labels show (LABEL_ZOOM_SUB).
// appear (GRID_ZOOM_SUB); grid labels now appear at that zoom too.
if (zoom < MaidenheadGridOverlay.GRID_ZOOM_SUB) return false
val grid = gridOfPoint(p.latitude, p.longitude) ?: return false
if (grid !in workedGrids) return false
// Every grid is tappable: worked grids show their confirmed QSOs,
// unworked grids open the same dialog with an empty list.
selectedGrid = grid
return true
}
@@ -347,7 +362,8 @@ private fun MapScreen(
centerOnStation = shouldCenter,
// 首通呼号标签只作用于 VUCC 视图(用户要求); "All"/其他奖状不过滤.
showFirstCallLabels = uiState.showFirstCallLabels && selectedAward == AwardType.VUCC,
firstCallsByGrid = firstCallsByGrid
firstCallsByGrid = firstCallsByGrid,
markedGrids = uiState.markedGrids
)
if (!shouldCenter || uiState.stationPosition != null) {
prevGridMode = uiState.isGridMode
@@ -407,13 +423,20 @@ private fun MapScreen(
}
}
// Centered dialog listing the tapped worked grid's confirmed satellite QSOs.
// Dismissed by tapping outside (no explicit close button).
// Dismissed by tapping outside (no explicit close button). Unworked grids
// open the same dialog with an empty list plus a mark-a-station reminder.
selectedGrid?.let { grid ->
WorkedGridQsoDialog(
grid = grid,
qsos = uiState.workedGridQsos[grid].orEmpty().sortedBy { it.epochMs },
marked = uiState.markedGrids[grid].orEmpty(),
isUtc = uiState.isUtc,
onDismiss = { selectedGrid = null }
matchCalculating = matchCalculating,
onDismiss = { selectedGrid = null },
onMatch = { onMatchGrid(grid) },
onMark = { call -> onAction(MapAction.SetMarkedStation(grid, call)) },
onRemoveMark = { call -> onAction(MapAction.RemoveMarkedStation(grid, call)) },
onPinMark = { call -> onAction(MapAction.PinMarkedStation(grid, call)) }
)
}
}
@@ -424,9 +447,17 @@ private fun MapScreen(
private fun WorkedGridQsoDialog(
grid: String,
qsos: List<com.rtbishop.look4sat.core.domain.model.GridQso>,
marked: List<com.rtbishop.look4sat.core.domain.model.MarkedStation>,
isUtc: Boolean,
onDismiss: () -> Unit
matchCalculating: Boolean,
onDismiss: () -> Unit,
onMatch: () -> Unit,
onMark: (String) -> Unit,
onRemoveMark: (String) -> Unit,
onPinMark: (String) -> Unit
) {
var showMarkInput by remember { mutableStateOf(false) }
var callInput by remember { mutableStateOf("") }
androidx.compose.ui.window.Dialog(onDismissRequest = onDismiss) {
// Centered card, ~85% width, internal scroll for long lists.
Card(
@@ -434,48 +465,202 @@ private fun WorkedGridQsoDialog(
modifier = Modifier.fillMaxWidth(0.88f)
) {
Column {
// Header: grid + counts
Column(Modifier.padding(horizontal = 16.dp, vertical = 10.dp)) {
Text(
text = grid,
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.primary,
fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace
)
val distinctCalls = qsos.map { it.call }.distinct().size
Text(
text = stringResource(R.string.grid_qso_calls_count, distinctCalls, qsos.size),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
// Header: grid + counts on the left, "Match" action on the right
// (jumps to the match page pre-filled with this grid).
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(start = 16.dp, end = 8.dp, top = 4.dp, bottom = 4.dp)
) {
Column(Modifier.weight(1f)) {
Text(
text = grid,
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.primary,
fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace
)
val distinctCalls = qsos.map { it.call }.distinct().size
Text(
text = stringResource(R.string.grid_qso_calls_count, distinctCalls, qsos.size),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
TextButton(
enabled = !matchCalculating,
onClick = {
onDismiss()
onMatch()
}
) {
if (matchCalculating) {
CircularProgressIndicator(
modifier = Modifier.size(18.dp),
strokeWidth = 2.dp
)
} else {
Icon(
painter = painterResource(R.drawable.ic_radio_tower),
contentDescription = null,
modifier = Modifier.size(18.dp)
)
}
Spacer(Modifier.width(4.dp))
Text(stringResource(R.string.grid_qso_match))
}
}
androidx.compose.material3.HorizontalDivider()
if (qsos.isEmpty()) {
Text(
text = stringResource(R.string.grid_qso_no_sat),
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(16.dp)
)
} else {
// Group by callsign preserving first-contact order (list is
// already sorted oldest-first); expandable rows.
val grouped = remember(qsos) {
qsos.groupBy { it.call }.entries.sortedBy { it.value.first().epochMs }
Column(
Modifier
.heightIn(max = 380.dp)
.verticalScroll(rememberScrollState())
) {
// Marked stations show first as red reminder rows: pale-yellow
// callsign, "标记" in the count column, the marking date in the
// date column, a small pin icon (first = pinned, grey; others
// pale yellow) and a delete icon to remove the mark.
val showPin = marked.size > 1
marked.forEachIndexed { index, station ->
MarkedStationRow(
marked = station,
isPinned = index == 0,
showPin = showPin,
isUtc = isUtc,
onRemoveMark = { onRemoveMark(station.call) },
onPinMark = { onPinMark(station.call) }
)
androidx.compose.material3.HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.3f))
}
Column(
Modifier
.heightIn(max = 380.dp)
.verticalScroll(rememberScrollState())
) {
if (qsos.isNotEmpty()) {
// Group by callsign preserving first-contact order (list is
// already sorted oldest-first); expandable rows.
val grouped = remember(qsos) {
qsos.groupBy { it.call }.entries.sortedBy { it.value.first().epochMs }
}
grouped.forEach { (call, callQsos) ->
WorkedGridCallRow(call, callQsos = callQsos, isUtc = isUtc)
androidx.compose.material3.HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.3f))
}
}
// Unworked grids: offer to mark a station the user wants to
// contact in this grid (a reminder, cleared when worked).
if (qsos.isEmpty()) {
TextButton(
onClick = {
callInput = ""
showMarkInput = true
},
modifier = Modifier.fillMaxWidth()
) {
Icon(
painter = painterResource(R.drawable.ic_add),
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(Modifier.width(4.dp))
Text(stringResource(R.string.grid_mark_station))
}
}
}
}
}
}
// Mark-a-station input dialog: enter a callsign as a reminder.
if (showMarkInput) {
androidx.compose.material3.AlertDialog(
onDismissRequest = { showMarkInput = false },
title = { Text(stringResource(R.string.grid_mark_station)) },
text = {
androidx.compose.material3.OutlinedTextField(
value = callInput,
onValueChange = { callInput = it.uppercase() },
label = { Text(stringResource(R.string.grid_mark_callsign)) },
singleLine = true
)
},
confirmButton = {
TextButton(
enabled = callInput.isNotBlank(),
onClick = {
onMark(callInput)
showMarkInput = false
}
) { Text(stringResource(R.string.grid_mark_confirm)) }
},
dismissButton = {
TextButton(onClick = { showMarkInput = false }) { Text(stringResource(R.string.btn_cancel)) }
}
)
}
}
@Composable
private fun MarkedStationRow(
marked: com.rtbishop.look4sat.core.domain.model.MarkedStation,
isPinned: Boolean,
showPin: Boolean,
isUtc: Boolean,
onRemoveMark: () -> Unit,
onPinMark: () -> Unit
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)
) {
Text(
text = marked.call,
style = MaterialTheme.typography.titleMedium,
fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
color = ComposeColor(0xFFFFE082),
maxLines = 1,
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
modifier = Modifier.weight(1f)
)
// "标记" column: pin icon (only when the grid has multiple marks) sits
// left of the label; pinned (first) row's icon is grey, others pale
// yellow — tapping moves that mark to the top.
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
modifier = Modifier.weight(1f)
) {
if (showPin) {
Icon(
painter = painterResource(R.drawable.ic_pin),
contentDescription = stringResource(R.string.grid_mark_pin),
tint = if (isPinned) ComposeColor(0xFF9E9E9E) else ComposeColor(0xFFFFE082),
modifier = Modifier
.size(18.dp)
.clickable(onClick = onPinMark)
)
Spacer(Modifier.width(2.dp))
}
Text(
text = stringResource(R.string.grid_mark_label),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = androidx.compose.ui.text.style.TextAlign.Center
)
}
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End,
modifier = Modifier.weight(1f)
) {
Text(
text = formatDate(marked.epochMs, isUtc),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Icon(
painter = painterResource(R.drawable.ic_delete),
contentDescription = stringResource(R.string.grid_mark_delete),
tint = MaterialTheme.colorScheme.error,
modifier = Modifier
.size(18.dp)
.clickable(onClick = onRemoveMark)
)
}
}
}
@Composable
@@ -903,7 +1088,8 @@ private fun setGridMode(
stationPosition: GeoPos?,
centerOnStation: Boolean = false,
showFirstCallLabels: Boolean = false,
firstCallsByGrid: Map<String, String> = emptyMap()
firstCallsByGrid: Map<String, String> = emptyMap(),
markedGrids: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>> = emptyMap()
) {
try {
val gridOverlay = mapView.overlays[OVERLAY_GRID]
@@ -914,6 +1100,7 @@ private fun setGridMode(
// 首通呼号模式: 绿格标注第一个通联的呼号, 非绿格不显示标签.
gridOverlay.showFirstCallLabels = showFirstCallLabels
gridOverlay.firstCallsByGrid = firstCallsByGrid
gridOverlay.markedGrids = markedGrids
// ownGrid must be set on EVERY update — the position is available
// regardless of whether this frame centers (centering happens only
// on entry, but passing null here would wipe the bold outline).
@@ -925,6 +1112,7 @@ private fun setGridMode(
this.roamedGrids = roamedGrids
this.showFirstCallLabels = showFirstCallLabels
this.firstCallsByGrid = firstCallsByGrid
this.markedGrids = markedGrids
this.ownGrid = ownGridOf(stationPosition)
}
}
@@ -34,6 +34,9 @@ data class MapState(
val workedGridQsos: Map<String, List<com.rtbishop.look4sat.core.domain.model.GridQso>> = emptyMap(),
/** 4-char gridsquares the station operated from (LoTW MY_GRIDSQUARE) — blue stripes. */
val roamedGrids: Set<String> = emptySet(),
/** Stations the user marked in unworked gridsquares (grid -> ordered list;
* first = pinned/top) — red fill. */
val markedGrids: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>> = emptyMap(),
val stationPosition: GeoPos? = null,
val orbitalPass: OrbitalPass,
val track: List<List<GeoPos>>? = null,
@@ -52,6 +55,9 @@ sealed interface MapAction {
data class SelectDefaultItem(val catnum: Int) : MapAction
data class ToggleGridMode(val value: Boolean) : MapAction
data class ToggleFirstCallLabels(val value: Boolean) : MapAction
data class SetMarkedStation(val grid: String, val call: String) : MapAction
data class RemoveMarkedStation(val grid: String, val call: String) : MapAction
data class PinMarkedStation(val grid: String, val call: String) : MapAction
data class SetVisible(val isVisible: Boolean) : MapAction
}
@@ -90,11 +90,19 @@ class MapViewModel(
}
viewModelScope.launch {
settingsRepo.wavelogSettings.collectLatest { _ ->
val workedGrids = settingsRepo.getWorkedGrids()
val markedGrids = settingsRepo.getMarkedGridStations()
// Marked stations auto-clear once their grid becomes worked:
// the reminder has served its purpose (user req: 网格变绿后标记自动清除).
val stale = markedGrids.keys.filter { it in workedGrids }
val activeMarks = if (stale.isEmpty()) markedGrids else markedGrids - stale.toSet()
if (stale.isNotEmpty()) settingsRepo.setMarkedGridStations(activeMarks)
_uiState.update {
it.copy(
workedGrids = settingsRepo.getWorkedGrids(),
workedGrids = workedGrids,
workedGridQsos = settingsRepo.getWorkedGridQsos(),
roamedGrids = settingsRepo.getRoamedGrids()
roamedGrids = settingsRepo.getRoamedGrids(),
markedGrids = activeMarks
)
}
}
@@ -112,6 +120,38 @@ class MapViewModel(
is MapAction.SelectDefaultItem -> selectDefaultSatellite(action.catnum)
is MapAction.ToggleGridMode -> settingsRepo.updateOtherSettings { it.copy(stateOfMapGrid = action.value) }
is MapAction.ToggleFirstCallLabels -> settingsRepo.updateOtherSettings { it.copy(stateOfMapFirstCall = action.value) }
is MapAction.SetMarkedStation -> {
val call = action.call.trim().uppercase()
val existing = settingsRepo.getMarkedGridStations()
val current = existing[action.grid].orEmpty()
// 重复呼号忽略: 同一网格已标记过的呼号不再重复添加.
val updated = if (current.any { it.call == call }) existing
else existing + (action.grid to current + com.rtbishop.look4sat.core.domain.model.MarkedStation(
call = call,
epochMs = System.currentTimeMillis()
))
settingsRepo.setMarkedGridStations(updated)
_uiState.update { it.copy(markedGrids = updated) }
}
is MapAction.RemoveMarkedStation -> {
val existing = settingsRepo.getMarkedGridStations()
val current = existing[action.grid].orEmpty()
val remaining = current.filterNot { it.call == action.call }
val updated = if (remaining.isEmpty()) existing - action.grid
else existing + (action.grid to remaining)
settingsRepo.setMarkedGridStations(updated)
_uiState.update { it.copy(markedGrids = updated) }
}
is MapAction.PinMarkedStation -> {
val existing = settingsRepo.getMarkedGridStations()
val current = existing[action.grid].orEmpty()
val target = current.firstOrNull { it.call == action.call }
if (target != null) {
val updated = existing + (action.grid to listOf(target) + current.filterNot { it.call == action.call })
settingsRepo.setMarkedGridStations(updated)
_uiState.update { it.copy(markedGrids = updated) }
}
}
is MapAction.SetVisible -> isScreenVisible.value = action.isVisible
}
}
+17 -1
View File
@@ -4,4 +4,20 @@ plugins {
android {
namespace = "com.rtbishop.look4sat.feature.mutual"
}
testOptions {
unitTests {
// Robolectric needs real Android resources for Compose UI tests.
isIncludeAndroidResources = true
}
}
}
dependencies {
testImplementation(libs.test.junit4)
testImplementation(libs.test.coroutines)
testImplementation(libs.robolectric)
testImplementation(libs.androidx.test.core)
testImplementation(libs.compose.ui.test.junit4)
testImplementation(libs.compose.navigation3)
debugImplementation(libs.compose.debug.manifest)
}
@@ -17,6 +17,7 @@
*/
package com.rtbishop.look4sat.feature.mutual
import android.util.Log
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.shrinkVertically
@@ -54,11 +55,13 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
@@ -77,6 +80,7 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.distinctUntilChanged
@Composable
@@ -157,7 +161,7 @@ fun MutualScreen(
viewModel = viewModel,
state = state,
isVertical = isVertical,
onQuery = viewModel::queryMutualPasses,
onQuery = { viewModel.queryMutualPasses() },
onSelectPass = viewModel::onSelectPass,
onNavigateToRadar = navigateToRadar,
onStationALat = viewModel::onStationALat,
@@ -170,6 +174,8 @@ fun MutualScreen(
onStationBMinElev = viewModel::onStationBMinElev,
onUseCurrentPosition = viewModel::onUseCurrentPosition,
onHoursAhead = viewModel::onHoursAhead,
onFilterFM = viewModel::onFilterFM,
onFilterLinear = viewModel::onFilterLinear,
onClearError = viewModel::clearError
)
}
@@ -193,6 +199,8 @@ private fun MutualContent(
onStationBMinElev: (Double) -> Unit,
onUseCurrentPosition: () -> Unit,
onHoursAhead: (Int) -> Unit,
onFilterFM: (Boolean) -> Unit,
onFilterLinear: (Boolean) -> Unit,
onClearError: () -> Unit
) {
val timeFormat = remember(state.isUtc) {
@@ -220,8 +228,24 @@ private fun MutualContent(
}
}
// Set once the list has actually been laid out. The prefill scroll only
// fires after this, because on a real device the Mutual entry appears
// through the NavDisplay transition and LaunchedEffect alone can run
// before the list is measurable (the scroll then never lands and the
// page stays at the top). onGloballyPositioned fires on the first real
// layout, so the subsequent scrollToItem always has a measured list.
var listReady by remember { mutableStateOf(false) }
Log.d(TAG, "composed: scrollToTimeRange=${state.scrollToTimeRange} matchIndex=${if (state.errorMessage != null) 2 else 1} listReady=$listReady")
LazyColumn(
modifier = Modifier.fillMaxSize(),
modifier = Modifier
.fillMaxSize()
.onGloballyPositioned {
if (!listReady) {
Log.d(TAG, "lazy list laid out, opening prefill scroll gate")
listReady = true
}
},
state = listState,
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
@@ -246,7 +270,7 @@ private fun MutualContent(
}
// Input form
item {
item(key = "stationInputs") {
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(6.dp)
@@ -323,16 +347,25 @@ private fun MutualContent(
)
}
}
MatchSearchCard(
hoursAhead = state.hoursAhead,
isCalculating = state.isCalculating,
onHoursAhead = onHoursAhead,
onQuery = onQuery
)
}
}
// Time range + query card. Its own LazyColumn item so a prefill from
// the map (grid-QSO dialog "Match" button) can scroll the page exactly
// to the time-range selector.
item(key = "matchSearch") {
MatchSearchCard(
hoursAhead = state.hoursAhead,
isCalculating = state.isCalculating,
filterFM = state.filterFM,
filterLinear = state.filterLinear,
onFilterFM = onFilterFM,
onFilterLinear = onFilterLinear,
onHoursAhead = onHoursAhead,
onQuery = onQuery
)
}
// Results
itemsIndexed(state.mutualPasses) { index, pass ->
val mutualData = MutualPassData(
@@ -364,8 +397,44 @@ private fun MutualContent(
)
}
}
// Prefill from the map's grid-QSO dialog "Match" button: once the page is
// laid out, jump straight to the time-range card. Index accounts for the
// optional error card at the top (error = 0, station inputs = 1, time
// range = 2; else 1). scrollToItem is used instead of initializing the
// LazyListState at index 1: the constructor parameter is ignored by this
// Compose version (verified in tests), while scrollToItem lands correctly.
val matchSearchIndex = if (state.errorMessage != null) 2 else 1
LaunchedEffect(state.scrollToTimeRange, matchSearchIndex, listReady) {
Log.d(TAG, "scroll effect: scrollToTimeRange=${state.scrollToTimeRange} matchIndex=$matchSearchIndex listReady=$listReady")
if (state.scrollToTimeRange && listReady) {
// Keep trying until the scroll really lands: on a device the first
// frame only contains the station cards + time-range card, which
// can be shorter than the viewport (no scroll range), so a single
// scrollToItem does nothing. When the async query results arrive
// the list grows past one screen and the scroll becomes possible.
for (attempt in 0 until 20) {
Log.d(TAG, "attempting scrollToItem($matchSearchIndex) #$attempt")
try {
listState.scrollToItem(matchSearchIndex)
} catch (t: Throwable) {
Log.e(TAG, "scrollToItem($matchSearchIndex) threw", t)
break
}
if (listState.firstVisibleItemIndex == matchSearchIndex) {
Log.d(TAG, "scroll landed at $matchSearchIndex on attempt #$attempt")
break
}
delay(100)
}
viewModel.consumeScrollToTimeRange()
Log.d(TAG, "scrollToTimeRange consumed")
}
}
}
private const val TAG = "Look4SatMutual"
@Composable
private fun MutualStatusChip(state: MutualUiState) {
val colorScheme = MaterialTheme.colorScheme
@@ -509,6 +578,10 @@ private fun StationInputCard(
private fun MatchSearchCard(
hoursAhead: Int,
isCalculating: Boolean,
filterFM: Boolean,
filterLinear: Boolean,
onFilterFM: (Boolean) -> Unit,
onFilterLinear: (Boolean) -> Unit,
onHoursAhead: (Int) -> Unit,
onQuery: () -> Unit,
modifier: Modifier = Modifier
@@ -535,6 +608,28 @@ private fun MatchSearchCard(
)
}
}
// 转发器类型筛选: 只匹配 AMSAT Live 清单里的 FM 话音 / 线性转发器卫星,
// 防止选入大量无转发器卫星占用匹配页.
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.mutual_filter_transponder),
style = MaterialTheme.typography.labelLarge
)
FilterChip(
selected = filterFM,
onClick = { onFilterFM(!filterFM) },
label = { Text(stringResource(R.string.mutual_filter_fm)) }
)
FilterChip(
selected = filterLinear,
onClick = { onFilterLinear(!filterLinear) },
label = { Text(stringResource(R.string.mutual_filter_linear)) }
)
}
Button(
onClick = onQuery,
enabled = !isCalculating,
@@ -40,6 +40,8 @@ import kotlinx.coroutines.withContext
import kotlin.math.PI
import kotlin.math.roundToInt
private const val TAG = "Look4SatMutual"
data class MutualUiState(
val stationALat: String = "",
val stationALon: String = "",
@@ -50,12 +52,28 @@ data class MutualUiState(
val stationBGrid: String = "",
val stationBMinElev: Double = 10.0,
val hoursAhead: Int = 24,
/** 历史过境回看窗口(小时), 跟随主页面 Passes 设置; 匹配查询从
* now-hoursBefore 开始, 使设置过历史回看时匹配页也包含历史过境. */
val hoursBefore: Int = 0,
/** 转发器类型筛选: 只匹配搭载 FM 话音转发器的卫星. 默认开启. */
val filterFM: Boolean = true,
/** 转发器类型筛选: 只匹配搭载线性(USB/LSB/CW/SSB)转发器的卫星. 默认开启. */
val filterLinear: Boolean = true,
val mutualPasses: List<MutualPass> = emptyList(),
val isCalculating: Boolean = false,
val hasSearched: Boolean = false,
val selectedPassIndex: Int = -1,
val isUtc: Boolean = false,
val errorMessage: String? = null
val errorMessage: String? = null,
// One-shot flag set by prefillMatchFromGrid() (map grid → Match button):
// the page scrolls to the time-range card after the first layout, then
// consumeScrollToTimeRange() clears it.
val scrollToTimeRange: Boolean = false,
// One-shot flag set by prefillMatchFromGrid(): the map page waits for the
// pre-filled query to finish, then navigates to the match page so the very
// first frame already contains the results (time-range card + pass curves,
// no scroll flicker). consumePendingNavigation() clears it.
val pendingNavigation: Boolean = false
)
class MutualViewModel(
@@ -97,6 +115,12 @@ class MutualViewModel(
_uiState.update { it.copy(isUtc = settings.stateOfUtc) }
}
}
// 历史过境回看窗口跟随主页面 Passes 设置 (设置里改小时数, 匹配页同步生效)
viewModelScope.launch {
settingsRepo.passesSettings.collectLatest { settings ->
_uiState.update { it.copy(hoursBefore = settings.hoursBefore) }
}
}
}
fun onStationALat(value: String) {
@@ -181,9 +205,54 @@ class MutualViewModel(
) }
}
fun onHoursAhead(value: Int) = _uiState.update { it.copy(hoursAhead = value) }
fun onFilterFM(value: Boolean) = _uiState.update { it.copy(filterFM = value) }
fun onFilterLinear(value: Boolean) = _uiState.update { it.copy(filterLinear = value) }
fun onSelectPass(index: Int) = _uiState.update { it.copy(selectedPassIndex = index) }
fun queryMutualPasses() {
/**
* Pre-fill the match page for a target grid picked from the map's grid-QSO
* dialog ("Match" button): set the opposite-station grid (with its
* coordinates), reset the time range to 24h, start the query immediately
* so results are ready when the page opens, and flag the page to scroll
* straight to the time-range card once it is laid out.
*/
fun prefillMatchFromGrid(grid: String) {
val g = grid.trim().uppercase()
val pos = qthToPosition(g)
android.util.Log.d(TAG, "prefillMatchFromGrid('$g')")
_uiState.update {
it.copy(
stationBGrid = g,
stationBLat = pos?.let { p -> "%.4f".format(p.latitude) } ?: it.stationBLat,
stationBLon = pos?.let { p -> "%.4f".format(p.longitude) } ?: it.stationBLon,
hoursAhead = 24,
scrollToTimeRange = true,
pendingNavigation = true
)
}
queryMutualPasses()
}
fun consumePendingNavigation() {
android.util.Log.d(TAG, "consumePendingNavigation")
_uiState.update { it.copy(pendingNavigation = false) }
}
fun consumeScrollToTimeRange() {
android.util.Log.d(TAG, "consumeScrollToTimeRange")
_uiState.update { it.copy(scrollToTimeRange = false) }
}
/**
* Run a mutual-pass query. `initialScrollIndex` non-null forces the list
* to rebuild at that position (legacy callers); null keeps the current
* scroll position, so re-running a query from the match page does not
* jump back to the top. The previous results stay on screen while the
* query runs (the list keeps its height, so the scroll position is not
* clamped away); they are replaced — possibly with empty — when the new
* results arrive.
*/
fun queryMutualPasses(initialScrollIndex: Int? = null) {
val state = _uiState.value
// Resolve positions from lat/lon or grid
@@ -201,29 +270,76 @@ class MutualViewModel(
return
}
// 转发器类型筛选: 至少勾选一种(默认 FM + Linear 都开), 否则提示不查询.
// 防止用户选入大量无转发器卫星占用匹配页.
if (!state.filterFM && !state.filterLinear) {
_uiState.update { it.copy(errorMessage = "Select at least one transponder type (FM / Linear) to run the match.") }
return
}
// AMSAT Live 清单(同步自 AMSAT "Live FM/Linear Satellites" 页面)是本过滤的
// 权威来源: 只匹配当前在轨且话音/线性转发器实际工作的卫星. 清单为空
// (从未成功同步过)时回退到数据库 downlinkMode 过滤, 避免首启匹配页空结果.
// 过滤本身在下面的协程里执行 (getSatelliteIdsWithModes 是 suspend).
_uiState.update {
it.copy(
isCalculating = true,
hasSearched = true,
errorMessage = null,
mutualPasses = emptyList(),
// Deliberately keep mutualPasses: clearing it would shrink the
// list below one screen and clamp the scroll position away.
// The stale results are replaced when the new ones arrive.
selectedPassIndex = -1
)
}
// The results list is about to be replaced, so the scroll position must
// not leak from the previous query's list.
listScrollIndex = 0
listScrollOffset = 0
// Scroll position: an explicit initialScrollIndex overrides (legacy
// callers start at a fixed spot); null keeps the current position so
// re-querying does not jump back to the top.
if (initialScrollIndex != null) {
listScrollIndex = initialScrollIndex
listScrollOffset = 0
}
queryGeneration += 1
viewModelScope.launch {
val time = System.currentTimeMillis()
val now = System.currentTimeMillis()
// 转发器类型过滤(协程上下文): AMSAT Live 清单优先, 为空时回退数据库.
val amSatFm = settingsRepo.getAmSatFmCatnums()
val amSatLinear = settingsRepo.getAmSatLinearCatnums()
val filteredSatellites = if (amSatFm.isEmpty() && amSatLinear.isEmpty()) {
// 回退到数据库模式过滤: 只用带上行频率的转发器记录, 排除纯下行
// 信标/遥测(如 CW 信标、FM 语音合成信标), 避免 ISS/IO-86/FO-29 等
// 因共享模式标签(CW/FM)被误判进错误类别.
val filterModes = buildList {
if (state.filterFM) add("FM")
if (state.filterLinear) addAll(listOf("USB", "LSB", "CW", "SSB"))
}
val idsWithModes = satelliteRepo.getSatelliteIdsWithModesAndUplink(filterModes)
if (idsWithModes.isEmpty()) satellites
else satellites.filter { it.data.catnum in idsWithModes }
} else {
val allowed = buildSet {
if (state.filterFM) addAll(amSatFm)
if (state.filterLinear) addAll(amSatLinear)
}
satellites.filter { it.data.catnum in allowed }
}
// 历史回看: 查询窗口起点 = now - hoursBefore (跟随主页面 Passes 设置),
// 终点 = now + hoursAhead 不变.
val time = now - state.hoursBefore * 60L * 60L * 1000L
val minElevA = state.stationAMinElev
val minElevB = state.stationBMinElev
val hours = state.hoursAhead
val results = withContext(computeDispatcher) {
findMutualPasses(satellites, posA, posB, minElevA, minElevB, time, hours)
val results = try {
withContext(computeDispatcher) {
findMutualPasses(filteredSatellites, posA, posB, minElevA, minElevB, time, hours, state.hoursBefore)
}
} catch (t: Throwable) {
// Never leave the query stuck in "calculating" (which would also
// block the pending map→match navigation forever).
android.util.Log.e(TAG, "findMutualPasses threw", t)
emptyList()
}
val errorMsg = if (results.isEmpty()) {
@@ -262,15 +378,20 @@ class MutualViewModel(
satellites: List<OrbitalObject>,
posA: GeoPos, posB: GeoPos,
minElevADeg: Double, minElevBDeg: Double,
time: Long, hours: Int
time: Long, hours: Int, hoursBefore: Int
): List<MutualPass> {
val endTime = time + hours * 60L * 60L * 1000L
// 终点始终是 now + hoursAhead; 起点已由调用方下移 hoursBefore 小时,
// 因此这里的 endTime 要在起点之上补回 hoursBefore, 保证窗口 = [now-hb, now+h].
val endTime = time + (hoursBefore + hours) * 60L * 60L * 1000L
val sampleInterval = 5_000L
// Use the main page's pass list for AOS/LOS times, then sample the curves
// using the actual positions. The passes list is already computed by getLeoPass
// and its AOS/LOS times match the Passes page exactly.
val existingPasses = satelliteRepo.passes.value
// The satellites argument may be a subset (transponder-type filter), so
// only passes belonging to the filtered satellites are reused.
val allowedCatnums = satellites.map { it.data.catnum }.toSet()
val existingPasses = satelliteRepo.passes.value.filter { it.catNum in allowedCatnums }
val results = findMutualPassesFromList(existingPasses, satellites, posA, posB,
minElevADeg, minElevBDeg, time, endTime, sampleInterval)
if (results.isNotEmpty()) return results
@@ -44,13 +44,20 @@ class FakeSatelliteRepo(
override suspend fun getTrack(sat: OrbitalObject, pos: GeoPos, start: Long, end: Long): List<OrbitalPos> = TODO()
override suspend fun getRadios(sat: OrbitalObject, pos: GeoPos, radios: List<SatRadio>, time: Long): List<SatRadio> = TODO()
override suspend fun getRadiosWithId(id: Int): List<SatRadio> = TODO()
override suspend fun getSatelliteIdsWithModes(modes: List<String>): List<Int> = emptyList()
override suspend fun getSatelliteIdsWithModesAndUplink(modes: List<String>): List<Int> = emptyList()
override suspend fun getSatelliteIdsWithModesAndAmateur(modes: List<String>): List<Int> = emptyList()
}
/**
* Test fake for ISettingsRepo. Only [stationPosition] is backed by mutable
* state; everything else the ViewModel never touches fails loudly.
*/
class FakeSettingsRepo(initialPosition: GeoPos = GeoPos(23.13, 113.26)) : ISettingsRepo {
class FakeSettingsRepo(
initialPosition: GeoPos = GeoPos(23.13, 113.26),
val amSatFm: Set<Int> = emptySet(),
val amSatLinear: Set<Int> = emptySet()
) : ISettingsRepo {
override val stationPosition = MutableStateFlow(initialPosition)
@@ -103,6 +110,13 @@ class FakeSettingsRepo(initialPosition: GeoPos = GeoPos(23.13, 113.26)) : ISetti
override fun updateDataSourcesStatus(status: Map<String, Int>) = TODO()
override fun getAmSatFmCatnums(): Set<Int> = amSatFm
override fun getAmSatLinearCatnums(): Set<Int> = amSatLinear
override val amSatListsVersion: StateFlow<Int> = MutableStateFlow(0)
override fun setAmSatCatnums(fmCatnums: Set<Int>, linearCatnums: Set<Int>) = TODO()
override fun getAmSatActiveCatnums(): Set<Int> = emptySet()
override fun setAmSatActiveCatnums(catnums: Set<Int>) = TODO()
override fun updateRadioControlSettings(settings: RadioControlSettings) = TODO()
override fun getSatelliteOffset(catnum: Int): String = ""
override fun setSatelliteOffset(catnum: Int, offset: String) = TODO()
@@ -115,6 +129,8 @@ class FakeSettingsRepo(initialPosition: GeoPos = GeoPos(23.13, 113.26)) : ISetti
override fun setWorkedGridQsos(qsos: Map<String, List<GridQso>>) = TODO()
override fun getRoamedGrids(): Set<String> = TODO()
override fun setRoamedGrids(grids: Set<String>) = TODO()
override fun getMarkedGridStations(): Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>> = emptyMap()
override fun setMarkedGridStations(stations: Map<String, List<com.rtbishop.look4sat.core.domain.model.MarkedStation>>) = Unit
override fun updateLoTWSettings(settings: LoTWSettings) = TODO()
override fun getLastLotwSyncDate(): String = ""
override fun setLastLotwSyncDate(date: String) = Unit
@@ -0,0 +1,291 @@
package com.rtbishop.look4sat.feature.mutual
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.unit.dp
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.navigation3.runtime.NavBackStack
import androidx.navigation3.runtime.NavKey
import androidx.navigation3.runtime.entryProvider
import androidx.navigation3.runtime.rememberNavBackStack
import androidx.navigation3.ui.NavDisplay
import com.rtbishop.look4sat.core.presentation.Screen
import kotlinx.coroutines.delay
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
/**
* Verifies the map grid-QSO dialog "Match" prefill: after
* [MutualViewModel.prefillMatchFromGrid] the page opens with the time-range
* card at the top and the 24h query auto-started.
*
* Note: `LazyListState(firstVisibleItemIndex = 1)` is deliberately NOT used to
* position the page. In this Compose version (BOM 2026.06.01 / ui 1.11.x) the
* constructor parameter is ignored — the list still starts at item 0 — while
* `listState.scrollToItem(1)` from a LaunchedEffect lands correctly. See
* [scrollToItemLandsAtTop] below, which guards the scrollToItem mechanism.
*
* Robolectric quirk: `assertIsNotDisplayed()` is unreliable here (a node
* scrolled fully out of the viewport can still report "displayed"), so the
* prefill test asserts the time-range card IS displayed (positive assertion)
* rather than that the station card is NOT.
*/
@RunWith(RobolectricTestRunner::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(sdk = [34], qualifiers = "w411dp-h891dp-port")
class MutualMatchPrefillScrollTest {
@get:Rule
val composeRule = createComposeRule()
@Test
fun sanity_textRenders() {
composeRule.setContent {
MaterialTheme {
Text("sanity-check-text")
}
}
composeRule.onNodeWithText("sanity-check-text").assertIsDisplayed()
}
@Test
fun scrollToItemLandsAtTop() {
// Guards the mechanism the prefill relies on: scrollToItem(1) from a
// LaunchedEffect moves item 1 to the top of the viewport.
composeRule.setContent {
MaterialTheme {
Surface(modifier = Modifier.fillMaxSize()) {
val state = remember { LazyListState(firstVisibleItemIndex = 0) }
LaunchedEffect(Unit) { state.scrollToItem(1) }
LazyColumn(state = state) {
item { Text("min-item-0") }
item { Text("min-item-1") }
item { Text("min-item-2") }
}
}
}
}
composeRule.waitForIdle()
composeRule.onNodeWithText("min-item-1").assertIsDisplayed()
}
@Test
fun defaultOpen_showsStationInputsAtTop() {
val vm = MutualViewModel(FakeSatelliteRepo(), FakeSettingsRepo())
composeRule.setContent {
MaterialTheme {
Surface(modifier = Modifier.fillMaxSize()) {
MutualScreen(viewModel = vm)
}
}
}
// Without a prefill the list starts at item 0 (station inputs).
composeRule.onNodeWithText("Your Station").assertIsDisplayed()
}
@Test
fun prefillFromMap_opensAtTimeRangeCard() {
val vm = MutualViewModel(FakeSatelliteRepo(), FakeSettingsRepo())
// Same call the map grid-QSO "Match" button makes.
vm.prefillMatchFromGrid("OL62")
composeRule.setContent {
MaterialTheme {
Surface(modifier = Modifier.fillMaxSize()) {
MutualScreen(viewModel = vm)
}
}
}
composeRule.waitForIdle()
// The time-range card must be visible at the top of the page after the
// prefill scroll.
composeRule.onNodeWithText("Time range").assertIsDisplayed()
// The snapshotFlow write-back stores the scrolled position in the VM.
// It equals 1 only if scrollToItem(1) REALLY scrolled the station card
// out. If the list content is shorter than the viewport there is no
// scroll range, scrollToItem cannot move, and this stays 0 — that is
// exactly the device symptom ("page stays at the top").
org.junit.Assert.assertEquals(
"list must have actually scrolled to item 1 (content shorter than viewport?)",
1, vm.listScrollIndex
)
}
@Test
fun prefillAutoStartsQueryAndFillsState() {
val vm = MutualViewModel(FakeSatelliteRepo(), FakeSettingsRepo())
vm.prefillMatchFromGrid("OL62")
val s = vm.uiState.value
// Query auto-started: with the empty-satellite fake the query reaches
// the "no satellite data" guard (rather than never being triggered),
// proving prefillMatchFromGrid kicks off queryMutualPasses.
assertTrue(
"auto-query should reach the satellite guard: gridA=${s.stationAGrid} " +
"gridB=${s.stationBGrid} err=${s.errorMessage}",
s.errorMessage?.contains("satellite", ignoreCase = true) == true
)
// ...and the target grid + 24h range pre-filled.
org.junit.Assert.assertEquals("OL62", s.stationBGrid)
org.junit.Assert.assertEquals(24, s.hoursAhead)
// ...and navigation to the match page is pending until the query done.
assertTrue("navigation should be pending", s.pendingNavigation)
// The early-return guard means the query finished immediately (no
// satellites): the map page must now be free to navigate.
org.junit.Assert.assertFalse("query finished -> not calculating", s.isCalculating)
vm.consumePendingNavigation()
org.junit.Assert.assertFalse("consume clears pending navigation", vm.uiState.value.pendingNavigation)
}
@Test
fun navDisplayEntryAfterPrefill_scrollsToTimeRange() {
// The Mutual screen composed inside a NavDisplay entry (back stack
// [Mutual]) right after prefillMatchFromGrid.
val vm = MutualViewModel(FakeSatelliteRepo(), FakeSettingsRepo())
vm.prefillMatchFromGrid("OL62")
composeRule.setContent {
val backStack = rememberNavBackStack(Screen.Mutual)
MaterialTheme {
Surface(modifier = Modifier.fillMaxSize()) {
NavDisplay(
backStack = backStack,
onBack = { backStack.removeLastOrNull() },
entryProvider = entryProvider {
entry<Screen.Mutual> { MutualScreen(viewModel = vm) }
}
)
}
}
}
composeRule.waitForIdle()
composeRule.onNodeWithText("Time range").assertIsDisplayed()
}
@Test
fun navDisplay_switchToMutualEntry_scrollsToTimeRange() {
// Closest device path: start on the Map entry, then push the Mutual
// entry (what the map "Match" button does). NavDisplay runs a real
// fade transition while the Mutual screen composes.
val vm = MutualViewModel(FakeSatelliteRepo(), FakeSettingsRepo())
vm.prefillMatchFromGrid("OL62")
val backStackRef = mutableStateOf<NavBackStack<NavKey>?>(null)
composeRule.setContent {
val backStack = rememberNavBackStack(Screen.Map)
backStackRef.value = backStack
MaterialTheme {
Surface(modifier = Modifier.fillMaxSize()) {
NavDisplay(
backStack = backStack,
onBack = { backStack.removeLastOrNull() },
entryProvider = entryProvider {
entry<Screen.Map> { Text("MAP PAGE") }
entry<Screen.Mutual> { MutualScreen(viewModel = vm) }
}
)
}
}
}
composeRule.waitForIdle()
// Push Mutual like onMatchGrid does, so the transition composes
// MutualScreen with scrollToTimeRange already set.
composeRule.runOnIdle { backStackRef.value?.add(Screen.Mutual) }
composeRule.waitForIdle()
composeRule.onNodeWithText("Time range").assertIsDisplayed()
}
@Test
fun scrollRetriesUntilContentGrows() {
// Reproduces the real-device mechanism: the first frame's content
// (item 0 short) is shorter than the viewport, so scrollToItem(1) has
// no range and cannot move. Then the content grows (async results)
// past one screen; the retry loop must land on item 1.
composeRule.setContent {
MaterialTheme {
Surface(modifier = Modifier.fillMaxSize()) {
val tall = mutableStateOf(false)
LaunchedEffect(Unit) { delay(300); tall.value = true }
val state = remember { LazyListState() }
LaunchedEffect(state) {
// Same retry loop MutualScreen uses for the prefill.
for (attempt in 0 until 20) {
state.scrollToItem(1)
if (state.firstVisibleItemIndex == 1) return@LaunchedEffect
delay(100)
}
}
LazyColumn(state = state) {
item {
if (tall.value) Spacer(modifier = Modifier.height(900.dp))
else Spacer(modifier = Modifier.height(40.dp))
}
item { Text("target-item") }
}
}
}
}
composeRule.waitForIdle()
composeRule.onNodeWithText("target-item").assertIsDisplayed()
// Confirm the list really scrolled (station card equivalent is gone).
// We can't read listState from here, so use the VM-style probe: none —
// the target visible + viewport tall enough implies item 1 on top.
}
@Test
fun keepPositionAcrossTabs_thenMapMatchPrefill_scrollsToTimeRange() {
// User hypothesis: the "keep scroll position across tab switches"
// machinery (listState remember(queryGeneration) + snapshotFlow
// write-back) interferes with the prefill auto-scroll. Reproduce the
// full journey: first visit -> scroll a bit -> leave -> return
// (position restored) -> leave -> enter via map Match button.
val vm = MutualViewModel(FakeSatelliteRepo(), FakeSettingsRepo())
val showMutual = mutableStateOf(true)
// First visit (e.g. bottom nav), user scrolls a little; the
// snapshotFlow write-back stored index/offset in the VM.
composeRule.setContent {
MaterialTheme {
Surface(modifier = Modifier.fillMaxSize()) {
if (showMutual.value) MutualScreen(viewModel = vm)
}
}
}
composeRule.waitForIdle()
vm.listScrollIndex = 0
vm.listScrollOffset = 40
// Leave the page (tab switch destroys the composition).
showMutual.value = false
composeRule.waitForIdle()
// Re-enter: keep-position restores the scroll offset.
showMutual.value = true
composeRule.waitForIdle()
// Leave again, then enter via the map grid-QSO Match button.
showMutual.value = false
composeRule.waitForIdle()
vm.prefillMatchFromGrid("OL62")
showMutual.value = true
composeRule.waitForIdle()
composeRule.onNodeWithText("Time range").assertIsDisplayed()
}
}
@@ -31,10 +31,12 @@ class MutualViewModelTest {
private fun TestScope.createVm(
satellites: List<OrbitalObject> = emptyList(),
passes: List<OrbitalPass> = emptyList(),
position: GeoPos = TestOrbits.GUANGZHOU
position: GeoPos = TestOrbits.GUANGZHOU,
amSatFm: Set<Int> = emptySet(),
amSatLinear: Set<Int> = emptySet()
): MutualViewModel = MutualViewModel(
satelliteRepo = FakeSatelliteRepo(satellites, passes),
settingsRepo = FakeSettingsRepo(position),
settingsRepo = FakeSettingsRepo(position, amSatFm, amSatLinear),
computeDispatcher = StandardTestDispatcher(mainDispatcherRule.dispatcher.scheduler)
)
@@ -285,4 +287,102 @@ class MutualViewModelTest {
assertNull(vm.uiState.value.errorMessage)
}
@Test
fun `requery keeps scroll position and stale results while running`() = runTest(mainDispatcherRule.dispatcher.scheduler) {
val windows = TestOrbits.findPassWindows()
assertTrue("fixture must produce ISS windows", windows.isNotEmpty())
val vm = createVm(
satellites = listOf(TestOrbits.ISS),
passes = windows
)
vm.onStationBGrid("OL62")
queryAndSettle(vm)
assertTrue("fixture must yield passes", vm.uiState.value.mutualPasses.isNotEmpty())
// The user scrolled into the results; the snapshotFlow write-back has
// stored this position in the VM.
vm.listScrollIndex = 4
vm.listScrollOffset = 137
// Re-run the query from the match page ("query" button).
vm.queryMutualPasses()
// While the query runs, the old results stay on screen (the list keeps
// its height, so the scroll position is not clamped away)...
assertTrue("stale results kept while calculating", vm.uiState.value.mutualPasses.isNotEmpty())
// ...and the scroll position must not be reset to the top.
assertEquals(4, vm.listScrollIndex)
assertEquals(137, vm.listScrollOffset)
advanceUntilIdle()
assertFalse(vm.uiState.value.isCalculating)
assertTrue("fresh results replace the stale ones", vm.uiState.value.mutualPasses.isNotEmpty())
// Position intact after the query settled.
assertEquals(4, vm.listScrollIndex)
assertEquals(137, vm.listScrollOffset)
}
// --------------------------------------------- transponder filters (AMSAT)
@Test
fun `both filters off sets an error and does not search`() = runTest(mainDispatcherRule.dispatcher.scheduler) {
val windows = TestOrbits.findPassWindows()
val vm = createVm(satellites = listOf(TestOrbits.ISS), passes = windows)
vm.onStationBGrid("OL62")
vm.onFilterFM(false)
vm.onFilterLinear(false)
queryAndSettle(vm)
assertEquals(
"Select at least one transponder type (FM / Linear) to run the match.",
vm.uiState.value.errorMessage
)
assertFalse(vm.uiState.value.hasSearched)
}
@Test
fun `AMSAT filter restricts results to listed catnums`() = runTest(mainDispatcherRule.dispatcher.scheduler) {
val windows = TestOrbits.findPassWindows(hoursAhead = 24) +
TestOrbits.findPassWindows(sat = TestOrbits.ISS_VARIANT, hoursAhead = 24)
assertTrue("fixture must produce windows", windows.isNotEmpty())
// Only ISS (25544) is on the AMSAT live FM list; ISS_VARIANT (25545) is not.
val vm = createVm(
satellites = listOf(TestOrbits.ISS, TestOrbits.ISS_VARIANT),
passes = windows,
amSatFm = setOf(25544)
)
vm.onStationBGrid("OL62")
vm.onHoursAhead(24)
queryAndSettle(vm)
val state = vm.uiState.value
assertNull(state.errorMessage)
assertTrue(state.mutualPasses.isNotEmpty())
assertTrue("only AMSAT-listed satellites should appear", state.mutualPasses.all { it.catNum == 25544 })
}
@Test
fun `AMSAT filter off for one type excludes its satellites`() = runTest(mainDispatcherRule.dispatcher.scheduler) {
val windows = TestOrbits.findPassWindows(hoursAhead = 24) +
TestOrbits.findPassWindows(sat = TestOrbits.ISS_VARIANT, hoursAhead = 24)
// FM filter off, Linear on: neither sat is linear-listed -> nothing matches.
val vm = createVm(
satellites = listOf(TestOrbits.ISS, TestOrbits.ISS_VARIANT),
passes = windows,
amSatFm = setOf(25544),
amSatLinear = setOf(25545)
)
vm.onStationBGrid("OL62")
vm.onHoursAhead(24)
vm.onFilterFM(false)
queryAndSettle(vm)
val state = vm.uiState.value
assertNull(state.errorMessage)
assertTrue("only linear-listed satellites should appear", state.mutualPasses.all { it.catNum == 25545 })
}
}
@@ -30,12 +30,15 @@ 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.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
@@ -145,11 +148,16 @@ private fun PassesScreen(
onAccept = dismiss,
titleFontSize = 18
) { padding ->
// The changelog is long; keep the dialog frame fixed and let the
// text scroll inside it (matches the update-checker page pattern).
Text(
text = stringResource(R.string.pass_whatsnew_message),
fontSize = 16.sp,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.padding(horizontal = padding)
modifier = Modifier
.padding(horizontal = padding)
.heightIn(max = 360.dp)
.verticalScroll(rememberScrollState())
)
}
}
@@ -96,8 +96,12 @@ class PassesViewModel(
val timeNow = System.currentTimeMillis()
val isUtc = _uiState.value.isUtc
val showDeepSpace = _uiState.value.showDeepSpace
// 历史过境窗口: 已结束的过境保留到超过 hoursBefore 小时后消失;
// DeepSpace 保持原行为(始终显示). hoursBefore=0 时过境一结束即消失.
val historyCutoff = timeNow - _uiState.value.hoursBefore * 3600_000L
val filtered = allPasses
.let { if (showDeepSpace) it else it.filter { pass -> !pass.isDeepSpace } }
.filter { pass -> pass.isDeepSpace || pass.losTime >= historyCutoff }
val processed = computePassProgress(filtered, timeNow)
val (nextPass, nextTime, isAos) = resolveNextPass(processed, timeNow)
val sunTimes = computeSunTimes(processed, isUtc)
@@ -339,9 +343,10 @@ class PassesViewModel(
private fun refreshPasses() = viewModelScope.launch {
val settings = settingsRepo.passesSettings.value
// 下拉刷新也保留历史过境窗口, 否则刷新即丢 history (与筛选/启动计算口径一致)
satelliteRepo.calculatePasses(
time = System.currentTimeMillis(),
hoursAhead = settings.hoursAhead,
time = System.currentTimeMillis() - settings.hoursBefore * 60L * 60L * 1000L,
hoursAhead = settings.hoursBefore + settings.hoursAhead,
minElevation = settings.minElevation,
aosStartMinute = settings.aosStartMinute,
aosEndMinute = settings.aosEndMinute,
@@ -42,6 +42,7 @@ import androidx.compose.ui.unit.dp
import com.rtbishop.look4sat.core.presentation.MainTheme
import com.rtbishop.look4sat.core.presentation.R
import com.rtbishop.look4sat.core.presentation.SharedDialog
import com.rtbishop.look4sat.core.domain.source.Sources
@Preview(showBackground = true)
@Composable
@@ -54,9 +55,20 @@ private fun MultiTypesDialogPreview() {
internal fun MultiTypesDialog(
allTypes: List<String>, types: List<String>, cancel: () -> Unit, accept: (List<String>) -> Unit
) {
// 虚拟类型(转发器/活动筛选)与普通 TLE 源类型互斥: 勾虚拟类型时取消普通类型,
// 勾普通类型时取消虚拟类型. 虚拟类型之间可多选组合.
val virtualTypes = Sources.virtualTypeNames
val selected = remember { mutableStateOf(types.toSet()) }
val toggle = { type: String ->
selected.value = if (type in selected.value) selected.value - type else selected.value + type
selected.value = if (type in selected.value) {
selected.value - type
} else if (type in virtualTypes) {
// 勾选虚拟类型: 移除所有普通类型, 保留已勾的虚拟类型.
(selected.value.filterTo(mutableSetOf()) { it in virtualTypes }) + type
} else {
// 勾选普通类型: 移除所有虚拟类型, 保留已勾的普通类型.
(selected.value.filterTo(mutableSetOf()) { it !in virtualTypes }) + type
}
}
val onAccept = { accept(selected.value.toList()) }
SharedDialog(title = stringResource(R.string.sat_type_title), onCancel = cancel, onAccept = onAccept) {
@@ -177,6 +177,7 @@ private fun SatellitesScreen(
)
}
}
// 转发器/活动筛选已在"卫星类型"对话框前三个选项中体现(AMSAT Live FM/Linear, Live SSTV).
ElevatedCard(modifier = Modifier.fillMaxSize()) {
val emptyMessage = stringResource(R.string.sat_empty_list_message)
when {
+7 -2
View File
@@ -1,8 +1,8 @@
[versions]
#noinspection UnusedVersionCatalogEntry
appVersionCode = "484"
appVersionCode = "504"
#noinspection UnusedVersionCatalogEntry
appVersionName = "4.4.7-ba7opf.11.3"
appVersionName = "4.4.7-ba7opf.15.7"
#noinspection UnusedVersionCatalogEntry
compileSdk = "37"
#noinspection UnusedVersionCatalogEntry
@@ -33,6 +33,8 @@ other-okhttp = "5.4.0"
other-osmdroid = "6.1.20"
test-junit4 = "4.13.2"
robolectric = "4.16"
androidx-test-core = "1.7.0"
androidTest-junit = "1.3.0"
androidTest-espresso = "3.7.0"
@@ -79,6 +81,9 @@ other-osmdroid = { module = "org.osmdroid:osmdroid-android", version.ref = "othe
test-coroutines = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlin-coroutines" }
test-junit4 = { module = "junit:junit", version.ref = "test-junit4" }
robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectric" }
androidx-test-core = { module = "androidx.test:core-ktx", version.ref = "androidx-test-core" }
compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
# Real org.json for unit tests (android.jar stub throws "not mocked")
test-json = { module = "org.json:json", version = "20240303" }