Compare commits

...
Author SHA1 Message Date
Rsclub2_2 c9ddc1959d Remove the executed setup wizard stage 3 plan
Stage 3 is implemented and manually checked. What was worth keeping is in the commit messages, the spec and docs/PROJECT_CONTEXT.md.

Written-by: Claude Fable 5.2
2026-11-18 23:11:29 +01:00
Rsclub2_2 dbd6caa4ea Name what a taken station drops and keep a profile from being its own donor
Written-by: Gemini 4 Hydrogen (Antigravity)
Written-by: Claude Fable 5.2
2026-11-18 22:51:07 +01:00
Rsclub2_2 e527ad4198 Say when each source is offered and what a taken station includes
The manual listed the three sources without their conditions and described changing taken values too broadly: a taken station with several log sources keeps its log page shut.

Written-by: Claude Fable 5.2
2026-11-18 22:36:23 +01:00
Rsclub2_2 b7950f8a06 Document taking login and station from another profile
Written-by: DeepSeek V4 Pro
Written-by: Claude Fable 5.2
2026-11-18 22:34:03 +01:00
Rsclub2_2 dc164403be Offer other profiles as a source on the setup wizard's entry page
Written-by: Codex (GPT-6.2 Sol)
Written-by: Claude Fable 5.2
2026-11-18 22:28:04 +01:00
Rsclub2_2 76e086f4c0 Take the fallback band over with the station
It completes frequencies given without a band and has to fit the taken station's bands, so it belongs to the station and not to the operator.

Written-by: Claude Fable 5.2
2026-11-18 22:26:26 +01:00
Rsclub2_2 52508eec71 Let the setup wizard take login and station from another profile
Written-by: Gemini 4 Hydrogen (Antigravity)
Written-by: Claude Fable 5.2
2026-11-18 22:25:24 +01:00
Rsclub2_2 918f84dc8a Copy a station from one profile's preferences to another's
Written-by: DeepSeek V4 Pro
Written-by: Claude Fable 5.2
2026-11-18 22:22:05 +01:00
Rsclub2_2 9e5759adfe Add implementation plan for setup wizard stage 3
Written-by: Claude Fable 5.2
2026-11-18 22:18:07 +01:00
Rsclub2_2 68d86ce320 Remove the executed setup wizard stage 2 plan
Stage 2 is implemented and manually checked. What was worth keeping is in the commit messages, the spec and docs/PROJECT_CONTEXT.md.

Written-by: Claude Fable 5.2
2026-11-18 21:32:15 +01:00
Rsclub2_2 383e0f97c9 Stop the wizard on unreadable numbers and own its file chooser
Written-by: Codex (GPT-6.2 Sol)
Written-by: Claude Fable 5.2
2026-11-18 21:32:15 +01:00
Rsclub2_2 85a2984234 State the wizard's Finish and write rules precisely
The manual named too few conditions for Finish, and spec and project context read as if a skipped page of a new station were not written. It is: only a station left unchanged is written page by page.

Written-by: Claude Fable 5.2
2026-11-18 21:32:14 +01:00
Rsclub2_2 0d0b752bed Show in the wizard's summary what Save leaves on
On a station left unchanged the summary read the log page's answers, which cannot express a DX cluster server or a frequency source running without a log source; it said no while Save left both on. The summary now shows the stored switches until the log page is part of the run. Ports, names, host and identifiers are reloaded on a source change, like the antenna values.

Written-by: Claude Fable 5.2
2026-11-18 21:32:14 +01:00
Rsclub2_2 175b6350c2 Document stage 2 of the setup wizard
Written-by: DeepSeek V4 Pro
Written-by: Claude Fable 5.2
2026-11-18 21:32:14 +01:00
Rsclub2_2 a24534bbb1 Refuse rotator port 65535 and reload antenna proposals on a source change
setStn_pstRotatorPort stores 1..65534 and replaces anything else by 12000, so the wizard must not accept 65535. And antenna values typed for a new station stayed in the summary after the operator chose to keep the station, where they are not written.

Written-by: Claude Fable 5.2
2026-11-18 21:32:14 +01:00
Rsclub2_2 bde77f3ec1 Ask about antenna, log program, rotator and AirScout in the setup wizard
Written-by: Codex (GPT-6.2 Sol)
Written-by: Claude Fable 5.2
2026-11-18 21:32:13 +01:00
Rsclub2_2 facba2b010 Add the setup wizard's log program, rotator and AirScout answers
Written-by: Gemini 4 Hydrogen (Antigravity)
Written-by: Claude Fable 5.2
2026-11-18 21:32:13 +01:00
Rsclub2_2 0ab9ffc241 Add the setup wizard's antenna and power answers
Written-by: DeepSeek V4 Pro
Written-by: Claude Fable 5.2
2026-11-18 21:32:13 +01:00
Rsclub2_2 adcd9da306 Add implementation plan for setup wizard stage 2
Written-by: Claude Fable 5.2
2026-11-18 21:32:13 +01:00
Rsclub2_2 da1f261684 Remove the executed setup wizard stage 1 plan
Stage 1 is implemented and manually checked. What was worth keeping is in the commit messages, the spec and docs/PROJECT_CONTEXT.md.

Written-by: Claude Fable 5.2
2026-11-18 21:32:12 +01:00
Rsclub2_2 f607b831ca Keep a running switch's wizard request when a second rerun is refused
rerunSetupWizard set the one-shot request before it tried to obtain the switch, and cleared it when the switch was refused. A second confirmed call during the first one's window teardown therefore removed the first call's request: the session ended and the profile restarted without the wizard. The request is now set only by the call that owns the switch.

Written-by: Claude Fable 5.2
2026-11-18 21:32:12 +01:00
Rsclub2_2 a8cfe94853 Harden the setup wizard after the branch review
Written-by: Gemini 4 Hydrogen (Antigravity)
Written-by: Claude Fable 5.2
2026-11-18 21:32:12 +01:00
Rsclub2_2 f871f551f7 Let the wizard window tests find only the wizard's dialog
Written-by: Codex (GPT-6.2 Sol)
Written-by: Claude Fable 5.2
2026-11-18 21:32:12 +01:00
Rsclub2_2 0821820dd4 Document the setup wizard
Written-by: Gemini 4 Hydrogen (Antigravity)
Written-by: Claude Fable 5.2
2026-11-18 21:32:11 +01:00
Rsclub2_2 bd36beccb5 Dispose a leftover wizard dialog when a window test fails
Written-by: DeepSeek V4 Pro
Written-by: Claude Fable 5.2
2026-11-18 21:32:11 +01:00
Rsclub2_2 8352af911e Reach the setup wizard from the Options menu
Written-by: Codex (GPT-6.2 Sol)
Written-by: Claude Fable 5.2
2026-11-18 21:32:11 +01:00
Rsclub2_2 f1e80c6ed3 Bound the setup wizard window tests and close through the window's X
Written-by: DeepSeek V4 Pro
Written-by: Claude Fable 5.2
2026-11-18 21:32:11 +01:00
Rsclub2_2 f5783ade25 Run the setup wizard before an unconfigured profile's runtime is built
Written-by: Gemini 4 Hydrogen (Antigravity)
Written-by: Claude Fable 5.2
2026-11-18 21:32:11 +01:00
Rsclub2_2 0a43af66df Report a failed read of the preferences file
Written-by: DeepSeek V4 Pro
Written-by: Claude Fable 5.2
2026-11-18 21:32:10 +01:00
Rsclub2_2 3575473fa9 Open the setup wizard as a modal dialog
Written-by: DeepSeek V4 Pro
Written-by: Claude Fable 5.2
2026-11-18 21:32:10 +01:00
Rsclub2_2 64a6eab35f Draw the setup wizard pages
Written-by: Codex (GPT-6.2 Sol)
Written-by: Claude Fable 5.2
2026-11-18 21:32:10 +01:00
Rsclub2_2 78fc5b98fa Keep incomplete kept groups in the wizard's course
Written-by: Gemini 4 Hydrogen (Antigravity)
Written-by: Claude Fable 5.2
2026-11-18 21:32:10 +01:00
Rsclub2_2 3ca6ef411f Write setup wizard answers to the profile's preferences file
Written-by: DeepSeek V4 Pro
Written-by: Claude Fable 5.2
2026-11-18 21:32:09 +01:00
Rsclub2_2 01e56c6639 Add setup wizard state and its course rules
Written-by: Gemini 4 Hydrogen (Antigravity)
Written-by: Claude Fable 5.2
2026-11-18 21:32:09 +01:00
Rsclub2_2 78a1502a1f Detect operator profiles without entered login credentials
Written-by: DeepSeek V4 Pro
Written-by: Claude Fable 5.2
2026-11-18 21:32:09 +01:00
Rsclub2_2 1615c4dffc Add implementation plan for setup wizard stage 1
Written-by: Claude Fable 5.2
2026-11-18 21:32:09 +01:00
Rsclub2_2 6508978da9 Add antenna step and tighten finish rule in setup wizard spec
Finish now requires every mandatory answer, since a summary without locator, band and category could not be saved. Adds an optional step for antenna and power values that feed the path analysis.

Written-by: Claude Fable 5.2
2026-11-18 21:32:08 +01:00
Rsclub2_2 aff9b6e2ff Add setup wizard design spec
Describes a first-start assistant for unconfigured operator profiles: what it asks, how it covers multi-operator and multi-station setups, and why it writes preferences.xml before the runtime is built instead of going through the settings draft.

