Compare commits

..
Author SHA1 Message Date
Rsclub2_2 ec7ea8ea1d test: render every ImageComposeScene on the AWT event thread
The rare CI hang is a lock-order deadlock in Compose Multiplatform 1.8.2,
shown by the thread dump of run 40299943329:

- the test thread renders the scene and holds the FlushCoroutineDispatcher
  runLock while LazyListState.scrollToItem measures and wants the
  SnapshotStateObserver's observedScopeMapsLock;
- the AWT event thread sends the global snapshot notifications and holds
  observedScopeMapsLock in drainChanges while a re-read derived state wakes
  the scene's snapshotFlow collector, whose dispatch wants runLock.

The application renders on the event thread, where both monitors are simply
re-entered. The tests now do the same: onEventThread builds, renders and
closes each scene there and rethrows what the block throws.

Claude-Session: https://claude.ai/code/session_01FJBfPYm6rCH4zD6T7bcC7Y
2026-10-26 11:02:17 +01:00
Rsclub2_2 05874d6ddb test: print all threads when a test times out
The rare CI hang in SelectedStationMessageUiVisualRenderingTest blocks on a
monitor in SnapshotStateObserver.observeReads (line 643 is the monitorenter
of observedScopeMapsLock in Compose 1.8.2). The timed-out thread's stack
shows where it waits but not which thread holds the lock. With the thread
dump enabled, JUnit prints every thread to the test's standard output, which
ends up in the XML report of the test-results artifact.

Claude-Session: https://claude.ai/code/session_01FJBfPYm6rCH4zD6T7bcC7Y
2026-10-26 10:29:18 +01:00
113 changed files with 481 additions and 4663 deletions

No files matched your search

+8 -8
View File
@@ -41,7 +41,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
@@ -143,7 +143,7 @@ jobs:
Add-Content -Path $env:GITHUB_ENV -Value "ASSET_BASENAME=praktiKST-$version-$shortSha"
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
@@ -193,7 +193,7 @@ jobs:
echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
@@ -267,7 +267,7 @@ jobs:
echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
@@ -313,7 +313,7 @@ jobs:
echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
@@ -361,7 +361,7 @@ jobs:
echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
@@ -473,7 +473,7 @@ jobs:
echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
@@ -664,7 +664,7 @@ jobs:
echo "ARCH=$ARCH" >> "$GITHUB_ENV"
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
+2 -2
View File
@@ -22,7 +22,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
@@ -167,7 +167,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
+8 -8
View File
@@ -60,7 +60,7 @@ jobs:
echo "Tag $REF_NAME matches composePackageVersion=$PROPERTY_VERSION"
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
@@ -153,7 +153,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
@@ -222,7 +222,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
@@ -289,7 +289,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
@@ -360,7 +360,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
@@ -431,7 +431,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
@@ -534,7 +534,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
@@ -664,7 +664,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up Java 21
uses: actions/setup-java@v6.2.0
uses: actions/setup-java@v6.1.0
with:
distribution: temurin
java-version: "21"
-2
View File
@@ -103,5 +103,3 @@ You can sponsor KST4Contest here: [Support on Ko-Fi](https://ko-fi.com/praktimar
The following people are sponsoring KST4Contest:
- Marco (DJ5KW)
- Steve (G1YBB/M1B/MW1B)
- Jens (DH1AKY)
@@ -319,9 +319,6 @@ map.showPathAnalysis=Streckenanalyse zeigen
map.hidePathAnalysis=Streckenanalyse ausblenden
map.pathAnalysisHidden=Die Streckenanalyse ist ausgeblendet.
map.tilesUnavailable=Kartenkacheln nicht verfügbar — die Netzverbindung prüfen.
map.overlayAntenna=Antenne
map.overlayFilters=Aktive Filter
map.overlayLegendTooltip=Rot: tatsächliche Antennenrichtung, Öffnungswinkel und maximaler QRB. Blau: aktive QTF- und QRB-Filter.
path.title=Strecken- und Geländeanalyse
path.selectStation=Eine Station wählen, um Strecken- und Geländeanalyse vorzubereiten.
path.fromLocator=Vom Locator:
@@ -473,17 +470,7 @@ profiles.changeAfterSwitch=Die Änderung wirkt erst nach einem erneuten Wechsel
profiles.alreadyActive=Dieses Profil ist bereits aktiv.
profiles.selectFirst=Zuerst ein Profil in der Tabelle wählen.
beacon.invalidMessage=Der Bakentext ist ungültig: {0}
beacon.intervalTooShort=Einen ganzzahligen Bakenabstand von mindestens {0} Minuten eingeben.
beacon.status.main=Hauptkategorie: {0}
beacon.status.second=Zweite Kategorie: {0}
beacon.status.enabled=aktiv
beacon.status.failed=Versand fehlgeschlagen
beacon.status.unavailable=nicht verfügbar
beacon.reason.session=in dieser Sitzung noch nicht aktiviert
beacon.reason.user=durch den Benutzer ausgeschaltet
beacon.reason.primaryQrg=Haupt-QRG fehlt oder ist ungültig
beacon.reason.secondaryQrg=zweite QRG fehlt oder ist ungültig
beacon.reason.automaticQrg=automatische QRG-Änderung um mehr als 5 kHz
beacon.intervalTooShort=Einen ganzzahligen Bakenabstand von mindestens {0} Minute eingeben.
notification.invalidPort=„{0}" ist kein gültiger TCP-Port. Einen Wert von 1 bis 65535 eingeben.
notification.invalidSpotter=„{0}" ist kein gültiges Spotter-Rufzeichen.
notification.invalidCallsign=Bitte ein gültiges Rufzeichen eingeben.
@@ -328,9 +328,6 @@ map.showPathAnalysis=Show path analysis
map.hidePathAnalysis=Hide path analysis
map.pathAnalysisHidden=Path analysis is hidden.
map.tilesUnavailable=Map tiles unavailable — check the network connection.
map.overlayAntenna=Antenna
map.overlayFilters=Active filters
map.overlayLegendTooltip=Red: actual antenna heading, beamwidth and maximum QRB. Blue: active QTF and QRB filters.
path.title=Path / terrain analysis
path.selectStation=Select a station to prepare path and terrain analysis.
path.fromLocator=From locator:
@@ -482,17 +479,7 @@ profiles.changeAfterSwitch=The change takes effect after switching to this profi
profiles.alreadyActive=This profile is already active.
profiles.selectFirst=Select a profile in the table first.
beacon.invalidMessage=The beacon message is invalid: {0}
beacon.intervalTooShort=Enter a whole beacon interval of at least {0} minutes.
beacon.status.main=Main category: {0}
beacon.status.second=Second category: {0}
beacon.status.enabled=active
beacon.status.failed=send failed
beacon.status.unavailable=unavailable
beacon.reason.session=not activated in this session
beacon.reason.user=switched off by the operator
beacon.reason.primaryQrg=primary QRG missing or invalid
beacon.reason.secondaryQrg=second QRG missing or invalid
beacon.reason.automaticQrg=automatic QRG change greater than 5 kHz
beacon.intervalTooShort=Enter a whole beacon interval of at least {0} minute.
notification.invalidPort="{0}" is not a valid TCP port. Enter a value from 1 to 65535.
notification.invalidSpotter="{0}" is not a valid spotter callsign.
notification.invalidCallsign=Please enter a valid callsign.
@@ -1,6 +1,5 @@
package kst4contest.view;
import kst4contest.controller.RadioSlot;
import kst4contest.model.ChatCategory;
import kst4contest.model.ChatMember;
import kst4contest.model.ChatMessage;
@@ -98,9 +97,4 @@ public final class ComposeChatInputActions implements ChatInputActions {
String value = application.chatcontroller.getChatPreferences().getMYQRGSecondCat().get();
return value == null ? "" : value;
}
@Override
public void applyManualQrg(final RadioSlot slot, final String value) {
application.chatcontroller.applyManualQrg(slot, value);
}
}
@@ -3032,20 +3032,6 @@ public class Kst4ContestApplication implements StatusUpdateListener, SettingsHos
private java.util.function.Consumer<java.util.List<ChatMessage>> composeChatListener;
private java.util.function.Consumer<java.util.List<ClusterMessage>> composeClusterListener;
/**
* Fills the three global Compose message tables from their filtered
* controller views.
*/
/* package */ static void refreshComposeMessageTables(
final ChatController controller,
final DataTableState<ChatMessage> directed,
final DataTableState<ChatMessage> publicMessages,
final DataTableState<ChatMessage> qsoOfTheOther) {
directed.replaceRows(controller.toMeMessages());
publicMessages.replaceRows(controller.toAllMessages());
qsoOfTheOther.replaceRows(controller.toOtherMessages());
}
/**
* Opens the Compose main window beside the JavaFX one.
*
@@ -3278,16 +3264,6 @@ public class Kst4ContestApplication implements StatusUpdateListener, SettingsHos
}),
newJoined,
reachability);
composeMainWindowState.getThreadButtons().registerAction(
ChatController.BEACON_STATUS_SOURCE,
() -> {
chatcontroller.toggleUsableBeacons();
return kotlin.Unit.INSTANCE;
});
composeMainWindowState.getThreadButtons().registerStatusProvider(
ChatController.BEACON_STATUS_SOURCE,
chatcontroller::currentBeaconStatus);
chatcontroller.refreshBeaconStatus();
/*
* The feed, not the window construction, owns the timeline's data from here.
@@ -3366,11 +3342,11 @@ public class Kst4ContestApplication implements StatusUpdateListener, SettingsHos
return kotlin.Unit.INSTANCE;
});
composeChatListener = rows -> uiDispatcher.runOnUi(() -> refreshComposeMessageTables(
chatcontroller,
directed,
publicMessages,
qsoOfTheOther));
composeChatListener = rows -> uiDispatcher.runOnUi(() -> {
directed.replaceRows(chatcontroller.toMeMessages());
publicMessages.replaceRows(rows);
qsoOfTheOther.replaceRows(chatcontroller.toOtherMessages());
});
chatcontroller.getLst_globalChatMessageList().addListener(composeChatListener);
composeClusterListener = rows -> uiDispatcher.runOnUi(() -> cluster.replaceRows(rows));
@@ -3385,8 +3361,10 @@ public class Kst4ContestApplication implements StatusUpdateListener, SettingsHos
stations.replaceRows(initialMembers);
newJoined.updateActiveMembers(initialMembers);
newJoined.updateEvents(chatcontroller.getRecentChatJoins().snapshot());
refreshComposeMessageTables(chatcontroller, directed, publicMessages, qsoOfTheOther);
directed.replaceRows(chatcontroller.toMeMessages());
publicMessages.replaceRows(chatcontroller.getLst_globalChatMessageList().snapshot());
cluster.replaceRows(chatcontroller.getLst_clusterMemberList().snapshot());
qsoOfTheOther.replaceRows(chatcontroller.toOtherMessages());
/*
* The only push that does not check the feed for null, and deliberately so: the
* feed is assigned earlier in this same method, so a guard here could never fire
@@ -4146,17 +4124,6 @@ public class Kst4ContestApplication implements StatusUpdateListener, SettingsHos
});
}
@Override
public void refreshMapDisplaySettings() {
uiDispatcher.runOnUi(() -> {
if (composeMainWindowState == null) {
return;
}
composeMainWindowState.refreshMapDisplaySettings();
forceChatMemberFilterRefresh();
});
}
/**
* No-op since the JavaFX own-QRG text field was removed with the never-shown window.
*
@@ -1,58 +0,0 @@
package kst4contest.view.compose
import kst4contest.model.BeaconStatusSnapshot
import kst4contest.model.BeaconStatusSnapshot.AggregateState
import kst4contest.model.BeaconStatusSnapshot.CategoryStatus
import kst4contest.model.BeaconStatusSnapshot.InactiveReason
import kst4contest.view.i18n.CurrentStrings
import kst4contest.view.i18n.Strings
enum class ThreadStatusVisualStyle {
DEFAULT,
BEACON_OFF,
BEACON_ACTIVE,
BEACON_FAILED,
}
data class BeaconStatusPresentation(
val label: String,
val tooltip: String,
val style: ThreadStatusVisualStyle,
) {
companion object {
fun from(
snapshot: BeaconStatusSnapshot,
strings: Strings = CurrentStrings.get(),
): BeaconStatusPresentation {
val label = when (snapshot.aggregateState) {
AggregateState.OFF -> "off"
AggregateState.PARTIAL -> "1/2"
AggregateState.ON -> "on"
AggregateState.FAILED -> "FAILED"
}
val style = when (snapshot.aggregateState) {
AggregateState.OFF -> ThreadStatusVisualStyle.BEACON_OFF
AggregateState.PARTIAL, AggregateState.ON -> ThreadStatusVisualStyle.BEACON_ACTIVE
AggregateState.FAILED -> ThreadStatusVisualStyle.BEACON_FAILED
}
val tooltip = listOf(
strings.beaconStatusMain(describe(snapshot.main, strings)),
strings.beaconStatusSecond(describe(snapshot.second, strings)),
).joinToString("\n")
return BeaconStatusPresentation(label, tooltip, style)
}
private fun describe(category: CategoryStatus, strings: Strings): String {
if (!category.isAvailable()) return strings.beaconStatusUnavailable
if (category.isFailed()) return strings.beaconStatusFailed
if (category.isEnabled()) return strings.beaconStatusEnabled
return when (category.inactiveReason) {
InactiveReason.NOT_ACTIVATED_THIS_SESSION -> strings.beaconReasonSession
InactiveReason.USER_DISABLED -> strings.beaconReasonUser
InactiveReason.PRIMARY_QRG_UNAVAILABLE -> strings.beaconReasonPrimaryQrg
InactiveReason.SECONDARY_QRG_UNAVAILABLE -> strings.beaconReasonSecondaryQrg
InactiveReason.AUTOMATIC_QRG_CHANGE -> strings.beaconReasonAutomaticQrg
}
}
}
}
@@ -163,12 +163,12 @@ fun ChatInputRow(
// profile on every keystroke.
InlineCommittedField(
stored = ownQrgMain.value.orEmpty(),
onCommit = { state.commitOwnQrg(mainCategory = true, it) },
onCommit = { prefs.getMYQRGFirstCat().set(it) },
tooltip = kst4contest.view.i18n.CurrentStrings.get().chatOwnQrgTooltip,
)
InlineCommittedField(
stored = ownQrgSecond.value.orEmpty(),
onCommit = { state.commitOwnQrg(mainCategory = false, it) },
onCommit = { prefs.getMYQRGSecondCat().set(it) },
tooltip = if (so2rEnabled) {
kst4contest.view.i18n.CurrentStrings.get().chatSecondQrgTooltipSo2r
} else {
@@ -5,7 +5,6 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import kst4contest.controller.RadioSlot
import kst4contest.model.ChatCategory
import kst4contest.model.ChatMember
import kst4contest.model.ChatMessage
@@ -47,8 +46,6 @@ interface ChatInputActions {
fun ownQrgMain(): String
fun ownQrgSecond(): String
fun applyManualQrg(slot: RadioSlot, value: String) {}
}
/**
@@ -153,10 +150,6 @@ class ChatInputState(private val actions: ChatInputActions) {
appendAndFocus("$qrg ")
}
fun commitOwnQrg(mainCategory: Boolean, value: String) {
actions.applyManualQrg(if (mainCategory) RadioSlot.FIRST else RadioSlot.SECOND, value)
}
/**
* Replaces the field with "/cq CALL <snippet>", resolved.
*
@@ -10,8 +10,6 @@ import androidx.compose.runtime.setValue
import kst4contest.controller.On4KstConnectionState
import kst4contest.model.ChatPreferences
import kst4contest.observe.SimpleRoster
import kst4contest.view.compose.map.MapDisplaySettingsState
import kst4contest.view.compose.map.MapNavigationState
/**
* Everything the main window draws, in one object.
@@ -69,19 +67,6 @@ class MainWindowState(
val reachability: ReachabilityState = ReachabilityState(activeBands),
) {
internal val mapNavigation = MapNavigationState()
internal val mapDisplaySettings = MapDisplaySettingsState(prefs)
init {
stationSelection.explicitSelectionListener = { member, source ->
when {
source == StationSelectionSource.RESET_VIEW -> mapNavigation.resetToHome()
member != null -> StationIdentity.of(member)?.let(mapNavigation::fitSelectedPath)
}
}
}
/** Explicit map analysis requested from either station context menu. */
val mapReachability = MapReachabilityState(prefs.stn_loginLocatorMainCat.orEmpty())
@@ -126,15 +111,9 @@ class MainWindowState(
/** Applies only a deliberate QTF filter entry, never a restored or reset filter value. */
fun applyExplicitQtfFilterDirection(qtf: Double) {
mapNavigation.centerOnQtf(qtf)
applyExplicitQtfHeading(prefs, qtf)
}
/** Refreshes map geometry after the Station settings draft has been applied. */
fun refreshMapDisplaySettings() {
mapDisplaySettings.refreshFromPreferences()
}
fun requestLayoutSave() {
layoutSaveRequested?.invoke()
}
@@ -1,11 +1,7 @@
package kst4contest.view.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import kst4contest.observe.ObservableValue
import java.util.function.Consumer
@@ -39,19 +35,3 @@ class ObservedValue<T>(private val source: ObservableValue<T>) {
source.removeListener(follower)
}
}
/** Observes a domain value only for the lifetime of the current composition. */
@Composable
internal fun <T> ObservableValue<T>.observeAsState(): State<T?> {
val state = remember(this) { mutableStateOf(get()) }
DisposableEffect(this) {
val follower = Consumer<T> { updated -> state.value = updated }
addListener(follower)
// Close the gap between the initial read and listener registration.
state.value = get()
onDispose { removeListener(follower) }
}
return state
}
@@ -62,9 +62,6 @@ interface SettingsHost {
*/
fun refreshSo2rState()
/** Pushes applied antenna-beam geometry into the open Compose map. */
fun refreshMapDisplaySettings()
/** Rebuilds the Ctrl+1..Ctrl+0 context menus from the snippet list. */
fun refreshTextSnippetContextMenusFromSettings()
@@ -151,8 +148,6 @@ fun buildSettingsTabs(
applySecondCategory = { category -> controller.setChatCategorySecondChat(category) },
connectionState = connectionState,
applySecondRotator = { controller.reconfigureSecondRotator(); host.refreshSo2rState() },
refreshBeaconStatus = controller::refreshBeaconStatus,
applyMapDisplaySettings = host::refreshMapDisplaySettings,
)
val notificationState = NotificationTabState(
@@ -190,14 +185,8 @@ fun buildSettingsTabs(
draft,
validateBeaconTemplate = { template -> controller.validateBeaconTemplate(template) },
restartBeaconTimer = { controller.restartBeaconTimer() },
setMainBeaconEnabled = controller::setMainBeaconEnabled,
setSecondBeaconEnabled = controller::setSecondBeaconEnabled,
mainCategoryName = categoryName(controller.chatCategoryMain, kst4contest.view.i18n.CurrentStrings.get().settingsCategoryMainFallback),
secondCategoryName = categoryName(controller.chatCategorySecondChat, kst4contest.view.i18n.CurrentStrings.get().settingsCategorySecondFallback),
onBeaconTemplatesApplied = {
controller.onMainBeaconTemplateApplied()
controller.onSecondBeaconTemplateApplied()
},
)
val logSynchState = LogSynchTabState(
@@ -90,13 +90,6 @@ class StationSelectionState : TableSelectionModel<ChatMember> {
var lastSource: StationSelectionSource by mutableStateOf(StationSelectionSource.PROGRAMMATIC)
private set
/** Changes only for deliberate station choices, including repeated choices. */
var explicitSelectionRevision: Long by mutableStateOf(0L)
private set
/** Receives deliberate station choices without observing roster reconciliation. */
internal var explicitSelectionListener: ((ChatMember?, StationSelectionSource) -> Unit)? = null
val identity: StationIdentity?
get() = StationIdentity.of(current)
@@ -108,10 +101,6 @@ class StationSelectionState : TableSelectionModel<ChatMember> {
current = row
lastSource = source
selectionRevision++
if (source.isExplicitSelection()) {
explicitSelectionRevision++
explicitSelectionListener?.invoke(row, source)
}
if (row != null && source.requestsStationTableScroll()) {
scrollRequestRevision++
}
@@ -129,11 +118,6 @@ class StationSelectionState : TableSelectionModel<ChatMember> {
}
}
private fun StationSelectionSource.isExplicitSelection(): Boolean = when (this) {
StationSelectionSource.PROGRAMMATIC -> false
else -> true
}
private fun StationSelectionSource.requestsStationTableScroll(): Boolean = when (this) {
StationSelectionSource.STATION_TABLE,
StationSelectionSource.STATION_CONTEXT_MENU,
@@ -7,7 +7,6 @@ import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.TooltipArea
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.ExperimentalLayoutApi
@@ -26,8 +25,6 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@@ -42,9 +39,11 @@ import kst4contest.controller.On4KstConnectionState
* only the indicators are left here — which is also what finally makes the bar wrap
* properly on a narrow window instead of pushing the badges out of sight.
*
* The connection and notice indicators remain non-clickable. A background-thread status is
* actionable only when the application explicitly registers an action for that source; the
* beacon uses this for its quick switch, while every other worker remains a plain label.
* Nothing in this bar is clickable. The three indicators were mouse-transparent and
* non-focusable in JavaFX and stay that way: the operator is typing into the chat, and a
* status badge must never take the keyboard. The background-thread buttons were ordinary
* focusable Buttons there, with no action attached — they are drawn as plain labels here,
* which is what they always behaved like.
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
@@ -203,41 +202,20 @@ private fun ThreadStatusButtonView(button: ThreadStatusButton) {
}
val scheme = MaterialTheme.colorScheme
val colors = if (button.visualStyle == ThreadStatusVisualStyle.DEFAULT) {
ThreadButtonColors(
background = if (button.highlighted) scheme.primary else scheme.surfaceVariant,
border = null,
text = if (button.highlighted) scheme.onPrimary else scheme.onSurfaceVariant,
)
} else {
beaconThreadButtonColors(
style = button.visualStyle,
highlighted = button.highlighted,
darkTheme = scheme.surface.luminance() < 0.5f,
neutralBackground = scheme.surfaceVariant,
)
}
val background = if (button.highlighted) scheme.primary else scheme.surfaceVariant
val foreground = if (button.highlighted) scheme.onPrimary else scheme.onSurfaceVariant
TooltipArea(tooltip = { TooltipCard(button.tooltip) }) {
val actionModifier = if (button.hasAction) {
Modifier.clickable(role = Role.Button) { button.activate() }
} else {
Modifier
}
var boxModifier = Modifier
.defaultMinSize(minHeight = 22.dp)
.background(colors.background, NOTICE_SHAPE)
.then(actionModifier)
colors.border?.let { border ->
boxModifier = boxModifier.border(1.dp, border, NOTICE_SHAPE)
}
Box(
modifier = boxModifier.padding(NOTICE_PADDING),
modifier = Modifier
.defaultMinSize(minHeight = 22.dp)
.background(background, NOTICE_SHAPE)
.padding(NOTICE_PADDING),
contentAlignment = Alignment.Center,
) {
Text(
text = button.label,
color = colors.text,
color = foreground,
style = MaterialTheme.typography.labelMedium,
maxLines = 1,
)
@@ -245,33 +223,6 @@ private fun ThreadStatusButtonView(button: ThreadStatusButton) {
}
}
internal data class ThreadButtonColors(
val background: Color,
val border: Color?,
val text: Color,
)
internal fun beaconThreadButtonColors(
style: ThreadStatusVisualStyle,
highlighted: Boolean,
darkTheme: Boolean,
neutralBackground: Color,
): ThreadButtonColors = when (style) {
ThreadStatusVisualStyle.BEACON_ACTIVE -> if (highlighted) {
ThreadButtonColors(Color(0xFFFFB300), Color(0xFFFFE082), Color(0xFF1B1B1B))
} else {
ThreadButtonColors(Color(0xFF238636), Color(0xFF56D364), Color.White)
}
ThreadStatusVisualStyle.BEACON_FAILED ->
ThreadButtonColors(Color(0xFFD50000), Color(0xFFFF6B6B), Color.White)
ThreadStatusVisualStyle.BEACON_OFF -> ThreadButtonColors(
neutralBackground,
null,
if (darkTheme) Color(0xFFFF6B6B) else Color(0xFFD50000),
)
ThreadStatusVisualStyle.DEFAULT -> error("Default worker colours come from the theme")
}
/** The tooltips in this bar carry the long text the badges had to cut. */
@Composable
internal fun TooltipCard(text: String) {
@@ -176,36 +176,20 @@ object StatusIndicators {
class ThreadStatusButtons {
private val bySource = LinkedHashMap<String, ThreadStatusButton>()
private val actions = LinkedHashMap<String, () -> Unit>()
private val statusProviders = LinkedHashMap<String, () -> ThreadStateMessage>()
private val ordered = mutableStateListOf<ThreadStatusButton>()
val buttons: List<ThreadStatusButton> get() = ordered
fun update(sourceName: String, message: ThreadStateMessage) {
val effectiveMessage = statusProviders[sourceName]?.invoke() ?: message
val button = bySource.getOrPut(sourceName) {
ThreadStatusButton(sourceName, actions[sourceName]).also { ordered.add(it) }
ThreadStatusButton(sourceName).also { ordered.add(it) }
}
val beacon = effectiveMessage.beaconStatusSnapshot?.let(BeaconStatusPresentation::from)
button.report(
label = "$sourceName: ${beacon?.label ?: effectiveMessage.runningInformationTextDescription}",
tooltip = beacon?.tooltip ?: effectiveMessage.runningInformation.orEmpty(),
style = beacon?.style ?: ThreadStatusVisualStyle.DEFAULT,
label = "$sourceName: ${message.runningInformationTextDescription}",
tooltip = message.runningInformation.orEmpty(),
)
}
/** Gives one status source an explicit action without changing any other source. */
fun registerAction(sourceName: String, action: () -> Unit) {
actions[sourceName] = action
bySource[sourceName]?.setAction(action)
}
/** Resolves a status only when its queued UI update is actually applied. */
fun registerStatusProvider(sourceName: String, provider: () -> ThreadStateMessage) {
statusProviders[sourceName] = provider
}
companion object {
/** How long the flash stays on; JavaFX used a 0.2 s PauseTransition. */
const val HIGHLIGHT_MILLIS = 200L
@@ -213,10 +197,7 @@ class ThreadStatusButtons {
}
/** One background thread's button. */
class ThreadStatusButton(
val sourceName: String,
initialAction: (() -> Unit)? = null,
) {
class ThreadStatusButton(val sourceName: String) {
var label: String by mutableStateOf(sourceName)
private set
@@ -228,43 +209,17 @@ class ThreadStatusButton(
var highlighted: Boolean by mutableStateOf(false)
private set
var visualStyle: ThreadStatusVisualStyle by mutableStateOf(ThreadStatusVisualStyle.DEFAULT)
private set
var revision: Int by mutableStateOf(0)
private set
var action: (() -> Unit)? by mutableStateOf(initialAction)
private set
val hasAction: Boolean
get() = action != null
internal fun report(
label: String,
tooltip: String,
style: ThreadStatusVisualStyle = ThreadStatusVisualStyle.DEFAULT,
) {
internal fun report(label: String, tooltip: String) {
this.label = label
this.tooltip = tooltip
visualStyle = style
highlighted = style == ThreadStatusVisualStyle.DEFAULT ||
style == ThreadStatusVisualStyle.BEACON_ACTIVE
highlighted = true
revision++
}
fun clearHighlight() {
highlighted = false
}
internal fun setAction(action: () -> Unit) {
this.action = action
}
/** Runs the registered action and reports whether this status is actionable. */
fun activate(): Boolean {
val current = action ?: return false
current()
return true
}
}
@@ -112,15 +112,10 @@ fun ComposeStationMap(
antennaAzimuthDeg: Double,
antennaBeamWidthDeg: Double,
maxQrbKm: Double,
selectedTarget: MapCallsignRawSnapshot? = markers.firstOrNull {
it.callSignRaw() == selectedMarkerCallsign
},
spatialFilterOverlay: SpatialFilterOverlayState? = null,
onMarkerClicked: ((MapCallsignRawSnapshot) -> Unit)?,
onMarkerContextRequested: ((List<MapCallsignRawSnapshot>, IntOffset) -> Unit)? = null,
workedGrossFields: Set<String> = emptySet(),
darkMode: Boolean = true,
onCanvasSizeChanged: (Size) -> Unit = { },
modifier: Modifier = Modifier,
) {
val imageCache = remember { TileBitmapCache() }
@@ -152,13 +147,6 @@ fun ComposeStationMap(
* one linear pass over a few hundred markers.
*/
val home = remember(ownLocator6) { homePosition(ownLocator6) }
val selectedTargetOutsideMarkers by remember(markers, selectedTarget) {
derivedStateOf {
selectedTarget?.takeIf { target ->
target.hasUsablePosition() && markers.none { it.callSignRaw() == target.callSignRaw() }
}
}
}
val clusterResult by remember(markers, groupingEnabled, canvasSize) {
derivedStateOf {
StationMapClusterer.cluster(
@@ -217,28 +205,17 @@ fun ComposeStationMap(
Canvas(
modifier = modifier
.clipToBounds()
.onSizeChanged {
canvasSize = Size(it.width.toFloat(), it.height.toFloat())
onCanvasSizeChanged(canvasSize)
}
.onSizeChanged { canvasSize = Size(it.width.toFloat(), it.height.toFloat()) }
.onGloballyPositioned { canvasCoordinates = it }
.onPointerEvent(PointerEventType.Press) { event ->
if (event.buttons.isSecondaryPressed) {
val local = event.changes.firstOrNull()?.position ?: return@onPointerEvent
val viewport = mapState.viewportFor(canvasSize.width, canvasSize.height)
val result = StationMapClusterer.cluster(markers, viewport, groupingEnabled)
val selectedOutside = selectedTargetOutsideMarkers?.takeIf { marker ->
within(
local,
viewport.screenXWrapped(marker.longitudeDeg()).toFloat(),
viewport.screenY(marker.latitudeDeg()).toFloat(),
MARKER_HIT_RADIUS_PX,
)
}
val cluster = result.clusters().firstOrNull { candidate ->
within(
local,
viewport.screenXWrapped(candidate.centerLon).toFloat(),
viewport.screenX(candidate.centerLon).toFloat(),
viewport.screenY(candidate.centerLat).toFloat(),
clusterRadiusPx(candidate.size()),
)
@@ -246,14 +223,12 @@ fun ComposeStationMap(
val individual = result.individual().firstOrNull { marker ->
within(
local,
viewport.screenXWrapped(marker.longitudeDeg()).toFloat(),
viewport.screenX(marker.longitudeDeg()).toFloat(),
viewport.screenY(marker.latitudeDeg()).toFloat(),
MARKER_HIT_RADIUS_PX,
)
}
val targets = selectedOutside?.let(::listOf)
?: cluster?.getMarkers()
?: individual?.let(::listOf)
val targets = cluster?.getMarkers() ?: individual?.let(::listOf)
val window = canvasCoordinates?.localToWindow(local)
if (!targets.isNullOrEmpty() && window != null) {
onMarkerContextRequested?.invoke(
@@ -306,28 +281,15 @@ fun ComposeStationMap(
}
}
}
.pointerInput(markers, selectedTargetOutsideMarkers, groupingEnabled, onMarkerClicked) {
.pointerInput(markers, groupingEnabled, onMarkerClicked) {
detectTapGestures { offset ->
val viewport = mapState.viewportFor(size.width.toFloat(), size.height.toFloat())
val result = StationMapClusterer.cluster(markers, viewport, groupingEnabled)
val selectedOutside = selectedTargetOutsideMarkers?.takeIf { marker ->
within(
offset,
viewport.screenXWrapped(marker.longitudeDeg()).toFloat(),
viewport.screenY(marker.latitudeDeg()).toFloat(),
MARKER_HIT_RADIUS_PX,
)
}
if (selectedOutside != null) {
onMarkerClicked?.invoke(selectedOutside)
return@detectTapGestures
}
val hitCluster = result.clusters().firstOrNull { cluster ->
within(
offset,
viewport.screenXWrapped(cluster.centerLon).toFloat(),
viewport.screenX(cluster.centerLon).toFloat(),
viewport.screenY(cluster.centerLat).toFloat(),
clusterRadiusPx(cluster.size()),
)
@@ -350,12 +312,14 @@ fun ComposeStationMap(
val hit = result.individual().firstOrNull { marker ->
within(
offset,
viewport.screenXWrapped(marker.longitudeDeg()).toFloat(),
viewport.screenX(marker.longitudeDeg()).toFloat(),
viewport.screenY(marker.latitudeDeg()).toFloat(),
MARKER_HIT_RADIUS_PX,
)
}
if (hit != null) onMarkerClicked?.invoke(hit)
if (hit != null) {
onMarkerClicked?.invoke(hit)
}
}
}
) {
@@ -371,34 +335,11 @@ fun ComposeStationMap(
drawRect(color = if (darkMode) MAP_BACKGROUND_DARK else MAP_BACKGROUND_LIGHT)
drawTiles(viewport, imageCache, darkMode)
if (home != null && spatialFilterOverlay != null) {
drawSpatialFilterOverlay(
viewport = viewport,
homeLatitudeDeg = home.first,
homeLongitudeDeg = home.second,
state = spatialFilterOverlay,
darkMode = darkMode,
)
}
drawMaidenheadGrid(viewport, textMeasurer, darkMode)
drawWorkedGrossFields(viewport, workedGrossFields)
drawBeamAndPath(
viewport,
home,
antennaAzimuthDeg,
antennaBeamWidthDeg,
maxQrbKm,
selectedTarget,
darkMode,
)
drawBeamAndPath(viewport, home, antennaAzimuthDeg, antennaBeamWidthDeg, maxQrbKm, markers, selectedMarkerCallsign, darkMode)
drawStations(viewport, clusterResult, selectedMarkerCallsign, textMeasurer, darkMode)
selectedTargetOutsideMarkers?.let { target ->
val x = viewport.screenXWrapped(target.longitudeDeg()).toFloat()
val y = viewport.screenY(target.latitudeDeg()).toFloat()
drawStationDot(x, y, selected = true, worked = target.worked(), warning = target.warningToMyDirection())
drawStationLabel(x, y, target.markerLabel(), target.warningToMyDirection(), textMeasurer, darkMode)
}
drawHover(viewport, hoverPosition, clusterResult, selectedTargetOutsideMarkers, textMeasurer)
drawHover(viewport, hoverPosition, clusterResult, textMeasurer)
}
}
@@ -533,8 +474,8 @@ private fun DrawScope.drawMaidenheadGrid(
val verticals = sortedSetOf<Float>()
val horizontals = sortedSetOf<Float>()
for (cell in cells) {
verticals.add(viewport.screenXWrapped(cell.westLon()).toFloat())
verticals.add(viewport.screenXWrapped(cell.eastLon()).toFloat())
verticals.add(viewport.screenX(cell.westLon()).toFloat())
verticals.add(viewport.screenX(cell.eastLon()).toFloat())
horizontals.add(viewport.screenY(cell.northLat()).toFloat())
horizontals.add(viewport.screenY(cell.southLat()).toFloat())
}
@@ -575,7 +516,7 @@ private fun DrawScope.drawMaidenheadGrid(
}
/* Centred in the cell, the way the stylesheet's translate(-50%, -50%) was. */
val centerX = viewport.screenXWrapped((cell.westLon() + cell.eastLon()) / 2.0).toFloat()
val centerX = viewport.screenX((cell.westLon() + cell.eastLon()) / 2.0).toFloat()
val centerY = viewport.screenY((cell.southLat() + cell.northLat()) / 2.0).toFloat()
val layout = textMeasurer.measure(cell.locatorLabel(), style = labelStyle)
@@ -599,7 +540,8 @@ private fun DrawScope.drawBeamAndPath(
antennaAzimuthDeg: Double,
antennaBeamWidthDeg: Double,
maxQrbKm: Double,
selectedTarget: MapCallsignRawSnapshot?,
markers: List<MapCallsignRawSnapshot>,
selectedMarkerCallsign: String?,
darkMode: Boolean,
) {
if (home == null) {
@@ -607,40 +549,32 @@ private fun DrawScope.drawBeamAndPath(
}
val (homeLat, homeLon) = home
if (isAntennaSectorDrawable(home, antennaAzimuthDeg, antennaBeamWidthDeg, maxQrbKm)) {
if (antennaBeamWidthDeg > 0.0 && maxQrbKm > 0.0) {
val polygon = Path()
buildBeamPolygon(homeLat, homeLon, antennaAzimuthDeg, antennaBeamWidthDeg, maxQrbKm)
.forEachIndexed { index, point ->
val x = viewport.screenXWrapped(point.second).toFloat()
val x = viewport.screenX(point.second).toFloat()
val y = viewport.screenY(point.first).toFloat()
if (index == 0) polygon.moveTo(x, y) else polygon.lineTo(x, y)
}
polygon.close()
drawPath(path = polygon, color = ANTENNA_OVERLAY_COLOR, alpha = BEAM_FILL_ALPHA, style = Fill)
drawPath(path = polygon, color = ANTENNA_OVERLAY_COLOR, style = Stroke(width = BEAM_STROKE_WIDTH_PX))
drawPath(path = polygon, color = BEAM_COLOR, alpha = BEAM_FILL_ALPHA, style = Fill)
drawPath(path = polygon, color = BEAM_COLOR, style = Stroke(width = BEAM_STROKE_WIDTH_PX))
}
val selected = selectedTarget?.takeIf(MapCallsignRawSnapshot::hasUsablePosition)
val selected = markers.firstOrNull {
it.callSignRaw() == selectedMarkerCallsign && it.hasUsablePosition()
}
if (selected != null) {
val start = Offset(viewport.screenXWrapped(homeLon).toFloat(), viewport.screenY(homeLat).toFloat())
val end = Offset(
viewport.screenXWrapped(selected.longitudeDeg()).toFloat(),
viewport.screenY(selected.latitudeDeg()).toFloat(),
)
drawLine(
color = if (darkMode) CONNECTION_HALO_DARK else CONNECTION_HALO_LIGHT,
alpha = CONNECTION_HALO_ALPHA,
start = start,
end = end,
strokeWidth = CONNECTION_HALO_WIDTH_PX,
pathEffect = PathEffect.dashPathEffect(CONNECTION_DASH_PX),
)
drawLine(
color = if (darkMode) CONNECTION_COLOR_DARK else CONNECTION_COLOR_LIGHT,
alpha = CONNECTION_ALPHA,
start = start,
end = end,
start = Offset(viewport.screenX(homeLon).toFloat(), viewport.screenY(homeLat).toFloat()),
end = Offset(
viewport.screenX(selected.longitudeDeg()).toFloat(),
viewport.screenY(selected.latitudeDeg()).toFloat(),
),
strokeWidth = CONNECTION_STROKE_WIDTH_PX,
pathEffect = PathEffect.dashPathEffect(CONNECTION_DASH_PX),
)
@@ -651,9 +585,9 @@ private fun DrawScope.drawBeamAndPath(
* home is, and with the beam switched off there was none. A small dot is kept here
* deliberately.
*/
val homeX = viewport.screenXWrapped(homeLon).toFloat()
val homeX = viewport.screenX(homeLon).toFloat()
val homeY = viewport.screenY(homeLat).toFloat()
drawCircle(color = ANTENNA_OVERLAY_COLOR, radius = HOME_RADIUS_PX, center = Offset(homeX, homeY))
drawCircle(color = BEAM_COLOR, radius = HOME_RADIUS_PX, center = Offset(homeX, homeY))
drawCircle(color = Color.White, radius = HOME_INNER_RADIUS_PX, center = Offset(homeX, homeY))
}
@@ -668,7 +602,7 @@ private fun DrawScope.drawStations(
) {
for (cluster in clusterResult.clusters()) {
drawClusterBubble(
x = viewport.screenXWrapped(cluster.centerLon).toFloat(),
x = viewport.screenX(cluster.centerLon).toFloat(),
y = viewport.screenY(cluster.centerLat).toFloat(),
count = cluster.size(),
containsWorked = cluster.getMarkers().any { it.worked() },
@@ -677,7 +611,7 @@ private fun DrawScope.drawStations(
}
for (marker in clusterResult.individual()) {
val x = viewport.screenXWrapped(marker.longitudeDeg()).toFloat()
val x = viewport.screenX(marker.longitudeDeg()).toFloat()
val y = viewport.screenY(marker.latitudeDeg()).toFloat()
val selected = marker.callSignRaw() == selectedMarkerCallsign
@@ -795,23 +729,14 @@ private fun DrawScope.drawHover(
viewport: MapViewport,
hoverPosition: Offset?,
clusterResult: StationMapClusterer.Result,
selectedTargetOutsideMarkers: MapCallsignRawSnapshot?,
textMeasurer: TextMeasurer,
) {
val position = hoverPosition ?: return
val selectedTargetUnderPointer = selectedTargetOutsideMarkers?.takeIf { marker ->
within(
position,
viewport.screenXWrapped(marker.longitudeDeg()).toFloat(),
viewport.screenY(marker.latitudeDeg()).toFloat(),
MARKER_HIT_RADIUS_PX,
)
}
val clusterUnderPointer = clusterResult.clusters().firstOrNull { cluster ->
within(
position,
viewport.screenXWrapped(cluster.centerLon).toFloat(),
viewport.screenX(cluster.centerLon).toFloat(),
viewport.screenY(cluster.centerLat).toFloat(),
clusterRadiusPx(cluster.size()),
)
@@ -819,14 +744,13 @@ private fun DrawScope.drawHover(
val markerUnderPointer = clusterResult.individual().firstOrNull { marker ->
within(
position,
viewport.screenXWrapped(marker.longitudeDeg()).toFloat(),
viewport.screenX(marker.longitudeDeg()).toFloat(),
viewport.screenY(marker.latitudeDeg()).toFloat(),
MARKER_HIT_RADIUS_PX,
)
}
val text = when {
selectedTargetUnderPointer != null -> selectedTargetUnderPointer.tooltipText()
val text = when {
clusterUnderPointer != null -> MapMarkerClusterTooltip.build(clusterUnderPointer)
markerUnderPointer != null -> markerUnderPointer.tooltipText()
@@ -880,8 +804,8 @@ private fun DrawScope.drawWorkedGrossFields(
workedGrossFields: Set<String>,
) {
visibleWorkedGrossFieldCells(viewport, workedGrossFields).forEach { cell ->
val left = viewport.screenXWrapped(cell.westLon()).toFloat()
val right = viewport.screenXWrapped(cell.eastLon()).toFloat()
val left = viewport.screenX(cell.westLon()).toFloat()
val right = viewport.screenX(cell.eastLon()).toFloat()
val top = viewport.screenY(cell.northLat()).toFloat()
val bottom = viewport.screenY(cell.southLat()).toFloat()
val topLeft = Offset(minOf(left, right), minOf(top, bottom))
@@ -939,7 +863,7 @@ private fun clusterFontSizePx(count: Int): Float = when {
}
/** Null rather than a guess when the operator has no usable locator configured. */
internal fun homePosition(ownLocator6: String): Pair<Double, Double>? {
private fun homePosition(ownLocator6: String): Pair<Double, Double>? {
if (ownLocator6.length < 4) {
return null
}
@@ -951,15 +875,6 @@ internal fun homePosition(ownLocator6: String): Pair<Double, Double>? {
}
}
internal fun isAntennaSectorDrawable(
home: Pair<Double, Double>?,
antennaAzimuthDeg: Double,
antennaBeamWidthDeg: Double,
maxQrbKm: Double,
): Boolean = home != null && antennaAzimuthDeg.isFinite() &&
antennaBeamWidthDeg.isFinite() && antennaBeamWidthDeg > 0.0 &&
maxQrbKm.isFinite() && maxQrbKm > 0.0
fun calculateDestinationPoint(
startLatDeg: Double,
startLonDeg: Double,
@@ -1067,20 +982,16 @@ private const val CLUSTER_RADIUS_SMALL_PX = 16f
private const val CLUSTER_RADIUS_MEDIUM_PX = 18f
private const val CLUSTER_RADIUS_LARGE_PX = 21f
internal val ANTENNA_OVERLAY_COLOR = Color(0xFFFF4D4D)
private val BEAM_COLOR = Color(0xFFFF4D4D)
private const val BEAM_FILL_ALPHA = 0.12f
private const val BEAM_STROKE_WIDTH_PX = 2f
private const val HOME_RADIUS_PX = 6f
private const val HOME_INNER_RADIUS_PX = 2f
private val CONNECTION_COLOR_DARK = Color(0xFF52E7FF)
private val CONNECTION_COLOR_LIGHT = Color(0xFF007A9E)
private val CONNECTION_HALO_DARK = Color.White
private val CONNECTION_HALO_LIGHT = Color.Black
private const val CONNECTION_ALPHA = 0.98f
private const val CONNECTION_HALO_ALPHA = 0.82f
private const val CONNECTION_STROKE_WIDTH_PX = 3f
private const val CONNECTION_HALO_WIDTH_PX = 5f
private val CONNECTION_COLOR_DARK = Color(0xFF2FD7FF)
private val CONNECTION_COLOR_LIGHT = Color(0xFF00A4CF)
private const val CONNECTION_ALPHA = 0.85f
private const val CONNECTION_STROKE_WIDTH_PX = 2f
private val CONNECTION_DASH_PX = floatArrayOf(6f, 6f)
private val TOOLTIP_BACKGROUND = Color.White.copy(alpha = 0.92f)
@@ -1,21 +0,0 @@
package kst4contest.view.compose.map
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import kst4contest.model.ChatPreferences
/** Compose-observable map geometry read from the active profile. */
internal class MapDisplaySettingsState(private val prefs: ChatPreferences) {
var antennaBeamWidthDeg: Double by mutableStateOf(prefs.stn_antennaBeamWidthDeg)
private set
var maxQrbKm: Double by mutableStateOf(prefs.stn_maxQRBDefault)
private set
fun refreshFromPreferences() {
antennaBeamWidthDeg = prefs.stn_antennaBeamWidthDeg
maxQrbKm = prefs.stn_maxQRBDefault
}
}
@@ -1,48 +0,0 @@
package kst4contest.view.compose.map
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import kst4contest.view.compose.StationIdentity
/** A deliberate operator action that may move the station-map camera. */
internal sealed interface MapNavigationRequest {
data class FitSelectedPath(val identity: StationIdentity) : MapNavigationRequest
data class CenterOnQtf(val qtfDegrees: Double) : MapNavigationRequest
data object ResetToHome : MapNavigationRequest
}
/**
* The latest deliberate map-navigation request.
*
* Ordinary model refreshes never write this state. Keeping one monotonically increasing
* revision makes repeated selections observable and gives the most recent station or QTF
* action deterministic precedence when several actions happen before the map draws.
*/
internal class MapNavigationState {
var request: MapNavigationRequest? by mutableStateOf(null)
private set
var requestRevision: Long by mutableStateOf(0L)
private set
fun fitSelectedPath(identity: StationIdentity) {
publish(MapNavigationRequest.FitSelectedPath(identity))
}
fun centerOnQtf(qtfDegrees: Double) {
if (!qtfDegrees.isFinite() || qtfDegrees !in 0.0..360.0) return
publish(MapNavigationRequest.CenterOnQtf(qtfDegrees))
}
fun resetToHome() {
publish(MapNavigationRequest.ResetToHome)
}
private fun publish(next: MapNavigationRequest) {
request = next
requestRevision++
}
}
@@ -1,79 +0,0 @@
package kst4contest.view.compose.map
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.TooltipArea
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.size
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import kst4contest.view.compose.TooltipCard
import kst4contest.view.i18n.LocalStrings
@OptIn(ExperimentalFoundationApi::class, ExperimentalLayoutApi::class)
@Composable
internal fun MapOverlayLegend(
showAntenna: Boolean,
showSpatialFilters: Boolean,
darkMode: Boolean,
modifier: Modifier = Modifier,
) {
if (!showAntenna && !showSpatialFilters) return
val strings = LocalStrings.current
TooltipArea(
tooltip = { TooltipCard(strings.mapOverlayLegendTooltip) },
modifier = modifier,
) {
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(2.dp),
itemVerticalAlignment = Alignment.CenterVertically,
) {
if (showAntenna) {
LegendItem(
color = ANTENNA_OVERLAY_COLOR,
label = strings.mapOverlayAntenna,
tag = MAP_ANTENNA_LEGEND_TAG,
)
}
if (showSpatialFilters) {
LegendItem(
color = spatialFilterOverlayLineColor(darkMode),
label = strings.mapOverlayFilters,
tag = MAP_FILTER_LEGEND_TAG,
)
}
}
}
}
@Composable
private fun LegendItem(color: Color, label: String, tag: String) {
Row(
modifier = Modifier.testTag(tag),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
androidx.compose.foundation.layout.Box(
Modifier
.size(9.dp)
.clip(androidx.compose.foundation.shape.CircleShape)
.background(color),
)
Text(text = label, style = MaterialTheme.typography.bodySmall)
}
}
internal const val MAP_ANTENNA_LEGEND_TAG = "station-map-antenna-legend"
internal const val MAP_FILTER_LEGEND_TAG = "station-map-filter-legend"
@@ -1,273 +0,0 @@
package kst4contest.view.compose.map
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import kst4contest.locatorUtils.DirectionUtils
import kst4contest.view.map.MapViewport
import kst4contest.view.map.PathGeometryUtils
import kotlin.math.ceil
/** Immutable effective QTF/QRB filter values drawn by the station map. */
data class SpatialFilterOverlayState(
val qtfEnabled: Boolean,
val qtfDegrees: Double,
val beamWidthDeg: Double,
val minQrbEnabled: Boolean,
val minQrbKm: Double,
val maxQrbEnabled: Boolean,
val maxQrbKm: Double,
) {
val isActive: Boolean
get() = qtfEnabled || minQrbEnabled || maxQrbEnabled
val hasEmptyDistanceRange: Boolean
get() = minQrbEnabled && maxQrbEnabled && minQrbKm >= maxQrbKm
val hasRenderableValues: Boolean
get() = (!qtfEnabled || qtfDegrees.isFinite() && beamWidthDeg.isFinite()) &&
(!minQrbEnabled || minQrbKm.isFinite()) &&
(!maxQrbEnabled || maxQrbKm.isFinite())
/** True when the current values produce at least one visible fill or boundary. */
val hasDrawableGeometry: Boolean
get() {
if (!isActive || !hasRenderableValues) return false
if (minQrbEnabled && !maxQrbEnabled) return true
if (minQrbEnabled && minQrbKm > 0.0) return true
if (maxQrbEnabled && maxQrbKm > 0.0) return true
return qtfEnabled && !maxQrbEnabled
}
/** Mirrors the filter predicate: minimum exclusive, maximum inclusive. */
fun accepts(distanceKm: Double, bearingDeg: Double): Boolean {
if (!distanceKm.isFinite() || !bearingDeg.isFinite()) return false
if (minQrbEnabled && distanceKm <= minQrbKm) return false
if (maxQrbEnabled && distanceKm > maxQrbKm) return false
if (qtfEnabled && !DirectionUtils.isAngleInRange(bearingDeg, qtfDegrees, beamWidthDeg)) return false
return true
}
}
internal fun DrawScope.drawSpatialFilterOverlay(
viewport: MapViewport,
homeLatitudeDeg: Double,
homeLongitudeDeg: Double,
state: SpatialFilterOverlayState,
darkMode: Boolean,
) {
if (!state.hasDrawableGeometry ||
!homeLatitudeDeg.isFinite() || !homeLongitudeDeg.isFinite()
) return
val fillColor = if (darkMode) FILTER_FILL_DARK else FILTER_FILL_LIGHT
val lineColor = spatialFilterOverlayLineColor(darkMode)
val angular = state.qtfEnabled && state.beamWidthDeg.isFinite()
val validAngularArea = !angular || state.beamWidthDeg > 0.0 && state.beamWidthDeg < 360.0
val visibleRadius = visibleRadiusKm(viewport, homeLatitudeDeg, homeLongitudeDeg)
val outerRadius = if (state.maxQrbEnabled) state.maxQrbKm else visibleRadius
val innerRadius = if (state.minQrbEnabled) state.minQrbKm else 0.0
if (!state.hasEmptyDistanceRange && validAngularArea && outerRadius > innerRadius && outerRadius > 0.0) {
val fillPath = when {
angular -> annularSectorPath(
viewport,
homeLatitudeDeg,
homeLongitudeDeg,
state.qtfDegrees,
state.beamWidthDeg,
innerRadius.coerceAtLeast(0.0),
outerRadius,
)
state.minQrbEnabled && !state.maxQrbEnabled -> outsideCirclePath(
viewport,
homeLatitudeDeg,
homeLongitudeDeg,
innerRadius.coerceAtLeast(0.0),
)
else -> ringPath(
viewport,
homeLatitudeDeg,
homeLongitudeDeg,
innerRadius.coerceAtLeast(0.0),
outerRadius,
)
}
drawPath(fillPath, fillColor, style = Fill)
}
val stroke = Stroke(
width = FILTER_LINE_WIDTH_PX,
pathEffect = PathEffect.dashPathEffect(FILTER_DASH_PX),
)
if (state.minQrbEnabled && state.minQrbKm > 0.0) {
drawPath(circlePath(viewport, homeLatitudeDeg, homeLongitudeDeg, state.minQrbKm), lineColor, style = stroke)
}
if (state.maxQrbEnabled && state.maxQrbKm > 0.0) {
drawPath(circlePath(viewport, homeLatitudeDeg, homeLongitudeDeg, state.maxQrbKm), lineColor, style = stroke)
}
if (angular) {
val boundaryRadius = if (state.maxQrbEnabled) state.maxQrbKm else visibleRadius
val halfWidth = state.beamWidthDeg.coerceAtLeast(0.0) / 2.0
listOf(state.qtfDegrees - halfWidth, state.qtfDegrees + halfWidth).forEach { bearing ->
val endpoint = calculateDestinationPoint(
homeLatitudeDeg,
homeLongitudeDeg,
bearing,
boundaryRadius,
)
drawLine(
color = lineColor,
start = Offset(
viewport.screenXWrapped(homeLongitudeDeg).toFloat(),
viewport.screenY(homeLatitudeDeg).toFloat(),
),
end = Offset(
viewport.screenXWrapped(endpoint.second).toFloat(),
viewport.screenY(endpoint.first).toFloat(),
),
strokeWidth = FILTER_LINE_WIDTH_PX,
pathEffect = PathEffect.dashPathEffect(FILTER_DASH_PX),
)
}
}
}
private fun outsideCirclePath(
viewport: MapViewport,
homeLatitudeDeg: Double,
homeLongitudeDeg: Double,
radiusKm: Double,
): Path = Path().apply {
fillType = PathFillType.EvenOdd
addRect(Rect(0f, 0f, viewport.widthPx().toFloat(), viewport.heightPx().toFloat()))
addPath(circlePath(viewport, homeLatitudeDeg, homeLongitudeDeg, radiusKm))
}
private fun ringPath(
viewport: MapViewport,
homeLatitudeDeg: Double,
homeLongitudeDeg: Double,
innerRadiusKm: Double,
outerRadiusKm: Double,
): Path = Path().apply {
fillType = PathFillType.EvenOdd
addPath(circlePath(viewport, homeLatitudeDeg, homeLongitudeDeg, outerRadiusKm))
if (innerRadiusKm > 0.0) {
addPath(circlePath(viewport, homeLatitudeDeg, homeLongitudeDeg, innerRadiusKm))
}
}
private fun annularSectorPath(
viewport: MapViewport,
homeLatitudeDeg: Double,
homeLongitudeDeg: Double,
centerBearingDeg: Double,
beamWidthDeg: Double,
innerRadiusKm: Double,
outerRadiusKm: Double,
): Path {
val halfWidth = beamWidthDeg / 2.0
val outer = arcPoints(
homeLatitudeDeg,
homeLongitudeDeg,
centerBearingDeg - halfWidth,
beamWidthDeg,
outerRadiusKm,
)
val inner = if (innerRadiusKm > 0.0) {
arcPoints(
homeLatitudeDeg,
homeLongitudeDeg,
centerBearingDeg - halfWidth,
beamWidthDeg,
innerRadiusKm,
).asReversed()
} else {
listOf(homeLatitudeDeg to homeLongitudeDeg)
}
return pathThrough(viewport, outer + inner, close = true)
}
private fun circlePath(
viewport: MapViewport,
homeLatitudeDeg: Double,
homeLongitudeDeg: Double,
radiusKm: Double,
): Path = pathThrough(
viewport,
arcPoints(homeLatitudeDeg, homeLongitudeDeg, 0.0, 360.0, radiusKm),
close = true,
)
private fun arcPoints(
homeLatitudeDeg: Double,
homeLongitudeDeg: Double,
startBearingDeg: Double,
sweepDeg: Double,
radiusKm: Double,
): List<Pair<Double, Double>> {
val segmentCount = maxOf(24, ceil(kotlin.math.abs(sweepDeg) / 3.0).toInt())
return (0..segmentCount).map { segment ->
calculateDestinationPoint(
homeLatitudeDeg,
homeLongitudeDeg,
startBearingDeg + sweepDeg * segment / segmentCount,
radiusKm,
)
}
}
private fun pathThrough(
viewport: MapViewport,
points: List<Pair<Double, Double>>,
close: Boolean,
): Path = Path().apply {
points.forEachIndexed { index, point ->
val x = viewport.screenXWrapped(point.second).toFloat()
val y = viewport.screenY(point.first).toFloat()
if (index == 0) moveTo(x, y) else lineTo(x, y)
}
if (close && points.isNotEmpty()) close()
}
private fun visibleRadiusKm(
viewport: MapViewport,
homeLatitudeDeg: Double,
homeLongitudeDeg: Double,
): Double {
val corners = listOf(
viewport.northLat() to viewport.westLon(),
viewport.northLat() to viewport.eastLon(),
viewport.southLat() to viewport.westLon(),
viewport.southLat() to viewport.eastLon(),
)
val farthestCorner = corners.maxOfOrNull { (latitude, longitude) ->
PathGeometryUtils.calculateGreatCircleDistanceKm(
homeLatitudeDeg,
homeLongitudeDeg,
latitude,
longitude,
)
} ?: 0.0
return farthestCorner * VIEWPORT_RADIUS_MARGIN
}
private val FILTER_FILL_LIGHT = Color(0xFF5B4BC4).copy(alpha = 0.16f)
private val FILTER_FILL_DARK = Color(0xFF78A9FF).copy(alpha = 0.18f)
private val FILTER_LINE_LIGHT = Color(0xFF4937B8).copy(alpha = 0.88f)
private val FILTER_LINE_DARK = Color(0xFF8CB8FF).copy(alpha = 0.92f)
internal fun spatialFilterOverlayLineColor(darkMode: Boolean): Color =
if (darkMode) FILTER_LINE_DARK else FILTER_LINE_LIGHT
private const val FILTER_LINE_WIDTH_PX = 2f
private val FILTER_DASH_PX = floatArrayOf(7f, 5f)
private const val VIEWPORT_RADIUS_MARGIN = 1.12
@@ -11,8 +11,6 @@ import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextOverflow
@@ -28,7 +26,6 @@ import kst4contest.view.compose.StationContextOverlays
import kst4contest.view.compose.StationSelectionSource
import kst4contest.view.map.MapCallsignRawSnapshotBuilder
import kst4contest.view.map.PathAnalysisResult
import kst4contest.view.map.MapViewportNavigation
import kst4contest.view.map.StationMapStatusText
import kst4contest.view.map.TileFetcher
import java.util.EnumSet
@@ -111,8 +108,9 @@ object StationMapWindow {
* @param chatMembers the roster a marker click looks its station up in; a marker stands
* for a raw callsign, and this is where its category variants come from
* @param mapState where the map is looking
* @param pathAnalysis asked for an explicit selection; null disables only the terrain
* analysis while viewport navigation remains available
* @param pathAnalysis asked each time the selection changes; null means there is no
* running application, and then the map neither pans nor analyses, exactly as
* when no chat controller existed before the split
*/
@Composable
internal fun Content(
@@ -153,8 +151,8 @@ object StationMapWindow {
val ownLocator6 by remember { androidx.compose.runtime.mutableStateOf(mainWindowState.prefs.stn_loginLocatorMainCat) }
val antennaAzimuthDeg = mainWindowState.antennaQtf.value
val antennaBeamWidthDeg = mainWindowState.mapDisplaySettings.antennaBeamWidthDeg
val maxQrbKm = mainWindowState.mapDisplaySettings.maxQrbKm
val antennaBeamWidthDeg = mainWindowState.prefs.stn_antennaBeamWidthDeg
val maxQrbKm = mainWindowState.prefs.stn_maxQRBDefault
/*
* The markers are the stations the list shows, not all of them (#21): the
@@ -186,37 +184,20 @@ object StationMapWindow {
}
}
/*
* Selection is independent of the filtered marker set. A selected station
* remains a target even when an active filter removes its normal marker; it is
* drawn in a separate selection layer and never enters marker counts or clusters.
*/
val selectedTarget by remember(
selectedMember,
mainWindowState.stations.contentRevision,
mainWindowState.activeBands,
) {
derivedStateOf {
selectedMember?.let { selected ->
val variants = chatMembers().filter { it.callSignRaw == selected.callSignRaw }
.ifEmpty { listOf(selected) }
val bands = EnumSet.noneOf(Band::class.java).apply {
addAll(mainWindowState.activeBands)
}
MapCallsignRawSnapshotBuilder()
.buildSnapshots(variants, selected, bands)
.firstOrNull()
}
}
}
var pathAnalysisResult by remember { mutableStateOf<PathAnalysisResult?>(null) }
var automaticAnalysisRevision by remember { mutableStateOf(0L) }
// Read through updated state so a caller passing a new lambda is never served a stale one.
val currentPathAnalysis by rememberUpdatedState(pathAnalysis)
LaunchedEffect(mainWindowState.stationSelection.explicitSelectionRevision) {
/*
* Whether the selected station has a marker. A filter can hide it (#21), and a
* station without a locator never has one; then there is nothing to analyse.
*/
val selectedHasMarker = selectedMember != null &&
markers.any { it.callSignRaw() == selectedMember.callSignRaw }
LaunchedEffect(selectedMember, selectedHasMarker) {
val automaticRequest = ++automaticAnalysisRevision
val explicitRevisionAtStart = mainWindowState.mapReachability.requestRevision
if (selectedMember == null) {
@@ -224,15 +205,34 @@ object StationMapWindow {
return@LaunchedEffect
}
val selectedSnapshot = selectedTarget
val selectedSnapshot = markers.find { it.callSignRaw() == selectedMember.callSignRaw }
if (selectedSnapshot == null) {
// No valid locator: no request and no misleading loading state.
// No marker: no request, and no "Loading" for a station the map does not show.
pathAnalysisResult = null
return@LaunchedEffect
}
val analysis = currentPathAnalysis()
if (analysis != null) {
if (selectedSnapshot.hasUsablePosition()) {
/*
* Pan to the station and leave the zoom alone. The Leaflet map
* did exactly this (focusCallsignRaw) and touched the zoom only
* when the station was hidden inside a bubble, and then only far
* enough to break the bubble open. An earlier Compose version
* recomputed a zoom from a bounding box on every selection and
* clamped it into 4..12, which threw an operator working at zoom
* 15 out to about 7 every time they picked the next station.
* AGENTS.md names zoom first among the things not to change as
* an incidental side effect.
*/
mapState.centerLon = selectedSnapshot.longitudeDeg()
mapState.centerLat = selectedSnapshot.latitudeDeg()
mapState.zoom = kst4contest.view.map.StationMapClusterer
.zoomToRevealStations(mapState.zoom.toDouble(), groupingEnabled)
.toFloat()
}
pathAnalysisResult = PathAnalysisResult.loading(
prefs.stn_loginLocatorMainCat,
selectedSnapshot.locator6(),
@@ -249,72 +249,6 @@ object StationMapWindow {
}
}
var mapCanvasSize by remember { mutableStateOf(Size.Zero) }
var consumedNavigationRevision by remember(mapState) { mutableStateOf(Long.MIN_VALUE) }
val navigationRevision = mainWindowState.mapNavigation.requestRevision
val navigationRequest = mainWindowState.mapNavigation.request
val navigationPaddingPx = with(LocalDensity.current) { 40.dp.toPx().toDouble() }
LaunchedEffect(
navigationRevision,
navigationRequest,
mapCanvasSize,
selectedTarget,
ownLocator6,
) {
if (navigationRevision == consumedNavigationRevision ||
mapCanvasSize.width <= 0f || mapCanvasSize.height <= 0f
) {
return@LaunchedEffect
}
val home = runCatching { kst4contest.locatorUtils.Location(ownLocator6) }.getOrNull()
val current = mapState.viewportFor(mapCanvasSize.width, mapCanvasSize.height)
val next = when (val request = navigationRequest) {
is MapNavigationRequest.FitSelectedPath -> {
val target = selectedTarget
if (home == null || target == null || !target.hasUsablePosition() ||
request.identity != StationIdentity.of(selectedMember)
) {
null
} else {
MapViewportNavigation.fitPath(
current,
home.latitude.toDegrees(),
home.longitude.toDegrees(),
target.latitudeDeg(),
target.longitudeDeg(),
navigationPaddingPx,
)
}
}
is MapNavigationRequest.CenterOnQtf -> {
if (home == null) null else MapViewportNavigation.centreOnBearing(
current,
home.latitude.toDegrees(),
home.longitude.toDegrees(),
request.qtfDegrees,
QTF_FORWARD_CENTRE_FRACTION,
)
}
MapNavigationRequest.ResetToHome -> {
if (home == null) null else MapViewportNavigation.centreOnHome(
current,
home.latitude.toDegrees(),
home.longitude.toDegrees(),
)
}
null -> null
}
consumedNavigationRevision = navigationRevision
if (next != null) {
mapState.applyFrom(next)
}
}
val explicitReachabilityResult = mainWindowState.mapReachability.result
LaunchedEffect(mainWindowState.mapReachability.requestRevision, explicitReachabilityResult) {
if (explicitReachabilityResult != null) {
@@ -330,24 +264,6 @@ object StationMapWindow {
} else {
emptySet()
}
val spatialFilterOverlay = SpatialFilterOverlayState(
qtfEnabled = mainWindowState.stationFilter.qtfEnabled,
qtfDegrees = mainWindowState.stationFilter.qtfDegrees,
beamWidthDeg = antennaBeamWidthDeg,
minQrbEnabled = mainWindowState.stationFilter.minQrbEnabled,
minQrbKm = mainWindowState.stationFilter.minQrbKm,
maxQrbEnabled = mainWindowState.stationFilter.maxQrbEnabled,
maxQrbKm = mainWindowState.stationFilter.maxQrbKm,
)
val mapHome = remember(ownLocator6) { homePosition(ownLocator6) }
val showAntennaOverlay = isAntennaSectorDrawable(
mapHome,
antennaAzimuthDeg ?: 0.0,
antennaBeamWidthDeg,
maxQrbKm,
)
val showSpatialFilterOverlay = mapHome != null && spatialFilterOverlay.hasDrawableGeometry
val isDarkTheme = isDarkThemeState.value
androidx.compose.material3.Surface(
color = androidx.compose.material3.MaterialTheme.colorScheme.background,
@@ -372,7 +288,7 @@ object StationMapWindow {
markers.size,
mainWindowState.stationFilter.activeFilters.isNotEmpty() ||
mainWindowState.stationFilter.searchText.isNotBlank(),
selectedTarget,
markers.firstOrNull { it.callSignRaw() == selectedMember?.callSignRaw },
)
/*
@@ -392,12 +308,6 @@ object StationMapWindow {
)
}
MapOverlayLegend(
showAntenna = showAntennaOverlay,
showSpatialFilters = showSpatialFilterOverlay,
darkMode = isDarkTheme,
)
if (selectedMember != null) {
kst4contest.view.compose.Form.button(strings.mapTriggerClusterSpot) {
ApplicationRuntimeLauncher.getCurrent()?.chatController
@@ -407,6 +317,12 @@ object StationMapWindow {
kst4contest.view.compose.Form.button(strings.mapResetView) {
mainWindowState.selectStation(null, StationSelectionSource.RESET_VIEW)
val home = runCatching {
kst4contest.locatorUtils.Location(ownLocator6)
}.getOrNull()
mapState.centerLon = home?.longitude?.toDegrees() ?: 10.0
mapState.centerLat = home?.latitude?.toDegrees() ?: 51.0
/* The zoom is deliberately left alone; see AGENTS.md, UI behaviour. */
}
kst4contest.view.compose.Form.button(strings.filterReset) {
@@ -472,6 +388,7 @@ object StationMapWindow {
val leftPane: @Composable () -> Unit = {
Column(Modifier.fillMaxHeight()) {
val isDarkTheme = isDarkThemeState.value
androidx.compose.foundation.layout.Box(Modifier.weight(1f).fillMaxWidth()) {
ComposeStationMap(
markers = markers,
@@ -483,11 +400,8 @@ object StationMapWindow {
antennaAzimuthDeg = antennaAzimuthDeg ?: 0.0,
antennaBeamWidthDeg = antennaBeamWidthDeg,
maxQrbKm = maxQrbKm,
selectedTarget = selectedTarget,
spatialFilterOverlay = spatialFilterOverlay,
darkMode = isDarkTheme,
workedGrossFields = workedGrossFields,
onCanvasSizeChanged = { mapCanvasSize = it },
onMarkerClicked = { snapshot ->
val variants = chatMembers()
.filter { it.callSignRaw == snapshot.callSignRaw() }
@@ -587,7 +501,6 @@ object StationMapWindow {
internal const val MAP_CANVAS_TAG = "station-map-canvas"
internal const val GROUPING_TAG = "station-map-grouping"
internal const val ALWAYS_ON_TOP_TAG = "station-map-always-on-top"
private const val QTF_FORWARD_CENTRE_FRACTION = 0.25
@JvmStatic
fun applyDarkMode(darkMode: Boolean) {
@@ -4,11 +4,9 @@ import kst4contest.view.i18n.LocalStrings
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kst4contest.view.compose.Form
import kst4contest.view.compose.observeAsState
/**
* The beacon tab: one CQ template per chat category and the interval they share.
@@ -20,14 +18,12 @@ import kst4contest.view.compose.observeAsState
@Composable
fun BeaconTab(state: BeaconTabState, onRefused: (String) -> Unit) {
val strings = LocalStrings.current
val mainEnabled by state.mainBeaconEnabled.observeAsState()
val secondEnabled by state.secondBeaconEnabled.observeAsState()
Column(
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Form.section(strings.beaconSectionFor(state.mainCategoryName)) {
Form.check(strings.beaconEnabled, mainEnabled == true) {
Form.check(strings.beaconEnabled, state.bcn_beaconsEnabledMainCat) {
state.bcn_beaconsEnabledMainCat = it
}
Form.committed(
@@ -40,7 +36,7 @@ fun BeaconTab(state: BeaconTabState, onRefused: (String) -> Unit) {
}
Form.section(strings.beaconSectionFor(state.secondCategoryName)) {
Form.check(strings.beaconEnabled, secondEnabled == true) {
Form.check(strings.beaconEnabled, state.bcn_beaconsEnabledSecondCat) {
state.bcn_beaconsEnabledSecondCat = it
}
Form.committed(
@@ -12,9 +12,8 @@ import kst4contest.view.compose.setting
* The two commit methods are the ports of `applyBeaconTextSetting` and
* `applySharedBeaconInterval`. Both returned nothing and opened an alert; here they
* return the refusal text instead, so the tab decides how to show it and a test can
* read it. Accepted templates and intervals are staged in the window's [SettingsDraft]
* and take effect when the operator applies them. The two enable switches deliberately
* bypass the draft so the running timer sees their values immediately.
* read it. An accepted value is staged in the window's [SettingsDraft] and takes effect
* when the operator applies it; a refused one never gets there.
*
* @param validateBeaconTemplate throws IllegalArgumentException with the reason,
* the contract of `ChatController.validateBeaconTemplate`.
@@ -28,32 +27,22 @@ class BeaconTabState(
private val restartBeaconTimer: () -> Unit,
val mainCategoryName: String,
val secondCategoryName: String,
private val setMainBeaconEnabled: (Boolean) -> Unit = prefs::setBcn_beaconsEnabledMainCat,
private val setSecondBeaconEnabled: (Boolean) -> Unit = prefs::setBcn_beaconsEnabledSecondCat,
private val onBeaconTemplatesApplied: () -> Unit = {},
) {
val mainBeaconEnabled = prefs.bcnBeaconsEnabledMainCatProperty()
val secondBeaconEnabled = prefs.bcnBeaconsEnabledSecondCatProperty()
var bcn_beaconsEnabledMainCat: Boolean by draft.setting(
{ prefs.isBcn_beaconsEnabledMainCat() },
) { prefs.setBcn_beaconsEnabledMainCat(it) }
var bcn_beaconsEnabledMainCat: Boolean
get() = prefs.isBcn_beaconsEnabledMainCat()
set(value) = setMainBeaconEnabled(value)
var bcn_beaconsEnabledSecondCat: Boolean
get() = prefs.isBcn_beaconsEnabledSecondCat()
set(value) = setSecondBeaconEnabled(value)
var bcn_beaconsEnabledSecondCat: Boolean by draft.setting(
{ prefs.isBcn_beaconsEnabledSecondCat() },
) { prefs.setBcn_beaconsEnabledSecondCat(it) }
private var textMainCat: String by draft.setting(
{ prefs.getBcn_beaconTextMainCat() },
effectKey = BEACON_TEMPLATE_EFFECT,
effect = onBeaconTemplatesApplied,
) { prefs.setBcn_beaconTextMainCat(it) }
private var textSecondCat: String by draft.setting(
{ prefs.getBcn_beaconTextSecondCat() },
effectKey = BEACON_TEMPLATE_EFFECT,
effect = onBeaconTemplatesApplied,
) { prefs.setBcn_beaconTextSecondCat(it) }
/*
@@ -80,7 +69,7 @@ class BeaconTabState(
*
* The clamp is not cosmetic: a stored zero would otherwise be displayed as a
* valid setting while `ChatController` sends at the minimum anyway
* when scheduling the timer. The JavaFX field applied the same `Math.max` when it
* (ChatController:3425). The JavaFX field applied the same `Math.max` when it
* restored the value after a rejected entry.
*/
val beaconIntervalMinutes: Int
@@ -128,8 +117,4 @@ class BeaconTabState(
interval = minutes
return null
}
private companion object {
const val BEACON_TEMPLATE_EFFECT = "beaconTemplates"
}
}
@@ -44,10 +44,6 @@ class StationTabState(
* TRX synch tab through [SECOND_ROTATOR], so it runs once per apply.
*/
private val applySecondRotator: () -> Unit = {},
/** Recomputes status whose available-count depends on the second-chat switch. */
private val refreshBeaconStatus: () -> Unit = {},
/** Repaints applied beam geometry and dependent QTF results in the running UI. */
private val applyMapDisplaySettings: () -> Unit = {},
) {
var loginChatCategoryMain: ChatCategory?
@@ -59,11 +55,7 @@ class StationTabState(
get() = prefs.getLoginChatCategorySecond()
set(value) { prefs.setLoginChatCategorySecond(value) }
var stn_antennaBeamWidthDeg: Double by draft.setting(
{ prefs.getStn_antennaBeamWidthDeg() },
effectKey = MAP_DISPLAY_SETTINGS,
effect = applyMapDisplaySettings,
) { prefs.setStn_antennaBeamWidthDeg(it) }
var stn_antennaBeamWidthDeg: Double by draft.setting({ prefs.getStn_antennaBeamWidthDeg() }) { prefs.setStn_antennaBeamWidthDeg(it) }
var stn_bandActive10G: Boolean by draft.setting({ prefs.isStn_bandActive10G() }) { prefs.setStn_bandActive10G(it) }
@@ -103,11 +95,7 @@ class StationTabState(
get() = prefs.getStn_loginPassword()
set(value) { prefs.setStn_loginPassword(value) }
var stn_maxQRBDefault: Double by draft.setting(
{ prefs.getStn_maxQRBDefault() },
effectKey = MAP_DISPLAY_SETTINGS,
effect = applyMapDisplaySettings,
) { prefs.setStn_maxQRBDefault(it) }
var stn_maxQRBDefault: Double by draft.setting({ prefs.getStn_maxQRBDefault() }) { prefs.setStn_maxQRBDefault(it) }
var stn_on4kstServersDns: String by draft.setting({ prefs.getStn_on4kstServersDns() }) { prefs.setStn_on4kstServersDns(it) }
@@ -246,10 +234,7 @@ class StationTabState(
* pickers it governs. It decides what the Connect button does, so it belongs with
* the login settings and not with the display options.
*/
var loginToSecondChatEnabled: Boolean by draft.setting(
{ prefs.isLoginToSecondChatEnabled() },
effect = { refreshBeaconStatus() },
) { prefs.setLoginToSecondChatEnabled(it) }
var loginToSecondChatEnabled: Boolean by draft.setting({ prefs.isLoginToSecondChatEnabled() }) { prefs.setLoginToSecondChatEnabled(it) }
/**
* Whether the login fields may be edited. The JavaFX window disabled callsign,
@@ -304,9 +289,6 @@ class StationTabState(
/** The effect key of everything that restarts rotator 2; shared with the TRX synch tab. */
const val SECOND_ROTATOR: String = "secondRotator"
/** Shared effect for the two settings that define the map's antenna sector. */
const val MAP_DISPLAY_SETTINGS: String = "mapDisplaySettings"
/**
* Whether two PSTRotator ports collide: the same port, or one apart because
* PSTRotator answers on port + 1, which would be the other client's local port.
@@ -1,60 +0,0 @@
package kst4contest.view
import kst4contest.controller.ChatController
import kst4contest.model.ChatMessage
import kst4contest.view.compose.DataTableState
import kst4contest.view.compose.RowKeys
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.mockito.Mockito.mock
import org.mockito.Mockito.`when`
class ComposeMessageTableRefreshTest {
@Test
fun `refresh keeps public table on the filtered controller view`() {
val controller = mock(ChatController::class.java)
val privateToMe = message("private to me")
val publicInitial = message("public initial")
val betweenOthers = message("between others")
val directed = table()
val publicMessages = table()
val qsoOfTheOther = table()
`when`(controller.toMeMessages()).thenReturn(listOf(privateToMe))
`when`(controller.toAllMessages()).thenReturn(listOf(publicInitial))
`when`(controller.toOtherMessages()).thenReturn(listOf(betweenOthers))
Kst4ContestApplication.refreshComposeMessageTables(
controller,
directed,
publicMessages,
qsoOfTheOther,
)
assertEquals(listOf(privateToMe), directed.rows)
assertEquals(listOf(publicInitial), publicMessages.rows)
assertEquals(listOf(betweenOthers), qsoOfTheOther.rows)
val publicLater = message("public later")
`when`(controller.toAllMessages()).thenReturn(listOf(publicLater, publicInitial))
Kst4ContestApplication.refreshComposeMessageTables(
controller,
directed,
publicMessages,
qsoOfTheOther,
)
assertEquals(listOf(publicLater, publicInitial), publicMessages.rows)
}
private fun table() = DataTableState(
columns = emptyList(),
rowKey = RowKeys.byReference<ChatMessage>(),
)
private fun message(text: String) = ChatMessage().apply {
messageText = text
}
}
@@ -1,58 +0,0 @@
package kst4contest.view.compose
import androidx.compose.ui.graphics.Color
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
class BeaconStatusColorsTest {
private val neutral = Color(0xFF123456)
@Test
fun `active and activity colours are the approved traffic colours`() {
assertEquals(
ThreadButtonColors(Color(0xFF238636), Color(0xFF56D364), Color.White),
beaconThreadButtonColors(ThreadStatusVisualStyle.BEACON_ACTIVE, false, false, neutral),
)
assertEquals(
ThreadButtonColors(Color(0xFFFFB300), Color(0xFFFFE082), Color(0xFF1B1B1B)),
beaconThreadButtonColors(ThreadStatusVisualStyle.BEACON_ACTIVE, true, false, neutral),
)
}
@Test
fun `off uses neutral background and theme specific red text`() {
assertEquals(Color(0xFFD50000),
beaconThreadButtonColors(ThreadStatusVisualStyle.BEACON_OFF, false, false, neutral).text)
assertEquals(Color(0xFFFF6B6B),
beaconThreadButtonColors(ThreadStatusVisualStyle.BEACON_OFF, false, true, neutral).text)
assertEquals(neutral,
beaconThreadButtonColors(ThreadStatusVisualStyle.BEACON_OFF, false, true, neutral).background)
}
@Test
fun `failed stays red even when a highlight is requested`() {
val colors = beaconThreadButtonColors(
ThreadStatusVisualStyle.BEACON_FAILED,
true,
false,
neutral,
)
assertEquals(ThreadButtonColors(Color(0xFFD50000), Color(0xFFFF6B6B), Color.White), colors)
}
@Test
fun `failed suppresses the flash while active status allows it`() {
val button = ThreadStatusButton("MyBeacon")
button.report("MyBeacon: on", "active", ThreadStatusVisualStyle.BEACON_ACTIVE)
assertTrue(button.highlighted)
button.report("MyBeacon: FAILED", "failed", ThreadStatusVisualStyle.BEACON_FAILED)
assertFalse(button.highlighted)
assertEquals(
ThreadButtonColors(Color(0xFFD50000), Color(0xFFFF6B6B), Color.White),
beaconThreadButtonColors(ThreadStatusVisualStyle.BEACON_FAILED, true, false, neutral),
)
}
}
@@ -1,59 +0,0 @@
package kst4contest.view.compose
import kst4contest.model.BeaconStatusSnapshot
import kst4contest.model.BeaconStatusSnapshot.AggregateState
import kst4contest.model.BeaconStatusSnapshot.CategoryStatus
import kst4contest.model.BeaconStatusSnapshot.InactiveReason
import kst4contest.view.i18n.LanguageStore
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.util.Locale
class BeaconStatusPresentationTest {
@Test
fun `partial status keeps the inactive category reason in English`() {
val presentation = BeaconStatusPresentation.from(snapshot(AggregateState.PARTIAL))
assertEquals("1/2", presentation.label)
assertTrue(presentation.tooltip.contains("Main category: active"))
assertTrue(presentation.tooltip.contains("primary QRG missing or invalid"))
}
@Test
fun `the same category reasons are available in German`() {
val language = LanguageStore({ "de" }, {}, Locale.UK)
try {
val presentation = BeaconStatusPresentation.from(
snapshot(AggregateState.PARTIAL),
language.strings,
)
assertTrue(presentation.tooltip.contains("Hauptkategorie: aktiv"))
assertTrue(presentation.tooltip.contains("Haupt-QRG fehlt oder ist ungültig"))
assertFalse(presentation.tooltip.contains("144."))
} finally {
language.use("en")
}
}
@Test
fun `failed style overrides an active category`() {
val main = CategoryStatus(true, true, true, InactiveReason.USER_DISABLED)
val second = CategoryStatus(false, false, false, InactiveReason.NOT_ACTIVATED_THIS_SESSION)
val presentation = BeaconStatusPresentation.from(
BeaconStatusSnapshot(AggregateState.FAILED, main, second),
)
assertEquals("FAILED", presentation.label)
assertEquals(ThreadStatusVisualStyle.BEACON_FAILED, presentation.style)
assertTrue(presentation.tooltip.contains("send failed"))
}
private fun snapshot(state: AggregateState): BeaconStatusSnapshot = BeaconStatusSnapshot(
state,
CategoryStatus(true, true, false, InactiveReason.USER_DISABLED),
CategoryStatus(true, false, false, InactiveReason.PRIMARY_QRG_UNAVAILABLE),
)
}
@@ -5,7 +5,6 @@ import androidx.compose.ui.text.input.TextFieldValue
import kst4contest.model.ChatCategory
import kst4contest.model.ChatMember
import kst4contest.model.ChatMessage
import kst4contest.controller.RadioSlot
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertSame
@@ -234,20 +233,6 @@ class ChatInputStateTest {
assertEquals("432.200 ", state.value.text)
}
@Test
fun `manual QRG commits keep their radio source explicit`() {
val actions = FakeActions()
val state = ChatInputState(actions)
state.commitOwnQrg(mainCategory = true, "144.300")
state.commitOwnQrg(mainCategory = false, "1296.100")
assertEquals(
listOf(RadioSlot.FIRST to "144.300", RadioSlot.SECOND to "1296.100"),
actions.manualQrgs,
)
}
// ---- the snippets ------------------------------------------------------
/**
@@ -422,7 +407,6 @@ class ChatInputStateTest {
val resolvedTemplates = mutableListOf<String>()
val recordedCqs = mutableListOf<String>()
val recomputeReasons = mutableListOf<String>()
val manualQrgs = mutableListOf<Pair<RadioSlot, String>>()
override fun panelSelection(): ChatMember? = panelSelection
override fun tableSelection(): ChatMember? = tableSelection
@@ -447,6 +431,5 @@ class ChatInputStateTest {
override fun queue(message: ChatMessage) { queued += message }
override fun ownQrgMain(): String = ownQrgMain
override fun ownQrgSecond(): String = ownQrgSecond
override fun applyManualQrg(slot: RadioSlot, value: String) { manualQrgs += slot to value }
}
}
@@ -35,9 +35,7 @@ class SettingsFieldCoverageTest {
""
}
val missing = expected.filterNot {
composeSources.contains("$it(") || composeSources.contains("::$it")
}
val missing = expected.filterNot { composeSources.contains("$it(") }
assertTrue(missing.isEmpty(),
"settings not written by any Compose source (${missing.size} of ${expected.size}):\n" +
@@ -70,27 +70,12 @@ class StationSelectionStateTest {
val state = StationSelectionState()
state.select(station("DL1ABC", 2), StationSelectionSource.STATION_TABLE)
val revision = state.scrollRequestRevision
val explicitRevision = state.explicitSelectionRevision
val refreshed = station("DL1ABC", 2)
state.reconcile(refreshed)
assertSame(refreshed, state.selected)
assertEquals(revision, state.scrollRequestRevision)
assertEquals(explicitRevision, state.explicitSelectionRevision)
}
@Test
fun `roster reconciliation does not publish explicit navigation`() {
val state = StationSelectionState()
val requests = mutableListOf<Pair<ChatMember?, StationSelectionSource>>()
state.explicitSelectionListener = { member, source -> requests += member to source }
state.select(station("DL1ABC", 2), StationSelectionSource.PUBLIC_MESSAGE)
state.reconcile(station("DL1ABC", 2))
assertEquals(1, requests.size)
assertEquals(StationSelectionSource.PUBLIC_MESSAGE, requests.single().second)
}
@Test
@@ -1,48 +0,0 @@
package kst4contest.view.compose
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertHasClickAction
import androidx.compose.ui.test.assertHasNoClickAction
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.runComposeUiTest
import kst4contest.model.ThreadStateMessage
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
@OptIn(ExperimentalTestApi::class)
class StatusBarScreenTest {
@Test
fun onlyAThreadWithARegisteredActionIsClickable() = runComposeUiTest {
val buttons = ThreadStatusButtons()
var beaconClicks = 0
buttons.registerAction("MyBeacon") { beaconClicks++ }
buttons.update("MyBeacon", status("off"))
buttons.update("Cluster", status("on"))
setContent {
Kst4ContestTheme(darkMode = false, baseFontSizeSp = 12f) {
StatusBar(
connectionState = null,
connectionDetail = null,
skedNotice = BlinkingNotice(),
bandUpgradeNotice = BlinkingNotice(),
threadButtons = buttons,
showConnectionBadge = false,
)
}
}
waitForIdle()
onNodeWithText("MyBeacon: off").assertHasClickAction().performClick()
waitForIdle()
assertEquals(1, beaconClicks)
onNodeWithText("Cluster: on").assertHasNoClickAction()
}
private fun status(description: String): ThreadStateMessage =
ThreadStateMessage("worker", true, description, false).apply {
runningInformationTextDescription = description
}
}
@@ -407,52 +407,6 @@ class StatusIndicatorStateTest {
assertEquals("Cluster: b", button.label)
}
@Test
fun `an action registered before the first report reaches the created button`() {
val buttons = ThreadStatusButtons()
var clicks = 0
buttons.registerAction("MyBeacon") { clicks++ }
buttons.update("MyBeacon", threadState(nick = "beacon", description = "off", info = "disabled"))
buttons.buttons.single().activate()
assertEquals(1, clicks)
}
@Test
fun `an action registered after a report reaches the existing button`() {
val buttons = ThreadStatusButtons()
var clicks = 0
buttons.update("MyBeacon", threadState(nick = "beacon", description = "off", info = "disabled"))
buttons.registerAction("MyBeacon") { clicks++ }
buttons.buttons.single().activate()
assertEquals(1, clicks)
}
@Test
fun `a thread without an action cannot be activated`() {
val buttons = ThreadStatusButtons()
buttons.update("Cluster", threadState(nick = "cluster", description = "on", info = "running"))
assertFalse(buttons.buttons.single().activate())
}
@Test
fun `a status provider replaces a stale worker snapshot when the UI applies it`() {
val buttons = ThreadStatusButtons()
var current = threadState(nick = "beacon", description = "on", info = "enabled")
buttons.registerStatusProvider("MyBeacon") { current }
val queuedSnapshot = current
current = threadState(nick = "beacon", description = "off", info = "disabled")
buttons.update("MyBeacon", queuedSnapshot)
assertEquals("MyBeacon: off", buttons.buttons.single().label)
assertEquals("disabled", buttons.buttons.single().tooltip)
}
private fun threadState(nick: String, description: String, info: String): ThreadStateMessage =
ThreadStateMessage(nick, true, info, false).apply {
setRunningInformationTextDescription(description)
@@ -49,8 +49,6 @@ class ComposeStationMapDrawingTest {
private val workedGridBorder = 0x000000
private val selectedDotBorder = 0xFF9900
/*
* An empty cache and a source that always fails, so that "tiles never arrive" holds by
* construction. The default fetcher read the user's disk cache and the real tile
@@ -73,10 +71,6 @@ class ComposeStationMapDrawingTest {
ownLocator6: String = "",
workedGrossFields: Set<String> = emptySet(),
darkMode: Boolean = true,
selectedTarget: MapCallsignRawSnapshot? = null,
spatialFilterOverlay: SpatialFilterOverlayState? = null,
antennaBeamWidthDeg: Double = 0.0,
maxQrbKm: Double = 0.0,
): BufferedImage {
return onEventThread {
val scene = ImageComposeScene(canvasWidth, canvasHeight, Density(1f)) {
@@ -88,10 +82,8 @@ class ComposeStationMapDrawingTest {
selectedMarkerCallsign = null,
ownLocator6 = ownLocator6,
antennaAzimuthDeg = 90.0,
antennaBeamWidthDeg = antennaBeamWidthDeg,
maxQrbKm = maxQrbKm,
selectedTarget = selectedTarget,
spatialFilterOverlay = spatialFilterOverlay,
antennaBeamWidthDeg = 0.0,
maxQrbKm = 0.0,
onMarkerClicked = null,
workedGrossFields = workedGrossFields,
darkMode = darkMode,
@@ -116,16 +108,6 @@ class ComposeStationMapDrawingTest {
return count
}
private fun changedPixels(before: BufferedImage, after: BufferedImage): Int {
var changed = 0
for (x in 0 until before.width) {
for (y in 0 until before.height) {
if (before.getRGB(x, y) != after.getRGB(x, y)) changed++
}
}
return changed
}
/** The widest horizontal run of a colour, which for a ring is its outer diameter. */
private fun widestRun(image: BufferedImage, rgb: Int): Int {
var widest = 0
@@ -300,54 +282,6 @@ class ComposeStationMapDrawingTest {
}
}
@Test
fun `active spatial filters add a distinct overlay in both themes`() {
val overlay = SpatialFilterOverlayState(
qtfEnabled = true,
qtfDegrees = 90.0,
beamWidthDeg = 60.0,
minQrbEnabled = true,
minQrbKm = 50.0,
maxQrbEnabled = true,
maxQrbKm = 400.0,
)
for (darkMode in listOf(false, true)) {
val without = render(6f, markers = emptyList(), ownLocator6 = "JO50JP", darkMode = darkMode)
val with = render(
6f,
markers = emptyList(),
ownLocator6 = "JO50JP",
darkMode = darkMode,
spatialFilterOverlay = overlay,
)
assertTrue(changedPixels(without, with) > 1_000) {
"the spatial filter overlay was not visible in darkMode=$darkMode"
}
}
}
@Test
fun `a filtered selected target is drawn without joining the normal marker list`() {
val targetLocation = kst4contest.locatorUtils.Location("JO51AA")
val target = station(
"DL1HIDE",
"JO51AA",
targetLocation.latitude.toDegrees(),
targetLocation.longitude.toDegrees(),
)
val image = render(
6f,
markers = emptyList(),
ownLocator6 = "JO50JP",
selectedTarget = target,
)
assertTrue(countColour(image, selectedDotBorder) > 0, "the separate selected marker is missing")
}
/**
* Every grid line has to be drawn once.
*
@@ -1,29 +0,0 @@
package kst4contest.view.compose.map
import kst4contest.model.ChatPreferences
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Path
class MapDisplaySettingsStateTest {
@TempDir
lateinit var directory: Path
@Test
fun `refresh publishes applied beam geometry from preferences`() {
val preferences = ChatPreferences(directory.resolve("preferences.xml")).apply {
stn_antennaBeamWidthDeg = 50.0
stn_maxQRBDefault = 750.0
}
val state = MapDisplaySettingsState(preferences)
preferences.stn_antennaBeamWidthDeg = 72.0
preferences.stn_maxQRBDefault = 1_100.0
state.refreshFromPreferences()
assertEquals(72.0, state.antennaBeamWidthDeg)
assertEquals(1_100.0, state.maxQrbKm)
}
}
@@ -1,42 +0,0 @@
package kst4contest.view.compose.map
import kst4contest.view.compose.StationIdentity
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
class MapNavigationStateTest {
@Test
fun `repeated station choices remain observable`() {
val state = MapNavigationState()
val identity = StationIdentity("DL1ABC", 2)
state.fitSelectedPath(identity)
val firstRevision = state.requestRevision
state.fitSelectedPath(identity)
assertTrue(state.requestRevision > firstRevision)
assertEquals(MapNavigationRequest.FitSelectedPath(identity), state.request)
}
@Test
fun `latest explicit action replaces an older one`() {
val state = MapNavigationState()
state.fitSelectedPath(StationIdentity("DL1ABC", 2))
state.centerOnQtf(45.0)
assertEquals(MapNavigationRequest.CenterOnQtf(45.0), state.request)
}
@Test
fun `invalid QTF values do not create requests`() {
val state = MapNavigationState()
listOf(Double.NaN, Double.POSITIVE_INFINITY, -1.0, 360.1).forEach(state::centerOnQtf)
assertEquals(0L, state.requestRevision)
assertEquals(null, state.request)
}
}
@@ -1,60 +0,0 @@
package kst4contest.view.compose.map
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.runComposeUiTest
import androidx.compose.ui.unit.dp
import kst4contest.view.compose.Kst4ContestTheme
import kst4contest.view.i18n.LanguageStore
import kst4contest.view.i18n.LocalStrings
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.util.Locale
@OptIn(ExperimentalTestApi::class)
class MapOverlayLegendScreenTest {
@Test
fun germanEveningLegendWrapsBothItemsInsideANarrowHeader() = runComposeUiTest {
var storedLanguage = "de"
val languages = LanguageStore(
storedLanguage = { storedLanguage },
storeLanguage = { storedLanguage = it },
systemDefault = Locale.GERMANY,
)
try {
setContent {
CompositionLocalProvider(LocalStrings provides languages.strings) {
Kst4ContestTheme(darkMode = true, baseFontSizeSp = 12f) {
Box(Modifier.width(110.dp)) {
MapOverlayLegend(
showAntenna = true,
showSpatialFilters = true,
darkMode = true,
)
}
}
}
}
onNodeWithText("Antenne").assertIsDisplayed()
onNodeWithText("Aktive Filter").assertIsDisplayed()
val antenna = onNodeWithTag(MAP_ANTENNA_LEGEND_TAG).fetchSemanticsNode().boundsInRoot
val filters = onNodeWithTag(MAP_FILTER_LEGEND_TAG).fetchSemanticsNode().boundsInRoot
val widthLimit = with(density) { 110.dp.toPx() }
assertTrue(antenna.right <= widthLimit + 0.5f)
assertTrue(filters.right <= widthLimit + 0.5f)
assertTrue(filters.top >= antenna.bottom, "the legend items did not wrap at narrow width")
} finally {
runOnIdle { languages.use("en") }
}
}
}
@@ -1,91 +0,0 @@
package kst4contest.view.compose.map
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
class SpatialFilterOverlayStateTest {
@Test
fun `maximum QRB is inclusive and minimum QRB is exclusive`() {
val state = overlay(minEnabled = true, minKm = 200.0, maxEnabled = true, maxKm = 500.0)
assertFalse(state.accepts(200.0, 90.0))
assertTrue(state.accepts(200.1, 90.0))
assertTrue(state.accepts(500.0, 90.0))
assertFalse(state.accepts(500.1, 90.0))
}
@Test
fun `QTF uses the same wrapped beamwidth semantics as the station filter`() {
val state = overlay(qtf = true, direction = 0.0, beamWidth = 60.0)
assertTrue(state.accepts(300.0, 350.0))
assertTrue(state.accepts(300.0, 30.0))
assertFalse(state.accepts(300.0, 31.0))
}
@Test
fun `unusual full-circle beamwidth retains the existing station filter semantics`() {
val state = overlay(qtf = true, direction = 0.0, beamWidth = 360.0)
assertTrue(state.accepts(300.0, 180.0))
assertFalse(state.accepts(300.0, 0.0))
}
@Test
fun `minimum above maximum is an empty distance range`() {
val state = overlay(minEnabled = true, minKm = 500.0, maxEnabled = true, maxKm = 200.0)
assertTrue(state.hasEmptyDistanceRange)
assertFalse(state.accepts(100.0, 0.0))
assertFalse(state.accepts(300.0, 0.0))
assertFalse(state.accepts(600.0, 0.0))
}
@Test
fun `non-finite active values cannot be rendered as a misleading area`() {
assertFalse(overlay(qtf = true, direction = Double.NaN).hasRenderableValues)
assertFalse(overlay(minEnabled = true, minKm = Double.POSITIVE_INFINITY).hasRenderableValues)
assertFalse(overlay(maxEnabled = true, maxKm = Double.NaN).hasRenderableValues)
}
@Test
fun `zero distance boundaries report only actually drawable geometry`() {
assertFalse(overlay(maxEnabled = true, maxKm = 0.0).hasDrawableGeometry)
assertFalse(overlay(qtf = true, maxEnabled = true, maxKm = 0.0).hasDrawableGeometry)
assertFalse(
overlay(minEnabled = true, minKm = 0.0, maxEnabled = true, maxKm = 0.0).hasDrawableGeometry
)
assertTrue(overlay(minEnabled = true, minKm = 0.0).hasDrawableGeometry)
assertTrue(overlay(qtf = true).hasDrawableGeometry)
assertTrue(overlay(minEnabled = true, minKm = 100.0, maxEnabled = true, maxKm = 0.0).hasDrawableGeometry)
assertTrue(overlay(maxEnabled = true, maxKm = 500.0).hasDrawableGeometry)
}
@Test
fun `no spatial filter accepts finite positions`() {
val state = overlay()
assertFalse(state.isActive)
assertTrue(state.accepts(1000.0, 275.0))
}
private fun overlay(
qtf: Boolean = false,
direction: Double = 0.0,
beamWidth: Double = 60.0,
minEnabled: Boolean = false,
minKm: Double = 0.0,
maxEnabled: Boolean = false,
maxKm: Double = 0.0,
) = SpatialFilterOverlayState(
qtfEnabled = qtf,
qtfDegrees = direction,
beamWidthDeg = beamWidth,
minQrbEnabled = minEnabled,
minQrbKm = minKm,
maxQrbEnabled = maxEnabled,
maxQrbKm = maxKm,
)
}
@@ -4,6 +4,7 @@ import androidx.compose.ui.test.ComposeUiTest
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertIsOff
import androidx.compose.ui.test.assertIsOn
import androidx.compose.ui.test.assertCountEquals
import androidx.compose.ui.test.click
import androidx.compose.ui.test.isToggleable
import androidx.compose.ui.test.onAllNodesWithText
@@ -41,6 +42,7 @@ import kst4contest.view.compose.STATION_CONTEXT_TARGET_CHOOSER_TAG
import kst4contest.view.compose.ThreadStatusButtons
import kst4contest.view.compose.TimelineState
import kst4contest.view.compose.TopPriorityState
import kst4contest.view.map.StationMapClusterer
import kst4contest.view.map.MapCallsignRawSnapshot
import kst4contest.view.map.PathAnalysisResult
import kst4contest.view.map.TileFetcher
@@ -229,10 +231,7 @@ class StationMapWindowScreenTest {
val dl1abc = station("DL1ABC", 2)
state.selectedStation.select(dl1abc)
val selectorCalls = mutableListOf<ChatMember?>()
state.stationSelector = { member, source ->
selectorCalls += member
state.selectedStation.select(member, source)
}
state.stationSelector = { member, _ -> selectorCalls += member }
val mapState = mapLookingAt("JO50JP", zoom = 15f)
show(state, listOf(dl1abc), mapState)
@@ -241,7 +240,11 @@ class StationMapWindowScreenTest {
waitForIdle()
assertEquals(listOf<ChatMember?>(null), selectorCalls, "reset did not go through the station selector")
assertEquals(null, state.selectedStation.selected)
assertSame(
dl1abc,
state.selectedStation.selected,
"reset cleared the panel's selection behind the selector's back",
)
assertEquals(15f, mapState.zoom, "reset changed the zoom")
val home = Location(ownLocator)
@@ -366,9 +369,12 @@ class StationMapWindowScreenTest {
assertEquals(readsWhileEnabled, reads, "disabled Grid color still read worked fields")
}
/** An explicit selection fits both ends and still starts the existing path analysis. */
/**
* The cc8c9020 rule: selecting a station pans the map to it and leaves the zoom alone.
* The earlier Compose version recomputed the zoom here and threw zoom 15 out to about 7.
*/
@Test
fun selectingAStationFitsTheCompletePath() = runComposeUiTest {
fun selectingAStationPansToItAndKeepsTheZoom() = runComposeUiTest {
val state = windowState(prefs())
val dl1abc = station("DL1ABC", 2, locator = "JO50JP")
val analysis = RecordingPathAnalysis()
@@ -376,49 +382,53 @@ class StationMapWindowScreenTest {
show(state, listOf(dl1abc), mapState, analysis)
runOnIdle { state.selectStation(dl1abc, StationSelectionSource.STATION_TABLE) }
runOnIdle { state.selectedStation.select(dl1abc) }
waitForIdle()
val home = Location(ownLocator)
val target = Location("JO50JP")
assertTrue(mapState.centerLon in home.longitude.toDegrees()..target.longitude.toDegrees())
assertTrue(mapState.centerLat in home.latitude.toDegrees()..target.latitude.toDegrees())
assertTrue(mapState.zoom < 15f, "a path too long for zoom 15 was not fitted")
assertEquals(target.longitude.toDegrees(), mapState.centerLon, 1e-9, "the map did not pan")
assertEquals(target.latitude.toDegrees(), mapState.centerLat, 1e-9, "the map did not pan")
assertEquals(15f, mapState.zoom, "selecting a station changed the zoom")
assertEquals(listOf(dl1abc), analysis.requested, "the path analysis was not asked")
}
/** Grouping never forces a path which already fits to zoom in. */
/**
* With grouping on, a selection zooms in only as far as it takes to break the station out
* of its bubble, and never out: StationMapClusterer.zoomToRevealStations.
*/
@Test
fun groupingDoesNotZoomInWhileFittingASelectedPath() = runComposeUiTest {
fun withGroupingOnASelectionOnlyZoomsInFarEnoughToRevealTheStation() = runComposeUiTest {
val prefs = prefs().apply { isGUIstationMapClusteringEnabled = true }
val state = windowState(prefs)
val dl1abc = station("DL1ABC", 2, locator = "JO40HB")
val mapState = mapLookingAt(ownLocator, zoom = 5f)
val dl1abc = station("DL1ABC", 2, locator = "JO50JP")
val far = mapLookingAt(ownLocator, zoom = 5f)
show(state, listOf(dl1abc), mapState, RecordingPathAnalysis())
show(state, listOf(dl1abc), far, RecordingPathAnalysis())
runOnIdle { state.selectStation(dl1abc, StationSelectionSource.STATION_TABLE) }
runOnIdle { state.selectedStation.select(dl1abc) }
waitForIdle()
assertEquals(5f, mapState.zoom)
assertEquals(StationMapClusterer.DISABLE_AT_ZOOM.toFloat(), far.zoom)
}
/** Camera navigation is independent of the optional path-analysis service. */
/** Without a running application there is nothing to ask, and the map stays put. */
@Test
fun withoutAPathAnalysisASelectionStillFitsThePath() = runComposeUiTest {
fun withoutAPathAnalysisASelectionLeavesTheMapWhereItIs() = runComposeUiTest {
val state = windowState(prefs())
val dl1abc = station("DL1ABC", 2, locator = "JO50JP")
val mapState = mapLookingAt(ownLocator, zoom = 15f)
val home = Location(ownLocator)
var asked = 0
show(state, listOf(dl1abc), mapState, pathAnalysis = null, onPathAnalysisAsked = { asked++ })
runOnIdle { state.selectStation(dl1abc, StationSelectionSource.STATION_TABLE) }
runOnIdle { state.selectedStation.select(dl1abc) }
waitForIdle()
// Proves the selection effect ran, so the unchanged map is not a vacuous pass.
assertEquals(1, asked, "the selection effect did not ask for a path analysis")
assertTrue(mapState.zoom < 15f)
assertEquals(home.longitude.toDegrees(), mapState.centerLon, 1e-9)
assertEquals(15f, mapState.zoom)
}
/** The two header switches write the profile, so the map opens the same way next time. */
@@ -467,54 +477,6 @@ class StationMapWindowScreenTest {
assertEquals(listOf(true, false), applied)
}
@Test
fun headerLegendFollowsDrawableAntennaAndSpatialFilterOverlays() = runComposeUiTest {
val prefs = prefs()
val state = windowState(prefs)
show(state, emptyList(), MapState())
onNodeWithText("Antenna").assertExists()
onNodeWithText("Active filters").assertDoesNotExist()
runOnIdle {
state.stationFilter.maxQrbKm = 666.0
state.stationFilter.maxQrbEnabled = true
}
waitForIdle()
onNodeWithText("Antenna").assertExists()
onNodeWithText("Active filters").assertExists()
runOnIdle {
prefs.stn_antennaBeamWidthDeg = 0.0
prefs.stn_maxQRBDefault = 0.0
state.refreshMapDisplaySettings()
state.stationFilter.maxQrbEnabled = false
}
waitForIdle()
onNodeWithText("Antenna").assertDoesNotExist()
onNodeWithText("Active filters").assertDoesNotExist()
}
@Test
fun invalidSpatialFilterDoesNotClaimAVisibleOverlay() = runComposeUiTest {
val state = windowState(prefs())
state.stationFilter.maxQrbKm = 0.0
state.stationFilter.maxQrbEnabled = true
show(state, emptyList(), MapState())
onNodeWithText("Antenna").assertExists()
onNodeWithText("Active filters").assertDoesNotExist()
runOnIdle { state.stationFilter.maxQrbKm = Double.NaN }
waitForIdle()
onNodeWithText("Active filters").assertDoesNotExist()
}
@Test
fun resetFiltersUsesTheSharedActionAndDoesNotResetTheView() = runComposeUiTest {
val state = windowState(prefs())
@@ -591,9 +553,13 @@ class StationMapWindowScreenTest {
onNodeWithText("Showing 1 visible stations | filtered view active").assertExists()
}
/** A filtered-out selection remains a separate target without entering the marker count. */
/**
* A selected station the filters hide has no marker, and so nothing to analyse: no
* request goes out and the analysis does not sit at "Loading" with an empty target (#21).
* The visible station beside it is the control: selecting it does ask and does load.
*/
@Test
fun aSelectedStationTheFiltersHideKeepsItsTargetAndPathAnalysis() = runComposeUiTest {
fun aSelectedStationTheFiltersHideGetsNoPathAnalysis() = runComposeUiTest {
val state = windowState(prefs(pathAnalysisVisible = true))
val hidden = station("DL1HIDE", 2, locator = "JO50JP").apply { qrb = 100.0 }
val shown = station("DL2SHOW", 2, locator = "JO62QM").apply { qrb = 800.0 }
@@ -602,128 +568,21 @@ class StationMapWindowScreenTest {
state.stations.rowFilter = { state.stationFilter.acceptsQrb(it.qrb) }
val analysis = RecordingPathAnalysis()
val mapState = mapLookingAt(ownLocator, zoom = 9f)
val home = Location(ownLocator)
show(state, listOf(hidden, shown), mapState, analysis)
runOnIdle { state.selectStation(hidden, StationSelectionSource.PRIORITY) }
runOnIdle { state.selectedStation.select(hidden) }
waitForIdle()
assertEquals(listOf(hidden), analysis.requested, "the selected hidden target was not analysed")
assertEquals(emptyList<ChatMember>(), analysis.requested, "a hidden station was analysed")
onAllNodesWithText("Loading", substring = true).assertCountEquals(0)
assertEquals(home.longitude.toDegrees(), mapState.centerLon, 1e-9, "the map panned to a hidden station")
runOnIdle { state.selectedStation.select(shown) }
waitForIdle()
assertEquals(listOf(shown), analysis.requested)
assertEquals(true, onAllNodesWithText("Loading", substring = true).fetchSemanticsNodes().isNotEmpty())
onNodeWithText("Showing 1 visible stations | filtered view active", substring = true).assertExists()
runOnIdle { state.selectStation(shown, StationSelectionSource.PRIORITY) }
waitForIdle()
assertEquals(listOf(hidden, shown), analysis.requested)
assertEquals(true, onAllNodesWithText("Loading", substring = true).fetchSemanticsNodes().isNotEmpty())
}
@Test
fun filteredSelectedMarkerWinsHitTestingWhenAnotherMarkerOverlapsIt() = runComposeUiTest {
val state = windowState(prefs())
val hidden = station("DL1HIDE", 2, locator = ownLocator).apply { qrb = 100.0 }
val shown = station("DL2SHOW", 2, locator = ownLocator).apply { qrb = 800.0 }
state.stationFilter.minQrbKm = 300.0
state.stationFilter.minQrbEnabled = true
state.stations.rowFilter = { state.stationFilter.acceptsQrb(it.qrb) }
val selections = mutableListOf<ChatMember?>()
state.stationSelector = { member, source ->
selections += member
state.selectedStation.select(member, source)
}
show(state, listOf(hidden, shown), mapLookingAt(ownLocator, zoom = 12f))
runOnIdle { state.selectStation(hidden, StationSelectionSource.PRIORITY) }
waitForIdle()
selections.clear()
onNodeWithTag(StationMapWindow.MAP_CANVAS_TAG).performMouseInput { click() }
waitForIdle()
assertEquals(listOf(hidden), selections)
}
@Test
fun rosterReconciliationDoesNotOverwriteManualCameraMovement() = runComposeUiTest {
val state = windowState(prefs())
val selected = station("DL1ABC", 2, locator = "JO50JP")
val mapState = mapLookingAt(ownLocator, zoom = 10f)
show(state, listOf(selected), mapState, RecordingPathAnalysis())
runOnIdle { state.selectStation(selected, StationSelectionSource.PUBLIC_MESSAGE) }
waitForIdle()
runOnIdle {
mapState.centerLon = 3.0
mapState.centerLat = 48.0
mapState.zoom = 11f
state.stations.replaceRows(listOf(station("DL1ABC", 2, locator = "JO50JP")))
}
waitForIdle()
assertEquals(3.0, mapState.centerLon, 1e-9)
assertEquals(48.0, mapState.centerLat, 1e-9)
assertEquals(11f, mapState.zoom)
}
@Test
fun explicitQtfNavigationPreservesZoomAndFilterResetDoesNotNavigate() = runComposeUiTest {
val state = windowState(prefs())
val mapState = mapLookingAt(ownLocator, zoom = 9.5f)
show(state, emptyList(), mapState)
runOnIdle { state.applyExplicitQtfFilterDirection(45.0) }
waitForIdle()
val qtfLon = mapState.centerLon
val qtfLat = mapState.centerLat
assertEquals(9.5f, mapState.zoom)
assertTrue(qtfLon > Location(ownLocator).longitude.toDegrees())
assertTrue(qtfLat > Location(ownLocator).latitude.toDegrees())
runOnIdle { state.resetStationFilters() }
waitForIdle()
assertEquals(qtfLon, mapState.centerLon, 1e-9)
assertEquals(qtfLat, mapState.centerLat, 1e-9)
assertEquals(9.5f, mapState.zoom)
}
@Test
fun QtfNavigationDoesNotRequireOrChangeManualAntennaHeading() = runComposeUiTest {
val prefs = prefs().apply {
setStn_useQtfFilterDirectionAsAntennaHeading(false)
actualQTF.set(123.0)
}
val state = windowState(prefs)
val mapState = mapLookingAt(ownLocator, zoom = 9.5f)
show(state, emptyList(), mapState)
runOnIdle { state.applyExplicitQtfFilterDirection(45.0) }
waitForIdle()
assertTrue(mapState.centerLon > Location(ownLocator).longitude.toDegrees())
assertTrue(mapState.centerLat > Location(ownLocator).latitude.toDegrees())
assertEquals(9.5f, mapState.zoom)
assertEquals(123.0, prefs.actualQTF.get(), 1e-9)
}
@Test
fun selectingTheSameStationAgainRepeatsPathNavigation() = runComposeUiTest {
val state = windowState(prefs())
val selected = station("DL1ABC", 2, locator = "JO50JP")
val mapState = mapLookingAt(ownLocator, zoom = 10f)
show(state, listOf(selected), mapState, RecordingPathAnalysis())
runOnIdle { state.selectStation(selected, StationSelectionSource.TIMELINE) }
waitForIdle()
val firstCentre = mapState.centerLon to mapState.centerLat
runOnIdle {
mapState.centerLon = 2.0
mapState.centerLat = 45.0
state.selectStation(selected, StationSelectionSource.TIMELINE)
}
waitForIdle()
assertEquals(firstCentre.first, mapState.centerLon, 1e-9)
assertEquals(firstCentre.second, mapState.centerLat, 1e-9)
}
}
@@ -41,7 +41,7 @@ class BeaconTabStateTest(@TempDir private val tempDir: Path) {
}
@Test
fun `enable changes immediately while template and interval wait for apply`() {
fun `beacon edits wait for apply, and the timer restarts only then`() {
val s = Session(draft = SettingsDraft())
s.prefs.setBcn_beaconIntervalInMinutesMainCat(5)
s.prefs.setBcn_beaconsEnabledMainCat(false)
@@ -51,7 +51,7 @@ class BeaconTabStateTest(@TempDir private val tempDir: Path) {
assertNull(state.commitBeaconTextMainCat("CQ MYCALL"))
assertNull(state.commitBeaconInterval("7"))
assertTrue(s.prefs.isBcn_beaconsEnabledMainCat(), "the runtime switch did not take effect immediately")
assertFalse(s.prefs.isBcn_beaconsEnabledMainCat(), "an edit took effect before Apply")
assertEquals(5, s.prefs.getBcn_beaconIntervalInMinutesMainCat())
assertEquals(0, s.timerRestarts, "the timer restarted before Apply")
assertEquals(7, state.beaconIntervalMinutes, "the tab shows the edit")
@@ -65,18 +65,6 @@ class BeaconTabStateTest(@TempDir private val tempDir: Path) {
assertEquals(1, s.timerRestarts)
}
@Test
fun `enable changes do not become pending draft edits`() {
val s = Session(draft = SettingsDraft())
s.prefs.setBcn_beaconsEnabledMainCat(false)
val state = s.state()
state.bcn_beaconsEnabledMainCat = true
assertTrue(s.prefs.isBcn_beaconsEnabledMainCat())
assertFalse(s.draft.hasPendingChanges)
}
@Test
fun `discarded beacon edits leave the timer and the templates alone`() {
val s = Session(draft = SettingsDraft())
@@ -173,24 +161,13 @@ class BeaconTabStateTest(@TempDir private val tempDir: Path) {
s.prefs.setBcn_beaconIntervalInMinutesMainCat(5)
val state = s.state()
assertNotNull(state.commitBeaconInterval("4"))
assertNotNull(state.commitBeaconInterval("0"))
assertEquals(5, s.prefs.getBcn_beaconIntervalInMinutesMainCat())
assertEquals(0, s.timerRestarts,
"restarting the timer per rejected keystroke would disturb the cooldown")
}
@Test
fun `exactly five minutes is accepted`() {
val s = Session()
val state = s.state()
assertNull(state.commitBeaconInterval("5"))
assertEquals(5, s.prefs.getBcn_beaconIntervalInMinutesMainCat())
assertEquals(5, s.prefs.getBcn_beaconIntervalInMinutesSecondCat())
}
@Test
fun `an interval that is not a whole number is refused`() {
val s = Session()
@@ -162,6 +162,8 @@ class DraftedSettingsTableTest {
}, { it.prefs.getLst_txtSnipList().snapshot() }),
// Beacon
flag("beacon main", { it.beacon.bcn_beaconsEnabledMainCat }) { f, v -> f.beacon.bcn_beaconsEnabledMainCat = v },
flag("beacon second", { it.beacon.bcn_beaconsEnabledSecondCat }) { f, v -> f.beacon.bcn_beaconsEnabledSecondCat = v },
Case("beacon text main", { it.beacon.commitBeaconTextMainCat(it.beacon.beaconTextMainCat + " x") },
{ it.prefs.getBcn_beaconTextMainCat() }),
Case("beacon text second", { it.beacon.commitBeaconTextSecondCat(it.beacon.beaconTextSecondCat + " x") },
@@ -3,7 +3,6 @@ package kst4contest.view.compose.tabs
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertIsOff
import androidx.compose.ui.test.assertIsOn
import androidx.compose.ui.test.assertTextEquals
import androidx.compose.ui.test.hasSetTextAction
import androidx.compose.ui.test.onAllNodesWithText
@@ -191,19 +190,6 @@ class MessagingTabsScreenTest {
assertEquals("cq %foo%", s.prefs.bcn_beaconTextMainCat)
}
@Test
fun anExternalBeaconToggleUpdatesTheOpenSettingsTab() = runComposeUiTest {
val s = Beacon(preferences())
s.prefs.isBcn_beaconsEnabledMainCat = false
showTab { BeaconTab(s.state) { s.refusals += it } }
checkBeside("Send the beacon in this category").assertIsOff()
runOnIdle { s.prefs.isBcn_beaconsEnabledMainCat = true }
waitForIdle()
checkBeside("Send the beacon in this category").assertIsOn()
}
/*
* The tab reads the interval from a plain preference getter, so nothing recomposes it
* after Enter commits. Compared with that stale value, leaving the field afterwards
@@ -107,14 +107,14 @@ class SettingsApplyScreenTest {
}
@Test
fun beaconEnableTakesEffectImmediatelyWhileTheIntervalWaitsForApply() = runComposeUiTest {
fun anEditTakesEffectOnlyWithApplyAndClose() = runComposeUiTest {
val w = Window()
show(w)
toggle("Send the beacon in this category")
typeAndCommit("Interval in whole minutes", "9")
assertTrue(w.prefs.isBcn_beaconsEnabledMainCat, "the runtime switch did not take effect immediately")
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat, "the box took effect before Apply")
assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat)
assertEquals(0, w.restarts, "the timer restarted before Apply")
@@ -178,19 +178,19 @@ class SettingsApplyScreenTest {
fun aRefusalAppliesNothingSoDiscardIsStillPossible() = runComposeUiTest {
val w = Window()
show(w)
typeAndCommit("Interval in whole minutes", "9")
toggle("Send the beacon in this category")
type("Server port", "23x")
onNodeWithText(APPLY_AND_CLOSE).performClick()
waitForIdle()
assertFalse(w.closed)
assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat, "the valid edit went into effect despite the refusal")
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat, "the valid edit went into effect despite the refusal")
assertTrue(w.draft.hasPendingChanges)
runOnIdle { w.notices.dismiss() }
runOnIdle { w.draft.discard() }
assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat)
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat)
}
/*
@@ -264,7 +264,7 @@ class SettingsApplyScreenTest {
fun theXAsksAboutPendingEditsAndApplyAppliesThem() = runComposeUiTest {
val w = Window()
show(w)
typeAndCommit("Interval in whole minutes", "9")
toggle("Send the beacon in this category")
runOnIdle { w.x() }
awaitNode(inDialog(PENDING_QUESTION))
@@ -273,7 +273,7 @@ class SettingsApplyScreenTest {
awaitNode(inDialog("Apply")).performClick()
awaitGone(inDialog(PENDING_QUESTION))
assertEquals(9, w.prefs.bcn_beaconIntervalInMinutesMainCat)
assertTrue(w.prefs.isBcn_beaconsEnabledMainCat)
assertTrue(w.closed)
}
@@ -288,7 +288,7 @@ class SettingsApplyScreenTest {
awaitNode(inDialog("Discard")).performClick()
awaitGone(inDialog(PENDING_QUESTION))
assertTrue(w.prefs.isBcn_beaconsEnabledMainCat, "the immediate runtime switch was unexpectedly reverted")
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat)
assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat)
assertEquals(0, w.restarts)
assertTrue(w.closed)
@@ -299,7 +299,7 @@ class SettingsApplyScreenTest {
fun goingBackKeepsTheWindowAndTheEdits() = runComposeUiTest {
val w = Window()
show(w)
typeAndCommit("Interval in whole minutes", "9")
toggle("Send the beacon in this category")
runOnIdle { w.x() }
awaitNode(inDialog("Back to the settings")).performClick()
@@ -307,7 +307,7 @@ class SettingsApplyScreenTest {
assertFalse(w.closed)
assertTrue(w.draft.hasPendingChanges)
assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat)
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat)
checkBeside("Send the beacon in this category").assertExists()
}
@@ -377,13 +377,13 @@ class SettingsApplyScreenTest {
val w = Window()
var wentOn = false
show(w)
typeAndCommit("Interval in whole minutes", "9")
toggle("Send the beacon in this category")
runOnIdle { w.switchOrExit { wentOn = true } }
awaitNode(inDialog("Apply")).performClick()
awaitGone(inDialog(PENDING_QUESTION))
assertEquals(9, w.prefs.bcn_beaconIntervalInMinutesMainCat)
assertTrue(w.prefs.isBcn_beaconsEnabledMainCat)
assertTrue(wentOn)
assertFalse(w.closed, "the window closed itself instead of leaving that to the teardown")
}
@@ -393,7 +393,7 @@ class SettingsApplyScreenTest {
val w = Window()
var wentOn = false
show(w)
typeAndCommit("Interval in whole minutes", "9")
toggle("Send the beacon in this category")
runOnIdle { w.switchOrExit { wentOn = true } }
awaitNode(inDialog("Back to the settings")).performClick()
@@ -408,14 +408,14 @@ class SettingsApplyScreenTest {
val w = Window()
var wentOn = false
show(w)
typeAndCommit("Interval in whole minutes", "9")
toggle("Send the beacon in this category")
runOnIdle { w.switchOrExit { wentOn = true } }
awaitNode(inDialog("Discard")).performClick()
awaitGone(inDialog(PENDING_QUESTION))
assertTrue(wentOn)
assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat)
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat)
}
@Test
@@ -423,7 +423,7 @@ class SettingsApplyScreenTest {
val w = Window()
var wentOn = false
show(w)
typeAndCommit("Interval in whole minutes", "9")
toggle("Send the beacon in this category")
runOnIdle { w.switchOrExit { wentOn = true } }
awaitNode(inDialog(PENDING_QUESTION))
@@ -432,7 +432,7 @@ class SettingsApplyScreenTest {
awaitGone(inDialog(PENDING_QUESTION))
assertFalse(wentOn, "went on over a refused entry")
assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat, "applied despite the refusal")
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat, "applied despite the refusal")
}
@Test
@@ -457,7 +457,7 @@ class SettingsApplyScreenTest {
val w = Window()
var wentOn = false
show(w)
typeAndCommit("Interval in whole minutes", "9")
toggle("Send the beacon in this category")
runOnIdle { w.switchOrExit { wentOn = true } }
awaitNode(inDialog(PENDING_QUESTION))
@@ -477,7 +477,7 @@ class SettingsApplyScreenTest {
fun anInvalidFieldStillLetsTheXDiscard() = runComposeUiTest {
val w = Window()
show(w)
typeAndCommit("Interval in whole minutes", "9")
toggle("Send the beacon in this category")
type("Server port", "23x")
runOnIdle { w.x() }
@@ -489,7 +489,7 @@ class SettingsApplyScreenTest {
awaitGone(inDialog(PENDING_QUESTION))
assertTrue(w.closed)
assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat, "something was applied")
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat, "something was applied")
}
/* The same for a switch or the exit, even when only the invalid field is unsettled. */
@@ -20,8 +20,6 @@ class StationTabStateTest(@param:TempDir private val tempDir: Path) {
var secondApplied: ChatCategory? = null
var secondWasApplied = false
val secondRotatorCalls = mutableListOf<Unit>()
var beaconStatusRefreshes = 0
var mapDisplayRefreshes = 0
val draft = SettingsDraft()
val state = StationTabState(
prefs,
@@ -29,8 +27,6 @@ class StationTabStateTest(@param:TempDir private val tempDir: Path) {
{ mainApplied = it },
{ secondApplied = it; secondWasApplied = true },
applySecondRotator = { secondRotatorCalls.add(Unit) },
refreshBeaconStatus = { beaconStatusRefreshes++ },
applyMapDisplaySettings = { mapDisplayRefreshes++ },
)
}
@@ -309,34 +305,6 @@ class StationTabStateTest(@param:TempDir private val tempDir: Path) {
assertEquals(true, state.loginToSecondChatEnabled)
}
@Test
fun `applying the second chat switch refreshes aggregate beacon status`() {
val session = Session()
session.state.loginToSecondChatEnabled = true
assertEquals(0, session.beaconStatusRefreshes)
session.draft.apply()
assertEquals(1, session.beaconStatusRefreshes)
}
@Test
fun `beam width and maximum QRB refresh the map once after both are applied`() {
val session = Session()
session.state.stn_antennaBeamWidthDeg = 72.0
session.state.stn_maxQRBDefault = 1_250.0
assertEquals(0, session.mapDisplayRefreshes)
val outcome = session.draft.apply()
assertTrue(outcome.isClean, outcome.failures.toString())
assertEquals(72.0, session.prefs.stn_antennaBeamWidthDeg, 0.0001)
assertEquals(1_250.0, session.prefs.stn_maxQRBDefault, 0.0001)
assertEquals(1, session.mapDisplayRefreshes)
}
@Test
fun `the own height above sea level reads empty while the elevation model decides`() {
val s = Session()
@@ -73,7 +73,7 @@ class RemainingTextsFollowTheLanguageTest {
assertEquals("Wertung", score.title(), "the column title stayed in the old language")
assertEquals(
"Einen ganzzahligen Bakenabstand von mindestens 5 Minuten eingeben.",
"Einen ganzzahligen Bakenabstand von mindestens 1 Minute eingeben.",
beacon.commitBeaconInterval("0"),
"the refusal from the tab state stayed in the old language",
)
@@ -1,15 +0,0 @@
package kst4contest.controller;
/** Adds the fixed marker used by every user-visible automatic chat message. */
final class AutomaticChatMessageFormatter {
/** Exact marker appended to every user-visible automatic chat message. */
/* default */ static final String SUFFIX = " *a*";
private AutomaticChatMessageFormatter() {
}
/* default */ static String appendSuffix(final String messageText) {
return messageText + SUFFIX;
}
}
@@ -1,66 +0,0 @@
package kst4contest.controller;
import java.util.OptionalLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import kst4contest.model.Band;
/** Parses complete beacon-reference frequencies without floating-point comparisons. */
final class BeaconFrequencyParser {
private static final Pattern GROUPED = Pattern.compile(
"^(\\d{2,5})[.,](\\d{1,3})(?:[.,](\\d{1,3}))?$"
);
private static final Pattern COMPACT = Pattern.compile("^\\d{5,8}$");
private BeaconFrequencyParser() {
}
static OptionalLong parseHz(String value) {
if (value == null) {
return OptionalLong.empty();
}
String normalized = value.trim();
if (normalized.isEmpty()) {
return OptionalLong.empty();
}
try {
long frequencyHz;
Matcher grouped = GROUPED.matcher(normalized);
if (grouped.matches()) {
long megahertz = Long.parseLong(grouped.group(1));
long kilohertz = rightPadToThree(grouped.group(2));
long hertz = grouped.group(3) == null
? 0L
: rightPadToThree(grouped.group(3));
frequencyHz = Math.addExact(
Math.multiplyExact(megahertz, 1_000_000L),
Math.addExact(Math.multiplyExact(kilohertz, 1_000L), hertz)
);
} else if (COMPACT.matcher(normalized).matches()) {
long compact = Long.parseLong(normalized);
frequencyHz = Math.multiplyExact(compact, 1_000L);
} else {
return OptionalLong.empty();
}
if (frequencyHz <= 0L
|| Band.fromFrequency(frequencyHz / 1_000_000.0) == null) {
return OptionalLong.empty();
}
return OptionalLong.of(frequencyHz);
} catch (ArithmeticException | NumberFormatException ignored) {
return OptionalLong.empty();
}
}
private static long rightPadToThree(String digits) {
long value = Long.parseLong(digits);
for (int index = digits.length(); index < 3; index++) {
value *= 10L;
}
return value;
}
}
@@ -1,225 +0,0 @@
package kst4contest.controller;
import java.util.OptionalLong;
import kst4contest.model.BeaconStatusSnapshot;
import kst4contest.model.BeaconStatusSnapshot.AggregateState;
import kst4contest.model.BeaconStatusSnapshot.CategoryStatus;
import kst4contest.model.BeaconStatusSnapshot.InactiveReason;
import kst4contest.model.ChatPreferences;
/** Owns session-only beacon activation, QRG references, reasons, and send failures. */
final class BeaconSessionState {
static final long MAX_AUTOMATIC_QRG_DELTA_HZ = 5_000L;
enum Channel {
MAIN,
SECOND
}
private final ChannelState main = new ChannelState();
private final ChannelState second = new ChannelState();
void resetSession(ChatPreferences preferences) {
synchronized (this) {
main.reset();
second.reset();
}
project(preferences);
}
boolean setEnabled(Channel channel, boolean enabled, ChatPreferences preferences) {
boolean accepted;
synchronized (this) {
ChannelState target = state(channel);
if (!enabled) {
target.disable(InactiveReason.USER_DISABLED);
accepted = true;
} else {
InactiveReason invalidReason = missingRequiredQrg(channel, preferences);
if (invalidReason != null) {
target.disable(invalidReason);
accepted = false;
} else {
target.enabled = true;
target.failed = false;
OptionalLong reference = ownQrg(channel, preferences);
target.referenceHz = reference.isPresent() ? reference.getAsLong() : null;
accepted = true;
}
}
}
project(preferences);
return accepted;
}
void onManualQrgChanged(Channel channel, String value, ChatPreferences preferences) {
if (channel == Channel.MAIN) {
preferences.getMYQRGFirstCat().set(value);
} else {
preferences.getMYQRGSecondCat().set(value);
}
OptionalLong parsed = BeaconFrequencyParser.parseHz(value);
synchronized (this) {
ChannelState target = state(channel);
if (target.enabled) {
target.referenceHz = parsed.isPresent() ? parsed.getAsLong() : null;
}
revalidateEnabled(preferences);
}
project(preferences);
}
void onExternalQrgChanged(Channel channel, long frequencyHz, ChatPreferences preferences) {
boolean valid = frequencyHz > 0L && ownQrg(channel, preferences).isPresent();
synchronized (this) {
ChannelState target = state(channel);
if (target.enabled) {
if (!valid) {
target.referenceHz = null;
} else if (target.referenceHz == null) {
target.referenceHz = frequencyHz;
} else if (absoluteDifference(target.referenceHz, frequencyHz)
> MAX_AUTOMATIC_QRG_DELTA_HZ) {
target.disable(InactiveReason.AUTOMATIC_QRG_CHANGE);
}
}
revalidateEnabled(preferences);
}
project(preferences);
}
void onTemplateChanged(Channel channel, ChatPreferences preferences) {
synchronized (this) {
ChannelState target = state(channel);
if (target.enabled) {
InactiveReason reason = missingRequiredQrg(channel, preferences);
if (reason != null) {
target.disable(reason);
}
}
}
project(preferences);
}
synchronized boolean isEnabled(Channel channel) {
return state(channel).enabled;
}
synchronized void recordSendFailure(Channel channel, boolean failed) {
ChannelState target = state(channel);
target.failed = target.enabled && failed;
}
synchronized BeaconStatusSnapshot snapshot(ChatPreferences preferences) {
boolean secondAvailable = preferences.isLoginToSecondChatEnabled();
boolean mainEnabled = main.enabled;
boolean secondEnabled = secondAvailable && second.enabled;
boolean failed = (mainEnabled && main.failed) || (secondEnabled && second.failed);
int available = secondAvailable ? 2 : 1;
int enabled = (mainEnabled ? 1 : 0) + (secondEnabled ? 1 : 0);
AggregateState aggregate;
if (failed) {
aggregate = AggregateState.FAILED;
} else if (enabled == 0) {
aggregate = AggregateState.OFF;
} else if (enabled == available) {
aggregate = AggregateState.ON;
} else {
aggregate = AggregateState.PARTIAL;
}
return new BeaconStatusSnapshot(
aggregate,
new CategoryStatus(true, mainEnabled, main.failed, main.reason),
new CategoryStatus(secondAvailable, secondEnabled, second.failed, second.reason)
);
}
private void revalidateEnabled(ChatPreferences preferences) {
revalidate(Channel.MAIN, preferences);
revalidate(Channel.SECOND, preferences);
}
private void revalidate(Channel channel, ChatPreferences preferences) {
ChannelState target = state(channel);
if (!target.enabled) {
return;
}
InactiveReason reason = missingRequiredQrg(channel, preferences);
if (reason != null) {
target.disable(reason);
}
}
private static InactiveReason missingRequiredQrg(
Channel channel,
ChatPreferences preferences
) {
String template = channel == Channel.MAIN
? preferences.getBcn_beaconTextMainCat()
: preferences.getBcn_beaconTextSecondCat();
String safeTemplate = template == null ? "" : template;
if ((safeTemplate.contains("MYQRG") || safeTemplate.contains("MYQRGSHORT"))
&& BeaconFrequencyParser.parseHz(preferences.getMYQRGFirstCat().get()).isEmpty()) {
return InactiveReason.PRIMARY_QRG_UNAVAILABLE;
}
if (safeTemplate.contains("SECONDQRG")
&& BeaconFrequencyParser.parseHz(preferences.getMYQRGSecondCat().get()).isEmpty()) {
return InactiveReason.SECONDARY_QRG_UNAVAILABLE;
}
return null;
}
private static OptionalLong ownQrg(Channel channel, ChatPreferences preferences) {
String value = channel == Channel.MAIN
? preferences.getMYQRGFirstCat().get()
: preferences.getMYQRGSecondCat().get();
return BeaconFrequencyParser.parseHz(value);
}
private static long absoluteDifference(long first, long second) {
return first >= second ? first - second : second - first;
}
private void project(ChatPreferences preferences) {
boolean mainEnabled;
boolean secondEnabled;
synchronized (this) {
mainEnabled = main.enabled;
secondEnabled = second.enabled;
}
if (preferences.isBcn_beaconsEnabledMainCat() != mainEnabled) {
preferences.setBcn_beaconsEnabledMainCat(mainEnabled);
}
if (preferences.isBcn_beaconsEnabledSecondCat() != secondEnabled) {
preferences.setBcn_beaconsEnabledSecondCat(secondEnabled);
}
}
private ChannelState state(Channel channel) {
return channel == Channel.MAIN ? main : second;
}
private static final class ChannelState {
private boolean enabled;
private boolean failed;
private Long referenceHz;
private InactiveReason reason = InactiveReason.NOT_ACTIVATED_THIS_SESSION;
private void reset() {
enabled = false;
failed = false;
referenceHz = null;
reason = InactiveReason.NOT_ACTIVATED_THIS_SESSION;
}
private void disable(InactiveReason inactiveReason) {
enabled = false;
failed = false;
referenceHz = null;
reason = inactiveReason;
}
}
}
@@ -1,54 +0,0 @@
package kst4contest.controller;
import kst4contest.model.BeaconStatusSnapshot;
import kst4contest.model.ChatPreferences;
import kst4contest.model.ThreadStateMessage;
/** Builds the single status shown for both beacons from their session state. */
final class BeaconStatus {
static final String SOURCE_NAME = ChatController.BEACON_STATUS_SOURCE;
private String activity = "Beacon configuration loaded.";
/** Records the result of one complete timer run. */
synchronized void recordRun(String activity) {
this.activity = activity;
}
/** Updates the explanation without hiding a still-relevant category failure. */
synchronized void recordActivity(String activity) {
this.activity = activity;
}
/** Builds a fresh aggregate from the current preferences and remembered failures. */
synchronized ThreadStateMessage message(
ChatPreferences preferences,
BeaconSessionState sessionState
) {
BeaconStatusSnapshot snapshot = sessionState.snapshot(preferences);
boolean critical = snapshot.getAggregateState()
== BeaconStatusSnapshot.AggregateState.FAILED;
boolean running = snapshot.getAggregateState()
!= BeaconStatusSnapshot.AggregateState.OFF;
String description;
switch (snapshot.getAggregateState()) {
case FAILED -> description = "FAILED";
case OFF -> description = "off";
case ON -> description = "on";
case PARTIAL -> description = "1/2";
default -> throw new IllegalStateException("Unknown beacon status");
}
ThreadStateMessage message = new ThreadStateMessage(
SOURCE_NAME,
running,
activity,
critical
);
message.setRunningInformationTextDescription(description);
message.setBeaconStatusSnapshot(snapshot);
return message;
}
}
@@ -4,6 +4,7 @@ import java.util.TimerTask;
import kst4contest.model.ChatCategory;
import kst4contest.model.ChatMessage;
import kst4contest.model.ThreadStateMessage;
/**
* Sends the configured public-chat beacons for both active chat categories.
@@ -19,10 +20,10 @@ import kst4contest.model.ChatMessage;
*/
public class BeaconTask extends TimerTask {
private static final String THREAD_NICKNAME = "MyBeacon";
private final ChatController chatController;
private final ThreadStatusCallback callbackToController;
private final BeaconStatus beaconStatus;
private final BeaconSessionState beaconSessionState;
/**
* Creates one execution of the shared beacon timer.
@@ -36,46 +37,30 @@ public class BeaconTask extends TimerTask {
) {
this.chatController = chatController;
this.callbackToController = callbackToController;
this.beaconStatus = chatController.beaconStatusState();
this.beaconSessionState = chatController.beaconSessionState();
}
@Override
public void run() {
Thread.currentThread().setName("BeaconTask");
Attempt main = sendMainCategoryBeacon();
Attempt second = sendSecondCategoryBeacon();
String activity = "Main category: " + main.description
+ "; second category: " + second.description;
recordSendResult(BeaconSessionState.Channel.MAIN, main);
recordSendResult(BeaconSessionState.Channel.SECOND, second);
beaconStatus.recordRun(activity);
callbackToController.onThreadStatus(
BeaconStatus.SOURCE_NAME,
beaconStatus.message(
chatController.getChatPreferences(),
beaconSessionState
)
);
}
reportStatus(THREAD_NICKNAME, true, "initialized", false);
private void recordSendResult(
BeaconSessionState.Channel channel,
Attempt attempt
) {
if (attempt == Attempt.INVALID) {
beaconSessionState.recordSendFailure(channel, true);
} else if (attempt == Attempt.SENT) {
beaconSessionState.recordSendFailure(channel, false);
}
sendMainCategoryBeacon();
sendSecondCategoryBeacon();
}
/**
* Sends the main-category beacon if it is currently enabled.
*/
private Attempt sendMainCategoryBeacon() {
if (!beaconSessionState.isEnabled(BeaconSessionState.Channel.MAIN)) {
return Attempt.OFF;
private void sendMainCategoryBeacon() {
if (!chatController.getChatPreferences()
.isBcn_beaconsEnabledMainCat()) {
reportStatus(
THREAD_NICKNAME + " 1",
false,
"off",
false
);
return;
}
ChatMessage beaconMessage = buildBeaconMessage(
@@ -87,7 +72,13 @@ public class BeaconTask extends TimerTask {
);
if (beaconMessage == null) {
return Attempt.INVALID;
reportStatus(
THREAD_NICKNAME + " 1",
false,
"invalid text",
true
);
return;
}
System.out.println(
@@ -97,19 +88,31 @@ public class BeaconTask extends TimerTask {
);
chatController.getMessageTXBus().add(beaconMessage);
return Attempt.SENT;
reportStatus(
THREAD_NICKNAME + " 1",
true,
"on",
false
);
}
/**
* Sends the second-category beacon if the second login and its beacon are
* currently enabled.
*/
private Attempt sendSecondCategoryBeacon() {
if (!chatController.getChatPreferences().isLoginToSecondChatEnabled()) {
return Attempt.UNAVAILABLE;
}
if (!beaconSessionState.isEnabled(BeaconSessionState.Channel.SECOND)) {
return Attempt.OFF;
private void sendSecondCategoryBeacon() {
if (!chatController.getChatPreferences()
.isLoginToSecondChatEnabled()
|| !chatController.getChatPreferences()
.isBcn_beaconsEnabledSecondCat()) {
reportStatus(
THREAD_NICKNAME + " 2",
false,
"off",
false
);
return;
}
ChatMessage beaconMessage = buildBeaconMessage(
@@ -121,7 +124,13 @@ public class BeaconTask extends TimerTask {
);
if (beaconMessage == null) {
return Attempt.INVALID;
reportStatus(
THREAD_NICKNAME + " 2",
false,
"invalid text",
true
);
return;
}
System.out.println(
@@ -131,7 +140,13 @@ public class BeaconTask extends TimerTask {
);
chatController.getMessageTXBus().add(beaconMessage);
return Attempt.SENT;
reportStatus(
THREAD_NICKNAME + " 2",
true,
"on",
false
);
}
/**
@@ -184,16 +199,24 @@ public class BeaconTask extends TimerTask {
}
}
private enum Attempt {
SENT("sent"),
OFF("off"),
UNAVAILABLE("unavailable"),
INVALID("invalid text");
private final String description;
Attempt(String description) {
this.description = description;
}
/**
* Forwards one state update to the existing thread-status display.
*/
private void reportStatus(
String threadName,
boolean running,
String information,
boolean criticalState
) {
ThreadStateMessage stateMessage = new ThreadStateMessage(
threadName,
running,
information,
criticalState
);
callbackToController.onThreadStatus(
THREAD_NICKNAME,
stateMessage
);
}
}
}
@@ -64,15 +64,9 @@ public class ChatController implements ThreadStatusCallback {
private static final boolean DEBUG_BAND_UPGRADE_HINT = true; //for new band hint
public static final String BEACON_STATUS_SOURCE = "MyBeacon";
public static final int MIN_BEACON_INTERVAL_MINUTES = 5;
public static final int MAX_BEACON_PAYLOAD_LENGTH = 120;
public static final int MAX_BEACON_TEXT_LENGTH =
MAX_BEACON_PAYLOAD_LENGTH
+ AutomaticChatMessageFormatter.SUFFIX.length();
public static final int MIN_BEACON_INTERVAL_MINUTES = 1;
public static final int MAX_BEACON_TEXT_LENGTH = 120;
private static final long INITIAL_BEACON_DELAY_MILLIS = 10_000L;
private final BeaconSessionState beaconSessionState = new BeaconSessionState();
private final BeaconStatus beaconStatus = new BeaconStatus();
private Consumer<Double> viewRotorCallback;
@@ -3040,7 +3034,6 @@ private SimpleRoster<String>
chatPreferences = new ChatPreferences(preferencesRelativeFileName);
chatPreferences.readPreferencesFromXmlFile();
beaconSessionState.resetSession(chatPreferences);
Path historyFile = Path.of(ApplicationFileUtils.getDebugFilePath(
ApplicationConstants.APPLICATION_NAME,
MessageHistoryRecorder.CURRENT_FILE_NAME));
@@ -3293,7 +3286,6 @@ private SimpleRoster<String>
public void setChatPreferences(ChatPreferences chatPreferences) {
this.chatPreferences = chatPreferences;
beaconSessionState.resetSession(chatPreferences);
}
public ChatMember getownChatMemberObject() {
@@ -3389,124 +3381,6 @@ private SimpleRoster<String>
this.dbHandler = dbHandler;
}
/** Applies the main-category beacon switch to the running session immediately. */
public void setMainBeaconEnabled(boolean enabled) {
beaconSessionState.setEnabled(
BeaconSessionState.Channel.MAIN,
enabled,
getChatPreferences()
);
publishBeaconStatus("Beacon configuration changed.");
}
/** Applies the second-category beacon switch to the running session immediately. */
public void setSecondBeaconEnabled(boolean enabled) {
beaconSessionState.setEnabled(
BeaconSessionState.Channel.SECOND,
enabled,
getChatPreferences()
);
publishBeaconStatus("Beacon configuration changed.");
}
/**
* Toggles every beacon usable in the current chat configuration.
*
* <p>The dormant second-category preference is deliberately left unchanged when
* the second chat is disabled. Enabling that chat later therefore restores the
* operator's previous category-specific choice.</p>
*/
public void toggleUsableBeacons() {
ChatPreferences preferences = getChatPreferences();
boolean secondAvailable = preferences.isLoginToSecondChatEnabled();
boolean anyEnabled = beaconSessionState.isEnabled(BeaconSessionState.Channel.MAIN)
|| (secondAvailable
&& beaconSessionState.isEnabled(BeaconSessionState.Channel.SECOND));
boolean enable = !anyEnabled;
beaconSessionState.setEnabled(
BeaconSessionState.Channel.MAIN,
enable,
preferences
);
if (secondAvailable) {
beaconSessionState.setEnabled(
BeaconSessionState.Channel.SECOND,
enable,
preferences
);
}
publishBeaconStatus("Beacon status toggled from the main window.");
}
/** Applies a deliberate operator QRG entry and rebases the affected beacon. */
public void applyManualQrg(RadioSlot slot, String value) {
BeaconSessionState.Channel channel = slot == RadioSlot.FIRST
? BeaconSessionState.Channel.MAIN
: BeaconSessionState.Channel.SECOND;
beaconSessionState.onManualQrgChanged(channel, value, getChatPreferences());
publishBeaconStatus("QRG changed by the operator.");
}
/** Applies a logger QRG report and enforces the automatic-QSY safety boundary. */
public void applyExternalQrg(RadioSlot slot, String displayValue, long frequencyHz) {
if (frequencyHz <= 0L) {
return;
}
slot.qrgIn(getChatPreferences()).set(displayValue);
BeaconSessionState.Channel channel = slot == RadioSlot.FIRST
? BeaconSessionState.Channel.MAIN
: BeaconSessionState.Channel.SECOND;
beaconSessionState.onExternalQrgChanged(channel, frequencyHz, getChatPreferences());
publishBeaconStatus("QRG updated by logging software.");
}
/** Revalidates the applied main-category template. */
public void onMainBeaconTemplateApplied() {
beaconSessionState.onTemplateChanged(
BeaconSessionState.Channel.MAIN,
getChatPreferences()
);
publishBeaconStatus("Beacon template changed.");
}
/** Revalidates the applied second-category template. */
public void onSecondBeaconTemplateApplied() {
beaconSessionState.onTemplateChanged(
BeaconSessionState.Channel.SECOND,
getChatPreferences()
);
publishBeaconStatus("Beacon template changed.");
}
/** Publishes the loaded state without changing either category switch. */
public void refreshBeaconStatus() {
publishBeaconStatus("Beacon configuration loaded.");
}
/** Returns the shared state used by the timer and manual controls. */
BeaconStatus beaconStatusState() {
return beaconStatus;
}
BeaconSessionState beaconSessionState() {
return beaconSessionState;
}
/** Builds the current aggregate when the UI is ready to display it. */
public ThreadStateMessage currentBeaconStatus() {
return beaconStatus.message(getChatPreferences(), beaconSessionState);
}
/** Publishes the aggregate state used by the single beacon status chip. */
private void publishBeaconStatus(String activity) {
beaconStatus.recordActivity(activity);
onThreadStatus(
BeaconStatus.SOURCE_NAME,
currentBeaconStatus()
);
}
/**
* Validates a configured beacon template before it is stored.
@@ -3520,7 +3394,7 @@ private SimpleRoster<String>
* @param configuredText configured beacon template
* @throws IllegalArgumentException if the template contains invalid protocol
* content or currently resolves to more than
* {@value MAX_BEACON_PAYLOAD_LENGTH} characters
* {@value MAX_BEACON_TEXT_LENGTH} characters
*/
public void validateBeaconTemplate(String configuredText) {
String normalizedTemplate =
@@ -3539,10 +3413,7 @@ private SimpleRoster<String>
return;
}
validateBeaconText(
resolvedText,
MAX_BEACON_PAYLOAD_LENGTH
);
validateResolvedBeaconText(resolvedText);
}
/**
@@ -3563,29 +3434,22 @@ private SimpleRoster<String>
new MessageVariableResolver(chatPreferences)
.resolveGlobalVariables(configuredText);
String normalizedPayload = validateBeaconText(
resolvedText,
MAX_BEACON_PAYLOAD_LENGTH
);
return validateBeaconText(
AutomaticChatMessageFormatter.appendSuffix(normalizedPayload),
MAX_BEACON_TEXT_LENGTH
);
return validateResolvedBeaconText(resolvedText);
}
/**
* Applies the message-text and length rules to a beacon processing stage.
* Applies the message-text and length rules to a fully resolved beacon.
*/
private String validateBeaconText(String resolvedText, int maximumLength) {
private String validateResolvedBeaconText(String resolvedText) {
String normalizedText =
On4KstProtocol.messageText(resolvedText);
if (normalizedText.length() > maximumLength) {
if (normalizedText.length() > MAX_BEACON_TEXT_LENGTH) {
throw new IllegalArgumentException(
"The resolved beacon message contains "
+ normalizedText.length()
+ " characters; maximum is "
+ maximumLength
+ MAX_BEACON_TEXT_LENGTH
+ "."
);
}
@@ -872,14 +872,10 @@ public class MessageBusManagementThread extends Thread {
versionInfo.setSender(itsMe);
versionInfo.setReceiver(newMessageArrived.getSender());
versionInfo.setChatCategory(newMessageArrived.getChatCategory());
versionInfo.setMessageText(
AutomaticChatMessageFormatter.appendSuffix(
"/CQ " + newMessageArrived.getSender().getCallSign()
+ " " + AUTOANSWER_PREFIX
+ " KST4Contest v" + ApplicationConstants.APPLICATION_CURRENT_VERSION
+ " by DO5AMF"
)
);
versionInfo.setMessageText("/CQ " + newMessageArrived.getSender().getCallSign()
+ " " + AUTOANSWER_PREFIX
+ " KST4Contest v" + ApplicationConstants.APPLICATION_CURRENT_VERSION
+ " by DO5AMF");
this.client.getMessageTXBus().add(versionInfo);
}
@@ -2074,9 +2070,7 @@ public class MessageBusManagementThread extends Thread {
+ payload;
try {
return On4KstProtocol.messageText(
AutomaticChatMessageFormatter.appendSuffix(messageText)
);
return On4KstProtocol.messageText(messageText);
} catch (IllegalArgumentException invalidMessage) {
LOGGER.warning(
@@ -535,7 +535,6 @@ public class ReadUDPByWintestThread extends Thread {
* interpreted as frequencies.
*/
String formattedPassQrg = null;
Long passFrequencyRawValue = null;
if (parts.size() > 11) {
try {
@@ -545,7 +544,6 @@ public class ReadUDPByWintestThread extends Thread {
passFrequencyRaw / 10.0;
if (passFrequencyKHz > 100.0) {
passFrequencyRawValue = passFrequencyRaw;
formattedPassQrg =
helper_formatWinTestFrequency(
passFrequencyRaw
@@ -568,16 +566,10 @@ public class ReadUDPByWintestThread extends Thread {
usePassQrg && formattedPassQrg != null
? formattedPassQrg
: formattedMainQrg;
final long selectedFrequencyRaw =
usePassQrg && passFrequencyRawValue != null
? passFrequencyRawValue
: mainFrequencyRaw;
final long selectedFrequencyHz = Math.multiplyExact(selectedFrequencyRaw, 100L);
if (prefs.isLogsynch_wintestQrgSyncEnabled()) {
RadioSlot target = slot.get();
client.uiDispatcher().runOnUi(() ->
client.applyExternalQrg(target, qrgToSet, selectedFrequencyHz));
client.uiDispatcher().runOnUi(() -> target.qrgIn(prefs).set(qrgToSet));
}
System.out.println(
@@ -417,19 +417,7 @@ public class ReadUDPbyUCXMessageThread extends Thread {
}
String qrg = freqNode.getTextContent();
qrg = qrg == null ? "" : qrg.trim();
String mode = modeNode.getTextContent();
final long frequencyHz;
try {
frequencyHz = Math.multiplyExact(Long.parseLong(qrg), 10L);
} catch (NumberFormatException | ArithmeticException invalidFrequency) {
System.out.println("[ReadUDPFromUCX, warning]: RadioInfo with invalid Freq ignored");
continue;
}
if (frequencyHz <= 0L) {
System.out.println("[ReadUDPFromUCX, warning]: RadioInfo with non-positive Freq ignored");
continue;
}
// System.out.println("QRG Length: " + qrg.length() + " // " + qrg);
@@ -476,7 +464,7 @@ public class ReadUDPbyUCXMessageThread extends Thread {
final String finalFormattedQRG = formattedQRG;
final RadioSlot target = slot.get();
helper_runOnFxThread(() ->
this.client.applyExternalQrg(target, finalFormattedQRG, frequencyHz)
target.qrgIn(this.client.getChatPreferences()).set(finalFormattedQRG)
);
// System.out.println("[ReadUDPbyUCXTh: ] Radioinfo processed: " + formattedQRG);
@@ -1,83 +0,0 @@
package kst4contest.model;
import java.util.Objects;
/** Immutable, display-neutral status of both beacon categories. */
public final class BeaconStatusSnapshot {
public enum AggregateState {
OFF,
PARTIAL,
ON,
FAILED
}
public enum InactiveReason {
NOT_ACTIVATED_THIS_SESSION,
USER_DISABLED,
PRIMARY_QRG_UNAVAILABLE,
SECONDARY_QRG_UNAVAILABLE,
AUTOMATIC_QRG_CHANGE
}
/** Immutable status of one beacon category. */
public static final class CategoryStatus {
private final boolean available;
private final boolean enabled;
private final boolean failed;
private final InactiveReason inactiveReason;
public CategoryStatus(
boolean available,
boolean enabled,
boolean failed,
InactiveReason inactiveReason
) {
this.available = available;
this.enabled = enabled;
this.failed = failed;
this.inactiveReason = Objects.requireNonNull(inactiveReason);
}
public boolean isAvailable() {
return available;
}
public boolean isEnabled() {
return enabled;
}
public boolean isFailed() {
return failed;
}
public InactiveReason getInactiveReason() {
return inactiveReason;
}
}
private final AggregateState aggregateState;
private final CategoryStatus main;
private final CategoryStatus second;
public BeaconStatusSnapshot(
AggregateState aggregateState,
CategoryStatus main,
CategoryStatus second
) {
this.aggregateState = Objects.requireNonNull(aggregateState);
this.main = Objects.requireNonNull(main);
this.second = Objects.requireNonNull(second);
}
public AggregateState getAggregateState() {
return aggregateState;
}
public CategoryStatus getMain() {
return main;
}
public CategoryStatus getSecond() {
return second;
}
}
@@ -366,9 +366,8 @@ public class ChatPreferences {
* Beacon prefs
*/
private static final int MIN_BEACON_INTERVAL_MINUTES = 5;
MutableValue<Boolean> bcn_beaconsEnabledMainCat = new SimpleValue<>(false);
MutableValue<Boolean> bcn_beaconsEnabledSecondCat = new SimpleValue<>(false);
boolean bcn_beaconsEnabledMainCat = true;
boolean bcn_beaconsEnabledSecondCat = false;
int bcn_beaconIntervalInMinutesMainCat = 20;
int bcn_beaconIntervalInMinutesSecondCat = 20;
String bcn_beaconTextMainCat = "Hi, pse call us";
@@ -738,15 +737,11 @@ public class ChatPreferences {
}
public boolean isBcn_beaconsEnabledSecondCat() {
return Boolean.TRUE.equals(bcn_beaconsEnabledSecondCat.get());
return bcn_beaconsEnabledSecondCat;
}
public void setBcn_beaconsEnabledSecondCat(boolean bcn_beaconsEnabledSecondCat) {
this.bcn_beaconsEnabledSecondCat.set(bcn_beaconsEnabledSecondCat);
}
public MutableValue<Boolean> bcnBeaconsEnabledSecondCatProperty() {
return bcn_beaconsEnabledSecondCat;
this.bcn_beaconsEnabledSecondCat = bcn_beaconsEnabledSecondCat;
}
public int getBcn_beaconIntervalInMinutesSecondCat() {
@@ -1584,10 +1579,6 @@ public class ChatPreferences {
// }
public boolean isBcn_beaconsEnabledMainCat() {
return Boolean.TRUE.equals(bcn_beaconsEnabledMainCat.get());
}
public MutableValue<Boolean> bcnBeaconsEnabledMainCatProperty() {
return bcn_beaconsEnabledMainCat;
}
@@ -1610,7 +1601,7 @@ public class ChatPreferences {
}
public void setBcn_beaconsEnabledMainCat(boolean bcn_beaconsEnabledMainCat) {
this.bcn_beaconsEnabledMainCat.set(bcn_beaconsEnabledMainCat);
this.bcn_beaconsEnabledMainCat = bcn_beaconsEnabledMainCat;
}
public int getBcn_beaconIntervalInMinutesMainCat() {
@@ -2199,11 +2190,11 @@ public class ChatPreferences {
beaconCQ.appendChild(bcn_beaconIntervalInMinutesMainCat);
Element beaconCQEnabled = doc.createElement("beaconCQEnabled");
beaconCQEnabled.setTextContent("false");
beaconCQEnabled.setTextContent(this.isBcn_beaconsEnabledMainCat()+"");
beaconCQ.appendChild(beaconCQEnabled);
Element bcn_beaconsEnabledMainCat = doc.createElement("bcn_beaconsEnabledMainCat");
bcn_beaconsEnabledMainCat.setTextContent("false");
bcn_beaconsEnabledMainCat.setTextContent(this.isBcn_beaconsEnabledMainCat()+"");
beaconCQ.appendChild(bcn_beaconsEnabledMainCat);
@@ -2224,11 +2215,11 @@ public class ChatPreferences {
beaconCQ.appendChild(bcn_beaconIntervalInMinutesSecondCat);
Element beaconCQEnabledSecondCat = doc.createElement("beaconCQEnabledSecondCat");
beaconCQEnabledSecondCat.setTextContent("false");
beaconCQEnabledSecondCat.setTextContent(this.isBcn_beaconsEnabledSecondCat()+"");
beaconCQ.appendChild(beaconCQEnabledSecondCat);
Element bcn_beaconsEnabledSecondCat = doc.createElement("bcn_beaconsEnabledSecondCat");
bcn_beaconsEnabledSecondCat.setTextContent("false");
bcn_beaconsEnabledSecondCat.setTextContent(this.isBcn_beaconsEnabledSecondCat()+"");
beaconCQ.appendChild(bcn_beaconsEnabledSecondCat);
/**
@@ -3179,18 +3170,12 @@ public class ChatPreferences {
Element beaconCQEl = getFirstElement(doc, "beaconCQ");
if (beaconCQEl != null) {
setBcn_beaconsEnabledMainCat(false);
bcn_beaconIntervalInMinutesMainCat = Math.max(
MIN_BEACON_INTERVAL_MINUTES,
getInt(beaconCQEl, bcn_beaconIntervalInMinutesMainCat, "bcn_beaconIntervalInMinutesMainCat", "beaconCQIntervalMinutes")
);
bcn_beaconsEnabledMainCat = getBoolean(beaconCQEl, bcn_beaconsEnabledMainCat, "bcn_beaconsEnabledMainCat", "beaconCQEnabled");
bcn_beaconIntervalInMinutesMainCat = getInt(beaconCQEl, bcn_beaconIntervalInMinutesMainCat, "bcn_beaconIntervalInMinutesMainCat", "beaconCQIntervalMinutes");
bcn_beaconTextMainCat = getText(beaconCQEl, bcn_beaconTextMainCat, "bcn_beaconTextMainCat", "beaconCQText");
setBcn_beaconsEnabledSecondCat(false);
bcn_beaconIntervalInMinutesSecondCat = Math.max(
MIN_BEACON_INTERVAL_MINUTES,
getInt(beaconCQEl, bcn_beaconIntervalInMinutesSecondCat, "bcn_beaconIntervalInMinutesSecondCat", "beaconCQIntervalMinutesSecondCat")
);
bcn_beaconsEnabledSecondCat = getBoolean(beaconCQEl, bcn_beaconsEnabledSecondCat, "bcn_beaconsEnabledSecondCat", "beaconCQEnabledSecondCat");
bcn_beaconIntervalInMinutesSecondCat = getInt(beaconCQEl, bcn_beaconIntervalInMinutesSecondCat, "bcn_beaconIntervalInMinutesSecondCat", "beaconCQIntervalMinutesSecondCat");
bcn_beaconTextSecondCat = getText(beaconCQEl, bcn_beaconTextSecondCat, "bcn_beaconTextSecondCat", "beaconCQTextSecondText");
System.out.println("[ChatPreferences, info]: beaconCQ main='" + bcn_beaconTextMainCat + "', second='" + bcn_beaconTextSecondCat + "'");
@@ -14,7 +14,6 @@ public class ThreadStateMessage {
boolean criticalState;
String criticalStateFurtherInfo;
BeaconStatusSnapshot beaconStatusSnapshot;
@@ -100,13 +99,5 @@ public class ThreadStateMessage {
public void setCriticalStateFurtherInfo(String criticalStateFurtherInfo) {
this.criticalStateFurtherInfo = criticalStateFurtherInfo;
}
public BeaconStatusSnapshot getBeaconStatusSnapshot() {
return beaconStatusSnapshot;
}
public void setBeaconStatusSnapshot(BeaconStatusSnapshot beaconStatusSnapshot) {
this.beaconStatusSnapshot = beaconStatusSnapshot;
}
}
@@ -1,9 +1,7 @@
package kst4contest.view.map;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Locale;
/**
@@ -83,39 +81,12 @@ public final class MaidenheadGridUtils {
double northLat,
double eastLon,
GridPrecision precision) {
if (!Double.isFinite(westLon) || !Double.isFinite(eastLon)) {
if (westLon > eastLon) {
// Anti-meridian handling is not needed for Europe in this project stage.
return List.of();
}
double unwrappedEast = eastLon;
if (unwrappedEast < westLon) {
unwrappedEast += 360.0;
}
if (unwrappedEast - westLon >= 360.0) {
return buildVisibleCellsWithinWorld(southLat, -180.0, northLat, 180.0, precision);
}
int firstWorld = (int) Math.floor((westLon + 180.0) / 360.0);
int lastWorld = (int) Math.floor((unwrappedEast + 180.0 - EPSILON) / 360.0);
Map<String, GridCell> cells = new LinkedHashMap<>();
for (int world = firstWorld; world <= lastWorld; world++) {
double worldWest = -180.0 + world * 360.0;
double worldEast = 180.0 + world * 360.0;
double localWest = Math.max(westLon, worldWest) - world * 360.0;
double localEast = Math.min(unwrappedEast, worldEast) - world * 360.0;
buildVisibleCellsWithinWorld(southLat, localWest, northLat, localEast, precision)
.forEach(cell -> cells.putIfAbsent(cell.locatorLabel(), cell));
}
return List.copyOf(cells.values());
}
private static List<GridCell> buildVisibleCellsWithinWorld(double southLat,
double westLon,
double northLat,
double eastLon,
GridPrecision precision) {
double clampedSouth = clamp(southLat, -90.0 + EPSILON, 90.0 - EPSILON);
double clampedNorth = clamp(northLat, -90.0 + EPSILON, 90.0 - EPSILON);
double clampedWest = clamp(westLon, -180.0 + EPSILON, 180.0 - EPSILON);
@@ -246,4 +217,4 @@ public final class MaidenheadGridUtils {
private static double clamp(double value, double min, double max) {
return Math.max(min, Math.min(max, value));
}
}
}
@@ -8,8 +8,6 @@ public final class MapMarkerCluster {
private final List<MapCallsignRawSnapshot> markers = new ArrayList<>();
private double sumLon = 0.0;
private double sumLat = 0.0;
private double sumLonSin = 0.0;
private double sumLonCos = 0.0;
public MapMarkerCluster(MapCallsignRawSnapshot first) {
add(first);
@@ -19,16 +17,10 @@ public final class MapMarkerCluster {
markers.add(marker);
sumLon += marker.longitudeDeg();
sumLat += marker.latitudeDeg();
double longitudeRad = Math.toRadians(marker.longitudeDeg());
sumLonSin += Math.sin(longitudeRad);
sumLonCos += Math.cos(longitudeRad);
}
public double getCenterLon() {
if (Math.abs(sumLonSin) < 1e-12 && Math.abs(sumLonCos) < 1e-12) {
return sumLon / markers.size();
}
return Math.toDegrees(Math.atan2(sumLonSin, sumLonCos));
return sumLon / markers.size();
}
public double getCenterLat() {
@@ -99,21 +99,6 @@ public final class MapViewport {
return widthPx / 2.0 + (WebMercatorProjection.lonToX(lon, tileZoom) - centerWorldX) * tileScale;
}
/**
* Places a longitude in the closest wrapped copy of the world.
*
* <p>A target at 179 degrees east and a centre at 179 degrees west are two degrees
* apart, not 358. Tiles already wrap at the anti-meridian; overlays and hit testing
* need the same world copy to stay aligned with them.</p>
*/
public double screenXWrapped(double lon) {
double worldSize = TILE_SIZE_PX * Math.pow(2.0, tileZoom);
double worldX = WebMercatorProjection.lonToX(lon, tileZoom);
double delta = worldX - centerWorldX;
delta -= Math.rint(delta / worldSize) * worldSize;
return widthPx / 2.0 + delta * tileScale;
}
public double screenY(double lat) {
return heightPx / 2.0 + (WebMercatorProjection.latToY(lat, tileZoom) - centerWorldY) * tileScale;
}
@@ -1,153 +0,0 @@
package kst4contest.view.map;
/** Pure viewport calculations for deliberate station-map navigation. */
public final class MapViewportNavigation {
private static final double WEB_MERCATOR_MAX_LATITUDE = 85.05112878;
private MapViewportNavigation() {
}
/**
* Centres the path and zooms out only when both endpoints do not fit with padding.
*
* @return the fitted viewport, or the original viewport for invalid positions or size
*/
public static MapViewport fitPath(MapViewport current,
double homeLatitudeDeg,
double homeLongitudeDeg,
double targetLatitudeDeg,
double targetLongitudeDeg,
double paddingPx) {
if (current == null
|| !isPosition(homeLatitudeDeg, homeLongitudeDeg)
|| !isPosition(targetLatitudeDeg, targetLongitudeDeg)
|| current.widthPx() <= 0.0
|| current.heightPx() <= 0.0) {
return current;
}
double padding = Math.max(0.0, paddingPx);
double availableWidth = current.widthPx() - 2.0 * padding;
double availableHeight = current.heightPx() - 2.0 * padding;
if (availableWidth <= 0.0 || availableHeight <= 0.0) {
return current;
}
double homeWorldX = WebMercatorProjection.lonToX(homeLongitudeDeg, 0);
double targetWorldX = WebMercatorProjection.lonToX(targetLongitudeDeg, 0);
double worldSize = 256.0;
double deltaX = targetWorldX - homeWorldX;
deltaX -= Math.rint(deltaX / worldSize) * worldSize;
double centerWorldX = homeWorldX + deltaX / 2.0;
double homeWorldY = WebMercatorProjection.latToY(homeLatitudeDeg, 0);
double targetWorldY = WebMercatorProjection.latToY(targetLatitudeDeg, 0);
double centerWorldY = (homeWorldY + targetWorldY) / 2.0;
double centerLongitude = WebMercatorProjection.xToLon(centerWorldX, 0);
double centerLatitude = WebMercatorProjection.yToLat(centerWorldY, 0);
MapViewport centred = new MapViewport(
centerLongitude,
centerLatitude,
current.zoom(),
current.widthPx(),
current.heightPx()
);
double widthAtCurrentZoom = Math.abs(
centred.screenXWrapped(targetLongitudeDeg)
- centred.screenXWrapped(homeLongitudeDeg)
);
double heightAtCurrentZoom = Math.abs(
centred.screenY(targetLatitudeDeg) - centred.screenY(homeLatitudeDeg)
);
double widthRatio = widthAtCurrentZoom == 0.0
? Double.POSITIVE_INFINITY
: availableWidth / widthAtCurrentZoom;
double heightRatio = heightAtCurrentZoom == 0.0
? Double.POSITIVE_INFINITY
: availableHeight / heightAtCurrentZoom;
double fitRatio = Math.min(widthRatio, heightRatio);
if (!Double.isFinite(fitRatio) || fitRatio >= 1.0) {
return centred;
}
double fittedZoom = current.zoom() + Math.log(fitRatio) / Math.log(2.0);
return new MapViewport(
centerLongitude,
centerLatitude,
fittedZoom,
current.widthPx(),
current.heightPx()
);
}
/**
* Leaves the zoom unchanged and places most of the viewport in the chosen direction.
*/
public static MapViewport centreOnBearing(MapViewport current,
double homeLatitudeDeg,
double homeLongitudeDeg,
double bearingDeg,
double forwardCentreFraction) {
if (current == null
|| !isPosition(homeLatitudeDeg, homeLongitudeDeg)
|| !Double.isFinite(bearingDeg)
|| current.widthPx() <= 0.0
|| current.heightPx() <= 0.0) {
return current;
}
double fraction = Math.max(0.0, Math.min(0.45, forwardCentreFraction));
double shiftPx = Math.min(current.widthPx(), current.heightPx()) * fraction;
double bearingRad = Math.toRadians(normaliseBearing(bearingDeg));
MapViewport homeCentred = new MapViewport(
homeLongitudeDeg,
homeLatitudeDeg,
current.zoom(),
current.widthPx(),
current.heightPx()
);
double centreX = current.widthPx() / 2.0 + Math.sin(bearingRad) * shiftPx;
double centreY = current.heightPx() / 2.0 - Math.cos(bearingRad) * shiftPx;
return new MapViewport(
homeCentred.lonAt(centreX),
homeCentred.latAt(centreY),
current.zoom(),
current.widthPx(),
current.heightPx()
);
}
public static MapViewport centreOnHome(MapViewport current,
double homeLatitudeDeg,
double homeLongitudeDeg) {
if (current == null || !isPosition(homeLatitudeDeg, homeLongitudeDeg)) {
return current;
}
return new MapViewport(
homeLongitudeDeg,
homeLatitudeDeg,
current.zoom(),
current.widthPx(),
current.heightPx()
);
}
private static boolean isPosition(double latitudeDeg, double longitudeDeg) {
return Double.isFinite(latitudeDeg)
&& Double.isFinite(longitudeDeg)
&& latitudeDeg >= -WEB_MERCATOR_MAX_LATITUDE
&& latitudeDeg <= WEB_MERCATOR_MAX_LATITUDE;
}
private static double normaliseBearing(double bearingDeg) {
double normalised = bearingDeg % 360.0;
return normalised < 0.0 ? normalised + 360.0 : normalised;
}
}
@@ -91,7 +91,7 @@ public final class StationMapClusterer {
continue;
}
long cellX = (long) Math.floor(viewport.screenXWrapped(marker.longitudeDeg()) / cellSizePx);
long cellX = (long) Math.floor(viewport.screenX(marker.longitudeDeg()) / cellSizePx);
long cellY = (long) Math.floor(viewport.screenY(marker.latitudeDeg()) / cellSizePx);
buckets.computeIfAbsent(cellKey(cellX, cellY), key -> new ArrayList<>()).add(marker);
@@ -112,10 +112,10 @@
</textSnippets>
<beaconCQ>
<beaconCQText>_.~'"´"'~.__.~'´ CQ CQ CQ NAC de MYCALL, pse try 144.317 for JO54 `'~.__.~'"`"'~._</beaconCQText>
<beaconCQIntervalMinutes>5</beaconCQIntervalMinutes>
<beaconCQIntervalMinutes>1</beaconCQIntervalMinutes>
<beaconCQEnabled>false</beaconCQEnabled>
<beaconCQTextSecondText>_.~'"´"'~.__.~'´ CQ CQ CQ de MYCALL, pse sked or SECONDQRG `'~.__.~'"`"'~._</beaconCQTextSecondText>
<beaconCQIntervalMinutesSecondCat>5</beaconCQIntervalMinutesSecondCat>
<beaconCQIntervalMinutesSecondCat>3</beaconCQIntervalMinutesSecondCat>
<beaconCQEnabledSecondCat>false</beaconCQEnabledSecondCat>
</beaconCQ>
<beaconUnworkedstations>
@@ -1,27 +0,0 @@
package kst4contest.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/** Verifies the fixed suffix contract for automatic chat messages. */
class AutomaticChatMessageFormatterTest {
@Test
void appendsTheExactAutomaticChatSuffix() {
assertEquals(
"CQ test *a*",
AutomaticChatMessageFormatter.appendSuffix("CQ test"),
"the suffix must include its leading space"
);
}
@Test
void appendsTheSuffixEvenWhenTheTextAlreadyEndsWithIt() {
assertEquals(
"CQ test *a* *a*",
AutomaticChatMessageFormatter.appendSuffix("CQ test *a*"),
"an existing suffix must not be deduplicated"
);
}
}
@@ -1,133 +0,0 @@
package kst4contest.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import java.nio.file.Path;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import kst4contest.model.ChatPreferences;
import kst4contest.model.ThreadStateMessage;
class BeaconControlTest {
@TempDir
Path tempDir;
private ChatPreferences preferences;
private ChatController controller;
private StatusUpdateListener listener;
@BeforeEach
void setUp() {
preferences = new ChatPreferences(tempDir.resolve("preferences.xml"));
controller = new ChatController();
controller.setChatPreferences(preferences);
listener = mock(StatusUpdateListener.class);
controller.setStatusListener(listener);
}
@Test
void toggleWithSecondChatDisabledChangesOnlyTheMainBeacon() {
preferences.setLoginToSecondChatEnabled(false);
controller.setSecondBeaconEnabled(true);
controller.toggleUsableBeacons();
assertTrue(preferences.isBcn_beaconsEnabledMainCat());
assertTrue(preferences.isBcn_beaconsEnabledSecondCat(),
"the dormant second-category choice must not be overwritten");
assertLastDescription("on");
controller.toggleUsableBeacons();
assertFalse(preferences.isBcn_beaconsEnabledMainCat());
assertTrue(preferences.isBcn_beaconsEnabledSecondCat());
assertLastDescription("off");
}
@Test
void toggleWithSecondChatEnabledSwitchesBothUsableBeacons() {
preferences.setLoginToSecondChatEnabled(true);
controller.toggleUsableBeacons();
assertTrue(preferences.isBcn_beaconsEnabledMainCat());
assertTrue(preferences.isBcn_beaconsEnabledSecondCat());
assertLastDescription("on");
controller.setSecondBeaconEnabled(false);
controller.toggleUsableBeacons();
assertFalse(preferences.isBcn_beaconsEnabledMainCat());
assertFalse(preferences.isBcn_beaconsEnabledSecondCat());
assertLastDescription("off");
}
@Test
void anIndividualCheckboxPublishesThePartialStateImmediately() {
preferences.setLoginToSecondChatEnabled(true);
controller.setMainBeaconEnabled(true);
assertTrue(preferences.isBcn_beaconsEnabledMainCat());
assertFalse(preferences.isBcn_beaconsEnabledSecondCat());
assertLastDescription("1/2");
}
@Test
void activationRejectsOnlyTheTemplateWhoseRequiredQrgIsMissing() {
preferences.setLoginToSecondChatEnabled(true);
preferences.setMYQRGSecondCat("1296.200");
preferences.setBcn_beaconTextMainCat("CQ SECONDQRG");
preferences.setBcn_beaconTextSecondCat("CQ MYQRG");
controller.toggleUsableBeacons();
assertTrue(preferences.isBcn_beaconsEnabledMainCat());
assertFalse(preferences.isBcn_beaconsEnabledSecondCat());
}
@Test
void manualQrgRebasesBeforeAnAutomaticMoveIsCompared() {
preferences.setBcn_beaconTextMainCat("CQ");
controller.setMainBeaconEnabled(true);
controller.applyManualQrg(RadioSlot.FIRST, "144.300");
controller.applyExternalQrg(RadioSlot.FIRST, "144.305", 144_305_000L);
assertTrue(preferences.isBcn_beaconsEnabledMainCat());
controller.applyManualQrg(RadioSlot.FIRST, "144.310");
controller.applyExternalQrg(RadioSlot.FIRST, "144.315.01", 144_315_010L);
assertFalse(preferences.isBcn_beaconsEnabledMainCat());
}
@Test
void nonPositiveExternalQrgCannotOverwriteTheDisplayOrClearTheReference() {
preferences.setBcn_beaconTextMainCat("CQ");
controller.applyManualQrg(RadioSlot.FIRST, "144.300");
controller.setMainBeaconEnabled(true);
controller.applyExternalQrg(RadioSlot.FIRST, "0", 0L);
assertEquals("144.300", preferences.getMYQRGFirstCat().get());
controller.applyExternalQrg(RadioSlot.FIRST, "144.306", 144_306_000L);
assertFalse(preferences.isBcn_beaconsEnabledMainCat(),
"the rejected packet must not clear the 144.300 reference");
}
private void assertLastDescription(String expected) {
ArgumentCaptor<String> key = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<ThreadStateMessage> message = ArgumentCaptor.forClass(ThreadStateMessage.class);
org.mockito.Mockito.verify(listener, org.mockito.Mockito.atLeastOnce())
.onThreadStatusChanged(key.capture(), message.capture());
assertEquals("MyBeacon", key.getValue());
assertEquals(expected, message.getValue().getRunningInformationTextDescription());
}
}
@@ -1,31 +0,0 @@
package kst4contest.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class BeaconFrequencyParserTest {
@Test
void parsesEveryCompleteQrgFormWithoutLosingHertz() {
assertHz("144.300", 144_300_000L);
assertHz("144,300", 144_300_000L);
assertHz("144.300.03", 144_300_030L);
assertHz("1296.123.000", 1_296_123_000L);
assertHz("144300", 144_300_000L);
assertHz("10368100", 10_368_100_000L);
}
@Test
void rejectsIncompleteMalformedAndUnsupportedValues() {
for (String value : new String[] {null, "", " ", "210", "144 MHz", "0", "-144.300",
"999999999999999999999999999999"}) {
assertTrue(BeaconFrequencyParser.parseHz(value).isEmpty(), value);
}
}
private static void assertHz(String value, long expected) {
assertEquals(expected, BeaconFrequencyParser.parseHz(value).orElseThrow());
}
}
@@ -1,136 +0,0 @@
package kst4contest.controller;
import static kst4contest.controller.BeaconSessionState.Channel.MAIN;
import static kst4contest.controller.BeaconSessionState.Channel.SECOND;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.Path;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import kst4contest.model.BeaconStatusSnapshot;
import kst4contest.model.BeaconStatusSnapshot.AggregateState;
import kst4contest.model.BeaconStatusSnapshot.InactiveReason;
import kst4contest.model.ChatPreferences;
class BeaconSessionStateTest {
@TempDir Path tempDir;
private ChatPreferences preferences;
private BeaconSessionState state;
@BeforeEach
void setUp() {
preferences = new ChatPreferences(tempDir.resolve("preferences.xml"));
preferences.setLoginToSecondChatEnabled(true);
preferences.setBcn_beaconTextMainCat("CQ MAIN");
preferences.setBcn_beaconTextSecondCat("CQ SECOND");
preferences.setMYQRGFirstCat("");
preferences.setMYQRGSecondCat("");
state = new BeaconSessionState();
state.resetSession(preferences);
}
@Test
void resetStartsBothCategoriesOffWithSessionReason() {
BeaconStatusSnapshot snapshot = state.snapshot(preferences);
assertEquals(AggregateState.OFF, snapshot.getAggregateState());
assertEquals(InactiveReason.NOT_ACTIVATED_THIS_SESSION, snapshot.getMain().getInactiveReason());
assertEquals(InactiveReason.NOT_ACTIVATED_THIS_SESSION, snapshot.getSecond().getInactiveReason());
assertFalse(preferences.isBcn_beaconsEnabledMainCat());
assertFalse(preferences.isBcn_beaconsEnabledSecondCat());
}
@Test
void enablesValidCategoryAndRejectsOtherCategoryWithMissingCrossTemplateQrg() {
preferences.setMYQRGSecondCat("1296.123");
preferences.setBcn_beaconTextMainCat("CQ SECONDQRG");
preferences.setBcn_beaconTextSecondCat("CQ MYQRG");
assertTrue(state.setEnabled(MAIN, true, preferences));
assertFalse(state.setEnabled(SECOND, true, preferences));
BeaconStatusSnapshot snapshot = state.snapshot(preferences);
assertEquals(AggregateState.PARTIAL, snapshot.getAggregateState());
assertTrue(snapshot.getMain().isEnabled());
assertEquals(InactiveReason.PRIMARY_QRG_UNAVAILABLE, snapshot.getSecond().getInactiveReason());
}
@Test
void manualQrgRebasesAndInvalidValueClearsReferenceWithoutPlaceholder() {
assertTrue(state.setEnabled(MAIN, true, preferences));
state.onManualQrgChanged(MAIN, "144.300", preferences);
state.onExternalQrgChanged(MAIN, 144_306_000L, preferences);
assertFalse(state.isEnabled(MAIN));
assertTrue(state.setEnabled(MAIN, true, preferences));
state.onManualQrgChanged(MAIN, "invalid", preferences);
assertTrue(state.isEnabled(MAIN));
state.onExternalQrgChanged(MAIN, 144_310_000L, preferences);
assertTrue(state.isEnabled(MAIN), "first valid report establishes the cleared reference");
}
@Test
void invalidManualQrgDisablesEveryActiveTemplateThatNeedsIt() {
preferences.setMYQRGFirstCat("144.300");
preferences.setBcn_beaconTextMainCat("CQ MYQRG");
preferences.setBcn_beaconTextSecondCat("CQ MYQRGSHORT");
assertTrue(state.setEnabled(MAIN, true, preferences));
assertTrue(state.setEnabled(SECOND, true, preferences));
state.onManualQrgChanged(MAIN, "", preferences);
assertFalse(state.isEnabled(MAIN));
assertFalse(state.isEnabled(SECOND));
assertEquals(InactiveReason.PRIMARY_QRG_UNAVAILABLE,
state.snapshot(preferences).getSecond().getInactiveReason());
}
@Test
void externalMoveUsesStrictFiveKhzBoundaryAndOnlyItsCategory() {
preferences.setMYQRGFirstCat("144.300");
preferences.setMYQRGSecondCat("1296.100");
assertTrue(state.setEnabled(MAIN, true, preferences));
assertTrue(state.setEnabled(SECOND, true, preferences));
state.onExternalQrgChanged(MAIN, 144_305_000L, preferences);
assertTrue(state.isEnabled(MAIN));
state.onExternalQrgChanged(MAIN, 144_305_001L, preferences);
assertFalse(state.isEnabled(MAIN));
assertTrue(state.isEnabled(SECOND));
assertEquals(InactiveReason.AUTOMATIC_QRG_CHANGE,
state.snapshot(preferences).getMain().getInactiveReason());
}
@Test
void invalidExternalQrgClearsTheReferenceWithoutAPlaceholder() {
assertTrue(state.setEnabled(MAIN, true, preferences));
preferences.setMYQRGFirstCat("7.100.00");
state.onExternalQrgChanged(MAIN, 7_100_000L, preferences);
assertTrue(state.isEnabled(MAIN));
preferences.setMYQRGFirstCat("144.300");
state.onExternalQrgChanged(MAIN, 144_300_000L, preferences);
assertTrue(state.isEnabled(MAIN), "the first valid report must establish the reference");
}
@Test
void failureOverridesAggregateAndA_successClearsOnlyThatCategory() {
assertTrue(state.setEnabled(MAIN, true, preferences));
assertTrue(state.setEnabled(SECOND, true, preferences));
state.recordSendFailure(MAIN, true);
state.recordSendFailure(SECOND, true);
assertEquals(AggregateState.FAILED, state.snapshot(preferences).getAggregateState());
state.recordSendFailure(MAIN, false);
BeaconStatusSnapshot snapshot = state.snapshot(preferences);
assertEquals(AggregateState.FAILED, snapshot.getAggregateState());
assertFalse(snapshot.getMain().isFailed());
assertTrue(snapshot.getSecond().isFailed());
}
}
@@ -1,154 +0,0 @@
package kst4contest.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import kst4contest.model.ChatCategory;
import kst4contest.model.ChatMessage;
import kst4contest.model.ChatPreferences;
import kst4contest.model.ThreadStateMessage;
class BeaconTaskTest {
@TempDir
Path tempDir;
private ChatPreferences preferences;
private LinkedBlockingQueue<ChatMessage> txBus;
private List<ThreadStateMessage> statuses;
private ChatController controller;
private BeaconTask task;
@BeforeEach
void setUp() {
preferences = new ChatPreferences(tempDir.resolve("preferences.xml"));
preferences.setLoginChatCategoryMain(new ChatCategory(ChatCategory.VUHF));
preferences.setLoginChatCategorySecond(new ChatCategory(ChatCategory.MICROWAVE));
preferences.setLoginToSecondChatEnabled(true);
preferences.setBcn_beaconTextMainCat("CQ MAIN");
preferences.setBcn_beaconTextSecondCat("CQ SECOND");
preferences.setBcn_beaconsEnabledMainCat(false);
preferences.setBcn_beaconsEnabledSecondCat(false);
statuses = new ArrayList<>();
controller = new ChatController();
controller.setChatPreferences(preferences);
txBus = new LinkedBlockingQueue<>();
controller.setMessageTXBus(txBus);
controller.setStatusListener(new StatusUpdateListener() {
@Override
public void onThreadStatusChanged(String key, ThreadStateMessage message) {
statuses.add(message);
}
@Override
public void onUserListUpdated() {
// Not used by beacon tests.
}
@Override
public void onUserListUpdated(String reason) {
// Not used by beacon tests.
}
});
task = new BeaconTask(controller, (key, message) -> statuses.add(message));
}
@Test
void invalidEnabledBeaconIsNotQueuedAndReportsOneCriticalAggregateState() {
controller.setMainBeaconEnabled(true);
preferences.setBcn_beaconTextMainCat("invalid|template");
statuses.clear();
task.run();
assertTrue(txBus.isEmpty());
assertEquals(1, statuses.size());
ThreadStateMessage status = statuses.get(0);
assertEquals("FAILED", status.getRunningInformationTextDescription());
assertTrue(status.isRunning());
assertTrue(status.isCriticalState());
}
@Test
void changingTheOtherCheckboxDoesNotHideAnActiveCategoryFailure() {
controller.setMainBeaconEnabled(true);
preferences.setBcn_beaconTextMainCat("invalid|template");
statuses.clear();
task.run();
statuses.clear();
controller.setSecondBeaconEnabled(true);
assertEquals(1, statuses.size());
ThreadStateMessage status = statuses.get(0);
assertEquals("FAILED", status.getRunningInformationTextDescription());
assertTrue(status.isCriticalState());
}
@Test
void unavailableCategoryRetainsFailureUntilItsNextSuccessfulRun() {
controller.setSecondBeaconEnabled(true);
preferences.setBcn_beaconTextSecondCat("invalid|template");
task.run();
assertTrue(controller.currentBeaconStatus()
.getBeaconStatusSnapshot().getSecond().isFailed());
preferences.setLoginToSecondChatEnabled(false);
task.run();
assertTrue(controller.currentBeaconStatus()
.getBeaconStatusSnapshot().getSecond().isFailed(),
"an unavailable run did not succeed and must not clear the failure");
preferences.setLoginToSecondChatEnabled(true);
assertEquals("FAILED", controller.currentBeaconStatus()
.getRunningInformationTextDescription());
preferences.setBcn_beaconTextSecondCat("CQ SECOND");
task.run();
assertFalse(controller.currentBeaconStatus()
.getBeaconStatusSnapshot().getSecond().isFailed());
}
@Test
void everyRunUsesTheCurrentEnableFlagsAndReportsOneAggregateState() {
task.run();
assertTrue(txBus.isEmpty());
assertAggregateStatus("off", false);
statuses.clear();
controller.setMainBeaconEnabled(true);
statuses.clear();
task.run();
assertEquals(1, txBus.size());
assertEquals(ChatCategory.VUHF, txBus.peek().getChatCategory().getCategoryNumber());
assertEquals("CQ MAIN *a*", txBus.peek().getMessageText());
assertAggregateStatus("1/2", true);
statuses.clear();
controller.setSecondBeaconEnabled(true);
statuses.clear();
task.run();
assertEquals(3, txBus.size());
List<ChatMessage> sentMessages = new ArrayList<>(txBus);
assertEquals("CQ MAIN *a*", sentMessages.get(1).getMessageText());
assertEquals("CQ SECOND *a*", sentMessages.get(2).getMessageText());
assertAggregateStatus("on", true);
}
private void assertAggregateStatus(String description, boolean running) {
assertEquals(1, statuses.size(), "one timer run must leave one authoritative chip state");
ThreadStateMessage status = statuses.get(0);
assertEquals(description, status.getRunningInformationTextDescription());
assertEquals(running, status.isRunning());
assertFalse(status.isCriticalState());
}
}
@@ -116,7 +116,7 @@ class MessageBusManagementThreadAutoAnswerDecisionTest {
@Test
void buildsTheQrgReply() {
assertEquals(
"/CQ DL1ABC " + MARKER + " QRG is: 144.300 *a*",
"/CQ DL1ABC " + MARKER + " QRG is: 144.300",
MessageBusManagementThread.buildAutoAnswerMessageText(
"DL1ABC", VUHF, true, " 144.300 ", false, null));
}
@@ -124,7 +124,7 @@ class MessageBusManagementThreadAutoAnswerDecisionTest {
@Test
void qrgRequestWinsOverTheGenericReply() {
assertEquals(
"/CQ DL1ABC " + MARKER + " QRG is: 144.300 *a*",
"/CQ DL1ABC " + MARKER + " QRG is: 144.300",
MessageBusManagementThread.buildAutoAnswerMessageText(
"DL1ABC", VUHF, true, "144.300", true, "not qrv"));
}
@@ -143,7 +143,7 @@ class MessageBusManagementThreadAutoAnswerDecisionTest {
@Test
void buildsTheGenericReplyTrimmed() {
assertEquals(
"/CQ DL1ABC " + MARKER + " not qrv, back at 18z *a*",
"/CQ DL1ABC " + MARKER + " not qrv, back at 18z",
MessageBusManagementThread.buildAutoAnswerMessageText(
"DL1ABC", VUHF, false, "144.300", true, " not qrv, back at 18z "));
}
@@ -169,7 +169,7 @@ class MessageBusManagementThreadAutoAnswerDecisionTest {
@Test
void senderCallSignIsTrimmedButNotUpperCased() {
assertEquals(
"/CQ dl1abc " + MARKER + " QRG is: 144.300 *a*",
"/CQ dl1abc " + MARKER + " QRG is: 144.300",
MessageBusManagementThread.buildAutoAnswerMessageText(
" dl1abc ", VUHF, true, "144.300", false, null));
}
@@ -104,7 +104,7 @@ class MessageBusManagementThreadAutoAnswerTest {
ChatMessage reply = replies.get(0);
assertEquals(
"/CQ " + REMOTE_CALL + " " + ApplicationConstants.AUTOANSWER_PREFIX
+ " QRG is: " + FIRST_QRG + " *a*",
+ " QRG is: " + FIRST_QRG,
reply.getMessageText());
assertEquals(MY_CALL, reply.getSender().getCallSign());
assertEquals(REMOTE_CALL, reply.getReceiver().getCallSign());
@@ -152,7 +152,7 @@ class MessageBusManagementThreadAutoAnswerTest {
"another station and another category each get their own reply");
assertEquals(
"/CQ " + REMOTE_CALL + " " + ApplicationConstants.AUTOANSWER_PREFIX
+ " QRG is: " + SECOND_QRG + " *a*",
+ " QRG is: " + SECOND_QRG,
replies.get(2).getMessageText(),
"the second-category question is answered with the second QRG");
assertSame(secondCategory, replies.get(2).getChatCategory());
@@ -232,7 +232,7 @@ class MessageBusManagementThreadAutoAnswerTest {
"the rejected reply must not have started the cooldown");
assertEquals(
"/CQ " + REMOTE_CALL + " " + ApplicationConstants.AUTOANSWER_PREFIX
+ " QRG is: " + FIRST_QRG + " *a*",
+ " QRG is: " + FIRST_QRG,
txBus.peek().getMessageText());
}
@@ -248,7 +248,7 @@ class MessageBusManagementThreadAutoAnswerTest {
assertEquals(1, txBus.size());
assertEquals(
"/CQ " + REMOTE_CALL + " " + ApplicationConstants.AUTOANSWER_PREFIX
+ " not qrv, back at 18z *a*",
+ " not qrv, back at 18z",
txBus.peek().getMessageText(),
"the configured text is trimmed");
}
@@ -265,7 +265,7 @@ class MessageBusManagementThreadAutoAnswerTest {
assertEquals(1, txBus.size());
assertEquals(
"/CQ " + REMOTE_CALL + " " + ApplicationConstants.AUTOANSWER_PREFIX
+ " QRG is: " + FIRST_QRG + " *a*",
+ " QRG is: " + FIRST_QRG,
txBus.peek().getMessageText());
}
@@ -282,7 +282,7 @@ class MessageBusManagementThreadAutoAnswerTest {
assertEquals(1, txBus.size(),
"the blank generic reply is dropped; the QRG reply still goes out");
assertTrue(txBus.peek().getMessageText().endsWith("QRG is: " + FIRST_QRG + " *a*"));
assertTrue(txBus.peek().getMessageText().endsWith("QRG is: " + FIRST_QRG));
}
@Test
@@ -295,7 +295,7 @@ class MessageBusManagementThreadAutoAnswerTest {
assertEquals(
"/CQ " + REMOTE_CALL + " " + ApplicationConstants.AUTOANSWER_PREFIX
+ " KST4Contest v" + ApplicationConstants.APPLICATION_CURRENT_VERSION
+ " by DO5AMF *a*",
+ " by DO5AMF",
txBus.peek().getMessageText());
}
@@ -134,7 +134,7 @@ class MessageBusManagementThreadChatFrameTest {
assertEquals(
"/CQ " + REMOTE_CALL + " " + ApplicationConstants.AUTOANSWER_PREFIX
+ " KST4Contest v" + ApplicationConstants.APPLICATION_CURRENT_VERSION
+ " by DO5AMF *a*",
+ " by DO5AMF",
txBus.peek().getMessageText());
verify(controller, times(1)).publishChatMessage(any(ChatMessage.class));
}
@@ -89,32 +89,13 @@ class On4KstProtocolTest {
);
assertEquals(
"calling cq at 144.300 *a*",
"calling cq at 144.300",
controller.resolveAndValidateBeaconText(
"calling cq at MYQRG"
)
);
}
@Test
void keepsThe120CharacterPayloadAllowanceWithA124CharacterFinalBeacon() {
ChatPreferences preferences = new ChatPreferences(tempDir.resolve("preferences.xml"));
ChatController controller = new ChatController();
controller.setChatPreferences(preferences);
String payload = "x".repeat(120);
assertDoesNotThrow(() -> controller.validateBeaconTemplate(payload));
String finalMessage = controller.resolveAndValidateBeaconText(payload);
assertEquals(124, finalMessage.length());
assertEquals(payload + " *a*", finalMessage);
assertThrows(
IllegalArgumentException.class,
() -> controller.validateBeaconTemplate("x".repeat(121))
);
}
@Test
void acceptsTemporarilyUnresolvedVariableOnlyBeaconTemplate() {
ChatPreferences preferences = new ChatPreferences(tempDir.resolve("preferences.xml"));
@@ -155,8 +136,11 @@ class On4KstProtocolTest {
assertThrows(
IllegalArgumentException.class,
() -> controller.validateBeaconTemplate(
"x".repeat(121)
"x".repeat(
ChatController.MAX_BEACON_TEXT_LENGTH
+ 1
)
)
);
}
}
}
@@ -4,10 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -108,7 +105,6 @@ class ReadUDPbyUCXMessageThreadLoopbackTest {
when(preferences.isTrxSynch_ucxLogUDPListenerEnabled()).thenReturn(true);
SimpleValue<String> qrg = new SimpleValue<>("");
when(preferences.getMYQRGFirstCat()).thenReturn(qrg);
stubExternalQrgWrites(qrg);
CountDownLatch firstQrg = new CountDownLatch(1);
CountDownLatch secondQrg = new CountDownLatch(1);
qrg.addListener(value -> {
@@ -234,29 +230,6 @@ class ReadUDPbyUCXMessageThreadLoopbackTest {
assertEquals("1296.200.00", markerQrg.get());
}
/** A malformed Freq is expected external input and must be ignored without the safety net. */
@Test
void malformedRadioInfoFrequencyIsSkippedWithoutAnUnexpectedError(@TempDir Path tempDir) throws Exception {
givenQsoProcessingEnabled(tempDir.resolve("udp-backup.txt"));
sendThenAwaitMarker("<RadioInfo><Freq>not-a-number</Freq><Mode>CW</Mode></RadioInfo>");
assertEquals("1296.200.00", markerQrg.get());
assertFalse(statusMessages.stream()
.anyMatch(message -> message.getRunningInformation().startsWith("packet dropped after error")));
}
@Test
void nonPositiveRadioInfoFrequencyIsIgnoredBeforeItReachesTheController(@TempDir Path tempDir)
throws Exception {
givenQsoProcessingEnabled(tempDir.resolve("udp-backup.txt"));
sendThenAwaitMarker("<RadioInfo><Freq>0</Freq><Mode>CW</Mode></RadioInfo>");
verify(controller, never()).applyExternalQrg(any(RadioSlot.class), eq("0"), eq(0L));
assertEquals("1296.200.00", markerQrg.get());
}
/**
* Any runtime exception while processing one packet drops that packet,
* reports a non-critical status and leaves the receive loop running.
@@ -302,16 +275,6 @@ class ReadUDPbyUCXMessageThreadLoopbackTest {
when(controller.uiDispatcher()).thenReturn(new DirectUiDispatcher());
when(preferences.isTrxSynch_ucxLogUDPListenerEnabled()).thenReturn(true);
when(preferences.getMYQRGFirstCat()).thenReturn(markerQrg);
stubExternalQrgWrites(markerQrg);
}
private void stubExternalQrgWrites(SimpleValue<String> firstQrg) {
doAnswer(invocation -> {
RadioSlot slot = invocation.getArgument(0);
String value = invocation.getArgument(1);
(slot == RadioSlot.FIRST ? firstQrg : secondQrg).set(value);
return null;
}).when(controller).applyExternalQrg(any(RadioSlot.class), anyString(), anyLong());
}
/**
@@ -5,10 +5,12 @@ import kst4contest.observe.DirectUiDispatcher;
import kst4contest.observe.SimpleValue;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** A Win-Test STATUS of the second station writes SECONDQRG when SO2R is on. */
@@ -16,10 +18,18 @@ class WinTestStatusSlotTest {
/* STATUS layout as parseStatus reads it: token 1 station, 5 mode, 7 frequency in 100 Hz. */
private static final String STATUS_STN2 = "STATUS: \"STN2\" \"\" 0 12 0 0 4322000 0";
private static final String STATUS_STN1 = "STATUS: \"STN1\" \"\" 0 12 0 0 1443000 0";
private final ChatController controller = mock(ChatController.class);
private final ChatPreferences prefs = mock(ChatPreferences.class);
private final List<String> first = new ArrayList<>();
private final List<String> second = new ArrayList<>();
private static SimpleValue<String> recording(List<String> writes) {
SimpleValue<String> value = new SimpleValue<>("");
value.addListener(writes::add);
return value;
}
private ReadUDPByWintestThread thread(boolean so2r) {
when(controller.getChatPreferences()).thenReturn(prefs);
when(controller.uiDispatcher()).thenReturn(new DirectUiDispatcher());
@@ -27,6 +37,8 @@ class WinTestStatusSlotTest {
when(prefs.isTrxSynch_so2rEnabled()).thenReturn(so2r);
when(prefs.getLogsynch_wintestNetworkStationNameOfWintestClient1()).thenReturn("STN1");
when(prefs.getLogsynch_wintestNetworkStationNameOfWintestClient2()).thenReturn("STN2");
when(prefs.getMYQRGFirstCat()).thenReturn(recording(first));
when(prefs.getMYQRGSecondCat()).thenReturn(recording(second));
return new ReadUDPByWintestThread(controller, mock(ThreadStatusCallback.class));
}
@@ -34,21 +46,15 @@ class WinTestStatusSlotTest {
void withSo2rTheSecondStationWritesTheSecondQrg() {
thread(true).parseStatus(STATUS_STN2);
verify(controller).applyExternalQrg(RadioSlot.SECOND, "432.200.00", 432_200_000L);
assertEquals(1, second.size());
assertTrue(first.isEmpty());
}
@Test
void withoutSo2rTheSecondStationIsFilteredOutAsBefore() {
thread(false).parseStatus(STATUS_STN2);
org.mockito.Mockito.verify(controller, org.mockito.Mockito.never())
.applyExternalQrg(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyLong());
}
@Test
void withoutSo2rTheFirstStationUpdatesOnlyTheMainSlotWithExactHz() {
thread(false).parseStatus(STATUS_STN1);
verify(controller).applyExternalQrg(RadioSlot.FIRST, "144.300.00", 144_300_000L);
assertTrue(first.isEmpty());
assertTrue(second.isEmpty());
}
}
@@ -1,87 +0,0 @@
package kst4contest.model;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.Path;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class ChatPreferencesBeaconStateTest {
@TempDir
Path tempDir;
@Test
void beaconActivationChangesAreObservableAndIndependent() {
ChatPreferences preferences = preferences("observable.xml");
List<Boolean> mainChanges = new ArrayList<>();
List<Boolean> secondChanges = new ArrayList<>();
preferences.bcnBeaconsEnabledMainCatProperty().addListener(mainChanges::add);
preferences.bcnBeaconsEnabledSecondCatProperty().addListener(secondChanges::add);
preferences.setBcn_beaconsEnabledMainCat(true);
preferences.setBcn_beaconsEnabledMainCat(false);
preferences.setBcn_beaconsEnabledSecondCat(true);
assertFalse(preferences.isBcn_beaconsEnabledMainCat());
assertTrue(preferences.isBcn_beaconsEnabledSecondCat());
assertEquals(List.of(true, false), mainChanges);
assertEquals(List.of(true), secondChanges);
}
@Test
void activationIsSessionOnlyAndEveryFullWriteStoresFalse() throws Exception {
ChatPreferences preferences = preferences("persistence.xml");
preferences.setBcn_beaconsEnabledMainCat(true);
preferences.setBcn_beaconsEnabledSecondCat(true);
assertTrue(preferences.writePreferencesToXmlFile());
String xml = Files.readString(tempDir.resolve("persistence.xml"));
assertTrue(xml.contains("<beaconCQEnabled>false</beaconCQEnabled>"));
assertTrue(xml.contains("<bcn_beaconsEnabledMainCat>false</bcn_beaconsEnabledMainCat>"));
assertTrue(xml.contains("<beaconCQEnabledSecondCat>false</beaconCQEnabledSecondCat>"));
assertTrue(xml.contains("<bcn_beaconsEnabledSecondCat>false</bcn_beaconsEnabledSecondCat>"));
preferences.setBcn_beaconsEnabledMainCat(true);
preferences.setBcn_beaconsEnabledSecondCat(true);
assertTrue(preferences.writeLayoutPreferencesToXmlFile());
ChatPreferences restored = preferences("persistence.xml");
restored.readPreferencesFromXmlFile();
assertFalse(restored.isBcn_beaconsEnabledMainCat());
assertFalse(restored.isBcn_beaconsEnabledSecondCat());
}
@Test
void storedActivationIsIgnoredAndIntervalsBelowFiveAreNormalized() throws Exception {
Path file = tempDir.resolve("legacy.xml");
Files.writeString(file, """
<?xml version="1.0" encoding="UTF-8"?>
<praktiKST><beaconCQ>
<beaconCQEnabled>true</beaconCQEnabled>
<beaconCQEnabledSecondCat>true</beaconCQEnabledSecondCat>
<beaconCQIntervalMinutes>1</beaconCQIntervalMinutes>
<beaconCQIntervalMinutesSecondCat>9</beaconCQIntervalMinutesSecondCat>
</beaconCQ></praktiKST>
""");
ChatPreferences restored = new ChatPreferences(file);
assertTrue(restored.readPreferencesFromXmlFile());
assertFalse(restored.isBcn_beaconsEnabledMainCat());
assertFalse(restored.isBcn_beaconsEnabledSecondCat());
assertEquals(5, restored.getBcn_beaconIntervalInMinutesMainCat());
assertEquals(9, restored.getBcn_beaconIntervalInMinutesSecondCat());
}
private ChatPreferences preferences(String fileName) {
return new ChatPreferences(tempDir.resolve(fileName));
}
}
@@ -64,10 +64,6 @@ class ChatPreferencesRoundTripTest {
Map.entry("setMessageHandling_autoAnswerEnabledSecondCat",
"Same deliberate mirroring as the second-category auto-answer text; the "
+ "main-category flag wins after every read"),
Map.entry("setBcn_beaconsEnabledMainCat",
"Session-only safety switch; every XML write stores false and every read starts false"),
Map.entry("setBcn_beaconsEnabledSecondCat",
"Session-only safety switch; every XML write stores false and every read starts false"),
Map.entry("setBcn_contestScoreSum",
"DEAD FIELD: declared with accessors only, no caller in core or app-desktop, "
+ "never written nor read")
@@ -1,30 +0,0 @@
package kst4contest.view.map;
import org.junit.jupiter.api.Test;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class MaidenheadGridUtilsTest {
@Test
void a_view_crossing_the_anti_meridian_contains_cells_from_both_world_edges() {
var cells = MaidenheadGridUtils.buildVisibleCells(
-2.0,
175.0,
2.0,
185.0,
MaidenheadGridUtils.GridPrecision.FIELD_2
);
Set<String> labels = cells.stream()
.map(MaidenheadGridUtils.GridCell::locatorLabel)
.collect(Collectors.toSet());
assertTrue(labels.stream().anyMatch(label -> label.startsWith("R")), labels.toString());
assertTrue(labels.stream().anyMatch(label -> label.startsWith("A")), labels.toString());
assertEquals(labels.size(), cells.size(), "a wrapped cell was returned twice");
}
}
@@ -1,70 +0,0 @@
package kst4contest.view.map;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class MapViewportNavigationTest {
private static final double PADDING_PX = 48.0;
@Test
void a_path_that_fits_keeps_the_existing_zoom() {
MapViewport before = new MapViewport(10.0, 51.0, 8.5, 1000.0, 700.0);
MapViewport fitted = MapViewportNavigation.fitPath(
before, 51.0, 10.0, 51.2, 10.4, PADDING_PX);
assertEquals(8.5, fitted.zoom(), 1e-9);
assertInsidePadding(fitted, 51.0, 10.0);
assertInsidePadding(fitted, 51.2, 10.4);
}
@Test
void a_long_path_zooms_out_until_both_endpoints_fit() {
MapViewport before = new MapViewport(10.0, 51.0, 12.0, 900.0, 600.0);
MapViewport fitted = MapViewportNavigation.fitPath(
before, 51.0, 10.0, 44.0, -3.0, PADDING_PX);
assertTrue(fitted.zoom() < before.zoom());
assertInsidePadding(fitted, 51.0, 10.0);
assertInsidePadding(fitted, 44.0, -3.0);
}
@Test
void fitting_across_the_anti_meridian_uses_the_short_path() {
MapViewport before = new MapViewport(180.0, 0.0, 7.0, 900.0, 600.0);
MapViewport fitted = MapViewportNavigation.fitPath(
before, 0.0, 179.0, 0.0, -179.0, PADDING_PX);
assertEquals(7.0, fitted.zoom(), 1e-9, "two degrees should not look like a world-spanning path");
assertInsidePadding(fitted, 0.0, 179.0);
assertInsidePadding(fitted, 0.0, -179.0);
}
@Test
void bearing_navigation_preserves_zoom_and_moves_towards_the_sector() {
MapViewport before = new MapViewport(10.0, 51.0, 8.25, 1000.0, 600.0);
MapViewport northEast = MapViewportNavigation.centreOnBearing(
before, 51.0, 10.0, 45.0, 0.25);
assertEquals(8.25, northEast.zoom(), 1e-9);
assertTrue(northEast.centerLon() > 10.0);
assertTrue(northEast.centerLat() > 51.0);
assertTrue(northEast.screenXWrapped(10.0) < northEast.widthPx() / 2.0);
assertTrue(northEast.screenY(51.0) > northEast.heightPx() / 2.0);
}
private static void assertInsidePadding(MapViewport viewport, double latitude, double longitude) {
double x = viewport.screenXWrapped(longitude);
double y = viewport.screenY(latitude);
assertTrue(x >= PADDING_PX - 1e-6 && x <= viewport.widthPx() - PADDING_PX + 1e-6,
"longitude outside padded viewport at x=" + x);
assertTrue(y >= PADDING_PX - 1e-6 && y <= viewport.heightPx() - PADDING_PX + 1e-6,
"latitude outside padded viewport at y=" + y);
}
}
@@ -203,12 +203,4 @@ class MapViewportTest {
assertEquals(179.0, new MapViewport(-181.0, 0.0, 6.0, 800.0, 600.0).centerLon(), TOLERANCE_DEG);
assertEquals(0.0, new MapViewport(360.0, 0.0, 6.0, 800.0, 600.0).centerLon(), TOLERANCE_DEG);
}
@Test
void wrapped_screen_coordinates_use_the_nearest_world_copy() {
MapViewport viewport = new MapViewport(179.0, 0.0, 6.0, 800.0, 600.0);
assertTrue(Math.abs(viewport.screenXWrapped(-179.0) - viewport.screenXWrapped(179.0)) < 100.0);
assertTrue(Math.abs(viewport.screenX(-179.0) - viewport.screenX(179.0)) > 10_000.0);
}
}
@@ -174,21 +174,6 @@ class StationMapClustererTest {
assertEquals(stations.size(), clustered + result.individual().size());
}
@Test
void nearby_stations_across_the_anti_meridian_share_a_cluster() {
MapViewport viewport = new MapViewport(180.0, 0.0, 5.0, 1000.0, 800.0);
List<MapCallsignRawSnapshot> stations = List.of(
station("ZL1AAA", 0.0, 179.9),
station("ZL1BBB", 0.0, -179.9),
station("ZL1CCC", 0.01, 179.8)
);
StationMapClusterer.Result result = StationMapClusterer.cluster(stations, viewport, true);
assertEquals(1, result.clusters().size());
assertTrue(Math.abs(Math.abs(result.clusters().get(0).getCenterLon()) - 180.0) < 0.2);
}
/**
* Selecting a station moves the map to it. It must not throw the operator's zoom
* away doing so.
+6 -23
View File
@@ -186,25 +186,23 @@ CR/LF framing, XML framing, ports/transports, callsign normalization and frequen
- Contest operating speed and low-friction interaction are primary goals.
- Incidental code changes must not unexpectedly change selection, focus, sorting, tab state, map zoom or prefilled text.
- Map reset clears the selected target and recentres on the local station without changing zoom.
- Map reset clears the selected target without changing zoom unless explicitly redesigned.
- **Grouping** changes only spatial clustering of the existing Compose map markers. It must not reload tiles or station data, request a new controller snapshot, or change zoom, viewport or selection.
- Base-callsign aggregation into one geographical marker happens before screen-based clustering. Disabling clustering displays each resulting positionable map station individually but never splits active variants of the same normalised base callsign into separate geographical markers.
- A hidden Station Map is not continuously refreshed. Relevant background changes mark it dirty; the next `showWindow()` performs one current full refresh before normal visible-window updates resume.
- Maidenhead grid construction depends only on viewport bounds, zoom and Compose-canvas size. Unwrapped viewport bounds may cross the international date line and must be split into valid world intervals without duplicating grid cells. Ordinary station-data refreshes must not rebuild the grid when those inputs are unchanged.
- Maidenhead grid construction depends only on viewport bounds, zoom and WebView size. Ordinary station-data refreshes must not rebuild or serialise the grid when those inputs are unchanged.
- Panning updates viewport and grid state through `notifyViewport()` without rebuilding station markers or screen-based clusters. Zoom changes, station-data changes and clustering toggles still rebuild the marker layer.
- Debug file logging reports Station Map refreshes only when total FX-thread refresh time reaches 100 ms. The diagnostic separates snapshot and render time and includes visible-member and station counts.
- Station selection preserves the established `/cq callsign` prefill behaviour.
- `StationSelectionState` is the canonical selection shared by the station table and Further Info panel. Its identity is the complete callsign plus chat category. Explicit actions carry a `StationSelectionSource` and increment separate scroll and explicit-selection revisions even when the same station is selected again; roster reconciliation replaces the selected instance without moving the table or map.
- `StationSelectionState` is the canonical selection shared by the station table and Further Info panel. Its identity is the complete callsign plus chat category. Explicit actions carry a `StationSelectionSource` and increment a separate scroll-request revision even when the same station is selected again; roster reconciliation replaces the selected instance without moving the table.
- Recent-join state is transient domain state keyed by complete callsign plus chat category. Only live `UA5`/`UA2` frames can create an entry; the `UA0`/`UE` initial or reconnect snapshot and `UM3` profile updates never do. Duplicate live updates do not renew the timestamp, a leave removes the entry, and a genuine rejoin begins a new ten-minute interval. The local login callsign is excluded. The core `ObservableRoster` is mirrored through `UiDispatcher`; New-joined actions reuse the canonical station selection and scroll request.
- The station table starts with a case-insensitive ascending callsign sort. A user-selected sort remains authoritative across roster and filter updates. An externally selected filtered station is pinned into the table. `filteredRows` remains the exact filter result used for ordinary map markers; the map renders the current filtered-out selection separately without counting or clustering it.
- The station table starts with a case-insensitive ascending callsign sort. A user-selected sort remains authoritative across roster and filter updates. An externally selected filtered station is pinned into the table only; `filteredRows` remains the exact filter result used by the map.
- PM, Public, QSO-of-the-other, priority, timeline and individual map-marker actions route through the application-level station selector. Directed messages target the sender, except that an outgoing local PM targets its receiver. Public and QSO-of-the-other rows target their sender in the message category. Direct clicks and context clicks inside the station table select without issuing an automatic scroll request; selections originating in the map, messages, priority, New joined or other station controls issue one even when the identity was already selected.
- The selected-station message radio mode is independent of station identity and always retains the complete callsign plus chat category. `PM_TO_ME` is the private conversation with the local station plus public traffic from the selected station carrying the structured leading `(LOCALCALL)` address, `PM_TO_OTHER` is private traffic sent by the selected station to other participants, `PUBLIC` is traffic sent by it to `ALL`, and `NOTHING` applies no additional type/receiver restriction. An arbitrary callsign mention in prose is not a structured public address.
- ON4KST chat parsing records `messageDirectedToCommunity` from the receiver field and `messageDirectedToMe` from either a genuine private receiver or the exact leading public address. The selected-station Compose message mirror is initialized with the main window state, before the first selection callback, and roster changes recompute and push the filtered rows automatically.
- The map's **Reset filters** action uses the same `StationFilterState.reset()` path as the main filter bar and does not change sort, selection, zoom, viewport or the display-only Grid-color toggle. Individual raw-callsign markers retain an already selected category variant; otherwise they use the configured Main category. Spatial clusters zoom and never choose an arbitrary member.
- The user list and map share one station context-menu implementation. A secondary click selects a unique target through `StationSelectionState`; base-call markers or screen clusters containing several full-callsign/category identities first require an explicit target choice. Message snippets reuse the existing send-field action, and the context sked editor owns an isolated draft with the target fixed at opening time.
- Map markers draw only the display callsign; bands, `B+`, locator and QRG details remain in tooltips. When Grid color is enabled, the canvas draws a black outline and a 30 percent black fill overlay for four-character squares from `WorkedGrossFieldCache.snapshotWorkedGrossFieldsAny()`, independently of visible station markers. The cache is rebuilt from SQLite at startup and is the same any-band state used by **Only new grids**.
- Explicit station selections publish a map-navigation request separate from ordinary selected-state reconciliation. The map fits the complete home-to-target path with padding, preserves an already sufficient zoom and only zooms out when required. Explicit QTF field and compass-button actions preserve zoom and shift the local station 25 percent of the shorter canvas dimension opposite the selected bearing. Background roster changes, filter restoration, reset, rotor feedback and asynchronous path analysis never publish these requests; the latest explicit request wins. A selection without valid coordinates leaves the camera unchanged. Reset view clears selection and recentres on home without changing zoom.
- Active QTF and QRB predicates are visualised by a distinct semi-transparent overlay using the same filter state and semantics: minimum QRB is exclusive, maximum QRB inclusive, and the QTF sector uses the configured complete beamwidth. An unbounded distance range is clipped by the visible canvas rather than a fabricated radio range. An empty minimum/maximum combination has no fill but retains both boundary lines. The actual antenna beam remains a separate overlay driven by `actualQTF`, `stn_antennaBeamWidthDeg` and `stn_maxQRBDefault`; applying Station settings refreshes its Compose-observable geometry immediately without issuing rotor commands. The map header shows a localized red/blue legend only for overlays that are currently drawable, and the legend reuses the exact canvas line colours rather than defining a parallel colour scheme.
- The AP timeline renders the producer's four candidate lanes in order (two in-beam, two global priority) plus a separate sked lane. Its relative 0–30 minute axis normally uses five-minute ticks and increases the interval when labels would overlap. The vertical message splitter applies pane-specific minimums for the timeline, shortcut row and send row, so older stored divider positions cannot clip these fixed-height controls; stored positions remain the unconstrained baseline.
- Sending without an explicitly selected send category preserves the established Main-category fallback unless explicitly changed.
- The lower selected-station panel contains a vertical two-pane `SplitterPane`: the upper pane owns the independently scrollable message table, while the lower pane scrolls NOT-QRV and Sked above a pinned lookup group. The lower pane reserves 160 dp before stored divider positions are applied, so normal small-window layouts retain direct access to lookup actions; impossible smaller layouts keep the action groups scrollable. `GUIselectedCallSignSplitPane_dividerposition` persists this divider through the existing profile-scoped layout autosave. Station or message updates never reset it. Empty `DataTableView` instances retain their header and border and show an explicit empty-state label. Header metadata and message filters use width-aware flow layouts; the NOT-QRV and sked groups switch between a row and a column from the panel's actual Compose constraint, without duplicating their domain state.
@@ -215,12 +213,8 @@ CR/LF framing, XML framing, ports/transports, callsign normalization and frequen
## Autoanswer / Beacon
- Automated-message loops must be prevented.
- Every user-visible automatic chat message generated by KST4Contest ends with the exact suffix ` *a*`: generic and QRG-specific automatic replies, `//VER` replies and both category beacons. Automatic replies retain their `[KST4C Automsg]` prefix as the loop guard. The suffix is appended unconditionally after message construction or beacon variable resolution; manual messages and internal login, keepalive and control frames are unchanged. Beacon content remains limited to 120 characters before the suffix, making 124 characters the final transmitted maximum.
- Cooldown/minimum-interval rules must be preserved. The shared beacon interval has a hard minimum of five minutes; older stored values below five are normalized while loading.
- Cooldown/minimum-interval rules must be preserved.
- A reply rejected before a complete valid TX item is queued must not consume cooldown.
- Both category beacons share one timer, while their message templates remain profile-scoped and independent. `BeaconSessionState` is the authoritative owner of activation, per-category QRG references, deactivation reasons and send failures. Activations are never restored from XML: both start off after program startup and every profile switch, remain unchanged during an ON4KST reconnect in the same application session, and are projected into the legacy observable preference booleans for Settings/UI compatibility. Full preference writes emit both legacy/current enable tags as `false`.
- Enabling validates QRG placeholders across either template: `MYQRG` and `MYQRGSHORT` require a valid primary QRG; `SECONDQRG` requires a valid secondary QRG. A template without a QRG placeholder may be enabled without a current QRG, and the first later valid own-category QRG establishes its reference. A valid manual QRG change always rebases the corresponding active beacon. A UCXLog or Win-Test update more than 5,000 Hz away from the reference disables only that category; exactly 5,000 Hz remains allowed. Without SO2R, logger updates reach the primary category only; with SO2R each radio/category is handled independently. A missing/invalid required QRG disables an active beacon, while an invalid own QRG without a QRG placeholder only clears its reference.
- `MyBeacon` owns one structured aggregate thread-status snapshot for both categories (`off`, `1/2`, `on`, or `FAILED`). Its action disables all currently usable beacons if any is enabled, otherwise it attempts to enable each usable beacon independently, so one invalid category can remain off. The tooltip derives the state or last general deactivation reason for each category from the same snapshot. Active states use the dedicated green treatment with a 200 ms orange activity flash; `off` keeps a neutral surface with red text; `FAILED` uses a persistent red surface with white text and suppresses the activity flash. Other thread-status chips keep their existing styling.
- Current implementation/tests define the exact message markers and timer details.
## Build / Verification
@@ -419,21 +413,10 @@ Before implementing planned items, re-check current decisions and obtain a fresh
- Historical project context is useful but may be stale; current code/tests win.
- External service/API behaviour must be verified against current upstream documentation when uncertain.
- Screenshots in manuals/website may need targeted replacement after visible UI changes; never fabricate them.
- `client_settings_window_beacon.png` was recaptured from the current Compose UI in a live application session on 2026-11-13. It shows both beacons disabled after a profile switch and the five-minute minimum interval.
- `station_map_path_analysis.png` and `station_map_reset.png` predate the current header controls, callsign-only markers, shared station context menu and Worked-square overlay. The former remains useful only where the visible analysis panel itself is the subject. `station_map_spatial_filters.png` is the current general map screenshot shared by the DE/EN interface manuals and the website through `/manual/assets/`.
- `station_map_path_analysis.png` and `station_map_reset.png` predate the current header controls, callsign-only markers, shared station context menu and Worked-square overlay. Replace them with current screenshots when suitable source images are available; the website reuses `station_map_path_analysis.png` through `/manual/assets/`.
## Recent Significant Changes
### 2026-11-13 – Automatic chat messages marked with a suffix
- Generic and QRG-specific automatic replies, `//VER` replies and both beacons now carry the exact ` *a*` suffix. Existing auto-reply loop protection remains based on `[KST4C Automsg]`; manual chat and ON4KST control traffic are unchanged.
- Beacon templates and resolved payloads retain the 120-character limit. The fixed suffix is added afterwards, so a transmitted beacon may contain up to 124 characters.
### 2026-11-12 – Beacon activation and QRG safety made session-scoped
- Beacon activation is now explicit per application session, while ordinary ON4KST reconnects preserve it. Per-category references distinguish deliberate manual QRG changes from UCXLog/Win-Test moves and disable only the affected beacon after a change greater than 5 kHz.
- The structured aggregate beacon status keeps per-category deactivation reasons and drives the dedicated green/orange/red `MyBeacon` chip without changing other thread-status chips.
### 2026-10-17 – Repository moved to the HamRadioOnline organisation
- The GitHub repository moved from `praktimarc/kst4contest` to `HamRadioOnline/kst4contest`. GitHub redirects the old repository, Pages, API and git URLs, so published links and release assets from before the move keep working.
@@ -1,68 +0,0 @@
# Public Message Tab Filter Fix Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Make the main-window **Public messages** tab show only ON4KST messages whose protocol receiver is public (`0`, represented as `ALL`).
**Architecture:** Keep the global message roster as the complete event store and reuse `ChatController.toAllMessages()` as the single existing public-message view. A small package-visible refresh method updates all three Compose message tables so initial population and live updates use the same filtered sources.
**Tech Stack:** Java 21, Kotlin 2.2, Compose Multiplatform, JUnit 5, Mockito, Gradle
**Spec:** `github_docs/en-User-Interface.md` and `github_docs/de-Benutzeroberflaeche.md` document the intended global-tab semantics.
## Global Constraints
- Preserve ON4KST parsing, the complete global message history, message order and chat-category identity.
- Preserve the selected-station message modes and the existing `pm to me`/`pm to other` semantics.
- Do not stage, commit, push or publish without separate authorization.
- Source comments remain English.
## Review Focus
- A genuine public frame remains in the public tab after initial population and a later refresh.
- A PM to the local callsign never enters the public tab.
- A directed message between other stations never enters the public tab.
- Directed and QSO-of-the-other tables continue to receive their existing filtered views.
- Repeated table refreshes replace rows without changing their newest-first order.
---
### Task 1: Route the Compose public table through the existing filtered view
**Files:**
- Modify: `app-desktop/src/main/java/kst4contest/view/Kst4ContestApplication.java`
- Create: `app-desktop/src/test/kotlin/kst4contest/view/ComposeMessageTableRefreshTest.kt`
**Interfaces:**
- Consumes: `ChatController.toMeMessages()`, `ChatController.toAllMessages()`, and `ChatController.toOtherMessages()`
- Produces: package-visible `Kst4ContestApplication.refreshComposeMessageTables(...)`
- [x] **Step 1: Write the failing regression test**
Create a mixed-message test whose mocked controller exposes separate directed, public and other-station views. Assert that the public table receives only `toAllMessages()`, then change the mocked public result, refresh again and assert the replacement remains filtered.
- [x] **Step 2: Run the focused test and verify it fails**
Run: `./gradlew.bat :app-desktop:test --tests kst4contest.view.ComposeMessageTableRefreshTest --console=plain`
Expected: compilation failure because `refreshComposeMessageTables(...)` does not yet exist.
- [x] **Step 3: Implement the shared refresh method**
Add package-visible static `refreshComposeMessageTables(ChatController, DataTableState<ChatMessage>, DataTableState<ChatMessage>, DataTableState<ChatMessage>)`. It must populate the tables from `toMeMessages()`, `toAllMessages()` and `toOtherMessages()` respectively.
- [x] **Step 4: Use the method for both update paths**
Call the shared method from the global-message listener on the UI dispatcher and from the initial Compose table population. Remove both raw writes to the public table.
- [x] **Step 5: Run focused and related tests**
Run the new test plus `MessageTabsScreenTest`, `MessageBusManagementThreadChatFrameTest`, `SelectedStationMessageFlowTest`, and `SelectedStationMessagePredicateTest`.
- [x] **Step 6: Run full verification**
Run `./gradlew.bat build --console=plain`, inspect test-result XML and changed-file static-analysis reports, then run `git diff --check` and `git status --short --branch`.
- [x] **Step 7: Assess documentation impact**
Confirm the German and English manuals already state that the global public tab contains public messages only. Update no documentation unless implementation reveals a conflicting invariant.
@@ -1,108 +0,0 @@
# Live Beacon Control Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Make both beacon enable switches effective immediately at runtime and make the aggregate beacon status chip an accurate shared toggle.
**Architecture:** Keep `ChatPreferences` as the profile-scoped source of truth, but expose the two activation flags as thread-safe observable values. Route settings and chip actions through `ChatController`, publish one aggregate `MyBeacon` status, and give only that thread-status chip an optional click action.
**Tech Stack:** Java 21, Kotlin 2.2, Compose Multiplatform, JUnit 5, Mockito, Gradle wrapper
**Spec:** `docs/superpowers/specs/2026-11-04-live-beacon-control-design.md`
## Global Constraints
- Work directly on `main`, as explicitly authorized.
- Do not stage, commit, push, merge, tag, release or deploy.
- Keep beacon templates, interval handling, TX framing and second-chat eligibility unchanged.
- Write source-code and configuration comments in English.
- Use focused tests first and finish with `./gradlew.bat build --console=plain`.
## Review Focus
- A disabled second chat must leave its dormant second-beacon flag unchanged when the chip is clicked.
- An external chip toggle must update an already open Beacon settings tab without reopening it.
- A runtime toggle must not restart the timer or enqueue an immediate message.
- An invalid beacon template must still be reported as a critical status rather than hidden by the aggregate state.
- Profile reload must replace the observable values without carrying the previous profile's runtime flags across.
---
### Task 1: Observable profile-scoped beacon activation
**Files:**
- Modify: `core/src/main/java/kst4contest/model/ChatPreferences.java`
- Test: `core/src/test/java/kst4contest/model/ChatPreferencesBeaconStateTest.java`
**Interfaces:**
- Produces: existing boolean getters/setters plus observable main/second beacon value accessors
- Consumes: existing `MutableValue` / `SimpleValue` infrastructure
- [x] Write tests that changes are observable, values remain independent, XML reload restores both values, and an unsaved in-memory change does not survive a fresh load.
- [x] Run `./gradlew.bat :core:test --tests kst4contest.model.ChatPreferencesBeaconStateTest --console=plain` and verify the new observable-accessor tests fail because the API is absent.
- [x] Back the two flags with `SimpleValue<Boolean>` while preserving the existing getters, setters and XML element names.
- [x] Re-run the focused test and the existing ChatPreferences tests.
### Task 2: Immediate settings effect and aggregate controller semantics
**Files:**
- Modify: `core/src/main/java/kst4contest/controller/ChatController.java`
- Modify: `core/src/main/java/kst4contest/controller/BeaconTask.java`
- Create: `core/src/main/java/kst4contest/controller/BeaconStatus.java`
- Test: `core/src/test/java/kst4contest/controller/BeaconControlTest.java`
- Test: `core/src/test/java/kst4contest/controller/BeaconTaskTest.java`
- Modify: `app-desktop/src/main/kotlin/kst4contest/view/compose/tabs/BeaconTabState.kt`
- Modify: `app-desktop/src/main/kotlin/kst4contest/view/compose/tabs/BeaconTab.kt`
- Modify: `app-desktop/src/main/kotlin/kst4contest/view/compose/ObservedValue.kt`
- Modify: `app-desktop/src/main/kotlin/kst4contest/view/compose/SettingsTabs.kt`
- Modify: `app-desktop/src/test/kotlin/kst4contest/view/compose/tabs/BeaconTabStateTest.kt`
- Modify: `app-desktop/src/test/kotlin/kst4contest/view/compose/tabs/SettingsApplyScreenTest.kt`
- Modify: `app-desktop/src/test/kotlin/kst4contest/view/compose/tabs/DraftedSettingsTableTest.kt`
**Interfaces:**
- Consumes: observable preference values from Task 1
- Produces: controller setters, usable-beacon toggle, aggregate status publication, Compose observation bridge
- [x] Write failing controller tests for `off`, `1/2`, `on`, main-only toggling when second chat is disabled, and both-category toggling when it is enabled.
- [x] Write failing BeaconTask tests proving a flag changed between two runs changes queued output without restarting a timer, and that the final status is aggregate.
- [x] Change Beacon settings tests so activation is immediate while templates and interval still wait for Apply; verify RED against the current draft-backed flags.
- [x] Implement the aggregate status helper and controller actions without changing the outbound-message path.
- [x] Make only the enable flags bypass `SettingsDraft`, observe their preference values in Compose, and wire their setters through the controller.
- [x] Run the core and app-desktop focused tests and verify GREEN.
### Task 3: Clickable beacon status chip
**Files:**
- Modify: `app-desktop/src/main/kotlin/kst4contest/view/compose/StatusIndicatorState.kt`
- Modify: `app-desktop/src/main/kotlin/kst4contest/view/compose/StatusBar.kt`
- Modify: `app-desktop/src/main/java/kst4contest/view/Kst4ContestApplication.java`
- Modify: `app-desktop/src/test/kotlin/kst4contest/view/compose/StatusIndicatorStateTest.kt`
- Create or modify: focused Compose status-bar rendering test under `app-desktop/src/test/kotlin/kst4contest/view/compose/`
**Interfaces:**
- Consumes: controller usable-beacon toggle from Task 2
- Produces: optional per-source chip action registered only for `MyBeacon`
- [x] Write failing state tests for actions registered before and after the first status report and for non-action thread chips.
- [x] Write a failing Compose test proving the beacon chip invokes its action while an ordinary status chip remains non-clickable.
- [x] Add optional actions to thread-status buttons and apply button semantics only when an action exists.
- [x] Register the controller toggle for `MyBeacon` during main-window state construction.
- [x] Run the focused status tests and the affected main-window tests.
### Task 4: Documentation and verification
**Files:**
- Modify: relevant beacon sections in `github_docs/de-Konfiguration.md`
- Modify: corresponding sections in `github_docs/en-Configuration.md`
- Modify: `docs/PROJECT_CONTEXT.md`
- Review: relevant screenshots and changelog impact only
**Interfaces:**
- Consumes: completed runtime and UI behavior from Tasks 1-3
- Produces: aligned user documentation and durable state/persistence invariant
- [x] Update both manuals with immediate runtime effect, explicit-save persistence, aggregate chip behavior and second-chat handling.
- [x] Record the observable canonical state, timer-read rule and persistence boundary in `docs/PROJECT_CONTEXT.md`.
- [x] Run all focused tests, then `./gradlew.bat build --console=plain` and read test-result XML summaries.
- [x] Run `git diff --check`, inspect PMD/SpotBugs XML for findings in changed production files, and review the final diff for unrelated changes.
- [x] Leave all changes unstaged and uncommitted and report remaining manual UI checks.
@@ -1,110 +0,0 @@
# Map Overlay Legend and Screenshot Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Add a responsive, localized map-overlay legend and document the spatial QRB overlay with the supplied screenshot.
**Architecture:** A focused Compose legend consumes the same red antenna and theme-aware blue filter colours as the canvas. `StationMapWindow` derives visibility from the effective antenna and spatial-filter state and places the legend in the existing header `FlowRow`. Documentation receives a new immutable screenshot asset without repurposing the path-analysis image.
**Tech Stack:** Kotlin, Compose Multiplatform, generated properties-based i18n, JUnit 5 Compose UI tests, Markdown, Eleventy
**Spec:** `docs/superpowers/specs/2026-11-04-map-overlay-legend-and-screenshot-design.md`
## Global Constraints
- Preserve map filtering, station selection, antenna heading, rotor control and overlay geometry.
- Reuse existing design tokens and exact overlay colours; add no dependency.
- Keep German and English strings and documentation semantically aligned.
- Keep all changes ungestaged and uncommitted.
## Review Focus
- A map with no drawable overlay must not reserve an empty legend area; Task 1 tests both items absent.
- A QRB-only filter must show the blue item without implying QTF is active; Task 1 tests the generic **Active filters** wording.
- Invalid spatial values must not show the blue item; Task 1 uses `hasRenderableValues` as the gate.
- Narrow windows must wrap rather than clip controls; Task 1 retains the existing `FlowRow` and adds a narrow rendering assertion.
- The screenshot must not replace an image whose caption promises visible path-analysis panels; Task 2 checks all asset references.
---
### Task 1: Localized responsive overlay legend
**Files:**
- Create: `app-desktop/src/main/kotlin/kst4contest/view/compose/map/MapOverlayLegend.kt`
- Modify: `app-desktop/src/main/kotlin/kst4contest/view/compose/map/ComposeStationMap.kt`
- Modify: `app-desktop/src/main/kotlin/kst4contest/view/compose/map/SpatialFilterOverlay.kt`
- Modify: `app-desktop/src/main/kotlin/kst4contest/view/compose/map/StationMapWindow.kt`
- Modify: `app-desktop/src/main/i18n/strings_en.properties`
- Modify: `app-desktop/src/main/i18n/strings_de.properties`
- Test: `app-desktop/src/test/kotlin/kst4contest/view/compose/map/StationMapWindowScreenTest.kt`
- Test: existing i18n-generator and translation tests
**Interfaces:**
- Consumes: antenna-sector visibility, `SpatialFilterOverlayState.isActive`, `SpatialFilterOverlayState.hasRenderableValues`, current theme.
- Produces: `MapOverlayLegend(showAntenna: Boolean, showSpatialFilters: Boolean, darkMode: Boolean)` and shared overlay-colour accessors.
- [ ] **Step 1: Add failing Compose tests**
Assert that the red item appears for a drawable antenna sector, the blue item appears only for an active valid spatial filter, both disappear with neither overlay, and the header remains laid out at a narrow test width.
- [ ] **Step 2: Run the focused screen test and confirm the missing legend fails**
Run: `./gradlew.bat :app-desktop:test --tests kst4contest.view.compose.map.StationMapWindowScreenTest --console=plain`
- [ ] **Step 3: Add localized labels and tooltip text**
Add English `Antenna`, `Active filters` and the two-colour explanation, with equivalent German strings `Antenne`, `Aktive Filter` and its explanation.
- [ ] **Step 4: Implement the legend with shared colours**
Expose the existing antenna colour and theme-aware spatial-filter line colour within the map package. Implement compact colour swatches and labels in `MapOverlayLegend.kt`, and add the component to the existing header `FlowRow` with dynamic visibility.
- [ ] **Step 5: Run focused Compose and i18n tests**
Expected: all selected tests pass in both languages; existing map interactions remain unchanged.
### Task 2: Replace the outdated general map screenshot
**Files:**
- Create: `github_docs/station_map_spatial_filters.png`
- Modify: `github_docs/de-Benutzeroberflaeche.md`
- Modify: `github_docs/en-User-Interface.md`
- Modify: `website/src/features/station-map.md`
- Modify when the durable UI invariant changes: `docs/PROJECT_CONTEXT.md`
**Interfaces:**
- Consumes: supplied 1257×1016 PNG showing `QRB > 500 km` and `QRB ≤ 666 km`.
- Produces: one shared manual/website asset copied by Eleventy to `/manual/assets/`.
- [ ] **Step 1: Copy the supplied PNG without resampling**
Verify its dimensions and file hash after copying.
- [ ] **Step 2: Update targeted DE/EN manual references**
Use captions that describe the selected path, red antenna sector and blue QRB ring. Remove only the obsolete screenshot note attached to the replaced general map image.
- [ ] **Step 3: Update the Station Map website feature page**
Reference `/manual/assets/station_map_spatial_filters.png` and retain the older path-analysis image for manual sections where the analysis panels are explicitly described.
- [ ] **Step 4: Verify asset references and website output**
Run: `npm.cmd test` and `npm.cmd run build` in `website`; verify the generated image path exists.
### Task 3: Final verification
**Files:**
- Review all files from Tasks 1 and 2.
**Interfaces:**
- Consumes: completed legend, translations and screenshot references.
- Produces: verified uncommitted working tree.
- [ ] **Step 1: Run focused map and translation tests**
- [ ] **Step 2: Run `./gradlew.bat build --console=plain` and inspect test XML plus PMD/SpotBugs reports**
- [ ] **Step 3: Run `git diff --check` and inspect `git status --short --branch`**
- [ ] **Step 4: Report native visual checks separately from automated rendering evidence**
@@ -1,207 +0,0 @@
# Beacon Session Safety Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Make beacon activation session-only, enforce a five-minute minimum, disable the correct category after an external QRG move beyond 5 kHz, and render a reason-aware traffic-colour `MyBeacon` chip.
**Architecture:** A controller-owned `BeaconSessionState` coordinates the existing observable runtime flags, category references, inactive reasons and send failures. Manual QRG commits and UCXLog/Win-Test reports enter through distinct controller methods; a structured model snapshot crosses the existing thread-status boundary and `app-desktop` localises and styles it.
**Tech Stack:** Java 21, Kotlin 2.2, Compose Multiplatform 1.8.x, JUnit 5, Mockito, Gradle wrapper
**Spec:** `docs/superpowers/specs/2026-11-11-beacon-session-safety-design.md`
## Global Constraints
- Work directly on `main`, as explicitly authorised.
- Do not stage, commit, push, merge, tag, release or deploy; commit steps are deliberately omitted because Marc authorised none of them.
- Keep source comments and Javadoc in English; user-facing DE/EN text follows the project writing style.
- Use exactly 5 minutes and 5,000 Hz; exactly 5,000 Hz must not disable a beacon.
- Do not add a production dependency or change ON4KST/UCXLog/Win-Test framing.
- Keep the shared timer, initial ten-second check, outbound queue and second-chat eligibility unchanged.
- Do not execute UI callbacks while holding an internal beacon-state lock.
- Preserve unrelated local changes and inspect the diff before and after every task.
## Review Focus
- A secondary beacon using `MYQRG` must be refused or disabled when the primary QRG is invalid, even though its own reference remains the secondary QRG; Task 1 pins this cross-template case.
- An external report with no reference must establish the reference without disabling; Task 1 pins this first-report case.
- Without SO2R a Win-Test/UCXLog report must affect only the main beacon; Task 3 pins both integrations.
- An old XML file with enabled flags and a one-minute interval must load as disabled with a five-minute interval and later write `false`; Task 2 pins the migration.
- `FAILED` must stay red without an orange flash while ordinary worker chips retain current theme colours; Task 4 pins both sides.
---
### Task 1: Pure beacon session policy and structured status
**Files:**
- Create: `core/src/main/java/kst4contest/controller/BeaconFrequencyParser.java`
- Create: `core/src/main/java/kst4contest/controller/BeaconSessionState.java`
- Create: `core/src/main/java/kst4contest/model/BeaconStatusSnapshot.java`
- Create: `core/src/test/java/kst4contest/controller/BeaconFrequencyParserTest.java`
- Create: `core/src/test/java/kst4contest/controller/BeaconSessionStateTest.java`
**Interfaces:**
- Produces: `BeaconFrequencyParser.parseHz(String): OptionalLong`.
- Produces: `BeaconSessionState.Channel { MAIN, SECOND }` and synchronized policy methods `resetSession(ChatPreferences)`, `setEnabled(Channel, boolean, ChatPreferences)`, `onManualQrgChanged(Channel, String, ChatPreferences)`, `onExternalQrgChanged(Channel, long, ChatPreferences)`, `onTemplateChanged(Channel, ChatPreferences)`, `recordSendFailure(Channel, boolean)` and `snapshot(ChatPreferences): BeaconStatusSnapshot`.
- Produces: explicit `BeaconStatusSnapshot` DTO with aggregate state `OFF`, `PARTIAL`, `ON`, `FAILED`, plus main/second category DTOs carrying availability, enablement, failure and `InactiveReason`.
- [ ] **Step 1: Write parser tests** for `144.300`, `144,300`, `144.300.03`, `1296.123.000`, compact `144300`, compact `10368100`, blanks, malformed text, non-positive values and overflow.
- [ ] **Step 2: Run the parser test and verify RED.**
Run: `.\gradlew.bat :core:test --tests kst4contest.controller.BeaconFrequencyParserTest --console=plain`
Expected: compilation failure because `BeaconFrequencyParser` does not exist.
- [ ] **Step 3: Implement `BeaconFrequencyParser`** with integer arithmetic and the QRG forms already used by the client; accept only a complete positive frequency that maps to a supported `Band`.
- [ ] **Step 4: Re-run the parser test and verify GREEN.**
- [ ] **Step 5: Write session-policy tests** for initial reasons, independent enablement, placeholder requirements in either template, partial aggregate activation, manual reference creation/rebase, invalid manual clearing, cross-template invalidation, first external reference, 5,000/5,001-Hz boundaries, per-category external changes, reason retention and send-failure clearing.
- [ ] **Step 6: Run `BeaconSessionStateTest` and verify RED** because the policy and DTO are absent.
- [ ] **Step 7: Implement the DTO and policy** so the existing observable preference booleans are projection only and no listener/callback leaves a synchronized method.
- [ ] **Step 8: Re-run both focused tests and verify GREEN.**
- [ ] **Step 9: Inspect the task diff** for duplicated state, floating-point frequency comparisons or display strings in `core`.
### Task 2: Session-only persistence and five-minute migration
**Files:**
- Modify: `core/src/main/java/kst4contest/model/ChatPreferences.java`
- Modify: `core/src/main/java/kst4contest/controller/ChatController.java`
- Modify: `core/src/main/resources/praktiKSTpreferences.xml`
- Modify: `core/src/test/java/kst4contest/model/ChatPreferencesBeaconStateTest.java`
- Modify: `core/src/test/java/kst4contest/model/ChatPreferencesRoundTripTest.java`
- Modify: `app-desktop/src/test/kotlin/kst4contest/view/compose/tabs/BeaconTabStateTest.kt`
- Modify: `app-desktop/src/test/kotlin/kst4contest/view/i18n/RemainingTextsFollowTheLanguageTest.kt`
**Interfaces:**
- Consumes: Task 1 `BeaconSessionState`.
- Produces: `ChatController.MIN_BEACON_INTERVAL_MINUTES == 5` and session reset during controller/profile construction without reset on reconnect.
- [ ] **Step 1: Replace persistence expectations with failing tests** proving defaults are off, stored `true` is ignored, every full write stores both legacy/current enable tags as `false`, layout-only writes do not revive them, and intervals below five normalise in memory.
- [ ] **Step 2: Add interval tests** proving four is refused, five accepted, and an old stored one becomes five without changing a larger value.
- [ ] **Step 3: Run the focused core and desktop tests and verify RED.**
Run: `.\gradlew.bat :core:test --tests kst4contest.model.ChatPreferencesBeaconStateTest --tests kst4contest.model.ChatPreferencesRoundTripTest :app-desktop:test --tests kst4contest.view.compose.tabs.BeaconTabStateTest --tests kst4contest.view.i18n.RemainingTextsFollowTheLanguageTest --console=plain`
- [ ] **Step 4: Make enable flags session-only**: initialise both false, ignore XML enable values, always serialise `false`, retain existing element names, and reset the policy only when a new controller/profile preferences object is installed.
- [ ] **Step 5: Set and enforce the five-minute minimum** in controller, XML defaults and preference-load normalisation; retain timer start/restart semantics.
- [ ] **Step 6: Re-run the focused tests and inspect their XML summaries.**
- [ ] **Step 7: Inspect the task diff** to confirm no reconnect path resets the session and no default was silently raised to ten minutes.
### Task 3: Explicit manual and external QRG paths
**Files:**
- Modify: `core/src/main/java/kst4contest/controller/ChatController.java`
- Modify: `core/src/main/java/kst4contest/controller/ReadUDPbyUCXMessageThread.java`
- Modify: `core/src/main/java/kst4contest/controller/ReadUDPByWintestThread.java`
- Modify: `app-desktop/src/main/kotlin/kst4contest/view/compose/ChatInputState.kt`
- Modify: `app-desktop/src/main/kotlin/kst4contest/view/compose/ChatInputRow.kt`
- Modify: `app-desktop/src/main/java/kst4contest/view/ComposeChatInputActions.java`
- Modify: `app-desktop/src/main/kotlin/kst4contest/view/compose/tabs/BeaconTabState.kt`
- Modify: `app-desktop/src/main/kotlin/kst4contest/view/compose/SettingsTabs.kt`
- Modify: focused fake `ChatInputActions` implementations in affected tests
- Modify: `core/src/test/java/kst4contest/controller/BeaconControlTest.java`
- Modify: `core/src/test/java/kst4contest/controller/ReadUDPbyUCXMessageThreadLoopbackTest.java`
- Modify: `core/src/test/java/kst4contest/controller/WinTestStatusSlotTest.java`
- Modify: `app-desktop/src/test/kotlin/kst4contest/view/compose/ChatInputStateTest.kt`
- Modify: `app-desktop/src/test/kotlin/kst4contest/view/compose/tabs/BeaconTabStateTest.kt`
**Interfaces:**
- Produces: controller methods `applyManualQrg(RadioSlot, String)`, `applyExternalQrg(RadioSlot, String, long)`, `onMainBeaconTemplateApplied()` and `onSecondBeaconTemplateApplied()`.
- Produces: a `ChatInputActions`/`ChatInputState` manual-QRG commit method used by `ChatInputRow` instead of writing preferences directly.
- Consumes: Task 1 policy and Task 2 session lifecycle.
- [ ] **Step 1: Add failing controller tests** for individual activation refusal, valid partial chip activation, user disable reason, manual rebase, invalid manual cross-template disabling and template-apply revalidation.
- [ ] **Step 2: Add failing chat-input tests** proving both manual fields call the explicit action with the correct `RadioSlot`/category and never write preferences directly.
- [ ] **Step 3: Add failing UCXLog tests** for exact Hz conversion, first-reference behaviour, >5-kHz main-only shutdown without SO2R and second-only shutdown for RadioNr 2 with SO2R.
- [ ] **Step 4: Add failing Win-Test tests** for main/pass frequency selection, 100-Hz units, non-SO2R main-only and SO2R slot routing.
- [ ] **Step 5: Run the four focused test groups and verify RED.**
- [ ] **Step 6: Implement the controller entry points** so the preference value and policy update occur together on the existing UI-dispatch boundary and publish a fresh beacon status only after state is consistent.
- [ ] **Step 7: Route manual Compose commits through `ComposeChatInputActions`** while preserving focus/commit behaviour and existing displayed `ObservedValue` mirrors.
- [ ] **Step 8: Give both template draft properties a shared post-apply effect key** that revalidates active beacons after all writes, without changing their validation-before-stage behaviour.
- [ ] **Step 9: Route UCXLog and Win-Test through `applyExternalQrg`** only when their current QRG-sync setting already permits the update; preserve packet parsing and diagnostics.
- [ ] **Step 10: Re-run focused tests and inspect XML summaries.**
- [ ] **Step 11: Run related integration tests** for SO2R routing, settings apply and chat-input rendering.
- [ ] **Step 12: Inspect the task diff** for protocol/framing changes, toolkit calls in `core`, or source inference through listeners.
### Task 4: Beacon task status, translated tooltips and traffic colours
**Files:**
- Modify: `core/src/main/java/kst4contest/controller/BeaconTask.java`
- Modify: `core/src/main/java/kst4contest/controller/BeaconStatus.java`
- Modify: `core/src/main/java/kst4contest/model/ThreadStateMessage.java`
- Create: `app-desktop/src/main/kotlin/kst4contest/view/compose/BeaconStatusPresentation.kt`
- Modify: `app-desktop/src/main/kotlin/kst4contest/view/compose/StatusIndicatorState.kt`
- Modify: `app-desktop/src/main/kotlin/kst4contest/view/compose/StatusBar.kt`
- Modify: `app-desktop/src/main/i18n/strings_de.properties`
- Modify: `app-desktop/src/main/i18n/strings_en.properties`
- Modify: `core/src/test/java/kst4contest/controller/BeaconTaskTest.java`
- Modify: `core/src/test/java/kst4contest/controller/BeaconControlTest.java`
- Create: `app-desktop/src/test/kotlin/kst4contest/view/compose/BeaconStatusPresentationTest.kt`
- Modify: `app-desktop/src/test/kotlin/kst4contest/view/compose/StatusIndicatorStateTest.kt`
- Modify: `app-desktop/src/test/kotlin/kst4contest/view/compose/StatusBarScreenTest.kt`
- Modify: relevant i18n boundary tests
**Interfaces:**
- Consumes: Task 1 `BeaconStatusSnapshot` and policy send-failure methods.
- Produces: optional structured beacon snapshot on `ThreadStateMessage`; other thread messages remain unchanged.
- Produces: `BeaconStatusPresentation` mapping snapshot plus current strings to label, tooltip and visual style.
- [ ] **Step 1: Add failing core tests** proving a failed active category yields `FAILED`, a later successful run clears only its failure, disabled categories are not failed, and ordinary timer runs preserve inactive reasons.
- [ ] **Step 2: Add failing presentation tests** for bilingual per-category tooltips, initial/user/QRG/QRG-invalid reasons, `1/2`, and no concrete frequency in the QRG reason.
- [ ] **Step 3: Add failing colour-model tests** for the exact light/dark OFF colours, ON/PARTIAL green, 200-ms orange highlight, FAILED red/white with highlight suppression and unchanged default-worker colours.
- [ ] **Step 4: Run focused core and desktop tests and verify RED.**
- [ ] **Step 5: Attach the structured snapshot to the existing status message** without adding translated display prose to `core`.
- [ ] **Step 6: Make `BeaconTask` record per-category outcomes** while retaining text resolution, category validation and regular TX queue insertion.
- [ ] **Step 7: Implement translated presentation and visual style** only for messages carrying a beacon snapshot; keep action/provider ordering and stale-update protection intact.
- [ ] **Step 8: Implement the selected colours in `ThreadStatusButtonView`** and suppress the highlight when style is FAILED.
- [ ] **Step 9: Add aligned DE/EN i18n keys** and re-run translation-boundary tests.
- [ ] **Step 10: Re-run focused tests and inspect XML summaries.**
- [ ] **Step 11: Run the affected Compose screen tests** and inspect a rendered light/dark result if the test harness emits one.
- [ ] **Step 12: Inspect the task diff** to ensure no non-beacon chip acquired special colours or click behaviour.
### Task 5: Targeted documentation, context and full verification
**Files:**
- Modify: `github_docs/de-Konfiguration.md`
- Modify: `github_docs/en-Configuration.md`
- Modify: `github_docs/de-Contest-Workflow.md`
- Modify: `github_docs/en-Contest-Workflow.md`
- Modify: `github_docs/de-Makros-und-Variablen.md`
- Modify: `github_docs/en-Macros-and-Variables.md`
- Review/modify: `github_docs/de-Funktionen.md`, `github_docs/en-Features.md`
- Review/modify: `github_docs/de-Benutzeroberflaeche.md`, `github_docs/en-User-Interface.md`
- Modify: `github_docs/de-Changelog.md`
- Modify: `github_docs/en-Changelog.md`
- Modify: `website/src/features/macros.md`
- Review/modify: `website/src/features/trx-qrg-synchronisation.md`
- Modify: `docs/PROJECT_CONTEXT.md`
- Modify: `docs/superpowers/specs/2026-11-04-live-beacon-control-design.md`
- Review: `github_docs/client_settings_window_beacon.png`
**Interfaces:**
- Consumes: completed behaviour from Tasks 1-4.
- Produces: semantically aligned DE/EN user documentation and current durable project context.
- [ ] **Step 1: Update the targeted manual sections** with session-only activation, five-minute minimum, activation prerequisites, source-specific reference/QSY rules, per-category tooltip and traffic colours.
- [ ] **Step 2: Update both changelogs compactly** without inventing a version or release state.
- [ ] **Step 3: Update only website sections that already describe interval or TRX-QRG behaviour**; do not duplicate the manual.
- [ ] **Step 4: Reconcile the older live-beacon design and `PROJECT_CONTEXT`** so they no longer claim activation persists or the one-minute minimum remains unchanged.
- [ ] **Step 5: Inspect the existing Beacon settings screenshot** and record replacement only if a visible value is now false; do not fabricate an image.
- [ ] **Step 6: Run all focused test classes from Tasks 1-4.**
- [ ] **Step 7: Run the full build.**
Run: `.\gradlew.bat build --console=plain`
Expected: `BUILD SUCCESSFUL` with no failed tests.
- [ ] **Step 8: Read every generated `*/build/test-results/**/TEST-*.xml` summary** and report test/failure/error/skipped totals rather than relying only on exit code.
- [ ] **Step 9: Count PMD and SpotBugs XML findings per module** from `<violation` and `<BugInstance>` and identify findings touching changed production files.
- [ ] **Step 10: Run `git diff --check` and inspect `git status --short`.**
- [ ] **Step 11: Review the complete diff against the approved spec** for unrelated cleanup, stale documentation, accidental protocol changes and user-authored changes.
- [ ] **Step 12: Perform a manual runtime check if safely possible**: initial off state, valid/invalid category activation, manual rebase, external >5-kHz shutdown, `1/2`, OFF tooltip, orange flash and persistent FAILED red.
## Self-Review Result
- Every approved behaviour maps to Tasks 1-4; documentation and durable context map to Task 5.
- Exact types and controller entry points are defined once in the Interfaces blocks.
- Cross-template QRG dependencies, first external reference, non-SO2R routing, XML migration and FAILED colour priority are explicit tests.
- Plan size reflects five independently reviewable deliverables; no implementation bodies or unauthorised Git actions are included.
@@ -1,96 +0,0 @@
# Automatic Chat Suffix Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Append the fixed suffix ` *a*` to every active KST4Contest autoanswer and beacon while leaving manual and protocol traffic unchanged.
**Architecture:** A package-private `AutomaticChatMessageFormatter` owns the suffix and performs unconditional appending. The active autoanswer and beacon producers call it explicitly; beacon validation keeps a 120-character payload allowance and validates the resulting 124-character maximum.
**Tech Stack:** Java 21, Kotlin 2.2, Gradle wrapper, JUnit 5, Mockito
**Spec:** `docs/superpowers/specs/2026-11-13-automatic-chat-suffix-design.md`
## Global Constraints
- The exact suffix is ` *a*`, including its leading space.
- `[KST4C Automsg]` remains on autoanswers and remains the loop-prevention marker.
- Suffix insertion is unconditional; duplicate `*a*` markers are allowed.
- Beacon payloads remain limited to 120 characters; complete suffixed beacons are limited to 124 characters.
- Manual messages and internal ON4KST frames must remain byte-for-byte unaffected by this feature.
- No new dependency, setting, persistence field, version bump, staging, commit or publication action.
## Review Focus
- A 120-character beacon payload must be sent as exactly 124 characters after suffix insertion.
- A 121-character beacon payload must still be rejected rather than producing a 125-character frame.
- Text already ending in `*a*` must receive a second suffix without deduplication.
- Autoanswer validation and cooldown accounting must still reject invalid text before consuming cooldown.
- The existing prefix-based ping-pong guard and all manual send paths must remain unchanged.
---
### Task 1: Shared automatic-message formatter and autoanswers
**Files:**
- Create: `core/src/main/java/kst4contest/controller/AutomaticChatMessageFormatter.java`
- Create: `core/src/test/java/kst4contest/controller/AutomaticChatMessageFormatterTest.java`
- Modify: `core/src/main/java/kst4contest/controller/MessageBusManagementThread.java`
- Modify: `core/src/test/java/kst4contest/controller/MessageBusManagementThreadAutoAnswerDecisionTest.java`
- Modify: `core/src/test/java/kst4contest/controller/MessageBusManagementThreadAutoAnswerTest.java`
- Modify: `core/src/test/java/kst4contest/controller/MessageBusManagementThreadChatFrameTest.java`
**Interfaces:**
- Produces: `AutomaticChatMessageFormatter.appendSuffix(String messageText): String`
- Consumes: existing `ApplicationConstants.AUTOANSWER_PREFIX` and `On4KstProtocol.messageText(String)`
- [x] Add failing formatter tests for exact suffix insertion and intentional duplicate suffixes.
- [x] Run `\.\gradlew.bat :core:test --tests "kst4contest.controller.AutomaticChatMessageFormatterTest"` and confirm the tests fail because the formatter is absent.
- [x] Implement the package-private formatter with `SUFFIX = " *a*"` and unconditional appending.
- [x] Update failing autoanswer and version-reply expectations so generic, QRG and `//VER` replies end in ` *a*` while retaining `[KST4C Automsg]`.
- [x] Append before final autoanswer protocol validation and in the `//VER` construction path.
- [x] Run the formatter and three focused autoanswer test classes and confirm zero failures.
### Task 2: Beacon suffix and length boundaries
**Files:**
- Modify: `core/src/main/java/kst4contest/controller/ChatController.java`
- Modify: `core/src/main/java/kst4contest/controller/BeaconTask.java`
- Modify: `core/src/test/java/kst4contest/controller/On4KstProtocolTest.java`
- Modify: `core/src/test/java/kst4contest/controller/BeaconTaskTest.java`
**Interfaces:**
- Consumes: `AutomaticChatMessageFormatter.appendSuffix(String)` from Task 1
- Produces: beacon payload validation at 120 characters and final-message validation at 124 characters
- [x] Add failing tests asserting that each queued beacon ends in ` *a*`, a 120-character payload produces a 124-character message, and a 121-character payload is rejected.
- [x] Run `\.\gradlew.bat :core:test --tests "kst4contest.controller.On4KstProtocolTest" --tests "kst4contest.controller.BeaconTaskTest"` and confirm the new assertions fail.
- [x] Separate the 120-character payload limit from the 124-character final beacon limit in `ChatController`.
- [x] Append the suffix only after macro resolution and payload validation, then validate the final message before queueing.
- [x] Run the focused beacon tests and confirm zero failures.
### Task 3: Targeted documentation and verification
**Files:**
- Modify: `github_docs/de-Konfiguration.md`
- Modify: `github_docs/en-Configuration.md`
- Modify: `github_docs/de-Makros-und-Variablen.md`
- Modify: `github_docs/en-Macros-and-Variables.md`
- Modify: `github_docs/de-Funktionen.md`
- Modify: `github_docs/en-Features.md`
- Modify: `github_docs/de-Changelog.md`
- Modify: `github_docs/en-Changelog.md`
- Modify: `website/src/features/automatic-replies.md`
- Modify: `website/src/features/macros.md`
- Modify: `docs/PROJECT_CONTEXT.md`
**Interfaces:**
- Consumes: implemented suffix and length behaviour from Tasks 1 and 2
- Produces: aligned German/English user documentation and durable current-state context
- [x] Update examples and behavioural text so autoanswers retain `[KST4C Automsg]` and all automated chat messages end in ` *a*`.
- [x] Document the 120-character beacon payload and 124-character transmitted-message limits in German and English.
- [x] Record the fixed suffix rule in the changelogs and `docs/PROJECT_CONTEXT.md` without changing unrelated documentation.
- [x] Run the focused core tests from Tasks 1 and 2, then `\.\gradlew.bat build`.
- [x] Read every Gradle test-result XML summary and report failures, errors and skipped tests; inspect PMD and SpotBugs XML counts produced by the build.
- [x] Run the website test/build commands defined by the current `website/package.json` if the changed website pages participate in that build.
- [x] Run `git diff --check` and review the complete scoped diff for accidental changes; perform no Git publication action.
@@ -1,50 +0,0 @@
# Live Beacon Control Design
Freigegeben von Marc am 2026-11-04.
> Durch das freigegebene [Beacon Session Safety Design](2026-11-11-beacon-session-safety-design.md)
> abgelöst, soweit Aktivierungspersistenz, Mindestintervall, QRG-Sicherung und Chip-Darstellung
> betroffen sind.
## Ziel
Die beiden Beacon-Aktivierungsschalter wirken in der laufenden Sitzung sofort. Der gemeinsame
Beacon-Timer bleibt bestehen und liest bei jedem Lauf die aktuellen Zustände. Der Beacon-Chip
im Hauptfenster zeigt den zusammengefassten Zustand und kann die aktuell nutzbaren Beacons
gemeinsam ein- oder ausschalten.
## Verbindliches Verhalten
- Nach einem Programmstart und Profilwechsel sind beide Beacon-Zustände ausgeschaltet.
- Ein normaler ON4KST-Reconnect innerhalb derselben Programmsitzung verändert sie nicht.
- Ein Klick auf eine Beacon-Checkbox wirkt sofort im Speicher und damit beim nächsten
regulären Timerlauf.
- Aktivieren sendet nicht sofort und startet den Timer nicht neu.
- Aktivierungszustände werden nicht in die Profil-XML übernommen; ein vollständiger
Einstellungsspeichervorgang schreibt die kompatiblen Aktivierungs-Tags als `false`.
- Beacon-Text und Intervall bleiben normale Settings-Entwurfswerte. Das Intervall startet den
Timer erst beim Anwenden neu.
- Der Status-Chip zeigt `off`, `1/2`, `on` oder `FAILED` für die aktuell nutzbaren Kategorien.
- Sind alle nutzbaren Beacons aus, aktiviert ein Chip-Klick alle nutzbaren Beacons. Ist
mindestens eine nutzbare Beacon an, deaktiviert der Klick alle nutzbaren Beacons.
- Bei deaktiviertem zweiten Chat schaltet der Chip nur die Hauptkategorie.
- Chip und geöffnetes Settings-Fenster zeigen denselben beobachtbaren Zustand.
- Nur der Beacon-Chip wird anklickbar. Andere Thread-Status-Chips bleiben reine Anzeigen.
## Unveränderte Grenzen
- Beide Kategorien behalten eigene Aktivierungsflags und Texte.
- Der zweite Beacon-Versand setzt weiterhin einen aktivierten zweiten Chat voraus.
- Nachrichtenvalidierung, TX-Warteschlange und ON4KST-Protokoll bleiben unverändert.
- Gemeinsamer Timer und Intervall-Persistenz bleiben unverändert; das Mindestintervall beträgt
fünf Minuten.
- Profilzustände werden nicht miteinander vermischt.
## Technischer Ansatz
`BeaconSessionState` ist die maßgebliche sitzungsbezogene Quelle für Aktivierung,
QRG-Referenzen, Abschaltgründe und Fehler. Die vorhandenen beobachtbaren
`ChatPreferences`-Werte bleiben die kompatible Projektion für Settings und UI. Controller und
`BeaconTask` veröffentlichen einen strukturierten `BeaconStatusSnapshot`, aus dem Chip-Text,
Tooltip und die Beacon-spezifische Farbgebung entstehen. Details der QRG-Prüfung und
Darstellung stehen im ablösenden Design vom 2026-11-11.
@@ -1,26 +0,0 @@
# Map Overlay Legend and Screenshot Design
## Intent
Make the two map overlays understandable without consulting the manual and replace the outdated general map image with the supplied screenshot of an active QRB range.
## Behaviour
- The map header shows a compact red **Antenna** legend item only while the antenna sector can be drawn.
- It shows a compact blue **Active filters** legend item only while a valid QTF or QRB overlay is active.
- A localized tooltip explains that red represents the actual antenna heading, beamwidth and maximum QRB, while blue represents active QTF and QRB filters.
- The existing responsive `FlowRow` may wrap the legend with the other header controls.
- Overlay rendering, filtering, antenna heading and rotor behaviour do not change.
## Screenshot
- Store the supplied image as `github_docs/station_map_spatial_filters.png` without altering its pixels.
- Use it in the German and English UI manual and on the Station Map website feature page.
- Describe the visible range correctly as minimum and maximum QRB, not QTF.
- Retain `station_map_path_analysis.png` where the visible path-analysis panels are the subject.
## Constraints
- Reuse the exact overlay colours rather than duplicating colour literals.
- Keep English and German UI strings and documentation aligned.
- Do not stage, commit, push or publish any change.
@@ -1,128 +0,0 @@
# Beacon Session Safety Design
Freigegeben von Marc am 2026-11-11.
## Ziel
Die Beacon-Funktion darf nach einem Programmstart oder Profilwechsel nicht aus einer
gespeicherten Aktivierung weiterlaufen. Jeder Beacon wird in der laufenden Sitzung bewusst
eingeschaltet, hält seine eigene Kategorie-QRG als Referenz fest und schaltet nur bei einer
automatisch von UCXLog oder Win-Test gemeldeten Abweichung von mehr als 5 kHz ab.
Der zusammengefasste `MyBeacon`-Chip macht Aktivierung, Teilaktivierung, automatische
Abschaltung und Versandfehler ohne Umweg über das Einstellungsfenster erkennbar.
## Verbindliches Verhalten
### Intervall und Sitzung
- Das kleinste zulässige gemeinsame Beacon-Intervall beträgt fünf Minuten.
- Genau fünf Minuten sind zulässig. Kleinere geladene Werte werden im Speicher auf fünf
Minuten normalisiert; die mitgelieferte Konfiguration verwendet für beide Kategorien fünf.
- Nach jedem Programmstart und Profilwechsel sind beide Beacons ausgeschaltet.
- Ein Disconnect oder Reconnect innerhalb derselben Programmsitzung verändert ihre
Aktivierung nicht.
- Die Aktivierungsflags werden nicht aus XML gelesen. Die vorhandenen XML-Elemente bleiben
für die Dateikompatibilität erhalten, werden aber immer mit `false` geschrieben.
### Aktivierung und benötigte QRG-Werte
- `MYQRG` und `MYQRGSHORT` benötigen eine gültige Haupt-QRG.
- `SECONDQRG` benötigt eine gültige zweite QRG.
- Diese Voraussetzung gilt unabhängig davon, in welchem der beiden Bakentexte die Variable
vorkommt.
- Fehlt ein benötigter Wert oder ist er ungültig, bleibt der betroffene Beacon aus. Sein
kategorieweiser Status nennt die fehlende oder ungültige QRG als Grund.
- Der gemeinsame Chip aktiviert beide nutzbaren Kategorien unabhängig. Ein gültiger Beacon
wird eingeschaltet, auch wenn der andere abgelehnt wird; der Chip zeigt dann `1/2`.
- Ein Text ohne QRG-Platzhalter darf ohne bekannte QRG aktiviert werden.
- Geprüft wird der bereits angewendete Text, nicht ein noch offener Settings-Entwurf.
### Kategoriebezogene Referenz-QRG
- Beim Einschalten übernimmt jeder Beacon die aktuell gültige QRG seiner eigenen Kategorie
als Referenz.
- Ist keine gültige Kategorie-QRG vorhanden und benötigt der Text sie nicht, wird die erste
später gültige manuelle oder externe QRG zur Referenz.
- Eine gültige manuelle QRG-Eingabe ist eine bewusste Operatorentscheidung. Sie deaktiviert
keinen Beacon und verschiebt die Referenz der zugehörigen Kategorie.
- Eine ungültige manuelle Eingabe deaktiviert jeden aktiven Beacon, dessen angewendeter Text
den betroffenen QRG-Wert benötigt. Benötigt sein Text ihn nicht, bleibt der Beacon aktiv;
nur die Referenz seiner Kategorie wird gelöscht.
- Ausschließlich QRG-Übernahmen von UCXLog `RadioInfo` und Win-Test `STATUS`, für die der
bestehende QRG-Abgleich aktiv ist, dürfen automatisch abschalten.
- Der Vergleich erfolgt in ganzzahligen Hz gegen die aktuelle Referenz. Genau 5.000 Hz sind
zulässig; erst eine größere Abweichung schaltet ab.
- Ohne Referenz setzt die erste externe QRG nur die Referenz und schaltet nicht ab.
- Ohne SO2R betrifft eine externe Änderung von `MYQRG` ausschließlich die Hauptbake. Mit
SO2R folgt Radio 1 `MYQRG` und Radio 2 `SECONDQRG`.
### Status und Tooltip
- Der Status wird als strukturierter Snapshot aus `core` geliefert. Übersetzte Anzeigetexte
entstehen ausschließlich in `app-desktop`.
- Der Snapshot kennt `OFF`, `PARTIAL`, `ON` und `FAILED` sowie den Zustand beider Kategorien.
- Der Tooltip zeigt je Kategorie den aktuellen Zustand oder letzten Abschalt-/Ablehnungsgrund:
noch nicht in dieser Sitzung aktiviert, durch den Benutzer ausgeschaltet, fehlende oder
ungültige Haupt-QRG, fehlende oder ungültige zweite QRG oder automatische QRG-Abweichung
von mehr als 5 kHz.
- Der QRG-Grund nennt keine konkreten Frequenzen.
- Timeraktivität überschreibt den kategorieweisen Grund nicht.
- Ein erfolgreicher späterer Lauf löscht einen früheren Versandfehler der Kategorie.
### Verkehrsfarben des `MyBeacon`-Chips
- `on` und `1/2`: Hintergrund `#238636`, Rand `#56D364`, weiße Schrift.
- Der bestehende 200-ms-Aktivitätsblitz verwendet Hintergrund `#FFB300`, Rand `#FFE082`
und Schrift `#1B1B1B`.
- `off`: neutraler Theme-Hintergrund mit `#D50000` im hellen beziehungsweise `#FF6B6B` im
dunklen Design.
- `FAILED`: dauerhaft `#D50000` mit Rand `#FF6B6B` und weißer Schrift.
- `FAILED` unterdrückt den orangefarbenen Aktivitätsblitz.
- Andere Status-Chips behalten ihr heutiges Theme-Verhalten.
## Technischer Ansatz
Eine controllerseitige `BeaconSessionState`-Komponente koordiniert den Zustand beider
Kategorien. Die beobachtbaren Flags in `ChatPreferences` bleiben kompatible UI-Projektion,
aber kein persistenter Produktzustand. Die Komponente verwaltet Referenzen, kategorieweise
Gründe und Versandfehler und ist der einzige Produktionsschreibpfad der Aktivierungsflags.
Manuelle QRG-Eingaben und externe Logger-Meldungen verwenden getrennte Controller-Einstiege.
UCXLog und Win-Test übergeben die bereits ermittelte Kategorie, den formatierten Anzeigewert
und die genaue Frequenz in Hz innerhalb der bestehenden `UiDispatcher`-Grenze. Damit ist die
Herkunft explizit; Listener, Thread-lokale Markierungen oder erratene Ursprünge sind unnötig.
Der vorhandene `BeaconTask` bleibt für Auflösung, Validierung und Einreihung in die reguläre
TX-Warteschlange verantwortlich. Er meldet je Kategorie Erfolg oder Fehler an den
Sitzungszustand zurück. Ein DTO im gemeinsamen Model transportiert den strukturierten Status
über den bestehenden Threadstatus-Kanal; Compose übersetzt Gründe und wählt die Chipfarben.
## Unveränderte Grenzen
- Beide Kategorien teilen einen Timer und besitzen getrennte Aktivierung und Texte.
- Der zweite Versand setzt weiterhin eine verfügbare zweite Chatkategorie voraus.
- Aktivieren sendet nicht sofort und startet den Timer nicht neu.
- Der erste Timerlauf nach dem Verbindungsaufbau bleibt bei ungefähr zehn Sekunden.
- Nachrichtenauflösung, Längenlimit, TX-Warteschlange und ON4KST-Framing bleiben unverändert.
- Die Chip-Texte `off`, `1/2`, `on` und `FAILED` und seine gemeinsame Klickfunktion bleiben.
- Es gibt keine neue Produktionsabhängigkeit, kein neues persistentes Schema und keine
Änderung eines externen Protokolls.
## Berücksichtigte Ansätze
1. **Gewählt:** controllerseitiger Sitzungszustand mit expliziten manuellen und externen
Ereignissen. Das hält Policy, Referenzen und Gründe zusammen und bleibt testbar.
2. **Verworfen:** Flags in Preferences, Referenzen in einem Guard und Gründe in `BeaconStatus`.
Der zusammengehörige Zustand wäre auf mehrere Besitzer verteilt.
3. **Verworfen:** Beobachtung der QRG-Werte mit temporärer Herkunftsmarkierung. `MutableValue`
trägt keine Quelle; die asynchrone UI-Weitergabe machte diesen Ansatz fragil.
## Dokumentationswirkung
Die Änderung ist benutzerseitig sichtbar, betrifft Laufzeit/Persistenz sowie die bestehende
UCXLog-/Win-Test-Integration. Geprüft und bei Bedarf angepasst werden die relevanten
deutschen und englischen Konfigurations-, Workflow-, Variablen-, Funktions- und
Benutzeroberflächenabschnitte, Changelog, Website-Texte, `docs/PROJECT_CONTEXT.md` und der
ältere Live-Beacon-Entwurf. README und verbundene Projekte sind voraussichtlich nicht
betroffen.
@@ -1,27 +0,0 @@
# Automatic Chat Suffix Design
## Intent
Every user-visible chat message generated and sent automatically by KST4Contest must end with the fixed suffix ` *a*`. The marker makes automatic traffic recognisable without changing manual messages or ON4KST control traffic.
## Behaviour
- Append ` *a*` to generic private autoanswers, QRG autoanswers, `//VER` replies and both beacon categories.
- Keep the existing `[KST4C Automsg]` prefix on every autoanswer and continue using it for the reply-loop guard.
- Append the suffix unconditionally after text preparation. A configured text which already ends in `*a*` therefore receives another ` *a*`.
- Preserve the existing 120-character beacon payload allowance. The complete transmitted beacon, including the four-character suffix, may contain up to 124 characters.
## Non-goals
- Do not mark manually sent messages, snippets or manually triggered CQ messages.
- Do not alter login, keepalive, ON4KST command or other internal protocol frames.
- Do not change cooldowns, category routing, beacon activation, QRG safeguards, timer behaviour, persistence or settings UI.
- Do not revive or refactor the unused legacy `ScoreboardUpdateTask`.
## Selected Approach
Use one package-private formatter in the controller package to append the fixed suffix. Call it explicitly from the active autoanswer and beacon construction paths. This keeps the scope visible and prevents a broad writer-layer rule from modifying manual messages or raw protocol frames.
## Validation and Documentation
Validate autoanswers after suffix insertion. Validate beacon payloads against 120 characters, append the suffix, then validate the final text against 124 characters. Update focused tests, the German and English manuals, relevant website feature pages, changelogs and durable project context.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 63 KiB

+9 -14
View File
@@ -206,8 +206,6 @@ Dezent umrahmte Flächen fassen **QRB**, **QTF** einschließlich Richtungstasten
Standardmäßig aktualisiert eine gültige direkte Eingabe in der QTF-Gruppe oder der Klick auf eine Richtungstaste zugleich die aktuelle eigene Antennenrichtung. Diese ausdrückliche Übernahme funktioniert unabhängig davon, ob **Show only QTF** ein- oder ausgeschaltet ist. Das Zurücksetzen oder bloße Ausschalten des Filters verändert die Antennenrichtung nicht. Im Abschnitt **Station → Manuelle Antennenrichtung** kann das Verhalten mit **QTF-Filterrichtung als eigene Antennenrichtung übernehmen** profilbezogen ausgeschaltet werden. PSTRotator 1 hat vorübergehend Vorrang, ohne diese gespeicherte Auswahl zu verändern.
Dieselbe ausdrückliche QTF-Eingabe beziehungsweise Richtungstaste zentriert eine geöffnete Stationskarte auf den gewählten Sektor, ohne den Zoom zu verändern. Wiederhergestellte Einstellungen, **Reset filters**, Rotor-Rückmeldungen und andere Hintergrundänderungen bewegen die Karte nicht. Diese Navigation ist von der optionalen Übernahme als tatsächliche Antennenrichtung getrennt und löst keinen Rotorbefehl aus.
Bei **New bands** werden aktuelle QRGs, Bandangaben im Namensfeld und aktive Rufzeichenvarianten gemeinsam ausgewertet. Manuelle NOT-QRV-Markierungen haben Vorrang.
Der Filter **Tropo >=0dB** entfernt nur Stationen, für die eine abgeschlossene Berechnung eine negative Marge ergeben hat. Noch nicht berechnete oder fehlgeschlagene Auswertungen bleiben sichtbar. Andernfalls würde ein fehlender API-Wert wie ein nachgewiesen ungeeigneter Funkweg behandelt.
@@ -363,9 +361,11 @@ Die Stationskarte kann auf zwei Wegen geöffnet werden:
- **Windows → Show / hide station map** öffnet oder schließt das Kartenfenster.
- **Show on map** im **Further Info**-Bereich öffnet die Karte und fokussiert die ausgewählte Station.
Die Karte verwendet die Stationen, die nach Anwendung der aktuellen Benutzerlistenfilter noch sichtbar sind. Die Kopfzeile zeigt die Anzahl der dargestellten Stationen und weist mit `filtered view active` auf eine gefilterte Ansicht hin. Aktive QTF- und QRB-Grenzen erscheinen zusätzlich als eigene halbtransparente Sektor-, Kreis- oder Ringfläche. Dieses Filter-Overlay ist von dem Sektor für die tatsächliche Antennenrichtung, den Öffnungswinkel und den maximalen QRB getrennt. Eine kompakte Legende in der Kopfzeile kennzeichnet das rote Antennen-Overlay und das blaue Overlay der aktiven Filter, sobald sie sichtbar sind.
Die Karte verwendet die Stationen, die nach Anwendung der aktuellen Benutzerlistenfilter noch sichtbar sind. Die Kopfzeile zeigt die Anzahl der dargestellten Stationen und weist mit `filtered view active` auf eine gefilterte Ansicht hin.
![Stationskarte mit ausgewähltem Pfad, rotem Antennensektor und aktivem blauem QRB-Bereich](station_map_spatial_filters.png)
![Stationskarte mit ausgewählter Station und eingeblendeter Streckenanalyse](station_map_path_analysis.png)
> **Screenshot-Hinweis:** Das Bild zeigt noch die frühere Markerbeschriftung und weder das neue Kontextmenü noch die Worked-Großfeldfläche. Es wird nach der manuellen Kartenabnahme ersetzt.
### Station auswählen
@@ -378,10 +378,6 @@ Ein einzelner Stationsmarker kann direkt angeklickt werden. KST4Contest:
3. aktualisiert den **Further Info**-Bereich und
4. bereitet das vollständige sichtbare Rufzeichen als `/cq`-Empfänger vor.
Jede ausdrückliche Stationsauswahl passt außerdem den Kartenausschnitt so an, dass der vollständige Weg vom eigenen Standort bis zur Gegenstation mit etwas Rand sichtbar ist. Reicht der aktuelle Zoom bereits aus, bleibt er erhalten; bei längeren Strecken wird nur so weit wie nötig herausgezoomt. Normale Userlisten-Aktualisierungen, Ergebnisse der Streckenanalyse und andere Hintergrund-Neuberechnungen bewegen die Karte nicht. Eine Station ohne verwendbaren Locator bleibt ausgewählt, löst aber keine Kamerabewegung aus.
Wird eine bereits ausgewählte Station durch eine spätere Filteränderung ausgeblendet, bleibt sie als separates ausgewähltes Ziel mit Verbindungslinie sichtbar. Sie wird nicht wieder in die normale Markerliste, Gruppierung oder angezeigte Stationsanzahl aufgenommen. Das eigentliche Filterergebnis bleibt dadurch unverändert.
Ist **Gruppierung** ausgewählt, werden Marker, die bei niedrigen Zoomstufen zu dicht beieinanderliegen, als Cluster mit einer Stationsanzahl dargestellt. Ein Klick auf einen Cluster vergrößert den betreffenden Kartenausschnitt. Erst ein anschließend sichtbarer einzelner Marker wählt eine konkrete Station aus. Wird die Checkbox ausgeschaltet, zeigt die Karte unabhängig von der Zoomstufe alle positionierbaren Stationen als einzelne Marker. Der Tooltip erläutert den vollständigen Zweck des kompakten Schalters.
Das Umschalten wirkt sofort und verändert weder Zoom noch Kartenausschnitt oder Stationsauswahl. Die Einstellung wird automatisch gespeichert und beim nächsten Programmstart wiederhergestellt. Ohne gespeicherte Einstellung bleibt **Gruppierung** ausgewählt, damit bestehende Installationen zunächst das bisherige Verhalten behalten.
@@ -411,7 +407,7 @@ Bei aktivem **Grid color** kennzeichnet die Karte dauerhaft bekannte, bereits ge
### Auswahl mit Reset view löschen
**Reset view** löscht die Stationsauswahl und zentriert die Karte wieder auf den eigenen Standort, ohne den Zoomlevel zu verändern.
**Reset view** löscht die Stationsauswahl, ohne die Kartenposition oder den Zoomlevel zu verändern.
Dabei werden:
@@ -419,10 +415,9 @@ Dabei werden:
- die Auswahl in der Benutzerliste aufgehoben,
- die Verbindungslinie zur Gegenstation entfernt,
- eine noch laufende Auswertung der vorherigen Station verworfen und
- der rechte Analysebereich entfernt und
- die Karte auf den eigenen Standort zentriert.
- der rechte Analysebereich entfernt.
Der Zoomlevel bleibt unverändert. Die nächste ausdrückliche Stations- oder QTF-Auswahl kann den Kartenausschnitt erneut bewegen.
Die Karte selbst bleibt im zuvor gewählten Ausschnitt. Die Funktion ist deshalb kein geografischer Reset auf den eigenen Standort.
![Stationskarte nach Reset view ohne ausgewählte Station](station_map_reset.png)
@@ -565,7 +560,7 @@ Bei einer ungünstigen Aufteilung sollten zuerst die Divider und Spaltenbreiten
## Tipps zur Bedienung
- **Beacon schnell schalten**: Die Aktivierung ist im geöffneten Einstellungsfenster je Kategorie möglich. Ein Klick auf den Status-Chip **MyBeacon** schaltet alle derzeit nutzbaren Beacons gemeinsam ein oder aus. **off** hat rote Schrift, **1/2** und **on** sind grün, bei gemeldeter Aktivität blitzt der Chip orange. **FAILED** bleibt rot mit weißer Schrift. Der Tooltip nennt den Zustand oder letzten Abschaltgrund je Kategorie.
- **Einstellungsfenster geöffnet lassen**: Schneller Zugriff auf Beacon-Aktivierung/Deaktivierung.
- **Rechtsklick in der Benutzerliste**: Öffnet das Snippet-Menü und weitere Aktionen (QRZ.com-Profil, NOT-QRV-Tags setzen).
- **Enter aus dem Chat heraus**: Wenn im Sendfeld Text steht, sendet Enter direkt – auch wenn der Fokus woanders liegt.
- **Beacon nach dem Start prüfen**: Nach einem Programmstart oder Profilwechsel sind beide Beacons ausgeschaltet. Ein normaler ON4KST-Reconnect innerhalb derselben Programmsitzung verändert ihren Zustand nicht.
- **Beacon stoppen**: Beim Scannen von Frequenzen den Beacon ausschalten, damit der Chat nicht mit Meldungen überflutet wird.
-4
View File
@@ -40,10 +40,6 @@ Mehrere Operateure an einem Rechner können jetzt eigene Rufzeichen, Locators un
### Geändert
- **Automatische Chatmeldungen eindeutig markiert:** Allgemeine und QRG-bezogene Autoantworten, `//VER`-Antworten sowie beide Beacons enden jetzt mit ` *a*`. Das bestehende Präfix `[KST4C Automsg]` der Autoantworten bleibt erhalten. Der aufgelöste Beacon-Inhalt bleibt auf 120 Zeichen begrenzt; mit dem festen Suffix kann die gesendete Nachricht 124 Zeichen lang sein.
- **Beacon mit Sitzungs- und QRG-Sicherung:** Beacons starten nach jedem Programmstart und Profilwechsel ausgeschaltet, bleiben bei einem normalen ON4KST-Reconnect aber aktiv. Das Mindestintervall beträgt fünf Minuten. Jeder aktive Beacon überwacht die QRG seiner eigenen Kategorie: Manuelle Änderungen verschieben die Referenz, ein automatischer Sprung durch UCXLog oder Win-Test von mehr als 5 kHz schaltet nur den betroffenen Beacon aus. Der **MyBeacon**-Chip zeigt `off`, `1/2`, `on` und `FAILED` mit eindeutigen Verkehrsfarben; sein Tooltip nennt den Zustand oder letzten Abschaltgrund je Kategorie.
- **Neues Zuhause auf GitHub:** Das Projekt ist vom Konto `praktimarc` in die GitHub-Organisation [HamRadioOnline](https://github.com/HamRadioOnline) umgezogen und liegt jetzt unter [HamRadioOnline/kst4contest](https://github.com/HamRadioOnline/kst4contest). Alte Links auf das Repository, die Releases, die Issues und das Wiki leiten auf die neue Adresse weiter. Auch das Flatpak-Repository ist umgezogen und liegt jetzt unter `https://hamradioonline.github.io/kst4contest/`; bestehende Flatpak-Installationen aktualisieren über die Weiterleitung der alten Adresse weiter, neue Einrichtungen verwenden die neue Adresse aus der Installationsanleitung. Die AUR-Pakete zeigen ebenfalls auf die neue Adresse.
- **Zwischenspeicher der Geländeprofile getrennt:** Berechnete Geländeprofile liegen jetzt in der eigenen, gemeinsam genutzten Datei `terrainprofilecache.db` und werden nach Besitzer getrennt gespeichert. Bisher wurde der gesamte Zwischenspeicher gelöscht, sobald sich Rufzeichen oder Locator änderten; bei einem Profilwechsel wäre damit jedes berechnete Profil verloren gegangen.
+2 -2
View File
@@ -93,9 +93,9 @@ KST4Contest hält die benötigten Informationen zwischen diesen Schritten zusamm
Bei einer weitgehend festen CQ-QRG sollten `MYQRG` beziehungsweise `SECONDQRG` den tatsächlich verwendeten Frequenzen entsprechen. Eine aktivierte und tatsächlich liefernde TRX-Synchronisation kann `MYQRG` automatisch aktualisieren. Die Aktivierung allein reicht nicht: Vor dem Contest sollte mit einer realen Frequenzänderung geprüft werden, ob gültige Pakete ankommen. Ohne funktionierende automatische Quelle muss der Wert von Hand gepflegt werden.
Der Beacon kann die aktuelle QRG, den Locator und die Antennenrichtung regelmäßig im Chat veröffentlichen. Er muss nach jedem Programmstart oder Profilwechsel bewusst aktiviert werden. Eine manuell geänderte QRG wird zur neuen Referenz; meldet UCXLog oder Win-Test danach einen Sprung von mehr als 5 kHz, wird der betroffene Beacon automatisch ausgeschaltet.
Der Beacon kann die aktuelle QRG, den Locator und die Antennenrichtung regelmäßig im Chat veröffentlichen. Seine Variablen werden bei jedem Sendedurchlauf erneut ausgewertet.
Beim Scannen über mehrere Frequenzen verhindert diese Sicherung eine unbeabsichtigte Aussendung mit einer neuen Logger-QRG. Der Status-Tooltip zeigt, welche Kategorie abgeschaltet wurde und warum.
Wird während des CQ-Betriebs über mehrere Frequenzen gescannt, sollte der Beacon deaktiviert werden. Eine automatisch veröffentlichte QRG ist nur hilfreich, solange sie noch stimmt.
Shortcuts und Snippets sollten die regelmäßig benötigten Nachrichten abdecken, beispielsweise:
+5 -5
View File
@@ -301,7 +301,7 @@ Bei zwei gleichzeitig geöffneten Chat-Kategorien bleibt der Zusammenhang erhalt
Fehlt die QRG der betreffenden Kategorie, sendet KST4Contest keine inhaltslose Auskunft. Auch ein leerer oder protokollwidriger allgemeiner Antworttext wird nicht in die Sendequeue übernommen.
Automatische Antworten benötigen Grenzen. KST4Contest versieht sie daher mit `[KST4C Automsg]`, ignoriert entsprechend gekennzeichnete Nachrichten und begrenzt weitere Antworten an dasselbe vollständige Rufzeichen in derselben Kategorie auf eine Nachricht innerhalb von zwei Minuten. Der Schutz gilt gemeinsam für die allgemeine und die QRG-bezogene Antwort. Zusätzlich endet jede automatisch erzeugte Chatmeldung einschließlich `//VER`-Antworten und Beacons mit ` *a*`.
Automatische Antworten benötigen Grenzen. KST4Contest versieht sie daher mit `[KST4C Automsg]`, ignoriert entsprechend gekennzeichnete Nachrichten und begrenzt weitere Antworten an dasselbe vollständige Rufzeichen in derselben Kategorie auf eine Nachricht innerhalb von zwei Minuten. Der Schutz gilt gemeinsam für die allgemeine und die QRG-bezogene Antwort.
Die Sperrzeit wird nur nach einer vollständigen und lokal gültigen Antwort gestartet. Eine fehlende QRG oder ein verworfener Antworttext verhindert daher keine spätere gültige Antwort.
@@ -798,13 +798,13 @@ Die Timeline ist eine Vorschau. AirScout-Daten können sich ändern, und ein ein
KST4Contest kann wiederkehrende CQ-Nachrichten in den öffentlichen Chat senden. Der Beacon ist für längeres CQ-Rufen auf einer festen Frequenz gedacht: Die eigene QRG wird regelmäßig veröffentlicht, ohne dass derselbe Text von Hand wiederholt werden muss.
Beide Chat-Kategorien verwenden ein gemeinsames Intervall von mindestens fünf Minuten, besitzen aber jeweils einen eigenen Aktivierungsschalter und Nachrichtentext. Die Aktivierung gilt nur für die laufende Programmsitzung und muss nach einem Programmstart oder Profilwechsel erneut erfolgen. Ein ON4KST-Reconnect ändert sie nicht. Der zweite Beacon wird nur gesendet, wenn die zweite Kategorie in derselben ON4KST-Sitzung aktiviert und vollständig synchronisiert ist.
Beide Chat-Kategorien verwenden ein gemeinsames Intervall, besitzen aber jeweils einen eigenen Aktivierungsschalter und Nachrichtentext. Der zweite Beacon wird nur gesendet, wenn die zweite Kategorie in derselben ON4KST-Sitzung aktiviert und vollständig synchronisiert ist.
Globale Variablen wie `MYQRG`, `SECONDQRG`, `MYLOCATOR` oder `MYQTF` werden unmittelbar vor jeder Aussendung neu aufgelöst. Jeder aktive Beacon überwacht dabei die QRG seiner eigenen Kategorie. Eine manuelle Änderung verschiebt die Referenz; ein automatischer Sprung durch UCXLog oder Win-Test von mehr als 5 kHz schaltet den betroffenen Beacon aus.
Globale Variablen wie `MYQRG`, `SECONDQRG`, `MYLOCATOR` oder `MYQTF` werden unmittelbar vor jeder Aussendung neu aufgelöst. Eine zwischenzeitlich vom Logprogramm aktualisierte QRG kann dadurch bereits im nächsten Beacon erscheinen.
Vor dem Versand prüft KST4Contest den vollständig aufgelösten Beacon-Inhalt. Leere Inhalte, Zeilenumbrüche, das Protokoll-Trennzeichen `|` und Inhalte mit mehr als 120 Zeichen werden nicht gesendet. Danach wird ` *a*` angehängt; die gesendete Nachricht kann damit bis zu 124 Zeichen lang sein.
Vor dem Versand prüft KST4Contest den vollständig aufgelösten Nachrichtentext. Leere Nachrichten, Zeilenumbrüche, das Protokoll-Trennzeichen `|` und Texte mit mehr als 120 Zeichen werden nicht gesendet.
Der farbige **MyBeacon**-Chip zeigt aktive, teilweise aktive, ausgeschaltete und fehlgeschlagene Zustände. Sein Tooltip nennt den Zustand oder letzten Abschaltgrund je Kategorie.
Beim Absuchen oder häufigen Wechseln der QRG sollte der Beacon ausgeschaltet werden. Eine automatisch verbreitete Frequenz ist nur dann hilfreich, wenn dort tatsächlich jemand hört und ruft.
Konfiguration, Timer-Verhalten und verfügbare Variablen: [Konfiguration – Beacon Settings](de-Konfiguration#beacon-settings-automatischer-beacon).
+18 -28
View File
@@ -4,7 +4,7 @@
Nach dem ersten Start öffnet sich das **Einstellungsfenster** – dieses ist der zentrale Ausgangspunkt für alle Konfigurationen. Es empfiehlt sich, das Einstellungsfenster während des Betriebs geöffnet zu lassen (z. B. um den Beacon schnell ein- und auszuschalten).
> **Wichtig**: Änderungen im Einstellungsfenster wirken, sobald **Apply/Close prefs** oder **Save Settings** gedrückt wird; **Connect** übernimmt sie ebenfalls vorher. Wer mit offenen Änderungen das Fenster schließt, das Profil wechselt oder das Programm beendet, wird zuerst gefragt, ob sie übernommen oder verworfen werden sollen, oder kann zurück. Farben, Sprache, die Anmeldedaten im Reiter **Station** und die beiden Beacon-Aktivierungsschalter wirken sofort.
> **Wichtig**: Änderungen im Einstellungsfenster wirken, sobald **Apply/Close prefs** oder **Save Settings** gedrückt wird; **Connect** übernimmt sie ebenfalls vorher. Wer mit offenen Änderungen das Fenster schließt, das Profil wechselt oder das Programm beendet, wird zuerst gefragt, ob sie übernommen oder verworfen werden sollen, oder kann zurück. Farben, Sprache und die Anmeldedaten im Reiter **Station** wirken sofort.
>
> Fachliche Einstellungen mit **„Save Settings"** sichern, wenn sie beim nächsten Start wieder gelten sollen. Layoutänderungen wie Fenstergrößen, Divider-Positionen und Tabellenbreiten speichert KST4Contest automatisch. Die gemeinsame Datei liegt unter Linux und macOS in `~/.praktiKST/preferences.xml` und unter Windows in `%USERPROFILE%\.praktiKST\preferences.xml` (bzw. `C:\Users\<Benutzername>\.praktiKST\preferences.xml`).
@@ -135,7 +135,7 @@ Dedizierter Netzwerk-Erkenner für Win-Test. KST4Contest empfängt und verarbeit
## TRX-Sync-Einstellungen
Die TRX-Synchronisation übernimmt die aktuelle Frequenz aus dem Logprogramm und stellt sie in KST4Contest als eigene QRG bereit. Ohne SO2R ist das `MYQRG` der ersten Chat-Kategorie; mit SO2R kann Gerät 2 getrennt `SECONDQRG` aktualisieren. QSO- und Frequenzsynchronisation verwenden teilweise denselben UDP-Empfänger, sind funktional aber voneinander getrennt: Ein empfangenes `RadioInfo`-Paket markiert keine Station als gearbeitet, und ein QSO-Paket ändert nicht automatisch die eigene QRG.
Die TRX-Synchronisation übernimmt die aktuelle Frequenz aus dem Logprogramm und stellt sie in KST4Contest als eigene QRG der ersten Chat-Kategorie bereit. QSO- und Frequenzsynchronisation verwenden teilweise denselben UDP-Empfänger, sind funktional aber voneinander getrennt: Ein empfangenes `RadioInfo`-Paket markiert keine Station als gearbeitet, und ein QSO-Paket ändert nicht automatisch die eigene QRG.
![Einstellungen für die TRX-Synchronisation](client_settings_window_trxsync.png)
@@ -153,11 +153,11 @@ Wird der gemeinsame UDP-Port geändert, muss KST4Contest neu gestartet werden. E
### Welche QRG wird aktualisiert?
Ohne SO2R aktualisieren beide automatischen Quellen ausschließlich `MYQRG`. Das ist die eigene QRG der ersten beziehungsweise primären Chat-Kategorie; `SECONDQRG` bleibt unabhängig und kann von Hand eingetragen werden.
Beide automatischen Quellen aktualisieren ausschließlich `MYQRG`. Das ist die eigene QRG der ersten beziehungsweise primären Chat-Kategorie.
Mit SO2R ordnet KST4Contest die Pakete einem Gerät zu: Gerät 1 aktualisiert `MYQRG`, Gerät 2 `SECONDQRG`. Die genaue Zuordnung steht unter [SO2R: zwei Funkgeräte getrennt führen](#so2r-zwei-funkgeräte-getrennt-führen).
Bei aktiviertem zweiten Chat bleibt dessen QRG davon unabhängig. Sie wird nicht aus den empfangenen TRX-Paketen abgeleitet und steht als `SECONDQRG` zur Verfügung. Dadurch kann beispielsweise die erste Kategorie automatisch der Frequenz des Logprogramms folgen, während für die zweite Kategorie eine eigene QRG von Hand eingetragen wird.
Sobald mindestens eine automatische QRG-Quelle aktiviert ist und einen gültigen Wert liefert, folgt das zugeordnete QRG-Feld im Hauptfenster der empfangenen Frequenz. Bleiben die erwarteten Pakete aus, sollte die Schnittstelle vor dem Contest geprüft werden. Eine manuelle Eingabe bleibt möglich und gilt für die Beacon-Sicherung als bewusste neue Referenz; ein späteres Logger-Paket wird gegen diesen Wert geprüft.
Sobald mindestens eine automatische QRG-Quelle aktiviert ist und einen gültigen Wert liefert, folgt das QRG-Feld der ersten Kategorie im Hauptfenster der empfangenen Frequenz. Bleiben die erwarteten Pakete aus, sollte die Schnittstelle vor dem Contest geprüft werden. Eine manuelle Eingabe in dieses Feld ist möglich, wenn sowohl der allgemeine RadioInfo-Listener als auch die Win-Test-STATUS-Synchronisation deaktiviert sind.
### Haupt- oder Pass-Frequenz aus Win-Test
@@ -176,7 +176,7 @@ Die Frequenzen werden einheitlich im KST4Contest-Format dargestellt, beispielswe
10368.100.00
```
Die Werte werden erst beim Auflösen des Nachrichtentextes eingesetzt. Bei normalen Nachrichten steht eine Logger-Änderung sofort zur Verfügung. Ein aktiver Beacon verwendet dagegen seine QRG-Referenz: Ein automatischer Sprung um mehr als 5 kHz schaltet den betroffenen Beacon aus. Einzelheiten stehen unter [Beacon Settings](#beacon-settings-automatischer-beacon).
Die Werte werden erst beim Auflösen des Nachrichtentextes eingesetzt. Ändert das Logprogramm zwischen zwei Beacon-Läufen die Frequenz, verwendet die nächste Nachricht bereits den aktualisierten Wert.
Die eigene QRG kann außerdem als Fallback für die Übergabe eines Skeds an Win-Test verwendet werden. Das geschieht nur, wenn die QRG auswertbar ist und zum ausdrücklich ausgewählten Sked-Band gehört. Einzelheiten stehen unter [Log-Synchronisation](de-Log-Synchronisation#skeds-an-win-test-übergeben).
@@ -603,13 +603,9 @@ KST4Contest verwendet einen gemeinsamen Timer für beide Chat-Kategorien. Aktivi
Sind beide Beacons aktiviert, werden sie beim selben Timer-Lauf nacheinander in ihren jeweiligen Kategorien gesendet. Der zweite Beacon wird nur berücksichtigt, wenn die zweite Kategorie in derselben ON4KST-Sitzung aktiviert und vollständig synchronisiert ist.
Die beiden Aktivierungsschalter wirken sofort auf den laufenden Timer. Sie starten weder den Countdown neu noch senden sie unmittelbar eine Nachricht; der nächste reguläre Timer-Lauf prüft den aktuellen Zustand. Die Aktivierung gilt bewusst nur für die laufende Programmsitzung: Nach jedem Programmstart und Profilwechsel sind beide Beacons ausgeschaltet. Ein normaler ON4KST-Reconnect innerhalb derselben Programmsitzung lässt den Zustand dagegen unverändert. Nachrichtentexte und Intervall folgen weiterhin der normalen Apply-/Save-Logik.
Der Status-Chip **MyBeacon** im Hauptfenster fasst beide nutzbaren Kategorien zusammen: **off** bedeutet kein aktiver Beacon, **1/2** genau eine von zwei aktiven Kategorien und **on** alle derzeit nutzbaren Kategorien. Ein Klick auf den Chip schaltet alle nutzbaren Beacons gemeinsam ein oder aus. Ist der zweite Chat deaktiviert, ändert der Chip nur den Beacon der Hauptkategorie. **off** erscheint mit roter Schrift, **1/2** und **on** dauerhaft grün. Bei gemeldeter Aktivität blitzt der aktive Chip kurz orange auf. **FAILED** überschreibt diese Anzeige dauerhaft mit rotem Hintergrund und weißer Schrift; der orange Aktivitätsblitz wird dann unterdrückt. Der Tooltip nennt für jede Kategorie den aktuellen Zustand oder den letzten allgemeinen Abschaltgrund.
### Intervall und Timer-Verhalten
Das Intervall wird in ganzen Minuten angegeben. Der kleinste zulässige Wert beträgt fünf Minuten. Kleinere Werte aus einer älteren Konfiguration werden beim Laden auf fünf Minuten angehoben.
Das Intervall wird in ganzen Minuten angegeben. Der kleinste zulässige Wert ist eine Minute.
Nach dem Aufbau der Chat-Verbindung prüft KST4Contest die Beacons erstmals nach ungefähr zehn Sekunden. Anschließend gilt das eingestellte Intervall.
@@ -635,19 +631,15 @@ Eine mögliche Nachricht für die erste Chat-Kategorie ist:
calling cq at MYQRGSHORT, ant MYQTF deg, loc MYLOCATOR
```
KST4Contest hängt an jede gesendete Beacon-Nachricht automatisch das feste Suffix ` *a*` an. Es gehört deshalb nicht in das konfigurierte Template.
Für den zweiten Chat muss `SECONDQRG` verwendet werden, wenn dessen Frequenz von der ersten Kategorie abweicht:
```text
calling cq at SECONDQRG, ant MYQTF deg, loc MYLOCATOR
```
Die Variablen werden bei jedem Timer-Lauf neu aufgelöst. `MYQRG` und `MYQRGSHORT` benötigen immer eine gültige QRG der ersten Chat-Kategorie, `SECONDQRG` immer eine gültige QRG der zweiten Kategorie. Diese Zuordnung gilt unabhängig davon, in welchem der beiden Beacon-Texte die Variable steht.
Die Variablen werden bei jedem Timer-Lauf neu aufgelöst. Ändert die Logsoftware zwischenzeitlich die in `MYQRG` gespeicherte Frequenz, verwendet bereits der nächste Beacon den aktualisierten Wert. Das Template selbst muss dafür nicht geändert werden.
Enthält ein Beacon-Text eine solche QRG-Variable, kann der betreffende Beacon nur mit gültigem zugeordnetem QRG-Wert aktiviert bleiben. Fehlt der Wert oder ist er ungültig, bleibt nur dieser Beacon ausgeschaltet beziehungsweise wird ausgeschaltet; der Tooltip nennt den Grund. Ein Beacon-Text ohne QRG-Variable darf dagegen auch ohne vorhandene QRG aktiviert werden.
Beim Einschalten merkt sich jeder Beacon die gültige QRG seiner eigenen Kategorie als Referenz. Ist noch keine gültige eigene QRG vorhanden und enthält der Text keine QRG-Variable, wird die erste später manuell oder vom Logger gemeldete gültige Frequenz zur Referenz. Eine manuelle QRG-Änderung gilt als bewusste Bedienung und verschiebt die Referenz auf den neuen Wert. Ändert UCXLog oder Win-Test die zugeordnete QRG später um mehr als 5 kHz gegenüber dieser Referenz, schaltet KST4Contest den betreffenden Beacon automatisch aus. Genau 5 kHz sind noch zulässig. Ohne SO2R betrifft eine automatische Logger-QRG nur den Beacon der Hauptkategorie; mit SO2R wird die zweite QRG und damit der zweite Beacon getrennt behandelt.
`MYQRG` und `MYQRGSHORT` beziehen sich immer auf die erste Chat-Kategorie. Die Auswahl oder Aktivierung des zweiten Chats ändert diese Zuordnung nicht.
Stationsbezogene Variablen wie `QRZNAME`, `FIRSTAP` oder `SECONDAP` benötigen eine ausgewählte Gegenstation. Da ein öffentlicher Beacon keine bestimmte Station adressiert, werden diese Variablen im Beacon nicht aufgelöst.
@@ -655,16 +647,16 @@ Stationsbezogene Variablen wie `QRZNAME`, `FIRSTAP` oder `SECONDAP` benötigen e
KST4Contest prüft sowohl das eingetragene Template als auch den nach der Variablenauflösung tatsächlich zu sendenden Text.
Für den aufgelösten Beacon-Inhalt vor dem festen Suffix gelten folgende Bedingungen:
Für Beacon-Nachrichten gelten folgende Bedingungen:
- Er darf nicht leer sein.
- Der endgültige Nachrichtentext darf nicht leer sein.
- Er darf höchstens 120 Zeichen enthalten.
- Das Protokoll-Trennzeichen `|` ist nicht zulässig.
- Zeilenumbrüche sind nicht zulässig.
KST4Contest hängt anschließend ` *a*` an. Die tatsächlich gesendete Beacon-Nachricht darf damit höchstens 124 Zeichen lang sein. Eine ungültige Eingabe wird nicht als neue Beacon-Konfiguration übernommen. Wird ein Template erst durch eine spätere Variablenauflösung ungültig, beispielsweise weil der aufgelöste Inhalt länger als 120 Zeichen ist, wird dieser Beacon-Lauf ausgelassen.
Eine ungültige Eingabe wird nicht als neue Beacon-Konfiguration übernommen. Wird ein Template erst durch eine spätere Variablenauflösung ungültig, beispielsweise weil der aufgelöste Text länger als 120 Zeichen ist, wird dieser Beacon-Lauf ausgelassen.
Ein Template mit einer QRG-Variable kann gespeichert werden, bevor eine passende QRG vorhanden ist; der betroffene Beacon lässt sich dann aber nicht aktivieren. Wird eine benötigte QRG später ungültig, wird ein bereits aktiver Beacon ausgeschaltet. Enthält das Template keine QRG-Variable, löscht eine ungültige eigene QRG lediglich die Referenz und der Beacon bleibt aktiv.
Ein Template, das ausschließlich aus einer momentan noch leeren globalen Variable besteht, kann gespeichert werden. Das ist beispielsweise beim Start möglich, bevor die erste QRG vom Logprogramm empfangen wurde. Solange die Variable keinen verwendbaren Inhalt liefert, sendet KST4Contest jedoch keine leere Nachricht.
### Wann sollte der Beacon ausgeschaltet werden?
@@ -672,7 +664,7 @@ Der Beacon ist nur dann hilfreich, wenn seine QRG-Angabe zum tatsächlichen Betr
Im Klartext: Solange auf einer festen QRG CQ gerufen wird, spart der Beacon Arbeit. Beim „Schleichen“ über das Band sollte er ausgeschaltet werden.
Änderungen wirken während der laufenden Verbindung. **Save Settings** speichert Texte und Intervall für den nächsten Programmstart. Die Aktivierung wird absichtlich nicht gespeichert und muss in jeder Programmsitzung erneut erfolgen.
Änderungen wirken während der laufenden Verbindung. Damit Aktivierung, Texte und Intervall auch nach dem nächsten Programmstart erhalten bleiben, anschließend **Save Settings** verwenden.
---
@@ -694,12 +686,12 @@ Eine zweckmäßige Nachricht ist beispielsweise:
Sri, I am not taking part in this contest. No skeds.
```
Das Präfix `[KST4C Automsg]` und das feste Suffix ` *a*` müssen nicht in das Eingabefeld geschrieben werden. KST4Contest ergänzt beides automatisch.
Das Präfix `[KST4C Automsg]` muss nicht in das Eingabefeld geschrieben werden. KST4Contest ergänzt es automatisch.
Die beim Empfänger sichtbare Nachricht lautet daher beispielsweise:
```text
[KST4C Automsg] Sri, I am not taking part in this contest. No skeds. *a*
[KST4C Automsg] Sri, I am not taking part in this contest. No skeds.
```
Die eingegangene Privatnachricht bleibt sichtbar. Die Funktion blockiert oder verwirft keine Anfrage, sondern erspart lediglich die wiederholte manuelle Antwort.
@@ -730,7 +722,7 @@ Die Antwort enthält ausschließlich die QRG der Kategorie, in der die Anfrage e
Eine mögliche Antwort lautet:
```text
[KST4C Automsg] QRG is: 144.300.00 *a*
[KST4C Automsg] QRG is: 144.300.00
```
Die Werte stammen aus denselben QRG-Feldern, die auch von `MYQRG` und `SECONDQRG` verwendet werden. Die Haupt-QRG kann manuell eingetragen oder durch die [TRX-Synchronisation](#trx-sync-einstellungen) aktualisiert werden. Für die zweite Kategorie wird der dort konfigurierte beziehungsweise manuell eingetragene Wert verwendet; mit SO2R schreibt Funkgerät 2 dieses Feld (`SECONDQRG`).
@@ -766,7 +758,7 @@ Das vorhandene Bild `client_settings_window_messagehandling.png` zeigt die neue
### Schutz vor wiederholten Antworten
Jede automatische Antwort trägt das feste Präfix:
Jede automatisch erzeugte Nachricht trägt das feste Präfix:
```text
[KST4C Automsg]
@@ -774,8 +766,6 @@ Jede automatische Antwort trägt das feste Präfix:
Die allgemeine und die QRG-bezogene Antwort reagieren nicht auf Nachrichten, die dieses Präfix bereits enthalten. Dadurch beantworten sich zwei entsprechend arbeitende Clients nicht gegenseitig in einer Schleife.
Zusätzlich endet jede von KST4Contest automatisch erzeugte Chatmeldung mit ` *a*`. Das gilt für allgemeine und QRG-bezogene Antworten, `//VER`-Antworten sowie beide Beacons. Das Suffix wird immer angehängt, auch wenn der konfigurierte Text bereits damit endet. Manuell gesendete Nachrichten und interne ON4KST-Steuerframes bleiben unverändert.
Zusätzlich gilt eine gemeinsame Sperrzeit von zwei Minuten für beide Antwortarten. Die Sperre wird getrennt nach vollständigem Rufzeichen und Chat-Kategorie geführt.
Daraus folgt:
+3 -7
View File
@@ -305,20 +305,16 @@ Verwendet die zweite Chat-Kategorie eine andere QRG, muss deren Vorlage `SECONDQ
calling cq at SECONDQRG, ant MYQTF deg, loc MYLOCATOR
```
Die globalen Variablen werden bei jedem Timer-Lauf erneut ausgewertet. `MYQRG` und `MYQRGSHORT` benötigen immer eine gültige QRG der Hauptkategorie, `SECONDQRG` immer eine gültige QRG der zweiten Kategorie – unabhängig davon, in welcher Beacon-Vorlage sie stehen. Fehlt eine benötigte QRG, lässt sich nur der betroffene Beacon nicht aktivieren beziehungsweise wird ausgeschaltet. Eine Vorlage ohne QRG-Variable darf auch ohne vorhandene QRG aktiviert werden.
Die globalen Variablen werden bei jedem Timer-Lauf erneut ausgewertet. Eine inzwischen vom Logprogramm aktualisierte QRG kann dadurch bereits in der nächsten Beacon-Nachricht erscheinen.
Beim Einschalten merkt sich jeder Beacon die QRG seiner eigenen Kategorie. Eine manuelle QRG-Änderung verschiebt diese Referenz. Ändert UCXLog oder Win-Test die zugeordnete QRG später um mehr als 5 kHz, schaltet KST4Contest den betreffenden Beacon automatisch aus, statt die neue Frequenz unbemerkt in die nächste Aussendung zu übernehmen. Ist beim Einschalten noch keine eigene QRG vorhanden, wird die erste später gültig eingegebene oder empfangene Frequenz zur Referenz.
Der vollständig aufgelöste Beacon-Inhalt vor dem festen Suffix ` *a*`:
Der vollständig aufgelöste Beacon-Text:
- muss mindestens ein gültiges Zeichen enthalten,
- darf höchstens 120 Zeichen lang sein,
- darf das Protokoll-Trennzeichen `|` nicht enthalten und
- darf keine Zeilenumbrüche enthalten.
KST4Contest hängt das Suffix anschließend automatisch an. Die tatsächlich gesendete Beacon-Nachricht kann deshalb bis zu 124 Zeichen lang sein.
Ist der aufgelöste Text beim vorgesehenen Versand aus einem anderen Grund leer oder ungültig, wird der betreffende Beacon-Lauf ausgelassen und der Status-Chip zeigt **FAILED**.
Ist der Text beim vorgesehenen Versand leer oder ungültig, wird der betreffende Beacon-Lauf ausgelassen.
Intervall, Aktivierung und Verhalten beider Kategorien sind unter [Konfiguration – Beacon Settings](de-Konfiguration#beacon-settings-automatischer-beacon) beschrieben.
-4
View File
@@ -40,10 +40,6 @@ Several operators sharing one computer can now use their own callsigns, locators
### Changed
- **Automatic chat messages marked consistently:** general and QRG-specific automatic replies, `//VER` replies and both beacons now end with ` *a*`. Automatic replies keep their existing `[KST4C Automsg]` prefix. Resolved beacon content remains limited to 120 characters; including the fixed suffix, the transmitted message may contain 124 characters.
- **Beacon session and QRG safeguards:** beacons start off after every program start and profile switch, but remain active across a normal ON4KST reconnect. The minimum interval is five minutes. Each active beacon monitors the QRG of its own category: manual changes move the reference, while an automatic UCXLog or Win-Test jump of more than 5 kHz disables only the affected beacon. The **MyBeacon** chip shows `off`, `1/2`, `on` and `FAILED` with clear traffic-light colours; its tooltip lists the state or last deactivation reason for each category.
- **New home on GitHub:** the project moved from the `praktimarc` account to the [HamRadioOnline](https://github.com/HamRadioOnline) GitHub organisation and now lives at [HamRadioOnline/kst4contest](https://github.com/HamRadioOnline/kst4contest). Old links to the repository, the releases, the issues and the wiki redirect to the new address. The Flatpak repository moved as well and now lives at `https://hamradioonline.github.io/kst4contest/`; existing Flatpak installations keep updating through the redirect of the old address, new setups use the new address from the installation manual. The AUR packages point to the new address too.
- **The terrain profile cache is separate:** computed terrain profiles now live in their own shared file `terrainprofilecache.db` and are stored per owner. Previously the whole cache was dropped whenever the callsign or locator changed, which would have discarded every computed profile on each profile switch.
+18 -28
View File
@@ -4,7 +4,7 @@
After the first start, the **settings window** opens – this is the central starting point for all configuration. It is recommended to keep the settings window open during operation (e.g. to quickly toggle the beacon on and off).
> **Important**: Changes in the settings window take effect when you click **Apply/Close prefs** or **Save Settings**; **Connect** applies them first as well. Closing the window, switching the operator profile or exiting with changes pending first asks whether to apply or discard them, or to go back. Colours, the language, the login data on the **Station** tab and both beacon enable settings take effect immediately.
> **Important**: Changes in the settings window take effect when you click **Apply/Close prefs** or **Save Settings**; **Connect** applies them first as well. Closing the window, switching the operator profile or exiting with changes pending first asks whether to apply or discard them, or to go back. Colours, the language and the login data on the **Station** tab take effect immediately.
>
> Use **Save Settings** for functional settings which should remain in effect after the next start. KST4Contest saves layout changes such as window sizes, divider positions and table-column widths automatically. The shared file is `~/.praktiKST/preferences.xml` on Linux and macOS and `%USERPROFILE%\.praktiKST\preferences.xml` (or `C:\Users\<Username>\.praktiKST\preferences.xml`) on Windows.
@@ -154,7 +154,7 @@ Configuration of the individual logging applications, band and locator handling,
## TRX Sync Settings
TRX synchronisation imports the current frequency from the logging application and makes it available as a local QRG in KST4Contest. Without SO2R this is `MYQRG` for the first chat category; with SO2R, radio 2 can update `SECONDQRG` separately. QSO and frequency synchronisation may use the same UDP receiver, but they remain separate functions: receiving a `RadioInfo` packet does not mark a station as worked, and receiving a QSO packet does not automatically change the local QRG.
TRX synchronisation imports the current frequency from the logging application and makes it available in KST4Contest as the local QRG of the first chat category. QSO and frequency synchronisation may use the same UDP receiver, but they remain separate functions: receiving a `RadioInfo` packet does not mark a station as worked, and receiving a QSO packet does not automatically change the local QRG.
![TRX synchronisation settings](client_settings_window_trxsync.png)
@@ -172,11 +172,11 @@ Restart KST4Contest after changing the shared UDP port. Changes to the two QRG-s
### Which QRG Is Updated?
Without SO2R, both automatic sources update `MYQRG` only. This is the local QRG of the first or primary chat category; `SECONDQRG` remains independent and can be entered manually.
Both automatic sources update `MYQRG` only. This is the local QRG of the first or primary chat category.
With SO2R, KST4Contest assigns packets to a radio: radio 1 updates `MYQRG`, while radio 2 updates `SECONDQRG`. The exact assignment is described under [SO2R: Keeping Two Radios Apart](#so2r-keeping-two-radios-apart).
If a second chat is enabled, its QRG remains independent. It is not derived from incoming TRX packets and is available through `SECONDQRG`. The first category can therefore follow the logging application's frequency automatically while a separate QRG is entered manually for the second category.
When at least one automatic QRG source is enabled and supplies a valid value, the assigned QRG field in the main window follows the received frequency. If the expected packets do not arrive, verify the interface before the contest. Manual entry remains possible and is treated as the deliberate new reference for beacon safety; a later logger packet is compared with that value.
When at least one automatic QRG source is enabled and supplies a valid value, the first category's QRG field in the main window follows the received frequency. If the expected packets do not arrive, verify the interface before the contest. Manual entry is available when both the general RadioInfo listener and Win-Test STATUS synchronisation are disabled.
### Main or Pass Frequency from Win-Test
@@ -220,7 +220,7 @@ The synchronised QRG can be used in every text processed by the common KST4Conte
- snippets, and
- automatic beacons.
`MYQRG` contains the complete QRG of the first chat category. `MYQRGSHORT` uses only its first seven characters. `SECONDQRG` contains the QRG of the second chat category, whether it was entered manually or supplied by radio 2 with SO2R enabled.
`MYQRG` contains the complete QRG of the first chat category. `MYQRGSHORT` uses only its first seven characters. `SECONDQRG` contains the separately entered QRG of the second chat category.
Examples:
@@ -603,13 +603,9 @@ KST4Contest uses one shared timer for both chat categories. Each category nevert
When both beacons are enabled, they are sent one after the other in their respective categories during the same timer run. The second beacon is only considered while the second category is enabled and fully synchronised in the same ON4KST session.
Both enable settings affect the running timer immediately. They neither restart the countdown nor send a message straight away; the next regular timer run checks the current state. Activation deliberately lasts only for the current program session: both beacons are off after every program start and profile switch. A normal ON4KST reconnect within the same program session preserves their state. Message templates and the interval continue to follow the normal Apply/Save workflow.
The **MyBeacon** status chip in the main window combines the currently usable categories: **off** means that no beacon is enabled, **1/2** that one of two categories is enabled, and **on** that every usable category is enabled. Clicking the chip enables or disables all usable beacons together. If the second chat is disabled, the chip changes only the primary-category beacon. **off** uses red text, while **1/2** and **on** remain green. The active chip briefly flashes orange when activity is reported. **FAILED** overrides this with a persistent red background and white text; no orange activity flash is shown then. The tooltip lists the current state or last general deactivation reason for each category.
### Interval and timer behaviour
The interval is entered in whole minutes. The minimum permitted value is five minutes. Smaller values from an older configuration are raised to five minutes when loaded.
The interval is entered in whole minutes. The minimum permitted value is one minute.
After the chat connection has been established, KST4Contest performs the first beacon check after approximately ten seconds. The configured interval applies after that initial check.
@@ -635,19 +631,15 @@ A suitable message for the primary chat category is:
calling cq at MYQRGSHORT, ant MYQTF deg, loc MYLOCATOR
```
KST4Contest automatically appends the fixed suffix ` *a*` to every transmitted beacon message. It therefore does not belong in the configured template.
Use `SECONDQRG` for the second chat if it operates on a different frequency:
```text
calling cq at SECONDQRG, ant MYQTF deg, loc MYLOCATOR
```
Variables are resolved again on every timer run. `MYQRG` and `MYQRGSHORT` always require a valid primary-category QRG, while `SECONDQRG` always requires a valid secondary-category QRG. This assignment is independent of which beacon template contains the variable.
Variables are resolved again on every timer run. If the logging software changes the QRG stored in `MYQRG`, the next beacon can already contain the updated value. The message template does not have to be edited.
If a beacon template contains one of these QRG variables, that beacon can remain enabled only while the assigned QRG is valid. If the value is missing or invalid, only that beacon remains off or is disabled, and its tooltip states the reason. A template without a QRG variable may still be enabled when no QRG is available.
When enabled, each beacon remembers the valid QRG of its own category as its reference. If no valid own QRG exists yet and the template has no QRG variable, the first valid frequency reported later by the user or logger becomes the reference. A manual QRG change is treated as intentional and moves the reference to the new value. If UCXLog or Win-Test later changes the assigned QRG by more than 5 kHz from that reference, KST4Contest disables the affected beacon automatically. Exactly 5 kHz is still permitted. Without SO2R, an automatic logger QRG affects only the primary beacon; with SO2R, the secondary QRG and beacon are handled separately.
`MYQRG` and `MYQRGSHORT` always refer to the primary chat category. Enabling or selecting the second chat does not change this assignment.
Station-specific variables such as `QRZNAME`, `FIRSTAP` and `SECONDAP` require a selected remote station. A public beacon has no such destination, so these variables are not resolved in beacon messages.
@@ -655,16 +647,16 @@ Station-specific variables such as `QRZNAME`, `FIRSTAP` and `SECONDAP` require a
KST4Contest validates both the configured template and the message which remains after all variables have been resolved.
The following restrictions apply to the resolved beacon content before the fixed suffix:
The following restrictions apply:
- It must not be empty.
- The final message must not be empty.
- It must not exceed 120 characters.
- The protocol separator `|` is not permitted.
- Line breaks are not permitted.
KST4Contest then appends ` *a*`, so the transmitted beacon message may contain up to 124 characters. An invalid entry is not accepted as the new beacon configuration. If a template becomes invalid only after resolving its variables, for example because the resolved content exceeds 120 characters, that beacon run is skipped.
An invalid entry is not accepted as the new beacon configuration. If a template becomes invalid only after resolving its variables, for example because the resulting text exceeds 120 characters, that beacon run is skipped.
A template containing a QRG variable may be stored before a matching QRG is available, but the affected beacon cannot then be enabled. If a required QRG becomes invalid later, an active beacon is disabled. If the template contains no QRG variable, an invalid own QRG only clears the reference and the beacon remains enabled.
A template which consists only of a temporarily empty global variable may still be stored. This can happen during startup before the first QRG has been received from the logger. KST4Contest does not send an empty message while the variable has no usable value.
### When should the beacon be disabled?
@@ -672,7 +664,7 @@ The beacon is useful only while its QRG matches the actual operation. Leaving it
In plain terms: the beacon saves work while calling CQ on a fixed QRG. It should be disabled while moving around the band.
Changes take effect during the current connection. **Save Settings** stores the message templates and interval for the next program start. Activation is deliberately not stored and must be performed again in every program session.
Changes take effect during the current connection. Use **Save Settings** afterwards to retain the enable settings, message templates and interval for the next program start.
---
@@ -694,12 +686,12 @@ A suitable message is:
Sri, I am not taking part in this contest. No skeds.
```
Do not add the `[KST4C Automsg]` prefix or the fixed ` *a*` suffix to the configured text. KST4Contest inserts both automatically.
Do not add the `[KST4C Automsg]` prefix to the configured text. KST4Contest inserts it automatically.
The message received by the remote station may therefore be:
```text
[KST4C Automsg] Sri, I am not taking part in this contest. No skeds. *a*
[KST4C Automsg] Sri, I am not taking part in this contest. No skeds.
```
The incoming private message remains visible. The function neither blocks nor discards the request; it merely avoids entering the same answer repeatedly.
@@ -730,7 +722,7 @@ The answer contains only the QRG belonging to the category in which the request
A possible reply is:
```text
[KST4C Automsg] QRG is: 144.300.00 *a*
[KST4C Automsg] QRG is: 144.300.00
```
The values come from the same QRG fields used by `MYQRG` and `SECONDQRG`. The primary QRG may be entered manually or updated through [TRX synchronisation](#trx-sync-settings). The second category uses the value configured or entered for that category; with SO2R, radio 2 writes this field (`SECONDQRG`).
@@ -766,7 +758,7 @@ The existing `client_settings_window_messagehandling.png` screenshot does not ye
### Protection against repeated replies
Every automatic reply contains the fixed prefix:
Every automatically generated reply contains the fixed prefix:
```text
[KST4C Automsg]
@@ -774,8 +766,6 @@ Every automatic reply contains the fixed prefix:
The general and QRG-specific functions ignore messages which already contain this prefix. This prevents two clients with automatic replies enabled from answering each other indefinitely.
In addition, every chat message generated automatically by KST4Contest ends with ` *a*`. This applies to general and QRG-specific replies, `//VER` replies and both beacons. The suffix is always appended, even if the configured text already ends with it. Manually sent messages and internal ON4KST control frames remain unchanged.
A common two-minute cooldown additionally applies to both reply types. The cooldown is tracked separately for each complete callsign and chat category.
This means:
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more