Add setup wizard state and its course rules

Written-by: Gemini 4 Hydrogen (Antigravity)
Written-by: Claude Fable 5.2
This commit is contained in:
Rsclub2_2 committed 2026-11-18 21:32:09 +01:00
1 parent 78a1502a1f
commit 01e56c6639
2 files changed
+614

No files matched your search

@@ -0,0 +1,319 @@
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,
/** What the profile already holds. */
KEEP,
}
/** The pages, in the order they can appear. */
enum class WizardPage { ENTRY, PERSONAL, LOGIN, SITE, 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
*/
class SetupWizardState(prefs: ChatPreferences) {
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 = prefs.getStn_loginLocatorMainCat().orEmpty()
private val storedBands: Set<WizardBand> = WizardBand.entries.filter { it.isActive(prefs) }.toSet()
private val storedCategory: Int? = prefs.getLoginChatCategoryMain()?.categoryNumber
private val storedSecondChat: Boolean = prefs.isLoginToSecondChatEnabled()
private val storedSecondCategory: Int? = prefs.getLoginChatCategorySecond()?.categoryNumber
/** A login can only be kept where an operator entered one. */
val loginSources: List<WizardSource> = buildList {
add(WizardSource.NEW)
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 (!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
private var appliedLoginSource: WizardSource? = null
private var appliedStationSource: WizardSource? = 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)
private var loginShown by mutableStateOf(false)
private var stationShown 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) loginSource = source
}
fun chooseStationSource(source: WizardSource) {
if (source in stationSources) stationSource = source
}
/**
* Loads the answers of a group whose source changed. A group whose source is the one
* already applied is left alone, so going back to the entry page costs nothing typed.
*/
private fun applySources() {
if (loginSource != appliedLoginSource) {
val keep = loginSource == WizardSource.KEEP
callsign = if (keep) storedCallsign else ""
password = if (keep) storedPassword else ""
loginShown = !keep
appliedLoginSource = loginSource
}
if (stationSource != appliedStationSource) {
val keep = stationSource == WizardSource.KEEP
locator = if (keep) storedLocator else ""
bands = if (keep) storedBands else emptySet()
category = if (keep) storedCategory else null
secondChat = keep && storedSecondChat
secondCategory = if (keep) storedSecondCategory else null
// A kept category is the operator's; the suggestion must not replace it.
categoryChosenByOperator = keep
stationShown = !keep
appliedStationSource = stationSource
}
}
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 (stationShown) add(WizardPage.SITE)
add(WizardPage.SUMMARY)
}
private val personalComplete: Boolean
get() = name.isNotBlank()
private val loginComplete: Boolean
get() = isPlausibleCallsign(callsign) && password.isNotEmpty()
private val stationComplete: Boolean
get() = isLocator(locator) && bands.isNotEmpty() && category != null &&
(!secondChat || (secondCategory != null && secondCategory != category))
/** Whether everything the profile needs to log in is there. */
val mandatoryComplete: Boolean
get() = personalComplete && loginComplete && stationComplete
/** 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 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 -> loginSource != null && stationSource != null
WizardPage.PERSONAL -> personalComplete
WizardPage.LOGIN -> loginComplete
WizardPage.SITE -> stationComplete
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
}
/** Opens a step from the summary, also one this run skipped. */
fun edit(target: WizardPage) {
when (target) {
WizardPage.LOGIN -> loginShown = true
WizardPage.SITE -> stationShown = true
WizardPage.PERSONAL -> Unit
WizardPage.ENTRY, WizardPage.SUMMARY -> return
}
page = target
}
/** The profile had a second chat and will have none. */
val turnsOffSecondChat: Boolean
get() = storedSecondChat && !secondChat
/**
* A new station is set up, and this stage does not ask about log program, rotator,
* AirScout and DX cluster server: they keep their stored values, and the summary says so.
*/
val leavesIntegrationsUntouched: Boolean
get() = stationSource == WizardSource.NEW
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())
/**
* 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,295 @@
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.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 theSummarySaysWhatIsSwitchedOffAndWhatIsLeftAlone() {
val fresh = SetupWizardState(freshInstallation())
assertTrue(fresh.turnsOffSecondChat, "the template has the second chat on, a new station has it off")
assertTrue(fresh.leavesIntegrationsUntouched)
val kept = SetupWizardState(duplicatedProfile())
kept.chooseStationSource(WizardSource.KEEP)
kept.next()
assertFalse(kept.turnsOffSecondChat)
assertFalse(kept.leavesIntegrationsUntouched)
}
}