Add a setup assistant for unconfigured profiles (#174)

A profile without a callsign of its own now starts in a setup assistant instead
of the twelve-tab settings window. It asks for name, login, locator, bands and
chat category, and optionally for antenna and power, log program, rotator and
AirScout. Login and station can each be taken from another configured profile.

The assistant runs in startRuntime after the profile is resolved and before the
ChatController exists. It works on a ChatPreferences of its own, writes
preferences.xml, and the runtime then reads that file like any stored setting.
It never touches a running session. From the Options menu the runtime is torn
down first and the same profile restarted with the assistant in front.

A station set up anew gets only what the operator confirmed: the bundled
template has several integrations enabled, and the assistant switches off what
was not chosen and names it in its summary. A station left unchanged is written
page by page, only for pages the operator opened. A taken station is the whole
station, every setter listed in wizard-station-setters.txt; a test fails when a
new ChatPreferences setter is classified in neither list.

Changes outside the assistant:
- ChatPreferences.readPreferencesFromXmlFile() returns false when the file could
  not be read or parsed, or its root element is not praktiKST. It reads on as
  before, and its two existing callers ignore the return value.
- ApplicationRuntimeLauncher.switchProfile refuses a second switch while one is
  in progress.
- The Log synch tab's file chooser takes an optional owner dialog.

The design and its reasons are in
docs/superpowers/specs/2026-11-18-einrichtungsassistent-design.md.

Written-by: Claude Fable 5.2
Written-by: DeepSeek V4 Pro
Written-by: Gemini 4 Hydrogen (Antigravity)
Written-by: Codex (GPT-6.2 Sol)
This commit is contained in:
Rsclub2_2 authored and GitHub committed 2026-11-18 23:16:52 +01:00
1 parent b0960a3f04
commit 1dd0139e10
36 files changed
+5768 -25

No files matched your search

@@ -460,7 +460,7 @@ column.score=Wertung
monitor.title=Cluster & Fremd-QSOs
monitor.dxCluster=DX-Cluster
profiles.createFailed=Das Profil konnte nicht angelegt werden. Die Profilliste konnte nicht geschrieben werden.
profiles.createdWithoutCredentials=Das Profil „{0}" wurde ohne Rufzeichen und Passwort angelegt. Nach dem Wechsel zu diesem Profil beides im Reiter „Station" eintragen.
profiles.createdWithoutCredentials=Das Profil „{0}" wurde ohne Rufzeichen und Passwort angelegt. Nach dem Wechsel zu diesem Profil fragt der Einrichtungsassistent beides ab.
profiles.duplicateFailed=Das Profil konnte nicht dupliziert werden.
profiles.rootNotDeletable=Das Standardprofil verwendet die Dateien der Installation selbst und kann nicht gelöscht werden.
profiles.activeNotDeletable=Das gerade benutzte Profil kann nicht gelöscht werden. Zuerst zu einem anderen Profil wechseln.
@@ -495,3 +495,95 @@ profiles.unknown=unbekannt
profiles.copyOf=Kopie von {0}
profiles.sharedDatabase=gemeinsame Stationsdatenbank
profiles.ownDatabase=eigene Datenbank
wizard.title=Einrichtungsassistent
wizard.later=Später
wizard.back=Zurück
wizard.next=Weiter
wizard.finish=Fertig
wizard.save=Speichern
wizard.saveAndConnect=Speichern und verbinden
wizard.change=Ändern
wizard.saveFailed=Die Einstellungen konnten nicht geschrieben werden. Es wurde nichts geändert.
wizard.missing=Es fehlen noch Pflichtangaben. Über „Ändern" ergänzen.
wizard.entry.title=Woher kommen die Angaben?
wizard.entry.lead=Für Anmeldung und Station getrennt wählen.
wizard.entry.login=Anmeldung (Rufzeichen, Passwort)
wizard.entry.station=Station (Locator, Bänder, Chatkategorie)
wizard.source.loginNew=Anmeldung neu eingeben
wizard.source.loginKeep=Anmeldung unverändert lassen ({0})
wizard.source.stationNew=Station neu einrichten
wizard.source.stationKeep=Station unverändert lassen (Locator {0})
wizard.personal.title=Persönliches
wizard.personal.lead=Gehört zum Operator.
wizard.personal.name=Anzeigename im Chat
wizard.personal.nameInvalid=Der Name darf kein Zeichen | enthalten.
wizard.login.title=Anmeldung bei ON4KST
wizard.login.lead=Die Zugangsdaten deines ON4KST-Kontos.
wizard.login.callsignInvalid=Das sieht nicht nach einem Rufzeichen aus.
wizard.login.passwordInvalid=Das Passwort darf nicht mit einem Leerzeichen beginnen oder enden und kein Zeichen | enthalten.
wizard.site.title=Standort und Bänder
wizard.site.lead=Gehört zur Station, nicht zum Operator.
wizard.site.locatorInvalid=Sechsstelliger Maidenhead-Locator, zum Beispiel JO50AA.
wizard.site.bands=Aktive Bänder
wizard.site.bandsHint=Aus den Bändern wird keine Frequenz abgeleitet.
wizard.site.categorySuggestion=Vorschlag aus den Bändern: {0}
wizard.site.secondChat=Zweiten Chat öffnen
wizard.summary.title=Zusammenfassung
wizard.summary.lead=Erst „Speichern" schreibt in die Einstellungsdatei.
wizard.summary.personal=Persönliches
wizard.summary.login=Anmeldung
wizard.summary.station=Station
wizard.summary.bands=Bänder
wizard.summary.none=keine
wizard.summary.passwordSet=gesetzt
menu.setupWizard=Einrichtungsassistent...
alert.setupWizardTitle=Einrichtungsassistent
alert.setupWizardQuestion=Sitzung beenden und den Einrichtungsassistenten starten?
alert.setupWizardBody=Die ON4KST-Verbindung wird geschlossen, und alle Fenster werden nach dem Assistenten neu aufgebaut. Für einzelne Änderungen im laufenden Betrieb ist das Einstellungsfenster da.
dialog.startSetupWizard=Assistent starten
wizard.antenna.title=Antenne und Leistung
wizard.antenna.lead=Freiwillig. Die Werte speisen die Pfadanalyse und den Antennensektor auf der Karte; für den Chat braucht sie niemand.
wizard.antenna.aslHint=Standorthöhe leer lassen, dann entscheidet das Höhenmodell.
wizard.log.title=Logprogramm
wizard.log.lead=Woher kommen deine gearbeiteten Stationen?
wizard.log.none=Keines, kein Abgleich
wizard.log.wintest=Win-Test
wizard.log.udp=UCXLog, DXLog.net, N1MM+ oder QARTEST
wizard.log.file=Eine Logdatei
wizard.log.qrgFollow=Eigene Frequenz aus dem Logprogramm übernehmen
wizard.log.clusterServer=Spots über den lokalen DX-Cluster-Server an das Logprogramm geben
wizard.log.incomplete=Die Angaben zu diesem Logprogramm sind unvollständig oder außerhalb des Bereichs.
wizard.gear.title=Rotor und AirScout
wizard.gear.lead=Nur was wirklich vorhanden ist.
wizard.gear.rotator=PSTRotator wird benutzt
wizard.gear.airScout=AirScout wird benutzt
wizard.gear.incomplete=Die Angaben auf dieser Seite sind unvollständig oder außerhalb des Bereichs.
wizard.switch.secondChat=Zweitchat
wizard.switch.logWintest=Win-Test-Abgleich
wizard.switch.logUdp=Netzwerk-Logabgleich
wizard.switch.logFile=Logdatei-Abgleich
wizard.switch.qrgFollow=Frequenz aus dem Logprogramm
wizard.switch.clusterServer=DX-Cluster-Server
wizard.switch.rotator=PSTRotator
wizard.switch.airScout=AirScout
wizard.summary.antenna=Antenne und Leistung
wizard.summary.log=Logprogramm
wizard.summary.gear=Rotor und AirScout
wizard.summary.qrgFollow=Eigene Frequenz aus dem Logprogramm
wizard.summary.clusterServer=DX-Cluster-Server
wizard.summary.yes=ja
wizard.summary.no=nein
wizard.summary.switchedOff=Wird abgeschaltet: {0}.
wizard.summary.logSeveral=In diesem Profil sind mehrere Logquellen eingeschaltet. Im Einstellungsfenster ändern.
wizard.source.loginTake=Anmeldung von Profil „{0}" übernehmen ({1})
wizard.source.loginTakeFrom=Anmeldung von einem anderen Profil übernehmen
wizard.source.stationTake=Station von Profil „{0}" übernehmen (Locator {1})
wizard.source.stationTakeFrom=Station von einem anderen Profil übernehmen
wizard.entry.donor=Profil
wizard.summary.takenFrom=Übernommen von Profil „{0}"
wizard.switch.so2r=SO2R
wizard.switch.rotator2=PSTRotator 2
wizard.summary.fallbackBand=Ausweichband für Spots
@@ -469,7 +469,7 @@ column.score=Score
monitor.title=Cluster & QSO of the other
monitor.dxCluster=DX cluster
profiles.createFailed=The profile could not be created. The profile registry could not be written.
profiles.createdWithoutCredentials=The profile "{0}" was created without callsign and password. Enter them on the Station tab after switching to it.
profiles.createdWithoutCredentials=The profile "{0}" was created without callsign and password. After switching to it, the setup assistant asks for both.
profiles.duplicateFailed=The profile could not be duplicated.
profiles.rootNotDeletable=The default profile uses the files of the installation itself and cannot be deleted.
profiles.activeNotDeletable=The profile currently in use cannot be deleted. Switch to another profile first.
@@ -504,3 +504,95 @@ profiles.unknown=unknown
profiles.copyOf=Copy of {0}
profiles.sharedDatabase=common station database
profiles.ownDatabase=own database
wizard.title=Setup assistant
wizard.later=Later
wizard.back=Back
wizard.next=Next
wizard.finish=Finish
wizard.save=Save
wizard.saveAndConnect=Save and connect
wizard.change=Change
wizard.saveFailed=The settings could not be written. Nothing was changed.
wizard.missing=Some required entries are still missing. Use Change to complete them.
wizard.entry.title=Where do the entries come from?
wizard.entry.lead=Choose separately for login and station.
wizard.entry.login=Login (callsign, password)
wizard.entry.station=Station (locator, bands, chat category)
wizard.source.loginNew=Enter a new login
wizard.source.loginKeep=Leave the login unchanged ({0})
wizard.source.stationNew=Set up a new station
wizard.source.stationKeep=Leave the station unchanged (locator {0})
wizard.personal.title=Personal
wizard.personal.lead=Belongs to the operator.
wizard.personal.name=Name shown in the chat
wizard.personal.nameInvalid=The name must not contain a | character.
wizard.login.title=ON4KST login
wizard.login.lead=The credentials of your ON4KST account.
wizard.login.callsignInvalid=This does not look like a callsign.
wizard.login.passwordInvalid=The password must not begin or end with a blank and must not contain a | character.
wizard.site.title=Location and bands
wizard.site.lead=Belongs to the station, not to the operator.
wizard.site.locatorInvalid=Six-character Maidenhead locator, for example JO50AA.
wizard.site.bands=Active bands
wizard.site.bandsHint=No frequency is derived from the bands.
wizard.site.categorySuggestion=Suggested from the bands: {0}
wizard.site.secondChat=Open a second chat
wizard.summary.title=Summary
wizard.summary.lead=Nothing is written until you save.
wizard.summary.personal=Personal
wizard.summary.login=Login
wizard.summary.station=Station
wizard.summary.bands=Bands
wizard.summary.none=none
wizard.summary.passwordSet=set
menu.setupWizard=Setup assistant...
alert.setupWizardTitle=Setup assistant
alert.setupWizardQuestion=End the session and start the setup assistant?
alert.setupWizardBody=The ON4KST connection is closed and all windows are rebuilt after the assistant. For single changes during operation use the settings window.
dialog.startSetupWizard=Start assistant
wizard.antenna.title=Antenna and power
wizard.antenna.lead=Optional. These values feed the path analysis and the antenna sector on the map; the chat does not need them.
wizard.antenna.aslHint=Leave the site elevation empty to let the elevation model decide.
wizard.log.title=Log program
wizard.log.lead=Where do your worked stations come from?
wizard.log.none=None, no synchronisation
wizard.log.wintest=Win-Test
wizard.log.udp=UCXLog, DXLog.net, N1MM+ or QARTEST
wizard.log.file=A log file
wizard.log.qrgFollow=Take my own frequency from the log program
wizard.log.clusterServer=Pass spots to the log program through the local DX cluster server
wizard.log.incomplete=The entries for this log program are incomplete or out of range.
wizard.gear.title=Rotator and AirScout
wizard.gear.lead=Only what is really there.
wizard.gear.rotator=PSTRotator is in use
wizard.gear.airScout=AirScout is in use
wizard.gear.incomplete=The entries on this page are incomplete or out of range.
wizard.switch.secondChat=second chat
wizard.switch.logWintest=Win-Test synchronisation
wizard.switch.logUdp=network log synchronisation
wizard.switch.logFile=log file polling
wizard.switch.qrgFollow=frequency from the log program
wizard.switch.clusterServer=DX cluster server
wizard.switch.rotator=PSTRotator
wizard.switch.airScout=AirScout
wizard.summary.antenna=Antenna and power
wizard.summary.log=Log program
wizard.summary.gear=Rotator and AirScout
wizard.summary.qrgFollow=Own frequency from the log program
wizard.summary.clusterServer=DX cluster server
wizard.summary.yes=yes
wizard.summary.no=no
wizard.summary.switchedOff=Will be switched off: {0}.
wizard.summary.logSeveral=Several log sources are enabled in this profile. Change them in the settings window.
wizard.source.loginTake=Take the login from profile "{0}" ({1})
wizard.source.loginTakeFrom=Take the login from another profile
wizard.source.stationTake=Take the station from profile "{0}" (locator {1})
wizard.source.stationTakeFrom=Take the station from another profile
wizard.entry.donor=Profile
wizard.summary.takenFrom=Taken from profile "{0}"
wizard.switch.so2r=SO2R
wizard.switch.rotator2=PSTRotator 2
wizard.summary.fallbackBand=Fallback band for spots
@@ -4,6 +4,7 @@ import kst4contest.controller.ActiveOperatorProfile;
import kst4contest.controller.OperatorProfilePaths;
import kst4contest.controller.OperatorProfileStore;
import kst4contest.model.OperatorProfile;
import kst4contest.model.OperatorProfileSelection;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -24,6 +25,20 @@ public final class ApplicationRuntimeLauncher {
private static Kst4ContestApplication currentRuntime;
/**
* Whether the next runtime start shows the setup wizard although the profile is set up.
* Set by the menu entry and cleared by the start that honours it.
*/
private static final java.util.concurrent.atomic.AtomicBoolean SETUP_WIZARD_REQUESTED =
new java.util.concurrent.atomic.AtomicBoolean(false);
/**
* Guards {@link #switchProfile(OperatorProfile)} against re-entry while window teardown
* inside {@link Kst4ContestApplication#shutdownRuntime()} is still pumping events.
*/
private static final java.util.concurrent.atomic.AtomicBoolean SWITCH_IN_PROGRESS =
new java.util.concurrent.atomic.AtomicBoolean(false);
private ApplicationRuntimeLauncher() {
// Utility class.
}
@@ -61,14 +76,100 @@ public final class ApplicationRuntimeLauncher {
System.exit(0);
}
/** Asks the next runtime start to show the setup wizard. */
static void requestSetupWizard() {
SETUP_WIZARD_REQUESTED.set(true);
}
/**
* Tells a starting runtime whether the wizard was asked for, and forgets the request.
*
* @return true exactly once per request
*/
static boolean consumeSetupWizardRequest() {
return SETUP_WIZARD_REQUESTED.getAndSet(false);
}
/**
* Marks a profile switch as in progress if none is currently running.
*
* @return true if this call obtained the mark
*/
static boolean beginSwitch() {
return SWITCH_IN_PROGRESS.compareAndSet(false, true);
}
/** Clears the in-progress mark of a profile switch. */
static void endSwitch() {
SWITCH_IN_PROGRESS.set(false);
}
/**
* Rebuilds the runtime of the active profile with the setup wizard in front of it.
*
* <p>The running runtime is torn down first and the wizard shown afterwards, not the
* other way round: a runtime shutting down flushes its pending layout write, and that
* must not land on the file the wizard has just written.</p>
*
* <p>The wizard is requested only once this call owns the switch. A call refused
* because a switch is already under way therefore leaves that switch's request alone:
* clearing it would let the running switch end the session and then start without the
* wizard it was made for.</p>
*
* @return true if the new runtime was built
*/
public static boolean rerunSetupWizard() {
OperatorProfileSelection active = ActiveOperatorProfile.get();
if (active == null) {
return false;
}
if (!beginSwitch()) {
return false;
}
try {
requestSetupWizard();
boolean switched = false;
try {
switched = performSwitch(active.getProfile());
} finally {
if (!switched) {
// The request is this call's own, and no start consumed it.
consumeSetupWizardRequest();
}
}
return switched;
} finally {
endSwitch();
}
}
/**
* Replaces the running runtime with one bound to another operator profile.
*
* @param targetProfile profile to activate
* @return true if the new runtime was built
* @return true if the new runtime was built; false also when another switch is
* already under way
*/
public static boolean switchProfile(final OperatorProfile targetProfile) {
if (!beginSwitch()) {
return false;
}
try {
return performSwitch(targetProfile);
} finally {
endSwitch();
}
}
/** The switch itself. The caller holds the switch-in-progress mark. */
private static boolean performSwitch(final OperatorProfile targetProfile) {
if (targetProfile == null) {
return false;
}
@@ -54,6 +54,11 @@ public final class ComposeMenuActions implements MainMenuActions {
application.runOnUi(application::menuActionToggleSettingsWindow);
}
@Override
public void openSetupWizard() {
application.runOnUi(application::menuActionOpenSetupWizard);
}
@Override
public void toggleMonitorWindow() {
application.runOnUi(application::menuActionToggleMonitorWindow);
@@ -42,6 +42,8 @@ import kst4contest.view.compose.SettingsWindow;
import kst4contest.controller.ScoreService;
import kst4contest.view.compose.SettingsWindow;
import kst4contest.controller.On4KstConnectionState;
import kst4contest.view.compose.wizard.SetupWizardLauncher;
import kst4contest.view.compose.wizard.SetupWizardOutcome;
import java.io.File;
import java.io.IOException;
@@ -2177,6 +2179,17 @@ public class Kst4ContestApplication implements StatusUpdateListener, SettingsHos
return;
}
/*
* The setup wizard, before anything of this profile's runtime exists. It writes
* preferences.xml and the ChatController built below reads it like any stored
* setting, so there is no running session to bring up to date and no reload.
* Blocks until the wizard is closed; see SetupWizardWindow for why that is safe on
* either thread this method is called from.
*/
SetupWizardOutcome setupWizardOutcome = SetupWizardLauncher.runIfNeeded(
ActiveOperatorProfile.get().getPreferencesRelativeFileName(),
ApplicationRuntimeLauncher.consumeSetupWizardRequest());
ApplicationRuntimeLauncher.setCurrent(this);
ApplicationFileUtils.copyResourceIfRequired(ApplicationConstants.APPLICATION_NAME, STYLE_DEFAULTCSSDAY_RESOURCE, STYLE_DEFAULTCSSDAY_FILE);
@@ -2297,6 +2310,15 @@ public class Kst4ContestApplication implements StatusUpdateListener, SettingsHos
//initialize the timeline
uiDispatcher.runOnUi(this::updateTimelineVisuals);
/*
* "Save and connect" in the setup wizard. Here and not earlier: connecting needs the
* runtime this method has just finished building. The same path as File -> Connect,
* so a refused or failed connection is reported the way it is there.
*/
if (setupWizardOutcome == SetupWizardOutcome.SAVED_AND_CONNECT) {
uiDispatcher.runOnUi(this::menuActionConnect);
}
/*
* Replaces Application.stop(), which only JavaFX ever called. This covers a SIGTERM
* and a closing terminal; the ordinary exit still goes through
@@ -4024,6 +4046,27 @@ public class Kst4ContestApplication implements StatusUpdateListener, SettingsHos
}
}
/**
* Options -> setup assistant. Rebuilds the runtime of the active profile with the wizard
* in front of it, which costs the running session; hence the question, and hence the
* settings edits are settled first, as before a profile switch.
*/
void menuActionOpenSetupWizard() {
SettingsWindow.settleThen(() -> {
boolean confirmed = ComposeAlert.confirm(
kst4contest.view.i18n.CurrentStrings.get().getAlertSetupWizardTitle(),
kst4contest.view.i18n.CurrentStrings.get().getAlertSetupWizardQuestion(),
kst4contest.view.i18n.CurrentStrings.get().getAlertSetupWizardBody(),
kst4contest.view.i18n.CurrentStrings.get().getDialogStartSetupWizard(),
kst4contest.view.i18n.CurrentStrings.get().getDialogCancel(),
chatcontroller.getChatPreferences().isGUI_darkModeActive());
if (confirmed) {
ApplicationRuntimeLauncher.rerunSetupWizard();
}
});
}
/** Windows -> open or close the cluster / stranger-QSO monitor window. */
void menuActionToggleMonitorWindow() {
if (MonitorWindow.isOpen()) {
@@ -55,6 +55,9 @@ interface MainMenuActions {
fun setQrgAsNameInChat()
fun toggleAwayState()
fun toggleSettingsWindow()
/** Ends the session after asking and runs the setup wizard for the active profile. */
fun openSetupWizard()
fun toggleMonitorWindow()
fun toggleStationMap()
fun useDarkDesign()
@@ -87,6 +87,11 @@ fun mainMenuModel(
enabled = true,
actions::toggleSettingsWindow,
),
/*
* Always usable, like the profile switch: it rebuilds the runtime and asks before
* it gives the session up.
*/
MenuEntry.Item(strings.menuSetupWizard, state.canSwitchProfile, actions::openSetupWizard),
),
),
MenuSpec(
@@ -18,10 +18,12 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.AwtWindow
import java.awt.Dialog
import java.awt.FileDialog
import java.awt.Frame
import java.io.File
@@ -125,34 +127,51 @@ internal fun FilePathRow(
}
}
/**
* The AWT file dialog, opened from Compose. The JavaFX chooser started in the user's
* home directory and a cancelled choice kept the stored path — both are preserved.
*/
/** The modal owner that keeps the native file chooser accessible when opened from the wizard. */
val LocalFileDialogOwner = staticCompositionLocalOf<Dialog?> { null }
/** The AWT file dialog, opened from Compose. */
@Composable
private fun FileChooserDialog(title: String, onResult: (String?) -> Unit) {
val owner = LocalFileDialogOwner.current
AwtWindow(
create = {
object : FileDialog(null as Frame?, title, LOAD) {
override fun setVisible(visible: Boolean) {
if (visible) {
directory = System.getProperty("user.home")
}
super.setVisible(visible)
if (visible) {
val chosenName = file
onResult(
if (chosenName == null) null
else File(directory ?: "", chosenName).absolutePath
)
}
}
}
if (owner == null) LogFileDialog(title, onResult) else LogFileDialog(owner, title, onResult)
},
dispose = FileDialog::dispose,
)
}
/**
* The JavaFX chooser started in the user's home directory and a cancelled choice kept the
* stored path. Both constructors share that behaviour.
*/
private class LogFileDialog : FileDialog {
private val onResult: (String?) -> Unit
constructor(title: String, onResult: (String?) -> Unit) : super(null as Frame?, title, LOAD) {
this.onResult = onResult
}
constructor(owner: Dialog, title: String, onResult: (String?) -> Unit) : super(owner, title, LOAD) {
this.onResult = onResult
}
override fun setVisible(visible: Boolean) {
if (visible) {
directory = System.getProperty("user.home")
}
super.setVisible(visible)
if (visible) {
val chosenName = file
onResult(
if (chosenName == null) null
else File(directory ?: "", chosenName).absolutePath
)
}
}
}
/** The label column width the shared form controls use, so the tabs line up. */
@Composable
private fun LabelledRow(label: String, field: @Composable () -> Unit) {
@@ -0,0 +1,492 @@
package kst4contest.view.compose.wizard
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import kst4contest.model.ChatCategory
import kst4contest.view.compose.Density
import kst4contest.view.compose.Form
import kst4contest.view.compose.LocalSettingsDraft
import kst4contest.view.compose.SettingsDraft
import kst4contest.view.compose.tabs.FilePathRow
import kst4contest.view.i18n.LanguageStore
import kst4contest.view.i18n.LocalStrings
import kst4contest.view.i18n.SYSTEM_LANGUAGE
import kst4contest.view.i18n.Strings
import kst4contest.view.i18n.Translations
/**
* A language store for the wizard: a choice takes effect on screen at once and is kept in
* the wizard's answers, not in the preferences. "Later" therefore stores no language, and
* the runtime built afterwards puts the stored one back in force.
*/
fun wizardLanguageStore(state: SetupWizardState): LanguageStore =
LanguageStore(storedLanguage = { state.language }, storeLanguage = { state.language = it })
/** The name a chat category carries in the pickers, the one the Station tab shows. */
private fun categoryName(number: Int): String = ChatCategory(number).getChatCategoryName(number)
/**
* The wizard's pages and its button row.
*
* All decisions are in [state]; this draws them. The texts are read from [languageStore] in
* the composition, so the language picker on the personal page switches the wizard itself.
*
* @param saveFailed whether the last Save could not write the file
* @param onLater the operator does not want to set up now; nothing is written
* @param onSave the operator saves; true when the session should be started afterwards
*/
@Composable
fun SetupWizardContent(
state: SetupWizardState,
languageStore: LanguageStore,
saveFailed: Boolean,
onLater: () -> Unit,
onSave: (connect: Boolean) -> Unit,
) {
val strings = languageStore.strings
// The draft only registers typed entries. Wizard answers are never staged or applied through it.
val typedEntries = remember { SettingsDraft() }
var typedEntryRefusals by remember { mutableStateOf(emptyList<String>()) }
fun withAcceptedTypedEntries(action: () -> Unit) {
val refusals = typedEntries.commitTypedEntries()
typedEntryRefusals = refusals
if (refusals.isEmpty()) action()
}
CompositionLocalProvider(LocalStrings provides strings, LocalSettingsDraft provides typedEntries) {
Surface(modifier = Modifier.fillMaxSize()) {
Column(modifier = Modifier.padding(15.dp)) {
Column(
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
when (state.page) {
WizardPage.ENTRY -> EntryPage(state, strings)
WizardPage.PERSONAL -> PersonalPage(state, strings, languageStore)
WizardPage.LOGIN -> LoginPage(state, strings)
WizardPage.SITE -> SitePage(state, strings)
WizardPage.ANTENNA -> AntennaPage(state.antenna, strings)
WizardPage.LOG -> LogPage(state.integrations, strings)
WizardPage.GEAR -> GearPage(state.integrations, strings)
WizardPage.SUMMARY -> SummaryPage(state, strings, saveFailed)
}
}
if (typedEntryRefusals.isNotEmpty()) {
Refusal(typedEntryRefusals.joinToString("\n"))
}
Row(
modifier = Modifier.fillMaxWidth().padding(top = 10.dp),
horizontalArrangement = Arrangement.spacedBy(Density.BUTTON_GAP),
) {
Form.button(strings.wizardLater, onClick = onLater)
Spacer(Modifier.weight(1f))
if (state.canGoBack) {
Form.button(strings.wizardBack, onClick = state::back)
}
if (state.page == WizardPage.SUMMARY) {
Form.button(strings.wizardSave, enabled = state.mandatoryComplete) {
withAcceptedTypedEntries { onSave(false) }
}
Form.button(
strings.wizardSaveAndConnect,
enabled = state.mandatoryComplete,
accented = true,
) { withAcceptedTypedEntries { onSave(true) } }
} else {
if (state.canFinish) {
Form.button(strings.wizardFinish) { withAcceptedTypedEntries(state::finish) }
}
Form.button(
strings.wizardNext,
enabled = state.canGoNext,
accented = true,
) { withAcceptedTypedEntries(state::next) }
}
}
}
}
}
}
@Composable
private fun Heading(title: String, lead: String) {
Text(title, style = MaterialTheme.typography.titleMedium)
Text(lead, style = MaterialTheme.typography.bodySmall)
}
@Composable
private fun Refusal(text: String) {
Text(text, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
}
@Composable
private fun RadioOption(label: String, selected: Boolean, onSelect: () -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.selectable(selected = selected, role = Role.RadioButton, onClick = onSelect)
.padding(vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(selected = selected, onClick = null)
Text(label, modifier = Modifier.padding(start = 6.dp))
}
}
@Composable
private fun EntryPage(state: SetupWizardState, strings: Strings) {
Heading(strings.wizardEntryTitle, strings.wizardEntryLead)
val oneDonor = state.donors.singleOrNull()
/* An axis with a single option is decided already and is not asked about. */
if (state.loginSources.size > 1) {
Form.section(strings.wizardEntryLogin) {
state.loginSources.forEach { source ->
RadioOption(
label = when (source) {
WizardSource.NEW -> strings.wizardSourceLoginNew
// One other profile is named in the option; several get a picker below.
WizardSource.TAKE ->
if (oneDonor != null) strings.wizardSourceLoginTake(oneDonor.displayName, oneDonor.callsign)
else strings.wizardSourceLoginTakeFrom
WizardSource.KEEP -> strings.wizardSourceLoginKeep(state.storedCallsign)
},
selected = state.loginSource == source,
onSelect = { state.chooseLoginSource(source) },
)
}
if (state.loginSource == WizardSource.TAKE && oneDonor == null) {
Form.choice(
label = strings.wizardEntryDonor,
items = state.donors,
selected = state.loginDonor,
describe = { "${it.displayName} (${it.callsign})" },
onSelect = state::chooseLoginDonor,
)
}
}
}
if (state.stationSources.size > 1) {
Form.section(strings.wizardEntryStation) {
state.stationSources.forEach { source ->
RadioOption(
label = when (source) {
WizardSource.NEW -> strings.wizardSourceStationNew
WizardSource.TAKE ->
if (oneDonor != null) strings.wizardSourceStationTake(oneDonor.displayName, oneDonor.locator)
else strings.wizardSourceStationTakeFrom
WizardSource.KEEP -> strings.wizardSourceStationKeep(state.storedLocator)
},
selected = state.stationSource == source,
onSelect = { state.chooseStationSource(source) },
)
}
if (state.stationSource == WizardSource.TAKE && oneDonor == null) {
Form.choice(
label = strings.wizardEntryDonor,
items = state.donors,
selected = state.stationDonor,
describe = { "${it.displayName} (${it.locator})" },
onSelect = state::chooseStationDonor,
)
}
}
}
}
@Composable
private fun PersonalPage(state: SetupWizardState, strings: Strings, languageStore: LanguageStore) {
Heading(strings.wizardPersonalTitle, strings.wizardPersonalLead)
Form.choice(
label = strings.guiLanguage,
items = listOf(SYSTEM_LANGUAGE) + Translations.BY_LANGUAGE.keys.sorted(),
selected = languageStore.stored,
// The code in capitals, as the GUI tab shows it.
describe = { code -> if (code == SYSTEM_LANGUAGE) strings.guiLanguageSystem else code.uppercase() },
onSelect = { languageStore.use(it) },
)
Form.text(strings.wizardPersonalName, state.name) { state.name = it }
if (state.nameRefused) Refusal(strings.wizardPersonalNameInvalid)
}
@Composable
private fun LoginPage(state: SetupWizardState, strings: Strings) {
Heading(strings.wizardLoginTitle, strings.wizardLoginLead)
Form.text(strings.stationCallsign, state.callsign) { state.callsign = it }
if (state.callsignRefused) Refusal(strings.wizardLoginCallsignInvalid)
Form.password(strings.stationPassword, state.password) { state.password = it }
if (state.passwordRefused) Refusal(strings.wizardLoginPasswordInvalid)
}
@Composable
private fun SitePage(state: SetupWizardState, strings: Strings) {
Heading(strings.wizardSiteTitle, strings.wizardSiteLead)
Form.text(strings.stationLocator, state.locator) { state.locator = it }
if (state.locatorRefused) Refusal(strings.wizardSiteLocatorInvalid)
Form.flowingSection(strings.wizardSiteBands) {
WizardBand.entries.forEach { band ->
Form.check(band.label, band in state.bands) { state.setBand(band, it) }
}
}
Text(strings.wizardSiteBandsHint, style = MaterialTheme.typography.bodySmall)
Form.choice(
label = strings.stationMainCategory,
items = SetupWizardState.CATEGORY_NUMBERS,
selected = state.category,
describe = ::categoryName,
onSelect = state::chooseCategory,
)
state.suggestedCategory?.let { suggested ->
Text(
strings.wizardSiteCategorySuggestion(categoryName(suggested)),
style = MaterialTheme.typography.bodySmall,
)
}
Form.check(strings.wizardSiteSecondChat, state.secondChat) { state.chooseSecondChat(it) }
if (state.secondChat) {
Form.choice(
label = strings.stationSecondCategory,
items = state.secondCategoryOptions,
selected = state.secondCategory,
describe = ::categoryName,
onSelect = { state.secondCategory = it },
)
}
}
/** The name a log program carries on its page and in the summary. */
private fun logProgramName(program: WizardLogProgram, strings: Strings): String = when (program) {
WizardLogProgram.NONE -> strings.wizardLogNone
WizardLogProgram.WINTEST -> strings.wizardLogWintest
WizardLogProgram.UDP -> strings.wizardLogUdp
WizardLogProgram.FILE -> strings.wizardLogFile
}
/** The name of something that will be switched off, for the summary's notice. */
private fun switchName(switch: WizardSwitch, strings: Strings): String = when (switch) {
WizardSwitch.SECOND_CHAT -> strings.wizardSwitchSecondChat
WizardSwitch.LOG_WINTEST -> strings.wizardSwitchLogWintest
WizardSwitch.LOG_UDP -> strings.wizardSwitchLogUdp
WizardSwitch.LOG_FILE -> strings.wizardSwitchLogFile
WizardSwitch.QRG_FOLLOW -> strings.wizardSwitchQrgFollow
WizardSwitch.CLUSTER_SERVER -> strings.wizardSwitchClusterServer
WizardSwitch.ROTATOR -> strings.wizardSwitchRotator
WizardSwitch.AIRSCOUT -> strings.wizardSwitchAirScout
WizardSwitch.SO2R -> strings.wizardSwitchSo2r
WizardSwitch.ROTATOR_2 -> strings.wizardSwitchRotator2
}
@Composable
private fun AntennaPage(antenna: WizardAntenna, strings: Strings) {
Heading(strings.wizardAntennaTitle, strings.wizardAntennaLead)
Form.decimal(strings.stationBeamWidth, antenna.beamWidthDeg, isValid = { it.isFinite() }) {
antenna.beamWidthDeg = it
}
Form.decimal(strings.stationOwnAntennaGain, antenna.gainDbi, isValid = { it.isFinite() }) {
antenna.gainDbi = it
}
Form.decimal(strings.stationOwnAntennaHeight, antenna.heightMeters, isValid = { it.isFinite() && it >= 0.0 }) {
antenna.heightMeters = it
}
Form.decimal(strings.stationOwnTxPower, antenna.txPowerWatts, isValid = { it.isFinite() }) {
antenna.txPowerWatts = it
}
Form.text(strings.stationOwnHeightAsl, antenna.heightAslText) { antenna.heightAslText = it }
if (antenna.heightAslRefused) {
Refusal(strings.stationInvalidOwnHeightAsl(antenna.heightAslText.trim()))
}
Text(strings.wizardAntennaAslHint, style = MaterialTheme.typography.bodySmall)
}
@Composable
private fun LogPage(integrations: WizardIntegrations, strings: Strings) {
Heading(strings.wizardLogTitle, strings.wizardLogLead)
WizardLogProgram.entries.forEach { program ->
RadioOption(
label = logProgramName(program, strings),
selected = integrations.logProgram == program,
onSelect = { integrations.chooseLogProgram(program) },
)
}
/* The details of a program appear only once it is chosen. */
when (integrations.logProgram) {
WizardLogProgram.WINTEST -> {
Form.int(strings.logSynchWinTestPort, integrations.wintestPort) { integrations.wintestPort = it }
Form.text(strings.logSynchWinTestStationName, integrations.wintestStationName) {
integrations.wintestStationName = it
}
}
WizardLogProgram.UDP ->
Form.int(strings.logSynchSharedPort, integrations.udpPort) { integrations.udpPort = it }
WizardLogProgram.FILE ->
FilePathRow(
label = strings.logSynchFileLabel,
value = integrations.filePath,
chooserTitle = strings.logSynchFileChooserTitle,
) { integrations.filePath = it }
WizardLogProgram.NONE -> Unit
}
if (!integrations.logComplete) Refusal(strings.wizardLogIncomplete)
if (integrations.networked) {
Form.check(strings.wizardLogQrgFollow, integrations.qrgFollow) { integrations.qrgFollow = it }
Form.check(strings.wizardLogClusterServer, integrations.clusterServer) { integrations.clusterServer = it }
// The settings tab's own words: an enabled source does not produce a frequency by itself.
Text(strings.trxSynchHint, style = MaterialTheme.typography.bodySmall)
}
}
@Composable
private fun GearPage(integrations: WizardIntegrations, strings: Strings) {
Heading(strings.wizardGearTitle, strings.wizardGearLead)
Form.check(strings.wizardGearRotator, integrations.rotator) { integrations.rotator = it }
if (integrations.rotator) {
Form.text(strings.stationRotatorHost, integrations.rotatorHost) { integrations.rotatorHost = it }
Form.int(strings.stationRotatorPort, integrations.rotatorPort) { integrations.rotatorPort = it }
if (integrations.rotatorPortClashes) {
Refusal(strings.stationRotator2PortClash(integrations.rotatorPort.toString()))
}
}
Form.check(strings.wizardGearAirScout, integrations.airScout) { integrations.airScout = it }
if (integrations.airScout) {
Form.int(strings.airscoutUdpPort, integrations.airScoutPort) { integrations.airScoutPort = it }
Form.text(strings.airscoutServerIdentifier, integrations.airScoutServerName) {
integrations.airScoutServerName = it
}
Form.text(strings.airscoutClientIdentifier, integrations.airScoutClientName) {
integrations.airScoutClientName = it
}
}
if (!integrations.gearComplete) Refusal(strings.wizardGearIncomplete)
}
@Composable
private fun SummaryRow(label: String, value: String) {
Form.labelledRow(label) { Text(value) }
}
@Composable
private fun SummaryPage(state: SetupWizardState, strings: Strings, saveFailed: Boolean) {
Heading(strings.wizardSummaryTitle, strings.wizardSummaryLead)
if (saveFailed) Refusal(strings.wizardSaveFailed)
if (!state.mandatoryComplete) Refusal(strings.wizardMissing)
if (state.switchedOff.isNotEmpty()) {
Text(strings.wizardSummarySwitchedOff(state.switchedOff.joinToString(", ") { switchName(it, strings) }))
}
Form.section(strings.wizardSummaryPersonal) {
SummaryRow(
strings.guiLanguage,
if (state.language == SYSTEM_LANGUAGE) strings.guiLanguageSystem else state.language.uppercase(),
)
SummaryRow(strings.wizardPersonalName, state.name.ifBlank { strings.wizardSummaryNone })
Form.button(strings.wizardChange) { state.edit(WizardPage.PERSONAL) }
}
Form.section(strings.wizardSummaryLogin) {
if (state.loginSource == WizardSource.TAKE) {
state.loginDonor?.let { Text(strings.wizardSummaryTakenFrom(it.displayName)) }
}
SummaryRow(strings.stationCallsign, state.callsign.ifBlank { strings.wizardSummaryNone })
// Never the password itself: the summary may be read over a shoulder.
SummaryRow(
strings.stationPassword,
if (state.password.isEmpty()) strings.wizardSummaryNone else strings.wizardSummaryPasswordSet,
)
Form.button(strings.wizardChange) { state.edit(WizardPage.LOGIN) }
}
Form.section(strings.wizardSummaryStation) {
if (state.stationSource == WizardSource.TAKE) {
state.stationDonor?.let { Text(strings.wizardSummaryTakenFrom(it.displayName)) }
}
SummaryRow(strings.stationLocator, state.locator.ifBlank { strings.wizardSummaryNone })
SummaryRow(
strings.wizardSummaryBands,
WizardBand.entries.filter { it in state.bands }.joinToString(", ") { it.label }
.ifEmpty { strings.wizardSummaryNone },
)
SummaryRow(
strings.wizardSummaryFallbackBand,
if (state.summaryFallbackBand.isBlank()) strings.wizardSummaryNone else "${state.summaryFallbackBand} MHz",
)
SummaryRow(
strings.stationMainCategory,
state.category?.let(::categoryName) ?: strings.wizardSummaryNone,
)
SummaryRow(
strings.stationSecondCategory,
state.secondCategory?.takeIf { state.secondChat }?.let(::categoryName) ?: strings.wizardSummaryNone,
)
Form.button(strings.wizardChange) { state.edit(WizardPage.SITE) }
}
val antenna = state.antenna
Form.section(strings.wizardSummaryAntenna) {
SummaryRow(strings.stationBeamWidth, antenna.beamWidthDeg.toString())
SummaryRow(strings.stationOwnAntennaGain, antenna.gainDbi.toString())
SummaryRow(strings.stationOwnAntennaHeight, antenna.heightMeters.toString())
SummaryRow(strings.stationOwnTxPower, antenna.txPowerWatts.toString())
SummaryRow(strings.stationOwnHeightAsl, antenna.heightAslText.trim().ifEmpty { strings.wizardSummaryNone })
Form.button(strings.wizardChange) { state.edit(WizardPage.ANTENNA) }
}
val integrations = state.integrations
val yesNo = { on: Boolean -> if (on) strings.wizardSummaryYes else strings.wizardSummaryNo }
Form.section(strings.wizardSummaryLog) {
if (state.logPageEditable) {
SummaryRow(strings.wizardSummaryLog, logProgramName(integrations.logProgram, strings))
SummaryRow(strings.wizardSummaryQrgFollow, yesNo(state.summaryQrgFollow))
SummaryRow(strings.wizardSummaryClusterServer, yesNo(state.summaryClusterServer))
Form.button(strings.wizardChange) { state.edit(WizardPage.LOG) }
} else {
/* Several sources are on; the page cannot show that and must not be opened. */
Text(strings.wizardSummaryLogSeveral)
}
}
Form.section(strings.wizardSummaryGear) {
SummaryRow(strings.wizardSwitchRotator, yesNo(integrations.rotator))
SummaryRow(strings.wizardSwitchAirScout, yesNo(integrations.airScout))
Form.button(strings.wizardChange) { state.edit(WizardPage.GEAR) }
}
}
@@ -0,0 +1,576 @@
package kst4contest.view.compose.wizard
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import kst4contest.controller.LoginConfiguration
import kst4contest.model.ChatCategory
import kst4contest.model.ChatPreferences
/** Where the answers of one group come from. */
enum class WizardSource {
/** Entered in the wizard, starting from the wizard's own empty values. */
NEW,
/** Taken from another, configured profile. */
TAKE,
/** What the profile already holds. */
KEEP,
}
/**
* Another profile the login or the station can be taken from.
*
* Its preferences are read from its file and never written: taking over fills the wizard's
* answers, and Save writes only into the active profile.
*
* @param prefs the other profile's preferences, already read from its file
*/
class WizardDonor(val profileId: String, val displayName: String, val prefs: ChatPreferences) {
/** For the entry page's label. */
val callsign: String = prefs.getStn_loginCallSign().orEmpty()
/** For the entry page's label. */
val locator: String = prefs.getStn_loginLocatorMainCat().orEmpty()
}
/** The pages, in the order they can appear. */
enum class WizardPage { ENTRY, PERSONAL, LOGIN, SITE, ANTENNA, LOG, GEAR, SUMMARY }
/**
* A band the station can be active on.
*
* The labels are amateur shorthand and deliberately not in the translation files.
*/
enum class WizardBand(
val label: String,
val megahertz: Int,
internal val isActive: (ChatPreferences) -> Boolean,
internal val setActive: (ChatPreferences, Boolean) -> Unit,
) {
B50("50 MHz", 50, { it.isStn_bandActive50() }, { p, on -> p.setStn_bandActive50(on) }),
B70("70 MHz", 70, { it.isStn_bandActive70() }, { p, on -> p.setStn_bandActive70(on) }),
B144("144 MHz", 144, { it.isStn_bandActive144() }, { p, on -> p.setStn_bandActive144(on) }),
B432("432 MHz", 432, { it.isStn_bandActive432() }, { p, on -> p.setStn_bandActive432(on) }),
B1240("1240 MHz", 1240, { it.isStn_bandActive1240() }, { p, on -> p.setStn_bandActive1240(on) }),
B2300("2300 MHz", 2300, { it.isStn_bandActive2300() }, { p, on -> p.setStn_bandActive2300(on) }),
B3400("3400 MHz", 3400, { it.isStn_bandActive3400() }, { p, on -> p.setStn_bandActive3400(on) }),
B5600("5600 MHz", 5600, { it.isStn_bandActive5600() }, { p, on -> p.setStn_bandActive5600(on) }),
B10G("10 GHz", 10000, { it.isStn_bandActive10G() }, { p, on -> p.setStn_bandActive10G(on) }),
}
/**
* The setup wizard's answers and the rules of its course, free of any window.
*
* It reads the preferences once, when it is built, and does not touch them again until
* [writeTo]: closing the wizard without saving therefore leaves the profile exactly as it
* was. The design is in `docs/superpowers/specs/2026-11-18-einrichtungsassistent-design.md`.
*
* The answers are Compose state, so a composition reading them follows; nothing else here
* depends on Compose.
*
* @param prefs the profile's preferences, already read from its file
* @param donors other configured profiles the login or the station can be taken from
*/
class SetupWizardState(prefs: ChatPreferences, val donors: List<WizardDonor> = emptyList()) {
/** What the pages of the station group show of one profile's preferences. */
private class StationSnapshot(prefs: ChatPreferences) {
val locator: String = prefs.getStn_loginLocatorMainCat().orEmpty()
val bands: Set<WizardBand> = WizardBand.entries.filter { it.isActive(prefs) }.toSet()
val category: Int? = prefs.getLoginChatCategoryMain()?.categoryNumber
val secondChat: Boolean = prefs.isLoginToSecondChatEnabled()
val secondCategory: Int? = prefs.getLoginChatCategorySecond()?.categoryNumber
}
/** Kept to rebuild the answers of the station group when its source changes. */
private val ownPrefs: ChatPreferences = prefs
private val ownStation = StationSnapshot(prefs)
/** What the own profile has on, whatever the answers are built from. */
private val ownSwitches: Set<WizardSwitch> = WizardIntegrations(prefs).let {
it.storedLogSwitches() + it.storedGearSwitches()
}
private val loginConfigured = !LoginConfiguration.isUnconfigured(prefs)
private val templateCredentials = LoginConfiguration.carriesTemplateCredentials(prefs)
/** The callsign the profile holds, for the label of "leave unchanged". */
val storedCallsign: String = prefs.getStn_loginCallSign().orEmpty()
private val storedPassword: String = prefs.getStn_loginPassword().orEmpty()
private val storedName: String = prefs.getStn_loginNameMainCat().orEmpty()
private val storedSecondName: String = prefs.getStn_loginNameSecondCat().orEmpty()
/** The locator the profile holds, for the label of "leave unchanged". */
val storedLocator: String = ownStation.locator
/** A login can be taken where another profile has one, and kept where an operator entered one. */
val loginSources: List<WizardSource> = buildList {
add(WizardSource.NEW)
if (donors.isNotEmpty()) add(WizardSource.TAKE)
if (loginConfigured) add(WizardSource.KEEP)
}
/**
* A station can be kept unless the profile is the untouched template: its locator and
* bands are then nobody's.
*/
val stationSources: List<WizardSource> = buildList {
add(WizardSource.NEW)
if (donors.isNotEmpty()) add(WizardSource.TAKE)
if (!templateCredentials) add(WizardSource.KEEP)
}
/** Whether there is anything to choose on the entry page. */
val hasEntryPage: Boolean = loginSources.size > 1 || stationSources.size > 1
var loginSource: WizardSource? by mutableStateOf(loginSources.singleOrNull())
private set
var stationSource: WizardSource? by mutableStateOf(stationSources.singleOrNull())
private set
/** The profile the login is taken from; decided with the source when there is only one. */
var loginDonor: WizardDonor? by mutableStateOf(null)
private set
/** The profile the station is taken from; decided with the source when there is only one. */
var stationDonor: WizardDonor? by mutableStateOf(null)
private set
/* A group is reloaded when its source or its donor changes, and only then. */
private var appliedLogin: Pair<WizardSource?, WizardDonor?> = null to null
private var appliedStation: Pair<WizardSource?, WizardDonor?> = null to null
/** The stored form of the language: a code, or empty for the system language. */
var language: String by mutableStateOf(prefs.getGuiOptions_language().orEmpty())
/** Empty on an unconfigured profile: its stored name is the template's or another operator's. */
var name: String by mutableStateOf(if (loginConfigured) storedName else "")
var callsign: String by mutableStateOf("")
var password: String by mutableStateOf("")
var locator: String by mutableStateOf("")
var bands: Set<WizardBand> by mutableStateOf(emptySet())
private set
var category: Int? by mutableStateOf(null)
private set
private var categoryChosenByOperator = false
var secondChat: Boolean by mutableStateOf(false)
private set
var secondCategory: Int? by mutableStateOf(null)
/**
* Antenna and power; always proposals from the profile the station comes from. Replaced
* when the station's source changes, so nothing typed under one choice shows under another.
*/
var antenna: WizardAntenna by mutableStateOf(WizardAntenna(prefs))
private set
/** Log program, rotator and AirScout; replaced like [antenna]. */
var integrations: WizardIntegrations by mutableStateOf(WizardIntegrations(prefs))
private set
private var loginShown by mutableStateOf(false)
/*
* One flag per page of the station group. A page that was shown in this run is written;
* a page that never was leaves its settings exactly as the profile has them. That is
* what keeps "leave the station unchanged" from touching integrations the wizard's
* simpler questions could not express.
*/
private var siteShown by mutableStateOf(false)
private var antennaShown by mutableStateOf(false)
private var logShown by mutableStateOf(false)
private var gearShown by mutableStateOf(false)
var page: WizardPage by mutableStateOf(if (hasEntryPage) WizardPage.ENTRY else WizardPage.PERSONAL)
private set
init {
if (!hasEntryPage) applySources()
}
fun chooseLoginSource(source: WizardSource) {
if (source !in loginSources) return
loginSource = source
if (source == WizardSource.TAKE && loginDonor == null) loginDonor = donors.singleOrNull()
}
fun chooseStationSource(source: WizardSource) {
if (source !in stationSources) return
stationSource = source
if (source == WizardSource.TAKE && stationDonor == null) stationDonor = donors.singleOrNull()
}
fun chooseLoginDonor(donor: WizardDonor) {
if (donor in donors) loginDonor = donor
}
fun chooseStationDonor(donor: WizardDonor) {
if (donor in donors) stationDonor = donor
}
/** A source is decided once it is chosen and, when it takes over, says from whom. */
private fun decided(source: WizardSource?, donor: WizardDonor?): Boolean =
source != null && (source != WizardSource.TAKE || donor != null)
/**
* Loads the answers of a group whose source or donor changed. A group whose choice is the
* one already applied is left alone, so going back to the entry page costs nothing typed.
*/
private fun applySources() {
val login = loginSource to loginDonor.takeIf { loginSource == WizardSource.TAKE }
if (login != appliedLogin) {
when (loginSource) {
WizardSource.KEEP -> {
callsign = storedCallsign
password = storedPassword
}
WizardSource.TAKE -> {
callsign = loginDonor?.prefs?.getStn_loginCallSign().orEmpty()
password = loginDonor?.prefs?.getStn_loginPassword().orEmpty()
}
else -> {
callsign = ""
password = ""
}
}
// Shown when entered anew, and when what was kept or taken cannot be saved as it is.
loginShown = loginSource == WizardSource.NEW || !loginComplete
appliedLogin = login
}
val station = stationSource to stationDonor.takeIf { stationSource == WizardSource.TAKE }
if (station != appliedStation) {
val fresh = stationSource == WizardSource.NEW
val base = if (stationSource == WizardSource.TAKE) stationDonor?.prefs ?: ownPrefs else ownPrefs
val snapshot = if (base === ownPrefs) ownStation else StationSnapshot(base)
locator = if (fresh) "" else snapshot.locator
bands = if (fresh) emptySet() else snapshot.bands
category = if (fresh) null else snapshot.category
secondChat = !fresh && snapshot.secondChat
secondCategory = if (fresh) null else snapshot.secondCategory
// A kept or taken category is an operator's; the suggestion must not replace it.
categoryChosenByOperator = !fresh
siteShown = fresh || !stationComplete
antennaShown = fresh
logShown = fresh
gearShown = fresh
// Built anew from the profile the station comes from; a new station gets only
// what the operator says yes to.
antenna = WizardAntenna(base)
integrations = WizardIntegrations(base).also { if (fresh) it.loadFresh() }
appliedStation = station
}
}
fun setBand(band: WizardBand, active: Boolean) {
bands = if (active) bands + band else bands - band
if (!categoryChosenByOperator) updateCategory(suggestCategory(bands))
}
/** What the bands suggest, shown beside the picker whatever is chosen. */
val suggestedCategory: Int?
get() = suggestCategory(bands)
fun chooseCategory(number: Int) {
categoryChosenByOperator = true
updateCategory(number)
}
private fun updateCategory(number: Int?) {
category = number
if (secondCategory == number) secondCategory = null
}
fun chooseSecondChat(enabled: Boolean) {
secondChat = enabled
}
/** The main category is left out, as the Station tab does. */
val secondCategoryOptions: List<Int>
get() = CATEGORY_NUMBERS.filter { it != category }
/** The pages of this run, in order. */
val pages: List<WizardPage>
get() = buildList {
if (hasEntryPage) add(WizardPage.ENTRY)
add(WizardPage.PERSONAL)
if (loginShown) add(WizardPage.LOGIN)
if (siteShown) add(WizardPage.SITE)
if (antennaShown) add(WizardPage.ANTENNA)
if (logShown) add(WizardPage.LOG)
if (gearShown) add(WizardPage.GEAR)
add(WizardPage.SUMMARY)
}
private val personalComplete: Boolean
get() = isStorableName(name)
private val loginComplete: Boolean
get() = isPlausibleCallsign(callsign) && isStorablePassword(password)
private val stationComplete: Boolean
get() = isLocator(locator) && bands.isNotEmpty() && category in CATEGORY_NUMBERS &&
(!secondChat || secondCategory in secondCategoryOptions)
/** The optional pages that are part of this run hold nothing that cannot be stored. */
private val shownOptionalPagesComplete: Boolean
get() = (!antennaShown || antenna.complete) &&
(!logShown || integrations.logComplete) &&
(!gearShown || integrations.gearComplete)
/**
* Whether the answers can be saved: everything the profile needs to log in is there, and
* no page of this run holds a value that cannot be stored. The optional pages need no
* answer, but an out-of-range port on one of them still blocks.
*/
val mandatoryComplete: Boolean
get() = personalComplete && loginComplete && stationComplete && shownOptionalPagesComplete
/** A chat name that was typed and cannot be sent. An empty or blank field is not an error yet. */
val nameRefused: Boolean
get() = name.isNotBlank() && !isStorableName(name)
/** A callsign that was typed and does not look like one. An empty field is not an error yet. */
val callsignRefused: Boolean
get() = callsign.isNotBlank() && !isPlausibleCallsign(callsign)
/** A password that was typed and cannot be stored or sent. An empty field is not an error yet. */
val passwordRefused: Boolean
get() = password.isNotEmpty() && !isStorablePassword(password)
/** A locator that was typed and is not one. An empty field is not an error yet. */
val locatorRefused: Boolean
get() = locator.isNotBlank() && !isLocator(locator)
val canGoNext: Boolean
get() = when (page) {
WizardPage.ENTRY -> decided(loginSource, loginDonor) && decided(stationSource, stationDonor)
WizardPage.PERSONAL -> personalComplete
WizardPage.LOGIN -> loginComplete
WizardPage.SITE -> stationComplete
WizardPage.ANTENNA -> antenna.complete
WizardPage.LOG -> integrations.logComplete
WizardPage.GEAR -> integrations.gearComplete
WizardPage.SUMMARY -> false
}
val canGoBack: Boolean
get() = pages.indexOf(page) > 0
/**
* Whether the remaining steps may be skipped. Only with every mandatory answer, because
* a summary that cannot be saved helps nobody.
*/
val canFinish: Boolean
get() = page != WizardPage.ENTRY && page != WizardPage.SUMMARY && mandatoryComplete
fun next() {
if (!canGoNext) return
if (page == WizardPage.ENTRY) applySources()
page = pages[pages.indexOf(page) + 1]
}
fun back() {
if (canGoBack) page = pages[pages.indexOf(page) - 1]
}
fun finish() {
if (canFinish) page = WizardPage.SUMMARY
}
/**
* Whether the log page may be opened: always once it is part of the run, and otherwise
* only if the profile has at most one log source on. The page knows one source; opened
* over several it would switch the others off.
*/
val logPageEditable: Boolean
get() = logShown || !integrations.severalStoredLogSources
/** Opens a step from the summary, also one this run skipped. */
fun edit(target: WizardPage) {
when (target) {
WizardPage.LOGIN -> loginShown = true
WizardPage.SITE -> siteShown = true
WizardPage.ANTENNA -> antennaShown = true
WizardPage.LOG -> if (logPageEditable) logShown = true else return
WizardPage.GEAR -> gearShown = true
WizardPage.PERSONAL -> Unit
WizardPage.ENTRY, WizardPage.SUMMARY -> return
}
page = target
}
/**
* Whether the frequency is taken from a log program after Save, for the summary: the
* page's answer once the log page is part of the run, and what the profile holds before.
* The two differ where a frequency source is on without its log source, which the
* settings window allows and the page cannot show.
*/
val summaryQrgFollow: Boolean
get() = if (logShown) integrations.qrgFollow else integrations.storedQrgFollow
/** Whether the DX cluster server runs after Save; see [summaryQrgFollow]. */
val summaryClusterServer: Boolean
get() = if (logShown) integrations.networked && integrations.clusterServer else integrations.storedClusterServer
/**
* The fallback band prefix the profile has after Save, for the summary: taken with the
* donor's station when chosen, otherwise left as the own profile holds it.
*/
val summaryFallbackBand: String
get() {
val sourcePrefs = stationDonor?.takeIf { stationSource == WizardSource.TAKE }?.prefs ?: ownPrefs
return sourcePrefs.getNotify_optionalFrequencyPrefix()?.get().orEmpty()
}
/** Rotator 2 only counts while SO2R uses it, as on the Station tab. */
private fun so2rSwitches(prefs: ChatPreferences): Set<WizardSwitch> = buildSet {
if (prefs.isTrxSynch_so2rEnabled()) {
add(WizardSwitch.SO2R)
if (prefs.isStn_pstRotator2Enabled()) add(WizardSwitch.ROTATOR_2)
}
}
/**
* What is on in the own profile and will be off after Save, for the summary. Always
* against the own profile: with a station taken from another one, that is what the
* operator loses, whatever the other profile had.
*
* A page that is not part of the run contributes what its profile holds -- the own one
* for a station left unchanged, the donor's for a station taken over. The wizard never
* writes SO2R or rotator 2 itself, so after Save they come from the donor when taking
* over a station, otherwise from the own profile.
*/
val switchedOff: List<WizardSwitch>
get() {
val neverAskedPrefs = stationDonor?.takeIf { stationSource == WizardSource.TAKE }?.prefs ?: ownPrefs
val after = buildSet {
if (secondChat) add(WizardSwitch.SECOND_CHAT)
addAll(if (logShown) integrations.answeredLogSwitches() else integrations.storedLogSwitches())
addAll(if (gearShown) integrations.answeredGearSwitches() else integrations.storedGearSwitches())
addAll(so2rSwitches(neverAskedPrefs))
}
val before = ownSwitches + so2rSwitches(ownPrefs) +
if (ownStation.secondChat) setOf(WizardSwitch.SECOND_CHAT) else emptySet()
return WizardSwitch.entries.filter { it in before && it !in after }
}
/**
* Puts the answers into [prefs] and writes its file.
*
* Everything the wizard did not ask about stays as [prefs] read it, because the whole
* file is read and written back. The callsign and the locator are stored as typed, the
* way the Station tab stores them; only surrounding blanks go.
*
* The second chat's name follows the first unless the operator had set it apart, and the
* second category is left alone while the second chat is off.
*
* Antenna, log program and equipment are written only for the pages that were part of
* this run.
*
* A station taken from another profile is copied whole before the answers are written.
*
* @return false when a mandatory answer is missing -- nothing is touched then -- or when
* the file could not be written
*/
fun writeTo(prefs: ChatPreferences): Boolean {
if (!mandatoryComplete) return false
val newName = name.trim()
prefs.setGuiOptions_language(language)
prefs.setStn_loginNameMainCat(newName)
if (storedSecondName.isBlank() || storedSecondName == storedName) {
prefs.setStn_loginNameSecondCat(newName)
}
prefs.setStn_loginCallSign(callsign.trim())
prefs.setStn_loginPassword(password)
// The whole station of the other profile first, also what no page asks about; the
// answers below then lie on top, so a taken value the operator changed wins.
if (stationSource == WizardSource.TAKE) {
stationDonor?.let { copyStation(it.prefs, prefs) }
}
prefs.setStn_loginLocatorMainCat(locator.trim())
WizardBand.entries.forEach { it.setActive(prefs, it in bands) }
prefs.setLoginChatCategoryMain(ChatCategory(requireNotNull(category)))
prefs.setLoginToSecondChatEnabled(secondChat)
if (secondChat) {
prefs.setLoginChatCategorySecond(ChatCategory(requireNotNull(secondCategory)))
}
if (antennaShown) antenna.writeTo(prefs)
if (logShown) integrations.writeLogTo(prefs)
if (gearShown) integrations.writeGearTo(prefs)
// A write that throws is a write that failed; the wizard must stay open either way.
return runCatching { prefs.writePreferencesToXmlFile() }.getOrDefault(false)
}
companion object {
/** The categories the pickers offer, the way the Station tab builds them. */
val CATEGORY_NUMBERS: List<Int> = ChatCategory(0).possibleCategoryNumbers.toList()
private val CALLSIGN = Regex("[A-Za-z0-9]+([-/][A-Za-z0-9]+)?")
private val LOCATOR = Regex("[A-Ra-r]{2}[0-9]{2}[A-Xa-x]{2}")
/**
* Whether a text can be a login callsign: letters and digits, at most one "-" or "/"
* suffix, and a base of three characters with a letter and a digit. Deliberately
* loose -- ON4KST decides what it accepts, this only catches a slip.
*/
fun isPlausibleCallsign(text: String): Boolean {
val trimmed = text.trim()
if (!CALLSIGN.matches(trimmed)) return false
val base = trimmed.substringBefore('-').substringBefore('/')
return base.length >= 3 && base.any(Char::isDigit) && base.any(Char::isLetter)
}
/** Whether a text is a six-character Maidenhead locator, in either case. */
fun isLocator(text: String): Boolean = LOCATOR.matches(text.trim())
/**
* Whether a password can be stored in preferences.xml and sent in an ON4KST login frame:
* not blank, free of surrounding whitespace (which the XML reader trims), and free of
* frame delimiters.
*/
fun isStorablePassword(text: String): Boolean =
text.isNotBlank() && text == text.trim() && '|' !in text && '\r' !in text && '\n' !in text
/**
* Whether a chat display name can be sent in an ON4KST frame: not blank and free of
* frame delimiters.
*/
fun isStorableName(text: String): Boolean =
text.isNotBlank() && '|' !in text && '\r' !in text && '\n' !in text
/**
* The chat category the lowest band belongs to: 1 for 50/70 MHz, 2 for 144/432 MHz,
* 3 above. Null without a band. A suggestion only -- the operator confirms it.
*/
fun suggestCategory(bands: Set<WizardBand>): Int? {
val lowest = bands.minOfOrNull { it.megahertz } ?: return null
return when {
lowest <= 70 -> ChatCategory.FIFTYSEVENTYMHz
lowest <= 432 -> ChatCategory.VUHF
else -> ChatCategory.MICROWAVE
}
}
}
}
@@ -0,0 +1,243 @@
package kst4contest.view.compose.wizard
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.awt.ComposeDialog
import kst4contest.ApplicationConstants
import kst4contest.controller.LoginConfiguration
import kst4contest.controller.OperatorProfilePaths
import kst4contest.controller.OperatorProfileStore
import kst4contest.model.ChatPreferences
import kst4contest.utils.ApplicationFileUtils
import kst4contest.view.compose.Kst4ContestTheme
import kst4contest.view.compose.WindowPlacementOnScreen
import kst4contest.view.compose.openOnEventThread
import kst4contest.view.compose.tabs.LocalFileDialogOwner
import java.awt.Dialog
import java.awt.Dimension
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.atomic.AtomicReference
import javax.swing.WindowConstants
/** How a run of the setup wizard ended. */
enum class SetupWizardOutcome {
/** The profile is set up, or its file could not be read: the wizard did not open. */
NOT_SHOWN,
/** Closed without saving; the file is as it was. */
LATER,
/** The answers are in the file. */
SAVED,
/** The answers are in the file and the operator wants the session started. */
SAVED_AND_CONNECT,
}
/**
* Writes the answers and says how the wizard ends.
*
* @return the outcome to close with, or null when the file could not be written -- the
* wizard then stays open, because "saved" would be a lie
*/
internal fun saveFromWizard(
state: SetupWizardState,
prefs: ChatPreferences,
connect: Boolean,
): SetupWizardOutcome? =
when {
!state.writeTo(prefs) -> null
connect -> SetupWizardOutcome.SAVED_AND_CONNECT
else -> SetupWizardOutcome.SAVED
}
/**
* The setup wizard's window.
*
* A modal [ComposeDialog] opened through [openOnEventThread], the construction
* OperatorProfilePickerWindow uses and for the reason given there: a wait that does not
* pump events deadlocks once the caller is the event thread, and this one is called from
* `main` at startup and from the event thread when the menu rebuilds the runtime.
*/
object SetupWizardWindow {
/** Runs before a profile's runtime exists, so there is no configured size to read. */
private const val DIALOG_FONT_SIZE_SP = 12f
private val DIALOG_SIZE = Dimension(640, 620)
/**
* Opens the wizard and blocks until it is closed.
*
* @param prefs the profile's preferences; written only by Save
* @return never [SetupWizardOutcome.NOT_SHOWN]
*/
fun show(state: SetupWizardState, prefs: ChatPreferences): SetupWizardOutcome {
/* The window's X leaves this untouched: closing is "later". */
val outcome = AtomicReference(SetupWizardOutcome.LATER)
openOnEventThread { open(state, prefs, outcome) }
return outcome.get()
}
private fun open(
state: SetupWizardState,
prefs: ChatPreferences,
outcome: AtomicReference<SetupWizardOutcome>,
) {
val languageStore = wizardLanguageStore(state)
var saveFailed by mutableStateOf(false)
val dialog = ComposeDialog(owner = null, modalityType = Dialog.ModalityType.APPLICATION_MODAL)
dialog.title = languageStore.strings.wizardTitle
dialog.size = DIALOG_SIZE
WindowPlacementOnScreen.centreOnMainWindowScreen(dialog)
/* Disposed and not hidden: a hidden dialog keeps its window and Skia layer alive. */
dialog.defaultCloseOperation = WindowConstants.DISPOSE_ON_CLOSE
dialog.setContent {
Kst4ContestTheme(
darkMode = prefs.isGUI_darkModeActiveByDefault(),
baseFontSizeSp = DIALOG_FONT_SIZE_SP,
) {
CompositionLocalProvider(LocalFileDialogOwner provides dialog) {
SetupWizardContent(
state = state,
languageStore = languageStore,
saveFailed = saveFailed,
onLater = { dialog.dispose() },
onSave = { connect ->
val saved = saveFromWizard(state, prefs, connect)
if (saved == null) {
saveFailed = true
} else {
outcome.set(saved)
dialog.dispose()
}
},
)
}
}
}
dialog.isVisible = true
}
}
/** Another profile that might serve as a donor: who it is and where its preferences lie. */
internal class DonorCandidate(val profileId: String, val displayName: String, val file: Path)
/**
* Reads the candidates that can serve as donors: the file exists, can be read, and holds a
* login an operator entered. A candidate whose file is the same file as [activeFile] (for
* example through a symbolic link) is skipped so a profile never becomes its own donor.
*
* A candidate's file is opened through `ChatPreferences(Path)` and never through the
* constructor that takes a name below the application directory: that one seeds a missing
* file from the bundled template, and looking for a donor must not create a profile's file.
* Nothing here writes.
*/
internal fun loadDonors(
candidates: List<DonorCandidate>,
activeFile: Path? = null,
): List<WizardDonor> =
candidates.mapNotNull { candidate ->
if (!Files.isRegularFile(candidate.file)) return@mapNotNull null
if (activeFile != null && Files.exists(activeFile) &&
runCatching { Files.isSameFile(candidate.file, activeFile) }.getOrDefault(false)
) {
return@mapNotNull null
}
val prefs = ChatPreferences(candidate.file)
// A throwing read counts as failed, as for the profile being set up.
if (!runCatching { prefs.readPreferencesFromXmlFile() }.getOrDefault(false)) return@mapNotNull null
if (LoginConfiguration.isUnconfigured(prefs)) return@mapNotNull null
WizardDonor(candidate.profileId, candidate.displayName, prefs)
}
/** Decides whether the wizard opens for a profile, and opens it. */
object SetupWizardLauncher {
/**
* Opens the wizard when the profile needs it, before the profile's runtime is built.
*
* @param preferencesRelativeFileName the profile's preferences file below the
* application directory; a missing one is seeded from the bundled template, as
* the runtime itself would do
* @param forced the operator asked for the wizard from the menu
*/
@JvmStatic
fun runIfNeeded(preferencesRelativeFileName: String, forced: Boolean): SetupWizardOutcome =
run(
ChatPreferences(preferencesRelativeFileName),
forced,
{
loadDonors(
otherProfiles(preferencesRelativeFileName),
activeFile = Path.of(
ApplicationFileUtils.getFilePath(
ApplicationConstants.APPLICATION_NAME,
preferencesRelativeFileName,
)
),
)
},
SetupWizardWindow::show,
)
/**
* Every registered profile but the one being set up, with the file its preferences lie
* in. Empty on an installation without a profile registry: there is only the root
* profile then, and it is the active one.
*/
private fun otherProfiles(activeRelativeFileName: String): List<DonorCandidate> =
OperatorProfileStore().loadProfiles().mapNotNull { profile ->
val relativeFileName = OperatorProfilePaths.preferencesRelativeFileName(profile)
if (relativeFileName == activeRelativeFileName) return@mapNotNull null
DonorCandidate(
profile.profileId,
profile.displayName,
Path.of(ApplicationFileUtils.getFilePath(ApplicationConstants.APPLICATION_NAME, relativeFileName)),
)
}
/** Without other profiles; for callers and tests that have none. */
internal fun run(
prefs: ChatPreferences,
forced: Boolean,
show: (SetupWizardState, ChatPreferences) -> SetupWizardOutcome,
): SetupWizardOutcome = run(prefs, forced, { emptyList() }, show)
/**
* @param prefs bound to the profile's file and not read yet
* @param donors reads the other profiles; called only once the wizard is certain to
* open, so an ordinary start reads no file but its own
* @param show opens the window; replaced in the tests
*/
internal fun run(
prefs: ChatPreferences,
forced: Boolean,
donors: () -> List<WizardDonor>,
show: (SetupWizardState, ChatPreferences) -> SetupWizardOutcome,
): SetupWizardOutcome {
/*
* A file that cannot be read is not a profile to set up: the wizard would start from
* compiled-in defaults and Save would write them over whatever the file holds. The
* runtime deals with such a file as it always did. A throwing read counts as failed too.
*/
if (!runCatching { prefs.readPreferencesFromXmlFile() }.getOrDefault(false)) {
return SetupWizardOutcome.NOT_SHOWN
}
if (!forced && !LoginConfiguration.isUnconfigured(prefs)) return SetupWizardOutcome.NOT_SHOWN
return show(SetupWizardState(prefs, donors()), prefs)
}
}
@@ -0,0 +1,80 @@
package kst4contest.view.compose.wizard
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import kst4contest.model.ChatPreferences
import kst4contest.view.compose.tabs.StationTabState
/**
* The setup wizard's answers about antenna and power.
*
* These numbers have no empty state: every answer starts as the stored value and is a
* proposal the operator may pass unchanged, also when a station is set up anew. They feed the
* path analysis and the antenna sector on the map; the chat does not need them.
*
* The site elevation is the exception in form, not in rule: it is text, because empty is a
* value of its own -- "let the elevation model decide" -- and it is read exactly as the
* Station tab reads it.
*
* @param prefs the profile's preferences, already read from its file
*/
class WizardAntenna(prefs: ChatPreferences) {
private val storedBeamWidthDeg = prefs.getStn_antennaBeamWidthDeg()
private val storedGainDbi = prefs.getStn_pathAnalysisOwnAntennaGainDbi()
// The XML reader assigns the field directly without clamping, whereas the setter and path analysis treat < 0 as 0.
private val storedHeightMeters = prefs.getStn_pathAnalysisOwnAntennaHeightMeters().coerceAtLeast(0.0)
private val storedTxPowerWatts = prefs.getStn_pathAnalysisOwnTxPowerWatts()
private val storedHeightAslText = elevationText(prefs.getStn_pathAnalysisOwnHeightAslMeters())
var beamWidthDeg: Double by mutableStateOf(storedBeamWidthDeg)
var gainDbi: Double by mutableStateOf(storedGainDbi)
var heightMeters: Double by mutableStateOf(storedHeightMeters)
var txPowerWatts: Double by mutableStateOf(storedTxPowerWatts)
/** The site elevation above sea level as the operator types it; empty for the model. */
var heightAslText: String by mutableStateOf(storedHeightAslText)
/**
* Puts every answer back to what the profile holds. For the moment the operator changes
* his mind about where the station comes from: what he typed for one choice must not
* show in the summary of the other, where it would not be written.
*/
fun loadStored() {
beamWidthDeg = storedBeamWidthDeg
gainDbi = storedGainDbi
heightMeters = storedHeightMeters
txPowerWatts = storedTxPowerWatts
heightAslText = storedHeightAslText
}
/** A site elevation that is neither empty nor a number in the accepted range. */
val heightAslRefused: Boolean
get() = StationTabState.parseOwnHeightAsl(heightAslText) == null
/** Whether every answer can be stored as it stands. */
val complete: Boolean
get() = beamWidthDeg.isFinite() && gainDbi.isFinite() && heightMeters.isFinite() &&
heightMeters >= 0.0 && txPowerWatts.isFinite() && !heightAslRefused
/** Puts the answers into [prefs]. Call only while [complete]. */
fun writeTo(prefs: ChatPreferences) {
prefs.setStn_antennaBeamWidthDeg(beamWidthDeg)
prefs.setStn_pathAnalysisOwnAntennaGainDbi(gainDbi)
prefs.setStn_pathAnalysisOwnAntennaHeightMeters(heightMeters)
prefs.setStn_pathAnalysisOwnTxPowerWatts(txPowerWatts)
prefs.setStn_pathAnalysisOwnHeightAslMeters(
StationTabState.parseOwnHeightAsl(heightAslText) ?: Double.NaN
)
}
private companion object {
/** Empty for "unset"; a whole number without ".0", so the field shows what one types. */
fun elevationText(meters: Double): String = when {
meters.isNaN() -> ""
meters == Math.floor(meters) && !meters.isInfinite() -> meters.toLong().toString()
else -> meters.toString()
}
}
}
@@ -0,0 +1,289 @@
package kst4contest.view.compose.wizard
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import kst4contest.model.ChatPreferences
import kst4contest.view.compose.tabs.AirscoutTabState
import kst4contest.view.compose.tabs.StationTabState
/** Where the worked stations come from. The wizard knows one source at a time. */
enum class WizardLogProgram {
NONE,
/** The Win-Test network listener. */
WINTEST,
/** UCXLog, DXLog.net, N1MM+ and QARTEST: QSO messages on the shared UDP port. */
UDP,
/** A log file polled for callsigns. */
FILE,
}
/** Something that was on in the profile and will be off after Save, for the summary. */
enum class WizardSwitch {
SECOND_CHAT,
LOG_WINTEST,
LOG_UDP,
LOG_FILE,
QRG_FOLLOW,
CLUSTER_SERVER,
ROTATOR,
AIRSCOUT,
SO2R,
ROTATOR_2,
}
/**
* The setup wizard's answers about log program, rotator and AirScout.
*
* Two pages share this class because they share a rule: a station set up anew gets only what
* the operator said yes to. [loadFresh] therefore switches everything off -- the bundled
* template has several of these on, which a newcomer without a log program does not know --
* while ports, names, host and identifiers stay as stored and are proposals.
*
* The wizard switches things on and off and takes numbers over. It invents none: no port,
* no identifier and no default here differs from what the settings tabs accept.
*
* The settings window allows several log sources at once and the wizard's question does
* not. [severalStoredLogSources] says when the stored profile is such a case, so the caller
* can keep the log page shut rather than collapse the sources into one.
*
* @param prefs the profile's preferences, already read from its file
*/
class WizardIntegrations(prefs: ChatPreferences) {
private val storedWintest = prefs.isLogsynch_wintestNetworkListenerEnabled()
private val storedUdp = prefs.isLogsynch_ucxUDPWkdCallListenerEnabled()
private val storedFile = prefs.isLogsynch_fileBasedWkdCallInterpreterEnabled()
private val storedUdpQrg = prefs.isTrxSynch_ucxLogUDPListenerEnabled()
private val storedWintestQrg = prefs.isLogsynch_wintestQrgSyncEnabled()
private val storedCluster = prefs.isNotify_dxClusterServerEnabled()
private val storedRotator = prefs.isStn_pstRotatorEnabled()
private val storedAirScout = prefs.isAirScout_asUDPListenerEnabled()
/** Rotator 2 only counts while SO2R uses it, as on the Station tab. */
private val rotatorTwoInUse = prefs.isTrxSynch_so2rEnabled() && prefs.isStn_pstRotator2Enabled()
private val rotatorTwoPort = prefs.getStn_pstRotator2Port()
/** More than one log source is on in the profile; the log page cannot show that. */
val severalStoredLogSources: Boolean = listOf(storedWintest, storedUdp, storedFile).count { it } > 1
var logProgram: WizardLogProgram by mutableStateOf(WizardLogProgram.NONE)
private set
private val storedUdpPort = prefs.getLogsynch_ucxUDPWkdCallListenerPort()
private val storedWintestPort = prefs.getLogsynch_wintestNetworkPort()
private val storedWintestStationName = prefs.getLogsynch_wintestNetworkStationNameOfKST().orEmpty()
private val storedFilePath = prefs.getLogsynch_fileBasedWkdCallInterpreterFileNameReadOnly().orEmpty()
private val storedRotatorHost = prefs.getStn_pstRotatorHost().orEmpty()
private val storedRotatorPort = prefs.getStn_pstRotatorPort()
private val storedAirScoutPort = prefs.getAirScout_asCommunicationPort()
private val storedAirScoutServerName = prefs.getAirScout_asServerNameString().orEmpty()
private val storedAirScoutClientName = prefs.getAirScout_asClientNameString().orEmpty()
/**
* Whether the profile takes its own frequency from a log program, whichever one. Known
* apart from [qrgFollow] because the settings window allows a frequency source without
* the matching log source, which the page's single choice cannot show.
*/
val storedQrgFollow: Boolean = storedUdpQrg || storedWintestQrg
/** Whether the profile runs the local DX cluster server, with or without a log source. */
val storedClusterServer: Boolean = storedCluster
var udpPort: Int by mutableStateOf(storedUdpPort)
var wintestPort: Int by mutableStateOf(storedWintestPort)
var wintestStationName: String by mutableStateOf(storedWintestStationName)
var filePath: String by mutableStateOf(storedFilePath)
/** Take the own frequency from the chosen network program. */
var qrgFollow: Boolean by mutableStateOf(false)
/** Pass spots to the log program through the local DX cluster server. */
var clusterServer: Boolean by mutableStateOf(false)
var rotator: Boolean by mutableStateOf(false)
var rotatorHost: String by mutableStateOf(storedRotatorHost)
var rotatorPort: Int by mutableStateOf(storedRotatorPort)
var airScout: Boolean by mutableStateOf(false)
var airScoutPort: Int by mutableStateOf(storedAirScoutPort)
var airScoutServerName: String by mutableStateOf(storedAirScoutServerName)
var airScoutClientName: String by mutableStateOf(storedAirScoutClientName)
init {
loadStored()
}
/** The switches as the profile has them. Several sources show as one, the network ones first. */
fun loadStored() {
logProgram = when {
storedWintest -> WizardLogProgram.WINTEST
storedUdp -> WizardLogProgram.UDP
storedFile -> WizardLogProgram.FILE
else -> WizardLogProgram.NONE
}
qrgFollow = when (logProgram) {
WizardLogProgram.WINTEST -> storedWintestQrg
WizardLogProgram.UDP -> storedUdpQrg
else -> false
}
clusterServer = networked && storedCluster
rotator = storedRotator
airScout = storedAirScout
loadStoredDetails()
}
/** A station set up anew: every switch off, every number left as a proposal. */
fun loadFresh() {
logProgram = WizardLogProgram.NONE
qrgFollow = false
clusterServer = false
rotator = false
airScout = false
loadStoredDetails()
}
/**
* Ports, names, host and identifiers back to what the profile holds. Both loads do this:
* they run when the operator changes his mind about where the station comes from, and a
* number typed under one choice must not turn up under the other.
*/
private fun loadStoredDetails() {
udpPort = storedUdpPort
wintestPort = storedWintestPort
wintestStationName = storedWintestStationName
filePath = storedFilePath
rotatorHost = storedRotatorHost
rotatorPort = storedRotatorPort
airScoutPort = storedAirScoutPort
airScoutServerName = storedAirScoutServerName
airScoutClientName = storedAirScoutClientName
}
/** Only a network program can deliver a frequency or take spots. */
val networked: Boolean
get() = logProgram == WizardLogProgram.WINTEST || logProgram == WizardLogProgram.UDP
fun chooseLogProgram(program: WizardLogProgram) {
logProgram = program
if (!networked) {
qrgFollow = false
clusterServer = false
}
}
/** Whether what the chosen program needs is there. A program not chosen needs nothing. */
val logComplete: Boolean
get() = when (logProgram) {
WizardLogProgram.NONE -> true
WizardLogProgram.WINTEST -> AirscoutTabState.isValidPort(wintestPort) && wintestStationName.isNotBlank()
WizardLogProgram.UDP -> AirscoutTabState.isValidPort(udpPort)
WizardLogProgram.FILE -> filePath.isNotBlank()
}
/** The same or the next port as rotator 2, which answers on its port + 1. */
val rotatorPortClashes: Boolean
get() = rotator && rotatorTwoInUse && StationTabState.portsClash(rotatorPort, rotatorTwoPort)
/** Whether what the switched-on equipment needs is there. */
val gearComplete: Boolean
get() {
val rotatorComplete = !rotator ||
(rotatorHost.isNotBlank() && rotatorPort in ROTATOR_PORTS && !rotatorPortClashes)
val airScoutComplete = !airScout ||
(AirscoutTabState.isValidPort(airScoutPort) &&
AirscoutTabState.isValidIdentifier(airScoutServerName) &&
AirscoutTabState.isValidIdentifier(airScoutClientName))
return rotatorComplete && airScoutComplete
}
/**
* Puts the log page's answers into [prefs]: exactly the chosen source on, its details
* stored, and the frequency source and the DX cluster server only with a network program.
* Details of a program that is not chosen are left as they are. Call only while
* [logComplete].
*/
fun writeLogTo(prefs: ChatPreferences) {
prefs.setLogsynch_wintestNetworkListenerEnabled(logProgram == WizardLogProgram.WINTEST)
prefs.setLogsynch_ucxUDPWkdCallListenerEnabled(logProgram == WizardLogProgram.UDP)
prefs.setLogsynch_fileBasedWkdCallInterpreterEnabled(logProgram == WizardLogProgram.FILE)
when (logProgram) {
WizardLogProgram.WINTEST -> {
prefs.setLogsynch_wintestNetworkPort(wintestPort)
prefs.setLogsynch_wintestNetworkStationNameOfKST(wintestStationName.trim())
}
WizardLogProgram.UDP -> prefs.setLogsynch_ucxUDPWkdCallListenerPort(udpPort)
WizardLogProgram.FILE -> prefs.setLogsynch_fileBasedWkdCallInterpreterFileNameReadOnly(filePath)
WizardLogProgram.NONE -> Unit
}
prefs.setLogsynch_wintestQrgSyncEnabled(logProgram == WizardLogProgram.WINTEST && qrgFollow)
prefs.setTrxSynch_ucxLogUDPListenerEnabled(logProgram == WizardLogProgram.UDP && qrgFollow)
prefs.setNotify_dxClusterServerEnabled(networked && clusterServer)
}
/**
* Puts the equipment page's answers into [prefs]. Host, port and identifiers are stored
* only for what is switched on. Call only while [gearComplete].
*/
fun writeGearTo(prefs: ChatPreferences) {
prefs.setStn_pstRotatorEnabled(rotator)
if (rotator) {
prefs.setStn_pstRotatorHost(rotatorHost.trim())
prefs.setStn_pstRotatorPort(rotatorPort)
}
prefs.setAirScout_asUDPListenerEnabled(airScout)
if (airScout) {
prefs.setAirScout_asCommunicationPort(airScoutPort)
prefs.setAirScout_asServerNameString(airScoutServerName.trim())
prefs.setAirScout_asClientNameString(airScoutClientName.trim())
}
}
/** The log-page switches the profile these answers were built from has on. */
fun storedLogSwitches(): Set<WizardSwitch> = buildSet {
if (storedWintest) add(WizardSwitch.LOG_WINTEST)
if (storedUdp) add(WizardSwitch.LOG_UDP)
if (storedFile) add(WizardSwitch.LOG_FILE)
if (storedQrgFollow) add(WizardSwitch.QRG_FOLLOW)
if (storedCluster) add(WizardSwitch.CLUSTER_SERVER)
}
/** The equipment switches the profile these answers were built from has on. */
fun storedGearSwitches(): Set<WizardSwitch> = buildSet {
if (storedRotator) add(WizardSwitch.ROTATOR)
if (storedAirScout) add(WizardSwitch.AIRSCOUT)
}
/** The log-page switches that are on once [writeLogTo] has run. */
fun answeredLogSwitches(): Set<WizardSwitch> = buildSet {
when (logProgram) {
WizardLogProgram.WINTEST -> add(WizardSwitch.LOG_WINTEST)
WizardLogProgram.UDP -> add(WizardSwitch.LOG_UDP)
WizardLogProgram.FILE -> add(WizardSwitch.LOG_FILE)
WizardLogProgram.NONE -> Unit
}
if (networked && qrgFollow) add(WizardSwitch.QRG_FOLLOW)
if (networked && clusterServer) add(WizardSwitch.CLUSTER_SERVER)
}
/** The equipment switches that are on once [writeGearTo] has run. */
fun answeredGearSwitches(): Set<WizardSwitch> = buildSet {
if (rotator) add(WizardSwitch.ROTATOR)
if (airScout) add(WizardSwitch.AIRSCOUT)
}
private companion object {
/**
* The ports setStn_pstRotatorPort stores. One short of the full range, because
* PSTRotator answers on port + 1; the setter replaces anything else by its factory
* default, which would be the wizard inventing a number.
*/
val ROTATOR_PORTS = 1..65534
}
}
@@ -0,0 +1,108 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatCategory
import kst4contest.model.ChatPreferences
/**
* Copies the station from one profile's preferences to another's.
*
* "The station" is what hangs on the site and the equipment: locator, bands, chat
* categories, antenna and path-analysis values, log program, frequency source, DX cluster
* server, rotators, AirScout. It is deliberately more than the setup wizard asks about -- a
* further operator at the same station should inherit the second rotator and the Win-Test
* station filter too, without ever seeing a question for them.
*
* It is deliberately not the operator: login, names, language, appearance, layout,
* shortcuts, snippets, beacons, automatic answers, sounds, filters. Nor the server address
* or the spotter callsign.
*
* Which setter belongs where is decided line by line in
* `src/test/resources/wizard-station-setters.txt` and `wizard-other-setters.txt`; a test
* holds this function and those lists together, and fails when ChatPreferences gains a
* setter nobody classified.
*
* Nothing is written to a file here, and [from] is only read.
*/
internal fun copyStation(from: ChatPreferences, to: ChatPreferences) {
// Location, bands and chats. The categories are copied by number: the two profiles
// must not share one mutable ChatCategory.
to.setStn_loginLocatorMainCat(from.getStn_loginLocatorMainCat())
to.setLoginChatCategoryMain(from.getLoginChatCategoryMain()?.let { ChatCategory(it.categoryNumber) })
to.setLoginChatCategorySecond(from.getLoginChatCategorySecond()?.let { ChatCategory(it.categoryNumber) })
to.setLoginToSecondChatEnabled(from.isLoginToSecondChatEnabled())
// Bands.
to.setStn_bandActive50(from.isStn_bandActive50())
to.setStn_bandActive70(from.isStn_bandActive70())
to.setStn_bandActive144(from.isStn_bandActive144())
to.setStn_bandActive432(from.isStn_bandActive432())
to.setStn_bandActive1240(from.isStn_bandActive1240())
to.setStn_bandActive2300(from.isStn_bandActive2300())
to.setStn_bandActive3400(from.isStn_bandActive3400())
to.setStn_bandActive5600(from.isStn_bandActive5600())
to.setStn_bandActive10G(from.isStn_bandActive10G())
// Antenna, defaults and everything the path analysis needs to know about the site.
to.setStn_antennaBeamWidthDeg(from.getStn_antennaBeamWidthDeg())
to.setStn_qtfDefault(from.getStn_qtfDefault())
to.setStn_maxQRBDefault(from.getStn_maxQRBDefault())
to.setStn_useQtfFilterDirectionAsAntennaHeading(from.isStn_useQtfFilterDirectionAsAntennaHeading())
to.setStn_pathAnalysisOwnAntennaGainDbi(from.getStn_pathAnalysisOwnAntennaGainDbi())
to.setStn_pathAnalysisOwnAntennaHeightMeters(from.getStn_pathAnalysisOwnAntennaHeightMeters())
to.setStn_pathAnalysisOwnTxPowerWatts(from.getStn_pathAnalysisOwnTxPowerWatts())
to.setStn_pathAnalysisOwnHeightAslMeters(from.getStn_pathAnalysisOwnHeightAslMeters())
to.setStn_pathAnalysisDefaultTargetAntennaGainDbi(from.getStn_pathAnalysisDefaultTargetAntennaGainDbi())
to.setStn_pathAnalysisDefaultTargetAntennaHeightMeters(from.getStn_pathAnalysisDefaultTargetAntennaHeightMeters())
to.setStn_pathAnalysisDefaultTargetTxPowerWatts(from.getStn_pathAnalysisDefaultTargetTxPowerWatts())
to.setStn_pathAnalysisDxHighestPointInSquare(from.isStn_pathAnalysisDxHighestPointInSquare())
to.setStn_pathAnalysisDemRootDirectory(from.getStn_pathAnalysisDemRootDirectory())
to.setStn_pathAnalysisDemDatasetId(from.getStn_pathAnalysisDemDatasetId())
to.setStn_pathAnalysisVhfFeederLossPerStationDb(from.getStn_pathAnalysisVhfFeederLossPerStationDb())
to.setStn_pathAnalysisFeederLossIncreaseDbPer200MHz(from.getStn_pathAnalysisFeederLossIncreaseDbPer200MHz())
to.setStn_pathAnalysisMaxEstimatedFeederLossPerStationDb(from.getStn_pathAnalysisMaxEstimatedFeederLossPerStationDb())
to.setStn_pathAnalysisRequiredSsbSignalDbm(from.getStn_pathAnalysisRequiredSsbSignalDbm())
to.setStn_pathAnalysisRequiredCwSignalDbm(from.getStn_pathAnalysisRequiredCwSignalDbm())
to.setStn_pathAnalysisContestMarginDb(from.getStn_pathAnalysisContestMarginDb())
// Log sources. All of them as they are: a station may run several at once.
to.setLogsynch_fileBasedWkdCallInterpreterEnabled(from.isLogsynch_fileBasedWkdCallInterpreterEnabled())
to.setLogsynch_fileBasedWkdCallInterpreterFileNameReadOnly(from.getLogsynch_fileBasedWkdCallInterpreterFileNameReadOnly())
to.setLogsynch_ucxUDPWkdCallListenerEnabled(from.isLogsynch_ucxUDPWkdCallListenerEnabled())
to.setLogsynch_ucxUDPWkdCallListenerPort(from.getLogsynch_ucxUDPWkdCallListenerPort())
to.setLogsynch_wintestNetworkListenerEnabled(from.isLogsynch_wintestNetworkListenerEnabled())
to.setLogsynch_wintestNetworkPort(from.getLogsynch_wintestNetworkPort())
to.setLogsynch_wintestNetworkBroadcastAddress(from.getLogsynch_wintestNetworkBroadcastAddress())
to.setLogsynch_wintestNetworkStationNameOfKST(from.getLogsynch_wintestNetworkStationNameOfKST())
to.setLogsynch_wintestNetworkStationIDOfKST(from.getLogsynch_wintestNetworkStationIDOfKST())
to.setLogsynch_wintestNetworkStationNameOfWintestClient1(from.getLogsynch_wintestNetworkStationNameOfWintestClient1())
to.setLogsynch_wintestNetworkStationNameOfWintestClient2(from.getLogsynch_wintestNetworkStationNameOfWintestClient2())
to.setLogsynch_wintestNetworkSkedPushEnabled(from.isLogsynch_wintestNetworkSkedPushEnabled())
to.setLogsynch_wintestNetworkSimulationEnabled(from.isLogsynch_wintestNetworkSimulationEnabled())
to.setLogsynch_wintestSkedMode(from.getLogsynch_wintestSkedMode())
// Frequency sources, SO2R and the DX cluster server for the log program.
to.setLogsynch_wintestQrgSyncEnabled(from.isLogsynch_wintestQrgSyncEnabled())
to.setLogsynch_wintestUsePassQrg(from.isLogsynch_wintestUsePassQrg())
to.setTrxSynch_ucxLogUDPListenerEnabled(from.isTrxSynch_ucxLogUDPListenerEnabled())
to.setTrxSynch_so2rEnabled(from.isTrxSynch_so2rEnabled())
to.setNotify_dxClusterServerEnabled(from.isNotify_dxClusterServerEnabled())
to.setNotify_dxclusterServerPort(from.getNotify_dxclusterServerPort())
// The band a frequency given without one is completed with; it has to fit the bands above.
to.setNotify_optionalFrequencyPrefix(from.getNotify_optionalFrequencyPrefix().get())
// Rotators.
to.setStn_pstRotatorEnabled(from.isStn_pstRotatorEnabled())
to.setStn_pstRotatorHost(from.getStn_pstRotatorHost())
to.setStn_pstRotatorPort(from.getStn_pstRotatorPort())
to.setStn_pstRotator2Enabled(from.isStn_pstRotator2Enabled())
to.setStn_pstRotator2Host(from.getStn_pstRotator2Host())
to.setStn_pstRotator2Port(from.getStn_pstRotator2Port())
// AirScout.
to.setAirScout_asUDPListenerEnabled(from.isAirScout_asUDPListenerEnabled())
to.setAirScout_asCommunicationPort(from.getAirScout_asCommunicationPort())
to.setAirScout_asServerNameString(from.getAirScout_asServerNameString())
to.setAirScout_asClientNameString(from.getAirScout_asClientNameString())
to.setAirScout_autoBandSelectionEnabled(from.isAirScout_autoBandSelectionEnabled())
to.setAirScout_asBandString(from.getAirScout_asBandString())
}
@@ -0,0 +1,87 @@
package kst4contest.view;
import kst4contest.controller.ActiveOperatorProfile;
import kst4contest.model.OperatorProfile;
import kst4contest.model.OperatorProfileSelection;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The request to show the setup wizard on the next runtime start is honoured exactly once.
* A request that stuck would open the wizard on every later profile switch.
*/
class ApplicationRuntimeLauncherSetupWizardTest {
@Test
void aRequestIsHonouredOnce() {
assertFalse(ApplicationRuntimeLauncher.consumeSetupWizardRequest(), "nothing was requested");
ApplicationRuntimeLauncher.requestSetupWizard();
assertTrue(ApplicationRuntimeLauncher.consumeSetupWizardRequest());
assertFalse(ApplicationRuntimeLauncher.consumeSetupWizardRequest(), "the request must not stick");
}
@Test
void switchGuardAllowsOnlyOneSwitchAtATime() {
try {
assertTrue(ApplicationRuntimeLauncher.beginSwitch());
assertFalse(ApplicationRuntimeLauncher.beginSwitch(),
"a second switch must be refused while one is in progress");
} finally {
ApplicationRuntimeLauncher.endSwitch();
}
try {
assertTrue(ApplicationRuntimeLauncher.beginSwitch(),
"ending the first switch must release the guard");
} finally {
ApplicationRuntimeLauncher.endSwitch();
}
}
@Test
void aRefusedRerunLeavesTheRequestOfTheRunningSwitchAlone() {
OperatorProfileSelection previous = ActiveOperatorProfile.get();
OperatorProfile profile = new OperatorProfile("wizard-guard-test", "Wizard Guard Test", false, false);
ActiveOperatorProfile.set(new OperatorProfileSelection(profile, "preferences.xml", "worked.db", false));
// A first rerun is under way: it holds the guard and its request waits for startRuntime.
assertTrue(ApplicationRuntimeLauncher.beginSwitch());
ApplicationRuntimeLauncher.requestSetupWizard();
try {
// A second one arrives while the first tears its windows down, and is refused.
assertFalse(ApplicationRuntimeLauncher.rerunSetupWizard());
assertTrue(ApplicationRuntimeLauncher.consumeSetupWizardRequest(),
"the refused rerun took the running switch's request with it: that switch "
+ "would end the session and then start without the wizard");
} finally {
ApplicationRuntimeLauncher.endSwitch();
ApplicationRuntimeLauncher.consumeSetupWizardRequest();
ActiveOperatorProfile.set(previous);
}
}
@Test
void aRefusedRerunLeavesNoRequestOfItsOwn() {
OperatorProfileSelection previous = ActiveOperatorProfile.get();
OperatorProfile profile = new OperatorProfile("wizard-guard-test", "Wizard Guard Test", false, false);
ActiveOperatorProfile.set(new OperatorProfileSelection(profile, "preferences.xml", "worked.db", false));
// A plain profile switch is under way; nobody asked for the wizard.
assertTrue(ApplicationRuntimeLauncher.beginSwitch());
try {
assertFalse(ApplicationRuntimeLauncher.rerunSetupWizard());
assertFalse(ApplicationRuntimeLauncher.consumeSetupWizardRequest(),
"a refused rerun must not hand its wizard to the switch that refused it");
} finally {
ApplicationRuntimeLauncher.endSwitch();
ApplicationRuntimeLauncher.consumeSetupWizardRequest();
ActiveOperatorProfile.set(previous);
}
}
}
@@ -28,6 +28,7 @@ class MainMenuModelTest {
override fun setQrgAsNameInChat() { calls += "setQrgAsNameInChat" }
override fun toggleAwayState() { calls += "toggleAwayState" }
override fun toggleSettingsWindow() { calls += "toggleSettingsWindow" }
override fun openSetupWizard() { calls += "openSetupWizard" }
override fun toggleMonitorWindow() { calls += "toggleMonitorWindow" }
override fun toggleStationMap() { calls += "toggleStationMap" }
override fun useDarkDesign() { calls += "useDarkDesign" }
@@ -181,4 +182,19 @@ class MainMenuModelTest {
"every item must reach an action; one of them did nothing",
)
}
@Test
fun theSetupAssistantIsReachableFromOptionsWhateverTheConnection() {
for (connectionState in On4KstConnectionState.values()) {
val actions = RecordingActions()
val model = model(connectionState = connectionState, actions = actions)
val entry = items(model.single { it.title == "Options" }).single { it.label == "Setup assistant..." }
// Like the profile switch: it gives the session up itself, after asking.
assertTrue(entry.enabled, "the assistant must be reachable while $connectionState")
entry.onClick()
assertEquals("openSetupWizard", actions.calls.last())
}
}
}
@@ -55,6 +55,7 @@ class MainMenuRowScreenTest {
override fun setQrgAsNameInChat() { calls += "setQrgAsNameInChat" }
override fun toggleAwayState() { calls += "toggleAwayState" }
override fun toggleSettingsWindow() { calls += "toggleSettingsWindow" }
override fun openSetupWizard() { calls += "openSetupWizard" }
override fun toggleMonitorWindow() { calls += "toggleMonitorWindow" }
override fun toggleStationMap() { calls += "toggleStationMap" }
override fun useDarkDesign() { calls += "useDarkDesign" }
@@ -116,6 +117,7 @@ class MainMenuRowScreenTest {
Triple("Options", "Set QRG as name in Chat (main category)", "setQrgAsNameInChat"),
Triple("Options", "Show me as AWAY FROM chat!", "toggleAwayState"),
Triple("Options", "Show options", "toggleSettingsWindow"),
Triple("Options", "Setup assistant...", "openSetupWizard"),
Triple("Windows", "Show cluster / stranger QSOs", "toggleMonitorWindow"),
Triple("Windows", "Show / hide station map", "toggleStationMap"),
Triple("Windows", "Use dark mode design", "useDarkDesign"),
@@ -0,0 +1,292 @@
package kst4contest.view.compose.wizard
import androidx.compose.ui.test.ComposeUiTest
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.hasSetTextAction
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTextReplacement
import androidx.compose.ui.test.runComposeUiTest
import kst4contest.model.ChatCategory
import kst4contest.model.ChatPreferences
import kst4contest.view.compose.Kst4ContestTheme
import kst4contest.view.i18n.LanguageStore
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.nio.file.Path
import java.util.Locale
/**
* The drawn wizard, clicked the way an operator clicks it. The rules live in
* SetupWizardState and are tested there; this holds the wiring -- that a button reaches the
* state, and that a button which must not work does not.
*/
@OptIn(ExperimentalTestApi::class)
class SetupWizardContentScreenTest {
private fun configuredProfile() =
ChatPreferences(Path.of("setup-wizard-screen-test-unused.xml")).apply {
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("secret")
setStn_loginNameMainCat("Philipp")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
// Stated, not left to the compiled-in default: with a second chat and no second
// category the summary could not be saved.
setLoginToSecondChatEnabled(false)
}
private class Recorded {
var later = 0
val saves = mutableListOf<Boolean>()
}
private fun ComposeUiTest.show(state: SetupWizardState, saveFailed: Boolean = false): Recorded {
val recorded = Recorded()
// English, whatever language an earlier test in this JVM left behind.
val english = LanguageStore({ "en" }, {}, Locale.ENGLISH)
setContent {
Kst4ContestTheme(darkMode = false, baseFontSizeSp = 12f) {
SetupWizardContent(
state = state,
languageStore = english,
saveFailed = saveFailed,
onLater = { recorded.later++ },
onSave = { recorded.saves += it },
)
}
}
return recorded
}
@Test
fun nextDoesNothingUntilBothSourcesAreChosen() = runComposeUiTest {
val state = SetupWizardState(configuredProfile())
show(state)
onNodeWithText("Next").performClick()
assertEquals(WizardPage.ENTRY, state.page, "Next worked without a choice")
onNodeWithText("Leave the login unchanged (DL0TEST)").performClick()
onNodeWithText("Leave the station unchanged (locator JO50AA)").performClick()
assertEquals(WizardSource.KEEP, state.loginSource)
assertEquals(WizardSource.KEEP, state.stationSource)
onNodeWithText("Next").performClick()
assertEquals(WizardPage.PERSONAL, state.page)
}
@Test
fun laterIsReportedAndNothingElse() = runComposeUiTest {
val recorded = show(SetupWizardState(configuredProfile()))
onNodeWithText("Later").performClick()
assertEquals(1, recorded.later)
assertTrue(recorded.saves.isEmpty())
}
@Test
fun theSummaryOffersBothWaysOfSaving() = runComposeUiTest {
val state = SetupWizardState(configuredProfile())
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
val recorded = show(state)
onNodeWithText("Save").performClick()
onNodeWithText("Save and connect").performClick()
assertEquals(listOf(false, true), recorded.saves)
}
@Test
fun aFailedSaveIsToldToTheOperator() = runComposeUiTest {
val state = SetupWizardState(configuredProfile())
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
show(state, saveFailed = true)
onNodeWithText("The settings could not be written. Nothing was changed.").assertExists()
}
@Test
fun theSummaryShowsTheChosenLanguage() = runComposeUiTest {
val state = SetupWizardState(configuredProfile().apply { setGuiOptions_language("de") })
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
show(state)
onNodeWithText("DE").assertExists()
}
/** A first installation: the template's credentials, so the wizard starts from scratch. */
private fun firstInstallation() =
ChatPreferences(Path.of("setup-wizard-screen-test-unused.xml")).apply {
setStn_loginCallSign("DO5AMF")
setStn_loginPassword("changeMe")
setLogsynch_wintestNetworkListenerEnabled(false)
setLogsynch_ucxUDPWkdCallListenerEnabled(true)
setLogsynch_fileBasedWkdCallInterpreterEnabled(false)
// Every other switch stated too, so the summary's wording does not hang on a
// compiled-in default.
setTrxSynch_ucxLogUDPListenerEnabled(false)
setLogsynch_wintestQrgSyncEnabled(false)
setNotify_dxClusterServerEnabled(false)
setStn_pstRotatorEnabled(false)
setAirScout_asUDPListenerEnabled(true)
setLoginToSecondChatEnabled(false)
}
private fun SetupWizardState.walkToTheLogPage() {
name = "Philipp"
next()
callsign = "DL0TEST"
password = "secret"
next()
locator = "JO50AA"
setBand(WizardBand.B144, true)
next()
next()
}
@Test
fun choosingALogProgramOnTheDrawnPageReachesTheState() = runComposeUiTest {
val state = SetupWizardState(firstInstallation())
state.walkToTheLogPage()
assertEquals(WizardPage.LOG, state.page)
show(state)
onNodeWithText("Win-Test").performClick()
assertEquals(WizardLogProgram.WINTEST, state.integrations.logProgram)
onNodeWithText("Take my own frequency from the log program").assertExists()
}
@Test
fun nextRefusesAnUnreadableUdpPortAndAcceptsItsCorrection() = runComposeUiTest {
val state = SetupWizardState(firstInstallation())
state.walkToTheLogPage()
state.integrations.chooseLogProgram(WizardLogProgram.UDP)
val originalPort = state.integrations.udpPort
show(state)
val portField = onNode(hasSetTextAction())
val refusal = onNodeWithText(
"Shared UDP port for QSO and TRX messages [default 12060]:: \"abc\" is not a valid entry.",
)
portField.performTextReplacement("abc")
onNodeWithText("Next").performClick()
assertEquals(originalPort, state.integrations.udpPort)
assertEquals(WizardPage.LOG, state.page)
refusal.assertExists()
portField.performTextReplacement("12061")
refusal.assertExists()
onNodeWithText("Next").performClick()
assertEquals(WizardPage.GEAR, state.page)
assertEquals(12061, state.integrations.udpPort)
refusal.assertDoesNotExist()
}
@Test
fun finishRefusesAnUnreadableUdpPort() = runComposeUiTest {
val state = SetupWizardState(firstInstallation())
state.walkToTheLogPage()
state.integrations.chooseLogProgram(WizardLogProgram.UDP)
show(state)
onNode(hasSetTextAction()).performTextReplacement("abc")
onNodeWithText("Finish").performClick()
assertEquals(WizardPage.LOG, state.page)
}
@Test
fun theSummaryNamesWhatANewStationSwitchesOff() = runComposeUiTest {
val state = SetupWizardState(firstInstallation())
state.walkToTheLogPage()
state.finish()
show(state)
onNodeWithText("Will be switched off: network log synchronisation, AirScout.").assertExists()
}
private fun donor(id: String, name: String, callsign: String, locator: String) =
WizardDonor(id, name, ChatPreferences(Path.of("setup-wizard-screen-donor-unused.xml")).apply {
setStn_loginCallSign(callsign)
setStn_loginPassword("secret")
setStn_loginLocatorMainCat(locator)
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
})
private fun emptyProfile() =
ChatPreferences(Path.of("setup-wizard-screen-test-unused.xml")).apply {
setStn_loginCallSign("")
setStn_loginPassword("")
setStn_loginLocatorMainCat("JO54ME")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
}
@Test
fun aSingleDonorIsNamedInTheOptionAndTakenWithOneClick() = runComposeUiTest {
val state = SetupWizardState(emptyProfile(), listOf(donor("a", "Conteststation", "DL0TEST", "JO50AA")))
show(state)
onNodeWithText("Take the login from profile \"Conteststation\" (DL0TEST)").performClick()
onNodeWithText("Take the station from profile \"Conteststation\" (locator JO50AA)").performClick()
assertEquals(WizardSource.TAKE, state.loginSource)
assertEquals("a", state.loginDonor?.profileId)
assertEquals(WizardSource.TAKE, state.stationSource)
onNodeWithText("Next").performClick()
assertEquals(WizardPage.PERSONAL, state.page)
assertEquals("DL0TEST", state.callsign)
}
@Test
fun withSeveralDonorsNextWaitsForAProfile() = runComposeUiTest {
val state = SetupWizardState(
emptyProfile(),
listOf(donor("a", "Conteststation", "DL0TEST", "JO50AA"), donor("b", "Portabel", "DL0TEST/P", "JN58QA")),
)
show(state)
onNodeWithText("Take the login from another profile").performClick()
onNodeWithText("Set up a new station").performClick()
onNodeWithText("Next").performClick()
assertEquals(WizardPage.ENTRY, state.page, "which profile is not said yet")
}
@Test
fun theSummaryShowsTheFallbackBandForSpots() = runComposeUiTest {
val prefs = configuredProfile().apply {
setStn_bandActive144(false)
setStn_bandActive432(true)
setNotify_optionalFrequencyPrefix("144")
}
val state = SetupWizardState(prefs)
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
show(state)
onNodeWithText("144 MHz").assertExists()
}
}
@@ -0,0 +1,446 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatCategory
import kst4contest.model.ChatPreferences
import org.junit.jupiter.api.Assertions.assertArrayEquals
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
/**
* Taking the login or the station from another profile: what is offered, what the answers
* become, what the summary says against the own profile, and what reaches the file.
*/
class SetupWizardDonorTest(@param:TempDir private val directory: Path) {
private fun prefs(configure: ChatPreferences.() -> Unit = {}): ChatPreferences =
ChatPreferences(Path.of("setup-wizard-donor-test-unused.xml")).apply(configure)
/** Every integration switch stated, so no test hangs on a compiled-in default. */
private fun ChatPreferences.integrationsOff() {
setLogsynch_wintestNetworkListenerEnabled(false)
setLogsynch_ucxUDPWkdCallListenerEnabled(false)
setLogsynch_fileBasedWkdCallInterpreterEnabled(false)
setTrxSynch_ucxLogUDPListenerEnabled(false)
setLogsynch_wintestQrgSyncEnabled(false)
setNotify_dxClusterServerEnabled(false)
setStn_pstRotatorEnabled(false)
setAirScout_asUDPListenerEnabled(false)
setTrxSynch_so2rEnabled(false)
setStn_pstRotator2Enabled(false)
}
/** An empty profile, as "new profile" creates it: no login, the template's integrations on. */
private fun emptyProfile() = prefs {
integrationsOff()
setStn_loginCallSign("")
setStn_loginPassword("")
setStn_loginLocatorMainCat("JO54ME")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(true)
setLoginChatCategorySecond(ChatCategory(3))
setLogsynch_ucxUDPWkdCallListenerEnabled(true)
setAirScout_asUDPListenerEnabled(true)
}
private fun contestStation() = WizardDonor("contest", "Conteststation", prefs {
integrationsOff()
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("secret")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setStn_bandActive432(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
setStn_antennaBeamWidthDeg(28.0)
setStn_qtfDefault(270.0)
setLogsynch_wintestNetworkListenerEnabled(true)
setLogsynch_wintestNetworkPort(9871)
setLogsynch_wintestNetworkStationNameOfKST("KST")
setLogsynch_wintestQrgSyncEnabled(true)
setStn_pstRotatorEnabled(true)
setStn_pstRotatorHost("127.0.0.1")
setStn_pstRotatorPort(12000)
})
private fun portable() = WizardDonor("portable", "Portabel", prefs {
integrationsOff()
setStn_loginCallSign("DL0TEST/P")
setStn_loginPassword("secret")
setStn_loginLocatorMainCat("JN58QA")
setStn_bandActive1240(true)
setLoginChatCategoryMain(ChatCategory(3))
setLoginToSecondChatEnabled(false)
})
@Test
fun withoutDonorsNothingChanges() {
val state = SetupWizardState(emptyProfile())
assertEquals(listOf(WizardSource.NEW), state.loginSources)
assertEquals(listOf(WizardSource.NEW, WizardSource.KEEP), state.stationSources)
assertTrue(state.donors.isEmpty())
}
@Test
fun aDonorAddsTakeBetweenNewAndKeep() {
val state = SetupWizardState(emptyProfile(), listOf(contestStation()))
assertEquals(listOf(WizardSource.NEW, WizardSource.TAKE), state.loginSources)
assertEquals(listOf(WizardSource.NEW, WizardSource.TAKE, WizardSource.KEEP), state.stationSources)
assertTrue(state.hasEntryPage)
assertNull(state.loginSource, "with a choice nothing is preselected")
}
@Test
fun aSingleDonorIsChosenWithTheSource() {
val donor = contestStation()
val state = SetupWizardState(emptyProfile(), listOf(donor))
state.chooseLoginSource(WizardSource.TAKE)
state.chooseStationSource(WizardSource.NEW)
assertEquals(donor, state.loginDonor, "one donor needs no second question")
assertTrue(state.canGoNext)
}
@Test
fun severalDonorsNeedAChoice() {
val contest = contestStation()
val state = SetupWizardState(emptyProfile(), listOf(contest, portable()))
state.chooseLoginSource(WizardSource.TAKE)
state.chooseStationSource(WizardSource.NEW)
assertNull(state.loginDonor)
assertFalse(state.canGoNext, "which profile is not said yet")
state.chooseLoginDonor(contest)
assertTrue(state.canGoNext)
}
@Test
fun aDonorThatIsNotOfferedIsNotAccepted() {
val state = SetupWizardState(emptyProfile(), listOf(contestStation()))
state.chooseLoginSource(WizardSource.TAKE)
val first = state.loginDonor
state.chooseLoginDonor(portable())
assertEquals(first, state.loginDonor)
}
@Test
fun takingTheLoginSkipsItsPageAndLeavesItChangeable() {
val state = SetupWizardState(emptyProfile(), listOf(contestStation()))
state.chooseLoginSource(WizardSource.TAKE)
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertEquals("DL0TEST", state.callsign)
assertEquals("secret", state.password)
assertFalse(state.pages.contains(WizardPage.LOGIN))
state.name = "Philipp"
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
state.edit(WizardPage.LOGIN)
state.callsign = "DL0TEST/P"
state.next()
assertEquals("DL0TEST/P", state.callsign, "a taken callsign gets its /P")
}
@Test
fun takingTheStationLoadsEverythingThePagesShow() {
val state = SetupWizardState(emptyProfile(), listOf(contestStation()))
state.chooseLoginSource(WizardSource.NEW)
state.chooseStationSource(WizardSource.TAKE)
state.next()
assertEquals("JO50AA", state.locator)
assertEquals(setOf(WizardBand.B144, WizardBand.B432), state.bands)
assertEquals(2, state.category)
assertFalse(state.secondChat)
assertEquals(28.0, state.antenna.beamWidthDeg)
assertEquals(WizardLogProgram.WINTEST, state.integrations.logProgram)
assertTrue(state.integrations.rotator)
assertTrue(state.summaryQrgFollow)
assertEquals(
listOf(WizardPage.ENTRY, WizardPage.PERSONAL, WizardPage.LOGIN, WizardPage.SUMMARY),
state.pages,
"a taken station shows no page of its own",
)
}
@Test
fun takingAStationNamesWhatTheOwnProfileLoses() {
val state = SetupWizardState(emptyProfile(), listOf(contestStation()))
state.chooseLoginSource(WizardSource.NEW)
state.chooseStationSource(WizardSource.TAKE)
state.next()
// The own profile had the second chat, the network listener and AirScout on; the
// donor has none of them. Win-Test and the rotator come new and are not "switched off".
assertEquals(
listOf(WizardSwitch.SECOND_CHAT, WizardSwitch.LOG_UDP, WizardSwitch.AIRSCOUT),
state.switchedOff,
)
}
@Test
fun aTakenStationKeepsSeveralLogSources() {
val several = WizardDonor("several", "Zwei Quellen", contestStation().prefs.apply {
setLogsynch_fileBasedWkdCallInterpreterEnabled(true)
})
val state = SetupWizardState(emptyProfile(), listOf(several))
state.chooseLoginSource(WizardSource.NEW)
state.chooseStationSource(WizardSource.TAKE)
state.next()
assertFalse(state.logPageEditable, "the page knows one source and would switch the other off")
state.edit(WizardPage.LOG)
assertFalse(state.pages.contains(WizardPage.LOG))
}
@Test
fun changingTheDonorLoadsItsValues() {
val contest = contestStation()
val other = portable()
val state = SetupWizardState(emptyProfile(), listOf(contest, other))
state.chooseLoginSource(WizardSource.NEW)
state.chooseStationSource(WizardSource.TAKE)
state.chooseStationDonor(contest)
state.next()
assertEquals("JO50AA", state.locator)
state.back()
state.chooseStationDonor(other)
state.next()
assertEquals("JN58QA", state.locator)
assertEquals(setOf(WizardBand.B1240), state.bands)
assertEquals(3, state.category)
assertEquals(WizardLogProgram.NONE, state.integrations.logProgram, "nothing of the first donor is left")
assertFalse(state.integrations.rotator)
}
@Test
fun goingBackToNewDropsWhatWasTaken() {
val state = SetupWizardState(emptyProfile(), listOf(contestStation()))
state.chooseLoginSource(WizardSource.NEW)
state.chooseStationSource(WizardSource.TAKE)
state.next()
state.back()
state.chooseStationSource(WizardSource.NEW)
state.next()
assertEquals("", state.locator)
assertTrue(state.bands.isEmpty())
assertEquals(WizardLogProgram.NONE, state.integrations.logProgram)
assertFalse(state.integrations.rotator)
assertTrue(state.pages.contains(WizardPage.LOG))
}
// --- against real files -------------------------------------------------------------
private fun file(name: String, configure: ChatPreferences.() -> Unit): Path {
val path = directory.resolve(name)
ChatPreferences::class.java.getResourceAsStream(ChatPreferences.PREFERENCE_RESOURCE).use { template ->
Files.copy(requireNotNull(template), path, StandardCopyOption.REPLACE_EXISTING)
}
ChatPreferences(path).apply {
assertTrue(readPreferencesFromXmlFile())
configure()
assertTrue(writePreferencesToXmlFile())
}
return path
}
private fun read(path: Path) = ChatPreferences(path).also { assertTrue(it.readPreferencesFromXmlFile()) }
@Test
fun saveWritesTheWholeTakenStationAndTheTakenLoginIntoTheOwnFile() {
val donorFile = file("donor.xml") {
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("secret")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
setStn_qtfDefault(270.0)
setTrxSynch_so2rEnabled(true)
setStn_pstRotator2Enabled(true)
setStn_pstRotator2Port(12020)
setLogsynch_wintestNetworkListenerEnabled(true)
setLogsynch_wintestNetworkStationNameOfWintestClient1("RUN")
}
val ownFile = file("own.xml") {
setStn_loginCallSign("")
setStn_loginPassword("")
setStn_on4kstServersDns("own.example")
}
val donorBytes = Files.readAllBytes(donorFile)
val own = read(ownFile)
val state = SetupWizardState(own, listOf(WizardDonor("contest", "Conteststation", read(donorFile))))
state.chooseLoginSource(WizardSource.TAKE)
state.chooseStationSource(WizardSource.TAKE)
state.next()
state.name = "Philipp"
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
assertTrue(state.writeTo(own))
val restored = read(ownFile)
assertEquals("DL0TEST", restored.getStn_loginCallSign())
assertEquals("secret", restored.getStn_loginPassword())
assertEquals("Philipp", restored.getStn_loginNameMainCat())
assertEquals("JO50AA", restored.getStn_loginLocatorMainCat())
assertEquals(270.0, restored.getStn_qtfDefault(), "a station value the wizard never asks about")
assertTrue(restored.isTrxSynch_so2rEnabled())
assertTrue(restored.isStn_pstRotator2Enabled())
assertEquals(12020, restored.getStn_pstRotator2Port())
assertTrue(restored.isLogsynch_wintestNetworkListenerEnabled())
assertEquals("RUN", restored.getLogsynch_wintestNetworkStationNameOfWintestClient1())
assertEquals("own.example", restored.getStn_on4kstServersDns(), "not part of the station")
assertArrayEquals(donorBytes, Files.readAllBytes(donorFile), "the donor's file was touched")
}
@Test
fun aPageOpenedAfterTakingOverridesTheCopy() {
val donorFile = file("donor.xml") {
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("secret")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
setStn_pstRotatorEnabled(true)
setStn_pstRotatorHost("127.0.0.1")
setStn_pstRotatorPort(12000)
}
val ownFile = file("own.xml") {
setStn_loginCallSign("")
setStn_loginPassword("")
}
val own = read(ownFile)
val state = SetupWizardState(own, listOf(WizardDonor("contest", "Conteststation", read(donorFile))))
state.chooseLoginSource(WizardSource.TAKE)
state.chooseStationSource(WizardSource.TAKE)
state.next()
state.name = "Philipp"
state.next()
state.edit(WizardPage.GEAR)
state.integrations.rotator = false
state.next()
state.edit(WizardPage.SITE)
state.locator = "JN58QA"
state.next()
assertTrue(state.writeTo(own))
val restored = read(ownFile)
assertFalse(restored.isStn_pstRotatorEnabled(), "the operator switched the taken rotator off")
assertEquals("JN58QA", restored.getStn_loginLocatorMainCat(), "the operator changed the taken locator")
}
@Test
fun takingAStationNamesSo2rAndRotatorTwoWhenTheDonorDropsThem() {
val own = emptyProfile().apply {
setTrxSynch_so2rEnabled(true)
setStn_pstRotator2Enabled(true)
}
val donorOff = contestStation()
val donorOn = WizardDonor("both-on", "Beide an", prefs {
integrationsOff()
setStn_loginCallSign("DL0BOTH")
setStn_loginPassword("secret")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
setTrxSynch_so2rEnabled(true)
setStn_pstRotator2Enabled(true)
})
val takeDrops = SetupWizardState(own, listOf(donorOff)).apply {
chooseLoginSource(WizardSource.NEW)
chooseStationSource(WizardSource.TAKE)
next()
}
assertEquals(
listOf(WizardSwitch.SO2R, WizardSwitch.ROTATOR_2),
takeDrops.switchedOff.takeLast(2),
)
val keep = SetupWizardState(own, listOf(donorOff)).apply {
chooseLoginSource(WizardSource.NEW)
chooseStationSource(WizardSource.KEEP)
next()
}
assertFalse(WizardSwitch.SO2R in keep.switchedOff)
assertFalse(WizardSwitch.ROTATOR_2 in keep.switchedOff)
val takeKeeps = SetupWizardState(own, listOf(donorOn)).apply {
chooseLoginSource(WizardSource.NEW)
chooseStationSource(WizardSource.TAKE)
next()
}
assertFalse(WizardSwitch.SO2R in takeKeeps.switchedOff)
assertFalse(WizardSwitch.ROTATOR_2 in takeKeeps.switchedOff)
val ownRotator2WithoutSo2r = emptyProfile().apply {
setTrxSynch_so2rEnabled(false)
setStn_pstRotator2Enabled(true)
}
val noSo2r = SetupWizardState(ownRotator2WithoutSo2r, listOf(donorOff)).apply {
chooseLoginSource(WizardSource.NEW)
chooseStationSource(WizardSource.TAKE)
next()
}
assertFalse(WizardSwitch.ROTATOR_2 in noSo2r.switchedOff)
assertFalse(WizardSwitch.SO2R in noSo2r.switchedOff)
}
@Test
fun theSummaryFallbackBandFollowsTheStationSource() {
val own = emptyProfile().apply { setNotify_optionalFrequencyPrefix("144") }
val donor = WizardDonor("uhf", "UHF", prefs {
integrationsOff()
setStn_loginCallSign("DL0UHF")
setStn_loginPassword("secret")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive432(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
setNotify_optionalFrequencyPrefix("432")
})
val take = SetupWizardState(own, listOf(donor)).apply {
chooseLoginSource(WizardSource.NEW)
chooseStationSource(WizardSource.TAKE)
next()
}
assertEquals("432", take.summaryFallbackBand)
val keep = SetupWizardState(own, listOf(donor)).apply {
chooseLoginSource(WizardSource.NEW)
chooseStationSource(WizardSource.KEEP)
next()
}
assertEquals("144", keep.summaryFallbackBand)
val fresh = SetupWizardState(own, listOf(donor)).apply {
chooseLoginSource(WizardSource.NEW)
chooseStationSource(WizardSource.NEW)
next()
}
assertEquals("144", fresh.summaryFallbackBand)
}
}
@@ -0,0 +1,224 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatPreferences
import org.junit.jupiter.api.Assertions.assertArrayEquals
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Assumptions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
/** When the wizard opens at all, decided without a window. */
class SetupWizardLauncherTest(@param:TempDir private val directory: Path) {
private fun templateFile(): Path {
val file = directory.resolve("preferences.xml")
ChatPreferences::class.java.getResourceAsStream(ChatPreferences.PREFERENCE_RESOURCE).use { template ->
Files.copy(requireNotNull(template), file, StandardCopyOption.REPLACE_EXISTING)
}
return file
}
private fun configuredFile(): Path {
val file = templateFile()
ChatPreferences(file).apply {
assertTrue(readPreferencesFromXmlFile())
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("secret")
assertTrue(writePreferencesToXmlFile())
}
return file
}
private val neverShown: (SetupWizardState, ChatPreferences) -> SetupWizardOutcome =
{ _, _ -> throw AssertionError("the wizard must not open here") }
@Test
fun anUnconfiguredProfileOpensTheWizard() {
var shown = 0
val outcome = SetupWizardLauncher.run(ChatPreferences(templateFile()), forced = false) { _, _ ->
shown++
SetupWizardOutcome.LATER
}
assertEquals(1, shown)
assertEquals(SetupWizardOutcome.LATER, outcome)
}
@Test
fun aConfiguredProfileStartsWithoutTheWizard() {
assertEquals(
SetupWizardOutcome.NOT_SHOWN,
SetupWizardLauncher.run(ChatPreferences(configuredFile()), forced = false, neverShown),
)
}
@Test
fun theMenuOpensItOnAConfiguredProfileToo() {
val outcome = SetupWizardLauncher.run(ChatPreferences(configuredFile()), forced = true) { state, _ ->
assertEquals(listOf(WizardSource.NEW, WizardSource.KEEP), state.loginSources)
SetupWizardOutcome.SAVED
}
assertEquals(SetupWizardOutcome.SAVED, outcome)
}
@Test
fun anUnreadableFileNeverOpensTheWizard() {
val garbage = directory.resolve("broken.xml")
Files.writeString(garbage, "this is not xml <<<")
val before = Files.readAllBytes(garbage)
// Forced as well: a wizard over a file it could not read would save over it.
assertEquals(
SetupWizardOutcome.NOT_SHOWN,
SetupWizardLauncher.run(ChatPreferences(garbage), forced = true, neverShown),
)
assertArrayEquals(before, Files.readAllBytes(garbage), "the unreadable file was touched")
}
@Test
fun aFileTheReaderThrowsOnNeverOpensTheWizard() {
val file = templateFile()
val original = Files.readString(file)
assertTrue(original.contains("<ChatCategory>2</ChatCategory>"))
Files.writeString(file, original.replace("<ChatCategory>2</ChatCategory>", "<ChatCategory>2.0</ChatCategory>"))
val before = Files.readAllBytes(file)
assertEquals(
SetupWizardOutcome.NOT_SHOWN,
SetupWizardLauncher.run(ChatPreferences(file), forced = true, neverShown),
)
assertArrayEquals(before, Files.readAllBytes(file), "the unreadable file was touched")
}
@Test
fun aFailedSaveKeepsTheWizardOpen() {
val source = ChatPreferences(templateFile()).apply { assertTrue(readPreferencesFromXmlFile()) }
val state = SetupWizardState(source).apply {
name = "Philipp"
next()
callsign = "DL0TEST"
password = "secret"
next()
locator = "JO50AA"
setBand(WizardBand.B144, true)
}
val unwritable = ChatPreferences(Files.createDirectory(directory.resolve("not-a-file")))
assertNull(saveFromWizard(state, unwritable, connect = true), "a failed write must not close the wizard")
}
@Test
fun aSaveReportsWhetherToConnect() {
val file = templateFile()
val prefs = ChatPreferences(file).apply { assertTrue(readPreferencesFromXmlFile()) }
val state = SetupWizardState(prefs).apply {
name = "Philipp"
next()
callsign = "DL0TEST"
password = "secret"
next()
locator = "JO50AA"
setBand(WizardBand.B144, true)
}
assertEquals(SetupWizardOutcome.SAVED, saveFromWizard(state, prefs, connect = false))
assertEquals(SetupWizardOutcome.SAVED_AND_CONNECT, saveFromWizard(state, prefs, connect = true))
}
private fun profileFile(name: String, callsign: String, password: String): Path {
val file = directory.resolve(name)
ChatPreferences::class.java.getResourceAsStream(ChatPreferences.PREFERENCE_RESOURCE).use { template ->
Files.copy(requireNotNull(template), file, StandardCopyOption.REPLACE_EXISTING)
}
ChatPreferences(file).apply {
assertTrue(readPreferencesFromXmlFile())
setStn_loginCallSign(callsign)
setStn_loginPassword(password)
assertTrue(writePreferencesToXmlFile())
}
return file
}
@Test
fun onlyConfiguredReadableProfilesBecomeDonors() {
val configured = profileFile("configured.xml", "DL0TEST", "secret")
val emptyLogin = profileFile("empty.xml", "", "")
val template = profileFile("template.xml", "DO5AMF", "changeMe")
val garbage = directory.resolve("garbage.xml").also { Files.writeString(it, "this is not xml <<<") }
val donors = loadDonors(
listOf(
DonorCandidate("a", "Conteststation", configured),
DonorCandidate("b", "Leer", emptyLogin),
DonorCandidate("c", "Vorlage", template),
DonorCandidate("d", "Kaputt", garbage),
DonorCandidate("e", "Fehlt", directory.resolve("missing.xml")),
)
)
assertEquals(listOf("a"), donors.map { it.profileId })
assertEquals("Conteststation", donors.single().displayName)
assertEquals("DL0TEST", donors.single().callsign)
}
@Test
fun aMissingDonorFileIsNotCreated() {
val missing = directory.resolve("missing.xml")
loadDonors(listOf(DonorCandidate("e", "Fehlt", missing)))
assertFalse(Files.exists(missing), "looking for a donor must not create its file")
}
@Test
fun readingADonorLeavesItsFileAlone() {
val configured = profileFile("configured.xml", "DL0TEST", "secret")
val before = Files.readAllBytes(configured)
loadDonors(listOf(DonorCandidate("a", "Conteststation", configured)))
assertArrayEquals(before, Files.readAllBytes(configured))
}
@Test
fun donorsAreOnlyLoadedWhenTheWizardOpens() {
var loaded = 0
val donors = { loaded++; emptyList<WizardDonor>() }
SetupWizardLauncher.run(ChatPreferences(configuredFile()), forced = false, donors, neverShown)
assertEquals(0, loaded, "a configured profile starts without reading other profiles")
var seen: List<WizardDonor>? = null
SetupWizardLauncher.run(ChatPreferences(templateFile()), forced = false, donors) { state, _ ->
seen = state.donors
SetupWizardOutcome.LATER
}
assertEquals(1, loaded)
assertEquals(emptyList<WizardDonor>(), seen)
}
@Test
fun aLinkedDirectoryToTheActiveProfileIsNotOfferedAsItsOwnDonor() {
val dirB = Files.createDirectory(directory.resolve("b"))
val fileInB = dirB.resolve("preferences.xml")
Files.copy(configuredFile(), fileInB, StandardCopyOption.REPLACE_EXISTING)
val linkA = directory.resolve("a")
val linked = runCatching { Files.createSymbolicLink(linkA, dirB) }
Assumptions.assumeTrue(
linked.isSuccess,
"file system refused symbolic link: ${linked.exceptionOrNull()?.message}",
)
val candidates = listOf(DonorCandidate("b", "B", fileInB))
assertTrue(loadDonors(candidates, activeFile = linkA.resolve("preferences.xml")).isEmpty())
assertEquals(listOf("b"), loadDonors(candidates).map { it.profileId })
}
}
@@ -0,0 +1,628 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatCategory
import kst4contest.model.ChatPreferences
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.nio.file.Path
/**
* The wizard's rules without a window: which pages appear, what they start with, and when
* the operator may go on. Nothing here reads or writes a file.
*/
class SetupWizardStateTest {
/** Preferences that never touch a file: the path is only read by read/write calls. */
private fun prefs(configure: ChatPreferences.() -> Unit = {}): ChatPreferences =
ChatPreferences(Path.of("setup-wizard-state-test-unused.xml")).apply(configure)
private fun freshInstallation() = prefs {
setStn_loginCallSign("DO5AMF")
setStn_loginPassword("changeMe")
setStn_loginNameMainCat("KST4Contest1263")
setStn_loginLocatorMainCat("JO54ME")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(true)
setLoginChatCategorySecond(ChatCategory(3))
}
private fun duplicatedProfile() = prefs {
setStn_loginCallSign("")
setStn_loginPassword("")
setStn_loginNameMainCat("Other Operator")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setStn_bandActive432(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
}
private fun configuredProfile() = duplicatedProfile().apply {
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("secret")
setStn_loginNameMainCat("Philipp")
}
/** Fills every mandatory answer of a first installation, leaving the wizard on SITE. */
private fun SetupWizardState.fillFirstInstallation() {
name = "Philipp"
next()
callsign = "DL0TEST"
password = "secret"
next()
locator = "JO50AA"
setBand(WizardBand.B144, true)
}
@Test
fun aFreshInstallationHasNoEntryPageAndStartsEmpty() {
val state = SetupWizardState(freshInstallation())
assertFalse(state.hasEntryPage)
assertEquals(WizardPage.PERSONAL, state.page)
assertEquals(
listOf(
WizardPage.PERSONAL, WizardPage.LOGIN, WizardPage.SITE,
WizardPage.ANTENNA, WizardPage.LOG, WizardPage.GEAR, WizardPage.SUMMARY,
),
state.pages,
)
assertEquals("", state.name, "the template's name is nobody's name")
assertEquals("", state.callsign)
assertEquals("", state.locator)
assertTrue(state.bands.isEmpty())
assertNull(state.category)
assertFalse(state.secondChat)
}
@Test
fun aDuplicatedProfileIsAskedOnlyAboutTheStation() {
val state = SetupWizardState(duplicatedProfile())
assertEquals(listOf(WizardSource.NEW), state.loginSources)
assertEquals(listOf(WizardSource.NEW, WizardSource.KEEP), state.stationSources)
assertTrue(state.hasEntryPage)
assertEquals(WizardPage.ENTRY, state.page)
assertEquals(WizardSource.NEW, state.loginSource, "a single option is chosen already")
assertNull(state.stationSource, "nothing is preselected where there is a choice")
assertFalse(state.canGoNext)
}
@Test
fun aConfiguredProfileMayKeepBoth() {
val state = SetupWizardState(configuredProfile())
assertEquals(listOf(WizardSource.NEW, WizardSource.KEEP), state.loginSources)
assertEquals(listOf(WizardSource.NEW, WizardSource.KEEP), state.stationSources)
assertEquals("Philipp", state.name, "a configured profile keeps its operator's name")
}
@Test
fun keepingTheStationSkipsItsStepAndCarriesTheStoredValues() {
val state = SetupWizardState(duplicatedProfile())
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertEquals(
listOf(WizardPage.ENTRY, WizardPage.PERSONAL, WizardPage.LOGIN, WizardPage.SUMMARY),
state.pages,
)
assertEquals("JO50AA", state.locator)
assertEquals(setOf(WizardBand.B144, WizardBand.B432), state.bands)
assertEquals(2, state.category)
}
@Test
fun aNewStationStartsEmptyEvenOnAProfileThatHasOne() {
val state = SetupWizardState(duplicatedProfile())
state.chooseStationSource(WizardSource.NEW)
state.next()
assertEquals("", state.locator)
assertTrue(state.bands.isEmpty())
assertNull(state.category)
assertTrue(state.pages.contains(WizardPage.SITE))
}
@Test
fun goingBackToTheEntryPageAndOnAgainKeepsWhatWasTyped() {
val state = SetupWizardState(duplicatedProfile())
state.chooseStationSource(WizardSource.NEW)
state.next()
state.name = "Philipp"
state.back()
state.next()
assertEquals("Philipp", state.name)
state.next()
state.callsign = "DL0TEST"
state.back()
state.back()
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertEquals("JO50AA", state.locator, "a changed source loads its own values")
state.next()
assertEquals("DL0TEST", state.callsign, "the login source did not change")
}
@Test
fun callsignsWithSuffixAndLowerCaseAreAccepted() {
listOf("DL0TEST", "DL0TEST/P", "DO5AMF-2", "do5amf", " DL0TEST ").forEach {
assertTrue(SetupWizardState.isPlausibleCallsign(it), "'$it' must be accepted")
}
listOf("", "DL", "ABC", "123", "DL0 TEST", "DL0TEST|X", "DL0-TEST-2", "DL0TEST/").forEach {
assertFalse(SetupWizardState.isPlausibleCallsign(it), "'$it' must be refused")
}
}
@Test
fun onlyASixCharacterLocatorIsAccepted() {
listOf("JO50AA", "jo50aa", " JN49FL ").forEach {
assertTrue(SetupWizardState.isLocator(it), "'$it' must be accepted")
}
listOf("", "JO50", "JO50AAA", "SS50AA", "JO50YY", "JO5OAA").forEach {
assertFalse(SetupWizardState.isLocator(it), "'$it' must be refused")
}
}
@Test
fun theCategoryIsSuggestedFromTheLowestBand() {
assertNull(SetupWizardState.suggestCategory(emptySet()))
assertEquals(1, SetupWizardState.suggestCategory(setOf(WizardBand.B50, WizardBand.B144)))
assertEquals(1, SetupWizardState.suggestCategory(setOf(WizardBand.B70)))
assertEquals(2, SetupWizardState.suggestCategory(setOf(WizardBand.B144, WizardBand.B1240)))
assertEquals(2, SetupWizardState.suggestCategory(setOf(WizardBand.B432)))
assertEquals(3, SetupWizardState.suggestCategory(setOf(WizardBand.B1240, WizardBand.B10G)))
}
@Test
fun theSuggestionFollowsTheBandsUntilTheOperatorChooses() {
val state = SetupWizardState(freshInstallation())
state.setBand(WizardBand.B1240, true)
assertEquals(3, state.category)
state.setBand(WizardBand.B144, true)
assertEquals(2, state.category)
state.chooseCategory(3)
state.setBand(WizardBand.B50, true)
assertEquals(3, state.category, "an operator's choice is not overwritten")
assertEquals(1, state.suggestedCategory, "the suggestion is still shown")
}
@Test
fun aSecondChatNeedsADifferentCategory() {
val state = SetupWizardState(freshInstallation())
state.fillFirstInstallation()
assertTrue(state.canGoNext)
state.chooseSecondChat(true)
assertFalse(state.canGoNext, "the second chat has no category yet")
assertFalse(state.secondCategoryOptions.contains(2), "the main category is not offered twice")
state.secondCategory = 3
assertTrue(state.canGoNext)
state.chooseCategory(3)
assertNull(state.secondCategory, "the same chat cannot be opened twice")
assertFalse(state.canGoNext)
}
@Test
fun finishNeedsEveryMandatoryAnswer() {
val state = SetupWizardState(freshInstallation())
state.name = "Philipp"
assertFalse(state.canFinish)
state.next()
state.callsign = "DL0TEST"
state.password = "secret"
assertFalse(state.canFinish, "a new station still lacks its locator")
state.next()
state.locator = "JO50AA"
assertFalse(state.canFinish, "no band yet")
state.setBand(WizardBand.B144, true)
assertTrue(state.canFinish)
state.finish()
assertEquals(WizardPage.SUMMARY, state.page)
assertTrue(state.mandatoryComplete)
assertFalse(state.canFinish, "the summary has Save instead")
}
@Test
fun aKeptStationLetsTheOperatorFinishAfterTheLogin() {
val state = SetupWizardState(duplicatedProfile())
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.name = "Philipp"
state.next()
state.callsign = "DL0TEST/P"
state.password = "secret"
assertTrue(state.canFinish)
}
@Test
fun aRefusedEntryIsOnlyShownOnceSomethingWasTyped() {
val state = SetupWizardState(freshInstallation())
assertFalse(state.callsignRefused, "an empty field is not an error yet")
state.callsign = "DL"
assertTrue(state.callsignRefused)
state.callsign = "DL0TEST"
assertFalse(state.callsignRefused)
assertFalse(state.locatorRefused)
state.locator = "JO50"
assertTrue(state.locatorRefused)
}
@Test
fun changeFromTheSummaryOpensAStepThatWasSkipped() {
val state = SetupWizardState(configuredProfile())
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
state.edit(WizardPage.LOGIN)
assertEquals(WizardPage.LOGIN, state.page)
assertEquals("DL0TEST", state.callsign, "the kept value is there to be changed")
state.callsign = "DL0TEST/P"
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
}
@Test
fun keepingAStationWithMissingLocatorKeepsTheSitePageInTheCourse() {
val state = SetupWizardState(duplicatedProfile().apply { setStn_loginLocatorMainCat("") })
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertTrue(state.pages.contains(WizardPage.SITE))
state.name = "Philipp"
state.next()
state.callsign = "DL0TEST"
state.password = "secret"
state.next()
assertEquals(WizardPage.SITE, state.page)
assertEquals(setOf(WizardBand.B144, WizardBand.B432), state.bands)
assertEquals(2, state.category)
}
@Test
fun keepingALoginWithMissingPasswordKeepsTheLoginPageInTheCourse() {
val state = SetupWizardState(configuredProfile().apply { setStn_loginPassword("") })
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertTrue(state.pages.contains(WizardPage.LOGIN))
assertEquals("DL0TEST", state.callsign)
assertEquals("", state.password)
assertFalse(state.mandatoryComplete)
}
@Test
fun keepingAnUnknownCategoryIsIncompleteAndKeepsTheSitePage() {
val state = SetupWizardState(configuredProfile().apply { setLoginChatCategoryMain(ChatCategory(13)) })
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertFalse(state.mandatoryComplete)
assertTrue(state.pages.contains(WizardPage.SITE))
}
@Test
fun keepingValidCategoriesOutsideTheBandSuggestionsCompletesAndSkipsSite() {
val state = SetupWizardState(
configuredProfile().apply {
setLoginChatCategoryMain(ChatCategory(7))
setLoginToSecondChatEnabled(true)
setLoginChatCategorySecond(ChatCategory(9))
},
)
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertTrue(state.mandatoryComplete)
assertFalse(state.pages.contains(WizardPage.SITE))
}
@Test
fun storablePasswordsAndNamesRejectDelimitersAndOuterWhitespace() {
listOf("secret", "se cret").forEach {
assertTrue(SetupWizardState.isStorablePassword(it), "'$it' must be accepted")
}
listOf("", " ", " secret", "secret ", "se|cret", "se\ncret", "se\rcret").forEach {
assertFalse(SetupWizardState.isStorablePassword(it), "'$it' must be refused")
}
listOf("Philipp", "Philipp W").forEach {
assertTrue(SetupWizardState.isStorableName(it), "'$it' must be accepted")
}
listOf("", " ", "Phil|ipp", "Phil\nipp", "Phil\ripp").forEach {
assertFalse(SetupWizardState.isStorableName(it), "'$it' must be refused")
}
}
@Test
fun aRefusedPasswordOrNameIsReportedAndBlocksCompletion() {
val state = SetupWizardState(freshInstallation())
assertFalse(state.nameRefused)
state.name = " "
assertFalse(state.nameRefused)
assertFalse(state.canGoNext)
state.name = "Phil|ipp"
assertTrue(state.nameRefused)
assertFalse(state.canGoNext)
state.fillFirstInstallation()
state.back()
assertEquals(WizardPage.LOGIN, state.page)
assertFalse(state.passwordRefused)
listOf(" secret", "secret ", " ", "se|cret", "se\ncret").forEach { refused ->
state.password = refused
assertTrue(state.passwordRefused, "'$refused' must set passwordRefused")
assertFalse(state.canGoNext, "'$refused' must block Next on login")
assertFalse(state.mandatoryComplete, "'$refused' must block mandatoryComplete")
}
state.password = ""
assertFalse(state.passwordRefused)
assertFalse(state.canGoNext)
state.password = "se cret"
assertFalse(state.passwordRefused)
assertTrue(state.canGoNext)
assertTrue(state.mandatoryComplete)
}
@Test
fun keepingALoginWithAStorablePasswordSkipsTheLoginPage() {
val state = SetupWizardState(configuredProfile())
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertFalse(state.pages.contains(WizardPage.LOGIN))
assertEquals(WizardPage.PERSONAL, state.page)
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
}
/** A first installation whose stored integrations are those of the bundled template. */
private fun freshInstallationLikeTheTemplate() = freshInstallation().apply {
setLogsynch_wintestNetworkListenerEnabled(false)
setLogsynch_ucxUDPWkdCallListenerEnabled(true)
setLogsynch_fileBasedWkdCallInterpreterEnabled(true)
setTrxSynch_ucxLogUDPListenerEnabled(true)
setLogsynch_wintestQrgSyncEnabled(false)
setNotify_dxClusterServerEnabled(true)
setStn_pstRotatorEnabled(false)
setAirScout_asUDPListenerEnabled(true)
setLogsynch_ucxUDPWkdCallListenerPort(12060)
}
/** A duplicated profile at a Win-Test station with a rotator. */
private fun duplicatedWinTestStation() = duplicatedProfile().apply {
setLogsynch_wintestNetworkListenerEnabled(true)
setLogsynch_wintestNetworkPort(9871)
setLogsynch_wintestNetworkStationNameOfKST("KST")
setLogsynch_ucxUDPWkdCallListenerEnabled(false)
setLogsynch_fileBasedWkdCallInterpreterEnabled(false)
setLogsynch_wintestQrgSyncEnabled(true)
setTrxSynch_ucxLogUDPListenerEnabled(false)
setNotify_dxClusterServerEnabled(false)
setStn_pstRotatorEnabled(true)
setStn_pstRotatorHost("127.0.0.1")
setStn_pstRotatorPort(12000)
setAirScout_asUDPListenerEnabled(false)
setTrxSynch_so2rEnabled(false)
}
@Test
fun aNewStationStartsWithEveryIntegrationOff() {
val state = SetupWizardState(freshInstallationLikeTheTemplate())
assertEquals(WizardLogProgram.NONE, state.integrations.logProgram)
assertFalse(state.integrations.qrgFollow)
assertFalse(state.integrations.clusterServer)
assertFalse(state.integrations.rotator)
assertFalse(state.integrations.airScout)
assertEquals(
listOf(
WizardSwitch.SECOND_CHAT, WizardSwitch.LOG_UDP, WizardSwitch.LOG_FILE,
WizardSwitch.QRG_FOLLOW, WizardSwitch.CLUSTER_SERVER, WizardSwitch.AIRSCOUT,
),
state.switchedOff,
"the summary names everything the template had on",
)
}
@Test
fun theNewPagesComeAfterTheLocationAndCanBeWalkedThrough() {
val state = SetupWizardState(freshInstallationLikeTheTemplate())
state.fillFirstInstallation()
state.next()
assertEquals(WizardPage.ANTENNA, state.page)
assertTrue(state.canGoNext, "the antenna values are proposals and valid as they stand")
state.next()
assertEquals(WizardPage.LOG, state.page)
state.next()
assertEquals(WizardPage.GEAR, state.page)
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
state.back()
assertEquals(WizardPage.GEAR, state.page)
}
@Test
fun finishingEarlyStillSwitchesANewStationsIntegrationsOff() {
val state = SetupWizardState(freshInstallationLikeTheTemplate())
state.fillFirstInstallation()
assertTrue(state.canFinish)
state.finish()
assertEquals(WizardPage.SUMMARY, state.page)
assertTrue(state.switchedOff.contains(WizardSwitch.LOG_UDP), "a skipped page of a new station still applies")
assertTrue(state.switchedOff.contains(WizardSwitch.AIRSCOUT))
}
@Test
fun aKeptStationSkipsTheNewPagesAndSwitchesNothingOff() {
val state = SetupWizardState(duplicatedWinTestStation())
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertEquals(
listOf(WizardPage.ENTRY, WizardPage.PERSONAL, WizardPage.LOGIN, WizardPage.SUMMARY),
state.pages,
)
assertEquals(WizardLogProgram.WINTEST, state.integrations.logProgram, "the summary shows what is stored")
assertTrue(state.integrations.rotator)
assertEquals(emptyList<WizardSwitch>(), state.switchedOff)
assertTrue(state.logPageEditable)
}
@Test
fun changeFromTheSummaryOpensANewPageOfAKeptStation() {
val state = SetupWizardState(duplicatedWinTestStation())
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.name = "Philipp"
state.next()
state.callsign = "DL0TEST"
state.password = "secret"
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
state.edit(WizardPage.GEAR)
assertEquals(WizardPage.GEAR, state.page)
state.integrations.rotator = false
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
assertEquals(listOf(WizardSwitch.ROTATOR), state.switchedOff)
}
@Test
fun aKeptStationWithSeveralLogSourcesCannotOpenTheLogPage() {
val state = SetupWizardState(duplicatedProfile().apply {
setLogsynch_wintestNetworkListenerEnabled(false)
setLogsynch_ucxUDPWkdCallListenerEnabled(true)
setLogsynch_fileBasedWkdCallInterpreterEnabled(true)
})
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.name = "Philipp"
state.next()
state.callsign = "DL0TEST"
state.password = "secret"
state.next()
assertFalse(state.logPageEditable, "the page knows one source and would switch the other off")
state.edit(WizardPage.LOG)
assertEquals(WizardPage.SUMMARY, state.page, "the log page must stay shut")
state.edit(WizardPage.GEAR)
assertEquals(WizardPage.GEAR, state.page, "the other pages are not affected")
}
@Test
fun anInvalidOptionalPageBlocksSaving() {
val state = SetupWizardState(freshInstallationLikeTheTemplate())
state.fillFirstInstallation()
state.next()
state.next()
assertEquals(WizardPage.LOG, state.page)
state.integrations.chooseLogProgram(WizardLogProgram.UDP)
state.integrations.udpPort = 0
assertFalse(state.canGoNext)
assertFalse(state.canFinish, "a summary that cannot be saved helps nobody")
assertFalse(state.mandatoryComplete)
state.integrations.udpPort = 12060
assertTrue(state.canGoNext)
assertTrue(state.mandatoryComplete)
}
@Test
fun antennaValuesTypedForANewStationAreGoneWhenTheStationIsKeptAfterAll() {
val profile = duplicatedWinTestStation().apply { setStn_antennaBeamWidthDeg(28.0) }
val state = SetupWizardState(profile)
state.chooseStationSource(WizardSource.NEW)
state.next()
state.name = "Philipp"
state.next()
state.callsign = "DL0TEST"
state.password = "secret"
state.next()
state.locator = "JO50AA"
state.setBand(WizardBand.B144, true)
state.next()
assertEquals(WizardPage.ANTENNA, state.page)
state.antenna.beamWidthDeg = 99.0
repeat(4) { state.back() }
assertEquals(WizardPage.ENTRY, state.page)
state.chooseStationSource(WizardSource.KEEP)
state.next()
assertFalse(state.pages.contains(WizardPage.ANTENNA), "a kept station does not write the antenna page")
assertEquals(
28.0,
state.antenna.beamWidthDeg,
"the summary must not show a value that Save will not write",
)
}
@Test
fun theSummaryOfAKeptStationShowsWhatSaveLeavesOn() {
// No log source, but the DX cluster server and a frequency source are on.
val state = SetupWizardState(duplicatedWinTestStation().apply {
setLogsynch_wintestNetworkListenerEnabled(false)
setLogsynch_wintestQrgSyncEnabled(true)
setNotify_dxClusterServerEnabled(true)
})
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.name = "Philipp"
state.next()
state.callsign = "DL0TEST"
state.password = "secret"
state.next()
assertEquals(WizardPage.SUMMARY, state.page)
assertTrue(state.summaryClusterServer, "Save leaves it on, so the summary must not say no")
assertTrue(state.summaryQrgFollow)
assertFalse(state.switchedOff.contains(WizardSwitch.CLUSTER_SERVER))
// Once the log page is part of the run its answers count, and what they drop is named.
state.edit(WizardPage.LOG)
state.next()
assertFalse(state.summaryClusterServer)
assertFalse(state.summaryQrgFollow)
assertTrue(state.switchedOff.containsAll(listOf(WizardSwitch.QRG_FOLLOW, WizardSwitch.CLUSTER_SERVER)))
}
}
@@ -0,0 +1,115 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatPreferences
import kst4contest.testing.Await.awaitUntil
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assumptions.assumeFalse
import org.junit.jupiter.api.Test
import java.awt.Dialog
import java.awt.EventQueue
import java.awt.GraphicsEnvironment
import java.awt.Window
import java.nio.file.Path
import java.time.Duration
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
/**
* The wizard's dialog must open from both threads that open it: `main` at startup, and the
* event thread when the menu rebuilds the runtime. A latch-based wait deadlocked the profile
* picker in exactly the second case; see OperatorProfilePickerWindow.
*/
class SetupWizardWindowTest {
private companion object {
fun prefs() = ChatPreferences(Path.of("setup-wizard-window-test-unused.xml"))
val wizardTitle = wizardLanguageStore(SetupWizardState(prefs())).strings.wizardTitle
}
private fun showingDialog(): Window? =
Window.getWindows().firstOrNull {
it is Dialog && it.isShowing && it.javaClass.name.contains("ComposeDialog") && it.title == wizardTitle
}
/** Removes whatever dialog this test still has showing, without waiting and without failing again. */
private fun disposeLeftoverDialog() {
EventQueue.invokeLater {
showingDialog()?.dispose()
}
}
private fun <T> showWithInterruptedCleanup(show: () -> T): T {
try {
return show()
} catch (interrupted: InterruptedException) {
// invokeAndWait can post the open event after the test's first cleanup was queued.
disposeLeftoverDialog()
throw interrupted
}
}
private val closer = Executors.newSingleThreadExecutor()
/** Closes the dialog the way its X does, as soon as it is on screen. */
private fun closeOnceShowing(): Future<*> =
closer.submit {
awaitUntil(Duration.ofSeconds(10), "the wizard's dialog never appeared") {
showingDialog() != null
}
EventQueue.invokeLater {
val window = showingDialog()
window?.dispatchEvent(java.awt.event.WindowEvent(window, java.awt.event.WindowEvent.WINDOW_CLOSING))
}
}
@Test
fun closingTheWindowCountsAsLater() {
assumeFalse(GraphicsEnvironment.isHeadless(), "needs a display")
val worker = Executors.newSingleThreadExecutor()
try {
val closing = closeOnceShowing()
val prefs = prefs()
val call = worker.submit<SetupWizardOutcome> {
showWithInterruptedCleanup { SetupWizardWindow.show(SetupWizardState(prefs), prefs) }
}
// A dialog that never appears must fail the test, not hang it.
val outcome = call.get(20, TimeUnit.SECONDS)
assertEquals(SetupWizardOutcome.LATER, outcome)
assertEquals("", prefs.getStn_loginCallSign(), "closing the window wrote something")
closing.get(1, TimeUnit.SECONDS)
} finally {
disposeLeftoverDialog()
worker.shutdownNow()
closer.shutdownNow()
}
}
@Test
fun opensAndReturnsWhenCalledOnTheEventThread() {
assumeFalse(GraphicsEnvironment.isHeadless(), "needs a display")
val worker = Executors.newSingleThreadExecutor()
try {
val closing = closeOnceShowing()
val prefs = prefs()
val call = worker.submit {
showWithInterruptedCleanup {
EventQueue.invokeAndWait { SetupWizardWindow.show(SetupWizardState(prefs), prefs) }
}
}
// A deadlock here has no timeout of its own: without one this never completes.
call.get(20, TimeUnit.SECONDS)
closing.get(1, TimeUnit.SECONDS)
} finally {
disposeLeftoverDialog()
worker.shutdownNow()
closer.shutdownNow()
}
}
}
@@ -0,0 +1,339 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatCategory
import kst4contest.model.ChatPreferences
import org.junit.jupiter.api.Assertions.assertArrayEquals
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 org.junit.jupiter.api.io.TempDir
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
/**
* What the wizard does to a real preferences file: nothing until Save, exactly the answers
* afterwards, and every setting it never asked about left as it was.
*/
class SetupWizardWriteTest(@param:TempDir private val directory: Path) {
/** A copy of the bundled template, read the way the runtime reads a profile. */
private fun templateFile(): Path {
val file = directory.resolve("preferences.xml")
ChatPreferences::class.java.getResourceAsStream(ChatPreferences.PREFERENCE_RESOURCE).use { template ->
Files.copy(requireNotNull(template), file, StandardCopyOption.REPLACE_EXISTING)
}
return file
}
private fun read(file: Path): ChatPreferences =
ChatPreferences(file).also { assertTrue(it.readPreferencesFromXmlFile(), "reading $file failed") }
/** A profile an operator set up: read the template, change it, write it back. */
private fun configuredFile(change: ChatPreferences.() -> Unit = {}): Path {
val file = templateFile()
read(file).apply {
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("secret")
setStn_loginNameMainCat("Philipp")
setStn_loginNameSecondCat("Philipp")
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(false)
change()
assertTrue(writePreferencesToXmlFile())
}
return file
}
private fun SetupWizardState.answerFirstInstallation() {
name = "Philipp"
next()
callsign = "DL0TEST"
password = "secret"
next()
locator = "JO50AA"
setBand(WizardBand.B144, true)
setBand(WizardBand.B1240, true)
finish()
}
@Test
fun nothingIsWrittenBeforeSave() {
val file = templateFile()
val prefs = read(file)
// Taken after the read, so only the wizard is measured here.
val before = Files.readAllBytes(file)
SetupWizardState(prefs).answerFirstInstallation()
assertArrayEquals(before, Files.readAllBytes(file), "the file changed without Save")
assertEquals("DO5AMF", prefs.getStn_loginCallSign(), "the preferences changed without Save")
}
@Test
fun saveWritesExactlyTheAnswers() {
val file = templateFile()
val prefs = read(file)
val state = SetupWizardState(prefs)
state.answerFirstInstallation()
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertEquals("DL0TEST", restored.getStn_loginCallSign())
assertEquals("secret", restored.getStn_loginPassword())
assertEquals("Philipp", restored.getStn_loginNameMainCat())
assertEquals("JO50AA", restored.getStn_loginLocatorMainCat())
assertTrue(restored.isStn_bandActive144())
assertTrue(restored.isStn_bandActive1240())
assertFalse(restored.isStn_bandActive432(), "a band the operator did not tick is off")
assertEquals(2, restored.getLoginChatCategoryMain().categoryNumber)
assertFalse(restored.isLoginToSecondChatEnabled(), "a new station starts without a second chat")
}
@Test
fun whatTheWizardNeverAskedAboutIsLeftAsItWas() {
val file = templateFile()
val prefs = read(file)
val server = prefs.getStn_on4kstServersDns()
val rotatorPort = prefs.getStn_pstRotatorPort()
val beamWidth = prefs.getStn_antennaBeamWidthDeg()
val state = SetupWizardState(prefs)
state.answerFirstInstallation()
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertEquals(server, restored.getStn_on4kstServersDns())
assertEquals(rotatorPort, restored.getStn_pstRotatorPort())
assertEquals(beamWidth, restored.getStn_antennaBeamWidthDeg())
}
@Test
fun aCallsignIsStoredAsTyped() {
val file = templateFile()
val prefs = read(file)
val state = SetupWizardState(prefs)
state.name = "Philipp"
state.next()
state.callsign = " do5amf-2 "
state.password = "secret"
state.next()
state.locator = " jo50aa "
state.setBand(WizardBand.B144, true)
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertEquals("do5amf-2", restored.getStn_loginCallSign(), "only the surrounding blanks go")
assertEquals("jo50aa", restored.getStn_loginLocatorMainCat(), "the Station tab stores it as typed too")
}
@Test
fun aKeptCategoryOutsideTheSuggestionsSurvives() {
val file = configuredFile {
setLoginChatCategoryMain(ChatCategory(7))
setLoginToSecondChatEnabled(true)
setLoginChatCategorySecond(ChatCategory(9))
}
val prefs = read(file)
val state = SetupWizardState(prefs)
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertEquals(7, restored.getLoginChatCategoryMain().categoryNumber)
assertTrue(restored.isLoginToSecondChatEnabled())
assertEquals(9, restored.getLoginChatCategorySecond().categoryNumber)
}
@Test
fun theSecondNameFollowsTheFirstUnlessItWasSetApart() {
val following = configuredFile()
val prefs = read(following)
val state = SetupWizardState(prefs)
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.name = "Marc"
state.next()
assertTrue(state.writeTo(prefs))
assertEquals("Marc", read(following).getStn_loginNameSecondCat())
val apart = configuredFile { setStn_loginNameSecondCat("Philipp SHF") }
val apartPrefs = read(apart)
val apartState = SetupWizardState(apartPrefs)
apartState.chooseLoginSource(WizardSource.KEEP)
apartState.chooseStationSource(WizardSource.KEEP)
apartState.next()
apartState.name = "Marc"
apartState.next()
assertTrue(apartState.writeTo(apartPrefs))
assertEquals("Philipp SHF", read(apart).getStn_loginNameSecondCat(), "a name set apart is the operator's")
}
@Test
fun anUntouchedLanguageStaysEvenIfThisBuildDoesNotKnowIt() {
val file = configuredFile { setGuiOptions_language("fr") }
val prefs = read(file)
val state = SetupWizardState(prefs)
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
assertTrue(state.writeTo(prefs))
assertEquals("fr", read(file).getGuiOptions_language())
}
@Test
fun incompleteAnswersAreNotWritten() {
val file = templateFile()
val prefs = read(file)
val before = Files.readAllBytes(file)
val state = SetupWizardState(prefs)
state.name = "Philipp"
assertFalse(state.writeTo(prefs))
assertArrayEquals(before, Files.readAllBytes(file))
assertEquals("DO5AMF", prefs.getStn_loginCallSign())
}
@Test
fun aFailedWriteIsReported() {
val source = read(templateFile())
// A directory where the file should be: the write cannot succeed.
val unwritable = ChatPreferences(Files.createDirectory(directory.resolve("not-a-file")))
val state = SetupWizardState(source)
state.answerFirstInstallation()
assertFalse(state.writeTo(unwritable), "a write that failed must not read as saved")
}
@Test
fun aNewStationWithoutALogProgramHasEverySynchronisationOff() {
val file = templateFile()
val prefs = read(file)
val state = SetupWizardState(prefs)
state.answerFirstInstallation()
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertFalse(restored.isLogsynch_wintestNetworkListenerEnabled())
assertFalse(restored.isLogsynch_ucxUDPWkdCallListenerEnabled())
assertFalse(restored.isLogsynch_fileBasedWkdCallInterpreterEnabled())
assertFalse(restored.isTrxSynch_ucxLogUDPListenerEnabled())
assertFalse(restored.isLogsynch_wintestQrgSyncEnabled())
assertFalse(restored.isNotify_dxClusterServerEnabled())
assertFalse(restored.isStn_pstRotatorEnabled())
assertFalse(restored.isAirScout_asUDPListenerEnabled())
}
@Test
fun theAnswersOfTheNewPagesAreWritten() {
val file = templateFile()
val prefs = read(file)
val state = SetupWizardState(prefs)
state.name = "Philipp"
state.next()
state.callsign = "DL0TEST"
state.password = "secret"
state.next()
state.locator = "JO50AA"
state.setBand(WizardBand.B144, true)
state.next()
state.antenna.beamWidthDeg = 28.0
state.antenna.heightAslText = "612"
state.next()
state.integrations.chooseLogProgram(WizardLogProgram.WINTEST)
state.integrations.wintestPort = 9871
// Stated, not taken from the template: without a name the page could not be left.
state.integrations.wintestStationName = "KST"
state.integrations.qrgFollow = true
state.next()
assertEquals(WizardPage.GEAR, state.page)
state.integrations.rotator = true
state.integrations.rotatorHost = "127.0.0.1"
state.integrations.rotatorPort = 12000
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertEquals(28.0, restored.getStn_antennaBeamWidthDeg())
assertEquals(612.0, restored.getStn_pathAnalysisOwnHeightAslMeters())
assertTrue(restored.isLogsynch_wintestNetworkListenerEnabled())
assertEquals(9871, restored.getLogsynch_wintestNetworkPort())
assertTrue(restored.isLogsynch_wintestQrgSyncEnabled())
assertFalse(restored.isLogsynch_ucxUDPWkdCallListenerEnabled())
assertTrue(restored.isStn_pstRotatorEnabled())
assertFalse(restored.isAirScout_asUDPListenerEnabled())
}
@Test
fun aKeptStationKeepsEveryIntegrationAsItWas() {
// The template's integrations, several log sources among them, under a real login.
val file = configuredFile()
val before = read(file)
val prefs = read(file)
val state = SetupWizardState(prefs)
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertEquals(before.isLogsynch_ucxUDPWkdCallListenerEnabled(), restored.isLogsynch_ucxUDPWkdCallListenerEnabled())
assertEquals(
before.isLogsynch_fileBasedWkdCallInterpreterEnabled(),
restored.isLogsynch_fileBasedWkdCallInterpreterEnabled(),
)
assertEquals(before.isTrxSynch_ucxLogUDPListenerEnabled(), restored.isTrxSynch_ucxLogUDPListenerEnabled())
assertEquals(before.isNotify_dxClusterServerEnabled(), restored.isNotify_dxClusterServerEnabled())
assertEquals(before.isAirScout_asUDPListenerEnabled(), restored.isAirScout_asUDPListenerEnabled())
assertEquals(before.getStn_antennaBeamWidthDeg(), restored.getStn_antennaBeamWidthDeg())
assertTrue(
restored.isLogsynch_ucxUDPWkdCallListenerEnabled() && restored.isLogsynch_fileBasedWkdCallInterpreterEnabled(),
"the template has two log sources on; if this fails the template changed and the test needs another example",
)
}
@Test
fun openingOneNewPageOfAKeptStationWritesOnlyThatPage() {
val file = configuredFile()
val before = read(file)
val prefs = read(file)
val state = SetupWizardState(prefs)
state.chooseLoginSource(WizardSource.KEEP)
state.chooseStationSource(WizardSource.KEEP)
state.next()
state.next()
state.edit(WizardPage.GEAR)
state.integrations.rotator = true
state.integrations.rotatorHost = "127.0.0.1"
state.integrations.rotatorPort = 12000
state.next()
assertTrue(state.writeTo(prefs))
val restored = read(file)
assertTrue(restored.isStn_pstRotatorEnabled())
assertEquals(
before.isLogsynch_fileBasedWkdCallInterpreterEnabled(),
restored.isLogsynch_fileBasedWkdCallInterpreterEnabled(),
"the log page was not opened, so the log sources stay",
)
assertEquals(before.isNotify_dxClusterServerEnabled(), restored.isNotify_dxClusterServerEnabled())
}
}
@@ -0,0 +1,151 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatPreferences
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.nio.file.Path
/**
* The antenna and power answers: always proposals taken from what is stored, never empty,
* and the site elevation read the way the Station tab reads it.
*/
class WizardAntennaTest {
private fun prefs(configure: ChatPreferences.() -> Unit = {}): ChatPreferences =
ChatPreferences(Path.of("wizard-antenna-test-unused.xml")).apply(configure)
private fun stored() = prefs {
setStn_antennaBeamWidthDeg(28.0)
setStn_pathAnalysisOwnAntennaGainDbi(16.5)
setStn_pathAnalysisOwnAntennaHeightMeters(18.0)
setStn_pathAnalysisOwnTxPowerWatts(400.0)
setStn_pathAnalysisOwnHeightAslMeters(612.0)
}
@Test
fun theAnswersStartAsTheStoredValues() {
val antenna = WizardAntenna(stored())
assertEquals(28.0, antenna.beamWidthDeg)
assertEquals(16.5, antenna.gainDbi)
assertEquals(18.0, antenna.heightMeters)
assertEquals(400.0, antenna.txPowerWatts)
assertEquals("612", antenna.heightAslText, "a whole number is shown without a decimal point")
assertTrue(antenna.complete)
}
@Test
fun anUnsetSiteElevationIsAnEmptyField() {
val antenna = WizardAntenna(prefs { setStn_pathAnalysisOwnHeightAslMeters(Double.NaN) })
assertEquals("", antenna.heightAslText)
assertFalse(antenna.heightAslRefused, "empty means the elevation model, not an error")
assertTrue(antenna.complete)
}
@Test
fun aFractionalSiteElevationKeepsItsFraction() {
val antenna = WizardAntenna(prefs { setStn_pathAnalysisOwnHeightAslMeters(250.5) })
assertEquals("250.5", antenna.heightAslText)
}
@Test
fun theSiteElevationIsReadTheWayTheStationTabReadsIt() {
val antenna = WizardAntenna(stored())
listOf("", " ", "250", "250,5", "250.5", "-100").forEach {
antenna.heightAslText = it
assertFalse(antenna.heightAslRefused, "'$it' must be accepted")
}
listOf("abc", "99999", "-501", "12 m").forEach {
antenna.heightAslText = it
assertTrue(antenna.heightAslRefused, "'$it' must be refused")
assertFalse(antenna.complete)
}
}
@Test
fun aNumberThatIsNotOneMakesThePageIncomplete() {
val antenna = WizardAntenna(stored())
antenna.gainDbi = Double.NaN
assertFalse(antenna.complete)
antenna.gainDbi = 12.0
antenna.txPowerWatts = Double.POSITIVE_INFINITY
assertFalse(antenna.complete)
}
@Test
fun antennaHeightMustBeNonNegative() {
val antenna = WizardAntenna(stored())
antenna.heightMeters = -5.0
assertFalse(antenna.complete)
antenna.heightMeters = 0.0
assertTrue(antenna.complete)
}
@Test
fun writingPutsTheAnswersIntoThePreferences() {
val target = prefs()
val antenna = WizardAntenna(stored())
antenna.beamWidthDeg = 35.0
antenna.heightAslText = "250,5"
antenna.writeTo(target)
assertEquals(35.0, target.getStn_antennaBeamWidthDeg())
assertEquals(16.5, target.getStn_pathAnalysisOwnAntennaGainDbi())
assertEquals(18.0, target.getStn_pathAnalysisOwnAntennaHeightMeters())
assertEquals(400.0, target.getStn_pathAnalysisOwnTxPowerWatts())
assertEquals(250.5, target.getStn_pathAnalysisOwnHeightAslMeters())
}
@Test
fun anEmptySiteElevationIsWrittenAsUnset() {
val target = prefs { setStn_pathAnalysisOwnHeightAslMeters(612.0) }
val antenna = WizardAntenna(stored())
antenna.heightAslText = ""
antenna.writeTo(target)
assertTrue(target.getStn_pathAnalysisOwnHeightAslMeters().isNaN(), "empty hands the elevation back to the model")
}
@Test
fun loadingTheStoredValuesAgainDropsWhatWasTyped() {
val antenna = WizardAntenna(stored())
antenna.beamWidthDeg = 99.0
antenna.gainDbi = 1.0
antenna.heightMeters = 2.0
antenna.txPowerWatts = 3.0
antenna.heightAslText = "abc"
antenna.loadStored()
assertEquals(28.0, antenna.beamWidthDeg)
assertEquals(16.5, antenna.gainDbi)
assertEquals(18.0, antenna.heightMeters)
assertEquals(400.0, antenna.txPowerWatts)
assertEquals("612", antenna.heightAslText)
assertTrue(antenna.complete)
}
@Test
fun aNegativeStoredAntennaHeightIsClampedToZero() {
val prefs = stored()
val field = ChatPreferences::class.java.getDeclaredField("stn_pathAnalysisOwnAntennaHeightMeters")
field.isAccessible = true
field.setDouble(prefs, -2.0)
val antenna = WizardAntenna(prefs)
assertEquals(0.0, antenna.heightMeters)
assertTrue(antenna.complete)
}
}
@@ -0,0 +1,363 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatPreferences
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.nio.file.Path
/**
* The answers about log program, rotator and AirScout: what a new station starts with, what
* a kept one shows, when a page may be left, and what is written.
*/
class WizardIntegrationsTest {
private fun prefs(configure: ChatPreferences.() -> Unit = {}): ChatPreferences =
ChatPreferences(Path.of("wizard-integrations-test-unused.xml")).apply(configure)
/** Everything off, so each test states what it switches on. */
private fun allOff(configure: ChatPreferences.() -> Unit = {}) = prefs {
setLogsynch_wintestNetworkListenerEnabled(false)
setLogsynch_ucxUDPWkdCallListenerEnabled(false)
setLogsynch_fileBasedWkdCallInterpreterEnabled(false)
setTrxSynch_ucxLogUDPListenerEnabled(false)
setLogsynch_wintestQrgSyncEnabled(false)
setNotify_dxClusterServerEnabled(false)
setStn_pstRotatorEnabled(false)
setAirScout_asUDPListenerEnabled(false)
setTrxSynch_so2rEnabled(false)
setStn_pstRotator2Enabled(false)
setLogsynch_ucxUDPWkdCallListenerPort(12060)
setLogsynch_wintestNetworkPort(9871)
setLogsynch_wintestNetworkStationNameOfKST("KST")
setStn_pstRotatorHost("127.0.0.1")
setStn_pstRotatorPort(12000)
setStn_pstRotator2Port(12010)
setAirScout_asCommunicationPort(9872)
setAirScout_asServerNameString("AS")
setAirScout_asClientNameString("KST")
configure()
}
/** What the bundled template switches on. */
private fun likeTheTemplate() = allOff {
setLogsynch_ucxUDPWkdCallListenerEnabled(true)
setLogsynch_fileBasedWkdCallInterpreterEnabled(true)
setTrxSynch_ucxLogUDPListenerEnabled(true)
setNotify_dxClusterServerEnabled(true)
setAirScout_asUDPListenerEnabled(true)
}
private fun winTestStation() = allOff {
setLogsynch_wintestNetworkListenerEnabled(true)
setLogsynch_wintestNetworkPort(9999)
setLogsynch_wintestQrgSyncEnabled(true)
setNotify_dxClusterServerEnabled(true)
setStn_pstRotatorEnabled(true)
}
@Test
fun aKeptStationShowsWhatIsStored() {
val answers = WizardIntegrations(winTestStation())
assertEquals(WizardLogProgram.WINTEST, answers.logProgram)
assertEquals(9999, answers.wintestPort)
assertTrue(answers.qrgFollow)
assertTrue(answers.clusterServer)
assertTrue(answers.rotator)
assertFalse(answers.airScout)
assertFalse(answers.severalStoredLogSources)
}
@Test
fun aNewStationStartsWithEverythingOffButKeepsTheNumbers() {
val answers = WizardIntegrations(winTestStation())
answers.loadFresh()
assertEquals(WizardLogProgram.NONE, answers.logProgram)
assertFalse(answers.qrgFollow)
assertFalse(answers.clusterServer)
assertFalse(answers.rotator)
assertFalse(answers.airScout)
assertEquals(9999, answers.wintestPort, "a port the operator once set is a proposal, not lost")
assertTrue(answers.logComplete)
assertTrue(answers.gearComplete)
}
@Test
fun loadingTheStoredValuesAgainUndoesAFreshStart() {
val answers = WizardIntegrations(winTestStation())
answers.loadFresh()
answers.loadStored()
assertEquals(WizardLogProgram.WINTEST, answers.logProgram)
assertTrue(answers.rotator)
}
@Test
fun severalStoredSourcesMakeTheLogPageUneditable() {
val answers = WizardIntegrations(likeTheTemplate())
assertTrue(answers.severalStoredLogSources, "the template has the network listener and the file on")
// Shown as one of them, the network one first; the state decides not to offer the page.
assertEquals(WizardLogProgram.UDP, answers.logProgram)
}
@Test
fun leavingANetworkProgramDropsWhatOnlyANetworkProgramCanDo() {
val answers = WizardIntegrations(allOff())
answers.chooseLogProgram(WizardLogProgram.UDP)
answers.qrgFollow = true
answers.clusterServer = true
assertTrue(answers.networked)
answers.chooseLogProgram(WizardLogProgram.FILE)
assertFalse(answers.networked)
assertFalse(answers.qrgFollow)
assertFalse(answers.clusterServer)
}
@Test
fun aLogFileNeedsAFile() {
val answers = WizardIntegrations(allOff())
// The compiled-in default names a file, which is a proposal like every stored value.
answers.filePath = ""
answers.chooseLogProgram(WizardLogProgram.FILE)
assertFalse(answers.logComplete)
answers.filePath = "/home/op/log.txt"
assertTrue(answers.logComplete)
}
@Test
fun anInvalidPortMakesItsPageIncomplete() {
val answers = WizardIntegrations(allOff())
answers.chooseLogProgram(WizardLogProgram.UDP)
answers.udpPort = 0
assertFalse(answers.logComplete)
answers.udpPort = 70000
assertFalse(answers.logComplete)
answers.udpPort = 12060
assertTrue(answers.logComplete)
answers.chooseLogProgram(WizardLogProgram.WINTEST)
answers.wintestStationName = " "
assertFalse(answers.logComplete, "Win-Test needs a station name to send from")
answers.wintestStationName = "KST"
answers.wintestPort = -1
assertFalse(answers.logComplete)
// A port of a program that is not chosen is nobody's problem.
answers.chooseLogProgram(WizardLogProgram.NONE)
assertTrue(answers.logComplete)
answers.airScout = true
answers.airScoutPort = 0
assertFalse(answers.gearComplete)
answers.airScoutPort = 9872
answers.airScoutServerName = "A\"S"
assertFalse(answers.gearComplete, "a quotation mark breaks the AirScout message")
answers.airScoutServerName = "AS"
assertTrue(answers.gearComplete)
answers.rotator = true
answers.rotatorHost = " "
assertFalse(answers.gearComplete)
}
@Test
fun aRotatorPortNextToRotatorTwoIsRefusedOnlyWithSo2r() {
val withSo2r = WizardIntegrations(allOff {
setTrxSynch_so2rEnabled(true)
setStn_pstRotator2Enabled(true)
})
withSo2r.rotator = true
withSo2r.rotatorPort = 12011
assertTrue(withSo2r.rotatorPortClashes, "PSTRotator answers on port + 1")
assertFalse(withSo2r.gearComplete)
withSo2r.rotatorPort = 12000
assertFalse(withSo2r.rotatorPortClashes)
assertTrue(withSo2r.gearComplete)
val withoutSo2r = WizardIntegrations(allOff())
withoutSo2r.rotator = true
withoutSo2r.rotatorPort = 12011
assertFalse(withoutSo2r.rotatorPortClashes, "rotator 2 is not in use without SO2R")
assertTrue(withoutSo2r.gearComplete)
}
@Test
fun writingTheLogPageSwitchesExactlyTheChosenSourceOn() {
val target = likeTheTemplate()
val answers = WizardIntegrations(target)
answers.loadFresh()
answers.chooseLogProgram(WizardLogProgram.WINTEST)
answers.wintestPort = 9871
answers.wintestStationName = " KST "
answers.qrgFollow = true
answers.writeLogTo(target)
assertTrue(target.isLogsynch_wintestNetworkListenerEnabled())
assertFalse(target.isLogsynch_ucxUDPWkdCallListenerEnabled())
assertFalse(target.isLogsynch_fileBasedWkdCallInterpreterEnabled())
assertEquals(9871, target.getLogsynch_wintestNetworkPort())
assertEquals("KST", target.getLogsynch_wintestNetworkStationNameOfKST(), "trimmed, as the tab stores it")
assertTrue(target.isLogsynch_wintestQrgSyncEnabled())
assertFalse(target.isTrxSynch_ucxLogUDPListenerEnabled(), "the other program's frequency source goes off")
assertFalse(target.isNotify_dxClusterServerEnabled())
assertTrue(target.isAirScout_asUDPListenerEnabled(), "the log page does not touch AirScout")
}
@Test
fun writingNoLogProgramSwitchesEverySynchronisationOff() {
val target = likeTheTemplate()
val answers = WizardIntegrations(target)
answers.loadFresh()
answers.writeLogTo(target)
assertFalse(target.isLogsynch_wintestNetworkListenerEnabled())
assertFalse(target.isLogsynch_ucxUDPWkdCallListenerEnabled())
assertFalse(target.isLogsynch_fileBasedWkdCallInterpreterEnabled())
assertFalse(target.isTrxSynch_ucxLogUDPListenerEnabled())
assertFalse(target.isLogsynch_wintestQrgSyncEnabled())
assertFalse(target.isNotify_dxClusterServerEnabled())
assertEquals(12060, target.getLogsynch_ucxUDPWkdCallListenerPort(), "an unused port is left alone")
}
@Test
fun writingTheGearPageSetsRotatorAndAirScoutOnly() {
val target = likeTheTemplate()
val answers = WizardIntegrations(target)
answers.loadFresh()
answers.rotator = true
answers.rotatorHost = " 192.168.1.20 "
answers.rotatorPort = 12040
answers.writeGearTo(target)
assertTrue(target.isStn_pstRotatorEnabled())
assertEquals("192.168.1.20", target.getStn_pstRotatorHost())
assertEquals(12040, target.getStn_pstRotatorPort())
assertFalse(target.isAirScout_asUDPListenerEnabled())
assertEquals(9872, target.getAirScout_asCommunicationPort(), "an unused port is left alone")
assertTrue(target.isLogsynch_ucxUDPWkdCallListenerEnabled(), "the gear page does not touch the log sources")
}
@Test
fun theStoredSwitchesAreWhatTheProfileHasOn() {
val template = WizardIntegrations(likeTheTemplate())
assertEquals(
setOf(WizardSwitch.LOG_UDP, WizardSwitch.LOG_FILE, WizardSwitch.QRG_FOLLOW, WizardSwitch.CLUSTER_SERVER),
template.storedLogSwitches(),
)
assertEquals(setOf(WizardSwitch.AIRSCOUT), template.storedGearSwitches())
val nothing = WizardIntegrations(allOff())
assertEquals(emptySet<WizardSwitch>(), nothing.storedLogSwitches())
assertEquals(emptySet<WizardSwitch>(), nothing.storedGearSwitches())
}
@Test
fun theAnsweredSwitchesFollowThePages() {
val answers = WizardIntegrations(likeTheTemplate())
answers.loadFresh()
assertEquals(emptySet<WizardSwitch>(), answers.answeredLogSwitches())
assertEquals(emptySet<WizardSwitch>(), answers.answeredGearSwitches())
answers.chooseLogProgram(WizardLogProgram.WINTEST)
answers.qrgFollow = true
answers.clusterServer = true
answers.rotator = true
assertEquals(
setOf(WizardSwitch.LOG_WINTEST, WizardSwitch.QRG_FOLLOW, WizardSwitch.CLUSTER_SERVER),
answers.answeredLogSwitches(),
)
assertEquals(setOf(WizardSwitch.ROTATOR), answers.answeredGearSwitches())
// The stored side does not move with the answers.
assertEquals(setOf(WizardSwitch.AIRSCOUT), answers.storedGearSwitches())
}
@Test
fun theHighestPortIsNoRotatorPort() {
// PSTRotator answers on port + 1, so the setter stores 1..65534 only and would
// replace 65535 by its factory default without a word.
val target = allOff()
val answers = WizardIntegrations(target)
answers.rotator = true
answers.rotatorPort = 65535
assertFalse(answers.gearComplete, "65535 would be stored as 12000")
answers.rotatorPort = 65534
assertTrue(answers.gearComplete)
answers.writeGearTo(target)
assertEquals(65534, target.getStn_pstRotatorPort(), "an accepted port is stored as entered")
answers.rotatorPort = 0
assertFalse(answers.gearComplete)
}
@Test
fun loadingAgainPutsTheDetailsBackToTheStoredOnes() {
val answers = WizardIntegrations(winTestStation())
val storedFilePath = answers.filePath
answers.udpPort = 1
answers.wintestPort = 2
answers.wintestStationName = "typed"
answers.filePath = "/typed"
answers.rotatorHost = "typed"
answers.rotatorPort = 3
answers.airScoutPort = 4
answers.airScoutServerName = "typed"
answers.airScoutClientName = "typed"
answers.loadFresh()
assertEquals(12060, answers.udpPort)
assertEquals(9999, answers.wintestPort)
assertEquals("KST", answers.wintestStationName)
assertEquals(storedFilePath, answers.filePath)
assertEquals("127.0.0.1", answers.rotatorHost)
assertEquals(12000, answers.rotatorPort)
assertEquals(9872, answers.airScoutPort)
assertEquals("AS", answers.airScoutServerName)
assertEquals("KST", answers.airScoutClientName)
answers.filePath = "/typed"
answers.rotatorPort = 3
answers.loadStored()
assertEquals(storedFilePath, answers.filePath)
assertEquals(12000, answers.rotatorPort)
}
@Test
fun theStoredSwitchesAreKnownWhateverTheLogProgram() {
// The settings window lets the DX cluster server and a frequency source run without
// a log source; the page's own answers cannot express that.
val answers = WizardIntegrations(allOff {
setNotify_dxClusterServerEnabled(true)
setTrxSynch_ucxLogUDPListenerEnabled(true)
})
assertEquals(WizardLogProgram.NONE, answers.logProgram)
assertFalse(answers.clusterServer, "the page shows none of it")
assertTrue(answers.storedClusterServer)
assertTrue(answers.storedQrgFollow)
val off = WizardIntegrations(allOff())
assertFalse(off.storedClusterServer)
assertFalse(off.storedQrgFollow)
}
}
@@ -0,0 +1,182 @@
package kst4contest.view.compose.wizard
import kst4contest.model.ChatCategory
import kst4contest.model.ChatPreferences
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 org.mockito.Mockito
import java.io.File
import java.lang.reflect.Modifier
import java.nio.file.Path
/**
* What "the station" is when one profile takes it from another.
*
* The two lists under src/test/resources are the decision, one line per ChatPreferences
* setter. A setter in neither list fails the first test, so a new setting cannot be forgotten
* here: somebody has to say whether another operator at the same station should inherit it.
*/
class WizardStationCopyTest {
private fun lines(name: String): Set<String> =
File("src/test/resources/$name").readLines().map { it.trim() }.filter { it.isNotEmpty() }.toSet()
private val stationSetters = lines("wizard-station-setters.txt")
private val otherSetters = lines("wizard-other-setters.txt")
/** Every public setter with one parameter, the shape every preference has. */
private fun allSetters(): Set<String> =
ChatPreferences::class.java.methods
.filter { it.name.startsWith("set") && it.parameterCount == 1 && Modifier.isPublic(it.modifiers) }
.map { it.name }
.toSet()
private fun prefs(configure: ChatPreferences.() -> Unit = {}): ChatPreferences =
ChatPreferences(Path.of("wizard-station-copy-test-unused.xml")).apply(configure)
@Test
fun everySetterIsClassified() {
val all = allSetters()
assertEquals(
emptySet<String>(),
all - stationSetters - otherSetters,
"new ChatPreferences setters: add each to wizard-station-setters.txt (and to copyStation) " +
"or to wizard-other-setters.txt",
)
assertEquals(emptySet<String>(), (stationSetters + otherSetters) - all, "listed setters that no longer exist")
assertEquals(emptySet<String>(), stationSetters.intersect(otherSetters), "a setter cannot be in both lists")
}
@Test
fun copyStationCallsExactlyTheStationSetters() {
val target = Mockito.mock(ChatPreferences::class.java)
copyStation(prefs(), target)
val called = Mockito.mockingDetails(target).invocations
.map { it.method.name }
.filter { it.startsWith("set") }
assertEquals(stationSetters, called.toSet(), "copyStation and wizard-station-setters.txt disagree")
assertEquals(called.size, called.toSet().size, "a setter was called twice")
assertTrue(
Mockito.mockingDetails(target).invocations.none { it.method.name == "writePreferencesToXmlFile" },
"copying must not write a file",
)
}
@Test
fun theStationArrivesIncludingWhatTheWizardNeverAsks() {
val donor = prefs {
setStn_loginLocatorMainCat("JO50AA")
setStn_bandActive144(true)
setStn_bandActive1240(true)
setStn_bandActive432(false)
setLoginChatCategoryMain(ChatCategory(2))
setLoginToSecondChatEnabled(true)
setLoginChatCategorySecond(ChatCategory(3))
setStn_qtfDefault(270.0)
setStn_maxQRBDefault(800.0)
setStn_pathAnalysisDemRootDirectory("/srv/dem")
setStn_pathAnalysisContestMarginDb(9.0)
setTrxSynch_so2rEnabled(true)
setStn_pstRotator2Enabled(true)
setStn_pstRotator2Port(12020)
// Several log sources at once: the wizard's own question could not express this.
setLogsynch_wintestNetworkListenerEnabled(true)
setLogsynch_fileBasedWkdCallInterpreterEnabled(true)
setLogsynch_wintestNetworkStationNameOfWintestClient1("RUN")
setLogsynch_wintestUsePassQrg(true)
setAirScout_asBandString("4320000")
}
val target = prefs {
setStn_bandActive432(true)
setLoginChatCategoryMain(ChatCategory(3))
}
copyStation(donor, target)
assertEquals("JO50AA", target.getStn_loginLocatorMainCat())
assertTrue(target.isStn_bandActive144())
assertTrue(target.isStn_bandActive1240())
assertFalse(target.isStn_bandActive432(), "a band the donor does not have goes off")
assertEquals(2, target.getLoginChatCategoryMain().categoryNumber)
assertTrue(target.isLoginToSecondChatEnabled())
assertEquals(3, target.getLoginChatCategorySecond().categoryNumber)
assertEquals(270.0, target.getStn_qtfDefault())
assertEquals(800.0, target.getStn_maxQRBDefault())
assertEquals("/srv/dem", target.getStn_pathAnalysisDemRootDirectory())
assertEquals(9.0, target.getStn_pathAnalysisContestMarginDb())
assertTrue(target.isTrxSynch_so2rEnabled())
assertTrue(target.isStn_pstRotator2Enabled())
assertEquals(12020, target.getStn_pstRotator2Port())
assertTrue(target.isLogsynch_wintestNetworkListenerEnabled())
assertTrue(target.isLogsynch_fileBasedWkdCallInterpreterEnabled())
assertEquals("RUN", target.getLogsynch_wintestNetworkStationNameOfWintestClient1())
assertTrue(target.isLogsynch_wintestUsePassQrg())
assertEquals("4320000", target.getAirScout_asBandString())
}
@Test
fun whatBelongsToTheOperatorStays() {
val donor = prefs {
setStn_loginCallSign("DL0TEST")
setStn_loginPassword("donor-secret")
setStn_loginNameMainCat("Donor")
setStn_loginNameSecondCat("Donor SHF")
setGuiOptions_language("en")
setGUI_darkModeActiveByDefault(true)
setStn_on4kstServersDns("donor.example")
setNotify_DXCSrv_SpottersCallSign("DL0TEST")
setBcn_beaconTextMainCat("donor beacon")
}
val target = prefs {
setStn_loginCallSign("DM5XX")
setStn_loginPassword("own-secret")
setStn_loginNameMainCat("Own")
setStn_loginNameSecondCat("Own SHF")
setGuiOptions_language("de")
setGUI_darkModeActiveByDefault(false)
setStn_on4kstServersDns("own.example")
setNotify_DXCSrv_SpottersCallSign("DM5XX")
setBcn_beaconTextMainCat("own beacon")
}
copyStation(donor, target)
assertEquals("DM5XX", target.getStn_loginCallSign())
assertEquals("own-secret", target.getStn_loginPassword())
assertEquals("Own", target.getStn_loginNameMainCat())
assertEquals("Own SHF", target.getStn_loginNameSecondCat())
assertEquals("de", target.getGuiOptions_language())
assertFalse(target.isGUI_darkModeActiveByDefault())
assertEquals("own.example", target.getStn_on4kstServersDns())
assertEquals("DM5XX", target.getNotify_DXCSrv_SpottersCallSign().get())
assertEquals("own beacon", target.getBcn_beaconTextMainCat())
}
@Test
fun theDonorIsNotChangedAndSharesNoObjectWithTheTarget() {
val donor = prefs { setLoginChatCategoryMain(ChatCategory(2)) }
val target = prefs()
copyStation(donor, target)
target.getLoginChatCategoryMain().categoryNumber = 7
assertEquals(2, donor.getLoginChatCategoryMain().categoryNumber, "the two profiles must not share a category object")
}
@Test
fun theFallbackBandComesWithTheStation() {
// It completes frequencies given without a band, so it has to fit the station's bands.
val donor = prefs { setNotify_optionalFrequencyPrefix("432") }
val target = prefs { setNotify_optionalFrequencyPrefix("144") }
copyStation(donor, target)
assertEquals("432", target.getNotify_optionalFrequencyPrefix().get())
}
}
@@ -0,0 +1,72 @@
setActualQTF
setBcn_beaconIntervalInMinutesMainCat
setBcn_beaconIntervalInMinutesSecondCat
setBcn_beaconTextMainCat
setBcn_beaconTextSecondCat
setBcn_beaconsEnabledMainCat
setBcn_beaconsEnabledSecondCat
setBcn_contestScoreSum
setChatState
setGUI_darkModeActive
setGUI_darkModeActiveByDefault
setGUIclusterAndQSOMonStage_SceneSizeHW
setGUImainWindowLeftSplitPane_dividerposition
setGUImainWindowRightSplitPane_dividerposition
setGUImessageSectionSplitpane_dividerposition
setGUIpnl_directedMSGWin_dividerpositionDefault
setGUIscn_ChatwindowMainSceneSizeHW
setGUIselectedCallSignSplitPane_dividerposition
setGUIsettingsStageSceneSizeHW
setGUIstage_updateStage_SceneSizeHW
setGUIstationMapAlwaysOnTop
setGUIstationMapClusteringEnabled
setGUIstationMapPathAnalysisVisible
setGUIstationMapStagePositionXY
setGUIstationMapStageSceneSizeHW
setGuiOptions_defaultFilterNothing
setGuiOptions_defaultFilterPmToMe
setGuiOptions_defaultFilterPmToOther
setGuiOptions_defaultFilterPublicMsgs
setGuiOptions_language
setGuiOptions_paletteOverridesDay
setGuiOptions_paletteOverridesEvening
setGuiOptions_rememberWindowPositions
setGuiOptions_showFreshCallHintInBandColumns
setGuiOptions_showGrossFieldWorkedHintInBandColumns
setLogSynch_storeWorkedCallSignsFileNameUDPMessageBackup
setLogsynch_storeWorkedCallSignsFileNameUDPMessageBackup
setLstNotify_QSOSniffer_sniffedPrefixLocList
setLst_txtShortCutBtnList
setLst_txtSnipList
setMYQRGFirstCat
setMYQRGSecondCat
setMessageHandling_autoAnswerEnabled
setMessageHandling_autoAnswerEnabledSecondCat
setMessageHandling_autoAnswerTextMainCat
setMessageHandling_autoAnswerTextSecondCat
setMessageHandling_autoAnswerToQRGRequestEnabled
setMessageHandling_beaconUnworkedstationsPrefix
setMessageHandling_debugModeToFileEnabled
setMessageHandling_unworkedStnRequesterBeaconsEnabled
setMessageHandling_unworkedStnRequesterBeaconsInterval
setMessageHandling_unworkedStnRequesterBeaconsText
setNotify_DXCSrv_SpottersCallSign
setNotify_DXClusterServerTriggerBearing
setNotify_DXClusterServerTriggerOnQRGDetect
setNotify_bandUpgradeHintOnLogEnabled
setNotify_bandUpgradePriorityBoostEnabled
setNotify_momentumWindowSeconds
setNotify_noReplyPenaltyMinutes
setNotify_playCWCallsignsOnRxedPMs
setNotify_playSimpleSounds
setNotify_playVoiceCallsignsOnRxedPMs
setNotify_positiveSignalsPatterns
setProgramVersion
setStn_loginAFKState
setStn_loginCallSign
setStn_loginNameMainCat
setStn_loginNameSecondCat
setStn_loginPassword
setStn_on4kstServersDns
setStn_on4kstServersPort
setStoreAndRestorePreferencesFileName
@@ -0,0 +1,66 @@
setAirScout_asBandString
setAirScout_asClientNameString
setAirScout_asCommunicationPort
setAirScout_asServerNameString
setAirScout_asUDPListenerEnabled
setAirScout_autoBandSelectionEnabled
setLoginChatCategoryMain
setLoginChatCategorySecond
setLoginToSecondChatEnabled
setLogsynch_fileBasedWkdCallInterpreterEnabled
setLogsynch_fileBasedWkdCallInterpreterFileNameReadOnly
setLogsynch_ucxUDPWkdCallListenerEnabled
setLogsynch_ucxUDPWkdCallListenerPort
setLogsynch_wintestNetworkBroadcastAddress
setLogsynch_wintestNetworkListenerEnabled
setLogsynch_wintestNetworkPort
setLogsynch_wintestNetworkSimulationEnabled
setLogsynch_wintestNetworkSkedPushEnabled
setLogsynch_wintestNetworkStationIDOfKST
setLogsynch_wintestNetworkStationNameOfKST
setLogsynch_wintestNetworkStationNameOfWintestClient1
setLogsynch_wintestNetworkStationNameOfWintestClient2
setLogsynch_wintestQrgSyncEnabled
setLogsynch_wintestSkedMode
setLogsynch_wintestUsePassQrg
setNotify_dxClusterServerEnabled
setNotify_dxclusterServerPort
setNotify_optionalFrequencyPrefix
setStn_antennaBeamWidthDeg
setStn_bandActive10G
setStn_bandActive1240
setStn_bandActive144
setStn_bandActive2300
setStn_bandActive3400
setStn_bandActive432
setStn_bandActive50
setStn_bandActive5600
setStn_bandActive70
setStn_loginLocatorMainCat
setStn_maxQRBDefault
setStn_pathAnalysisContestMarginDb
setStn_pathAnalysisDefaultTargetAntennaGainDbi
setStn_pathAnalysisDefaultTargetAntennaHeightMeters
setStn_pathAnalysisDefaultTargetTxPowerWatts
setStn_pathAnalysisDemDatasetId
setStn_pathAnalysisDemRootDirectory
setStn_pathAnalysisDxHighestPointInSquare
setStn_pathAnalysisFeederLossIncreaseDbPer200MHz
setStn_pathAnalysisMaxEstimatedFeederLossPerStationDb
setStn_pathAnalysisOwnAntennaGainDbi
setStn_pathAnalysisOwnAntennaHeightMeters
setStn_pathAnalysisOwnHeightAslMeters
setStn_pathAnalysisOwnTxPowerWatts
setStn_pathAnalysisRequiredCwSignalDbm
setStn_pathAnalysisRequiredSsbSignalDbm
setStn_pathAnalysisVhfFeederLossPerStationDb
setStn_pstRotator2Enabled
setStn_pstRotator2Host
setStn_pstRotator2Port
setStn_pstRotatorEnabled
setStn_pstRotatorHost
setStn_pstRotatorPort
setStn_qtfDefault
setStn_useQtfFilterDirectionAsAntennaHeading
setTrxSynch_so2rEnabled
setTrxSynch_ucxLogUDPListenerEnabled