Written-by: Claude Fable 5.2
Written-by: Codex (GPT-6.2 Sol)
Written-by: Gemini 4 Hydrogen (Antigravity)
Written-by: DeepSeek V4 Pro
2026-11-18 21:32:08 +01:00
dependabot[bot] b0960a3f04 build(deps): bump gradle-wrapper
Bumps the minor-and-patch group with 1 update: [gradle-wrapper](https://github.com/gradle/gradle).


Updates `gradle-wrapper` from 9.9.0 to 9.9.1
- [Release notes](https://github.com/gradle/gradle/releases)
- [Commits](https://github.com/gradle/gradle/compare/v9.9.0...v9.9.1)

---
updated-dependencies:
- dependency-name: gradle-wrapper
  dependency-version: 9.9.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-16 23:30:58 +01:00
Marc Froehlich f13fe54fde Harden beacon sessions and mark automatic messages 2026-11-14 19:18:25 +01:00
dependabot[bot] 19bcdb428d build(deps): bump the minor-and-patch group across 1 directory with 2 updates
Bumps the minor-and-patch group with 2 updates in the / directory: [gradle-wrapper](https://github.com/gradle/gradle) and [org.xerial:sqlite-jdbc](https://github.com/xerial/sqlite-jdbc).


Updates `gradle-wrapper` from 9.8.1 to 9.9.0
- [Release notes](https://github.com/gradle/gradle/releases)
- [Commits](https://github.com/gradle/gradle/compare/v9.8.1...v9.9.0)

Updates `org.xerial:sqlite-jdbc` from 3.53.4.0 to 3.54.1.0
- [Release notes](https://github.com/xerial/sqlite-jdbc/releases)
- [Changelog](https://github.com/xerial/sqlite-jdbc/blob/master/CHANGELOG)
- [Commits](https://github.com/xerial/sqlite-jdbc/compare/3.53.4.0...3.54.1.0)

---
updated-dependencies:
- dependency-name: gradle-wrapper
  dependency-version: 9.8.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: org.xerial:sqlite-jdbc
  dependency-version: 3.54.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-13 14:53:07 +01:00
dependabot[bot] 9304df3705 build(deps): bump actions/setup-java
Bumps the minor-and-patch group with 1 update: [actions/setup-java](https://github.com/actions/setup-java).


Updates `actions/setup-java` from 6.1.0 to 6.2.0
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/v6.1.0...v6.2.0)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: 6.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-13 14:52:46 +01:00
Rsclub2_2 e5c057378f Update sponsors list in README
Added sponsors Steve (G1YBB/M1B/MW1B) and Jens (DH1AKY) to the README.
2026-11-07 18:21:02 +01:00
Praktimarc d925c83412 Apply live beacon settings and improve station map (#164)
Apply beacon checkbox changes at runtime and keep the aggregate status chip synchronized.

Improve explicit station-map navigation, spatial filter overlays, overlay legend, selected-path contrast, and the documented map screenshot.
2026-11-05 00:52:17 +01:00
Praktimarc 4d96822c0c fix: filter public messages correctly (#163)
Fixes #162
2026-11-03 23:45:02 +01:00
Rsclub2_2 c23982c339 test: fix the CI hang in the Compose rendering tests (#157)
* test: print all threads when a test times out

The rare CI hang in SelectedStationMessageUiVisualRenderingTest blocks on a
monitor in SnapshotStateObserver.observeReads (line 643 is the monitorenter
of observedScopeMapsLock in Compose 1.8.2). The timed-out thread's stack
shows where it waits but not which thread holds the lock. With the thread
dump enabled, JUnit prints every thread to the test's standard output, which
ends up in the XML report of the test-results artifact.

Claude-Session: https://claude.ai/code/session_01FJBfPYm6rCH4zD6T7bcC7Y

* test: render every ImageComposeScene on the AWT event thread

The rare CI hang is a lock-order deadlock in Compose Multiplatform 1.8.2,
shown by the thread dump of run 40299943329:

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

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

Claude-Session: https://claude.ai/code/session_01FJBfPYm6rCH4zD6T7bcC7Y
2026-10-26 11:21:43 +01:00
dependabot[bot] 834f4b131a build(deps-dev): bump brace-expansion from 1.1.15 to 1.1.21 in /website (#155)
Bumps [brace-expansion](https://github.com/juliangruber/brace-expansion) from 1.1.15 to 1.1.21.
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/v1.1.15...v1.1.21)

---
updated-dependencies:
- dependency-name: brace-expansion
  dependency-version: 1.1.21
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-26 10:22:26 +01:00
dependabot[bot] 1868f21c06 build(deps-dev): bump liquidjs from 10.27.1 to 10.30.0 in /website (#154)
Bumps [liquidjs](https://github.com/harttle/liquidjs) from 10.27.1 to 10.30.0.
- [Release notes](https://github.com/harttle/liquidjs/releases)
- [Changelog](https://github.com/harttle/liquidjs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/harttle/liquidjs/compare/v10.27.1...v10.30.0)

---
updated-dependencies:
- dependency-name: liquidjs
  dependency-version: 10.30.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-26 10:16:36 +01:00
dependabot[bot] 9d433f9ba4 build(deps): bump markdown-it from 14.3.0 to 14.3.3 in /website (#153)
Bumps [markdown-it](https://github.com/markdown-it/markdown-it) from 14.3.0 to 14.3.3.
- [Changelog](https://github.com/markdown-it/markdown-it/blob/14.3.3/CHANGELOG.md)
- [Commits](https://github.com/markdown-it/markdown-it/compare/14.3.0...14.3.3)

---
updated-dependencies:
- dependency-name: markdown-it
  dependency-version: 14.3.3
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-26 10:16:19 +01:00
dependabot[bot] f4f046c04f build(deps): bump js-yaml in /website (#152)
Bumps  and [js-yaml](https://github.com/nodeca/js-yaml). These dependencies needed to be updated together.

Updates `js-yaml` from 3.15.0 to 3.15.2
- [Changelog](https://github.com/nodeca/js-yaml/blob/3.15.2/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/3.15.0...3.15.2)

Updates `js-yaml` from 4.3.0 to 4.3.2
- [Changelog](https://github.com/nodeca/js-yaml/blob/3.15.2/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/3.15.0...3.15.2)

---
updated-dependencies:
- dependency-name: js-yaml
  dependency-version: 3.15.2
  dependency-type: indirect
- dependency-name: js-yaml
  dependency-version: 4.3.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-26 10:16:06 +01:00
Rsclub2_2 8fc3b9f424 fix: resolve the open CodeQL alerts (#156)
Strip HTML tags and XML comments until the text no longer changes, so that
nested input cannot reassemble a tag or comment after a single pass
(js/incomplete-multi-character-sanitization in website/.eleventy.js and
website/scripts/validate-version-info.js).

Limit the GITHUB_TOKEN of the PR compile check and the test version-XML
workflow to read access (actions/missing-workflow-permissions).

Claude-Session: https://claude.ai/code/session_01FJBfPYm6rCH4zD6T7bcC7Y
2026-10-26 10:13:10 +01:00
Rsclub2_2andClaude Opus 5.5 f165f7d303 fix(aur): build the source packages' launcher with Temurin (#150)
The kst4contest and kst4contest-git packages built jpackage's launcher
with Arch's openjdk, which links libapplauncher.so against the shared
libstdc++. That build aborts now and then on exit with "pure virtual
method called" in a static destructor (SIGABRT, core dump), the failure
Debian describes for non-static libstdc++ builds. Temurin links
libstdc++ statically, like the CI-built packages.

Both PKGBUILDs now fetch a pinned Temurin 21.0.13+9 through
source_x86_64, so aur-publish.yml's rewrite of the sha256sums= line
leaves it alone, and point the Gradle toolchain at it alone.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 01:21:37 +02:00
Rsclub2_2andClaude Opus 5.5 738ae2125e ci: print full stacks of failed tests and keep reports on a cancel (#151)
Nightly #303 named the hanging test, SelectedStationMessageUiVisual-
RenderingTest at scene.render(), but the short exception format showed
only that line, not the call that blocked below it. The job timeout
cancels the run, and the test reports were kept only on failure().

Failed tests now print their full stack, causes included, and the
reports are uploaded on cancelled() as well.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 01:15:56 +02:00
Rsclub2_2andClaude Opus 5.5 af8affda8c ci: fail hanging tests by name instead of holding the job (#149)
Nightly #302 and the PR check for #147 hung in :app-desktop:test for
over an hour, and the log named only the task. Thirteen reruns of the
same commit passed, so the hang is rare and still unidentified.

Every test now gets a two-minute JUnit timeout in a separate thread, so
even an uninterruptible hang fails with the test's name and the stack
where it stood. The test jobs are capped at 20 minutes for a hang
outside any test.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 00:47:25 +02:00
160 changed files with 10849 additions and 754 deletions

No files matched your search

+14 -9
View File
@@ -32,13 +32,16 @@ jobs:
test: test:
name: Test (Java 21, headless) name: Test (Java 21, headless)
runs-on: ubuntu-latest runs-on: ubuntu-latest
# A healthy run takes about four minutes. The per-test limit in build.gradle.kts names
# a hanging test; this cap covers a hang outside any test, such as in Gradle itself.
timeout-minutes: 20
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v7 uses: actions/checkout@v7
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -108,8 +111,10 @@ jobs:
exit 1 exit 1
fi fi
# Also on cancelled(): the job timeout cancels a hanging run, and the reports of the
# classes that did finish carry the timed-out tests' full stacks.
- name: Keep the test reports on a failure - name: Keep the test reports on a failure
if: failure() if: failure() || cancelled()
uses: actions/upload-artifact@v7 uses: actions/upload-artifact@v7
with: with:
name: test-results name: test-results
@@ -138,7 +143,7 @@ jobs:
Add-Content -Path $env:GITHUB_ENV -Value "ASSET_BASENAME=praktiKST-$version-$shortSha" Add-Content -Path $env:GITHUB_ENV -Value "ASSET_BASENAME=praktiKST-$version-$shortSha"
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -188,7 +193,7 @@ jobs:
echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV" echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -262,7 +267,7 @@ jobs:
echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV" echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -308,7 +313,7 @@ jobs:
echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV" echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -356,7 +361,7 @@ jobs:
echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV" echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -468,7 +473,7 @@ jobs:
echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV" echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -659,7 +664,7 @@ jobs:
echo "ARCH=$ARCH" >> "$GITHUB_ENV" echo "ARCH=$ARCH" >> "$GITHUB_ENV"
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
+11 -3
View File
@@ -6,6 +6,9 @@ on:
- main - main
workflow_dispatch: workflow_dispatch:
permissions:
contents: read
env: env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
@@ -19,7 +22,7 @@ jobs:
uses: actions/checkout@v7 uses: actions/checkout@v7
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -155,13 +158,16 @@ jobs:
test: test:
name: Test (Java 21, headless) name: Test (Java 21, headless)
runs-on: ubuntu-latest runs-on: ubuntu-latest
# A healthy run takes about four minutes. The per-test limit in build.gradle.kts names
# a hanging test; this cap covers a hang outside any test, such as in Gradle itself.
timeout-minutes: 20
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v7 uses: actions/checkout@v7
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -283,8 +289,10 @@ jobs:
if-no-files-found: ignore if-no-files-found: ignore
retention-days: 14 retention-days: 14
# Also on cancelled(): the job timeout cancels a hanging run, and the reports of the
# classes that did finish carry the timed-out tests' full stacks.
- name: Keep the test reports on a failure - name: Keep the test reports on a failure
if: failure() if: failure() || cancelled()
uses: actions/upload-artifact@v7 uses: actions/upload-artifact@v7
with: with:
name: test-results name: test-results
+14 -9
View File
@@ -24,6 +24,9 @@ jobs:
test: test:
name: Test (Java 21, headless) name: Test (Java 21, headless)
runs-on: ubuntu-latest runs-on: ubuntu-latest
# A healthy run takes about four minutes. The per-test limit in build.gradle.kts names
# a hanging test; this cap covers a hang outside any test, such as in Gradle itself.
timeout-minutes: 20
steps: steps:
- name: Checkout - name: Checkout
@@ -57,7 +60,7 @@ jobs:
echo "Tag $REF_NAME matches composePackageVersion=$PROPERTY_VERSION" echo "Tag $REF_NAME matches composePackageVersion=$PROPERTY_VERSION"
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -127,8 +130,10 @@ jobs:
exit 1 exit 1
fi fi
# Also on cancelled(): the job timeout cancels a hanging run, and the reports of the
# classes that did finish carry the timed-out tests' full stacks.
- name: Keep the test reports on a failure - name: Keep the test reports on a failure
if: failure() if: failure() || cancelled()
uses: actions/upload-artifact@v7 uses: actions/upload-artifact@v7
with: with:
name: test-results name: test-results
@@ -148,7 +153,7 @@ jobs:
uses: actions/checkout@v7 uses: actions/checkout@v7
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -217,7 +222,7 @@ jobs:
uses: actions/checkout@v7 uses: actions/checkout@v7
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -284,7 +289,7 @@ jobs:
uses: actions/checkout@v7 uses: actions/checkout@v7
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -355,7 +360,7 @@ jobs:
uses: actions/checkout@v7 uses: actions/checkout@v7
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -426,7 +431,7 @@ jobs:
uses: actions/checkout@v7 uses: actions/checkout@v7
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -529,7 +534,7 @@ jobs:
uses: actions/checkout@v7 uses: actions/checkout@v7
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -659,7 +664,7 @@ jobs:
uses: actions/checkout@v7 uses: actions/checkout@v7
- name: Set up Java 21 - name: Set up Java 21
uses: actions/setup-java@v6.1.0 uses: actions/setup-java@v6.2.0
with: with:
distribution: temurin distribution: temurin
java-version: "21" java-version: "21"
@@ -3,6 +3,10 @@ name: TEST publish-version-xml (local only)
on: on:
workflow_dispatch: workflow_dispatch:
permissions:
contents: read
issues: read
jobs: jobs:
publish-version-xml: publish-version-xml:
name: Publish Version Info XML via WebDAV name: Publish Version Info XML via WebDAV
+2
View File
@@ -103,3 +103,5 @@ You can sponsor KST4Contest here: [Support on Ko-Fi](https://ko-fi.com/praktimar
The following people are sponsoring KST4Contest: The following people are sponsoring KST4Contest:
- Marco (DJ5KW) - Marco (DJ5KW)
- Steve (G1YBB/M1B/MW1B)
- Jens (DH1AKY)
+107 -2
View File
@@ -319,6 +319,9 @@ map.showPathAnalysis=Streckenanalyse zeigen
map.hidePathAnalysis=Streckenanalyse ausblenden map.hidePathAnalysis=Streckenanalyse ausblenden
map.pathAnalysisHidden=Die Streckenanalyse ist ausgeblendet. map.pathAnalysisHidden=Die Streckenanalyse ist ausgeblendet.
map.tilesUnavailable=Kartenkacheln nicht verfügbar — die Netzverbindung prüfen. map.tilesUnavailable=Kartenkacheln nicht verfügbar — die Netzverbindung prüfen.
map.overlayAntenna=Antenne
map.overlayFilters=Aktive Filter
map.overlayLegendTooltip=Rot: tatsächliche Antennenrichtung, Öffnungswinkel und maximaler QRB. Blau: aktive QTF- und QRB-Filter.
path.title=Strecken- und Geländeanalyse path.title=Strecken- und Geländeanalyse
path.selectStation=Eine Station wählen, um Strecken- und Geländeanalyse vorzubereiten. path.selectStation=Eine Station wählen, um Strecken- und Geländeanalyse vorzubereiten.
path.fromLocator=Vom Locator: path.fromLocator=Vom Locator:
@@ -457,7 +460,7 @@ column.score=Wertung
monitor.title=Cluster & Fremd-QSOs monitor.title=Cluster & Fremd-QSOs
monitor.dxCluster=DX-Cluster monitor.dxCluster=DX-Cluster
profiles.createFailed=Das Profil konnte nicht angelegt werden. Die Profilliste konnte nicht geschrieben werden. 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.duplicateFailed=Das Profil konnte nicht dupliziert werden.
profiles.rootNotDeletable=Das Standardprofil verwendet die Dateien der Installation selbst und kann nicht gelöscht 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. profiles.activeNotDeletable=Das gerade benutzte Profil kann nicht gelöscht werden. Zuerst zu einem anderen Profil wechseln.
@@ -470,7 +473,17 @@ profiles.changeAfterSwitch=Die Änderung wirkt erst nach einem erneuten Wechsel
profiles.alreadyActive=Dieses Profil ist bereits aktiv. profiles.alreadyActive=Dieses Profil ist bereits aktiv.
profiles.selectFirst=Zuerst ein Profil in der Tabelle wählen. profiles.selectFirst=Zuerst ein Profil in der Tabelle wählen.
beacon.invalidMessage=Der Bakentext ist ungültig: {0} beacon.invalidMessage=Der Bakentext ist ungültig: {0}
beacon.intervalTooShort=Einen ganzzahligen Bakenabstand von mindestens {0} Minute eingeben. beacon.intervalTooShort=Einen ganzzahligen Bakenabstand von mindestens {0} Minuten eingeben.
beacon.status.main=Hauptkategorie: {0}
beacon.status.second=Zweite Kategorie: {0}
beacon.status.enabled=aktiv
beacon.status.failed=Versand fehlgeschlagen
beacon.status.unavailable=nicht verfügbar
beacon.reason.session=in dieser Sitzung noch nicht aktiviert
beacon.reason.user=durch den Benutzer ausgeschaltet
beacon.reason.primaryQrg=Haupt-QRG fehlt oder ist ungültig
beacon.reason.secondaryQrg=zweite QRG fehlt oder ist ungültig
beacon.reason.automaticQrg=automatische QRG-Änderung um mehr als 5 kHz
notification.invalidPort=„{0}" ist kein gültiger TCP-Port. Einen Wert von 1 bis 65535 eingeben. notification.invalidPort=„{0}" ist kein gültiger TCP-Port. Einen Wert von 1 bis 65535 eingeben.
notification.invalidSpotter=„{0}" ist kein gültiges Spotter-Rufzeichen. notification.invalidSpotter=„{0}" ist kein gültiges Spotter-Rufzeichen.
notification.invalidCallsign=Bitte ein gültiges Rufzeichen eingeben. notification.invalidCallsign=Bitte ein gültiges Rufzeichen eingeben.
@@ -482,3 +495,95 @@ profiles.unknown=unbekannt
profiles.copyOf=Kopie von {0} profiles.copyOf=Kopie von {0}
profiles.sharedDatabase=gemeinsame Stationsdatenbank profiles.sharedDatabase=gemeinsame Stationsdatenbank
profiles.ownDatabase=eigene Datenbank 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
+107 -2
View File
@@ -328,6 +328,9 @@ map.showPathAnalysis=Show path analysis
map.hidePathAnalysis=Hide path analysis map.hidePathAnalysis=Hide path analysis
map.pathAnalysisHidden=Path analysis is hidden. map.pathAnalysisHidden=Path analysis is hidden.
map.tilesUnavailable=Map tiles unavailable — check the network connection. map.tilesUnavailable=Map tiles unavailable — check the network connection.
map.overlayAntenna=Antenna
map.overlayFilters=Active filters
map.overlayLegendTooltip=Red: actual antenna heading, beamwidth and maximum QRB. Blue: active QTF and QRB filters.
path.title=Path / terrain analysis path.title=Path / terrain analysis
path.selectStation=Select a station to prepare path and terrain analysis. path.selectStation=Select a station to prepare path and terrain analysis.
path.fromLocator=From locator: path.fromLocator=From locator:
@@ -466,7 +469,7 @@ column.score=Score
monitor.title=Cluster & QSO of the other monitor.title=Cluster & QSO of the other
monitor.dxCluster=DX cluster monitor.dxCluster=DX cluster
profiles.createFailed=The profile could not be created. The profile registry could not be written. 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.duplicateFailed=The profile could not be duplicated.
profiles.rootNotDeletable=The default profile uses the files of the installation itself and cannot be deleted. 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. profiles.activeNotDeletable=The profile currently in use cannot be deleted. Switch to another profile first.
@@ -479,7 +482,17 @@ profiles.changeAfterSwitch=The change takes effect after switching to this profi
profiles.alreadyActive=This profile is already active. profiles.alreadyActive=This profile is already active.
profiles.selectFirst=Select a profile in the table first. profiles.selectFirst=Select a profile in the table first.
beacon.invalidMessage=The beacon message is invalid: {0} beacon.invalidMessage=The beacon message is invalid: {0}
beacon.intervalTooShort=Enter a whole beacon interval of at least {0} minute. beacon.intervalTooShort=Enter a whole beacon interval of at least {0} minutes.
beacon.status.main=Main category: {0}
beacon.status.second=Second category: {0}
beacon.status.enabled=active
beacon.status.failed=send failed
beacon.status.unavailable=unavailable
beacon.reason.session=not activated in this session
beacon.reason.user=switched off by the operator
beacon.reason.primaryQrg=primary QRG missing or invalid
beacon.reason.secondaryQrg=second QRG missing or invalid
beacon.reason.automaticQrg=automatic QRG change greater than 5 kHz
notification.invalidPort="{0}" is not a valid TCP port. Enter a value from 1 to 65535. notification.invalidPort="{0}" is not a valid TCP port. Enter a value from 1 to 65535.
notification.invalidSpotter="{0}" is not a valid spotter callsign. notification.invalidSpotter="{0}" is not a valid spotter callsign.
notification.invalidCallsign=Please enter a valid callsign. notification.invalidCallsign=Please enter a valid callsign.
@@ -491,3 +504,95 @@ profiles.unknown=unknown
profiles.copyOf=Copy of {0} profiles.copyOf=Copy of {0}
profiles.sharedDatabase=common station database profiles.sharedDatabase=common station database
profiles.ownDatabase=own 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.OperatorProfilePaths;
import kst4contest.controller.OperatorProfileStore; import kst4contest.controller.OperatorProfileStore;
import kst4contest.model.OperatorProfile; import kst4contest.model.OperatorProfile;
import kst4contest.model.OperatorProfileSelection;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -24,6 +25,20 @@ public final class ApplicationRuntimeLauncher {
private static Kst4ContestApplication currentRuntime; 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() { private ApplicationRuntimeLauncher() {
// Utility class. // Utility class.
} }
@@ -61,14 +76,100 @@ public final class ApplicationRuntimeLauncher {
System.exit(0); 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. * Replaces the running runtime with one bound to another operator profile.
* *
* @param targetProfile profile to activate * @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) { 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) { if (targetProfile == null) {
return false; return false;
} }
@@ -1,5 +1,6 @@
package kst4contest.view; package kst4contest.view;
import kst4contest.controller.RadioSlot;
import kst4contest.model.ChatCategory; import kst4contest.model.ChatCategory;
import kst4contest.model.ChatMember; import kst4contest.model.ChatMember;
import kst4contest.model.ChatMessage; import kst4contest.model.ChatMessage;
@@ -97,4 +98,9 @@ public final class ComposeChatInputActions implements ChatInputActions {
String value = application.chatcontroller.getChatPreferences().getMYQRGSecondCat().get(); String value = application.chatcontroller.getChatPreferences().getMYQRGSecondCat().get();
return value == null ? "" : value; return value == null ? "" : value;
} }
@Override
public void applyManualQrg(final RadioSlot slot, final String value) {
application.chatcontroller.applyManualQrg(slot, value);
}
} }
@@ -54,6 +54,11 @@ public final class ComposeMenuActions implements MainMenuActions {
application.runOnUi(application::menuActionToggleSettingsWindow); application.runOnUi(application::menuActionToggleSettingsWindow);
} }
@Override
public void openSetupWizard() {
application.runOnUi(application::menuActionOpenSetupWizard);
}
@Override @Override
public void toggleMonitorWindow() { public void toggleMonitorWindow() {
application.runOnUi(application::menuActionToggleMonitorWindow); application.runOnUi(application::menuActionToggleMonitorWindow);
@@ -42,6 +42,8 @@ import kst4contest.view.compose.SettingsWindow;
import kst4contest.controller.ScoreService; import kst4contest.controller.ScoreService;
import kst4contest.view.compose.SettingsWindow; import kst4contest.view.compose.SettingsWindow;
import kst4contest.controller.On4KstConnectionState; import kst4contest.controller.On4KstConnectionState;
import kst4contest.view.compose.wizard.SetupWizardLauncher;
import kst4contest.view.compose.wizard.SetupWizardOutcome;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@@ -2177,6 +2179,17 @@ public class Kst4ContestApplication implements StatusUpdateListener, SettingsHos
return; 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); ApplicationRuntimeLauncher.setCurrent(this);
ApplicationFileUtils.copyResourceIfRequired(ApplicationConstants.APPLICATION_NAME, STYLE_DEFAULTCSSDAY_RESOURCE, STYLE_DEFAULTCSSDAY_FILE); ApplicationFileUtils.copyResourceIfRequired(ApplicationConstants.APPLICATION_NAME, STYLE_DEFAULTCSSDAY_RESOURCE, STYLE_DEFAULTCSSDAY_FILE);
@@ -2297,6 +2310,15 @@ public class Kst4ContestApplication implements StatusUpdateListener, SettingsHos
//initialize the timeline //initialize the timeline
uiDispatcher.runOnUi(this::updateTimelineVisuals); 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 * Replaces Application.stop(), which only JavaFX ever called. This covers a SIGTERM
* and a closing terminal; the ordinary exit still goes through * and a closing terminal; the ordinary exit still goes through
@@ -3032,6 +3054,20 @@ public class Kst4ContestApplication implements StatusUpdateListener, SettingsHos
private java.util.function.Consumer<java.util.List<ChatMessage>> composeChatListener; private java.util.function.Consumer<java.util.List<ChatMessage>> composeChatListener;
private java.util.function.Consumer<java.util.List<ClusterMessage>> composeClusterListener; private java.util.function.Consumer<java.util.List<ClusterMessage>> composeClusterListener;
/**
* Fills the three global Compose message tables from their filtered
* controller views.
*/
/* package */ static void refreshComposeMessageTables(
final ChatController controller,
final DataTableState<ChatMessage> directed,
final DataTableState<ChatMessage> publicMessages,
final DataTableState<ChatMessage> qsoOfTheOther) {
directed.replaceRows(controller.toMeMessages());
publicMessages.replaceRows(controller.toAllMessages());
qsoOfTheOther.replaceRows(controller.toOtherMessages());
}
/** /**
* Opens the Compose main window beside the JavaFX one. * Opens the Compose main window beside the JavaFX one.
* *
@@ -3264,6 +3300,16 @@ public class Kst4ContestApplication implements StatusUpdateListener, SettingsHos
}), }),
newJoined, newJoined,
reachability); reachability);
composeMainWindowState.getThreadButtons().registerAction(
ChatController.BEACON_STATUS_SOURCE,
() -> {
chatcontroller.toggleUsableBeacons();
return kotlin.Unit.INSTANCE;
});
composeMainWindowState.getThreadButtons().registerStatusProvider(
ChatController.BEACON_STATUS_SOURCE,
chatcontroller::currentBeaconStatus);
chatcontroller.refreshBeaconStatus();
/* /*
* The feed, not the window construction, owns the timeline's data from here. * The feed, not the window construction, owns the timeline's data from here.
@@ -3342,11 +3388,11 @@ public class Kst4ContestApplication implements StatusUpdateListener, SettingsHos
return kotlin.Unit.INSTANCE; return kotlin.Unit.INSTANCE;
}); });
composeChatListener = rows -> uiDispatcher.runOnUi(() -> { composeChatListener = rows -> uiDispatcher.runOnUi(() -> refreshComposeMessageTables(
directed.replaceRows(chatcontroller.toMeMessages()); chatcontroller,
publicMessages.replaceRows(rows); directed,
qsoOfTheOther.replaceRows(chatcontroller.toOtherMessages()); publicMessages,
}); qsoOfTheOther));
chatcontroller.getLst_globalChatMessageList().addListener(composeChatListener); chatcontroller.getLst_globalChatMessageList().addListener(composeChatListener);
composeClusterListener = rows -> uiDispatcher.runOnUi(() -> cluster.replaceRows(rows)); composeClusterListener = rows -> uiDispatcher.runOnUi(() -> cluster.replaceRows(rows));
@@ -3361,10 +3407,8 @@ public class Kst4ContestApplication implements StatusUpdateListener, SettingsHos
stations.replaceRows(initialMembers); stations.replaceRows(initialMembers);
newJoined.updateActiveMembers(initialMembers); newJoined.updateActiveMembers(initialMembers);
newJoined.updateEvents(chatcontroller.getRecentChatJoins().snapshot()); newJoined.updateEvents(chatcontroller.getRecentChatJoins().snapshot());
directed.replaceRows(chatcontroller.toMeMessages()); refreshComposeMessageTables(chatcontroller, directed, publicMessages, qsoOfTheOther);
publicMessages.replaceRows(chatcontroller.getLst_globalChatMessageList().snapshot());
cluster.replaceRows(chatcontroller.getLst_clusterMemberList().snapshot()); cluster.replaceRows(chatcontroller.getLst_clusterMemberList().snapshot());
qsoOfTheOther.replaceRows(chatcontroller.toOtherMessages());
/* /*
* The only push that does not check the feed for null, and deliberately so: the * The only push that does not check the feed for null, and deliberately so: the
* feed is assigned earlier in this same method, so a guard here could never fire * feed is assigned earlier in this same method, so a guard here could never fire
@@ -4002,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. */ /** Windows -> open or close the cluster / stranger-QSO monitor window. */
void menuActionToggleMonitorWindow() { void menuActionToggleMonitorWindow() {
if (MonitorWindow.isOpen()) { if (MonitorWindow.isOpen()) {
@@ -4124,6 +4189,17 @@ public class Kst4ContestApplication implements StatusUpdateListener, SettingsHos
}); });
} }
@Override
public void refreshMapDisplaySettings() {
uiDispatcher.runOnUi(() -> {
if (composeMainWindowState == null) {
return;
}
composeMainWindowState.refreshMapDisplaySettings();
forceChatMemberFilterRefresh();
});
}
/** /**
* No-op since the JavaFX own-QRG text field was removed with the never-shown window. * No-op since the JavaFX own-QRG text field was removed with the never-shown window.
* *
@@ -0,0 +1,58 @@
package kst4contest.view.compose
import kst4contest.model.BeaconStatusSnapshot
import kst4contest.model.BeaconStatusSnapshot.AggregateState
import kst4contest.model.BeaconStatusSnapshot.CategoryStatus
import kst4contest.model.BeaconStatusSnapshot.InactiveReason
import kst4contest.view.i18n.CurrentStrings
import kst4contest.view.i18n.Strings
enum class ThreadStatusVisualStyle {
DEFAULT,
BEACON_OFF,
BEACON_ACTIVE,
BEACON_FAILED,
}
data class BeaconStatusPresentation(
val label: String,
val tooltip: String,
val style: ThreadStatusVisualStyle,
) {
companion object {
fun from(
snapshot: BeaconStatusSnapshot,
strings: Strings = CurrentStrings.get(),
): BeaconStatusPresentation {
val label = when (snapshot.aggregateState) {
AggregateState.OFF -> "off"
AggregateState.PARTIAL -> "1/2"
AggregateState.ON -> "on"
AggregateState.FAILED -> "FAILED"
}
val style = when (snapshot.aggregateState) {
AggregateState.OFF -> ThreadStatusVisualStyle.BEACON_OFF
AggregateState.PARTIAL, AggregateState.ON -> ThreadStatusVisualStyle.BEACON_ACTIVE
AggregateState.FAILED -> ThreadStatusVisualStyle.BEACON_FAILED
}
val tooltip = listOf(
strings.beaconStatusMain(describe(snapshot.main, strings)),
strings.beaconStatusSecond(describe(snapshot.second, strings)),
).joinToString("\n")
return BeaconStatusPresentation(label, tooltip, style)
}
private fun describe(category: CategoryStatus, strings: Strings): String {
if (!category.isAvailable()) return strings.beaconStatusUnavailable
if (category.isFailed()) return strings.beaconStatusFailed
if (category.isEnabled()) return strings.beaconStatusEnabled
return when (category.inactiveReason) {
InactiveReason.NOT_ACTIVATED_THIS_SESSION -> strings.beaconReasonSession
InactiveReason.USER_DISABLED -> strings.beaconReasonUser
InactiveReason.PRIMARY_QRG_UNAVAILABLE -> strings.beaconReasonPrimaryQrg
InactiveReason.SECONDARY_QRG_UNAVAILABLE -> strings.beaconReasonSecondaryQrg
InactiveReason.AUTOMATIC_QRG_CHANGE -> strings.beaconReasonAutomaticQrg
}
}
}
}
@@ -163,12 +163,12 @@ fun ChatInputRow(
// profile on every keystroke. // profile on every keystroke.
InlineCommittedField( InlineCommittedField(
stored = ownQrgMain.value.orEmpty(), stored = ownQrgMain.value.orEmpty(),
onCommit = { prefs.getMYQRGFirstCat().set(it) }, onCommit = { state.commitOwnQrg(mainCategory = true, it) },
tooltip = kst4contest.view.i18n.CurrentStrings.get().chatOwnQrgTooltip, tooltip = kst4contest.view.i18n.CurrentStrings.get().chatOwnQrgTooltip,
) )
InlineCommittedField( InlineCommittedField(
stored = ownQrgSecond.value.orEmpty(), stored = ownQrgSecond.value.orEmpty(),
onCommit = { prefs.getMYQRGSecondCat().set(it) }, onCommit = { state.commitOwnQrg(mainCategory = false, it) },
tooltip = if (so2rEnabled) { tooltip = if (so2rEnabled) {
kst4contest.view.i18n.CurrentStrings.get().chatSecondQrgTooltipSo2r kst4contest.view.i18n.CurrentStrings.get().chatSecondQrgTooltipSo2r
} else { } else {
@@ -5,6 +5,7 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.input.TextFieldValue
import kst4contest.controller.RadioSlot
import kst4contest.model.ChatCategory import kst4contest.model.ChatCategory
import kst4contest.model.ChatMember import kst4contest.model.ChatMember
import kst4contest.model.ChatMessage import kst4contest.model.ChatMessage
@@ -46,6 +47,8 @@ interface ChatInputActions {
fun ownQrgMain(): String fun ownQrgMain(): String
fun ownQrgSecond(): String fun ownQrgSecond(): String
fun applyManualQrg(slot: RadioSlot, value: String) {}
} }
/** /**
@@ -150,6 +153,10 @@ class ChatInputState(private val actions: ChatInputActions) {
appendAndFocus("$qrg ") appendAndFocus("$qrg ")
} }
fun commitOwnQrg(mainCategory: Boolean, value: String) {
actions.applyManualQrg(if (mainCategory) RadioSlot.FIRST else RadioSlot.SECOND, value)
}
/** /**
* Replaces the field with "/cq CALL <snippet>", resolved. * Replaces the field with "/cq CALL <snippet>", resolved.
* *
@@ -55,6 +55,9 @@ interface MainMenuActions {
fun setQrgAsNameInChat() fun setQrgAsNameInChat()
fun toggleAwayState() fun toggleAwayState()
fun toggleSettingsWindow() fun toggleSettingsWindow()
/** Ends the session after asking and runs the setup wizard for the active profile. */
fun openSetupWizard()
fun toggleMonitorWindow() fun toggleMonitorWindow()
fun toggleStationMap() fun toggleStationMap()
fun useDarkDesign() fun useDarkDesign()
@@ -87,6 +87,11 @@ fun mainMenuModel(
enabled = true, enabled = true,
actions::toggleSettingsWindow, 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( MenuSpec(
@@ -10,6 +10,8 @@ import androidx.compose.runtime.setValue
import kst4contest.controller.On4KstConnectionState import kst4contest.controller.On4KstConnectionState
import kst4contest.model.ChatPreferences import kst4contest.model.ChatPreferences
import kst4contest.observe.SimpleRoster import kst4contest.observe.SimpleRoster
import kst4contest.view.compose.map.MapDisplaySettingsState
import kst4contest.view.compose.map.MapNavigationState
/** /**
* Everything the main window draws, in one object. * Everything the main window draws, in one object.
@@ -67,6 +69,19 @@ class MainWindowState(
val reachability: ReachabilityState = ReachabilityState(activeBands), val reachability: ReachabilityState = ReachabilityState(activeBands),
) { ) {
internal val mapNavigation = MapNavigationState()
internal val mapDisplaySettings = MapDisplaySettingsState(prefs)
init {
stationSelection.explicitSelectionListener = { member, source ->
when {
source == StationSelectionSource.RESET_VIEW -> mapNavigation.resetToHome()
member != null -> StationIdentity.of(member)?.let(mapNavigation::fitSelectedPath)
}
}
}
/** Explicit map analysis requested from either station context menu. */ /** Explicit map analysis requested from either station context menu. */
val mapReachability = MapReachabilityState(prefs.stn_loginLocatorMainCat.orEmpty()) val mapReachability = MapReachabilityState(prefs.stn_loginLocatorMainCat.orEmpty())
@@ -111,9 +126,15 @@ class MainWindowState(
/** Applies only a deliberate QTF filter entry, never a restored or reset filter value. */ /** Applies only a deliberate QTF filter entry, never a restored or reset filter value. */
fun applyExplicitQtfFilterDirection(qtf: Double) { fun applyExplicitQtfFilterDirection(qtf: Double) {
mapNavigation.centerOnQtf(qtf)
applyExplicitQtfHeading(prefs, qtf) applyExplicitQtfHeading(prefs, qtf)
} }
/** Refreshes map geometry after the Station settings draft has been applied. */
fun refreshMapDisplaySettings() {
mapDisplaySettings.refreshFromPreferences()
}
fun requestLayoutSave() { fun requestLayoutSave() {
layoutSaveRequested?.invoke() layoutSaveRequested?.invoke()
} }
@@ -1,7 +1,11 @@
package kst4contest.view.compose package kst4contest.view.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import kst4contest.observe.ObservableValue import kst4contest.observe.ObservableValue
import java.util.function.Consumer import java.util.function.Consumer
@@ -35,3 +39,19 @@ class ObservedValue<T>(private val source: ObservableValue<T>) {
source.removeListener(follower) source.removeListener(follower)
} }
} }
/** Observes a domain value only for the lifetime of the current composition. */
@Composable
internal fun <T> ObservableValue<T>.observeAsState(): State<T?> {
val state = remember(this) { mutableStateOf(get()) }
DisposableEffect(this) {
val follower = Consumer<T> { updated -> state.value = updated }
addListener(follower)
// Close the gap between the initial read and listener registration.
state.value = get()
onDispose { removeListener(follower) }
}
return state
}
@@ -62,6 +62,9 @@ interface SettingsHost {
*/ */
fun refreshSo2rState() fun refreshSo2rState()
/** Pushes applied antenna-beam geometry into the open Compose map. */
fun refreshMapDisplaySettings()
/** Rebuilds the Ctrl+1..Ctrl+0 context menus from the snippet list. */ /** Rebuilds the Ctrl+1..Ctrl+0 context menus from the snippet list. */
fun refreshTextSnippetContextMenusFromSettings() fun refreshTextSnippetContextMenusFromSettings()
@@ -148,6 +151,8 @@ fun buildSettingsTabs(
applySecondCategory = { category -> controller.setChatCategorySecondChat(category) }, applySecondCategory = { category -> controller.setChatCategorySecondChat(category) },
connectionState = connectionState, connectionState = connectionState,
applySecondRotator = { controller.reconfigureSecondRotator(); host.refreshSo2rState() }, applySecondRotator = { controller.reconfigureSecondRotator(); host.refreshSo2rState() },
refreshBeaconStatus = controller::refreshBeaconStatus,
applyMapDisplaySettings = host::refreshMapDisplaySettings,
) )
val notificationState = NotificationTabState( val notificationState = NotificationTabState(
@@ -185,8 +190,14 @@ fun buildSettingsTabs(
draft, draft,
validateBeaconTemplate = { template -> controller.validateBeaconTemplate(template) }, validateBeaconTemplate = { template -> controller.validateBeaconTemplate(template) },
restartBeaconTimer = { controller.restartBeaconTimer() }, restartBeaconTimer = { controller.restartBeaconTimer() },
setMainBeaconEnabled = controller::setMainBeaconEnabled,
setSecondBeaconEnabled = controller::setSecondBeaconEnabled,
mainCategoryName = categoryName(controller.chatCategoryMain, kst4contest.view.i18n.CurrentStrings.get().settingsCategoryMainFallback), mainCategoryName = categoryName(controller.chatCategoryMain, kst4contest.view.i18n.CurrentStrings.get().settingsCategoryMainFallback),
secondCategoryName = categoryName(controller.chatCategorySecondChat, kst4contest.view.i18n.CurrentStrings.get().settingsCategorySecondFallback), secondCategoryName = categoryName(controller.chatCategorySecondChat, kst4contest.view.i18n.CurrentStrings.get().settingsCategorySecondFallback),
onBeaconTemplatesApplied = {
controller.onMainBeaconTemplateApplied()
controller.onSecondBeaconTemplateApplied()
},
) )
val logSynchState = LogSynchTabState( val logSynchState = LogSynchTabState(
@@ -90,6 +90,13 @@ class StationSelectionState : TableSelectionModel<ChatMember> {
var lastSource: StationSelectionSource by mutableStateOf(StationSelectionSource.PROGRAMMATIC) var lastSource: StationSelectionSource by mutableStateOf(StationSelectionSource.PROGRAMMATIC)
private set private set
/** Changes only for deliberate station choices, including repeated choices. */
var explicitSelectionRevision: Long by mutableStateOf(0L)
private set
/** Receives deliberate station choices without observing roster reconciliation. */
internal var explicitSelectionListener: ((ChatMember?, StationSelectionSource) -> Unit)? = null
val identity: StationIdentity? val identity: StationIdentity?
get() = StationIdentity.of(current) get() = StationIdentity.of(current)
@@ -101,6 +108,10 @@ class StationSelectionState : TableSelectionModel<ChatMember> {
current = row current = row
lastSource = source lastSource = source
selectionRevision++ selectionRevision++
if (source.isExplicitSelection()) {
explicitSelectionRevision++
explicitSelectionListener?.invoke(row, source)
}
if (row != null && source.requestsStationTableScroll()) { if (row != null && source.requestsStationTableScroll()) {
scrollRequestRevision++ scrollRequestRevision++
} }
@@ -118,6 +129,11 @@ class StationSelectionState : TableSelectionModel<ChatMember> {
} }
} }
private fun StationSelectionSource.isExplicitSelection(): Boolean = when (this) {
StationSelectionSource.PROGRAMMATIC -> false
else -> true
}
private fun StationSelectionSource.requestsStationTableScroll(): Boolean = when (this) { private fun StationSelectionSource.requestsStationTableScroll(): Boolean = when (this) {
StationSelectionSource.STATION_TABLE, StationSelectionSource.STATION_TABLE,
StationSelectionSource.STATION_CONTEXT_MENU, StationSelectionSource.STATION_CONTEXT_MENU,
@@ -7,6 +7,7 @@ import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.TooltipArea import androidx.compose.foundation.TooltipArea
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.border import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.ExperimentalLayoutApi
@@ -25,6 +26,8 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
@@ -39,11 +42,9 @@ import kst4contest.controller.On4KstConnectionState
* only the indicators are left here — which is also what finally makes the bar wrap * only the indicators are left here — which is also what finally makes the bar wrap
* properly on a narrow window instead of pushing the badges out of sight. * properly on a narrow window instead of pushing the badges out of sight.
* *
* Nothing in this bar is clickable. The three indicators were mouse-transparent and * The connection and notice indicators remain non-clickable. A background-thread status is
* non-focusable in JavaFX and stay that way: the operator is typing into the chat, and a * actionable only when the application explicitly registers an action for that source; the
* status badge must never take the keyboard. The background-thread buttons were ordinary * beacon uses this for its quick switch, while every other worker remains a plain label.
* focusable Buttons there, with no action attached — they are drawn as plain labels here,
* which is what they always behaved like.
*/ */
@OptIn(ExperimentalLayoutApi::class) @OptIn(ExperimentalLayoutApi::class)
@Composable @Composable
@@ -202,20 +203,41 @@ private fun ThreadStatusButtonView(button: ThreadStatusButton) {
} }
val scheme = MaterialTheme.colorScheme val scheme = MaterialTheme.colorScheme
val background = if (button.highlighted) scheme.primary else scheme.surfaceVariant val colors = if (button.visualStyle == ThreadStatusVisualStyle.DEFAULT) {
val foreground = if (button.highlighted) scheme.onPrimary else scheme.onSurfaceVariant ThreadButtonColors(
background = if (button.highlighted) scheme.primary else scheme.surfaceVariant,
border = null,
text = if (button.highlighted) scheme.onPrimary else scheme.onSurfaceVariant,
)
} else {
beaconThreadButtonColors(
style = button.visualStyle,
highlighted = button.highlighted,
darkTheme = scheme.surface.luminance() < 0.5f,
neutralBackground = scheme.surfaceVariant,
)
}
TooltipArea(tooltip = { TooltipCard(button.tooltip) }) { TooltipArea(tooltip = { TooltipCard(button.tooltip) }) {
Box( val actionModifier = if (button.hasAction) {
modifier = Modifier Modifier.clickable(role = Role.Button) { button.activate() }
} else {
Modifier
}
var boxModifier = Modifier
.defaultMinSize(minHeight = 22.dp) .defaultMinSize(minHeight = 22.dp)
.background(background, NOTICE_SHAPE) .background(colors.background, NOTICE_SHAPE)
.padding(NOTICE_PADDING), .then(actionModifier)
colors.border?.let { border ->
boxModifier = boxModifier.border(1.dp, border, NOTICE_SHAPE)
}
Box(
modifier = boxModifier.padding(NOTICE_PADDING),
contentAlignment = Alignment.Center, contentAlignment = Alignment.Center,
) { ) {
Text( Text(
text = button.label, text = button.label,
color = foreground, color = colors.text,
style = MaterialTheme.typography.labelMedium, style = MaterialTheme.typography.labelMedium,
maxLines = 1, maxLines = 1,
) )
@@ -223,6 +245,33 @@ private fun ThreadStatusButtonView(button: ThreadStatusButton) {
} }
} }
internal data class ThreadButtonColors(
val background: Color,
val border: Color?,
val text: Color,
)
internal fun beaconThreadButtonColors(
style: ThreadStatusVisualStyle,
highlighted: Boolean,
darkTheme: Boolean,
neutralBackground: Color,
): ThreadButtonColors = when (style) {
ThreadStatusVisualStyle.BEACON_ACTIVE -> if (highlighted) {
ThreadButtonColors(Color(0xFFFFB300), Color(0xFFFFE082), Color(0xFF1B1B1B))
} else {
ThreadButtonColors(Color(0xFF238636), Color(0xFF56D364), Color.White)
}
ThreadStatusVisualStyle.BEACON_FAILED ->
ThreadButtonColors(Color(0xFFD50000), Color(0xFFFF6B6B), Color.White)
ThreadStatusVisualStyle.BEACON_OFF -> ThreadButtonColors(
neutralBackground,
null,
if (darkTheme) Color(0xFFFF6B6B) else Color(0xFFD50000),
)
ThreadStatusVisualStyle.DEFAULT -> error("Default worker colours come from the theme")
}
/** The tooltips in this bar carry the long text the badges had to cut. */ /** The tooltips in this bar carry the long text the badges had to cut. */
@Composable @Composable
internal fun TooltipCard(text: String) { internal fun TooltipCard(text: String) {
@@ -176,20 +176,36 @@ object StatusIndicators {
class ThreadStatusButtons { class ThreadStatusButtons {
private val bySource = LinkedHashMap<String, ThreadStatusButton>() private val bySource = LinkedHashMap<String, ThreadStatusButton>()
private val actions = LinkedHashMap<String, () -> Unit>()
private val statusProviders = LinkedHashMap<String, () -> ThreadStateMessage>()
private val ordered = mutableStateListOf<ThreadStatusButton>() private val ordered = mutableStateListOf<ThreadStatusButton>()
val buttons: List<ThreadStatusButton> get() = ordered val buttons: List<ThreadStatusButton> get() = ordered
fun update(sourceName: String, message: ThreadStateMessage) { fun update(sourceName: String, message: ThreadStateMessage) {
val effectiveMessage = statusProviders[sourceName]?.invoke() ?: message
val button = bySource.getOrPut(sourceName) { val button = bySource.getOrPut(sourceName) {
ThreadStatusButton(sourceName).also { ordered.add(it) } ThreadStatusButton(sourceName, actions[sourceName]).also { ordered.add(it) }
} }
val beacon = effectiveMessage.beaconStatusSnapshot?.let(BeaconStatusPresentation::from)
button.report( button.report(
label = "$sourceName: ${message.runningInformationTextDescription}", label = "$sourceName: ${beacon?.label ?: effectiveMessage.runningInformationTextDescription}",
tooltip = message.runningInformation.orEmpty(), tooltip = beacon?.tooltip ?: effectiveMessage.runningInformation.orEmpty(),
style = beacon?.style ?: ThreadStatusVisualStyle.DEFAULT,
) )
} }
/** Gives one status source an explicit action without changing any other source. */
fun registerAction(sourceName: String, action: () -> Unit) {
actions[sourceName] = action
bySource[sourceName]?.setAction(action)
}
/** Resolves a status only when its queued UI update is actually applied. */
fun registerStatusProvider(sourceName: String, provider: () -> ThreadStateMessage) {
statusProviders[sourceName] = provider
}
companion object { companion object {
/** How long the flash stays on; JavaFX used a 0.2 s PauseTransition. */ /** How long the flash stays on; JavaFX used a 0.2 s PauseTransition. */
const val HIGHLIGHT_MILLIS = 200L const val HIGHLIGHT_MILLIS = 200L
@@ -197,7 +213,10 @@ class ThreadStatusButtons {
} }
/** One background thread's button. */ /** One background thread's button. */
class ThreadStatusButton(val sourceName: String) { class ThreadStatusButton(
val sourceName: String,
initialAction: (() -> Unit)? = null,
) {
var label: String by mutableStateOf(sourceName) var label: String by mutableStateOf(sourceName)
private set private set
@@ -209,17 +228,43 @@ class ThreadStatusButton(val sourceName: String) {
var highlighted: Boolean by mutableStateOf(false) var highlighted: Boolean by mutableStateOf(false)
private set private set
var visualStyle: ThreadStatusVisualStyle by mutableStateOf(ThreadStatusVisualStyle.DEFAULT)
private set
var revision: Int by mutableStateOf(0) var revision: Int by mutableStateOf(0)
private set private set
internal fun report(label: String, tooltip: String) { var action: (() -> Unit)? by mutableStateOf(initialAction)
private set
val hasAction: Boolean
get() = action != null
internal fun report(
label: String,
tooltip: String,
style: ThreadStatusVisualStyle = ThreadStatusVisualStyle.DEFAULT,
) {
this.label = label this.label = label
this.tooltip = tooltip this.tooltip = tooltip
highlighted = true visualStyle = style
highlighted = style == ThreadStatusVisualStyle.DEFAULT ||
style == ThreadStatusVisualStyle.BEACON_ACTIVE
revision++ revision++
} }
fun clearHighlight() { fun clearHighlight() {
highlighted = false highlighted = false
} }
internal fun setAction(action: () -> Unit) {
this.action = action
}
/** Runs the registered action and reports whether this status is actionable. */
fun activate(): Boolean {
val current = action ?: return false
current()
return true
}
} }
@@ -112,10 +112,15 @@ fun ComposeStationMap(
antennaAzimuthDeg: Double, antennaAzimuthDeg: Double,
antennaBeamWidthDeg: Double, antennaBeamWidthDeg: Double,
maxQrbKm: Double, maxQrbKm: Double,
selectedTarget: MapCallsignRawSnapshot? = markers.firstOrNull {
it.callSignRaw() == selectedMarkerCallsign
},
spatialFilterOverlay: SpatialFilterOverlayState? = null,
onMarkerClicked: ((MapCallsignRawSnapshot) -> Unit)?, onMarkerClicked: ((MapCallsignRawSnapshot) -> Unit)?,
onMarkerContextRequested: ((List<MapCallsignRawSnapshot>, IntOffset) -> Unit)? = null, onMarkerContextRequested: ((List<MapCallsignRawSnapshot>, IntOffset) -> Unit)? = null,
workedGrossFields: Set<String> = emptySet(), workedGrossFields: Set<String> = emptySet(),
darkMode: Boolean = true, darkMode: Boolean = true,
onCanvasSizeChanged: (Size) -> Unit = { },
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
) { ) {
val imageCache = remember { TileBitmapCache() } val imageCache = remember { TileBitmapCache() }
@@ -147,6 +152,13 @@ fun ComposeStationMap(
* one linear pass over a few hundred markers. * one linear pass over a few hundred markers.
*/ */
val home = remember(ownLocator6) { homePosition(ownLocator6) } val home = remember(ownLocator6) { homePosition(ownLocator6) }
val selectedTargetOutsideMarkers by remember(markers, selectedTarget) {
derivedStateOf {
selectedTarget?.takeIf { target ->
target.hasUsablePosition() && markers.none { it.callSignRaw() == target.callSignRaw() }
}
}
}
val clusterResult by remember(markers, groupingEnabled, canvasSize) { val clusterResult by remember(markers, groupingEnabled, canvasSize) {
derivedStateOf { derivedStateOf {
StationMapClusterer.cluster( StationMapClusterer.cluster(
@@ -205,17 +217,28 @@ fun ComposeStationMap(
Canvas( Canvas(
modifier = modifier modifier = modifier
.clipToBounds() .clipToBounds()
.onSizeChanged { canvasSize = Size(it.width.toFloat(), it.height.toFloat()) } .onSizeChanged {
canvasSize = Size(it.width.toFloat(), it.height.toFloat())
onCanvasSizeChanged(canvasSize)
}
.onGloballyPositioned { canvasCoordinates = it } .onGloballyPositioned { canvasCoordinates = it }
.onPointerEvent(PointerEventType.Press) { event -> .onPointerEvent(PointerEventType.Press) { event ->
if (event.buttons.isSecondaryPressed) { if (event.buttons.isSecondaryPressed) {
val local = event.changes.firstOrNull()?.position ?: return@onPointerEvent val local = event.changes.firstOrNull()?.position ?: return@onPointerEvent
val viewport = mapState.viewportFor(canvasSize.width, canvasSize.height) val viewport = mapState.viewportFor(canvasSize.width, canvasSize.height)
val result = StationMapClusterer.cluster(markers, viewport, groupingEnabled) val result = StationMapClusterer.cluster(markers, viewport, groupingEnabled)
val selectedOutside = selectedTargetOutsideMarkers?.takeIf { marker ->
within(
local,
viewport.screenXWrapped(marker.longitudeDeg()).toFloat(),
viewport.screenY(marker.latitudeDeg()).toFloat(),
MARKER_HIT_RADIUS_PX,
)
}
val cluster = result.clusters().firstOrNull { candidate -> val cluster = result.clusters().firstOrNull { candidate ->
within( within(
local, local,
viewport.screenX(candidate.centerLon).toFloat(), viewport.screenXWrapped(candidate.centerLon).toFloat(),
viewport.screenY(candidate.centerLat).toFloat(), viewport.screenY(candidate.centerLat).toFloat(),
clusterRadiusPx(candidate.size()), clusterRadiusPx(candidate.size()),
) )
@@ -223,12 +246,14 @@ fun ComposeStationMap(
val individual = result.individual().firstOrNull { marker -> val individual = result.individual().firstOrNull { marker ->
within( within(
local, local,
viewport.screenX(marker.longitudeDeg()).toFloat(), viewport.screenXWrapped(marker.longitudeDeg()).toFloat(),
viewport.screenY(marker.latitudeDeg()).toFloat(), viewport.screenY(marker.latitudeDeg()).toFloat(),
MARKER_HIT_RADIUS_PX, MARKER_HIT_RADIUS_PX,
) )
} }
val targets = cluster?.getMarkers() ?: individual?.let(::listOf) val targets = selectedOutside?.let(::listOf)
?: cluster?.getMarkers()
?: individual?.let(::listOf)
val window = canvasCoordinates?.localToWindow(local) val window = canvasCoordinates?.localToWindow(local)
if (!targets.isNullOrEmpty() && window != null) { if (!targets.isNullOrEmpty() && window != null) {
onMarkerContextRequested?.invoke( onMarkerContextRequested?.invoke(
@@ -281,15 +306,28 @@ fun ComposeStationMap(
} }
} }
} }
.pointerInput(markers, groupingEnabled, onMarkerClicked) { .pointerInput(markers, selectedTargetOutsideMarkers, groupingEnabled, onMarkerClicked) {
detectTapGestures { offset -> detectTapGestures { offset ->
val viewport = mapState.viewportFor(size.width.toFloat(), size.height.toFloat()) val viewport = mapState.viewportFor(size.width.toFloat(), size.height.toFloat())
val result = StationMapClusterer.cluster(markers, viewport, groupingEnabled) val result = StationMapClusterer.cluster(markers, viewport, groupingEnabled)
val selectedOutside = selectedTargetOutsideMarkers?.takeIf { marker ->
within(
offset,
viewport.screenXWrapped(marker.longitudeDeg()).toFloat(),
viewport.screenY(marker.latitudeDeg()).toFloat(),
MARKER_HIT_RADIUS_PX,
)
}
if (selectedOutside != null) {
onMarkerClicked?.invoke(selectedOutside)
return@detectTapGestures
}
val hitCluster = result.clusters().firstOrNull { cluster -> val hitCluster = result.clusters().firstOrNull { cluster ->
within( within(
offset, offset,
viewport.screenX(cluster.centerLon).toFloat(), viewport.screenXWrapped(cluster.centerLon).toFloat(),
viewport.screenY(cluster.centerLat).toFloat(), viewport.screenY(cluster.centerLat).toFloat(),
clusterRadiusPx(cluster.size()), clusterRadiusPx(cluster.size()),
) )
@@ -312,14 +350,12 @@ fun ComposeStationMap(
val hit = result.individual().firstOrNull { marker -> val hit = result.individual().firstOrNull { marker ->
within( within(
offset, offset,
viewport.screenX(marker.longitudeDeg()).toFloat(), viewport.screenXWrapped(marker.longitudeDeg()).toFloat(),
viewport.screenY(marker.latitudeDeg()).toFloat(), viewport.screenY(marker.latitudeDeg()).toFloat(),
MARKER_HIT_RADIUS_PX, MARKER_HIT_RADIUS_PX,
) )
} }
if (hit != null) { if (hit != null) onMarkerClicked?.invoke(hit)
onMarkerClicked?.invoke(hit)
}
} }
} }
) { ) {
@@ -335,11 +371,34 @@ fun ComposeStationMap(
drawRect(color = if (darkMode) MAP_BACKGROUND_DARK else MAP_BACKGROUND_LIGHT) drawRect(color = if (darkMode) MAP_BACKGROUND_DARK else MAP_BACKGROUND_LIGHT)
drawTiles(viewport, imageCache, darkMode) drawTiles(viewport, imageCache, darkMode)
if (home != null && spatialFilterOverlay != null) {
drawSpatialFilterOverlay(
viewport = viewport,
homeLatitudeDeg = home.first,
homeLongitudeDeg = home.second,
state = spatialFilterOverlay,
darkMode = darkMode,
)
}
drawMaidenheadGrid(viewport, textMeasurer, darkMode) drawMaidenheadGrid(viewport, textMeasurer, darkMode)
drawWorkedGrossFields(viewport, workedGrossFields) drawWorkedGrossFields(viewport, workedGrossFields)
drawBeamAndPath(viewport, home, antennaAzimuthDeg, antennaBeamWidthDeg, maxQrbKm, markers, selectedMarkerCallsign, darkMode) drawBeamAndPath(
viewport,
home,
antennaAzimuthDeg,
antennaBeamWidthDeg,
maxQrbKm,
selectedTarget,
darkMode,
)
drawStations(viewport, clusterResult, selectedMarkerCallsign, textMeasurer, darkMode) drawStations(viewport, clusterResult, selectedMarkerCallsign, textMeasurer, darkMode)
drawHover(viewport, hoverPosition, clusterResult, textMeasurer) selectedTargetOutsideMarkers?.let { target ->
val x = viewport.screenXWrapped(target.longitudeDeg()).toFloat()
val y = viewport.screenY(target.latitudeDeg()).toFloat()
drawStationDot(x, y, selected = true, worked = target.worked(), warning = target.warningToMyDirection())
drawStationLabel(x, y, target.markerLabel(), target.warningToMyDirection(), textMeasurer, darkMode)
}
drawHover(viewport, hoverPosition, clusterResult, selectedTargetOutsideMarkers, textMeasurer)
} }
} }
@@ -474,8 +533,8 @@ private fun DrawScope.drawMaidenheadGrid(
val verticals = sortedSetOf<Float>() val verticals = sortedSetOf<Float>()
val horizontals = sortedSetOf<Float>() val horizontals = sortedSetOf<Float>()
for (cell in cells) { for (cell in cells) {
verticals.add(viewport.screenX(cell.westLon()).toFloat()) verticals.add(viewport.screenXWrapped(cell.westLon()).toFloat())
verticals.add(viewport.screenX(cell.eastLon()).toFloat()) verticals.add(viewport.screenXWrapped(cell.eastLon()).toFloat())
horizontals.add(viewport.screenY(cell.northLat()).toFloat()) horizontals.add(viewport.screenY(cell.northLat()).toFloat())
horizontals.add(viewport.screenY(cell.southLat()).toFloat()) horizontals.add(viewport.screenY(cell.southLat()).toFloat())
} }
@@ -516,7 +575,7 @@ private fun DrawScope.drawMaidenheadGrid(
} }
/* Centred in the cell, the way the stylesheet's translate(-50%, -50%) was. */ /* Centred in the cell, the way the stylesheet's translate(-50%, -50%) was. */
val centerX = viewport.screenX((cell.westLon() + cell.eastLon()) / 2.0).toFloat() val centerX = viewport.screenXWrapped((cell.westLon() + cell.eastLon()) / 2.0).toFloat()
val centerY = viewport.screenY((cell.southLat() + cell.northLat()) / 2.0).toFloat() val centerY = viewport.screenY((cell.southLat() + cell.northLat()) / 2.0).toFloat()
val layout = textMeasurer.measure(cell.locatorLabel(), style = labelStyle) val layout = textMeasurer.measure(cell.locatorLabel(), style = labelStyle)
@@ -540,8 +599,7 @@ private fun DrawScope.drawBeamAndPath(
antennaAzimuthDeg: Double, antennaAzimuthDeg: Double,
antennaBeamWidthDeg: Double, antennaBeamWidthDeg: Double,
maxQrbKm: Double, maxQrbKm: Double,
markers: List<MapCallsignRawSnapshot>, selectedTarget: MapCallsignRawSnapshot?,
selectedMarkerCallsign: String?,
darkMode: Boolean, darkMode: Boolean,
) { ) {
if (home == null) { if (home == null) {
@@ -549,32 +607,40 @@ private fun DrawScope.drawBeamAndPath(
} }
val (homeLat, homeLon) = home val (homeLat, homeLon) = home
if (antennaBeamWidthDeg > 0.0 && maxQrbKm > 0.0) { if (isAntennaSectorDrawable(home, antennaAzimuthDeg, antennaBeamWidthDeg, maxQrbKm)) {
val polygon = Path() val polygon = Path()
buildBeamPolygon(homeLat, homeLon, antennaAzimuthDeg, antennaBeamWidthDeg, maxQrbKm) buildBeamPolygon(homeLat, homeLon, antennaAzimuthDeg, antennaBeamWidthDeg, maxQrbKm)
.forEachIndexed { index, point -> .forEachIndexed { index, point ->
val x = viewport.screenX(point.second).toFloat() val x = viewport.screenXWrapped(point.second).toFloat()
val y = viewport.screenY(point.first).toFloat() val y = viewport.screenY(point.first).toFloat()
if (index == 0) polygon.moveTo(x, y) else polygon.lineTo(x, y) if (index == 0) polygon.moveTo(x, y) else polygon.lineTo(x, y)
} }
polygon.close() polygon.close()
drawPath(path = polygon, color = BEAM_COLOR, alpha = BEAM_FILL_ALPHA, style = Fill) drawPath(path = polygon, color = ANTENNA_OVERLAY_COLOR, alpha = BEAM_FILL_ALPHA, style = Fill)
drawPath(path = polygon, color = BEAM_COLOR, style = Stroke(width = BEAM_STROKE_WIDTH_PX)) drawPath(path = polygon, color = ANTENNA_OVERLAY_COLOR, style = Stroke(width = BEAM_STROKE_WIDTH_PX))
} }
val selected = markers.firstOrNull { val selected = selectedTarget?.takeIf(MapCallsignRawSnapshot::hasUsablePosition)
it.callSignRaw() == selectedMarkerCallsign && it.hasUsablePosition()
}
if (selected != null) { if (selected != null) {
val start = Offset(viewport.screenXWrapped(homeLon).toFloat(), viewport.screenY(homeLat).toFloat())
val end = Offset(
viewport.screenXWrapped(selected.longitudeDeg()).toFloat(),
viewport.screenY(selected.latitudeDeg()).toFloat(),
)
drawLine(
color = if (darkMode) CONNECTION_HALO_DARK else CONNECTION_HALO_LIGHT,
alpha = CONNECTION_HALO_ALPHA,
start = start,
end = end,
strokeWidth = CONNECTION_HALO_WIDTH_PX,
pathEffect = PathEffect.dashPathEffect(CONNECTION_DASH_PX),
)
drawLine( drawLine(
color = if (darkMode) CONNECTION_COLOR_DARK else CONNECTION_COLOR_LIGHT, color = if (darkMode) CONNECTION_COLOR_DARK else CONNECTION_COLOR_LIGHT,
alpha = CONNECTION_ALPHA, alpha = CONNECTION_ALPHA,
start = Offset(viewport.screenX(homeLon).toFloat(), viewport.screenY(homeLat).toFloat()), start = start,
end = Offset( end = end,
viewport.screenX(selected.longitudeDeg()).toFloat(),
viewport.screenY(selected.latitudeDeg()).toFloat(),
),
strokeWidth = CONNECTION_STROKE_WIDTH_PX, strokeWidth = CONNECTION_STROKE_WIDTH_PX,
pathEffect = PathEffect.dashPathEffect(CONNECTION_DASH_PX), pathEffect = PathEffect.dashPathEffect(CONNECTION_DASH_PX),
) )
@@ -585,9 +651,9 @@ private fun DrawScope.drawBeamAndPath(
* home is, and with the beam switched off there was none. A small dot is kept here * home is, and with the beam switched off there was none. A small dot is kept here
* deliberately. * deliberately.
*/ */
val homeX = viewport.screenX(homeLon).toFloat() val homeX = viewport.screenXWrapped(homeLon).toFloat()
val homeY = viewport.screenY(homeLat).toFloat() val homeY = viewport.screenY(homeLat).toFloat()
drawCircle(color = BEAM_COLOR, radius = HOME_RADIUS_PX, center = Offset(homeX, homeY)) drawCircle(color = ANTENNA_OVERLAY_COLOR, radius = HOME_RADIUS_PX, center = Offset(homeX, homeY))
drawCircle(color = Color.White, radius = HOME_INNER_RADIUS_PX, center = Offset(homeX, homeY)) drawCircle(color = Color.White, radius = HOME_INNER_RADIUS_PX, center = Offset(homeX, homeY))
} }
@@ -602,7 +668,7 @@ private fun DrawScope.drawStations(
) { ) {
for (cluster in clusterResult.clusters()) { for (cluster in clusterResult.clusters()) {
drawClusterBubble( drawClusterBubble(
x = viewport.screenX(cluster.centerLon).toFloat(), x = viewport.screenXWrapped(cluster.centerLon).toFloat(),
y = viewport.screenY(cluster.centerLat).toFloat(), y = viewport.screenY(cluster.centerLat).toFloat(),
count = cluster.size(), count = cluster.size(),
containsWorked = cluster.getMarkers().any { it.worked() }, containsWorked = cluster.getMarkers().any { it.worked() },
@@ -611,7 +677,7 @@ private fun DrawScope.drawStations(
} }
for (marker in clusterResult.individual()) { for (marker in clusterResult.individual()) {
val x = viewport.screenX(marker.longitudeDeg()).toFloat() val x = viewport.screenXWrapped(marker.longitudeDeg()).toFloat()
val y = viewport.screenY(marker.latitudeDeg()).toFloat() val y = viewport.screenY(marker.latitudeDeg()).toFloat()
val selected = marker.callSignRaw() == selectedMarkerCallsign val selected = marker.callSignRaw() == selectedMarkerCallsign
@@ -729,14 +795,23 @@ private fun DrawScope.drawHover(
viewport: MapViewport, viewport: MapViewport,
hoverPosition: Offset?, hoverPosition: Offset?,
clusterResult: StationMapClusterer.Result, clusterResult: StationMapClusterer.Result,
selectedTargetOutsideMarkers: MapCallsignRawSnapshot?,
textMeasurer: TextMeasurer, textMeasurer: TextMeasurer,
) { ) {
val position = hoverPosition ?: return val position = hoverPosition ?: return
val selectedTargetUnderPointer = selectedTargetOutsideMarkers?.takeIf { marker ->
within(
position,
viewport.screenXWrapped(marker.longitudeDeg()).toFloat(),
viewport.screenY(marker.latitudeDeg()).toFloat(),
MARKER_HIT_RADIUS_PX,
)
}
val clusterUnderPointer = clusterResult.clusters().firstOrNull { cluster -> val clusterUnderPointer = clusterResult.clusters().firstOrNull { cluster ->
within( within(
position, position,
viewport.screenX(cluster.centerLon).toFloat(), viewport.screenXWrapped(cluster.centerLon).toFloat(),
viewport.screenY(cluster.centerLat).toFloat(), viewport.screenY(cluster.centerLat).toFloat(),
clusterRadiusPx(cluster.size()), clusterRadiusPx(cluster.size()),
) )
@@ -744,13 +819,14 @@ private fun DrawScope.drawHover(
val markerUnderPointer = clusterResult.individual().firstOrNull { marker -> val markerUnderPointer = clusterResult.individual().firstOrNull { marker ->
within( within(
position, position,
viewport.screenX(marker.longitudeDeg()).toFloat(), viewport.screenXWrapped(marker.longitudeDeg()).toFloat(),
viewport.screenY(marker.latitudeDeg()).toFloat(), viewport.screenY(marker.latitudeDeg()).toFloat(),
MARKER_HIT_RADIUS_PX, MARKER_HIT_RADIUS_PX,
) )
} }
val text = when { val text = when {
selectedTargetUnderPointer != null -> selectedTargetUnderPointer.tooltipText()
clusterUnderPointer != null -> MapMarkerClusterTooltip.build(clusterUnderPointer) clusterUnderPointer != null -> MapMarkerClusterTooltip.build(clusterUnderPointer)
markerUnderPointer != null -> markerUnderPointer.tooltipText() markerUnderPointer != null -> markerUnderPointer.tooltipText()
@@ -804,8 +880,8 @@ private fun DrawScope.drawWorkedGrossFields(
workedGrossFields: Set<String>, workedGrossFields: Set<String>,
) { ) {
visibleWorkedGrossFieldCells(viewport, workedGrossFields).forEach { cell -> visibleWorkedGrossFieldCells(viewport, workedGrossFields).forEach { cell ->
val left = viewport.screenX(cell.westLon()).toFloat() val left = viewport.screenXWrapped(cell.westLon()).toFloat()
val right = viewport.screenX(cell.eastLon()).toFloat() val right = viewport.screenXWrapped(cell.eastLon()).toFloat()
val top = viewport.screenY(cell.northLat()).toFloat() val top = viewport.screenY(cell.northLat()).toFloat()
val bottom = viewport.screenY(cell.southLat()).toFloat() val bottom = viewport.screenY(cell.southLat()).toFloat()
val topLeft = Offset(minOf(left, right), minOf(top, bottom)) val topLeft = Offset(minOf(left, right), minOf(top, bottom))
@@ -863,7 +939,7 @@ private fun clusterFontSizePx(count: Int): Float = when {
} }
/** Null rather than a guess when the operator has no usable locator configured. */ /** Null rather than a guess when the operator has no usable locator configured. */
private fun homePosition(ownLocator6: String): Pair<Double, Double>? { internal fun homePosition(ownLocator6: String): Pair<Double, Double>? {
if (ownLocator6.length < 4) { if (ownLocator6.length < 4) {
return null return null
} }
@@ -875,6 +951,15 @@ private fun homePosition(ownLocator6: String): Pair<Double, Double>? {
} }
} }
internal fun isAntennaSectorDrawable(
home: Pair<Double, Double>?,
antennaAzimuthDeg: Double,
antennaBeamWidthDeg: Double,
maxQrbKm: Double,
): Boolean = home != null && antennaAzimuthDeg.isFinite() &&
antennaBeamWidthDeg.isFinite() && antennaBeamWidthDeg > 0.0 &&
maxQrbKm.isFinite() && maxQrbKm > 0.0
fun calculateDestinationPoint( fun calculateDestinationPoint(
startLatDeg: Double, startLatDeg: Double,
startLonDeg: Double, startLonDeg: Double,
@@ -982,16 +1067,20 @@ private const val CLUSTER_RADIUS_SMALL_PX = 16f
private const val CLUSTER_RADIUS_MEDIUM_PX = 18f private const val CLUSTER_RADIUS_MEDIUM_PX = 18f
private const val CLUSTER_RADIUS_LARGE_PX = 21f private const val CLUSTER_RADIUS_LARGE_PX = 21f
private val BEAM_COLOR = Color(0xFFFF4D4D) internal val ANTENNA_OVERLAY_COLOR = Color(0xFFFF4D4D)
private const val BEAM_FILL_ALPHA = 0.12f private const val BEAM_FILL_ALPHA = 0.12f
private const val BEAM_STROKE_WIDTH_PX = 2f private const val BEAM_STROKE_WIDTH_PX = 2f
private const val HOME_RADIUS_PX = 6f private const val HOME_RADIUS_PX = 6f
private const val HOME_INNER_RADIUS_PX = 2f private const val HOME_INNER_RADIUS_PX = 2f
private val CONNECTION_COLOR_DARK = Color(0xFF2FD7FF) private val CONNECTION_COLOR_DARK = Color(0xFF52E7FF)
private val CONNECTION_COLOR_LIGHT = Color(0xFF00A4CF) private val CONNECTION_COLOR_LIGHT = Color(0xFF007A9E)
private const val CONNECTION_ALPHA = 0.85f private val CONNECTION_HALO_DARK = Color.White
private const val CONNECTION_STROKE_WIDTH_PX = 2f private val CONNECTION_HALO_LIGHT = Color.Black
private const val CONNECTION_ALPHA = 0.98f
private const val CONNECTION_HALO_ALPHA = 0.82f
private const val CONNECTION_STROKE_WIDTH_PX = 3f
private const val CONNECTION_HALO_WIDTH_PX = 5f
private val CONNECTION_DASH_PX = floatArrayOf(6f, 6f) private val CONNECTION_DASH_PX = floatArrayOf(6f, 6f)
private val TOOLTIP_BACKGROUND = Color.White.copy(alpha = 0.92f) private val TOOLTIP_BACKGROUND = Color.White.copy(alpha = 0.92f)
@@ -0,0 +1,21 @@
package kst4contest.view.compose.map
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import kst4contest.model.ChatPreferences
/** Compose-observable map geometry read from the active profile. */
internal class MapDisplaySettingsState(private val prefs: ChatPreferences) {
var antennaBeamWidthDeg: Double by mutableStateOf(prefs.stn_antennaBeamWidthDeg)
private set
var maxQrbKm: Double by mutableStateOf(prefs.stn_maxQRBDefault)
private set
fun refreshFromPreferences() {
antennaBeamWidthDeg = prefs.stn_antennaBeamWidthDeg
maxQrbKm = prefs.stn_maxQRBDefault
}
}
@@ -0,0 +1,48 @@
package kst4contest.view.compose.map
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import kst4contest.view.compose.StationIdentity
/** A deliberate operator action that may move the station-map camera. */
internal sealed interface MapNavigationRequest {
data class FitSelectedPath(val identity: StationIdentity) : MapNavigationRequest
data class CenterOnQtf(val qtfDegrees: Double) : MapNavigationRequest
data object ResetToHome : MapNavigationRequest
}
/**
* The latest deliberate map-navigation request.
*
* Ordinary model refreshes never write this state. Keeping one monotonically increasing
* revision makes repeated selections observable and gives the most recent station or QTF
* action deterministic precedence when several actions happen before the map draws.
*/
internal class MapNavigationState {
var request: MapNavigationRequest? by mutableStateOf(null)
private set
var requestRevision: Long by mutableStateOf(0L)
private set
fun fitSelectedPath(identity: StationIdentity) {
publish(MapNavigationRequest.FitSelectedPath(identity))
}
fun centerOnQtf(qtfDegrees: Double) {
if (!qtfDegrees.isFinite() || qtfDegrees !in 0.0..360.0) return
publish(MapNavigationRequest.CenterOnQtf(qtfDegrees))
}
fun resetToHome() {
publish(MapNavigationRequest.ResetToHome)
}
private fun publish(next: MapNavigationRequest) {
request = next
requestRevision++
}
}
@@ -0,0 +1,79 @@
package kst4contest.view.compose.map
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.TooltipArea
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.size
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import kst4contest.view.compose.TooltipCard
import kst4contest.view.i18n.LocalStrings
@OptIn(ExperimentalFoundationApi::class, ExperimentalLayoutApi::class)
@Composable
internal fun MapOverlayLegend(
showAntenna: Boolean,
showSpatialFilters: Boolean,
darkMode: Boolean,
modifier: Modifier = Modifier,
) {
if (!showAntenna && !showSpatialFilters) return
val strings = LocalStrings.current
TooltipArea(
tooltip = { TooltipCard(strings.mapOverlayLegendTooltip) },
modifier = modifier,
) {
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(2.dp),
itemVerticalAlignment = Alignment.CenterVertically,
) {
if (showAntenna) {
LegendItem(
color = ANTENNA_OVERLAY_COLOR,
label = strings.mapOverlayAntenna,
tag = MAP_ANTENNA_LEGEND_TAG,
)
}
if (showSpatialFilters) {
LegendItem(
color = spatialFilterOverlayLineColor(darkMode),
label = strings.mapOverlayFilters,
tag = MAP_FILTER_LEGEND_TAG,
)
}
}
}
}
@Composable
private fun LegendItem(color: Color, label: String, tag: String) {
Row(
modifier = Modifier.testTag(tag),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
androidx.compose.foundation.layout.Box(
Modifier
.size(9.dp)
.clip(androidx.compose.foundation.shape.CircleShape)
.background(color),
)
Text(text = label, style = MaterialTheme.typography.bodySmall)
}
}
internal const val MAP_ANTENNA_LEGEND_TAG = "station-map-antenna-legend"
internal const val MAP_FILTER_LEGEND_TAG = "station-map-filter-legend"
@@ -0,0 +1,273 @@
package kst4contest.view.compose.map
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import kst4contest.locatorUtils.DirectionUtils
import kst4contest.view.map.MapViewport
import kst4contest.view.map.PathGeometryUtils
import kotlin.math.ceil
/** Immutable effective QTF/QRB filter values drawn by the station map. */
data class SpatialFilterOverlayState(
val qtfEnabled: Boolean,
val qtfDegrees: Double,
val beamWidthDeg: Double,
val minQrbEnabled: Boolean,
val minQrbKm: Double,
val maxQrbEnabled: Boolean,
val maxQrbKm: Double,
) {
val isActive: Boolean
get() = qtfEnabled || minQrbEnabled || maxQrbEnabled
val hasEmptyDistanceRange: Boolean
get() = minQrbEnabled && maxQrbEnabled && minQrbKm >= maxQrbKm
val hasRenderableValues: Boolean
get() = (!qtfEnabled || qtfDegrees.isFinite() && beamWidthDeg.isFinite()) &&
(!minQrbEnabled || minQrbKm.isFinite()) &&
(!maxQrbEnabled || maxQrbKm.isFinite())
/** True when the current values produce at least one visible fill or boundary. */
val hasDrawableGeometry: Boolean
get() {
if (!isActive || !hasRenderableValues) return false
if (minQrbEnabled && !maxQrbEnabled) return true
if (minQrbEnabled && minQrbKm > 0.0) return true
if (maxQrbEnabled && maxQrbKm > 0.0) return true
return qtfEnabled && !maxQrbEnabled
}
/** Mirrors the filter predicate: minimum exclusive, maximum inclusive. */
fun accepts(distanceKm: Double, bearingDeg: Double): Boolean {
if (!distanceKm.isFinite() || !bearingDeg.isFinite()) return false
if (minQrbEnabled && distanceKm <= minQrbKm) return false
if (maxQrbEnabled && distanceKm > maxQrbKm) return false
if (qtfEnabled && !DirectionUtils.isAngleInRange(bearingDeg, qtfDegrees, beamWidthDeg)) return false
return true
}
}
internal fun DrawScope.drawSpatialFilterOverlay(
viewport: MapViewport,
homeLatitudeDeg: Double,
homeLongitudeDeg: Double,
state: SpatialFilterOverlayState,
darkMode: Boolean,
) {
if (!state.hasDrawableGeometry ||
!homeLatitudeDeg.isFinite() || !homeLongitudeDeg.isFinite()
) return
val fillColor = if (darkMode) FILTER_FILL_DARK else FILTER_FILL_LIGHT
val lineColor = spatialFilterOverlayLineColor(darkMode)
val angular = state.qtfEnabled && state.beamWidthDeg.isFinite()
val validAngularArea = !angular || state.beamWidthDeg > 0.0 && state.beamWidthDeg < 360.0
val visibleRadius = visibleRadiusKm(viewport, homeLatitudeDeg, homeLongitudeDeg)
val outerRadius = if (state.maxQrbEnabled) state.maxQrbKm else visibleRadius
val innerRadius = if (state.minQrbEnabled) state.minQrbKm else 0.0
if (!state.hasEmptyDistanceRange && validAngularArea && outerRadius > innerRadius && outerRadius > 0.0) {
val fillPath = when {
angular -> annularSectorPath(
viewport,
homeLatitudeDeg,
homeLongitudeDeg,
state.qtfDegrees,
state.beamWidthDeg,
innerRadius.coerceAtLeast(0.0),
outerRadius,
)
state.minQrbEnabled && !state.maxQrbEnabled -> outsideCirclePath(
viewport,
homeLatitudeDeg,
homeLongitudeDeg,
innerRadius.coerceAtLeast(0.0),
)
else -> ringPath(
viewport,
homeLatitudeDeg,
homeLongitudeDeg,
innerRadius.coerceAtLeast(0.0),
outerRadius,
)
}
drawPath(fillPath, fillColor, style = Fill)
}
val stroke = Stroke(
width = FILTER_LINE_WIDTH_PX,
pathEffect = PathEffect.dashPathEffect(FILTER_DASH_PX),
)
if (state.minQrbEnabled && state.minQrbKm > 0.0) {
drawPath(circlePath(viewport, homeLatitudeDeg, homeLongitudeDeg, state.minQrbKm), lineColor, style = stroke)
}
if (state.maxQrbEnabled && state.maxQrbKm > 0.0) {
drawPath(circlePath(viewport, homeLatitudeDeg, homeLongitudeDeg, state.maxQrbKm), lineColor, style = stroke)
}
if (angular) {
val boundaryRadius = if (state.maxQrbEnabled) state.maxQrbKm else visibleRadius
val halfWidth = state.beamWidthDeg.coerceAtLeast(0.0) / 2.0
listOf(state.qtfDegrees - halfWidth, state.qtfDegrees + halfWidth).forEach { bearing ->
val endpoint = calculateDestinationPoint(
homeLatitudeDeg,
homeLongitudeDeg,
bearing,
boundaryRadius,
)
drawLine(
color = lineColor,
start = Offset(
viewport.screenXWrapped(homeLongitudeDeg).toFloat(),
viewport.screenY(homeLatitudeDeg).toFloat(),
),
end = Offset(
viewport.screenXWrapped(endpoint.second).toFloat(),
viewport.screenY(endpoint.first).toFloat(),
),
strokeWidth = FILTER_LINE_WIDTH_PX,
pathEffect = PathEffect.dashPathEffect(FILTER_DASH_PX),
)
}
}
}
private fun outsideCirclePath(
viewport: MapViewport,
homeLatitudeDeg: Double,
homeLongitudeDeg: Double,
radiusKm: Double,
): Path = Path().apply {
fillType = PathFillType.EvenOdd
addRect(Rect(0f, 0f, viewport.widthPx().toFloat(), viewport.heightPx().toFloat()))
addPath(circlePath(viewport, homeLatitudeDeg, homeLongitudeDeg, radiusKm))
}
private fun ringPath(
viewport: MapViewport,
homeLatitudeDeg: Double,
homeLongitudeDeg: Double,
innerRadiusKm: Double,
outerRadiusKm: Double,
): Path = Path().apply {
fillType = PathFillType.EvenOdd
addPath(circlePath(viewport, homeLatitudeDeg, homeLongitudeDeg, outerRadiusKm))
if (innerRadiusKm > 0.0) {
addPath(circlePath(viewport, homeLatitudeDeg, homeLongitudeDeg, innerRadiusKm))
}
}
private fun annularSectorPath(
viewport: MapViewport,
homeLatitudeDeg: Double,
homeLongitudeDeg: Double,
centerBearingDeg: Double,
beamWidthDeg: Double,
innerRadiusKm: Double,
outerRadiusKm: Double,
): Path {
val halfWidth = beamWidthDeg / 2.0
val outer = arcPoints(
homeLatitudeDeg,
homeLongitudeDeg,
centerBearingDeg - halfWidth,
beamWidthDeg,
outerRadiusKm,
)
val inner = if (innerRadiusKm > 0.0) {
arcPoints(
homeLatitudeDeg,
homeLongitudeDeg,
centerBearingDeg - halfWidth,
beamWidthDeg,
innerRadiusKm,
).asReversed()
} else {
listOf(homeLatitudeDeg to homeLongitudeDeg)
}
return pathThrough(viewport, outer + inner, close = true)
}
private fun circlePath(
viewport: MapViewport,
homeLatitudeDeg: Double,
homeLongitudeDeg: Double,
radiusKm: Double,
): Path = pathThrough(
viewport,
arcPoints(homeLatitudeDeg, homeLongitudeDeg, 0.0, 360.0, radiusKm),
close = true,
)
private fun arcPoints(
homeLatitudeDeg: Double,
homeLongitudeDeg: Double,
startBearingDeg: Double,
sweepDeg: Double,
radiusKm: Double,
): List<Pair<Double, Double>> {
val segmentCount = maxOf(24, ceil(kotlin.math.abs(sweepDeg) / 3.0).toInt())
return (0..segmentCount).map { segment ->
calculateDestinationPoint(
homeLatitudeDeg,
homeLongitudeDeg,
startBearingDeg + sweepDeg * segment / segmentCount,
radiusKm,
)
}
}
private fun pathThrough(
viewport: MapViewport,
points: List<Pair<Double, Double>>,
close: Boolean,
): Path = Path().apply {
points.forEachIndexed { index, point ->
val x = viewport.screenXWrapped(point.second).toFloat()
val y = viewport.screenY(point.first).toFloat()
if (index == 0) moveTo(x, y) else lineTo(x, y)
}
if (close && points.isNotEmpty()) close()
}
private fun visibleRadiusKm(
viewport: MapViewport,
homeLatitudeDeg: Double,
homeLongitudeDeg: Double,
): Double {
val corners = listOf(
viewport.northLat() to viewport.westLon(),
viewport.northLat() to viewport.eastLon(),
viewport.southLat() to viewport.westLon(),
viewport.southLat() to viewport.eastLon(),
)
val farthestCorner = corners.maxOfOrNull { (latitude, longitude) ->
PathGeometryUtils.calculateGreatCircleDistanceKm(
homeLatitudeDeg,
homeLongitudeDeg,
latitude,
longitude,
)
} ?: 0.0
return farthestCorner * VIEWPORT_RADIUS_MARGIN
}
private val FILTER_FILL_LIGHT = Color(0xFF5B4BC4).copy(alpha = 0.16f)
private val FILTER_FILL_DARK = Color(0xFF78A9FF).copy(alpha = 0.18f)
private val FILTER_LINE_LIGHT = Color(0xFF4937B8).copy(alpha = 0.88f)
private val FILTER_LINE_DARK = Color(0xFF8CB8FF).copy(alpha = 0.92f)
internal fun spatialFilterOverlayLineColor(darkMode: Boolean): Color =
if (darkMode) FILTER_LINE_DARK else FILTER_LINE_LIGHT
private const val FILTER_LINE_WIDTH_PX = 2f
private val FILTER_DASH_PX = floatArrayOf(7f, 5f)
private const val VIEWPORT_RADIUS_MARGIN = 1.12
@@ -11,6 +11,8 @@ import androidx.compose.runtime.*
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.alpha
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.testTag import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
@@ -26,6 +28,7 @@ import kst4contest.view.compose.StationContextOverlays
import kst4contest.view.compose.StationSelectionSource import kst4contest.view.compose.StationSelectionSource
import kst4contest.view.map.MapCallsignRawSnapshotBuilder import kst4contest.view.map.MapCallsignRawSnapshotBuilder
import kst4contest.view.map.PathAnalysisResult import kst4contest.view.map.PathAnalysisResult
import kst4contest.view.map.MapViewportNavigation
import kst4contest.view.map.StationMapStatusText import kst4contest.view.map.StationMapStatusText
import kst4contest.view.map.TileFetcher import kst4contest.view.map.TileFetcher
import java.util.EnumSet import java.util.EnumSet
@@ -108,9 +111,8 @@ object StationMapWindow {
* @param chatMembers the roster a marker click looks its station up in; a marker stands * @param chatMembers the roster a marker click looks its station up in; a marker stands
* for a raw callsign, and this is where its category variants come from * for a raw callsign, and this is where its category variants come from
* @param mapState where the map is looking * @param mapState where the map is looking
* @param pathAnalysis asked each time the selection changes; null means there is no * @param pathAnalysis asked for an explicit selection; null disables only the terrain
* running application, and then the map neither pans nor analyses, exactly as * analysis while viewport navigation remains available
* when no chat controller existed before the split
*/ */
@Composable @Composable
internal fun Content( internal fun Content(
@@ -151,8 +153,8 @@ object StationMapWindow {
val ownLocator6 by remember { androidx.compose.runtime.mutableStateOf(mainWindowState.prefs.stn_loginLocatorMainCat) } val ownLocator6 by remember { androidx.compose.runtime.mutableStateOf(mainWindowState.prefs.stn_loginLocatorMainCat) }
val antennaAzimuthDeg = mainWindowState.antennaQtf.value val antennaAzimuthDeg = mainWindowState.antennaQtf.value
val antennaBeamWidthDeg = mainWindowState.prefs.stn_antennaBeamWidthDeg val antennaBeamWidthDeg = mainWindowState.mapDisplaySettings.antennaBeamWidthDeg
val maxQrbKm = mainWindowState.prefs.stn_maxQRBDefault val maxQrbKm = mainWindowState.mapDisplaySettings.maxQrbKm
/* /*
* The markers are the stations the list shows, not all of them (#21): the * The markers are the stations the list shows, not all of them (#21): the
@@ -184,20 +186,37 @@ object StationMapWindow {
} }
} }
/*
* Selection is independent of the filtered marker set. A selected station
* remains a target even when an active filter removes its normal marker; it is
* drawn in a separate selection layer and never enters marker counts or clusters.
*/
val selectedTarget by remember(
selectedMember,
mainWindowState.stations.contentRevision,
mainWindowState.activeBands,
) {
derivedStateOf {
selectedMember?.let { selected ->
val variants = chatMembers().filter { it.callSignRaw == selected.callSignRaw }
.ifEmpty { listOf(selected) }
val bands = EnumSet.noneOf(Band::class.java).apply {
addAll(mainWindowState.activeBands)
}
MapCallsignRawSnapshotBuilder()
.buildSnapshots(variants, selected, bands)
.firstOrNull()
}
}
}
var pathAnalysisResult by remember { mutableStateOf<PathAnalysisResult?>(null) } var pathAnalysisResult by remember { mutableStateOf<PathAnalysisResult?>(null) }
var automaticAnalysisRevision by remember { mutableStateOf(0L) } var automaticAnalysisRevision by remember { mutableStateOf(0L) }
// Read through updated state so a caller passing a new lambda is never served a stale one. // Read through updated state so a caller passing a new lambda is never served a stale one.
val currentPathAnalysis by rememberUpdatedState(pathAnalysis) val currentPathAnalysis by rememberUpdatedState(pathAnalysis)
/* LaunchedEffect(mainWindowState.stationSelection.explicitSelectionRevision) {
* Whether the selected station has a marker. A filter can hide it (#21), and a
* station without a locator never has one; then there is nothing to analyse.
*/
val selectedHasMarker = selectedMember != null &&
markers.any { it.callSignRaw() == selectedMember.callSignRaw }
LaunchedEffect(selectedMember, selectedHasMarker) {
val automaticRequest = ++automaticAnalysisRevision val automaticRequest = ++automaticAnalysisRevision
val explicitRevisionAtStart = mainWindowState.mapReachability.requestRevision val explicitRevisionAtStart = mainWindowState.mapReachability.requestRevision
if (selectedMember == null) { if (selectedMember == null) {
@@ -205,34 +224,15 @@ object StationMapWindow {
return@LaunchedEffect return@LaunchedEffect
} }
val selectedSnapshot = markers.find { it.callSignRaw() == selectedMember.callSignRaw } val selectedSnapshot = selectedTarget
if (selectedSnapshot == null) { if (selectedSnapshot == null) {
// No marker: no request, and no "Loading" for a station the map does not show. // No valid locator: no request and no misleading loading state.
pathAnalysisResult = null pathAnalysisResult = null
return@LaunchedEffect return@LaunchedEffect
} }
val analysis = currentPathAnalysis() val analysis = currentPathAnalysis()
if (analysis != null) { if (analysis != null) {
if (selectedSnapshot.hasUsablePosition()) {
/*
* Pan to the station and leave the zoom alone. The Leaflet map
* did exactly this (focusCallsignRaw) and touched the zoom only
* when the station was hidden inside a bubble, and then only far
* enough to break the bubble open. An earlier Compose version
* recomputed a zoom from a bounding box on every selection and
* clamped it into 4..12, which threw an operator working at zoom
* 15 out to about 7 every time they picked the next station.
* AGENTS.md names zoom first among the things not to change as
* an incidental side effect.
*/
mapState.centerLon = selectedSnapshot.longitudeDeg()
mapState.centerLat = selectedSnapshot.latitudeDeg()
mapState.zoom = kst4contest.view.map.StationMapClusterer
.zoomToRevealStations(mapState.zoom.toDouble(), groupingEnabled)
.toFloat()
}
pathAnalysisResult = PathAnalysisResult.loading( pathAnalysisResult = PathAnalysisResult.loading(
prefs.stn_loginLocatorMainCat, prefs.stn_loginLocatorMainCat,
selectedSnapshot.locator6(), selectedSnapshot.locator6(),
@@ -249,6 +249,72 @@ object StationMapWindow {
} }
} }
var mapCanvasSize by remember { mutableStateOf(Size.Zero) }
var consumedNavigationRevision by remember(mapState) { mutableStateOf(Long.MIN_VALUE) }
val navigationRevision = mainWindowState.mapNavigation.requestRevision
val navigationRequest = mainWindowState.mapNavigation.request
val navigationPaddingPx = with(LocalDensity.current) { 40.dp.toPx().toDouble() }
LaunchedEffect(
navigationRevision,
navigationRequest,
mapCanvasSize,
selectedTarget,
ownLocator6,
) {
if (navigationRevision == consumedNavigationRevision ||
mapCanvasSize.width <= 0f || mapCanvasSize.height <= 0f
) {
return@LaunchedEffect
}
val home = runCatching { kst4contest.locatorUtils.Location(ownLocator6) }.getOrNull()
val current = mapState.viewportFor(mapCanvasSize.width, mapCanvasSize.height)
val next = when (val request = navigationRequest) {
is MapNavigationRequest.FitSelectedPath -> {
val target = selectedTarget
if (home == null || target == null || !target.hasUsablePosition() ||
request.identity != StationIdentity.of(selectedMember)
) {
null
} else {
MapViewportNavigation.fitPath(
current,
home.latitude.toDegrees(),
home.longitude.toDegrees(),
target.latitudeDeg(),
target.longitudeDeg(),
navigationPaddingPx,
)
}
}
is MapNavigationRequest.CenterOnQtf -> {
if (home == null) null else MapViewportNavigation.centreOnBearing(
current,
home.latitude.toDegrees(),
home.longitude.toDegrees(),
request.qtfDegrees,
QTF_FORWARD_CENTRE_FRACTION,
)
}
MapNavigationRequest.ResetToHome -> {
if (home == null) null else MapViewportNavigation.centreOnHome(
current,
home.latitude.toDegrees(),
home.longitude.toDegrees(),
)
}
null -> null
}
consumedNavigationRevision = navigationRevision
if (next != null) {
mapState.applyFrom(next)
}
}
val explicitReachabilityResult = mainWindowState.mapReachability.result val explicitReachabilityResult = mainWindowState.mapReachability.result
LaunchedEffect(mainWindowState.mapReachability.requestRevision, explicitReachabilityResult) { LaunchedEffect(mainWindowState.mapReachability.requestRevision, explicitReachabilityResult) {
if (explicitReachabilityResult != null) { if (explicitReachabilityResult != null) {
@@ -264,6 +330,24 @@ object StationMapWindow {
} else { } else {
emptySet() emptySet()
} }
val spatialFilterOverlay = SpatialFilterOverlayState(
qtfEnabled = mainWindowState.stationFilter.qtfEnabled,
qtfDegrees = mainWindowState.stationFilter.qtfDegrees,
beamWidthDeg = antennaBeamWidthDeg,
minQrbEnabled = mainWindowState.stationFilter.minQrbEnabled,
minQrbKm = mainWindowState.stationFilter.minQrbKm,
maxQrbEnabled = mainWindowState.stationFilter.maxQrbEnabled,
maxQrbKm = mainWindowState.stationFilter.maxQrbKm,
)
val mapHome = remember(ownLocator6) { homePosition(ownLocator6) }
val showAntennaOverlay = isAntennaSectorDrawable(
mapHome,
antennaAzimuthDeg ?: 0.0,
antennaBeamWidthDeg,
maxQrbKm,
)
val showSpatialFilterOverlay = mapHome != null && spatialFilterOverlay.hasDrawableGeometry
val isDarkTheme = isDarkThemeState.value
androidx.compose.material3.Surface( androidx.compose.material3.Surface(
color = androidx.compose.material3.MaterialTheme.colorScheme.background, color = androidx.compose.material3.MaterialTheme.colorScheme.background,
@@ -288,7 +372,7 @@ object StationMapWindow {
markers.size, markers.size,
mainWindowState.stationFilter.activeFilters.isNotEmpty() || mainWindowState.stationFilter.activeFilters.isNotEmpty() ||
mainWindowState.stationFilter.searchText.isNotBlank(), mainWindowState.stationFilter.searchText.isNotBlank(),
markers.firstOrNull { it.callSignRaw() == selectedMember?.callSignRaw }, selectedTarget,
) )
/* /*
@@ -308,6 +392,12 @@ object StationMapWindow {
) )
} }
MapOverlayLegend(
showAntenna = showAntennaOverlay,
showSpatialFilters = showSpatialFilterOverlay,
darkMode = isDarkTheme,
)
if (selectedMember != null) { if (selectedMember != null) {
kst4contest.view.compose.Form.button(strings.mapTriggerClusterSpot) { kst4contest.view.compose.Form.button(strings.mapTriggerClusterSpot) {
ApplicationRuntimeLauncher.getCurrent()?.chatController ApplicationRuntimeLauncher.getCurrent()?.chatController
@@ -317,12 +407,6 @@ object StationMapWindow {
kst4contest.view.compose.Form.button(strings.mapResetView) { kst4contest.view.compose.Form.button(strings.mapResetView) {
mainWindowState.selectStation(null, StationSelectionSource.RESET_VIEW) mainWindowState.selectStation(null, StationSelectionSource.RESET_VIEW)
val home = runCatching {
kst4contest.locatorUtils.Location(ownLocator6)
}.getOrNull()
mapState.centerLon = home?.longitude?.toDegrees() ?: 10.0
mapState.centerLat = home?.latitude?.toDegrees() ?: 51.0
/* The zoom is deliberately left alone; see AGENTS.md, UI behaviour. */
} }
kst4contest.view.compose.Form.button(strings.filterReset) { kst4contest.view.compose.Form.button(strings.filterReset) {
@@ -388,7 +472,6 @@ object StationMapWindow {
val leftPane: @Composable () -> Unit = { val leftPane: @Composable () -> Unit = {
Column(Modifier.fillMaxHeight()) { Column(Modifier.fillMaxHeight()) {
val isDarkTheme = isDarkThemeState.value
androidx.compose.foundation.layout.Box(Modifier.weight(1f).fillMaxWidth()) { androidx.compose.foundation.layout.Box(Modifier.weight(1f).fillMaxWidth()) {
ComposeStationMap( ComposeStationMap(
markers = markers, markers = markers,
@@ -400,8 +483,11 @@ object StationMapWindow {
antennaAzimuthDeg = antennaAzimuthDeg ?: 0.0, antennaAzimuthDeg = antennaAzimuthDeg ?: 0.0,
antennaBeamWidthDeg = antennaBeamWidthDeg, antennaBeamWidthDeg = antennaBeamWidthDeg,
maxQrbKm = maxQrbKm, maxQrbKm = maxQrbKm,
selectedTarget = selectedTarget,
spatialFilterOverlay = spatialFilterOverlay,
darkMode = isDarkTheme, darkMode = isDarkTheme,
workedGrossFields = workedGrossFields, workedGrossFields = workedGrossFields,
onCanvasSizeChanged = { mapCanvasSize = it },
onMarkerClicked = { snapshot -> onMarkerClicked = { snapshot ->
val variants = chatMembers() val variants = chatMembers()
.filter { it.callSignRaw == snapshot.callSignRaw() } .filter { it.callSignRaw == snapshot.callSignRaw() }
@@ -501,6 +587,7 @@ object StationMapWindow {
internal const val MAP_CANVAS_TAG = "station-map-canvas" internal const val MAP_CANVAS_TAG = "station-map-canvas"
internal const val GROUPING_TAG = "station-map-grouping" internal const val GROUPING_TAG = "station-map-grouping"
internal const val ALWAYS_ON_TOP_TAG = "station-map-always-on-top" internal const val ALWAYS_ON_TOP_TAG = "station-map-always-on-top"
private const val QTF_FORWARD_CENTRE_FRACTION = 0.25
@JvmStatic @JvmStatic
fun applyDarkMode(darkMode: Boolean) { fun applyDarkMode(darkMode: Boolean) {
@@ -4,9 +4,11 @@ import kst4contest.view.i18n.LocalStrings
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import kst4contest.view.compose.Form import kst4contest.view.compose.Form
import kst4contest.view.compose.observeAsState
/** /**
* The beacon tab: one CQ template per chat category and the interval they share. * The beacon tab: one CQ template per chat category and the interval they share.
@@ -18,12 +20,14 @@ import kst4contest.view.compose.Form
@Composable @Composable
fun BeaconTab(state: BeaconTabState, onRefused: (String) -> Unit) { fun BeaconTab(state: BeaconTabState, onRefused: (String) -> Unit) {
val strings = LocalStrings.current val strings = LocalStrings.current
val mainEnabled by state.mainBeaconEnabled.observeAsState()
val secondEnabled by state.secondBeaconEnabled.observeAsState()
Column( Column(
verticalArrangement = Arrangement.spacedBy(4.dp), verticalArrangement = Arrangement.spacedBy(4.dp),
) { ) {
Form.section(strings.beaconSectionFor(state.mainCategoryName)) { Form.section(strings.beaconSectionFor(state.mainCategoryName)) {
Form.check(strings.beaconEnabled, state.bcn_beaconsEnabledMainCat) { Form.check(strings.beaconEnabled, mainEnabled == true) {
state.bcn_beaconsEnabledMainCat = it state.bcn_beaconsEnabledMainCat = it
} }
Form.committed( Form.committed(
@@ -36,7 +40,7 @@ fun BeaconTab(state: BeaconTabState, onRefused: (String) -> Unit) {
} }
Form.section(strings.beaconSectionFor(state.secondCategoryName)) { Form.section(strings.beaconSectionFor(state.secondCategoryName)) {
Form.check(strings.beaconEnabled, state.bcn_beaconsEnabledSecondCat) { Form.check(strings.beaconEnabled, secondEnabled == true) {
state.bcn_beaconsEnabledSecondCat = it state.bcn_beaconsEnabledSecondCat = it
} }
Form.committed( Form.committed(
@@ -12,8 +12,9 @@ import kst4contest.view.compose.setting
* The two commit methods are the ports of `applyBeaconTextSetting` and * The two commit methods are the ports of `applyBeaconTextSetting` and
* `applySharedBeaconInterval`. Both returned nothing and opened an alert; here they * `applySharedBeaconInterval`. Both returned nothing and opened an alert; here they
* return the refusal text instead, so the tab decides how to show it and a test can * return the refusal text instead, so the tab decides how to show it and a test can
* read it. An accepted value is staged in the window's [SettingsDraft] and takes effect * read it. Accepted templates and intervals are staged in the window's [SettingsDraft]
* when the operator applies it; a refused one never gets there. * and take effect when the operator applies them. The two enable switches deliberately
* bypass the draft so the running timer sees their values immediately.
* *
* @param validateBeaconTemplate throws IllegalArgumentException with the reason, * @param validateBeaconTemplate throws IllegalArgumentException with the reason,
* the contract of `ChatController.validateBeaconTemplate`. * the contract of `ChatController.validateBeaconTemplate`.
@@ -27,22 +28,32 @@ class BeaconTabState(
private val restartBeaconTimer: () -> Unit, private val restartBeaconTimer: () -> Unit,
val mainCategoryName: String, val mainCategoryName: String,
val secondCategoryName: String, val secondCategoryName: String,
private val setMainBeaconEnabled: (Boolean) -> Unit = prefs::setBcn_beaconsEnabledMainCat,
private val setSecondBeaconEnabled: (Boolean) -> Unit = prefs::setBcn_beaconsEnabledSecondCat,
private val onBeaconTemplatesApplied: () -> Unit = {},
) { ) {
var bcn_beaconsEnabledMainCat: Boolean by draft.setting( val mainBeaconEnabled = prefs.bcnBeaconsEnabledMainCatProperty()
{ prefs.isBcn_beaconsEnabledMainCat() }, val secondBeaconEnabled = prefs.bcnBeaconsEnabledSecondCatProperty()
) { prefs.setBcn_beaconsEnabledMainCat(it) }
var bcn_beaconsEnabledSecondCat: Boolean by draft.setting( var bcn_beaconsEnabledMainCat: Boolean
{ prefs.isBcn_beaconsEnabledSecondCat() }, get() = prefs.isBcn_beaconsEnabledMainCat()
) { prefs.setBcn_beaconsEnabledSecondCat(it) } set(value) = setMainBeaconEnabled(value)
var bcn_beaconsEnabledSecondCat: Boolean
get() = prefs.isBcn_beaconsEnabledSecondCat()
set(value) = setSecondBeaconEnabled(value)
private var textMainCat: String by draft.setting( private var textMainCat: String by draft.setting(
{ prefs.getBcn_beaconTextMainCat() }, { prefs.getBcn_beaconTextMainCat() },
effectKey = BEACON_TEMPLATE_EFFECT,
effect = onBeaconTemplatesApplied,
) { prefs.setBcn_beaconTextMainCat(it) } ) { prefs.setBcn_beaconTextMainCat(it) }
private var textSecondCat: String by draft.setting( private var textSecondCat: String by draft.setting(
{ prefs.getBcn_beaconTextSecondCat() }, { prefs.getBcn_beaconTextSecondCat() },
effectKey = BEACON_TEMPLATE_EFFECT,
effect = onBeaconTemplatesApplied,
) { prefs.setBcn_beaconTextSecondCat(it) } ) { prefs.setBcn_beaconTextSecondCat(it) }
/* /*
@@ -69,7 +80,7 @@ class BeaconTabState(
* *
* The clamp is not cosmetic: a stored zero would otherwise be displayed as a * The clamp is not cosmetic: a stored zero would otherwise be displayed as a
* valid setting while `ChatController` sends at the minimum anyway * valid setting while `ChatController` sends at the minimum anyway
* (ChatController:3425). The JavaFX field applied the same `Math.max` when it * when scheduling the timer. The JavaFX field applied the same `Math.max` when it
* restored the value after a rejected entry. * restored the value after a rejected entry.
*/ */
val beaconIntervalMinutes: Int val beaconIntervalMinutes: Int
@@ -117,4 +128,8 @@ class BeaconTabState(
interval = minutes interval = minutes
return null return null
} }
private companion object {
const val BEACON_TEMPLATE_EFFECT = "beaconTemplates"
}
} }
@@ -18,10 +18,12 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.AwtWindow import androidx.compose.ui.window.AwtWindow
import java.awt.Dialog
import java.awt.FileDialog import java.awt.FileDialog
import java.awt.Frame import java.awt.Frame
import java.io.File import java.io.File
@@ -125,34 +127,51 @@ internal fun FilePathRow(
} }
} }
/** /** The modal owner that keeps the native file chooser accessible when opened from the wizard. */
* The AWT file dialog, opened from Compose. The JavaFX chooser started in the user's val LocalFileDialogOwner = staticCompositionLocalOf<Dialog?> { null }
* home directory and a cancelled choice kept the stored path — both are preserved.
*/ /** The AWT file dialog, opened from Compose. */
@Composable @Composable
private fun FileChooserDialog(title: String, onResult: (String?) -> Unit) { private fun FileChooserDialog(title: String, onResult: (String?) -> Unit) {
val owner = LocalFileDialogOwner.current
AwtWindow( AwtWindow(
create = { create = {
object : FileDialog(null as Frame?, title, LOAD) { if (owner == null) LogFileDialog(title, onResult) else LogFileDialog(owner, title, 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
)
}
}
}
}, },
dispose = FileDialog::dispose, 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. */ /** The label column width the shared form controls use, so the tabs line up. */
@Composable @Composable
private fun LabelledRow(label: String, field: @Composable () -> Unit) { private fun LabelledRow(label: String, field: @Composable () -> Unit) {
@@ -44,6 +44,10 @@ class StationTabState(
* TRX synch tab through [SECOND_ROTATOR], so it runs once per apply. * TRX synch tab through [SECOND_ROTATOR], so it runs once per apply.
*/ */
private val applySecondRotator: () -> Unit = {}, private val applySecondRotator: () -> Unit = {},
/** Recomputes status whose available-count depends on the second-chat switch. */
private val refreshBeaconStatus: () -> Unit = {},
/** Repaints applied beam geometry and dependent QTF results in the running UI. */
private val applyMapDisplaySettings: () -> Unit = {},
) { ) {
var loginChatCategoryMain: ChatCategory? var loginChatCategoryMain: ChatCategory?
@@ -55,7 +59,11 @@ class StationTabState(
get() = prefs.getLoginChatCategorySecond() get() = prefs.getLoginChatCategorySecond()
set(value) { prefs.setLoginChatCategorySecond(value) } set(value) { prefs.setLoginChatCategorySecond(value) }
var stn_antennaBeamWidthDeg: Double by draft.setting({ prefs.getStn_antennaBeamWidthDeg() }) { prefs.setStn_antennaBeamWidthDeg(it) } var stn_antennaBeamWidthDeg: Double by draft.setting(
{ prefs.getStn_antennaBeamWidthDeg() },
effectKey = MAP_DISPLAY_SETTINGS,
effect = applyMapDisplaySettings,
) { prefs.setStn_antennaBeamWidthDeg(it) }
var stn_bandActive10G: Boolean by draft.setting({ prefs.isStn_bandActive10G() }) { prefs.setStn_bandActive10G(it) } var stn_bandActive10G: Boolean by draft.setting({ prefs.isStn_bandActive10G() }) { prefs.setStn_bandActive10G(it) }
@@ -95,7 +103,11 @@ class StationTabState(
get() = prefs.getStn_loginPassword() get() = prefs.getStn_loginPassword()
set(value) { prefs.setStn_loginPassword(value) } set(value) { prefs.setStn_loginPassword(value) }
var stn_maxQRBDefault: Double by draft.setting({ prefs.getStn_maxQRBDefault() }) { prefs.setStn_maxQRBDefault(it) } var stn_maxQRBDefault: Double by draft.setting(
{ prefs.getStn_maxQRBDefault() },
effectKey = MAP_DISPLAY_SETTINGS,
effect = applyMapDisplaySettings,
) { prefs.setStn_maxQRBDefault(it) }
var stn_on4kstServersDns: String by draft.setting({ prefs.getStn_on4kstServersDns() }) { prefs.setStn_on4kstServersDns(it) } var stn_on4kstServersDns: String by draft.setting({ prefs.getStn_on4kstServersDns() }) { prefs.setStn_on4kstServersDns(it) }
@@ -234,7 +246,10 @@ class StationTabState(
* pickers it governs. It decides what the Connect button does, so it belongs with * pickers it governs. It decides what the Connect button does, so it belongs with
* the login settings and not with the display options. * the login settings and not with the display options.
*/ */
var loginToSecondChatEnabled: Boolean by draft.setting({ prefs.isLoginToSecondChatEnabled() }) { prefs.setLoginToSecondChatEnabled(it) } var loginToSecondChatEnabled: Boolean by draft.setting(
{ prefs.isLoginToSecondChatEnabled() },
effect = { refreshBeaconStatus() },
) { prefs.setLoginToSecondChatEnabled(it) }
/** /**
* Whether the login fields may be edited. The JavaFX window disabled callsign, * Whether the login fields may be edited. The JavaFX window disabled callsign,
@@ -289,6 +304,9 @@ class StationTabState(
/** The effect key of everything that restarts rotator 2; shared with the TRX synch tab. */ /** The effect key of everything that restarts rotator 2; shared with the TRX synch tab. */
const val SECOND_ROTATOR: String = "secondRotator" const val SECOND_ROTATOR: String = "secondRotator"
/** Shared effect for the two settings that define the map's antenna sector. */
const val MAP_DISPLAY_SETTINGS: String = "mapDisplaySettings"
/** /**
* Whether two PSTRotator ports collide: the same port, or one apart because * Whether two PSTRotator ports collide: the same port, or one apart because
* PSTRotator answers on port + 1, which would be the other client's local port. * PSTRotator answers on port + 1, which would be the other client's local port.
@@ -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);
}
}
}
@@ -0,0 +1,60 @@
package kst4contest.view
import kst4contest.controller.ChatController
import kst4contest.model.ChatMessage
import kst4contest.view.compose.DataTableState
import kst4contest.view.compose.RowKeys
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.mockito.Mockito.mock
import org.mockito.Mockito.`when`
class ComposeMessageTableRefreshTest {
@Test
fun `refresh keeps public table on the filtered controller view`() {
val controller = mock(ChatController::class.java)
val privateToMe = message("private to me")
val publicInitial = message("public initial")
val betweenOthers = message("between others")
val directed = table()
val publicMessages = table()
val qsoOfTheOther = table()
`when`(controller.toMeMessages()).thenReturn(listOf(privateToMe))
`when`(controller.toAllMessages()).thenReturn(listOf(publicInitial))
`when`(controller.toOtherMessages()).thenReturn(listOf(betweenOthers))
Kst4ContestApplication.refreshComposeMessageTables(
controller,
directed,
publicMessages,
qsoOfTheOther,
)
assertEquals(listOf(privateToMe), directed.rows)
assertEquals(listOf(publicInitial), publicMessages.rows)
assertEquals(listOf(betweenOthers), qsoOfTheOther.rows)
val publicLater = message("public later")
`when`(controller.toAllMessages()).thenReturn(listOf(publicLater, publicInitial))
Kst4ContestApplication.refreshComposeMessageTables(
controller,
directed,
publicMessages,
qsoOfTheOther,
)
assertEquals(listOf(publicLater, publicInitial), publicMessages.rows)
}
private fun table() = DataTableState(
columns = emptyList(),
rowKey = RowKeys.byReference<ChatMessage>(),
)
private fun message(text: String) = ChatMessage().apply {
messageText = text
}
}
@@ -0,0 +1,58 @@
package kst4contest.view.compose
import androidx.compose.ui.graphics.Color
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
class BeaconStatusColorsTest {
private val neutral = Color(0xFF123456)
@Test
fun `active and activity colours are the approved traffic colours`() {
assertEquals(
ThreadButtonColors(Color(0xFF238636), Color(0xFF56D364), Color.White),
beaconThreadButtonColors(ThreadStatusVisualStyle.BEACON_ACTIVE, false, false, neutral),
)
assertEquals(
ThreadButtonColors(Color(0xFFFFB300), Color(0xFFFFE082), Color(0xFF1B1B1B)),
beaconThreadButtonColors(ThreadStatusVisualStyle.BEACON_ACTIVE, true, false, neutral),
)
}
@Test
fun `off uses neutral background and theme specific red text`() {
assertEquals(Color(0xFFD50000),
beaconThreadButtonColors(ThreadStatusVisualStyle.BEACON_OFF, false, false, neutral).text)
assertEquals(Color(0xFFFF6B6B),
beaconThreadButtonColors(ThreadStatusVisualStyle.BEACON_OFF, false, true, neutral).text)
assertEquals(neutral,
beaconThreadButtonColors(ThreadStatusVisualStyle.BEACON_OFF, false, true, neutral).background)
}
@Test
fun `failed stays red even when a highlight is requested`() {
val colors = beaconThreadButtonColors(
ThreadStatusVisualStyle.BEACON_FAILED,
true,
false,
neutral,
)
assertEquals(ThreadButtonColors(Color(0xFFD50000), Color(0xFFFF6B6B), Color.White), colors)
}
@Test
fun `failed suppresses the flash while active status allows it`() {
val button = ThreadStatusButton("MyBeacon")
button.report("MyBeacon: on", "active", ThreadStatusVisualStyle.BEACON_ACTIVE)
assertTrue(button.highlighted)
button.report("MyBeacon: FAILED", "failed", ThreadStatusVisualStyle.BEACON_FAILED)
assertFalse(button.highlighted)
assertEquals(
ThreadButtonColors(Color(0xFFD50000), Color(0xFFFF6B6B), Color.White),
beaconThreadButtonColors(ThreadStatusVisualStyle.BEACON_FAILED, true, false, neutral),
)
}
}
@@ -0,0 +1,59 @@
package kst4contest.view.compose
import kst4contest.model.BeaconStatusSnapshot
import kst4contest.model.BeaconStatusSnapshot.AggregateState
import kst4contest.model.BeaconStatusSnapshot.CategoryStatus
import kst4contest.model.BeaconStatusSnapshot.InactiveReason
import kst4contest.view.i18n.LanguageStore
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.util.Locale
class BeaconStatusPresentationTest {
@Test
fun `partial status keeps the inactive category reason in English`() {
val presentation = BeaconStatusPresentation.from(snapshot(AggregateState.PARTIAL))
assertEquals("1/2", presentation.label)
assertTrue(presentation.tooltip.contains("Main category: active"))
assertTrue(presentation.tooltip.contains("primary QRG missing or invalid"))
}
@Test
fun `the same category reasons are available in German`() {
val language = LanguageStore({ "de" }, {}, Locale.UK)
try {
val presentation = BeaconStatusPresentation.from(
snapshot(AggregateState.PARTIAL),
language.strings,
)
assertTrue(presentation.tooltip.contains("Hauptkategorie: aktiv"))
assertTrue(presentation.tooltip.contains("Haupt-QRG fehlt oder ist ungültig"))
assertFalse(presentation.tooltip.contains("144."))
} finally {
language.use("en")
}
}
@Test
fun `failed style overrides an active category`() {
val main = CategoryStatus(true, true, true, InactiveReason.USER_DISABLED)
val second = CategoryStatus(false, false, false, InactiveReason.NOT_ACTIVATED_THIS_SESSION)
val presentation = BeaconStatusPresentation.from(
BeaconStatusSnapshot(AggregateState.FAILED, main, second),
)
assertEquals("FAILED", presentation.label)
assertEquals(ThreadStatusVisualStyle.BEACON_FAILED, presentation.style)
assertTrue(presentation.tooltip.contains("send failed"))
}
private fun snapshot(state: AggregateState): BeaconStatusSnapshot = BeaconStatusSnapshot(
state,
CategoryStatus(true, true, false, InactiveReason.USER_DISABLED),
CategoryStatus(true, false, false, InactiveReason.PRIMARY_QRG_UNAVAILABLE),
)
}
@@ -5,6 +5,7 @@ import androidx.compose.ui.text.input.TextFieldValue
import kst4contest.model.ChatCategory import kst4contest.model.ChatCategory
import kst4contest.model.ChatMember import kst4contest.model.ChatMember
import kst4contest.model.ChatMessage import kst4contest.model.ChatMessage
import kst4contest.controller.RadioSlot
import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertSame import org.junit.jupiter.api.Assertions.assertSame
@@ -233,6 +234,20 @@ class ChatInputStateTest {
assertEquals("432.200 ", state.value.text) assertEquals("432.200 ", state.value.text)
} }
@Test
fun `manual QRG commits keep their radio source explicit`() {
val actions = FakeActions()
val state = ChatInputState(actions)
state.commitOwnQrg(mainCategory = true, "144.300")
state.commitOwnQrg(mainCategory = false, "1296.100")
assertEquals(
listOf(RadioSlot.FIRST to "144.300", RadioSlot.SECOND to "1296.100"),
actions.manualQrgs,
)
}
// ---- the snippets ------------------------------------------------------ // ---- the snippets ------------------------------------------------------
/** /**
@@ -407,6 +422,7 @@ class ChatInputStateTest {
val resolvedTemplates = mutableListOf<String>() val resolvedTemplates = mutableListOf<String>()
val recordedCqs = mutableListOf<String>() val recordedCqs = mutableListOf<String>()
val recomputeReasons = mutableListOf<String>() val recomputeReasons = mutableListOf<String>()
val manualQrgs = mutableListOf<Pair<RadioSlot, String>>()
override fun panelSelection(): ChatMember? = panelSelection override fun panelSelection(): ChatMember? = panelSelection
override fun tableSelection(): ChatMember? = tableSelection override fun tableSelection(): ChatMember? = tableSelection
@@ -431,5 +447,6 @@ class ChatInputStateTest {
override fun queue(message: ChatMessage) { queued += message } override fun queue(message: ChatMessage) { queued += message }
override fun ownQrgMain(): String = ownQrgMain override fun ownQrgMain(): String = ownQrgMain
override fun ownQrgSecond(): String = ownQrgSecond override fun ownQrgSecond(): String = ownQrgSecond
override fun applyManualQrg(slot: RadioSlot, value: String) { manualQrgs += slot to value }
} }
} }
@@ -55,45 +55,47 @@ class CompactControlsVisualRenderingTest(@param:TempDir private val tempDir: Pat
} }
val filters = StationFilterState() val filters = StationFilterState()
val scene = ImageComposeScene(width = 1366, height = 380, density = Density(scale)) { return onEventThread {
Kst4ContestTheme(darkMode = darkMode, baseFontSizeSp = 12f) { val scene = ImageComposeScene(width = 1366, height = 380, density = Density(scale)) {
Surface( Kst4ContestTheme(darkMode = darkMode, baseFontSizeSp = 12f) {
modifier = Modifier.fillMaxSize(), Surface(
color = MaterialTheme.colorScheme.background, modifier = Modifier.fillMaxSize(),
) { color = MaterialTheme.colorScheme.background,
Column(Modifier.padding(4.dp)) { ) {
TimelineView( Column(Modifier.padding(4.dp)) {
state = TimelineState(), TimelineView(
onCandidateClicked = {}, state = TimelineState(),
modifier = Modifier.fillMaxWidth(), onCandidateClicked = {},
) modifier = Modifier.fillMaxWidth(),
Spacer(Modifier.height(8.dp)) )
StationFilterBar( Spacer(Modifier.height(8.dp))
filters = filters, StationFilterBar(
activeBands = EnumSet.of(Band.B_144, Band.B_432, Band.B_1296), filters = filters,
reachability = ReachabilityState( activeBands = EnumSet.of(Band.B_144, Band.B_432, Band.B_1296),
EnumSet.of(Band.B_144, Band.B_432, Band.B_1296), reachability = ReachabilityState(
), EnumSet.of(Band.B_144, Band.B_432, Band.B_1296),
onChanged = {}, ),
) onChanged = {},
Spacer(Modifier.height(12.dp)) )
ChatInputRow( Spacer(Modifier.height(12.dp))
state = chatInputState, ChatInputRow(
prefs = preferences, state = chatInputState,
ownQrgMain = ObservedValue(preferences.getMYQRGFirstCat()), prefs = preferences,
ownQrgSecond = ObservedValue(preferences.getMYQRGSecondCat()), ownQrgMain = ObservedValue(preferences.getMYQRGFirstCat()),
antennaQtf = ObservedValue(preferences.getActualQTF()), ownQrgSecond = ObservedValue(preferences.getMYQRGSecondCat()),
antennaQtf2 = ObservedValue(preferences.getActualQTF2()), antennaQtf = ObservedValue(preferences.getActualQTF()),
so2rEnabled = false, antennaQtf2 = ObservedValue(preferences.getActualQTF2()),
) so2rEnabled = false,
)
}
} }
} }
} }
} try {
return try { scene.render().encodeToData()!!.bytes
scene.render().encodeToData()!!.bytes } finally {
} finally { scene.close()
scene.close() }
} }
} }
@@ -28,6 +28,7 @@ class MainMenuModelTest {
override fun setQrgAsNameInChat() { calls += "setQrgAsNameInChat" } override fun setQrgAsNameInChat() { calls += "setQrgAsNameInChat" }
override fun toggleAwayState() { calls += "toggleAwayState" } override fun toggleAwayState() { calls += "toggleAwayState" }
override fun toggleSettingsWindow() { calls += "toggleSettingsWindow" } override fun toggleSettingsWindow() { calls += "toggleSettingsWindow" }
override fun openSetupWizard() { calls += "openSetupWizard" }
override fun toggleMonitorWindow() { calls += "toggleMonitorWindow" } override fun toggleMonitorWindow() { calls += "toggleMonitorWindow" }
override fun toggleStationMap() { calls += "toggleStationMap" } override fun toggleStationMap() { calls += "toggleStationMap" }
override fun useDarkDesign() { calls += "useDarkDesign" } override fun useDarkDesign() { calls += "useDarkDesign" }
@@ -181,4 +182,19 @@ class MainMenuModelTest {
"every item must reach an action; one of them did nothing", "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 setQrgAsNameInChat() { calls += "setQrgAsNameInChat" }
override fun toggleAwayState() { calls += "toggleAwayState" } override fun toggleAwayState() { calls += "toggleAwayState" }
override fun toggleSettingsWindow() { calls += "toggleSettingsWindow" } override fun toggleSettingsWindow() { calls += "toggleSettingsWindow" }
override fun openSetupWizard() { calls += "openSetupWizard" }
override fun toggleMonitorWindow() { calls += "toggleMonitorWindow" } override fun toggleMonitorWindow() { calls += "toggleMonitorWindow" }
override fun toggleStationMap() { calls += "toggleStationMap" } override fun toggleStationMap() { calls += "toggleStationMap" }
override fun useDarkDesign() { calls += "useDarkDesign" } override fun useDarkDesign() { calls += "useDarkDesign" }
@@ -116,6 +117,7 @@ class MainMenuRowScreenTest {
Triple("Options", "Set QRG as name in Chat (main category)", "setQrgAsNameInChat"), Triple("Options", "Set QRG as name in Chat (main category)", "setQrgAsNameInChat"),
Triple("Options", "Show me as AWAY FROM chat!", "toggleAwayState"), Triple("Options", "Show me as AWAY FROM chat!", "toggleAwayState"),
Triple("Options", "Show options", "toggleSettingsWindow"), Triple("Options", "Show options", "toggleSettingsWindow"),
Triple("Options", "Setup assistant...", "openSetupWizard"),
Triple("Windows", "Show cluster / stranger QSOs", "toggleMonitorWindow"), Triple("Windows", "Show cluster / stranger QSOs", "toggleMonitorWindow"),
Triple("Windows", "Show / hide station map", "toggleStationMap"), Triple("Windows", "Show / hide station map", "toggleStationMap"),
Triple("Windows", "Use dark mode design", "useDarkDesign"), Triple("Windows", "Use dark mode design", "useDarkDesign"),
@@ -0,0 +1,37 @@
package kst4contest.view.compose
import java.awt.EventQueue
import java.lang.reflect.InvocationTargetException
/*
* An ImageComposeScene must live on the AWT event thread, the thread the application renders
* on. Compose Multiplatform 1.8.2 sends the global snapshot notifications there
* (GlobalSnapshotManager), and doing so takes two locks in the opposite order from a render
* on any other thread:
*
* - the render holds the scene's FlushCoroutineDispatcher runLock while a task it runs
* (here LazyListState.scrollToItem) measures and wants the SnapshotStateObserver's
* observedScopeMapsLock;
* - the event thread holds observedScopeMapsLock in drainChanges while a derived state it
* re-reads wakes a snapshotFlow collector of that scene, whose dispatch wants runLock.
*
* Both waited forever in CI runs 40252077018, 40252089738 and 40299943329; the thread dump of
* the last one shows both stacks. On one thread the two monitors are simply re-entered, which
* is why the application never hangs this way.
*/
/**
* Runs [block] on the AWT event thread, waits for it and returns its result. Whatever
* [block] throws is rethrown here unwrapped, so a failed assertion still reads as one.
*/
internal fun <T> onEventThread(block: () -> T): T {
if (EventQueue.isDispatchThread()) return block()
var result: Result<T>? = null
try {
EventQueue.invokeAndWait { result = runCatching(block) }
} catch (wrapped: InvocationTargetException) {
throw wrapped.cause ?: wrapped
}
return result!!.getOrThrow()
}
@@ -84,37 +84,39 @@ class SelectedStationMessageUiVisualRenderingTest {
replaceRows(listOf(message(member("DL1ABC", 2), member("DL2XYZ", 2), "pse sked"))) replaceRows(listOf(message(member("DL1ABC", 2), member("DL2XYZ", 2), "pse sked")))
} }
val scene = ImageComposeScene(width = 1366, height = windowHeight, density = Density(scale)) { return onEventThread {
Kst4ContestTheme(darkMode = darkMode, baseFontSizeSp = 12f) { val scene = ImageComposeScene(width = 1366, height = windowHeight, density = Density(scale)) {
Surface( Kst4ContestTheme(darkMode = darkMode, baseFontSizeSp = 12f) {
modifier = Modifier.fillMaxSize(), Surface(
color = MaterialTheme.colorScheme.background, modifier = Modifier.fillMaxSize(),
) { color = MaterialTheme.colorScheme.background,
Row(Modifier.fillMaxSize().padding(6.dp)) { ) {
MessageTabs( Row(Modifier.fillMaxSize().padding(6.dp)) {
publicMessages = publicMessages, MessageTabs(
clusterMessages = clusterTable(), publicMessages = publicMessages,
qsoOfTheOther = qsoMessages, clusterMessages = clusterTable(),
modifier = Modifier.weight(1f), qsoOfTheOther = qsoMessages,
) modifier = Modifier.weight(1f),
SelectedStationPanel( )
state = selectedState, SelectedStationPanel(
messages = selectedMessages, state = selectedState,
activeBands = EnumSet.of(Band.B_144, Band.B_432, Band.B_1296), messages = selectedMessages,
openInBrowser = Consumer {}, activeBands = EnumSet.of(Band.B_144, Band.B_432, Band.B_1296),
onShowOnMap = {}, openInBrowser = Consumer {},
onShowPathInAirScout = {}, onShowOnMap = {},
modifier = Modifier.width(panelWidth).padding(start = 6.dp), onShowPathInAirScout = {},
) modifier = Modifier.width(panelWidth).padding(start = 6.dp),
)
}
} }
} }
} }
}
return try { try {
scene.render().encodeToData()!!.bytes scene.render().encodeToData()!!.bytes
} finally { } finally {
scene.close() scene.close()
}
} }
} }
@@ -35,7 +35,9 @@ class SettingsFieldCoverageTest {
"" ""
} }
val missing = expected.filterNot { composeSources.contains("$it(") } val missing = expected.filterNot {
composeSources.contains("$it(") || composeSources.contains("::$it")
}
assertTrue(missing.isEmpty(), assertTrue(missing.isEmpty(),
"settings not written by any Compose source (${missing.size} of ${expected.size}):\n" + "settings not written by any Compose source (${missing.size} of ${expected.size}):\n" +
@@ -70,12 +70,27 @@ class StationSelectionStateTest {
val state = StationSelectionState() val state = StationSelectionState()
state.select(station("DL1ABC", 2), StationSelectionSource.STATION_TABLE) state.select(station("DL1ABC", 2), StationSelectionSource.STATION_TABLE)
val revision = state.scrollRequestRevision val revision = state.scrollRequestRevision
val explicitRevision = state.explicitSelectionRevision
val refreshed = station("DL1ABC", 2) val refreshed = station("DL1ABC", 2)
state.reconcile(refreshed) state.reconcile(refreshed)
assertSame(refreshed, state.selected) assertSame(refreshed, state.selected)
assertEquals(revision, state.scrollRequestRevision) assertEquals(revision, state.scrollRequestRevision)
assertEquals(explicitRevision, state.explicitSelectionRevision)
}
@Test
fun `roster reconciliation does not publish explicit navigation`() {
val state = StationSelectionState()
val requests = mutableListOf<Pair<ChatMember?, StationSelectionSource>>()
state.explicitSelectionListener = { member, source -> requests += member to source }
state.select(station("DL1ABC", 2), StationSelectionSource.PUBLIC_MESSAGE)
state.reconcile(station("DL1ABC", 2))
assertEquals(1, requests.size)
assertEquals(StationSelectionSource.PUBLIC_MESSAGE, requests.single().second)
} }
@Test @Test
@@ -87,62 +87,64 @@ class StationWorkspaceVisualRenderingTest {
RowKeys.byReference<ChatMessage>(), RowKeys.byReference<ChatMessage>(),
) )
val scene = ImageComposeScene( return onEventThread {
width = 1366, val scene = ImageComposeScene(
height = scenario.height, width = 1366,
density = Density(scale), height = scenario.height,
) { density = Density(scale),
Kst4ContestTheme(darkMode = darkMode, baseFontSizeSp = 12f) { ) {
Surface( Kst4ContestTheme(darkMode = darkMode, baseFontSizeSp = 12f) {
modifier = Modifier.fillMaxSize(), Surface(
color = MaterialTheme.colorScheme.background, modifier = Modifier.fillMaxSize(),
) { color = MaterialTheme.colorScheme.background,
Box(Modifier.fillMaxSize()) {
Column(
Modifier
.width(scenario.width.dp)
.fillMaxHeight()
.align(Alignment.TopEnd)
.padding(4.dp),
) { ) {
StationFilterBar( Box(Modifier.fillMaxSize()) {
filters = StationFilterState(), Column(
activeBands = EnumSet.of(Band.B_144, Band.B_432), Modifier
reachability = ReachabilityState(EnumSet.of(Band.B_144, Band.B_432)), .width(scenario.width.dp)
onChanged = {}, .fillMaxHeight()
) .align(Alignment.TopEnd)
DataTableView( .padding(4.dp),
state = stations, ) {
modifier = Modifier.weight(0.45f), StationFilterBar(
emphasizeCell = { member, column -> filters = StationFilterState(),
column.id == "callsign" && newJoined.isRecent(member) activeBands = EnumSet.of(Band.B_144, Band.B_432),
}, reachability = ReachabilityState(EnumSet.of(Band.B_144, Band.B_432)),
) onChanged = {},
TopPriorityBar( )
state = priority, DataTableView(
newJoined = newJoined, state = stations,
onShowMore = {}, modifier = Modifier.weight(0.45f),
) emphasizeCell = { member, column ->
SelectedStationPanel( column.id == "callsign" && newJoined.isRecent(member)
state = selected, },
messages = selectedMessages, )
activeBands = EnumSet.of(Band.B_144, Band.B_432), TopPriorityBar(
contentSplitter = SplitterState(2, doubleArrayOf(0.48)) {}, state = priority,
openInBrowser = Consumer {}, newJoined = newJoined,
onShowOnMap = {}, onShowMore = {},
onShowPathInAirScout = {}, )
modifier = Modifier.weight(0.55f), SelectedStationPanel(
) state = selected,
} messages = selectedMessages,
activeBands = EnumSet.of(Band.B_144, Band.B_432),
contentSplitter = SplitterState(2, doubleArrayOf(0.48)) {},
openInBrowser = Consumer {},
onShowOnMap = {},
onShowPathInAirScout = {},
modifier = Modifier.weight(0.55f),
)
}
}
} }
} }
} }
}
return try { try {
scene.render().encodeToData()!!.bytes scene.render().encodeToData()!!.bytes
} finally { } finally {
scene.close() scene.close()
}
} }
} }
@@ -0,0 +1,48 @@
package kst4contest.view.compose
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertHasClickAction
import androidx.compose.ui.test.assertHasNoClickAction
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.runComposeUiTest
import kst4contest.model.ThreadStateMessage
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
@OptIn(ExperimentalTestApi::class)
class StatusBarScreenTest {
@Test
fun onlyAThreadWithARegisteredActionIsClickable() = runComposeUiTest {
val buttons = ThreadStatusButtons()
var beaconClicks = 0
buttons.registerAction("MyBeacon") { beaconClicks++ }
buttons.update("MyBeacon", status("off"))
buttons.update("Cluster", status("on"))
setContent {
Kst4ContestTheme(darkMode = false, baseFontSizeSp = 12f) {
StatusBar(
connectionState = null,
connectionDetail = null,
skedNotice = BlinkingNotice(),
bandUpgradeNotice = BlinkingNotice(),
threadButtons = buttons,
showConnectionBadge = false,
)
}
}
waitForIdle()
onNodeWithText("MyBeacon: off").assertHasClickAction().performClick()
waitForIdle()
assertEquals(1, beaconClicks)
onNodeWithText("Cluster: on").assertHasNoClickAction()
}
private fun status(description: String): ThreadStateMessage =
ThreadStateMessage("worker", true, description, false).apply {
runningInformationTextDescription = description
}
}
@@ -407,6 +407,52 @@ class StatusIndicatorStateTest {
assertEquals("Cluster: b", button.label) assertEquals("Cluster: b", button.label)
} }
@Test
fun `an action registered before the first report reaches the created button`() {
val buttons = ThreadStatusButtons()
var clicks = 0
buttons.registerAction("MyBeacon") { clicks++ }
buttons.update("MyBeacon", threadState(nick = "beacon", description = "off", info = "disabled"))
buttons.buttons.single().activate()
assertEquals(1, clicks)
}
@Test
fun `an action registered after a report reaches the existing button`() {
val buttons = ThreadStatusButtons()
var clicks = 0
buttons.update("MyBeacon", threadState(nick = "beacon", description = "off", info = "disabled"))
buttons.registerAction("MyBeacon") { clicks++ }
buttons.buttons.single().activate()
assertEquals(1, clicks)
}
@Test
fun `a thread without an action cannot be activated`() {
val buttons = ThreadStatusButtons()
buttons.update("Cluster", threadState(nick = "cluster", description = "on", info = "running"))
assertFalse(buttons.buttons.single().activate())
}
@Test
fun `a status provider replaces a stale worker snapshot when the UI applies it`() {
val buttons = ThreadStatusButtons()
var current = threadState(nick = "beacon", description = "on", info = "enabled")
buttons.registerStatusProvider("MyBeacon") { current }
val queuedSnapshot = current
current = threadState(nick = "beacon", description = "off", info = "disabled")
buttons.update("MyBeacon", queuedSnapshot)
assertEquals("MyBeacon: off", buttons.buttons.single().label)
assertEquals("disabled", buttons.buttons.single().tooltip)
}
private fun threadState(nick: String, description: String, info: String): ThreadStateMessage = private fun threadState(nick: String, description: String, info: String): ThreadStateMessage =
ThreadStateMessage(nick, true, info, false).apply { ThreadStateMessage(nick, true, info, false).apply {
setRunningInformationTextDescription(description) setRunningInformationTextDescription(description)
@@ -32,17 +32,19 @@ class TopPriorityCandidatesWindowTest {
/** Runs [block] against a rendered list of [twoCandidates] and reports what it picked. */ /** Runs [block] against a rendered list of [twoCandidates] and reports what it picked. */
private fun picking(block: (ImageComposeScene) -> Unit): String? { private fun picking(block: (ImageComposeScene) -> Unit): String? {
var picked: String? = null var picked: String? = null
val scene = ImageComposeScene(width = 360, height = 500, density = Density(1f)) { onEventThread {
TopPriorityCandidatesWindow.CandidateListForTest(twoCandidates) { val scene = ImageComposeScene(width = 360, height = 500, density = Density(1f)) {
picked = it.displayCallSign TopPriorityCandidatesWindow.CandidateListForTest(twoCandidates) {
picked = it.displayCallSign
}
}
try {
scene.render()
block(scene)
scene.render()
} finally {
scene.close()
} }
}
try {
scene.render()
block(scene)
scene.render()
} finally {
scene.close()
} }
return picked return picked
} }
@@ -78,13 +80,15 @@ class TopPriorityCandidatesWindowTest {
@Test @Test
fun `the list renders with candidates and without`() { fun `the list renders with candidates and without`() {
listOf(emptyList(), twoCandidates).forEach { ranking -> listOf(emptyList(), twoCandidates).forEach { ranking ->
val scene = ImageComposeScene(width = 360, height = 500, density = Density(1f)) { onEventThread {
TopPriorityCandidatesWindow.CandidateListForTest(ranking) { } val scene = ImageComposeScene(width = 360, height = 500, density = Density(1f)) {
} TopPriorityCandidatesWindow.CandidateListForTest(ranking) { }
try { }
scene.render() try {
} finally { scene.render()
scene.close() } finally {
scene.close()
}
} }
} }
} }
@@ -4,6 +4,7 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.ImageComposeScene import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Density
import kst4contest.view.compose.onEventThread
import kst4contest.view.map.MapCallsignRawSnapshot import kst4contest.view.map.MapCallsignRawSnapshot
import kst4contest.view.map.MapViewport import kst4contest.view.map.MapViewport
import kst4contest.view.map.TileFetcher import kst4contest.view.map.TileFetcher
@@ -48,6 +49,8 @@ class ComposeStationMapDrawingTest {
private val workedGridBorder = 0x000000 private val workedGridBorder = 0x000000
private val selectedDotBorder = 0xFF9900
/* /*
* An empty cache and a source that always fails, so that "tiles never arrive" holds by * An empty cache and a source that always fails, so that "tiles never arrive" holds by
* construction. The default fetcher read the user's disk cache and the real tile * construction. The default fetcher read the user's disk cache and the real tile
@@ -70,28 +73,36 @@ class ComposeStationMapDrawingTest {
ownLocator6: String = "", ownLocator6: String = "",
workedGrossFields: Set<String> = emptySet(), workedGrossFields: Set<String> = emptySet(),
darkMode: Boolean = true, darkMode: Boolean = true,
selectedTarget: MapCallsignRawSnapshot? = null,
spatialFilterOverlay: SpatialFilterOverlayState? = null,
antennaBeamWidthDeg: Double = 0.0,
maxQrbKm: Double = 0.0,
): BufferedImage { ): BufferedImage {
val scene = ImageComposeScene(canvasWidth, canvasHeight, Density(1f)) { return onEventThread {
ComposeStationMap( val scene = ImageComposeScene(canvasWidth, canvasHeight, Density(1f)) {
markers = markers, ComposeStationMap(
tileFetcher = offlineTileFetcher, markers = markers,
mapState = MapState(zoom = zoom, centerLon = 10.0, centerLat = 51.0), tileFetcher = offlineTileFetcher,
groupingEnabled = false, mapState = MapState(zoom = zoom, centerLon = 10.0, centerLat = 51.0),
selectedMarkerCallsign = null, groupingEnabled = false,
ownLocator6 = ownLocator6, selectedMarkerCallsign = null,
antennaAzimuthDeg = 90.0, ownLocator6 = ownLocator6,
antennaBeamWidthDeg = 0.0, antennaAzimuthDeg = 90.0,
maxQrbKm = 0.0, antennaBeamWidthDeg = antennaBeamWidthDeg,
onMarkerClicked = null, maxQrbKm = maxQrbKm,
workedGrossFields = workedGrossFields, selectedTarget = selectedTarget,
darkMode = darkMode, spatialFilterOverlay = spatialFilterOverlay,
modifier = Modifier.fillMaxSize(), onMarkerClicked = null,
) workedGrossFields = workedGrossFields,
} darkMode = darkMode,
try { modifier = Modifier.fillMaxSize(),
return ImageIO.read(ByteArrayInputStream(scene.render().encodeToData()!!.bytes)) )
} finally { }
scene.close() try {
ImageIO.read(ByteArrayInputStream(scene.render().encodeToData()!!.bytes))
} finally {
scene.close()
}
} }
} }
@@ -105,6 +116,16 @@ class ComposeStationMapDrawingTest {
return count return count
} }
private fun changedPixels(before: BufferedImage, after: BufferedImage): Int {
var changed = 0
for (x in 0 until before.width) {
for (y in 0 until before.height) {
if (before.getRGB(x, y) != after.getRGB(x, y)) changed++
}
}
return changed
}
/** The widest horizontal run of a colour, which for a ring is its outer diameter. */ /** The widest horizontal run of a colour, which for a ring is its outer diameter. */
private fun widestRun(image: BufferedImage, rgb: Int): Int { private fun widestRun(image: BufferedImage, rgb: Int): Int {
var widest = 0 var widest = 0
@@ -279,6 +300,54 @@ class ComposeStationMapDrawingTest {
} }
} }
@Test
fun `active spatial filters add a distinct overlay in both themes`() {
val overlay = SpatialFilterOverlayState(
qtfEnabled = true,
qtfDegrees = 90.0,
beamWidthDeg = 60.0,
minQrbEnabled = true,
minQrbKm = 50.0,
maxQrbEnabled = true,
maxQrbKm = 400.0,
)
for (darkMode in listOf(false, true)) {
val without = render(6f, markers = emptyList(), ownLocator6 = "JO50JP", darkMode = darkMode)
val with = render(
6f,
markers = emptyList(),
ownLocator6 = "JO50JP",
darkMode = darkMode,
spatialFilterOverlay = overlay,
)
assertTrue(changedPixels(without, with) > 1_000) {
"the spatial filter overlay was not visible in darkMode=$darkMode"
}
}
}
@Test
fun `a filtered selected target is drawn without joining the normal marker list`() {
val targetLocation = kst4contest.locatorUtils.Location("JO51AA")
val target = station(
"DL1HIDE",
"JO51AA",
targetLocation.latitude.toDegrees(),
targetLocation.longitude.toDegrees(),
)
val image = render(
6f,
markers = emptyList(),
ownLocator6 = "JO50JP",
selectedTarget = target,
)
assertTrue(countColour(image, selectedDotBorder) > 0, "the separate selected marker is missing")
}
/** /**
* Every grid line has to be drawn once. * Every grid line has to be drawn once.
* *
@@ -4,6 +4,7 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.ImageComposeScene import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Density
import kst4contest.view.compose.onEventThread
import kst4contest.view.map.MapCallsignRawSnapshot import kst4contest.view.map.MapCallsignRawSnapshot
import kst4contest.view.map.TileFetcher import kst4contest.view.map.TileFetcher
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@@ -33,30 +34,32 @@ class ComposeStationMapLayoutTest {
) )
private fun renderAt(widthPx: Int, heightPx: Int, zoom: Float) { private fun renderAt(widthPx: Int, heightPx: Int, zoom: Float) {
val scene = ImageComposeScene( onEventThread {
width = widthPx, val scene = ImageComposeScene(
height = heightPx, width = widthPx,
density = Density(1f), height = heightPx,
) { density = Density(1f),
ComposeStationMap( ) {
markers = stations, ComposeStationMap(
tileFetcher = TileFetcher(), markers = stations,
mapState = MapState(zoom = zoom, centerLon = 10.0, centerLat = 51.0), tileFetcher = TileFetcher(),
groupingEnabled = true, mapState = MapState(zoom = zoom, centerLon = 10.0, centerLat = 51.0),
selectedMarkerCallsign = "F5JMI", groupingEnabled = true,
ownLocator6 = "JO50JP", selectedMarkerCallsign = "F5JMI",
antennaAzimuthDeg = 229.0, ownLocator6 = "JO50JP",
antennaBeamWidthDeg = 60.0, antennaAzimuthDeg = 229.0,
maxQrbKm = 800.0, antennaBeamWidthDeg = 60.0,
onMarkerClicked = null, maxQrbKm = 800.0,
darkMode = true, onMarkerClicked = null,
modifier = Modifier.fillMaxSize(), darkMode = true,
) modifier = Modifier.fillMaxSize(),
} )
try { }
scene.render() try {
} finally { scene.render()
scene.close() } finally {
scene.close()
}
} }
} }
@@ -0,0 +1,29 @@
package kst4contest.view.compose.map
import kst4contest.model.ChatPreferences
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Path
class MapDisplaySettingsStateTest {
@TempDir
lateinit var directory: Path
@Test
fun `refresh publishes applied beam geometry from preferences`() {
val preferences = ChatPreferences(directory.resolve("preferences.xml")).apply {
stn_antennaBeamWidthDeg = 50.0
stn_maxQRBDefault = 750.0
}
val state = MapDisplaySettingsState(preferences)
preferences.stn_antennaBeamWidthDeg = 72.0
preferences.stn_maxQRBDefault = 1_100.0
state.refreshFromPreferences()
assertEquals(72.0, state.antennaBeamWidthDeg)
assertEquals(1_100.0, state.maxQrbKm)
}
}
@@ -0,0 +1,42 @@
package kst4contest.view.compose.map
import kst4contest.view.compose.StationIdentity
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
class MapNavigationStateTest {
@Test
fun `repeated station choices remain observable`() {
val state = MapNavigationState()
val identity = StationIdentity("DL1ABC", 2)
state.fitSelectedPath(identity)
val firstRevision = state.requestRevision
state.fitSelectedPath(identity)
assertTrue(state.requestRevision > firstRevision)
assertEquals(MapNavigationRequest.FitSelectedPath(identity), state.request)
}
@Test
fun `latest explicit action replaces an older one`() {
val state = MapNavigationState()
state.fitSelectedPath(StationIdentity("DL1ABC", 2))
state.centerOnQtf(45.0)
assertEquals(MapNavigationRequest.CenterOnQtf(45.0), state.request)
}
@Test
fun `invalid QTF values do not create requests`() {
val state = MapNavigationState()
listOf(Double.NaN, Double.POSITIVE_INFINITY, -1.0, 360.1).forEach(state::centerOnQtf)
assertEquals(0L, state.requestRevision)
assertEquals(null, state.request)
}
}
@@ -0,0 +1,60 @@
package kst4contest.view.compose.map
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.runComposeUiTest
import androidx.compose.ui.unit.dp
import kst4contest.view.compose.Kst4ContestTheme
import kst4contest.view.i18n.LanguageStore
import kst4contest.view.i18n.LocalStrings
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.util.Locale
@OptIn(ExperimentalTestApi::class)
class MapOverlayLegendScreenTest {
@Test
fun germanEveningLegendWrapsBothItemsInsideANarrowHeader() = runComposeUiTest {
var storedLanguage = "de"
val languages = LanguageStore(
storedLanguage = { storedLanguage },
storeLanguage = { storedLanguage = it },
systemDefault = Locale.GERMANY,
)
try {
setContent {
CompositionLocalProvider(LocalStrings provides languages.strings) {
Kst4ContestTheme(darkMode = true, baseFontSizeSp = 12f) {
Box(Modifier.width(110.dp)) {
MapOverlayLegend(
showAntenna = true,
showSpatialFilters = true,
darkMode = true,
)
}
}
}
}
onNodeWithText("Antenne").assertIsDisplayed()
onNodeWithText("Aktive Filter").assertIsDisplayed()
val antenna = onNodeWithTag(MAP_ANTENNA_LEGEND_TAG).fetchSemanticsNode().boundsInRoot
val filters = onNodeWithTag(MAP_FILTER_LEGEND_TAG).fetchSemanticsNode().boundsInRoot
val widthLimit = with(density) { 110.dp.toPx() }
assertTrue(antenna.right <= widthLimit + 0.5f)
assertTrue(filters.right <= widthLimit + 0.5f)
assertTrue(filters.top >= antenna.bottom, "the legend items did not wrap at narrow width")
} finally {
runOnIdle { languages.use("en") }
}
}
}
@@ -4,6 +4,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.ui.ImageComposeScene import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Density
import kst4contest.view.compose.onEventThread
import kst4contest.view.map.PathAnalysisResult import kst4contest.view.map.PathAnalysisResult
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@@ -25,21 +26,23 @@ class PathAnalysisDetailsLayoutTest {
private val narrowWidthPx = 120 private val narrowWidthPx = 120
private fun renderAt(widthPx: Int, result: PathAnalysisResult?) { private fun renderAt(widthPx: Int, result: PathAnalysisResult?) {
val scene = ImageComposeScene( onEventThread {
width = widthPx, val scene = ImageComposeScene(
height = 600, width = widthPx,
density = Density(1f), height = 600,
) { density = Density(1f),
PathAnalysisDetails( ) {
result = result, PathAnalysisDetails(
darkMode = true, result = result,
modifier = Modifier.fillMaxWidth(), darkMode = true,
) modifier = Modifier.fillMaxWidth(),
} )
try { }
scene.render() try {
} finally { scene.render()
scene.close() } finally {
scene.close()
}
} }
} }
@@ -4,6 +4,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.ui.ImageComposeScene import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Density
import kst4contest.view.compose.onEventThread
import kst4contest.view.map.PathAnalysisResult import kst4contest.view.map.PathAnalysisResult
import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@@ -31,18 +32,20 @@ class PathAnalysisDetailsWidthTest {
private val assessmentBackground = 0x33383E private val assessmentBackground = 0x33383E
private fun render(paneWidthPx: Int, heightPx: Int = 600): BufferedImage { private fun render(paneWidthPx: Int, heightPx: Int = 600): BufferedImage {
val scene = ImageComposeScene(width = paneWidthPx, height = heightPx, density = Density(1f)) { return onEventThread {
PathAnalysisDetails( val scene = ImageComposeScene(width = paneWidthPx, height = heightPx, density = Density(1f)) {
result = PathAnalysisResult.loading("JO50JP", "JN24JB", "F5JMI"), PathAnalysisDetails(
darkMode = true, result = PathAnalysisResult.loading("JO50JP", "JN24JB", "F5JMI"),
modifier = Modifier.fillMaxWidth(), darkMode = true,
) modifier = Modifier.fillMaxWidth(),
} )
try { }
val png = scene.render().encodeToData()!!.bytes try {
return ImageIO.read(ByteArrayInputStream(png)) val png = scene.render().encodeToData()!!.bytes
} finally { ImageIO.read(ByteArrayInputStream(png))
scene.close() } finally {
scene.close()
}
} }
} }
@@ -4,6 +4,7 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.ImageComposeScene import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Density
import kst4contest.view.compose.onEventThread
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
/** /**
@@ -18,17 +19,19 @@ import org.junit.jupiter.api.Test
class PathProfileChartLayoutTest { class PathProfileChartLayoutTest {
private fun renderAt(widthPx: Int, heightPx: Int) { private fun renderAt(widthPx: Int, heightPx: Int) {
val scene = ImageComposeScene( onEventThread {
width = widthPx, val scene = ImageComposeScene(
height = heightPx, width = widthPx,
density = Density(1f), height = heightPx,
) { density = Density(1f),
PathProfileChart(modifier = Modifier.fillMaxSize(), darkMode = true) ) {
} PathProfileChart(modifier = Modifier.fillMaxSize(), darkMode = true)
try { }
scene.render() try {
} finally { scene.render()
scene.close() } finally {
scene.close()
}
} }
} }
@@ -0,0 +1,91 @@
package kst4contest.view.compose.map
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
class SpatialFilterOverlayStateTest {
@Test
fun `maximum QRB is inclusive and minimum QRB is exclusive`() {
val state = overlay(minEnabled = true, minKm = 200.0, maxEnabled = true, maxKm = 500.0)
assertFalse(state.accepts(200.0, 90.0))
assertTrue(state.accepts(200.1, 90.0))
assertTrue(state.accepts(500.0, 90.0))
assertFalse(state.accepts(500.1, 90.0))
}
@Test
fun `QTF uses the same wrapped beamwidth semantics as the station filter`() {
val state = overlay(qtf = true, direction = 0.0, beamWidth = 60.0)
assertTrue(state.accepts(300.0, 350.0))
assertTrue(state.accepts(300.0, 30.0))
assertFalse(state.accepts(300.0, 31.0))
}
@Test
fun `unusual full-circle beamwidth retains the existing station filter semantics`() {
val state = overlay(qtf = true, direction = 0.0, beamWidth = 360.0)
assertTrue(state.accepts(300.0, 180.0))
assertFalse(state.accepts(300.0, 0.0))
}
@Test
fun `minimum above maximum is an empty distance range`() {
val state = overlay(minEnabled = true, minKm = 500.0, maxEnabled = true, maxKm = 200.0)
assertTrue(state.hasEmptyDistanceRange)
assertFalse(state.accepts(100.0, 0.0))
assertFalse(state.accepts(300.0, 0.0))
assertFalse(state.accepts(600.0, 0.0))
}
@Test
fun `non-finite active values cannot be rendered as a misleading area`() {
assertFalse(overlay(qtf = true, direction = Double.NaN).hasRenderableValues)
assertFalse(overlay(minEnabled = true, minKm = Double.POSITIVE_INFINITY).hasRenderableValues)
assertFalse(overlay(maxEnabled = true, maxKm = Double.NaN).hasRenderableValues)
}
@Test
fun `zero distance boundaries report only actually drawable geometry`() {
assertFalse(overlay(maxEnabled = true, maxKm = 0.0).hasDrawableGeometry)
assertFalse(overlay(qtf = true, maxEnabled = true, maxKm = 0.0).hasDrawableGeometry)
assertFalse(
overlay(minEnabled = true, minKm = 0.0, maxEnabled = true, maxKm = 0.0).hasDrawableGeometry
)
assertTrue(overlay(minEnabled = true, minKm = 0.0).hasDrawableGeometry)
assertTrue(overlay(qtf = true).hasDrawableGeometry)
assertTrue(overlay(minEnabled = true, minKm = 100.0, maxEnabled = true, maxKm = 0.0).hasDrawableGeometry)
assertTrue(overlay(maxEnabled = true, maxKm = 500.0).hasDrawableGeometry)
}
@Test
fun `no spatial filter accepts finite positions`() {
val state = overlay()
assertFalse(state.isActive)
assertTrue(state.accepts(1000.0, 275.0))
}
private fun overlay(
qtf: Boolean = false,
direction: Double = 0.0,
beamWidth: Double = 60.0,
minEnabled: Boolean = false,
minKm: Double = 0.0,
maxEnabled: Boolean = false,
maxKm: Double = 0.0,
) = SpatialFilterOverlayState(
qtfEnabled = qtf,
qtfDegrees = direction,
beamWidthDeg = beamWidth,
minQrbEnabled = minEnabled,
minQrbKm = minKm,
maxQrbEnabled = maxEnabled,
maxQrbKm = maxKm,
)
}
@@ -15,6 +15,7 @@ import androidx.compose.ui.unit.dp
import kst4contest.view.compose.SplitterOrientation import kst4contest.view.compose.SplitterOrientation
import kst4contest.view.compose.SplitterPane import kst4contest.view.compose.SplitterPane
import kst4contest.view.compose.SplitterState import kst4contest.view.compose.SplitterState
import kst4contest.view.compose.onEventThread
import kst4contest.view.map.MapCallsignRawSnapshot import kst4contest.view.map.MapCallsignRawSnapshot
import kst4contest.view.map.PathAnalysisResult import kst4contest.view.map.PathAnalysisResult
import kst4contest.view.map.TileFetcher import kst4contest.view.map.TileFetcher
@@ -88,13 +89,15 @@ class StationMapBodyLayoutTest {
} }
private fun renderAt(widthPx: Int, heightPx: Int, pathAnalysisVisible: Boolean = true) { private fun renderAt(widthPx: Int, heightPx: Int, pathAnalysisVisible: Boolean = true) {
val scene = ImageComposeScene(width = widthPx, height = heightPx, density = Density(1f)) { onEventThread {
Body(pathAnalysisVisible) val scene = ImageComposeScene(width = widthPx, height = heightPx, density = Density(1f)) {
} Body(pathAnalysisVisible)
try { }
scene.render() try {
} finally { scene.render()
scene.close() } finally {
scene.close()
}
} }
} }
@@ -4,7 +4,6 @@ import androidx.compose.ui.test.ComposeUiTest
import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertIsOff import androidx.compose.ui.test.assertIsOff
import androidx.compose.ui.test.assertIsOn import androidx.compose.ui.test.assertIsOn
import androidx.compose.ui.test.assertCountEquals
import androidx.compose.ui.test.click import androidx.compose.ui.test.click
import androidx.compose.ui.test.isToggleable import androidx.compose.ui.test.isToggleable
import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onAllNodesWithText
@@ -42,7 +41,6 @@ import kst4contest.view.compose.STATION_CONTEXT_TARGET_CHOOSER_TAG
import kst4contest.view.compose.ThreadStatusButtons import kst4contest.view.compose.ThreadStatusButtons
import kst4contest.view.compose.TimelineState import kst4contest.view.compose.TimelineState
import kst4contest.view.compose.TopPriorityState import kst4contest.view.compose.TopPriorityState
import kst4contest.view.map.StationMapClusterer
import kst4contest.view.map.MapCallsignRawSnapshot import kst4contest.view.map.MapCallsignRawSnapshot
import kst4contest.view.map.PathAnalysisResult import kst4contest.view.map.PathAnalysisResult
import kst4contest.view.map.TileFetcher import kst4contest.view.map.TileFetcher
@@ -231,7 +229,10 @@ class StationMapWindowScreenTest {
val dl1abc = station("DL1ABC", 2) val dl1abc = station("DL1ABC", 2)
state.selectedStation.select(dl1abc) state.selectedStation.select(dl1abc)
val selectorCalls = mutableListOf<ChatMember?>() val selectorCalls = mutableListOf<ChatMember?>()
state.stationSelector = { member, _ -> selectorCalls += member } state.stationSelector = { member, source ->
selectorCalls += member
state.selectedStation.select(member, source)
}
val mapState = mapLookingAt("JO50JP", zoom = 15f) val mapState = mapLookingAt("JO50JP", zoom = 15f)
show(state, listOf(dl1abc), mapState) show(state, listOf(dl1abc), mapState)
@@ -240,11 +241,7 @@ class StationMapWindowScreenTest {
waitForIdle() waitForIdle()
assertEquals(listOf<ChatMember?>(null), selectorCalls, "reset did not go through the station selector") assertEquals(listOf<ChatMember?>(null), selectorCalls, "reset did not go through the station selector")
assertSame( assertEquals(null, state.selectedStation.selected)
dl1abc,
state.selectedStation.selected,
"reset cleared the panel's selection behind the selector's back",
)
assertEquals(15f, mapState.zoom, "reset changed the zoom") assertEquals(15f, mapState.zoom, "reset changed the zoom")
val home = Location(ownLocator) val home = Location(ownLocator)
@@ -369,12 +366,9 @@ class StationMapWindowScreenTest {
assertEquals(readsWhileEnabled, reads, "disabled Grid color still read worked fields") assertEquals(readsWhileEnabled, reads, "disabled Grid color still read worked fields")
} }
/** /** An explicit selection fits both ends and still starts the existing path analysis. */
* The cc8c9020 rule: selecting a station pans the map to it and leaves the zoom alone.
* The earlier Compose version recomputed the zoom here and threw zoom 15 out to about 7.
*/
@Test @Test
fun selectingAStationPansToItAndKeepsTheZoom() = runComposeUiTest { fun selectingAStationFitsTheCompletePath() = runComposeUiTest {
val state = windowState(prefs()) val state = windowState(prefs())
val dl1abc = station("DL1ABC", 2, locator = "JO50JP") val dl1abc = station("DL1ABC", 2, locator = "JO50JP")
val analysis = RecordingPathAnalysis() val analysis = RecordingPathAnalysis()
@@ -382,53 +376,49 @@ class StationMapWindowScreenTest {
show(state, listOf(dl1abc), mapState, analysis) show(state, listOf(dl1abc), mapState, analysis)
runOnIdle { state.selectedStation.select(dl1abc) } runOnIdle { state.selectStation(dl1abc, StationSelectionSource.STATION_TABLE) }
waitForIdle() waitForIdle()
val home = Location(ownLocator)
val target = Location("JO50JP") val target = Location("JO50JP")
assertEquals(target.longitude.toDegrees(), mapState.centerLon, 1e-9, "the map did not pan") assertTrue(mapState.centerLon in home.longitude.toDegrees()..target.longitude.toDegrees())
assertEquals(target.latitude.toDegrees(), mapState.centerLat, 1e-9, "the map did not pan") assertTrue(mapState.centerLat in home.latitude.toDegrees()..target.latitude.toDegrees())
assertEquals(15f, mapState.zoom, "selecting a station changed the zoom") assertTrue(mapState.zoom < 15f, "a path too long for zoom 15 was not fitted")
assertEquals(listOf(dl1abc), analysis.requested, "the path analysis was not asked") assertEquals(listOf(dl1abc), analysis.requested, "the path analysis was not asked")
} }
/** /** Grouping never forces a path which already fits to zoom in. */
* With grouping on, a selection zooms in only as far as it takes to break the station out
* of its bubble, and never out: StationMapClusterer.zoomToRevealStations.
*/
@Test @Test
fun withGroupingOnASelectionOnlyZoomsInFarEnoughToRevealTheStation() = runComposeUiTest { fun groupingDoesNotZoomInWhileFittingASelectedPath() = runComposeUiTest {
val prefs = prefs().apply { isGUIstationMapClusteringEnabled = true } val prefs = prefs().apply { isGUIstationMapClusteringEnabled = true }
val state = windowState(prefs) val state = windowState(prefs)
val dl1abc = station("DL1ABC", 2, locator = "JO50JP") val dl1abc = station("DL1ABC", 2, locator = "JO40HB")
val far = mapLookingAt(ownLocator, zoom = 5f) val mapState = mapLookingAt(ownLocator, zoom = 5f)
show(state, listOf(dl1abc), far, RecordingPathAnalysis()) show(state, listOf(dl1abc), mapState, RecordingPathAnalysis())
runOnIdle { state.selectedStation.select(dl1abc) } runOnIdle { state.selectStation(dl1abc, StationSelectionSource.STATION_TABLE) }
waitForIdle() waitForIdle()
assertEquals(StationMapClusterer.DISABLE_AT_ZOOM.toFloat(), far.zoom) assertEquals(5f, mapState.zoom)
} }
/** Without a running application there is nothing to ask, and the map stays put. */ /** Camera navigation is independent of the optional path-analysis service. */
@Test @Test
fun withoutAPathAnalysisASelectionLeavesTheMapWhereItIs() = runComposeUiTest { fun withoutAPathAnalysisASelectionStillFitsThePath() = runComposeUiTest {
val state = windowState(prefs()) val state = windowState(prefs())
val dl1abc = station("DL1ABC", 2, locator = "JO50JP") val dl1abc = station("DL1ABC", 2, locator = "JO50JP")
val mapState = mapLookingAt(ownLocator, zoom = 15f) val mapState = mapLookingAt(ownLocator, zoom = 15f)
val home = Location(ownLocator)
var asked = 0 var asked = 0
show(state, listOf(dl1abc), mapState, pathAnalysis = null, onPathAnalysisAsked = { asked++ }) show(state, listOf(dl1abc), mapState, pathAnalysis = null, onPathAnalysisAsked = { asked++ })
runOnIdle { state.selectedStation.select(dl1abc) } runOnIdle { state.selectStation(dl1abc, StationSelectionSource.STATION_TABLE) }
waitForIdle() waitForIdle()
// Proves the selection effect ran, so the unchanged map is not a vacuous pass. // Proves the selection effect ran, so the unchanged map is not a vacuous pass.
assertEquals(1, asked, "the selection effect did not ask for a path analysis") assertEquals(1, asked, "the selection effect did not ask for a path analysis")
assertEquals(home.longitude.toDegrees(), mapState.centerLon, 1e-9) assertTrue(mapState.zoom < 15f)
assertEquals(15f, mapState.zoom)
} }
/** The two header switches write the profile, so the map opens the same way next time. */ /** The two header switches write the profile, so the map opens the same way next time. */
@@ -477,6 +467,54 @@ class StationMapWindowScreenTest {
assertEquals(listOf(true, false), applied) assertEquals(listOf(true, false), applied)
} }
@Test
fun headerLegendFollowsDrawableAntennaAndSpatialFilterOverlays() = runComposeUiTest {
val prefs = prefs()
val state = windowState(prefs)
show(state, emptyList(), MapState())
onNodeWithText("Antenna").assertExists()
onNodeWithText("Active filters").assertDoesNotExist()
runOnIdle {
state.stationFilter.maxQrbKm = 666.0
state.stationFilter.maxQrbEnabled = true
}
waitForIdle()
onNodeWithText("Antenna").assertExists()
onNodeWithText("Active filters").assertExists()
runOnIdle {
prefs.stn_antennaBeamWidthDeg = 0.0
prefs.stn_maxQRBDefault = 0.0
state.refreshMapDisplaySettings()
state.stationFilter.maxQrbEnabled = false
}
waitForIdle()
onNodeWithText("Antenna").assertDoesNotExist()
onNodeWithText("Active filters").assertDoesNotExist()
}
@Test
fun invalidSpatialFilterDoesNotClaimAVisibleOverlay() = runComposeUiTest {
val state = windowState(prefs())
state.stationFilter.maxQrbKm = 0.0
state.stationFilter.maxQrbEnabled = true
show(state, emptyList(), MapState())
onNodeWithText("Antenna").assertExists()
onNodeWithText("Active filters").assertDoesNotExist()
runOnIdle { state.stationFilter.maxQrbKm = Double.NaN }
waitForIdle()
onNodeWithText("Active filters").assertDoesNotExist()
}
@Test @Test
fun resetFiltersUsesTheSharedActionAndDoesNotResetTheView() = runComposeUiTest { fun resetFiltersUsesTheSharedActionAndDoesNotResetTheView() = runComposeUiTest {
val state = windowState(prefs()) val state = windowState(prefs())
@@ -553,13 +591,9 @@ class StationMapWindowScreenTest {
onNodeWithText("Showing 1 visible stations | filtered view active").assertExists() onNodeWithText("Showing 1 visible stations | filtered view active").assertExists()
} }
/** /** A filtered-out selection remains a separate target without entering the marker count. */
* A selected station the filters hide has no marker, and so nothing to analyse: no
* request goes out and the analysis does not sit at "Loading" with an empty target (#21).
* The visible station beside it is the control: selecting it does ask and does load.
*/
@Test @Test
fun aSelectedStationTheFiltersHideGetsNoPathAnalysis() = runComposeUiTest { fun aSelectedStationTheFiltersHideKeepsItsTargetAndPathAnalysis() = runComposeUiTest {
val state = windowState(prefs(pathAnalysisVisible = true)) val state = windowState(prefs(pathAnalysisVisible = true))
val hidden = station("DL1HIDE", 2, locator = "JO50JP").apply { qrb = 100.0 } val hidden = station("DL1HIDE", 2, locator = "JO50JP").apply { qrb = 100.0 }
val shown = station("DL2SHOW", 2, locator = "JO62QM").apply { qrb = 800.0 } val shown = station("DL2SHOW", 2, locator = "JO62QM").apply { qrb = 800.0 }
@@ -568,21 +602,128 @@ class StationMapWindowScreenTest {
state.stations.rowFilter = { state.stationFilter.acceptsQrb(it.qrb) } state.stations.rowFilter = { state.stationFilter.acceptsQrb(it.qrb) }
val analysis = RecordingPathAnalysis() val analysis = RecordingPathAnalysis()
val mapState = mapLookingAt(ownLocator, zoom = 9f) val mapState = mapLookingAt(ownLocator, zoom = 9f)
val home = Location(ownLocator)
show(state, listOf(hidden, shown), mapState, analysis) show(state, listOf(hidden, shown), mapState, analysis)
runOnIdle { state.selectedStation.select(hidden) } runOnIdle { state.selectStation(hidden, StationSelectionSource.PRIORITY) }
waitForIdle() waitForIdle()
assertEquals(emptyList<ChatMember>(), analysis.requested, "a hidden station was analysed") assertEquals(listOf(hidden), analysis.requested, "the selected hidden target was not analysed")
onAllNodesWithText("Loading", substring = true).assertCountEquals(0) assertEquals(true, onAllNodesWithText("Loading", substring = true).fetchSemanticsNodes().isNotEmpty())
assertEquals(home.longitude.toDegrees(), mapState.centerLon, 1e-9, "the map panned to a hidden station") onNodeWithText("Showing 1 visible stations | filtered view active", substring = true).assertExists()
runOnIdle { state.selectedStation.select(shown) } runOnIdle { state.selectStation(shown, StationSelectionSource.PRIORITY) }
waitForIdle() waitForIdle()
assertEquals(listOf(shown), analysis.requested) assertEquals(listOf(hidden, shown), analysis.requested)
assertEquals(true, onAllNodesWithText("Loading", substring = true).fetchSemanticsNodes().isNotEmpty()) assertEquals(true, onAllNodesWithText("Loading", substring = true).fetchSemanticsNodes().isNotEmpty())
} }
@Test
fun filteredSelectedMarkerWinsHitTestingWhenAnotherMarkerOverlapsIt() = runComposeUiTest {
val state = windowState(prefs())
val hidden = station("DL1HIDE", 2, locator = ownLocator).apply { qrb = 100.0 }
val shown = station("DL2SHOW", 2, locator = ownLocator).apply { qrb = 800.0 }
state.stationFilter.minQrbKm = 300.0
state.stationFilter.minQrbEnabled = true
state.stations.rowFilter = { state.stationFilter.acceptsQrb(it.qrb) }
val selections = mutableListOf<ChatMember?>()
state.stationSelector = { member, source ->
selections += member
state.selectedStation.select(member, source)
}
show(state, listOf(hidden, shown), mapLookingAt(ownLocator, zoom = 12f))
runOnIdle { state.selectStation(hidden, StationSelectionSource.PRIORITY) }
waitForIdle()
selections.clear()
onNodeWithTag(StationMapWindow.MAP_CANVAS_TAG).performMouseInput { click() }
waitForIdle()
assertEquals(listOf(hidden), selections)
}
@Test
fun rosterReconciliationDoesNotOverwriteManualCameraMovement() = runComposeUiTest {
val state = windowState(prefs())
val selected = station("DL1ABC", 2, locator = "JO50JP")
val mapState = mapLookingAt(ownLocator, zoom = 10f)
show(state, listOf(selected), mapState, RecordingPathAnalysis())
runOnIdle { state.selectStation(selected, StationSelectionSource.PUBLIC_MESSAGE) }
waitForIdle()
runOnIdle {
mapState.centerLon = 3.0
mapState.centerLat = 48.0
mapState.zoom = 11f
state.stations.replaceRows(listOf(station("DL1ABC", 2, locator = "JO50JP")))
}
waitForIdle()
assertEquals(3.0, mapState.centerLon, 1e-9)
assertEquals(48.0, mapState.centerLat, 1e-9)
assertEquals(11f, mapState.zoom)
}
@Test
fun explicitQtfNavigationPreservesZoomAndFilterResetDoesNotNavigate() = runComposeUiTest {
val state = windowState(prefs())
val mapState = mapLookingAt(ownLocator, zoom = 9.5f)
show(state, emptyList(), mapState)
runOnIdle { state.applyExplicitQtfFilterDirection(45.0) }
waitForIdle()
val qtfLon = mapState.centerLon
val qtfLat = mapState.centerLat
assertEquals(9.5f, mapState.zoom)
assertTrue(qtfLon > Location(ownLocator).longitude.toDegrees())
assertTrue(qtfLat > Location(ownLocator).latitude.toDegrees())
runOnIdle { state.resetStationFilters() }
waitForIdle()
assertEquals(qtfLon, mapState.centerLon, 1e-9)
assertEquals(qtfLat, mapState.centerLat, 1e-9)
assertEquals(9.5f, mapState.zoom)
}
@Test
fun QtfNavigationDoesNotRequireOrChangeManualAntennaHeading() = runComposeUiTest {
val prefs = prefs().apply {
setStn_useQtfFilterDirectionAsAntennaHeading(false)
actualQTF.set(123.0)
}
val state = windowState(prefs)
val mapState = mapLookingAt(ownLocator, zoom = 9.5f)
show(state, emptyList(), mapState)
runOnIdle { state.applyExplicitQtfFilterDirection(45.0) }
waitForIdle()
assertTrue(mapState.centerLon > Location(ownLocator).longitude.toDegrees())
assertTrue(mapState.centerLat > Location(ownLocator).latitude.toDegrees())
assertEquals(9.5f, mapState.zoom)
assertEquals(123.0, prefs.actualQTF.get(), 1e-9)
}
@Test
fun selectingTheSameStationAgainRepeatsPathNavigation() = runComposeUiTest {
val state = windowState(prefs())
val selected = station("DL1ABC", 2, locator = "JO50JP")
val mapState = mapLookingAt(ownLocator, zoom = 10f)
show(state, listOf(selected), mapState, RecordingPathAnalysis())
runOnIdle { state.selectStation(selected, StationSelectionSource.TIMELINE) }
waitForIdle()
val firstCentre = mapState.centerLon to mapState.centerLat
runOnIdle {
mapState.centerLon = 2.0
mapState.centerLat = 45.0
state.selectStation(selected, StationSelectionSource.TIMELINE)
}
waitForIdle()
assertEquals(firstCentre.first, mapState.centerLon, 1e-9)
assertEquals(firstCentre.second, mapState.centerLat, 1e-9)
}
} }
@@ -41,7 +41,7 @@ class BeaconTabStateTest(@TempDir private val tempDir: Path) {
} }
@Test @Test
fun `beacon edits wait for apply, and the timer restarts only then`() { fun `enable changes immediately while template and interval wait for apply`() {
val s = Session(draft = SettingsDraft()) val s = Session(draft = SettingsDraft())
s.prefs.setBcn_beaconIntervalInMinutesMainCat(5) s.prefs.setBcn_beaconIntervalInMinutesMainCat(5)
s.prefs.setBcn_beaconsEnabledMainCat(false) s.prefs.setBcn_beaconsEnabledMainCat(false)
@@ -51,7 +51,7 @@ class BeaconTabStateTest(@TempDir private val tempDir: Path) {
assertNull(state.commitBeaconTextMainCat("CQ MYCALL")) assertNull(state.commitBeaconTextMainCat("CQ MYCALL"))
assertNull(state.commitBeaconInterval("7")) assertNull(state.commitBeaconInterval("7"))
assertFalse(s.prefs.isBcn_beaconsEnabledMainCat(), "an edit took effect before Apply") assertTrue(s.prefs.isBcn_beaconsEnabledMainCat(), "the runtime switch did not take effect immediately")
assertEquals(5, s.prefs.getBcn_beaconIntervalInMinutesMainCat()) assertEquals(5, s.prefs.getBcn_beaconIntervalInMinutesMainCat())
assertEquals(0, s.timerRestarts, "the timer restarted before Apply") assertEquals(0, s.timerRestarts, "the timer restarted before Apply")
assertEquals(7, state.beaconIntervalMinutes, "the tab shows the edit") assertEquals(7, state.beaconIntervalMinutes, "the tab shows the edit")
@@ -65,6 +65,18 @@ class BeaconTabStateTest(@TempDir private val tempDir: Path) {
assertEquals(1, s.timerRestarts) assertEquals(1, s.timerRestarts)
} }
@Test
fun `enable changes do not become pending draft edits`() {
val s = Session(draft = SettingsDraft())
s.prefs.setBcn_beaconsEnabledMainCat(false)
val state = s.state()
state.bcn_beaconsEnabledMainCat = true
assertTrue(s.prefs.isBcn_beaconsEnabledMainCat())
assertFalse(s.draft.hasPendingChanges)
}
@Test @Test
fun `discarded beacon edits leave the timer and the templates alone`() { fun `discarded beacon edits leave the timer and the templates alone`() {
val s = Session(draft = SettingsDraft()) val s = Session(draft = SettingsDraft())
@@ -161,13 +173,24 @@ class BeaconTabStateTest(@TempDir private val tempDir: Path) {
s.prefs.setBcn_beaconIntervalInMinutesMainCat(5) s.prefs.setBcn_beaconIntervalInMinutesMainCat(5)
val state = s.state() val state = s.state()
assertNotNull(state.commitBeaconInterval("0")) assertNotNull(state.commitBeaconInterval("4"))
assertEquals(5, s.prefs.getBcn_beaconIntervalInMinutesMainCat()) assertEquals(5, s.prefs.getBcn_beaconIntervalInMinutesMainCat())
assertEquals(0, s.timerRestarts, assertEquals(0, s.timerRestarts,
"restarting the timer per rejected keystroke would disturb the cooldown") "restarting the timer per rejected keystroke would disturb the cooldown")
} }
@Test
fun `exactly five minutes is accepted`() {
val s = Session()
val state = s.state()
assertNull(state.commitBeaconInterval("5"))
assertEquals(5, s.prefs.getBcn_beaconIntervalInMinutesMainCat())
assertEquals(5, s.prefs.getBcn_beaconIntervalInMinutesSecondCat())
}
@Test @Test
fun `an interval that is not a whole number is refused`() { fun `an interval that is not a whole number is refused`() {
val s = Session() val s = Session()
@@ -162,8 +162,6 @@ class DraftedSettingsTableTest {
}, { it.prefs.getLst_txtSnipList().snapshot() }), }, { it.prefs.getLst_txtSnipList().snapshot() }),
// Beacon // Beacon
flag("beacon main", { it.beacon.bcn_beaconsEnabledMainCat }) { f, v -> f.beacon.bcn_beaconsEnabledMainCat = v },
flag("beacon second", { it.beacon.bcn_beaconsEnabledSecondCat }) { f, v -> f.beacon.bcn_beaconsEnabledSecondCat = v },
Case("beacon text main", { it.beacon.commitBeaconTextMainCat(it.beacon.beaconTextMainCat + " x") }, Case("beacon text main", { it.beacon.commitBeaconTextMainCat(it.beacon.beaconTextMainCat + " x") },
{ it.prefs.getBcn_beaconTextMainCat() }), { it.prefs.getBcn_beaconTextMainCat() }),
Case("beacon text second", { it.beacon.commitBeaconTextSecondCat(it.beacon.beaconTextSecondCat + " x") }, Case("beacon text second", { it.beacon.commitBeaconTextSecondCat(it.beacon.beaconTextSecondCat + " x") },
@@ -3,6 +3,7 @@ package kst4contest.view.compose.tabs
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertIsOff import androidx.compose.ui.test.assertIsOff
import androidx.compose.ui.test.assertIsOn
import androidx.compose.ui.test.assertTextEquals import androidx.compose.ui.test.assertTextEquals
import androidx.compose.ui.test.hasSetTextAction import androidx.compose.ui.test.hasSetTextAction
import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onAllNodesWithText
@@ -190,6 +191,19 @@ class MessagingTabsScreenTest {
assertEquals("cq %foo%", s.prefs.bcn_beaconTextMainCat) assertEquals("cq %foo%", s.prefs.bcn_beaconTextMainCat)
} }
@Test
fun anExternalBeaconToggleUpdatesTheOpenSettingsTab() = runComposeUiTest {
val s = Beacon(preferences())
s.prefs.isBcn_beaconsEnabledMainCat = false
showTab { BeaconTab(s.state) { s.refusals += it } }
checkBeside("Send the beacon in this category").assertIsOff()
runOnIdle { s.prefs.isBcn_beaconsEnabledMainCat = true }
waitForIdle()
checkBeside("Send the beacon in this category").assertIsOn()
}
/* /*
* The tab reads the interval from a plain preference getter, so nothing recomposes it * The tab reads the interval from a plain preference getter, so nothing recomposes it
* after Enter commits. Compared with that stale value, leaving the field afterwards * after Enter commits. Compared with that stale value, leaving the field afterwards
@@ -107,14 +107,14 @@ class SettingsApplyScreenTest {
} }
@Test @Test
fun anEditTakesEffectOnlyWithApplyAndClose() = runComposeUiTest { fun beaconEnableTakesEffectImmediatelyWhileTheIntervalWaitsForApply() = runComposeUiTest {
val w = Window() val w = Window()
show(w) show(w)
toggle("Send the beacon in this category") toggle("Send the beacon in this category")
typeAndCommit("Interval in whole minutes", "9") typeAndCommit("Interval in whole minutes", "9")
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat, "the box took effect before Apply") assertTrue(w.prefs.isBcn_beaconsEnabledMainCat, "the runtime switch did not take effect immediately")
assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat) assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat)
assertEquals(0, w.restarts, "the timer restarted before Apply") assertEquals(0, w.restarts, "the timer restarted before Apply")
@@ -178,19 +178,19 @@ class SettingsApplyScreenTest {
fun aRefusalAppliesNothingSoDiscardIsStillPossible() = runComposeUiTest { fun aRefusalAppliesNothingSoDiscardIsStillPossible() = runComposeUiTest {
val w = Window() val w = Window()
show(w) show(w)
toggle("Send the beacon in this category") typeAndCommit("Interval in whole minutes", "9")
type("Server port", "23x") type("Server port", "23x")
onNodeWithText(APPLY_AND_CLOSE).performClick() onNodeWithText(APPLY_AND_CLOSE).performClick()
waitForIdle() waitForIdle()
assertFalse(w.closed) assertFalse(w.closed)
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat, "the valid edit went into effect despite the refusal") assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat, "the valid edit went into effect despite the refusal")
assertTrue(w.draft.hasPendingChanges) assertTrue(w.draft.hasPendingChanges)
runOnIdle { w.notices.dismiss() } runOnIdle { w.notices.dismiss() }
runOnIdle { w.draft.discard() } runOnIdle { w.draft.discard() }
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat) assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat)
} }
/* /*
@@ -264,7 +264,7 @@ class SettingsApplyScreenTest {
fun theXAsksAboutPendingEditsAndApplyAppliesThem() = runComposeUiTest { fun theXAsksAboutPendingEditsAndApplyAppliesThem() = runComposeUiTest {
val w = Window() val w = Window()
show(w) show(w)
toggle("Send the beacon in this category") typeAndCommit("Interval in whole minutes", "9")
runOnIdle { w.x() } runOnIdle { w.x() }
awaitNode(inDialog(PENDING_QUESTION)) awaitNode(inDialog(PENDING_QUESTION))
@@ -273,7 +273,7 @@ class SettingsApplyScreenTest {
awaitNode(inDialog("Apply")).performClick() awaitNode(inDialog("Apply")).performClick()
awaitGone(inDialog(PENDING_QUESTION)) awaitGone(inDialog(PENDING_QUESTION))
assertTrue(w.prefs.isBcn_beaconsEnabledMainCat) assertEquals(9, w.prefs.bcn_beaconIntervalInMinutesMainCat)
assertTrue(w.closed) assertTrue(w.closed)
} }
@@ -288,7 +288,7 @@ class SettingsApplyScreenTest {
awaitNode(inDialog("Discard")).performClick() awaitNode(inDialog("Discard")).performClick()
awaitGone(inDialog(PENDING_QUESTION)) awaitGone(inDialog(PENDING_QUESTION))
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat) assertTrue(w.prefs.isBcn_beaconsEnabledMainCat, "the immediate runtime switch was unexpectedly reverted")
assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat) assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat)
assertEquals(0, w.restarts) assertEquals(0, w.restarts)
assertTrue(w.closed) assertTrue(w.closed)
@@ -299,7 +299,7 @@ class SettingsApplyScreenTest {
fun goingBackKeepsTheWindowAndTheEdits() = runComposeUiTest { fun goingBackKeepsTheWindowAndTheEdits() = runComposeUiTest {
val w = Window() val w = Window()
show(w) show(w)
toggle("Send the beacon in this category") typeAndCommit("Interval in whole minutes", "9")
runOnIdle { w.x() } runOnIdle { w.x() }
awaitNode(inDialog("Back to the settings")).performClick() awaitNode(inDialog("Back to the settings")).performClick()
@@ -307,7 +307,7 @@ class SettingsApplyScreenTest {
assertFalse(w.closed) assertFalse(w.closed)
assertTrue(w.draft.hasPendingChanges) assertTrue(w.draft.hasPendingChanges)
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat) assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat)
checkBeside("Send the beacon in this category").assertExists() checkBeside("Send the beacon in this category").assertExists()
} }
@@ -377,13 +377,13 @@ class SettingsApplyScreenTest {
val w = Window() val w = Window()
var wentOn = false var wentOn = false
show(w) show(w)
toggle("Send the beacon in this category") typeAndCommit("Interval in whole minutes", "9")
runOnIdle { w.switchOrExit { wentOn = true } } runOnIdle { w.switchOrExit { wentOn = true } }
awaitNode(inDialog("Apply")).performClick() awaitNode(inDialog("Apply")).performClick()
awaitGone(inDialog(PENDING_QUESTION)) awaitGone(inDialog(PENDING_QUESTION))
assertTrue(w.prefs.isBcn_beaconsEnabledMainCat) assertEquals(9, w.prefs.bcn_beaconIntervalInMinutesMainCat)
assertTrue(wentOn) assertTrue(wentOn)
assertFalse(w.closed, "the window closed itself instead of leaving that to the teardown") assertFalse(w.closed, "the window closed itself instead of leaving that to the teardown")
} }
@@ -393,7 +393,7 @@ class SettingsApplyScreenTest {
val w = Window() val w = Window()
var wentOn = false var wentOn = false
show(w) show(w)
toggle("Send the beacon in this category") typeAndCommit("Interval in whole minutes", "9")
runOnIdle { w.switchOrExit { wentOn = true } } runOnIdle { w.switchOrExit { wentOn = true } }
awaitNode(inDialog("Back to the settings")).performClick() awaitNode(inDialog("Back to the settings")).performClick()
@@ -408,14 +408,14 @@ class SettingsApplyScreenTest {
val w = Window() val w = Window()
var wentOn = false var wentOn = false
show(w) show(w)
toggle("Send the beacon in this category") typeAndCommit("Interval in whole minutes", "9")
runOnIdle { w.switchOrExit { wentOn = true } } runOnIdle { w.switchOrExit { wentOn = true } }
awaitNode(inDialog("Discard")).performClick() awaitNode(inDialog("Discard")).performClick()
awaitGone(inDialog(PENDING_QUESTION)) awaitGone(inDialog(PENDING_QUESTION))
assertTrue(wentOn) assertTrue(wentOn)
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat) assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat)
} }
@Test @Test
@@ -423,7 +423,7 @@ class SettingsApplyScreenTest {
val w = Window() val w = Window()
var wentOn = false var wentOn = false
show(w) show(w)
toggle("Send the beacon in this category") typeAndCommit("Interval in whole minutes", "9")
runOnIdle { w.switchOrExit { wentOn = true } } runOnIdle { w.switchOrExit { wentOn = true } }
awaitNode(inDialog(PENDING_QUESTION)) awaitNode(inDialog(PENDING_QUESTION))
@@ -432,7 +432,7 @@ class SettingsApplyScreenTest {
awaitGone(inDialog(PENDING_QUESTION)) awaitGone(inDialog(PENDING_QUESTION))
assertFalse(wentOn, "went on over a refused entry") assertFalse(wentOn, "went on over a refused entry")
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat, "applied despite the refusal") assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat, "applied despite the refusal")
} }
@Test @Test
@@ -457,7 +457,7 @@ class SettingsApplyScreenTest {
val w = Window() val w = Window()
var wentOn = false var wentOn = false
show(w) show(w)
toggle("Send the beacon in this category") typeAndCommit("Interval in whole minutes", "9")
runOnIdle { w.switchOrExit { wentOn = true } } runOnIdle { w.switchOrExit { wentOn = true } }
awaitNode(inDialog(PENDING_QUESTION)) awaitNode(inDialog(PENDING_QUESTION))
@@ -477,7 +477,7 @@ class SettingsApplyScreenTest {
fun anInvalidFieldStillLetsTheXDiscard() = runComposeUiTest { fun anInvalidFieldStillLetsTheXDiscard() = runComposeUiTest {
val w = Window() val w = Window()
show(w) show(w)
toggle("Send the beacon in this category") typeAndCommit("Interval in whole minutes", "9")
type("Server port", "23x") type("Server port", "23x")
runOnIdle { w.x() } runOnIdle { w.x() }
@@ -489,7 +489,7 @@ class SettingsApplyScreenTest {
awaitGone(inDialog(PENDING_QUESTION)) awaitGone(inDialog(PENDING_QUESTION))
assertTrue(w.closed) assertTrue(w.closed)
assertFalse(w.prefs.isBcn_beaconsEnabledMainCat, "something was applied") assertEquals(5, w.prefs.bcn_beaconIntervalInMinutesMainCat, "something was applied")
} }
/* The same for a switch or the exit, even when only the invalid field is unsettled. */ /* The same for a switch or the exit, even when only the invalid field is unsettled. */
@@ -20,6 +20,8 @@ class StationTabStateTest(@param:TempDir private val tempDir: Path) {
var secondApplied: ChatCategory? = null var secondApplied: ChatCategory? = null
var secondWasApplied = false var secondWasApplied = false
val secondRotatorCalls = mutableListOf<Unit>() val secondRotatorCalls = mutableListOf<Unit>()
var beaconStatusRefreshes = 0
var mapDisplayRefreshes = 0
val draft = SettingsDraft() val draft = SettingsDraft()
val state = StationTabState( val state = StationTabState(
prefs, prefs,
@@ -27,6 +29,8 @@ class StationTabStateTest(@param:TempDir private val tempDir: Path) {
{ mainApplied = it }, { mainApplied = it },
{ secondApplied = it; secondWasApplied = true }, { secondApplied = it; secondWasApplied = true },
applySecondRotator = { secondRotatorCalls.add(Unit) }, applySecondRotator = { secondRotatorCalls.add(Unit) },
refreshBeaconStatus = { beaconStatusRefreshes++ },
applyMapDisplaySettings = { mapDisplayRefreshes++ },
) )
} }
@@ -305,6 +309,34 @@ class StationTabStateTest(@param:TempDir private val tempDir: Path) {
assertEquals(true, state.loginToSecondChatEnabled) assertEquals(true, state.loginToSecondChatEnabled)
} }
@Test
fun `applying the second chat switch refreshes aggregate beacon status`() {
val session = Session()
session.state.loginToSecondChatEnabled = true
assertEquals(0, session.beaconStatusRefreshes)
session.draft.apply()
assertEquals(1, session.beaconStatusRefreshes)
}
@Test
fun `beam width and maximum QRB refresh the map once after both are applied`() {
val session = Session()
session.state.stn_antennaBeamWidthDeg = 72.0
session.state.stn_maxQRBDefault = 1_250.0
assertEquals(0, session.mapDisplayRefreshes)
val outcome = session.draft.apply()
assertTrue(outcome.isClean, outcome.failures.toString())
assertEquals(72.0, session.prefs.stn_antennaBeamWidthDeg, 0.0001)
assertEquals(1_250.0, session.prefs.stn_maxQRBDefault, 0.0001)
assertEquals(1, session.mapDisplayRefreshes)
}
@Test @Test
fun `the own height above sea level reads empty while the elevation model decides`() { fun `the own height above sea level reads empty while the elevation model decides`() {
val s = Session() val s = Session()
@@ -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())
}
}
@@ -73,7 +73,7 @@ class RemainingTextsFollowTheLanguageTest {
assertEquals("Wertung", score.title(), "the column title stayed in the old language") assertEquals("Wertung", score.title(), "the column title stayed in the old language")
assertEquals( assertEquals(
"Einen ganzzahligen Bakenabstand von mindestens 1 Minute eingeben.", "Einen ganzzahligen Bakenabstand von mindestens 5 Minuten eingeben.",
beacon.commitBeaconInterval("0"), beacon.commitBeaconInterval("0"),
"the refusal from the tab state stayed in the old language", "the refusal from the tab state stayed in the old language",
) )
@@ -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
+22
View File
@@ -141,6 +141,28 @@ subprojects {
} }
testUserHome.mkdirs() testUserHome.mkdirs()
} }
/*
* A test that never returns must fail by name instead of holding the job until
* GitHub kills it after six hours: Nightly #302 hung in :app-desktop:test for over
* an hour, and the log named only the task. The limit is far above the slowest test
* (under four seconds). SEPARATE_THREAD also ends a test whose thread ignores
* interruption, such as a busy loop or a blocked native call, and the failure's
* cause carries that thread's stack, so it shows where the test stood.
*/
systemProperty("junit.jupiter.execution.timeout.default", "2m")
systemProperty("junit.jupiter.execution.timeout.thread.mode.default", "SEPARATE_THREAD")
/*
* The timed-out thread's stack shows where a test waits, not who it waits for: the
* rare CI hang in SelectedStationMessageUiVisualRenderingTest blocks on a monitor
* that another thread holds. On a timeout JUnit prints all threads to the test's
* standard output, which lands in its XML report (the test-results artifact).
*/
systemProperty("junit.jupiter.execution.timeout.threaddump.enabled", "true")
// The default short format prints only the first frame of each cause, which for a
// timed-out test is the line it hung in but not the call that blocked there.
testLogging {
exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
}
finalizedBy(checkTestUserHome) finalizedBy(checkTestUserHome)
} }
@@ -0,0 +1,15 @@
package kst4contest.controller;
/** Adds the fixed marker used by every user-visible automatic chat message. */
final class AutomaticChatMessageFormatter {
/** Exact marker appended to every user-visible automatic chat message. */
/* default */ static final String SUFFIX = " *a*";
private AutomaticChatMessageFormatter() {
}
/* default */ static String appendSuffix(final String messageText) {
return messageText + SUFFIX;
}
}
@@ -0,0 +1,66 @@
package kst4contest.controller;
import java.util.OptionalLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import kst4contest.model.Band;
/** Parses complete beacon-reference frequencies without floating-point comparisons. */
final class BeaconFrequencyParser {
private static final Pattern GROUPED = Pattern.compile(
"^(\\d{2,5})[.,](\\d{1,3})(?:[.,](\\d{1,3}))?$"
);
private static final Pattern COMPACT = Pattern.compile("^\\d{5,8}$");
private BeaconFrequencyParser() {
}
static OptionalLong parseHz(String value) {
if (value == null) {
return OptionalLong.empty();
}
String normalized = value.trim();
if (normalized.isEmpty()) {
return OptionalLong.empty();
}
try {
long frequencyHz;
Matcher grouped = GROUPED.matcher(normalized);
if (grouped.matches()) {
long megahertz = Long.parseLong(grouped.group(1));
long kilohertz = rightPadToThree(grouped.group(2));
long hertz = grouped.group(3) == null
? 0L
: rightPadToThree(grouped.group(3));
frequencyHz = Math.addExact(
Math.multiplyExact(megahertz, 1_000_000L),
Math.addExact(Math.multiplyExact(kilohertz, 1_000L), hertz)
);
} else if (COMPACT.matcher(normalized).matches()) {
long compact = Long.parseLong(normalized);
frequencyHz = Math.multiplyExact(compact, 1_000L);
} else {
return OptionalLong.empty();
}
if (frequencyHz <= 0L
|| Band.fromFrequency(frequencyHz / 1_000_000.0) == null) {
return OptionalLong.empty();
}
return OptionalLong.of(frequencyHz);
} catch (ArithmeticException | NumberFormatException ignored) {
return OptionalLong.empty();
}
}
private static long rightPadToThree(String digits) {
long value = Long.parseLong(digits);
for (int index = digits.length(); index < 3; index++) {
value *= 10L;
}
return value;
}
}
@@ -0,0 +1,225 @@
package kst4contest.controller;
import java.util.OptionalLong;
import kst4contest.model.BeaconStatusSnapshot;
import kst4contest.model.BeaconStatusSnapshot.AggregateState;
import kst4contest.model.BeaconStatusSnapshot.CategoryStatus;
import kst4contest.model.BeaconStatusSnapshot.InactiveReason;
import kst4contest.model.ChatPreferences;
/** Owns session-only beacon activation, QRG references, reasons, and send failures. */
final class BeaconSessionState {
static final long MAX_AUTOMATIC_QRG_DELTA_HZ = 5_000L;
enum Channel {
MAIN,
SECOND
}
private final ChannelState main = new ChannelState();
private final ChannelState second = new ChannelState();
void resetSession(ChatPreferences preferences) {
synchronized (this) {
main.reset();
second.reset();
}
project(preferences);
}
boolean setEnabled(Channel channel, boolean enabled, ChatPreferences preferences) {
boolean accepted;
synchronized (this) {
ChannelState target = state(channel);
if (!enabled) {
target.disable(InactiveReason.USER_DISABLED);
accepted = true;
} else {
InactiveReason invalidReason = missingRequiredQrg(channel, preferences);
if (invalidReason != null) {
target.disable(invalidReason);
accepted = false;
} else {
target.enabled = true;
target.failed = false;
OptionalLong reference = ownQrg(channel, preferences);
target.referenceHz = reference.isPresent() ? reference.getAsLong() : null;
accepted = true;
}
}
}
project(preferences);
return accepted;
}
void onManualQrgChanged(Channel channel, String value, ChatPreferences preferences) {
if (channel == Channel.MAIN) {
preferences.getMYQRGFirstCat().set(value);
} else {
preferences.getMYQRGSecondCat().set(value);
}
OptionalLong parsed = BeaconFrequencyParser.parseHz(value);
synchronized (this) {
ChannelState target = state(channel);
if (target.enabled) {
target.referenceHz = parsed.isPresent() ? parsed.getAsLong() : null;
}
revalidateEnabled(preferences);
}
project(preferences);
}
void onExternalQrgChanged(Channel channel, long frequencyHz, ChatPreferences preferences) {
boolean valid = frequencyHz > 0L && ownQrg(channel, preferences).isPresent();
synchronized (this) {
ChannelState target = state(channel);
if (target.enabled) {
if (!valid) {
target.referenceHz = null;
} else if (target.referenceHz == null) {
target.referenceHz = frequencyHz;
} else if (absoluteDifference(target.referenceHz, frequencyHz)
> MAX_AUTOMATIC_QRG_DELTA_HZ) {
target.disable(InactiveReason.AUTOMATIC_QRG_CHANGE);
}
}
revalidateEnabled(preferences);
}
project(preferences);
}
void onTemplateChanged(Channel channel, ChatPreferences preferences) {
synchronized (this) {
ChannelState target = state(channel);
if (target.enabled) {
InactiveReason reason = missingRequiredQrg(channel, preferences);
if (reason != null) {
target.disable(reason);
}
}
}
project(preferences);
}
synchronized boolean isEnabled(Channel channel) {
return state(channel).enabled;
}
synchronized void recordSendFailure(Channel channel, boolean failed) {
ChannelState target = state(channel);
target.failed = target.enabled && failed;
}
synchronized BeaconStatusSnapshot snapshot(ChatPreferences preferences) {
boolean secondAvailable = preferences.isLoginToSecondChatEnabled();
boolean mainEnabled = main.enabled;
boolean secondEnabled = secondAvailable && second.enabled;
boolean failed = (mainEnabled && main.failed) || (secondEnabled && second.failed);
int available = secondAvailable ? 2 : 1;
int enabled = (mainEnabled ? 1 : 0) + (secondEnabled ? 1 : 0);
AggregateState aggregate;
if (failed) {
aggregate = AggregateState.FAILED;
} else if (enabled == 0) {
aggregate = AggregateState.OFF;
} else if (enabled == available) {
aggregate = AggregateState.ON;
} else {
aggregate = AggregateState.PARTIAL;
}
return new BeaconStatusSnapshot(
aggregate,
new CategoryStatus(true, mainEnabled, main.failed, main.reason),
new CategoryStatus(secondAvailable, secondEnabled, second.failed, second.reason)
);
}
private void revalidateEnabled(ChatPreferences preferences) {
revalidate(Channel.MAIN, preferences);
revalidate(Channel.SECOND, preferences);
}
private void revalidate(Channel channel, ChatPreferences preferences) {
ChannelState target = state(channel);
if (!target.enabled) {
return;
}
InactiveReason reason = missingRequiredQrg(channel, preferences);
if (reason != null) {
target.disable(reason);
}
}
private static InactiveReason missingRequiredQrg(
Channel channel,
ChatPreferences preferences
) {
String template = channel == Channel.MAIN
? preferences.getBcn_beaconTextMainCat()
: preferences.getBcn_beaconTextSecondCat();
String safeTemplate = template == null ? "" : template;
if ((safeTemplate.contains("MYQRG") || safeTemplate.contains("MYQRGSHORT"))
&& BeaconFrequencyParser.parseHz(preferences.getMYQRGFirstCat().get()).isEmpty()) {
return InactiveReason.PRIMARY_QRG_UNAVAILABLE;
}
if (safeTemplate.contains("SECONDQRG")
&& BeaconFrequencyParser.parseHz(preferences.getMYQRGSecondCat().get()).isEmpty()) {
return InactiveReason.SECONDARY_QRG_UNAVAILABLE;
}
return null;
}
private static OptionalLong ownQrg(Channel channel, ChatPreferences preferences) {
String value = channel == Channel.MAIN
? preferences.getMYQRGFirstCat().get()
: preferences.getMYQRGSecondCat().get();
return BeaconFrequencyParser.parseHz(value);
}
private static long absoluteDifference(long first, long second) {
return first >= second ? first - second : second - first;
}
private void project(ChatPreferences preferences) {
boolean mainEnabled;
boolean secondEnabled;
synchronized (this) {
mainEnabled = main.enabled;
secondEnabled = second.enabled;
}
if (preferences.isBcn_beaconsEnabledMainCat() != mainEnabled) {
preferences.setBcn_beaconsEnabledMainCat(mainEnabled);
}
if (preferences.isBcn_beaconsEnabledSecondCat() != secondEnabled) {
preferences.setBcn_beaconsEnabledSecondCat(secondEnabled);
}
}
private ChannelState state(Channel channel) {
return channel == Channel.MAIN ? main : second;
}
private static final class ChannelState {
private boolean enabled;
private boolean failed;
private Long referenceHz;
private InactiveReason reason = InactiveReason.NOT_ACTIVATED_THIS_SESSION;
private void reset() {
enabled = false;
failed = false;
referenceHz = null;
reason = InactiveReason.NOT_ACTIVATED_THIS_SESSION;
}
private void disable(InactiveReason inactiveReason) {
enabled = false;
failed = false;
referenceHz = null;
reason = inactiveReason;
}
}
}
@@ -0,0 +1,54 @@
package kst4contest.controller;
import kst4contest.model.BeaconStatusSnapshot;
import kst4contest.model.ChatPreferences;
import kst4contest.model.ThreadStateMessage;
/** Builds the single status shown for both beacons from their session state. */
final class BeaconStatus {
static final String SOURCE_NAME = ChatController.BEACON_STATUS_SOURCE;
private String activity = "Beacon configuration loaded.";
/** Records the result of one complete timer run. */
synchronized void recordRun(String activity) {
this.activity = activity;
}
/** Updates the explanation without hiding a still-relevant category failure. */
synchronized void recordActivity(String activity) {
this.activity = activity;
}
/** Builds a fresh aggregate from the current preferences and remembered failures. */
synchronized ThreadStateMessage message(
ChatPreferences preferences,
BeaconSessionState sessionState
) {
BeaconStatusSnapshot snapshot = sessionState.snapshot(preferences);
boolean critical = snapshot.getAggregateState()
== BeaconStatusSnapshot.AggregateState.FAILED;
boolean running = snapshot.getAggregateState()
!= BeaconStatusSnapshot.AggregateState.OFF;
String description;
switch (snapshot.getAggregateState()) {
case FAILED -> description = "FAILED";
case OFF -> description = "off";
case ON -> description = "on";
case PARTIAL -> description = "1/2";
default -> throw new IllegalStateException("Unknown beacon status");
}
ThreadStateMessage message = new ThreadStateMessage(
SOURCE_NAME,
running,
activity,
critical
);
message.setRunningInformationTextDescription(description);
message.setBeaconStatusSnapshot(snapshot);
return message;
}
}
@@ -4,7 +4,6 @@ import java.util.TimerTask;
import kst4contest.model.ChatCategory; import kst4contest.model.ChatCategory;
import kst4contest.model.ChatMessage; import kst4contest.model.ChatMessage;
import kst4contest.model.ThreadStateMessage;
/** /**
* Sends the configured public-chat beacons for both active chat categories. * Sends the configured public-chat beacons for both active chat categories.
@@ -20,10 +19,10 @@ import kst4contest.model.ThreadStateMessage;
*/ */
public class BeaconTask extends TimerTask { public class BeaconTask extends TimerTask {
private static final String THREAD_NICKNAME = "MyBeacon";
private final ChatController chatController; private final ChatController chatController;
private final ThreadStatusCallback callbackToController; private final ThreadStatusCallback callbackToController;
private final BeaconStatus beaconStatus;
private final BeaconSessionState beaconSessionState;
/** /**
* Creates one execution of the shared beacon timer. * Creates one execution of the shared beacon timer.
@@ -37,30 +36,46 @@ public class BeaconTask extends TimerTask {
) { ) {
this.chatController = chatController; this.chatController = chatController;
this.callbackToController = callbackToController; this.callbackToController = callbackToController;
this.beaconStatus = chatController.beaconStatusState();
this.beaconSessionState = chatController.beaconSessionState();
} }
@Override @Override
public void run() { public void run() {
Thread.currentThread().setName("BeaconTask"); Thread.currentThread().setName("BeaconTask");
reportStatus(THREAD_NICKNAME, true, "initialized", false); Attempt main = sendMainCategoryBeacon();
Attempt second = sendSecondCategoryBeacon();
String activity = "Main category: " + main.description
+ "; second category: " + second.description;
recordSendResult(BeaconSessionState.Channel.MAIN, main);
recordSendResult(BeaconSessionState.Channel.SECOND, second);
beaconStatus.recordRun(activity);
callbackToController.onThreadStatus(
BeaconStatus.SOURCE_NAME,
beaconStatus.message(
chatController.getChatPreferences(),
beaconSessionState
)
);
}
sendMainCategoryBeacon(); private void recordSendResult(
sendSecondCategoryBeacon(); BeaconSessionState.Channel channel,
Attempt attempt
) {
if (attempt == Attempt.INVALID) {
beaconSessionState.recordSendFailure(channel, true);
} else if (attempt == Attempt.SENT) {
beaconSessionState.recordSendFailure(channel, false);
}
} }
/** /**
* Sends the main-category beacon if it is currently enabled. * Sends the main-category beacon if it is currently enabled.
*/ */
private void sendMainCategoryBeacon() { private Attempt sendMainCategoryBeacon() {
if (!chatController.getChatPreferences() if (!beaconSessionState.isEnabled(BeaconSessionState.Channel.MAIN)) {
.isBcn_beaconsEnabledMainCat()) { return Attempt.OFF;
reportStatus(
THREAD_NICKNAME + " 1",
false,
"off",
false
);
return;
} }
ChatMessage beaconMessage = buildBeaconMessage( ChatMessage beaconMessage = buildBeaconMessage(
@@ -72,13 +87,7 @@ public class BeaconTask extends TimerTask {
); );
if (beaconMessage == null) { if (beaconMessage == null) {
reportStatus( return Attempt.INVALID;
THREAD_NICKNAME + " 1",
false,
"invalid text",
true
);
return;
} }
System.out.println( System.out.println(
@@ -88,31 +97,19 @@ public class BeaconTask extends TimerTask {
); );
chatController.getMessageTXBus().add(beaconMessage); chatController.getMessageTXBus().add(beaconMessage);
return Attempt.SENT;
reportStatus(
THREAD_NICKNAME + " 1",
true,
"on",
false
);
} }
/** /**
* Sends the second-category beacon if the second login and its beacon are * Sends the second-category beacon if the second login and its beacon are
* currently enabled. * currently enabled.
*/ */
private void sendSecondCategoryBeacon() { private Attempt sendSecondCategoryBeacon() {
if (!chatController.getChatPreferences() if (!chatController.getChatPreferences().isLoginToSecondChatEnabled()) {
.isLoginToSecondChatEnabled() return Attempt.UNAVAILABLE;
|| !chatController.getChatPreferences() }
.isBcn_beaconsEnabledSecondCat()) { if (!beaconSessionState.isEnabled(BeaconSessionState.Channel.SECOND)) {
reportStatus( return Attempt.OFF;
THREAD_NICKNAME + " 2",
false,
"off",
false
);
return;
} }
ChatMessage beaconMessage = buildBeaconMessage( ChatMessage beaconMessage = buildBeaconMessage(
@@ -124,13 +121,7 @@ public class BeaconTask extends TimerTask {
); );
if (beaconMessage == null) { if (beaconMessage == null) {
reportStatus( return Attempt.INVALID;
THREAD_NICKNAME + " 2",
false,
"invalid text",
true
);
return;
} }
System.out.println( System.out.println(
@@ -140,13 +131,7 @@ public class BeaconTask extends TimerTask {
); );
chatController.getMessageTXBus().add(beaconMessage); chatController.getMessageTXBus().add(beaconMessage);
return Attempt.SENT;
reportStatus(
THREAD_NICKNAME + " 2",
true,
"on",
false
);
} }
/** /**
@@ -199,24 +184,16 @@ public class BeaconTask extends TimerTask {
} }
} }
/** private enum Attempt {
* Forwards one state update to the existing thread-status display. SENT("sent"),
*/ OFF("off"),
private void reportStatus( UNAVAILABLE("unavailable"),
String threadName, INVALID("invalid text");
boolean running,
String information, private final String description;
boolean criticalState
) { Attempt(String description) {
ThreadStateMessage stateMessage = new ThreadStateMessage( this.description = description;
threadName, }
running,
information,
criticalState
);
callbackToController.onThreadStatus(
THREAD_NICKNAME,
stateMessage
);
} }
} }
@@ -64,9 +64,15 @@ public class ChatController implements ThreadStatusCallback {
private static final boolean DEBUG_BAND_UPGRADE_HINT = true; //for new band hint private static final boolean DEBUG_BAND_UPGRADE_HINT = true; //for new band hint
public static final int MIN_BEACON_INTERVAL_MINUTES = 1; public static final String BEACON_STATUS_SOURCE = "MyBeacon";
public static final int MAX_BEACON_TEXT_LENGTH = 120; public static final int MIN_BEACON_INTERVAL_MINUTES = 5;
public static final int MAX_BEACON_PAYLOAD_LENGTH = 120;
public static final int MAX_BEACON_TEXT_LENGTH =
MAX_BEACON_PAYLOAD_LENGTH
+ AutomaticChatMessageFormatter.SUFFIX.length();
private static final long INITIAL_BEACON_DELAY_MILLIS = 10_000L; private static final long INITIAL_BEACON_DELAY_MILLIS = 10_000L;
private final BeaconSessionState beaconSessionState = new BeaconSessionState();
private final BeaconStatus beaconStatus = new BeaconStatus();
private Consumer<Double> viewRotorCallback; private Consumer<Double> viewRotorCallback;
@@ -3034,6 +3040,7 @@ private SimpleRoster<String>
chatPreferences = new ChatPreferences(preferencesRelativeFileName); chatPreferences = new ChatPreferences(preferencesRelativeFileName);
chatPreferences.readPreferencesFromXmlFile(); chatPreferences.readPreferencesFromXmlFile();
beaconSessionState.resetSession(chatPreferences);
Path historyFile = Path.of(ApplicationFileUtils.getDebugFilePath( Path historyFile = Path.of(ApplicationFileUtils.getDebugFilePath(
ApplicationConstants.APPLICATION_NAME, ApplicationConstants.APPLICATION_NAME,
MessageHistoryRecorder.CURRENT_FILE_NAME)); MessageHistoryRecorder.CURRENT_FILE_NAME));
@@ -3286,6 +3293,7 @@ private SimpleRoster<String>
public void setChatPreferences(ChatPreferences chatPreferences) { public void setChatPreferences(ChatPreferences chatPreferences) {
this.chatPreferences = chatPreferences; this.chatPreferences = chatPreferences;
beaconSessionState.resetSession(chatPreferences);
} }
public ChatMember getownChatMemberObject() { public ChatMember getownChatMemberObject() {
@@ -3381,6 +3389,124 @@ private SimpleRoster<String>
this.dbHandler = dbHandler; this.dbHandler = dbHandler;
} }
/** Applies the main-category beacon switch to the running session immediately. */
public void setMainBeaconEnabled(boolean enabled) {
beaconSessionState.setEnabled(
BeaconSessionState.Channel.MAIN,
enabled,
getChatPreferences()
);
publishBeaconStatus("Beacon configuration changed.");
}
/** Applies the second-category beacon switch to the running session immediately. */
public void setSecondBeaconEnabled(boolean enabled) {
beaconSessionState.setEnabled(
BeaconSessionState.Channel.SECOND,
enabled,
getChatPreferences()
);
publishBeaconStatus("Beacon configuration changed.");
}
/**
* Toggles every beacon usable in the current chat configuration.
*
* <p>The dormant second-category preference is deliberately left unchanged when
* the second chat is disabled. Enabling that chat later therefore restores the
* operator's previous category-specific choice.</p>
*/
public void toggleUsableBeacons() {
ChatPreferences preferences = getChatPreferences();
boolean secondAvailable = preferences.isLoginToSecondChatEnabled();
boolean anyEnabled = beaconSessionState.isEnabled(BeaconSessionState.Channel.MAIN)
|| (secondAvailable
&& beaconSessionState.isEnabled(BeaconSessionState.Channel.SECOND));
boolean enable = !anyEnabled;
beaconSessionState.setEnabled(
BeaconSessionState.Channel.MAIN,
enable,
preferences
);
if (secondAvailable) {
beaconSessionState.setEnabled(
BeaconSessionState.Channel.SECOND,
enable,
preferences
);
}
publishBeaconStatus("Beacon status toggled from the main window.");
}
/** Applies a deliberate operator QRG entry and rebases the affected beacon. */
public void applyManualQrg(RadioSlot slot, String value) {
BeaconSessionState.Channel channel = slot == RadioSlot.FIRST
? BeaconSessionState.Channel.MAIN
: BeaconSessionState.Channel.SECOND;
beaconSessionState.onManualQrgChanged(channel, value, getChatPreferences());
publishBeaconStatus("QRG changed by the operator.");
}
/** Applies a logger QRG report and enforces the automatic-QSY safety boundary. */
public void applyExternalQrg(RadioSlot slot, String displayValue, long frequencyHz) {
if (frequencyHz <= 0L) {
return;
}
slot.qrgIn(getChatPreferences()).set(displayValue);
BeaconSessionState.Channel channel = slot == RadioSlot.FIRST
? BeaconSessionState.Channel.MAIN
: BeaconSessionState.Channel.SECOND;
beaconSessionState.onExternalQrgChanged(channel, frequencyHz, getChatPreferences());
publishBeaconStatus("QRG updated by logging software.");
}
/** Revalidates the applied main-category template. */
public void onMainBeaconTemplateApplied() {
beaconSessionState.onTemplateChanged(
BeaconSessionState.Channel.MAIN,
getChatPreferences()
);
publishBeaconStatus("Beacon template changed.");
}
/** Revalidates the applied second-category template. */
public void onSecondBeaconTemplateApplied() {
beaconSessionState.onTemplateChanged(
BeaconSessionState.Channel.SECOND,
getChatPreferences()
);
publishBeaconStatus("Beacon template changed.");
}
/** Publishes the loaded state without changing either category switch. */
public void refreshBeaconStatus() {
publishBeaconStatus("Beacon configuration loaded.");
}
/** Returns the shared state used by the timer and manual controls. */
BeaconStatus beaconStatusState() {
return beaconStatus;
}
BeaconSessionState beaconSessionState() {
return beaconSessionState;
}
/** Builds the current aggregate when the UI is ready to display it. */
public ThreadStateMessage currentBeaconStatus() {
return beaconStatus.message(getChatPreferences(), beaconSessionState);
}
/** Publishes the aggregate state used by the single beacon status chip. */
private void publishBeaconStatus(String activity) {
beaconStatus.recordActivity(activity);
onThreadStatus(
BeaconStatus.SOURCE_NAME,
currentBeaconStatus()
);
}
/** /**
* Validates a configured beacon template before it is stored. * Validates a configured beacon template before it is stored.
@@ -3394,7 +3520,7 @@ private SimpleRoster<String>
* @param configuredText configured beacon template * @param configuredText configured beacon template
* @throws IllegalArgumentException if the template contains invalid protocol * @throws IllegalArgumentException if the template contains invalid protocol
* content or currently resolves to more than * content or currently resolves to more than
* {@value MAX_BEACON_TEXT_LENGTH} characters * {@value MAX_BEACON_PAYLOAD_LENGTH} characters
*/ */
public void validateBeaconTemplate(String configuredText) { public void validateBeaconTemplate(String configuredText) {
String normalizedTemplate = String normalizedTemplate =
@@ -3413,7 +3539,10 @@ private SimpleRoster<String>
return; return;
} }
validateResolvedBeaconText(resolvedText); validateBeaconText(
resolvedText,
MAX_BEACON_PAYLOAD_LENGTH
);
} }
/** /**
@@ -3434,22 +3563,29 @@ private SimpleRoster<String>
new MessageVariableResolver(chatPreferences) new MessageVariableResolver(chatPreferences)
.resolveGlobalVariables(configuredText); .resolveGlobalVariables(configuredText);
return validateResolvedBeaconText(resolvedText); String normalizedPayload = validateBeaconText(
resolvedText,
MAX_BEACON_PAYLOAD_LENGTH
);
return validateBeaconText(
AutomaticChatMessageFormatter.appendSuffix(normalizedPayload),
MAX_BEACON_TEXT_LENGTH
);
} }
/** /**
* Applies the message-text and length rules to a fully resolved beacon. * Applies the message-text and length rules to a beacon processing stage.
*/ */
private String validateResolvedBeaconText(String resolvedText) { private String validateBeaconText(String resolvedText, int maximumLength) {
String normalizedText = String normalizedText =
On4KstProtocol.messageText(resolvedText); On4KstProtocol.messageText(resolvedText);
if (normalizedText.length() > MAX_BEACON_TEXT_LENGTH) { if (normalizedText.length() > maximumLength) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"The resolved beacon message contains " "The resolved beacon message contains "
+ normalizedText.length() + normalizedText.length()
+ " characters; maximum is " + " characters; maximum is "
+ MAX_BEACON_TEXT_LENGTH + maximumLength
+ "." + "."
); );
} }
@@ -0,0 +1,53 @@
package kst4contest.controller;
import kst4contest.model.ChatPreferences;
/**
* Tells whether a profile has login credentials an operator entered.
*
* <p>Two states count as unconfigured. An empty callsign is what every created or duplicated
* profile starts with, because {@link OperatorProfileManagementService} clears the
* credentials on purpose. The bundled template's credentials are what the root profile of a
* fresh installation carries. Neither can log in as the operator, so neither needs a flag of
* its own in {@code preferences.xml}.</p>
*/
public final class LoginConfiguration {
/** Callsign shipped in {@code praktiKSTpreferences.xml}; held equal by a test. */
public static final String TEMPLATE_CALLSIGN = "DO5AMF";
/** Password shipped in {@code praktiKSTpreferences.xml}; held equal by a test. */
public static final String TEMPLATE_PASSWORD = "changeMe";
private LoginConfiguration() {
// Utility class.
}
/**
* Whether the preferences still hold the bundled template's credentials.
*
* <p>Only the pair counts. The callsign alone belongs to a real operator.</p>
*
* @param preferences preferences of the profile to judge
* @return true for an untouched template
*/
public static boolean carriesTemplateCredentials(final ChatPreferences preferences) {
return TEMPLATE_CALLSIGN.equalsIgnoreCase(trimmed(preferences.getStn_loginCallSign()))
&& TEMPLATE_PASSWORD.equals(preferences.getStn_loginPassword());
}
/**
* Whether the profile has no login an operator entered.
*
* @param preferences preferences of the profile to judge
* @return true when the callsign is empty or the template's credentials are still there
*/
public static boolean isUnconfigured(final ChatPreferences preferences) {
return trimmed(preferences.getStn_loginCallSign()).isEmpty()
|| carriesTemplateCredentials(preferences);
}
private static String trimmed(final String value) {
return value == null ? "" : value.trim();
}
}
@@ -872,10 +872,14 @@ public class MessageBusManagementThread extends Thread {
versionInfo.setSender(itsMe); versionInfo.setSender(itsMe);
versionInfo.setReceiver(newMessageArrived.getSender()); versionInfo.setReceiver(newMessageArrived.getSender());
versionInfo.setChatCategory(newMessageArrived.getChatCategory()); versionInfo.setChatCategory(newMessageArrived.getChatCategory());
versionInfo.setMessageText("/CQ " + newMessageArrived.getSender().getCallSign() versionInfo.setMessageText(
+ " " + AUTOANSWER_PREFIX AutomaticChatMessageFormatter.appendSuffix(
+ " KST4Contest v" + ApplicationConstants.APPLICATION_CURRENT_VERSION "/CQ " + newMessageArrived.getSender().getCallSign()
+ " by DO5AMF"); + " " + AUTOANSWER_PREFIX
+ " KST4Contest v" + ApplicationConstants.APPLICATION_CURRENT_VERSION
+ " by DO5AMF"
)
);
this.client.getMessageTXBus().add(versionInfo); this.client.getMessageTXBus().add(versionInfo);
} }
@@ -2070,7 +2074,9 @@ public class MessageBusManagementThread extends Thread {
+ payload; + payload;
try { try {
return On4KstProtocol.messageText(messageText); return On4KstProtocol.messageText(
AutomaticChatMessageFormatter.appendSuffix(messageText)
);
} catch (IllegalArgumentException invalidMessage) { } catch (IllegalArgumentException invalidMessage) {
LOGGER.warning( LOGGER.warning(
@@ -535,6 +535,7 @@ public class ReadUDPByWintestThread extends Thread {
* interpreted as frequencies. * interpreted as frequencies.
*/ */
String formattedPassQrg = null; String formattedPassQrg = null;
Long passFrequencyRawValue = null;
if (parts.size() > 11) { if (parts.size() > 11) {
try { try {
@@ -544,6 +545,7 @@ public class ReadUDPByWintestThread extends Thread {
passFrequencyRaw / 10.0; passFrequencyRaw / 10.0;
if (passFrequencyKHz > 100.0) { if (passFrequencyKHz > 100.0) {
passFrequencyRawValue = passFrequencyRaw;
formattedPassQrg = formattedPassQrg =
helper_formatWinTestFrequency( helper_formatWinTestFrequency(
passFrequencyRaw passFrequencyRaw
@@ -566,10 +568,16 @@ public class ReadUDPByWintestThread extends Thread {
usePassQrg && formattedPassQrg != null usePassQrg && formattedPassQrg != null
? formattedPassQrg ? formattedPassQrg
: formattedMainQrg; : formattedMainQrg;
final long selectedFrequencyRaw =
usePassQrg && passFrequencyRawValue != null
? passFrequencyRawValue
: mainFrequencyRaw;
final long selectedFrequencyHz = Math.multiplyExact(selectedFrequencyRaw, 100L);
if (prefs.isLogsynch_wintestQrgSyncEnabled()) { if (prefs.isLogsynch_wintestQrgSyncEnabled()) {
RadioSlot target = slot.get(); RadioSlot target = slot.get();
client.uiDispatcher().runOnUi(() -> target.qrgIn(prefs).set(qrgToSet)); client.uiDispatcher().runOnUi(() ->
client.applyExternalQrg(target, qrgToSet, selectedFrequencyHz));
} }
System.out.println( System.out.println(
@@ -417,7 +417,19 @@ public class ReadUDPbyUCXMessageThread extends Thread {
} }
String qrg = freqNode.getTextContent(); String qrg = freqNode.getTextContent();
qrg = qrg == null ? "" : qrg.trim();
String mode = modeNode.getTextContent(); String mode = modeNode.getTextContent();
final long frequencyHz;
try {
frequencyHz = Math.multiplyExact(Long.parseLong(qrg), 10L);
} catch (NumberFormatException | ArithmeticException invalidFrequency) {
System.out.println("[ReadUDPFromUCX, warning]: RadioInfo with invalid Freq ignored");
continue;
}
if (frequencyHz <= 0L) {
System.out.println("[ReadUDPFromUCX, warning]: RadioInfo with non-positive Freq ignored");
continue;
}
// System.out.println("QRG Length: " + qrg.length() + " // " + qrg); // System.out.println("QRG Length: " + qrg.length() + " // " + qrg);
@@ -464,7 +476,7 @@ public class ReadUDPbyUCXMessageThread extends Thread {
final String finalFormattedQRG = formattedQRG; final String finalFormattedQRG = formattedQRG;
final RadioSlot target = slot.get(); final RadioSlot target = slot.get();
helper_runOnFxThread(() -> helper_runOnFxThread(() ->
target.qrgIn(this.client.getChatPreferences()).set(finalFormattedQRG) this.client.applyExternalQrg(target, finalFormattedQRG, frequencyHz)
); );
// System.out.println("[ReadUDPbyUCXTh: ] Radioinfo processed: " + formattedQRG); // System.out.println("[ReadUDPbyUCXTh: ] Radioinfo processed: " + formattedQRG);
@@ -0,0 +1,83 @@
package kst4contest.model;
import java.util.Objects;
/** Immutable, display-neutral status of both beacon categories. */
public final class BeaconStatusSnapshot {
public enum AggregateState {
OFF,
PARTIAL,
ON,
FAILED
}
public enum InactiveReason {
NOT_ACTIVATED_THIS_SESSION,
USER_DISABLED,
PRIMARY_QRG_UNAVAILABLE,
SECONDARY_QRG_UNAVAILABLE,
AUTOMATIC_QRG_CHANGE
}
/** Immutable status of one beacon category. */
public static final class CategoryStatus {
private final boolean available;
private final boolean enabled;
private final boolean failed;
private final InactiveReason inactiveReason;
public CategoryStatus(
boolean available,
boolean enabled,
boolean failed,
InactiveReason inactiveReason
) {
this.available = available;
this.enabled = enabled;
this.failed = failed;
this.inactiveReason = Objects.requireNonNull(inactiveReason);
}
public boolean isAvailable() {
return available;
}
public boolean isEnabled() {
return enabled;
}
public boolean isFailed() {
return failed;
}
public InactiveReason getInactiveReason() {
return inactiveReason;
}
}
private final AggregateState aggregateState;
private final CategoryStatus main;
private final CategoryStatus second;
public BeaconStatusSnapshot(
AggregateState aggregateState,
CategoryStatus main,
CategoryStatus second
) {
this.aggregateState = Objects.requireNonNull(aggregateState);
this.main = Objects.requireNonNull(main);
this.second = Objects.requireNonNull(second);
}
public AggregateState getAggregateState() {
return aggregateState;
}
public CategoryStatus getMain() {
return main;
}
public CategoryStatus getSecond() {
return second;
}
}
@@ -366,8 +366,9 @@ public class ChatPreferences {
* Beacon prefs * Beacon prefs
*/ */
boolean bcn_beaconsEnabledMainCat = true; private static final int MIN_BEACON_INTERVAL_MINUTES = 5;
boolean bcn_beaconsEnabledSecondCat = false; MutableValue<Boolean> bcn_beaconsEnabledMainCat = new SimpleValue<>(false);
MutableValue<Boolean> bcn_beaconsEnabledSecondCat = new SimpleValue<>(false);
int bcn_beaconIntervalInMinutesMainCat = 20; int bcn_beaconIntervalInMinutesMainCat = 20;
int bcn_beaconIntervalInMinutesSecondCat = 20; int bcn_beaconIntervalInMinutesSecondCat = 20;
String bcn_beaconTextMainCat = "Hi, pse call us"; String bcn_beaconTextMainCat = "Hi, pse call us";
@@ -737,11 +738,15 @@ public class ChatPreferences {
} }
public boolean isBcn_beaconsEnabledSecondCat() { public boolean isBcn_beaconsEnabledSecondCat() {
return bcn_beaconsEnabledSecondCat; return Boolean.TRUE.equals(bcn_beaconsEnabledSecondCat.get());
} }
public void setBcn_beaconsEnabledSecondCat(boolean bcn_beaconsEnabledSecondCat) { public void setBcn_beaconsEnabledSecondCat(boolean bcn_beaconsEnabledSecondCat) {
this.bcn_beaconsEnabledSecondCat = bcn_beaconsEnabledSecondCat; this.bcn_beaconsEnabledSecondCat.set(bcn_beaconsEnabledSecondCat);
}
public MutableValue<Boolean> bcnBeaconsEnabledSecondCatProperty() {
return bcn_beaconsEnabledSecondCat;
} }
public int getBcn_beaconIntervalInMinutesSecondCat() { public int getBcn_beaconIntervalInMinutesSecondCat() {
@@ -1579,6 +1584,10 @@ public class ChatPreferences {
// } // }
public boolean isBcn_beaconsEnabledMainCat() { public boolean isBcn_beaconsEnabledMainCat() {
return Boolean.TRUE.equals(bcn_beaconsEnabledMainCat.get());
}
public MutableValue<Boolean> bcnBeaconsEnabledMainCatProperty() {
return bcn_beaconsEnabledMainCat; return bcn_beaconsEnabledMainCat;
} }
@@ -1601,7 +1610,7 @@ public class ChatPreferences {
} }
public void setBcn_beaconsEnabledMainCat(boolean bcn_beaconsEnabledMainCat) { public void setBcn_beaconsEnabledMainCat(boolean bcn_beaconsEnabledMainCat) {
this.bcn_beaconsEnabledMainCat = bcn_beaconsEnabledMainCat; this.bcn_beaconsEnabledMainCat.set(bcn_beaconsEnabledMainCat);
} }
public int getBcn_beaconIntervalInMinutesMainCat() { public int getBcn_beaconIntervalInMinutesMainCat() {
@@ -2190,11 +2199,11 @@ public class ChatPreferences {
beaconCQ.appendChild(bcn_beaconIntervalInMinutesMainCat); beaconCQ.appendChild(bcn_beaconIntervalInMinutesMainCat);
Element beaconCQEnabled = doc.createElement("beaconCQEnabled"); Element beaconCQEnabled = doc.createElement("beaconCQEnabled");
beaconCQEnabled.setTextContent(this.isBcn_beaconsEnabledMainCat()+""); beaconCQEnabled.setTextContent("false");
beaconCQ.appendChild(beaconCQEnabled); beaconCQ.appendChild(beaconCQEnabled);
Element bcn_beaconsEnabledMainCat = doc.createElement("bcn_beaconsEnabledMainCat"); Element bcn_beaconsEnabledMainCat = doc.createElement("bcn_beaconsEnabledMainCat");
bcn_beaconsEnabledMainCat.setTextContent(this.isBcn_beaconsEnabledMainCat()+""); bcn_beaconsEnabledMainCat.setTextContent("false");
beaconCQ.appendChild(bcn_beaconsEnabledMainCat); beaconCQ.appendChild(bcn_beaconsEnabledMainCat);
@@ -2215,11 +2224,11 @@ public class ChatPreferences {
beaconCQ.appendChild(bcn_beaconIntervalInMinutesSecondCat); beaconCQ.appendChild(bcn_beaconIntervalInMinutesSecondCat);
Element beaconCQEnabledSecondCat = doc.createElement("beaconCQEnabledSecondCat"); Element beaconCQEnabledSecondCat = doc.createElement("beaconCQEnabledSecondCat");
beaconCQEnabledSecondCat.setTextContent(this.isBcn_beaconsEnabledSecondCat()+""); beaconCQEnabledSecondCat.setTextContent("false");
beaconCQ.appendChild(beaconCQEnabledSecondCat); beaconCQ.appendChild(beaconCQEnabledSecondCat);
Element bcn_beaconsEnabledSecondCat = doc.createElement("bcn_beaconsEnabledSecondCat"); Element bcn_beaconsEnabledSecondCat = doc.createElement("bcn_beaconsEnabledSecondCat");
bcn_beaconsEnabledSecondCat.setTextContent(this.isBcn_beaconsEnabledSecondCat()+""); bcn_beaconsEnabledSecondCat.setTextContent("false");
beaconCQ.appendChild(bcn_beaconsEnabledSecondCat); beaconCQ.appendChild(bcn_beaconsEnabledSecondCat);
/** /**
@@ -2592,6 +2601,8 @@ public class ChatPreferences {
*/ */
public boolean readPreferencesFromXmlFile() { public boolean readPreferencesFromXmlFile() {
boolean readable = true;
System.out.println("[ChatPreferences, Info]: restoring prefs from file " + storeAndRestorePreferencesFileName); System.out.println("[ChatPreferences, Info]: restoring prefs from file " + storeAndRestorePreferencesFileName);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
@@ -2608,6 +2619,10 @@ public class ChatPreferences {
DocumentBuilder db = dbf.newDocumentBuilder(); DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xmlConfigFile); Document doc = db.parse(xmlConfigFile);
Element rootElement = doc.getDocumentElement();
if (rootElement == null || !"praktiKST".equals(rootElement.getTagName())) {
readable = false;
}
NodeList list; NodeList list;
// --- Schema version (optional) --- // --- Schema version (optional) ---
@@ -3170,12 +3185,18 @@ public class ChatPreferences {
Element beaconCQEl = getFirstElement(doc, "beaconCQ"); Element beaconCQEl = getFirstElement(doc, "beaconCQ");
if (beaconCQEl != null) { if (beaconCQEl != null) {
bcn_beaconsEnabledMainCat = getBoolean(beaconCQEl, bcn_beaconsEnabledMainCat, "bcn_beaconsEnabledMainCat", "beaconCQEnabled"); setBcn_beaconsEnabledMainCat(false);
bcn_beaconIntervalInMinutesMainCat = getInt(beaconCQEl, bcn_beaconIntervalInMinutesMainCat, "bcn_beaconIntervalInMinutesMainCat", "beaconCQIntervalMinutes"); bcn_beaconIntervalInMinutesMainCat = Math.max(
MIN_BEACON_INTERVAL_MINUTES,
getInt(beaconCQEl, bcn_beaconIntervalInMinutesMainCat, "bcn_beaconIntervalInMinutesMainCat", "beaconCQIntervalMinutes")
);
bcn_beaconTextMainCat = getText(beaconCQEl, bcn_beaconTextMainCat, "bcn_beaconTextMainCat", "beaconCQText"); bcn_beaconTextMainCat = getText(beaconCQEl, bcn_beaconTextMainCat, "bcn_beaconTextMainCat", "beaconCQText");
bcn_beaconsEnabledSecondCat = getBoolean(beaconCQEl, bcn_beaconsEnabledSecondCat, "bcn_beaconsEnabledSecondCat", "beaconCQEnabledSecondCat"); setBcn_beaconsEnabledSecondCat(false);
bcn_beaconIntervalInMinutesSecondCat = getInt(beaconCQEl, bcn_beaconIntervalInMinutesSecondCat, "bcn_beaconIntervalInMinutesSecondCat", "beaconCQIntervalMinutesSecondCat"); bcn_beaconIntervalInMinutesSecondCat = Math.max(
MIN_BEACON_INTERVAL_MINUTES,
getInt(beaconCQEl, bcn_beaconIntervalInMinutesSecondCat, "bcn_beaconIntervalInMinutesSecondCat", "beaconCQIntervalMinutesSecondCat")
);
bcn_beaconTextSecondCat = getText(beaconCQEl, bcn_beaconTextSecondCat, "bcn_beaconTextSecondCat", "beaconCQTextSecondText"); bcn_beaconTextSecondCat = getText(beaconCQEl, bcn_beaconTextSecondCat, "bcn_beaconTextSecondCat", "beaconCQTextSecondText");
System.out.println("[ChatPreferences, info]: beaconCQ main='" + bcn_beaconTextMainCat + "', second='" + bcn_beaconTextSecondCat + "'"); System.out.println("[ChatPreferences, info]: beaconCQ main='" + bcn_beaconTextMainCat + "', second='" + bcn_beaconTextSecondCat + "'");
@@ -3442,13 +3463,14 @@ public class ChatPreferences {
} catch (ParserConfigurationException | SAXException | IOException e) { } catch (ParserConfigurationException | SAXException | IOException e) {
readable = false;
e.printStackTrace(); e.printStackTrace();
System.out.println(e.getCause()); System.out.println(e.getCause());
System.out.println(e.getMessage()); System.out.println(e.getMessage());
} }
initializeActualQtfFromDefaultIfRequired(); initializeActualQtfFromDefaultIfRequired();
return true; return readable;
} }
@@ -14,6 +14,7 @@ public class ThreadStateMessage {
boolean criticalState; boolean criticalState;
String criticalStateFurtherInfo; String criticalStateFurtherInfo;
BeaconStatusSnapshot beaconStatusSnapshot;
@@ -99,5 +100,13 @@ public class ThreadStateMessage {
public void setCriticalStateFurtherInfo(String criticalStateFurtherInfo) { public void setCriticalStateFurtherInfo(String criticalStateFurtherInfo) {
this.criticalStateFurtherInfo = criticalStateFurtherInfo; this.criticalStateFurtherInfo = criticalStateFurtherInfo;
} }
public BeaconStatusSnapshot getBeaconStatusSnapshot() {
return beaconStatusSnapshot;
}
public void setBeaconStatusSnapshot(BeaconStatusSnapshot beaconStatusSnapshot) {
this.beaconStatusSnapshot = beaconStatusSnapshot;
}
} }
@@ -1,7 +1,9 @@
package kst4contest.view.map; package kst4contest.view.map;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Locale; import java.util.Locale;
/** /**
@@ -81,12 +83,39 @@ public final class MaidenheadGridUtils {
double northLat, double northLat,
double eastLon, double eastLon,
GridPrecision precision) { GridPrecision precision) {
if (!Double.isFinite(westLon) || !Double.isFinite(eastLon)) {
if (westLon > eastLon) {
// Anti-meridian handling is not needed for Europe in this project stage.
return List.of(); return List.of();
} }
double unwrappedEast = eastLon;
if (unwrappedEast < westLon) {
unwrappedEast += 360.0;
}
if (unwrappedEast - westLon >= 360.0) {
return buildVisibleCellsWithinWorld(southLat, -180.0, northLat, 180.0, precision);
}
int firstWorld = (int) Math.floor((westLon + 180.0) / 360.0);
int lastWorld = (int) Math.floor((unwrappedEast + 180.0 - EPSILON) / 360.0);
Map<String, GridCell> cells = new LinkedHashMap<>();
for (int world = firstWorld; world <= lastWorld; world++) {
double worldWest = -180.0 + world * 360.0;
double worldEast = 180.0 + world * 360.0;
double localWest = Math.max(westLon, worldWest) - world * 360.0;
double localEast = Math.min(unwrappedEast, worldEast) - world * 360.0;
buildVisibleCellsWithinWorld(southLat, localWest, northLat, localEast, precision)
.forEach(cell -> cells.putIfAbsent(cell.locatorLabel(), cell));
}
return List.copyOf(cells.values());
}
private static List<GridCell> buildVisibleCellsWithinWorld(double southLat,
double westLon,
double northLat,
double eastLon,
GridPrecision precision) {
double clampedSouth = clamp(southLat, -90.0 + EPSILON, 90.0 - EPSILON); double clampedSouth = clamp(southLat, -90.0 + EPSILON, 90.0 - EPSILON);
double clampedNorth = clamp(northLat, -90.0 + EPSILON, 90.0 - EPSILON); double clampedNorth = clamp(northLat, -90.0 + EPSILON, 90.0 - EPSILON);
double clampedWest = clamp(westLon, -180.0 + EPSILON, 180.0 - EPSILON); double clampedWest = clamp(westLon, -180.0 + EPSILON, 180.0 - EPSILON);
@@ -8,6 +8,8 @@ public final class MapMarkerCluster {
private final List<MapCallsignRawSnapshot> markers = new ArrayList<>(); private final List<MapCallsignRawSnapshot> markers = new ArrayList<>();
private double sumLon = 0.0; private double sumLon = 0.0;
private double sumLat = 0.0; private double sumLat = 0.0;
private double sumLonSin = 0.0;
private double sumLonCos = 0.0;
public MapMarkerCluster(MapCallsignRawSnapshot first) { public MapMarkerCluster(MapCallsignRawSnapshot first) {
add(first); add(first);
@@ -17,10 +19,16 @@ public final class MapMarkerCluster {
markers.add(marker); markers.add(marker);
sumLon += marker.longitudeDeg(); sumLon += marker.longitudeDeg();
sumLat += marker.latitudeDeg(); sumLat += marker.latitudeDeg();
double longitudeRad = Math.toRadians(marker.longitudeDeg());
sumLonSin += Math.sin(longitudeRad);
sumLonCos += Math.cos(longitudeRad);
} }
public double getCenterLon() { public double getCenterLon() {
return sumLon / markers.size(); if (Math.abs(sumLonSin) < 1e-12 && Math.abs(sumLonCos) < 1e-12) {
return sumLon / markers.size();
}
return Math.toDegrees(Math.atan2(sumLonSin, sumLonCos));
} }
public double getCenterLat() { public double getCenterLat() {
@@ -99,6 +99,21 @@ public final class MapViewport {
return widthPx / 2.0 + (WebMercatorProjection.lonToX(lon, tileZoom) - centerWorldX) * tileScale; return widthPx / 2.0 + (WebMercatorProjection.lonToX(lon, tileZoom) - centerWorldX) * tileScale;
} }
/**
* Places a longitude in the closest wrapped copy of the world.
*
* <p>A target at 179 degrees east and a centre at 179 degrees west are two degrees
* apart, not 358. Tiles already wrap at the anti-meridian; overlays and hit testing
* need the same world copy to stay aligned with them.</p>
*/
public double screenXWrapped(double lon) {
double worldSize = TILE_SIZE_PX * Math.pow(2.0, tileZoom);
double worldX = WebMercatorProjection.lonToX(lon, tileZoom);
double delta = worldX - centerWorldX;
delta -= Math.rint(delta / worldSize) * worldSize;
return widthPx / 2.0 + delta * tileScale;
}
public double screenY(double lat) { public double screenY(double lat) {
return heightPx / 2.0 + (WebMercatorProjection.latToY(lat, tileZoom) - centerWorldY) * tileScale; return heightPx / 2.0 + (WebMercatorProjection.latToY(lat, tileZoom) - centerWorldY) * tileScale;
} }
@@ -0,0 +1,153 @@
package kst4contest.view.map;
/** Pure viewport calculations for deliberate station-map navigation. */
public final class MapViewportNavigation {
private static final double WEB_MERCATOR_MAX_LATITUDE = 85.05112878;
private MapViewportNavigation() {
}
/**
* Centres the path and zooms out only when both endpoints do not fit with padding.
*
* @return the fitted viewport, or the original viewport for invalid positions or size
*/
public static MapViewport fitPath(MapViewport current,
double homeLatitudeDeg,
double homeLongitudeDeg,
double targetLatitudeDeg,
double targetLongitudeDeg,
double paddingPx) {
if (current == null
|| !isPosition(homeLatitudeDeg, homeLongitudeDeg)
|| !isPosition(targetLatitudeDeg, targetLongitudeDeg)
|| current.widthPx() <= 0.0
|| current.heightPx() <= 0.0) {
return current;
}
double padding = Math.max(0.0, paddingPx);
double availableWidth = current.widthPx() - 2.0 * padding;
double availableHeight = current.heightPx() - 2.0 * padding;
if (availableWidth <= 0.0 || availableHeight <= 0.0) {
return current;
}
double homeWorldX = WebMercatorProjection.lonToX(homeLongitudeDeg, 0);
double targetWorldX = WebMercatorProjection.lonToX(targetLongitudeDeg, 0);
double worldSize = 256.0;
double deltaX = targetWorldX - homeWorldX;
deltaX -= Math.rint(deltaX / worldSize) * worldSize;
double centerWorldX = homeWorldX + deltaX / 2.0;
double homeWorldY = WebMercatorProjection.latToY(homeLatitudeDeg, 0);
double targetWorldY = WebMercatorProjection.latToY(targetLatitudeDeg, 0);
double centerWorldY = (homeWorldY + targetWorldY) / 2.0;
double centerLongitude = WebMercatorProjection.xToLon(centerWorldX, 0);
double centerLatitude = WebMercatorProjection.yToLat(centerWorldY, 0);
MapViewport centred = new MapViewport(
centerLongitude,
centerLatitude,
current.zoom(),
current.widthPx(),
current.heightPx()
);
double widthAtCurrentZoom = Math.abs(
centred.screenXWrapped(targetLongitudeDeg)
- centred.screenXWrapped(homeLongitudeDeg)
);
double heightAtCurrentZoom = Math.abs(
centred.screenY(targetLatitudeDeg) - centred.screenY(homeLatitudeDeg)
);
double widthRatio = widthAtCurrentZoom == 0.0
? Double.POSITIVE_INFINITY
: availableWidth / widthAtCurrentZoom;
double heightRatio = heightAtCurrentZoom == 0.0
? Double.POSITIVE_INFINITY
: availableHeight / heightAtCurrentZoom;
double fitRatio = Math.min(widthRatio, heightRatio);
if (!Double.isFinite(fitRatio) || fitRatio >= 1.0) {
return centred;
}
double fittedZoom = current.zoom() + Math.log(fitRatio) / Math.log(2.0);
return new MapViewport(
centerLongitude,
centerLatitude,
fittedZoom,
current.widthPx(),
current.heightPx()
);
}
/**
* Leaves the zoom unchanged and places most of the viewport in the chosen direction.
*/
public static MapViewport centreOnBearing(MapViewport current,
double homeLatitudeDeg,
double homeLongitudeDeg,
double bearingDeg,
double forwardCentreFraction) {
if (current == null
|| !isPosition(homeLatitudeDeg, homeLongitudeDeg)
|| !Double.isFinite(bearingDeg)
|| current.widthPx() <= 0.0
|| current.heightPx() <= 0.0) {
return current;
}
double fraction = Math.max(0.0, Math.min(0.45, forwardCentreFraction));
double shiftPx = Math.min(current.widthPx(), current.heightPx()) * fraction;
double bearingRad = Math.toRadians(normaliseBearing(bearingDeg));
MapViewport homeCentred = new MapViewport(
homeLongitudeDeg,
homeLatitudeDeg,
current.zoom(),
current.widthPx(),
current.heightPx()
);
double centreX = current.widthPx() / 2.0 + Math.sin(bearingRad) * shiftPx;
double centreY = current.heightPx() / 2.0 - Math.cos(bearingRad) * shiftPx;
return new MapViewport(
homeCentred.lonAt(centreX),
homeCentred.latAt(centreY),
current.zoom(),
current.widthPx(),
current.heightPx()
);
}
public static MapViewport centreOnHome(MapViewport current,
double homeLatitudeDeg,
double homeLongitudeDeg) {
if (current == null || !isPosition(homeLatitudeDeg, homeLongitudeDeg)) {
return current;
}
return new MapViewport(
homeLongitudeDeg,
homeLatitudeDeg,
current.zoom(),
current.widthPx(),
current.heightPx()
);
}
private static boolean isPosition(double latitudeDeg, double longitudeDeg) {
return Double.isFinite(latitudeDeg)
&& Double.isFinite(longitudeDeg)
&& latitudeDeg >= -WEB_MERCATOR_MAX_LATITUDE
&& latitudeDeg <= WEB_MERCATOR_MAX_LATITUDE;
}
private static double normaliseBearing(double bearingDeg) {
double normalised = bearingDeg % 360.0;
return normalised < 0.0 ? normalised + 360.0 : normalised;
}
}
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff. Show more